lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | apache-2.0 | a2f918bd3a3b13a029062acca80b93a1a651b7f8 | 0 | MobilityData/gtfs-validator,MobilityData/gtfs-validator,MobilityData/gtfs-validator,MobilityData/gtfs-validator | /*
* Copyright (c) 2020. MobilityData IO.
*
* 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.mobilitydata.gtfsvalidator.usecase.port;
import org.apache.commons.cli.Options;
import org.apache.logging.log4j.Logger;
import org.mobilitydata.gtfsvalidator.domain.entity.ExecParam;
import java.io.IOException;
import java.util.Map;
/**
* This holds the execution parameters passed as parameters of the main execution method from a .json file or from
* Apache command line.
*/
public interface ExecParamRepository {
String HELP_KEY = "help";
String EXTRACT_KEY = "extract";
String OUTPUT_KEY = "output";
String PROTO_KEY = "proto";
String URL_KEY = "url";
String ZIP_KEY = "zipinput";
ExecParam getExecParamByKey(final String optionName);
Map<String, ExecParam> getExecParamCollection();
ExecParam addExecParam(final ExecParam newExecParam) throws IllegalArgumentException;
boolean hasExecParam(final String key);
boolean hasExecParamValue(final String key);
ExecParamParser getParser(final String parameterJsonString, final String[] args, final Logger logger);
String getExecParamValue(final String key) throws IllegalArgumentException;
Options getOptions();
boolean isEmpty();
interface ExecParamParser {
Map<String, ExecParam> parse() throws IOException;
}
} | usecase/src/main/java/org/mobilitydata/gtfsvalidator/usecase/port/ExecParamRepository.java | /*
* Copyright (c) 2020. MobilityData IO.
*
* 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.mobilitydata.gtfsvalidator.usecase.port;
import org.apache.commons.cli.Options;
import org.apache.logging.log4j.Logger;
import org.mobilitydata.gtfsvalidator.domain.entity.ExecParam;
import java.io.IOException;
import java.util.Map;
/**
* This holds the execution parameters passed as parameters of the main execution method from a .json file or from
* Apache command line.
*/
public interface ExecParamRepository {
String HELP_KEY = "help";
String EXTRACT_KEY = "extract";
String OUTPUT_KEY = "output";
String PROTO_KEY = "proto";
String URL_KEY = "url";
String ZIP_KEY = "inputzip";
ExecParam getExecParamByKey(final String optionName);
Map<String, ExecParam> getExecParamCollection();
ExecParam addExecParam(final ExecParam newExecParam) throws IllegalArgumentException;
boolean hasExecParam(final String key);
boolean hasExecParamValue(final String key);
ExecParamParser getParser(final String parameterJsonString, final String[] args, final Logger logger);
String getExecParamValue(final String key) throws IllegalArgumentException;
Options getOptions();
boolean isEmpty();
interface ExecParamParser {
Map<String, ExecParam> parse() throws IOException;
}
} | Change content of constant ZIP_KEY: inputzip -> zipinput (#118)
| usecase/src/main/java/org/mobilitydata/gtfsvalidator/usecase/port/ExecParamRepository.java | Change content of constant ZIP_KEY: inputzip -> zipinput (#118) | <ide><path>secase/src/main/java/org/mobilitydata/gtfsvalidator/usecase/port/ExecParamRepository.java
<ide> String OUTPUT_KEY = "output";
<ide> String PROTO_KEY = "proto";
<ide> String URL_KEY = "url";
<del> String ZIP_KEY = "inputzip";
<add> String ZIP_KEY = "zipinput";
<ide>
<ide> ExecParam getExecParamByKey(final String optionName);
<ide> |
|
Java | apache-2.0 | 6fd6bba9934c8a43041937f72c5bb792e0adf98f | 0 | operasoftware/operaprestodriver,operasoftware/operaprestodriver,operasoftware/operaprestodriver | package com.opera.core.systems.profile;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.opera.core.systems.settings.OperaDriverSettings;
public class ProfileUtils {
private String largePrefsFolder;
private String smallPrefsFolder;
private String cachePrefsFolder;
public ProfileUtils(OperaDriverSettings settings){
this.largePrefsFolder = settings.getLargePrefsFolder();
this.smallPrefsFolder = settings.getSmallPrefsFolder();
this.cachePrefsFolder = settings.getCachePrefsFolder();
}
public void deleteProfile() {
deleteFolder(smallPrefsFolder);
deleteFolder(largePrefsFolder);
deleteFolder(cachePrefsFolder);
}
public void copyProfile(String newPrefs) {
// For now, copy all to smallPrefsFolder
if (new File(newPrefs).exists())
{
copyFolder(newPrefs, smallPrefsFolder);
}
}
public boolean deleteFolder(String folderPath) {
File dir = new File(folderPath);
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteFolder(folderPath + children[i]);
if (!success) {
//return false;
}
}
}
// The directory/file is now empty so delete it
boolean res = dir.delete();
return res;
}
public void copyFolder(String from, String to) {
try {
copyFolder(new File(from), new File(to));
} catch (IOException ex) {
}
}
public void copyFolder(File srcFile, File dstFile) throws IOException {
if (srcFile.isDirectory()){
// Create destination folder if needed
if (!dstFile.exists()){
dstFile.mkdir();
}
String files[] = srcFile.list();
for(int i = 0; i < files.length; i++){
copyFolder(new File(srcFile, files[i]), new File(dstFile, files[i]));
}
}
else {
/*if(!srcFile.exists()){
System.out.println("File or directory " + srcFile.getAbsolutePath() + " does not exist.");
}
else*/
{
InputStream in = new FileInputStream(srcFile);
OutputStream out = new FileOutputStream(dstFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
}
}
| src/com/opera/core/systems/profile/ProfileUtils.java | package com.opera.core.systems.profile;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.opera.core.systems.settings.OperaDriverSettings;
public class ProfileUtils {
private String largePrefsFolder;
private String smallPrefsFolder;
private String cachePrefsFolder;
public ProfileUtils(OperaDriverSettings settings){
this.largePrefsFolder = settings.getLargePrefsFolder();
this.smallPrefsFolder = settings.getSmallPrefsFolder();
this.cachePrefsFolder = settings.getCachePrefsFolder();
}
public void deleteProfile() {
deleteFolder(smallPrefsFolder);
deleteFolder(largePrefsFolder);
deleteFolder(cachePrefsFolder);
}
public void copyProfile(String newPrefs) {
// For now, copy all to smallPrefsFolder
// TODO: If newPrefs doesn't exist
if (new File(newPrefs).exists())
{
copyFolder(newPrefs, smallPrefsFolder);
}
}
public boolean deleteFolder(String folderPath) {
File dir = new File(folderPath);
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteFolder(folderPath + children[i]);
if (!success) {
//return false;
}
}
}
// The directory/file is now empty so delete it
boolean res = dir.delete();
return res;
}
public void copyFolder(String from, String to) {
try {
copyFolder(new File(from), new File(to));
} catch (IOException ex) {
}
}
public void copyFolder(File srcFile, File dstFile) throws IOException {
if (srcFile.isDirectory()){
// Create destination folder if needed
if (!dstFile.exists()){
dstFile.mkdir();
}
String files[] = srcFile.list();
for(int i = 0; i < files.length; i++){
copyFolder(new File(srcFile, files[i]), new File(dstFile, files[i]));
}
}
else {
/*if(!srcFile.exists()){
System.out.println("File or directory " + srcFile.getAbsolutePath() + " does not exist.");
}
else*/
{
InputStream in = new FileInputStream(srcFile);
OutputStream out = new FileOutputStream(dstFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
}
}
| Cleanup
| src/com/opera/core/systems/profile/ProfileUtils.java | Cleanup | <ide><path>rc/com/opera/core/systems/profile/ProfileUtils.java
<ide>
<ide> public void copyProfile(String newPrefs) {
<ide> // For now, copy all to smallPrefsFolder
<del>
<del> // TODO: If newPrefs doesn't exist
<ide> if (new File(newPrefs).exists())
<ide> {
<ide> copyFolder(newPrefs, smallPrefsFolder); |
|
Java | apache-2.0 | 6baec44bc2eec06591cbe4614980bceddace0e48 | 0 | ontop/ontop,ontop/ontop,ontop/ontop,ontop/ontop,ontop/ontop | package it.unibz.inf.ontop.spec.mapping.parser;
/*
* #%L
* ontop-obdalib-core
* %%
* Copyright (C) 2009 - 2014 Free University of Bozen-Bolzano
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Injector;
import it.unibz.inf.ontop.exception.TargetQueryParserException;
import it.unibz.inf.ontop.injection.OntopMappingConfiguration;
import it.unibz.inf.ontop.injection.SpecificationFactory;
import it.unibz.inf.ontop.model.term.ImmutableFunctionalTerm;
import it.unibz.inf.ontop.spec.mapping.PrefixManager;
import it.unibz.inf.ontop.spec.mapping.parser.impl.TurtleOBDASQLParser;
import junit.framework.TestCase;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Test syntax of the parser.
* Added new extension. Define if the mapping column contains a data property with rdfs:Literal ("{column}")
* or an object property (<{column}>)
* @link {it.unibz.inf.obda.parser.TurtleOBDA.g}
* */
public class TurtleSyntaxParserTest {
private final static Logger log = LoggerFactory.getLogger(TurtleSyntaxParserTest.class);
private final SpecificationFactory specificationFactory;
public TurtleSyntaxParserTest() {
OntopMappingConfiguration configuration = OntopMappingConfiguration
.defaultBuilder().build();
Injector injector = configuration.getInjector();
specificationFactory = injector.getInstance(SpecificationFactory.class);
}
public void test_1_1() {
final boolean result = parse(":Person-{id} a :Person .");
TestCase.assertTrue(result);
}
@Test
public void test_1_2() {
final boolean result = parse("<http://example.org/testcase#Person-{id}> a :Person .");
TestCase.assertTrue(result);
}
@Test
public void test_1_3() {
final boolean result = parse("<http://example.org/testcase#Person-{id}> a <http://example.org/testcase#Person> .");
TestCase.assertTrue(result);
}
@Test
public void test_1_4() {
final boolean result = parse("<http://example.org/testcase#Person-{id}> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://example.org/testcase#Person> .");
TestCase.assertTrue(result);
}
@Test
public void test_2_1() {
final boolean result = parse(":Person-{id} :hasFather :Person-{id} .");
TestCase.assertTrue(result);
}
@Test
public void test_2_2() {
final boolean result = parse(":Person-{id} :hasFather <http://example.org/testcase#Person-12> .");
TestCase.assertTrue(result);
}
@Test
public void test_2_3() {
final boolean result = parse(":Person-{id} <http://example.org/testcase#hasFather> <http://example.org/testcase#Person-12> .");
TestCase.assertTrue(result);
}
@Test
public void test_3_1_database() {
final boolean result = parse(":Person-{id} :firstName {fname} .");
TestCase.assertTrue(result);
}
@Test
public void test_3_1_new_literal() {
final boolean result = parse(":Person-{id} :firstName \"{fname}\" .");
TestCase.assertTrue(result);
}
@Test
public void test_3_1_new_string() {
final boolean result = parse(":Person-{id} :firstName \"{fname}\"^^xsd:string .");
TestCase.assertTrue(result);
}
@Test
public void test_3_1_new_iri() {
final boolean result = parse(":Person-{id} :firstName <{fname}> .");
TestCase.assertTrue(result);
}
@Test
public void test_3_2() {
final boolean result = parse(":Person-{id} :firstName {fname}^^xsd:string .");
TestCase.assertTrue(result);
}
@Test
public void test_3_concat() {
final boolean result = parse(":Person-{id} :firstName \"hello {fname}\"^^xsd:string .");
TestCase.assertTrue(result);
}
@Test
public void test_3_concat_number() {
final boolean result = parse(":Person-{id} :firstName \"hello {fname}\"^^xsd:double .");
TestCase.assertTrue(result);
}
public void test_3_3() {
final boolean result = parse(":Person-{id} :firstName {fname}@en-US .");
TestCase.assertTrue(result);
}
@Test
public void test_4_1_1() {
final boolean result = parse(":Person-{id} :firstName \"John\"^^xsd:string .");
TestCase.assertTrue(result);
}
@Test
public void test_4_1_2() {
final boolean result = parse(":Person-{id} <http://example.org/testcase#firstName> \"John\"^^xsd:string .");
TestCase.assertTrue(result);
}
@Test
public void test_4_2_1() {
final boolean result = parse(":Person-{id} :firstName \"John\"^^rdfs:Literal .");
TestCase.assertFalse(result);
}
@Test
public void test_4_2_2() {
final boolean result = parse(":Person-{id} :firstName \"John\"@en-US .");
TestCase.assertTrue(result);
}
@Test
public void test_5_1_1() {
final boolean result = parse(":Person-{id} a :Person ; :firstName {fname} .");
TestCase.assertTrue(result);
}
@Test
public void test_5_1_2() {
final boolean result = parse(":Person-{id} a :Person ; :firstName {fname} ; :age {age} .");
TestCase.assertTrue(result);
}
@Test
public void test_5_1_3() {
final boolean result = parse(":Person-{id} a :Person ; :hasFather :Person-{id} ; :firstName {fname} ; :age {age} .");
TestCase.assertTrue(result);
}
@Test
public void test_5_2_1() {
final boolean result = parse(":Person-{id} a :Person ; :firstName {fname}^^xsd:string .");
TestCase.assertTrue(result);
}
@Test
public void test_5_2_2() {
final boolean result = parse(":Person-{id} a :Person ; :firstName {fname}^^xsd:string ; :age {age}^^xsd:integer .");
TestCase.assertTrue(result);
}
@Test
public void test_5_2_3() {
final boolean result = parse(":Person-{id} a :Person ; :hasFather :Person-{id} ; :firstName {fname}^^xsd:string ; :age {age}^^xsd:integer .");
TestCase.assertTrue(result);
}
@Test
public void test_5_2_4() {
final boolean result = parse(":Person-{id} a :Person ; :hasFather :Person-{id} ; :firstName {fname}^^xsd:string ; :age {age}^^xsd:integer ; :description {text}@en-US .");
TestCase.assertTrue(result);
}
@Test
public void test_5_2_5() {
final boolean result = parse(":Person-{id} a <http://example.org/testcase#Person> ; <http://example.org/testcase:hasFather> :Person-{id} ; <http://example.org/testcase#firstName> {fname}^^xsd:string ; <http://example.org/testcase#age> {age}^^xsd:integer ; <http://example.org/testcase#description> {text}@en-US .");
TestCase.assertTrue(result);
}
@Test
public void test_6_1() {
final boolean result = parse(":Person-{id} a :Person ; :firstName {fname}^^xsd:String .");
TestCase.assertFalse(result);
}
@Test
public void test_6_1_literal() {
final boolean result = parse(":Person-{id} a :Person ; :firstName \"Sarah\" .");
TestCase.assertTrue(result);
}
@Test
public void test_6_2() {
final boolean result = parse(":Person-{id} a :Person ; :firstName {fname}^^ex:randomDatatype .");
TestCase.assertFalse(result);
}
@Test
public void test_7_1() {
final boolean result = parse(":Person-{id} a :Person .");
TestCase.assertTrue(result);
}
@Test
public void test_7_2() {
final boolean result = parse(":Person-{id} :hasFather :Person-{id} .");
TestCase.assertTrue(result);
}
@Test
public void test_8_1() {
final boolean result = parse(":Person-{id} rdf:type :Person .");
TestCase.assertTrue(result);
}
@Test
public void test_8_2() {
final boolean result = parse("ex:Person-{id} rdf:type ex:Person .");
TestCase.assertTrue(result);
}
@Test
public void test_8_3() {
final boolean result = parse("ex:Person-{id} ex:hasFather ex:Person-123 .");
TestCase.assertTrue(result);
}
@Test
public void test_8_4() {
final boolean result = parse("ex:Person/{id}/ ex:hasFather ex:Person/123/ .");
TestCase.assertTrue(result);
}
//multiple triples with different subjects
@Test
public void test_9_1(){
final boolean result = compareCQIE(":S_{id} a :Student ; :fname {first_name} ; :hasCourse :C_{course_id} .\n" +
":C_{course_id} a :Course ; :hasProfessor :P_{id} . \n" +
":P_{id} a :Professor ; :teaches :C_{course_id} .\n" +
"{first_name} a :Name . ", 8);
TestCase.assertTrue(result);
}
@Test
public void test_9_2(){
final boolean result = compareCQIE("{idEmigrante} a :E21_Person ; :P131_is_identified_by {nome} ; :P11i_participated_in {numCM} .\n" +
"{nome} a :E82_Actor_Appellation ; :P3_has_note {nome}^^xsd:string .\n" +
"{numCM} a :E9_Move .", 6);
TestCase.assertTrue(result);
}
//Test for value constant
@Test
public void test10() {
final boolean result = parse(":Person-{id} a :Person ; :age 25 ; :hasDegree true ; :averageGrade 28.3 .");
TestCase.assertTrue(result);
}
//Test for fully identified column
@Test
public void test_11_1(){
final boolean result = parse(":Person-{person.id} a :Person ; :age 25 .");
TestCase.assertFalse(result);
}
//Test for language tag from db
// @Test
// public void test_12_1(){
// final boolean result = parse(":Person-{id} a :Person ; :firstName {name}@{lang} . ");
// TestCase.assertTrue(result);
//
// }
private boolean compareCQIE(String input, int countBody) {
TargetQueryParser parser = new TurtleOBDASQLParser(getPrefixManager().getPrefixMap());
ImmutableList<ImmutableFunctionalTerm> mapping;
try {
mapping = parser.parse(input);
} catch (TargetQueryParserException e) {
log.debug(e.getMessage());
return false;
} catch (Exception e) {
log.debug(e.getMessage());
return false;
}
return mapping.size()==countBody;
}
private boolean parse(String input) {
TargetQueryParser parser = new TurtleOBDASQLParser(getPrefixManager().getPrefixMap());
ImmutableList<ImmutableFunctionalTerm> mapping;
try {
mapping = parser.parse(input);
log.debug("mapping " + mapping);
} catch (TargetQueryParserException e) {
log.debug(e.getMessage());
return false;
} catch (Exception e) {
log.debug(e.getMessage());
return false;
}
return true;
}
private PrefixManager getPrefixManager() {
return specificationFactory.createPrefixManager(ImmutableMap.of(
PrefixManager.DEFAULT_PREFIX, "http://obda.inf.unibz.it/testcase#",
"ex:", "http://www.example.org/"
));
}
}
| mapping/core/src/test/java/it/unibz/inf/ontop/spec/mapping/parser/TurtleSyntaxParserTest.java | package it.unibz.inf.ontop.spec.mapping.parser;
/*
* #%L
* ontop-obdalib-core
* %%
* Copyright (C) 2009 - 2014 Free University of Bozen-Bolzano
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Injector;
import it.unibz.inf.ontop.exception.TargetQueryParserException;
import it.unibz.inf.ontop.injection.OntopMappingConfiguration;
import it.unibz.inf.ontop.injection.SpecificationFactory;
import it.unibz.inf.ontop.model.term.ImmutableFunctionalTerm;
import it.unibz.inf.ontop.spec.mapping.PrefixManager;
import it.unibz.inf.ontop.spec.mapping.parser.impl.TurtleOBDASQLParser;
import junit.framework.TestCase;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Test syntax of the parser.
* Added new extension. Define if the mapping column contains a data property with rdfs:Literal ("{column}")
* or an object property (<{column}>)
* @link {it.unibz.inf.obda.parser.TurtleOBDA.g}
* */
public class TurtleSyntaxParserTest {
private final static Logger log = LoggerFactory.getLogger(TurtleSyntaxParserTest.class);
private final SpecificationFactory specificationFactory;
public TurtleSyntaxParserTest() {
OntopMappingConfiguration configuration = OntopMappingConfiguration
.defaultBuilder().build();
Injector injector = configuration.getInjector();
specificationFactory = injector.getInstance(SpecificationFactory.class);
}
public void test_1_1() {
final boolean result = parse(":Person-{id} a :Person .");
TestCase.assertTrue(result);
}
@Test
public void test_1_2() {
final boolean result = parse("<http://example.org/testcase#Person-{id}> a :Person .");
TestCase.assertTrue(result);
}
@Test
public void test_1_3() {
final boolean result = parse("<http://example.org/testcase#Person-{id}> a <http://example.org/testcase#Person> .");
TestCase.assertTrue(result);
}
@Test
public void test_1_4() {
final boolean result = parse("<http://example.org/testcase#Person-{id}> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://example.org/testcase#Person> .");
TestCase.assertTrue(result);
}
@Test
public void test_2_1() {
final boolean result = parse(":Person-{id} :hasFather :Person-{id} .");
TestCase.assertTrue(result);
}
@Test
public void test_2_2() {
final boolean result = parse(":Person-{id} :hasFather <http://example.org/testcase#Person-12> .");
TestCase.assertTrue(result);
}
@Test
public void test_2_3() {
final boolean result = parse(":Person-{id} <http://example.org/testcase#hasFather> <http://example.org/testcase#Person-12> .");
TestCase.assertTrue(result);
}
@Test
public void test_3_1_database() {
final boolean result = parse(":Person-{id} :firstName {fname} .");
TestCase.assertTrue(result);
}
@Test
public void test_3_1_new_literal() {
final boolean result = parse(":Person-{id} :firstName \"{fname}\" .");
TestCase.assertTrue(result);
}
@Test
public void test_3_1_new_string() {
final boolean result = parse(":Person-{id} :firstName \"{fname}\"^^xsd:string .");
TestCase.assertTrue(result);
}
@Test
public void test_3_1_new_iri() {
final boolean result = parse(":Person-{id} :firstName <{fname}> .");
TestCase.assertTrue(result);
}
@Test
public void test_3_2() {
final boolean result = parse(":Person-{id} :firstName {fname}^^xsd:string .");
TestCase.assertTrue(result);
}
@Test
public void test_3_concat() {
final boolean result = parse(":Person-{id} :firstName \"hello {fname}\"^^xsd:string .");
TestCase.assertTrue(result);
}
@Test
public void test_3_concat_number() {
final boolean result = parse(":Person-{id} :firstName \"hello {fname}\"^^xsd:double .");
TestCase.assertTrue(result);
}
public void test_3_3() {
final boolean result = parse(":Person-{id} :firstName {fname}@en-US .");
TestCase.assertTrue(result);
}
@Test
public void test_4_1_1() {
final boolean result = parse(":Person-{id} :firstName \"John\"^^xsd:string .");
TestCase.assertTrue(result);
}
@Test
public void test_4_1_2() {
final boolean result = parse(":Person-{id} <http://example.org/testcase#firstName> \"John\"^^xsd:string .");
TestCase.assertTrue(result);
}
@Test
public void test_4_2_1() {
final boolean result = parse(":Person-{id} :firstName \"John\"^^rdfs:Literal .");
TestCase.assertFalse(result);
}
@Test
public void test_4_2_2() {
final boolean result = parse(":Person-{id} :firstName \"John\"@en-US .");
TestCase.assertTrue(result);
}
@Test
public void test_5_1_1() {
final boolean result = parse(":Person-{id} a :Person ; :firstName {fname} .");
TestCase.assertTrue(result);
}
@Test
public void test_5_1_2() {
final boolean result = parse(":Person-{id} a :Person ; :firstName {fname} ; :age {age} .");
TestCase.assertTrue(result);
}
@Test
public void test_5_1_3() {
final boolean result = parse(":Person-{id} a :Person ; :hasFather :Person-{id} ; :firstName {fname} ; :age {age} .");
TestCase.assertTrue(result);
}
@Test
public void test_5_2_1() {
final boolean result = parse(":Person-{id} a :Person ; :firstName {fname}^^xsd:string .");
TestCase.assertTrue(result);
}
@Test
public void test_5_2_2() {
final boolean result = parse(":Person-{id} a :Person ; :firstName {fname}^^xsd:string ; :age {age}^^xsd:integer .");
TestCase.assertTrue(result);
}
@Test
public void test_5_2_3() {
final boolean result = parse(":Person-{id} a :Person ; :hasFather :Person-{id} ; :firstName {fname}^^xsd:string ; :age {age}^^xsd:integer .");
TestCase.assertTrue(result);
}
@Test
public void test_5_2_4() {
final boolean result = parse(":Person-{id} a :Person ; :hasFather :Person-{id} ; :firstName {fname}^^xsd:string ; :age {age}^^xsd:integer ; :description {text}@en-US .");
TestCase.assertTrue(result);
}
@Test
public void test_5_2_5() {
final boolean result = parse(":Person-{id} a <http://example.org/testcase#Person> ; <http://example.org/testcase:hasFather> :Person-{id} ; <http://example.org/testcase#firstName> {fname}^^xsd:string ; <http://example.org/testcase#age> {age}^^xsd:integer ; <http://example.org/testcase#description> {text}@en-US .");
TestCase.assertTrue(result);
}
@Test
public void test_6_1() {
final boolean result = parse(":Person-{id} a :Person ; :firstName {fname}^^xsd:String .");
TestCase.assertFalse(result);
}
@Test
public void test_6_1_literal() {
final boolean result = parse(":Person-{id} a :Person ; :firstName \"Sarah\" .");
TestCase.assertTrue(result);
}
@Test
public void test_6_2() {
final boolean result = parse(":Person-{id} a :Person ; :firstName {fname}^^ex:randomDatatype .");
TestCase.assertFalse(result);
}
@Test
public void test_7_1() {
final boolean result = parse(":Person-{id} a :Person .");
TestCase.assertTrue(result);
}
@Test
public void test_7_2() {
final boolean result = parse(":Person-{id} :hasFather :Person-{id} .");
TestCase.assertTrue(result);
}
@Test
public void test_8_1() {
final boolean result = parse(":Person-{id} rdf:type :Person .");
TestCase.assertTrue(result);
}
@Test
public void test_8_2() {
final boolean result = parse("ex:Person-{id} rdf:type ex:Person .");
TestCase.assertTrue(result);
}
@Test
public void test_8_3() {
final boolean result = parse("ex:Person-{id} ex:hasFather ex:Person-123 .");
TestCase.assertTrue(result);
}
@Test
public void test_8_4() {
final boolean result = parse("ex:Person/{id}/ ex:hasFather ex:Person/123/ .");
TestCase.assertTrue(result);
}
//multiple triples with different subjects
@Test
public void test_9_1(){
final boolean result = compareCQIE(":S_{id} a :Student ; :fname {first_name} ; :hasCourse :C_{course_id} .\n" +
":C_{course_id} a :Course ; :hasProfessor :P_{id} . \n" +
":P_{id} a :Professor ; :teaches :C_{course_id} .\n" +
"{first_name} a :Name . ", 8);
TestCase.assertTrue(result);
}
@Test
public void test_9_2(){
final boolean result = compareCQIE("{idEmigrante} a :E21_Person ; :P131_is_identified_by {nome} ; :P11i_participated_in {numCM} .\n" +
"{nome} a :E82_Actor_Appellation ; :P3_has_note {nome}^^xsd:string .\n" +
"{numCM} a :E9_Move .", 6);
TestCase.assertTrue(result);
}
//Test for value constant
@Test
public void test10() {
final boolean result = parse(":Person-{id} a :Person ; :age 25 ; :hasDegree true ; :averageGrade 28.3 .");
TestCase.assertTrue(result);
}
//Test for fully identified column
@Test
public void test_11_1(){
final boolean result = parse(":Person-{person.id} a :Person ; :age 25 .");
TestCase.assertFalse(result);
}
//Test for language tag from db
@Test
public void test_12_1(){
final boolean result = parse(":Person-{id} a :Person ; :firstName {name}@{lang} . ");
TestCase.assertTrue(result);
}
private boolean compareCQIE(String input, int countBody) {
TargetQueryParser parser = new TurtleOBDASQLParser(getPrefixManager().getPrefixMap());
ImmutableList<ImmutableFunctionalTerm> mapping;
try {
mapping = parser.parse(input);
} catch (TargetQueryParserException e) {
log.debug(e.getMessage());
return false;
} catch (Exception e) {
log.debug(e.getMessage());
return false;
}
return mapping.size()==countBody;
}
private boolean parse(String input) {
TargetQueryParser parser = new TurtleOBDASQLParser(getPrefixManager().getPrefixMap());
ImmutableList<ImmutableFunctionalTerm> mapping;
try {
mapping = parser.parse(input);
log.debug("mapping " + mapping);
} catch (TargetQueryParserException e) {
log.debug(e.getMessage());
return false;
} catch (Exception e) {
log.debug(e.getMessage());
return false;
}
return true;
}
private PrefixManager getPrefixManager() {
return specificationFactory.createPrefixManager(ImmutableMap.of(
PrefixManager.DEFAULT_PREFIX, "http://obda.inf.unibz.it/testcase#",
"ex:", "http://www.example.org/"
));
}
}
| Deactivated variable as langTag test
| mapping/core/src/test/java/it/unibz/inf/ontop/spec/mapping/parser/TurtleSyntaxParserTest.java | Deactivated variable as langTag test | <ide><path>apping/core/src/test/java/it/unibz/inf/ontop/spec/mapping/parser/TurtleSyntaxParserTest.java
<ide> }
<ide>
<ide> //Test for language tag from db
<del> @Test
<del> public void test_12_1(){
<del> final boolean result = parse(":Person-{id} a :Person ; :firstName {name}@{lang} . ");
<del> TestCase.assertTrue(result);
<del>
<del> }
<add>// @Test
<add>// public void test_12_1(){
<add>// final boolean result = parse(":Person-{id} a :Person ; :firstName {name}@{lang} . ");
<add>// TestCase.assertTrue(result);
<add>//
<add>// }
<ide>
<ide> private boolean compareCQIE(String input, int countBody) {
<ide> TargetQueryParser parser = new TurtleOBDASQLParser(getPrefixManager().getPrefixMap()); |
|
JavaScript | mit | 2169d84f9744f5714af7c3d3011b9e3ff3796e5a | 0 | MovingImage24/mi-angular-chat | !function(n){function t(e){if(r[e])return r[e].exports;var u=r[e]={exports:{},id:e,loaded:!1};return n[e].call(u.exports,u,u.exports,t),u.loaded=!0,u.exports}var r={};return t.m=n,t.c=r,t.p="",t(0)}([function(n,t,r){"use strict";r(1),n.exports=angular.module("mi.Chat",["mi/template/chat.html","ngLodash"]).controller("MiChatController",["$scope","$timeout",function(n,t){function r(){n.submitCallback()(u.message,u.username),u.message="",e()}function e(){t(function(){n.$msgContainer[0].scrollTop=n.$msgContainer[0].scrollHeight},200,!1)}var u=this;u.messages=n.messages,u.username=n.username,u.inputPlaceholderText=n.inputPlaceholderText,u.submitButtonText=n.submitButtonText,u.title=n.title,u.message="",u.submitCall=r,n.$watch("chat.messages",function(){e(),t(function(){n.$chatInput.focus()},200)}),n.$watch("chat.messages.length",function(){n.historyLoading||e()})}]).directive("miChat",["$timeout","lodash",function(n,t){return{restrict:"EA",replace:!0,controller:"MiChatController",controllerAs:"chat",templateUrl:function(n,t){return t.templateUrl||"mi/template/chat.html"},scope:{messages:"=",username:"=",title:"@",inputPlaceholderText:"@",submitButtonText:"@",submitCallback:"&"},link:function(r,e){r.title||(r.title="Chat"),r.inputPlaceholderText||(r.inputPlaceholderText="... your message ..."),r.submitButtonText||(r.submitButtonText="Send"),r.$msgContainer=angular.element(e[0].querySelector(".chat-body")),r.$chatInput=e[0].querySelector(".chat-input-field");var u=r.$msgContainer[0];r.$msgContainer.bind("scroll",t.throttle(function(){var t=u.scrollHeight;u.scrollTop<=10&&(r.historyLoading=!0,r.$apply(r.infiniteScroll),n(function(){r.historyLoading=!1,t!==u.scrollHeight&&(r.$msgContainer[0].scrollTop=360)},150))},300))}}}]),angular.module("mi/template/chat.html",[]).run(["$templateCache",function(n){n.put("mi/template/chat.html",'<div class="row mi-chat"><div class="col-xs-12 col-sm-12"><div class="panel panel-default"><div class="panel-heading chat-header"><h3 class="panel-title">{{chat.title}}</h3></div><div class="panel-body chat-body"><div class="row chat-message" ng-repeat="message in chat.messages" ng-class="{\'self-authored\': (chat.username == message.username)}"><div class="col-xs-12 col-sm-12"><p>{{message.content}}</p><p>{{message.username}}</p></div></div></div><div class="panel-footer chat-footer"><form ng-submit="chat.submitCall()"><div class="input-group"><input type="text" class="form-control chat-input-field" placeholder="{{chat.inputPlaceholderText}}" ng-model="chat.message"/><span class="input-group-btn"><input type="submit" class="btn btn-primary chat-submit-button" value="{{chat.submitButtonText}}"/></span></div></form></div></div></div></div>')}])},function(n,t,r){var e;(function(n,u){/**
* @license
* lodash 3.8.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern exports="amd,commonjs,node" iife="angular.module('ngLodash', []).constant('lodash', null).config(function ($provide) { %output% $provide.constant('lodash', _);});" --output build/ng-lodash.js`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
angular.module("ngLodash",[]).constant("lodash",null).config(["$provide",function(i){function o(n,t){if(n!==t){var r=n===n,e=t===t;if(n>t||!r||n===E&&e)return 1;if(t>n||!e||t===E&&r)return-1}return 0}function a(n,t,r){for(var e=n.length,u=r?e:-1;r?u--:++u<e;)if(t(n[u],u,n))return u;return-1}function c(n,t,r){if(t!==t)return m(n,r);for(var e=r-1,u=n.length;++e<u;)if(n[e]===t)return e;return-1}function l(n){return"function"==typeof n||!1}function f(n){return"string"==typeof n?n:null==n?"":n+""}function s(n){return n.charCodeAt(0)}function p(n,t){for(var r=-1,e=n.length;++r<e&&t.indexOf(n.charAt(r))>-1;);return r}function h(n,t){for(var r=n.length;r--&&t.indexOf(n.charAt(r))>-1;);return r}function v(n,t){return o(n.criteria,t.criteria)||n.index-t.index}function _(n,t,r){for(var e=-1,u=n.criteria,i=t.criteria,a=u.length,c=r.length;++e<a;){var l=o(u[e],i[e]);if(l)return e>=c?l:l*(r[e]?1:-1)}return n.index-t.index}function g(n){return Gn[n]}function y(n){return Jn[n]}function d(n){return"\\"+Qn[n]}function m(n,t,r){for(var e=n.length,u=t+(r?0:-1);r?u--:++u<e;){var i=n[u];if(i!==i)return u}return-1}function w(n){return!!n&&"object"==typeof n}function b(n){return 160>=n&&n>=9&&13>=n||32==n||160==n||5760==n||6158==n||n>=8192&&(8202>=n||8232==n||8233==n||8239==n||8287==n||12288==n||65279==n)}function x(n,t){for(var r=-1,e=n.length,u=-1,i=[];++r<e;)n[r]===t&&(n[r]=Y,i[++u]=r);return i}function A(n,t){for(var r,e=-1,u=n.length,i=-1,o=[];++e<u;){var a=n[e],c=t?t(a,e,n):a;e&&r===c||(r=c,o[++i]=a)}return o}function j(n){for(var t=-1,r=n.length;++t<r&&b(n.charCodeAt(t)););return t}function C(n){for(var t=n.length;t--&&b(n.charCodeAt(t)););return t}function k(n){return Xn[n]}function O(n){function t(n){if(w(n)&&!ka(n)&&!(n instanceof u)){if(n instanceof e)return n;if(Mi.call(n,"__chain__")&&Mi.call(n,"__wrapped__"))return oe(n)}return new e(n)}function r(){}function e(n,t,r){this.__wrapped__=n,this.__actions__=r||[],this.__chain__=!!t}function u(n){this.__wrapped__=n,this.__actions__=null,this.__dir__=1,this.__dropCount__=0,this.__filtered__=!1,this.__iteratees__=null,this.__takeCount__=xo,this.__views__=null}function i(){var n=this.__actions__,t=this.__iteratees__,r=this.__views__,e=new u(this.__wrapped__);return e.__actions__=n?tt(n):null,e.__dir__=this.__dir__,e.__filtered__=this.__filtered__,e.__iteratees__=t?tt(t):null,e.__takeCount__=this.__takeCount__,e.__views__=r?tt(r):null,e}function b(){if(this.__filtered__){var n=new u(this);n.__dir__=-1,n.__filtered__=!0}else n=this.clone(),n.__dir__*=-1;return n}function nn(){var n=this.__wrapped__.value();if(!ka(n))return tr(n,this.__actions__);var t=this.__dir__,r=0>t,e=Fr(0,n.length,this.__views__),u=e.start,i=e.end,o=i-u,a=r?i:u-1,c=_o(o,this.__takeCount__),l=this.__iteratees__,f=l?l.length:0,s=0,p=[];n:for(;o--&&c>s;){a+=t;for(var h=-1,v=n[a];++h<f;){var _=l[h],g=_.iteratee,y=_.type;if(y==q){if(_.done&&(r?a>_.index:a<_.index)&&(_.count=0,_.done=!1),_.index=a,!_.done){var d=_.limit;if(!(_.done=d>-1?_.count++>=d:!g(v)))continue n}}else{var m=g(v);if(y==K)v=m;else if(!m){if(y==D)continue n;break n}}}p[s++]=v}return p}function un(){this.__data__={}}function an(n){return this.has(n)&&delete this.__data__[n]}function Gn(n){return"__proto__"==n?E:this.__data__[n]}function Jn(n){return"__proto__"!=n&&Mi.call(this.__data__,n)}function Xn(n,t){return"__proto__"!=n&&(this.__data__[n]=t),this}function Zn(n){var t=n?n.length:0;for(this.data={hash:so(null),set:new eo};t--;)this.push(n[t])}function Qn(n,t){var r=n.data,e="string"==typeof t||ju(t)?r.set.has(t):r.hash[t];return e?0:-1}function nt(n){var t=this.data;"string"==typeof n||ju(n)?t.set.add(n):t.hash[n]=!0}function tt(n,t){var r=-1,e=n.length;for(t||(t=Oi(e));++r<e;)t[r]=n[r];return t}function rt(n,t){for(var r=-1,e=n.length;++r<e&&t(n[r],r,n)!==!1;);return n}function et(n,t){for(var r=n.length;r--&&t(n[r],r,n)!==!1;);return n}function ut(n,t){for(var r=-1,e=n.length;++r<e;)if(!t(n[r],r,n))return!1;return!0}function at(n,t){for(var r=-1,e=n.length,u=-1,i=[];++r<e;){var o=n[r];t(o,r,n)&&(i[++u]=o)}return i}function ct(n,t){for(var r=-1,e=n.length,u=Oi(e);++r<e;)u[r]=t(n[r],r,n);return u}function lt(n){for(var t=-1,r=n.length,e=bo;++t<r;){var u=n[t];u>e&&(e=u)}return e}function ft(n){for(var t=-1,r=n.length,e=xo;++t<r;){var u=n[t];e>u&&(e=u)}return e}function st(n,t,r,e){var u=-1,i=n.length;for(e&&i&&(r=n[++u]);++u<i;)r=t(r,n[u],u,n);return r}function pt(n,t,r,e){var u=n.length;for(e&&u&&(r=n[--u]);u--;)r=t(r,n[u],u,n);return r}function ht(n,t){for(var r=-1,e=n.length;++r<e;)if(t(n[r],r,n))return!0;return!1}function vt(n){for(var t=n.length,r=0;t--;)r+=+n[t]||0;return r}function _t(n,t){return n===E?t:n}function gt(n,t,r,e){return n!==E&&Mi.call(e,r)?n:t}function yt(n,t,r){var e=Na(t);no.apply(e,Mo(t));for(var u=-1,i=e.length;++u<i;){var o=e[u],a=n[o],c=r(a,t[o],o,n,t);(c===c?c===a:a!==a)&&(a!==E||o in n)||(n[o]=c)}return n}function dt(n,t){for(var r=-1,e=null==n,u=!e&&Dr(n),i=u&&n.length,o=t.length,a=Oi(o);++r<o;){var c=t[r];u?a[r]=Kr(c,i)?n[c]:E:a[r]=e?E:n[c]}return a}function mt(n,t,r){r||(r={});for(var e=-1,u=t.length;++e<u;){var i=t[e];r[i]=n[i]}return r}function wt(n,t,r){var e=typeof n;return"function"==e?t===E?n:ur(n,t,r):null==n?vi:"object"==e?Nt(n):t===E?wi(n):Ft(n,t)}function bt(n,t,r,e,u,i,o){var a;if(r&&(a=u?r(n,e,u):r(n)),a!==E)return a;if(!ju(n))return n;var c=ka(n);if(c){if(a=Pr(n),!t)return tt(n,a)}else{var l=Di.call(n),f=l==Q;if(l!=rn&&l!=H&&(!f||u))return Yn[l]?Mr(n,l,t):u?n:{};if(a=zr(f?{}:n),!t)return To(a,n)}i||(i=[]),o||(o=[]);for(var s=i.length;s--;)if(i[s]==n)return o[s];return i.push(n),o.push(a),(c?rt:Rt)(n,function(e,u){a[u]=bt(e,t,r,u,n,i,o)}),a}function xt(n,t,r){if("function"!=typeof n)throw new Bi(V);return uo(function(){n.apply(E,r)},t)}function At(n,t){var r=n?n.length:0,e=[];if(!r)return e;var u=-1,i=Nr(),o=i==c,a=o&&t.length>=200?No(t):null,l=t.length;a&&(i=Qn,o=!1,t=a);n:for(;++u<r;){var f=n[u];if(o&&f===f){for(var s=l;s--;)if(t[s]===f)continue n;e.push(f)}else i(t,f,0)<0&&e.push(f)}return e}function jt(n,t){var r=!0;return So(n,function(n,e,u){return r=!!t(n,e,u)}),r}function Ct(n,t,r,e){var u=n.length;for(r=null==r?0:+r||0,0>r&&(r=-r>u?0:u+r),e=e===E||e>u?u:+e||0,0>e&&(e+=u),u=r>e?0:e>>>0,r>>>=0;u>r;)n[r++]=t;return n}function kt(n,t){var r=[];return So(n,function(n,e,u){t(n,e,u)&&r.push(n)}),r}function Ot(n,t,r,e){var u;return r(n,function(n,r,i){return t(n,r,i)?(u=e?r:n,!1):void 0}),u}function Et(n,t,r){for(var e=-1,u=n.length,i=-1,o=[];++e<u;){var a=n[e];if(w(a)&&Dr(a)&&(r||ka(a)||yu(a))){t&&(a=Et(a,t,r));for(var c=-1,l=a.length;++c<l;)o[++i]=a[c]}else r||(o[++i]=a)}return o}function It(n,t){return Wo(n,t,zu)}function Rt(n,t){return Wo(n,t,Na)}function Tt(n,t){return Bo(n,t,Na)}function $t(n,t){for(var r=-1,e=t.length,u=-1,i=[];++r<e;){var o=t[r];Ea(n[o])&&(i[++u]=o)}return i}function St(n,t,r){if(null!=n){r!==E&&r in ue(n)&&(t=[r]);for(var e=-1,u=t.length;null!=n&&++e<u;)n=n[t[e]];return e&&e==u?n:E}}function Ut(n,t,r,e,u,i){if(n===t)return!0;var o=typeof n,a=typeof t;return"function"!=o&&"object"!=o&&"function"!=a&&"object"!=a||null==n||null==t?n!==n&&t!==t:Wt(n,t,Ut,r,e,u,i)}function Wt(n,t,r,e,u,i,o){var a=ka(n),c=ka(t),l=G,f=G;a||(l=Di.call(n),l==H?l=rn:l!=rn&&(a=$u(n))),c||(f=Di.call(t),f==H?f=rn:f!=rn&&(c=$u(t)));var s=l==rn,p=f==rn,h=l==f;if(h&&!a&&!s)return Ur(n,t,l);if(!u){var v=s&&Mi.call(n,"__wrapped__"),_=p&&Mi.call(t,"__wrapped__");if(v||_)return r(v?n.value():n,_?t.value():t,e,u,i,o)}if(!h)return!1;i||(i=[]),o||(o=[]);for(var g=i.length;g--;)if(i[g]==n)return o[g]==t;i.push(n),o.push(t);var y=(a?Sr:Wr)(n,t,r,e,u,i,o);return i.pop(),o.pop(),y}function Bt(n,t,r,e,u){for(var i=-1,o=t.length,a=!u;++i<o;)if(a&&e[i]?r[i]!==n[t[i]]:!(t[i]in n))return!1;for(i=-1;++i<o;){var c=t[i],l=n[c],f=r[i];if(a&&e[i])var s=l!==E||c in n;else s=u?u(l,f,c):E,s===E&&(s=Ut(f,l,u,!0));if(!s)return!1}return!0}function Lt(n,t){var r=-1,e=Dr(n)?Oi(n.length):[];return So(n,function(n,u,i){e[++r]=t(n,u,i)}),e}function Nt(n){var t=Na(n),r=t.length;if(!r)return hi(!0);if(1==r){var e=t[0],u=n[e];if(Jr(u))return function(n){return null==n?!1:n[e]===u&&(u!==E||e in ue(n))}}for(var i=Oi(r),o=Oi(r);r--;)u=n[t[r]],i[r]=u,o[r]=Jr(u);return function(n){return null!=n&&Bt(ue(n),t,i,o)}}function Ft(n,t){var r=ka(n),e=Yr(n)&&Jr(t),u=n+"";return n=ie(n),function(i){if(null==i)return!1;var o=u;if(i=ue(i),(r||!e)&&!(o in i)){if(i=1==n.length?i:St(i,Yt(n,0,-1)),null==i)return!1;o=we(n),i=ue(i)}return i[o]===t?t!==E||o in i:Ut(t,i[o],null,!0)}}function Pt(n,t,r,e,u){if(!ju(n))return n;var i=Dr(t)&&(ka(t)||$u(t));if(!i){var o=Na(t);no.apply(o,Mo(t))}return rt(o||t,function(a,c){if(o&&(c=a,a=t[c]),w(a))e||(e=[]),u||(u=[]),zt(n,t,c,Pt,r,e,u);else{var l=n[c],f=r?r(l,a,c,n,t):E,s=f===E;s&&(f=a),!i&&f===E||!s&&(f===f?f===l:l!==l)||(n[c]=f)}}),n}function zt(n,t,r,e,u,i,o){for(var a=i.length,c=t[r];a--;)if(i[a]==c)return void(n[r]=o[a]);var l=n[r],f=u?u(l,c,r,n,t):E,s=f===E;s&&(f=c,Dr(c)&&(ka(c)||$u(c))?f=ka(l)?l:Dr(l)?tt(l):[]:Ia(c)||yu(c)?f=yu(l)?Wu(l):Ia(l)?l:{}:s=!1),i.push(c),o.push(f),s?n[r]=e(f,c,u,i,o):(f===f?f!==l:l===l)&&(n[r]=f)}function Mt(n){return function(t){return null==t?E:t[n]}}function qt(n){var t=n+"";return n=ie(n),function(r){return St(r,n,t)}}function Dt(n,t){for(var r=n?t.length:0;r--;){var e=parseFloat(t[r]);if(e!=u&&Kr(e)){var u=e;io.call(n,e,1)}}return n}function Kt(n,t){return n+Xi(wo()*(t-n+1))}function Vt(n,t,r,e,u){return u(n,function(n,u,i){r=e?(e=!1,n):t(r,n,u,i)}),r}function Yt(n,t,r){var e=-1,u=n.length;t=null==t?0:+t||0,0>t&&(t=-t>u?0:u+t),r=r===E||r>u?u:+r||0,0>r&&(r+=u),u=t>r?0:r-t>>>0,t>>>=0;for(var i=Oi(u);++e<u;)i[e]=n[e+t];return i}function Ht(n,t){var r;return So(n,function(n,e,u){return r=t(n,e,u),!r}),!!r}function Gt(n,t){var r=n.length;for(n.sort(t);r--;)n[r]=n[r].value;return n}function Jt(n,t,r){var e=Lr(),u=-1;t=ct(t,function(n){return e(n)});var i=Lt(n,function(n){var r=ct(t,function(t){return t(n)});return{criteria:r,index:++u,value:n}});return Gt(i,function(n,t){return _(n,t,r)})}function Xt(n,t){var r=0;return So(n,function(n,e,u){r+=+t(n,e,u)||0}),r}function Zt(n,t){var r=-1,e=Nr(),u=n.length,i=e==c,o=i&&u>=200,a=o?No():null,l=[];a?(e=Qn,i=!1):(o=!1,a=t?[]:l);n:for(;++r<u;){var f=n[r],s=t?t(f,r,n):f;if(i&&f===f){for(var p=a.length;p--;)if(a[p]===s)continue n;t&&a.push(s),l.push(f)}else e(a,s,0)<0&&((t||o)&&a.push(s),l.push(f))}return l}function Qt(n,t){for(var r=-1,e=t.length,u=Oi(e);++r<e;)u[r]=n[t[r]];return u}function nr(n,t,r,e){for(var u=n.length,i=e?u:-1;(e?i--:++i<u)&&t(n[i],i,n););return r?Yt(n,e?0:i,e?i+1:u):Yt(n,e?i+1:0,e?u:i)}function tr(n,t){var r=n;r instanceof u&&(r=r.value());for(var e=-1,i=t.length;++e<i;){var o=[r],a=t[e];no.apply(o,a.args),r=a.func.apply(a.thisArg,o)}return r}function rr(n,t,r){var e=0,u=n?n.length:e;if("number"==typeof t&&t===t&&Co>=u){for(;u>e;){var i=e+u>>>1,o=n[i];(r?t>=o:t>o)?e=i+1:u=i}return u}return er(n,t,vi,r)}function er(n,t,r,e){t=r(t);for(var u=0,i=n?n.length:0,o=t!==t,a=t===E;i>u;){var c=Xi((u+i)/2),l=r(n[c]),f=l===l;if(o)var s=f||e;else s=a?f&&(e||l!==E):e?t>=l:t>l;s?u=c+1:i=c}return _o(i,jo)}function ur(n,t,r){if("function"!=typeof n)return vi;if(t===E)return n;switch(r){case 1:return function(r){return n.call(t,r)};case 3:return function(r,e,u){return n.call(t,r,e,u)};case 4:return function(r,e,u,i){return n.call(t,r,e,u,i)};case 5:return function(r,e,u,i,o){return n.call(t,r,e,u,i,o)}}return function(){return n.apply(t,arguments)}}function ir(n){return Hi.call(n,0)}function or(n,t,r){for(var e=r.length,u=-1,i=vo(n.length-e,0),o=-1,a=t.length,c=Oi(i+a);++o<a;)c[o]=t[o];for(;++u<e;)c[r[u]]=n[u];for(;i--;)c[o++]=n[u++];return c}function ar(n,t,r){for(var e=-1,u=r.length,i=-1,o=vo(n.length-u,0),a=-1,c=t.length,l=Oi(o+c);++i<o;)l[i]=n[i];for(var f=i;++a<c;)l[f+a]=t[a];for(;++e<u;)l[f+r[e]]=n[i++];return l}function cr(n,t){return function(r,e,u){var i=t?t():{};if(e=Lr(e,u,3),ka(r))for(var o=-1,a=r.length;++o<a;){var c=r[o];n(i,c,e(c,o,r),r)}else So(r,function(t,r,u){n(i,t,e(t,r,u),u)});return i}}function lr(n){return su(function(t,r){var e=-1,u=null==t?0:r.length,i=u>2&&r[u-2],o=u>2&&r[2],a=u>1&&r[u-1];for("function"==typeof i?(i=ur(i,a,5),u-=2):(i="function"==typeof a?a:null,u-=i?1:0),o&&Vr(r[0],r[1],o)&&(i=3>u?null:i,u=1);++e<u;){var c=r[e];c&&n(t,c,i)}return t})}function fr(n,t){return function(r,e){var u=r?zo(r):0;if(!Gr(u))return n(r,e);for(var i=t?u:-1,o=ue(r);(t?i--:++i<u)&&e(o[i],i,o)!==!1;);return r}}function sr(n){return function(t,r,e){for(var u=ue(t),i=e(t),o=i.length,a=n?o:-1;n?a--:++a<o;){var c=i[a];if(r(u[c],c,u)===!1)break}return t}}function pr(n,t){function r(){var u=this&&this!==it&&this instanceof r?e:n;return u.apply(t,arguments)}var e=vr(n);return r}function hr(n){return function(t){for(var r=-1,e=si(Xu(t)),u=e.length,i="";++r<u;)i=n(i,e[r],r);return i}}function vr(n){return function(){var t=$o(n.prototype),r=n.apply(t,arguments);return ju(r)?r:t}}function _r(n){function t(r,e,u){u&&Vr(r,e,u)&&(e=null);var i=$r(r,n,null,null,null,null,null,e);return i.placeholder=t.placeholder,i}return t}function gr(n,t){return function(r,e,u){u&&Vr(r,e,u)&&(e=null);var i=Lr(),o=null==e;if(i===wt&&o||(o=!1,e=i(e,u,3)),o){var a=ka(r);if(a||!Tu(r))return n(a?r:ee(r));e=s}return Br(r,e,t)}}function yr(n,t){return function(r,e,u){if(e=Lr(e,u,3),ka(r)){var i=a(r,e,t);return i>-1?r[i]:E}return Ot(r,e,n)}}function dr(n){return function(t,r,e){return t&&t.length?(r=Lr(r,e,3),a(t,r,n)):-1}}function mr(n){return function(t,r,e){return r=Lr(r,e,3),Ot(t,r,n,!0)}}function wr(n){return function(){var t=arguments.length;if(!t)return function(){return arguments[0]};for(var r,u=n?t:-1,i=0,o=Oi(t);n?u--:++u<t;){var a=o[i++]=arguments[u];if("function"!=typeof a)throw new Bi(V);var c=r?"":Po(a);r="wrapper"==c?new e([]):r}for(u=r?-1:t;++u<t;){a=o[u],c=Po(a);var l="wrapper"==c?Fo(a):null;r=l&&Hr(l[0])&&l[1]==(L|S|W|N)&&!l[4].length&&1==l[9]?r[Po(l[0])].apply(r,l[3]):1==a.length&&Hr(a)?r[c]():r.thru(a)}return function(){var n=arguments;if(r&&1==n.length&&ka(n[0]))return r.plant(n[0]).value();for(var e=0,u=o[e].apply(this,n);++e<t;)u=o[e].call(this,u);return u}}}function br(n,t){return function(r,e,u){return"function"==typeof e&&u===E&&ka(r)?n(r,e):t(r,ur(e,u,3))}}function xr(n){return function(t,r,e){return("function"!=typeof r||e!==E)&&(r=ur(r,e,3)),n(t,r,zu)}}function Ar(n){return function(t,r,e){return("function"!=typeof r||e!==E)&&(r=ur(r,e,3)),n(t,r)}}function jr(n){return function(t,r,e){var u={};return r=Lr(r,e,3),Rt(t,function(t,e,i){var o=r(t,e,i);e=n?o:e,t=n?t:o,u[e]=t}),u}}function Cr(n){return function(t,r,e){return t=f(t),(n?t:"")+Ir(t,r,e)+(n?"":t)}}function kr(n){var t=su(function(r,e){var u=x(e,t.placeholder);return $r(r,n,null,e,u)});return t}function Or(n,t){return function(r,e,u,i){var o=arguments.length<3;return"function"==typeof e&&i===E&&ka(r)?n(r,e,u,o):Vt(r,Lr(e,i,4),u,o,t)}}function Er(n,t,r,e,u,i,o,a,c,l){function f(){for(var m=arguments.length,w=m,b=Oi(m);w--;)b[w]=arguments[w];if(e&&(b=or(b,e,u)),i&&(b=ar(b,i,o)),v||g){var A=f.placeholder,j=x(b,A);if(m-=j.length,l>m){var C=a?tt(a):null,k=vo(l-m,0),O=v?j:null,I=v?null:j,$=v?b:null,S=v?null:b;t|=v?W:B,t&=~(v?B:W),_||(t&=~(R|T));var U=[n,t,r,$,O,S,I,C,c,k],L=Er.apply(E,U);return Hr(n)&&qo(L,U),L.placeholder=A,L}}var N=p?r:this;h&&(n=N[d]),a&&(b=ne(b,a)),s&&c<b.length&&(b.length=c);var F=this&&this!==it&&this instanceof f?y||vr(n):n;return F.apply(N,b)}var s=t&L,p=t&R,h=t&T,v=t&S,_=t&$,g=t&U,y=!h&&vr(n),d=n;return f}function Ir(n,t,r){var e=n.length;if(t=+t,e>=t||!po(t))return"";var u=t-e;return r=null==r?" ":r+"",ei(r,Gi(u/r.length)).slice(0,u)}function Rr(n,t,r,e){function u(){for(var t=-1,a=arguments.length,c=-1,l=e.length,f=Oi(a+l);++c<l;)f[c]=e[c];for(;a--;)f[c++]=arguments[++t];var s=this&&this!==it&&this instanceof u?o:n;return s.apply(i?r:this,f)}var i=t&R,o=vr(n);return u}function Tr(n){return function(t,r,e,u){var i=Lr(e);return i===wt&&null==e?rr(t,r,n):er(t,r,i(e,u,1),n)}}function $r(n,t,r,e,u,i,o,a){var c=t&T;if(!c&&"function"!=typeof n)throw new Bi(V);var l=e?e.length:0;if(l||(t&=~(W|B),e=u=null),l-=u?u.length:0,t&B){var f=e,s=u;e=u=null}var p=c?null:Fo(n),h=[n,t,r,e,u,f,s,i,o,a];if(p&&(Xr(h,p),t=h[1],a=h[9]),h[9]=null==a?c?0:n.length:vo(a-l,0)||0,t==R)var v=pr(h[0],h[2]);else v=t!=W&&t!=(R|W)||h[4].length?Er.apply(E,h):Rr.apply(E,h);var _=p?Lo:qo;return _(v,h)}function Sr(n,t,r,e,u,i,o){var a=-1,c=n.length,l=t.length,f=!0;if(c!=l&&!(u&&l>c))return!1;for(;f&&++a<c;){var s=n[a],p=t[a];if(f=E,e&&(f=u?e(p,s,a):e(s,p,a)),f===E)if(u)for(var h=l;h--&&(p=t[h],!(f=s&&s===p||r(s,p,e,u,i,o))););else f=s&&s===p||r(s,p,e,u,i,o)}return!!f}function Ur(n,t,r){switch(r){case J:case X:return+n==+t;case Z:return n.name==t.name&&n.message==t.message;case tn:return n!=+n?t!=+t:n==+t;case en:case on:return n==t+""}return!1}function Wr(n,t,r,e,u,i,o){var a=Na(n),c=a.length,l=Na(t),f=l.length;if(c!=f&&!u)return!1;for(var s=u,p=-1;++p<c;){var h=a[p],v=u?h in t:Mi.call(t,h);if(v){var _=n[h],g=t[h];v=E,e&&(v=u?e(g,_,h):e(_,g,h)),v===E&&(v=_&&_===g||r(_,g,e,u,i,o))}if(!v)return!1;s||(s="constructor"==h)}if(!s){var y=n.constructor,d=t.constructor;if(y!=d&&"constructor"in n&&"constructor"in t&&!("function"==typeof y&&y instanceof y&&"function"==typeof d&&d instanceof d))return!1}return!0}function Br(n,t,r){var e=r?xo:bo,u=e,i=u;return So(n,function(n,o,a){var c=t(n,o,a);((r?u>c:c>u)||c===e&&c===i)&&(u=c,i=n)}),i}function Lr(n,r,e){var u=t.callback||pi;return u=u===pi?wt:u,e?u(n,r,e):u}function Nr(n,r,e){var u=t.indexOf||ye;return u=u===ye?c:u,n?u(n,r,e):u}function Fr(n,t,r){for(var e=-1,u=r?r.length:0;++e<u;){var i=r[e],o=i.size;switch(i.type){case"drop":n+=o;break;case"dropRight":t-=o;break;case"take":t=_o(t,n+o);break;case"takeRight":n=vo(n,t-o)}}return{start:n,end:t}}function Pr(n){var t=n.length,r=new n.constructor(t);return t&&"string"==typeof n[0]&&Mi.call(n,"index")&&(r.index=n.index,r.input=n.input),r}function zr(n){var t=n.constructor;return"function"==typeof t&&t instanceof t||(t=Si),new t}function Mr(n,t,r){var e=n.constructor;switch(t){case cn:return ir(n);case J:case X:return new e(+n);case ln:case fn:case sn:case pn:case hn:case vn:case _n:case gn:case yn:var u=n.buffer;return new e(r?ir(u):u,n.byteOffset,n.length);case tn:case on:return new e(n);case en:var i=new e(n.source,Bn.exec(n));i.lastIndex=n.lastIndex}return i}function qr(n,t,r){null==n||Yr(t,n)||(t=ie(t),n=1==t.length?n:St(n,Yt(t,0,-1)),t=we(t));var e=null==n?n:n[t];return null==e?E:e.apply(n,r)}function Dr(n){return null!=n&&Gr(zo(n))}function Kr(n,t){return n=+n,t=null==t?Oo:t,n>-1&&n%1==0&&t>n}function Vr(n,t,r){if(!ju(r))return!1;var e=typeof t;if("number"==e?Dr(r)&&Kr(t,r.length):"string"==e&&t in r){var u=r[t];return n===n?n===u:u!==u}return!1}function Yr(n,t){var r=typeof n;if("string"==r&&In.test(n)||"number"==r)return!0;if(ka(n))return!1;var e=!En.test(n);return e||null!=t&&n in ue(t)}function Hr(n){var r=Po(n);return!!r&&n===t[r]&&r in u.prototype}function Gr(n){return"number"==typeof n&&n>-1&&n%1==0&&Oo>=n}function Jr(n){return n===n&&!ju(n)}function Xr(n,t){var r=n[1],e=t[1],u=r|e,i=L>u,o=e==L&&r==S||e==L&&r==N&&n[7].length<=t[8]||e==(L|N)&&r==S;if(!i&&!o)return n;e&R&&(n[2]=t[2],u|=r&R?0:$);var a=t[3];if(a){var c=n[3];n[3]=c?or(c,a,t[4]):tt(a),n[4]=c?x(n[3],Y):tt(t[4])}return a=t[5],a&&(c=n[5],n[5]=c?ar(c,a,t[6]):tt(a),n[6]=c?x(n[5],Y):tt(t[6])),a=t[7],a&&(n[7]=tt(a)),e&L&&(n[8]=null==n[8]?t[8]:_o(n[8],t[8])),null==n[9]&&(n[9]=t[9]),n[0]=t[0],n[1]=u,n}function Zr(n,t){n=ue(n);for(var r=-1,e=t.length,u={};++r<e;){var i=t[r];i in n&&(u[i]=n[i])}return u}function Qr(n,t){var r={};return It(n,function(n,e,u){t(n,e,u)&&(r[e]=n)}),r}function ne(n,t){for(var r=n.length,e=_o(t.length,r),u=tt(n);e--;){var i=t[e];n[e]=Kr(i,r)?u[i]:E}return n}function te(n){var r;t.support;if(!w(n)||Di.call(n)!=rn||!Mi.call(n,"constructor")&&(r=n.constructor,"function"==typeof r&&!(r instanceof r)))return!1;var e;return It(n,function(n,t){e=t}),e===E||Mi.call(n,e)}function re(n){for(var r=zu(n),e=r.length,u=e&&n.length,i=t.support,o=u&&Gr(u)&&(ka(n)||i.nonEnumArgs&&yu(n)),a=-1,c=[];++a<e;){var l=r[a];(o&&Kr(l,u)||Mi.call(n,l))&&c.push(l)}return c}function ee(n){return null==n?[]:Dr(n)?ju(n)?n:Si(n):Vu(n)}function ue(n){return ju(n)?n:Si(n)}function ie(n){if(ka(n))return n;var t=[];return f(n).replace(Rn,function(n,r,e,u){t.push(e?u.replace(Un,"$1"):r||n)}),t}function oe(n){return n instanceof u?n.clone():new e(n.__wrapped__,n.__chain__,tt(n.__actions__))}function ae(n,t,r){t=(r?Vr(n,t,r):null==t)?1:vo(+t||1,1);for(var e=0,u=n?n.length:0,i=-1,o=Oi(Gi(u/t));u>e;)o[++i]=Yt(n,e,e+=t);return o}function ce(n){for(var t=-1,r=n?n.length:0,e=-1,u=[];++t<r;){var i=n[t];i&&(u[++e]=i)}return u}function le(n,t,r){var e=n?n.length:0;return e?((r?Vr(n,t,r):null==t)&&(t=1),Yt(n,0>t?0:t)):[]}function fe(n,t,r){var e=n?n.length:0;return e?((r?Vr(n,t,r):null==t)&&(t=1),t=e-(+t||0),Yt(n,0,0>t?0:t)):[]}function se(n,t,r){return n&&n.length?nr(n,Lr(t,r,3),!0,!0):[]}function pe(n,t,r){return n&&n.length?nr(n,Lr(t,r,3),!0):[]}function he(n,t,r,e){var u=n?n.length:0;return u?(r&&"number"!=typeof r&&Vr(n,t,r)&&(r=0,e=u),Ct(n,t,r,e)):[]}function ve(n){return n?n[0]:E}function _e(n,t,r){var e=n?n.length:0;return r&&Vr(n,t,r)&&(t=!1),e?Et(n,t):[]}function ge(n){var t=n?n.length:0;return t?Et(n,!0):[]}function ye(n,t,r){var e=n?n.length:0;if(!e)return-1;if("number"==typeof r)r=0>r?vo(e+r,0):r;else if(r){var u=rr(n,t),i=n[u];return(t===t?t===i:i!==i)?u:-1}return c(n,t,r||0)}function de(n){return fe(n,1)}function me(){for(var n=[],t=-1,r=arguments.length,e=[],u=Nr(),i=u==c,o=[];++t<r;){var a=arguments[t];Dr(a)&&(n.push(a),e.push(i&&a.length>=120?No(t&&a):null))}if(r=n.length,2>r)return o;var l=n[0],f=-1,s=l?l.length:0,p=e[0];n:for(;++f<s;)if(a=l[f],(p?Qn(p,a):u(o,a,0))<0){for(t=r;--t;){var h=e[t];if((h?Qn(h,a):u(n[t],a,0))<0)continue n}p&&p.push(a),o.push(a)}return o}function we(n){var t=n?n.length:0;return t?n[t-1]:E}function be(n,t,r){var e=n?n.length:0;if(!e)return-1;var u=e;if("number"==typeof r)u=(0>r?vo(e+r,0):_o(r||0,e-1))+1;else if(r){u=rr(n,t,!0)-1;var i=n[u];return(t===t?t===i:i!==i)?u:-1}if(t!==t)return m(n,u,!0);for(;u--;)if(n[u]===t)return u;return-1}function xe(){var n=arguments,t=n[0];if(!t||!t.length)return t;for(var r=0,e=Nr(),u=n.length;++r<u;)for(var i=0,o=n[r];(i=e(t,o,i))>-1;)io.call(t,i,1);return t}function Ae(n,t,r){var e=[];if(!n||!n.length)return e;var u=-1,i=[],o=n.length;for(t=Lr(t,r,3);++u<o;){var a=n[u];t(a,u,n)&&(e.push(a),i.push(u))}return Dt(n,i),e}function je(n){return le(n,1)}function Ce(n,t,r){var e=n?n.length:0;return e?(r&&"number"!=typeof r&&Vr(n,t,r)&&(t=0,r=e),Yt(n,t,r)):[]}function ke(n,t,r){var e=n?n.length:0;return e?((r?Vr(n,t,r):null==t)&&(t=1),Yt(n,0,0>t?0:t)):[]}function Oe(n,t,r){var e=n?n.length:0;return e?((r?Vr(n,t,r):null==t)&&(t=1),t=e-(+t||0),Yt(n,0>t?0:t)):[]}function Ee(n,t,r){return n&&n.length?nr(n,Lr(t,r,3),!1,!0):[]}function Ie(n,t,r){return n&&n.length?nr(n,Lr(t,r,3)):[]}function Re(n,t,r,e){var u=n?n.length:0;if(!u)return[];null!=t&&"boolean"!=typeof t&&(e=r,r=Vr(n,t,e)?null:t,t=!1);var i=Lr();return(i!==wt||null!=r)&&(r=i(r,e,3)),t&&Nr()==c?A(n,r):Zt(n,r)}function Te(n){if(!n||!n.length)return[];var t=-1,r=0;n=at(n,function(n){return Dr(n)?(r=vo(n.length,r),!0):void 0});for(var e=Oi(r);++t<r;)e[t]=ct(n,Mt(t));return e}function $e(n,t,r){var e=n?n.length:0;if(!e)return[];var u=Te(n);return null==t?u:(t=ur(t,r,4),ct(u,function(n){return st(n,t,E,!0)}))}function Se(){for(var n=-1,t=arguments.length;++n<t;){var r=arguments[n];if(Dr(r))var e=e?At(e,r).concat(At(r,e)):r}return e?Zt(e):[]}function Ue(n,t){var r=-1,e=n?n.length:0,u={};for(!e||t||ka(n[0])||(t=[]);++r<e;){var i=n[r];t?u[i]=t[r]:i&&(u[i[0]]=i[1])}return u}function We(n){var r=t(n);return r.__chain__=!0,r}function Be(n,t,r){return t.call(r,n),n}function Le(n,t,r){return t.call(r,n)}function Ne(){return We(this)}function Fe(){return new e(this.value(),this.__chain__)}function Pe(n){for(var t,e=this;e instanceof r;){var u=oe(e);t?i.__wrapped__=u:t=u;var i=u;e=e.__wrapped__}return i.__wrapped__=n,t}function ze(){var n=this.__wrapped__;return n instanceof u?(this.__actions__.length&&(n=new u(this)),new e(n.reverse(),this.__chain__)):this.thru(function(n){return n.reverse()})}function Me(){return this.value()+""}function qe(){return tr(this.__wrapped__,this.__actions__)}function De(n,t,r){var e=ka(n)?ut:jt;return r&&Vr(n,t,r)&&(t=null),("function"!=typeof t||r!==E)&&(t=Lr(t,r,3)),e(n,t)}function Ke(n,t,r){var e=ka(n)?at:kt;return t=Lr(t,r,3),e(n,t)}function Ve(n,t){return ra(n,Nt(t))}function Ye(n,t,r,e){var u=n?zo(n):0;return Gr(u)||(n=Vu(n),u=n.length),u?(r="number"!=typeof r||e&&Vr(t,r,e)?0:0>r?vo(u+r,0):r||0,"string"==typeof n||!ka(n)&&Tu(n)?u>r&&n.indexOf(t,r)>-1:Nr(n,t,r)>-1):!1}function He(n,t,r){var e=ka(n)?ct:Lt;return t=Lr(t,r,3),e(n,t)}function Ge(n,t){return He(n,wi(t))}function Je(n,t,r){var e=ka(n)?at:kt;return t=Lr(t,r,3),e(n,function(n,r,e){return!t(n,r,e)})}function Xe(n,t,r){if(r?Vr(n,t,r):null==t){n=ee(n);var e=n.length;return e>0?n[Kt(0,e-1)]:E}var u=Ze(n);return u.length=_o(0>t?0:+t||0,u.length),u}function Ze(n){n=ee(n);for(var t=-1,r=n.length,e=Oi(r);++t<r;){var u=Kt(0,t);t!=u&&(e[t]=e[u]),e[u]=n[t]}return e}function Qe(n){var t=n?zo(n):0;return Gr(t)?t:Na(n).length}function nu(n,t,r){var e=ka(n)?ht:Ht;return r&&Vr(n,t,r)&&(t=null),("function"!=typeof t||r!==E)&&(t=Lr(t,r,3)),e(n,t)}function tu(n,t,r){if(null==n)return[];r&&Vr(n,t,r)&&(t=null);var e=-1;t=Lr(t,r,3);var u=Lt(n,function(n,r,u){return{criteria:t(n,r,u),index:++e,value:n}});return Gt(u,v)}function ru(n,t,r,e){return null==n?[]:(e&&Vr(t,r,e)&&(r=null),ka(t)||(t=null==t?[]:[t]),ka(r)||(r=null==r?[]:[r]),Jt(n,t,r))}function eu(n,t){return Ke(n,Nt(t))}function uu(n,t){if("function"!=typeof t){if("function"!=typeof n)throw new Bi(V);var r=n;n=t,t=r}return n=po(n=+n)?n:0,function(){return--n<1?t.apply(this,arguments):void 0}}function iu(n,t,r){return r&&Vr(n,t,r)&&(t=null),t=n&&null==t?n.length:vo(+t||0,0),$r(n,L,null,null,null,null,t)}function ou(n,t){var r;if("function"!=typeof t){if("function"!=typeof n)throw new Bi(V);var e=n;n=t,t=e}return function(){return--n>0&&(r=t.apply(this,arguments)),1>=n&&(t=null),r}}function au(n,t,r){function e(){p&&Ji(p),c&&Ji(c),c=p=h=E}function u(){var r=t-(ha()-f);if(0>=r||r>t){c&&Ji(c);var e=h;c=p=h=E,e&&(v=ha(),l=n.apply(s,a),p||c||(a=s=null))}else p=uo(u,r)}function i(){p&&Ji(p),c=p=h=E,(g||_!==t)&&(v=ha(),l=n.apply(s,a),p||c||(a=s=null))}function o(){if(a=arguments,f=ha(),s=this,h=g&&(p||!y),_===!1)var r=y&&!p;else{c||y||(v=f);var e=_-(f-v),o=0>=e||e>_;o?(c&&(c=Ji(c)),v=f,l=n.apply(s,a)):c||(c=uo(i,e))}return o&&p?p=Ji(p):p||t===_||(p=uo(u,t)),r&&(o=!0,l=n.apply(s,a)),!o||p||c||(a=s=null),l}var a,c,l,f,s,p,h,v=0,_=!1,g=!0;if("function"!=typeof n)throw new Bi(V);if(t=0>t?0:+t||0,r===!0){var y=!0;g=!1}else ju(r)&&(y=r.leading,_="maxWait"in r&&vo(+r.maxWait||0,t),g="trailing"in r?r.trailing:g);return o.cancel=e,o}function cu(n,t){if("function"!=typeof n||t&&"function"!=typeof t)throw new Bi(V);var r=function(){var e=arguments,u=r.cache,i=t?t.apply(this,e):e[0];if(u.has(i))return u.get(i);var o=n.apply(this,e);return u.set(i,o),o};return r.cache=new cu.Cache,r}function lu(n){if("function"!=typeof n)throw new Bi(V);return function(){return!n.apply(this,arguments)}}function fu(n){return ou(2,n)}function su(n,t){if("function"!=typeof n)throw new Bi(V);return t=vo(t===E?n.length-1:+t||0,0),function(){for(var r=arguments,e=-1,u=vo(r.length-t,0),i=Oi(u);++e<u;)i[e]=r[t+e];switch(t){case 0:return n.call(this,i);case 1:return n.call(this,r[0],i);case 2:return n.call(this,r[0],r[1],i)}var o=Oi(t+1);for(e=-1;++e<t;)o[e]=r[e];return o[t]=i,n.apply(this,o)}}function pu(n){if("function"!=typeof n)throw new Bi(V);return function(t){return n.apply(this,t)}}function hu(n,t,r){var e=!0,u=!0;if("function"!=typeof n)throw new Bi(V);return r===!1?e=!1:ju(r)&&(e="leading"in r?!!r.leading:e,u="trailing"in r?!!r.trailing:u),Hn.leading=e,Hn.maxWait=+t,Hn.trailing=u,au(n,t,Hn)}function vu(n,t){return t=null==t?vi:t,$r(t,W,null,[n],[])}function _u(n,t,r,e){return t&&"boolean"!=typeof t&&Vr(n,t,r)?t=!1:"function"==typeof t&&(e=r,r=t,t=!1),r="function"==typeof r&&ur(r,e,1),bt(n,t,r)}function gu(n,t,r){return t="function"==typeof t&&ur(t,r,1),bt(n,!0,t)}function yu(n){return w(n)&&Dr(n)&&Di.call(n)==H}function du(n){return n===!0||n===!1||w(n)&&Di.call(n)==J}function mu(n){return w(n)&&Di.call(n)==X}function wu(n){return!!n&&1===n.nodeType&&w(n)&&Di.call(n).indexOf("Element")>-1}function bu(n){return null==n?!0:Dr(n)&&(ka(n)||Tu(n)||yu(n)||w(n)&&Ea(n.splice))?!n.length:!Na(n).length}function xu(n,t,r,e){if(r="function"==typeof r&&ur(r,e,3),!r&&Jr(n)&&Jr(t))return n===t;var u=r?r(n,t):E;return u===E?Ut(n,t,r):!!u}function Au(n){return w(n)&&"string"==typeof n.message&&Di.call(n)==Z}function ju(n){var t=typeof n;return"function"==t||!!n&&"object"==t}function Cu(n,t,r,e){var u=Na(t),i=u.length;if(!i)return!0;if(null==n)return!1;if(r="function"==typeof r&&ur(r,e,3),n=ue(n),!r&&1==i){var o=u[0],a=t[o];if(Jr(a))return a===n[o]&&(a!==E||o in n)}for(var c=Oi(i),l=Oi(i);i--;)a=c[i]=t[u[i]],l[i]=Jr(a);return Bt(n,u,c,l,r)}function ku(n){return Iu(n)&&n!=+n}function Ou(n){return null==n?!1:Di.call(n)==Q?Vi.test(zi.call(n)):w(n)&&Nn.test(n)}function Eu(n){return null===n}function Iu(n){return"number"==typeof n||w(n)&&Di.call(n)==tn}function Ru(n){return w(n)&&Di.call(n)==en}function Tu(n){return"string"==typeof n||w(n)&&Di.call(n)==on}function $u(n){return w(n)&&Gr(n.length)&&!!Vn[Di.call(n)]}function Su(n){return n===E}function Uu(n){var t=n?zo(n):0;return Gr(t)?t?tt(n):[]:Vu(n)}function Wu(n){return mt(n,zu(n))}function Bu(n,t,r){var e=$o(n);return r&&Vr(n,t,r)&&(t=null),t?To(e,t):e}function Lu(n){return $t(n,zu(n))}function Nu(n,t,r){var e=null==n?E:St(n,ie(t),t+"");return e===E?r:e}function Fu(n,t){if(null==n)return!1;var r=Mi.call(n,t);return r||Yr(t)||(t=ie(t),n=1==t.length?n:St(n,Yt(t,0,-1)),t=we(t),r=null!=n&&Mi.call(n,t)),r}function Pu(n,t,r){r&&Vr(n,t,r)&&(t=null);for(var e=-1,u=Na(n),i=u.length,o={};++e<i;){var a=u[e],c=n[a];t?Mi.call(o,c)?o[c].push(a):o[c]=[a]:o[c]=a}return o}function zu(n){if(null==n)return[];ju(n)||(n=Si(n));var t=n.length;t=t&&Gr(t)&&(ka(n)||Ro.nonEnumArgs&&yu(n))&&t||0;for(var r=n.constructor,e=-1,u="function"==typeof r&&r.prototype===n,i=Oi(t),o=t>0;++e<t;)i[e]=e+"";for(var a in n)o&&Kr(a,t)||"constructor"==a&&(u||!Mi.call(n,a))||i.push(a);return i}function Mu(n){for(var t=-1,r=Na(n),e=r.length,u=Oi(e);++t<e;){var i=r[t];u[t]=[i,n[i]]}return u}function qu(n,t,r){var e=null==n?E:n[t];return e===E&&(null==n||Yr(t,n)||(t=ie(t),n=1==t.length?n:St(n,Yt(t,0,-1)),e=null==n?E:n[we(t)]),e=e===E?r:e),Ea(e)?e.call(n):e}function Du(n,t,r){if(null==n)return n;var e=t+"";t=null!=n[e]||Yr(t,n)?[e]:ie(t);for(var u=-1,i=t.length,o=i-1,a=n;null!=a&&++u<i;){var c=t[u];ju(a)&&(u==o?a[c]=r:null==a[c]&&(a[c]=Kr(t[u+1])?[]:{})),a=a[c]}return n}function Ku(n,t,r,e){var u=ka(n)||$u(n);if(t=Lr(t,e,4),null==r)if(u||ju(n)){var i=n.constructor;r=u?ka(n)?new i:[]:$o(Ea(i)&&i.prototype)}else r={};return(u?rt:Rt)(n,function(n,e,u){return t(r,n,e,u)}),r}function Vu(n){return Qt(n,Na(n))}function Yu(n){return Qt(n,zu(n))}function Hu(n,t,r){return t=+t||0,"undefined"==typeof r?(r=t,t=0):r=+r||0,n>=_o(t,r)&&n<vo(t,r)}function Gu(n,t,r){r&&Vr(n,t,r)&&(t=r=null);var e=null==n,u=null==t;if(null==r&&(u&&"boolean"==typeof n?(r=n,n=1):"boolean"==typeof t&&(r=t,u=!0)),e&&u&&(t=1,u=!1),n=+n||0,u?(t=n,n=0):t=+t||0,r||n%1||t%1){var i=wo();return _o(n+i*(t-n+parseFloat("1e-"+((i+"").length-1))),t)}return Kt(n,t)}function Ju(n){return n=f(n),n&&n.charAt(0).toUpperCase()+n.slice(1)}function Xu(n){return n=f(n),n&&n.replace(Fn,g).replace(Sn,"")}function Zu(n,t,r){n=f(n),t+="";var e=n.length;return r=r===E?e:_o(0>r?0:+r||0,e),r-=t.length,r>=0&&n.indexOf(t,r)==r}function Qu(n){return n=f(n),n&&jn.test(n)?n.replace(xn,y):n}function ni(n){return n=f(n),n&&$n.test(n)?n.replace(Tn,"\\$&"):n}function ti(n,t,r){n=f(n),t=+t;var e=n.length;if(e>=t||!po(t))return n;var u=(t-e)/2,i=Xi(u),o=Gi(u);
return r=Ir("",o,r),r.slice(0,i)+n+r}function ri(n,t,r){return r&&Vr(n,t,r)&&(t=0),mo(n,t)}function ei(n,t){var r="";if(n=f(n),t=+t,1>t||!n||!po(t))return r;do t%2&&(r+=n),t=Xi(t/2),n+=n;while(t);return r}function ui(n,t,r){return n=f(n),r=null==r?0:_o(0>r?0:+r||0,n.length),n.lastIndexOf(t,r)==r}function ii(n,r,e){var u=t.templateSettings;e&&Vr(n,r,e)&&(r=e=null),n=f(n),r=yt(To({},e||r),u,gt);var i,o,a=yt(To({},r.imports),u.imports,gt),c=Na(a),l=Qt(a,c),s=0,p=r.interpolate||Pn,h="__p += '",v=Ui((r.escape||Pn).source+"|"+p.source+"|"+(p===On?Wn:Pn).source+"|"+(r.evaluate||Pn).source+"|$","g"),_="//# sourceURL="+("sourceURL"in r?r.sourceURL:"lodash.templateSources["+ ++Kn+"]")+"\n";n.replace(v,function(t,r,e,u,a,c){return e||(e=u),h+=n.slice(s,c).replace(zn,d),r&&(i=!0,h+="' +\n__e("+r+") +\n'"),a&&(o=!0,h+="';\n"+a+";\n__p += '"),e&&(h+="' +\n((__t = ("+e+")) == null ? '' : __t) +\n'"),s=c+t.length,t}),h+="';\n";var g=r.variable;g||(h="with (obj) {\n"+h+"\n}\n"),h=(o?h.replace(dn,""):h).replace(mn,"$1").replace(wn,"$1;"),h="function("+(g||"obj")+") {\n"+(g?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(i?", __e = _.escape":"")+(o?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+h+"return __p\n}";var y=Ja(function(){return Ri(c,_+"return "+h).apply(E,l)});if(y.source=h,Au(y))throw y;return y}function oi(n,t,r){var e=n;return(n=f(n))?(r?Vr(e,t,r):null==t)?n.slice(j(n),C(n)+1):(t+="",n.slice(p(n,t),h(n,t)+1)):n}function ai(n,t,r){var e=n;return n=f(n),n?(r?Vr(e,t,r):null==t)?n.slice(j(n)):n.slice(p(n,t+"")):n}function ci(n,t,r){var e=n;return n=f(n),n?(r?Vr(e,t,r):null==t)?n.slice(0,C(n)+1):n.slice(0,h(n,t+"")+1):n}function li(n,t,r){r&&Vr(n,t,r)&&(t=null);var e=F,u=P;if(null!=t)if(ju(t)){var i="separator"in t?t.separator:i;e="length"in t?+t.length||0:e,u="omission"in t?f(t.omission):u}else e=+t||0;if(n=f(n),e>=n.length)return n;var o=e-u.length;if(1>o)return u;var a=n.slice(0,o);if(null==i)return a+u;if(Ru(i)){if(n.slice(o).search(i)){var c,l,s=n.slice(0,o);for(i.global||(i=Ui(i.source,(Bn.exec(i)||"")+"g")),i.lastIndex=0;c=i.exec(s);)l=c.index;a=a.slice(0,null==l?o:l)}}else if(n.indexOf(i,o)!=o){var p=a.lastIndexOf(i);p>-1&&(a=a.slice(0,p))}return a+u}function fi(n){return n=f(n),n&&An.test(n)?n.replace(bn,k):n}function si(n,t,r){return r&&Vr(n,t,r)&&(t=null),n=f(n),n.match(t||Mn)||[]}function pi(n,t,r){return r&&Vr(n,t,r)&&(t=null),w(n)?_i(n):wt(n,t)}function hi(n){return function(){return n}}function vi(n){return n}function _i(n){return Nt(bt(n,!0))}function gi(n,t){return Ft(n,bt(t,!0))}function yi(n,t,r){if(null==r){var e=ju(t),u=e&&Na(t),i=u&&u.length&&$t(t,u);(i?i.length:e)||(i=!1,r=t,t=n,n=this)}i||(i=$t(t,Na(t)));var o=!0,a=-1,c=Ea(n),l=i.length;r===!1?o=!1:ju(r)&&"chain"in r&&(o=r.chain);for(;++a<l;){var f=i[a],s=t[f];n[f]=s,c&&(n.prototype[f]=function(t){return function(){var r=this.__chain__;if(o||r){var e=n(this.__wrapped__),u=e.__actions__=tt(this.__actions__);return u.push({func:t,args:arguments,thisArg:n}),e.__chain__=r,e}var i=[this.value()];return no.apply(i,arguments),t.apply(n,i)}}(s))}return n}function di(){return n._=Ki,this}function mi(){}function wi(n){return Yr(n)?Mt(n):qt(n)}function bi(n){return function(t){return St(n,ie(t),t+"")}}function xi(n,t,r){r&&Vr(n,t,r)&&(t=r=null),n=+n||0,r=null==r?1:+r||0,null==t?(t=n,n=0):t=+t||0;for(var e=-1,u=vo(Gi((t-n)/(r||1)),0),i=Oi(u);++e<u;)i[e]=n,n+=r;return i}function Ai(n,t,r){if(n=Xi(n),1>n||!po(n))return[];var e=-1,u=Oi(_o(n,Ao));for(t=ur(t,r,1);++e<n;)Ao>e?u[e]=t(e):t(e);return u}function ji(n){var t=++qi;return f(n)+t}function Ci(n,t){return(+n||0)+(+t||0)}function ki(n,t,r){r&&Vr(n,t,r)&&(t=null);var e=Lr(),u=null==t;return e===wt&&u||(u=!1,t=e(t,r,3)),u?vt(ka(n)?n:ee(n)):Xt(n,t)}n=n?ot.defaults(it.Object(),n,ot.pick(it,Dn)):it;var Oi=n.Array,Ei=n.Date,Ii=n.Error,Ri=n.Function,Ti=n.Math,$i=n.Number,Si=n.Object,Ui=n.RegExp,Wi=n.String,Bi=n.TypeError,Li=Oi.prototype,Ni=Si.prototype,Fi=Wi.prototype,Pi=(Pi=n.window)&&Pi.document,zi=Ri.prototype.toString,Mi=Ni.hasOwnProperty,qi=0,Di=Ni.toString,Ki=n._,Vi=Ui("^"+ni(Di).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Yi=Ou(Yi=n.ArrayBuffer)&&Yi,Hi=Ou(Hi=Yi&&new Yi(0).slice)&&Hi,Gi=Ti.ceil,Ji=n.clearTimeout,Xi=Ti.floor,Zi=Ou(Zi=Si.getOwnPropertySymbols)&&Zi,Qi=Ou(Qi=Si.getPrototypeOf)&&Qi,no=Li.push,to=Ou(to=Si.preventExtensions)&&to,ro=Ni.propertyIsEnumerable,eo=Ou(eo=n.Set)&&eo,uo=n.setTimeout,io=Li.splice,oo=Ou(oo=n.Uint8Array)&&oo,ao=Ou(ao=n.WeakMap)&&ao,co=function(){try{var t=Ou(t=n.Float64Array)&&t,r=new t(new Yi(10),0,1)&&t}catch(e){}return r}(),lo=function(){var n=to&&Ou(n=Si.assign)&&n;try{if(n){var t=to({1:0});t[0]=1}}catch(r){try{n(t,"xo")}catch(r){}return!t[1]&&n}return!1}(),fo=Ou(fo=Oi.isArray)&&fo,so=Ou(so=Si.create)&&so,po=n.isFinite,ho=Ou(ho=Si.keys)&&ho,vo=Ti.max,_o=Ti.min,go=Ou(go=Ei.now)&&go,yo=Ou(yo=$i.isFinite)&&yo,mo=n.parseInt,wo=Ti.random,bo=$i.NEGATIVE_INFINITY,xo=$i.POSITIVE_INFINITY,Ao=Ti.pow(2,32)-1,jo=Ao-1,Co=Ao>>>1,ko=co?co.BYTES_PER_ELEMENT:0,Oo=Ti.pow(2,53)-1,Eo=ao&&new ao,Io={},Ro=t.support={};!function(n){var t=function(){this.x=n},r=arguments,e=[];t.prototype={valueOf:n,y:n};for(var u in new t)e.push(u);Ro.funcDecomp=/\bthis\b/.test(function(){return this}),Ro.funcNames="string"==typeof Ri.name;try{Ro.dom=11===Pi.createDocumentFragment().nodeType}catch(i){Ro.dom=!1}try{Ro.nonEnumArgs=!ro.call(r,1)}catch(i){Ro.nonEnumArgs=!0}}(1,0),t.templateSettings={escape:Cn,evaluate:kn,interpolate:On,variable:"",imports:{_:t}};var To=lo||function(n,t){return null==t?n:mt(t,Mo(t),mt(t,Na(t),n))},$o=function(){function t(){}return function(r){if(ju(r)){t.prototype=r;var e=new t;t.prototype=null}return e||n.Object()}}(),So=fr(Rt),Uo=fr(Tt,!0),Wo=sr(),Bo=sr(!0),Lo=Eo?function(n,t){return Eo.set(n,t),n}:vi;Hi||(ir=Yi&&oo?function(n){var t=n.byteLength,r=co?Xi(t/ko):0,e=r*ko,u=new Yi(t);if(r){var i=new co(u,0,r);i.set(new co(n,0,r))}return t!=e&&(i=new oo(u,e),i.set(new oo(n,e))),u}:hi(null));var No=so&&eo?function(n){return new Zn(n)}:hi(null),Fo=Eo?function(n){return Eo.get(n)}:mi,Po=function(){return Ro.funcNames?"constant"==hi.name?Mt("name"):function(n){for(var t=n.name,r=Io[t],e=r?r.length:0;e--;){var u=r[e],i=u.func;if(null==i||i==n)return u.name}return t}:hi("")}(),zo=Mt("length"),Mo=Zi?function(n){return Zi(ue(n))}:hi([]),qo=function(){var n=0,t=0;return function(r,e){var u=ha(),i=M-(u-t);if(t=u,i>0){if(++n>=z)return r}else n=0;return Lo(r,e)}}(),Do=su(function(n,t){return Dr(n)?At(n,Et(t,!1,!0)):[]}),Ko=dr(),Vo=dr(!0),Yo=su(function(n,t){t=Et(t);var r=dt(n,t);return Dt(n,t.sort(o)),r}),Ho=Tr(),Go=Tr(!0),Jo=su(function(n){return Zt(Et(n,!1,!0))}),Xo=su(function(n,t){return Dr(n)?At(n,t):[]}),Zo=su(Te),Qo=su(function(n){var t=n.length,r=n[t-2],e=n[t-1];return t>2&&"function"==typeof r?t-=2:(r=t>1&&"function"==typeof e?(--t,e):E,e=E),n.length=t,$e(n,r,e)}),na=su(function(n,t){return dt(n,Et(t))}),ta=cr(function(n,t,r){Mi.call(n,r)?++n[r]:n[r]=1}),ra=yr(So),ea=yr(Uo,!0),ua=br(rt,So),ia=br(et,Uo),oa=cr(function(n,t,r){Mi.call(n,r)?n[r].push(t):n[r]=[t]}),aa=cr(function(n,t,r){n[r]=t}),ca=su(function(n,t,r){var e=-1,u="function"==typeof t,i=Yr(t),o=Dr(n)?Oi(n.length):[];return So(n,function(n){var a=u?t:i&&null!=n&&n[t];o[++e]=a?a.apply(n,r):qr(n,t,r)}),o}),la=cr(function(n,t,r){n[r?0:1].push(t)},function(){return[[],[]]}),fa=Or(st,So),sa=Or(pt,Uo),pa=su(function(n,t){if(null==n)return[];var r=t[2];return r&&Vr(t[0],t[1],r)&&(t.length=1),Jt(n,Et(t),[])}),ha=go||function(){return(new Ei).getTime()},va=su(function(n,t,r){var e=R;if(r.length){var u=x(r,va.placeholder);e|=W}return $r(n,e,t,r,u)}),_a=su(function(n,t){t=t.length?Et(t):Lu(n);for(var r=-1,e=t.length;++r<e;){var u=t[r];n[u]=$r(n[u],R,n)}return n}),ga=su(function(n,t,r){var e=R|T;if(r.length){var u=x(r,ga.placeholder);e|=W}return $r(t,e,n,r,u)}),ya=_r(S),da=_r(U),ma=su(function(n,t){return xt(n,1,t)}),wa=su(function(n,t,r){return xt(n,t,r)}),ba=wr(),xa=wr(!0),Aa=kr(W),ja=kr(B),Ca=su(function(n,t){return $r(n,N,null,null,null,Et(t))}),ka=fo||function(n){return w(n)&&Gr(n.length)&&Di.call(n)==G};Ro.dom||(wu=function(n){return!!n&&1===n.nodeType&&w(n)&&!Ia(n)});var Oa=yo||function(n){return"number"==typeof n&&po(n)},Ea=l(/x/)||oo&&!l(oo)?function(n){return Di.call(n)==Q}:l,Ia=Qi?function(n){if(!n||Di.call(n)!=rn)return!1;var t=n.valueOf,r=Ou(t)&&(r=Qi(t))&&Qi(r);return r?n==r||Qi(n)==r:te(n)}:te,Ra=lr(function(n,t,r){return r?yt(n,t,r):To(n,t)}),Ta=su(function(n){var t=n[0];return null==t?t:(n.push(_t),Ra.apply(E,n))}),$a=mr(Rt),Sa=mr(Tt),Ua=xr(Wo),Wa=xr(Bo),Ba=Ar(Rt),La=Ar(Tt),Na=ho?function(n){var t=null!=n&&n.constructor;return"function"==typeof t&&t.prototype===n||"function"!=typeof n&&Dr(n)?re(n):ju(n)?ho(n):[]}:re,Fa=jr(!0),Pa=jr(),za=lr(Pt),Ma=su(function(n,t){if(null==n)return{};if("function"!=typeof t[0]){var t=ct(Et(t),Wi);return Zr(n,At(zu(n),t))}var r=ur(t[0],t[1],3);return Qr(n,function(n,t,e){return!r(n,t,e)})}),qa=su(function(n,t){return null==n?{}:"function"==typeof t[0]?Qr(n,ur(t[0],t[1],3)):Zr(n,Et(t))}),Da=hr(function(n,t,r){return t=t.toLowerCase(),n+(r?t.charAt(0).toUpperCase()+t.slice(1):t)}),Ka=hr(function(n,t,r){return n+(r?"-":"")+t.toLowerCase()}),Va=Cr(),Ya=Cr(!0);8!=mo(qn+"08")&&(ri=function(n,t,r){return(r?Vr(n,t,r):null==t)?t=0:t&&(t=+t),n=oi(n),mo(n,t||(Ln.test(n)?16:10))});var Ha=hr(function(n,t,r){return n+(r?"_":"")+t.toLowerCase()}),Ga=hr(function(n,t,r){return n+(r?" ":"")+(t.charAt(0).toUpperCase()+t.slice(1))}),Ja=su(function(n,t){try{return n.apply(E,t)}catch(r){return Au(r)?r:new Ii(r)}}),Xa=su(function(n,t){return function(r){return qr(r,n,t)}}),Za=su(function(n,t){return function(r){return qr(n,r,t)}}),Qa=gr(lt),nc=gr(ft,!0);return t.prototype=r.prototype,e.prototype=$o(r.prototype),e.prototype.constructor=e,u.prototype=$o(r.prototype),u.prototype.constructor=u,un.prototype["delete"]=an,un.prototype.get=Gn,un.prototype.has=Jn,un.prototype.set=Xn,Zn.prototype.push=nt,cu.Cache=un,t.after=uu,t.ary=iu,t.assign=Ra,t.at=na,t.before=ou,t.bind=va,t.bindAll=_a,t.bindKey=ga,t.callback=pi,t.chain=We,t.chunk=ae,t.compact=ce,t.constant=hi,t.countBy=ta,t.create=Bu,t.curry=ya,t.curryRight=da,t.debounce=au,t.defaults=Ta,t.defer=ma,t.delay=wa,t.difference=Do,t.drop=le,t.dropRight=fe,t.dropRightWhile=se,t.dropWhile=pe,t.fill=he,t.filter=Ke,t.flatten=_e,t.flattenDeep=ge,t.flow=ba,t.flowRight=xa,t.forEach=ua,t.forEachRight=ia,t.forIn=Ua,t.forInRight=Wa,t.forOwn=Ba,t.forOwnRight=La,t.functions=Lu,t.groupBy=oa,t.indexBy=aa,t.initial=de,t.intersection=me,t.invert=Pu,t.invoke=ca,t.keys=Na,t.keysIn=zu,t.map=He,t.mapKeys=Fa,t.mapValues=Pa,t.matches=_i,t.matchesProperty=gi,t.memoize=cu,t.merge=za,t.method=Xa,t.methodOf=Za,t.mixin=yi,t.negate=lu,t.omit=Ma,t.once=fu,t.pairs=Mu,t.partial=Aa,t.partialRight=ja,t.partition=la,t.pick=qa,t.pluck=Ge,t.property=wi,t.propertyOf=bi,t.pull=xe,t.pullAt=Yo,t.range=xi,t.rearg=Ca,t.reject=Je,t.remove=Ae,t.rest=je,t.restParam=su,t.set=Du,t.shuffle=Ze,t.slice=Ce,t.sortBy=tu,t.sortByAll=pa,t.sortByOrder=ru,t.spread=pu,t.take=ke,t.takeRight=Oe,t.takeRightWhile=Ee,t.takeWhile=Ie,t.tap=Be,t.throttle=hu,t.thru=Le,t.times=Ai,t.toArray=Uu,t.toPlainObject=Wu,t.transform=Ku,t.union=Jo,t.uniq=Re,t.unzip=Te,t.unzipWith=$e,t.values=Vu,t.valuesIn=Yu,t.where=eu,t.without=Xo,t.wrap=vu,t.xor=Se,t.zip=Zo,t.zipObject=Ue,t.zipWith=Qo,t.backflow=xa,t.collect=He,t.compose=xa,t.each=ua,t.eachRight=ia,t.extend=Ra,t.iteratee=pi,t.methods=Lu,t.object=Ue,t.select=Ke,t.tail=je,t.unique=Re,yi(t,t),t.add=Ci,t.attempt=Ja,t.camelCase=Da,t.capitalize=Ju,t.clone=_u,t.cloneDeep=gu,t.deburr=Xu,t.endsWith=Zu,t.escape=Qu,t.escapeRegExp=ni,t.every=De,t.find=ra,t.findIndex=Ko,t.findKey=$a,t.findLast=ea,t.findLastIndex=Vo,t.findLastKey=Sa,t.findWhere=Ve,t.first=ve,t.get=Nu,t.has=Fu,t.identity=vi,t.includes=Ye,t.indexOf=ye,t.inRange=Hu,t.isArguments=yu,t.isArray=ka,t.isBoolean=du,t.isDate=mu,t.isElement=wu,t.isEmpty=bu,t.isEqual=xu,t.isError=Au,t.isFinite=Oa,t.isFunction=Ea,t.isMatch=Cu,t.isNaN=ku,t.isNative=Ou,t.isNull=Eu,t.isNumber=Iu,t.isObject=ju,t.isPlainObject=Ia,t.isRegExp=Ru,t.isString=Tu,t.isTypedArray=$u,t.isUndefined=Su,t.kebabCase=Ka,t.last=we,t.lastIndexOf=be,t.max=Qa,t.min=nc,t.noConflict=di,t.noop=mi,t.now=ha,t.pad=ti,t.padLeft=Va,t.padRight=Ya,t.parseInt=ri,t.random=Gu,t.reduce=fa,t.reduceRight=sa,t.repeat=ei,t.result=qu,t.runInContext=O,t.size=Qe,t.snakeCase=Ha,t.some=nu,t.sortedIndex=Ho,t.sortedLastIndex=Go,t.startCase=Ga,t.startsWith=ui,t.sum=ki,t.template=ii,t.trim=oi,t.trimLeft=ai,t.trimRight=ci,t.trunc=li,t.unescape=fi,t.uniqueId=ji,t.words=si,t.all=De,t.any=nu,t.contains=Ye,t.detect=ra,t.foldl=fa,t.foldr=sa,t.head=ve,t.include=Ye,t.inject=fa,yi(t,function(){var n={};return Rt(t,function(r,e){t.prototype[e]||(n[e]=r)}),n}(),!1),t.sample=Xe,t.prototype.sample=function(n){return this.__chain__||null!=n?this.thru(function(t){return Xe(t,n)}):Xe(this.value())},t.VERSION=I,rt(["bind","bindKey","curry","curryRight","partial","partialRight"],function(n){t[n].placeholder=t}),rt(["dropWhile","filter","map","takeWhile"],function(n,t){var r=t!=K,e=t==q;u.prototype[n]=function(n,i){var o=this.__filtered__,a=o&&e?new u(this):this.clone(),c=a.__iteratees__||(a.__iteratees__=[]);return c.push({done:!1,count:0,index:0,iteratee:Lr(n,i,1),limit:-1,type:t}),a.__filtered__=o||r,a}}),rt(["drop","take"],function(n,t){var r=n+"While";u.prototype[n]=function(r){var e=this.__filtered__,u=e&&!t?this.dropWhile():this.clone();if(r=null==r?1:vo(Xi(r)||0,0),e)t?u.__takeCount__=_o(u.__takeCount__,r):we(u.__iteratees__).limit=r;else{var i=u.__views__||(u.__views__=[]);i.push({size:r,type:n+(u.__dir__<0?"Right":"")})}return u},u.prototype[n+"Right"]=function(t){return this.reverse()[n](t).reverse()},u.prototype[n+"RightWhile"]=function(n,t){return this.reverse()[r](n,t).reverse()}}),rt(["first","last"],function(n,t){var r="take"+(t?"Right":"");u.prototype[n]=function(){return this[r](1).value()[0]}}),rt(["initial","rest"],function(n,t){var r="drop"+(t?"":"Right");u.prototype[n]=function(){return this[r](1)}}),rt(["pluck","where"],function(n,t){var r=t?"filter":"map",e=t?Nt:wi;u.prototype[n]=function(n){return this[r](e(n))}}),u.prototype.compact=function(){return this.filter(vi)},u.prototype.reject=function(n,t){return n=Lr(n,t,1),this.filter(function(t){return!n(t)})},u.prototype.slice=function(n,t){n=null==n?0:+n||0;var r=this;return 0>n?r=this.takeRight(-n):n&&(r=this.drop(n)),t!==E&&(t=+t||0,r=0>t?r.dropRight(-t):r.take(t-n)),r},u.prototype.toArray=function(){return this.drop(0)},Rt(u.prototype,function(n,r){var i=t[r];if(i){var o=/^(?:filter|map|reject)|While$/.test(r),a=/^(?:first|last)$/.test(r);t.prototype[r]=function(){var r=arguments,c=this.__chain__,l=this.__wrapped__,f=!!this.__actions__.length,s=l instanceof u,p=r[0],h=s||ka(l);h&&o&&"function"==typeof p&&1!=p.length&&(s=h=!1);var v=s&&!f;if(a&&!c)return v?n.call(l):i.call(t,this.value());var _=function(n){var e=[n];return no.apply(e,r),i.apply(t,e)};if(h){var g=v?l:new u(this),y=n.apply(g,r);if(!a&&(f||y.__actions__)){var d=y.__actions__||(y.__actions__=[]);d.push({func:Le,args:[_],thisArg:t})}return new e(y,c)}return this.thru(_)}}}),rt(["concat","join","pop","push","replace","shift","sort","splice","split","unshift"],function(n){var r=(/^(?:replace|split)$/.test(n)?Fi:Li)[n],e=/^(?:push|sort|unshift)$/.test(n)?"tap":"thru",u=/^(?:join|pop|replace|shift)$/.test(n);t.prototype[n]=function(){var n=arguments;return u&&!this.__chain__?r.apply(this.value(),n):this[e](function(t){return r.apply(t,n)})}}),Rt(u.prototype,function(n,r){var e=t[r];if(e){var u=e.name,i=Io[u]||(Io[u]=[]);i.push({name:r,func:e})}}),Io[Er(null,T).name]=[{name:"wrapper",func:null}],u.prototype.clone=i,u.prototype.reverse=b,u.prototype.value=nn,t.prototype.chain=Ne,t.prototype.commit=Fe,t.prototype.plant=Pe,t.prototype.reverse=ze,t.prototype.toString=Me,t.prototype.run=t.prototype.toJSON=t.prototype.valueOf=t.prototype.value=qe,t.prototype.collect=t.prototype.map,t.prototype.head=t.prototype.first,t.prototype.select=t.prototype.filter,t.prototype.tail=t.prototype.rest,t}var E,I="3.8.0",R=1,T=2,$=4,S=8,U=16,W=32,B=64,L=128,N=256,F=30,P="...",z=150,M=16,q=0,D=1,K=2,V="Expected a function",Y="__lodash_placeholder__",H="[object Arguments]",G="[object Array]",J="[object Boolean]",X="[object Date]",Z="[object Error]",Q="[object Function]",nn="[object Map]",tn="[object Number]",rn="[object Object]",en="[object RegExp]",un="[object Set]",on="[object String]",an="[object WeakMap]",cn="[object ArrayBuffer]",ln="[object Float32Array]",fn="[object Float64Array]",sn="[object Int8Array]",pn="[object Int16Array]",hn="[object Int32Array]",vn="[object Uint8Array]",_n="[object Uint8ClampedArray]",gn="[object Uint16Array]",yn="[object Uint32Array]",dn=/\b__p \+= '';/g,mn=/\b(__p \+=) '' \+/g,wn=/(__e\(.*?\)|\b__t\)) \+\n'';/g,bn=/&(?:amp|lt|gt|quot|#39|#96);/g,xn=/[&<>"'`]/g,An=RegExp(bn.source),jn=RegExp(xn.source),Cn=/<%-([\s\S]+?)%>/g,kn=/<%([\s\S]+?)%>/g,On=/<%=([\s\S]+?)%>/g,En=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/,In=/^\w*$/,Rn=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g,Tn=/[.*+?^${}()|[\]\/\\]/g,$n=RegExp(Tn.source),Sn=/[\u0300-\u036f\ufe20-\ufe23]/g,Un=/\\(\\)?/g,Wn=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,Bn=/\w*$/,Ln=/^0[xX]/,Nn=/^\[object .+?Constructor\]$/,Fn=/[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g,Pn=/($^)/,zn=/['\n\r\u2028\u2029\\]/g,Mn=function(){var n="[A-Z\\xc0-\\xd6\\xd8-\\xde]",t="[a-z\\xdf-\\xf6\\xf8-\\xff]+";return RegExp(n+"+(?="+n+t+")|"+n+"?"+t+"|"+n+"+|[0-9]+","g")}(),qn=" \x0B\f \ufeff\n\r\u2028\u2029 ",Dn=["Array","ArrayBuffer","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Math","Number","Object","RegExp","Set","String","_","clearTimeout","document","isFinite","parseInt","setTimeout","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","window"],Kn=-1,Vn={};Vn[ln]=Vn[fn]=Vn[sn]=Vn[pn]=Vn[hn]=Vn[vn]=Vn[_n]=Vn[gn]=Vn[yn]=!0,Vn[H]=Vn[G]=Vn[cn]=Vn[J]=Vn[X]=Vn[Z]=Vn[Q]=Vn[nn]=Vn[tn]=Vn[rn]=Vn[en]=Vn[un]=Vn[on]=Vn[an]=!1;var Yn={};Yn[H]=Yn[G]=Yn[cn]=Yn[J]=Yn[X]=Yn[ln]=Yn[fn]=Yn[sn]=Yn[pn]=Yn[hn]=Yn[tn]=Yn[rn]=Yn[en]=Yn[on]=Yn[vn]=Yn[_n]=Yn[gn]=Yn[yn]=!0,Yn[Z]=Yn[Q]=Yn[nn]=Yn[un]=Yn[an]=!1;var Hn={leading:!1,maxWait:0,trailing:!1},Gn={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss"},Jn={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},Xn={"&":"&","<":"<",">":">",""":'"',"'":"'","`":"`"},Zn={"function":!0,object:!0},Qn={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},nt=Zn[typeof t]&&t&&!t.nodeType&&t,tt=Zn[typeof n]&&n&&!n.nodeType&&n,rt=nt&&tt&&"object"==typeof u&&u&&u.Object&&u,et=Zn[typeof self]&&self&&self.Object&&self,ut=Zn[typeof window]&&window&&window.Object&&window,it=(tt&&tt.exports===nt&&nt,rt||ut!==(this&&this.window)&&ut||et||this),ot=O();e=function(){return ot}.call(t,r,t,n),!(e!==E&&(n.exports=e)),i.constant("lodash",ot)}])}).call(t,r(2)(n),function(){return this}())},function(n,t){n.exports=function(n){return n.webpackPolyfill||(n.deprecate=function(){},n.paths=[],n.children=[],n.webpackPolyfill=1),n}}]); | dist/mi-angular-chat.min.js | !function(t){function e(s){if(a[s])return a[s].exports;var l=a[s]={exports:{},id:s,loaded:!1};return t[s].call(l.exports,l,l.exports,e),l.loaded=!0,l.exports}var a={};return e.m=t,e.c=a,e.p="",e(0)}([function(t,e){"use strict";t.exports=angular.module("mi.Chat",["mi/template/chat.html"]).controller("MiChatController",["$scope","$timeout",function(t,e){function a(){t.submitCallback()(l.message,l.username),l.message="",s()}function s(){e(function(){t.$msgContainer[0].scrollTop=t.$msgContainer[0].scrollHeight},200,!1)}var l=this;l.messages=t.messages,l.username=t.username,l.inputPlaceholderText=t.inputPlaceholderText,l.submitButtonText=t.submitButtonText,l.title=t.title,l.message="",l.submitCall=a,t.$watch("chat.messages",function(){s(),e(function(){t.$chatInput.focus()},200)}),t.$watch("chat.messages.length",function(){t.historyLoading||s()})}]).directive("miChat",["$timeout","lodash",function(t,e){return{restrict:"EA",replace:!0,controller:"MiChatController",controllerAs:"chat",templateUrl:function(t,e){return e.templateUrl||"mi/template/chat.html"},scope:{messages:"=",username:"=",title:"@",inputPlaceholderText:"@",submitButtonText:"@",submitCallback:"&"},link:function(a,s){a.title||(a.title="Chat"),a.inputPlaceholderText||(a.inputPlaceholderText="... your message ..."),a.submitButtonText||(a.submitButtonText="Send"),a.$msgContainer=angular.element(s[0].querySelector(".chat-body")),a.$chatInput=s[0].querySelector(".chat-input-field");var l=a.$msgContainer[0];a.$msgContainer.bind("scroll",e.throttle(function(){var e=l.scrollHeight;l.scrollTop<=10&&(a.historyLoading=!0,a.$apply(a.infiniteScroll),t(function(){a.historyLoading=!1,e!==l.scrollHeight&&(a.$msgContainer[0].scrollTop=360)},150))},300))}}}]),angular.module("mi/template/chat.html",[]).run(["$templateCache",function(t){t.put("mi/template/chat.html",'<div class="row mi-chat"><div class="col-xs-12 col-sm-12"><div class="panel panel-default"><div class="panel-heading chat-header"><h3 class="panel-title">{{chat.title}}</h3></div><div class="panel-body chat-body"><div class="row chat-message" ng-repeat="message in chat.messages" ng-class="{\'self-authored\': (chat.username == message.username)}"><div class="col-xs-12 col-sm-12"><p>{{message.content}}</p><p>{{message.username}}</p></div></div></div><div class="panel-footer chat-footer"><form ng-submit="chat.submitCall()"><div class="input-group"><input type="text" class="form-control chat-input-field" placeholder="{{chat.inputPlaceholderText}}" ng-model="chat.message"/><span class="input-group-btn"><input type="submit" class="btn btn-primary chat-submit-button" value="{{chat.submitButtonText}}"/></span></div></form></div></div></div></div>')}])}]); | add lodash dependency
| dist/mi-angular-chat.min.js | add lodash dependency | <ide><path>ist/mi-angular-chat.min.js
<del>!function(t){function e(s){if(a[s])return a[s].exports;var l=a[s]={exports:{},id:s,loaded:!1};return t[s].call(l.exports,l,l.exports,e),l.loaded=!0,l.exports}var a={};return e.m=t,e.c=a,e.p="",e(0)}([function(t,e){"use strict";t.exports=angular.module("mi.Chat",["mi/template/chat.html"]).controller("MiChatController",["$scope","$timeout",function(t,e){function a(){t.submitCallback()(l.message,l.username),l.message="",s()}function s(){e(function(){t.$msgContainer[0].scrollTop=t.$msgContainer[0].scrollHeight},200,!1)}var l=this;l.messages=t.messages,l.username=t.username,l.inputPlaceholderText=t.inputPlaceholderText,l.submitButtonText=t.submitButtonText,l.title=t.title,l.message="",l.submitCall=a,t.$watch("chat.messages",function(){s(),e(function(){t.$chatInput.focus()},200)}),t.$watch("chat.messages.length",function(){t.historyLoading||s()})}]).directive("miChat",["$timeout","lodash",function(t,e){return{restrict:"EA",replace:!0,controller:"MiChatController",controllerAs:"chat",templateUrl:function(t,e){return e.templateUrl||"mi/template/chat.html"},scope:{messages:"=",username:"=",title:"@",inputPlaceholderText:"@",submitButtonText:"@",submitCallback:"&"},link:function(a,s){a.title||(a.title="Chat"),a.inputPlaceholderText||(a.inputPlaceholderText="... your message ..."),a.submitButtonText||(a.submitButtonText="Send"),a.$msgContainer=angular.element(s[0].querySelector(".chat-body")),a.$chatInput=s[0].querySelector(".chat-input-field");var l=a.$msgContainer[0];a.$msgContainer.bind("scroll",e.throttle(function(){var e=l.scrollHeight;l.scrollTop<=10&&(a.historyLoading=!0,a.$apply(a.infiniteScroll),t(function(){a.historyLoading=!1,e!==l.scrollHeight&&(a.$msgContainer[0].scrollTop=360)},150))},300))}}}]),angular.module("mi/template/chat.html",[]).run(["$templateCache",function(t){t.put("mi/template/chat.html",'<div class="row mi-chat"><div class="col-xs-12 col-sm-12"><div class="panel panel-default"><div class="panel-heading chat-header"><h3 class="panel-title">{{chat.title}}</h3></div><div class="panel-body chat-body"><div class="row chat-message" ng-repeat="message in chat.messages" ng-class="{\'self-authored\': (chat.username == message.username)}"><div class="col-xs-12 col-sm-12"><p>{{message.content}}</p><p>{{message.username}}</p></div></div></div><div class="panel-footer chat-footer"><form ng-submit="chat.submitCall()"><div class="input-group"><input type="text" class="form-control chat-input-field" placeholder="{{chat.inputPlaceholderText}}" ng-model="chat.message"/><span class="input-group-btn"><input type="submit" class="btn btn-primary chat-submit-button" value="{{chat.submitButtonText}}"/></span></div></form></div></div></div></div>')}])}]);
<add>!function(n){function t(e){if(r[e])return r[e].exports;var u=r[e]={exports:{},id:e,loaded:!1};return n[e].call(u.exports,u,u.exports,t),u.loaded=!0,u.exports}var r={};return t.m=n,t.c=r,t.p="",t(0)}([function(n,t,r){"use strict";r(1),n.exports=angular.module("mi.Chat",["mi/template/chat.html","ngLodash"]).controller("MiChatController",["$scope","$timeout",function(n,t){function r(){n.submitCallback()(u.message,u.username),u.message="",e()}function e(){t(function(){n.$msgContainer[0].scrollTop=n.$msgContainer[0].scrollHeight},200,!1)}var u=this;u.messages=n.messages,u.username=n.username,u.inputPlaceholderText=n.inputPlaceholderText,u.submitButtonText=n.submitButtonText,u.title=n.title,u.message="",u.submitCall=r,n.$watch("chat.messages",function(){e(),t(function(){n.$chatInput.focus()},200)}),n.$watch("chat.messages.length",function(){n.historyLoading||e()})}]).directive("miChat",["$timeout","lodash",function(n,t){return{restrict:"EA",replace:!0,controller:"MiChatController",controllerAs:"chat",templateUrl:function(n,t){return t.templateUrl||"mi/template/chat.html"},scope:{messages:"=",username:"=",title:"@",inputPlaceholderText:"@",submitButtonText:"@",submitCallback:"&"},link:function(r,e){r.title||(r.title="Chat"),r.inputPlaceholderText||(r.inputPlaceholderText="... your message ..."),r.submitButtonText||(r.submitButtonText="Send"),r.$msgContainer=angular.element(e[0].querySelector(".chat-body")),r.$chatInput=e[0].querySelector(".chat-input-field");var u=r.$msgContainer[0];r.$msgContainer.bind("scroll",t.throttle(function(){var t=u.scrollHeight;u.scrollTop<=10&&(r.historyLoading=!0,r.$apply(r.infiniteScroll),n(function(){r.historyLoading=!1,t!==u.scrollHeight&&(r.$msgContainer[0].scrollTop=360)},150))},300))}}}]),angular.module("mi/template/chat.html",[]).run(["$templateCache",function(n){n.put("mi/template/chat.html",'<div class="row mi-chat"><div class="col-xs-12 col-sm-12"><div class="panel panel-default"><div class="panel-heading chat-header"><h3 class="panel-title">{{chat.title}}</h3></div><div class="panel-body chat-body"><div class="row chat-message" ng-repeat="message in chat.messages" ng-class="{\'self-authored\': (chat.username == message.username)}"><div class="col-xs-12 col-sm-12"><p>{{message.content}}</p><p>{{message.username}}</p></div></div></div><div class="panel-footer chat-footer"><form ng-submit="chat.submitCall()"><div class="input-group"><input type="text" class="form-control chat-input-field" placeholder="{{chat.inputPlaceholderText}}" ng-model="chat.message"/><span class="input-group-btn"><input type="submit" class="btn btn-primary chat-submit-button" value="{{chat.submitButtonText}}"/></span></div></form></div></div></div></div>')}])},function(n,t,r){var e;(function(n,u){/**
<add> * @license
<add> * lodash 3.8.0 (Custom Build) <https://lodash.com/>
<add> * Build: `lodash modern exports="amd,commonjs,node" iife="angular.module('ngLodash', []).constant('lodash', null).config(function ($provide) { %output% $provide.constant('lodash', _);});" --output build/ng-lodash.js`
<add> * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
<add> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
<add> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
<add> * Available under MIT license <https://lodash.com/license>
<add> */
<add>angular.module("ngLodash",[]).constant("lodash",null).config(["$provide",function(i){function o(n,t){if(n!==t){var r=n===n,e=t===t;if(n>t||!r||n===E&&e)return 1;if(t>n||!e||t===E&&r)return-1}return 0}function a(n,t,r){for(var e=n.length,u=r?e:-1;r?u--:++u<e;)if(t(n[u],u,n))return u;return-1}function c(n,t,r){if(t!==t)return m(n,r);for(var e=r-1,u=n.length;++e<u;)if(n[e]===t)return e;return-1}function l(n){return"function"==typeof n||!1}function f(n){return"string"==typeof n?n:null==n?"":n+""}function s(n){return n.charCodeAt(0)}function p(n,t){for(var r=-1,e=n.length;++r<e&&t.indexOf(n.charAt(r))>-1;);return r}function h(n,t){for(var r=n.length;r--&&t.indexOf(n.charAt(r))>-1;);return r}function v(n,t){return o(n.criteria,t.criteria)||n.index-t.index}function _(n,t,r){for(var e=-1,u=n.criteria,i=t.criteria,a=u.length,c=r.length;++e<a;){var l=o(u[e],i[e]);if(l)return e>=c?l:l*(r[e]?1:-1)}return n.index-t.index}function g(n){return Gn[n]}function y(n){return Jn[n]}function d(n){return"\\"+Qn[n]}function m(n,t,r){for(var e=n.length,u=t+(r?0:-1);r?u--:++u<e;){var i=n[u];if(i!==i)return u}return-1}function w(n){return!!n&&"object"==typeof n}function b(n){return 160>=n&&n>=9&&13>=n||32==n||160==n||5760==n||6158==n||n>=8192&&(8202>=n||8232==n||8233==n||8239==n||8287==n||12288==n||65279==n)}function x(n,t){for(var r=-1,e=n.length,u=-1,i=[];++r<e;)n[r]===t&&(n[r]=Y,i[++u]=r);return i}function A(n,t){for(var r,e=-1,u=n.length,i=-1,o=[];++e<u;){var a=n[e],c=t?t(a,e,n):a;e&&r===c||(r=c,o[++i]=a)}return o}function j(n){for(var t=-1,r=n.length;++t<r&&b(n.charCodeAt(t)););return t}function C(n){for(var t=n.length;t--&&b(n.charCodeAt(t)););return t}function k(n){return Xn[n]}function O(n){function t(n){if(w(n)&&!ka(n)&&!(n instanceof u)){if(n instanceof e)return n;if(Mi.call(n,"__chain__")&&Mi.call(n,"__wrapped__"))return oe(n)}return new e(n)}function r(){}function e(n,t,r){this.__wrapped__=n,this.__actions__=r||[],this.__chain__=!!t}function u(n){this.__wrapped__=n,this.__actions__=null,this.__dir__=1,this.__dropCount__=0,this.__filtered__=!1,this.__iteratees__=null,this.__takeCount__=xo,this.__views__=null}function i(){var n=this.__actions__,t=this.__iteratees__,r=this.__views__,e=new u(this.__wrapped__);return e.__actions__=n?tt(n):null,e.__dir__=this.__dir__,e.__filtered__=this.__filtered__,e.__iteratees__=t?tt(t):null,e.__takeCount__=this.__takeCount__,e.__views__=r?tt(r):null,e}function b(){if(this.__filtered__){var n=new u(this);n.__dir__=-1,n.__filtered__=!0}else n=this.clone(),n.__dir__*=-1;return n}function nn(){var n=this.__wrapped__.value();if(!ka(n))return tr(n,this.__actions__);var t=this.__dir__,r=0>t,e=Fr(0,n.length,this.__views__),u=e.start,i=e.end,o=i-u,a=r?i:u-1,c=_o(o,this.__takeCount__),l=this.__iteratees__,f=l?l.length:0,s=0,p=[];n:for(;o--&&c>s;){a+=t;for(var h=-1,v=n[a];++h<f;){var _=l[h],g=_.iteratee,y=_.type;if(y==q){if(_.done&&(r?a>_.index:a<_.index)&&(_.count=0,_.done=!1),_.index=a,!_.done){var d=_.limit;if(!(_.done=d>-1?_.count++>=d:!g(v)))continue n}}else{var m=g(v);if(y==K)v=m;else if(!m){if(y==D)continue n;break n}}}p[s++]=v}return p}function un(){this.__data__={}}function an(n){return this.has(n)&&delete this.__data__[n]}function Gn(n){return"__proto__"==n?E:this.__data__[n]}function Jn(n){return"__proto__"!=n&&Mi.call(this.__data__,n)}function Xn(n,t){return"__proto__"!=n&&(this.__data__[n]=t),this}function Zn(n){var t=n?n.length:0;for(this.data={hash:so(null),set:new eo};t--;)this.push(n[t])}function Qn(n,t){var r=n.data,e="string"==typeof t||ju(t)?r.set.has(t):r.hash[t];return e?0:-1}function nt(n){var t=this.data;"string"==typeof n||ju(n)?t.set.add(n):t.hash[n]=!0}function tt(n,t){var r=-1,e=n.length;for(t||(t=Oi(e));++r<e;)t[r]=n[r];return t}function rt(n,t){for(var r=-1,e=n.length;++r<e&&t(n[r],r,n)!==!1;);return n}function et(n,t){for(var r=n.length;r--&&t(n[r],r,n)!==!1;);return n}function ut(n,t){for(var r=-1,e=n.length;++r<e;)if(!t(n[r],r,n))return!1;return!0}function at(n,t){for(var r=-1,e=n.length,u=-1,i=[];++r<e;){var o=n[r];t(o,r,n)&&(i[++u]=o)}return i}function ct(n,t){for(var r=-1,e=n.length,u=Oi(e);++r<e;)u[r]=t(n[r],r,n);return u}function lt(n){for(var t=-1,r=n.length,e=bo;++t<r;){var u=n[t];u>e&&(e=u)}return e}function ft(n){for(var t=-1,r=n.length,e=xo;++t<r;){var u=n[t];e>u&&(e=u)}return e}function st(n,t,r,e){var u=-1,i=n.length;for(e&&i&&(r=n[++u]);++u<i;)r=t(r,n[u],u,n);return r}function pt(n,t,r,e){var u=n.length;for(e&&u&&(r=n[--u]);u--;)r=t(r,n[u],u,n);return r}function ht(n,t){for(var r=-1,e=n.length;++r<e;)if(t(n[r],r,n))return!0;return!1}function vt(n){for(var t=n.length,r=0;t--;)r+=+n[t]||0;return r}function _t(n,t){return n===E?t:n}function gt(n,t,r,e){return n!==E&&Mi.call(e,r)?n:t}function yt(n,t,r){var e=Na(t);no.apply(e,Mo(t));for(var u=-1,i=e.length;++u<i;){var o=e[u],a=n[o],c=r(a,t[o],o,n,t);(c===c?c===a:a!==a)&&(a!==E||o in n)||(n[o]=c)}return n}function dt(n,t){for(var r=-1,e=null==n,u=!e&&Dr(n),i=u&&n.length,o=t.length,a=Oi(o);++r<o;){var c=t[r];u?a[r]=Kr(c,i)?n[c]:E:a[r]=e?E:n[c]}return a}function mt(n,t,r){r||(r={});for(var e=-1,u=t.length;++e<u;){var i=t[e];r[i]=n[i]}return r}function wt(n,t,r){var e=typeof n;return"function"==e?t===E?n:ur(n,t,r):null==n?vi:"object"==e?Nt(n):t===E?wi(n):Ft(n,t)}function bt(n,t,r,e,u,i,o){var a;if(r&&(a=u?r(n,e,u):r(n)),a!==E)return a;if(!ju(n))return n;var c=ka(n);if(c){if(a=Pr(n),!t)return tt(n,a)}else{var l=Di.call(n),f=l==Q;if(l!=rn&&l!=H&&(!f||u))return Yn[l]?Mr(n,l,t):u?n:{};if(a=zr(f?{}:n),!t)return To(a,n)}i||(i=[]),o||(o=[]);for(var s=i.length;s--;)if(i[s]==n)return o[s];return i.push(n),o.push(a),(c?rt:Rt)(n,function(e,u){a[u]=bt(e,t,r,u,n,i,o)}),a}function xt(n,t,r){if("function"!=typeof n)throw new Bi(V);return uo(function(){n.apply(E,r)},t)}function At(n,t){var r=n?n.length:0,e=[];if(!r)return e;var u=-1,i=Nr(),o=i==c,a=o&&t.length>=200?No(t):null,l=t.length;a&&(i=Qn,o=!1,t=a);n:for(;++u<r;){var f=n[u];if(o&&f===f){for(var s=l;s--;)if(t[s]===f)continue n;e.push(f)}else i(t,f,0)<0&&e.push(f)}return e}function jt(n,t){var r=!0;return So(n,function(n,e,u){return r=!!t(n,e,u)}),r}function Ct(n,t,r,e){var u=n.length;for(r=null==r?0:+r||0,0>r&&(r=-r>u?0:u+r),e=e===E||e>u?u:+e||0,0>e&&(e+=u),u=r>e?0:e>>>0,r>>>=0;u>r;)n[r++]=t;return n}function kt(n,t){var r=[];return So(n,function(n,e,u){t(n,e,u)&&r.push(n)}),r}function Ot(n,t,r,e){var u;return r(n,function(n,r,i){return t(n,r,i)?(u=e?r:n,!1):void 0}),u}function Et(n,t,r){for(var e=-1,u=n.length,i=-1,o=[];++e<u;){var a=n[e];if(w(a)&&Dr(a)&&(r||ka(a)||yu(a))){t&&(a=Et(a,t,r));for(var c=-1,l=a.length;++c<l;)o[++i]=a[c]}else r||(o[++i]=a)}return o}function It(n,t){return Wo(n,t,zu)}function Rt(n,t){return Wo(n,t,Na)}function Tt(n,t){return Bo(n,t,Na)}function $t(n,t){for(var r=-1,e=t.length,u=-1,i=[];++r<e;){var o=t[r];Ea(n[o])&&(i[++u]=o)}return i}function St(n,t,r){if(null!=n){r!==E&&r in ue(n)&&(t=[r]);for(var e=-1,u=t.length;null!=n&&++e<u;)n=n[t[e]];return e&&e==u?n:E}}function Ut(n,t,r,e,u,i){if(n===t)return!0;var o=typeof n,a=typeof t;return"function"!=o&&"object"!=o&&"function"!=a&&"object"!=a||null==n||null==t?n!==n&&t!==t:Wt(n,t,Ut,r,e,u,i)}function Wt(n,t,r,e,u,i,o){var a=ka(n),c=ka(t),l=G,f=G;a||(l=Di.call(n),l==H?l=rn:l!=rn&&(a=$u(n))),c||(f=Di.call(t),f==H?f=rn:f!=rn&&(c=$u(t)));var s=l==rn,p=f==rn,h=l==f;if(h&&!a&&!s)return Ur(n,t,l);if(!u){var v=s&&Mi.call(n,"__wrapped__"),_=p&&Mi.call(t,"__wrapped__");if(v||_)return r(v?n.value():n,_?t.value():t,e,u,i,o)}if(!h)return!1;i||(i=[]),o||(o=[]);for(var g=i.length;g--;)if(i[g]==n)return o[g]==t;i.push(n),o.push(t);var y=(a?Sr:Wr)(n,t,r,e,u,i,o);return i.pop(),o.pop(),y}function Bt(n,t,r,e,u){for(var i=-1,o=t.length,a=!u;++i<o;)if(a&&e[i]?r[i]!==n[t[i]]:!(t[i]in n))return!1;for(i=-1;++i<o;){var c=t[i],l=n[c],f=r[i];if(a&&e[i])var s=l!==E||c in n;else s=u?u(l,f,c):E,s===E&&(s=Ut(f,l,u,!0));if(!s)return!1}return!0}function Lt(n,t){var r=-1,e=Dr(n)?Oi(n.length):[];return So(n,function(n,u,i){e[++r]=t(n,u,i)}),e}function Nt(n){var t=Na(n),r=t.length;if(!r)return hi(!0);if(1==r){var e=t[0],u=n[e];if(Jr(u))return function(n){return null==n?!1:n[e]===u&&(u!==E||e in ue(n))}}for(var i=Oi(r),o=Oi(r);r--;)u=n[t[r]],i[r]=u,o[r]=Jr(u);return function(n){return null!=n&&Bt(ue(n),t,i,o)}}function Ft(n,t){var r=ka(n),e=Yr(n)&&Jr(t),u=n+"";return n=ie(n),function(i){if(null==i)return!1;var o=u;if(i=ue(i),(r||!e)&&!(o in i)){if(i=1==n.length?i:St(i,Yt(n,0,-1)),null==i)return!1;o=we(n),i=ue(i)}return i[o]===t?t!==E||o in i:Ut(t,i[o],null,!0)}}function Pt(n,t,r,e,u){if(!ju(n))return n;var i=Dr(t)&&(ka(t)||$u(t));if(!i){var o=Na(t);no.apply(o,Mo(t))}return rt(o||t,function(a,c){if(o&&(c=a,a=t[c]),w(a))e||(e=[]),u||(u=[]),zt(n,t,c,Pt,r,e,u);else{var l=n[c],f=r?r(l,a,c,n,t):E,s=f===E;s&&(f=a),!i&&f===E||!s&&(f===f?f===l:l!==l)||(n[c]=f)}}),n}function zt(n,t,r,e,u,i,o){for(var a=i.length,c=t[r];a--;)if(i[a]==c)return void(n[r]=o[a]);var l=n[r],f=u?u(l,c,r,n,t):E,s=f===E;s&&(f=c,Dr(c)&&(ka(c)||$u(c))?f=ka(l)?l:Dr(l)?tt(l):[]:Ia(c)||yu(c)?f=yu(l)?Wu(l):Ia(l)?l:{}:s=!1),i.push(c),o.push(f),s?n[r]=e(f,c,u,i,o):(f===f?f!==l:l===l)&&(n[r]=f)}function Mt(n){return function(t){return null==t?E:t[n]}}function qt(n){var t=n+"";return n=ie(n),function(r){return St(r,n,t)}}function Dt(n,t){for(var r=n?t.length:0;r--;){var e=parseFloat(t[r]);if(e!=u&&Kr(e)){var u=e;io.call(n,e,1)}}return n}function Kt(n,t){return n+Xi(wo()*(t-n+1))}function Vt(n,t,r,e,u){return u(n,function(n,u,i){r=e?(e=!1,n):t(r,n,u,i)}),r}function Yt(n,t,r){var e=-1,u=n.length;t=null==t?0:+t||0,0>t&&(t=-t>u?0:u+t),r=r===E||r>u?u:+r||0,0>r&&(r+=u),u=t>r?0:r-t>>>0,t>>>=0;for(var i=Oi(u);++e<u;)i[e]=n[e+t];return i}function Ht(n,t){var r;return So(n,function(n,e,u){return r=t(n,e,u),!r}),!!r}function Gt(n,t){var r=n.length;for(n.sort(t);r--;)n[r]=n[r].value;return n}function Jt(n,t,r){var e=Lr(),u=-1;t=ct(t,function(n){return e(n)});var i=Lt(n,function(n){var r=ct(t,function(t){return t(n)});return{criteria:r,index:++u,value:n}});return Gt(i,function(n,t){return _(n,t,r)})}function Xt(n,t){var r=0;return So(n,function(n,e,u){r+=+t(n,e,u)||0}),r}function Zt(n,t){var r=-1,e=Nr(),u=n.length,i=e==c,o=i&&u>=200,a=o?No():null,l=[];a?(e=Qn,i=!1):(o=!1,a=t?[]:l);n:for(;++r<u;){var f=n[r],s=t?t(f,r,n):f;if(i&&f===f){for(var p=a.length;p--;)if(a[p]===s)continue n;t&&a.push(s),l.push(f)}else e(a,s,0)<0&&((t||o)&&a.push(s),l.push(f))}return l}function Qt(n,t){for(var r=-1,e=t.length,u=Oi(e);++r<e;)u[r]=n[t[r]];return u}function nr(n,t,r,e){for(var u=n.length,i=e?u:-1;(e?i--:++i<u)&&t(n[i],i,n););return r?Yt(n,e?0:i,e?i+1:u):Yt(n,e?i+1:0,e?u:i)}function tr(n,t){var r=n;r instanceof u&&(r=r.value());for(var e=-1,i=t.length;++e<i;){var o=[r],a=t[e];no.apply(o,a.args),r=a.func.apply(a.thisArg,o)}return r}function rr(n,t,r){var e=0,u=n?n.length:e;if("number"==typeof t&&t===t&&Co>=u){for(;u>e;){var i=e+u>>>1,o=n[i];(r?t>=o:t>o)?e=i+1:u=i}return u}return er(n,t,vi,r)}function er(n,t,r,e){t=r(t);for(var u=0,i=n?n.length:0,o=t!==t,a=t===E;i>u;){var c=Xi((u+i)/2),l=r(n[c]),f=l===l;if(o)var s=f||e;else s=a?f&&(e||l!==E):e?t>=l:t>l;s?u=c+1:i=c}return _o(i,jo)}function ur(n,t,r){if("function"!=typeof n)return vi;if(t===E)return n;switch(r){case 1:return function(r){return n.call(t,r)};case 3:return function(r,e,u){return n.call(t,r,e,u)};case 4:return function(r,e,u,i){return n.call(t,r,e,u,i)};case 5:return function(r,e,u,i,o){return n.call(t,r,e,u,i,o)}}return function(){return n.apply(t,arguments)}}function ir(n){return Hi.call(n,0)}function or(n,t,r){for(var e=r.length,u=-1,i=vo(n.length-e,0),o=-1,a=t.length,c=Oi(i+a);++o<a;)c[o]=t[o];for(;++u<e;)c[r[u]]=n[u];for(;i--;)c[o++]=n[u++];return c}function ar(n,t,r){for(var e=-1,u=r.length,i=-1,o=vo(n.length-u,0),a=-1,c=t.length,l=Oi(o+c);++i<o;)l[i]=n[i];for(var f=i;++a<c;)l[f+a]=t[a];for(;++e<u;)l[f+r[e]]=n[i++];return l}function cr(n,t){return function(r,e,u){var i=t?t():{};if(e=Lr(e,u,3),ka(r))for(var o=-1,a=r.length;++o<a;){var c=r[o];n(i,c,e(c,o,r),r)}else So(r,function(t,r,u){n(i,t,e(t,r,u),u)});return i}}function lr(n){return su(function(t,r){var e=-1,u=null==t?0:r.length,i=u>2&&r[u-2],o=u>2&&r[2],a=u>1&&r[u-1];for("function"==typeof i?(i=ur(i,a,5),u-=2):(i="function"==typeof a?a:null,u-=i?1:0),o&&Vr(r[0],r[1],o)&&(i=3>u?null:i,u=1);++e<u;){var c=r[e];c&&n(t,c,i)}return t})}function fr(n,t){return function(r,e){var u=r?zo(r):0;if(!Gr(u))return n(r,e);for(var i=t?u:-1,o=ue(r);(t?i--:++i<u)&&e(o[i],i,o)!==!1;);return r}}function sr(n){return function(t,r,e){for(var u=ue(t),i=e(t),o=i.length,a=n?o:-1;n?a--:++a<o;){var c=i[a];if(r(u[c],c,u)===!1)break}return t}}function pr(n,t){function r(){var u=this&&this!==it&&this instanceof r?e:n;return u.apply(t,arguments)}var e=vr(n);return r}function hr(n){return function(t){for(var r=-1,e=si(Xu(t)),u=e.length,i="";++r<u;)i=n(i,e[r],r);return i}}function vr(n){return function(){var t=$o(n.prototype),r=n.apply(t,arguments);return ju(r)?r:t}}function _r(n){function t(r,e,u){u&&Vr(r,e,u)&&(e=null);var i=$r(r,n,null,null,null,null,null,e);return i.placeholder=t.placeholder,i}return t}function gr(n,t){return function(r,e,u){u&&Vr(r,e,u)&&(e=null);var i=Lr(),o=null==e;if(i===wt&&o||(o=!1,e=i(e,u,3)),o){var a=ka(r);if(a||!Tu(r))return n(a?r:ee(r));e=s}return Br(r,e,t)}}function yr(n,t){return function(r,e,u){if(e=Lr(e,u,3),ka(r)){var i=a(r,e,t);return i>-1?r[i]:E}return Ot(r,e,n)}}function dr(n){return function(t,r,e){return t&&t.length?(r=Lr(r,e,3),a(t,r,n)):-1}}function mr(n){return function(t,r,e){return r=Lr(r,e,3),Ot(t,r,n,!0)}}function wr(n){return function(){var t=arguments.length;if(!t)return function(){return arguments[0]};for(var r,u=n?t:-1,i=0,o=Oi(t);n?u--:++u<t;){var a=o[i++]=arguments[u];if("function"!=typeof a)throw new Bi(V);var c=r?"":Po(a);r="wrapper"==c?new e([]):r}for(u=r?-1:t;++u<t;){a=o[u],c=Po(a);var l="wrapper"==c?Fo(a):null;r=l&&Hr(l[0])&&l[1]==(L|S|W|N)&&!l[4].length&&1==l[9]?r[Po(l[0])].apply(r,l[3]):1==a.length&&Hr(a)?r[c]():r.thru(a)}return function(){var n=arguments;if(r&&1==n.length&&ka(n[0]))return r.plant(n[0]).value();for(var e=0,u=o[e].apply(this,n);++e<t;)u=o[e].call(this,u);return u}}}function br(n,t){return function(r,e,u){return"function"==typeof e&&u===E&&ka(r)?n(r,e):t(r,ur(e,u,3))}}function xr(n){return function(t,r,e){return("function"!=typeof r||e!==E)&&(r=ur(r,e,3)),n(t,r,zu)}}function Ar(n){return function(t,r,e){return("function"!=typeof r||e!==E)&&(r=ur(r,e,3)),n(t,r)}}function jr(n){return function(t,r,e){var u={};return r=Lr(r,e,3),Rt(t,function(t,e,i){var o=r(t,e,i);e=n?o:e,t=n?t:o,u[e]=t}),u}}function Cr(n){return function(t,r,e){return t=f(t),(n?t:"")+Ir(t,r,e)+(n?"":t)}}function kr(n){var t=su(function(r,e){var u=x(e,t.placeholder);return $r(r,n,null,e,u)});return t}function Or(n,t){return function(r,e,u,i){var o=arguments.length<3;return"function"==typeof e&&i===E&&ka(r)?n(r,e,u,o):Vt(r,Lr(e,i,4),u,o,t)}}function Er(n,t,r,e,u,i,o,a,c,l){function f(){for(var m=arguments.length,w=m,b=Oi(m);w--;)b[w]=arguments[w];if(e&&(b=or(b,e,u)),i&&(b=ar(b,i,o)),v||g){var A=f.placeholder,j=x(b,A);if(m-=j.length,l>m){var C=a?tt(a):null,k=vo(l-m,0),O=v?j:null,I=v?null:j,$=v?b:null,S=v?null:b;t|=v?W:B,t&=~(v?B:W),_||(t&=~(R|T));var U=[n,t,r,$,O,S,I,C,c,k],L=Er.apply(E,U);return Hr(n)&&qo(L,U),L.placeholder=A,L}}var N=p?r:this;h&&(n=N[d]),a&&(b=ne(b,a)),s&&c<b.length&&(b.length=c);var F=this&&this!==it&&this instanceof f?y||vr(n):n;return F.apply(N,b)}var s=t&L,p=t&R,h=t&T,v=t&S,_=t&$,g=t&U,y=!h&&vr(n),d=n;return f}function Ir(n,t,r){var e=n.length;if(t=+t,e>=t||!po(t))return"";var u=t-e;return r=null==r?" ":r+"",ei(r,Gi(u/r.length)).slice(0,u)}function Rr(n,t,r,e){function u(){for(var t=-1,a=arguments.length,c=-1,l=e.length,f=Oi(a+l);++c<l;)f[c]=e[c];for(;a--;)f[c++]=arguments[++t];var s=this&&this!==it&&this instanceof u?o:n;return s.apply(i?r:this,f)}var i=t&R,o=vr(n);return u}function Tr(n){return function(t,r,e,u){var i=Lr(e);return i===wt&&null==e?rr(t,r,n):er(t,r,i(e,u,1),n)}}function $r(n,t,r,e,u,i,o,a){var c=t&T;if(!c&&"function"!=typeof n)throw new Bi(V);var l=e?e.length:0;if(l||(t&=~(W|B),e=u=null),l-=u?u.length:0,t&B){var f=e,s=u;e=u=null}var p=c?null:Fo(n),h=[n,t,r,e,u,f,s,i,o,a];if(p&&(Xr(h,p),t=h[1],a=h[9]),h[9]=null==a?c?0:n.length:vo(a-l,0)||0,t==R)var v=pr(h[0],h[2]);else v=t!=W&&t!=(R|W)||h[4].length?Er.apply(E,h):Rr.apply(E,h);var _=p?Lo:qo;return _(v,h)}function Sr(n,t,r,e,u,i,o){var a=-1,c=n.length,l=t.length,f=!0;if(c!=l&&!(u&&l>c))return!1;for(;f&&++a<c;){var s=n[a],p=t[a];if(f=E,e&&(f=u?e(p,s,a):e(s,p,a)),f===E)if(u)for(var h=l;h--&&(p=t[h],!(f=s&&s===p||r(s,p,e,u,i,o))););else f=s&&s===p||r(s,p,e,u,i,o)}return!!f}function Ur(n,t,r){switch(r){case J:case X:return+n==+t;case Z:return n.name==t.name&&n.message==t.message;case tn:return n!=+n?t!=+t:n==+t;case en:case on:return n==t+""}return!1}function Wr(n,t,r,e,u,i,o){var a=Na(n),c=a.length,l=Na(t),f=l.length;if(c!=f&&!u)return!1;for(var s=u,p=-1;++p<c;){var h=a[p],v=u?h in t:Mi.call(t,h);if(v){var _=n[h],g=t[h];v=E,e&&(v=u?e(g,_,h):e(_,g,h)),v===E&&(v=_&&_===g||r(_,g,e,u,i,o))}if(!v)return!1;s||(s="constructor"==h)}if(!s){var y=n.constructor,d=t.constructor;if(y!=d&&"constructor"in n&&"constructor"in t&&!("function"==typeof y&&y instanceof y&&"function"==typeof d&&d instanceof d))return!1}return!0}function Br(n,t,r){var e=r?xo:bo,u=e,i=u;return So(n,function(n,o,a){var c=t(n,o,a);((r?u>c:c>u)||c===e&&c===i)&&(u=c,i=n)}),i}function Lr(n,r,e){var u=t.callback||pi;return u=u===pi?wt:u,e?u(n,r,e):u}function Nr(n,r,e){var u=t.indexOf||ye;return u=u===ye?c:u,n?u(n,r,e):u}function Fr(n,t,r){for(var e=-1,u=r?r.length:0;++e<u;){var i=r[e],o=i.size;switch(i.type){case"drop":n+=o;break;case"dropRight":t-=o;break;case"take":t=_o(t,n+o);break;case"takeRight":n=vo(n,t-o)}}return{start:n,end:t}}function Pr(n){var t=n.length,r=new n.constructor(t);return t&&"string"==typeof n[0]&&Mi.call(n,"index")&&(r.index=n.index,r.input=n.input),r}function zr(n){var t=n.constructor;return"function"==typeof t&&t instanceof t||(t=Si),new t}function Mr(n,t,r){var e=n.constructor;switch(t){case cn:return ir(n);case J:case X:return new e(+n);case ln:case fn:case sn:case pn:case hn:case vn:case _n:case gn:case yn:var u=n.buffer;return new e(r?ir(u):u,n.byteOffset,n.length);case tn:case on:return new e(n);case en:var i=new e(n.source,Bn.exec(n));i.lastIndex=n.lastIndex}return i}function qr(n,t,r){null==n||Yr(t,n)||(t=ie(t),n=1==t.length?n:St(n,Yt(t,0,-1)),t=we(t));var e=null==n?n:n[t];return null==e?E:e.apply(n,r)}function Dr(n){return null!=n&&Gr(zo(n))}function Kr(n,t){return n=+n,t=null==t?Oo:t,n>-1&&n%1==0&&t>n}function Vr(n,t,r){if(!ju(r))return!1;var e=typeof t;if("number"==e?Dr(r)&&Kr(t,r.length):"string"==e&&t in r){var u=r[t];return n===n?n===u:u!==u}return!1}function Yr(n,t){var r=typeof n;if("string"==r&&In.test(n)||"number"==r)return!0;if(ka(n))return!1;var e=!En.test(n);return e||null!=t&&n in ue(t)}function Hr(n){var r=Po(n);return!!r&&n===t[r]&&r in u.prototype}function Gr(n){return"number"==typeof n&&n>-1&&n%1==0&&Oo>=n}function Jr(n){return n===n&&!ju(n)}function Xr(n,t){var r=n[1],e=t[1],u=r|e,i=L>u,o=e==L&&r==S||e==L&&r==N&&n[7].length<=t[8]||e==(L|N)&&r==S;if(!i&&!o)return n;e&R&&(n[2]=t[2],u|=r&R?0:$);var a=t[3];if(a){var c=n[3];n[3]=c?or(c,a,t[4]):tt(a),n[4]=c?x(n[3],Y):tt(t[4])}return a=t[5],a&&(c=n[5],n[5]=c?ar(c,a,t[6]):tt(a),n[6]=c?x(n[5],Y):tt(t[6])),a=t[7],a&&(n[7]=tt(a)),e&L&&(n[8]=null==n[8]?t[8]:_o(n[8],t[8])),null==n[9]&&(n[9]=t[9]),n[0]=t[0],n[1]=u,n}function Zr(n,t){n=ue(n);for(var r=-1,e=t.length,u={};++r<e;){var i=t[r];i in n&&(u[i]=n[i])}return u}function Qr(n,t){var r={};return It(n,function(n,e,u){t(n,e,u)&&(r[e]=n)}),r}function ne(n,t){for(var r=n.length,e=_o(t.length,r),u=tt(n);e--;){var i=t[e];n[e]=Kr(i,r)?u[i]:E}return n}function te(n){var r;t.support;if(!w(n)||Di.call(n)!=rn||!Mi.call(n,"constructor")&&(r=n.constructor,"function"==typeof r&&!(r instanceof r)))return!1;var e;return It(n,function(n,t){e=t}),e===E||Mi.call(n,e)}function re(n){for(var r=zu(n),e=r.length,u=e&&n.length,i=t.support,o=u&&Gr(u)&&(ka(n)||i.nonEnumArgs&&yu(n)),a=-1,c=[];++a<e;){var l=r[a];(o&&Kr(l,u)||Mi.call(n,l))&&c.push(l)}return c}function ee(n){return null==n?[]:Dr(n)?ju(n)?n:Si(n):Vu(n)}function ue(n){return ju(n)?n:Si(n)}function ie(n){if(ka(n))return n;var t=[];return f(n).replace(Rn,function(n,r,e,u){t.push(e?u.replace(Un,"$1"):r||n)}),t}function oe(n){return n instanceof u?n.clone():new e(n.__wrapped__,n.__chain__,tt(n.__actions__))}function ae(n,t,r){t=(r?Vr(n,t,r):null==t)?1:vo(+t||1,1);for(var e=0,u=n?n.length:0,i=-1,o=Oi(Gi(u/t));u>e;)o[++i]=Yt(n,e,e+=t);return o}function ce(n){for(var t=-1,r=n?n.length:0,e=-1,u=[];++t<r;){var i=n[t];i&&(u[++e]=i)}return u}function le(n,t,r){var e=n?n.length:0;return e?((r?Vr(n,t,r):null==t)&&(t=1),Yt(n,0>t?0:t)):[]}function fe(n,t,r){var e=n?n.length:0;return e?((r?Vr(n,t,r):null==t)&&(t=1),t=e-(+t||0),Yt(n,0,0>t?0:t)):[]}function se(n,t,r){return n&&n.length?nr(n,Lr(t,r,3),!0,!0):[]}function pe(n,t,r){return n&&n.length?nr(n,Lr(t,r,3),!0):[]}function he(n,t,r,e){var u=n?n.length:0;return u?(r&&"number"!=typeof r&&Vr(n,t,r)&&(r=0,e=u),Ct(n,t,r,e)):[]}function ve(n){return n?n[0]:E}function _e(n,t,r){var e=n?n.length:0;return r&&Vr(n,t,r)&&(t=!1),e?Et(n,t):[]}function ge(n){var t=n?n.length:0;return t?Et(n,!0):[]}function ye(n,t,r){var e=n?n.length:0;if(!e)return-1;if("number"==typeof r)r=0>r?vo(e+r,0):r;else if(r){var u=rr(n,t),i=n[u];return(t===t?t===i:i!==i)?u:-1}return c(n,t,r||0)}function de(n){return fe(n,1)}function me(){for(var n=[],t=-1,r=arguments.length,e=[],u=Nr(),i=u==c,o=[];++t<r;){var a=arguments[t];Dr(a)&&(n.push(a),e.push(i&&a.length>=120?No(t&&a):null))}if(r=n.length,2>r)return o;var l=n[0],f=-1,s=l?l.length:0,p=e[0];n:for(;++f<s;)if(a=l[f],(p?Qn(p,a):u(o,a,0))<0){for(t=r;--t;){var h=e[t];if((h?Qn(h,a):u(n[t],a,0))<0)continue n}p&&p.push(a),o.push(a)}return o}function we(n){var t=n?n.length:0;return t?n[t-1]:E}function be(n,t,r){var e=n?n.length:0;if(!e)return-1;var u=e;if("number"==typeof r)u=(0>r?vo(e+r,0):_o(r||0,e-1))+1;else if(r){u=rr(n,t,!0)-1;var i=n[u];return(t===t?t===i:i!==i)?u:-1}if(t!==t)return m(n,u,!0);for(;u--;)if(n[u]===t)return u;return-1}function xe(){var n=arguments,t=n[0];if(!t||!t.length)return t;for(var r=0,e=Nr(),u=n.length;++r<u;)for(var i=0,o=n[r];(i=e(t,o,i))>-1;)io.call(t,i,1);return t}function Ae(n,t,r){var e=[];if(!n||!n.length)return e;var u=-1,i=[],o=n.length;for(t=Lr(t,r,3);++u<o;){var a=n[u];t(a,u,n)&&(e.push(a),i.push(u))}return Dt(n,i),e}function je(n){return le(n,1)}function Ce(n,t,r){var e=n?n.length:0;return e?(r&&"number"!=typeof r&&Vr(n,t,r)&&(t=0,r=e),Yt(n,t,r)):[]}function ke(n,t,r){var e=n?n.length:0;return e?((r?Vr(n,t,r):null==t)&&(t=1),Yt(n,0,0>t?0:t)):[]}function Oe(n,t,r){var e=n?n.length:0;return e?((r?Vr(n,t,r):null==t)&&(t=1),t=e-(+t||0),Yt(n,0>t?0:t)):[]}function Ee(n,t,r){return n&&n.length?nr(n,Lr(t,r,3),!1,!0):[]}function Ie(n,t,r){return n&&n.length?nr(n,Lr(t,r,3)):[]}function Re(n,t,r,e){var u=n?n.length:0;if(!u)return[];null!=t&&"boolean"!=typeof t&&(e=r,r=Vr(n,t,e)?null:t,t=!1);var i=Lr();return(i!==wt||null!=r)&&(r=i(r,e,3)),t&&Nr()==c?A(n,r):Zt(n,r)}function Te(n){if(!n||!n.length)return[];var t=-1,r=0;n=at(n,function(n){return Dr(n)?(r=vo(n.length,r),!0):void 0});for(var e=Oi(r);++t<r;)e[t]=ct(n,Mt(t));return e}function $e(n,t,r){var e=n?n.length:0;if(!e)return[];var u=Te(n);return null==t?u:(t=ur(t,r,4),ct(u,function(n){return st(n,t,E,!0)}))}function Se(){for(var n=-1,t=arguments.length;++n<t;){var r=arguments[n];if(Dr(r))var e=e?At(e,r).concat(At(r,e)):r}return e?Zt(e):[]}function Ue(n,t){var r=-1,e=n?n.length:0,u={};for(!e||t||ka(n[0])||(t=[]);++r<e;){var i=n[r];t?u[i]=t[r]:i&&(u[i[0]]=i[1])}return u}function We(n){var r=t(n);return r.__chain__=!0,r}function Be(n,t,r){return t.call(r,n),n}function Le(n,t,r){return t.call(r,n)}function Ne(){return We(this)}function Fe(){return new e(this.value(),this.__chain__)}function Pe(n){for(var t,e=this;e instanceof r;){var u=oe(e);t?i.__wrapped__=u:t=u;var i=u;e=e.__wrapped__}return i.__wrapped__=n,t}function ze(){var n=this.__wrapped__;return n instanceof u?(this.__actions__.length&&(n=new u(this)),new e(n.reverse(),this.__chain__)):this.thru(function(n){return n.reverse()})}function Me(){return this.value()+""}function qe(){return tr(this.__wrapped__,this.__actions__)}function De(n,t,r){var e=ka(n)?ut:jt;return r&&Vr(n,t,r)&&(t=null),("function"!=typeof t||r!==E)&&(t=Lr(t,r,3)),e(n,t)}function Ke(n,t,r){var e=ka(n)?at:kt;return t=Lr(t,r,3),e(n,t)}function Ve(n,t){return ra(n,Nt(t))}function Ye(n,t,r,e){var u=n?zo(n):0;return Gr(u)||(n=Vu(n),u=n.length),u?(r="number"!=typeof r||e&&Vr(t,r,e)?0:0>r?vo(u+r,0):r||0,"string"==typeof n||!ka(n)&&Tu(n)?u>r&&n.indexOf(t,r)>-1:Nr(n,t,r)>-1):!1}function He(n,t,r){var e=ka(n)?ct:Lt;return t=Lr(t,r,3),e(n,t)}function Ge(n,t){return He(n,wi(t))}function Je(n,t,r){var e=ka(n)?at:kt;return t=Lr(t,r,3),e(n,function(n,r,e){return!t(n,r,e)})}function Xe(n,t,r){if(r?Vr(n,t,r):null==t){n=ee(n);var e=n.length;return e>0?n[Kt(0,e-1)]:E}var u=Ze(n);return u.length=_o(0>t?0:+t||0,u.length),u}function Ze(n){n=ee(n);for(var t=-1,r=n.length,e=Oi(r);++t<r;){var u=Kt(0,t);t!=u&&(e[t]=e[u]),e[u]=n[t]}return e}function Qe(n){var t=n?zo(n):0;return Gr(t)?t:Na(n).length}function nu(n,t,r){var e=ka(n)?ht:Ht;return r&&Vr(n,t,r)&&(t=null),("function"!=typeof t||r!==E)&&(t=Lr(t,r,3)),e(n,t)}function tu(n,t,r){if(null==n)return[];r&&Vr(n,t,r)&&(t=null);var e=-1;t=Lr(t,r,3);var u=Lt(n,function(n,r,u){return{criteria:t(n,r,u),index:++e,value:n}});return Gt(u,v)}function ru(n,t,r,e){return null==n?[]:(e&&Vr(t,r,e)&&(r=null),ka(t)||(t=null==t?[]:[t]),ka(r)||(r=null==r?[]:[r]),Jt(n,t,r))}function eu(n,t){return Ke(n,Nt(t))}function uu(n,t){if("function"!=typeof t){if("function"!=typeof n)throw new Bi(V);var r=n;n=t,t=r}return n=po(n=+n)?n:0,function(){return--n<1?t.apply(this,arguments):void 0}}function iu(n,t,r){return r&&Vr(n,t,r)&&(t=null),t=n&&null==t?n.length:vo(+t||0,0),$r(n,L,null,null,null,null,t)}function ou(n,t){var r;if("function"!=typeof t){if("function"!=typeof n)throw new Bi(V);var e=n;n=t,t=e}return function(){return--n>0&&(r=t.apply(this,arguments)),1>=n&&(t=null),r}}function au(n,t,r){function e(){p&&Ji(p),c&&Ji(c),c=p=h=E}function u(){var r=t-(ha()-f);if(0>=r||r>t){c&&Ji(c);var e=h;c=p=h=E,e&&(v=ha(),l=n.apply(s,a),p||c||(a=s=null))}else p=uo(u,r)}function i(){p&&Ji(p),c=p=h=E,(g||_!==t)&&(v=ha(),l=n.apply(s,a),p||c||(a=s=null))}function o(){if(a=arguments,f=ha(),s=this,h=g&&(p||!y),_===!1)var r=y&&!p;else{c||y||(v=f);var e=_-(f-v),o=0>=e||e>_;o?(c&&(c=Ji(c)),v=f,l=n.apply(s,a)):c||(c=uo(i,e))}return o&&p?p=Ji(p):p||t===_||(p=uo(u,t)),r&&(o=!0,l=n.apply(s,a)),!o||p||c||(a=s=null),l}var a,c,l,f,s,p,h,v=0,_=!1,g=!0;if("function"!=typeof n)throw new Bi(V);if(t=0>t?0:+t||0,r===!0){var y=!0;g=!1}else ju(r)&&(y=r.leading,_="maxWait"in r&&vo(+r.maxWait||0,t),g="trailing"in r?r.trailing:g);return o.cancel=e,o}function cu(n,t){if("function"!=typeof n||t&&"function"!=typeof t)throw new Bi(V);var r=function(){var e=arguments,u=r.cache,i=t?t.apply(this,e):e[0];if(u.has(i))return u.get(i);var o=n.apply(this,e);return u.set(i,o),o};return r.cache=new cu.Cache,r}function lu(n){if("function"!=typeof n)throw new Bi(V);return function(){return!n.apply(this,arguments)}}function fu(n){return ou(2,n)}function su(n,t){if("function"!=typeof n)throw new Bi(V);return t=vo(t===E?n.length-1:+t||0,0),function(){for(var r=arguments,e=-1,u=vo(r.length-t,0),i=Oi(u);++e<u;)i[e]=r[t+e];switch(t){case 0:return n.call(this,i);case 1:return n.call(this,r[0],i);case 2:return n.call(this,r[0],r[1],i)}var o=Oi(t+1);for(e=-1;++e<t;)o[e]=r[e];return o[t]=i,n.apply(this,o)}}function pu(n){if("function"!=typeof n)throw new Bi(V);return function(t){return n.apply(this,t)}}function hu(n,t,r){var e=!0,u=!0;if("function"!=typeof n)throw new Bi(V);return r===!1?e=!1:ju(r)&&(e="leading"in r?!!r.leading:e,u="trailing"in r?!!r.trailing:u),Hn.leading=e,Hn.maxWait=+t,Hn.trailing=u,au(n,t,Hn)}function vu(n,t){return t=null==t?vi:t,$r(t,W,null,[n],[])}function _u(n,t,r,e){return t&&"boolean"!=typeof t&&Vr(n,t,r)?t=!1:"function"==typeof t&&(e=r,r=t,t=!1),r="function"==typeof r&&ur(r,e,1),bt(n,t,r)}function gu(n,t,r){return t="function"==typeof t&&ur(t,r,1),bt(n,!0,t)}function yu(n){return w(n)&&Dr(n)&&Di.call(n)==H}function du(n){return n===!0||n===!1||w(n)&&Di.call(n)==J}function mu(n){return w(n)&&Di.call(n)==X}function wu(n){return!!n&&1===n.nodeType&&w(n)&&Di.call(n).indexOf("Element")>-1}function bu(n){return null==n?!0:Dr(n)&&(ka(n)||Tu(n)||yu(n)||w(n)&&Ea(n.splice))?!n.length:!Na(n).length}function xu(n,t,r,e){if(r="function"==typeof r&&ur(r,e,3),!r&&Jr(n)&&Jr(t))return n===t;var u=r?r(n,t):E;return u===E?Ut(n,t,r):!!u}function Au(n){return w(n)&&"string"==typeof n.message&&Di.call(n)==Z}function ju(n){var t=typeof n;return"function"==t||!!n&&"object"==t}function Cu(n,t,r,e){var u=Na(t),i=u.length;if(!i)return!0;if(null==n)return!1;if(r="function"==typeof r&&ur(r,e,3),n=ue(n),!r&&1==i){var o=u[0],a=t[o];if(Jr(a))return a===n[o]&&(a!==E||o in n)}for(var c=Oi(i),l=Oi(i);i--;)a=c[i]=t[u[i]],l[i]=Jr(a);return Bt(n,u,c,l,r)}function ku(n){return Iu(n)&&n!=+n}function Ou(n){return null==n?!1:Di.call(n)==Q?Vi.test(zi.call(n)):w(n)&&Nn.test(n)}function Eu(n){return null===n}function Iu(n){return"number"==typeof n||w(n)&&Di.call(n)==tn}function Ru(n){return w(n)&&Di.call(n)==en}function Tu(n){return"string"==typeof n||w(n)&&Di.call(n)==on}function $u(n){return w(n)&&Gr(n.length)&&!!Vn[Di.call(n)]}function Su(n){return n===E}function Uu(n){var t=n?zo(n):0;return Gr(t)?t?tt(n):[]:Vu(n)}function Wu(n){return mt(n,zu(n))}function Bu(n,t,r){var e=$o(n);return r&&Vr(n,t,r)&&(t=null),t?To(e,t):e}function Lu(n){return $t(n,zu(n))}function Nu(n,t,r){var e=null==n?E:St(n,ie(t),t+"");return e===E?r:e}function Fu(n,t){if(null==n)return!1;var r=Mi.call(n,t);return r||Yr(t)||(t=ie(t),n=1==t.length?n:St(n,Yt(t,0,-1)),t=we(t),r=null!=n&&Mi.call(n,t)),r}function Pu(n,t,r){r&&Vr(n,t,r)&&(t=null);for(var e=-1,u=Na(n),i=u.length,o={};++e<i;){var a=u[e],c=n[a];t?Mi.call(o,c)?o[c].push(a):o[c]=[a]:o[c]=a}return o}function zu(n){if(null==n)return[];ju(n)||(n=Si(n));var t=n.length;t=t&&Gr(t)&&(ka(n)||Ro.nonEnumArgs&&yu(n))&&t||0;for(var r=n.constructor,e=-1,u="function"==typeof r&&r.prototype===n,i=Oi(t),o=t>0;++e<t;)i[e]=e+"";for(var a in n)o&&Kr(a,t)||"constructor"==a&&(u||!Mi.call(n,a))||i.push(a);return i}function Mu(n){for(var t=-1,r=Na(n),e=r.length,u=Oi(e);++t<e;){var i=r[t];u[t]=[i,n[i]]}return u}function qu(n,t,r){var e=null==n?E:n[t];return e===E&&(null==n||Yr(t,n)||(t=ie(t),n=1==t.length?n:St(n,Yt(t,0,-1)),e=null==n?E:n[we(t)]),e=e===E?r:e),Ea(e)?e.call(n):e}function Du(n,t,r){if(null==n)return n;var e=t+"";t=null!=n[e]||Yr(t,n)?[e]:ie(t);for(var u=-1,i=t.length,o=i-1,a=n;null!=a&&++u<i;){var c=t[u];ju(a)&&(u==o?a[c]=r:null==a[c]&&(a[c]=Kr(t[u+1])?[]:{})),a=a[c]}return n}function Ku(n,t,r,e){var u=ka(n)||$u(n);if(t=Lr(t,e,4),null==r)if(u||ju(n)){var i=n.constructor;r=u?ka(n)?new i:[]:$o(Ea(i)&&i.prototype)}else r={};return(u?rt:Rt)(n,function(n,e,u){return t(r,n,e,u)}),r}function Vu(n){return Qt(n,Na(n))}function Yu(n){return Qt(n,zu(n))}function Hu(n,t,r){return t=+t||0,"undefined"==typeof r?(r=t,t=0):r=+r||0,n>=_o(t,r)&&n<vo(t,r)}function Gu(n,t,r){r&&Vr(n,t,r)&&(t=r=null);var e=null==n,u=null==t;if(null==r&&(u&&"boolean"==typeof n?(r=n,n=1):"boolean"==typeof t&&(r=t,u=!0)),e&&u&&(t=1,u=!1),n=+n||0,u?(t=n,n=0):t=+t||0,r||n%1||t%1){var i=wo();return _o(n+i*(t-n+parseFloat("1e-"+((i+"").length-1))),t)}return Kt(n,t)}function Ju(n){return n=f(n),n&&n.charAt(0).toUpperCase()+n.slice(1)}function Xu(n){return n=f(n),n&&n.replace(Fn,g).replace(Sn,"")}function Zu(n,t,r){n=f(n),t+="";var e=n.length;return r=r===E?e:_o(0>r?0:+r||0,e),r-=t.length,r>=0&&n.indexOf(t,r)==r}function Qu(n){return n=f(n),n&&jn.test(n)?n.replace(xn,y):n}function ni(n){return n=f(n),n&&$n.test(n)?n.replace(Tn,"\\$&"):n}function ti(n,t,r){n=f(n),t=+t;var e=n.length;if(e>=t||!po(t))return n;var u=(t-e)/2,i=Xi(u),o=Gi(u);
<add>return r=Ir("",o,r),r.slice(0,i)+n+r}function ri(n,t,r){return r&&Vr(n,t,r)&&(t=0),mo(n,t)}function ei(n,t){var r="";if(n=f(n),t=+t,1>t||!n||!po(t))return r;do t%2&&(r+=n),t=Xi(t/2),n+=n;while(t);return r}function ui(n,t,r){return n=f(n),r=null==r?0:_o(0>r?0:+r||0,n.length),n.lastIndexOf(t,r)==r}function ii(n,r,e){var u=t.templateSettings;e&&Vr(n,r,e)&&(r=e=null),n=f(n),r=yt(To({},e||r),u,gt);var i,o,a=yt(To({},r.imports),u.imports,gt),c=Na(a),l=Qt(a,c),s=0,p=r.interpolate||Pn,h="__p += '",v=Ui((r.escape||Pn).source+"|"+p.source+"|"+(p===On?Wn:Pn).source+"|"+(r.evaluate||Pn).source+"|$","g"),_="//# sourceURL="+("sourceURL"in r?r.sourceURL:"lodash.templateSources["+ ++Kn+"]")+"\n";n.replace(v,function(t,r,e,u,a,c){return e||(e=u),h+=n.slice(s,c).replace(zn,d),r&&(i=!0,h+="' +\n__e("+r+") +\n'"),a&&(o=!0,h+="';\n"+a+";\n__p += '"),e&&(h+="' +\n((__t = ("+e+")) == null ? '' : __t) +\n'"),s=c+t.length,t}),h+="';\n";var g=r.variable;g||(h="with (obj) {\n"+h+"\n}\n"),h=(o?h.replace(dn,""):h).replace(mn,"$1").replace(wn,"$1;"),h="function("+(g||"obj")+") {\n"+(g?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(i?", __e = _.escape":"")+(o?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+h+"return __p\n}";var y=Ja(function(){return Ri(c,_+"return "+h).apply(E,l)});if(y.source=h,Au(y))throw y;return y}function oi(n,t,r){var e=n;return(n=f(n))?(r?Vr(e,t,r):null==t)?n.slice(j(n),C(n)+1):(t+="",n.slice(p(n,t),h(n,t)+1)):n}function ai(n,t,r){var e=n;return n=f(n),n?(r?Vr(e,t,r):null==t)?n.slice(j(n)):n.slice(p(n,t+"")):n}function ci(n,t,r){var e=n;return n=f(n),n?(r?Vr(e,t,r):null==t)?n.slice(0,C(n)+1):n.slice(0,h(n,t+"")+1):n}function li(n,t,r){r&&Vr(n,t,r)&&(t=null);var e=F,u=P;if(null!=t)if(ju(t)){var i="separator"in t?t.separator:i;e="length"in t?+t.length||0:e,u="omission"in t?f(t.omission):u}else e=+t||0;if(n=f(n),e>=n.length)return n;var o=e-u.length;if(1>o)return u;var a=n.slice(0,o);if(null==i)return a+u;if(Ru(i)){if(n.slice(o).search(i)){var c,l,s=n.slice(0,o);for(i.global||(i=Ui(i.source,(Bn.exec(i)||"")+"g")),i.lastIndex=0;c=i.exec(s);)l=c.index;a=a.slice(0,null==l?o:l)}}else if(n.indexOf(i,o)!=o){var p=a.lastIndexOf(i);p>-1&&(a=a.slice(0,p))}return a+u}function fi(n){return n=f(n),n&&An.test(n)?n.replace(bn,k):n}function si(n,t,r){return r&&Vr(n,t,r)&&(t=null),n=f(n),n.match(t||Mn)||[]}function pi(n,t,r){return r&&Vr(n,t,r)&&(t=null),w(n)?_i(n):wt(n,t)}function hi(n){return function(){return n}}function vi(n){return n}function _i(n){return Nt(bt(n,!0))}function gi(n,t){return Ft(n,bt(t,!0))}function yi(n,t,r){if(null==r){var e=ju(t),u=e&&Na(t),i=u&&u.length&&$t(t,u);(i?i.length:e)||(i=!1,r=t,t=n,n=this)}i||(i=$t(t,Na(t)));var o=!0,a=-1,c=Ea(n),l=i.length;r===!1?o=!1:ju(r)&&"chain"in r&&(o=r.chain);for(;++a<l;){var f=i[a],s=t[f];n[f]=s,c&&(n.prototype[f]=function(t){return function(){var r=this.__chain__;if(o||r){var e=n(this.__wrapped__),u=e.__actions__=tt(this.__actions__);return u.push({func:t,args:arguments,thisArg:n}),e.__chain__=r,e}var i=[this.value()];return no.apply(i,arguments),t.apply(n,i)}}(s))}return n}function di(){return n._=Ki,this}function mi(){}function wi(n){return Yr(n)?Mt(n):qt(n)}function bi(n){return function(t){return St(n,ie(t),t+"")}}function xi(n,t,r){r&&Vr(n,t,r)&&(t=r=null),n=+n||0,r=null==r?1:+r||0,null==t?(t=n,n=0):t=+t||0;for(var e=-1,u=vo(Gi((t-n)/(r||1)),0),i=Oi(u);++e<u;)i[e]=n,n+=r;return i}function Ai(n,t,r){if(n=Xi(n),1>n||!po(n))return[];var e=-1,u=Oi(_o(n,Ao));for(t=ur(t,r,1);++e<n;)Ao>e?u[e]=t(e):t(e);return u}function ji(n){var t=++qi;return f(n)+t}function Ci(n,t){return(+n||0)+(+t||0)}function ki(n,t,r){r&&Vr(n,t,r)&&(t=null);var e=Lr(),u=null==t;return e===wt&&u||(u=!1,t=e(t,r,3)),u?vt(ka(n)?n:ee(n)):Xt(n,t)}n=n?ot.defaults(it.Object(),n,ot.pick(it,Dn)):it;var Oi=n.Array,Ei=n.Date,Ii=n.Error,Ri=n.Function,Ti=n.Math,$i=n.Number,Si=n.Object,Ui=n.RegExp,Wi=n.String,Bi=n.TypeError,Li=Oi.prototype,Ni=Si.prototype,Fi=Wi.prototype,Pi=(Pi=n.window)&&Pi.document,zi=Ri.prototype.toString,Mi=Ni.hasOwnProperty,qi=0,Di=Ni.toString,Ki=n._,Vi=Ui("^"+ni(Di).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Yi=Ou(Yi=n.ArrayBuffer)&&Yi,Hi=Ou(Hi=Yi&&new Yi(0).slice)&&Hi,Gi=Ti.ceil,Ji=n.clearTimeout,Xi=Ti.floor,Zi=Ou(Zi=Si.getOwnPropertySymbols)&&Zi,Qi=Ou(Qi=Si.getPrototypeOf)&&Qi,no=Li.push,to=Ou(to=Si.preventExtensions)&&to,ro=Ni.propertyIsEnumerable,eo=Ou(eo=n.Set)&&eo,uo=n.setTimeout,io=Li.splice,oo=Ou(oo=n.Uint8Array)&&oo,ao=Ou(ao=n.WeakMap)&&ao,co=function(){try{var t=Ou(t=n.Float64Array)&&t,r=new t(new Yi(10),0,1)&&t}catch(e){}return r}(),lo=function(){var n=to&&Ou(n=Si.assign)&&n;try{if(n){var t=to({1:0});t[0]=1}}catch(r){try{n(t,"xo")}catch(r){}return!t[1]&&n}return!1}(),fo=Ou(fo=Oi.isArray)&&fo,so=Ou(so=Si.create)&&so,po=n.isFinite,ho=Ou(ho=Si.keys)&&ho,vo=Ti.max,_o=Ti.min,go=Ou(go=Ei.now)&&go,yo=Ou(yo=$i.isFinite)&&yo,mo=n.parseInt,wo=Ti.random,bo=$i.NEGATIVE_INFINITY,xo=$i.POSITIVE_INFINITY,Ao=Ti.pow(2,32)-1,jo=Ao-1,Co=Ao>>>1,ko=co?co.BYTES_PER_ELEMENT:0,Oo=Ti.pow(2,53)-1,Eo=ao&&new ao,Io={},Ro=t.support={};!function(n){var t=function(){this.x=n},r=arguments,e=[];t.prototype={valueOf:n,y:n};for(var u in new t)e.push(u);Ro.funcDecomp=/\bthis\b/.test(function(){return this}),Ro.funcNames="string"==typeof Ri.name;try{Ro.dom=11===Pi.createDocumentFragment().nodeType}catch(i){Ro.dom=!1}try{Ro.nonEnumArgs=!ro.call(r,1)}catch(i){Ro.nonEnumArgs=!0}}(1,0),t.templateSettings={escape:Cn,evaluate:kn,interpolate:On,variable:"",imports:{_:t}};var To=lo||function(n,t){return null==t?n:mt(t,Mo(t),mt(t,Na(t),n))},$o=function(){function t(){}return function(r){if(ju(r)){t.prototype=r;var e=new t;t.prototype=null}return e||n.Object()}}(),So=fr(Rt),Uo=fr(Tt,!0),Wo=sr(),Bo=sr(!0),Lo=Eo?function(n,t){return Eo.set(n,t),n}:vi;Hi||(ir=Yi&&oo?function(n){var t=n.byteLength,r=co?Xi(t/ko):0,e=r*ko,u=new Yi(t);if(r){var i=new co(u,0,r);i.set(new co(n,0,r))}return t!=e&&(i=new oo(u,e),i.set(new oo(n,e))),u}:hi(null));var No=so&&eo?function(n){return new Zn(n)}:hi(null),Fo=Eo?function(n){return Eo.get(n)}:mi,Po=function(){return Ro.funcNames?"constant"==hi.name?Mt("name"):function(n){for(var t=n.name,r=Io[t],e=r?r.length:0;e--;){var u=r[e],i=u.func;if(null==i||i==n)return u.name}return t}:hi("")}(),zo=Mt("length"),Mo=Zi?function(n){return Zi(ue(n))}:hi([]),qo=function(){var n=0,t=0;return function(r,e){var u=ha(),i=M-(u-t);if(t=u,i>0){if(++n>=z)return r}else n=0;return Lo(r,e)}}(),Do=su(function(n,t){return Dr(n)?At(n,Et(t,!1,!0)):[]}),Ko=dr(),Vo=dr(!0),Yo=su(function(n,t){t=Et(t);var r=dt(n,t);return Dt(n,t.sort(o)),r}),Ho=Tr(),Go=Tr(!0),Jo=su(function(n){return Zt(Et(n,!1,!0))}),Xo=su(function(n,t){return Dr(n)?At(n,t):[]}),Zo=su(Te),Qo=su(function(n){var t=n.length,r=n[t-2],e=n[t-1];return t>2&&"function"==typeof r?t-=2:(r=t>1&&"function"==typeof e?(--t,e):E,e=E),n.length=t,$e(n,r,e)}),na=su(function(n,t){return dt(n,Et(t))}),ta=cr(function(n,t,r){Mi.call(n,r)?++n[r]:n[r]=1}),ra=yr(So),ea=yr(Uo,!0),ua=br(rt,So),ia=br(et,Uo),oa=cr(function(n,t,r){Mi.call(n,r)?n[r].push(t):n[r]=[t]}),aa=cr(function(n,t,r){n[r]=t}),ca=su(function(n,t,r){var e=-1,u="function"==typeof t,i=Yr(t),o=Dr(n)?Oi(n.length):[];return So(n,function(n){var a=u?t:i&&null!=n&&n[t];o[++e]=a?a.apply(n,r):qr(n,t,r)}),o}),la=cr(function(n,t,r){n[r?0:1].push(t)},function(){return[[],[]]}),fa=Or(st,So),sa=Or(pt,Uo),pa=su(function(n,t){if(null==n)return[];var r=t[2];return r&&Vr(t[0],t[1],r)&&(t.length=1),Jt(n,Et(t),[])}),ha=go||function(){return(new Ei).getTime()},va=su(function(n,t,r){var e=R;if(r.length){var u=x(r,va.placeholder);e|=W}return $r(n,e,t,r,u)}),_a=su(function(n,t){t=t.length?Et(t):Lu(n);for(var r=-1,e=t.length;++r<e;){var u=t[r];n[u]=$r(n[u],R,n)}return n}),ga=su(function(n,t,r){var e=R|T;if(r.length){var u=x(r,ga.placeholder);e|=W}return $r(t,e,n,r,u)}),ya=_r(S),da=_r(U),ma=su(function(n,t){return xt(n,1,t)}),wa=su(function(n,t,r){return xt(n,t,r)}),ba=wr(),xa=wr(!0),Aa=kr(W),ja=kr(B),Ca=su(function(n,t){return $r(n,N,null,null,null,Et(t))}),ka=fo||function(n){return w(n)&&Gr(n.length)&&Di.call(n)==G};Ro.dom||(wu=function(n){return!!n&&1===n.nodeType&&w(n)&&!Ia(n)});var Oa=yo||function(n){return"number"==typeof n&&po(n)},Ea=l(/x/)||oo&&!l(oo)?function(n){return Di.call(n)==Q}:l,Ia=Qi?function(n){if(!n||Di.call(n)!=rn)return!1;var t=n.valueOf,r=Ou(t)&&(r=Qi(t))&&Qi(r);return r?n==r||Qi(n)==r:te(n)}:te,Ra=lr(function(n,t,r){return r?yt(n,t,r):To(n,t)}),Ta=su(function(n){var t=n[0];return null==t?t:(n.push(_t),Ra.apply(E,n))}),$a=mr(Rt),Sa=mr(Tt),Ua=xr(Wo),Wa=xr(Bo),Ba=Ar(Rt),La=Ar(Tt),Na=ho?function(n){var t=null!=n&&n.constructor;return"function"==typeof t&&t.prototype===n||"function"!=typeof n&&Dr(n)?re(n):ju(n)?ho(n):[]}:re,Fa=jr(!0),Pa=jr(),za=lr(Pt),Ma=su(function(n,t){if(null==n)return{};if("function"!=typeof t[0]){var t=ct(Et(t),Wi);return Zr(n,At(zu(n),t))}var r=ur(t[0],t[1],3);return Qr(n,function(n,t,e){return!r(n,t,e)})}),qa=su(function(n,t){return null==n?{}:"function"==typeof t[0]?Qr(n,ur(t[0],t[1],3)):Zr(n,Et(t))}),Da=hr(function(n,t,r){return t=t.toLowerCase(),n+(r?t.charAt(0).toUpperCase()+t.slice(1):t)}),Ka=hr(function(n,t,r){return n+(r?"-":"")+t.toLowerCase()}),Va=Cr(),Ya=Cr(!0);8!=mo(qn+"08")&&(ri=function(n,t,r){return(r?Vr(n,t,r):null==t)?t=0:t&&(t=+t),n=oi(n),mo(n,t||(Ln.test(n)?16:10))});var Ha=hr(function(n,t,r){return n+(r?"_":"")+t.toLowerCase()}),Ga=hr(function(n,t,r){return n+(r?" ":"")+(t.charAt(0).toUpperCase()+t.slice(1))}),Ja=su(function(n,t){try{return n.apply(E,t)}catch(r){return Au(r)?r:new Ii(r)}}),Xa=su(function(n,t){return function(r){return qr(r,n,t)}}),Za=su(function(n,t){return function(r){return qr(n,r,t)}}),Qa=gr(lt),nc=gr(ft,!0);return t.prototype=r.prototype,e.prototype=$o(r.prototype),e.prototype.constructor=e,u.prototype=$o(r.prototype),u.prototype.constructor=u,un.prototype["delete"]=an,un.prototype.get=Gn,un.prototype.has=Jn,un.prototype.set=Xn,Zn.prototype.push=nt,cu.Cache=un,t.after=uu,t.ary=iu,t.assign=Ra,t.at=na,t.before=ou,t.bind=va,t.bindAll=_a,t.bindKey=ga,t.callback=pi,t.chain=We,t.chunk=ae,t.compact=ce,t.constant=hi,t.countBy=ta,t.create=Bu,t.curry=ya,t.curryRight=da,t.debounce=au,t.defaults=Ta,t.defer=ma,t.delay=wa,t.difference=Do,t.drop=le,t.dropRight=fe,t.dropRightWhile=se,t.dropWhile=pe,t.fill=he,t.filter=Ke,t.flatten=_e,t.flattenDeep=ge,t.flow=ba,t.flowRight=xa,t.forEach=ua,t.forEachRight=ia,t.forIn=Ua,t.forInRight=Wa,t.forOwn=Ba,t.forOwnRight=La,t.functions=Lu,t.groupBy=oa,t.indexBy=aa,t.initial=de,t.intersection=me,t.invert=Pu,t.invoke=ca,t.keys=Na,t.keysIn=zu,t.map=He,t.mapKeys=Fa,t.mapValues=Pa,t.matches=_i,t.matchesProperty=gi,t.memoize=cu,t.merge=za,t.method=Xa,t.methodOf=Za,t.mixin=yi,t.negate=lu,t.omit=Ma,t.once=fu,t.pairs=Mu,t.partial=Aa,t.partialRight=ja,t.partition=la,t.pick=qa,t.pluck=Ge,t.property=wi,t.propertyOf=bi,t.pull=xe,t.pullAt=Yo,t.range=xi,t.rearg=Ca,t.reject=Je,t.remove=Ae,t.rest=je,t.restParam=su,t.set=Du,t.shuffle=Ze,t.slice=Ce,t.sortBy=tu,t.sortByAll=pa,t.sortByOrder=ru,t.spread=pu,t.take=ke,t.takeRight=Oe,t.takeRightWhile=Ee,t.takeWhile=Ie,t.tap=Be,t.throttle=hu,t.thru=Le,t.times=Ai,t.toArray=Uu,t.toPlainObject=Wu,t.transform=Ku,t.union=Jo,t.uniq=Re,t.unzip=Te,t.unzipWith=$e,t.values=Vu,t.valuesIn=Yu,t.where=eu,t.without=Xo,t.wrap=vu,t.xor=Se,t.zip=Zo,t.zipObject=Ue,t.zipWith=Qo,t.backflow=xa,t.collect=He,t.compose=xa,t.each=ua,t.eachRight=ia,t.extend=Ra,t.iteratee=pi,t.methods=Lu,t.object=Ue,t.select=Ke,t.tail=je,t.unique=Re,yi(t,t),t.add=Ci,t.attempt=Ja,t.camelCase=Da,t.capitalize=Ju,t.clone=_u,t.cloneDeep=gu,t.deburr=Xu,t.endsWith=Zu,t.escape=Qu,t.escapeRegExp=ni,t.every=De,t.find=ra,t.findIndex=Ko,t.findKey=$a,t.findLast=ea,t.findLastIndex=Vo,t.findLastKey=Sa,t.findWhere=Ve,t.first=ve,t.get=Nu,t.has=Fu,t.identity=vi,t.includes=Ye,t.indexOf=ye,t.inRange=Hu,t.isArguments=yu,t.isArray=ka,t.isBoolean=du,t.isDate=mu,t.isElement=wu,t.isEmpty=bu,t.isEqual=xu,t.isError=Au,t.isFinite=Oa,t.isFunction=Ea,t.isMatch=Cu,t.isNaN=ku,t.isNative=Ou,t.isNull=Eu,t.isNumber=Iu,t.isObject=ju,t.isPlainObject=Ia,t.isRegExp=Ru,t.isString=Tu,t.isTypedArray=$u,t.isUndefined=Su,t.kebabCase=Ka,t.last=we,t.lastIndexOf=be,t.max=Qa,t.min=nc,t.noConflict=di,t.noop=mi,t.now=ha,t.pad=ti,t.padLeft=Va,t.padRight=Ya,t.parseInt=ri,t.random=Gu,t.reduce=fa,t.reduceRight=sa,t.repeat=ei,t.result=qu,t.runInContext=O,t.size=Qe,t.snakeCase=Ha,t.some=nu,t.sortedIndex=Ho,t.sortedLastIndex=Go,t.startCase=Ga,t.startsWith=ui,t.sum=ki,t.template=ii,t.trim=oi,t.trimLeft=ai,t.trimRight=ci,t.trunc=li,t.unescape=fi,t.uniqueId=ji,t.words=si,t.all=De,t.any=nu,t.contains=Ye,t.detect=ra,t.foldl=fa,t.foldr=sa,t.head=ve,t.include=Ye,t.inject=fa,yi(t,function(){var n={};return Rt(t,function(r,e){t.prototype[e]||(n[e]=r)}),n}(),!1),t.sample=Xe,t.prototype.sample=function(n){return this.__chain__||null!=n?this.thru(function(t){return Xe(t,n)}):Xe(this.value())},t.VERSION=I,rt(["bind","bindKey","curry","curryRight","partial","partialRight"],function(n){t[n].placeholder=t}),rt(["dropWhile","filter","map","takeWhile"],function(n,t){var r=t!=K,e=t==q;u.prototype[n]=function(n,i){var o=this.__filtered__,a=o&&e?new u(this):this.clone(),c=a.__iteratees__||(a.__iteratees__=[]);return c.push({done:!1,count:0,index:0,iteratee:Lr(n,i,1),limit:-1,type:t}),a.__filtered__=o||r,a}}),rt(["drop","take"],function(n,t){var r=n+"While";u.prototype[n]=function(r){var e=this.__filtered__,u=e&&!t?this.dropWhile():this.clone();if(r=null==r?1:vo(Xi(r)||0,0),e)t?u.__takeCount__=_o(u.__takeCount__,r):we(u.__iteratees__).limit=r;else{var i=u.__views__||(u.__views__=[]);i.push({size:r,type:n+(u.__dir__<0?"Right":"")})}return u},u.prototype[n+"Right"]=function(t){return this.reverse()[n](t).reverse()},u.prototype[n+"RightWhile"]=function(n,t){return this.reverse()[r](n,t).reverse()}}),rt(["first","last"],function(n,t){var r="take"+(t?"Right":"");u.prototype[n]=function(){return this[r](1).value()[0]}}),rt(["initial","rest"],function(n,t){var r="drop"+(t?"":"Right");u.prototype[n]=function(){return this[r](1)}}),rt(["pluck","where"],function(n,t){var r=t?"filter":"map",e=t?Nt:wi;u.prototype[n]=function(n){return this[r](e(n))}}),u.prototype.compact=function(){return this.filter(vi)},u.prototype.reject=function(n,t){return n=Lr(n,t,1),this.filter(function(t){return!n(t)})},u.prototype.slice=function(n,t){n=null==n?0:+n||0;var r=this;return 0>n?r=this.takeRight(-n):n&&(r=this.drop(n)),t!==E&&(t=+t||0,r=0>t?r.dropRight(-t):r.take(t-n)),r},u.prototype.toArray=function(){return this.drop(0)},Rt(u.prototype,function(n,r){var i=t[r];if(i){var o=/^(?:filter|map|reject)|While$/.test(r),a=/^(?:first|last)$/.test(r);t.prototype[r]=function(){var r=arguments,c=this.__chain__,l=this.__wrapped__,f=!!this.__actions__.length,s=l instanceof u,p=r[0],h=s||ka(l);h&&o&&"function"==typeof p&&1!=p.length&&(s=h=!1);var v=s&&!f;if(a&&!c)return v?n.call(l):i.call(t,this.value());var _=function(n){var e=[n];return no.apply(e,r),i.apply(t,e)};if(h){var g=v?l:new u(this),y=n.apply(g,r);if(!a&&(f||y.__actions__)){var d=y.__actions__||(y.__actions__=[]);d.push({func:Le,args:[_],thisArg:t})}return new e(y,c)}return this.thru(_)}}}),rt(["concat","join","pop","push","replace","shift","sort","splice","split","unshift"],function(n){var r=(/^(?:replace|split)$/.test(n)?Fi:Li)[n],e=/^(?:push|sort|unshift)$/.test(n)?"tap":"thru",u=/^(?:join|pop|replace|shift)$/.test(n);t.prototype[n]=function(){var n=arguments;return u&&!this.__chain__?r.apply(this.value(),n):this[e](function(t){return r.apply(t,n)})}}),Rt(u.prototype,function(n,r){var e=t[r];if(e){var u=e.name,i=Io[u]||(Io[u]=[]);i.push({name:r,func:e})}}),Io[Er(null,T).name]=[{name:"wrapper",func:null}],u.prototype.clone=i,u.prototype.reverse=b,u.prototype.value=nn,t.prototype.chain=Ne,t.prototype.commit=Fe,t.prototype.plant=Pe,t.prototype.reverse=ze,t.prototype.toString=Me,t.prototype.run=t.prototype.toJSON=t.prototype.valueOf=t.prototype.value=qe,t.prototype.collect=t.prototype.map,t.prototype.head=t.prototype.first,t.prototype.select=t.prototype.filter,t.prototype.tail=t.prototype.rest,t}var E,I="3.8.0",R=1,T=2,$=4,S=8,U=16,W=32,B=64,L=128,N=256,F=30,P="...",z=150,M=16,q=0,D=1,K=2,V="Expected a function",Y="__lodash_placeholder__",H="[object Arguments]",G="[object Array]",J="[object Boolean]",X="[object Date]",Z="[object Error]",Q="[object Function]",nn="[object Map]",tn="[object Number]",rn="[object Object]",en="[object RegExp]",un="[object Set]",on="[object String]",an="[object WeakMap]",cn="[object ArrayBuffer]",ln="[object Float32Array]",fn="[object Float64Array]",sn="[object Int8Array]",pn="[object Int16Array]",hn="[object Int32Array]",vn="[object Uint8Array]",_n="[object Uint8ClampedArray]",gn="[object Uint16Array]",yn="[object Uint32Array]",dn=/\b__p \+= '';/g,mn=/\b(__p \+=) '' \+/g,wn=/(__e\(.*?\)|\b__t\)) \+\n'';/g,bn=/&(?:amp|lt|gt|quot|#39|#96);/g,xn=/[&<>"'`]/g,An=RegExp(bn.source),jn=RegExp(xn.source),Cn=/<%-([\s\S]+?)%>/g,kn=/<%([\s\S]+?)%>/g,On=/<%=([\s\S]+?)%>/g,En=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/,In=/^\w*$/,Rn=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g,Tn=/[.*+?^${}()|[\]\/\\]/g,$n=RegExp(Tn.source),Sn=/[\u0300-\u036f\ufe20-\ufe23]/g,Un=/\\(\\)?/g,Wn=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,Bn=/\w*$/,Ln=/^0[xX]/,Nn=/^\[object .+?Constructor\]$/,Fn=/[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g,Pn=/($^)/,zn=/['\n\r\u2028\u2029\\]/g,Mn=function(){var n="[A-Z\\xc0-\\xd6\\xd8-\\xde]",t="[a-z\\xdf-\\xf6\\xf8-\\xff]+";return RegExp(n+"+(?="+n+t+")|"+n+"?"+t+"|"+n+"+|[0-9]+","g")}(),qn=" \x0B\f \ufeff\n\r\u2028\u2029 ",Dn=["Array","ArrayBuffer","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Math","Number","Object","RegExp","Set","String","_","clearTimeout","document","isFinite","parseInt","setTimeout","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","window"],Kn=-1,Vn={};Vn[ln]=Vn[fn]=Vn[sn]=Vn[pn]=Vn[hn]=Vn[vn]=Vn[_n]=Vn[gn]=Vn[yn]=!0,Vn[H]=Vn[G]=Vn[cn]=Vn[J]=Vn[X]=Vn[Z]=Vn[Q]=Vn[nn]=Vn[tn]=Vn[rn]=Vn[en]=Vn[un]=Vn[on]=Vn[an]=!1;var Yn={};Yn[H]=Yn[G]=Yn[cn]=Yn[J]=Yn[X]=Yn[ln]=Yn[fn]=Yn[sn]=Yn[pn]=Yn[hn]=Yn[tn]=Yn[rn]=Yn[en]=Yn[on]=Yn[vn]=Yn[_n]=Yn[gn]=Yn[yn]=!0,Yn[Z]=Yn[Q]=Yn[nn]=Yn[un]=Yn[an]=!1;var Hn={leading:!1,maxWait:0,trailing:!1},Gn={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss"},Jn={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},Xn={"&":"&","<":"<",">":">",""":'"',"'":"'","`":"`"},Zn={"function":!0,object:!0},Qn={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},nt=Zn[typeof t]&&t&&!t.nodeType&&t,tt=Zn[typeof n]&&n&&!n.nodeType&&n,rt=nt&&tt&&"object"==typeof u&&u&&u.Object&&u,et=Zn[typeof self]&&self&&self.Object&&self,ut=Zn[typeof window]&&window&&window.Object&&window,it=(tt&&tt.exports===nt&&nt,rt||ut!==(this&&this.window)&&ut||et||this),ot=O();e=function(){return ot}.call(t,r,t,n),!(e!==E&&(n.exports=e)),i.constant("lodash",ot)}])}).call(t,r(2)(n),function(){return this}())},function(n,t){n.exports=function(n){return n.webpackPolyfill||(n.deprecate=function(){},n.paths=[],n.children=[],n.webpackPolyfill=1),n}}]); |
|
Java | apache-2.0 | 3ab0ef2767d4533283c942e0048cae557108ef32 | 0 | chibenwa/james,chibenwa/james,aduprat/james,rouazana/james,aduprat/james,chibenwa/james,chibenwa/james,aduprat/james,rouazana/james,aduprat/james,rouazana/james,rouazana/james | /****************************************************************
* 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.james.transport.mailets;
import org.apache.avalon.cornerstone.services.store.Store;
import org.apache.avalon.framework.configuration.DefaultConfiguration;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.james.Constants;
import org.apache.james.core.MailImpl;
import org.apache.james.services.MailRepository;
import org.apache.james.services.MailServer;
import org.apache.mailet.GenericMailet;
import org.apache.mailet.Mail;
import org.apache.mailet.MailAddress;
import org.apache.mailet.RFC2822Headers;
import javax.mail.Header;
import javax.mail.MessagingException;
import javax.mail.internet.InternetHeaders;
import javax.mail.internet.MimeMessage;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Vector;
/**
* Receives a Mail from JamesSpoolManager and takes care of delivery of the
* message to local inboxes or a specific repository.
*
* Differently from LocalDelivery this does not lookup the UserRepository This
* simply store the message in a repository named like the local part of the
* recipient address or the full recipient address, depending on the configuration
* (repositorySelector).
*
* If no repository is specified then this fallback to MailServer.getUserInbox.
* Otherwise you can add your own configuration for the repository
*
* e.g: <repositoryUrl>file://var/spool/userspools/</repositoryUrl>
* <repositoryType>SPOOL</repositoryType>
*
* <repositoryUrl>file://var/mail/inboxes/</repositoryUrl> <repositoryType>MAIL</repositoryType>
*
* Header "Delivered-To" can be added to every message adding the
* <addDeliveryHeader>Delivered-To</addDeliveryHeader>
*
* <repositorySelector> defaults to "localpart" and can be changed to "full" if you
* prefer to use full recipient emails as repository names.
*/
public class ToMultiRepository extends GenericMailet {
/**
* The number of mails generated. Access needs to be synchronized for thread
* safety and to ensure that all threads see the latest value.
*/
private static long count;
/**
* The mailserver reference
*/
private MailServer mailServer;
/**
* The mailstore
*/
private Store store;
/**
* The optional repositoryUrl
*/
private String repositoryUrl;
/**
* The optional repositoryType
*/
private String repositoryType;
private final static String SELECTOR_LOCALPART = "localpart";
private final static String SELECTOR_FULL = "full";
/**
* The optional repositorySelector
*/
private String repositorySelector;
/**
* The delivery header
*/
private String deliveryHeader;
/**
* resetReturnPath
*/
private boolean resetReturnPath;
/**
* Delivers a mail to a local mailbox.
*
* @param mail
* the mail being processed
*
* @throws MessagingException
* if an error occurs while storing the mail
*/
public void service(Mail mail) throws MessagingException {
Collection recipients = mail.getRecipients();
Collection errors = new Vector();
MimeMessage message = mail.getMessage();
if (resetReturnPath) {
// Set Return-Path and remove all other Return-Path headers from the
// message
// This only works because there is a placeholder inserted by
// MimeMessageWrapper
message.setHeader(RFC2822Headers.RETURN_PATH,
(mail.getSender() == null ? "<>" : "<" + mail.getSender()
+ ">"));
}
Enumeration headers;
InternetHeaders deliveredTo = new InternetHeaders();
if (deliveryHeader != null) {
// Copy any Delivered-To headers from the message
headers = message
.getMatchingHeaders(new String[] { deliveryHeader });
while (headers.hasMoreElements()) {
Header header = (Header) headers.nextElement();
deliveredTo.addHeader(header.getName(), header.getValue());
}
}
for (Iterator i = recipients.iterator(); i.hasNext();) {
MailAddress recipient = (MailAddress) i.next();
try {
if (deliveryHeader != null) {
// Add qmail's de facto standard Delivered-To header
message.addHeader(deliveryHeader, recipient.toString());
}
storeMail(mail.getSender(), recipient, message);
if (deliveryHeader != null) {
if (i.hasNext()) {
// Remove headers but leave all placeholders
message.removeHeader(deliveryHeader);
headers = deliveredTo.getAllHeaders();
// And restore any original Delivered-To headers
while (headers.hasMoreElements()) {
Header header = (Header) headers.nextElement();
message.addHeader(header.getName(), header
.getValue());
}
}
}
} catch (Exception ex) {
getMailetContext().log("Error while storing mail.", ex);
errors.add(recipient);
}
}
if (!errors.isEmpty()) {
// If there were errors, we redirect the email to the ERROR
// processor.
// In order for this server to meet the requirements of the SMTP
// specification, mails on the ERROR processor must be returned to
// the sender. Note that this email doesn't include any details
// regarding the details of the failure(s).
// In the future we may wish to address this.
getMailetContext().sendMail(mail.getSender(), errors, mail.getMessage(),
Mail.ERROR);
}
// We always consume this message
mail.setState(Mail.GHOST);
}
/**
* Return a string describing this mailet.
*
* @return a string describing this mailet
*/
public String getMailetInfo() {
return "ToMultiRepository Mailet";
}
/**
*
* @param sender
* @param recipient
* @param message
* @throws MessagingException
*/
public void storeMail(MailAddress sender, MailAddress recipient,
MimeMessage message) throws MessagingException {
String username;
if (recipient == null) {
throw new IllegalArgumentException(
"Recipient for mail to be spooled cannot be null.");
}
if (message == null) {
throw new IllegalArgumentException(
"Mail message to be spooled cannot be null.");
}
username = recipient.toString();
Collection recipients = new HashSet();
recipients.add(recipient);
MailImpl mail = new MailImpl(getId(), sender, recipients, message);
try {
MailRepository userInbox = getRepository(username);
if (userInbox == null) {
StringBuffer errorBuffer = new StringBuffer(128).append(
"The repository for user ").append(username).append(
" was not found on this server.");
throw new MessagingException(errorBuffer.toString());
}
userInbox.store(mail);
} finally {
mail.dispose();
}
}
/**
* Return a new mail id.
*
* @return a new mail id
*/
public String getId() {
long localCount = -1;
synchronized (this) {
localCount = count++;
}
StringBuffer idBuffer = new StringBuffer(64).append("Mail").append(
System.currentTimeMillis()).append("-").append(localCount).append('L');
return idBuffer.toString();
}
/**
* @see org.apache.mailet.GenericMailet#init()
*/
public void init() throws MessagingException {
super.init();
ServiceManager compMgr = (ServiceManager) getMailetContext()
.getAttribute(Constants.AVALON_COMPONENT_MANAGER);
try {
// Instantiate the a MailRepository for outgoing mails
store = (Store) compMgr.lookup(Store.ROLE);
} catch (ServiceException cnfe) {
log("Failed to retrieve Store component:" + cnfe.getMessage());
} catch (Exception e) {
log("Failed to retrieve Store component:" + e.getMessage());
}
repositoryUrl = getInitParameter("repositoryUrl");
if (repositoryUrl != null) {
if (!repositoryUrl.endsWith("/"))
repositoryUrl += "/";
repositoryType = getInitParameter("repositoryType");
if (repositoryType == null)
repositoryType = "MAIL";
repositorySelector = getInitParameter("repositorySelector");
if (repositorySelector == null)
repositorySelector = SELECTOR_LOCALPART;
if (!SELECTOR_LOCALPART.equals(repositorySelector) && !SELECTOR_FULL.equals(repositorySelector)) {
throw new MessagingException("repositorySelector valid options are "+SELECTOR_FULL+" or "+SELECTOR_LOCALPART);
}
} else {
try {
// Instantiate the a MailRepository for outgoing mails
mailServer = (MailServer) compMgr.lookup(MailServer.ROLE);
} catch (ServiceException cnfe) {
log("Failed to retrieve MailServer component:" + cnfe.getMessage());
} catch (Exception e) {
log("Failed to retrieve MailServer component:" + e.getMessage());
}
}
deliveryHeader = getInitParameter("addDeliveryHeader");
String resetReturnPathString = getInitParameter("resetReturnPath");
resetReturnPath = "true".equalsIgnoreCase(resetReturnPathString);
}
/**
* Get the user inbox: if the repositoryUrl is null then get the userinbox
* from the mailserver, otherwise lookup the store with the given
* repositoryurl/type
*
* @param userName
*/
private MailRepository getRepository(String userName) {
MailRepository userInbox;
if (repositoryUrl == null) {
userInbox = mailServer.getUserInbox(userName);
} else {
if (SELECTOR_LOCALPART.equals(repositorySelector)) {
// find the username for delivery to that user - localname, ignore the rest
String[] addressParts = userName.split("@");
userName = addressParts[0];
}
StringBuffer destinationBuffer = new StringBuffer(192).append(
repositoryUrl).append(userName).append("/");
String destination = destinationBuffer.toString();
DefaultConfiguration mboxConf = new DefaultConfiguration(
"repository", "generated:ToMultiRepository.getUserInbox()");
mboxConf.setAttribute("destinationURL", destination);
mboxConf.setAttribute("type", repositoryType);
try {
userInbox = (MailRepository) store.select(mboxConf);
} catch (Exception e) {
log("Cannot open repository " + e);
userInbox = null;
}
}
return userInbox;
}
}
| trunk/spoolmanager-function/src/main/java/org/apache/james/transport/mailets/ToMultiRepository.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.james.transport.mailets;
import org.apache.avalon.cornerstone.services.store.Store;
import org.apache.avalon.framework.configuration.DefaultConfiguration;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.james.Constants;
import org.apache.james.James;
import org.apache.james.core.MailImpl;
import org.apache.james.services.MailRepository;
import org.apache.james.services.MailServer;
import org.apache.mailet.GenericMailet;
import org.apache.mailet.Mail;
import org.apache.mailet.MailAddress;
import org.apache.mailet.RFC2822Headers;
import javax.mail.Header;
import javax.mail.MessagingException;
import javax.mail.internet.InternetHeaders;
import javax.mail.internet.MimeMessage;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Vector;
/**
* Receives a Mail from JamesSpoolManager and takes care of delivery of the
* message to local inboxes or a specific repository.
*
* Differently from LocalDelivery this does not lookup the UserRepository This
* simply store the message in a repository named like the local part of the
* recipient address or the full recipient address, depending on the configuration
* (repositorySelector).
*
* If no repository is specified then this fallback to MailServer.getUserInbox.
* Otherwise you can add your own configuration for the repository
*
* e.g: <repositoryUrl>file://var/spool/userspools/</repositoryUrl>
* <repositoryType>SPOOL</repositoryType>
*
* <repositoryUrl>file://var/mail/inboxes/</repositoryUrl> <repositoryType>MAIL</repositoryType>
*
* Header "Delivered-To" can be added to every message adding the
* <addDeliveryHeader>Delivered-To</addDeliveryHeader>
*
* <repositorySelector> defaults to "localpart" and can be changed to "full" if you
* prefer to use full recipient emails as repository names.
*/
public class ToMultiRepository extends GenericMailet {
/**
* The number of mails generated. Access needs to be synchronized for thread
* safety and to ensure that all threads see the latest value.
*/
private static long count;
/**
* The mailserver reference
*/
private MailServer mailServer;
/**
* The mailstore
*/
private Store store;
/**
* The optional repositoryUrl
*/
private String repositoryUrl;
/**
* The optional repositoryType
*/
private String repositoryType;
private final static String SELECTOR_LOCALPART = "localpart";
private final static String SELECTOR_FULL = "full";
/**
* The optional repositorySelector
*/
private String repositorySelector;
/**
* The delivery header
*/
private String deliveryHeader;
/**
* resetReturnPath
*/
private boolean resetReturnPath;
/**
* Delivers a mail to a local mailbox.
*
* @param mail
* the mail being processed
*
* @throws MessagingException
* if an error occurs while storing the mail
*/
public void service(Mail mail) throws MessagingException {
Collection recipients = mail.getRecipients();
Collection errors = new Vector();
MimeMessage message = mail.getMessage();
if (resetReturnPath) {
// Set Return-Path and remove all other Return-Path headers from the
// message
// This only works because there is a placeholder inserted by
// MimeMessageWrapper
message.setHeader(RFC2822Headers.RETURN_PATH,
(mail.getSender() == null ? "<>" : "<" + mail.getSender()
+ ">"));
}
Enumeration headers;
InternetHeaders deliveredTo = new InternetHeaders();
if (deliveryHeader != null) {
// Copy any Delivered-To headers from the message
headers = message
.getMatchingHeaders(new String[] { deliveryHeader });
while (headers.hasMoreElements()) {
Header header = (Header) headers.nextElement();
deliveredTo.addHeader(header.getName(), header.getValue());
}
}
for (Iterator i = recipients.iterator(); i.hasNext();) {
MailAddress recipient = (MailAddress) i.next();
try {
if (deliveryHeader != null) {
// Add qmail's de facto standard Delivered-To header
message.addHeader(deliveryHeader, recipient.toString());
}
storeMail(mail.getSender(), recipient, message);
if (deliveryHeader != null) {
if (i.hasNext()) {
// Remove headers but leave all placeholders
message.removeHeader(deliveryHeader);
headers = deliveredTo.getAllHeaders();
// And restore any original Delivered-To headers
while (headers.hasMoreElements()) {
Header header = (Header) headers.nextElement();
message.addHeader(header.getName(), header
.getValue());
}
}
}
} catch (Exception ex) {
getMailetContext().log("Error while storing mail.", ex);
errors.add(recipient);
}
}
if (!errors.isEmpty()) {
// If there were errors, we redirect the email to the ERROR
// processor.
// In order for this server to meet the requirements of the SMTP
// specification, mails on the ERROR processor must be returned to
// the sender. Note that this email doesn't include any details
// regarding the details of the failure(s).
// In the future we may wish to address this.
getMailetContext().sendMail(mail.getSender(), errors, mail.getMessage(),
Mail.ERROR);
}
// We always consume this message
mail.setState(Mail.GHOST);
}
/**
* Return a string describing this mailet.
*
* @return a string describing this mailet
*/
public String getMailetInfo() {
return "ToMultiRepository Mailet";
}
/**
*
* @param sender
* @param recipient
* @param message
* @throws MessagingException
*/
public void storeMail(MailAddress sender, MailAddress recipient,
MimeMessage message) throws MessagingException {
String username;
if (recipient == null) {
throw new IllegalArgumentException(
"Recipient for mail to be spooled cannot be null.");
}
if (message == null) {
throw new IllegalArgumentException(
"Mail message to be spooled cannot be null.");
}
username = recipient.toString();
Collection recipients = new HashSet();
recipients.add(recipient);
MailImpl mail = new MailImpl(getId(), sender, recipients, message);
try {
MailRepository userInbox = getRepository(username);
if (userInbox == null) {
StringBuffer errorBuffer = new StringBuffer(128).append(
"The repository for user ").append(username).append(
" was not found on this server.");
throw new MessagingException(errorBuffer.toString());
}
userInbox.store(mail);
} finally {
mail.dispose();
}
}
/**
* Return a new mail id.
*
* @return a new mail id
*/
public String getId() {
long localCount = -1;
synchronized (James.class) {
localCount = count++;
}
StringBuffer idBuffer = new StringBuffer(64).append("Mail").append(
System.currentTimeMillis()).append("-").append(localCount);
return idBuffer.toString();
}
/**
* @see org.apache.mailet.GenericMailet#init()
*/
public void init() throws MessagingException {
super.init();
ServiceManager compMgr = (ServiceManager) getMailetContext()
.getAttribute(Constants.AVALON_COMPONENT_MANAGER);
try {
// Instantiate the a MailRepository for outgoing mails
store = (Store) compMgr.lookup(Store.ROLE);
} catch (ServiceException cnfe) {
log("Failed to retrieve Store component:" + cnfe.getMessage());
} catch (Exception e) {
log("Failed to retrieve Store component:" + e.getMessage());
}
repositoryUrl = getInitParameter("repositoryUrl");
if (repositoryUrl != null) {
if (!repositoryUrl.endsWith("/"))
repositoryUrl += "/";
repositoryType = getInitParameter("repositoryType");
if (repositoryType == null)
repositoryType = "MAIL";
repositorySelector = getInitParameter("repositorySelector");
if (repositorySelector == null)
repositorySelector = SELECTOR_LOCALPART;
if (!SELECTOR_LOCALPART.equals(repositorySelector) && !SELECTOR_FULL.equals(repositorySelector)) {
throw new MessagingException("repositorySelector valid options are "+SELECTOR_FULL+" or "+SELECTOR_LOCALPART);
}
} else {
try {
// Instantiate the a MailRepository for outgoing mails
mailServer = (MailServer) compMgr.lookup(MailServer.ROLE);
} catch (ServiceException cnfe) {
log("Failed to retrieve MailServer component:" + cnfe.getMessage());
} catch (Exception e) {
log("Failed to retrieve MailServer component:" + e.getMessage());
}
}
deliveryHeader = getInitParameter("addDeliveryHeader");
String resetReturnPathString = getInitParameter("resetReturnPath");
resetReturnPath = "true".equalsIgnoreCase(resetReturnPathString);
}
/**
* Get the user inbox: if the repositoryUrl is null then get the userinbox
* from the mailserver, otherwise lookup the store with the given
* repositoryurl/type
*
* @param userName
*/
private MailRepository getRepository(String userName) {
MailRepository userInbox;
if (repositoryUrl == null) {
userInbox = mailServer.getUserInbox(userName);
} else {
if (SELECTOR_LOCALPART.equals(repositorySelector)) {
// find the username for delivery to that user - localname, ignore the rest
String[] addressParts = userName.split("@");
userName = addressParts[0];
}
StringBuffer destinationBuffer = new StringBuffer(192).append(
repositoryUrl).append(userName).append("/");
String destination = destinationBuffer.toString();
DefaultConfiguration mboxConf = new DefaultConfiguration(
"repository", "generated:ToMultiRepository.getUserInbox()");
mboxConf.setAttribute("destinationURL", destination);
mboxConf.setAttribute("type", repositoryType);
try {
userInbox = (MailRepository) store.select(mboxConf);
} catch (Exception e) {
log("Cannot open repository " + e);
userInbox = null;
}
}
return userInbox;
}
}
| Remove "bad" synchronization on James.class with custom counter: replaced with local synchronization/counter + custom naming scheme (identical to James one but adds a final "L" to the name)
git-svn-id: 88158f914d5603334254b4adf21dfd50ec107162@655453 13f79535-47bb-0310-9956-ffa450edef68
| trunk/spoolmanager-function/src/main/java/org/apache/james/transport/mailets/ToMultiRepository.java | Remove "bad" synchronization on James.class with custom counter: replaced with local synchronization/counter + custom naming scheme (identical to James one but adds a final "L" to the name) | <ide><path>runk/spoolmanager-function/src/main/java/org/apache/james/transport/mailets/ToMultiRepository.java
<ide> import org.apache.avalon.framework.service.ServiceException;
<ide> import org.apache.avalon.framework.service.ServiceManager;
<ide> import org.apache.james.Constants;
<del>import org.apache.james.James;
<ide> import org.apache.james.core.MailImpl;
<ide> import org.apache.james.services.MailRepository;
<ide> import org.apache.james.services.MailServer;
<ide> */
<ide> public String getId() {
<ide> long localCount = -1;
<del> synchronized (James.class) {
<add> synchronized (this) {
<ide> localCount = count++;
<ide> }
<ide> StringBuffer idBuffer = new StringBuffer(64).append("Mail").append(
<del> System.currentTimeMillis()).append("-").append(localCount);
<add> System.currentTimeMillis()).append("-").append(localCount).append('L');
<ide> return idBuffer.toString();
<ide> }
<ide>
<ide> String[] addressParts = userName.split("@");
<ide> userName = addressParts[0];
<ide> }
<del>
<add>
<ide> StringBuffer destinationBuffer = new StringBuffer(192).append(
<ide> repositoryUrl).append(userName).append("/");
<ide> String destination = destinationBuffer.toString(); |
|
JavaScript | mit | f5ab38b26ca15e14523fee144a1f3b73e682e01a | 0 | Limelight-Management-Group/sessions-auth-cookies-and-milk,Limelight-Management-Group/sessions-auth-cookies-and-milk | 'use strict'
const http = require('http')
const express = require( 'express' );
const app = express();
const server = http.createServer(app)
// const wss = new SocketServer({ server });
const socketIo = require('socket.io')
const io = require('socket.io').listen(server);
var session = require( 'express-session' );
const bodyParser = require( 'body-parser' );
const ejs = require( 'ejs' );
require('./controllers/userController')(app);
const queries = require('./database/db.js')
require('./views/tracker')(app);
require('./views/header/head')(app);
var morgan = require('morgan')
const path = require("path");
const locationMap = new Map()
const cookieParser = require('cookie-parser')
//use the morgan middleware to log each transaction
app.use(morgan('dev'));
app.use( cookieParser() );
// direct requests to the public directory
app.use( express.static( __dirname + '/public' ) );
// set up template
app.set( 'view engine', 'ejs' );
app.use( bodyParser.json() );
app.use( bodyParser.urlencoded( {
extended: false
} ) );
app.use((req, res, next) => {
if (req.cookies.user_sid && req.session) {
console.log('id check')
next();
} else {
console.log('id else condition')
next();
}
});
// initialize express-session to allow us track the logged-in user across sessions.
app.use(session( {
key: 'user_sid',
secret: 'somerandonstuffs',
resave: true,
saveUninitialized: true,
cookie: {
expires: 60000
}
} ) );
// middleware function to check for logged-in users
var sessionChecker = (req, res, next) => {
if (req.cookies.user_sid) {
console.log(req.cookies.user_sid)
res.render('profile');
} else {
next();
}
};
app.get('/', (req, res) => {
console.log('HERE IS THE COOKIE!', req.cookies)
console.log('session check!', req.session)
res.render('index');
})
app.get('/profile', (req, res) => {
console.log('here is the profile')
console.log('session check!', req.session)
res.render('profile');
})
app.route('/sign_up')
.get(sessionChecker, (req, res) => {
console.log('checking in from mentee home!')
res.render('sign_up');
})
.post((req, res) => {
queries.create({
username: req.body.username,
password: req.body.password,
f_name: req.body.f_name,
l_name: req.body.l_name,
email: req.body.email,
location: req.body.location,
age: req.body.age
})
.then(user => {
req.session.user = user.dataValues;
res.render('login', {user: user});
console.log('this is the user: ', user)
})
.catch(error => {
console.log(error)
res.redirect('/')
})
})
// route for user Login
app.get('/login', (req, res) => {
// console.log('this is the session Checker', sessionChecker)
res.render(__dirname + '/views/login.ejs');
});
app.post('/login', (req, res) => {
console.log('sent the post')
// console.log(mentee)
// console.log('username', mentee.username)
console.log('this is req.body from login: ', req.body)
// console.log('this is the req.body: ', req.body)
var username = req.body.login_username;
var password = req.body.login_password;
queries.getOneuser(username, password)
.then(user => {
// console.log('this si the user: ', user)
// console.log(mentee.menteename)
if (( user.username === username && user.password === password)){
// document.cookie = `username = ${user.username}`
console.log("yo! You're logged-in!!!!")
console.log('this is the user object', req.session)
var image = user.image
req.session.user_id = user.id;
// if(req.files){
// // console.log('these is the req.files', req.files)
// }
// fs.writeFile('public/images/kanye-west-fan.jpg', image, 'binary', function(err){
// if (err) throw err
// console.log('File saved.')
res.redirect('/profile');
// })
} else {
console.log('I did not login!!!')
// req.session.mentee = user.dataValues;
res.render('/');
}
}).catch(console.log)
});
app.get('/tracker', (req, res) => {
console.log('here is the tracker')
// console.log('session check!', req.session)
res.render('tracker');
})
app.get('/viewer', (req, res) => {
console.log('this is viewer!')
// console.log('session check!', req.session)
res.render('viewer');
})
io.on('connection', socket => {
socket.on('registerTracker', () => {
locationMap.set(socket.id, {lat: null, lng: null})
})
socket.on('updateLocation', pos => {
if(locationMap.has(socket.id)) {
locationMap.set(socket.id, pos)
console.log(socket.id, pos)
}
// locationMap.set(socket.id)
})
socket.on('requestLocations', () => {
socket.emit('locationsUpdate', Array.from(locationMap))
})
socket.on('disconnect', () => {
locationMap.delete(socket.id)
})
})
var port = process.env.PORT || 3002
// listen to port
server.listen(port)
console.log('session and cookies is listening on port: ' + port);;
module.exports = app;
| app.js | 'use strict'
const http = require('http')
const express = require( 'express' );
const app = express();
const server = http.createServer(app)
// const wss = new SocketServer({ server });
const socketIo = require('socket.io')
const io = require('socket.io').listen(server);
var session = require( 'express-session' );
const bodyParser = require( 'body-parser' );
const ejs = require( 'ejs' );
require('./controllers/userController')(app);
const queries = require('./database/db.js')
require('./views/tracker')(app);
require('./views/header/head')(app);
var morgan = require('morgan')
const path = require("path");
const locationMap = new Map()
const cookieParser = require('cookie-parser')
//use the morgan middleware to log each transaction
app.use(morgan('dev'));
app.use( cookieParser() );
// direct requests to the public directory
app.use( express.static( __dirname + '/public' ) );
// set up template
app.set( 'view engine', 'ejs' );
app.use( bodyParser.json() );
app.use( bodyParser.urlencoded( {
extended: false
} ) );
app.use((req, res, next) => {
if (req.cookies.user_sid && req.session) {
console.log('id check')
next();
} else {
console.log('id else condition')
next();
}
});
// initialize express-session to allow us track the logged-in user across sessions.
app.use(session( {
key: 'user_sid',
secret: 'somerandonstuffs',
resave: true,
saveUninitialized: true,
cookie: {
expires: 60000
}
} ) );
// middleware function to check for logged-in users
var sessionChecker = (req, res, next) => {
if (req.cookies.user_sid) {
console.log(req.cookies.user_sid)
res.render('profile');
} else {
next();
}
};
app.get('/', (req, res) => {
console.log('HERE IS THE COOKIE!', req.cookies)
console.log('session check!', req.session)
res.render('index');
})
app.get('/profile', (req, res) => {
console.log('here is the profile')
console.log('session check!', req.session)
res.render('profile');
})
app.route('/sign_up')
.get(sessionChecker, (req, res) => {
console.log('checking in from mentee home!')
res.render('sign_up');
})
.post((req, res) => {
queries.create({
username: req.body.username,
password: req.body.password,
f_name: req.body.f_name,
l_name: req.body.l_name,
email: req.body.email,
location: req.body.location,
age: req.body.age
})
.then(user => {
req.session.user = user.dataValues;
res.render('login', {user: user});
})
.catch(error => {
console.log(error)
res.redirect('/')
})
})
// route for user Login
app.get('/login', (req, res) => {
// console.log('this is the session Checker', sessionChecker)
res.render(__dirname + '/views/login.ejs');
});
app.post('/login', (req, res) => {
console.log('sent the post')
// console.log(mentee)
// console.log('username', mentee.username)
console.log('this is req.body from login: ', req.body)
// console.log('this is the req.body: ', req.body)
var username = req.body.login_username;
var password = req.body.login_password;
queries.getOneuser(username, password)
.then(user => {
// console.log('this si the user: ', user)
// console.log(mentee.menteename)
if (( user.username === username && user.password === password)){
// document.cookie = `username = ${user.username}`
console.log("yo! You're logged-in!!!!")
console.log('this is the user object', req.session)
var image = user.image
req.session.user_id = user.id;
// if(req.files){
// // console.log('these is the req.files', req.files)
// }
// fs.writeFile('public/images/kanye-west-fan.jpg', image, 'binary', function(err){
// if (err) throw err
// console.log('File saved.')
res.redirect('/profile');
// })
} else {
console.log('I did not login!!!')
// req.session.mentee = user.dataValues;
res.render('/');
}
}).catch(console.log)
});
app.get('/tracker', (req, res) => {
console.log('here is the tracker')
// console.log('session check!', req.session)
res.render('tracker');
})
app.get('/viewer', (req, res) => {
console.log('this is viewer!')
// console.log('session check!', req.session)
res.render('viewer');
})
io.on('connection', socket => {
socket.on('registerTracker', () => {
locationMap.set(socket.id, {lat: null, lng: null})
})
socket.on('updateLocation', pos => {
if(locationMap.has(socket.id)) {
locationMap.set(socket.id, pos)
console.log(socket.id, pos)
}
// locationMap.set(socket.id)
})
socket.on('requestLocations', () => {
socket.emit('locationsUpdate', Array.from(locationMap))
})
socket.on('disconnect', () => {
locationMap.delete(socket.id)
})
})
var port = process.env.PORT || 3002
// listen to port
server.listen(port)
console.log('session and cookies is listening on port: ' + port);;
module.exports = app;
| added database, created login and session, connected to heroku
| app.js | added database, created login and session, connected to heroku | <ide><path>pp.js
<ide> .then(user => {
<ide> req.session.user = user.dataValues;
<ide> res.render('login', {user: user});
<add> console.log('this is the user: ', user)
<ide> })
<ide> .catch(error => {
<ide> console.log(error) |
|
Java | apache-2.0 | 0acf9c981554f84b56467ca68dce9dbc41d477a9 | 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 | /*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.handler;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;
/**
* {@link org.springframework.web.servlet.HandlerExceptionResolver} implementation
* that allows for mapping exception class names to view names, either for a list
* of given handlers or for all handlers in the DispatcherServlet.
*
* <p>Error views are analogous to error page JSPs, but can be used with any
* kind of exception including any checked one, with fine-granular mappings for
* specific handlers.
*
* @author Juergen Hoeller
* @since 22.11.2003
* @see org.springframework.web.servlet.DispatcherServlet
*/
public class SimpleMappingExceptionResolver implements HandlerExceptionResolver, Ordered {
/**
* The default name of the exception attribute: "exception".
*/
public static final String DEFAULT_EXCEPTION_ATTRIBUTE = "exception";
/** Logger available to subclasses */
protected final Log logger = LogFactory.getLog(getClass());
private int order = Integer.MAX_VALUE; // default: same as non-Ordered
private Set mappedHandlers;
private Log warnLogger;
private Properties exceptionMappings;
private String defaultErrorView;
private Integer defaultStatusCode;
private String exceptionAttribute = DEFAULT_EXCEPTION_ATTRIBUTE;
public void setOrder(int order) {
this.order = order;
}
public int getOrder() {
return this.order;
}
/**
* Specify the set of handlers that this exception resolver should map.
* The exception mappings and the default error view will only apply
* to the specified handlers.
* <p>If no handlers set, both the exception mappings and the default error
* view will apply to all handlers. This means that a specified default
* error view will be used as fallback for all exceptions; any further
* HandlerExceptionResolvers in the chain will be ignored in this case.
*/
public void setMappedHandlers(Set mappedHandlers) {
this.mappedHandlers = mappedHandlers;
}
/**
* Set the log category for warn logging. The name will be passed to the
* underlying logger implementation through Commons Logging, getting
* interpreted as log category according to the logger's configuration.
* <p>Default is no warn logging. Specify this setting to activate
* warn logging into a specific category. Alternatively, override
* the {@link #logException} method for custom logging.
* @see org.apache.commons.logging.LogFactory#getLog(String)
* @see org.apache.log4j.Logger#getLogger(String)
* @see java.util.logging.Logger#getLogger(String)
*/
public void setWarnLogCategory(String loggerName) {
this.warnLogger = LogFactory.getLog(loggerName);
}
/**
* Set the mappings between exception class names and error view names.
* The exception class name can be a substring, with no wildcard support
* at present. A value of "ServletException" would match
* <code>javax.servlet.ServletException</code> and subclasses, for example.
* <p><b>NB:</b> Consider carefully how specific the pattern is, and whether
* to include package information (which isn't mandatory). For example,
* "Exception" will match nearly anything, and will probably hide other rules.
* "java.lang.Exception" would be correct if "Exception" was meant to define
* a rule for all checked exceptions. With more unusual exception names such
* as "BaseBusinessException" there's no need to use a FQN.
* <p>Follows the same matching algorithm as RuleBasedTransactionAttribute
* and RollbackRuleAttribute.
* @param mappings exception patterns (can also be fully qualified class names)
* as keys, and error view names as values
* @see org.springframework.transaction.interceptor.RuleBasedTransactionAttribute
* @see org.springframework.transaction.interceptor.RollbackRuleAttribute
*/
public void setExceptionMappings(Properties mappings) {
this.exceptionMappings = mappings;
}
/**
* Set the name of the default error view.
* This view will be returned if no specific mapping was found.
* <p>Default is none.
*/
public void setDefaultErrorView(String defaultErrorView) {
this.defaultErrorView = defaultErrorView;
}
/**
* Set the default HTTP status code that this exception resolver will apply
* if it resolves an error view.
* <p>Note that this error code will only get applied in case of a top-level
* request. It will not be set for an include request, since the HTTP status
* cannot be modified from within an include.
* <p>If not specified, no status code will be applied, either leaving this to
* the controller or view, or keeping the servlet engine's default of 200 (OK).
* @param defaultStatusCode HTTP status code value, for example
* 500 (SC_INTERNAL_SERVER_ERROR) or 404 (SC_NOT_FOUND)
* @see javax.servlet.http.HttpServletResponse#SC_INTERNAL_SERVER_ERROR
* @see javax.servlet.http.HttpServletResponse#SC_NOT_FOUND
*/
public void setDefaultStatusCode(int defaultStatusCode) {
this.defaultStatusCode = new Integer(defaultStatusCode);
}
/**
* Set the name of the model attribute as which the exception should
* be exposed. Default is "exception".
* <p>This can be either set to a different attribute name or to
* <code>null</code> for not exposing an exception attribute at all.
* @see #DEFAULT_EXCEPTION_ATTRIBUTE
*/
public void setExceptionAttribute(String exceptionAttribute) {
this.exceptionAttribute = exceptionAttribute;
}
public ModelAndView resolveException(
HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
// Check whether we're supposed to apply to the given handler.
if (this.mappedHandlers != null && !this.mappedHandlers.contains(handler)) {
return null;
}
// Log exception, both at debug log level and at warn level, if desired.
if (logger.isDebugEnabled()) {
logger.debug("Resolving exception from handler [" + handler + "]: " + ex);
}
logException(ex, request);
// Expose ModelAndView for chosen error view.
String viewName = determineViewName(ex, request);
if (viewName != null) {
// Apply HTTP status code for error views, if specified.
// Only apply it if we're processing a top-level request.
Integer statusCode = determineStatusCode(request, viewName);
if (statusCode != null) {
applyStatusCodeIfPossible(request, response, statusCode.intValue());
}
return getModelAndView(viewName, ex, request);
}
else {
return null;
}
}
/**
* Log the given exception at warn level, provided that warn logging has been
* activated through the {@link #setWarnLogCategory "warnLogCategory"} property.
* <p>Calls {@link #buildLogMessage} in order to determine the concrete message
* to log. Always passes the full exception to the logger.
* @param ex the exception that got thrown during handler execution
* @param request current HTTP request (useful for obtaining metadata)
* @see #setWarnLogCategory
* @see #buildLogMessage
* @see org.apache.commons.logging.Log#warn(Object, Throwable)
*/
protected void logException(Exception ex, HttpServletRequest request) {
if (this.warnLogger != null && this.warnLogger.isWarnEnabled()) {
this.warnLogger.warn(buildLogMessage(ex, request), ex);
}
}
/**
* Build a log message for the given exception, occured during processing
* the given request.
* @param ex the exception that got thrown during handler execution
* @param request current HTTP request (useful for obtaining metadata)
* @return the log message to use
*/
protected String buildLogMessage(Exception ex, HttpServletRequest request) {
return "Handler execution resulted in exception";
}
/**
* Determine the view name for the given exception, searching the
* {@link #setExceptionMappings "exceptionMappings"}, using the
* {@link #setDefaultErrorView "defaultErrorView"} as fallback.
* @param ex the exception that got thrown during handler execution
* @param request current HTTP request (useful for obtaining metadata)
* @return the resolved view name, or <code>null</code> if none found
*/
protected String determineViewName(Exception ex, HttpServletRequest request) {
String viewName = null;
// Check for specific exception mappings.
if (this.exceptionMappings != null) {
viewName = findMatchingViewName(this.exceptionMappings, ex);
}
// Return default error view else, if defined.
if (viewName == null && this.defaultErrorView != null) {
if (logger.isDebugEnabled()) {
logger.debug("Resolving to default view '" + this.defaultErrorView +
"' for exception of type [" + ex.getClass().getName() + "]");
}
viewName = this.defaultErrorView;
}
return viewName;
}
/**
* Find a matching view name in the given exception mappings.
* @param exceptionMappings mappings between exception class names and error view names
* @param ex the exception that got thrown during handler execution
* @return the view name, or <code>null</code> if none found
* @see #setExceptionMappings
*/
protected String findMatchingViewName(Properties exceptionMappings, Exception ex) {
String viewName = null;
String dominantMapping = null;
int deepest = Integer.MAX_VALUE;
for (Enumeration names = exceptionMappings.propertyNames(); names.hasMoreElements();) {
String exceptionMapping = (String) names.nextElement();
int depth = getDepth(exceptionMapping, ex);
if (depth >= 0 && depth < deepest) {
deepest = depth;
dominantMapping = exceptionMapping;
viewName = exceptionMappings.getProperty(exceptionMapping);
}
}
if (viewName != null && logger.isDebugEnabled()) {
logger.debug("Resolving to view '" + viewName + "' for exception of type [" + ex.getClass().getName() +
"], based on exception mapping [" + dominantMapping + "]");
}
return viewName;
}
/**
* Return the depth to the superclass matching.
* <p>0 means ex matches exactly. Returns -1 if there's no match.
* Otherwise, returns depth. Lowest depth wins.
* <p>Follows the same algorithm as
* {@link org.springframework.transaction.interceptor.RollbackRuleAttribute}.
*/
protected int getDepth(String exceptionMapping, Exception ex) {
return getDepth(exceptionMapping, ex.getClass(), 0);
}
private int getDepth(String exceptionMapping, Class exceptionClass, int depth) {
if (exceptionClass.getName().indexOf(exceptionMapping) != -1) {
// Found it!
return depth;
}
// If we've gone as far as we can go and haven't found it...
if (exceptionClass.equals(Throwable.class)) {
return -1;
}
return getDepth(exceptionMapping, exceptionClass.getSuperclass(), depth + 1);
}
/**
* Determine the HTTP status code to apply for the given error view.
* <p>The default implementation always returns the specified
* {@link #setDefaultStatusCode "defaultStatusCode"}, as a common
* status code for all error views. Override this in a custom subclass
* to determine a specific status code for the given view.
* @param request current HTTP request
* @param viewName the name of the error view
* @return the HTTP status code to use, or <code>null</code> for the
* servlet container's default (200 in case of a standard error view)
* @see #setDefaultStatusCode
* @see #applyStatusCodeIfPossible
*/
protected Integer determineStatusCode(HttpServletRequest request, String viewName) {
return this.defaultStatusCode;
}
/**
* Apply the specified HTTP status code to the given response, if possible
* (that is, if not executing within an include request).
* @param request current HTTP request
* @param response current HTTP response
* @param statusCode the status code to apply
* @see #determineStatusCode
* @see #setDefaultStatusCode
* @see javax.servlet.http.HttpServletResponse#setStatus
*/
protected void applyStatusCodeIfPossible(HttpServletRequest request, HttpServletResponse response, int statusCode) {
if (!WebUtils.isIncludeRequest(request)) {
if (logger.isDebugEnabled()) {
logger.debug("Applying HTTP status code " + statusCode);
}
response.setStatus(statusCode);
}
}
/**
* Return a ModelAndView for the given request, view name and exception.
* <p>The default implementation delegates to {@link #getModelAndView(String, Exception)}.
* @param viewName the name of the error view
* @param ex the exception that got thrown during handler execution
* @param request current HTTP request (useful for obtaining metadata)
* @return the ModelAndView instance
*/
protected ModelAndView getModelAndView(String viewName, Exception ex, HttpServletRequest request) {
return getModelAndView(viewName, ex);
}
/**
* Return a ModelAndView for the given view name and exception.
* <p>The default implementation adds the specified exception attribute.
* Can be overridden in subclasses.
* @param viewName the name of the error view
* @param ex the exception that got thrown during handler execution
* @return the ModelAndView instance
* @see #setExceptionAttribute
*/
protected ModelAndView getModelAndView(String viewName, Exception ex) {
ModelAndView mv = new ModelAndView(viewName);
if (this.exceptionAttribute != null) {
if (logger.isDebugEnabled()) {
logger.debug("Exposing Exception as model attribute '" + this.exceptionAttribute + "'");
}
mv.addObject(this.exceptionAttribute, ex);
}
return mv;
}
}
| src/org/springframework/web/servlet/handler/SimpleMappingExceptionResolver.java | /*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.handler;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;
/**
* Exception resolver that allows for mapping exception class names to view names,
* either for a list of given handlers or for all handlers in the DispatcherServlet.
*
* <p>Error views are analogous to error page JSPs, but can be used with any
* kind of exception including any checked one, with fine-granular mappings for
* specific handlers.
*
* @author Juergen Hoeller
* @since 22.11.2003
*/
public class SimpleMappingExceptionResolver implements HandlerExceptionResolver, Ordered {
/**
* The default name of the exception attribute: "exception".
*/
public static final String DEFAULT_EXCEPTION_ATTRIBUTE = "exception";
/** Logger available to subclasses */
protected final Log logger = LogFactory.getLog(getClass());
private int order = Integer.MAX_VALUE; // default: same as non-Ordered
private Set mappedHandlers;
private Log warnLogger;
private Properties exceptionMappings;
private String defaultErrorView;
private Integer defaultStatusCode;
private String exceptionAttribute = DEFAULT_EXCEPTION_ATTRIBUTE;
public void setOrder(int order) {
this.order = order;
}
public int getOrder() {
return this.order;
}
/**
* Specify the set of handlers that this exception resolver should map.
* The exception mappings and the default error view will only apply
* to the specified handlers.
* <p>If no handlers set, both the exception mappings and the default error
* view will apply to all handlers. This means that a specified default
* error view will be used as fallback for all exceptions; any further
* HandlerExceptionResolvers in the chain will be ignored in this case.
*/
public void setMappedHandlers(Set mappedHandlers) {
this.mappedHandlers = mappedHandlers;
}
/**
* Set the log category for warn logging. The name will be passed to the
* underlying logger implementation through Commons Logging, getting
* interpreted as log category according to the logger's configuration.
* <p>Default is no warn logging. Specify this setting to activate
* warn logging into a specific category. Alternatively, override
* the {@link #logException} method for custom logging.
* @see org.apache.commons.logging.LogFactory#getLog(String)
* @see org.apache.log4j.Logger#getLogger(String)
* @see java.util.logging.Logger#getLogger(String)
*/
public void setWarnLogCategory(String loggerName) {
this.warnLogger = LogFactory.getLog(loggerName);
}
/**
* Set the mappings between exception class names and error view names.
* The exception class name can be a substring, with no wildcard support
* at present. A value of "ServletException" would match
* <code>javax.servlet.ServletException</code> and subclasses, for example.
* <p><b>NB:</b> Consider carefully how specific the pattern is, and whether
* to include package information (which isn't mandatory). For example,
* "Exception" will match nearly anything, and will probably hide other rules.
* "java.lang.Exception" would be correct if "Exception" was meant to define
* a rule for all checked exceptions. With more unusual exception names such
* as "BaseBusinessException" there's no need to use a FQN.
* <p>Follows the same matching algorithm as RuleBasedTransactionAttribute
* and RollbackRuleAttribute.
* @param mappings exception patterns (can also be fully qualified class names)
* as keys, and error view names as values
* @see org.springframework.transaction.interceptor.RuleBasedTransactionAttribute
* @see org.springframework.transaction.interceptor.RollbackRuleAttribute
*/
public void setExceptionMappings(Properties mappings) {
this.exceptionMappings = mappings;
}
/**
* Set the name of the default error view.
* This view will be returned if no specific mapping was found.
* <p>Default is none.
*/
public void setDefaultErrorView(String defaultErrorView) {
this.defaultErrorView = defaultErrorView;
}
/**
* Set the default HTTP status code that this exception resolver will apply
* if it resolves an error view.
* <p>Note that this error code will only get applied in case of a top-level
* request. It will not be set for an include request, since the HTTP status
* cannot be modified from within an include.
* <p>If not specified, no status code will be applied, either leaving this to
* the controller or view, or keeping the servlet engine's default of 200 (OK).
* @param defaultStatusCode HTTP status code value, for example
* 500 (SC_INTERNAL_SERVER_ERROR) or 404 (SC_NOT_FOUND)
* @see javax.servlet.http.HttpServletResponse#SC_INTERNAL_SERVER_ERROR
* @see javax.servlet.http.HttpServletResponse#SC_NOT_FOUND
*/
public void setDefaultStatusCode(int defaultStatusCode) {
this.defaultStatusCode = new Integer(defaultStatusCode);
}
/**
* Set the name of the model attribute as which the exception should
* be exposed. Default is "exception".
* <p>This can be either set to a different attribute name or to
* <code>null</code> for not exposing an exception attribute at all.
* @see #DEFAULT_EXCEPTION_ATTRIBUTE
*/
public void setExceptionAttribute(String exceptionAttribute) {
this.exceptionAttribute = exceptionAttribute;
}
public ModelAndView resolveException(
HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
// Check whether we're supposed to apply to the given handler.
if (this.mappedHandlers != null && !this.mappedHandlers.contains(handler)) {
return null;
}
// Log exception, both at debug log level and at warn level, if desired.
if (logger.isDebugEnabled()) {
logger.debug("Resolving exception from handler [" + handler + "]: " + ex);
}
logException(ex, request);
// Expose ModelAndView for chosen error view.
String viewName = determineViewName(ex, request);
if (viewName != null) {
// Apply HTTP status code for error views, if specified.
// Only apply it if we're processing a top-level request.
Integer statusCode = determineStatusCode(request, viewName);
if (statusCode != null) {
applyStatusCodeIfPossible(request, response, statusCode.intValue());
}
return getModelAndView(viewName, ex, request);
}
else {
return null;
}
}
/**
* Log the given exception at warn level, provided that warn logging has been
* activated through the {@link #setWarnLogCategory "warnLogCategory"} property.
* <p>Calls {@link #buildLogMessage} in order to determine the concrete message
* to log. Always passes the full exception to the logger.
* @param ex the exception that got thrown during handler execution
* @param request current HTTP request (useful for obtaining metadata)
* @see #setWarnLogCategory
* @see #buildLogMessage
* @see org.apache.commons.logging.Log#warn(Object, Throwable)
*/
protected void logException(Exception ex, HttpServletRequest request) {
if (this.warnLogger != null && this.warnLogger.isWarnEnabled()) {
this.warnLogger.warn(buildLogMessage(ex, request), ex);
}
}
/**
* Build a log message for the given exception, occured during processing
* the given request.
* @param ex the exception that got thrown during handler execution
* @param request current HTTP request (useful for obtaining metadata)
* @return the log message to use
*/
protected String buildLogMessage(Exception ex, HttpServletRequest request) {
return "Handler execution resulted in exception";
}
/**
* Determine the view name for the given exception, searching the
* {@link #setExceptionMappings "exceptionMappings"}, using the
* {@link #setDefaultErrorView "defaultErrorView"} as fallback.
* @param ex the exception that got thrown during handler execution
* @param request current HTTP request (useful for obtaining metadata)
* @return the resolved view name, or <code>null</code> if none found
*/
protected String determineViewName(Exception ex, HttpServletRequest request) {
String viewName = null;
// Check for specific exception mappings.
if (this.exceptionMappings != null) {
viewName = findMatchingViewName(this.exceptionMappings, ex);
}
// Return default error view else, if defined.
if (viewName == null && this.defaultErrorView != null) {
if (logger.isDebugEnabled()) {
logger.debug("Resolving to default view '" + this.defaultErrorView +
"' for exception of type [" + ex.getClass().getName() + "]");
}
viewName = this.defaultErrorView;
}
return viewName;
}
/**
* Find a matching view name in the given exception mappings
* @param exceptionMappings mappings between exception class names and error view names
* @param ex the exception that got thrown during handler execution
* @return the view name, or <code>null</code> if none found
* @see #setExceptionMappings
*/
protected String findMatchingViewName(Properties exceptionMappings, Exception ex) {
String viewName = null;
String dominantMapping = null;
int deepest = Integer.MAX_VALUE;
for (Enumeration names = exceptionMappings.propertyNames(); names.hasMoreElements();) {
String exceptionMapping = (String) names.nextElement();
int depth = getDepth(exceptionMapping, ex);
if (depth >= 0 && depth < deepest) {
deepest = depth;
dominantMapping = exceptionMapping;
viewName = exceptionMappings.getProperty(exceptionMapping);
}
}
if (viewName != null && logger.isDebugEnabled()) {
logger.debug("Resolving to view '" + viewName + "' for exception of type [" + ex.getClass().getName() +
"], based on exception mapping [" + dominantMapping + "]");
}
return viewName;
}
/**
* Return the depth to the superclass matching.
* <p>0 means ex matches exactly. Returns -1 if there's no match.
* Otherwise, returns depth. Lowest depth wins.
* <p>Follows the same algorithm as
* {@link org.springframework.transaction.interceptor.RollbackRuleAttribute}.
*/
protected int getDepth(String exceptionMapping, Exception ex) {
return getDepth(exceptionMapping, ex.getClass(), 0);
}
private int getDepth(String exceptionMapping, Class exceptionClass, int depth) {
if (exceptionClass.getName().indexOf(exceptionMapping) != -1) {
// Found it!
return depth;
}
// If we've gone as far as we can go and haven't found it...
if (exceptionClass.equals(Throwable.class)) {
return -1;
}
return getDepth(exceptionMapping, exceptionClass.getSuperclass(), depth + 1);
}
/**
* Determine the HTTP status code to apply for the given error view.
* <p>The default implementation always returns the specified
* {@link #setDefaultStatusCode "defaultStatusCode"}, as a common
* status code for all error views. Override this in a custom subclass
* to determine a specific status code for the given view.
* @param request current HTTP request
* @param viewName the name of the error view
* @return the HTTP status code to use, or <code>null</code> for the
* servlet container's default (200 in case of a standard error view)
* @see #setDefaultStatusCode
* @see #applyStatusCodeIfPossible
*/
protected Integer determineStatusCode(HttpServletRequest request, String viewName) {
return this.defaultStatusCode;
}
/**
* Apply the specified HTTP status code to the given response, if possible
* (that is, if not executing within an include request).
* @param request current HTTP request
* @param response current HTTP response
* @param statusCode the status code to apply
* @see #determineStatusCode
* @see #setDefaultStatusCode
* @see javax.servlet.http.HttpServletResponse#setStatus
*/
protected void applyStatusCodeIfPossible(HttpServletRequest request, HttpServletResponse response, int statusCode) {
if (!WebUtils.isIncludeRequest(request)) {
if (logger.isDebugEnabled()) {
logger.debug("Applying HTTP status code " + statusCode);
}
response.setStatus(statusCode);
}
}
/**
* Return a ModelAndView for the given request, view name and exception.
* Default implementation delegates to <code>getModelAndView(viewName, ex)</code>.
* @param viewName the name of the error view
* @param ex the exception that got thrown during handler execution
* @param request current HTTP request (useful for obtaining metadata)
* @return the ModelAndView instance
* @see #getModelAndView(String, Exception)
*/
protected ModelAndView getModelAndView(String viewName, Exception ex, HttpServletRequest request) {
return getModelAndView(viewName, ex);
}
/**
* Return a ModelAndView for the given view name and exception.
* Default implementation adds the specified exception attribute.
* Can be overridden in subclasses.
* @param viewName the name of the error view
* @param ex the exception that got thrown during handler execution
* @return the ModelAndView instance
* @see #setExceptionAttribute
*/
protected ModelAndView getModelAndView(String viewName, Exception ex) {
ModelAndView mv = new ModelAndView(viewName);
if (this.exceptionAttribute != null) {
if (logger.isDebugEnabled()) {
logger.debug("Exposing Exception as model attribute '" + this.exceptionAttribute + "'");
}
mv.addObject(this.exceptionAttribute, ex);
}
return mv;
}
}
| revised javadoc
git-svn-id: b619a0c99665f88f1afe72824344cefe9a1c8c90@13249 fd5a2b45-1f63-4059-99e9-3c7cb7fd75c8
| src/org/springframework/web/servlet/handler/SimpleMappingExceptionResolver.java | revised javadoc | <ide><path>rc/org/springframework/web/servlet/handler/SimpleMappingExceptionResolver.java
<ide> import org.springframework.web.util.WebUtils;
<ide>
<ide> /**
<del> * Exception resolver that allows for mapping exception class names to view names,
<del> * either for a list of given handlers or for all handlers in the DispatcherServlet.
<add> * {@link org.springframework.web.servlet.HandlerExceptionResolver} implementation
<add> * that allows for mapping exception class names to view names, either for a list
<add> * of given handlers or for all handlers in the DispatcherServlet.
<ide> *
<ide> * <p>Error views are analogous to error page JSPs, but can be used with any
<ide> * kind of exception including any checked one, with fine-granular mappings for
<ide> *
<ide> * @author Juergen Hoeller
<ide> * @since 22.11.2003
<add> * @see org.springframework.web.servlet.DispatcherServlet
<ide> */
<ide> public class SimpleMappingExceptionResolver implements HandlerExceptionResolver, Ordered {
<ide>
<ide> }
<ide>
<ide> /**
<del> * Find a matching view name in the given exception mappings
<add> * Find a matching view name in the given exception mappings.
<ide> * @param exceptionMappings mappings between exception class names and error view names
<ide> * @param ex the exception that got thrown during handler execution
<ide> * @return the view name, or <code>null</code> if none found
<ide>
<ide> /**
<ide> * Return a ModelAndView for the given request, view name and exception.
<del> * Default implementation delegates to <code>getModelAndView(viewName, ex)</code>.
<add> * <p>The default implementation delegates to {@link #getModelAndView(String, Exception)}.
<ide> * @param viewName the name of the error view
<ide> * @param ex the exception that got thrown during handler execution
<ide> * @param request current HTTP request (useful for obtaining metadata)
<ide> * @return the ModelAndView instance
<del> * @see #getModelAndView(String, Exception)
<ide> */
<ide> protected ModelAndView getModelAndView(String viewName, Exception ex, HttpServletRequest request) {
<ide> return getModelAndView(viewName, ex);
<ide>
<ide> /**
<ide> * Return a ModelAndView for the given view name and exception.
<del> * Default implementation adds the specified exception attribute.
<add> * <p>The default implementation adds the specified exception attribute.
<ide> * Can be overridden in subclasses.
<ide> * @param viewName the name of the error view
<ide> * @param ex the exception that got thrown during handler execution |
|
Java | apache-2.0 | 6bc1680253e2562f859bc4361924741b44670ed3 | 0 | kalaspuffar/pdfbox,kalaspuffar/pdfbox,apache/pdfbox,apache/pdfbox | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.rendering;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.Paint;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.TexturePaint;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.GeneralPath;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.font.PDCIDFontType0;
import org.apache.pdfbox.pdmodel.font.PDCIDFontType2;
import org.apache.pdfbox.pdmodel.graphics.color.PDPattern;
import org.apache.pdfbox.pdmodel.graphics.image.PDImage;
import org.apache.pdfbox.pdmodel.graphics.pattern.PDAbstractPattern;
import org.apache.pdfbox.pdmodel.graphics.pattern.PDShadingPattern;
import org.apache.pdfbox.pdmodel.graphics.state.RenderingMode;
import org.apache.pdfbox.rendering.font.CIDType0Glyph2D;
import org.apache.pdfbox.rendering.font.Glyph2D;
import org.apache.pdfbox.rendering.font.TTFGlyph2D;
import org.apache.pdfbox.rendering.font.Type1Glyph2D;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDTrueTypeFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.font.PDType1CFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.graphics.PDLineDashPattern;
import org.apache.pdfbox.pdmodel.graphics.state.PDSoftMask;
import org.apache.pdfbox.pdmodel.graphics.blend.SoftMaskPaint;
import org.apache.pdfbox.pdmodel.graphics.color.PDColor;
import org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace;
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
import org.apache.pdfbox.pdmodel.graphics.pattern.PDTilingPattern;
import org.apache.pdfbox.pdmodel.graphics.shading.PDShading;
import org.apache.pdfbox.pdmodel.graphics.state.PDGraphicsState;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
import org.apache.pdfbox.util.Matrix;
import org.apache.pdfbox.contentstream.PDFGraphicsStreamEngine;
import org.apache.pdfbox.util.Vector;
/**
* Paints a page in a PDF document to a Graphics context.
*
* @author Ben Litchfield
*/
public final class PageDrawer extends PDFGraphicsStreamEngine
{
private static final Log LOG = LogFactory.getLog(PageDrawer.class);
// parent document renderer
private final PDFRenderer renderer;
// the graphics device to draw to, xform is the initial transform of the device (i.e. DPI)
private Graphics2D graphics;
private AffineTransform xform;
// the page box to draw (usually the crop box but may be another)
PDRectangle pageSize;
// clipping winding rule used for the clipping path
private int clipWindingRule = -1;
private GeneralPath linePath = new GeneralPath();
// last clipping path
private Area lastClip;
// buffered clipping area for text being drawn
private Area textClippingArea;
private final Map<PDFont, Glyph2D> fontGlyph2D = new HashMap<PDFont, Glyph2D>();
/**
* Constructor.
*
* @param renderer renderer to render the page.
* @param page the page that is to be rendered.
* @throws IOException If there is an error loading properties from the file.
*/
public PageDrawer(PDFRenderer renderer, PDPage page) throws IOException
{
super(page);
this.renderer = renderer;
}
/**
* Returns the parent renderer.
*/
public PDFRenderer getRenderer()
{
return renderer;
}
/**
* Sets high-quality rendering hints on the current Graphics2D.
*/
private void setRenderingHints()
{
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
}
/**
* Draws the page to the requested context.
*
* @param g The graphics context to draw onto.
* @param pageSize The size of the page to draw.
* @throws IOException If there is an IO error while drawing the page.
*/
public void drawPage(Graphics g, PDRectangle pageSize) throws IOException
{
graphics = (Graphics2D) g;
xform = graphics.getTransform();
this.pageSize = pageSize;
setRenderingHints();
graphics.translate(0, (int) pageSize.getHeight());
graphics.scale(1, -1);
// TODO use getStroke() to set the initial stroke
graphics.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
// adjust for non-(0,0) crop box
graphics.translate(-pageSize.getLowerLeftX(), -pageSize.getLowerLeftY());
processPage(getPage());
for (PDAnnotation annotation : getPage().getAnnotations())
{
showAnnotation(annotation);
}
graphics = null;
}
/**
* Draws the pattern stream to the requested context.
*
* @param g The graphics context to draw onto.
* @param pattern The tiling pattern to be used.
* @param colorSpace color space for this tiling.
* @param color color for this tiling.
* @param patternMatrix the pattern matrix
* @throws IOException If there is an IO error while drawing the page.
*/
public void drawTilingPattern(Graphics2D g, PDTilingPattern pattern, PDColorSpace colorSpace,
PDColor color, Matrix patternMatrix) throws IOException
{
Graphics2D oldGraphics = graphics;
graphics = g;
GeneralPath oldLinePath = linePath;
linePath = new GeneralPath();
Area oldLastClip = lastClip;
lastClip = null;
setRenderingHints();
processTilingPattern(pattern, color, colorSpace, patternMatrix);
graphics = oldGraphics;
linePath = oldLinePath;
lastClip = oldLastClip;
}
/**
* Returns an AWT paint for the given PDColor.
*/
private Paint getPaint(PDColor color) throws IOException
{
PDColorSpace colorSpace = color.getColorSpace();
if (!(colorSpace instanceof PDPattern))
{
float[] rgb = colorSpace.toRGB(color.getComponents());
return new Color(rgb[0], rgb[1], rgb[2]);
}
else
{
PDPattern patternSpace = (PDPattern)colorSpace;
PDAbstractPattern pattern = patternSpace.getPattern(color);
if (pattern instanceof PDTilingPattern)
{
PDTilingPattern tilingPattern = (PDTilingPattern) pattern;
if (tilingPattern.getPaintType() == PDTilingPattern.PAINT_COLORED)
{
// colored tiling pattern
return new TilingPaint(this, tilingPattern, xform);
}
else
{
// uncolored tiling pattern
return new TilingPaint(this, tilingPattern,
patternSpace.getUnderlyingColorSpace(), color, xform);
}
}
else
{
PDShadingPattern shadingPattern = (PDShadingPattern)pattern;
PDShading shading = shadingPattern.getShading();
if (shading == null)
{
LOG.error("shadingPattern is null, will be filled with transparency");
return new Color(0,0,0,0);
}
return shading.toPaint(Matrix.concatenate(getInitialMatrix(),
shadingPattern.getMatrix()));
}
}
}
// sets the clipping path using caching for performance, we track lastClip manually because
// Graphics2D#getClip() returns a new object instead of the same one passed to setClip
private void setClip()
{
Area clippingPath = getGraphicsState().getCurrentClippingPath();
if (clippingPath != lastClip)
{
graphics.setClip(clippingPath);
lastClip = clippingPath;
}
}
@Override
public void beginText() throws IOException
{
setClip();
}
@Override
protected void showText(byte[] string) throws IOException
{
PDGraphicsState state = getGraphicsState();
RenderingMode renderingMode = state.getTextState().getRenderingMode();
// buffer the text clip because it represents a single clipping area
if (renderingMode.isClip())
{
textClippingArea = new Area();
}
super.showText(string);
// apply the buffered clip as one area
if (renderingMode.isClip())
{
state.intersectClippingPath(textClippingArea);
textClippingArea = null;
}
}
@Override
protected void showFontGlyph(Matrix textRenderingMatrix, PDFont font, int code, String unicode,
Vector displacement) throws IOException
{
AffineTransform at = textRenderingMatrix.createAffineTransform();
at.concatenate(font.getFontMatrix().createAffineTransform());
Glyph2D glyph2D = createGlyph2D(font);
drawGlyph2D(glyph2D, font, code, displacement, at);
}
/**
* Render the font using the Glyph2D interface.
*
* @param glyph2D the Glyph2D implementation provided a GeneralPath for each glyph
* @param font the font
* @param code character code
* @param displacement the glyph's displacement (advance)
* @param at the transformation
* @throws IOException if something went wrong
*/
private void drawGlyph2D(Glyph2D glyph2D, PDFont font, int code, Vector displacement,
AffineTransform at) throws IOException
{
PDGraphicsState state = getGraphicsState();
RenderingMode renderingMode = state.getTextState().getRenderingMode();
GeneralPath path = glyph2D.getPathForCharacterCode(code);
if (path != null)
{
// stretch non-embedded glyph if it does not match the width contained in the PDF
if (!font.isEmbedded())
{
float fontWidth = font.getWidthFromFont(code);
if (fontWidth > 0 && // ignore spaces
Math.abs(fontWidth - displacement.getX() * 1000) > 0.0001)
{
float pdfWidth = displacement.getX() * 1000;
at.scale(pdfWidth / fontWidth, 1);
}
}
// render glyph
Shape glyph = at.createTransformedShape(path);
if (renderingMode.isFill())
{
graphics.setComposite(state.getNonStrokingJavaComposite());
graphics.setPaint(getNonStrokingPaint());
setClip();
graphics.fill(glyph);
}
if (renderingMode.isStroke())
{
graphics.setComposite(state.getStrokingJavaComposite());
graphics.setPaint(getStrokingPaint());
graphics.setStroke(getStroke());
setClip();
graphics.draw(glyph);
}
if (renderingMode.isClip())
{
textClippingArea.add(new Area(glyph));
}
}
}
/**
* Provide a Glyph2D for the given font.
*
* @param font the font
* @return the implementation of the Glyph2D interface for the given font
* @throws IOException if something went wrong
*/
private Glyph2D createGlyph2D(PDFont font) throws IOException
{
// Is there already a Glyph2D for the given font?
if (fontGlyph2D.containsKey(font))
{
return fontGlyph2D.get(font);
}
Glyph2D glyph2D = null;
if (font instanceof PDTrueTypeFont)
{
PDTrueTypeFont ttfFont = (PDTrueTypeFont)font;
glyph2D = new TTFGlyph2D(ttfFont); // TTF is never null
}
else if (font instanceof PDType1Font)
{
PDType1Font pdType1Font = (PDType1Font)font;
glyph2D = new Type1Glyph2D(pdType1Font); // T1 is never null
}
else if (font instanceof PDType1CFont)
{
PDType1CFont type1CFont = (PDType1CFont)font;
glyph2D = new Type1Glyph2D(type1CFont);
}
else if (font instanceof PDType0Font)
{
PDType0Font type0Font = (PDType0Font) font;
if (type0Font.getDescendantFont() instanceof PDCIDFontType2)
{
glyph2D = new TTFGlyph2D(type0Font); // TTF is never null
}
else if (type0Font.getDescendantFont() instanceof PDCIDFontType0)
{
// a Type0 CIDFont contains CFF font
PDCIDFontType0 cidType0Font = (PDCIDFontType0)type0Font.getDescendantFont();
glyph2D = new CIDType0Glyph2D(cidType0Font); // todo: could be null (need incorporate fallback)
}
}
else
{
throw new IllegalStateException("Bad font type: " + font.getClass().getSimpleName());
}
// cache the Glyph2D instance
if (glyph2D != null)
{
fontGlyph2D.put(font, glyph2D);
}
if (glyph2D == null)
{
// todo: make sure this never happens
throw new UnsupportedOperationException("No font for " + font.getName());
}
return glyph2D;
}
@Override
public void appendRectangle(Point2D p0, Point2D p1, Point2D p2, Point2D p3)
{
// to ensure that the path is created in the right direction, we have to create
// it by combining single lines instead of creating a simple rectangle
linePath.moveTo((float) p0.getX(), (float) p0.getY());
linePath.lineTo((float) p1.getX(), (float) p1.getY());
linePath.lineTo((float) p2.getX(), (float) p2.getY());
linePath.lineTo((float) p3.getX(), (float) p3.getY());
// close the subpath instead of adding the last line so that a possible set line
// cap style isn't taken into account at the "beginning" of the rectangle
linePath.closePath();
}
/**
* Generates AWT raster for a soft mask
*
* @param softMask soft mask
* @return AWT raster for soft mask
* @throws IOException
*/
private Raster createSoftMaskRaster(PDSoftMask softMask) throws IOException
{
TransparencyGroup transparencyGroup = new TransparencyGroup(softMask.getGroup(), true);
COSName subtype = softMask.getSubType();
if (COSName.ALPHA.equals(subtype))
{
return transparencyGroup.getAlphaRaster();
}
else if (COSName.LUMINOSITY.equals(subtype))
{
return transparencyGroup.getLuminosityRaster();
}
else
{
throw new IOException("Invalid soft mask subtype.");
}
}
private Paint applySoftMaskToPaint(Paint parentPaint, PDSoftMask softMask) throws IOException
{
if (softMask != null)
{
return new SoftMaskPaint(parentPaint, createSoftMaskRaster(softMask));
}
else
{
return parentPaint;
}
}
// returns the stroking AWT Paint
private Paint getStrokingPaint() throws IOException
{
return applySoftMaskToPaint(
getPaint(getGraphicsState().getStrokingColor()),
getGraphicsState().getSoftMask());
}
// returns the non-stroking AWT Paint
private Paint getNonStrokingPaint() throws IOException
{
return getPaint(getGraphicsState().getNonStrokingColor());
}
// create a new stroke based on the current CTM and the current stroke
private BasicStroke getStroke()
{
PDGraphicsState state = getGraphicsState();
// apply the CTM
float lineWidth = transformWidth(state.getLineWidth());
// minimum line width as used by Adobe Reader
if (lineWidth < 0.25)
{
lineWidth = 0.25f;
}
PDLineDashPattern dashPattern = state.getLineDashPattern();
int phaseStart = dashPattern.getPhase();
float[] dashArray = dashPattern.getDashArray();
if (dashArray != null)
{
// apply the CTM
for (int i = 0; i < dashArray.length; ++i)
{
// minimum line dash width avoids JVM crash, see PDFBOX-2373
dashArray[i] = Math.max(transformWidth(dashArray[i]), 0.25f);
}
phaseStart = (int)transformWidth(phaseStart);
// empty dash array is illegal
if (dashArray.length == 0)
{
dashArray = null;
}
}
return new BasicStroke(lineWidth, state.getLineCap(), state.getLineJoin(),
state.getMiterLimit(), dashArray, phaseStart);
}
@Override
public void strokePath() throws IOException
{
graphics.setComposite(getGraphicsState().getStrokingJavaComposite());
graphics.setPaint(getStrokingPaint());
graphics.setStroke(getStroke());
setClip();
graphics.draw(linePath);
linePath.reset();
}
@Override
public void fillPath(int windingRule) throws IOException
{
graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
graphics.setPaint(getNonStrokingPaint());
setClip();
linePath.setWindingRule(windingRule);
// disable anti-aliasing for rectangular paths, this is a workaround to avoid small stripes
// which occur when solid fills are used to simulate piecewise gradients, see PDFBOX-2302
boolean isRectangular = isRectangular(linePath);
if (isRectangular)
{
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
}
graphics.fill(linePath);
linePath.reset();
if (isRectangular)
{
// JDK 1.7 has a bug where rendering hints are reset by the above call to
// the setRenderingHint method, so we re-set all hints, see PDFBOX-2302
setRenderingHints();
}
}
/**
* Returns true if the given path is rectangular.
*/
private boolean isRectangular(GeneralPath path)
{
PathIterator iter = path.getPathIterator(null);
double[] coords = new double[6];
int count = 0;
int[] xs = new int[4];
int[] ys = new int[4];
while (!iter.isDone())
{
switch(iter.currentSegment(coords))
{
case PathIterator.SEG_MOVETO:
if (count == 0)
{
xs[count] = (int)Math.floor(coords[0]);
ys[count] = (int)Math.floor(coords[1]);
}
else
{
return false;
}
count++;
break;
case PathIterator.SEG_LINETO:
if (count < 4)
{
xs[count] = (int)Math.floor(coords[0]);
ys[count] = (int)Math.floor(coords[1]);
}
else
{
return false;
}
count++;
break;
case PathIterator.SEG_CUBICTO:
return false;
case PathIterator.SEG_CLOSE:
break;
}
iter.next();
}
if (count == 4)
{
return xs[0] == xs[1] || xs[0] == xs[2] ||
ys[0] == ys[1] || ys[0] == ys[3];
}
return false;
}
/**
* Fills and then strokes the path.
*
* @param windingRule The winding rule this path will use.
* @throws IOException If there is an IO error while filling the path.
*/
@Override
public void fillAndStrokePath(int windingRule) throws IOException
{
// TODO can we avoid cloning the path?
GeneralPath path = (GeneralPath)linePath.clone();
fillPath(windingRule);
linePath = path;
strokePath();
}
@Override
public void clip(int windingRule)
{
// the clipping path will not be updated until the succeeding painting operator is called
clipWindingRule = windingRule;
}
@Override
public void moveTo(float x, float y)
{
linePath.moveTo(x, y);
}
@Override
public void lineTo(float x, float y)
{
linePath.lineTo(x, y);
}
@Override
public void curveTo(float x1, float y1, float x2, float y2, float x3, float y3)
{
linePath.curveTo(x1, y1, x2, y2, x3, y3);
}
@Override
public Point2D.Float getCurrentPoint()
{
Point2D current = linePath.getCurrentPoint();
return new Point2D.Float((float)current.getX(), (float)current.getY());
}
@Override
public void closePath()
{
linePath.closePath();
}
@Override
public void endPath()
{
if (clipWindingRule != -1)
{
linePath.setWindingRule(clipWindingRule);
getGraphicsState().intersectClippingPath(linePath);
clipWindingRule = -1;
}
linePath.reset();
}
@Override
public void drawImage(PDImage pdImage) throws IOException
{
Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
AffineTransform at = ctm.createAffineTransform();
if (!pdImage.getInterpolate())
{
boolean isScaledUp = pdImage.getWidth() < Math.round(at.getScaleX()) ||
pdImage.getHeight() < Math.round(at.getScaleY());
// if the image is scaled down, we use smooth interpolation, eg PDFBOX-2364
// only when scaled up do we use nearest neighbour, eg PDFBOX-2302 / mori-cvpr01.pdf
// stencils are excluded from this rule (see survey.pdf)
if (isScaledUp || pdImage.isStencil())
{
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
}
}
if (pdImage.isStencil())
{
// fill the image with paint
PDColor color = getGraphicsState().getNonStrokingColor();
BufferedImage image = pdImage.getStencilImage(getPaint(color));
// draw the image
drawBufferedImage(image, at);
}
else
{
// draw the image
drawBufferedImage(pdImage.getImage(), at);
}
if (!pdImage.getInterpolate())
{
// JDK 1.7 has a bug where rendering hints are reset by the above call to
// the setRenderingHint method, so we re-set all hints, see PDFBOX-2302
setRenderingHints();
}
}
public void drawBufferedImage(BufferedImage image, AffineTransform at) throws IOException
{
graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
setClip();
PDSoftMask softMask = getGraphicsState().getSoftMask();
if( softMask != null )
{
AffineTransform imageTransform = new AffineTransform(at);
imageTransform.scale(1, -1);
imageTransform.translate(0, -1);
Paint awtPaint = new TexturePaint(image,
new Rectangle2D.Double(imageTransform.getTranslateX(), imageTransform.getTranslateY(),
imageTransform.getScaleX(), imageTransform.getScaleY()));
awtPaint = applySoftMaskToPaint(awtPaint, softMask);
graphics.setPaint(awtPaint);
Rectangle2D unitRect = new Rectangle2D.Float(0, 0, 1, 1);
graphics.fill(at.createTransformedShape(unitRect));
}
else
{
int width = image.getWidth(null);
int height = image.getHeight(null);
AffineTransform imageTransform = new AffineTransform(at);
imageTransform.scale(1.0 / width, -1.0 / height);
imageTransform.translate(0, -height);
graphics.drawImage(image, imageTransform, null);
}
}
@Override
public void shadingFill(COSName shadingName) throws IOException
{
PDShading shading = getResources().getShading(shadingName);
Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
Paint paint = shading.toPaint(ctm);
graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
graphics.setPaint(paint);
graphics.setClip(null);
lastClip = null;
graphics.fill(getGraphicsState().getCurrentClippingPath());
}
@Override
public void showAnnotation(PDAnnotation annotation) throws IOException
{
lastClip = null;
//TODO support more annotation flags (Invisible, NoZoom, NoRotate)
int deviceType = graphics.getDeviceConfiguration().getDevice().getType();
if (deviceType == GraphicsDevice.TYPE_PRINTER && !annotation.isPrinted())
{
return;
}
if (deviceType == GraphicsDevice.TYPE_RASTER_SCREEN && annotation.isNoView())
{
return;
}
if (annotation.isHidden())
{
return;
}
super.showAnnotation(annotation);
}
@Override
public void showTransparencyGroup(PDFormXObject form) throws IOException
{
TransparencyGroup group = new TransparencyGroup(form, false);
graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
setClip();
// both the DPI xform and the CTM were already applied to the group, so all we do
// here is draw it directly onto the Graphics2D device at the appropriate position
PDRectangle bbox = group.getBBox();
AffineTransform prev = graphics.getTransform();
float x = bbox.getLowerLeftX();
float y = pageSize.getHeight() - bbox.getLowerLeftY() - bbox.getHeight();
graphics.setTransform(AffineTransform.getTranslateInstance(x * xform.getScaleX(),
y * xform.getScaleY()));
PDSoftMask softMask = getGraphicsState().getSoftMask();
if (softMask != null)
{
BufferedImage image = group.getImage();
Paint awtPaint = new TexturePaint(image,
new Rectangle2D.Float(0, 0, image.getWidth(), image.getHeight()));
awtPaint = applySoftMaskToPaint(awtPaint, softMask); // todo: PDFBOX-994 problem here?
graphics.setPaint(awtPaint);
graphics.fill(new Rectangle2D.Float(0, 0, bbox.getWidth() * (float)xform.getScaleX(),
bbox.getHeight() * (float)xform.getScaleY()));
}
else
{
graphics.drawImage(group.getImage(), null, null);
}
graphics.setTransform(prev);
}
/**
* Transparency group.
**/
private final class TransparencyGroup
{
private final BufferedImage image;
private final PDRectangle bbox;
private final int minX;
private final int minY;
private final int width;
private final int height;
/**
* Creates a buffered image for a transparency group result.
*/
private TransparencyGroup(PDFormXObject form, boolean isSoftMask) throws IOException
{
Graphics2D g2dOriginal = graphics;
Area lastClipOriginal = lastClip;
// get the CTM x Form Matrix transform
Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
Matrix transform = Matrix.concatenate(ctm, form.getMatrix());
// transform the bbox
GeneralPath transformedBox = form.getBBox().transform(transform);
// clip the bbox to prevent giant bboxes from consuming all memory
Area clip = (Area)getGraphicsState().getCurrentClippingPath().clone();
clip.intersect(new Area(transformedBox));
Rectangle2D clipRect = clip.getBounds2D();
this.bbox = new PDRectangle((float)clipRect.getX(), (float)clipRect.getY(),
(float)clipRect.getWidth(), (float)clipRect.getHeight());
// apply the underlying Graphics2D device's DPI transform
Shape deviceClip = xform.createTransformedShape(clip);
Rectangle2D bounds = deviceClip.getBounds2D();
minX = (int) Math.floor(bounds.getMinX());
minY = (int) Math.floor(bounds.getMinY());
int maxX = (int) Math.floor(bounds.getMaxX()) + 1;
int maxY = (int) Math.floor(bounds.getMaxY()) + 1;
width = maxX - minX;
height = maxY - minY;
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); // FIXME - color space
Graphics2D g = image.createGraphics();
// flip y-axis
g.translate(0, height);
g.scale(1, -1);
// apply device transform (DPI)
g.transform(xform);
// adjust the origin
g.translate(-clipRect.getX(), -clipRect.getY());
graphics = g;
try
{
if (isSoftMask)
{
processSoftMask(form);
}
else
{
processTransparencyGroup(form);
}
}
finally
{
lastClip = lastClipOriginal;
graphics.dispose();
graphics = g2dOriginal;
}
}
public BufferedImage getImage()
{
return image;
}
public PDRectangle getBBox()
{
return bbox;
}
public Raster getAlphaRaster()
{
return image.getAlphaRaster();
}
public Raster getLuminosityRaster()
{
BufferedImage gray = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
Graphics g = gray.getGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return gray.getRaster();
}
}
}
| pdfbox/src/main/java/org/apache/pdfbox/rendering/PageDrawer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.rendering;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.Paint;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.TexturePaint;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.GeneralPath;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.font.PDCIDFontType0;
import org.apache.pdfbox.pdmodel.font.PDCIDFontType2;
import org.apache.pdfbox.pdmodel.graphics.color.PDPattern;
import org.apache.pdfbox.pdmodel.graphics.image.PDImage;
import org.apache.pdfbox.pdmodel.graphics.pattern.PDAbstractPattern;
import org.apache.pdfbox.pdmodel.graphics.pattern.PDShadingPattern;
import org.apache.pdfbox.pdmodel.graphics.state.RenderingMode;
import org.apache.pdfbox.rendering.font.CIDType0Glyph2D;
import org.apache.pdfbox.rendering.font.Glyph2D;
import org.apache.pdfbox.rendering.font.TTFGlyph2D;
import org.apache.pdfbox.rendering.font.Type1Glyph2D;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDTrueTypeFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.font.PDType1CFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.graphics.PDLineDashPattern;
import org.apache.pdfbox.pdmodel.graphics.state.PDSoftMask;
import org.apache.pdfbox.pdmodel.graphics.blend.SoftMaskPaint;
import org.apache.pdfbox.pdmodel.graphics.color.PDColor;
import org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace;
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
import org.apache.pdfbox.pdmodel.graphics.pattern.PDTilingPattern;
import org.apache.pdfbox.pdmodel.graphics.shading.PDShading;
import org.apache.pdfbox.pdmodel.graphics.state.PDGraphicsState;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
import org.apache.pdfbox.util.Matrix;
import org.apache.pdfbox.contentstream.PDFGraphicsStreamEngine;
import org.apache.pdfbox.util.Vector;
/**
* Paints a page in a PDF document to a Graphics context.
*
* @author Ben Litchfield
*/
public final class PageDrawer extends PDFGraphicsStreamEngine
{
private static final Log LOG = LogFactory.getLog(PageDrawer.class);
// parent document renderer
private final PDFRenderer renderer;
// the graphics device to draw to, xform is the initial transform of the device (i.e. DPI)
private Graphics2D graphics;
private AffineTransform xform;
// the page box to draw (usually the crop box but may be another)
PDRectangle pageSize;
// clipping winding rule used for the clipping path
private int clipWindingRule = -1;
private GeneralPath linePath = new GeneralPath();
// last clipping path
private Area lastClip;
// buffered clipping area for text being drawn
private Area textClippingArea;
private final Map<PDFont, Glyph2D> fontGlyph2D = new HashMap<PDFont, Glyph2D>();
/**
* Constructor.
*
* @param renderer renderer to render the page.
* @param page the page that is to be rendered.
* @throws IOException If there is an error loading properties from the file.
*/
public PageDrawer(PDFRenderer renderer, PDPage page) throws IOException
{
super(page);
this.renderer = renderer;
}
/**
* Returns the parent renderer.
*/
public PDFRenderer getRenderer()
{
return renderer;
}
/**
* Sets high-quality rendering hints on the current Graphics2D.
*/
private void setRenderingHints()
{
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
}
/**
* Draws the page to the requested context.
*
* @param g The graphics context to draw onto.
* @param pageSize The size of the page to draw.
* @throws IOException If there is an IO error while drawing the page.
*/
public void drawPage(Graphics g, PDRectangle pageSize) throws IOException
{
graphics = (Graphics2D) g;
xform = graphics.getTransform();
this.pageSize = pageSize;
setRenderingHints();
graphics.translate(0, (int) pageSize.getHeight());
graphics.scale(1, -1);
// TODO use getStroke() to set the initial stroke
graphics.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
// adjust for non-(0,0) crop box
graphics.translate(-pageSize.getLowerLeftX(), -pageSize.getLowerLeftY());
processPage(getPage());
for (PDAnnotation annotation : getPage().getAnnotations())
{
showAnnotation(annotation);
}
graphics = null;
}
/**
* Draws the pattern stream to the requested context.
*
* @param g The graphics context to draw onto.
* @param pattern The tiling pattern to be used.
* @param colorSpace color space for this tiling.
* @param color color for this tiling.
* @param patternMatrix the pattern matrix
* @throws IOException If there is an IO error while drawing the page.
*/
public void drawTilingPattern(Graphics2D g, PDTilingPattern pattern, PDColorSpace colorSpace,
PDColor color, Matrix patternMatrix) throws IOException
{
Graphics2D oldGraphics = graphics;
graphics = g;
GeneralPath oldLinePath = linePath;
linePath = new GeneralPath();
Area oldLastClip = lastClip;
lastClip = null;
setRenderingHints();
processTilingPattern(pattern, color, colorSpace, patternMatrix);
graphics = oldGraphics;
linePath = oldLinePath;
lastClip = oldLastClip;
}
/**
* Returns an AWT paint for the given PDColor.
*/
private Paint getPaint(PDColor color) throws IOException
{
PDColorSpace colorSpace = color.getColorSpace();
if (!(colorSpace instanceof PDPattern))
{
float[] rgb = colorSpace.toRGB(color.getComponents());
return new Color(rgb[0], rgb[1], rgb[2]);
}
else
{
PDPattern patternSpace = (PDPattern)colorSpace;
PDAbstractPattern pattern = patternSpace.getPattern(color);
if (pattern instanceof PDTilingPattern)
{
PDTilingPattern tilingPattern = (PDTilingPattern) pattern;
if (tilingPattern.getPaintType() == PDTilingPattern.PAINT_COLORED)
{
// colored tiling pattern
return new TilingPaint(this, tilingPattern, xform);
}
else
{
// uncolored tiling pattern
return new TilingPaint(this, tilingPattern,
patternSpace.getUnderlyingColorSpace(), color, xform);
}
}
else
{
PDShadingPattern shadingPattern = (PDShadingPattern)pattern;
PDShading shading = shadingPattern.getShading();
if (shading == null)
{
LOG.error("shadingPattern is null, will be filled with transparency");
return new Color(0,0,0,0);
}
return shading.toPaint(Matrix.concatenate(getInitialMatrix(),
shadingPattern.getMatrix()));
}
}
}
// sets the clipping path using caching for performance, we track lastClip manually because
// Graphics2D#getClip() returns a new object instead of the same one passed to setClip
private void setClip()
{
Area clippingPath = getGraphicsState().getCurrentClippingPath();
if (clippingPath != lastClip)
{
graphics.setClip(clippingPath);
lastClip = clippingPath;
}
}
@Override
public void beginText() throws IOException
{
setClip();
}
@Override
protected void showText(byte[] string) throws IOException
{
PDGraphicsState state = getGraphicsState();
RenderingMode renderingMode = state.getTextState().getRenderingMode();
// buffer the text clip because it represents a single clipping area
if (renderingMode.isClip())
{
textClippingArea = new Area();
}
super.showText(string);
// apply the buffered clip as one area
if (renderingMode.isClip())
{
state.intersectClippingPath(textClippingArea);
textClippingArea = null;
}
}
@Override
protected void showFontGlyph(Matrix textRenderingMatrix, PDFont font, int code, String unicode,
Vector displacement) throws IOException
{
AffineTransform at = textRenderingMatrix.createAffineTransform();
at.concatenate(font.getFontMatrix().createAffineTransform());
Glyph2D glyph2D = createGlyph2D(font);
drawGlyph2D(glyph2D, font, code, displacement, at);
}
/**
* Render the font using the Glyph2D interface.
*
* @param glyph2D the Glyph2D implementation provided a GeneralPath for each glyph
* @param font the font
* @param code character code
* @param displacement the glyph's displacement (advance)
* @param at the transformation
* @throws IOException if something went wrong
*/
private void drawGlyph2D(Glyph2D glyph2D, PDFont font, int code, Vector displacement,
AffineTransform at) throws IOException
{
PDGraphicsState state = getGraphicsState();
RenderingMode renderingMode = state.getTextState().getRenderingMode();
GeneralPath path = glyph2D.getPathForCharacterCode(code);
if (path != null)
{
// stretch non-embedded glyph if it does not match the width contained in the PDF
if (!font.isEmbedded())
{
float fontWidth = font.getWidthFromFont(code);
if (fontWidth > 0 && // ignore spaces
Math.abs(fontWidth - displacement.getX() * 1000) > 0.0001)
{
float pdfWidth = displacement.getX() * 1000;
at.scale(pdfWidth / fontWidth, 1);
}
}
// render glyph
Shape glyph = at.createTransformedShape(path);
if (renderingMode.isFill())
{
graphics.setComposite(state.getNonStrokingJavaComposite());
graphics.setPaint(getNonStrokingPaint());
setClip();
graphics.fill(glyph);
}
if (renderingMode.isStroke())
{
graphics.setComposite(state.getStrokingJavaComposite());
graphics.setPaint(getStrokingPaint());
graphics.setStroke(getStroke());
setClip();
graphics.draw(glyph);
}
if (renderingMode.isClip())
{
textClippingArea.add(new Area(glyph));
}
}
}
/**
* Provide a Glyph2D for the given font.
*
* @param font the font
* @return the implementation of the Glyph2D interface for the given font
* @throws IOException if something went wrong
*/
private Glyph2D createGlyph2D(PDFont font) throws IOException
{
// Is there already a Glyph2D for the given font?
if (fontGlyph2D.containsKey(font))
{
return fontGlyph2D.get(font);
}
Glyph2D glyph2D = null;
if (font instanceof PDTrueTypeFont)
{
PDTrueTypeFont ttfFont = (PDTrueTypeFont)font;
glyph2D = new TTFGlyph2D(ttfFont); // TTF is never null
}
else if (font instanceof PDType1Font)
{
PDType1Font pdType1Font = (PDType1Font)font;
glyph2D = new Type1Glyph2D(pdType1Font); // T1 is never null
}
else if (font instanceof PDType1CFont)
{
PDType1CFont type1CFont = (PDType1CFont)font;
glyph2D = new Type1Glyph2D(type1CFont);
}
else if (font instanceof PDType0Font)
{
PDType0Font type0Font = (PDType0Font) font;
if (type0Font.getDescendantFont() instanceof PDCIDFontType2)
{
glyph2D = new TTFGlyph2D(type0Font); // TTF is never null
}
else if (type0Font.getDescendantFont() instanceof PDCIDFontType0)
{
// a Type0 CIDFont contains CFF font
PDCIDFontType0 cidType0Font = (PDCIDFontType0)type0Font.getDescendantFont();
glyph2D = new CIDType0Glyph2D(cidType0Font); // todo: could be null (need incorporate fallback)
}
}
else
{
throw new IllegalStateException("Bad font type: " + font.getClass().getSimpleName());
}
// cache the Glyph2D instance
if (glyph2D != null)
{
fontGlyph2D.put(font, glyph2D);
}
if (glyph2D == null)
{
// todo: make sure this never happens
throw new UnsupportedOperationException("No font for " + font.getName());
}
return glyph2D;
}
@Override
public void appendRectangle(Point2D p0, Point2D p1, Point2D p2, Point2D p3)
{
// to ensure that the path is created in the right direction, we have to create
// it by combining single lines instead of creating a simple rectangle
linePath.moveTo((float) p0.getX(), (float) p0.getY());
linePath.lineTo((float) p1.getX(), (float) p1.getY());
linePath.lineTo((float) p2.getX(), (float) p2.getY());
linePath.lineTo((float) p3.getX(), (float) p3.getY());
// close the subpath instead of adding the last line so that a possible set line
// cap style isn't taken into account at the "beginning" of the rectangle
linePath.closePath();
}
/**
* Generates AWT raster for a soft mask
*
* @param softMask soft mask
* @return AWT raster for soft mask
* @throws IOException
*/
private Raster createSoftMaskRaster(PDSoftMask softMask) throws IOException
{
TransparencyGroup transparencyGroup = new TransparencyGroup(softMask.getGroup(), true);
COSName subtype = softMask.getSubType();
if (COSName.ALPHA.equals(subtype))
{
return transparencyGroup.getAlphaRaster();
}
else if (COSName.LUMINOSITY.equals(subtype))
{
return transparencyGroup.getLuminosityRaster();
}
else
{
throw new IOException("Invalid soft mask subtype.");
}
}
private Paint applySoftMaskToPaint(Paint parentPaint, PDSoftMask softMask) throws IOException
{
if (softMask != null)
{
return new SoftMaskPaint(parentPaint, createSoftMaskRaster(softMask));
}
else
{
return parentPaint;
}
}
// returns the stroking AWT Paint
private Paint getStrokingPaint() throws IOException
{
return applySoftMaskToPaint(
getPaint(getGraphicsState().getStrokingColor()),
getGraphicsState().getSoftMask());
}
// returns the non-stroking AWT Paint
private Paint getNonStrokingPaint() throws IOException
{
return getPaint(getGraphicsState().getNonStrokingColor());
}
// create a new stroke based on the current CTM and the current stroke
private BasicStroke getStroke()
{
PDGraphicsState state = getGraphicsState();
// apply the CTM
float lineWidth = transformWidth(state.getLineWidth());
// minimum line width as used by Adobe Reader
if (lineWidth < 0.25)
{
lineWidth = 0.25f;
}
PDLineDashPattern dashPattern = state.getLineDashPattern();
int phaseStart = dashPattern.getPhase();
float[] dashArray = dashPattern.getDashArray();
if (dashArray != null)
{
// apply the CTM
for (int i = 0; i < dashArray.length; ++i)
{
dashArray[i] = transformWidth(dashArray[i]);
}
phaseStart = (int)transformWidth(phaseStart);
// empty dash array is illegal
if (dashArray.length == 0)
{
dashArray = null;
}
}
return new BasicStroke(lineWidth, state.getLineCap(), state.getLineJoin(),
state.getMiterLimit(), dashArray, phaseStart);
}
@Override
public void strokePath() throws IOException
{
graphics.setComposite(getGraphicsState().getStrokingJavaComposite());
graphics.setPaint(getStrokingPaint());
graphics.setStroke(getStroke());
setClip();
graphics.draw(linePath);
linePath.reset();
}
@Override
public void fillPath(int windingRule) throws IOException
{
graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
graphics.setPaint(getNonStrokingPaint());
setClip();
linePath.setWindingRule(windingRule);
// disable anti-aliasing for rectangular paths, this is a workaround to avoid small stripes
// which occur when solid fills are used to simulate piecewise gradients, see PDFBOX-2302
boolean isRectangular = isRectangular(linePath);
if (isRectangular)
{
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
}
graphics.fill(linePath);
linePath.reset();
if (isRectangular)
{
// JDK 1.7 has a bug where rendering hints are reset by the above call to
// the setRenderingHint method, so we re-set all hints, see PDFBOX-2302
setRenderingHints();
}
}
/**
* Returns true if the given path is rectangular.
*/
private boolean isRectangular(GeneralPath path)
{
PathIterator iter = path.getPathIterator(null);
double[] coords = new double[6];
int count = 0;
int[] xs = new int[4];
int[] ys = new int[4];
while (!iter.isDone())
{
switch(iter.currentSegment(coords))
{
case PathIterator.SEG_MOVETO:
if (count == 0)
{
xs[count] = (int)Math.floor(coords[0]);
ys[count] = (int)Math.floor(coords[1]);
}
else
{
return false;
}
count++;
break;
case PathIterator.SEG_LINETO:
if (count < 4)
{
xs[count] = (int)Math.floor(coords[0]);
ys[count] = (int)Math.floor(coords[1]);
}
else
{
return false;
}
count++;
break;
case PathIterator.SEG_CUBICTO:
return false;
case PathIterator.SEG_CLOSE:
break;
}
iter.next();
}
if (count == 4)
{
return xs[0] == xs[1] || xs[0] == xs[2] ||
ys[0] == ys[1] || ys[0] == ys[3];
}
return false;
}
/**
* Fills and then strokes the path.
*
* @param windingRule The winding rule this path will use.
* @throws IOException If there is an IO error while filling the path.
*/
@Override
public void fillAndStrokePath(int windingRule) throws IOException
{
// TODO can we avoid cloning the path?
GeneralPath path = (GeneralPath)linePath.clone();
fillPath(windingRule);
linePath = path;
strokePath();
}
@Override
public void clip(int windingRule)
{
// the clipping path will not be updated until the succeeding painting operator is called
clipWindingRule = windingRule;
}
@Override
public void moveTo(float x, float y)
{
linePath.moveTo(x, y);
}
@Override
public void lineTo(float x, float y)
{
linePath.lineTo(x, y);
}
@Override
public void curveTo(float x1, float y1, float x2, float y2, float x3, float y3)
{
linePath.curveTo(x1, y1, x2, y2, x3, y3);
}
@Override
public Point2D.Float getCurrentPoint()
{
Point2D current = linePath.getCurrentPoint();
return new Point2D.Float((float)current.getX(), (float)current.getY());
}
@Override
public void closePath()
{
linePath.closePath();
}
@Override
public void endPath()
{
if (clipWindingRule != -1)
{
linePath.setWindingRule(clipWindingRule);
getGraphicsState().intersectClippingPath(linePath);
clipWindingRule = -1;
}
linePath.reset();
}
@Override
public void drawImage(PDImage pdImage) throws IOException
{
Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
AffineTransform at = ctm.createAffineTransform();
if (!pdImage.getInterpolate())
{
boolean isScaledUp = pdImage.getWidth() < Math.round(at.getScaleX()) ||
pdImage.getHeight() < Math.round(at.getScaleY());
// if the image is scaled down, we use smooth interpolation, eg PDFBOX-2364
// only when scaled up do we use nearest neighbour, eg PDFBOX-2302 / mori-cvpr01.pdf
// stencils are excluded from this rule (see survey.pdf)
if (isScaledUp || pdImage.isStencil())
{
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
}
}
if (pdImage.isStencil())
{
// fill the image with paint
PDColor color = getGraphicsState().getNonStrokingColor();
BufferedImage image = pdImage.getStencilImage(getPaint(color));
// draw the image
drawBufferedImage(image, at);
}
else
{
// draw the image
drawBufferedImage(pdImage.getImage(), at);
}
if (!pdImage.getInterpolate())
{
// JDK 1.7 has a bug where rendering hints are reset by the above call to
// the setRenderingHint method, so we re-set all hints, see PDFBOX-2302
setRenderingHints();
}
}
public void drawBufferedImage(BufferedImage image, AffineTransform at) throws IOException
{
graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
setClip();
PDSoftMask softMask = getGraphicsState().getSoftMask();
if( softMask != null )
{
AffineTransform imageTransform = new AffineTransform(at);
imageTransform.scale(1, -1);
imageTransform.translate(0, -1);
Paint awtPaint = new TexturePaint(image,
new Rectangle2D.Double(imageTransform.getTranslateX(), imageTransform.getTranslateY(),
imageTransform.getScaleX(), imageTransform.getScaleY()));
awtPaint = applySoftMaskToPaint(awtPaint, softMask);
graphics.setPaint(awtPaint);
Rectangle2D unitRect = new Rectangle2D.Float(0, 0, 1, 1);
graphics.fill(at.createTransformedShape(unitRect));
}
else
{
int width = image.getWidth(null);
int height = image.getHeight(null);
AffineTransform imageTransform = new AffineTransform(at);
imageTransform.scale(1.0 / width, -1.0 / height);
imageTransform.translate(0, -height);
graphics.drawImage(image, imageTransform, null);
}
}
@Override
public void shadingFill(COSName shadingName) throws IOException
{
PDShading shading = getResources().getShading(shadingName);
Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
Paint paint = shading.toPaint(ctm);
graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
graphics.setPaint(paint);
graphics.setClip(null);
lastClip = null;
graphics.fill(getGraphicsState().getCurrentClippingPath());
}
@Override
public void showAnnotation(PDAnnotation annotation) throws IOException
{
lastClip = null;
//TODO support more annotation flags (Invisible, NoZoom, NoRotate)
int deviceType = graphics.getDeviceConfiguration().getDevice().getType();
if (deviceType == GraphicsDevice.TYPE_PRINTER && !annotation.isPrinted())
{
return;
}
if (deviceType == GraphicsDevice.TYPE_RASTER_SCREEN && annotation.isNoView())
{
return;
}
if (annotation.isHidden())
{
return;
}
super.showAnnotation(annotation);
}
@Override
public void showTransparencyGroup(PDFormXObject form) throws IOException
{
TransparencyGroup group = new TransparencyGroup(form, false);
graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
setClip();
// both the DPI xform and the CTM were already applied to the group, so all we do
// here is draw it directly onto the Graphics2D device at the appropriate position
PDRectangle bbox = group.getBBox();
AffineTransform prev = graphics.getTransform();
float x = bbox.getLowerLeftX();
float y = pageSize.getHeight() - bbox.getLowerLeftY() - bbox.getHeight();
graphics.setTransform(AffineTransform.getTranslateInstance(x * xform.getScaleX(),
y * xform.getScaleY()));
PDSoftMask softMask = getGraphicsState().getSoftMask();
if (softMask != null)
{
BufferedImage image = group.getImage();
Paint awtPaint = new TexturePaint(image,
new Rectangle2D.Float(0, 0, image.getWidth(), image.getHeight()));
awtPaint = applySoftMaskToPaint(awtPaint, softMask); // todo: PDFBOX-994 problem here?
graphics.setPaint(awtPaint);
graphics.fill(new Rectangle2D.Float(0, 0, bbox.getWidth() * (float)xform.getScaleX(),
bbox.getHeight() * (float)xform.getScaleY()));
}
else
{
graphics.drawImage(group.getImage(), null, null);
}
graphics.setTransform(prev);
}
/**
* Transparency group.
**/
private final class TransparencyGroup
{
private final BufferedImage image;
private final PDRectangle bbox;
private final int minX;
private final int minY;
private final int width;
private final int height;
/**
* Creates a buffered image for a transparency group result.
*/
private TransparencyGroup(PDFormXObject form, boolean isSoftMask) throws IOException
{
Graphics2D g2dOriginal = graphics;
Area lastClipOriginal = lastClip;
// get the CTM x Form Matrix transform
Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
Matrix transform = Matrix.concatenate(ctm, form.getMatrix());
// transform the bbox
GeneralPath transformedBox = form.getBBox().transform(transform);
// clip the bbox to prevent giant bboxes from consuming all memory
Area clip = (Area)getGraphicsState().getCurrentClippingPath().clone();
clip.intersect(new Area(transformedBox));
Rectangle2D clipRect = clip.getBounds2D();
this.bbox = new PDRectangle((float)clipRect.getX(), (float)clipRect.getY(),
(float)clipRect.getWidth(), (float)clipRect.getHeight());
// apply the underlying Graphics2D device's DPI transform
Shape deviceClip = xform.createTransformedShape(clip);
Rectangle2D bounds = deviceClip.getBounds2D();
minX = (int) Math.floor(bounds.getMinX());
minY = (int) Math.floor(bounds.getMinY());
int maxX = (int) Math.floor(bounds.getMaxX()) + 1;
int maxY = (int) Math.floor(bounds.getMaxY()) + 1;
width = maxX - minX;
height = maxY - minY;
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); // FIXME - color space
Graphics2D g = image.createGraphics();
// flip y-axis
g.translate(0, height);
g.scale(1, -1);
// apply device transform (DPI)
g.transform(xform);
// adjust the origin
g.translate(-clipRect.getX(), -clipRect.getY());
graphics = g;
try
{
if (isSoftMask)
{
processSoftMask(form);
}
else
{
processTransparencyGroup(form);
}
}
finally
{
lastClip = lastClipOriginal;
graphics.dispose();
graphics = g2dOriginal;
}
}
public BufferedImage getImage()
{
return image;
}
public PDRectangle getBBox()
{
return bbox;
}
public Raster getAlphaRaster()
{
return image.getAlphaRaster();
}
public Raster getLuminosityRaster()
{
BufferedImage gray = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
Graphics g = gray.getGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return gray.getRaster();
}
}
}
| PDFBOX-2373: Use minimum line width for dash patterns to avoid JVM crash
git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1657690 13f79535-47bb-0310-9956-ffa450edef68
| pdfbox/src/main/java/org/apache/pdfbox/rendering/PageDrawer.java | PDFBOX-2373: Use minimum line width for dash patterns to avoid JVM crash | <ide><path>dfbox/src/main/java/org/apache/pdfbox/rendering/PageDrawer.java
<ide> // apply the CTM
<ide> for (int i = 0; i < dashArray.length; ++i)
<ide> {
<del> dashArray[i] = transformWidth(dashArray[i]);
<add> // minimum line dash width avoids JVM crash, see PDFBOX-2373
<add> dashArray[i] = Math.max(transformWidth(dashArray[i]), 0.25f);
<ide> }
<ide> phaseStart = (int)transformWidth(phaseStart);
<ide> |
|
Java | apache-2.0 | 9e64ba02f5437dd047c63d6e238b9b867ae53536 | 0 | semonte/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,semonte/intellij-community,dslomov/intellij-community,dslomov/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,samthor/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,hurricup/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,da1z/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,robovm/robovm-studio,dslomov/intellij-community,slisson/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,slisson/intellij-community,signed/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,semonte/intellij-community,apixandru/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,adedayo/intellij-community,kool79/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,fnouama/intellij-community,samthor/intellij-community,diorcety/intellij-community,caot/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,adedayo/intellij-community,kool79/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,signed/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,samthor/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,signed/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,signed/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,signed/intellij-community,ryano144/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,caot/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,ryano144/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,vvv1559/intellij-community,slisson/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,holmes/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,kdwink/intellij-community,fitermay/intellij-community,retomerz/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,semonte/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,izonder/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,fnouama/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,supersven/intellij-community,apixandru/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,kool79/intellij-community,mglukhikh/intellij-community,signed/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,adedayo/intellij-community,jagguli/intellij-community,slisson/intellij-community,robovm/robovm-studio,FHannes/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,ryano144/intellij-community,amith01994/intellij-community,fitermay/intellij-community,izonder/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,diorcety/intellij-community,slisson/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,jagguli/intellij-community,blademainer/intellij-community,izonder/intellij-community,supersven/intellij-community,clumsy/intellij-community,signed/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,asedunov/intellij-community,da1z/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,da1z/intellij-community,signed/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,caot/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,samthor/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,da1z/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,retomerz/intellij-community,retomerz/intellij-community,xfournet/intellij-community,clumsy/intellij-community,signed/intellij-community,akosyakov/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,ibinti/intellij-community,semonte/intellij-community,da1z/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,fnouama/intellij-community,dslomov/intellij-community,kdwink/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,da1z/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,ibinti/intellij-community,izonder/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,holmes/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,FHannes/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,FHannes/intellij-community,supersven/intellij-community,vvv1559/intellij-community,slisson/intellij-community,semonte/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,caot/intellij-community,caot/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,signed/intellij-community,robovm/robovm-studio,samthor/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,kool79/intellij-community,apixandru/intellij-community,allotria/intellij-community,retomerz/intellij-community,semonte/intellij-community,kool79/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,supersven/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,amith01994/intellij-community,ibinti/intellij-community,allotria/intellij-community,vladmm/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,diorcety/intellij-community,adedayo/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,ryano144/intellij-community,FHannes/intellij-community,ibinti/intellij-community,ibinti/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,caot/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,kdwink/intellij-community,petteyg/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,fitermay/intellij-community,clumsy/intellij-community,ibinti/intellij-community,adedayo/intellij-community,signed/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,caot/intellij-community,pwoodworth/intellij-community,caot/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,izonder/intellij-community,holmes/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,da1z/intellij-community,asedunov/intellij-community,caot/intellij-community,da1z/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,petteyg/intellij-community,izonder/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,kool79/intellij-community,supersven/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,kool79/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,slisson/intellij-community,robovm/robovm-studio,allotria/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,supersven/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,fnouama/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,semonte/intellij-community,xfournet/intellij-community,holmes/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,izonder/intellij-community,petteyg/intellij-community,diorcety/intellij-community,supersven/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,adedayo/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,samthor/intellij-community,jagguli/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,amith01994/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,allotria/intellij-community,xfournet/intellij-community,amith01994/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,orekyuu/intellij-community,holmes/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,fitermay/intellij-community,retomerz/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,jagguli/intellij-community,allotria/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,signed/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,samthor/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,blademainer/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,clumsy/intellij-community,robovm/robovm-studio,akosyakov/intellij-community | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.updateSettings.impl;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.ide.plugins.PluginManagerMain;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.util.Comparing;
import com.intellij.ui.ColoredTableCellRenderer;
import com.intellij.ui.OrderPanel;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.UIUtil;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.util.*;
import java.util.List;
/**
* @author anna
* Date: 04-Dec-2007
*/
public class DetectedPluginsPanel extends OrderPanel<PluginDownloader> {
private final List<Listener> myListeners = ContainerUtil.createLockFreeCopyOnWriteList();
private static JEditorPane myDescriptionPanel = new JEditorPane();
public DetectedPluginsPanel() {
super(PluginDownloader.class);
final JTable entryTable = getEntryTable();
entryTable.setTableHeader(null);
entryTable.setDefaultRenderer(PluginDownloader.class, new ColoredTableCellRenderer() {
protected void customizeCellRenderer(final JTable table,
final Object value,
final boolean selected,
final boolean hasFocus,
final int row,
final int column) {
setBorder(null);
final PluginDownloader downloader = (PluginDownloader)value;
if (downloader != null) {
final String pluginName = downloader.getPluginName();
append(pluginName, SimpleTextAttributes.REGULAR_ATTRIBUTES);
final IdeaPluginDescriptor ideaPluginDescriptor = PluginManager.getPlugin(PluginId.getId(downloader.getPluginId()));
if (ideaPluginDescriptor != null) {
final String oldPluginName = ideaPluginDescriptor.getName();
if (!Comparing.strEqual(pluginName, oldPluginName)) {
append(" - " + oldPluginName, SimpleTextAttributes.REGULAR_ATTRIBUTES);
}
}
final String loadedVersion = downloader.getPluginVersion();
if (loadedVersion != null || (ideaPluginDescriptor != null && ideaPluginDescriptor.getVersion() != null)) {
final String installedVersion = ideaPluginDescriptor != null && ideaPluginDescriptor.getVersion() != null
? "v. " + ideaPluginDescriptor.getVersion() + (loadedVersion != null ? " -> " : "")
: "";
final String availableVersion = loadedVersion != null ? loadedVersion : "";
append(" (" + installedVersion + availableVersion + ")", SimpleTextAttributes.GRAY_ATTRIBUTES);
}
}
}
});
entryTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
final int selectedRow = entryTable.getSelectedRow();
if (selectedRow != -1) {
final PluginDownloader selection = getValueAt(selectedRow);
final IdeaPluginDescriptor descriptor = selection.getDescriptor();
if (descriptor != null) {
PluginManagerMain.pluginInfoUpdate(descriptor, null, myDescriptionPanel);
}
}
}
});
setCheckboxColumnName("");
myDescriptionPanel.setPreferredSize(new Dimension(400, -1));
myDescriptionPanel.setEditable(false);
myDescriptionPanel.setContentType(UIUtil.HTML_MIME);
myDescriptionPanel.addHyperlinkListener(new PluginManagerMain.MyHyperlinkListener());
removeAll();
final Splitter splitter = new Splitter(false);
splitter.setFirstComponent(ScrollPaneFactory.createScrollPane(entryTable));
splitter.setSecondComponent(ScrollPaneFactory.createScrollPane(myDescriptionPanel));
add(splitter, BorderLayout.CENTER);
}
public String getCheckboxColumnName() {
return "";
}
public boolean isCheckable(final PluginDownloader downloader) {
return true;
}
public boolean isChecked(final PluginDownloader downloader) {
return !getSkippedPlugins().contains(downloader.getPluginId());
}
public void setChecked(final PluginDownloader downloader, final boolean checked) {
if (checked) {
getSkippedPlugins().remove(downloader.getPluginId());
} else {
getSkippedPlugins().add(downloader.getPluginId());
}
for (Listener listener : myListeners) {
listener.stateChanged();
}
}
protected Set<String> getSkippedPlugins() {
return UpdateChecker.getDisabledToUpdatePlugins();
}
public void addStateListener(Listener l) {
myListeners.add(l);
}
public interface Listener {
void stateChanged();
}
} | platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/DetectedPluginsPanel.java | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.updateSettings.impl;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.ide.plugins.PluginManagerMain;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.util.Comparing;
import com.intellij.ui.ColoredTableCellRenderer;
import com.intellij.ui.OrderPanel;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.UIUtil;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.util.*;
import java.util.List;
/**
* @author anna
* Date: 04-Dec-2007
*/
public class DetectedPluginsPanel extends OrderPanel<PluginDownloader> {
private final List<Listener> myListeners = ContainerUtil.createLockFreeCopyOnWriteList();
private static JEditorPane myDescriptionPanel = new JEditorPane();
public DetectedPluginsPanel() {
super(PluginDownloader.class);
final JTable entryTable = getEntryTable();
entryTable.setTableHeader(null);
entryTable.setDefaultRenderer(PluginDownloader.class, new ColoredTableCellRenderer() {
protected void customizeCellRenderer(final JTable table,
final Object value,
final boolean selected,
final boolean hasFocus,
final int row,
final int column) {
final PluginDownloader downloader = (PluginDownloader)value;
if (downloader != null) {
final String pluginName = downloader.getPluginName();
append(pluginName, SimpleTextAttributes.REGULAR_ATTRIBUTES);
final IdeaPluginDescriptor ideaPluginDescriptor = PluginManager.getPlugin(PluginId.getId(downloader.getPluginId()));
if (ideaPluginDescriptor != null) {
final String oldPluginName = ideaPluginDescriptor.getName();
if (!Comparing.strEqual(pluginName, oldPluginName)) {
append(" - " + oldPluginName, SimpleTextAttributes.REGULAR_ATTRIBUTES);
}
}
final String loadedVersion = downloader.getPluginVersion();
if (loadedVersion != null || (ideaPluginDescriptor != null && ideaPluginDescriptor.getVersion() != null)) {
final String installedVersion = ideaPluginDescriptor != null && ideaPluginDescriptor.getVersion() != null
? "v. " + ideaPluginDescriptor.getVersion() + (loadedVersion != null ? " -> " : "")
: "";
final String availableVersion = loadedVersion != null ? loadedVersion : "";
append(" (" + installedVersion + availableVersion + ")", SimpleTextAttributes.GRAY_ATTRIBUTES);
}
}
}
});
entryTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
final int selectedRow = entryTable.getSelectedRow();
if (selectedRow != -1) {
final PluginDownloader selection = getValueAt(selectedRow);
final IdeaPluginDescriptor descriptor = selection.getDescriptor();
if (descriptor != null) {
PluginManagerMain.pluginInfoUpdate(descriptor, null, myDescriptionPanel);
}
}
}
});
setCheckboxColumnName("");
myDescriptionPanel.setPreferredSize(new Dimension(400, -1));
myDescriptionPanel.setEditable(false);
myDescriptionPanel.setContentType(UIUtil.HTML_MIME);
myDescriptionPanel.addHyperlinkListener(new PluginManagerMain.MyHyperlinkListener());
removeAll();
final Splitter splitter = new Splitter(false);
splitter.setFirstComponent(ScrollPaneFactory.createScrollPane(entryTable));
splitter.setSecondComponent(ScrollPaneFactory.createScrollPane(myDescriptionPanel));
add(splitter, BorderLayout.CENTER);
}
public String getCheckboxColumnName() {
return "";
}
public boolean isCheckable(final PluginDownloader downloader) {
return true;
}
public boolean isChecked(final PluginDownloader downloader) {
return !getSkippedPlugins().contains(downloader.getPluginId());
}
public void setChecked(final PluginDownloader downloader, final boolean checked) {
if (checked) {
getSkippedPlugins().remove(downloader.getPluginId());
} else {
getSkippedPlugins().add(downloader.getPluginId());
}
for (Listener listener : myListeners) {
listener.stateChanged();
}
}
protected Set<String> getSkippedPlugins() {
return UpdateChecker.getDisabledToUpdatePlugins();
}
public void addStateListener(Listener l) {
myListeners.add(l);
}
public interface Listener {
void stateChanged();
}
} | plugin advertiser: no border over plugin name
| platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/DetectedPluginsPanel.java | plugin advertiser: no border over plugin name | <ide><path>latform/platform-impl/src/com/intellij/openapi/updateSettings/impl/DetectedPluginsPanel.java
<ide> final boolean hasFocus,
<ide> final int row,
<ide> final int column) {
<add> setBorder(null);
<ide> final PluginDownloader downloader = (PluginDownloader)value;
<ide> if (downloader != null) {
<ide> final String pluginName = downloader.getPluginName(); |
|
JavaScript | bsd-3-clause | ba9e633311bbcbf70d29f6e6538c0f4959e71df2 | 0 | yahoo/mojito-cli-build,isao/mojito-cli-build | /*jslint sloppy:true, stupid:true, node:true */
var Stream = require('stream');
function Scaper(mojito) {
this.mojito = mojito;
this.server = null;
}
function start(opts) {
this.server = this.mojito.createServer(opts);
return this;
}
function fetch(buildmap, cb) {
var me = this;
this.server.listen(null, null, function (err) {
var keys = Object.keys(buildmap),
have = 0,
failed = 0,
need = keys.length,
opts = {headers: {'x-mojito-build': 'html5app'}};
if (err) {
me.emit('error', err);
return cb('Failed to start server.');
}
keys.forEach(function (key) {
me.server.getWebPage(key, opts, function (err, uri, content) {
if (err) {
failed += 1;
me.emit('warn', 'FAILED to get ' + uri);
} else {
me.emit('scraped-one', buildmap[uri], content);
}
have += 1;
if (have === need) {
me.server.close();
me.emit('scraping-done', null, have, failed);
}
});
});
});
}
Scaper.prototype = Object.create(Stream.prototype, {
start: {value: start},
fetch: {value: fetch}
});
module.exports = Scaper;
| scraper.js | /*jslint sloppy:true, stupid:true, node:true */
var Stream = require('stream');
function Scaper(mojito) {
this.mojito = mojito;
this.server = null;
}
function start(opts) {
this.server = this.mojito.createServer(opts);
return this;
}
function fetch(buildmap, cb) {
var me = this;
this.server.listen(null, null, function (err) {
var keys = Object.keys(buildmap),
have = 0,
failed = 0,
need = keys.length,
opts = {headers: {'x-mojito-build': 'html5app'}};
if (err) {
me.emit('error', err);
return cb('Failed to start server.');
}
keys.forEach(function (key) {
me.server.getWebPage(key, opts, function (err, uri, content) {
if (err) {
failed += 1;
me.emit('warn', 'FAILED to get ' + uri);
} else {
me.emit('scraped-one', buildmap[uri], content);
}
have += 1;
if (have === need) {
me.server.close();
me.emit('scraping-done');
}
});
});
});
}
Scaper.prototype = Object.create(Stream.prototype, {
start: {value: start},
fetch: {value: fetch}
});
module.exports = Scaper;
| minor
| scraper.js | minor | <ide><path>craper.js
<ide> have += 1;
<ide> if (have === need) {
<ide> me.server.close();
<del> me.emit('scraping-done');
<add> me.emit('scraping-done', null, have, failed);
<ide> }
<ide> });
<ide> }); |
|
JavaScript | agpl-3.0 | a7476f802994ccbe7446f725727d09c45c09186c | 0 | cgwire/kitsu,cgwire/kitsu | import productionsApi from '../api/productions'
import { sortProductions, sortByName } from '../../lib/sorting'
import { updateModelFromList, removeModelFromList } from '../../lib/models'
import {
LOAD_PRODUCTIONS_START,
LOAD_PRODUCTIONS_ERROR,
LOAD_PRODUCTIONS_END,
LOAD_OPEN_PRODUCTIONS_START,
LOAD_OPEN_PRODUCTIONS_ERROR,
LOAD_OPEN_PRODUCTIONS_END,
LOAD_PRODUCTION_STATUS_START,
LOAD_PRODUCTION_STATUS_ERROR,
LOAD_PRODUCTION_STATUS_END,
EDIT_PRODUCTION_START,
EDIT_PRODUCTION_ERROR,
EDIT_PRODUCTION_END,
DELETE_PRODUCTION_START,
DELETE_PRODUCTION_ERROR,
DELETE_PRODUCTION_END,
ADD_PRODUCTION,
UPDATE_PRODUCTION,
REMOVE_PRODUCTION,
RESET_PRODUCTION_PATH,
SET_CURRENT_PRODUCTION,
PRODUCTION_PICTURE_FILE_SELECTED,
PRODUCTION_AVATAR_UPLOADED,
TEAM_ADD_PERSON,
TEAM_REMOVE_PERSON,
ASSIGN_TASKS,
ADD_METADATA_DESCRIPTOR_END,
UPDATE_METADATA_DESCRIPTOR_END,
DELETE_METADATA_DESCRIPTOR_END,
RESET_ALL
} from '../mutation-types'
const initialState = {
productions: [],
productionMap: {},
openProductions: [],
productionStatus: [],
productionStatusMap: {},
currentProduction: null,
productionAvatarFormData: null,
isProductionsLoading: false,
isProductionsLoadingError: false,
isOpenProductionsLoading: false,
editProduction: {
isLoading: false,
isError: false
},
deleteProduction: {
isLoading: false,
isError: false
},
assetsPath: { name: 'open-productions' },
assetTypesPath: { name: 'open-productions' },
shotsPath: { name: 'open-productions' },
sequencesPath: { name: 'open-productions' },
episodesPath: { name: 'open-productions' },
breakdownPath: { name: 'open-productions' },
playlistsPath: { name: 'open-productions' },
teamPath: { name: 'open-productions' }
}
let state = { ...initialState }
const helpers = {
getProductionComponentPath (routeName, productionId, episodeId) {
if (episodeId) {
return {
name: 'episode-' + routeName,
params: {
episode_id: episodeId,
production_id: productionId
}
}
} else if (productionId) {
return {
name: routeName,
params: {
production_id: productionId
}
}
} else {
return { name: 'open-productions' }
}
}
}
const getters = {
productions: state => state.productions,
productionMap: state => state.productionMap,
openProductions: state => state.openProductions,
productionStatus: state => state.productionStatus,
productionAvatarFormData: state => state.productionAvatarFormData,
isProductionsLoading: state => state.isProductionsLoading,
isProductionsLoadingError: state => state.isProductionsLoadingError,
isOpenProductionsLoading: state => state.isOpenProductionsLoading,
editProduction: state => state.editProduction,
deleteProduction: state => state.deleteProduction,
assetsPath: state => state.assetsPath,
assetTypesPath: state => state.assetTypesPath,
shotsPath: state => state.shotsPath,
sequencesPath: state => state.sequencesPath,
episodesPath: state => state.episodesPath,
breakdownPath: state => state.breakdownPath,
playlistsPath: state => state.playlistsPath,
teamPath: state => state.teamPath,
currentProduction: (state) => {
if (state.currentProduction) {
return state.currentProduction
} else if (state.openProductions.length > 0) {
return state.openProductions[0]
} else {
return null
}
},
isTVShow: (state) => {
const production = getters.currentProduction(state)
return production && production.production_type === 'tvshow'
},
assetMetadataDescriptors: (state) => {
if (!state.currentProduction || !state.currentProduction.descriptors) {
return []
} else {
return sortByName(
state.currentProduction.descriptors
.filter(d => d.entity_type === 'Asset')
)
}
},
shotMetadataDescriptors: (state) => {
if (!state.currentProduction || !state.currentProduction.descriptors) {
return []
} else {
return sortByName(
state.currentProduction.descriptors
.filter(d => d.entity_type === 'Shot')
)
}
},
productionStatusOptions: state => state.productionStatus.map(
(status) => { return { label: status.name, value: status.id } }
),
openProductionOptions: state => state.openProductions.map(
(production) => { return { label: production.name, value: production.id } }
),
getProduction: (state, getters) => (id) => {
return state.productions.find(
(production) => production.id === id
)
},
getProductionStatus: (state, getters) => (id) => {
return state.productionStatus.find(
(productionStatus) => productionStatus.id === id
)
}
}
const actions = {
loadProductionStatus ({ commit, state }, callback) {
commit(LOAD_PRODUCTION_STATUS_START)
productionsApi.getProductionStatus((err, productionStatus) => {
if (err) commit(LOAD_PRODUCTION_STATUS_ERROR)
else commit(LOAD_PRODUCTION_STATUS_END, productionStatus)
if (callback) callback(err)
})
},
loadOpenProductions ({ commit, state }, callback) {
commit(LOAD_OPEN_PRODUCTIONS_START)
productionsApi.getOpenProductions((err, productions) => {
if (err) commit(LOAD_OPEN_PRODUCTIONS_ERROR)
else {
commit(LOAD_OPEN_PRODUCTIONS_END, productions)
}
if (callback) callback(err)
})
},
loadProductions ({ commit, state }, callback) {
commit(LOAD_PRODUCTIONS_START)
productionsApi.getProductions((err, productions) => {
if (err) commit(LOAD_PRODUCTIONS_ERROR)
else commit(LOAD_PRODUCTIONS_END, productions)
if (callback) callback(err)
})
},
loadProduction ({ commit, state }, productionId) {
return productionsApi.getProduction(productionId)
.then((production) => {
if (state.productionMap[production.id]) {
commit(UPDATE_PRODUCTION, production)
} else {
commit(ADD_PRODUCTION, production)
}
})
.catch((err) => console.error(err))
},
newProduction ({ commit, state }, { data, callback }) {
commit(EDIT_PRODUCTION_START, data)
productionsApi.newProduction(data, (err, production) => {
if (err) {
commit(EDIT_PRODUCTION_ERROR)
} else {
commit(EDIT_PRODUCTION_END, production)
}
if (callback) callback(err, production)
})
},
editProduction ({ commit, state }, payload) {
commit(EDIT_PRODUCTION_START)
productionsApi.updateProduction(payload.data, (err, production) => {
if (err) {
commit(EDIT_PRODUCTION_ERROR)
} else {
commit(EDIT_PRODUCTION_END, production)
}
if (payload.callback) payload.callback(err)
})
},
deleteProduction ({ commit, state }, payload) {
commit(DELETE_PRODUCTION_START)
const production = payload.production
productionsApi.deleteProduction(production, (err) => {
if (err) {
commit(DELETE_PRODUCTION_ERROR)
} else {
commit(REMOVE_PRODUCTION, production)
commit(DELETE_PRODUCTION_END)
}
if (payload.callback) payload.callback(err)
})
},
setProduction ({ commit, rootGetters }, productionId) {
commit(SET_CURRENT_PRODUCTION, productionId)
if (rootGetters.isTVShow) {
const episode = rootGetters.currentEpisode
const episodeId = episode ? episode.id : null
if (productionId && episodeId) {
commit(RESET_PRODUCTION_PATH, { productionId, episodeId })
}
} else {
if (productionId) {
commit(RESET_PRODUCTION_PATH, { productionId })
}
}
},
storeProductionPicture ({ commit }, formData) {
commit(PRODUCTION_PICTURE_FILE_SELECTED, formData)
},
uploadProductionAvatar ({ commit, state }, productionId) {
return new Promise((resolve, reject) => {
productionsApi.postAvatar(
productionId,
state.productionAvatarFormData,
(err) => {
commit(PRODUCTION_AVATAR_UPLOADED, productionId)
if (err) reject(err)
else resolve()
}
)
})
},
addPersonToTeam ({ commit, state }, person) {
return new Promise((resolve, reject) => {
commit(TEAM_ADD_PERSON, person.id)
return productionsApi.addPersonToTeam(
state.currentProduction.id,
person.id
)
.then(resolve)
.catch(reject)
})
},
removePersonFromTeam ({ commit, state }, person) {
return new Promise((resolve, reject) => {
commit(TEAM_REMOVE_PERSON, person.id)
return productionsApi.removePersonFromTeam(
state.currentProduction.id,
person.id
)
.then(resolve)
.catch(reject)
})
},
addMetadataDescriptor ({ commit, state }, descriptor) {
return new Promise((resolve, reject) => {
if (descriptor.id) {
return productionsApi.updateMetadataDescriptor(
state.currentProduction.id,
descriptor
)
.then((descriptor) => {
commit(UPDATE_METADATA_DESCRIPTOR_END, {
production: state.currentProduction,
descriptor
})
resolve()
})
.catch(reject)
} else {
return productionsApi.addMetadataDescriptor(
state.currentProduction.id,
descriptor
)
.then((descriptor) => {
commit(ADD_METADATA_DESCRIPTOR_END, {
production: state.currentProduction,
descriptor
})
resolve()
})
.catch(reject)
}
})
},
deleteMetadataDescriptor ({ commit, state }, descriptorId) {
return new Promise((resolve, reject) => {
return productionsApi.deleteMetadataDescriptor(
state.currentProduction.id,
descriptorId
)
.then(() => {
commit(DELETE_METADATA_DESCRIPTOR_END, { id: descriptorId })
resolve()
})
.catch(reject)
})
},
refreshMetadataDescriptor ({ commit, state }, descriptorId) {
return new Promise((resolve, reject) => {
return productionsApi.getMetadataDescriptor(
state.currentProduction.id,
descriptorId
)
.then((descriptor) => {
const descriptorMap = {}
state.openProductions.forEach((production) => {
production.descriptors.forEach((desc) => {
descriptorMap[desc.id] = desc
})
})
if (!descriptorMap[descriptor.id]) {
commit(ADD_METADATA_DESCRIPTOR_END, {
production: state.productionMap[descriptor.project_id],
descriptor
})
} else {
commit(UPDATE_METADATA_DESCRIPTOR_END, {
production: state.productionMap[descriptor.project_id],
descriptor
})
}
resolve()
})
.catch(reject)
})
}
}
const mutations = {
[LOAD_PRODUCTIONS_START] (state) {
state.productions = []
state.isProductionsLoading = true
state.isProductionsLoadingError = false
},
[LOAD_PRODUCTIONS_ERROR] (state) {
state.productions = []
state.isProductionsLoading = false
state.isProductionsLoadingError = true
},
[LOAD_PRODUCTIONS_END] (state, productions) {
state.isProductionsLoading = false
state.isProductionsLoadingError = false
state.productions = sortProductions(productions)
const productionMap = {}
const addProductionToMap = (production) => {
if (!productionMap[production.id]) {
productionMap[production.id] = production
}
}
state.openProductions.forEach(addProductionToMap)
state.productions.forEach(addProductionToMap)
state.productionMap = productionMap
},
[LOAD_OPEN_PRODUCTIONS_START] (state) {
state.isOpenProductionsLoading = true
state.openProductions = []
},
[LOAD_OPEN_PRODUCTIONS_ERROR] (state) {
state.isOpenProductionsLoading = false
},
[LOAD_OPEN_PRODUCTIONS_END] (state, productions) {
state.isOpenProductionsLoading = false
state.openProductions = sortByName(productions)
const productionMap = {}
productions.forEach((production) => {
productionMap[production.id] = production
})
state.productionMap = productionMap
if (!state.currentProduction && state.openProductions.length > 0) {
state.currentProduction = state.openProductions[0]
}
},
[LOAD_PRODUCTION_STATUS_START] (state) {
state.productionStatus = []
},
[LOAD_PRODUCTION_STATUS_ERROR] (state) {
},
[LOAD_PRODUCTION_STATUS_END] (state, productionStatus) {
const productionStatusMap = {}
productionStatus.forEach((status) => {
productionStatusMap[status.id] = status
})
state.productionStatus = productionStatus
state.productionStatusMap = productionStatusMap
},
[EDIT_PRODUCTION_START] (state, data) {
state.editProduction.isLoading = true
state.editProduction.isError = false
},
[EDIT_PRODUCTION_ERROR] (state) {
state.editProduction.isLoading = false
state.editProduction.isError = true
},
[EDIT_PRODUCTION_END] (state, newProduction) {
const production = state.productionMap[newProduction.id]
const productionStatus = getters.getProductionStatus(state)(
newProduction.project_status_id
)
const openProduction = state.openProductions.find(
(openProduction) => openProduction.id === newProduction.id
)
newProduction.project_status_name = productionStatus.name
if (production) {
const openProductionIndex = state.openProductions.findIndex(
(openProduction) => openProduction.id === newProduction.id
)
if (newProduction.project_status_id) {
// Status changed from open to close
if (
openProductionIndex >= 0 &&
production.project_status_id !== newProduction.project_status_id
) {
state.openProductions.splice(openProductionIndex, 1)
// Status change from close to open
} else if (openProductionIndex < 0) {
state.openProductions.push(production)
state.openProductions = sortByName(state.openProductions)
}
}
if (
newProduction.production_type &&
newProduction.production_type !== production.production_type &&
newProduction.production_type === 'short'
) {
production.first_episode_id = undefined
openProduction.first_episode_id = undefined
}
Object.assign(production, newProduction)
if (openProduction) Object.assign(openProduction, newProduction)
} else {
state.productions.push(newProduction)
state.productionMap[newProduction.id] = newProduction
state.openProductions.push(newProduction)
state.productions = sortProductions(state.productions)
state.openProductions = sortByName(state.openProductions)
}
state.editProduction = {
isLoading: false,
isError: false
}
},
[ADD_PRODUCTION] (state, production) {
state.productions.push(production)
state.openProductions.push(production)
state.productions = sortProductions(state.productions)
state.openProductions = sortByName(state.openProductions)
state.productionMap[production.id] = production
},
[UPDATE_PRODUCTION] (state, production) {
const previousProduction = state.productionMap[production.id]
const productionStatus =
state.productionStatusMap[production.project_status_id]
const openProduction =
state.openProductions.find(p => p.id === production.id)
const isStatusChanged =
previousProduction.project_status_id !== productionStatus.id
production.project_status_name = productionStatus.name
Object.assign(previousProduction, production)
if (openProduction) Object.assign(openProduction, production)
if (isStatusChanged) {
if (production.project_status_name === 'Open') {
state.openProductions.push(previousProduction)
} else {
state.openProductions = removeModelFromList(
state.openProductions,
previousProduction
)
}
}
state.productions = sortProductions(state.productions)
state.openProductions = sortByName(state.openProductions)
},
[DELETE_PRODUCTION_START] (state) {
state.deleteProduction = {
isLoading: true,
isError: false
}
},
[DELETE_PRODUCTION_ERROR] (state) {
state.deleteProduction = {
isLoading: false,
isError: true
}
},
[REMOVE_PRODUCTION] (state, productionToDelete) {
state.productions =
removeModelFromList(state.productions, productionToDelete)
state.openProductions =
removeModelFromList(state.openProductions, productionToDelete)
delete state.productionMap[productionToDelete.id]
},
[DELETE_PRODUCTION_END] (state, productionToDelete) {
state.deleteProduction = {
isLoading: false,
isError: false
}
},
[PRODUCTION_PICTURE_FILE_SELECTED] (state, formData) {
state.productionAvatarFormData = formData
},
[PRODUCTION_AVATAR_UPLOADED] (state, productionId) {
const production = state.productionMap[productionId]
if (production) production.has_avatar = true
},
[SET_CURRENT_PRODUCTION] (state, productionId) {
const production = state.productionMap[productionId]
state.currentProduction = production
},
[RESET_PRODUCTION_PATH] (state, { productionId, episodeId }) {
state.assetsPath = helpers.getProductionComponentPath(
'assets', productionId, episodeId)
state.assetTypesPath = helpers.getProductionComponentPath(
'production-asset-types', productionId, episodeId)
state.shotsPath = helpers.getProductionComponentPath(
'shots', productionId, episodeId)
state.sequencesPath = helpers.getProductionComponentPath(
'sequences', productionId, episodeId)
state.episodesPath = helpers.getProductionComponentPath(
'episodes', productionId)
state.breakdownPath = helpers.getProductionComponentPath(
'breakdown', productionId, episodeId)
state.playlistsPath = helpers.getProductionComponentPath(
'playlists', productionId, episodeId)
state.teamPath = helpers.getProductionComponentPath(
'team', productionId)
},
[TEAM_ADD_PERSON] (state, personId) {
if (!state.currentProduction.team.find((pId) => pId === personId)) {
state.currentProduction.team.push(personId)
}
},
[TEAM_REMOVE_PERSON] (state, personId) {
const personIndex = state.currentProduction.team.findIndex(
(pId) => pId === personId
)
if (personIndex !== null) {
state.currentProduction.team.splice(personIndex, 1)
}
},
[ADD_METADATA_DESCRIPTOR_END] (state, { production, descriptor }) {
if (production) {
if (production.descriptors) {
production.descriptors.push(descriptor)
} else {
production.descriptors = [descriptor]
}
}
},
[UPDATE_METADATA_DESCRIPTOR_END] (state, { production, descriptor }) {
if (production) {
if (production.descriptors) {
updateModelFromList(production.descriptors, descriptor)
} else {
production.descriptors = []
}
}
},
[DELETE_METADATA_DESCRIPTOR_END] (state, descriptor) {
const production = state.openProductions.find((production) => {
return production.descriptors.find((d) => d.id === descriptor.id)
})
if (production) {
production.descriptors =
removeModelFromList(production.descriptors, descriptor)
}
},
[ASSIGN_TASKS] (state, { personId }) {
const isTeamMember =
state.currentProduction &&
state.currentProduction.team.some(
pId => pId === personId
)
if (!isTeamMember && state.currentProduction) {
state.currentProduction.team.push(personId)
}
},
[RESET_ALL] (state) {
Object.assign(state, { ...initialState })
}
}
export default {
state,
getters,
actions,
mutations
}
| src/store/modules/productions.js | import productionsApi from '../api/productions'
import { sortProductions, sortByName } from '../../lib/sorting'
import { updateModelFromList, removeModelFromList } from '../../lib/models'
import {
LOAD_PRODUCTIONS_START,
LOAD_PRODUCTIONS_ERROR,
LOAD_PRODUCTIONS_END,
LOAD_OPEN_PRODUCTIONS_START,
LOAD_OPEN_PRODUCTIONS_ERROR,
LOAD_OPEN_PRODUCTIONS_END,
LOAD_PRODUCTION_STATUS_START,
LOAD_PRODUCTION_STATUS_ERROR,
LOAD_PRODUCTION_STATUS_END,
EDIT_PRODUCTION_START,
EDIT_PRODUCTION_ERROR,
EDIT_PRODUCTION_END,
DELETE_PRODUCTION_START,
DELETE_PRODUCTION_ERROR,
DELETE_PRODUCTION_END,
ADD_PRODUCTION,
UPDATE_PRODUCTION,
REMOVE_PRODUCTION,
RESET_PRODUCTION_PATH,
SET_CURRENT_PRODUCTION,
PRODUCTION_PICTURE_FILE_SELECTED,
PRODUCTION_AVATAR_UPLOADED,
TEAM_ADD_PERSON,
TEAM_REMOVE_PERSON,
ASSIGN_TASKS,
ADD_METADATA_DESCRIPTOR_END,
UPDATE_METADATA_DESCRIPTOR_END,
DELETE_METADATA_DESCRIPTOR_END,
RESET_ALL
} from '../mutation-types'
const initialState = {
productions: [],
productionMap: {},
openProductions: [],
productionStatus: [],
productionStatusMap: {},
currentProduction: null,
productionAvatarFormData: null,
isProductionsLoading: false,
isProductionsLoadingError: false,
isOpenProductionsLoading: false,
editProduction: {
isLoading: false,
isError: false
},
deleteProduction: {
isLoading: false,
isError: false
},
assetsPath: { name: 'open-productions' },
assetTypesPath: { name: 'open-productions' },
shotsPath: { name: 'open-productions' },
sequencesPath: { name: 'open-productions' },
episodesPath: { name: 'open-productions' },
breakdownPath: { name: 'open-productions' },
playlistsPath: { name: 'open-productions' },
teamPath: { name: 'open-productions' }
}
let state = { ...initialState }
const helpers = {
getProductionComponentPath (routeName, productionId, episodeId) {
if (episodeId) {
return {
name: 'episode-' + routeName,
params: {
episode_id: episodeId,
production_id: productionId
}
}
} else if (productionId) {
return {
name: routeName,
params: {
production_id: productionId
}
}
} else {
return { name: 'open-productions' }
}
}
}
const getters = {
productions: state => state.productions,
productionMap: state => state.productionMap,
openProductions: state => state.openProductions,
productionStatus: state => state.productionStatus,
productionAvatarFormData: state => state.productionAvatarFormData,
isProductionsLoading: state => state.isProductionsLoading,
isProductionsLoadingError: state => state.isProductionsLoadingError,
isOpenProductionsLoading: state => state.isOpenProductionsLoading,
editProduction: state => state.editProduction,
deleteProduction: state => state.deleteProduction,
assetsPath: state => state.assetsPath,
assetTypesPath: state => state.assetTypesPath,
shotsPath: state => state.shotsPath,
sequencesPath: state => state.sequencesPath,
episodesPath: state => state.episodesPath,
breakdownPath: state => state.breakdownPath,
playlistsPath: state => state.playlistsPath,
teamPath: state => state.teamPath,
currentProduction: (state) => {
if (state.currentProduction) {
return state.currentProduction
} else if (state.openProductions.length > 0) {
return state.openProductions[0]
} else {
return null
}
},
isTVShow: (state) => {
const production = getters.currentProduction(state)
return production && production.production_type === 'tvshow'
},
assetMetadataDescriptors: (state) => {
if (!state.currentProduction || !state.currentProduction.descriptors) {
return []
} else {
return sortByName(
state.currentProduction.descriptors
.filter(d => d.entity_type === 'Asset')
)
}
},
shotMetadataDescriptors: (state) => {
if (!state.currentProduction || !state.currentProduction.descriptors) {
return []
} else {
return sortByName(
state.currentProduction.descriptors
.filter(d => d.entity_type === 'Shot')
)
}
},
productionStatusOptions: state => state.productionStatus.map(
(status) => { return { label: status.name, value: status.id } }
),
openProductionOptions: state => state.openProductions.map(
(production) => { return { label: production.name, value: production.id } }
),
getProduction: (state, getters) => (id) => {
return state.productions.find(
(production) => production.id === id
)
},
getProductionStatus: (state, getters) => (id) => {
return state.productionStatus.find(
(productionStatus) => productionStatus.id === id
)
}
}
const actions = {
loadProductionStatus ({ commit, state }, callback) {
commit(LOAD_PRODUCTION_STATUS_START)
productionsApi.getProductionStatus((err, productionStatus) => {
if (err) commit(LOAD_PRODUCTION_STATUS_ERROR)
else commit(LOAD_PRODUCTION_STATUS_END, productionStatus)
if (callback) callback(err)
})
},
loadOpenProductions ({ commit, state }, callback) {
commit(LOAD_OPEN_PRODUCTIONS_START)
productionsApi.getOpenProductions((err, productions) => {
if (err) commit(LOAD_OPEN_PRODUCTIONS_ERROR)
else {
commit(LOAD_OPEN_PRODUCTIONS_END, productions)
}
if (callback) callback(err)
})
},
loadProductions ({ commit, state }, callback) {
commit(LOAD_PRODUCTIONS_START)
productionsApi.getProductions((err, productions) => {
if (err) commit(LOAD_PRODUCTIONS_ERROR)
else commit(LOAD_PRODUCTIONS_END, productions)
if (callback) callback(err)
})
},
loadProduction ({ commit, state }, productionId) {
return productionsApi.getProduction(productionId)
.then((production) => {
if (state.productionMap[production.id]) {
commit(UPDATE_PRODUCTION, production)
} else {
commit(ADD_PRODUCTION, production)
}
})
.catch((err) => console.error(err))
},
newProduction ({ commit, state }, { data, callback }) {
commit(EDIT_PRODUCTION_START, data)
productionsApi.newProduction(data, (err, production) => {
if (err) {
commit(EDIT_PRODUCTION_ERROR)
} else {
commit(EDIT_PRODUCTION_END, production)
}
if (callback) callback(err, production)
})
},
editProduction ({ commit, state }, payload) {
commit(EDIT_PRODUCTION_START)
productionsApi.updateProduction(payload.data, (err, production) => {
if (err) {
commit(EDIT_PRODUCTION_ERROR)
} else {
commit(EDIT_PRODUCTION_END, production)
}
if (payload.callback) payload.callback(err)
})
},
deleteProduction ({ commit, state }, payload) {
commit(DELETE_PRODUCTION_START)
const production = payload.production
productionsApi.deleteProduction(production, (err) => {
if (err) {
commit(DELETE_PRODUCTION_ERROR)
} else {
commit(REMOVE_PRODUCTION, production)
commit(DELETE_PRODUCTION_END)
}
if (payload.callback) payload.callback(err)
})
},
setProduction ({ commit, rootGetters }, productionId) {
commit(SET_CURRENT_PRODUCTION, productionId)
if (rootGetters.isTVShow) {
const episode = rootGetters.currentEpisode
const episodeId = episode ? episode.id : null
if (productionId && episodeId) {
commit(RESET_PRODUCTION_PATH, { productionId, episodeId })
}
} else {
if (productionId) {
commit(RESET_PRODUCTION_PATH, { productionId })
}
}
},
storeProductionPicture ({ commit }, formData) {
commit(PRODUCTION_PICTURE_FILE_SELECTED, formData)
},
uploadProductionAvatar ({ commit, state }, productionId) {
return new Promise((resolve, reject) => {
productionsApi.postAvatar(
productionId,
state.productionAvatarFormData,
(err) => {
commit(PRODUCTION_AVATAR_UPLOADED, productionId)
if (err) reject(err)
else resolve()
}
)
})
},
addPersonToTeam ({ commit, state }, person) {
return new Promise((resolve, reject) => {
commit(TEAM_ADD_PERSON, person.id)
return productionsApi.addPersonToTeam(
state.currentProduction.id,
person.id
)
.then(resolve)
.catch(reject)
})
},
removePersonFromTeam ({ commit, state }, person) {
return new Promise((resolve, reject) => {
commit(TEAM_REMOVE_PERSON, person.id)
return productionsApi.removePersonFromTeam(
state.currentProduction.id,
person.id
)
.then(resolve)
.catch(reject)
})
},
addMetadataDescriptor ({ commit, state }, descriptor) {
return new Promise((resolve, reject) => {
if (descriptor.id) {
return productionsApi.updateMetadataDescriptor(
state.currentProduction.id,
descriptor
)
.then((descriptor) => {
commit(UPDATE_METADATA_DESCRIPTOR_END, {
production: state.currentProduction,
descriptor
})
resolve()
})
.catch(reject)
} else {
return productionsApi.addMetadataDescriptor(
state.currentProduction.id,
descriptor
)
.then((descriptor) => {
commit(ADD_METADATA_DESCRIPTOR_END, {
production: state.currentProduction,
descriptor
})
resolve()
})
.catch(reject)
}
})
},
deleteMetadataDescriptor ({ commit, state }, descriptorId) {
return new Promise((resolve, reject) => {
return productionsApi.deleteMetadataDescriptor(
state.currentProduction.id,
descriptorId
)
.then(() => {
commit(DELETE_METADATA_DESCRIPTOR_END, { id: descriptorId })
resolve()
})
.catch(reject)
})
},
refreshMetadataDescriptor ({ commit, state }, descriptorId) {
return new Promise((resolve, reject) => {
return productionsApi.getMetadataDescriptor(
state.currentProduction.id,
descriptorId
)
.then((descriptor) => {
const descriptorMap = {}
state.openProductions.forEach((production) => {
production.descriptors.forEach((desc) => {
descriptorMap[desc.id] = desc
})
})
if (!descriptorMap[descriptor.id]) {
commit(ADD_METADATA_DESCRIPTOR_END, {
production: state.productionMap[descriptor.project_id],
descriptor
})
} else {
commit(UPDATE_METADATA_DESCRIPTOR_END, {
production: state.productionMap[descriptor.project_id],
descriptor
})
}
resolve()
})
.catch(reject)
})
}
}
const mutations = {
[LOAD_PRODUCTIONS_START] (state) {
state.productions = []
state.isProductionsLoading = true
state.isProductionsLoadingError = false
},
[LOAD_PRODUCTIONS_ERROR] (state) {
state.productions = []
state.isProductionsLoading = false
state.isProductionsLoadingError = true
},
[LOAD_PRODUCTIONS_END] (state, productions) {
state.isProductionsLoading = false
state.isProductionsLoadingError = false
state.productions = sortProductions(productions)
const productionMap = {}
const addProductionToMap = (production) => {
if (!productionMap[production.id]) {
productionMap[production.id] = production
}
}
state.openProductions.forEach(addProductionToMap)
state.productions.forEach(addProductionToMap)
state.productionMap = productionMap
},
[LOAD_OPEN_PRODUCTIONS_START] (state) {
state.isOpenProductionsLoading = true
state.openProductions = []
},
[LOAD_OPEN_PRODUCTIONS_ERROR] (state) {
state.isOpenProductionsLoading = false
},
[LOAD_OPEN_PRODUCTIONS_END] (state, productions) {
state.isOpenProductionsLoading = false
state.openProductions = sortByName(productions)
const productionMap = {}
productions.forEach((production) => {
productionMap[production.id] = production
})
state.productionMap = productionMap
if (!state.currentProduction && state.openProductions.length > 0) {
state.currentProduction = state.openProductions[0]
}
},
[LOAD_PRODUCTION_STATUS_START] (state) {
state.productionStatus = []
},
[LOAD_PRODUCTION_STATUS_ERROR] (state) {
},
[LOAD_PRODUCTION_STATUS_END] (state, productionStatus) {
const productionStatusMap = {}
productionStatus.forEach((status) => {
productionStatusMap[status.id] = status
})
state.productionStatus = productionStatus
state.productionStatusMap = productionStatusMap
},
[EDIT_PRODUCTION_START] (state, data) {
state.editProduction.isLoading = true
state.editProduction.isError = false
},
[EDIT_PRODUCTION_ERROR] (state) {
state.editProduction.isLoading = false
state.editProduction.isError = true
},
[EDIT_PRODUCTION_END] (state, newProduction) {
const production = state.productionMap[newProduction.id]
const productionStatus = getters.getProductionStatus(state)(
newProduction.project_status_id
)
const openProduction = state.openProductions.find(
(openProduction) => openProduction.id === newProduction.id
)
newProduction.project_status_name = productionStatus.name
if (production) {
const openProductionIndex = state.openProductions.findIndex(
(openProduction) => openProduction.id === newProduction.id
)
if (newProduction.project_status_id) {
// Status changed from open to close
if (
openProductionIndex >= 0 &&
production.project_status_id !== newProduction.project_status_id
) {
state.openProductions.splice(openProductionIndex, 1)
// Status change from close to open
} else if (openProductionIndex < 0) {
state.openProductions.push(production)
state.openProductions = sortByName(state.openProductions)
}
}
if (
newProduction.production_type &&
newProduction.production_type !== production.production_type &&
newProduction.production_type === 'short'
) {
production.first_episode_id = undefined
openProduction.first_episode_id = undefined
}
Object.assign(production, newProduction)
if (openProduction) Object.assign(openProduction, newProduction)
} else {
state.productions.push(newProduction)
state.productionMap[newProduction.id] = newProduction
state.openProductions.push(newProduction)
state.productions = sortProductions(state.productions)
state.openProductions = sortByName(state.openProductions)
}
state.editProduction = {
isLoading: false,
isError: false
}
},
[ADD_PRODUCTION] (state, production) {
state.productions.push(production)
state.openProductions.push(production)
state.productions = sortProductions(state.productions)
state.openProductions = sortByName(state.openProductions)
state.productionMap[production.id] = production
},
[UPDATE_PRODUCTION] (state, production) {
const previousProduction = state.productionMap[production.id]
const productionStatus =
state.productionStatusMap[production.project_status_id]
const openProduction =
state.openProductions.find(p => p.id === production.id)
const isStatusChanged =
previousProduction.project_status_id !== productionStatus.id
production.project_status_name = productionStatus.name
Object.assign(previousProduction, production)
if (openProduction) Object.assign(openProduction, production)
if (isStatusChanged) {
if (production.project_status_name === 'Open') {
state.openProductions.push(previousProduction)
} else {
state.openProductions = removeModelFromList(
state.openProductions,
previousProduction
)
}
}
state.productions = sortProductions(state.productions)
state.openProductions = sortByName(state.openProductions)
},
[DELETE_PRODUCTION_START] (state) {
state.deleteProduction = {
isLoading: true,
isError: false
}
},
[DELETE_PRODUCTION_ERROR] (state) {
state.deleteProduction = {
isLoading: false,
isError: true
}
},
[REMOVE_PRODUCTION] (state, productionToDelete) {
state.productions =
removeModelFromList(state.productions, productionToDelete)
state.openProductions =
removeModelFromList(state.openProductions, productionToDelete)
delete state.productionMap[productionToDelete.id]
},
[DELETE_PRODUCTION_END] (state, productionToDelete) {
state.deleteProduction = {
isLoading: false,
isError: false
}
},
[PRODUCTION_PICTURE_FILE_SELECTED] (state, formData) {
state.productionAvatarFormData = formData
},
[PRODUCTION_AVATAR_UPLOADED] (state, productionId) {
const production = state.productionMap[productionId]
if (production) production.has_avatar = true
},
[SET_CURRENT_PRODUCTION] (state, productionId) {
const production = state.productionMap[productionId]
state.currentProduction = production
},
[RESET_PRODUCTION_PATH] (state, { productionId, episodeId }) {
state.assetsPath = helpers.getProductionComponentPath(
'assets', productionId, episodeId)
state.assetTypesPath = helpers.getProductionComponentPath(
'production-asset-types', productionId, episodeId)
state.shotsPath = helpers.getProductionComponentPath(
'shots', productionId, episodeId)
state.sequencesPath = helpers.getProductionComponentPath(
'sequences', productionId, episodeId)
state.episodesPath = helpers.getProductionComponentPath(
'episodes', productionId)
state.breakdownPath = helpers.getProductionComponentPath(
'breakdown', productionId, episodeId)
state.playlistsPath = helpers.getProductionComponentPath(
'playlists', productionId, episodeId)
state.teamPath = helpers.getProductionComponentPath(
'team', productionId)
},
[TEAM_ADD_PERSON] (state, personId) {
if (!state.currentProduction.team.find((pId) => pId === personId)) {
state.currentProduction.team.push(personId)
}
},
[TEAM_REMOVE_PERSON] (state, personId) {
const personIndex = state.currentProduction.team.findIndex(
(pId) => pId === personId
)
if (personIndex !== null) {
state.currentProduction.team.splice(personIndex, 1)
}
},
[ADD_METADATA_DESCRIPTOR_END] (state, { production, descriptor }) {
if (production) {
if (production.descriptors) {
production.descriptors.push(descriptor)
} else {
production.descriptors = [descriptor]
}
}
},
[UPDATE_METADATA_DESCRIPTOR_END] (state, { production, descriptor }) {
if (production) {
if (production.descriptors) {
updateModelFromList(production.descriptors, descriptor)
} else {
production.descriptors = []
}
}
},
[DELETE_METADATA_DESCRIPTOR_END] (state, descriptor) {
const production = state.openProductions.find((production) => {
return production.descriptors.find((d) => d.id === descriptor.id)
})
if (production) {
production.descriptors =
removeModelFromList(production.descriptors, descriptor)
}
},
[ASSIGN_TASKS] (state, { personId }) {
const isTeamMember =
state.currentProduction &&
state.currentProduction.team.some(
pId => pId === personId
)
if (!isTeamMember) {
state.currentProduction.team.push(personId)
}
},
[RESET_ALL] (state) {
Object.assign(state, { ...initialState })
}
}
export default {
state,
getters,
actions,
mutations
}
| Fix todo list reload on assignation
| src/store/modules/productions.js | Fix todo list reload on assignation | <ide><path>rc/store/modules/productions.js
<ide> state.currentProduction.team.some(
<ide> pId => pId === personId
<ide> )
<del> if (!isTeamMember) {
<add> if (!isTeamMember && state.currentProduction) {
<ide> state.currentProduction.team.push(personId)
<ide> }
<ide> }, |
|
Java | bsd-3-clause | deefd576fcb224354a2defc93e2a17f1aaab094e | 0 | NighatYasmin/RESOLVE,yushan87/RESOLVE,ClemsonRSRG/RESOLVE,yushan87/RESOLVE,ClemsonRSRG/RESOLVE,yushan87/RESOLVE,NighatYasmin/RESOLVE,ClemsonRSRG/RESOLVE,mikekab/RESOLVE,NighatYasmin/RESOLVE,mikekab/RESOLVE | /**
* VCGenerator.java
* ---------------------------------
* Copyright (c) 2014
* RESOLVE Software Research Group
* School of Computing
* Clemson University
* All rights reserved.
* ---------------------------------
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
package edu.clemson.cs.r2jt.vcgeneration;
/*
* Libraries
*/
import edu.clemson.cs.r2jt.absyn.*;
import edu.clemson.cs.r2jt.data.*;
import edu.clemson.cs.r2jt.init.CompileEnvironment;
import edu.clemson.cs.r2jt.proving2.VC;
import edu.clemson.cs.r2jt.treewalk.TreeWalkerVisitor;
import edu.clemson.cs.r2jt.typeandpopulate.*;
import edu.clemson.cs.r2jt.typeandpopulate.entry.*;
import edu.clemson.cs.r2jt.typeandpopulate.MathSymbolTable.FacilityStrategy;
import edu.clemson.cs.r2jt.typeandpopulate.MathSymbolTable.ImportStrategy;
import edu.clemson.cs.r2jt.typeandpopulate.programtypes.PTType;
import edu.clemson.cs.r2jt.typeandpopulate.query.NameQuery;
import edu.clemson.cs.r2jt.typeandpopulate.query.OperationQuery;
import edu.clemson.cs.r2jt.typeandpopulate.query.UnqualifiedNameQuery;
import edu.clemson.cs.r2jt.typereasoning.TypeGraph;
import edu.clemson.cs.r2jt.utilities.Flag;
import edu.clemson.cs.r2jt.utilities.FlagDependencies;
import edu.clemson.cs.r2jt.utilities.SourceErrorException;
import java.io.File;
import java.util.*;
import java.util.List;
import java.util.Stack;
/**
* TODO: Write a description of this module
*/
public class VCGenerator extends TreeWalkerVisitor {
// ===========================================================
// Global Variables
// ===========================================================
// Symbol table related items
private final MathSymbolTableBuilder mySymbolTable;
private final TypeGraph myTypeGraph;
private final MTType BOOLEAN;
private final MTType MTYPE;
private final MTType Z;
private ModuleScope myCurrentModuleScope;
// Module level global variables
private Exp myGlobalRequiresExp;
private Exp myGlobalConstraintExp;
// Operation/Procedure level global variables
private OperationEntry myCurrentOperationEntry;
private Exp myOperationDecreasingExp;
/**
* <p>The current assertion we are applying
* VC rules to.</p>
*/
private AssertiveCode myCurrentAssertiveCode;
/**
* <p>The current compile environment used throughout
* the compiler.</p>
*/
private CompileEnvironment myInstanceEnvironment;
/**
* <p>A list that will be built up with <code>AssertiveCode</code>
* objects, each representing a VC or group of VCs that must be
* satisfied to verify a parsed program.</p>
*/
private Collection<AssertiveCode> myFinalAssertiveCode;
/**
* <p>This object creates the different VC outputs.</p>
*/
private OutputVCs myOutputGenerator;
/**
* <p>This string buffer holds all the steps
* the VC generator takes to generate VCs.</p>
*/
private StringBuffer myVCBuffer;
// ===========================================================
// Flag Strings
// ===========================================================
private static final String FLAG_ALTSECTION_NAME = "GenerateVCs";
private static final String FLAG_DESC_ATLVERIFY_VC = "Generate VCs.";
private static final String FLAG_DESC_ATTLISTVCS_VC = "";
// ===========================================================
// Flags
// ===========================================================
public static final Flag FLAG_ALTVERIFY_VC =
new Flag(FLAG_ALTSECTION_NAME, "altVCs", FLAG_DESC_ATLVERIFY_VC);
public static final Flag FLAG_ALTLISTVCS_VC =
new Flag(FLAG_ALTSECTION_NAME, "altListVCs",
FLAG_DESC_ATTLISTVCS_VC, Flag.Type.HIDDEN);
public static final void setUpFlags() {
FlagDependencies.addImplies(FLAG_ALTVERIFY_VC, FLAG_ALTLISTVCS_VC);
}
// ===========================================================
// Constructors
// ===========================================================
public VCGenerator(ScopeRepository table, final CompileEnvironment env) {
// Symbol table items
mySymbolTable = (MathSymbolTableBuilder) table;
myTypeGraph = mySymbolTable.getTypeGraph();
BOOLEAN = myTypeGraph.BOOLEAN;
MTYPE = myTypeGraph.MTYPE;
Z = myTypeGraph.Z;
// Current items
myCurrentModuleScope = null;
myCurrentOperationEntry = null;
myGlobalConstraintExp = null;
myGlobalRequiresExp = null;
myOperationDecreasingExp = null;
// Instance Environment
myInstanceEnvironment = env;
// VCs + Debugging String
myCurrentAssertiveCode = null;
myFinalAssertiveCode = new LinkedList<AssertiveCode>();
myOutputGenerator = null;
myVCBuffer = new StringBuffer();
}
// ===========================================================
// Visitor Methods
// ===========================================================
// -----------------------------------------------------------
// ConceptBodyModuleDec
// -----------------------------------------------------------
@Override
public void preConceptBodyModuleDec(ConceptBodyModuleDec dec) {
// Verbose Mode Debug Messages
myVCBuffer.append("\n=========================");
myVCBuffer.append(" VC Generation Details ");
myVCBuffer.append(" =========================\n");
myVCBuffer.append("\n Concept Realization Name:\t");
myVCBuffer.append(dec.getName().getName());
myVCBuffer.append("\n Concept Name:\t");
myVCBuffer.append(dec.getConceptName().getName());
myVCBuffer.append("\n");
myVCBuffer.append("\n====================================");
myVCBuffer.append("======================================\n");
myVCBuffer.append("\n");
// Set the current module scope
try {
myCurrentModuleScope =
mySymbolTable.getModuleScope(new ModuleIdentifier(dec));
// From the list of imports, obtain the global constraints
// of the imported modules.
myGlobalConstraintExp =
getConstraints(dec.getLocation(), myCurrentModuleScope
.getImports());
// Store the global requires clause
myGlobalRequiresExp = getRequiresClause(dec);
}
catch (NoSuchSymbolException e) {
System.err.println("Module " + dec.getName()
+ " does not exist or is not in scope.");
noSuchModule(dec.getLocation());
}
}
@Override
public void postConceptBodyModuleDec(ConceptBodyModuleDec dec) {
// Set the module level global variables to null
myCurrentModuleScope = null;
myGlobalConstraintExp = null;
myGlobalRequiresExp = null;
}
// -----------------------------------------------------------
// EnhancementBodyModuleDec
// -----------------------------------------------------------
@Override
public void preEnhancementBodyModuleDec(EnhancementBodyModuleDec dec) {
// Verbose Mode Debug Messages
myVCBuffer.append("\n=========================");
myVCBuffer.append(" VC Generation Details ");
myVCBuffer.append(" =========================\n");
myVCBuffer.append("\n Enhancement Realization Name:\t");
myVCBuffer.append(dec.getName().getName());
myVCBuffer.append("\n Enhancement Name:\t");
myVCBuffer.append(dec.getEnhancementName().getName());
myVCBuffer.append("\n Concept Name:\t");
myVCBuffer.append(dec.getConceptName().getName());
myVCBuffer.append("\n");
myVCBuffer.append("\n====================================");
myVCBuffer.append("======================================\n");
myVCBuffer.append("\n");
// Set the current module scope
try {
myCurrentModuleScope =
mySymbolTable.getModuleScope(new ModuleIdentifier(dec));
// From the list of imports, obtain the global constraints
// of the imported modules.
myGlobalConstraintExp =
getConstraints(dec.getLocation(), myCurrentModuleScope
.getImports());
// Store the global requires clause
myGlobalRequiresExp = getRequiresClause(dec);
}
catch (NoSuchSymbolException e) {
System.err.println("Module " + dec.getName()
+ " does not exist or is not in scope.");
noSuchModule(dec.getLocation());
}
}
@Override
public void postEnhancementBodyModuleDec(EnhancementBodyModuleDec dec) {
// Set the module level global variables to null
myCurrentModuleScope = null;
myGlobalConstraintExp = null;
myGlobalRequiresExp = null;
}
// -----------------------------------------------------------
// FacilityModuleDec
// -----------------------------------------------------------
@Override
public void preFacilityModuleDec(FacilityModuleDec dec) {
// Verbose Mode Debug Messages
myVCBuffer.append("\n=========================");
myVCBuffer.append(" VC Generation Details ");
myVCBuffer.append(" =========================\n");
myVCBuffer.append("\n Facility Name:\t");
myVCBuffer.append(dec.getName().getName());
myVCBuffer.append("\n");
myVCBuffer.append("\n====================================");
myVCBuffer.append("======================================\n");
myVCBuffer.append("\n");
// Set the current module scope
try {
myCurrentModuleScope =
mySymbolTable.getModuleScope(new ModuleIdentifier(dec));
// From the list of imports, obtain the global constraints
// of the imported modules.
myGlobalConstraintExp =
getConstraints(dec.getLocation(), myCurrentModuleScope
.getImports());
// Store the global requires clause
myGlobalRequiresExp = getRequiresClause(dec);
}
catch (NoSuchSymbolException e) {
System.err.println("Module " + dec.getName()
+ " does not exist or is not in scope.");
noSuchModule(dec.getLocation());
}
}
@Override
public void postFacilityModuleDec(FacilityModuleDec dec) {
// Set the module level global variables to null
myCurrentModuleScope = null;
myGlobalConstraintExp = null;
myGlobalRequiresExp = null;
}
// -----------------------------------------------------------
// FacilityOperationDec
// -----------------------------------------------------------
@Override
public void preFacilityOperationDec(FacilityOperationDec dec) {
// Keep the current operation dec
List<PTType> argTypes = new LinkedList<PTType>();
for (ParameterVarDec p : dec.getParameters()) {
argTypes.add(p.getTy().getProgramTypeValue());
}
myCurrentOperationEntry =
searchOperation(dec.getLocation(), null, dec.getName(),
argTypes);
}
@Override
public void postFacilityOperationDec(FacilityOperationDec dec) {
// Create assertive code
myCurrentAssertiveCode = new AssertiveCode(myInstanceEnvironment);
// Verbose Mode Debug Messages
myVCBuffer.append("\n=========================");
myVCBuffer.append(" Procedure: ");
myVCBuffer.append(dec.getName().getName());
myVCBuffer.append(" =========================\n");
// Obtains items from the current operation
Location loc = dec.getLocation();
String name = dec.getName().getName();
Exp requires = modifyRequiresClause(getRequiresClause(dec), loc, name);
Exp ensures = modifyEnsuresClause(getEnsuresClause(dec), loc, name);
List<Statement> statementList = dec.getStatements();
List<VarDec> variableList = dec.getAllVariables();
Exp decreasing = dec.getDecreasing();
// Apply the procedure declaration rule
applyProcedureDeclRule(requires, ensures, decreasing, variableList,
statementList);
// Apply proof rules
applyEBRules();
myOperationDecreasingExp = null;
myCurrentOperationEntry = null;
myFinalAssertiveCode.add(myCurrentAssertiveCode);
myCurrentAssertiveCode = null;
}
// -----------------------------------------------------------
// ModuleDec
// -----------------------------------------------------------
@Override
public void postModuleDec(ModuleDec dec) {
// Create the output generator and finalize output
myOutputGenerator =
new OutputVCs(myInstanceEnvironment, myFinalAssertiveCode,
myVCBuffer);
// Print to file if we are in debug mode
// TODO: Add debug flag here
String filename;
if (myInstanceEnvironment.getOutputFilename() != null) {
filename = myInstanceEnvironment.getOutputFilename();
}
else {
filename = createVCFileName();
}
myOutputGenerator.outputToFile(filename);
}
// -----------------------------------------------------------
// ProcedureDec
// -----------------------------------------------------------
@Override
public void postProcedureDec(ProcedureDec dec) {}
// ===========================================================
// Public Methods
// ===========================================================
// -----------------------------------------------------------
// Error Handling
// -----------------------------------------------------------
public void expNotHandled(Exp exp, Location l) {
String message = "Exp not handled: " + exp.toString();
throw new SourceErrorException(message, l);
}
public void illegalOperationEnsures(Location l) {
// TODO: Move this to sanity check.
String message =
"Ensures clauses of operations that return a value should be of the form <OperationName> = <value>";
throw new SourceErrorException(message, l);
}
public void notAType(SymbolTableEntry entry, Location l) {
throw new SourceErrorException(entry.getSourceModuleIdentifier()
.fullyQualifiedRepresentation(entry.getName())
+ " is not known to be a type.", l);
}
public void notInFreeVarList(PosSymbol name, Location l) {
String message =
"State variable " + name + " not in free variable list";
throw new SourceErrorException(message, l);
}
public void noSuchModule(Location location) {
throw new SourceErrorException(
"Module does not exist or is not in scope.", location);
}
public void noSuchSymbol(PosSymbol qualifier, String symbolName, Location l) {
String message;
if (qualifier == null) {
message = "No such symbol: " + symbolName;
}
else {
message =
"No such symbol in module: " + qualifier.getName() + "."
+ symbolName;
}
throw new SourceErrorException(message, l);
}
public void tyNotHandled(Ty ty, Location location) {
String message = "Ty not handled: " + ty.toString();
throw new SourceErrorException(message, location);
}
// -----------------------------------------------------------
// Prover Mode
// -----------------------------------------------------------
/**
* <p>The set of immmutable VCs that the in house provers can use.</p>
*
* @return VCs to be proved.
*/
public List<VC> proverOutput() {
return myOutputGenerator.getProverOutput();
}
// ===========================================================
// Private Methods
// ===========================================================
/**
* <p>Loop through the list of <code>VarDec</code>, search
* for their corresponding <code>ProgramVariableEntry</code>
* and add the result to the list of free variables.</p>
*
* @param variableList List of the all variables as
* <code>VarDec</code>.
*/
public void addVarDecsAsFreeVars(List<VarDec> variableList) {
// Loop through the variable list
for (VarDec v : variableList) {
myCurrentAssertiveCode.addFreeVar(createVarExp(v.getLocation(), v.getName(), v
.getTy().getMathTypeValue()));
}
}
/**
* <p>Converts the different types of <code>Exp</code> to the
* ones used by the VC Generator.</p>
*
* @param oldExp The expression to be converted.
*
* @return An <code>Exp</code>.
*/
private Exp convertExp(Exp oldExp) {
// Case #1: ProgramIntegerExp
if (oldExp instanceof ProgramIntegerExp) {
IntegerExp exp = new IntegerExp();
exp.setValue(((ProgramIntegerExp) oldExp).getValue());
exp.setMathType(Z);
return exp;
}
// Case #2: VariableDotExp
else if (oldExp instanceof VariableDotExp) {
DotExp exp = new DotExp();
List<VariableExp> segments =
((VariableDotExp) oldExp).getSegments();
edu.clemson.cs.r2jt.collections.List<Exp> newSegments =
new edu.clemson.cs.r2jt.collections.List<Exp>();
// Need to replace each of the segments in a dot expression
MTType lastMathType = null;
MTType lastMathTypeValue = null;
for (VariableExp v : segments) {
VarExp varExp = new VarExp();
// Can only be a VariableNameExp. Anything else
// is a case we have not handled.
if (v instanceof VariableNameExp) {
varExp.setName(((VariableNameExp) v).getName());
lastMathType = v.getMathType();
lastMathTypeValue = v.getMathTypeValue();
newSegments.add(varExp);
}
else {
expNotHandled(v, v.getLocation());
}
}
// Set the segments and the type information.
exp.setSegments(newSegments);
exp.setMathType(lastMathType);
exp.setMathTypeValue(lastMathTypeValue);
return exp;
}
// Case #3: VariableNameExp
else if (oldExp instanceof VariableNameExp) {
VarExp exp = new VarExp();
exp.setName(((VariableNameExp) oldExp).getName());
exp.setMathType(oldExp.getMathType());
exp.setMathTypeValue(oldExp.getMathTypeValue());
return exp;
}
return oldExp;
}
/**
* <p>Returns a newly created <code>PosSymbol</code>
* with the string provided.</p>
*
* @param name String of the new <code>PosSymbol</code>.
*
* @return The new <code>PosSymbol</code>.
*/
private PosSymbol createPosSymbol(String name) {
// Create the PosSymbol
PosSymbol posSym = new PosSymbol();
posSym.setSymbol(Symbol.symbol(name));
return posSym;
}
/**
* <p>Returns an <code>DotExp</code> with the <code>VarDec</code>
* and its initialization ensures clause.</p>
*
* @param var The declared variable.
* @param initExp The initialization ensures of the variable.
*
* @return The new <code>DotExp</code>.
*/
private DotExp createInitExp(VarDec var, Exp initExp) {
// Convert the declared variable into a VarExp
VarExp varExp =
createVarExp(var.getLocation(), var.getName(), var.getTy()
.getMathTypeValue());
// Left hand side of the expression
VarExp left = null;
// NameTy
if (var.getTy() instanceof NameTy) {
NameTy ty = (NameTy) var.getTy();
left = createVarExp(ty.getLocation(), ty.getName(), MTYPE);
}
else {
tyNotHandled(var.getTy(), var.getTy().getLocation());
}
// Complicated steps to construct the argument list
// YS: No idea why it is so complicated!
edu.clemson.cs.r2jt.collections.List<Exp> expList =
new edu.clemson.cs.r2jt.collections.List<Exp>();
expList.add(varExp);
FunctionArgList argList = new FunctionArgList();
argList.setArguments(expList);
edu.clemson.cs.r2jt.collections.List<FunctionArgList> functionArgLists =
new edu.clemson.cs.r2jt.collections.List<FunctionArgList>();
functionArgLists.add(argList);
// Right hand side of the expression
FunctionExp right =
new FunctionExp(var.getLocation(), null,
createPosSymbol("is_initial"), null, functionArgLists);
right.setMathType(BOOLEAN);
// Create the DotExp
edu.clemson.cs.r2jt.collections.List<Exp> exps =
new edu.clemson.cs.r2jt.collections.List<Exp>();
exps.add(left);
exps.add(right);
DotExp exp = new DotExp(var.getLocation(), exps, null);
exp.setMathType(BOOLEAN);
return exp;
}
/**
* <p>Creates a variable expression with the name
* "P_val" and has type "N".</p>
*
* @param location Location that wants to create
* this variable.
*
* @return The created <code>VarExp</code>.
*/
private VarExp createPValExp(Location location) {
// Locate "N" (Natural Number)
MathSymbolEntry mse = searchMathSymbol(location, "N");
try {
// Create a variable with the name P_val
return createVarExp(location, createPosSymbol("P_val"), mse
.getTypeValue());
}
catch (SymbolNotOfKindTypeException e) {
notAType(mse, location);
}
return null;
}
/**
* <p>Create a question mark variable with the oldVar
* passed in.</p>
*
* @param exp The full expression clause.
* @param oldVar The old variable expression.
*
* @return A new variable with the question mark in <code>VarExp</code> form.
*/
private VarExp createQuestionMarkVariable(Exp exp, VarExp oldVar) {
// Add an extra question mark to the front of oldVar
VarExp newOldVar =
new VarExp(null, null, createPosSymbol("?"
+ oldVar.getName().getName()));
newOldVar.setMathType(oldVar.getMathType());
newOldVar.setMathTypeValue(oldVar.getMathTypeValue());
// Applies the question mark to oldVar if it is our first time visiting.
if (exp.containsVar(oldVar.getName().getName(), false)) {
return createQuestionMarkVariable(exp, newOldVar);
}
// Don't need to apply the question mark here.
else if (exp.containsVar(newOldVar.getName().toString(), false)) {
return createQuestionMarkVariable(exp, newOldVar);
}
else {
// Return the new variable expression with the question mark
if (oldVar.getName().getName().charAt(0) != '?') {
return newOldVar;
}
}
// Return our old self.
return oldVar;
}
/**
* <p>Returns a newly created <code>VarExp</code>
* with the <code>PosSymbol</code> and math type provided.</p>
*
* @param loc Location of the new <code>VarExp</code>
* @param name <code>PosSymbol</code> of the new <code>VarExp</code>.
* @param type Math type of the new <code>VarExp</code>.
*
* @return The new <code>VarExp</code>.
*/
private VarExp createVarExp(Location loc, PosSymbol name, MTType type) {
// Create the VarExp
VarExp exp = new VarExp(loc, null, name);
exp.setMathType(type);
return exp;
}
/**
* <p>Creates the name of the output file.</p>
*
* @return Name of the file
*/
private String createVCFileName() {
File file = myInstanceEnvironment.getTargetFile();
ModuleID cid = myInstanceEnvironment.getModuleID(file);
file = myInstanceEnvironment.getFile(cid);
String filename = file.toString();
int temp = filename.indexOf(".");
String tempfile = filename.substring(0, temp);
String mainFileName;
mainFileName = tempfile + ".asrt_new";
return mainFileName;
}
/**
* <p>Returns all the constraint clauses combined together for the
* for the current <code>ModuleDec</code>.</p>
*
* @param loc The location of the <code>ModuleDec</code>.
* @param imports The list of imported modules.
*
* @return The constraint clause <code>Exp</code>.
*/
private Exp getConstraints(Location loc, List<ModuleIdentifier> imports) {
Exp retExp = null;
// Loop
for (ModuleIdentifier mi : imports) {
try {
ModuleDec dec =
mySymbolTable.getModuleScope(mi).getDefiningElement();
List<Exp> contraintExpList = null;
// Handling for facility imports
if (dec instanceof ShortFacilityModuleDec) {
FacilityDec facDec =
((ShortFacilityModuleDec) dec).getDec();
dec =
mySymbolTable.getModuleScope(
new ModuleIdentifier(facDec
.getConceptName().getName()))
.getDefiningElement();
}
if (dec instanceof ConceptModuleDec) {
contraintExpList =
((ConceptModuleDec) dec).getConstraints();
// Copy all the constraints
for (Exp e : contraintExpList) {
// Deep copy and set the location detail
Exp constraint = Exp.copy(e);
if (constraint.getLocation() != null) {
Location theLoc = constraint.getLocation();
theLoc.setDetails("Constraint of Module: "
+ dec.getName());
setLocation(constraint, theLoc);
}
// Form conjunct if needed.
if (retExp == null) {
retExp = Exp.copy(e);
}
else {
retExp =
myTypeGraph.formConjunct(retExp, Exp
.copy(e));
}
}
}
}
catch (NoSuchSymbolException e) {
System.err.println("Module " + mi.toString()
+ " does not exist or is not in scope.");
noSuchModule(loc);
}
}
return retExp;
}
/**
* <p>Returns the ensures clause for the current <code>Dec</code>.</p>
*
* @param dec The corresponding <code>Dec</code>.
*
* @return The ensures clause <code>Exp</code>.
*/
private Exp getEnsuresClause(Dec dec) {
PosSymbol name = dec.getName();
Exp ensures = null;
Exp retExp = null;
// Check for each kind of ModuleDec possible
if (dec instanceof FacilityOperationDec) {
ensures = ((FacilityOperationDec) dec).getEnsures();
}
else if (dec instanceof OperationDec) {
ensures = ((OperationDec) dec).getEnsures();
}
// Deep copy and fill in the details of this location
if (ensures != null) {
retExp = Exp.copy(ensures);
if (retExp.getLocation() != null) {
Location myLoc = retExp.getLocation();
myLoc.setDetails("Ensures Clause of " + name);
setLocation(retExp, myLoc);
}
}
return retExp;
}
/**
* <p>Returns the requires clause for the current <code>Dec</code>.</p>
*
* @param dec The corresponding <code>Dec</code>.
*
* @return The requires clause <code>Exp</code>.
*/
private Exp getRequiresClause(Dec dec) {
PosSymbol name = dec.getName();
Exp requires = null;
Exp retExp = null;
// Check for each kind of ModuleDec possible
if (dec instanceof FacilityOperationDec) {
requires = ((FacilityOperationDec) dec).getRequires();
}
else if (dec instanceof OperationDec) {
requires = ((OperationDec) dec).getRequires();
}
else if (dec instanceof ConceptModuleDec) {
requires = ((ConceptModuleDec) dec).getRequirement();
}
else if (dec instanceof ConceptBodyModuleDec) {
requires = ((ConceptBodyModuleDec) dec).getRequires();
}
else if (dec instanceof EnhancementModuleDec) {
requires = ((EnhancementModuleDec) dec).getRequirement();
}
else if (dec instanceof EnhancementBodyModuleDec) {
requires = ((EnhancementBodyModuleDec) dec).getRequires();
}
else if (dec instanceof FacilityModuleDec) {
requires = ((FacilityModuleDec) dec).getRequirement();
}
// Deep copy and fill in the details of this location
if (requires != null) {
retExp = Exp.copy(requires);
if (retExp.getLocation() != null) {
Location myLoc = retExp.getLocation();
myLoc.setDetails("Requires Clause for " + name);
setLocation(retExp, myLoc);
}
}
return retExp;
}
/**
* <p>Get the <code>PosSymbol</code> associated with the
* <code>VariableExp</code> left.</p>
*
* @param left The variable expression.
*
* @return The <code>PosSymbol</code> of left.
*/
private PosSymbol getVarName(VariableExp left) {
// Return value
PosSymbol name;
// Variable Name Expression
if (left instanceof VariableNameExp) {
name = ((VariableNameExp) left).getName();
}
// Variable Dot Expression
else if (left instanceof VariableDotExp) {
VariableRecordExp varRecExp =
(VariableRecordExp) ((VariableDotExp) left)
.getSemanticExp();
name = varRecExp.getName();
}
// Variable Record Expression
else if (left instanceof VariableRecordExp) {
VariableRecordExp varRecExp = (VariableRecordExp) left;
name = varRecExp.getName();
}
//
// Creates an expression with "false" as its name
else {
name = createPosSymbol("false");
}
return name;
}
/**
* <p>Checks to see if the initialization ensures clause
* passed is in the simple form where one side has a
* <code>VarExp</code>.</p>
*
* @param initEnsures The initialization ensures clause,
* or part of it that we are currently
* checking.
* @param name The name of the variable we are checking.
*
* @return True/False
*/
private boolean isInitEnsuresSimpleForm(Exp initEnsures, PosSymbol name) {
boolean isSimple = false;
// Case #1: EqualExp in initEnsures
if (initEnsures instanceof EqualsExp) {
EqualsExp exp = (EqualsExp) initEnsures;
// Recursively call this on the left and
// right hand side. Only one of the sides
// needs to be a VarExp.
if (isInitEnsuresSimpleForm(exp.getLeft(), name)
|| isInitEnsuresSimpleForm(exp.getRight(), name)) {
isSimple = true;
}
}
// Case #2: InfixExp in initEnsures
else if (initEnsures instanceof InfixExp) {
InfixExp exp = (InfixExp) initEnsures;
// Only check if we have an "and" expression
if (exp.getOpName().equals("and")) {
// Recursively call this on the left and
// right hand side. Both sides need to be
// a VarExp.
if (isInitEnsuresSimpleForm(exp.getLeft(), name)
&& isInitEnsuresSimpleForm(exp.getRight(), name)) {
isSimple = true;
}
}
}
// Case #3: VarExp = initEnsures
else if (initEnsures instanceof VarExp) {
VarExp exp = (VarExp) initEnsures;
// Check to see if the name matches the initEnsures
if (exp.getName().equals(name.getName())) {
isSimple = true;
}
}
return isSimple;
}
/**
* <p>Checks to see if the expression passed in is a
* verification variable or not. A verification variable
* is either "P_val" or starts with "?".</p>
*
* @param name Expression that we want to check
*
* @return True/False
*/
private boolean isVerificationVar(Exp name) {
// VarExp
if (name instanceof VarExp) {
String strName = ((VarExp) name).getName().getName();
// Case #1: Question mark variables
if (strName.charAt(0) == '?') {
return true;
}
// Case #2: P_val
else if (strName.equals("P_val")) {
return true;
}
}
// DotExp
else if (name instanceof DotExp) {
// Recursively call this method until we get
// either true or false.
List<Exp> names = ((DotExp) name).getSegments();
return isVerificationVar(names.get(0));
}
// Definitely not a verification variable.
return false;
}
/**
* <p>Modifies the ensures clause based on the parameter mode.</p>
*
* @param ensures The <code>Exp</code> containing the ensures clause.
* @param opLocation The <code>Location</code> for the operation
* @param opName The name of the operation.
* @param parameterVarDecList The list of parameter variables for the operation.
*
* @return The modified ensures clause <code>Exp</code>.
*/
private Exp modifyEnsuresByParameter(Exp ensures, Location opLocation,
String opName, List<ParameterVarDec> parameterVarDecList) {
// Loop through each parameter
for (ParameterVarDec p : parameterVarDecList) {
// Ty is NameTy
if (p.getTy() instanceof NameTy) {
NameTy pNameTy = (NameTy) p.getTy();
// Exp form of the parameter variable
VarExp parameterExp =
new VarExp(p.getLocation(), null, p.getName().copy());
parameterExp.setMathType(pNameTy.getMathTypeValue());
// Create an old exp (#parameterExp)
OldExp oldParameterExp =
new OldExp(p.getLocation(), Exp.copy(parameterExp));
oldParameterExp.setMathType(pNameTy.getMathTypeValue());
// Preserves or Restores mode
if (p.getMode() == Mode.PRESERVES
|| p.getMode() == Mode.RESTORES) {
// Create an equals expression of the form "#parameterExp = parameterExp"
EqualsExp equalsExp =
new EqualsExp(opLocation, oldParameterExp,
EqualsExp.EQUAL, parameterExp);
equalsExp.setMathType(BOOLEAN);
// Set the details for the new location
Location equalLoc;
if (ensures != null && ensures.getLocation() != null) {
Location enLoc = ensures.getLocation();
equalLoc = ((Location) enLoc.clone());
}
else {
equalLoc = ((Location) opLocation.clone());
equalLoc.setDetails("Ensures Clause of " + opName);
}
equalLoc.setDetails(equalLoc.getDetails()
+ " (Condition from \""
+ p.getMode().getModeName().toUpperCase()
+ "\" parameter mode)");
equalsExp.setLocation(equalLoc);
// Create an AND infix expression with the ensures clause
if (ensures != null
&& !ensures.equals(myTypeGraph.getTrueVarExp())) {
ensures = myTypeGraph.formConjunct(ensures, equalsExp);
}
// Make new expression the ensures clause
else {
ensures = equalsExp;
}
}
// Clears mode
else if (p.getMode() == Mode.CLEARS) {
// Query for the type entry in the symbol table
ProgramTypeEntry typeEntry =
searchProgramType(pNameTy.getLocation(), pNameTy
.getName());
// Obtain the original dec from the AST
TypeDec type = (TypeDec) typeEntry.getDefiningElement();
// Obtain the exemplar in VarExp form
VarExp exemplar =
new VarExp(null, null, type.getExemplar());
exemplar.setMathType(pNameTy.getMathTypeValue());
// Deep copy the original initialization ensures and the constraint
Exp init = Exp.copy(type.getInitialization().getEnsures());
// Replace the formal with the actual
init = replace(init, exemplar, parameterExp);
// Set the details for the new location
if (init.getLocation() != null) {
Location initLoc;
if (ensures != null && ensures.getLocation() != null) {
Location reqLoc = ensures.getLocation();
initLoc = ((Location) reqLoc.clone());
}
else {
initLoc = ((Location) opLocation.clone());
initLoc.setDetails("Ensures Clause of " + opName);
}
initLoc.setDetails(initLoc.getDetails()
+ " (Condition from \""
+ p.getMode().getModeName().toUpperCase()
+ "\" parameter mode)");
init.setLocation(initLoc);
}
// Create an AND infix expression with the ensures clause
if (ensures != null
&& !ensures.equals(myTypeGraph.getTrueVarExp())) {
ensures = myTypeGraph.formConjunct(ensures, init);
}
// Make initialization expression the ensures clause
else {
ensures = init;
}
}
}
else {
// Ty not handled.
tyNotHandled(p.getTy(), p.getLocation());
}
}
return ensures;
}
/**
* <p>Returns the ensures clause.</p>
*
* @param ensures The <code>Exp</code> containing the ensures clause.
* @param opLocation The <code>Location</code> for the operation.
* @param opName The name for the operation.
*
* @return The modified ensures clause <code>Exp</code>.
*/
private Exp modifyEnsuresClause(Exp ensures, Location opLocation,
String opName) {
// Obtain the list of parameters for the current operation
List<ParameterVarDec> parameterVarDecList;
if (myCurrentOperationEntry.getDefiningElement() instanceof FacilityOperationDec) {
parameterVarDecList =
((FacilityOperationDec) myCurrentOperationEntry
.getDefiningElement()).getParameters();
}
else {
parameterVarDecList =
((OperationDec) myCurrentOperationEntry
.getDefiningElement()).getParameters();
}
// Modifies the existing ensures clause based on
// the parameter modes.
ensures =
modifyEnsuresByParameter(ensures, opLocation, opName,
parameterVarDecList);
return ensures;
}
/**
* <p>Modifies the requires clause based on .</p>
*
* @param requires The <code>Exp</code> containing the requires clause.
*
* @return The modified requires clause <code>Exp</code>.
*/
private Exp modifyRequiresByGlobalMode(Exp requires) {
return requires;
}
/**
* <p>Modifies the requires clause based on the parameter mode.</p>
*
* @param requires The <code>Exp</code> containing the requires clause.
* @param opLocation The <code>Location</code> for the operation.
* @param opName The name for the operation.
*
* @return The modified requires clause <code>Exp</code>.
*/
private Exp modifyRequiresByParameter(Exp requires, Location opLocation,
String opName) {
// Obtain the list of parameters
List<ParameterVarDec> parameterVarDecList;
if (myCurrentOperationEntry.getDefiningElement() instanceof FacilityOperationDec) {
parameterVarDecList =
((FacilityOperationDec) myCurrentOperationEntry
.getDefiningElement()).getParameters();
}
else {
parameterVarDecList =
((OperationDec) myCurrentOperationEntry
.getDefiningElement()).getParameters();
}
// Loop through each parameter
for (ParameterVarDec p : parameterVarDecList) {
ProgramTypeEntry typeEntry;
// Ty is NameTy
if (p.getTy() instanceof NameTy) {
NameTy pNameTy = (NameTy) p.getTy();
// Query for the type entry in the symbol table
typeEntry =
searchProgramType(pNameTy.getLocation(), pNameTy
.getName());
// Obtain the original dec from the AST
TypeDec type = (TypeDec) typeEntry.getDefiningElement();
// Convert p to a VarExp
VarExp pExp = new VarExp(null, null, p.getName());
pExp.setMathType(pNameTy.getMathTypeValue());
// Obtain the exemplar in VarExp form
VarExp exemplar = new VarExp(null, null, type.getExemplar());
exemplar.setMathType(pNameTy.getMathTypeValue());
// Deep copy the original initialization ensures and the constraint
Exp init = Exp.copy(type.getInitialization().getEnsures());
Exp constraint = Exp.copy(type.getConstraint());
// Only worry about replaces mode parameters
if (p.getMode() == Mode.REPLACES && init != null) {
// Replace the formal with the actual
init = replace(init, exemplar, pExp);
// Set the details for the new location
if (init.getLocation() != null) {
Location initLoc;
if (requires != null && requires.getLocation() != null) {
Location reqLoc = requires.getLocation();
initLoc = ((Location) reqLoc.clone());
}
else {
// Append the name of the current procedure
String details = "";
if (myCurrentOperationEntry != null) {
details =
" in Procedure "
+ myCurrentOperationEntry
.getName();
}
// Set the details of the current location
initLoc = ((Location) opLocation.clone());
initLoc.setDetails("Requires Clause of " + opName
+ details);
}
initLoc.setDetails(initLoc.getDetails()
+ " (Assumption from \""
+ p.getMode().getModeName().toUpperCase()
+ "\" parameter mode)");
init.setLocation(initLoc);
}
// Create an AND infix expression with the requires clause
if (requires != null
&& !requires.equals(myTypeGraph.getTrueVarExp())) {
requires = myTypeGraph.formConjunct(requires, init);
}
// Make initialization expression the requires clause
else {
requires = init;
}
}
// Constraints for the other parameter modes needs to be added
// to the requires clause as conjuncts.
else {
if (constraint != null
&& !constraint.equals(myTypeGraph.getTrueVarExp())) {
// Replace the formal with the actual
constraint = replace(constraint, exemplar, pExp);
// Set the details for the new location
if (constraint.getLocation() != null) {
Location constLoc;
if (requires != null
&& requires.getLocation() != null) {
Location reqLoc = requires.getLocation();
constLoc = ((Location) reqLoc.clone());
}
else {
// Append the name of the current procedure
String details = "";
if (myCurrentOperationEntry != null) {
details =
" in Procedure "
+ myCurrentOperationEntry
.getName();
}
constLoc = ((Location) opLocation.clone());
constLoc.setDetails("Requires Clause of "
+ opName + details);
}
constLoc.setDetails(constLoc.getDetails()
+ " (Constraint from \""
+ p.getMode().getModeName().toUpperCase()
+ "\" parameter mode)");
constraint.setLocation(constLoc);
}
// Create an AND infix expression with the requires clause
if (requires != null
&& !requires
.equals(myTypeGraph.getTrueVarExp())) {
requires =
myTypeGraph.formConjunct(requires,
constraint);
}
// Make constraint expression the requires clause
else {
requires = constraint;
}
}
}
// Add the current variable to our list of free variables
myCurrentAssertiveCode.addFreeVar(createVarExp(p.getLocation(), p
.getName(), pNameTy.getMathTypeValue()));
}
else {
// Ty not handled.
tyNotHandled(p.getTy(), p.getLocation());
}
}
return requires;
}
/**
* <p>Modifies the requires clause.</p>
*
* @param requires The <code>Exp</code> containing the requires clause.
* @param opLocation The <code>Location</code> for the operation.
* @param opName The name of the operation.
*
* @return The modified requires clause <code>Exp</code>.
*/
private Exp modifyRequiresClause(Exp requires, Location opLocation,
String opName) {
// Modifies the existing requires clause based on
// the parameter modes.
requires = modifyRequiresByParameter(requires, opLocation, opName);
// Modifies the existing requires clause based on
// the parameter modes.
// TODO: Ask Murali what this means
requires = modifyRequiresByGlobalMode(requires);
return requires;
}
/**
* <p>Copy and replace the old <code>Exp</code>.</p>
*
* @param exp The <code>Exp</code> to be replaced.
* @param old The old sub-expression of <code>exp</code>.
* @param repl The new sub-expression of <code>exp</code>.
*
* @return The new <code>Exp</code>.
*/
private Exp replace(Exp exp, Exp old, Exp repl) {
// Clone old and repl and use the Exp replace to do all its work
Exp tmp = Exp.replace(exp, Exp.copy(old), Exp.copy(repl));
// Return the corresponding Exp
if (tmp != null)
return tmp;
else
return exp;
}
/**
* <p>Replace the formal with the actual variables
* inside the ensures clause.</p>
*
* @param ensures The ensures clause.
* @param paramList The list of parameter variables.
* @param stateVarList The list of state variables.
* @param argList The list of arguments from the operation call.
* @param isSimple Check if it is a simple replacement.
*
* @return The ensures clause in <code>Exp</code> form.
*/
private Exp replaceFormalWithActualEns(Exp ensures,
List<ParameterVarDec> paramList, List<AffectsItem> stateVarList,
List<ProgramExp> argList, boolean isSimple) {
// Current final confirm
Exp newConfirm = myCurrentAssertiveCode.getFinalConfirm();
// List to hold temp and real values of variables in case
// of duplicate spec and real variables
List<Exp> undRepList = new ArrayList<Exp>();
List<Exp> replList = new ArrayList<Exp>();
// Replace state variables in the ensures clause
// and create new confirm statements if needed.
for (int i = 0; i < stateVarList.size(); i++) {
newConfirm = myCurrentAssertiveCode.getFinalConfirm();
AffectsItem stateVar = stateVarList.get(i);
// Only deal with Alters/Reassigns/Replaces/Updates modes
if (stateVar.getMode() == Mode.ALTERS
|| stateVar.getMode() == Mode.REASSIGNS
|| stateVar.getMode() == Mode.REPLACES
|| stateVar.getMode() == Mode.UPDATES) {
// Obtain the variable from our free variable list
Exp globalFreeVar =
myCurrentAssertiveCode.getFreeVar(stateVar.getName(), true);
if (globalFreeVar != null) {
VarExp oldNamesVar = new VarExp();
oldNamesVar.setName(stateVar.getName());
// Create a local free variable if it is not there
Exp localFreeVar =
myCurrentAssertiveCode.getFreeVar(stateVar.getName(), false);
if (localFreeVar == null) {
// TODO: Don't have a type for state variables?
localFreeVar =
new VarExp(null, null, stateVar.getName());
localFreeVar =
createQuestionMarkVariable(myTypeGraph
.formConjunct(ensures, newConfirm),
(VarExp) localFreeVar);
myCurrentAssertiveCode.addFreeVar(localFreeVar);
}
else {
localFreeVar =
createQuestionMarkVariable(myTypeGraph
.formConjunct(ensures, newConfirm),
(VarExp) localFreeVar);
}
// Creating "#" expressions and replace these in the
// ensures clause.
OldExp osVar = new OldExp(null, Exp.copy(globalFreeVar));
OldExp oldNameOSVar =
new OldExp(null, Exp.copy(oldNamesVar));
ensures = replace(ensures, oldNamesVar, globalFreeVar);
ensures = replace(ensures, oldNameOSVar, osVar);
// If it is not simple replacement, replace all ensures clauses
// with the appropriate expressions.
if (!isSimple) {
ensures = replace(ensures, globalFreeVar, localFreeVar);
ensures = replace(ensures, osVar, globalFreeVar);
newConfirm =
replace(newConfirm, globalFreeVar, localFreeVar);
}
// Set newConfirm as our new final confirm statement
myCurrentAssertiveCode.setFinalConfirm(newConfirm);
}
// Error: Why isn't it a free variable.
else {
notInFreeVarList(stateVar.getName(), stateVar.getLocation());
}
}
}
// Replace postcondition variables in the ensures clause
for (int i = 0; i < argList.size(); i++) {
ParameterVarDec varDec = paramList.get(i);
ProgramExp pExp = argList.get(i);
PosSymbol VDName = varDec.getName();
// VarExp form of the parameter variable
VarExp oldExp = new VarExp(null, null, VDName);
oldExp.setMathType(pExp.getMathType());
oldExp.setMathTypeValue(pExp.getMathTypeValue());
// Convert the pExp into a something we can use
Exp repl = convertExp(pExp);
Exp undqRep = null, quesRep = null;
OldExp oSpecVar, oRealVar;
String replName = null;
// Case #1: ProgramIntegerExp
if (pExp instanceof ProgramIntegerExp) {
replName =
Integer.toString(((ProgramIntegerExp) repl).getValue());
// Create a variable expression of the form "_?[Argument Name]"
undqRep =
new VarExp(null, null, createPosSymbol("_?" + replName));
undqRep.setMathType(pExp.getMathType());
undqRep.setMathTypeValue(pExp.getMathTypeValue());
// Create a variable expression of the form "?[Argument Name]"
quesRep =
new VarExp(null, null, createPosSymbol("?" + replName));
quesRep.setMathType(pExp.getMathType());
quesRep.setMathTypeValue(pExp.getMathTypeValue());
}
// Case #2: VariableDotExp
else if (pExp instanceof VariableDotExp) {
if (repl instanceof DotExp) {
Exp pE = ((DotExp) repl).getSegments().get(0);
replName = pE.toString(0);
// Create a variable expression of the form "_?[Argument Name]"
undqRep = Exp.copy(repl);
edu.clemson.cs.r2jt.collections.List<Exp> segList =
((DotExp) undqRep).getSegments();
VariableNameExp undqNameRep =
new VariableNameExp(null, null,
createPosSymbol("_?" + replName));
undqNameRep.setMathType(pE.getMathType());
segList.set(0, undqNameRep);
((DotExp) undqRep).setSegments(segList);
// Create a variable expression of the form "?[Argument Name]"
quesRep = Exp.copy(repl);
segList = ((DotExp) quesRep).getSegments();
segList
.set(0, ((VariableDotExp) pExp).getSegments()
.get(0));
((DotExp) quesRep).setSegments(segList);
}
else if (repl instanceof VariableDotExp) {
Exp pE = ((VariableDotExp) repl).getSegments().get(0);
replName = pE.toString(0);
// Create a variable expression of the form "_?[Argument Name]"
undqRep = Exp.copy(repl);
edu.clemson.cs.r2jt.collections.List<VariableExp> segList =
((VariableDotExp) undqRep).getSegments();
VariableNameExp undqNameRep =
new VariableNameExp(null, null,
createPosSymbol("_?" + replName));
undqNameRep.setMathType(pE.getMathType());
segList.set(0, undqNameRep);
((VariableDotExp) undqRep).setSegments(segList);
// Create a variable expression of the form "?[Argument Name]"
quesRep = Exp.copy(repl);
segList = ((VariableDotExp) quesRep).getSegments();
segList
.set(0, ((VariableDotExp) pExp).getSegments()
.get(0));
((VariableDotExp) quesRep).setSegments(segList);
}
// Error: Case not handled!
else {
expNotHandled(pExp, pExp.getLocation());
}
}
// Case #3: VariableNameExp
else if (pExp instanceof VariableNameExp) {
// Name of repl in string form
replName = ((VariableNameExp) pExp).getName().getName();
// Create a variable expression of the form "_?[Argument Name]"
undqRep =
new VarExp(null, null, createPosSymbol("_?" + replName));
undqRep.setMathType(pExp.getMathType());
undqRep.setMathTypeValue(pExp.getMathTypeValue());
// Create a variable expression of the form "?[Argument Name]"
quesRep =
new VarExp(null, null, createPosSymbol("?" + replName));
quesRep.setMathType(pExp.getMathType());
quesRep.setMathTypeValue(pExp.getMathTypeValue());
}
// Error: Case not handled!
else {
expNotHandled(pExp, pExp.getLocation());
}
// "#" versions of oldExp and repl
oSpecVar = new OldExp(null, Exp.copy(oldExp));
oRealVar = new OldExp(null, Exp.copy(repl));
// Nothing can be null!
if (oldExp != null && quesRep != null && oSpecVar != null
&& repl != null && oRealVar != null) {
// Alters, Clears, Reassigns, Replaces, Updates
if (varDec.getMode() == Mode.ALTERS
|| varDec.getMode() == Mode.CLEARS
|| varDec.getMode() == Mode.REASSIGNS
|| varDec.getMode() == Mode.REPLACES
|| varDec.getMode() == Mode.UPDATES) {
Exp quesVar;
// Obtain the free variable
VarExp freeVar =
(VarExp) myCurrentAssertiveCode.getFreeVar(
createPosSymbol(replName), false);
if (freeVar == null) {
freeVar =
createVarExp(varDec.getLocation(),
createPosSymbol(replName), varDec
.getTy().getMathTypeValue());
}
// Apply the question mark to the free variable
freeVar =
createQuestionMarkVariable(myTypeGraph
.formConjunct(ensures, newConfirm), freeVar);
if (pExp instanceof ProgramDotExp
|| pExp instanceof VariableDotExp) {
// Make a copy from repl
quesVar = Exp.copy(repl);
// Replace the free variable in the question mark variable as the first element
// in the dot expression.
VarExp tmpVar =
new VarExp(null, null, freeVar.getName());
tmpVar.setMathType(myTypeGraph.BOOLEAN);
edu.clemson.cs.r2jt.collections.List<Exp> segs =
((DotExp) quesVar).getSegments();
segs.set(0, tmpVar);
((DotExp) quesVar).setSegments(segs);
}
else {
// Create a variable expression from free variable
quesVar = new VarExp(null, null, freeVar.getName());
quesVar.setMathType(freeVar.getMathType());
quesVar.setMathTypeValue(freeVar.getMathTypeValue());
}
// Add the new free variable to free variable list
myCurrentAssertiveCode.addFreeVar(freeVar);
// Check if our ensures clause has the parameter variable in it.
if (ensures.containsVar(VDName.getName(), true)
|| ensures.containsVar(VDName.getName(), false)) {
// Replace the ensures clause
ensures = replace(ensures, oldExp, undqRep);
ensures = replace(ensures, oSpecVar, repl);
// Add it to our list of variables to be replaced later
undRepList.add(undqRep);
replList.add(quesVar);
}
else {
// Replace the ensures clause
ensures = replace(ensures, oldExp, quesRep);
ensures = replace(ensures, oSpecVar, repl);
}
// Update our final confirm with the parameter argument
newConfirm = replace(newConfirm, repl, quesVar);
myCurrentAssertiveCode.setFinalConfirm(newConfirm);
}
// All other modes
else {
// Check if our ensures clause has the parameter variable in it.
if (ensures.containsVar(VDName.getName(), true)
|| ensures.containsVar(VDName.getName(), false)) {
// Replace the ensures clause
ensures = replace(ensures, oldExp, undqRep);
ensures = replace(ensures, oSpecVar, undqRep);
// Add it to our list of variables to be replaced later
undRepList.add(undqRep);
replList.add(repl);
}
else {
// Replace the ensures clause
ensures = replace(ensures, oldExp, repl);
ensures = replace(ensures, oSpecVar, repl);
}
}
}
}
// Replace the temp values with the actual values
for (int i = 0; i < undRepList.size(); i++) {
ensures = replace(ensures, undRepList.get(i), replList.get(i));
}
return ensures;
}
/**
* <p>Replace the formal with the actual variables
* inside the requires clause.</p>
*
* @param requires The requires clause.
* @param paramList The list of parameter variables.
* @param argList The list of arguments from the operation call.
*
* @return The requires clause in <code>Exp</code> form.
*/
private Exp replaceFormalWithActualReq(Exp requires,
List<ParameterVarDec> paramList, List<ProgramExp> argList) {
// List to hold temp and real values of variables in case
// of duplicate spec and real variables
List<Exp> undRepList = new ArrayList<Exp>();
List<Exp> replList = new ArrayList<Exp>();
// Replace precondition variables in the requires clause
for (int i = 0; i < argList.size(); i++) {
ParameterVarDec varDec = paramList.get(i);
ProgramExp pExp = argList.get(i);
// Convert the pExp into a something we can use
Exp repl = convertExp(pExp);
// VarExp form of the parameter variable
VarExp oldExp = new VarExp(null, null, varDec.getName());
oldExp.setMathType(pExp.getMathType());
oldExp.setMathTypeValue(pExp.getMathTypeValue());
// New VarExp
VarExp newExp =
new VarExp(null, null, createPosSymbol("_"
+ varDec.getName().getName()));
newExp.setMathType(repl.getMathType());
newExp.setMathTypeValue(repl.getMathTypeValue());
// Replace the old with the new in the requires clause
requires = replace(requires, oldExp, newExp);
// Add it to our list
undRepList.add(newExp);
replList.add(repl);
}
// Replace the temp values with the actual values
for (int i = 0; i < undRepList.size(); i++) {
requires = replace(requires, undRepList.get(i), replList.get(i));
}
return requires;
}
/**
* <p>Given a math symbol name, locate and return
* the <code>MathSymbolEntry</code> stored in the
* symbol table.</p>
*
* @param loc The location in the AST that we are
* currently visiting.
* @param name The string name of the math symbol.
*
* @return An <code>MathSymbolEntry</code> from the
* symbol table.
*/
private MathSymbolEntry searchMathSymbol(Location loc, String name) {
// Query for the corresponding math symbol
MathSymbolEntry ms = null;
try {
ms =
myCurrentModuleScope.queryForOne(
new UnqualifiedNameQuery(name,
ImportStrategy.IMPORT_RECURSIVE,
FacilityStrategy.FACILITY_IGNORE, true,
true)).toMathSymbolEntry(loc);
}
catch (NoSuchSymbolException nsse) {
noSuchSymbol(null, name, loc);
}
catch (DuplicateSymbolException dse) {
//This should be caught earlier, when the duplicate symbol is
//created
throw new RuntimeException(dse);
}
return ms;
}
/**
* <p>Given the qualifier, name and the list of argument
* types, locate and return the <code>OperationEntry</code>
* stored in the symbol table.</p>
*
* @param loc The location in the AST that we are
* currently visiting.
* @param qualifier The qualifier of the operation.
* @param name The name of the operation.
* @param argTypes The list of argument types.
*
* @return An <code>OperationEntry</code> from the
* symbol table.
*/
private OperationEntry searchOperation(Location loc, PosSymbol qualifier,
PosSymbol name, List<PTType> argTypes) {
// Query for the corresponding operation
OperationEntry op = null;
try {
op =
myCurrentModuleScope.queryForOne(new OperationQuery(
qualifier, name, argTypes));
}
catch (NoSuchSymbolException nsse) {
noSuchSymbol(null, name.getName(), loc);
}
catch (DuplicateSymbolException dse) {
//This should be caught earlier, when the duplicate operation is
//created
throw new RuntimeException(dse);
}
return op;
}
/**
* <p>Given the name of the type locate and return
* the <code>ProgramTypeEntry</code> stored in the
* symbol table.</p>
*
* @param loc The location in the AST that we are
* currently visiting.
* @param name The name of the type.
*
* @return An <code>ProgramTypeEntry</code> from the
* symbol table.
*/
private ProgramTypeEntry searchProgramType(Location loc, PosSymbol name) {
// Query for the corresponding operation
ProgramTypeEntry pt = null;
try {
pt =
myCurrentModuleScope.queryForOne(
new NameQuery(null, name,
ImportStrategy.IMPORT_NAMED,
FacilityStrategy.FACILITY_INSTANTIATE,
false)).toProgramTypeEntry(loc);
}
catch (NoSuchSymbolException nsse) {
noSuchSymbol(null, name.getName(), loc);
}
catch (DuplicateSymbolException dse) {
//This should be caught earlier, when the duplicate type is
//created
throw new RuntimeException(dse);
}
return pt;
}
/**
* <p>Changes the <code>Exp</code> with the new
* <code>Location</code>.</p>
*
* @param exp The <code>Exp</code> that needs to be modified.
* @param loc The new <code>Location</code>.
*/
private void setLocation(Exp exp, Location loc) {
// Special handling for InfixExp
if (exp instanceof InfixExp) {
((InfixExp) exp).setAllLocations(loc);
}
else {
exp.setLocation(loc);
}
}
/**
* <p>Simplify the assume statement where possible.</p>
*
* @param stmt The assume statement we want to simplify.
* @param exp The current expression we are dealing with.
*
* @return The modified expression in <code>Exp/code> form.
*/
private Exp simplifyAssumeRule(AssumeStmt stmt, Exp exp) {
// Variables
Exp assertion = stmt.getAssertion();
boolean keepAssumption = false;
// EqualsExp
if (assertion instanceof EqualsExp) {
EqualsExp equalsExp = (EqualsExp) assertion;
// Only do simplifications if we have an equals
if (equalsExp.getOperator() == EqualsExp.EQUAL) {
boolean verificationVariable =
isVerificationVar(equalsExp.getLeft());
// Create a temp expression where left is replaced with the right
Exp tmp =
replace(exp, equalsExp.getLeft(), equalsExp.getRight());
if (equalsExp.getLeft() instanceof VarExp) {
// If left is still part of confirm
VarExp left = (VarExp) equalsExp.getLeft();
if (tmp.containsVar(left.getName().getName(), false)) {
keepAssumption = true;
}
}
// If tmp is not null, then it means we have to check the right
if (tmp == null) {
// Create a temp expression where right is replaced with the left
verificationVariable =
isVerificationVar(equalsExp.getRight());
tmp =
replace(exp, equalsExp.getRight(), equalsExp
.getLeft());
if (equalsExp.getRight() instanceof VarExp) {
// If right is still part of confirm
VarExp right = (VarExp) equalsExp.getRight();
if (tmp.containsVar(right.getName().getName(), false)) {
keepAssumption = true;
}
}
}
// We clear our assertion for this assumes if
// we have a verification variable and we don't have to
// keep this assumption.
if (verificationVariable && !keepAssumption) {
assertion = null;
}
// Update exp
if (!tmp.equals(exp)) {
exp = tmp;
}
}
}
// InfixExp
else if (assertion instanceof InfixExp) {
InfixExp infixExp = (InfixExp) assertion;
// Only do simplifications if we have an and operator
if (infixExp.getOpName().equals("and")) {
// Recursively call simplify on the left and on the right
AssumeStmt left = new AssumeStmt(Exp.copy(infixExp.getLeft()));
AssumeStmt right =
new AssumeStmt(Exp.copy(infixExp.getRight()));
exp = simplifyAssumeRule(left, exp);
exp = simplifyAssumeRule(right, exp);
// Case #1: Nothing left
if (left.getAssertion() == null && right.getAssertion() == null) {
assertion = null;
}
// Case #2: Both still have assertions
else if (left.getAssertion() != null
&& right.getAssertion() != null) {
assertion =
myTypeGraph.formConjunct(left.getAssertion(), right
.getAssertion());
}
// Case #3: Left still has assertions
else if (left.getAssertion() != null) {
assertion = left.getAssertion();
}
// Case #r: Right still has assertions
else {
assertion = right.getAssertion();
}
}
}
// Store the new assertion
stmt.setAssertion(assertion);
return exp;
}
// -----------------------------------------------------------
// Proof Rules
// -----------------------------------------------------------
/**
* <p>Applies the assume rule.</p>
*
* @param assume The assume clause
*/
private void applyAssumeRule(VerificationStatement assume) {
if (assume.getAssertion() instanceof VarExp
&& ((VarExp) assume.getAssertion()).equals(Exp
.getTrueVarExp(myTypeGraph))) {
// Verbose Mode Debug Messages
myVCBuffer.append("\nAssume Rule Applied and Simplified: \n");
myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
else {
// Obtain the current final confirm clause
Exp conf = myCurrentAssertiveCode.getFinalConfirm();
// Create a new implies expression
InfixExp newConf =
myTypeGraph.formImplies((Exp) assume.getAssertion(), conf);
// Set this new expression as the new final confirm
myCurrentAssertiveCode.setFinalConfirm(newConf);
// Verbose Mode Debug Messages
myVCBuffer.append("\nAssume Rule Applied: \n");
myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
}
/**
* <p>Applies different rules to code statements.</p>
*
* @param statement The different statements.
*/
private void applyCodeRules(Statement statement) {
// Apply each statement rule here.
if (statement instanceof AssumeStmt) {
applyEBAssumeStmtRule((AssumeStmt) statement);
}
else if (statement instanceof CallStmt) {
applyEBCallStmtRule((CallStmt) statement);
}
else if (statement instanceof ConfirmStmt) {
applyEBConfirmStmtRule((ConfirmStmt) statement);
}
else if (statement instanceof FuncAssignStmt) {
applyEBFuncAssignStmtRule((FuncAssignStmt) statement);
}
else if (statement instanceof SwapStmt) {
applyEBSwapStmtRule((SwapStmt) statement);
}
}
/**
* <p>Applies the confirm rule.</p>
*
* @param confirm The confirm clause
*/
private void applyConfirmRule(VerificationStatement confirm) {
if (confirm.getAssertion() instanceof VarExp
&& ((VarExp) confirm.getAssertion()).equals(Exp
.getTrueVarExp(myTypeGraph))) {
myVCBuffer.append("\nConfirm Rule Applied and Simplified: \n");
myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
else {
// Obtain the current final confirm clause
Exp conf = myCurrentAssertiveCode.getFinalConfirm();
// Create a new and expression
InfixExp newConf =
myTypeGraph
.formConjunct((Exp) confirm.getAssertion(), conf);
// Set this new expression as the new final confirm
myCurrentAssertiveCode.setFinalConfirm(newConf);
// Verbose Mode Debug Messages
myVCBuffer.append("\nConfirm Rule Applied: \n");
myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
}
/**
* <p>Applies the assume rule to the
* <code>Statement</code>.</p>
*
* @param stmt Our current <code>AssumeStmt</code>.
*/
private void applyEBAssumeStmtRule(AssumeStmt stmt) {
// Check to see if our assertion just has "True"
Exp assertion = stmt.getAssertion();
if (assertion instanceof VarExp
&& assertion.equals(myTypeGraph.getTrueVarExp())) {
// Verbose Mode Debug Messages
myVCBuffer.append("\nAssume Rule Applied and Simplified: \n");
myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
myVCBuffer.append("\n_____________________ \n");
return;
}
// Apply simplification
Exp currentFinalConfirm =
simplifyAssumeRule(stmt, myCurrentAssertiveCode.getFinalConfirm());
if (stmt.getAssertion() != null) {
// Create a new implies expression
currentFinalConfirm =
myTypeGraph.formImplies(assertion, currentFinalConfirm);
}
// Set this as our new final confirm
myCurrentAssertiveCode.setFinalConfirm(currentFinalConfirm);
// Verbose Mode Debug Messages
myVCBuffer.append("\nAssume Rule Applied: \n");
myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
/**
* <p>Applies the call statement rule to the
* <code>Statement</code>.</p>
*
* @param stmt Our current <code>CallStmt</code>.
*/
private void applyEBCallStmtRule(CallStmt stmt) {
// Obtain the corresponding OperationEntry and OperationDec
List<PTType> argTypes = new LinkedList<PTType>();
for (ProgramExp arg : stmt.getArguments()) {
argTypes.add(arg.getProgramType());
}
OperationEntry opEntry =
searchOperation(stmt.getLocation(), stmt.getQualifier(), stmt
.getName(), argTypes);
// Obtain an OperationDec from the OperationEntry
ResolveConceptualElement element = opEntry.getDefiningElement();
OperationDec opDec;
if (element instanceof OperationDec) {
opDec = (OperationDec) opEntry.getDefiningElement();
}
else {
FacilityOperationDec fOpDec =
(FacilityOperationDec) opEntry.getDefiningElement();
opDec =
new OperationDec(fOpDec.getName(), fOpDec.getParameters(),
fOpDec.getReturnTy(), fOpDec.getStateVars(), fOpDec
.getRequires(), fOpDec.getEnsures());
}
// Get the ensures clause for this operation
// Note: If there isn't an ensures clause, it is set to "True"
Exp ensures;
if (opDec.getEnsures() != null) {
ensures = Exp.copy(opDec.getEnsures());
// Set the location for the ensures clause
if (ensures.getLocation() != null) {
Location newLoc = ensures.getLocation();
newLoc.setDetails("Ensures Clause For " + opDec.getName());
ensures.setLocation(newLoc);
}
}
else {
ensures = myTypeGraph.getTrueVarExp();
}
// Get the requires clause for this operation
Exp requires;
if (opDec.getRequires() != null) {
requires = Exp.copy(opDec.getRequires());
}
else {
requires = myTypeGraph.getTrueVarExp();
}
// Check for recursive call of itself
if (myCurrentOperationEntry.getName().equals(opEntry.getName())
&& myCurrentOperationEntry.getReturnType() != null) {
// Create a new confirm statement using P_val and the decreasing clause
VarExp pVal = createPValExp(myOperationDecreasingExp.getLocation());
// Create a new infix expression
InfixExp exp =
new InfixExp(stmt.getLocation(), Exp
.copy(myOperationDecreasingExp),
createPosSymbol("<"), pVal);
exp.setMathType(BOOLEAN);
// Create the new confirm statement
Location loc;
if (myOperationDecreasingExp.getLocation() != null) {
loc = (Location) myOperationDecreasingExp.getLocation().clone();
}
else {
loc = (Location) stmt.getLocation().clone();
}
loc.setDetails("Show Termination of Recursive Call");
setLocation(exp, loc);
ConfirmStmt conf = new ConfirmStmt(loc, exp);
// Add it to our list of assertions
myCurrentAssertiveCode.addCode(conf);
}
// Modify ensures using the parameter modes
ensures =
modifyEnsuresByParameter(ensures, stmt.getLocation(), opDec
.getName().getName(), opDec.getParameters());
// Replace PreCondition variables in the requires clause
requires =
replaceFormalWithActualReq(requires, opDec.getParameters(),
stmt.getArguments());
// Replace PostCondition variables in the ensures clause
ensures =
replaceFormalWithActualEns(ensures, opDec.getParameters(),
opDec.getStateVars(), stmt.getArguments(), false);
// Modify the location of the requires clause and add it to myCurrentAssertiveCode
if (requires != null) {
// Obtain the current location
// Note: If we don't have a location, we create one
Location loc;
if (stmt.getName().getLocation() != null) {
loc = (Location) stmt.getName().getLocation().clone();
}
else {
loc = new Location(null, null);
}
// Append the name of the current procedure
String details = "";
if (myCurrentOperationEntry != null) {
details = " in Procedure " + myCurrentOperationEntry.getName();
}
// Set the details of the current location
loc.setDetails("Requires Clause of " + opDec.getName() + details);
setLocation(requires, loc);
// Add this to our list of things to confirm
myCurrentAssertiveCode.addConfirm(requires);
}
// Modify the location of the requires clause and add it to myCurrentAssertiveCode
if (ensures != null) {
// Obtain the current location
if (stmt.getName().getLocation() != null) {
// Set the details of the current location
Location loc = (Location) stmt.getName().getLocation().clone();
loc.setDetails("Ensures Clause of " + opDec.getName());
setLocation(ensures, loc);
}
// Add this to our list of things to assume
myCurrentAssertiveCode.addAssume(ensures);
}
// Verbose Mode Debug Messages
myVCBuffer.append("\nOperation Call Rule Applied: \n");
myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
/**
* <p>Applies the confirm rule to the
* <code>Statement</code>.</p>
*
* @param stmt Our current <code>ConfirmStmt</code>.
*/
private void applyEBConfirmStmtRule(ConfirmStmt stmt) {
// Check to see if our assertion just has "True"
Exp assertion = stmt.getAssertion();
if (assertion instanceof VarExp
&& assertion.equals(myTypeGraph.getTrueVarExp())) {
// Verbose Mode Debug Messages
myVCBuffer.append("\nConfirm Rule Applied and Simplified: \n");
myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
myVCBuffer.append("\n_____________________ \n");
return;
}
// Obtain the current final confirm statement
Exp currentFinalConfirm = myCurrentAssertiveCode.getFinalConfirm();
// Check to see if we have a final confirm of "True"
if (currentFinalConfirm instanceof VarExp
&& currentFinalConfirm.equals(myTypeGraph.getTrueVarExp())) {
// Obtain the current location
if (assertion.getLocation() != null) {
// Set the details of the current location
Location loc = (Location) assertion.getLocation().clone();
setLocation(assertion, loc);
}
myCurrentAssertiveCode.setFinalConfirm(assertion);
// Verbose Mode Debug Messages
myVCBuffer.append("\nConfirm Rule Applied and Simplified: \n");
myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
else {
// Create a new and expression
InfixExp newConf =
myTypeGraph.formConjunct(assertion, currentFinalConfirm);
// Set this new expression as the new final confirm
myCurrentAssertiveCode.setFinalConfirm(newConf);
// Verbose Mode Debug Messages
myVCBuffer.append("\nConfirm Rule Applied: \n");
myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
}
/**
* <p>Applies each of the proof rules. This <code>AssertiveCode</code> will be
* stored for later use and therefore should be considered immutable after
* a call to this method.</p>
*/
private void applyEBRules() {
// Apply a proof rule to each of the assertions
while (myCurrentAssertiveCode.hasAnotherAssertion()) {
// Work our way from the last assertion
VerificationStatement curAssertion = myCurrentAssertiveCode.getLastAssertion();
switch (curAssertion.getType()) {
// Assume Assertion
case VerificationStatement.ASSUME:
applyAssumeRule(curAssertion);
break;
case VerificationStatement.CHANGE:
// TODO: Add when we have change rule implemented.
break;
// Confirm Assertion
case VerificationStatement.CONFIRM:
applyConfirmRule(curAssertion);
break;
// Code
case VerificationStatement.CODE:
applyCodeRules((Statement) curAssertion.getAssertion());
if (curAssertion.getAssertion() instanceof WhileStmt
|| curAssertion.getAssertion() instanceof IfStmt) {
return;
}
break;
// Remember Assertion
case VerificationStatement.REMEMBER:
applyRememberRule();
break;
// Variable Declaration Assertion
case VerificationStatement.VARIABLE:
applyVarDeclRule(curAssertion);
break;
}
}
}
/**
* <p>Applies the function assignment rule to the
* <code>Statement</code>.</p>
*
* @param stmt Our current <code>FuncAssignStmt</code>.
*/
private void applyEBFuncAssignStmtRule(FuncAssignStmt stmt) {
OperationDec opDec;
PosSymbol qualifier = null;
ProgramExp assignExp = stmt.getAssign();
ProgramParamExp assignParamExp = null;
// Check to see what kind of expression is on the right hand side
if (assignExp instanceof ProgramParamExp) {
// Cast to a ProgramParamExp
assignParamExp = (ProgramParamExp) assignExp;
}
else if (assignExp instanceof ProgramDotExp) {
// Cast to a ProgramParamExp
ProgramDotExp dotExp = (ProgramDotExp) assignExp;
assignParamExp = (ProgramParamExp) dotExp.getExp();
qualifier = dotExp.getQualifier();
}
else {
// TODO: ERROR!
}
// Obtain the corresponding OperationEntry and OperationDec
List<PTType> argTypes = new LinkedList<PTType>();
for (ProgramExp arg : assignParamExp.getArguments()) {
argTypes.add(arg.getProgramType());
}
OperationEntry opEntry =
searchOperation(stmt.getLocation(), qualifier, assignParamExp
.getName(), argTypes);
// Obtain an OperationDec from the OperationEntry
ResolveConceptualElement element = opEntry.getDefiningElement();
if (element instanceof OperationDec) {
opDec = (OperationDec) opEntry.getDefiningElement();
}
else {
FacilityOperationDec fOpDec =
(FacilityOperationDec) opEntry.getDefiningElement();
opDec =
new OperationDec(fOpDec.getName(), fOpDec.getParameters(),
fOpDec.getReturnTy(), fOpDec.getStateVars(), fOpDec
.getRequires(), fOpDec.getEnsures());
}
// Check for recursive call of itself
if (myCurrentOperationEntry.getName().equals(opEntry.getName())
&& myCurrentOperationEntry.getReturnType() != null) {
// Create a new confirm statement using P_val and the decreasing clause
VarExp pVal = createPValExp(myOperationDecreasingExp.getLocation());
// Create a new infix expression
InfixExp exp =
new InfixExp(stmt.getLocation(), Exp
.copy(myOperationDecreasingExp),
createPosSymbol("<"), pVal);
exp.setMathType(BOOLEAN);
// Create the new confirm statement
Location loc;
if (myOperationDecreasingExp.getLocation() != null) {
loc = (Location) myOperationDecreasingExp.getLocation().clone();
}
else {
loc = (Location) stmt.getLocation().clone();
}
loc.setDetails("Show Termination of Recursive Call");
setLocation(exp, loc);
ConfirmStmt conf = new ConfirmStmt(loc, exp);
// Add it to our list of assertions
myCurrentAssertiveCode.addCode(conf);
}
// Get the requires clause for this operation
Exp requires;
if (opDec.getRequires() != null) {
requires = Exp.copy(opDec.getRequires());
}
else {
requires = myTypeGraph.getTrueVarExp();
}
// Replace PreCondition variables in the requires clause
requires =
replaceFormalWithActualReq(requires, opDec.getParameters(),
assignParamExp.getArguments());
// Modify the location of the requires clause and add it to myCurrentAssertiveCode
// Obtain the current location
// Note: If we don't have a location, we create one
Location reqloc;
if (assignParamExp.getName().getLocation() != null) {
reqloc = (Location) assignParamExp.getName().getLocation().clone();
}
else {
reqloc = new Location(null, null);
}
// Append the name of the current procedure
String details = "";
if (myCurrentOperationEntry != null) {
details = " in Procedure " + myCurrentOperationEntry.getName();
}
// Set the details of the current location
reqloc.setDetails("Requires Clause of " + opDec.getName() + details);
setLocation(requires, reqloc);
// Add this to our list of things to confirm
myCurrentAssertiveCode.addConfirm(requires);
// Get the ensures clause for this operation
// Note: If there isn't an ensures clause, it is set to "True"
Exp ensures, opEnsures;
if (opDec.getEnsures() != null) {
opEnsures = Exp.copy(opDec.getEnsures());
// Make sure we have an EqualsExp, else it is an error.
if (opEnsures instanceof EqualsExp) {
// Has to be a VarExp on the left hand side (containing the name
// of the function operation)
if (((EqualsExp) opEnsures).getLeft() instanceof VarExp) {
VarExp leftExp = (VarExp) ((EqualsExp) opEnsures).getLeft();
// Check if it has the name of the operation
if (leftExp.getName().equals(opDec.getName())) {
ensures = ((EqualsExp) opEnsures).getRight();
// Obtain the current location
if (assignParamExp.getName().getLocation() != null) {
// Set the details of the current location
Location loc =
(Location) assignParamExp.getName()
.getLocation().clone();
loc.setDetails("Ensures Clause of "
+ opDec.getName());
setLocation(ensures, loc);
}
// Replace all instances of the variable on the left hand side
// in the ensures clause with the expression on the right.
Exp leftVariable;
// We have a variable inside a record as the variable being assigned.
if (stmt.getVar() instanceof VariableDotExp) {
VariableDotExp v = (VariableDotExp) stmt.getVar();
List<VariableExp> vList = v.getSegments();
edu.clemson.cs.r2jt.collections.List<Exp> newSegments =
new edu.clemson.cs.r2jt.collections.List<Exp>();
// Loot through each variable expression and add it to our dot list
for (VariableExp vr : vList) {
VarExp varExp = new VarExp();
if (vr instanceof VariableNameExp) {
varExp.setName(((VariableNameExp) vr)
.getName());
varExp.setMathType(vr.getMathType());
varExp.setMathTypeValue(vr
.getMathTypeValue());
newSegments.add(varExp);
}
}
// Expression to be replaced
leftVariable =
new DotExp(v.getLocation(), newSegments,
null);
leftVariable.setMathType(v.getMathType());
leftVariable.setMathTypeValue(v.getMathTypeValue());
}
// We have a regular variable being assigned.
else {
// Expression to be replaced
VariableNameExp v = (VariableNameExp) stmt.getVar();
leftVariable =
new VarExp(v.getLocation(), null, v
.getName());
leftVariable.setMathType(v.getMathType());
leftVariable.setMathTypeValue(v.getMathTypeValue());
}
// Replace all instances of the left hand side
// variable in the current final confirm statement.
Exp newConf = myCurrentAssertiveCode.getFinalConfirm();
newConf = replace(newConf, leftVariable, ensures);
// Replace the formals with the actuals.
newConf =
replaceFormalWithActualEns(newConf, opDec
.getParameters(), opDec.getStateVars(),
assignParamExp.getArguments(), false);
// Set this as our new final confirm statement.
myCurrentAssertiveCode.setFinalConfirm(newConf);
}
else {
illegalOperationEnsures(opDec.getLocation());
}
}
else {
illegalOperationEnsures(opDec.getLocation());
}
}
else {
illegalOperationEnsures(opDec.getLocation());
}
}
// Verbose Mode Debug Messages
myVCBuffer.append("\nFunction Rule Applied: \n");
myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
/**
* <p>Applies the swap statement rule to the
* <code>Statement</code>.</p>
*
* @param stmt Our current <code>SwapStmt</code>.
*/
private void applyEBSwapStmtRule(SwapStmt stmt) {
// Obtain the current final confirm clause
Exp conf = myCurrentAssertiveCode.getFinalConfirm();
// Create a copy of the left and right hand side
VariableExp stmtLeft = (VariableExp) Exp.copy(stmt.getLeft());
VariableExp stmtRight = (VariableExp) Exp.copy(stmt.getRight());
// New left and right
Exp newLeft = convertExp(stmtLeft);
Exp newRight = convertExp(stmtRight);
// Use our final confirm to obtain the math types
List lst = conf.getSubExpressions();
for (int i = 0; i < lst.size(); i++) {
if (lst.get(i) instanceof VarExp) {
VarExp thisExp = (VarExp) lst.get(i);
if (newRight instanceof VarExp) {
if (thisExp.getName().equals(
((VarExp) newRight).getName().getName())) {
newRight.setMathType(thisExp.getMathType());
newRight.setMathTypeValue(thisExp.getMathTypeValue());
}
}
if (newLeft instanceof VarExp) {
if (thisExp.getName().equals(
((VarExp) newLeft).getName().getName())) {
newLeft.setMathType(thisExp.getMathType());
newLeft.setMathTypeValue(thisExp.getMathTypeValue());
}
}
}
}
// Temp variable
VarExp tmp = new VarExp();
tmp.setName(createPosSymbol("_" + getVarName(stmtLeft).getName()));
tmp.setMathType(stmtLeft.getMathType());
tmp.setMathTypeValue(stmtLeft.getMathTypeValue());
// Replace according to the swap rule
conf = replace(conf, newRight, tmp);
conf = replace(conf, newLeft, newRight);
conf = replace(conf, tmp, newLeft);
// Set this new expression as the new final confirm
myCurrentAssertiveCode.setFinalConfirm(conf);
// Verbose Mode Debug Messages
myVCBuffer.append("\nSwap Rule Applied: \n");
myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
/**
* <p>Applies the procedure declaration rule.</p>
*
* @param requires Requires clause
* @param ensures Ensures clause
* @param decreasing Decreasing clause (if any)
* @param variableList List of all variables for this procedure
* @param statementList List of statements for this procedure
*/
private void applyProcedureDeclRule(Exp requires, Exp ensures,
Exp decreasing, List<VarDec> variableList,
List<Statement> statementList) {
// Add the global requires clause
if (myGlobalRequiresExp != null) {
myCurrentAssertiveCode.addAssume(myGlobalRequiresExp);
}
// Add the global constraints
if (myGlobalConstraintExp != null) {
myCurrentAssertiveCode.addAssume(myGlobalConstraintExp);
}
// Add the requires clause
if (requires != null) {
myCurrentAssertiveCode.addAssume(requires);
}
// Add the remember rule
myCurrentAssertiveCode.addRemember();
// Add declared variables into the assertion. Also add
// them to the list of free variables.
myCurrentAssertiveCode.addVariableDecs(variableList);
addVarDecsAsFreeVars(variableList);
// Check to see if we have a recursive procedure.
// If yes, we will need to create an additional assume clause
// (P_val = (decreasing clause)) in our list of assertions.
if (decreasing != null) {
// Store for future use
myOperationDecreasingExp = decreasing;
// Add P_val as a free variable
VarExp pVal = createPValExp(decreasing.getLocation());
myCurrentAssertiveCode.addFreeVar(pVal);
// Create an equals expression
EqualsExp equalsExp =
new EqualsExp(null, pVal, EqualsExp.EQUAL, Exp
.copy(decreasing));
equalsExp.setMathType(BOOLEAN);
Location eqLoc = (Location) decreasing.getLocation().clone();
eqLoc.setDetails("Progress Metric for Recursive Procedure");
setLocation(equalsExp, eqLoc);
// Add it to our things to assume
myCurrentAssertiveCode.addAssume(equalsExp);
}
// Add the list of statements
myCurrentAssertiveCode.addStatements(statementList);
// Add the final confirms clause
myCurrentAssertiveCode.setFinalConfirm(ensures);
// Verbose Mode Debug Messages
myVCBuffer.append("\nProcedure Declaration Rule Applied: \n");
myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
/**
* <p>Applies the remember rule.</p>
*/
private void applyRememberRule() {
// Obtain the final confirm and apply the remember method for Exp
Exp conf = myCurrentAssertiveCode.getFinalConfirm();
conf = conf.remember();
myCurrentAssertiveCode.setFinalConfirm(conf);
// Verbose Mode Debug Messages
myVCBuffer.append("\nRemember Rule Applied: \n");
myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
/**
* <p>Applies the variable declaration rule.</p>
*
* @param var A declared variable stored as a
* <code>VerificationStatement</code>
*/
private void applyVarDeclRule(VerificationStatement var) {
// Obtain the variable from the verification statement
VarDec varDec = (VarDec) var.getAssertion();
ProgramTypeEntry typeEntry;
// Ty is NameTy
if (varDec.getTy() instanceof NameTy) {
NameTy pNameTy = (NameTy) varDec.getTy();
// Query for the type entry in the symbol table
typeEntry =
searchProgramType(pNameTy.getLocation(), pNameTy.getName());
// Obtain the original dec from the AST
TypeDec type = (TypeDec) typeEntry.getDefiningElement();
// Deep copy the original initialization ensures
Exp init = Exp.copy(type.getInitialization().getEnsures());
// Create an is_initial dot expression
DotExp isInitialExp = createInitExp(varDec, init);
if (init.getLocation() != null) {
Location loc = (Location) init.getLocation().clone();
loc.setDetails("Initial Value for "
+ varDec.getName().getName());
setLocation(isInitialExp, loc);
}
// Make sure we have a constraint
Exp constraint;
if (type.getConstraint() == null) {
constraint = myTypeGraph.getTrueVarExp();
}
else {
constraint = Exp.copy(type.getConstraint());
}
// Set the location for the constraint
Location loc;
if (constraint.getLocation() != null) {
loc = (Location) constraint.getLocation().clone();
}
else {
loc = (Location) type.getLocation().clone();
}
loc.setDetails("Constraints on " + varDec.getName().getName());
setLocation(constraint, loc);
// Check if our initialization ensures clause is
// in simple form.
if (isInitEnsuresSimpleForm(init, varDec.getName())) {
// Only deal with initialization ensures of the
// form left = right
if (init instanceof EqualsExp) {
EqualsExp exp = (EqualsExp) init;
// If the initialization of the variable sets
// the variable equal to a value, then we need
// replace the formal with the actual.
if (exp.getLeft() instanceof VarExp) {
PosSymbol exemplar = type.getExemplar();
// TODO: Figure out this evil dragon!
}
}
}
// We must have a complex initialization ensures clause
else {
// The variable must be a variable dot expression,
// therefore we will need to extract the name.
String varName = varDec.getName().getName();
int dotIndex = varName.indexOf(".");
if (dotIndex > 0)
varName = varName.substring(0, dotIndex);
// Check if our confirm clause uses this variable
Exp finalConfirm = myCurrentAssertiveCode.getFinalConfirm();
if (finalConfirm.containsVar(varName, false)) {
// We don't have any constraints, so the initialization
// clause implies the final confirm statement and
// set this as our new final confirm statement.
if (constraint.equals(myTypeGraph.getTrueVarExp())) {
myCurrentAssertiveCode.setFinalConfirm(myTypeGraph.formImplies(
init, finalConfirm));
}
// We actually have a constraint, so both the initialization
// and constraint imply the final confirm statement.
// This then becomes our new final confirm statement.
else {
InfixExp exp =
myTypeGraph.formConjunct(constraint, init);
myCurrentAssertiveCode.setFinalConfirm(myTypeGraph.formImplies(
exp, finalConfirm));
}
}
// Verbose Mode Debug Messages
myVCBuffer.append("\nVariable Declaration Rule Applied: \n");
myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
}
else {
// Ty not handled.
tyNotHandled(varDec.getTy(), varDec.getLocation());
}
}
} | src/main/java/edu/clemson/cs/r2jt/vcgeneration/VCGenerator.java | /**
* VCGenerator.java
* ---------------------------------
* Copyright (c) 2014
* RESOLVE Software Research Group
* School of Computing
* Clemson University
* All rights reserved.
* ---------------------------------
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
package edu.clemson.cs.r2jt.vcgeneration;
/*
* Libraries
*/
import edu.clemson.cs.r2jt.absyn.*;
import edu.clemson.cs.r2jt.data.*;
import edu.clemson.cs.r2jt.init.CompileEnvironment;
import edu.clemson.cs.r2jt.proving2.VC;
import edu.clemson.cs.r2jt.treewalk.TreeWalkerVisitor;
import edu.clemson.cs.r2jt.typeandpopulate.*;
import edu.clemson.cs.r2jt.typeandpopulate.entry.*;
import edu.clemson.cs.r2jt.typeandpopulate.MathSymbolTable.FacilityStrategy;
import edu.clemson.cs.r2jt.typeandpopulate.MathSymbolTable.ImportStrategy;
import edu.clemson.cs.r2jt.typeandpopulate.programtypes.PTType;
import edu.clemson.cs.r2jt.typeandpopulate.query.NameQuery;
import edu.clemson.cs.r2jt.typeandpopulate.query.OperationQuery;
import edu.clemson.cs.r2jt.typeandpopulate.query.UnqualifiedNameQuery;
import edu.clemson.cs.r2jt.typereasoning.TypeGraph;
import edu.clemson.cs.r2jt.utilities.Flag;
import edu.clemson.cs.r2jt.utilities.FlagDependencies;
import edu.clemson.cs.r2jt.utilities.SourceErrorException;
import java.io.File;
import java.util.*;
import java.util.List;
import java.util.Stack;
/**
* TODO: Write a description of this module
*/
public class VCGenerator extends TreeWalkerVisitor {
// ===========================================================
// Global Variables
// ===========================================================
// Symbol table related items
private final MathSymbolTableBuilder mySymbolTable;
private final TypeGraph myTypeGraph;
private final MTType BOOLEAN;
private final MTType MTYPE;
private final MTType Z;
private ModuleScope myCurrentModuleScope;
// Module level global variables
private Exp myGlobalRequiresExp;
private Exp myGlobalConstraintExp;
// Operation/Procedure level global variables
private OperationEntry myCurrentOperationEntry;
private Exp myOperationDecreasingExp;
/**
* <p>The current assertion we are applying
* VC rules to.</p>
*/
private AssertiveCode myAssertion;
/**
* <p>A stack to keep track of the RESOLVE Conceptual Elements
* we are still visiting and generating VCs for.</p>
*/
private Stack<ResolveConceptualElement> myCurrentVisitingStack;
/**
* <p>The current compile environment used throughout
* the compiler.</p>
*/
private CompileEnvironment myInstanceEnvironment;
/**
* <p>A list that will be built up with <code>AssertiveCode</code>
* objects, each representing a VC or group of VCs that must be
* satisfied to verify a parsed program.</p>
*/
private Collection<AssertiveCode> myFinalAssertiveCode;
/**
* <p>This object creates the different VC outputs.</p>
*/
private OutputVCs myOutputGenerator;
/**
* <p>This string buffer holds all the steps
* the VC generator takes to generate VCs.</p>
*/
private StringBuffer myVCBuffer;
// ===========================================================
// Flag Strings
// ===========================================================
private static final String FLAG_ALTSECTION_NAME = "GenerateVCs";
private static final String FLAG_DESC_ATLVERIFY_VC = "Generate VCs.";
private static final String FLAG_DESC_ATTLISTVCS_VC = "";
// ===========================================================
// Flags
// ===========================================================
public static final Flag FLAG_ALTVERIFY_VC =
new Flag(FLAG_ALTSECTION_NAME, "altVCs", FLAG_DESC_ATLVERIFY_VC);
public static final Flag FLAG_ALTLISTVCS_VC =
new Flag(FLAG_ALTSECTION_NAME, "altListVCs",
FLAG_DESC_ATTLISTVCS_VC, Flag.Type.HIDDEN);
public static final void setUpFlags() {
FlagDependencies.addImplies(FLAG_ALTVERIFY_VC, FLAG_ALTLISTVCS_VC);
}
// ===========================================================
// Constructors
// ===========================================================
public VCGenerator(ScopeRepository table, final CompileEnvironment env) {
// Symbol table items
mySymbolTable = (MathSymbolTableBuilder) table;
myTypeGraph = mySymbolTable.getTypeGraph();
BOOLEAN = myTypeGraph.BOOLEAN;
MTYPE = myTypeGraph.MTYPE;
Z = myTypeGraph.Z;
// Current items
myCurrentModuleScope = null;
myCurrentOperationEntry = null;
myCurrentVisitingStack = new Stack<ResolveConceptualElement>();
myGlobalConstraintExp = null;
myGlobalRequiresExp = null;
myOperationDecreasingExp = null;
// Instance Environment
myInstanceEnvironment = env;
// VCs + Debugging String
myAssertion = null;
myFinalAssertiveCode = new LinkedList<AssertiveCode>();
myOutputGenerator = null;
myVCBuffer = new StringBuffer();
}
// ===========================================================
// Visitor Methods
// ===========================================================
// -----------------------------------------------------------
// ConceptBodyModuleDec
// -----------------------------------------------------------
@Override
public void preConceptBodyModuleDec(ConceptBodyModuleDec dec) {
// Verbose Mode Debug Messages
myVCBuffer.append("\n=========================");
myVCBuffer.append(" VC Generation Details ");
myVCBuffer.append(" =========================\n");
myVCBuffer.append("\n Concept Realization Name:\t");
myVCBuffer.append(dec.getName().getName());
myVCBuffer.append("\n Concept Name:\t");
myVCBuffer.append(dec.getConceptName().getName());
myVCBuffer.append("\n");
myVCBuffer.append("\n====================================");
myVCBuffer.append("======================================\n");
myVCBuffer.append("\n");
// Set the current module scope
try {
myCurrentModuleScope =
mySymbolTable.getModuleScope(new ModuleIdentifier(dec));
// Store the current visiting item into the stack
myCurrentVisitingStack.push(dec);
// From the list of imports, obtain the global constraints
// of the imported modules.
myGlobalConstraintExp =
getConstraints(dec.getLocation(), myCurrentModuleScope
.getImports());
// Store the global requires clause
myGlobalRequiresExp = getRequiresClause(dec);
}
catch (NoSuchSymbolException e) {
System.err.println("Module " + dec.getName()
+ " does not exist or is not in scope.");
noSuchModule(dec.getLocation());
}
}
@Override
public void postConceptBodyModuleDec(ConceptBodyModuleDec dec) {
// Set the module level global variables to null
myCurrentModuleScope = null;
myGlobalConstraintExp = null;
myGlobalRequiresExp = null;
// Pop the top most item from the Stack
// Note: Must be us since we always push in a pre and
// pop in a post.
myCurrentVisitingStack.pop();
}
// -----------------------------------------------------------
// EnhancementBodyModuleDec
// -----------------------------------------------------------
@Override
public void preEnhancementBodyModuleDec(EnhancementBodyModuleDec dec) {
// Verbose Mode Debug Messages
myVCBuffer.append("\n=========================");
myVCBuffer.append(" VC Generation Details ");
myVCBuffer.append(" =========================\n");
myVCBuffer.append("\n Enhancement Realization Name:\t");
myVCBuffer.append(dec.getName().getName());
myVCBuffer.append("\n Enhancement Name:\t");
myVCBuffer.append(dec.getEnhancementName().getName());
myVCBuffer.append("\n Concept Name:\t");
myVCBuffer.append(dec.getConceptName().getName());
myVCBuffer.append("\n");
myVCBuffer.append("\n====================================");
myVCBuffer.append("======================================\n");
myVCBuffer.append("\n");
// Set the current module scope
try {
myCurrentModuleScope =
mySymbolTable.getModuleScope(new ModuleIdentifier(dec));
// Store the current visiting item into the stack
myCurrentVisitingStack.push(dec);
// From the list of imports, obtain the global constraints
// of the imported modules.
myGlobalConstraintExp =
getConstraints(dec.getLocation(), myCurrentModuleScope
.getImports());
// Store the global requires clause
myGlobalRequiresExp = getRequiresClause(dec);
}
catch (NoSuchSymbolException e) {
System.err.println("Module " + dec.getName()
+ " does not exist or is not in scope.");
noSuchModule(dec.getLocation());
}
}
@Override
public void postEnhancementBodyModuleDec(EnhancementBodyModuleDec dec) {
// Set the module level global variables to null
myCurrentModuleScope = null;
myGlobalConstraintExp = null;
myGlobalRequiresExp = null;
// Pop the top most item from the Stack
// Note: Must be us since we always push in a pre and
// pop in a post.
myCurrentVisitingStack.pop();
}
// -----------------------------------------------------------
// FacilityModuleDec
// -----------------------------------------------------------
@Override
public void preFacilityModuleDec(FacilityModuleDec dec) {
// Verbose Mode Debug Messages
myVCBuffer.append("\n=========================");
myVCBuffer.append(" VC Generation Details ");
myVCBuffer.append(" =========================\n");
myVCBuffer.append("\n Facility Name:\t");
myVCBuffer.append(dec.getName().getName());
myVCBuffer.append("\n");
myVCBuffer.append("\n====================================");
myVCBuffer.append("======================================\n");
myVCBuffer.append("\n");
// Set the current module scope
try {
myCurrentModuleScope =
mySymbolTable.getModuleScope(new ModuleIdentifier(dec));
// Store the current visiting item into the stack
myCurrentVisitingStack.push(dec);
// From the list of imports, obtain the global constraints
// of the imported modules.
myGlobalConstraintExp =
getConstraints(dec.getLocation(), myCurrentModuleScope
.getImports());
// Store the global requires clause
myGlobalRequiresExp = getRequiresClause(dec);
}
catch (NoSuchSymbolException e) {
System.err.println("Module " + dec.getName()
+ " does not exist or is not in scope.");
noSuchModule(dec.getLocation());
}
}
@Override
public void postFacilityModuleDec(FacilityModuleDec dec) {
// Set the module level global variables to null
myCurrentModuleScope = null;
myGlobalConstraintExp = null;
myGlobalRequiresExp = null;
// Pop the top most item from the Stack
// Note: Must be us since we always push in a pre and
// pop in a post.
myCurrentVisitingStack.pop();
}
// -----------------------------------------------------------
// FacilityOperationDec
// -----------------------------------------------------------
@Override
public void preFacilityOperationDec(FacilityOperationDec dec) {
// Keep the current operation dec
List<PTType> argTypes = new LinkedList<PTType>();
for (ParameterVarDec p : dec.getParameters()) {
argTypes.add(p.getTy().getProgramTypeValue());
}
myCurrentOperationEntry =
searchOperation(dec.getLocation(), null, dec.getName(),
argTypes);
// Store the current visiting item into the stack
myCurrentVisitingStack.push(dec);
}
@Override
public void postFacilityOperationDec(FacilityOperationDec dec) {
// Create assertive code
myAssertion = new AssertiveCode(myInstanceEnvironment);
// Verbose Mode Debug Messages
myVCBuffer.append("\n=========================");
myVCBuffer.append(" Procedure: ");
myVCBuffer.append(dec.getName().getName());
myVCBuffer.append(" =========================\n");
// Obtains items from the current operation
Location loc = dec.getLocation();
String name = dec.getName().getName();
Exp requires = modifyRequiresClause(getRequiresClause(dec), loc, name);
Exp ensures = modifyEnsuresClause(getEnsuresClause(dec), loc, name);
List<Statement> statementList = dec.getStatements();
List<VarDec> variableList = dec.getAllVariables();
Exp decreasing = dec.getDecreasing();
// Apply the procedure declaration rule
applyProcedureDeclRule(requires, ensures, decreasing, variableList,
statementList);
// Apply proof rules
applyEBRules();
myOperationDecreasingExp = null;
myCurrentOperationEntry = null;
myFinalAssertiveCode.add(myAssertion);
myAssertion = null;
// Pop the top most item from the Stack
// Note: Must be us since we always push in a pre and
// pop in a post.
myCurrentVisitingStack.pop();
}
// -----------------------------------------------------------
// ModuleDec
// -----------------------------------------------------------
@Override
public void postModuleDec(ModuleDec dec) {
// Make sure that our stack of visiting items is 0.
if (myCurrentVisitingStack.isEmpty()) {
// Create the output generator and finalize output
myOutputGenerator =
new OutputVCs(myInstanceEnvironment, myFinalAssertiveCode,
myVCBuffer);
// Print to file if we are in debug mode
// TODO: Add debug flag here
String filename;
if (myInstanceEnvironment.getOutputFilename() != null) {
filename = myInstanceEnvironment.getOutputFilename();
}
else {
filename = createVCFileName();
}
myOutputGenerator.outputToFile(filename);
}
else {
incorrectVisit(dec.getName(), dec.getLocation());
}
}
// -----------------------------------------------------------
// ProcedureDec
// -----------------------------------------------------------
@Override
public void postProcedureDec(ProcedureDec dec) {}
// ===========================================================
// Public Methods
// ===========================================================
// -----------------------------------------------------------
// Error Handling
// -----------------------------------------------------------
public void expNotHandled(Exp exp, Location l) {
String message = "Exp not handled: " + exp.toString();
throw new SourceErrorException(message, l);
}
public void illegalOperationEnsures(Location l) {
// TODO: Move this to sanity check.
String message =
"Ensures clauses of operations that return a value should be of the form <OperationName> = <value>";
throw new SourceErrorException(message, l);
}
public void incorrectVisit(PosSymbol name, Location l) {
String message =
"After visiting all elements in ModuleDec: " + name
+ ", our stack of visiting items is not empty!";
throw new SourceErrorException(message, l);
}
public void notAType(SymbolTableEntry entry, Location l) {
throw new SourceErrorException(entry.getSourceModuleIdentifier()
.fullyQualifiedRepresentation(entry.getName())
+ " is not known to be a type.", l);
}
public void notInFreeVarList(PosSymbol name, Location l) {
String message =
"State variable " + name + " not in free variable list";
throw new SourceErrorException(message, l);
}
public void noSuchModule(Location location) {
throw new SourceErrorException(
"Module does not exist or is not in scope.", location);
}
public void noSuchSymbol(PosSymbol qualifier, String symbolName, Location l) {
String message;
if (qualifier == null) {
message = "No such symbol: " + symbolName;
}
else {
message =
"No such symbol in module: " + qualifier.getName() + "."
+ symbolName;
}
throw new SourceErrorException(message, l);
}
public void tyNotHandled(Ty ty, Location location) {
String message = "Ty not handled: " + ty.toString();
throw new SourceErrorException(message, location);
}
// -----------------------------------------------------------
// Prover Mode
// -----------------------------------------------------------
/**
* <p>The set of immmutable VCs that the in house provers can use.</p>
*
* @return VCs to be proved.
*/
public List<VC> proverOutput() {
return myOutputGenerator.getProverOutput();
}
// ===========================================================
// Private Methods
// ===========================================================
/**
* <p>Loop through the list of <code>VarDec</code>, search
* for their corresponding <code>ProgramVariableEntry</code>
* and add the result to the list of free variables.</p>
*
* @param variableList List of the all variables as
* <code>VarDec</code>.
*/
public void addVarDecsAsFreeVars(List<VarDec> variableList) {
// Loop through the variable list
for (VarDec v : variableList) {
myAssertion.addFreeVar(createVarExp(v.getLocation(), v.getName(), v
.getTy().getMathTypeValue()));
}
}
/**
* <p>Converts the different types of <code>Exp</code> to the
* ones used by the VC Generator.</p>
*
* @param oldExp The expression to be converted.
*
* @return An <code>Exp</code>.
*/
private Exp convertExp(Exp oldExp) {
// Case #1: ProgramIntegerExp
if (oldExp instanceof ProgramIntegerExp) {
IntegerExp exp = new IntegerExp();
exp.setValue(((ProgramIntegerExp) oldExp).getValue());
exp.setMathType(Z);
return exp;
}
// Case #2: VariableDotExp
else if (oldExp instanceof VariableDotExp) {
DotExp exp = new DotExp();
List<VariableExp> segments =
((VariableDotExp) oldExp).getSegments();
edu.clemson.cs.r2jt.collections.List<Exp> newSegments =
new edu.clemson.cs.r2jt.collections.List<Exp>();
// Need to replace each of the segments in a dot expression
MTType lastMathType = null;
MTType lastMathTypeValue = null;
for (VariableExp v : segments) {
VarExp varExp = new VarExp();
// Can only be a VariableNameExp. Anything else
// is a case we have not handled.
if (v instanceof VariableNameExp) {
varExp.setName(((VariableNameExp) v).getName());
lastMathType = v.getMathType();
lastMathTypeValue = v.getMathTypeValue();
newSegments.add(varExp);
}
else {
expNotHandled(v, v.getLocation());
}
}
// Set the segments and the type information.
exp.setSegments(newSegments);
exp.setMathType(lastMathType);
exp.setMathTypeValue(lastMathTypeValue);
return exp;
}
// Case #3: VariableNameExp
else if (oldExp instanceof VariableNameExp) {
VarExp exp = new VarExp();
exp.setName(((VariableNameExp) oldExp).getName());
exp.setMathType(oldExp.getMathType());
exp.setMathTypeValue(oldExp.getMathTypeValue());
return exp;
}
return oldExp;
}
/**
* <p>Returns a newly created <code>PosSymbol</code>
* with the string provided.</p>
*
* @param name String of the new <code>PosSymbol</code>.
*
* @return The new <code>PosSymbol</code>.
*/
private PosSymbol createPosSymbol(String name) {
// Create the PosSymbol
PosSymbol posSym = new PosSymbol();
posSym.setSymbol(Symbol.symbol(name));
return posSym;
}
/**
* <p>Returns an <code>DotExp</code> with the <code>VarDec</code>
* and its initialization ensures clause.</p>
*
* @param var The declared variable.
* @param initExp The initialization ensures of the variable.
*
* @return The new <code>DotExp</code>.
*/
private DotExp createInitExp(VarDec var, Exp initExp) {
// Convert the declared variable into a VarExp
VarExp varExp =
createVarExp(var.getLocation(), var.getName(), var.getTy()
.getMathTypeValue());
// Left hand side of the expression
VarExp left = null;
// NameTy
if (var.getTy() instanceof NameTy) {
NameTy ty = (NameTy) var.getTy();
left = createVarExp(ty.getLocation(), ty.getName(), MTYPE);
}
else {
tyNotHandled(var.getTy(), var.getTy().getLocation());
}
// Complicated steps to construct the argument list
// YS: No idea why it is so complicated!
edu.clemson.cs.r2jt.collections.List<Exp> expList =
new edu.clemson.cs.r2jt.collections.List<Exp>();
expList.add(varExp);
FunctionArgList argList = new FunctionArgList();
argList.setArguments(expList);
edu.clemson.cs.r2jt.collections.List<FunctionArgList> functionArgLists =
new edu.clemson.cs.r2jt.collections.List<FunctionArgList>();
functionArgLists.add(argList);
// Right hand side of the expression
FunctionExp right =
new FunctionExp(var.getLocation(), null,
createPosSymbol("is_initial"), null, functionArgLists);
right.setMathType(BOOLEAN);
// Create the DotExp
edu.clemson.cs.r2jt.collections.List<Exp> exps =
new edu.clemson.cs.r2jt.collections.List<Exp>();
exps.add(left);
exps.add(right);
DotExp exp = new DotExp(var.getLocation(), exps, null);
exp.setMathType(BOOLEAN);
return exp;
}
/**
* <p>Creates a variable expression with the name
* "P_val" and has type "N".</p>
*
* @param location Location that wants to create
* this variable.
*
* @return The created <code>VarExp</code>.
*/
private VarExp createPValExp(Location location) {
// Locate "N" (Natural Number)
MathSymbolEntry mse = searchMathSymbol(location, "N");
try {
// Create a variable with the name P_val
return createVarExp(location, createPosSymbol("P_val"), mse
.getTypeValue());
}
catch (SymbolNotOfKindTypeException e) {
notAType(mse, location);
}
return null;
}
/**
* <p>Create a question mark variable with the oldVar
* passed in.</p>
*
* @param exp The full expression clause.
* @param oldVar The old variable expression.
*
* @return A new variable with the question mark in <code>VarExp</code> form.
*/
private VarExp createQuestionMarkVariable(Exp exp, VarExp oldVar) {
// Add an extra question mark to the front of oldVar
VarExp newOldVar =
new VarExp(null, null, createPosSymbol("?"
+ oldVar.getName().getName()));
newOldVar.setMathType(oldVar.getMathType());
newOldVar.setMathTypeValue(oldVar.getMathTypeValue());
// Applies the question mark to oldVar if it is our first time visiting.
if (exp.containsVar(oldVar.getName().getName(), false)) {
return createQuestionMarkVariable(exp, newOldVar);
}
// Don't need to apply the question mark here.
else if (exp.containsVar(newOldVar.getName().toString(), false)) {
return createQuestionMarkVariable(exp, newOldVar);
}
else {
// Return the new variable expression with the question mark
if (oldVar.getName().getName().charAt(0) != '?') {
return newOldVar;
}
}
// Return our old self.
return oldVar;
}
/**
* <p>Returns a newly created <code>VarExp</code>
* with the <code>PosSymbol</code> and math type provided.</p>
*
* @param loc Location of the new <code>VarExp</code>
* @param name <code>PosSymbol</code> of the new <code>VarExp</code>.
* @param type Math type of the new <code>VarExp</code>.
*
* @return The new <code>VarExp</code>.
*/
private VarExp createVarExp(Location loc, PosSymbol name, MTType type) {
// Create the VarExp
VarExp exp = new VarExp(loc, null, name);
exp.setMathType(type);
return exp;
}
/**
* <p>Creates the name of the output file.</p>
*
* @return Name of the file
*/
private String createVCFileName() {
File file = myInstanceEnvironment.getTargetFile();
ModuleID cid = myInstanceEnvironment.getModuleID(file);
file = myInstanceEnvironment.getFile(cid);
String filename = file.toString();
int temp = filename.indexOf(".");
String tempfile = filename.substring(0, temp);
String mainFileName;
mainFileName = tempfile + ".asrt_new";
return mainFileName;
}
/**
* <p>Returns all the constraint clauses combined together for the
* for the current <code>ModuleDec</code>.</p>
*
* @param loc The location of the <code>ModuleDec</code>.
* @param imports The list of imported modules.
*
* @return The constraint clause <code>Exp</code>.
*/
private Exp getConstraints(Location loc, List<ModuleIdentifier> imports) {
Exp retExp = null;
// Loop
for (ModuleIdentifier mi : imports) {
try {
ModuleDec dec =
mySymbolTable.getModuleScope(mi).getDefiningElement();
List<Exp> contraintExpList = null;
// Handling for facility imports
if (dec instanceof ShortFacilityModuleDec) {
FacilityDec facDec =
((ShortFacilityModuleDec) dec).getDec();
dec =
mySymbolTable.getModuleScope(
new ModuleIdentifier(facDec
.getConceptName().getName()))
.getDefiningElement();
}
if (dec instanceof ConceptModuleDec) {
contraintExpList =
((ConceptModuleDec) dec).getConstraints();
// Copy all the constraints
for (Exp e : contraintExpList) {
// Deep copy and set the location detail
Exp constraint = Exp.copy(e);
if (constraint.getLocation() != null) {
Location theLoc = constraint.getLocation();
theLoc.setDetails("Constraint of Module: "
+ dec.getName());
setLocation(constraint, theLoc);
}
// Form conjunct if needed.
if (retExp == null) {
retExp = Exp.copy(e);
}
else {
retExp =
myTypeGraph.formConjunct(retExp, Exp
.copy(e));
}
}
}
}
catch (NoSuchSymbolException e) {
System.err.println("Module " + mi.toString()
+ " does not exist or is not in scope.");
noSuchModule(loc);
}
}
return retExp;
}
/**
* <p>Returns the ensures clause for the current <code>Dec</code>.</p>
*
* @param dec The corresponding <code>Dec</code>.
*
* @return The ensures clause <code>Exp</code>.
*/
private Exp getEnsuresClause(Dec dec) {
PosSymbol name = dec.getName();
Exp ensures = null;
Exp retExp = null;
// Check for each kind of ModuleDec possible
if (dec instanceof FacilityOperationDec) {
ensures = ((FacilityOperationDec) dec).getEnsures();
}
else if (dec instanceof OperationDec) {
ensures = ((OperationDec) dec).getEnsures();
}
// Deep copy and fill in the details of this location
if (ensures != null) {
retExp = Exp.copy(ensures);
if (retExp.getLocation() != null) {
Location myLoc = retExp.getLocation();
myLoc.setDetails("Ensures Clause of " + name);
setLocation(retExp, myLoc);
}
}
return retExp;
}
/**
* <p>Returns the requires clause for the current <code>Dec</code>.</p>
*
* @param dec The corresponding <code>Dec</code>.
*
* @return The requires clause <code>Exp</code>.
*/
private Exp getRequiresClause(Dec dec) {
PosSymbol name = dec.getName();
Exp requires = null;
Exp retExp = null;
// Check for each kind of ModuleDec possible
if (dec instanceof FacilityOperationDec) {
requires = ((FacilityOperationDec) dec).getRequires();
}
else if (dec instanceof OperationDec) {
requires = ((OperationDec) dec).getRequires();
}
else if (dec instanceof ConceptModuleDec) {
requires = ((ConceptModuleDec) dec).getRequirement();
}
else if (dec instanceof ConceptBodyModuleDec) {
requires = ((ConceptBodyModuleDec) dec).getRequires();
}
else if (dec instanceof EnhancementModuleDec) {
requires = ((EnhancementModuleDec) dec).getRequirement();
}
else if (dec instanceof EnhancementBodyModuleDec) {
requires = ((EnhancementBodyModuleDec) dec).getRequires();
}
else if (dec instanceof FacilityModuleDec) {
requires = ((FacilityModuleDec) dec).getRequirement();
}
// Deep copy and fill in the details of this location
if (requires != null) {
retExp = Exp.copy(requires);
if (retExp.getLocation() != null) {
Location myLoc = retExp.getLocation();
myLoc.setDetails("Requires Clause for " + name);
setLocation(retExp, myLoc);
}
}
return retExp;
}
/**
* <p>Get the <code>PosSymbol</code> associated with the
* <code>VariableExp</code> left.</p>
*
* @param left The variable expression.
*
* @return The <code>PosSymbol</code> of left.
*/
private PosSymbol getVarName(VariableExp left) {
// Return value
PosSymbol name;
// Variable Name Expression
if (left instanceof VariableNameExp) {
name = ((VariableNameExp) left).getName();
}
// Variable Dot Expression
else if (left instanceof VariableDotExp) {
VariableRecordExp varRecExp =
(VariableRecordExp) ((VariableDotExp) left)
.getSemanticExp();
name = varRecExp.getName();
}
// Variable Record Expression
else if (left instanceof VariableRecordExp) {
VariableRecordExp varRecExp = (VariableRecordExp) left;
name = varRecExp.getName();
}
//
// Creates an expression with "false" as its name
else {
name = createPosSymbol("false");
}
return name;
}
/**
* <p>Checks to see if the initialization ensures clause
* passed is in the simple form where one side has a
* <code>VarExp</code>.</p>
*
* @param initEnsures The initialization ensures clause,
* or part of it that we are currently
* checking.
* @param name The name of the variable we are checking.
*
* @return True/False
*/
private boolean isInitEnsuresSimpleForm(Exp initEnsures, PosSymbol name) {
boolean isSimple = false;
// Case #1: EqualExp in initEnsures
if (initEnsures instanceof EqualsExp) {
EqualsExp exp = (EqualsExp) initEnsures;
// Recursively call this on the left and
// right hand side. Only one of the sides
// needs to be a VarExp.
if (isInitEnsuresSimpleForm(exp.getLeft(), name)
|| isInitEnsuresSimpleForm(exp.getRight(), name)) {
isSimple = true;
}
}
// Case #2: InfixExp in initEnsures
else if (initEnsures instanceof InfixExp) {
InfixExp exp = (InfixExp) initEnsures;
// Only check if we have an "and" expression
if (exp.getOpName().equals("and")) {
// Recursively call this on the left and
// right hand side. Both sides need to be
// a VarExp.
if (isInitEnsuresSimpleForm(exp.getLeft(), name)
&& isInitEnsuresSimpleForm(exp.getRight(), name)) {
isSimple = true;
}
}
}
// Case #3: VarExp = initEnsures
else if (initEnsures instanceof VarExp) {
VarExp exp = (VarExp) initEnsures;
// Check to see if the name matches the initEnsures
if (exp.getName().equals(name.getName())) {
isSimple = true;
}
}
return isSimple;
}
/**
* <p>Checks to see if the expression passed in is a
* verification variable or not. A verification variable
* is either "P_val" or starts with "?".</p>
*
* @param name Expression that we want to check
*
* @return True/False
*/
private boolean isVerificationVar(Exp name) {
// VarExp
if (name instanceof VarExp) {
String strName = ((VarExp) name).getName().getName();
// Case #1: Question mark variables
if (strName.charAt(0) == '?') {
return true;
}
// Case #2: P_val
else if (strName.equals("P_val")) {
return true;
}
}
// DotExp
else if (name instanceof DotExp) {
// Recursively call this method until we get
// either true or false.
List<Exp> names = ((DotExp) name).getSegments();
return isVerificationVar(names.get(0));
}
// Definitely not a verification variable.
return false;
}
/**
* <p>Modifies the ensures clause based on the parameter mode.</p>
*
* @param ensures The <code>Exp</code> containing the ensures clause.
* @param opLocation The <code>Location</code> for the operation
* @param opName The name of the operation.
* @param parameterVarDecList The list of parameter variables for the operation.
*
* @return The modified ensures clause <code>Exp</code>.
*/
private Exp modifyEnsuresByParameter(Exp ensures, Location opLocation,
String opName, List<ParameterVarDec> parameterVarDecList) {
// Loop through each parameter
for (ParameterVarDec p : parameterVarDecList) {
// Ty is NameTy
if (p.getTy() instanceof NameTy) {
NameTy pNameTy = (NameTy) p.getTy();
// Exp form of the parameter variable
VarExp parameterExp =
new VarExp(p.getLocation(), null, p.getName().copy());
parameterExp.setMathType(pNameTy.getMathTypeValue());
// Create an old exp (#parameterExp)
OldExp oldParameterExp =
new OldExp(p.getLocation(), Exp.copy(parameterExp));
oldParameterExp.setMathType(pNameTy.getMathTypeValue());
// Preserves or Restores mode
if (p.getMode() == Mode.PRESERVES
|| p.getMode() == Mode.RESTORES) {
// Create an equals expression of the form "#parameterExp = parameterExp"
EqualsExp equalsExp =
new EqualsExp(opLocation, oldParameterExp,
EqualsExp.EQUAL, parameterExp);
equalsExp.setMathType(BOOLEAN);
// Set the details for the new location
Location equalLoc;
if (ensures != null && ensures.getLocation() != null) {
Location enLoc = ensures.getLocation();
equalLoc = ((Location) enLoc.clone());
}
else {
equalLoc = ((Location) opLocation.clone());
equalLoc.setDetails("Ensures Clause of " + opName);
}
equalLoc.setDetails(equalLoc.getDetails()
+ " (Condition from \""
+ p.getMode().getModeName().toUpperCase()
+ "\" parameter mode)");
equalsExp.setLocation(equalLoc);
// Create an AND infix expression with the ensures clause
if (ensures != null
&& !ensures.equals(myTypeGraph.getTrueVarExp())) {
ensures = myTypeGraph.formConjunct(ensures, equalsExp);
}
// Make new expression the ensures clause
else {
ensures = equalsExp;
}
}
// Clears mode
else if (p.getMode() == Mode.CLEARS) {
// Query for the type entry in the symbol table
ProgramTypeEntry typeEntry =
searchProgramType(pNameTy.getLocation(), pNameTy
.getName());
// Obtain the original dec from the AST
TypeDec type = (TypeDec) typeEntry.getDefiningElement();
// Obtain the exemplar in VarExp form
VarExp exemplar =
new VarExp(null, null, type.getExemplar());
exemplar.setMathType(pNameTy.getMathTypeValue());
// Deep copy the original initialization ensures and the constraint
Exp init = Exp.copy(type.getInitialization().getEnsures());
// Replace the formal with the actual
init = replace(init, exemplar, parameterExp);
// Set the details for the new location
if (init.getLocation() != null) {
Location initLoc;
if (ensures != null && ensures.getLocation() != null) {
Location reqLoc = ensures.getLocation();
initLoc = ((Location) reqLoc.clone());
}
else {
initLoc = ((Location) opLocation.clone());
initLoc.setDetails("Ensures Clause of " + opName);
}
initLoc.setDetails(initLoc.getDetails()
+ " (Condition from \""
+ p.getMode().getModeName().toUpperCase()
+ "\" parameter mode)");
init.setLocation(initLoc);
}
// Create an AND infix expression with the ensures clause
if (ensures != null
&& !ensures.equals(myTypeGraph.getTrueVarExp())) {
ensures = myTypeGraph.formConjunct(ensures, init);
}
// Make initialization expression the ensures clause
else {
ensures = init;
}
}
}
else {
// Ty not handled.
tyNotHandled(p.getTy(), p.getLocation());
}
}
return ensures;
}
/**
* <p>Returns the ensures clause.</p>
*
* @param ensures The <code>Exp</code> containing the ensures clause.
* @param opLocation The <code>Location</code> for the operation.
* @param opName The name for the operation.
*
* @return The modified ensures clause <code>Exp</code>.
*/
private Exp modifyEnsuresClause(Exp ensures, Location opLocation,
String opName) {
// Obtain the list of parameters for the current operation
List<ParameterVarDec> parameterVarDecList;
if (myCurrentOperationEntry.getDefiningElement() instanceof FacilityOperationDec) {
parameterVarDecList =
((FacilityOperationDec) myCurrentOperationEntry
.getDefiningElement()).getParameters();
}
else {
parameterVarDecList =
((OperationDec) myCurrentOperationEntry
.getDefiningElement()).getParameters();
}
// Modifies the existing ensures clause based on
// the parameter modes.
ensures =
modifyEnsuresByParameter(ensures, opLocation, opName,
parameterVarDecList);
return ensures;
}
/**
* <p>Modifies the requires clause based on .</p>
*
* @param requires The <code>Exp</code> containing the requires clause.
*
* @return The modified requires clause <code>Exp</code>.
*/
private Exp modifyRequiresByGlobalMode(Exp requires) {
return requires;
}
/**
* <p>Modifies the requires clause based on the parameter mode.</p>
*
* @param requires The <code>Exp</code> containing the requires clause.
* @param opLocation The <code>Location</code> for the operation.
* @param opName The name for the operation.
*
* @return The modified requires clause <code>Exp</code>.
*/
private Exp modifyRequiresByParameter(Exp requires, Location opLocation,
String opName) {
// Obtain the list of parameters
List<ParameterVarDec> parameterVarDecList;
if (myCurrentOperationEntry.getDefiningElement() instanceof FacilityOperationDec) {
parameterVarDecList =
((FacilityOperationDec) myCurrentOperationEntry
.getDefiningElement()).getParameters();
}
else {
parameterVarDecList =
((OperationDec) myCurrentOperationEntry
.getDefiningElement()).getParameters();
}
// Loop through each parameter
for (ParameterVarDec p : parameterVarDecList) {
ProgramTypeEntry typeEntry;
// Ty is NameTy
if (p.getTy() instanceof NameTy) {
NameTy pNameTy = (NameTy) p.getTy();
// Query for the type entry in the symbol table
typeEntry =
searchProgramType(pNameTy.getLocation(), pNameTy
.getName());
// Obtain the original dec from the AST
TypeDec type = (TypeDec) typeEntry.getDefiningElement();
// Convert p to a VarExp
VarExp pExp = new VarExp(null, null, p.getName());
pExp.setMathType(pNameTy.getMathTypeValue());
// Obtain the exemplar in VarExp form
VarExp exemplar = new VarExp(null, null, type.getExemplar());
exemplar.setMathType(pNameTy.getMathTypeValue());
// Deep copy the original initialization ensures and the constraint
Exp init = Exp.copy(type.getInitialization().getEnsures());
Exp constraint = Exp.copy(type.getConstraint());
// Only worry about replaces mode parameters
if (p.getMode() == Mode.REPLACES && init != null) {
// Replace the formal with the actual
init = replace(init, exemplar, pExp);
// Set the details for the new location
if (init.getLocation() != null) {
Location initLoc;
if (requires != null && requires.getLocation() != null) {
Location reqLoc = requires.getLocation();
initLoc = ((Location) reqLoc.clone());
}
else {
// Append the name of the current procedure
String details = "";
if (myCurrentOperationEntry != null) {
details =
" in Procedure "
+ myCurrentOperationEntry
.getName();
}
// Set the details of the current location
initLoc = ((Location) opLocation.clone());
initLoc.setDetails("Requires Clause of " + opName
+ details);
}
initLoc.setDetails(initLoc.getDetails()
+ " (Assumption from \""
+ p.getMode().getModeName().toUpperCase()
+ "\" parameter mode)");
init.setLocation(initLoc);
}
// Create an AND infix expression with the requires clause
if (requires != null
&& !requires.equals(myTypeGraph.getTrueVarExp())) {
requires = myTypeGraph.formConjunct(requires, init);
}
// Make initialization expression the requires clause
else {
requires = init;
}
}
// Constraints for the other parameter modes needs to be added
// to the requires clause as conjuncts.
else {
if (constraint != null
&& !constraint.equals(myTypeGraph.getTrueVarExp())) {
// Replace the formal with the actual
constraint = replace(constraint, exemplar, pExp);
// Set the details for the new location
if (constraint.getLocation() != null) {
Location constLoc;
if (requires != null
&& requires.getLocation() != null) {
Location reqLoc = requires.getLocation();
constLoc = ((Location) reqLoc.clone());
}
else {
// Append the name of the current procedure
String details = "";
if (myCurrentOperationEntry != null) {
details =
" in Procedure "
+ myCurrentOperationEntry
.getName();
}
constLoc = ((Location) opLocation.clone());
constLoc.setDetails("Requires Clause of "
+ opName + details);
}
constLoc.setDetails(constLoc.getDetails()
+ " (Constraint from \""
+ p.getMode().getModeName().toUpperCase()
+ "\" parameter mode)");
constraint.setLocation(constLoc);
}
// Create an AND infix expression with the requires clause
if (requires != null
&& !requires
.equals(myTypeGraph.getTrueVarExp())) {
requires =
myTypeGraph.formConjunct(requires,
constraint);
}
// Make constraint expression the requires clause
else {
requires = constraint;
}
}
}
// Add the current variable to our list of free variables
myAssertion.addFreeVar(createVarExp(p.getLocation(), p
.getName(), pNameTy.getMathTypeValue()));
}
else {
// Ty not handled.
tyNotHandled(p.getTy(), p.getLocation());
}
}
return requires;
}
/**
* <p>Modifies the requires clause.</p>
*
* @param requires The <code>Exp</code> containing the requires clause.
* @param opLocation The <code>Location</code> for the operation.
* @param opName The name of the operation.
*
* @return The modified requires clause <code>Exp</code>.
*/
private Exp modifyRequiresClause(Exp requires, Location opLocation,
String opName) {
// Modifies the existing requires clause based on
// the parameter modes.
requires = modifyRequiresByParameter(requires, opLocation, opName);
// Modifies the existing requires clause based on
// the parameter modes.
// TODO: Ask Murali what this means
requires = modifyRequiresByGlobalMode(requires);
return requires;
}
/**
* <p>Copy and replace the old <code>Exp</code>.</p>
*
* @param exp The <code>Exp</code> to be replaced.
* @param old The old sub-expression of <code>exp</code>.
* @param repl The new sub-expression of <code>exp</code>.
*
* @return The new <code>Exp</code>.
*/
private Exp replace(Exp exp, Exp old, Exp repl) {
// Clone old and repl and use the Exp replace to do all its work
Exp tmp = Exp.replace(exp, Exp.copy(old), Exp.copy(repl));
// Return the corresponding Exp
if (tmp != null)
return tmp;
else
return exp;
}
/**
* <p>Replace the formal with the actual variables
* inside the ensures clause.</p>
*
* @param ensures The ensures clause.
* @param paramList The list of parameter variables.
* @param stateVarList The list of state variables.
* @param argList The list of arguments from the operation call.
* @param isSimple Check if it is a simple replacement.
*
* @return The ensures clause in <code>Exp</code> form.
*/
private Exp replaceFormalWithActualEns(Exp ensures,
List<ParameterVarDec> paramList, List<AffectsItem> stateVarList,
List<ProgramExp> argList, boolean isSimple) {
// Current final confirm
Exp newConfirm = myAssertion.getFinalConfirm();
// List to hold temp and real values of variables in case
// of duplicate spec and real variables
List<Exp> undRepList = new ArrayList<Exp>();
List<Exp> replList = new ArrayList<Exp>();
// Replace state variables in the ensures clause
// and create new confirm statements if needed.
for (int i = 0; i < stateVarList.size(); i++) {
newConfirm = myAssertion.getFinalConfirm();
AffectsItem stateVar = stateVarList.get(i);
// Only deal with Alters/Reassigns/Replaces/Updates modes
if (stateVar.getMode() == Mode.ALTERS
|| stateVar.getMode() == Mode.REASSIGNS
|| stateVar.getMode() == Mode.REPLACES
|| stateVar.getMode() == Mode.UPDATES) {
// Obtain the variable from our free variable list
Exp globalFreeVar =
myAssertion.getFreeVar(stateVar.getName(), true);
if (globalFreeVar != null) {
VarExp oldNamesVar = new VarExp();
oldNamesVar.setName(stateVar.getName());
// Create a local free variable if it is not there
Exp localFreeVar =
myAssertion.getFreeVar(stateVar.getName(), false);
if (localFreeVar == null) {
// TODO: Don't have a type for state variables?
localFreeVar =
new VarExp(null, null, stateVar.getName());
localFreeVar =
createQuestionMarkVariable(myTypeGraph
.formConjunct(ensures, newConfirm),
(VarExp) localFreeVar);
myAssertion.addFreeVar(localFreeVar);
}
else {
localFreeVar =
createQuestionMarkVariable(myTypeGraph
.formConjunct(ensures, newConfirm),
(VarExp) localFreeVar);
}
// Creating "#" expressions and replace these in the
// ensures clause.
OldExp osVar = new OldExp(null, Exp.copy(globalFreeVar));
OldExp oldNameOSVar =
new OldExp(null, Exp.copy(oldNamesVar));
ensures = replace(ensures, oldNamesVar, globalFreeVar);
ensures = replace(ensures, oldNameOSVar, osVar);
// If it is not simple replacement, replace all ensures clauses
// with the appropriate expressions.
if (!isSimple) {
ensures = replace(ensures, globalFreeVar, localFreeVar);
ensures = replace(ensures, osVar, globalFreeVar);
newConfirm =
replace(newConfirm, globalFreeVar, localFreeVar);
}
// Set newConfirm as our new final confirm statement
myAssertion.setFinalConfirm(newConfirm);
}
// Error: Why isn't it a free variable.
else {
notInFreeVarList(stateVar.getName(), stateVar.getLocation());
}
}
}
// Replace postcondition variables in the ensures clause
for (int i = 0; i < argList.size(); i++) {
ParameterVarDec varDec = paramList.get(i);
ProgramExp pExp = argList.get(i);
PosSymbol VDName = varDec.getName();
// VarExp form of the parameter variable
VarExp oldExp = new VarExp(null, null, VDName);
oldExp.setMathType(pExp.getMathType());
oldExp.setMathTypeValue(pExp.getMathTypeValue());
// Convert the pExp into a something we can use
Exp repl = convertExp(pExp);
Exp undqRep = null, quesRep = null;
OldExp oSpecVar, oRealVar;
String replName = null;
// Case #1: ProgramIntegerExp
if (pExp instanceof ProgramIntegerExp) {
replName =
Integer.toString(((ProgramIntegerExp) repl).getValue());
// Create a variable expression of the form "_?[Argument Name]"
undqRep =
new VarExp(null, null, createPosSymbol("_?" + replName));
undqRep.setMathType(pExp.getMathType());
undqRep.setMathTypeValue(pExp.getMathTypeValue());
// Create a variable expression of the form "?[Argument Name]"
quesRep =
new VarExp(null, null, createPosSymbol("?" + replName));
quesRep.setMathType(pExp.getMathType());
quesRep.setMathTypeValue(pExp.getMathTypeValue());
}
// Case #2: VariableDotExp
else if (pExp instanceof VariableDotExp) {
if (repl instanceof DotExp) {
Exp pE = ((DotExp) repl).getSegments().get(0);
replName = pE.toString(0);
// Create a variable expression of the form "_?[Argument Name]"
undqRep = Exp.copy(repl);
edu.clemson.cs.r2jt.collections.List<Exp> segList =
((DotExp) undqRep).getSegments();
VariableNameExp undqNameRep =
new VariableNameExp(null, null,
createPosSymbol("_?" + replName));
undqNameRep.setMathType(pE.getMathType());
segList.set(0, undqNameRep);
((DotExp) undqRep).setSegments(segList);
// Create a variable expression of the form "?[Argument Name]"
quesRep = Exp.copy(repl);
segList = ((DotExp) quesRep).getSegments();
segList
.set(0, ((VariableDotExp) pExp).getSegments()
.get(0));
((DotExp) quesRep).setSegments(segList);
}
else if (repl instanceof VariableDotExp) {
Exp pE = ((VariableDotExp) repl).getSegments().get(0);
replName = pE.toString(0);
// Create a variable expression of the form "_?[Argument Name]"
undqRep = Exp.copy(repl);
edu.clemson.cs.r2jt.collections.List<VariableExp> segList =
((VariableDotExp) undqRep).getSegments();
VariableNameExp undqNameRep =
new VariableNameExp(null, null,
createPosSymbol("_?" + replName));
undqNameRep.setMathType(pE.getMathType());
segList.set(0, undqNameRep);
((VariableDotExp) undqRep).setSegments(segList);
// Create a variable expression of the form "?[Argument Name]"
quesRep = Exp.copy(repl);
segList = ((VariableDotExp) quesRep).getSegments();
segList
.set(0, ((VariableDotExp) pExp).getSegments()
.get(0));
((VariableDotExp) quesRep).setSegments(segList);
}
// Error: Case not handled!
else {
expNotHandled(pExp, pExp.getLocation());
}
}
// Case #3: VariableNameExp
else if (pExp instanceof VariableNameExp) {
// Name of repl in string form
replName = ((VariableNameExp) pExp).getName().getName();
// Create a variable expression of the form "_?[Argument Name]"
undqRep =
new VarExp(null, null, createPosSymbol("_?" + replName));
undqRep.setMathType(pExp.getMathType());
undqRep.setMathTypeValue(pExp.getMathTypeValue());
// Create a variable expression of the form "?[Argument Name]"
quesRep =
new VarExp(null, null, createPosSymbol("?" + replName));
quesRep.setMathType(pExp.getMathType());
quesRep.setMathTypeValue(pExp.getMathTypeValue());
}
// Error: Case not handled!
else {
expNotHandled(pExp, pExp.getLocation());
}
// "#" versions of oldExp and repl
oSpecVar = new OldExp(null, Exp.copy(oldExp));
oRealVar = new OldExp(null, Exp.copy(repl));
// Nothing can be null!
if (oldExp != null && quesRep != null && oSpecVar != null
&& repl != null && oRealVar != null) {
// Alters, Clears, Reassigns, Replaces, Updates
if (varDec.getMode() == Mode.ALTERS
|| varDec.getMode() == Mode.CLEARS
|| varDec.getMode() == Mode.REASSIGNS
|| varDec.getMode() == Mode.REPLACES
|| varDec.getMode() == Mode.UPDATES) {
Exp quesVar;
// Obtain the free variable
VarExp freeVar =
(VarExp) myAssertion.getFreeVar(
createPosSymbol(replName), false);
if (freeVar == null) {
freeVar =
createVarExp(varDec.getLocation(),
createPosSymbol(replName), varDec
.getTy().getMathTypeValue());
}
// Apply the question mark to the free variable
freeVar =
createQuestionMarkVariable(myTypeGraph
.formConjunct(ensures, newConfirm), freeVar);
if (pExp instanceof ProgramDotExp
|| pExp instanceof VariableDotExp) {
// Make a copy from repl
quesVar = Exp.copy(repl);
// Replace the free variable in the question mark variable as the first element
// in the dot expression.
VarExp tmpVar =
new VarExp(null, null, freeVar.getName());
tmpVar.setMathType(myTypeGraph.BOOLEAN);
edu.clemson.cs.r2jt.collections.List<Exp> segs =
((DotExp) quesVar).getSegments();
segs.set(0, tmpVar);
((DotExp) quesVar).setSegments(segs);
}
else {
// Create a variable expression from free variable
quesVar = new VarExp(null, null, freeVar.getName());
quesVar.setMathType(freeVar.getMathType());
quesVar.setMathTypeValue(freeVar.getMathTypeValue());
}
// Add the new free variable to free variable list
myAssertion.addFreeVar(freeVar);
// Check if our ensures clause has the parameter variable in it.
if (ensures.containsVar(VDName.getName(), true)
|| ensures.containsVar(VDName.getName(), false)) {
// Replace the ensures clause
ensures = replace(ensures, oldExp, undqRep);
ensures = replace(ensures, oSpecVar, repl);
// Add it to our list of variables to be replaced later
undRepList.add(undqRep);
replList.add(quesVar);
}
else {
// Replace the ensures clause
ensures = replace(ensures, oldExp, quesRep);
ensures = replace(ensures, oSpecVar, repl);
}
// Update our final confirm with the parameter argument
newConfirm = replace(newConfirm, repl, quesVar);
myAssertion.setFinalConfirm(newConfirm);
}
// All other modes
else {
// Check if our ensures clause has the parameter variable in it.
if (ensures.containsVar(VDName.getName(), true)
|| ensures.containsVar(VDName.getName(), false)) {
// Replace the ensures clause
ensures = replace(ensures, oldExp, undqRep);
ensures = replace(ensures, oSpecVar, undqRep);
// Add it to our list of variables to be replaced later
undRepList.add(undqRep);
replList.add(repl);
}
else {
// Replace the ensures clause
ensures = replace(ensures, oldExp, repl);
ensures = replace(ensures, oSpecVar, repl);
}
}
}
}
// Replace the temp values with the actual values
for (int i = 0; i < undRepList.size(); i++) {
ensures = replace(ensures, undRepList.get(i), replList.get(i));
}
return ensures;
}
/**
* <p>Replace the formal with the actual variables
* inside the requires clause.</p>
*
* @param requires The requires clause.
* @param paramList The list of parameter variables.
* @param argList The list of arguments from the operation call.
*
* @return The requires clause in <code>Exp</code> form.
*/
private Exp replaceFormalWithActualReq(Exp requires,
List<ParameterVarDec> paramList, List<ProgramExp> argList) {
// List to hold temp and real values of variables in case
// of duplicate spec and real variables
List<Exp> undRepList = new ArrayList<Exp>();
List<Exp> replList = new ArrayList<Exp>();
// Replace precondition variables in the requires clause
for (int i = 0; i < argList.size(); i++) {
ParameterVarDec varDec = paramList.get(i);
ProgramExp pExp = argList.get(i);
// Convert the pExp into a something we can use
Exp repl = convertExp(pExp);
// VarExp form of the parameter variable
VarExp oldExp = new VarExp(null, null, varDec.getName());
oldExp.setMathType(pExp.getMathType());
oldExp.setMathTypeValue(pExp.getMathTypeValue());
// New VarExp
VarExp newExp =
new VarExp(null, null, createPosSymbol("_"
+ varDec.getName().getName()));
newExp.setMathType(repl.getMathType());
newExp.setMathTypeValue(repl.getMathTypeValue());
// Replace the old with the new in the requires clause
requires = replace(requires, oldExp, newExp);
// Add it to our list
undRepList.add(newExp);
replList.add(repl);
}
// Replace the temp values with the actual values
for (int i = 0; i < undRepList.size(); i++) {
requires = replace(requires, undRepList.get(i), replList.get(i));
}
return requires;
}
/**
* <p>Given a math symbol name, locate and return
* the <code>MathSymbolEntry</code> stored in the
* symbol table.</p>
*
* @param loc The location in the AST that we are
* currently visiting.
* @param name The string name of the math symbol.
*
* @return An <code>MathSymbolEntry</code> from the
* symbol table.
*/
private MathSymbolEntry searchMathSymbol(Location loc, String name) {
// Query for the corresponding math symbol
MathSymbolEntry ms = null;
try {
ms =
myCurrentModuleScope.queryForOne(
new UnqualifiedNameQuery(name,
ImportStrategy.IMPORT_RECURSIVE,
FacilityStrategy.FACILITY_IGNORE, true,
true)).toMathSymbolEntry(loc);
}
catch (NoSuchSymbolException nsse) {
noSuchSymbol(null, name, loc);
}
catch (DuplicateSymbolException dse) {
//This should be caught earlier, when the duplicate symbol is
//created
throw new RuntimeException(dse);
}
return ms;
}
/**
* <p>Given the qualifier, name and the list of argument
* types, locate and return the <code>OperationEntry</code>
* stored in the symbol table.</p>
*
* @param loc The location in the AST that we are
* currently visiting.
* @param qualifier The qualifier of the operation.
* @param name The name of the operation.
* @param argTypes The list of argument types.
*
* @return An <code>OperationEntry</code> from the
* symbol table.
*/
private OperationEntry searchOperation(Location loc, PosSymbol qualifier,
PosSymbol name, List<PTType> argTypes) {
// Query for the corresponding operation
OperationEntry op = null;
try {
op =
myCurrentModuleScope.queryForOne(new OperationQuery(
qualifier, name, argTypes));
}
catch (NoSuchSymbolException nsse) {
noSuchSymbol(null, name.getName(), loc);
}
catch (DuplicateSymbolException dse) {
//This should be caught earlier, when the duplicate operation is
//created
throw new RuntimeException(dse);
}
return op;
}
/**
* <p>Given the name of the type locate and return
* the <code>ProgramTypeEntry</code> stored in the
* symbol table.</p>
*
* @param loc The location in the AST that we are
* currently visiting.
* @param name The name of the type.
*
* @return An <code>ProgramTypeEntry</code> from the
* symbol table.
*/
private ProgramTypeEntry searchProgramType(Location loc, PosSymbol name) {
// Query for the corresponding operation
ProgramTypeEntry pt = null;
try {
pt =
myCurrentModuleScope.queryForOne(
new NameQuery(null, name,
ImportStrategy.IMPORT_NAMED,
FacilityStrategy.FACILITY_INSTANTIATE,
false)).toProgramTypeEntry(loc);
}
catch (NoSuchSymbolException nsse) {
noSuchSymbol(null, name.getName(), loc);
}
catch (DuplicateSymbolException dse) {
//This should be caught earlier, when the duplicate type is
//created
throw new RuntimeException(dse);
}
return pt;
}
/**
* <p>Changes the <code>Exp</code> with the new
* <code>Location</code>.</p>
*
* @param exp The <code>Exp</code> that needs to be modified.
* @param loc The new <code>Location</code>.
*/
private void setLocation(Exp exp, Location loc) {
// Special handling for InfixExp
if (exp instanceof InfixExp) {
((InfixExp) exp).setAllLocations(loc);
}
else {
exp.setLocation(loc);
}
}
/**
* <p>Simplify the assume statement where possible.</p>
*
* @param stmt The assume statement we want to simplify.
* @param exp The current expression we are dealing with.
*
* @return The modified expression in <code>Exp/code> form.
*/
private Exp simplifyAssumeRule(AssumeStmt stmt, Exp exp) {
// Variables
Exp assertion = stmt.getAssertion();
boolean keepAssumption = false;
// EqualsExp
if (assertion instanceof EqualsExp) {
EqualsExp equalsExp = (EqualsExp) assertion;
// Only do simplifications if we have an equals
if (equalsExp.getOperator() == EqualsExp.EQUAL) {
boolean verificationVariable =
isVerificationVar(equalsExp.getLeft());
// Create a temp expression where left is replaced with the right
Exp tmp =
replace(exp, equalsExp.getLeft(), equalsExp.getRight());
if (equalsExp.getLeft() instanceof VarExp) {
// If left is still part of confirm
VarExp left = (VarExp) equalsExp.getLeft();
if (tmp.containsVar(left.getName().getName(), false)) {
keepAssumption = true;
}
}
// If tmp is not null, then it means we have to check the right
if (tmp == null) {
// Create a temp expression where right is replaced with the left
verificationVariable =
isVerificationVar(equalsExp.getRight());
tmp =
replace(exp, equalsExp.getRight(), equalsExp
.getLeft());
if (equalsExp.getRight() instanceof VarExp) {
// If right is still part of confirm
VarExp right = (VarExp) equalsExp.getRight();
if (tmp.containsVar(right.getName().getName(), false)) {
keepAssumption = true;
}
}
}
// We clear our assertion for this assumes if
// we have a verification variable and we don't have to
// keep this assumption.
if (verificationVariable && !keepAssumption) {
assertion = null;
}
// Update exp
if (!tmp.equals(exp)) {
exp = tmp;
}
}
}
// InfixExp
else if (assertion instanceof InfixExp) {
InfixExp infixExp = (InfixExp) assertion;
// Only do simplifications if we have an and operator
if (infixExp.getOpName().equals("and")) {
// Recursively call simplify on the left and on the right
AssumeStmt left = new AssumeStmt(Exp.copy(infixExp.getLeft()));
AssumeStmt right =
new AssumeStmt(Exp.copy(infixExp.getRight()));
exp = simplifyAssumeRule(left, exp);
exp = simplifyAssumeRule(right, exp);
// Case #1: Nothing left
if (left.getAssertion() == null && right.getAssertion() == null) {
assertion = null;
}
// Case #2: Both still have assertions
else if (left.getAssertion() != null
&& right.getAssertion() != null) {
assertion =
myTypeGraph.formConjunct(left.getAssertion(), right
.getAssertion());
}
// Case #3: Left still has assertions
else if (left.getAssertion() != null) {
assertion = left.getAssertion();
}
// Case #r: Right still has assertions
else {
assertion = right.getAssertion();
}
}
}
// Store the new assertion
stmt.setAssertion(assertion);
return exp;
}
// -----------------------------------------------------------
// Proof Rules
// -----------------------------------------------------------
/**
* <p>Applies the assume rule.</p>
*
* @param assume The assume clause
*/
private void applyAssumeRule(VerificationStatement assume) {
if (assume.getAssertion() instanceof VarExp
&& ((VarExp) assume.getAssertion()).equals(Exp
.getTrueVarExp(myTypeGraph))) {
// Verbose Mode Debug Messages
myVCBuffer.append("\nAssume Rule Applied and Simplified: \n");
myVCBuffer.append(myAssertion.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
else {
// Obtain the current final confirm clause
Exp conf = myAssertion.getFinalConfirm();
// Create a new implies expression
InfixExp newConf =
myTypeGraph.formImplies((Exp) assume.getAssertion(), conf);
// Set this new expression as the new final confirm
myAssertion.setFinalConfirm(newConf);
// Verbose Mode Debug Messages
myVCBuffer.append("\nAssume Rule Applied: \n");
myVCBuffer.append(myAssertion.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
}
/**
* <p>Applies different rules to code statements.</p>
*
* @param statement The different statements.
*/
private void applyCodeRules(Statement statement) {
// Apply each statement rule here.
if (statement instanceof AssumeStmt) {
applyEBAssumeStmtRule((AssumeStmt) statement);
}
else if (statement instanceof CallStmt) {
applyEBCallStmtRule((CallStmt) statement);
}
else if (statement instanceof ConfirmStmt) {
applyEBConfirmStmtRule((ConfirmStmt) statement);
}
else if (statement instanceof FuncAssignStmt) {
applyEBFuncAssignStmtRule((FuncAssignStmt) statement);
}
else if (statement instanceof SwapStmt) {
applyEBSwapStmtRule((SwapStmt) statement);
}
}
/**
* <p>Applies the confirm rule.</p>
*
* @param confirm The confirm clause
*/
private void applyConfirmRule(VerificationStatement confirm) {
if (confirm.getAssertion() instanceof VarExp
&& ((VarExp) confirm.getAssertion()).equals(Exp
.getTrueVarExp(myTypeGraph))) {
myVCBuffer.append("\nConfirm Rule Applied and Simplified: \n");
myVCBuffer.append(myAssertion.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
else {
// Obtain the current final confirm clause
Exp conf = myAssertion.getFinalConfirm();
// Create a new and expression
InfixExp newConf =
myTypeGraph
.formConjunct((Exp) confirm.getAssertion(), conf);
// Set this new expression as the new final confirm
myAssertion.setFinalConfirm(newConf);
// Verbose Mode Debug Messages
myVCBuffer.append("\nConfirm Rule Applied: \n");
myVCBuffer.append(myAssertion.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
}
/**
* <p>Applies the assume rule to the
* <code>Statement</code>.</p>
*
* @param stmt Our current <code>AssumeStmt</code>.
*/
private void applyEBAssumeStmtRule(AssumeStmt stmt) {
// Check to see if our assertion just has "True"
Exp assertion = stmt.getAssertion();
if (assertion instanceof VarExp
&& assertion.equals(myTypeGraph.getTrueVarExp())) {
// Verbose Mode Debug Messages
myVCBuffer.append("\nAssume Rule Applied and Simplified: \n");
myVCBuffer.append(myAssertion.assertionToString());
myVCBuffer.append("\n_____________________ \n");
return;
}
// Apply simplification
Exp currentFinalConfirm =
simplifyAssumeRule(stmt, myAssertion.getFinalConfirm());
if (stmt.getAssertion() != null) {
// Create a new implies expression
currentFinalConfirm =
myTypeGraph.formImplies(assertion, currentFinalConfirm);
}
// Set this as our new final confirm
myAssertion.setFinalConfirm(currentFinalConfirm);
// Verbose Mode Debug Messages
myVCBuffer.append("\nAssume Rule Applied: \n");
myVCBuffer.append(myAssertion.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
/**
* <p>Applies the call statement rule to the
* <code>Statement</code>.</p>
*
* @param stmt Our current <code>CallStmt</code>.
*/
private void applyEBCallStmtRule(CallStmt stmt) {
// Obtain the corresponding OperationEntry and OperationDec
List<PTType> argTypes = new LinkedList<PTType>();
for (ProgramExp arg : stmt.getArguments()) {
argTypes.add(arg.getProgramType());
}
OperationEntry opEntry =
searchOperation(stmt.getLocation(), stmt.getQualifier(), stmt
.getName(), argTypes);
// Obtain an OperationDec from the OperationEntry
ResolveConceptualElement element = opEntry.getDefiningElement();
OperationDec opDec;
if (element instanceof OperationDec) {
opDec = (OperationDec) opEntry.getDefiningElement();
}
else {
FacilityOperationDec fOpDec =
(FacilityOperationDec) opEntry.getDefiningElement();
opDec =
new OperationDec(fOpDec.getName(), fOpDec.getParameters(),
fOpDec.getReturnTy(), fOpDec.getStateVars(), fOpDec
.getRequires(), fOpDec.getEnsures());
}
// Get the ensures clause for this operation
// Note: If there isn't an ensures clause, it is set to "True"
Exp ensures;
if (opDec.getEnsures() != null) {
ensures = Exp.copy(opDec.getEnsures());
// Set the location for the ensures clause
if (ensures.getLocation() != null) {
Location newLoc = ensures.getLocation();
newLoc.setDetails("Ensures Clause For " + opDec.getName());
ensures.setLocation(newLoc);
}
}
else {
ensures = myTypeGraph.getTrueVarExp();
}
// Get the requires clause for this operation
Exp requires;
if (opDec.getRequires() != null) {
requires = Exp.copy(opDec.getRequires());
}
else {
requires = myTypeGraph.getTrueVarExp();
}
// Check for recursive call of itself
if (myCurrentOperationEntry.getName().equals(opEntry.getName())
&& myCurrentOperationEntry.getReturnType() != null) {
// Create a new confirm statement using P_val and the decreasing clause
VarExp pVal = createPValExp(myOperationDecreasingExp.getLocation());
// Create a new infix expression
InfixExp exp =
new InfixExp(stmt.getLocation(), Exp
.copy(myOperationDecreasingExp),
createPosSymbol("<"), pVal);
exp.setMathType(BOOLEAN);
// Create the new confirm statement
Location loc;
if (myOperationDecreasingExp.getLocation() != null) {
loc = (Location) myOperationDecreasingExp.getLocation().clone();
}
else {
loc = (Location) stmt.getLocation().clone();
}
loc.setDetails("Show Termination of Recursive Call");
setLocation(exp, loc);
ConfirmStmt conf = new ConfirmStmt(loc, exp);
// Add it to our list of assertions
myAssertion.addCode(conf);
}
// Modify ensures using the parameter modes
ensures =
modifyEnsuresByParameter(ensures, stmt.getLocation(), opDec
.getName().getName(), opDec.getParameters());
// Replace PreCondition variables in the requires clause
requires =
replaceFormalWithActualReq(requires, opDec.getParameters(),
stmt.getArguments());
// Replace PostCondition variables in the ensures clause
ensures =
replaceFormalWithActualEns(ensures, opDec.getParameters(),
opDec.getStateVars(), stmt.getArguments(), false);
// Modify the location of the requires clause and add it to myAssertion
if (requires != null) {
// Obtain the current location
// Note: If we don't have a location, we create one
Location loc;
if (stmt.getName().getLocation() != null) {
loc = (Location) stmt.getName().getLocation().clone();
}
else {
loc = new Location(null, null);
}
// Append the name of the current procedure
String details = "";
if (myCurrentOperationEntry != null) {
details = " in Procedure " + myCurrentOperationEntry.getName();
}
// Set the details of the current location
loc.setDetails("Requires Clause of " + opDec.getName() + details);
setLocation(requires, loc);
// Add this to our list of things to confirm
myAssertion.addConfirm(requires);
}
// Modify the location of the requires clause and add it to myAssertion
if (ensures != null) {
// Obtain the current location
if (stmt.getName().getLocation() != null) {
// Set the details of the current location
Location loc = (Location) stmt.getName().getLocation().clone();
loc.setDetails("Ensures Clause of " + opDec.getName());
setLocation(ensures, loc);
}
// Add this to our list of things to assume
myAssertion.addAssume(ensures);
}
// Verbose Mode Debug Messages
myVCBuffer.append("\nOperation Call Rule Applied: \n");
myVCBuffer.append(myAssertion.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
/**
* <p>Applies the confirm rule to the
* <code>Statement</code>.</p>
*
* @param stmt Our current <code>ConfirmStmt</code>.
*/
private void applyEBConfirmStmtRule(ConfirmStmt stmt) {
// Check to see if our assertion just has "True"
Exp assertion = stmt.getAssertion();
if (assertion instanceof VarExp
&& assertion.equals(myTypeGraph.getTrueVarExp())) {
// Verbose Mode Debug Messages
myVCBuffer.append("\nConfirm Rule Applied and Simplified: \n");
myVCBuffer.append(myAssertion.assertionToString());
myVCBuffer.append("\n_____________________ \n");
return;
}
// Obtain the current final confirm statement
Exp currentFinalConfirm = myAssertion.getFinalConfirm();
// Check to see if we have a final confirm of "True"
if (currentFinalConfirm instanceof VarExp
&& currentFinalConfirm.equals(myTypeGraph.getTrueVarExp())) {
// Obtain the current location
if (assertion.getLocation() != null) {
// Set the details of the current location
Location loc = (Location) assertion.getLocation().clone();
setLocation(assertion, loc);
}
myAssertion.setFinalConfirm(assertion);
// Verbose Mode Debug Messages
myVCBuffer.append("\nConfirm Rule Applied and Simplified: \n");
myVCBuffer.append(myAssertion.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
else {
// Create a new and expression
InfixExp newConf =
myTypeGraph.formConjunct(assertion, currentFinalConfirm);
// Set this new expression as the new final confirm
myAssertion.setFinalConfirm(newConf);
// Verbose Mode Debug Messages
myVCBuffer.append("\nConfirm Rule Applied: \n");
myVCBuffer.append(myAssertion.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
}
/**
* <p>Applies each of the proof rules. This <code>AssertiveCode</code> will be
* stored for later use and therefore should be considered immutable after
* a call to this method.</p>
*/
private void applyEBRules() {
// Apply a proof rule to each of the assertions
while (myAssertion.hasAnotherAssertion()) {
// Work our way from the last assertion
VerificationStatement curAssertion = myAssertion.getLastAssertion();
switch (curAssertion.getType()) {
// Assume Assertion
case VerificationStatement.ASSUME:
applyAssumeRule(curAssertion);
break;
case VerificationStatement.CHANGE:
// TODO: Add when we have change rule implemented.
break;
// Confirm Assertion
case VerificationStatement.CONFIRM:
applyConfirmRule(curAssertion);
break;
// Code
case VerificationStatement.CODE:
applyCodeRules((Statement) curAssertion.getAssertion());
if (curAssertion.getAssertion() instanceof WhileStmt
|| curAssertion.getAssertion() instanceof IfStmt) {
return;
}
break;
// Remember Assertion
case VerificationStatement.REMEMBER:
applyRememberRule();
break;
// Variable Declaration Assertion
case VerificationStatement.VARIABLE:
applyVarDeclRule(curAssertion);
break;
}
}
}
/**
* <p>Applies the function assignment rule to the
* <code>Statement</code>.</p>
*
* @param stmt Our current <code>FuncAssignStmt</code>.
*/
private void applyEBFuncAssignStmtRule(FuncAssignStmt stmt) {
OperationDec opDec;
PosSymbol qualifier = null;
ProgramExp assignExp = stmt.getAssign();
ProgramParamExp assignParamExp = null;
// Check to see what kind of expression is on the right hand side
if (assignExp instanceof ProgramParamExp) {
// Cast to a ProgramParamExp
assignParamExp = (ProgramParamExp) assignExp;
}
else if (assignExp instanceof ProgramDotExp) {
// Cast to a ProgramParamExp
ProgramDotExp dotExp = (ProgramDotExp) assignExp;
assignParamExp = (ProgramParamExp) dotExp.getExp();
qualifier = dotExp.getQualifier();
}
else {
// TODO: ERROR!
}
// Obtain the corresponding OperationEntry and OperationDec
List<PTType> argTypes = new LinkedList<PTType>();
for (ProgramExp arg : assignParamExp.getArguments()) {
argTypes.add(arg.getProgramType());
}
OperationEntry opEntry =
searchOperation(stmt.getLocation(), qualifier, assignParamExp
.getName(), argTypes);
// Obtain an OperationDec from the OperationEntry
ResolveConceptualElement element = opEntry.getDefiningElement();
if (element instanceof OperationDec) {
opDec = (OperationDec) opEntry.getDefiningElement();
}
else {
FacilityOperationDec fOpDec =
(FacilityOperationDec) opEntry.getDefiningElement();
opDec =
new OperationDec(fOpDec.getName(), fOpDec.getParameters(),
fOpDec.getReturnTy(), fOpDec.getStateVars(), fOpDec
.getRequires(), fOpDec.getEnsures());
}
// Check for recursive call of itself
if (myCurrentOperationEntry.getName().equals(opEntry.getName())
&& myCurrentOperationEntry.getReturnType() != null) {
// Create a new confirm statement using P_val and the decreasing clause
VarExp pVal = createPValExp(myOperationDecreasingExp.getLocation());
// Create a new infix expression
InfixExp exp =
new InfixExp(stmt.getLocation(), Exp
.copy(myOperationDecreasingExp),
createPosSymbol("<"), pVal);
exp.setMathType(BOOLEAN);
// Create the new confirm statement
Location loc;
if (myOperationDecreasingExp.getLocation() != null) {
loc = (Location) myOperationDecreasingExp.getLocation().clone();
}
else {
loc = (Location) stmt.getLocation().clone();
}
loc.setDetails("Show Termination of Recursive Call");
setLocation(exp, loc);
ConfirmStmt conf = new ConfirmStmt(loc, exp);
// Add it to our list of assertions
myAssertion.addCode(conf);
}
// Get the requires clause for this operation
Exp requires;
if (opDec.getRequires() != null) {
requires = Exp.copy(opDec.getRequires());
}
else {
requires = myTypeGraph.getTrueVarExp();
}
// Replace PreCondition variables in the requires clause
requires =
replaceFormalWithActualReq(requires, opDec.getParameters(),
assignParamExp.getArguments());
// Modify the location of the requires clause and add it to myAssertion
// Obtain the current location
// Note: If we don't have a location, we create one
Location reqloc;
if (assignParamExp.getName().getLocation() != null) {
reqloc = (Location) assignParamExp.getName().getLocation().clone();
}
else {
reqloc = new Location(null, null);
}
// Append the name of the current procedure
String details = "";
if (myCurrentOperationEntry != null) {
details = " in Procedure " + myCurrentOperationEntry.getName();
}
// Set the details of the current location
reqloc.setDetails("Requires Clause of " + opDec.getName() + details);
setLocation(requires, reqloc);
// Add this to our list of things to confirm
myAssertion.addConfirm(requires);
// Get the ensures clause for this operation
// Note: If there isn't an ensures clause, it is set to "True"
Exp ensures, opEnsures;
if (opDec.getEnsures() != null) {
opEnsures = Exp.copy(opDec.getEnsures());
// Make sure we have an EqualsExp, else it is an error.
if (opEnsures instanceof EqualsExp) {
// Has to be a VarExp on the left hand side (containing the name
// of the function operation)
if (((EqualsExp) opEnsures).getLeft() instanceof VarExp) {
VarExp leftExp = (VarExp) ((EqualsExp) opEnsures).getLeft();
// Check if it has the name of the operation
if (leftExp.getName().equals(opDec.getName())) {
ensures = ((EqualsExp) opEnsures).getRight();
// Obtain the current location
if (assignParamExp.getName().getLocation() != null) {
// Set the details of the current location
Location loc =
(Location) assignParamExp.getName()
.getLocation().clone();
loc.setDetails("Ensures Clause of "
+ opDec.getName());
setLocation(ensures, loc);
}
// Replace all instances of the variable on the left hand side
// in the ensures clause with the expression on the right.
Exp leftVariable;
// We have a variable inside a record as the variable being assigned.
if (stmt.getVar() instanceof VariableDotExp) {
VariableDotExp v = (VariableDotExp) stmt.getVar();
List<VariableExp> vList = v.getSegments();
edu.clemson.cs.r2jt.collections.List<Exp> newSegments =
new edu.clemson.cs.r2jt.collections.List<Exp>();
// Loot through each variable expression and add it to our dot list
for (VariableExp vr : vList) {
VarExp varExp = new VarExp();
if (vr instanceof VariableNameExp) {
varExp.setName(((VariableNameExp) vr)
.getName());
varExp.setMathType(vr.getMathType());
varExp.setMathTypeValue(vr
.getMathTypeValue());
newSegments.add(varExp);
}
}
// Expression to be replaced
leftVariable =
new DotExp(v.getLocation(), newSegments,
null);
leftVariable.setMathType(v.getMathType());
leftVariable.setMathTypeValue(v.getMathTypeValue());
}
// We have a regular variable being assigned.
else {
// Expression to be replaced
VariableNameExp v = (VariableNameExp) stmt.getVar();
leftVariable =
new VarExp(v.getLocation(), null, v
.getName());
leftVariable.setMathType(v.getMathType());
leftVariable.setMathTypeValue(v.getMathTypeValue());
}
// Replace all instances of the left hand side
// variable in the current final confirm statement.
Exp newConf = myAssertion.getFinalConfirm();
newConf = replace(newConf, leftVariable, ensures);
// Replace the formals with the actuals.
newConf =
replaceFormalWithActualEns(newConf, opDec
.getParameters(), opDec.getStateVars(),
assignParamExp.getArguments(), false);
// Set this as our new final confirm statement.
myAssertion.setFinalConfirm(newConf);
}
else {
illegalOperationEnsures(opDec.getLocation());
}
}
else {
illegalOperationEnsures(opDec.getLocation());
}
}
else {
illegalOperationEnsures(opDec.getLocation());
}
}
// Verbose Mode Debug Messages
myVCBuffer.append("\nFunction Rule Applied: \n");
myVCBuffer.append(myAssertion.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
/**
* <p>Applies the swap statement rule to the
* <code>Statement</code>.</p>
*
* @param stmt Our current <code>SwapStmt</code>.
*/
private void applyEBSwapStmtRule(SwapStmt stmt) {
// Obtain the current final confirm clause
Exp conf = myAssertion.getFinalConfirm();
// Create a copy of the left and right hand side
VariableExp stmtLeft = (VariableExp) Exp.copy(stmt.getLeft());
VariableExp stmtRight = (VariableExp) Exp.copy(stmt.getRight());
// New left and right
Exp newLeft = convertExp(stmtLeft);
Exp newRight = convertExp(stmtRight);
// Use our final confirm to obtain the math types
List lst = conf.getSubExpressions();
for (int i = 0; i < lst.size(); i++) {
if (lst.get(i) instanceof VarExp) {
VarExp thisExp = (VarExp) lst.get(i);
if (newRight instanceof VarExp) {
if (thisExp.getName().equals(
((VarExp) newRight).getName().getName())) {
newRight.setMathType(thisExp.getMathType());
newRight.setMathTypeValue(thisExp.getMathTypeValue());
}
}
if (newLeft instanceof VarExp) {
if (thisExp.getName().equals(
((VarExp) newLeft).getName().getName())) {
newLeft.setMathType(thisExp.getMathType());
newLeft.setMathTypeValue(thisExp.getMathTypeValue());
}
}
}
}
// Temp variable
VarExp tmp = new VarExp();
tmp.setName(createPosSymbol("_" + getVarName(stmtLeft).getName()));
tmp.setMathType(stmtLeft.getMathType());
tmp.setMathTypeValue(stmtLeft.getMathTypeValue());
// Replace according to the swap rule
conf = replace(conf, newRight, tmp);
conf = replace(conf, newLeft, newRight);
conf = replace(conf, tmp, newLeft);
// Set this new expression as the new final confirm
myAssertion.setFinalConfirm(conf);
// Verbose Mode Debug Messages
myVCBuffer.append("\nSwap Rule Applied: \n");
myVCBuffer.append(myAssertion.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
/**
* <p>Applies the procedure declaration rule.</p>
*
* @param requires Requires clause
* @param ensures Ensures clause
* @param decreasing Decreasing clause (if any)
* @param variableList List of all variables for this procedure
* @param statementList List of statements for this procedure
*/
private void applyProcedureDeclRule(Exp requires, Exp ensures,
Exp decreasing, List<VarDec> variableList,
List<Statement> statementList) {
// Add the global requires clause
if (myGlobalRequiresExp != null) {
myAssertion.addAssume(myGlobalRequiresExp);
}
// Add the global constraints
if (myGlobalConstraintExp != null) {
myAssertion.addAssume(myGlobalConstraintExp);
}
// Add the requires clause
if (requires != null) {
myAssertion.addAssume(requires);
}
// Add the remember rule
myAssertion.addRemember();
// Add declared variables into the assertion. Also add
// them to the list of free variables.
myAssertion.addVariableDecs(variableList);
addVarDecsAsFreeVars(variableList);
// Check to see if we have a recursive procedure.
// If yes, we will need to create an additional assume clause
// (P_val = (decreasing clause)) in our list of assertions.
if (decreasing != null) {
// Store for future use
myOperationDecreasingExp = decreasing;
// Add P_val as a free variable
VarExp pVal = createPValExp(decreasing.getLocation());
myAssertion.addFreeVar(pVal);
// Create an equals expression
EqualsExp equalsExp =
new EqualsExp(null, pVal, EqualsExp.EQUAL, Exp
.copy(decreasing));
equalsExp.setMathType(BOOLEAN);
Location eqLoc = (Location) decreasing.getLocation().clone();
eqLoc.setDetails("Progress Metric for Recursive Procedure");
setLocation(equalsExp, eqLoc);
// Add it to our things to assume
myAssertion.addAssume(equalsExp);
}
// Add the list of statements
myAssertion.addStatements(statementList);
// Add the final confirms clause
myAssertion.setFinalConfirm(ensures);
// Verbose Mode Debug Messages
myVCBuffer.append("\nProcedure Declaration Rule Applied: \n");
myVCBuffer.append(myAssertion.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
/**
* <p>Applies the remember rule.</p>
*/
private void applyRememberRule() {
// Obtain the final confirm and apply the remember method for Exp
Exp conf = myAssertion.getFinalConfirm();
conf = conf.remember();
myAssertion.setFinalConfirm(conf);
// Verbose Mode Debug Messages
myVCBuffer.append("\nRemember Rule Applied: \n");
myVCBuffer.append(myAssertion.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
/**
* <p>Applies the variable declaration rule.</p>
*
* @param var A declared variable stored as a
* <code>VerificationStatement</code>
*/
private void applyVarDeclRule(VerificationStatement var) {
// Obtain the variable from the verification statement
VarDec varDec = (VarDec) var.getAssertion();
ProgramTypeEntry typeEntry;
// Ty is NameTy
if (varDec.getTy() instanceof NameTy) {
NameTy pNameTy = (NameTy) varDec.getTy();
// Query for the type entry in the symbol table
typeEntry =
searchProgramType(pNameTy.getLocation(), pNameTy.getName());
// Obtain the original dec from the AST
TypeDec type = (TypeDec) typeEntry.getDefiningElement();
// Deep copy the original initialization ensures
Exp init = Exp.copy(type.getInitialization().getEnsures());
// Create an is_initial dot expression
DotExp isInitialExp = createInitExp(varDec, init);
if (init.getLocation() != null) {
Location loc = (Location) init.getLocation().clone();
loc.setDetails("Initial Value for "
+ varDec.getName().getName());
setLocation(isInitialExp, loc);
}
// Make sure we have a constraint
Exp constraint;
if (type.getConstraint() == null) {
constraint = myTypeGraph.getTrueVarExp();
}
else {
constraint = Exp.copy(type.getConstraint());
}
// Set the location for the constraint
Location loc;
if (constraint.getLocation() != null) {
loc = (Location) constraint.getLocation().clone();
}
else {
loc = (Location) type.getLocation().clone();
}
loc.setDetails("Constraints on " + varDec.getName().getName());
setLocation(constraint, loc);
// Check if our initialization ensures clause is
// in simple form.
if (isInitEnsuresSimpleForm(init, varDec.getName())) {
// Only deal with initialization ensures of the
// form left = right
if (init instanceof EqualsExp) {
EqualsExp exp = (EqualsExp) init;
// If the initialization of the variable sets
// the variable equal to a value, then we need
// replace the formal with the actual.
if (exp.getLeft() instanceof VarExp) {
PosSymbol exemplar = type.getExemplar();
// TODO: Figure out this evil dragon!
}
}
}
// We must have a complex initialization ensures clause
else {
// The variable must be a variable dot expression,
// therefore we will need to extract the name.
String varName = varDec.getName().getName();
int dotIndex = varName.indexOf(".");
if (dotIndex > 0)
varName = varName.substring(0, dotIndex);
// Check if our confirm clause uses this variable
Exp finalConfirm = myAssertion.getFinalConfirm();
if (finalConfirm.containsVar(varName, false)) {
// We don't have any constraints, so the initialization
// clause implies the final confirm statement and
// set this as our new final confirm statement.
if (constraint.equals(myTypeGraph.getTrueVarExp())) {
myAssertion.setFinalConfirm(myTypeGraph.formImplies(
init, finalConfirm));
}
// We actually have a constraint, so both the initialization
// and constraint imply the final confirm statement.
// This then becomes our new final confirm statement.
else {
InfixExp exp =
myTypeGraph.formConjunct(constraint, init);
myAssertion.setFinalConfirm(myTypeGraph.formImplies(
exp, finalConfirm));
}
}
// Verbose Mode Debug Messages
myVCBuffer.append("\nVariable Declaration Rule Applied: \n");
myVCBuffer.append(myAssertion.assertionToString());
myVCBuffer.append("\n_____________________ \n");
}
}
else {
// Ty not handled.
tyNotHandled(varDec.getTy(), varDec.getLocation());
}
}
} | don't really need to keep track of what we visit in a stack (could use the stack visitor if we wanted to keep track...)
| src/main/java/edu/clemson/cs/r2jt/vcgeneration/VCGenerator.java | don't really need to keep track of what we visit in a stack (could use the stack visitor if we wanted to keep track...) | <ide><path>rc/main/java/edu/clemson/cs/r2jt/vcgeneration/VCGenerator.java
<ide> * <p>The current assertion we are applying
<ide> * VC rules to.</p>
<ide> */
<del> private AssertiveCode myAssertion;
<del>
<del> /**
<del> * <p>A stack to keep track of the RESOLVE Conceptual Elements
<del> * we are still visiting and generating VCs for.</p>
<del> */
<del> private Stack<ResolveConceptualElement> myCurrentVisitingStack;
<add> private AssertiveCode myCurrentAssertiveCode;
<ide>
<ide> /**
<ide> * <p>The current compile environment used throughout
<ide> // Current items
<ide> myCurrentModuleScope = null;
<ide> myCurrentOperationEntry = null;
<del> myCurrentVisitingStack = new Stack<ResolveConceptualElement>();
<ide> myGlobalConstraintExp = null;
<ide> myGlobalRequiresExp = null;
<ide> myOperationDecreasingExp = null;
<ide> myInstanceEnvironment = env;
<ide>
<ide> // VCs + Debugging String
<del> myAssertion = null;
<add> myCurrentAssertiveCode = null;
<ide> myFinalAssertiveCode = new LinkedList<AssertiveCode>();
<ide> myOutputGenerator = null;
<ide> myVCBuffer = new StringBuffer();
<ide> myCurrentModuleScope =
<ide> mySymbolTable.getModuleScope(new ModuleIdentifier(dec));
<ide>
<del> // Store the current visiting item into the stack
<del> myCurrentVisitingStack.push(dec);
<del>
<ide> // From the list of imports, obtain the global constraints
<ide> // of the imported modules.
<ide> myGlobalConstraintExp =
<ide> myCurrentModuleScope = null;
<ide> myGlobalConstraintExp = null;
<ide> myGlobalRequiresExp = null;
<del>
<del> // Pop the top most item from the Stack
<del> // Note: Must be us since we always push in a pre and
<del> // pop in a post.
<del> myCurrentVisitingStack.pop();
<ide> }
<ide>
<ide> // -----------------------------------------------------------
<ide> myCurrentModuleScope =
<ide> mySymbolTable.getModuleScope(new ModuleIdentifier(dec));
<ide>
<del> // Store the current visiting item into the stack
<del> myCurrentVisitingStack.push(dec);
<del>
<ide> // From the list of imports, obtain the global constraints
<ide> // of the imported modules.
<ide> myGlobalConstraintExp =
<ide> myCurrentModuleScope = null;
<ide> myGlobalConstraintExp = null;
<ide> myGlobalRequiresExp = null;
<del>
<del> // Pop the top most item from the Stack
<del> // Note: Must be us since we always push in a pre and
<del> // pop in a post.
<del> myCurrentVisitingStack.pop();
<ide> }
<ide>
<ide> // -----------------------------------------------------------
<ide> myCurrentModuleScope =
<ide> mySymbolTable.getModuleScope(new ModuleIdentifier(dec));
<ide>
<del> // Store the current visiting item into the stack
<del> myCurrentVisitingStack.push(dec);
<del>
<ide> // From the list of imports, obtain the global constraints
<ide> // of the imported modules.
<ide> myGlobalConstraintExp =
<ide> myCurrentModuleScope = null;
<ide> myGlobalConstraintExp = null;
<ide> myGlobalRequiresExp = null;
<del>
<del> // Pop the top most item from the Stack
<del> // Note: Must be us since we always push in a pre and
<del> // pop in a post.
<del> myCurrentVisitingStack.pop();
<ide> }
<ide>
<ide> // -----------------------------------------------------------
<ide> myCurrentOperationEntry =
<ide> searchOperation(dec.getLocation(), null, dec.getName(),
<ide> argTypes);
<del>
<del> // Store the current visiting item into the stack
<del> myCurrentVisitingStack.push(dec);
<ide> }
<ide>
<ide> @Override
<ide> public void postFacilityOperationDec(FacilityOperationDec dec) {
<ide> // Create assertive code
<del> myAssertion = new AssertiveCode(myInstanceEnvironment);
<add> myCurrentAssertiveCode = new AssertiveCode(myInstanceEnvironment);
<ide>
<ide> // Verbose Mode Debug Messages
<ide> myVCBuffer.append("\n=========================");
<ide>
<ide> myOperationDecreasingExp = null;
<ide> myCurrentOperationEntry = null;
<del> myFinalAssertiveCode.add(myAssertion);
<del> myAssertion = null;
<del>
<del> // Pop the top most item from the Stack
<del> // Note: Must be us since we always push in a pre and
<del> // pop in a post.
<del> myCurrentVisitingStack.pop();
<add> myFinalAssertiveCode.add(myCurrentAssertiveCode);
<add> myCurrentAssertiveCode = null;
<ide> }
<ide>
<ide> // -----------------------------------------------------------
<ide>
<ide> @Override
<ide> public void postModuleDec(ModuleDec dec) {
<del> // Make sure that our stack of visiting items is 0.
<del> if (myCurrentVisitingStack.isEmpty()) {
<ide> // Create the output generator and finalize output
<ide> myOutputGenerator =
<ide> new OutputVCs(myInstanceEnvironment, myFinalAssertiveCode,
<ide> filename = createVCFileName();
<ide> }
<ide> myOutputGenerator.outputToFile(filename);
<del> }
<del> else {
<del> incorrectVisit(dec.getName(), dec.getLocation());
<del> }
<ide> }
<ide>
<ide> // -----------------------------------------------------------
<ide> throw new SourceErrorException(message, l);
<ide> }
<ide>
<del> public void incorrectVisit(PosSymbol name, Location l) {
<del> String message =
<del> "After visiting all elements in ModuleDec: " + name
<del> + ", our stack of visiting items is not empty!";
<del> throw new SourceErrorException(message, l);
<del> }
<del>
<ide> public void notAType(SymbolTableEntry entry, Location l) {
<ide> throw new SourceErrorException(entry.getSourceModuleIdentifier()
<ide> .fullyQualifiedRepresentation(entry.getName())
<ide> public void addVarDecsAsFreeVars(List<VarDec> variableList) {
<ide> // Loop through the variable list
<ide> for (VarDec v : variableList) {
<del> myAssertion.addFreeVar(createVarExp(v.getLocation(), v.getName(), v
<add> myCurrentAssertiveCode.addFreeVar(createVarExp(v.getLocation(), v.getName(), v
<ide> .getTy().getMathTypeValue()));
<ide> }
<ide> }
<ide> }
<ide>
<ide> // Add the current variable to our list of free variables
<del> myAssertion.addFreeVar(createVarExp(p.getLocation(), p
<add> myCurrentAssertiveCode.addFreeVar(createVarExp(p.getLocation(), p
<ide> .getName(), pNameTy.getMathTypeValue()));
<ide> }
<ide> else {
<ide> List<ParameterVarDec> paramList, List<AffectsItem> stateVarList,
<ide> List<ProgramExp> argList, boolean isSimple) {
<ide> // Current final confirm
<del> Exp newConfirm = myAssertion.getFinalConfirm();
<add> Exp newConfirm = myCurrentAssertiveCode.getFinalConfirm();
<ide>
<ide> // List to hold temp and real values of variables in case
<ide> // of duplicate spec and real variables
<ide> // Replace state variables in the ensures clause
<ide> // and create new confirm statements if needed.
<ide> for (int i = 0; i < stateVarList.size(); i++) {
<del> newConfirm = myAssertion.getFinalConfirm();
<add> newConfirm = myCurrentAssertiveCode.getFinalConfirm();
<ide> AffectsItem stateVar = stateVarList.get(i);
<ide>
<ide> // Only deal with Alters/Reassigns/Replaces/Updates modes
<ide> || stateVar.getMode() == Mode.UPDATES) {
<ide> // Obtain the variable from our free variable list
<ide> Exp globalFreeVar =
<del> myAssertion.getFreeVar(stateVar.getName(), true);
<add> myCurrentAssertiveCode.getFreeVar(stateVar.getName(), true);
<ide> if (globalFreeVar != null) {
<ide> VarExp oldNamesVar = new VarExp();
<ide> oldNamesVar.setName(stateVar.getName());
<ide>
<ide> // Create a local free variable if it is not there
<ide> Exp localFreeVar =
<del> myAssertion.getFreeVar(stateVar.getName(), false);
<add> myCurrentAssertiveCode.getFreeVar(stateVar.getName(), false);
<ide> if (localFreeVar == null) {
<ide> // TODO: Don't have a type for state variables?
<ide> localFreeVar =
<ide> createQuestionMarkVariable(myTypeGraph
<ide> .formConjunct(ensures, newConfirm),
<ide> (VarExp) localFreeVar);
<del> myAssertion.addFreeVar(localFreeVar);
<add> myCurrentAssertiveCode.addFreeVar(localFreeVar);
<ide> }
<ide> else {
<ide> localFreeVar =
<ide> }
<ide>
<ide> // Set newConfirm as our new final confirm statement
<del> myAssertion.setFinalConfirm(newConfirm);
<add> myCurrentAssertiveCode.setFinalConfirm(newConfirm);
<ide> }
<ide> // Error: Why isn't it a free variable.
<ide> else {
<ide>
<ide> // Obtain the free variable
<ide> VarExp freeVar =
<del> (VarExp) myAssertion.getFreeVar(
<add> (VarExp) myCurrentAssertiveCode.getFreeVar(
<ide> createPosSymbol(replName), false);
<ide> if (freeVar == null) {
<ide> freeVar =
<ide> }
<ide>
<ide> // Add the new free variable to free variable list
<del> myAssertion.addFreeVar(freeVar);
<add> myCurrentAssertiveCode.addFreeVar(freeVar);
<ide>
<ide> // Check if our ensures clause has the parameter variable in it.
<ide> if (ensures.containsVar(VDName.getName(), true)
<ide>
<ide> // Update our final confirm with the parameter argument
<ide> newConfirm = replace(newConfirm, repl, quesVar);
<del> myAssertion.setFinalConfirm(newConfirm);
<add> myCurrentAssertiveCode.setFinalConfirm(newConfirm);
<ide> }
<ide> // All other modes
<ide> else {
<ide> .getTrueVarExp(myTypeGraph))) {
<ide> // Verbose Mode Debug Messages
<ide> myVCBuffer.append("\nAssume Rule Applied and Simplified: \n");
<del> myVCBuffer.append(myAssertion.assertionToString());
<add> myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
<ide> myVCBuffer.append("\n_____________________ \n");
<ide> }
<ide> else {
<ide> // Obtain the current final confirm clause
<del> Exp conf = myAssertion.getFinalConfirm();
<add> Exp conf = myCurrentAssertiveCode.getFinalConfirm();
<ide>
<ide> // Create a new implies expression
<ide> InfixExp newConf =
<ide> myTypeGraph.formImplies((Exp) assume.getAssertion(), conf);
<ide>
<ide> // Set this new expression as the new final confirm
<del> myAssertion.setFinalConfirm(newConf);
<add> myCurrentAssertiveCode.setFinalConfirm(newConf);
<ide>
<ide> // Verbose Mode Debug Messages
<ide> myVCBuffer.append("\nAssume Rule Applied: \n");
<del> myVCBuffer.append(myAssertion.assertionToString());
<add> myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
<ide> myVCBuffer.append("\n_____________________ \n");
<ide> }
<ide> }
<ide> && ((VarExp) confirm.getAssertion()).equals(Exp
<ide> .getTrueVarExp(myTypeGraph))) {
<ide> myVCBuffer.append("\nConfirm Rule Applied and Simplified: \n");
<del> myVCBuffer.append(myAssertion.assertionToString());
<add> myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
<ide> myVCBuffer.append("\n_____________________ \n");
<ide> }
<ide> else {
<ide> // Obtain the current final confirm clause
<del> Exp conf = myAssertion.getFinalConfirm();
<add> Exp conf = myCurrentAssertiveCode.getFinalConfirm();
<ide>
<ide> // Create a new and expression
<ide> InfixExp newConf =
<ide> .formConjunct((Exp) confirm.getAssertion(), conf);
<ide>
<ide> // Set this new expression as the new final confirm
<del> myAssertion.setFinalConfirm(newConf);
<add> myCurrentAssertiveCode.setFinalConfirm(newConf);
<ide>
<ide> // Verbose Mode Debug Messages
<ide> myVCBuffer.append("\nConfirm Rule Applied: \n");
<del> myVCBuffer.append(myAssertion.assertionToString());
<add> myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
<ide> myVCBuffer.append("\n_____________________ \n");
<ide> }
<ide> }
<ide> && assertion.equals(myTypeGraph.getTrueVarExp())) {
<ide> // Verbose Mode Debug Messages
<ide> myVCBuffer.append("\nAssume Rule Applied and Simplified: \n");
<del> myVCBuffer.append(myAssertion.assertionToString());
<add> myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
<ide> myVCBuffer.append("\n_____________________ \n");
<ide>
<ide> return;
<ide>
<ide> // Apply simplification
<ide> Exp currentFinalConfirm =
<del> simplifyAssumeRule(stmt, myAssertion.getFinalConfirm());
<add> simplifyAssumeRule(stmt, myCurrentAssertiveCode.getFinalConfirm());
<ide> if (stmt.getAssertion() != null) {
<ide> // Create a new implies expression
<ide> currentFinalConfirm =
<ide> }
<ide>
<ide> // Set this as our new final confirm
<del> myAssertion.setFinalConfirm(currentFinalConfirm);
<add> myCurrentAssertiveCode.setFinalConfirm(currentFinalConfirm);
<ide>
<ide> // Verbose Mode Debug Messages
<ide> myVCBuffer.append("\nAssume Rule Applied: \n");
<del> myVCBuffer.append(myAssertion.assertionToString());
<add> myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
<ide> myVCBuffer.append("\n_____________________ \n");
<ide> }
<ide>
<ide> ConfirmStmt conf = new ConfirmStmt(loc, exp);
<ide>
<ide> // Add it to our list of assertions
<del> myAssertion.addCode(conf);
<add> myCurrentAssertiveCode.addCode(conf);
<ide> }
<ide>
<ide> // Modify ensures using the parameter modes
<ide> replaceFormalWithActualEns(ensures, opDec.getParameters(),
<ide> opDec.getStateVars(), stmt.getArguments(), false);
<ide>
<del> // Modify the location of the requires clause and add it to myAssertion
<add> // Modify the location of the requires clause and add it to myCurrentAssertiveCode
<ide> if (requires != null) {
<ide> // Obtain the current location
<ide> // Note: If we don't have a location, we create one
<ide> setLocation(requires, loc);
<ide>
<ide> // Add this to our list of things to confirm
<del> myAssertion.addConfirm(requires);
<del> }
<del>
<del> // Modify the location of the requires clause and add it to myAssertion
<add> myCurrentAssertiveCode.addConfirm(requires);
<add> }
<add>
<add> // Modify the location of the requires clause and add it to myCurrentAssertiveCode
<ide> if (ensures != null) {
<ide> // Obtain the current location
<ide> if (stmt.getName().getLocation() != null) {
<ide> }
<ide>
<ide> // Add this to our list of things to assume
<del> myAssertion.addAssume(ensures);
<add> myCurrentAssertiveCode.addAssume(ensures);
<ide> }
<ide>
<ide> // Verbose Mode Debug Messages
<ide> myVCBuffer.append("\nOperation Call Rule Applied: \n");
<del> myVCBuffer.append(myAssertion.assertionToString());
<add> myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
<ide> myVCBuffer.append("\n_____________________ \n");
<ide> }
<ide>
<ide> && assertion.equals(myTypeGraph.getTrueVarExp())) {
<ide> // Verbose Mode Debug Messages
<ide> myVCBuffer.append("\nConfirm Rule Applied and Simplified: \n");
<del> myVCBuffer.append(myAssertion.assertionToString());
<add> myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
<ide> myVCBuffer.append("\n_____________________ \n");
<ide>
<ide> return;
<ide> }
<ide>
<ide> // Obtain the current final confirm statement
<del> Exp currentFinalConfirm = myAssertion.getFinalConfirm();
<add> Exp currentFinalConfirm = myCurrentAssertiveCode.getFinalConfirm();
<ide>
<ide> // Check to see if we have a final confirm of "True"
<ide> if (currentFinalConfirm instanceof VarExp
<ide> setLocation(assertion, loc);
<ide> }
<ide>
<del> myAssertion.setFinalConfirm(assertion);
<add> myCurrentAssertiveCode.setFinalConfirm(assertion);
<ide>
<ide> // Verbose Mode Debug Messages
<ide> myVCBuffer.append("\nConfirm Rule Applied and Simplified: \n");
<del> myVCBuffer.append(myAssertion.assertionToString());
<add> myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
<ide> myVCBuffer.append("\n_____________________ \n");
<ide> }
<ide> else {
<ide> myTypeGraph.formConjunct(assertion, currentFinalConfirm);
<ide>
<ide> // Set this new expression as the new final confirm
<del> myAssertion.setFinalConfirm(newConf);
<add> myCurrentAssertiveCode.setFinalConfirm(newConf);
<ide>
<ide> // Verbose Mode Debug Messages
<ide> myVCBuffer.append("\nConfirm Rule Applied: \n");
<del> myVCBuffer.append(myAssertion.assertionToString());
<add> myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
<ide> myVCBuffer.append("\n_____________________ \n");
<ide> }
<ide> }
<ide> */
<ide> private void applyEBRules() {
<ide> // Apply a proof rule to each of the assertions
<del> while (myAssertion.hasAnotherAssertion()) {
<add> while (myCurrentAssertiveCode.hasAnotherAssertion()) {
<ide> // Work our way from the last assertion
<del> VerificationStatement curAssertion = myAssertion.getLastAssertion();
<add> VerificationStatement curAssertion = myCurrentAssertiveCode.getLastAssertion();
<ide>
<ide> switch (curAssertion.getType()) {
<ide> // Assume Assertion
<ide> ConfirmStmt conf = new ConfirmStmt(loc, exp);
<ide>
<ide> // Add it to our list of assertions
<del> myAssertion.addCode(conf);
<add> myCurrentAssertiveCode.addCode(conf);
<ide> }
<ide>
<ide> // Get the requires clause for this operation
<ide> replaceFormalWithActualReq(requires, opDec.getParameters(),
<ide> assignParamExp.getArguments());
<ide>
<del> // Modify the location of the requires clause and add it to myAssertion
<add> // Modify the location of the requires clause and add it to myCurrentAssertiveCode
<ide> // Obtain the current location
<ide> // Note: If we don't have a location, we create one
<ide> Location reqloc;
<ide> setLocation(requires, reqloc);
<ide>
<ide> // Add this to our list of things to confirm
<del> myAssertion.addConfirm(requires);
<add> myCurrentAssertiveCode.addConfirm(requires);
<ide>
<ide> // Get the ensures clause for this operation
<ide> // Note: If there isn't an ensures clause, it is set to "True"
<ide>
<ide> // Replace all instances of the left hand side
<ide> // variable in the current final confirm statement.
<del> Exp newConf = myAssertion.getFinalConfirm();
<add> Exp newConf = myCurrentAssertiveCode.getFinalConfirm();
<ide> newConf = replace(newConf, leftVariable, ensures);
<ide>
<ide> // Replace the formals with the actuals.
<ide> assignParamExp.getArguments(), false);
<ide>
<ide> // Set this as our new final confirm statement.
<del> myAssertion.setFinalConfirm(newConf);
<add> myCurrentAssertiveCode.setFinalConfirm(newConf);
<ide> }
<ide> else {
<ide> illegalOperationEnsures(opDec.getLocation());
<ide>
<ide> // Verbose Mode Debug Messages
<ide> myVCBuffer.append("\nFunction Rule Applied: \n");
<del> myVCBuffer.append(myAssertion.assertionToString());
<add> myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
<ide> myVCBuffer.append("\n_____________________ \n");
<ide> }
<ide>
<ide> */
<ide> private void applyEBSwapStmtRule(SwapStmt stmt) {
<ide> // Obtain the current final confirm clause
<del> Exp conf = myAssertion.getFinalConfirm();
<add> Exp conf = myCurrentAssertiveCode.getFinalConfirm();
<ide>
<ide> // Create a copy of the left and right hand side
<ide> VariableExp stmtLeft = (VariableExp) Exp.copy(stmt.getLeft());
<ide> conf = replace(conf, tmp, newLeft);
<ide>
<ide> // Set this new expression as the new final confirm
<del> myAssertion.setFinalConfirm(conf);
<add> myCurrentAssertiveCode.setFinalConfirm(conf);
<ide>
<ide> // Verbose Mode Debug Messages
<ide> myVCBuffer.append("\nSwap Rule Applied: \n");
<del> myVCBuffer.append(myAssertion.assertionToString());
<add> myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
<ide> myVCBuffer.append("\n_____________________ \n");
<ide> }
<ide>
<ide> List<Statement> statementList) {
<ide> // Add the global requires clause
<ide> if (myGlobalRequiresExp != null) {
<del> myAssertion.addAssume(myGlobalRequiresExp);
<add> myCurrentAssertiveCode.addAssume(myGlobalRequiresExp);
<ide> }
<ide>
<ide> // Add the global constraints
<ide> if (myGlobalConstraintExp != null) {
<del> myAssertion.addAssume(myGlobalConstraintExp);
<add> myCurrentAssertiveCode.addAssume(myGlobalConstraintExp);
<ide> }
<ide>
<ide> // Add the requires clause
<ide> if (requires != null) {
<del> myAssertion.addAssume(requires);
<add> myCurrentAssertiveCode.addAssume(requires);
<ide> }
<ide>
<ide> // Add the remember rule
<del> myAssertion.addRemember();
<add> myCurrentAssertiveCode.addRemember();
<ide>
<ide> // Add declared variables into the assertion. Also add
<ide> // them to the list of free variables.
<del> myAssertion.addVariableDecs(variableList);
<add> myCurrentAssertiveCode.addVariableDecs(variableList);
<ide> addVarDecsAsFreeVars(variableList);
<ide>
<ide> // Check to see if we have a recursive procedure.
<ide>
<ide> // Add P_val as a free variable
<ide> VarExp pVal = createPValExp(decreasing.getLocation());
<del> myAssertion.addFreeVar(pVal);
<add> myCurrentAssertiveCode.addFreeVar(pVal);
<ide>
<ide> // Create an equals expression
<ide> EqualsExp equalsExp =
<ide> setLocation(equalsExp, eqLoc);
<ide>
<ide> // Add it to our things to assume
<del> myAssertion.addAssume(equalsExp);
<add> myCurrentAssertiveCode.addAssume(equalsExp);
<ide> }
<ide>
<ide> // Add the list of statements
<del> myAssertion.addStatements(statementList);
<add> myCurrentAssertiveCode.addStatements(statementList);
<ide>
<ide> // Add the final confirms clause
<del> myAssertion.setFinalConfirm(ensures);
<add> myCurrentAssertiveCode.setFinalConfirm(ensures);
<ide>
<ide> // Verbose Mode Debug Messages
<ide> myVCBuffer.append("\nProcedure Declaration Rule Applied: \n");
<del> myVCBuffer.append(myAssertion.assertionToString());
<add> myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
<ide> myVCBuffer.append("\n_____________________ \n");
<ide> }
<ide>
<ide> */
<ide> private void applyRememberRule() {
<ide> // Obtain the final confirm and apply the remember method for Exp
<del> Exp conf = myAssertion.getFinalConfirm();
<add> Exp conf = myCurrentAssertiveCode.getFinalConfirm();
<ide> conf = conf.remember();
<del> myAssertion.setFinalConfirm(conf);
<add> myCurrentAssertiveCode.setFinalConfirm(conf);
<ide>
<ide> // Verbose Mode Debug Messages
<ide> myVCBuffer.append("\nRemember Rule Applied: \n");
<del> myVCBuffer.append(myAssertion.assertionToString());
<add> myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
<ide> myVCBuffer.append("\n_____________________ \n");
<ide> }
<ide>
<ide> varName = varName.substring(0, dotIndex);
<ide>
<ide> // Check if our confirm clause uses this variable
<del> Exp finalConfirm = myAssertion.getFinalConfirm();
<add> Exp finalConfirm = myCurrentAssertiveCode.getFinalConfirm();
<ide> if (finalConfirm.containsVar(varName, false)) {
<ide> // We don't have any constraints, so the initialization
<ide> // clause implies the final confirm statement and
<ide> // set this as our new final confirm statement.
<ide> if (constraint.equals(myTypeGraph.getTrueVarExp())) {
<del> myAssertion.setFinalConfirm(myTypeGraph.formImplies(
<add> myCurrentAssertiveCode.setFinalConfirm(myTypeGraph.formImplies(
<ide> init, finalConfirm));
<ide> }
<ide> // We actually have a constraint, so both the initialization
<ide> else {
<ide> InfixExp exp =
<ide> myTypeGraph.formConjunct(constraint, init);
<del> myAssertion.setFinalConfirm(myTypeGraph.formImplies(
<add> myCurrentAssertiveCode.setFinalConfirm(myTypeGraph.formImplies(
<ide> exp, finalConfirm));
<ide> }
<ide> }
<ide>
<ide> // Verbose Mode Debug Messages
<ide> myVCBuffer.append("\nVariable Declaration Rule Applied: \n");
<del> myVCBuffer.append(myAssertion.assertionToString());
<add> myVCBuffer.append(myCurrentAssertiveCode.assertionToString());
<ide> myVCBuffer.append("\n_____________________ \n");
<ide> }
<ide> } |
|
Java | apache-2.0 | 307203e3b4832dd8e3914c4412fa7a203c47ba96 | 0 | cucina/opencucina,cucina/opencucina,cucina/opencucina | package org.cucina.i18n;
import org.apache.commons.lang3.ClassUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.ConverterRegistry;
import org.springframework.core.convert.support.DefaultConversionService;
import org.cucina.core.InstanceFactory;
import org.cucina.core.PackageBasedInstanceFactory;
import org.cucina.core.service.ContextService;
import org.cucina.core.service.ThreadLocalContextService;
import org.cucina.core.spring.ContextPrinter;
import org.cucina.core.spring.SingletonBeanFactory;
import org.cucina.i18n.converter.DtoToListItemConverter;
import org.cucina.i18n.converter.ListItemToDtoConverter;
import org.cucina.i18n.converter.MessageConverter;
import org.cucina.i18n.model.Message;
import org.cucina.i18n.repository.MessageRepository;
import org.cucina.i18n.service.I18nService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* JAVADOC for Class Level
*
* @author $Author: $
* @version $Revision: $
*/
@SpringBootApplication
public class I18nApplication {
private static final Logger LOG = LoggerFactory.getLogger(I18nApplication.class);
/**
* JAVADOC Method Level Comments
*
* @param args
* JAVADOC.
*/
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(I18nApplication.class, args);
((SingletonBeanFactory) SingletonBeanFactory.getInstance()).setBeanFactory(context);
if (LOG.isTraceEnabled()) {
ContextPrinter.traceBeanNames(context, LOG);
}
}
/**
* JAVADOC Method Level Comments
*
* @return JAVADOC.
*/
@Bean
public ContextService contextService() {
return new ThreadLocalContextService();
}
/**
* JAVADOC Method Level Comments
*
* @return JAVADOC.
*/
@Bean
public InstanceFactory instanceFactory() {
return new PackageBasedInstanceFactory(ClassUtils.getPackageName(Message.class));
}
/**
* JAVADOC Method Level Comments
*
* @return JAVADOC.
*/
@Bean
public ConversionService myConversionService(InstanceFactory instanceFactory,
MessageRepository messageRepository, I18nService i18nService) {
ConversionService conversionService = new DefaultConversionService();
if (conversionService instanceof ConverterRegistry) {
((ConverterRegistry) conversionService).addConverter(new MessageConverter());
((ConverterRegistry) conversionService).addConverter(new ListItemToDtoConverter(
i18nService));
((ConverterRegistry) conversionService).addConverter(new DtoToListItemConverter(
messageRepository));
}
return conversionService;
}
}
| i18n/src/main/java/org/cucina/i18n/I18nApplication.java | package org.cucina.i18n;
import org.apache.commons.lang3.ClassUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.ConverterRegistry;
import org.springframework.core.convert.support.DefaultConversionService;
import org.cucina.core.CompositeInstanceFactory;
import org.cucina.core.InstanceFactory;
import org.cucina.core.PackageBasedInstanceFactory;
import org.cucina.core.service.ContextService;
import org.cucina.core.service.ThreadLocalContextService;
import org.cucina.core.spring.ContextPrinter;
import org.cucina.core.spring.SingletonBeanFactory;
import org.cucina.i18n.api.MessageDto;
import org.cucina.i18n.converter.DtoToListItemConverter;
import org.cucina.i18n.converter.ListItemToDtoConverter;
import org.cucina.i18n.converter.MessageConverter;
import org.cucina.i18n.model.Message;
import org.cucina.i18n.repository.MessageRepository;
import org.cucina.i18n.service.I18nService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* JAVADOC for Class Level
*
* @author $Author: $
* @version $Revision: $
*/
@SpringBootApplication
public class I18nApplication {
private static final Logger LOG = LoggerFactory.getLogger(I18nApplication.class);
/**
* JAVADOC Method Level Comments
*
* @param args
* JAVADOC.
*/
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(I18nApplication.class, args);
((SingletonBeanFactory) SingletonBeanFactory.getInstance()).setBeanFactory(context);
if (LOG.isTraceEnabled()) {
ContextPrinter.traceBeanNames(context, LOG);
}
}
/**
* JAVADOC Method Level Comments
*
* @return JAVADOC.
*/
@Bean
public ContextService contextService() {
return new ThreadLocalContextService();
}
/**
* JAVADOC Method Level Comments
*
* @return JAVADOC.
*/
@Bean
public InstanceFactory instanceFactory() {
return new CompositeInstanceFactory(new PackageBasedInstanceFactory(
ClassUtils.getPackageName(Message.class)),
new PackageBasedInstanceFactory(ClassUtils.getPackageName(MessageDto.class)));
}
/**
* JAVADOC Method Level Comments
*
* @return JAVADOC.
*/
@Bean
public ConversionService myConversionService(InstanceFactory instanceFactory,
MessageRepository messageRepository, I18nService i18nService) {
ConversionService conversionService = new DefaultConversionService();
if (conversionService instanceof ConverterRegistry) {
((ConverterRegistry) conversionService).addConverter(new MessageConverter());
((ConverterRegistry) conversionService).addConverter(new ListItemToDtoConverter(
i18nService));
((ConverterRegistry) conversionService).addConverter(new DtoToListItemConverter(
messageRepository));
}
return conversionService;
}
}
| streamlined | i18n/src/main/java/org/cucina/i18n/I18nApplication.java | streamlined | <ide><path>18n/src/main/java/org/cucina/i18n/I18nApplication.java
<ide> import org.springframework.core.convert.converter.ConverterRegistry;
<ide> import org.springframework.core.convert.support.DefaultConversionService;
<ide>
<del>import org.cucina.core.CompositeInstanceFactory;
<ide> import org.cucina.core.InstanceFactory;
<ide> import org.cucina.core.PackageBasedInstanceFactory;
<ide> import org.cucina.core.service.ContextService;
<ide> import org.cucina.core.spring.ContextPrinter;
<ide> import org.cucina.core.spring.SingletonBeanFactory;
<ide>
<del>import org.cucina.i18n.api.MessageDto;
<ide> import org.cucina.i18n.converter.DtoToListItemConverter;
<ide> import org.cucina.i18n.converter.ListItemToDtoConverter;
<ide> import org.cucina.i18n.converter.MessageConverter;
<ide> */
<ide> @Bean
<ide> public InstanceFactory instanceFactory() {
<del> return new CompositeInstanceFactory(new PackageBasedInstanceFactory(
<del> ClassUtils.getPackageName(Message.class)),
<del> new PackageBasedInstanceFactory(ClassUtils.getPackageName(MessageDto.class)));
<add> return new PackageBasedInstanceFactory(ClassUtils.getPackageName(Message.class));
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | 6dc79b067397a9e26c8396e752c17ab1a4f6a97f | 0 | RestExpress/PluginExpress | /*
Copyright 2015, Strategic Gains, 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.restexpress.plugin.correlationid;
import java.util.UUID;
import org.restexpress.Request;
import org.restexpress.Response;
import org.restexpress.RestExpress;
import org.restexpress.pipeline.Postprocessor;
import org.restexpress.pipeline.Preprocessor;
import org.restexpress.plugin.AbstractPlugin;
import org.restexpress.util.RequestContext;
/**
* This RestExpress plugin retrieves the Correlation-ID header from the request
* and adds it to the global, thread-safe RequestContext to be available in deeper
* levels of the application.
*
* If the Correlation-Id header does not exist on the request, one is assigned
* using a UUID string.
*
* The Correlation-Id header is assigned to the response on its way out, also.
*
* @author tfredrich
* @since Jul 25, 2015
*/
public class CorrelationIdPlugin
extends AbstractPlugin
implements Preprocessor, Postprocessor
{
public static final String CORRELATION_ID = "Correlation-Id";
@Override
public AbstractPlugin register(RestExpress server)
{
if (isRegistered()) return this;
super.register(server);
server.addPreprocessor(this);
server.addPostprocessor(this);
return this;
}
/**
* Preprocessor method to pull the Correlation-Id header or assign one
* as well as placing it in the RequestContext.
*
* @param request the incoming Request.
*/
@Override
public void process(Request request)
{
String correlationId = request.getHeader(CORRELATION_ID);
// Generation on empty causes problems, since the request already has a value for Correlation-Id in this case.
// The method call request.addHeader() only adds ANOTHER header to the request and doesn't fix the problem.
// Currently then, the plugin only adds the header if it doesn't exist, assuming that if a client sets the
// header to ANYTHING, that's the correlation ID they desired.
if (correlationId == null) // || correlationId.trim().isEmpty())
{
correlationId = UUID.randomUUID().toString();
}
RequestContext.put(CORRELATION_ID, correlationId);
request.addHeader(CORRELATION_ID, correlationId);
}
/**
* Postprocessor method that assigns the Correlation-Id from the
* request to a header on the Response.
*
* @param request the incoming Request.
* @param response the outgoing Response.
*/
@Override
public void process(Request request, Response response)
{
if (!response.hasHeader(CORRELATION_ID))
{
response.addHeader(CORRELATION_ID, request.getHeader(CORRELATION_ID));
}
}
}
| correlation-id/src/main/java/org/restexpress/plugin/correlationid/CorrelationIdPlugin.java | /*
Copyright 2015, Strategic Gains, 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.restexpress.plugin.correlationid;
import java.util.UUID;
import org.restexpress.Request;
import org.restexpress.Response;
import org.restexpress.RestExpress;
import org.restexpress.pipeline.Postprocessor;
import org.restexpress.pipeline.Preprocessor;
import org.restexpress.plugin.AbstractPlugin;
import org.restexpress.util.RequestContext;
/**
* This RestExpress plugin retrieves the Correlation-ID header from the request
* and adds it to the global, thread-safe RequestContext to be available in deeper
* levels of the application.
*
* If the Correlation-Id header does not exist on the request, one is assigned
* using a UUID string.
*
* The Correlation-Id header is assigned to the response on its way out, also.
*
* @author tfredrich
* @since Jul 25, 2015
*/
public class CorrelationIdPlugin
extends AbstractPlugin
implements Preprocessor, Postprocessor
{
public static final String CORRELATION_ID = "Correlation-Id";
@Override
public AbstractPlugin register(RestExpress server)
{
if (isRegistered()) return this;
super.register(server);
server.addPreprocessor(this);
return this;
}
/**
* Preprocessor method to pull the Correlation-Id header or assign one
* as well as placing it in the RequestContext.
*
* @param request the incoming Request.
*/
@Override
public void process(Request request)
{
String correlationId = request.getHeader(CORRELATION_ID);
// Generation on empty causes problems, since the request already has a value for Correlation-Id in this case.
// The method call request.addHeader() only adds ANOTHER header to the request and doesn't fix the problem.
// Currently then, the plugin only adds the header if it doesn't exist, assuming that if a client sets the
// header to ANYTHING, that's the correlation ID they desired.
if (correlationId == null) // || correlationId.trim().isEmpty())
{
correlationId = UUID.randomUUID().toString();
}
RequestContext.put(CORRELATION_ID, correlationId);
request.addHeader(CORRELATION_ID, correlationId);
}
/**
* Postprocessor method that assigns the Correlation-Id from the
* request to a header on the Response.
*
* @param request the incoming Request.
* @param response the outgoing Response.
*/
@Override
public void process(Request request, Response response)
{
if (!response.hasHeader(CORRELATION_ID))
{
response.addHeader(CORRELATION_ID, request.getHeader(CORRELATION_ID));
}
}
}
| Adding Postprocessor to the server
| correlation-id/src/main/java/org/restexpress/plugin/correlationid/CorrelationIdPlugin.java | Adding Postprocessor to the server | <ide><path>orrelation-id/src/main/java/org/restexpress/plugin/correlationid/CorrelationIdPlugin.java
<ide>
<ide> super.register(server);
<ide> server.addPreprocessor(this);
<del>
<add> server.addPostprocessor(this);
<ide> return this;
<ide> }
<ide> |
|
Java | epl-1.0 | 69037b61ba25ec0ef041291b09336cdb09ad5948 | 0 | mareknovotny/windup,johnsteele/windup,mareknovotny/windup,OndraZizka/windup,jsight/windup,windup/windup,d-s/windup,jsight/windup,windup/windup,Maarc/windup,windup/windup,jsight/windup,windup/windup,johnsteele/windup,OndraZizka/windup,OndraZizka/windup,johnsteele/windup,Maarc/windup,d-s/windup,Maarc/windup,d-s/windup,johnsteele/windup,jsight/windup,mareknovotny/windup,d-s/windup,mareknovotny/windup,Maarc/windup,OndraZizka/windup | package org.jboss.windup.rules.apps.java.reporting.freemarker;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.apache.commons.lang.StringUtils;
import org.jboss.windup.config.GraphRewrite;
import org.jboss.windup.graph.GraphContext;
import org.jboss.windup.graph.model.LinkModel;
import org.jboss.windup.graph.model.resource.FileModel;
import org.jboss.windup.graph.model.resource.ReportResourceFileModel;
import org.jboss.windup.reporting.freemarker.WindupFreeMarkerTemplateDirective;
import org.jboss.windup.reporting.model.association.LinkableModel;
import org.jboss.windup.reporting.model.source.SourceReportModel;
import org.jboss.windup.reporting.service.SourceReportService;
import org.jboss.windup.rules.apps.java.model.JavaClassFileModel;
import org.jboss.windup.rules.apps.java.model.JavaClassModel;
import org.jboss.windup.rules.apps.java.model.JavaSourceFileModel;
import org.jboss.windup.rules.apps.java.service.JavaClassService;
import org.jboss.windup.rules.files.model.FileLocationModel;
import org.jboss.windup.util.Logging;
import freemarker.core.Environment;
import freemarker.ext.beans.StringModel;
import freemarker.template.SimpleScalar;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
/**
* Renders linkable elements as a list of links
*
* @author <a href="mailto:[email protected]">Brad Davis</a>
*
*/
public class RenderLinkDirective implements WindupFreeMarkerTemplateDirective
{
private static final Logger LOG = Logging.get(RenderLinkDirective.class);
public static final String NAME = "render_link";
private GraphContext context;
private SourceReportService sourceReportService;
private JavaClassService javaClassService;
@Override
public String getDescription()
{
return "Takes the following parameters: FileModel (a " + FileModel.class.getSimpleName() + ")";
}
@Override
public void execute(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
throws TemplateException, IOException
{
final Writer writer = env.getOut();
StringModel stringModel = (StringModel) params.get("model");
SimpleScalar defaultTextModel = (SimpleScalar) params.get("text");
String defaultText = params.get("text") == null ? null : defaultTextModel.getAsString();
if (stringModel == null || stringModel.getWrappedObject() == null)
{
if (StringUtils.isNotBlank(defaultText))
writer.append(defaultText);
else
{
writer.append("unknown");
LOG.warning("Failed to resolve name or text for " + getClass().getName() + ". " + env);
}
return;
}
Object model = stringModel.getWrappedObject();
LayoutType layoutType = resolveLayoutType(params);
String cssClass = resolveCssClass(params);
if (model instanceof FileLocationModel)
{
processFileLocationModel(writer, cssClass, (FileLocationModel) model, defaultText);
}
else if (model instanceof FileModel)
{
processFileModel(writer, cssClass, (FileModel) model, defaultText);
}
else if (model instanceof JavaClassModel)
{
processJavaClassModel(writer, layoutType, cssClass, (JavaClassModel) model, defaultText);
}
else if (model instanceof LinkableModel)
{
processLinkableModel(writer, layoutType, cssClass, (LinkableModel) model, defaultText);
}
else
{
throw new TemplateException("Object type not permitted: " + model.getClass().getSimpleName(), env);
}
}
private String resolveCssClass(Map params)
{
SimpleScalar renderStyleModel = (SimpleScalar) params.get("class");
if (renderStyleModel != null)
{
return renderStyleModel.getAsString();
}
return "";
}
private LayoutType resolveLayoutType(Map params) throws TemplateException
{
LayoutType layoutType = LayoutType.HORIZONTAL;
SimpleScalar layoutModel = (SimpleScalar) params.get("layout");
if (layoutModel != null)
{
String lt = layoutModel.getAsString();
try
{
layoutType = LayoutType.valueOf(lt.toUpperCase());
}
catch (IllegalArgumentException e)
{
throw new TemplateException("Layout: " + lt + " is not supported.", e, null);
}
}
return layoutType;
}
private void processFileLocationModel(Writer writer, String cssClass, FileLocationModel obj, String defaultText) throws IOException
{
String position = " (" + obj.getLineNumber() + ", " + obj.getColumnNumber() + ")";
String linkText = StringUtils.isBlank(defaultText) ? getPrettyPathForFile(obj.getFile()) + position : defaultText;
String anchor = obj.asVertex().getId().toString();
SourceReportModel result = sourceReportService.getSourceReportForFileModel(obj.getFile());
if (result == null)
writer.write(linkText);
else
renderLink(writer, cssClass, result.getReportFilename() + "#" + anchor, linkText);
}
private void processLinkableModel(Writer writer, LayoutType layoutType, String cssClass, LinkableModel obj, String defaultText) throws IOException
{
List<Link> links = new LinkedList<>();
for (LinkModel model : obj.getLinks())
{
Link l = new Link(model.getLink(), model.getDescription());
links.add(l);
}
renderLinks(writer, layoutType, cssClass, links);
}
private void processFileModel(Writer writer, String cssClass, FileModel fileModel, String defaultText) throws IOException
{
String linkText = StringUtils.isBlank(defaultText) ? getPrettyPathForFile(fileModel) : defaultText;
SourceReportModel result = sourceReportService.getSourceReportForFileModel(fileModel);
if (result == null)
{
writer.write(linkText);
}
else
{
renderLink(writer, cssClass, result.getReportFilename(), linkText);
}
}
private void processJavaClassModel(Writer writer, LayoutType layoutType, String cssClass, JavaClassModel clz, String defaultText)
throws IOException
{
Iterator<JavaSourceFileModel> results = javaClassService.getJavaSource(clz.getQualifiedName()).iterator();
int i = 0;
if (results.hasNext())
{
while (results.hasNext())
{
if (i == 0)
{
String linkText = StringUtils.isBlank(defaultText) ? clz.getQualifiedName() : defaultText;
JavaSourceFileModel source = results.next();
SourceReportModel result = sourceReportService.getSourceReportForFileModel(source);
if (result == null)
{
writer.write(linkText);
}
else
{
renderLink(writer, cssClass, result.getReportFilename(), linkText);
}
}
else
{
JavaSourceFileModel source = results.next();
SourceReportModel result = sourceReportService.getSourceReportForFileModel(source);
if (result == null)
{
writer.write(" (" + (i + 1) + ")");
}
else
{
renderLink(writer, cssClass, result.getReportFilename(), " (" + (i + 1) + ")");
}
}
i++;
}
}
else
{
writer.write(clz.getQualifiedName());
}
}
private void renderLinks(Writer writer, LayoutType layoutType, String cssClass, Iterable<Link> linkIterable) throws IOException
{
Iterator<Link> links = linkIterable.iterator();
if (layoutType == LayoutType.UL)
{
renderAsUL(writer, links);
}
if (layoutType == LayoutType.LI)
{
renderAsLI(writer, links);
}
else if (layoutType == LayoutType.DL)
{
renderAsDL(writer, links);
}
else if (layoutType == LayoutType.DT)
{
renderAsDT(writer, links);
}
else
{
renderAsHorizontal(writer, links);
}
}
private void renderLink(Writer writer, String cssClass, String href, String linkText) throws IOException
{
if (cssClass == null)
{
cssClass = "";
}
writer.append("<a class='" + cssClass + "' href='" + href + "'>");
writer.append(linkText);
writer.append("</a>");
}
/*
* Wraps with UL tags
*/
private void renderAsUL(Writer writer, Iterator<Link> links) throws IOException
{
if (links.hasNext())
{
writer.append("<ul>");
renderAsLI(writer, links);
writer.append("</ul>");
}
}
/*
* Renders only LI tags
*/
private void renderAsLI(Writer writer, Iterator<Link> links) throws IOException
{
if (links.hasNext())
{
while (links.hasNext())
{
Link link = links.next();
writer.append("<li>");
renderLink(writer, link);
writer.append("</li>");
}
}
}
/*
* Renders the full DL
*/
private void renderAsDL(Writer writer, Iterator<Link> links) throws IOException
{
if (links.hasNext())
{
writer.append("<dl>");
renderAsDT(writer, links);
writer.append("</dl>");
}
}
/*
* Renders as DT elements
*/
private void renderAsDT(Writer writer, Iterator<Link> links) throws IOException
{
if (links.hasNext())
{
while (links.hasNext())
{
Link link = links.next();
writer.append("<dt>");
writer.append(link.getDescription());
writer.append("</dt>");
writer.append("<dd>");
writer.append("<a href='" + link.getLink() + "'>Link</a>");
writer.append("</dd>");
}
}
}
private void renderAsHorizontal(Writer writer, Iterator<Link> links) throws IOException
{
while (links.hasNext())
{
Link link = links.next();
renderLink(writer, link);
if (links.hasNext())
{
writer.append(" | ");
}
}
}
private void renderLink(Writer writer, Link link) throws IOException
{
writer.append("<a href='" + link.getLink() + "'>");
writer.append(link.getDescription());
writer.append("</a>");
}
private String getPrettyPathForFile(FileModel fileModel)
{
if (fileModel instanceof JavaClassFileModel)
{
JavaClassFileModel jcfm = (JavaClassFileModel) fileModel;
if (jcfm.getJavaClass() == null)
return fileModel.getPrettyPathWithinProject();
else
return jcfm.getJavaClass().getQualifiedName();
}
else if (fileModel instanceof ReportResourceFileModel)
{
return "resources/" + fileModel.getPrettyPath();
}
else if (fileModel instanceof JavaSourceFileModel)
{
JavaSourceFileModel javaSourceModel = (JavaSourceFileModel) fileModel;
String filename = fileModel.getFileName();
String packageName = javaSourceModel.getPackageName();
if (filename.endsWith(".java"))
{
filename = filename.substring(0, filename.length() - 5);
}
return packageName == null || packageName.isEmpty() ? filename : packageName + "." + filename;
}
else
{
return fileModel.getPrettyPathWithinProject();
}
}
@Override
public String getDirectiveName()
{
return NAME;
}
@Override
public void setContext(GraphRewrite event)
{
this.context = event.getGraphContext();
this.sourceReportService = new SourceReportService(this.context);
this.javaClassService = new JavaClassService(this.context);
}
private static enum LayoutType
{
HORIZONTAL, UL, DL, LI, DT
}
public enum RenderStyleType
{
DEFAULT, LABEL
}
private static class Link
{
private final String link;
private final String description;
Link(String link, String description)
{
this.link = link;
this.description = description;
}
public String getLink()
{
return link;
}
public String getDescription()
{
return description;
}
}
}
| rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/reporting/freemarker/RenderLinkDirective.java | package org.jboss.windup.rules.apps.java.reporting.freemarker;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.apache.commons.lang.StringUtils;
import org.jboss.windup.config.GraphRewrite;
import org.jboss.windup.graph.GraphContext;
import org.jboss.windup.graph.model.LinkModel;
import org.jboss.windup.graph.model.resource.FileModel;
import org.jboss.windup.graph.model.resource.ReportResourceFileModel;
import org.jboss.windup.reporting.freemarker.WindupFreeMarkerTemplateDirective;
import org.jboss.windup.reporting.model.association.LinkableModel;
import org.jboss.windup.reporting.model.source.SourceReportModel;
import org.jboss.windup.reporting.service.SourceReportService;
import org.jboss.windup.rules.apps.java.model.JavaClassFileModel;
import org.jboss.windup.rules.apps.java.model.JavaClassModel;
import org.jboss.windup.rules.apps.java.model.JavaSourceFileModel;
import org.jboss.windup.rules.apps.java.service.JavaClassService;
import org.jboss.windup.rules.files.model.FileLocationModel;
import org.jboss.windup.util.Logging;
import freemarker.core.Environment;
import freemarker.ext.beans.StringModel;
import freemarker.template.SimpleScalar;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
/**
* Renders linkable elements as a list of links
*
* @author <a href="mailto:[email protected]">Brad Davis</a>
*
*/
public class RenderLinkDirective implements WindupFreeMarkerTemplateDirective
{
private static final Logger LOG = Logging.get(RenderLinkDirective.class);
public static final String NAME = "render_link";
private GraphContext context;
private SourceReportService sourceReportService;
private JavaClassService javaClassService;
@Override
public String getDescription()
{
return "Takes the following parameters: FileModel (a " + FileModel.class.getSimpleName() + ")";
}
@Override
public void execute(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
throws TemplateException, IOException
{
final Writer writer = env.getOut();
StringModel stringModel = (StringModel) params.get("model");
SimpleScalar defaultTextModel = (SimpleScalar) params.get("text");
String defaultText = params.get("text") == null ? null : defaultTextModel.getAsString();
if (stringModel == null || stringModel.getWrappedObject() == null)
{
if (StringUtils.isNotBlank(defaultText))
writer.append(defaultText);
else
{
writer.append("unknown");
LOG.warning("Failed to resolve name or text for " + getClass().getName() + ". " + env);
}
return;
}
Object model = stringModel.getWrappedObject();
LayoutType layoutType = resolveLayoutType(params);
String cssClass = resolveCssClass(params);
if (model instanceof FileLocationModel)
{
processFileLocationModel(writer, cssClass, (FileLocationModel) model, defaultText);
}
else if (model instanceof FileModel)
{
processFileModel(writer, cssClass, (FileModel) model, defaultText);
}
else if (model instanceof JavaClassModel)
{
processJavaClassModel(writer, layoutType, cssClass, (JavaClassModel) model, defaultText);
}
else if (model instanceof LinkableModel)
{
processLinkableModel(writer, layoutType, cssClass, (LinkableModel) model, defaultText);
}
else
{
throw new TemplateException("Object type not permitted: " + model.getClass().getSimpleName(), env);
}
}
private String resolveCssClass(Map params)
{
SimpleScalar renderStyleModel = (SimpleScalar) params.get("class");
if (renderStyleModel != null)
{
return renderStyleModel.getAsString();
}
return "";
}
private LayoutType resolveLayoutType(Map params) throws TemplateException
{
LayoutType layoutType = LayoutType.HORIZONTAL;
SimpleScalar layoutModel = (SimpleScalar) params.get("layout");
if (layoutModel != null)
{
String lt = layoutModel.getAsString();
try
{
layoutType = LayoutType.valueOf(lt.toUpperCase());
}
catch (IllegalArgumentException e)
{
throw new TemplateException("Layout: " + lt + " is not supported.", e, null);
}
}
return layoutType;
}
private void processFileLocationModel(Writer writer, String cssClass, FileLocationModel obj, String defaultText) throws IOException
{
String position = " (" + obj.getLineNumber() + ", " + obj.getColumnNumber() + ")";
String linkText = StringUtils.isBlank(defaultText) ? getPrettyPathForFile(obj.getFile()) + position : defaultText;
String anchor = obj.asVertex().getId().toString();
SourceReportModel result = sourceReportService.getSourceReportForFileModel(obj.getFile());
if (result == null)
{
writer.write(linkText);
}
renderLink(writer, cssClass, result.getReportFilename() + "#" + anchor, linkText);
}
private void processLinkableModel(Writer writer, LayoutType layoutType, String cssClass, LinkableModel obj, String defaultText) throws IOException
{
List<Link> links = new LinkedList<>();
for (LinkModel model : obj.getLinks())
{
Link l = new Link(model.getLink(), model.getDescription());
links.add(l);
}
renderLinks(writer, layoutType, cssClass, links);
}
private void processFileModel(Writer writer, String cssClass, FileModel fileModel, String defaultText) throws IOException
{
String linkText = StringUtils.isBlank(defaultText) ? getPrettyPathForFile(fileModel) : defaultText;
SourceReportModel result = sourceReportService.getSourceReportForFileModel(fileModel);
if (result == null)
{
writer.write(linkText);
}
else
{
renderLink(writer, cssClass, result.getReportFilename(), linkText);
}
}
private void processJavaClassModel(Writer writer, LayoutType layoutType, String cssClass, JavaClassModel clz, String defaultText)
throws IOException
{
Iterator<JavaSourceFileModel> results = javaClassService.getJavaSource(clz.getQualifiedName()).iterator();
int i = 0;
if (results.hasNext())
{
while (results.hasNext())
{
if (i == 0)
{
String linkText = StringUtils.isBlank(defaultText) ? clz.getQualifiedName() : defaultText;
JavaSourceFileModel source = results.next();
SourceReportModel result = sourceReportService.getSourceReportForFileModel(source);
if (result == null)
{
writer.write(linkText);
}
else
{
renderLink(writer, cssClass, result.getReportFilename(), linkText);
}
}
else
{
JavaSourceFileModel source = results.next();
SourceReportModel result = sourceReportService.getSourceReportForFileModel(source);
if (result == null)
{
writer.write(" (" + (i + 1) + ")");
}
else
{
renderLink(writer, cssClass, result.getReportFilename(), " (" + (i + 1) + ")");
}
}
i++;
}
}
else
{
writer.write(clz.getQualifiedName());
}
}
private void renderLinks(Writer writer, LayoutType layoutType, String cssClass, Iterable<Link> linkIterable) throws IOException
{
Iterator<Link> links = linkIterable.iterator();
if (layoutType == LayoutType.UL)
{
renderAsUL(writer, links);
}
if (layoutType == LayoutType.LI)
{
renderAsLI(writer, links);
}
else if (layoutType == LayoutType.DL)
{
renderAsDL(writer, links);
}
else if (layoutType == LayoutType.DT)
{
renderAsDT(writer, links);
}
else
{
renderAsHorizontal(writer, links);
}
}
private void renderLink(Writer writer, String cssClass, String href, String linkText) throws IOException
{
if (cssClass == null)
{
cssClass = "";
}
writer.append("<a class='" + cssClass + "' href='" + href + "'>");
writer.append(linkText);
writer.append("</a>");
}
/*
* Wraps with UL tags
*/
private void renderAsUL(Writer writer, Iterator<Link> links) throws IOException
{
if (links.hasNext())
{
writer.append("<ul>");
renderAsLI(writer, links);
writer.append("</ul>");
}
}
/*
* Renders only LI tags
*/
private void renderAsLI(Writer writer, Iterator<Link> links) throws IOException
{
if (links.hasNext())
{
while (links.hasNext())
{
Link link = links.next();
writer.append("<li>");
renderLink(writer, link);
writer.append("</li>");
}
}
}
/*
* Renders the full DL
*/
private void renderAsDL(Writer writer, Iterator<Link> links) throws IOException
{
if (links.hasNext())
{
writer.append("<dl>");
renderAsDT(writer, links);
writer.append("</dl>");
}
}
/*
* Renders as DT elements
*/
private void renderAsDT(Writer writer, Iterator<Link> links) throws IOException
{
if (links.hasNext())
{
while (links.hasNext())
{
Link link = links.next();
writer.append("<dt>");
writer.append(link.getDescription());
writer.append("</dt>");
writer.append("<dd>");
writer.append("<a href='" + link.getLink() + "'>Link</a>");
writer.append("</dd>");
}
}
}
private void renderAsHorizontal(Writer writer, Iterator<Link> links) throws IOException
{
while (links.hasNext())
{
Link link = links.next();
renderLink(writer, link);
if (links.hasNext())
{
writer.append(" | ");
}
}
}
private void renderLink(Writer writer, Link link) throws IOException
{
writer.append("<a href='" + link.getLink() + "'>");
writer.append(link.getDescription());
writer.append("</a>");
}
private String getPrettyPathForFile(FileModel fileModel)
{
if (fileModel instanceof JavaClassFileModel)
{
JavaClassFileModel jcfm = (JavaClassFileModel) fileModel;
if (jcfm.getJavaClass() == null)
return fileModel.getPrettyPathWithinProject();
else
return jcfm.getJavaClass().getQualifiedName();
}
else if (fileModel instanceof ReportResourceFileModel)
{
return "resources/" + fileModel.getPrettyPath();
}
else if (fileModel instanceof JavaSourceFileModel)
{
JavaSourceFileModel javaSourceModel = (JavaSourceFileModel) fileModel;
String filename = fileModel.getFileName();
String packageName = javaSourceModel.getPackageName();
if (filename.endsWith(".java"))
{
filename = filename.substring(0, filename.length() - 5);
}
return packageName == null || packageName.isEmpty() ? filename : packageName + "." + filename;
}
else
{
return fileModel.getPrettyPathWithinProject();
}
}
@Override
public String getDirectiveName()
{
return NAME;
}
@Override
public void setContext(GraphRewrite event)
{
this.context = event.getGraphContext();
this.sourceReportService = new SourceReportService(this.context);
this.javaClassService = new JavaClassService(this.context);
}
private static enum LayoutType
{
HORIZONTAL, UL, DL, LI, DT
}
public enum RenderStyleType
{
DEFAULT, LABEL
}
private static class Link
{
private final String link;
private final String description;
Link(String link, String description)
{
this.link = link;
this.description = description;
}
public String getLink()
{
return link;
}
public String getDescription()
{
return description;
}
}
}
| Fix bug in RenderLinkDirectove#processFileLocationModel()
Might fix WINDUP-966 | rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/reporting/freemarker/RenderLinkDirective.java | Fix bug in RenderLinkDirectove#processFileLocationModel() | <ide><path>ules-java/api/src/main/java/org/jboss/windup/rules/apps/java/reporting/freemarker/RenderLinkDirective.java
<ide>
<ide> SourceReportModel result = sourceReportService.getSourceReportForFileModel(obj.getFile());
<ide> if (result == null)
<del> {
<ide> writer.write(linkText);
<del> }
<del> renderLink(writer, cssClass, result.getReportFilename() + "#" + anchor, linkText);
<add> else
<add> renderLink(writer, cssClass, result.getReportFilename() + "#" + anchor, linkText);
<ide> }
<ide>
<ide> private void processLinkableModel(Writer writer, LayoutType layoutType, String cssClass, LinkableModel obj, String defaultText) throws IOException |
|
Java | agpl-3.0 | 4ef4e2eb1d0f2bb4de68d2c808d7499c948c836b | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | 340f2b6a-2e62-11e5-9284-b827eb9e62be | hello.java | 3409c18e-2e62-11e5-9284-b827eb9e62be | 340f2b6a-2e62-11e5-9284-b827eb9e62be | hello.java | 340f2b6a-2e62-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>3409c18e-2e62-11e5-9284-b827eb9e62be
<add>340f2b6a-2e62-11e5-9284-b827eb9e62be |
|
Java | mpl-2.0 | 1ae6708de42e82073f317774140fde11b1c69d9f | 0 | Prof9/mmbn-randomizer | package mmbn;
public class ShopItem extends Item {
protected int stock;
protected int price;
public ShopItem(byte[] base) {
super(base);
this.stock = 0;
this.price = 0;
}
public ShopItem(ShopItem shopItem) {
super(shopItem);
this.stock = shopItem.stock;
this.price = shopItem.price;
}
public void setItem(Item item) {
this.type = item.type;
this.value = item.value;
this.subValue = item.subValue;
this.chip = item.chip;
}
public int getStock() {
return this.stock;
}
public void setStock(int stock) {
this.stock = stock;
}
public int getPrice() {
return this.price;
}
public void setPrice(int price) {
this.price = price;
}
}
| src/mmbn/ShopItem.java | package mmbn;
public class ShopItem extends Item {
protected int stock;
protected int price;
public ShopItem(byte[] base) {
super(base);
this.stock = 0;
this.price = 0;
}
public int getStock() {
return this.stock;
}
public void setStock(int stock) {
this.stock = stock;
}
public int getPrice() {
return this.price;
}
public void setPrice(int price) {
this.price = price;
}
}
| Added way to clone ShopItem and replace all properties inherited from Item.
| src/mmbn/ShopItem.java | Added way to clone ShopItem and replace all properties inherited from Item. | <ide><path>rc/mmbn/ShopItem.java
<ide> super(base);
<ide> this.stock = 0;
<ide> this.price = 0;
<add> }
<add> public ShopItem(ShopItem shopItem) {
<add> super(shopItem);
<add> this.stock = shopItem.stock;
<add> this.price = shopItem.price;
<add> }
<add>
<add> public void setItem(Item item) {
<add> this.type = item.type;
<add> this.value = item.value;
<add> this.subValue = item.subValue;
<add> this.chip = item.chip;
<ide> }
<ide>
<ide> public int getStock() { |
|
JavaScript | mit | f2105fedbe101fca2238b8ea68d488b198460f62 | 0 | monsterlane/node-runner |
/**
* View: Html
*/
var config = require( '../../config' )( ),
util = require( '../../helpers/util' ),
fs = require( 'fs' ),
async = require( 'async' ),
dot = require( 'dot' ),
Base_view = require( './view' );
function Html_view( res, name ) {
Base_view.apply( this, arguments );
this._name = name;
this._webPath = '/' + this._name;
this._filePath = '/controllers/' + this._name;
this._viewPath = this._filePath + '/views';
this._meta = [ ];
this._styles = [ ];
this._scripts = [ ];
this.resolveOptions( );
this.resolveMetaTags( );
this.resolveIncludes( );
}
util.inherits( Html_view, Base_view );
/**
* Method: resolveOptions
*/
Html_view.prototype.resolveOptions = function( ) {
this.getOptions( ).set( 'app.use.googleAnalytics', null );
};
/**
* Method: resolveMetaTags
*/
Html_view.prototype.resolveMetaTags = function( ) {
this.addMetaTag( 'author', 'Jonathan Down' );
this.addMetaTag( 'description', 'An HTML5 app framework written in Express, doT.js, MongoDB, and Redis' );
this.addMetaTag( 'robots', 'index,follow' );
this.addMetaTag( 'viewport', 'initial-scale=1.0,width=device-width' );
};
/**
* Method: addMetaTag
* @param {String} name
* @param {String} content
*/
Html_view.prototype.addMetaTag = function( name, content ) {
this._meta.push( {
name: name,
content: content
} );
};
/**
* Method: createMetaTags
* @return {String}
*/
Html_view.prototype.createMetaTags = function( ) {
var str = '',
i, len;
for ( i = 0, len = this._meta.length; i < len; i++ ) {
str += '<meta name="' + this._meta[ i ].name + '" content="' + this._meta[ i ].content + '" />';
}
return str;
};
/**
* Method: resolveIncludes
*/
Html_view.prototype.resolveIncludes = function( ) {
var opts = { group: 0 };
this.addStyle( '/base/css/bootstrap.min.css', opts );
this.addScript( '/base/js/jquery.min.js', opts );
this.addScript( '/base/js/bootstrap.min.js', opts );
this.addScript( '/base/js/app.js', opts );
this.addScript( '/base/js/app.module.js', opts );
};
/**
* Method: addStyle
* @param {String} path
* @param {Object} opts
*/
Html_view.prototype.addStyle = function( path, opts ) {
var opts = util.merge( {
group: 1,
media: 'all'
}, opts );
if ( !this._styles[ opts.group ] ) {
this._styles[ opts.group ] = [ ];
}
this._styles[ opts.group ].push( {
path: path,
media: opts.media
} );
};
/**
* Method: createStyleIncludes
* @return {String}
*/
Html_view.prototype.createStyleIncludes = function( ) {
var t = new Date( ).getTime( ),
str = '',
i, len1,
j, len2;
for ( i = 0, len1 = this._styles.length; i < len1; i++ ) {
for ( j = 0, len2 = this._styles[ i ].length; j < len2; j++ ) {
if ( config.environment == 'development' && this._styles[ i ][ j ].path.substring( 0, 2 ) != '//' && this._styles[ i ][ j ].path.indexOf( '.min.' ) == -1 ) {
str += '<link href="' + this._styles[ i ][ j ].path + '?t=' + t + '" type="text/css" rel="stylesheet" media="' + this._styles[ i ][ j ].media + '" />';
}
else {
str += '<link href="' + this._styles[ i ][ j ].path + '" type="text/css" rel="stylesheet" media="' + this._styles[ i ][ j ].media + '" />';
}
}
}
return str;
};
/**
* Method: addScript
* @param {String} path
* @param {Object} opts
*/
Html_view.prototype.addScript = function( path, opts ) {
var opts = util.merge( {
group: 1
}, opts );
if ( !this._scripts[ opts.group ] ) {
this._scripts[ opts.group ] = [ ];
}
this._scripts[ opts.group ].push( {
path: path,
} );
};
/**
* Method: createScriptIncludes
* @return {String}
*/
Html_view.prototype.createScriptIncludes = function( ) {
var t = new Date( ).getTime( ),
str = '',
i, len1,
j, len2;
for ( i = 0, len1 = this._scripts.length; i < len1; i++ ) {
for ( j = 0, len2 = this._scripts[ i ].length; j < len2; j++ ) {
if ( config.environment == 'development' && this._scripts[ i ][ j ].path.substring( 0, 2 ) != '//' && this._scripts[ i ][ j ].path.indexOf( '.min.' ) == -1 ) {
str += '<script src="' + this._scripts[ i ][ j ].path + '?t=' + t + '" type="text/javascript"></script>';
}
else {
str += '<script src="' + this._scripts[ i ][ j ].path + '" type="text/javascript"></script>';
}
}
}
return str;
};
/**
* Method: getDocumentTitle
* @return {String}
*/
Html_view.prototype.getDocumentTitle = function( ) {
return this._name;
};
/**
* Method: getDocumentContent
* @param {Object} def
* @param {Function} callback
*/
Html_view.prototype.getDocumentContent = function( def, callback ) {
var def = util.merge( {
name: config.name,
title: this.getDocumentTitle( ),
meta: this.createMetaTags( ),
styles: this.createStyleIncludes( ),
module: this._name.charAt( 0 ).toUpperCase( ) + this._name.slice( 1 ),
scripts: this.createScriptIncludes( ),
analytics: this.getOptions( ).get( 'app.use.googleAnalytics' )
}, def );
this.partial( '/controllers/base/views/document.html', def, function( err, content ) {
callback( err, content );
});
};
/**
* Method: partial
* @param {String} path
* @param {Object} def
* @param {Function} callback
*/
Html_view.prototype.partial = function( path, def, callback ) {
var path = ( path.indexOf( '/' ) == -1 ) ? this._viewPath + '/' + path : path,
def = def || { };
fs.readFile( process.argv[ 1 ].replace( /\/[^\/]*$/, path ), 'utf8', function( err, data ) {
if ( err ) {
callback( new Error( err ), null );
}
else {
var tpl = dot.compile( data ),
str = tpl( def );
callback( null, str );
}
});
};
/**
* Method: render
* @param {String} body
*/
Html_view.prototype.render = function( body ) {
var body = body || '',
self = this;
self.getDocumentContent( { body: body }, function( err, result ) {
self._response.send( result );
});
};
/* bind */
module.exports = Html_view;
| app/controllers/base/html.js |
/**
* View: Html
*/
var config = require( '../../config' )( ),
util = require( '../../helpers/util' ),
fs = require( 'fs' ),
async = require( 'async' ),
dot = require( 'dot' ),
Base_view = require( './view' );
function Html_view( res, name ) {
Base_view.apply( this, arguments );
this._name = name;
this._webPath = '/' + this._name;
this._filePath = '/controllers/' + this._name;
this._viewPath = this._filePath + '/views';
this._meta = [ ];
this._styles = [ ];
this._scripts = [ ];
this.resolveOptions( );
this.resolveMetaTags( );
this.resolveIncludes( );
}
util.inherits( Html_view, Base_view );
/**
* Method: resolveOptions
*/
Html_view.prototype.resolveOptions = function( ) {
this.getOptions( ).set( 'app.use.googleAnalytics', null );
};
/**
* Method: resolveIncludes
*/
Html_view.prototype.resolveIncludes = function( ) {
var opts = { group: 0 };
this.addStyle( '/base/css/bootstrap.min.css', opts );
this.addScript( '/base/js/jquery.min.js', opts );
this.addScript( '/base/js/bootstrap.min.js', opts );
this.addScript( '/base/js/app.js', opts );
this.addScript( '/base/js/app.module.js', opts );
};
/**
* Method: addStyle
* @param {String} path
* @param {Object} opts
*/
Html_view.prototype.addStyle = function( path, opts ) {
var opts = util.merge( {
group: 1,
media: 'all'
}, opts );
if ( !this._styles[ opts.group ] ) {
this._styles[ opts.group ] = [ ];
}
this._styles[ opts.group ].push( {
path: path,
media: opts.media
} );
};
/**
* Method: createStyleIncludes
* @return {String}
*/
Html_view.prototype.createStyleIncludes = function( ) {
var t = new Date( ).getTime( ),
str = '',
i, len1,
j, len2;
for ( i = 0, len1 = this._styles.length; i < len1; i++ ) {
for ( j = 0, len2 = this._styles[ i ].length; j < len2; j++ ) {
if ( config.environment == 'development' && this._styles[ i ][ j ].path.substring( 0, 2 ) != '//' && this._styles[ i ][ j ].path.indexOf( '.min.' ) == -1 ) {
str += '<link href="' + this._styles[ i ][ j ].path + '?t=' + t + '" type="text/css" rel="stylesheet" media="' + this._styles[ i ][ j ].media + '" />';
}
else {
str += '<link href="' + this._styles[ i ][ j ].path + '" type="text/css" rel="stylesheet" media="' + this._styles[ i ][ j ].media + '" />';
}
}
}
return str;
};
/**
* Method: addScript
* @param {String} path
* @param {Object} opts
*/
Html_view.prototype.addScript = function( path, opts ) {
var opts = util.merge( {
group: 1
}, opts );
if ( !this._scripts[ opts.group ] ) {
this._scripts[ opts.group ] = [ ];
}
this._scripts[ opts.group ].push( {
path: path,
} );
};
/**
* Method: createScriptIncludes
* @return {String}
*/
Html_view.prototype.createScriptIncludes = function( ) {
var t = new Date( ).getTime( ),
str = '',
i, len1,
j, len2;
for ( i = 0, len1 = this._scripts.length; i < len1; i++ ) {
for ( j = 0, len2 = this._scripts[ i ].length; j < len2; j++ ) {
if ( config.environment == 'development' && this._scripts[ i ][ j ].path.substring( 0, 2 ) != '//' && this._scripts[ i ][ j ].path.indexOf( '.min.' ) == -1 ) {
str += '<script src="' + this._scripts[ i ][ j ].path + '?t=' + t + '" type="text/javascript"></script>';
}
else {
str += '<script src="' + this._scripts[ i ][ j ].path + '" type="text/javascript"></script>';
}
}
}
return str;
};
/**
* Method: resolveMetaTags
*/
Html_view.prototype.resolveMetaTags = function( ) {
this.addMetaTag( 'author', 'Jonathan Down' );
this.addMetaTag( 'description', 'An HTML5 app framework written in Express, doT.js, MongoDB, and Redis' );
this.addMetaTag( 'robots', 'index,follow' );
this.addMetaTag( 'viewport', 'initial-scale=1.0,width=device-width' );
};
/**
* Method: addMetaTag
* @param {String} name
* @param {String} content
*/
Html_view.prototype.addMetaTag = function( name, content ) {
this._meta.push( {
name: name,
content: content
} );
};
/**
* Method: createMetaTags
* @return {String}
*/
Html_view.prototype.createMetaTags = function( ) {
var str = '',
i, len;
for ( i = 0, len = this._meta.length; i < len; i++ ) {
str += '<meta name="' + this._meta[ i ].name + '" content="' + this._meta[ i ].content + '" />';
}
return str;
};
/**
* Method: getDocumentTitle
* @return {String}
*/
Html_view.prototype.getDocumentTitle = function( ) {
return this._name;
};
/**
* Method: getDocumentContent
* @param {Object} def
* @param {Function} callback
*/
Html_view.prototype.getDocumentContent = function( def, callback ) {
var def = util.merge( {
name: config.name,
title: this.getDocumentTitle( ),
meta: this.createMetaTags( ),
styles: this.createStyleIncludes( ),
module: this._name.charAt( 0 ).toUpperCase( ) + this._name.slice( 1 ),
scripts: this.createScriptIncludes( ),
analytics: this.getOptions( ).get( 'app.use.googleAnalytics' )
}, def );
this.partial( '/controllers/base/views/document.html', def, function( err, content ) {
callback( err, content );
});
};
/**
* Method: partial
* @param {String} path
* @param {Object} def
* @param {Function} callback
*/
Html_view.prototype.partial = function( path, def, callback ) {
var path = ( path.indexOf( '/' ) == -1 ) ? this._viewPath + '/' + path : path,
def = def || { };
fs.readFile( process.argv[ 1 ].replace( /\/[^\/]*$/, path ), 'utf8', function( err, data ) {
if ( err ) {
callback( new Error( err ), null );
}
else {
var tpl = dot.compile( data ),
str = tpl( def );
callback( null, str );
}
});
};
/**
* Method: render
* @param {String} body
*/
Html_view.prototype.render = function( body ) {
var body = body || '',
self = this;
self.getDocumentContent( { body: body }, function( err, result ) {
self._response.send( result );
});
};
/* bind */
module.exports = Html_view;
| reorder view methods
| app/controllers/base/html.js | reorder view methods | <ide><path>pp/controllers/base/html.js
<ide> };
<ide>
<ide> /**
<add> * Method: resolveMetaTags
<add> */
<add>
<add>Html_view.prototype.resolveMetaTags = function( ) {
<add> this.addMetaTag( 'author', 'Jonathan Down' );
<add> this.addMetaTag( 'description', 'An HTML5 app framework written in Express, doT.js, MongoDB, and Redis' );
<add> this.addMetaTag( 'robots', 'index,follow' );
<add> this.addMetaTag( 'viewport', 'initial-scale=1.0,width=device-width' );
<add>};
<add>
<add>/**
<add> * Method: addMetaTag
<add> * @param {String} name
<add> * @param {String} content
<add> */
<add>
<add>Html_view.prototype.addMetaTag = function( name, content ) {
<add> this._meta.push( {
<add> name: name,
<add> content: content
<add> } );
<add>};
<add>
<add>/**
<add> * Method: createMetaTags
<add> * @return {String}
<add> */
<add>
<add>Html_view.prototype.createMetaTags = function( ) {
<add> var str = '',
<add> i, len;
<add>
<add> for ( i = 0, len = this._meta.length; i < len; i++ ) {
<add> str += '<meta name="' + this._meta[ i ].name + '" content="' + this._meta[ i ].content + '" />';
<add> }
<add>
<add> return str;
<add>};
<add>
<add>/**
<ide> * Method: resolveIncludes
<ide> */
<ide>
<ide> str += '<script src="' + this._scripts[ i ][ j ].path + '" type="text/javascript"></script>';
<ide> }
<ide> }
<del> }
<del>
<del> return str;
<del>};
<del>
<del>/**
<del> * Method: resolveMetaTags
<del> */
<del>
<del>Html_view.prototype.resolveMetaTags = function( ) {
<del> this.addMetaTag( 'author', 'Jonathan Down' );
<del> this.addMetaTag( 'description', 'An HTML5 app framework written in Express, doT.js, MongoDB, and Redis' );
<del> this.addMetaTag( 'robots', 'index,follow' );
<del> this.addMetaTag( 'viewport', 'initial-scale=1.0,width=device-width' );
<del>};
<del>
<del>/**
<del> * Method: addMetaTag
<del> * @param {String} name
<del> * @param {String} content
<del> */
<del>
<del>Html_view.prototype.addMetaTag = function( name, content ) {
<del> this._meta.push( {
<del> name: name,
<del> content: content
<del> } );
<del>};
<del>
<del>/**
<del> * Method: createMetaTags
<del> * @return {String}
<del> */
<del>
<del>Html_view.prototype.createMetaTags = function( ) {
<del> var str = '',
<del> i, len;
<del>
<del> for ( i = 0, len = this._meta.length; i < len; i++ ) {
<del> str += '<meta name="' + this._meta[ i ].name + '" content="' + this._meta[ i ].content + '" />';
<ide> }
<ide>
<ide> return str; |
|
Java | apache-2.0 | 88d215f7d03c5a0526dd42dc28c1081a7b3f4769 | 0 | vibur/vibur-dbcp | /**
* Copyright 2015 Simeon Malchev
*
* 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.vibur.dbcp.cache;
import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap;
import com.googlecode.concurrentlinkedhashmap.EvictionListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vibur.dbcp.proxy.TargetInvoker;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import static org.vibur.dbcp.cache.StatementHolder.*;
import static org.vibur.dbcp.util.JdbcUtils.clearWarnings;
import static org.vibur.dbcp.util.JdbcUtils.closeStatement;
import static org.vibur.objectpool.util.ArgumentUtils.forbidIllegalArgument;
/**
* Implements and encapsulates all JDBC Statement caching functionality and logic.
*
* @author Simeon Malchev
*/
public class StatementCache {
private static final Logger logger = LoggerFactory.getLogger(StatementCache.class);
private final ConcurrentMap<ConnMethod, StatementHolder> statementCache;
public StatementCache(int maxSize) {
forbidIllegalArgument(maxSize <= 0);
statementCache = buildStatementCache(maxSize);
}
protected ConcurrentMap<ConnMethod, StatementHolder> buildStatementCache(int maxSize) {
return new ConcurrentLinkedHashMap.Builder<ConnMethod, StatementHolder>()
.initialCapacity(maxSize)
.maximumWeightedCapacity(maxSize)
.listener(getListener())
.build();
}
/**
* Creates and returns a new EvictionListener for the CLHM. It is worth noting that this
* EvictionListener is called in the context of the thread that has executed an insert (putIfAbsent)
* operation which has increased the CLHM size above its maxSize - in which case the CLHM
* evicts its LRU entry.
*
* @return a new EvictionListener for the CLHM
*/
protected EvictionListener<ConnMethod, StatementHolder> getListener() {
return new EvictionListener<ConnMethod, StatementHolder>() {
@Override
public void onEviction(ConnMethod key, StatementHolder value) {
if (value.state().getAndSet(EVICTED) == AVAILABLE)
closeStatement(value.value());
logger.trace("Evicted {}", value.value());
}
};
}
/**
* Returns <i>a possibly</i> cached StatementHolder object for the given connection method key.
*
* @param key the connection method key
* @param invoker the invoker through which to create the raw JDBC Statement object, if needed
* @return a retrieved from the cache or newly created StatementHolder object wrapping the raw JDBC Statement object
* @throws Throwable if the invoked underlying prepareXYZ method throws an exception
*/
public StatementHolder retrieve(ConnMethod key, TargetInvoker invoker) throws Throwable {
StatementHolder statement = statementCache.get(key);
if (statement != null && statement.state().compareAndSet(AVAILABLE, IN_USE)) {
logger.trace("Using cached statement for {}", key);
return statement;
}
Statement rawStatement = (Statement) invoker.targetInvoke(key.getMethod(), key.getArgs());
if (statement == null) { // there was no entry for the key, so we'll try to put a new one
statement = new StatementHolder(rawStatement, new AtomicInteger(IN_USE));
if (statementCache.putIfAbsent(key, statement) == null)
return statement; // the new entry was successfully put in the cache
}
return new StatementHolder(rawStatement, null);
}
public void restore(StatementHolder statement, boolean clearWarnings) {
if (statement.state() == null) // this statement is not in the cache
return;
Statement rawStatement = statement.value();
if (clearWarnings)
clearWarnings(rawStatement);
if (!statement.state().compareAndSet(IN_USE, AVAILABLE)) // just mark it as AVAILABLE if its state was IN_USE
closeStatement(rawStatement); // and close it if it was already EVICTED (while its state was IN_USE)
}
public boolean remove(Statement rawStatement, boolean close) {
for (Map.Entry<ConnMethod, StatementHolder> entry : statementCache.entrySet()) {
StatementHolder value = entry.getValue();
if (value.value() == rawStatement) { // comparing with == as these JDBC Statements are cached objects
if (close)
closeStatement(rawStatement);
return statementCache.remove(entry.getKey(), value);
}
}
return false;
}
public int removeAll(Connection rawConnection) {
int removed = 0;
for (Map.Entry<ConnMethod, StatementHolder> entry : statementCache.entrySet()) {
ConnMethod key = entry.getKey();
StatementHolder value = entry.getValue();
if (key.getTarget() == rawConnection && statementCache.remove(key, value)) {
closeStatement(value.value());
removed++;
}
}
return removed;
}
public void clear() {
for (Map.Entry<ConnMethod, StatementHolder> entry : statementCache.entrySet()) {
StatementHolder value = entry.getValue();
statementCache.remove(entry.getKey(), value);
closeStatement(value.value());
}
}
}
| src/main/java/org/vibur/dbcp/cache/StatementCache.java | /**
* Copyright 2015 Simeon Malchev
*
* 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.vibur.dbcp.cache;
import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap;
import com.googlecode.concurrentlinkedhashmap.EvictionListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vibur.dbcp.proxy.TargetInvoker;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import static org.vibur.dbcp.cache.StatementHolder.*;
import static org.vibur.dbcp.util.JdbcUtils.clearWarnings;
import static org.vibur.dbcp.util.JdbcUtils.closeStatement;
import static org.vibur.objectpool.util.ArgumentUtils.forbidIllegalArgument;
/**
* Implements and encapsulates all JDBC Statement caching functionality and logic.
*
* @author Simeon Malchev
*/
public class StatementCache {
private static final Logger logger = LoggerFactory.getLogger(StatementCache.class);
private final ConcurrentMap<ConnMethod, StatementHolder> statementCache;
public StatementCache(int maxSize) {
forbidIllegalArgument(maxSize <= 0);
statementCache = buildStatementCache(maxSize);
}
protected ConcurrentMap<ConnMethod, StatementHolder> buildStatementCache(int maxSize) {
return new ConcurrentLinkedHashMap.Builder<ConnMethod, StatementHolder>()
.initialCapacity(maxSize)
.maximumWeightedCapacity(maxSize)
.listener(getListener())
.build();
}
/**
* Creates and returns a new EvictionListener for the CLHM. It is worth noting that this
* EvictionListener is called in the context of the thread that has executed an insert (putIfAbsent)
* operation which has increased the CLHM size above its maxSize - in which case the CLHM
* evicts its LRU entry.
*
* @return a new EvictionListener for the CLHM
*/
protected EvictionListener<ConnMethod, StatementHolder> getListener() {
return new EvictionListener<ConnMethod, StatementHolder>() {
@Override
public void onEviction(ConnMethod key, StatementHolder value) {
if (value.state().getAndSet(EVICTED) == AVAILABLE)
closeStatement(value.value());
logger.trace("Evicted {}", value.value());
}
};
}
/**
* Returns <i>a possibly</i> cached StatementHolder object for the given connection method key.
*
* @param key the connection method key
* @param invoker the invoker through which to create the raw JDBC Statement object, if needed
* @return a retrieved from the cache or newly created StatementHolder object wrapping the raw JDBC Statement object
* @throws Throwable if the invoked underlying prepareXYZ method throws an exception
*/
public StatementHolder retrieve(ConnMethod key, TargetInvoker invoker) throws Throwable {
StatementHolder statement = statementCache.get(key);
if (statement != null && statement.state().compareAndSet(AVAILABLE, IN_USE)) {
logger.trace("Using cached statement for {}", key);
return statement;
}
Statement rawStatement = (Statement) invoker.targetInvoke(key.getMethod(), key.getArgs());
if (statement == null) { // there was no entry for the key, so we'll try to put a new one
statement = new StatementHolder(rawStatement, new AtomicInteger(IN_USE));
if (statementCache.putIfAbsent(key, statement) == null)
return statement; // the new entry was successfully put in the cache
}
return new StatementHolder(rawStatement, null);
}
public void restore(StatementHolder statement, boolean clearWarnings) {
if (statement.state() == null) // this statement is not in the cache
return;
Statement rawStatement = statement.value();
if (clearWarnings)
clearWarnings(rawStatement);
if (!statement.state().compareAndSet(IN_USE, AVAILABLE)) // just mark it as available if its state was in_use
closeStatement(rawStatement); // and close it if it was already evicted (while its state was in_use)
}
public boolean remove(Statement rawStatement, boolean close) {
for (Map.Entry<ConnMethod, StatementHolder> entry : statementCache.entrySet()) {
StatementHolder value = entry.getValue();
if (value.value() == rawStatement) { // comparing with == as these JDBC Statements are cached objects
if (close)
closeStatement(rawStatement);
return statementCache.remove(entry.getKey(), value);
}
}
return false;
}
public int removeAll(Connection rawConnection) {
int removed = 0;
for (Map.Entry<ConnMethod, StatementHolder> entry : statementCache.entrySet()) {
ConnMethod key = entry.getKey();
StatementHolder value = entry.getValue();
if (key.getTarget() == rawConnection && statementCache.remove(key, value)) {
closeStatement(value.value());
removed++;
}
}
return removed;
}
public void clear() {
for (Map.Entry<ConnMethod, StatementHolder> entry : statementCache.entrySet()) {
StatementHolder value = entry.getValue();
statementCache.remove(entry.getKey(), value);
closeStatement(value.value());
}
}
}
| minor
| src/main/java/org/vibur/dbcp/cache/StatementCache.java | minor | <ide><path>rc/main/java/org/vibur/dbcp/cache/StatementCache.java
<ide> Statement rawStatement = statement.value();
<ide> if (clearWarnings)
<ide> clearWarnings(rawStatement);
<del> if (!statement.state().compareAndSet(IN_USE, AVAILABLE)) // just mark it as available if its state was in_use
<del> closeStatement(rawStatement); // and close it if it was already evicted (while its state was in_use)
<add> if (!statement.state().compareAndSet(IN_USE, AVAILABLE)) // just mark it as AVAILABLE if its state was IN_USE
<add> closeStatement(rawStatement); // and close it if it was already EVICTED (while its state was IN_USE)
<ide> }
<ide>
<ide> public boolean remove(Statement rawStatement, boolean close) { |
|
Java | apache-2.0 | a6df526ccdbfc080e60df14a6ff632ad96691f18 | 0 | pierre/eventtracker | /*
* Copyright 2010 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.metrics.eventtracker;
import com.google.inject.Inject;
import com.ning.http.client.*;
import com.ning.metrics.serialization.event.Event;
import com.ning.metrics.serialization.writer.CallbackHandler;
import java.io.IOException;
class HttpSender implements EventSender
{
public static final String URI_PATH = "/rest/1.0/event";
private static final int DEFAULT_IDLE_CONNECTION_IN_POOL_TIMEOUT_IN_MS = 120000; // 2 minutes
private final String collectorURI;
private final String httpContentType;
private final AsyncHttpClient client;
@Inject
public HttpSender(EventTrackerConfig config)
{
collectorURI = String.format("http://%s:%d%s", config.getCollectorHost(), config.getCollectorPort(), URI_PATH);
// CAUTION: it is not enforced that the actual event encoding type on the wire matches what the config says it is
// the event encoding type is determined by the Event's writeExternal() method.
httpContentType = EventEncodingType.valueOf(config.getHttpEventEncodingType()).toString();
AsyncHttpClientConfig clientConfig = new AsyncHttpClientConfig.Builder()
.setIdleConnectionInPoolTimeoutInMs(DEFAULT_IDLE_CONNECTION_IN_POOL_TIMEOUT_IN_MS)
.setConnectionTimeoutInMs(100)
.setMaximumConnectionsPerHost(-1) // unlimited connections
.build();
client = new AsyncHttpClient(clientConfig);
}
@Override
public void send(final Event event, final CallbackHandler handler)
{
// Submit the event
try {
client.executeRequest(createPostRequest(event),
new AsyncCompletionHandler<String>()
{
@Override
public String onCompleted(Response response) throws Exception
{
if (response.getStatusCode() == 202) {
handler.onSuccess(event);
}
else {
handler.onError(new Throwable(String.format("Received response %d: %s",response.getStatusCode(),response.getStatusText())), event);
}
return response.getResponseBody(); // this return value's never read.
}
@Override
public void onThrowable(Throwable t)
{
handler.onError(t, event);
}
});
}
catch (IOException e) {
handler.onError(new Throwable(e), event);
}
}
// TODO when should we close this?
public void closeClient()
{
client.close();
}
private Request createPostRequest(Event event)
{
byte[] serializedEvent = event.getSerializedEvent();
AsyncHttpClient.BoundRequestBuilder requestBuilder = client.preparePost(collectorURI)
.addHeader("Content-Length", String.valueOf(serializedEvent.length))
.addHeader("Content-Type", httpContentType)
.setBody(serializedEvent)
.addQueryParameter("name", event.getName());
if (event.getEventDateTime() != null) {
requestBuilder.addQueryParameter("date", event.getEventDateTime().toString());
}
if (event.getGranularity() != null) {
requestBuilder.addQueryParameter("granularity", event.getGranularity().toString());
}
return requestBuilder.build();
}
}
| src/main/java/com/ning/metrics/eventtracker/HttpSender.java | /*
* Copyright 2010 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.metrics.eventtracker;
import com.google.inject.Inject;
import com.ning.http.client.*;
import com.ning.metrics.serialization.event.Event;
import com.ning.metrics.serialization.writer.CallbackHandler;
import org.joda.time.DateTime;
import java.io.IOException;
class HttpSender implements EventSender
{
public static final String URI_PATH = "/rest/1.0/event";
private static final int DEFAULT_IDLE_CONNECTION_IN_POOL_TIMEOUT_IN_MS = 120000; // 2 minutes
private final String collectorURI;
private final String httpContentType;
private final AsyncHttpClient client;
@Inject
public HttpSender(EventTrackerConfig config)
{
collectorURI = String.format("http://%s:%d%s", config.getCollectorHost(), config.getCollectorPort(), URI_PATH);
// CAUTION: it is not enforced that the actual event encoding type on the wire matches what the config says it is
// the event encoding type is determined by the Event's writeExternal() method.
httpContentType = EventEncodingType.valueOf(config.getHttpEventEncodingType()).toString();
AsyncHttpClientConfig clientConfig = new AsyncHttpClientConfig.Builder()
.setIdleConnectionInPoolTimeoutInMs(DEFAULT_IDLE_CONNECTION_IN_POOL_TIMEOUT_IN_MS)
.setConnectionTimeoutInMs(100)
.setMaximumConnectionsPerHost(-1) // unlimited connections
.build();
client = new AsyncHttpClient(clientConfig);
}
@Override
public void send(final Event event, final CallbackHandler handler)
{
// Submit the event
try {
client.executeRequest(createPostRequest(event),
new AsyncCompletionHandler<String>()
{
@Override
public String onCompleted(Response response) throws Exception
{
if (response.getStatusCode() == 202) {
handler.onSuccess(event);
}
else {
handler.onError(new Throwable(String.format("Received response %d: %s",response.getStatusCode(),response.getStatusText())), null);
}
return response.getResponseBody();
}
@Override
public void onThrowable(Throwable t)
{
handler.onError(t, event);
}
});
}
catch (IOException e) {
handler.onError(new Throwable(e), event);
}
}
// TODO when should we close this?
public void closeClient()
{
client.close();
}
private Request createPostRequest(Event event)
{
byte[] serializedEvent = event.getSerializedEvent();
AsyncHttpClient.BoundRequestBuilder requestBuilder = client.preparePost(collectorURI)
.addHeader("Content-Length", String.valueOf(serializedEvent.length))
.addHeader("Content-Type", httpContentType)
.setBody(serializedEvent)
.addQueryParameter("name", event.getName());
if (event.getEventDateTime() != null) {
requestBuilder.addQueryParameter("date", event.getEventDateTime().toString());
}
if (event.getGranularity() != null) {
requestBuilder.addQueryParameter("granularity", event.getGranularity().toString());
}
return requestBuilder.build();
}
}
| HttpSender: made more helpful error message when response status != 202
| src/main/java/com/ning/metrics/eventtracker/HttpSender.java | HttpSender: made more helpful error message when response status != 202 | <ide><path>rc/main/java/com/ning/metrics/eventtracker/HttpSender.java
<ide> import com.ning.http.client.*;
<ide> import com.ning.metrics.serialization.event.Event;
<ide> import com.ning.metrics.serialization.writer.CallbackHandler;
<del>import org.joda.time.DateTime;
<ide>
<ide> import java.io.IOException;
<ide>
<ide> handler.onSuccess(event);
<ide> }
<ide> else {
<del> handler.onError(new Throwable(String.format("Received response %d: %s",response.getStatusCode(),response.getStatusText())), null);
<add> handler.onError(new Throwable(String.format("Received response %d: %s",response.getStatusCode(),response.getStatusText())), event);
<ide> }
<del> return response.getResponseBody();
<add> return response.getResponseBody(); // this return value's never read.
<ide> }
<ide>
<ide> @Override |
|
JavaScript | mit | 803fd3d4926ce79da52877f303ad85e1bafd0180 | 0 | noelboss/featherlight,noelboss/featherlight | /**
* Featherlight - ultra slim jQuery lightbox
* Version 1.7.9 - http://noelboss.github.io/featherlight/
*
* Copyright 2017, Noël Raoul Bossart (http://www.noelboss.com)
* MIT Licensed.
**/
(function($) {
"use strict";
if('undefined' === typeof $) {
if('console' in window){ window.console.info('Too much lightness, Featherlight needs jQuery.'); }
return;
}
if($.fn.jquery.match(/-ajax/)) {
if('console' in window){ window.console.info('Featherlight needs regular jQuery, not the slim version.'); }
return;
}
/* Featherlight is exported as $.featherlight.
It is a function used to open a featherlight lightbox.
[tech]
Featherlight uses prototype inheritance.
Each opened lightbox will have a corresponding object.
That object may have some attributes that override the
prototype's.
Extensions created with Featherlight.extend will have their
own prototype that inherits from Featherlight's prototype,
thus attributes can be overriden either at the object level,
or at the extension level.
To create callbacks that chain themselves instead of overriding,
use chainCallbacks.
For those familiar with CoffeeScript, this correspond to
Featherlight being a class and the Gallery being a class
extending Featherlight.
The chainCallbacks is used since we don't have access to
CoffeeScript's `super`.
*/
function Featherlight($content, config) {
if(this instanceof Featherlight) { /* called with new */
this.id = Featherlight.id++;
this.setup($content, config);
this.chainCallbacks(Featherlight._callbackChain);
} else {
var fl = new Featherlight($content, config);
fl.open();
return fl;
}
}
var opened = [],
pruneOpened = function(remove) {
opened = $.grep(opened, function(fl) {
return fl !== remove && fl.$instance.closest('body').length > 0;
} );
return opened;
};
// Removes keys of `set` from `obj` and returns the removed key/values.
function slice(obj, set) {
var r = {};
for (var key in obj) {
if (key in set) {
r[key] = obj[key];
delete obj[key];
}
}
return r;
}
// NOTE: List of available [iframe attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe).
var iFrameAttributeSet = {
allowfullscreen: 1, frameborder: 1, height: 1, longdesc: 1, marginheight: 1, marginwidth: 1,
name: 1, referrerpolicy: 1, scrolling: 1, sandbox: 1, src: 1, srcdoc: 1, width: 1
};
// Converts camelCased attributes to dasherized versions for given prefix:
// parseAttrs({hello: 1, hellFrozeOver: 2}, 'hell') => {froze-over: 2}
function parseAttrs(obj, prefix) {
var attrs = {},
regex = new RegExp('^' + prefix + '([A-Z])(.*)');
for (var key in obj) {
var match = key.match(regex);
if (match) {
var dasherized = (match[1] + match[2].replace(/([A-Z])/g, '-$1')).toLowerCase();
attrs[dasherized] = obj[key];
}
}
return attrs;
}
/* document wide key handler */
var eventMap = { keyup: 'onKeyUp', resize: 'onResize' };
var globalEventHandler = function(event) {
$.each(Featherlight.opened().reverse(), function() {
if (!event.isDefaultPrevented()) {
if (false === this[eventMap[event.type]](event)) {
event.preventDefault(); event.stopPropagation(); return false;
}
}
});
};
var toggleGlobalEvents = function(set) {
if(set !== Featherlight._globalHandlerInstalled) {
Featherlight._globalHandlerInstalled = set;
var events = $.map(eventMap, function(_, name) { return name+'.'+Featherlight.prototype.namespace; } ).join(' ');
$(window)[set ? 'on' : 'off'](events, globalEventHandler);
}
};
Featherlight.prototype = {
constructor: Featherlight,
/*** defaults ***/
/* extend featherlight with defaults and methods */
namespace: 'featherlight', /* Name of the events and css class prefix */
targetAttr: 'data-featherlight', /* Attribute of the triggered element that contains the selector to the lightbox content */
variant: null, /* Class that will be added to change look of the lightbox */
resetCss: false, /* Reset all css */
background: null, /* Custom DOM for the background, wrapper and the closebutton */
openTrigger: 'click', /* Event that triggers the lightbox */
closeTrigger: 'click', /* Event that triggers the closing of the lightbox */
filter: null, /* Selector to filter events. Think $(...).on('click', filter, eventHandler) */
root: 'body', /* Where to append featherlights */
openSpeed: 250, /* Duration of opening animation */
closeSpeed: 250, /* Duration of closing animation */
closeOnClick: 'background', /* Close lightbox on click ('background', 'anywhere' or false) */
closeOnEsc: true, /* Close lightbox when pressing esc */
closeIcon: '✕', /* Close icon */
loading: '', /* Content to show while initial content is loading */
persist: false, /* If set, the content will persist and will be shown again when opened again. 'shared' is a special value when binding multiple elements for them to share the same content */
otherClose: null, /* Selector for alternate close buttons (e.g. "a.close") */
beforeOpen: $.noop, /* Called before open. can return false to prevent opening of lightbox. Gets event as parameter, this contains all data */
beforeContent: $.noop, /* Called when content is loaded. Gets event as parameter, this contains all data */
beforeClose: $.noop, /* Called before close. can return false to prevent opening of lightbox. Gets event as parameter, this contains all data */
afterOpen: $.noop, /* Called after open. Gets event as parameter, this contains all data */
afterContent: $.noop, /* Called after content is ready and has been set. Gets event as parameter, this contains all data */
afterClose: $.noop, /* Called after close. Gets event as parameter, this contains all data */
onKeyUp: $.noop, /* Called on key up for the frontmost featherlight */
onResize: $.noop, /* Called after new content and when a window is resized */
type: null, /* Specify type of lightbox. If unset, it will check for the targetAttrs value. */
contentFilters: ['jquery', 'image', 'html', 'ajax', 'iframe', 'text'], /* List of content filters to use to determine the content */
/*** methods ***/
/* setup iterates over a single instance of featherlight and prepares the background and binds the events */
setup: function(target, config){
/* all arguments are optional */
if (typeof target === 'object' && target instanceof $ === false && !config) {
config = target;
target = undefined;
}
var self = $.extend(this, config, {target: target}),
css = !self.resetCss ? self.namespace : self.namespace+'-reset', /* by adding -reset to the classname, we reset all the default css */
$background = $(self.background || [
'<div class="'+css+'-loading '+css+'">',
'<div class="'+css+'-content">',
'<button class="'+css+'-close-icon '+ self.namespace + '-close" aria-label="Close">',
self.closeIcon,
'</button>',
'<div class="'+self.namespace+'-inner">' + self.loading + '</div>',
'</div>',
'</div>'].join('')),
closeButtonSelector = '.'+self.namespace+'-close' + (self.otherClose ? ',' + self.otherClose : '');
self.$instance = $background.clone().addClass(self.variant); /* clone DOM for the background, wrapper and the close button */
/* close when click on background/anywhere/null or closebox */
self.$instance.on(self.closeTrigger+'.'+self.namespace, function(event) {
var $target = $(event.target);
if( ('background' === self.closeOnClick && $target.is('.'+self.namespace))
|| 'anywhere' === self.closeOnClick
|| $target.closest(closeButtonSelector).length ){
self.close(event);
event.preventDefault();
}
});
return this;
},
/* this method prepares the content and converts it into a jQuery object or a promise */
getContent: function(){
if(this.persist !== false && this.$content) {
return this.$content;
}
var self = this,
filters = this.constructor.contentFilters,
readTargetAttr = function(name){ return self.$currentTarget && self.$currentTarget.attr(name); },
targetValue = readTargetAttr(self.targetAttr),
data = self.target || targetValue || '';
/* Find which filter applies */
var filter = filters[self.type]; /* check explicit type like {type: 'image'} */
/* check explicit type like data-featherlight="image" */
if(!filter && data in filters) {
filter = filters[data];
data = self.target && targetValue;
}
data = data || readTargetAttr('href') || '';
/* check explicity type & content like {image: 'photo.jpg'} */
if(!filter) {
for(var filterName in filters) {
if(self[filterName]) {
filter = filters[filterName];
data = self[filterName];
}
}
}
/* otherwise it's implicit, run checks */
if(!filter) {
var target = data;
data = null;
$.each(self.contentFilters, function() {
filter = filters[this];
if(filter.test) {
data = filter.test(target);
}
if(!data && filter.regex && target.match && target.match(filter.regex)) {
data = target;
}
return !data;
});
if(!data) {
if('console' in window){ window.console.error('Featherlight: no content filter found ' + (target ? ' for "' + target + '"' : ' (no target specified)')); }
return false;
}
}
/* Process it */
return filter.process.call(self, data);
},
/* sets the content of $instance to $content */
setContent: function($content){
var self = this;
/* we need a special class for the iframe */
if($content.is('iframe')) {
self.$instance.addClass(self.namespace+'-iframe');
}
self.$instance.removeClass(self.namespace+'-loading');
/* replace content by appending to existing one before it is removed
this insures that featherlight-inner remain at the same relative
position to any other items added to featherlight-content */
self.$instance.find('.'+self.namespace+'-inner')
.not($content) /* excluded new content, important if persisted */
.slice(1).remove().end() /* In the unexpected event where there are many inner elements, remove all but the first one */
.replaceWith($.contains(self.$instance[0], $content[0]) ? '' : $content);
self.$content = $content.addClass(self.namespace+'-inner');
return self;
},
/* opens the lightbox. "this" contains $instance with the lightbox, and with the config.
Returns a promise that is resolved after is successfully opened. */
open: function(event){
var self = this;
self.$instance.hide().appendTo(self.root);
if((!event || !event.isDefaultPrevented())
&& self.beforeOpen(event) !== false) {
if(event){
event.preventDefault();
}
var $content = self.getContent();
if($content) {
opened.push(self);
toggleGlobalEvents(true);
self.$instance.fadeIn(self.openSpeed);
self.beforeContent(event);
/* Set content and show */
return $.when($content)
.always(function($content){
self.setContent($content);
self.afterContent(event);
})
.then(self.$instance.promise())
/* Call afterOpen after fadeIn is done */
.done(function(){ self.afterOpen(event); });
}
}
self.$instance.detach();
return $.Deferred().reject().promise();
},
/* closes the lightbox. "this" contains $instance with the lightbox, and with the config
returns a promise, resolved after the lightbox is successfully closed. */
close: function(event){
var self = this,
deferred = $.Deferred();
if(self.beforeClose(event) === false) {
deferred.reject();
} else {
if (0 === pruneOpened(self).length) {
toggleGlobalEvents(false);
}
self.$instance.fadeOut(self.closeSpeed,function(){
self.$instance.detach();
self.afterClose(event);
deferred.resolve();
});
}
return deferred.promise();
},
/* resizes the content so it fits in visible area and keeps the same aspect ratio.
Does nothing if either the width or the height is not specified.
Called automatically on window resize.
Override if you want different behavior. */
resize: function(w, h) {
if (w && h) {
/* Reset apparent image size first so container grows */
this.$content.css('width', '').css('height', '');
/* Calculate the worst ratio so that dimensions fit */
/* Note: -1 to avoid rounding errors */
var ratio = Math.max(
w / (this.$content.parent().width()-1),
h / (this.$content.parent().height()-1));
/* Resize content */
if (ratio > 1) {
ratio = h / Math.floor(h / ratio); /* Round ratio down so height calc works */
this.$content.css('width', '' + w / ratio + 'px').css('height', '' + h / ratio + 'px');
}
}
},
/* Utility function to chain callbacks
[Warning: guru-level]
Used be extensions that want to let users specify callbacks but
also need themselves to use the callbacks.
The argument 'chain' has callback names as keys and function(super, event)
as values. That function is meant to call `super` at some point.
*/
chainCallbacks: function(chain) {
for (var name in chain) {
this[name] = $.proxy(chain[name], this, $.proxy(this[name], this));
}
}
};
$.extend(Featherlight, {
id: 0, /* Used to id single featherlight instances */
autoBind: '[data-featherlight]', /* Will automatically bind elements matching this selector. Clear or set before onReady */
defaults: Featherlight.prototype, /* You can access and override all defaults using $.featherlight.defaults, which is just a synonym for $.featherlight.prototype */
/* Contains the logic to determine content */
contentFilters: {
jquery: {
regex: /^[#.]\w/, /* Anything that starts with a class name or identifiers */
test: function(elem) { return elem instanceof $ && elem; },
process: function(elem) { return this.persist !== false ? $(elem) : $(elem).clone(true); }
},
image: {
regex: /\.(png|jpg|jpeg|gif|tiff?|bmp|svg)(\?\S*)?$/i,
process: function(url) {
var self = this,
deferred = $.Deferred(),
img = new Image(),
$img = $('<img src="'+url+'" alt="" class="'+self.namespace+'-image" />');
img.onload = function() {
/* Store naturalWidth & height for IE8 */
$img.naturalWidth = img.width; $img.naturalHeight = img.height;
deferred.resolve( $img );
};
img.onerror = function() { deferred.reject($img); };
img.src = url;
return deferred.promise();
}
},
html: {
regex: /^\s*<[\w!][^<]*>/, /* Anything that starts with some kind of valid tag */
process: function(html) { return $(html); }
},
ajax: {
regex: /./, /* At this point, any content is assumed to be an URL */
process: function(url) {
var self = this,
deferred = $.Deferred();
/* we are using load so one can specify a target with: url.html #targetelement */
var $container = $('<div></div>').load(url, function(response, status){
if ( status !== "error" ) {
deferred.resolve($container.contents());
}
deferred.fail();
});
return deferred.promise();
}
},
iframe: {
process: function(url) {
var deferred = new $.Deferred();
var $content = $('<iframe/>');
var css = parseAttrs(this, 'iframe');
var attrs = slice(css, iFrameAttributeSet);
$content.hide()
.attr('src', url)
.attr(attrs)
.css(css)
.on('load', function() { deferred.resolve($content.show()); })
// We can't move an <iframe> and avoid reloading it,
// so let's put it in place ourselves right now:
.appendTo(this.$instance.find('.' + this.namespace + '-content'));
return deferred.promise();
}
},
text: {
process: function(text) { return $('<div>', {text: text}); }
}
},
functionAttributes: ['beforeOpen', 'afterOpen', 'beforeContent', 'afterContent', 'beforeClose', 'afterClose'],
/*** class methods ***/
/* read element's attributes starting with data-featherlight- */
readElementConfig: function(element, namespace) {
var Klass = this,
regexp = new RegExp('^data-' + namespace + '-(.*)'),
config = {};
if (element && element.attributes) {
$.each(element.attributes, function(){
var match = this.name.match(regexp);
if (match) {
var val = this.value,
name = $.camelCase(match[1]);
if ($.inArray(name, Klass.functionAttributes) >= 0) { /* jshint -W054 */
val = new Function(val); /* jshint +W054 */
} else {
try { val = JSON.parse(val); }
catch(e) {}
}
config[name] = val;
}
});
}
return config;
},
/* Used to create a Featherlight extension
[Warning: guru-level]
Creates the extension's prototype that in turn
inherits Featherlight's prototype.
Could be used to extend an extension too...
This is pretty high level wizardy, it comes pretty much straight
from CoffeeScript and won't teach you anything about Featherlight
as it's not really specific to this library.
My suggestion: move along and keep your sanity.
*/
extend: function(child, defaults) {
/* Setup class hierarchy, adapted from CoffeeScript */
var Ctor = function(){ this.constructor = child; };
Ctor.prototype = this.prototype;
child.prototype = new Ctor();
child.__super__ = this.prototype;
/* Copy class methods & attributes */
$.extend(child, this, defaults);
child.defaults = child.prototype;
return child;
},
attach: function($source, $content, config) {
var Klass = this;
if (typeof $content === 'object' && $content instanceof $ === false && !config) {
config = $content;
$content = undefined;
}
/* make a copy */
config = $.extend({}, config);
/* Only for openTrigger and namespace... */
var namespace = config.namespace || Klass.defaults.namespace,
tempConfig = $.extend({}, Klass.defaults, Klass.readElementConfig($source[0], namespace), config),
sharedPersist;
var handler = function(event) {
var $target = $(event.currentTarget);
/* ... since we might as well compute the config on the actual target */
var elemConfig = $.extend(
{$source: $source, $currentTarget: $target},
Klass.readElementConfig($source[0], tempConfig.namespace),
Klass.readElementConfig(event.currentTarget, tempConfig.namespace),
config);
var fl = sharedPersist || $target.data('featherlight-persisted') || new Klass($content, elemConfig);
if(fl.persist === 'shared') {
sharedPersist = fl;
} else if(fl.persist !== false) {
$target.data('featherlight-persisted', fl);
}
if (elemConfig.$currentTarget.blur) {
elemConfig.$currentTarget.blur(); // Otherwise 'enter' key might trigger the dialog again
}
fl.open(event);
};
$source.on(tempConfig.openTrigger+'.'+tempConfig.namespace, tempConfig.filter, handler);
return handler;
},
current: function() {
var all = this.opened();
return all[all.length - 1] || null;
},
opened: function() {
var klass = this;
pruneOpened();
return $.grep(opened, function(fl) { return fl instanceof klass; } );
},
close: function(event) {
var cur = this.current();
if(cur) { return cur.close(event); }
},
/* Does the auto binding on startup.
Meant only to be used by Featherlight and its extensions
*/
_onReady: function() {
var Klass = this;
if(Klass.autoBind){
/* Bind existing elements */
$(Klass.autoBind).each(function(){
Klass.attach($(this));
});
/* If a click propagates to the document level, then we have an item that was added later on */
$(document).on('click', Klass.autoBind, function(evt) {
if (evt.isDefaultPrevented()) {
return;
}
/* Bind featherlight */
var handler = Klass.attach($(evt.currentTarget));
/* Dispatch event directly */
handler(evt);
});
}
},
/* Featherlight uses the onKeyUp callback to intercept the escape key.
Private to Featherlight.
*/
_callbackChain: {
onKeyUp: function(_super, event){
if(27 === event.keyCode) {
if (this.closeOnEsc) {
$.featherlight.close(event);
}
return false;
} else {
return _super(event);
}
},
beforeOpen: function(_super, event) {
// Used to disable scrolling
$(document.documentElement).addClass('with-featherlight');
// Remember focus:
this._previouslyActive = document.activeElement;
// Disable tabbing:
// See http://stackoverflow.com/questions/1599660/which-html-elements-can-receive-focus
this._$previouslyTabbable = $("a, input, select, textarea, iframe, button, iframe, [contentEditable=true]")
.not('[tabindex]')
.not(this.$instance.find('button'));
this._$previouslyWithTabIndex = $('[tabindex]').not('[tabindex="-1"]');
this._previousWithTabIndices = this._$previouslyWithTabIndex.map(function(_i, elem) {
return $(elem).attr('tabindex');
});
this._$previouslyWithTabIndex.add(this._$previouslyTabbable).attr('tabindex', -1);
if (document.activeElement.blur) {
document.activeElement.blur();
}
return _super(event);
},
afterClose: function(_super, event) {
var r = _super(event);
// Restore focus
var self = this;
this._$previouslyTabbable.removeAttr('tabindex');
this._$previouslyWithTabIndex.each(function(i, elem) {
$(elem).attr('tabindex', self._previousWithTabIndices[i]);
});
this._previouslyActive.focus();
// Restore scroll
if(Featherlight.opened().length === 0) {
$(document.documentElement).removeClass('with-featherlight');
}
return r;
},
onResize: function(_super, event){
this.resize(this.$content.naturalWidth, this.$content.naturalHeight);
return _super(event);
},
afterContent: function(_super, event){
var r = _super(event);
this.$instance.find('[autofocus]:not([disabled])').focus();
this.onResize(event);
return r;
}
}
});
$.featherlight = Featherlight;
/* bind jQuery elements to trigger featherlight */
$.fn.featherlight = function($content, config) {
Featherlight.attach(this, $content, config);
return this;
};
/* bind featherlight on ready if config autoBind is set */
$(document).ready(function(){ Featherlight._onReady(); });
}(jQuery));
| src/featherlight.js | /**
* Featherlight - ultra slim jQuery lightbox
* Version 1.7.9 - http://noelboss.github.io/featherlight/
*
* Copyright 2017, Noël Raoul Bossart (http://www.noelboss.com)
* MIT Licensed.
**/
(function($) {
"use strict";
if('undefined' === typeof $) {
if('console' in window){ window.console.info('Too much lightness, Featherlight needs jQuery.'); }
return;
}
/* Featherlight is exported as $.featherlight.
It is a function used to open a featherlight lightbox.
[tech]
Featherlight uses prototype inheritance.
Each opened lightbox will have a corresponding object.
That object may have some attributes that override the
prototype's.
Extensions created with Featherlight.extend will have their
own prototype that inherits from Featherlight's prototype,
thus attributes can be overriden either at the object level,
or at the extension level.
To create callbacks that chain themselves instead of overriding,
use chainCallbacks.
For those familiar with CoffeeScript, this correspond to
Featherlight being a class and the Gallery being a class
extending Featherlight.
The chainCallbacks is used since we don't have access to
CoffeeScript's `super`.
*/
function Featherlight($content, config) {
if(this instanceof Featherlight) { /* called with new */
this.id = Featherlight.id++;
this.setup($content, config);
this.chainCallbacks(Featherlight._callbackChain);
} else {
var fl = new Featherlight($content, config);
fl.open();
return fl;
}
}
var opened = [],
pruneOpened = function(remove) {
opened = $.grep(opened, function(fl) {
return fl !== remove && fl.$instance.closest('body').length > 0;
} );
return opened;
};
// Removes keys of `set` from `obj` and returns the removed key/values.
function slice(obj, set) {
var r = {};
for (var key in obj) {
if (key in set) {
r[key] = obj[key];
delete obj[key];
}
}
return r;
}
// NOTE: List of available [iframe attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe).
var iFrameAttributeSet = {
allowfullscreen: 1, frameborder: 1, height: 1, longdesc: 1, marginheight: 1, marginwidth: 1,
name: 1, referrerpolicy: 1, scrolling: 1, sandbox: 1, src: 1, srcdoc: 1, width: 1
};
// Converts camelCased attributes to dasherized versions for given prefix:
// parseAttrs({hello: 1, hellFrozeOver: 2}, 'hell') => {froze-over: 2}
function parseAttrs(obj, prefix) {
var attrs = {},
regex = new RegExp('^' + prefix + '([A-Z])(.*)');
for (var key in obj) {
var match = key.match(regex);
if (match) {
var dasherized = (match[1] + match[2].replace(/([A-Z])/g, '-$1')).toLowerCase();
attrs[dasherized] = obj[key];
}
}
return attrs;
}
/* document wide key handler */
var eventMap = { keyup: 'onKeyUp', resize: 'onResize' };
var globalEventHandler = function(event) {
$.each(Featherlight.opened().reverse(), function() {
if (!event.isDefaultPrevented()) {
if (false === this[eventMap[event.type]](event)) {
event.preventDefault(); event.stopPropagation(); return false;
}
}
});
};
var toggleGlobalEvents = function(set) {
if(set !== Featherlight._globalHandlerInstalled) {
Featherlight._globalHandlerInstalled = set;
var events = $.map(eventMap, function(_, name) { return name+'.'+Featherlight.prototype.namespace; } ).join(' ');
$(window)[set ? 'on' : 'off'](events, globalEventHandler);
}
};
Featherlight.prototype = {
constructor: Featherlight,
/*** defaults ***/
/* extend featherlight with defaults and methods */
namespace: 'featherlight', /* Name of the events and css class prefix */
targetAttr: 'data-featherlight', /* Attribute of the triggered element that contains the selector to the lightbox content */
variant: null, /* Class that will be added to change look of the lightbox */
resetCss: false, /* Reset all css */
background: null, /* Custom DOM for the background, wrapper and the closebutton */
openTrigger: 'click', /* Event that triggers the lightbox */
closeTrigger: 'click', /* Event that triggers the closing of the lightbox */
filter: null, /* Selector to filter events. Think $(...).on('click', filter, eventHandler) */
root: 'body', /* Where to append featherlights */
openSpeed: 250, /* Duration of opening animation */
closeSpeed: 250, /* Duration of closing animation */
closeOnClick: 'background', /* Close lightbox on click ('background', 'anywhere' or false) */
closeOnEsc: true, /* Close lightbox when pressing esc */
closeIcon: '✕', /* Close icon */
loading: '', /* Content to show while initial content is loading */
persist: false, /* If set, the content will persist and will be shown again when opened again. 'shared' is a special value when binding multiple elements for them to share the same content */
otherClose: null, /* Selector for alternate close buttons (e.g. "a.close") */
beforeOpen: $.noop, /* Called before open. can return false to prevent opening of lightbox. Gets event as parameter, this contains all data */
beforeContent: $.noop, /* Called when content is loaded. Gets event as parameter, this contains all data */
beforeClose: $.noop, /* Called before close. can return false to prevent opening of lightbox. Gets event as parameter, this contains all data */
afterOpen: $.noop, /* Called after open. Gets event as parameter, this contains all data */
afterContent: $.noop, /* Called after content is ready and has been set. Gets event as parameter, this contains all data */
afterClose: $.noop, /* Called after close. Gets event as parameter, this contains all data */
onKeyUp: $.noop, /* Called on key up for the frontmost featherlight */
onResize: $.noop, /* Called after new content and when a window is resized */
type: null, /* Specify type of lightbox. If unset, it will check for the targetAttrs value. */
contentFilters: ['jquery', 'image', 'html', 'ajax', 'iframe', 'text'], /* List of content filters to use to determine the content */
/*** methods ***/
/* setup iterates over a single instance of featherlight and prepares the background and binds the events */
setup: function(target, config){
/* all arguments are optional */
if (typeof target === 'object' && target instanceof $ === false && !config) {
config = target;
target = undefined;
}
var self = $.extend(this, config, {target: target}),
css = !self.resetCss ? self.namespace : self.namespace+'-reset', /* by adding -reset to the classname, we reset all the default css */
$background = $(self.background || [
'<div class="'+css+'-loading '+css+'">',
'<div class="'+css+'-content">',
'<button class="'+css+'-close-icon '+ self.namespace + '-close" aria-label="Close">',
self.closeIcon,
'</button>',
'<div class="'+self.namespace+'-inner">' + self.loading + '</div>',
'</div>',
'</div>'].join('')),
closeButtonSelector = '.'+self.namespace+'-close' + (self.otherClose ? ',' + self.otherClose : '');
self.$instance = $background.clone().addClass(self.variant); /* clone DOM for the background, wrapper and the close button */
/* close when click on background/anywhere/null or closebox */
self.$instance.on(self.closeTrigger+'.'+self.namespace, function(event) {
var $target = $(event.target);
if( ('background' === self.closeOnClick && $target.is('.'+self.namespace))
|| 'anywhere' === self.closeOnClick
|| $target.closest(closeButtonSelector).length ){
self.close(event);
event.preventDefault();
}
});
return this;
},
/* this method prepares the content and converts it into a jQuery object or a promise */
getContent: function(){
if(this.persist !== false && this.$content) {
return this.$content;
}
var self = this,
filters = this.constructor.contentFilters,
readTargetAttr = function(name){ return self.$currentTarget && self.$currentTarget.attr(name); },
targetValue = readTargetAttr(self.targetAttr),
data = self.target || targetValue || '';
/* Find which filter applies */
var filter = filters[self.type]; /* check explicit type like {type: 'image'} */
/* check explicit type like data-featherlight="image" */
if(!filter && data in filters) {
filter = filters[data];
data = self.target && targetValue;
}
data = data || readTargetAttr('href') || '';
/* check explicity type & content like {image: 'photo.jpg'} */
if(!filter) {
for(var filterName in filters) {
if(self[filterName]) {
filter = filters[filterName];
data = self[filterName];
}
}
}
/* otherwise it's implicit, run checks */
if(!filter) {
var target = data;
data = null;
$.each(self.contentFilters, function() {
filter = filters[this];
if(filter.test) {
data = filter.test(target);
}
if(!data && filter.regex && target.match && target.match(filter.regex)) {
data = target;
}
return !data;
});
if(!data) {
if('console' in window){ window.console.error('Featherlight: no content filter found ' + (target ? ' for "' + target + '"' : ' (no target specified)')); }
return false;
}
}
/* Process it */
return filter.process.call(self, data);
},
/* sets the content of $instance to $content */
setContent: function($content){
var self = this;
/* we need a special class for the iframe */
if($content.is('iframe')) {
self.$instance.addClass(self.namespace+'-iframe');
}
self.$instance.removeClass(self.namespace+'-loading');
/* replace content by appending to existing one before it is removed
this insures that featherlight-inner remain at the same relative
position to any other items added to featherlight-content */
self.$instance.find('.'+self.namespace+'-inner')
.not($content) /* excluded new content, important if persisted */
.slice(1).remove().end() /* In the unexpected event where there are many inner elements, remove all but the first one */
.replaceWith($.contains(self.$instance[0], $content[0]) ? '' : $content);
self.$content = $content.addClass(self.namespace+'-inner');
return self;
},
/* opens the lightbox. "this" contains $instance with the lightbox, and with the config.
Returns a promise that is resolved after is successfully opened. */
open: function(event){
var self = this;
self.$instance.hide().appendTo(self.root);
if((!event || !event.isDefaultPrevented())
&& self.beforeOpen(event) !== false) {
if(event){
event.preventDefault();
}
var $content = self.getContent();
if($content) {
opened.push(self);
toggleGlobalEvents(true);
self.$instance.fadeIn(self.openSpeed);
self.beforeContent(event);
/* Set content and show */
return $.when($content)
.always(function($content){
self.setContent($content);
self.afterContent(event);
})
.then(self.$instance.promise())
/* Call afterOpen after fadeIn is done */
.done(function(){ self.afterOpen(event); });
}
}
self.$instance.detach();
return $.Deferred().reject().promise();
},
/* closes the lightbox. "this" contains $instance with the lightbox, and with the config
returns a promise, resolved after the lightbox is successfully closed. */
close: function(event){
var self = this,
deferred = $.Deferred();
if(self.beforeClose(event) === false) {
deferred.reject();
} else {
if (0 === pruneOpened(self).length) {
toggleGlobalEvents(false);
}
self.$instance.fadeOut(self.closeSpeed,function(){
self.$instance.detach();
self.afterClose(event);
deferred.resolve();
});
}
return deferred.promise();
},
/* resizes the content so it fits in visible area and keeps the same aspect ratio.
Does nothing if either the width or the height is not specified.
Called automatically on window resize.
Override if you want different behavior. */
resize: function(w, h) {
if (w && h) {
/* Reset apparent image size first so container grows */
this.$content.css('width', '').css('height', '');
/* Calculate the worst ratio so that dimensions fit */
/* Note: -1 to avoid rounding errors */
var ratio = Math.max(
w / (this.$content.parent().width()-1),
h / (this.$content.parent().height()-1));
/* Resize content */
if (ratio > 1) {
ratio = h / Math.floor(h / ratio); /* Round ratio down so height calc works */
this.$content.css('width', '' + w / ratio + 'px').css('height', '' + h / ratio + 'px');
}
}
},
/* Utility function to chain callbacks
[Warning: guru-level]
Used be extensions that want to let users specify callbacks but
also need themselves to use the callbacks.
The argument 'chain' has callback names as keys and function(super, event)
as values. That function is meant to call `super` at some point.
*/
chainCallbacks: function(chain) {
for (var name in chain) {
this[name] = $.proxy(chain[name], this, $.proxy(this[name], this));
}
}
};
$.extend(Featherlight, {
id: 0, /* Used to id single featherlight instances */
autoBind: '[data-featherlight]', /* Will automatically bind elements matching this selector. Clear or set before onReady */
defaults: Featherlight.prototype, /* You can access and override all defaults using $.featherlight.defaults, which is just a synonym for $.featherlight.prototype */
/* Contains the logic to determine content */
contentFilters: {
jquery: {
regex: /^[#.]\w/, /* Anything that starts with a class name or identifiers */
test: function(elem) { return elem instanceof $ && elem; },
process: function(elem) { return this.persist !== false ? $(elem) : $(elem).clone(true); }
},
image: {
regex: /\.(png|jpg|jpeg|gif|tiff?|bmp|svg)(\?\S*)?$/i,
process: function(url) {
var self = this,
deferred = $.Deferred(),
img = new Image(),
$img = $('<img src="'+url+'" alt="" class="'+self.namespace+'-image" />');
img.onload = function() {
/* Store naturalWidth & height for IE8 */
$img.naturalWidth = img.width; $img.naturalHeight = img.height;
deferred.resolve( $img );
};
img.onerror = function() { deferred.reject($img); };
img.src = url;
return deferred.promise();
}
},
html: {
regex: /^\s*<[\w!][^<]*>/, /* Anything that starts with some kind of valid tag */
process: function(html) { return $(html); }
},
ajax: {
regex: /./, /* At this point, any content is assumed to be an URL */
process: function(url) {
var self = this,
deferred = $.Deferred();
/* we are using load so one can specify a target with: url.html #targetelement */
var $container = $('<div></div>').load(url, function(response, status){
if ( status !== "error" ) {
deferred.resolve($container.contents());
}
deferred.fail();
});
return deferred.promise();
}
},
iframe: {
process: function(url) {
var deferred = new $.Deferred();
var $content = $('<iframe/>');
var css = parseAttrs(this, 'iframe');
var attrs = slice(css, iFrameAttributeSet);
$content.hide()
.attr('src', url)
.attr(attrs)
.css(css)
.on('load', function() { deferred.resolve($content.show()); })
// We can't move an <iframe> and avoid reloading it,
// so let's put it in place ourselves right now:
.appendTo(this.$instance.find('.' + this.namespace + '-content'));
return deferred.promise();
}
},
text: {
process: function(text) { return $('<div>', {text: text}); }
}
},
functionAttributes: ['beforeOpen', 'afterOpen', 'beforeContent', 'afterContent', 'beforeClose', 'afterClose'],
/*** class methods ***/
/* read element's attributes starting with data-featherlight- */
readElementConfig: function(element, namespace) {
var Klass = this,
regexp = new RegExp('^data-' + namespace + '-(.*)'),
config = {};
if (element && element.attributes) {
$.each(element.attributes, function(){
var match = this.name.match(regexp);
if (match) {
var val = this.value,
name = $.camelCase(match[1]);
if ($.inArray(name, Klass.functionAttributes) >= 0) { /* jshint -W054 */
val = new Function(val); /* jshint +W054 */
} else {
try { val = JSON.parse(val); }
catch(e) {}
}
config[name] = val;
}
});
}
return config;
},
/* Used to create a Featherlight extension
[Warning: guru-level]
Creates the extension's prototype that in turn
inherits Featherlight's prototype.
Could be used to extend an extension too...
This is pretty high level wizardy, it comes pretty much straight
from CoffeeScript and won't teach you anything about Featherlight
as it's not really specific to this library.
My suggestion: move along and keep your sanity.
*/
extend: function(child, defaults) {
/* Setup class hierarchy, adapted from CoffeeScript */
var Ctor = function(){ this.constructor = child; };
Ctor.prototype = this.prototype;
child.prototype = new Ctor();
child.__super__ = this.prototype;
/* Copy class methods & attributes */
$.extend(child, this, defaults);
child.defaults = child.prototype;
return child;
},
attach: function($source, $content, config) {
var Klass = this;
if (typeof $content === 'object' && $content instanceof $ === false && !config) {
config = $content;
$content = undefined;
}
/* make a copy */
config = $.extend({}, config);
/* Only for openTrigger and namespace... */
var namespace = config.namespace || Klass.defaults.namespace,
tempConfig = $.extend({}, Klass.defaults, Klass.readElementConfig($source[0], namespace), config),
sharedPersist;
var handler = function(event) {
var $target = $(event.currentTarget);
/* ... since we might as well compute the config on the actual target */
var elemConfig = $.extend(
{$source: $source, $currentTarget: $target},
Klass.readElementConfig($source[0], tempConfig.namespace),
Klass.readElementConfig(event.currentTarget, tempConfig.namespace),
config);
var fl = sharedPersist || $target.data('featherlight-persisted') || new Klass($content, elemConfig);
if(fl.persist === 'shared') {
sharedPersist = fl;
} else if(fl.persist !== false) {
$target.data('featherlight-persisted', fl);
}
if (elemConfig.$currentTarget.blur) {
elemConfig.$currentTarget.blur(); // Otherwise 'enter' key might trigger the dialog again
}
fl.open(event);
};
$source.on(tempConfig.openTrigger+'.'+tempConfig.namespace, tempConfig.filter, handler);
return handler;
},
current: function() {
var all = this.opened();
return all[all.length - 1] || null;
},
opened: function() {
var klass = this;
pruneOpened();
return $.grep(opened, function(fl) { return fl instanceof klass; } );
},
close: function(event) {
var cur = this.current();
if(cur) { return cur.close(event); }
},
/* Does the auto binding on startup.
Meant only to be used by Featherlight and its extensions
*/
_onReady: function() {
var Klass = this;
if(Klass.autoBind){
/* Bind existing elements */
$(Klass.autoBind).each(function(){
Klass.attach($(this));
});
/* If a click propagates to the document level, then we have an item that was added later on */
$(document).on('click', Klass.autoBind, function(evt) {
if (evt.isDefaultPrevented()) {
return;
}
/* Bind featherlight */
var handler = Klass.attach($(evt.currentTarget));
/* Dispatch event directly */
handler(evt);
});
}
},
/* Featherlight uses the onKeyUp callback to intercept the escape key.
Private to Featherlight.
*/
_callbackChain: {
onKeyUp: function(_super, event){
if(27 === event.keyCode) {
if (this.closeOnEsc) {
$.featherlight.close(event);
}
return false;
} else {
return _super(event);
}
},
beforeOpen: function(_super, event) {
// Used to disable scrolling
$(document.documentElement).addClass('with-featherlight');
// Remember focus:
this._previouslyActive = document.activeElement;
// Disable tabbing:
// See http://stackoverflow.com/questions/1599660/which-html-elements-can-receive-focus
this._$previouslyTabbable = $("a, input, select, textarea, iframe, button, iframe, [contentEditable=true]")
.not('[tabindex]')
.not(this.$instance.find('button'));
this._$previouslyWithTabIndex = $('[tabindex]').not('[tabindex="-1"]');
this._previousWithTabIndices = this._$previouslyWithTabIndex.map(function(_i, elem) {
return $(elem).attr('tabindex');
});
this._$previouslyWithTabIndex.add(this._$previouslyTabbable).attr('tabindex', -1);
if (document.activeElement.blur) {
document.activeElement.blur();
}
return _super(event);
},
afterClose: function(_super, event) {
var r = _super(event);
// Restore focus
var self = this;
this._$previouslyTabbable.removeAttr('tabindex');
this._$previouslyWithTabIndex.each(function(i, elem) {
$(elem).attr('tabindex', self._previousWithTabIndices[i]);
});
this._previouslyActive.focus();
// Restore scroll
if(Featherlight.opened().length === 0) {
$(document.documentElement).removeClass('with-featherlight');
}
return r;
},
onResize: function(_super, event){
this.resize(this.$content.naturalWidth, this.$content.naturalHeight);
return _super(event);
},
afterContent: function(_super, event){
var r = _super(event);
this.$instance.find('[autofocus]:not([disabled])').focus();
this.onResize(event);
return r;
}
}
});
$.featherlight = Featherlight;
/* bind jQuery elements to trigger featherlight */
$.fn.featherlight = function($content, config) {
Featherlight.attach(this, $content, config);
return this;
};
/* bind featherlight on ready if config autoBind is set */
$(document).ready(function(){ Featherlight._onReady(); });
}(jQuery));
| Add check for slim version [#329]
| src/featherlight.js | Add check for slim version [#329] | <ide><path>rc/featherlight.js
<ide> if('console' in window){ window.console.info('Too much lightness, Featherlight needs jQuery.'); }
<ide> return;
<ide> }
<del>
<add> if($.fn.jquery.match(/-ajax/)) {
<add> if('console' in window){ window.console.info('Featherlight needs regular jQuery, not the slim version.'); }
<add> return;
<add> }
<ide> /* Featherlight is exported as $.featherlight.
<ide> It is a function used to open a featherlight lightbox.
<ide> |
|
Java | apache-2.0 | d08ef09bc37b2d40eceb7a433ee82e8f35e2598a | 0 | dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android | package org.commcare.views.widgets;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import org.commcare.dalvik.R;
import org.commcare.interfaces.AdvanceToNextListener;
import org.commcare.views.media.MediaLayout;
import org.javarosa.core.model.SelectChoice;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.SelectOneData;
import org.javarosa.core.model.data.helper.Selection;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryPrompt;
import java.util.Vector;
/**
* SelectOneWidgets handles select-one fields using radio buttons. Unlike the classic
* SelectOneWidget, when a user clicks an option they are then immediately advanced to the next
* question.
*
* @author Jeff Beorse ([email protected])
*/
public class SelectOneAutoAdvanceWidget extends QuestionWidget implements OnCheckedChangeListener {
private final Vector<SelectChoice> mItems;
private final Vector<RadioButton> buttons;
private final AdvanceToNextListener listener;
private final int buttonIdBase;
public SelectOneAutoAdvanceWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
LayoutInflater inflater = LayoutInflater.from(getContext());
mItems = prompt.getSelectChoices();
buttons = new Vector<>();
listener = (AdvanceToNextListener)context;
String s = null;
if (prompt.getAnswerValue() != null) {
s = ((Selection)prompt.getAnswerValue().getValue()).getValue();
}
//Is this safe enough from collisions?
buttonIdBase = Math.abs(prompt.getIndex().hashCode());
if (prompt.getSelectChoices() != null) {
for (int i = 0; i < mItems.size(); i++) {
RelativeLayout thisParentLayout =
(RelativeLayout)inflater.inflate(R.layout.quick_select_layout, null);
final LinearLayout questionLayout = (LinearLayout)thisParentLayout.getChildAt(0);
ImageView rightArrow = (ImageView)thisParentLayout.getChildAt(1);
final RadioButton r = new RadioButton(getContext());
r.setOnCheckedChangeListener(this);
String markdownText = prompt.getSelectItemMarkdownText(mItems.get(i));
if (markdownText != null) {
r.setText(forceMarkdown(markdownText));
} else {
r.setText(prompt.getSelectChoiceText(mItems.get(i)));
}
r.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize);
r.setId(i + buttonIdBase);
r.setEnabled(!prompt.isReadOnly());
r.setFocusable(!prompt.isReadOnly());
Drawable image = getResources().getDrawable(R.drawable.icon_auto_advance_arrow);
rightArrow.setImageDrawable(image);
rightArrow.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
r.onTouchEvent(event);
return false;
}
});
buttons.add(r);
if (mItems.get(i).getValue().equals(s)) {
r.setChecked(true);
}
String audioURI = null;
audioURI =
prompt.getSpecialFormSelectChoiceText(mItems.get(i),
FormEntryCaption.TEXT_FORM_AUDIO);
String imageURI = null;
imageURI =
prompt.getSpecialFormSelectChoiceText(mItems.get(i),
FormEntryCaption.TEXT_FORM_IMAGE);
String videoURI = null;
videoURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i), "video");
String bigImageURI = null;
bigImageURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i), "big-image");
MediaLayout mediaLayout = MediaLayout.buildAudioImageVisualLayout(getContext(), r, audioURI, imageURI, videoURI, bigImageURI);
questionLayout.addView(mediaLayout);
// Last, add the dividing line (except for the last element)
ImageView divider = new ImageView(getContext());
divider.setBackgroundResource(android.R.drawable.divider_horizontal_bright);
if (i != mItems.size() - 1) {
mediaLayout.addDivider(divider);
}
addView(thisParentLayout);
}
}
}
@Override
public void clearAnswer() {
for (RadioButton button : this.buttons) {
if (button.isChecked()) {
button.setChecked(false);
return;
}
}
}
@Override
public IAnswerData getAnswer() {
int i = getCheckedId();
if (i == -1) {
return null;
} else {
SelectChoice sc = mItems.elementAt(i - buttonIdBase);
return new SelectOneData(new Selection(sc));
}
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
private int getCheckedId() {
for (RadioButton button : this.buttons) {
if (button.isChecked()) {
return button.getId();
}
}
return -1;
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!buttonView.isPressed()) {
return;
}
if (!isChecked) {
// If it got unchecked, we don't care.
return;
}
for (RadioButton button : this.buttons) {
if (button.isChecked() && !(buttonView == button)) {
button.setChecked(false);
}
}
widgetEntryChanged();
listener.advance();
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
for (RadioButton r : buttons) {
r.setOnLongClickListener(l);
}
}
@Override
public void unsetListeners() {
super.unsetListeners();
for (RadioButton r : buttons) {
r.setOnLongClickListener(null);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
for (RadioButton r : buttons) {
r.cancelLongPress();
}
}
}
| app/src/org/commcare/views/widgets/SelectOneAutoAdvanceWidget.java | package org.commcare.views.widgets;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import org.commcare.dalvik.R;
import org.commcare.interfaces.AdvanceToNextListener;
import org.commcare.views.media.MediaLayout;
import org.javarosa.core.model.SelectChoice;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.SelectOneData;
import org.javarosa.core.model.data.helper.Selection;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryPrompt;
import java.util.Vector;
/**
* SelectOneWidgets handles select-one fields using radio buttons. Unlike the classic
* SelectOneWidget, when a user clicks an option they are then immediately advanced to the next
* question.
*
* @author Jeff Beorse ([email protected])
*/
public class SelectOneAutoAdvanceWidget extends QuestionWidget implements OnCheckedChangeListener {
private final Vector<SelectChoice> mItems;
private final Vector<RadioButton> buttons;
private final AdvanceToNextListener listener;
private final int buttonIdBase;
public SelectOneAutoAdvanceWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
LayoutInflater inflater = LayoutInflater.from(getContext());
mItems = prompt.getSelectChoices();
buttons = new Vector<>();
listener = (AdvanceToNextListener)context;
String s = null;
if (prompt.getAnswerValue() != null) {
s = ((Selection)prompt.getAnswerValue().getValue()).getValue();
}
//Is this safe enough from collisions?
buttonIdBase = Math.abs(prompt.getIndex().hashCode());
if (prompt.getSelectChoices() != null) {
for (int i = 0; i < mItems.size(); i++) {
RelativeLayout thisParentLayout =
(RelativeLayout)inflater.inflate(R.layout.quick_select_layout, null);
final LinearLayout questionLayout = (LinearLayout)thisParentLayout.getChildAt(0);
ImageView rightArrow = (ImageView)thisParentLayout.getChildAt(1);
final RadioButton r = new RadioButton(getContext());
r.setOnCheckedChangeListener(this);
String markdownText = prompt.getSelectItemMarkdownText(mItems.get(i));
if (markdownText != null) {
r.setText(forceMarkdown(markdownText));
} else {
r.setText(prompt.getSelectChoiceText(mItems.get(i)));
}
r.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize);
r.setId(i + buttonIdBase);
r.setEnabled(!prompt.isReadOnly());
r.setFocusable(!prompt.isReadOnly());
Drawable image = getResources().getDrawable(R.drawable.icon_auto_advance_arrow);
rightArrow.setImageDrawable(image);
rightArrow.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
r.onTouchEvent(event);
return false;
}
});
rightArrow.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//r.performClick();
int g = 3;
}
});
buttons.add(r);
if (mItems.get(i).getValue().equals(s)) {
r.setChecked(true);
}
String audioURI = null;
audioURI =
prompt.getSpecialFormSelectChoiceText(mItems.get(i),
FormEntryCaption.TEXT_FORM_AUDIO);
String imageURI = null;
imageURI =
prompt.getSpecialFormSelectChoiceText(mItems.get(i),
FormEntryCaption.TEXT_FORM_IMAGE);
String videoURI = null;
videoURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i), "video");
String bigImageURI = null;
bigImageURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i), "big-image");
MediaLayout mediaLayout = MediaLayout.buildAudioImageVisualLayout(getContext(), r, audioURI, imageURI, videoURI, bigImageURI);
questionLayout.addView(mediaLayout);
// Last, add the dividing line (except for the last element)
ImageView divider = new ImageView(getContext());
divider.setBackgroundResource(android.R.drawable.divider_horizontal_bright);
if (i != mItems.size() - 1) {
mediaLayout.addDivider(divider);
}
addView(thisParentLayout);
}
}
}
@Override
public void clearAnswer() {
for (RadioButton button : this.buttons) {
if (button.isChecked()) {
button.setChecked(false);
return;
}
}
}
@Override
public IAnswerData getAnswer() {
int i = getCheckedId();
if (i == -1) {
return null;
} else {
SelectChoice sc = mItems.elementAt(i - buttonIdBase);
return new SelectOneData(new Selection(sc));
}
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
private int getCheckedId() {
for (RadioButton button : this.buttons) {
if (button.isChecked()) {
return button.getId();
}
}
return -1;
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!buttonView.isPressed()) {
return;
}
if (!isChecked) {
// If it got unchecked, we don't care.
return;
}
for (RadioButton button : this.buttons) {
if (button.isChecked() && !(buttonView == button)) {
button.setChecked(false);
}
}
widgetEntryChanged();
listener.advance();
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
for (RadioButton r : buttons) {
r.setOnLongClickListener(l);
}
}
@Override
public void unsetListeners() {
super.unsetListeners();
for (RadioButton r : buttons) {
r.setOnLongClickListener(null);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
for (RadioButton r : buttons) {
r.cancelLongPress();
}
}
}
| removed unused code
| app/src/org/commcare/views/widgets/SelectOneAutoAdvanceWidget.java | removed unused code | <ide><path>pp/src/org/commcare/views/widgets/SelectOneAutoAdvanceWidget.java
<ide> return false;
<ide> }
<ide> });
<del> rightArrow.setOnClickListener(new OnClickListener() {
<del>
<del> @Override
<del> public void onClick(View v) {
<del> //r.performClick();
<del> int g = 3;
<del> }
<del> });
<del>
<del>
<ide>
<ide> buttons.add(r);
<ide> |
|
JavaScript | mit | 7d08ffca7ebe8981e45a6abfd570eddcd3f792dd | 0 | davidbonnet/astring | // Astring is a tiny and fast JavaScript code generator from an ESTree-compliant AST.
//
// Astring was written by David Bonnet and released under an MIT license.
//
// The Git repository for Astring is available at:
// https://github.com/davidbonnet/astring.git
//
// Please use the GitHub bug tracker to report issues:
// https://github.com/davidbonnet/astring/issues
const { stringify } = JSON;
const OPERATORS_PRECEDENCE = {
'||': 3,
'&&': 4,
'|': 5,
'^': 6,
'&': 7,
'==': 8,
'!=': 8,
'===': 8,
'!==': 8,
'<': 9,
'>': 9,
'<=': 9,
'>=': 9,
'in': 9,
'instanceof': 9,
'<<': 10,
'>>': 10,
'>>>': 10,
'+': 11,
'-': 11,
'*': 12,
'%': 12,
'/': 12,
'**': 12
}
const EXPRESSIONS_PRECEDENCE = {
// Definitions
ArrayExpression: 20,
TaggedTemplateExpression: 20,
ThisExpression: 20,
Identifier: 20,
Literal: 18,
TemplateLiteral: 20,
Super: 20,
SequenceExpression: 20,
// Operations
MemberExpression: 19,
CallExpression: 19,
NewExpression: 19,
ArrowFunctionExpression: 18,
// Other definitions
// Value 17 enables parenthesis in an `ExpressionStatement` node
ClassExpression: 17,
FunctionExpression: 17,
ObjectExpression: 17,
// Other operations
UpdateExpression: 16,
UnaryExpression: 15,
BinaryExpression: 14,
LogicalExpression: 13,
ConditionalExpression: 4,
AssignmentExpression: 3,
YieldExpression: 2,
RestElement: 1
}
function formatSequence( nodes, state, traveler ) {
/*
Formats a sequence of `nodes`.
*/
const { output } = state
output.write( '(' )
if ( nodes != null && nodes.length > 0 ) {
traveler[ nodes[ 0 ].type ]( nodes[ 0 ], state )
const { length } = nodes
for ( let i = 1; i < length; i++ ) {
let param = nodes[ i ]
output.write( ', ' )
traveler[ param.type ]( param, state )
}
}
output.write( ')' )
}
function formatBinaryExpressionPart( node, parentNode, isRightHand, state, traveler ) {
/*
Formats into the `output` stream a left-hand or right-hand expression `node` from a binary expression applying the provided `operator`.
The `isRightHand` parameter should be `true` if the `node` is a right-hand argument.
*/
const nodePrecedence = EXPRESSIONS_PRECEDENCE[ node.type ]
const parentNodePrecedence = EXPRESSIONS_PRECEDENCE[ parentNode.type ]
if ( nodePrecedence > parentNodePrecedence ) {
traveler[ node.type ]( node, state )
return
} else if ( nodePrecedence === parentNodePrecedence ) {
if ( nodePrecedence === 13 || nodePrecedence === 14 ) {
// Either `LogicalExpression` or `BinaryExpression`
if ( isRightHand ) {
if ( OPERATORS_PRECEDENCE[ node.operator ] > OPERATORS_PRECEDENCE[ parentNode.operator ] ) {
traveler[ node.type ]( node, state )
return
}
} else {
if ( OPERATORS_PRECEDENCE[ node.operator ] >= OPERATORS_PRECEDENCE[ parentNode.operator ] ) {
traveler[ node.type ]( node, state )
return
}
}
} else {
traveler[ node.type ]( node, state )
return
}
}
state.output.write( '(' )
traveler[ node.type ]( node, state )
state.output.write( ')' )
}
function reindent( text, indentation ) {
/*
Returns the `text` string reindented with the provided `indentation`.
*/
text = text.trimRight()
let indents = '\n'
let secondLine = false
const { length } = text
for ( let i = 0; i < length; i++ ) {
let char = text[ i ]
if ( secondLine ) {
if ( char === ' ' || char === '\t' ) {
indents += char
} else {
return indentation + text.trimLeft().split( indents ).join( '\n' + indentation )
}
} else {
if ( char === '\n' ) {
secondLine = true
}
}
}
return indentation + text.trimLeft()
}
function formatComments( comments, output, indent, lineEnd ) {
/*
Inserts into `output` the provided list of `comments`, with the given `indent` and `lineEnd` strings.
Line comments will end with `"\n"` regardless of the value of `lineEnd`.
Expects to start on a new unindented line.
*/
const { length } = comments
for ( let i = 0; i < length; i++ ) {
let comment = comments[ i ]
output.write( indent )
if ( comment.type[ 0 ] === 'L' )
// Line comment
output.write( '// ' + comment.value.trim() + '\n' )
else
// Block comment
output.write( '/*' + lineEnd + reindent( comment.value, indent ) + lineEnd + indent + '*/' + lineEnd )
}
}
function hasCallExpression( node ) {
/*
Returns `true` if the provided `node` contains a call expression and `false` otherwise.
*/
while ( node != null ) {
let { type } = node
if ( type[ 0 ] === 'C' && type[ 1 ] === 'a' ) {
// Is CallExpression
return true
} else if ( type[ 0 ] === 'M' && type[ 1 ] === 'e' && type[ 2 ] === 'm' ) {
// Is MemberExpression
node = node.object
} else {
return false
}
}
}
let ForInStatement, FunctionDeclaration, RestElement, BinaryExpression, ArrayExpression, BlockStatement
export const defaultGenerator = {
Program( node, state ) {
const indent = state.indent.repeat( state.indentLevel )
const { lineEnd, output, writeComments } = state
if ( writeComments && node.comments != null )
formatComments( node.comments, output, indent, lineEnd )
let statements = node.body
const { length } = statements
for ( let i = 0; i < length; i++ ) {
let statement = statements[ i ]
if ( writeComments && statement.comments != null )
formatComments( statement.comments, output, indent, lineEnd )
output.write( indent )
this[ statement.type ]( statement, state )
output.write( lineEnd )
}
if ( writeComments && node.trailingComments != null )
formatComments( node.trailingComments, output, indent, lineEnd )
},
BlockStatement: BlockStatement = function( node, state ) {
const indent = state.indent.repeat( state.indentLevel++ )
const { lineEnd, output, writeComments } = state
const statementIndent = indent + state.indent
output.write( '{' )
let statements = node.body
if ( statements != null && statements.length > 0 ) {
output.write( lineEnd )
if ( writeComments && node.comments != null ) {
formatComments( node.comments, output, statementIndent, lineEnd )
}
const { length } = statements
for ( let i = 0; i < length; i++ ) {
let statement = statements[ i ]
if ( writeComments && statement.comments != null )
formatComments( statement.comments, output, statementIndent, lineEnd )
output.write( statementIndent )
this[ statement.type ]( statement, state )
output.write( lineEnd )
}
output.write( indent )
} else {
if ( writeComments && node.comments != null ) {
output.write( lineEnd )
formatComments( node.comments, output, statementIndent, lineEnd )
output.write( indent )
}
}
if ( writeComments && node.trailingComments != null )
formatComments( node.trailingComments, output, statementIndent, lineEnd )
output.write( '}' )
state.indentLevel--
},
ClassBody: BlockStatement,
EmptyStatement( node, state ) {
state.output.write( ';' )
},
ExpressionStatement( node, state ) {
const precedence = EXPRESSIONS_PRECEDENCE[ node.expression.type ]
if ( precedence === 17 || ( precedence === 3 && node.expression.left.type[ 0 ] === 'O' ) ) {
// Should always have parentheses or is an AssignmentExpression to an ObjectPattern
state.output.write( '(' )
this[ node.expression.type ]( node.expression, state )
state.output.write( ')' )
} else {
this[ node.expression.type ]( node.expression, state )
}
state.output.write( ';' )
},
IfStatement( node, state ) {
const { output } = state
output.write( 'if (' )
this[ node.test.type ]( node.test, state )
output.write( ') ' )
this[ node.consequent.type ]( node.consequent, state )
if ( node.alternate != null ) {
output.write( ' else ' )
this[ node.alternate.type ]( node.alternate, state )
}
},
LabeledStatement( node, state ) {
this[ node.label.type ]( node.label, state )
state.output.write( ': ' )
this[ node.body.type ]( node.body, state )
},
BreakStatement( node, state ) {
const { output } = state
output.write( 'break' )
if ( node.label ) {
output.write( ' ' )
this[ node.label.type ]( node.label, state )
}
output.write( ';' )
},
ContinueStatement( node, state ) {
const { output } = state
output.write( 'continue' )
if ( node.label ) {
output.write( ' ' )
this[ node.label.type ]( node.label, state )
}
output.write( ';' )
},
WithStatement( node, state ) {
const { output } = state
output.write( 'with (' )
this[ node.object.type ]( node.object, state )
output.write( ') ' )
this[ node.body.type ]( node.body, state )
},
SwitchStatement( node, state ) {
const indent = state.indent.repeat( state.indentLevel++ )
const { lineEnd, output, writeComments } = state
state.indentLevel++
const caseIndent = indent + state.indent
const statementIndent = caseIndent + state.indent
output.write( 'switch (' )
this[ node.discriminant.type ]( node.discriminant, state )
output.write( ') \{' + lineEnd )
const { cases: occurences } = node
const { length: occurencesCount } = occurences
for ( let i = 0; i < occurencesCount; i++ ) {
let occurence = occurences[ i ]
if ( writeComments && occurence.comments != null )
formatComments( occurence.comments, output, caseIndent, lineEnd )
if ( occurence.test ) {
output.write( caseIndent + 'case ' )
this[ occurence.test.type ]( occurence.test, state )
output.write( ':' + lineEnd )
} else {
output.write( caseIndent + 'default:' + lineEnd )
}
let { consequent } = occurence
const { length: consequentCount } = consequent
for ( let i = 0; i < consequentCount; i++ ) {
let statement = consequent[ i ]
if ( writeComments && statement.comments != null )
formatComments( statement.comments, output, statementIndent, lineEnd )
output.write( statementIndent )
this[ statement.type ]( statement, state )
output.write( lineEnd )
}
}
state.indentLevel -= 2
output.write( indent + '}' )
},
ReturnStatement( node, state ) {
const { output } = state
output.write( 'return' )
if ( node.argument ) {
output.write( ' ' )
this[ node.argument.type ]( node.argument, state )
}
output.write( ';' )
},
ThrowStatement( node, state ) {
const { output } = state
output.write( 'throw ' )
this[ node.argument.type ]( node.argument, state )
output.write( ';' )
},
TryStatement( node, state ) {
const { output } = state
output.write( 'try ' )
this[ node.block.type ]( node.block, state )
if ( node.handler ) {
let { handler } = node
output.write( ' catch (' )
this[ handler.param.type ]( handler.param, state )
output.write( ') ' )
this[ handler.body.type ]( handler.body, state )
}
if ( node.finalizer ) {
output.write( ' finally ' )
this[ node.finalizer.type ]( node.finalizer, state )
}
},
WhileStatement( node, state ) {
const { output } = state
output.write( 'while (' )
this[ node.test.type ]( node.test, state )
output.write( ') ' )
this[ node.body.type ]( node.body, state )
},
DoWhileStatement( node, state ) {
const { output } = state
output.write( 'do ' )
this[ node.body.type ]( node.body, state )
output.write( ' while (' )
this[ node.test.type ]( node.test, state )
output.write( ');' )
},
ForStatement( node, state ) {
const { output } = state
output.write( 'for (' )
if ( node.init != null ) {
const { init } = node
state.noTrailingSemicolon = true
this[ node.init.type ]( node.init, state )
state.noTrailingSemicolon = false
}
output.write( '; ' )
if ( node.test )
this[ node.test.type ]( node.test, state )
output.write( '; ' )
if ( node.update )
this[ node.update.type ]( node.update, state )
output.write( ') ' )
this[ node.body.type ]( node.body, state )
},
ForInStatement: ForInStatement = function( node, state ) {
const { output } = state
output.write( 'for (' )
const { left } = node, { type } = left
state.noTrailingSemicolon = true
this[ type ]( left, state )
state.noTrailingSemicolon = false
// Identifying whether node.type is `ForInStatement` or `ForOfStatement`
output.write( node.type[ 3 ] === 'I' ? ' in ' : ' of ' )
this[ node.right.type ]( node.right, state )
output.write( ') ' )
this[ node.body.type ]( node.body, state )
},
ForOfStatement: ForInStatement,
DebuggerStatement( node, state ) {
state.output.write( 'debugger;' + state.lineEnd )
},
FunctionDeclaration: FunctionDeclaration = function( node, state ) {
const { output } = state
output.write( node.generator ? 'function* ' : 'function ' )
if ( node.id )
output.write( node.id.name )
formatSequence( node.params, state, this )
output.write( ' ' )
this[ node.body.type ]( node.body, state )
},
FunctionExpression: FunctionDeclaration,
VariableDeclaration( node, state ) {
const { output } = state
const { declarations } = node
output.write( node.kind + ' ' )
const { length } = declarations
if ( length > 0 ) {
this.VariableDeclarator( declarations[ 0 ], state )
for ( let i = 1; i < length; i++ ) {
output.write( ', ' )
this.VariableDeclarator( declarations[ i ], state )
}
}
if ( state.noTrailingSemicolon !== true )
output.write( ';' )
},
VariableDeclarator( node, state ) {
this[ node.id.type ]( node.id, state )
if ( node.init != null ) {
state.output.write( ' = ' )
this[ node.init.type ]( node.init, state )
}
},
ClassDeclaration( node, state ) {
const { output } = state
output.write( 'class ' )
if ( node.id ) {
output.write( node.id.name + ' ' )
}
if ( node.superClass ) {
output.write( 'extends ' )
this[ node.superClass.type ]( node.superClass, state )
output.write( ' ' )
}
this[ node.body.type ]( node.body, state )
},
ImportDeclaration( node, state ) {
const { output } = state
output.write( 'import ' )
const { specifiers } = node
const { length } = specifiers
if ( length > 0 ) {
let i = 0, specifier
while ( i < length ) {
if ( i > 0 )
output.write( ', ' )
specifier = specifiers[ i ]
const type = specifier.type[ 6 ]
if (type === 'D') {
// ImportDefaultSpecifier
output.write( specifier.local.name )
i++
} else if (type === 'N') {
// ImportNamespaceSpecifier
output.write( '* as ' + specifier.local.name )
i++
} else {
// ImportSpecifier
break
}
}
if ( i < length ) {
output.write( '{' )
for ( ; ; ) {
specifier = specifiers[ i ]
let { name } = specifier.imported
output.write( name )
if ( name !== specifier.local.name ) {
output.write( ' as ' + specifier.local.name )
}
if ( ++i < length )
output.write( ', ' )
else
break
}
output.write( '}' )
}
output.write( ' from ' )
}
this.Literal( node.source, state )
output.write( ';' )
},
ExportDefaultDeclaration( node, state ) {
const { output } = state
output.write( 'export default ' )
this[ node.declaration.type ]( node.declaration, state )
if ( EXPRESSIONS_PRECEDENCE[ node.declaration.type ] && node.declaration.type[ 0 ] !== 'F' )
// All expression nodes except `FunctionExpression`
output.write( ';' )
},
ExportNamedDeclaration( node, state ) {
const { output } = state
output.write( 'export ' )
if ( node.declaration ) {
this[ node.declaration.type ]( node.declaration, state )
} else {
output.write( '{' )
const { specifiers } = node, { length } = specifiers
if ( length > 0 ) {
for ( let i = 0; ; ) {
let specifier = specifiers[ i ]
let { name } = specifier.local
output.write( name )
if ( name !== specifier.exported.name )
output.write( ' as ' + specifier.exported.name )
if ( ++i < length )
output.write( ', ' )
else
break
}
}
output.write( '}' )
if ( node.source ) {
output.write( ' from ' )
this.Literal( node.source, state )
}
output.write( ';' )
}
},
ExportAllDeclaration( node, state ) {
const { output } = state
output.write( 'export * from ' )
this.Literal( node.source, state )
output.write( ';' )
},
MethodDefinition( node, state ) {
const { output } = state
if ( node.static )
output.write( 'static ' )
switch ( node.kind[ 0 ] ) {
case 'g': // `get`
case 's': // `set`
output.write( node.kind + ' ' )
break
default:
break
}
if ( node.value.generator )
output.write( '*' )
if ( node.computed ) {
output.write( '[' )
this[ node.key.type ]( node.key, state )
output.write( ']' )
} else {
this[ node.key.type ]( node.key, state )
}
formatSequence( node.value.params, state, this )
output.write( ' ' )
this[ node.value.body.type ]( node.value.body, state )
},
ClassExpression( node, state ) {
this.ClassDeclaration( node, state )
},
ArrowFunctionExpression( node, state ) {
const { output } = state
const { params } = node
if ( params != null ) {
if ( params.length === 1 && params[ 0 ].type[ 0 ] === 'I' ) {
// If params[0].type[0] starts with 'I', it can't be `ImportDeclaration` nor `IfStatement` and thus is `Identifier`
output.write( params[ 0 ].name )
} else {
formatSequence( node.params, state, this )
}
}
output.write( ' => ' )
if ( node.body.type[ 0 ] === 'O' ) {
output.write( '(' )
this.ObjectExpression( node.body, state )
output.write( ')' )
} else {
this[ node.body.type ]( node.body, state )
}
},
ThisExpression( node, state ) {
state.output.write( 'this' )
},
Super( node, state ) {
state.output.write( 'super' )
},
RestElement: RestElement = function( node, state ) {
state.output.write( '...' )
this[ node.argument.type ]( node.argument, state )
},
SpreadElement: RestElement,
YieldExpression( node, state ) {
const { output } = state
output.write( node.delegate ? 'yield*' : 'yield' )
if ( node.argument ) {
output.write( ' ' )
this[ node.argument.type ]( node.argument, state )
}
},
TemplateLiteral( node, state ) {
const { output } = state
const { quasis, expressions } = node
output.write( '`' )
const { length } = expressions
for ( let i = 0; i < length; i++ ) {
let expression = expressions[ i ]
output.write( quasis[ i ].value.raw )
output.write( '${' )
this[ expression.type ]( expression, state )
output.write( '}' )
}
output.write( quasis[ quasis.length - 1 ].value.raw )
output.write( '`' )
},
TaggedTemplateExpression( node, state ) {
this[ node.tag.type ]( node.tag, state )
this[ node.quasi.type ]( node.quasi, state )
},
ArrayExpression: ArrayExpression = function( node, state ) {
const { output } = state
output.write( '[' )
if ( node.elements.length > 0 ) {
const { elements } = node, { length } = elements
for ( let i = 0; ; ) {
let element = elements[ i ]
if ( element != null )
this[ element.type ]( element, state )
if ( ++i < length ) {
output.write( ', ' )
} else {
if ( element == null )
output.write( ', ' )
break
}
}
}
output.write( ']' )
},
ArrayPattern: ArrayExpression,
ObjectExpression( node, state ) {
const indent = state.indent.repeat( state.indentLevel++ )
const { lineEnd, output, writeComments } = state
const propertyIndent = indent + state.indent
output.write( '{' )
if ( node.properties.length > 0 ) {
output.write( lineEnd )
if ( writeComments && node.comments != null )
formatComments( node.comments, output, propertyIndent, lineEnd )
const comma = ',' + lineEnd, { properties } = node, { length } = properties
for ( let i = 0; ; ) {
let property = properties[ i ]
if ( writeComments && property.comments != null )
formatComments( property.comments, output, propertyIndent, lineEnd )
output.write( propertyIndent )
this.Property( property, state )
if ( ++i < length )
output.write( comma )
else
break
}
output.write( lineEnd )
if ( writeComments && node.trailingComments != null )
formatComments( node.trailingComments, output, propertyIndent, lineEnd )
output.write( indent + '}' )
} else if ( writeComments ) {
if ( node.comments != null ) {
output.write( lineEnd )
formatComments( node.comments, output, propertyIndent, lineEnd )
if ( node.trailingComments != null )
formatComments( node.trailingComments, output, propertyIndent, lineEnd )
output.write( indent + '}' )
} else if ( node.trailingComments != null ) {
output.write( lineEnd )
formatComments( node.trailingComments, output, propertyIndent, lineEnd )
output.write( indent + '}' )
} else {
output.write( '}' )
}
} else {
output.write( '}' )
}
state.indentLevel--
},
Property( node, state ) {
if ( node.method || node.kind[ 0 ] !== 'i' ) {
// Either a method or of kind `set` or `get` (not `init`)
this.MethodDefinition( node, state )
} else {
const { output } = state
if ( !node.shorthand ) {
if ( node.computed ) {
output.write( '[' )
this[ node.key.type ]( node.key, state )
output.write( ']' )
} else {
this[ node.key.type ]( node.key, state )
}
output.write( ': ' )
}
this[ node.value.type ]( node.value, state )
}
},
ObjectPattern( node, state ) {
const { output } = state
output.write( '{' )
if ( node.properties.length > 0 ) {
const { properties } = node, { length } = properties
for ( let i = 0; ; ) {
this.Property( properties[ i ], state )
if ( ++i < length )
output.write( ', ' )
else
break
}
}
output.write( '}' )
},
SequenceExpression( node, state ) {
formatSequence( node.expressions, state, this )
},
UnaryExpression( node, state ) {
const { output } = state
if ( node.prefix ) {
output.write( node.operator )
if ( node.operator.length > 1 )
state.output.write( ' ' )
if ( EXPRESSIONS_PRECEDENCE[ node.argument.type ] < EXPRESSIONS_PRECEDENCE.UnaryExpression ) {
output.write( '(' )
this[ node.argument.type ]( node.argument, state )
output.write( ')' )
} else {
this[ node.argument.type ]( node.argument, state )
}
} else {
// FIXME: This case never occurs
this[ node.argument.type ]( node.argument, state )
state.output.write( node.operator )
}
},
UpdateExpression( node, state ) {
// Always applied to identifiers or members, no parenthesis check needed
if ( node.prefix ) {
state.output.write( node.operator )
this[ node.argument.type ]( node.argument, state )
} else {
this[ node.argument.type ]( node.argument, state )
state.output.write( node.operator )
}
},
AssignmentExpression( node, state ) {
this[ node.left.type ]( node.left, state )
state.output.write( ' ' + node.operator + ' ' )
this[ node.right.type ]( node.right, state )
},
AssignmentPattern( node, state ) {
this[ node.left.type ]( node.left, state )
state.output.write( ' = ' )
this[ node.right.type ]( node.right, state )
},
BinaryExpression: BinaryExpression = function( node, state ) {
const { output } = state
if ( node.operator === 'in' ) {
// Avoids confusion in `for` loops initializers
output.write( '(' )
formatBinaryExpressionPart( node.left, node, false, state, this )
output.write( ' ' + node.operator + ' ' )
formatBinaryExpressionPart( node.right, node, true, state, this )
output.write( ')' )
} else {
formatBinaryExpressionPart( node.left, node, false, state, this )
output.write( ' ' + node.operator + ' ' )
formatBinaryExpressionPart( node.right, node, true, state, this )
}
},
LogicalExpression: BinaryExpression,
ConditionalExpression( node, state ) {
const { output } = state
if ( EXPRESSIONS_PRECEDENCE[ node.test.type ] > EXPRESSIONS_PRECEDENCE.ConditionalExpression ) {
this[ node.test.type ]( node.test, state )
} else {
output.write( '(' )
this[ node.test.type ]( node.test, state )
output.write( ')' )
}
output.write( ' ? ' )
this[ node.consequent.type ]( node.consequent, state )
output.write( ' : ' )
this[ node.alternate.type ]( node.alternate, state )
},
NewExpression( node, state ) {
state.output.write( 'new ' )
const { output } = state
if ( EXPRESSIONS_PRECEDENCE[ node.callee.type ] < EXPRESSIONS_PRECEDENCE.CallExpression
|| hasCallExpression( node.callee ) ) {
output.write( '(' )
this[ node.callee.type ]( node.callee, state )
output.write( ')' )
} else {
this[ node.callee.type ]( node.callee, state )
}
formatSequence( node[ 'arguments' ], state, this )
},
CallExpression( node, state ) {
const { output } = state
if ( EXPRESSIONS_PRECEDENCE[ node.callee.type ] < EXPRESSIONS_PRECEDENCE.CallExpression ) {
output.write( '(' )
this[ node.callee.type ]( node.callee, state )
output.write( ')' )
} else {
this[ node.callee.type ]( node.callee, state )
}
formatSequence( node[ 'arguments' ], state, this )
},
MemberExpression( node, state ) {
const { output } = state
if ( EXPRESSIONS_PRECEDENCE[ node.object.type ] < EXPRESSIONS_PRECEDENCE.MemberExpression ) {
output.write( '(' )
this[ node.object.type ]( node.object, state )
output.write( ')' )
} else {
this[ node.object.type ]( node.object, state )
}
if ( node.computed ) {
output.write( '[' )
this[ node.property.type ]( node.property, state )
output.write( ']' )
} else {
output.write( '.' )
this[ node.property.type ]( node.property, state )
}
},
MetaProperty( node, state ) {
state.output.write( node.meta.name + '.' + node.property.name )
},
Identifier( node, state ) {
state.output.write( node.name )
},
Literal( node, state ) {
if ( node.raw != null ) {
state.output.write( node.raw )
} else if ( node.regex != null ) {
this.RegExpLiteral( node, state )
} else {
state.output.write( stringify( node.value ) )
}
},
RegExpLiteral( node, state ) {
const { regex } = node
state.output.write( 'new RegExp(' + stringify( regex.pattern ) + ', ' + stringify( regex.flags ) + ')' )
}
}
class Stream {
constructor() {
this.data = ''
}
write( string ) {
this.data += string
}
toString() {
return this.data
}
}
export default function astring( node, options ) {
/*
Returns a string representing the rendered code of the provided AST `node`.
The `options` are:
- `indent`: string to use for indentation (defaults to `\t`)
- `lineEnd`: string to use for line endings (defaults to `\n`)
- `startingIndentLevel`: indent level to start from (default to `0`)
- `comments`: generate comments if `true` (defaults to `false`)
- `output`: output stream to write the rendered code to (defaults to `null`)
- `generator`: custom code generator (defaults to `defaultGenerator`)
*/
const state = options == null ? {
output: new Stream(),
generator: defaultGenerator,
indent: '\t',
lineEnd: '\n',
indentLevel: 0,
writeComments: false,
noTrailingSemicolon: false
} : {
// Functional options
output: options.output ? options.output : new Stream(),
generator: options.generator ? options.generator : defaultGenerator,
// Formating options
indent: options.indent != null ? options.indent : '\t',
lineEnd: options.lineEnd != null ? options.lineEnd : '\n',
indentLevel: options.startingIndentLevel != null ? options.startingIndentLevel : 0,
writeComments: options.comments ? options.comments : false,
// Internal state
noTrailingSemicolon: false
}
// Travel through the AST node and generate the code
state.generator[ node.type ]( node, state )
const { output } = state
return output.data != null ? output.data : output
}
| src/astring.js | // Astring is a tiny and fast JavaScript code generator from an ESTree-compliant AST.
//
// Astring was written by David Bonnet and released under an MIT license.
//
// The Git repository for Astring is available at:
// https://github.com/davidbonnet/astring.git
//
// Please use the GitHub bug tracker to report issues:
// https://github.com/davidbonnet/astring/issues
const { stringify } = JSON;
const OPERATORS_PRECEDENCE = {
'||': 3,
'&&': 4,
'|': 5,
'^': 6,
'&': 7,
'==': 8,
'!=': 8,
'===': 8,
'!==': 8,
'<': 9,
'>': 9,
'<=': 9,
'>=': 9,
'in': 9,
'instanceof': 9,
'<<': 10,
'>>': 10,
'>>>': 10,
'+': 11,
'-': 11,
'*': 12,
'%': 12,
'/': 12,
'**': 12
}
const EXPRESSIONS_PRECEDENCE = {
// Definitions
ArrayExpression: 20,
TaggedTemplateExpression: 20,
ThisExpression: 20,
Identifier: 20,
Literal: 18,
TemplateLiteral: 20,
Super: 20,
SequenceExpression: 20,
// Operations
MemberExpression: 19,
CallExpression: 19,
NewExpression: 19,
ArrowFunctionExpression: 18,
// Other definitions
// Value 17 enables parenthesis in an `ExpressionStatement` node
ClassExpression: 17,
FunctionExpression: 17,
ObjectExpression: 17,
// Other operations
UpdateExpression: 16,
UnaryExpression: 15,
BinaryExpression: 14,
LogicalExpression: 13,
ConditionalExpression: 4,
AssignmentExpression: 3,
YieldExpression: 2,
RestElement: 1
}
function formatSequence( nodes, state, traveler ) {
/*
Formats a sequence of `nodes`.
*/
const { output } = state
output.write( '(' )
if ( nodes != null && nodes.length > 0 ) {
traveler[ nodes[ 0 ].type ]( nodes[ 0 ], state )
const { length } = nodes
for ( let i = 1; i < length; i++ ) {
let param = nodes[ i ]
output.write( ', ' )
traveler[ param.type ]( param, state )
}
}
output.write( ')' )
}
function formatBinaryExpressionPart( node, parentNode, isRightHand, state, traveler ) {
/*
Formats into the `output` stream a left-hand or right-hand expression `node` from a binary expression applying the provided `operator`.
The `isRightHand` parameter should be `true` if the `node` is a right-hand argument.
*/
const nodePrecedence = EXPRESSIONS_PRECEDENCE[ node.type ]
const parentNodePrecedence = EXPRESSIONS_PRECEDENCE[ parentNode.type ]
if ( nodePrecedence > parentNodePrecedence ) {
traveler[ node.type ]( node, state )
return
} else if ( nodePrecedence === parentNodePrecedence ) {
if ( nodePrecedence === 13 || nodePrecedence === 14 ) {
// Either `LogicalExpression` or `BinaryExpression`
if ( isRightHand ) {
if ( OPERATORS_PRECEDENCE[ node.operator ] > OPERATORS_PRECEDENCE[ parentNode.operator ] ) {
traveler[ node.type ]( node, state )
return
}
} else {
if ( OPERATORS_PRECEDENCE[ node.operator ] >= OPERATORS_PRECEDENCE[ parentNode.operator ] ) {
traveler[ node.type ]( node, state )
return
}
}
} else {
traveler[ node.type ]( node, state )
return
}
}
state.output.write( '(' )
traveler[ node.type ]( node, state )
state.output.write( ')' )
}
function reindent( text, indentation ) {
/*
Returns the `text` string reindented with the provided `indentation`.
*/
text = text.trimRight()
let indents = '\n'
let secondLine = false
const { length } = text
for ( let i = 0; i < length; i++ ) {
let char = text[ i ]
if ( secondLine ) {
if ( char === ' ' || char === '\t' ) {
indents += char
} else {
return indentation + text.trimLeft().split( indents ).join( '\n' + indentation )
}
} else {
if ( char === '\n' ) {
secondLine = true
}
}
}
return indentation + text.trimLeft()
}
function formatComments( comments, output, indent, lineEnd ) {
/*
Inserts into `output` the provided list of `comments`, with the given `indent` and `lineEnd` strings.
Line comments will end with `"\n"` regardless of the value of `lineEnd`.
Expects to start on a new unindented line.
*/
const { length } = comments
for ( let i = 0; i < length; i++ ) {
let comment = comments[ i ]
output.write( indent )
if ( comment.type[ 0 ] === 'L' )
// Line comment
output.write( '// ' + comment.value.trim() + '\n' )
else
// Block comment
output.write( '/*' + lineEnd + reindent( comment.value, indent ) + lineEnd + indent + '*/' + lineEnd )
}
}
function hasCallExpression( node ) {
/*
Returns `true` if the provided `node` contains a call expression and `false` otherwise.
*/
while ( node != null ) {
let { type } = node
if ( type[ 0 ] === 'C' && type[ 1 ] === 'a' ) {
// Is CallExpression
return true
} else if ( type[ 0 ] === 'M' && type[ 1 ] === 'e' && type[ 2 ] === 'm' ) {
// Is MemberExpression
node = node.object
} else {
return false
}
}
}
let ForInStatement, FunctionDeclaration, RestElement, BinaryExpression, ArrayExpression
export const defaultGenerator = {
Program( node, state ) {
const indent = state.indent.repeat( state.indentLevel )
const { lineEnd, output, writeComments } = state
if ( writeComments && node.comments != null )
formatComments( node.comments, output, indent, lineEnd )
let statements = node.body
const { length } = statements
for ( let i = 0; i < length; i++ ) {
let statement = statements[ i ]
if ( writeComments && statement.comments != null )
formatComments( statement.comments, output, indent, lineEnd )
output.write( indent )
this[ statement.type ]( statement, state )
output.write( lineEnd )
}
if ( writeComments && node.trailingComments != null )
formatComments( node.trailingComments, output, indent, lineEnd )
},
BlockStatement( node, state ) {
const indent = state.indent.repeat( state.indentLevel++ )
const { lineEnd, output, writeComments } = state
const statementIndent = indent + state.indent
output.write( '{' )
let statements = node.body
if ( statements != null && statements.length > 0 ) {
output.write( lineEnd )
if ( writeComments && node.comments != null ) {
formatComments( node.comments, output, statementIndent, lineEnd )
}
const { length } = statements
for ( let i = 0; i < length; i++ ) {
let statement = statements[ i ]
if ( writeComments && statement.comments != null )
formatComments( statement.comments, output, statementIndent, lineEnd )
output.write( statementIndent )
this[ statement.type ]( statement, state )
output.write( lineEnd )
}
output.write( indent )
} else {
if ( writeComments && node.comments != null ) {
output.write( lineEnd )
formatComments( node.comments, output, statementIndent, lineEnd )
output.write( indent )
}
}
if ( writeComments && node.trailingComments != null )
formatComments( node.trailingComments, output, statementIndent, lineEnd )
output.write( '}' )
state.indentLevel--
},
EmptyStatement( node, state ) {
state.output.write( ';' )
},
ExpressionStatement( node, state ) {
const precedence = EXPRESSIONS_PRECEDENCE[ node.expression.type ]
if ( precedence === 17 || ( precedence === 3 && node.expression.left.type[ 0 ] === 'O' ) ) {
// Should always have parentheses or is an AssignmentExpression to an ObjectPattern
state.output.write( '(' )
this[ node.expression.type ]( node.expression, state )
state.output.write( ')' )
} else {
this[ node.expression.type ]( node.expression, state )
}
state.output.write( ';' )
},
IfStatement( node, state ) {
const { output } = state
output.write( 'if (' )
this[ node.test.type ]( node.test, state )
output.write( ') ' )
this[ node.consequent.type ]( node.consequent, state )
if ( node.alternate != null ) {
output.write( ' else ' )
this[ node.alternate.type ]( node.alternate, state )
}
},
LabeledStatement( node, state ) {
this[ node.label.type ]( node.label, state )
state.output.write( ': ' )
this[ node.body.type ]( node.body, state )
},
BreakStatement( node, state ) {
const { output } = state
output.write( 'break' )
if ( node.label ) {
output.write( ' ' )
this[ node.label.type ]( node.label, state )
}
output.write( ';' )
},
ContinueStatement( node, state ) {
const { output } = state
output.write( 'continue' )
if ( node.label ) {
output.write( ' ' )
this[ node.label.type ]( node.label, state )
}
output.write( ';' )
},
WithStatement( node, state ) {
const { output } = state
output.write( 'with (' )
this[ node.object.type ]( node.object, state )
output.write( ') ' )
this[ node.body.type ]( node.body, state )
},
SwitchStatement( node, state ) {
const indent = state.indent.repeat( state.indentLevel++ )
const { lineEnd, output, writeComments } = state
state.indentLevel++
const caseIndent = indent + state.indent
const statementIndent = caseIndent + state.indent
output.write( 'switch (' )
this[ node.discriminant.type ]( node.discriminant, state )
output.write( ') \{' + lineEnd )
const { cases: occurences } = node
const { length: occurencesCount } = occurences
for ( let i = 0; i < occurencesCount; i++ ) {
let occurence = occurences[ i ]
if ( writeComments && occurence.comments != null )
formatComments( occurence.comments, output, caseIndent, lineEnd )
if ( occurence.test ) {
output.write( caseIndent + 'case ' )
this[ occurence.test.type ]( occurence.test, state )
output.write( ':' + lineEnd )
} else {
output.write( caseIndent + 'default:' + lineEnd )
}
let { consequent } = occurence
const { length: consequentCount } = consequent
for ( let i = 0; i < consequentCount; i++ ) {
let statement = consequent[ i ]
if ( writeComments && statement.comments != null )
formatComments( statement.comments, output, statementIndent, lineEnd )
output.write( statementIndent )
this[ statement.type ]( statement, state )
output.write( lineEnd )
}
}
state.indentLevel -= 2
output.write( indent + '}' )
},
ReturnStatement( node, state ) {
const { output } = state
output.write( 'return' )
if ( node.argument ) {
output.write( ' ' )
this[ node.argument.type ]( node.argument, state )
}
output.write( ';' )
},
ThrowStatement( node, state ) {
const { output } = state
output.write( 'throw ' )
this[ node.argument.type ]( node.argument, state )
output.write( ';' )
},
TryStatement( node, state ) {
const { output } = state
output.write( 'try ' )
this[ node.block.type ]( node.block, state )
if ( node.handler ) {
let { handler } = node
output.write( ' catch (' )
this[ handler.param.type ]( handler.param, state )
output.write( ') ' )
this[ handler.body.type ]( handler.body, state )
}
if ( node.finalizer ) {
output.write( ' finally ' )
this[ node.finalizer.type ]( node.finalizer, state )
}
},
WhileStatement( node, state ) {
const { output } = state
output.write( 'while (' )
this[ node.test.type ]( node.test, state )
output.write( ') ' )
this[ node.body.type ]( node.body, state )
},
DoWhileStatement( node, state ) {
const { output } = state
output.write( 'do ' )
this[ node.body.type ]( node.body, state )
output.write( ' while (' )
this[ node.test.type ]( node.test, state )
output.write( ');' )
},
ForStatement( node, state ) {
const { output } = state
output.write( 'for (' )
if ( node.init != null ) {
const { init } = node
state.noTrailingSemicolon = true
this[ node.init.type ]( node.init, state )
state.noTrailingSemicolon = false
}
output.write( '; ' )
if ( node.test )
this[ node.test.type ]( node.test, state )
output.write( '; ' )
if ( node.update )
this[ node.update.type ]( node.update, state )
output.write( ') ' )
this[ node.body.type ]( node.body, state )
},
ForInStatement: ForInStatement = function( node, state ) {
const { output } = state
output.write( 'for (' )
const { left } = node, { type } = left
state.noTrailingSemicolon = true
this[ type ]( left, state )
state.noTrailingSemicolon = false
// Identifying whether node.type is `ForInStatement` or `ForOfStatement`
output.write( node.type[ 3 ] === 'I' ? ' in ' : ' of ' )
this[ node.right.type ]( node.right, state )
output.write( ') ' )
this[ node.body.type ]( node.body, state )
},
ForOfStatement: ForInStatement,
DebuggerStatement( node, state ) {
state.output.write( 'debugger;' + state.lineEnd )
},
FunctionDeclaration: FunctionDeclaration = function( node, state ) {
const { output } = state
output.write( node.generator ? 'function* ' : 'function ' )
if ( node.id )
output.write( node.id.name )
formatSequence( node.params, state, this )
output.write( ' ' )
this[ node.body.type ]( node.body, state )
},
FunctionExpression: FunctionDeclaration,
VariableDeclaration( node, state ) {
const { output } = state
const { declarations } = node
output.write( node.kind + ' ' )
const { length } = declarations
if ( length > 0 ) {
this.VariableDeclarator( declarations[ 0 ], state )
for ( let i = 1; i < length; i++ ) {
output.write( ', ' )
this.VariableDeclarator( declarations[ i ], state )
}
}
if ( state.noTrailingSemicolon !== true )
output.write( ';' )
},
VariableDeclarator( node, state ) {
this[ node.id.type ]( node.id, state )
if ( node.init != null ) {
state.output.write( ' = ' )
this[ node.init.type ]( node.init, state )
}
},
ClassDeclaration( node, state ) {
const { output } = state
output.write( 'class ' )
if ( node.id ) {
output.write( node.id.name + ' ' )
}
if ( node.superClass ) {
output.write( 'extends ' )
this[ node.superClass.type ]( node.superClass, state )
output.write( ' ' )
}
this.BlockStatement( node.body, state )
},
ImportDeclaration( node, state ) {
const { output } = state
output.write( 'import ' )
const { specifiers } = node
const { length } = specifiers
if ( length > 0 ) {
let i = 0, specifier
while ( i < length ) {
if ( i > 0 )
output.write( ', ' )
specifier = specifiers[ i ]
const type = specifier.type[ 6 ]
if (type === 'D') {
// ImportDefaultSpecifier
output.write( specifier.local.name )
i++
} else if (type === 'N') {
// ImportNamespaceSpecifier
output.write( '* as ' + specifier.local.name )
i++
} else {
// ImportSpecifier
break
}
}
if ( i < length ) {
output.write( '{' )
for ( ; ; ) {
specifier = specifiers[ i ]
let { name } = specifier.imported
output.write( name )
if ( name !== specifier.local.name ) {
output.write( ' as ' + specifier.local.name )
}
if ( ++i < length )
output.write( ', ' )
else
break
}
output.write( '}' )
}
output.write( ' from ' )
}
this.Literal( node.source, state )
output.write( ';' )
},
ExportDefaultDeclaration( node, state ) {
const { output } = state
output.write( 'export default ' )
this[ node.declaration.type ]( node.declaration, state )
if ( EXPRESSIONS_PRECEDENCE[ node.declaration.type ] && node.declaration.type[ 0 ] !== 'F' )
// All expression nodes except `FunctionExpression`
output.write( ';' )
},
ExportNamedDeclaration( node, state ) {
const { output } = state
output.write( 'export ' )
if ( node.declaration ) {
this[ node.declaration.type ]( node.declaration, state )
} else {
output.write( '{' )
const { specifiers } = node, { length } = specifiers
if ( length > 0 ) {
for ( let i = 0; ; ) {
let specifier = specifiers[ i ]
let { name } = specifier.local
output.write( name )
if ( name !== specifier.exported.name )
output.write( ' as ' + specifier.exported.name )
if ( ++i < length )
output.write( ', ' )
else
break
}
}
output.write( '}' )
if ( node.source ) {
output.write( ' from ' )
this.Literal( node.source, state )
}
output.write( ';' )
}
},
ExportAllDeclaration( node, state ) {
const { output } = state
output.write( 'export * from ' )
this.Literal( node.source, state )
output.write( ';' )
},
MethodDefinition( node, state ) {
const { output } = state
if ( node.static )
output.write( 'static ' )
switch ( node.kind[ 0 ] ) {
case 'g': // `get`
case 's': // `set`
output.write( node.kind + ' ' )
break
default:
break
}
if ( node.value.generator )
output.write( '*' )
if ( node.computed ) {
output.write( '[' )
this[ node.key.type ]( node.key, state )
output.write( ']' )
} else {
this[ node.key.type ]( node.key, state )
}
formatSequence( node.value.params, state, this )
output.write( ' ' )
this[ node.value.body.type ]( node.value.body, state )
},
ClassExpression( node, state ) {
this.ClassDeclaration( node, state )
},
ArrowFunctionExpression( node, state ) {
const { output } = state
const { params } = node
if ( params != null ) {
if ( params.length === 1 && params[ 0 ].type[ 0 ] === 'I' ) {
// If params[0].type[0] starts with 'I', it can't be `ImportDeclaration` nor `IfStatement` and thus is `Identifier`
output.write( params[ 0 ].name )
} else {
formatSequence( node.params, state, this )
}
}
output.write( ' => ' )
if ( node.body.type[ 0 ] === 'O' ) {
output.write( '(' )
this.ObjectExpression( node.body, state )
output.write( ')' )
} else {
this[ node.body.type ]( node.body, state )
}
},
ThisExpression( node, state ) {
state.output.write( 'this' )
},
Super( node, state ) {
state.output.write( 'super' )
},
RestElement: RestElement = function( node, state ) {
state.output.write( '...' )
this[ node.argument.type ]( node.argument, state )
},
SpreadElement: RestElement,
YieldExpression( node, state ) {
const { output } = state
output.write( node.delegate ? 'yield*' : 'yield' )
if ( node.argument ) {
output.write( ' ' )
this[ node.argument.type ]( node.argument, state )
}
},
TemplateLiteral( node, state ) {
const { output } = state
const { quasis, expressions } = node
output.write( '`' )
const { length } = expressions
for ( let i = 0; i < length; i++ ) {
let expression = expressions[ i ]
output.write( quasis[ i ].value.raw )
output.write( '${' )
this[ expression.type ]( expression, state )
output.write( '}' )
}
output.write( quasis[ quasis.length - 1 ].value.raw )
output.write( '`' )
},
TaggedTemplateExpression( node, state ) {
this[ node.tag.type ]( node.tag, state )
this[ node.quasi.type ]( node.quasi, state )
},
ArrayExpression: ArrayExpression = function( node, state ) {
const { output } = state
output.write( '[' )
if ( node.elements.length > 0 ) {
const { elements } = node, { length } = elements
for ( let i = 0; ; ) {
let element = elements[ i ]
if ( element != null )
this[ element.type ]( element, state )
if ( ++i < length ) {
output.write( ', ' )
} else {
if ( element == null )
output.write( ', ' )
break
}
}
}
output.write( ']' )
},
ArrayPattern: ArrayExpression,
ObjectExpression( node, state ) {
const indent = state.indent.repeat( state.indentLevel++ )
const { lineEnd, output, writeComments } = state
const propertyIndent = indent + state.indent
output.write( '{' )
if ( node.properties.length > 0 ) {
output.write( lineEnd )
if ( writeComments && node.comments != null )
formatComments( node.comments, output, propertyIndent, lineEnd )
const comma = ',' + lineEnd, { properties } = node, { length } = properties
for ( let i = 0; ; ) {
let property = properties[ i ]
if ( writeComments && property.comments != null )
formatComments( property.comments, output, propertyIndent, lineEnd )
output.write( propertyIndent )
this.Property( property, state )
if ( ++i < length )
output.write( comma )
else
break
}
output.write( lineEnd )
if ( writeComments && node.trailingComments != null )
formatComments( node.trailingComments, output, propertyIndent, lineEnd )
output.write( indent + '}' )
} else if ( writeComments ) {
if ( node.comments != null ) {
output.write( lineEnd )
formatComments( node.comments, output, propertyIndent, lineEnd )
if ( node.trailingComments != null )
formatComments( node.trailingComments, output, propertyIndent, lineEnd )
output.write( indent + '}' )
} else if ( node.trailingComments != null ) {
output.write( lineEnd )
formatComments( node.trailingComments, output, propertyIndent, lineEnd )
output.write( indent + '}' )
} else {
output.write( '}' )
}
} else {
output.write( '}' )
}
state.indentLevel--
},
Property( node, state ) {
if ( node.method || node.kind[ 0 ] !== 'i' ) {
// Either a method or of kind `set` or `get` (not `init`)
this.MethodDefinition( node, state )
} else {
const { output } = state
if ( !node.shorthand ) {
if ( node.computed ) {
output.write( '[' )
this[ node.key.type ]( node.key, state )
output.write( ']' )
} else {
this[ node.key.type ]( node.key, state )
}
output.write( ': ' )
}
this[ node.value.type ]( node.value, state )
}
},
ObjectPattern( node, state ) {
const { output } = state
output.write( '{' )
if ( node.properties.length > 0 ) {
const { properties } = node, { length } = properties
for ( let i = 0; ; ) {
this.Property( properties[ i ], state )
if ( ++i < length )
output.write( ', ' )
else
break
}
}
output.write( '}' )
},
SequenceExpression( node, state ) {
formatSequence( node.expressions, state, this )
},
UnaryExpression( node, state ) {
const { output } = state
if ( node.prefix ) {
output.write( node.operator )
if ( node.operator.length > 1 )
state.output.write( ' ' )
if ( EXPRESSIONS_PRECEDENCE[ node.argument.type ] < EXPRESSIONS_PRECEDENCE.UnaryExpression ) {
output.write( '(' )
this[ node.argument.type ]( node.argument, state )
output.write( ')' )
} else {
this[ node.argument.type ]( node.argument, state )
}
} else {
// FIXME: This case never occurs
this[ node.argument.type ]( node.argument, state )
state.output.write( node.operator )
}
},
UpdateExpression( node, state ) {
// Always applied to identifiers or members, no parenthesis check needed
if ( node.prefix ) {
state.output.write( node.operator )
this[ node.argument.type ]( node.argument, state )
} else {
this[ node.argument.type ]( node.argument, state )
state.output.write( node.operator )
}
},
AssignmentExpression( node, state ) {
this[ node.left.type ]( node.left, state )
state.output.write( ' ' + node.operator + ' ' )
this[ node.right.type ]( node.right, state )
},
AssignmentPattern( node, state ) {
this[ node.left.type ]( node.left, state )
state.output.write( ' = ' )
this[ node.right.type ]( node.right, state )
},
BinaryExpression: BinaryExpression = function( node, state ) {
const { output } = state
if ( node.operator === 'in' ) {
// Avoids confusion in `for` loops initializers
output.write( '(' )
formatBinaryExpressionPart( node.left, node, false, state, this )
output.write( ' ' + node.operator + ' ' )
formatBinaryExpressionPart( node.right, node, true, state, this )
output.write( ')' )
} else {
formatBinaryExpressionPart( node.left, node, false, state, this )
output.write( ' ' + node.operator + ' ' )
formatBinaryExpressionPart( node.right, node, true, state, this )
}
},
LogicalExpression: BinaryExpression,
ConditionalExpression( node, state ) {
const { output } = state
if ( EXPRESSIONS_PRECEDENCE[ node.test.type ] > EXPRESSIONS_PRECEDENCE.ConditionalExpression ) {
this[ node.test.type ]( node.test, state )
} else {
output.write( '(' )
this[ node.test.type ]( node.test, state )
output.write( ')' )
}
output.write( ' ? ' )
this[ node.consequent.type ]( node.consequent, state )
output.write( ' : ' )
this[ node.alternate.type ]( node.alternate, state )
},
NewExpression( node, state ) {
state.output.write( 'new ' )
const { output } = state
if ( EXPRESSIONS_PRECEDENCE[ node.callee.type ] < EXPRESSIONS_PRECEDENCE.CallExpression
|| hasCallExpression( node.callee ) ) {
output.write( '(' )
this[ node.callee.type ]( node.callee, state )
output.write( ')' )
} else {
this[ node.callee.type ]( node.callee, state )
}
formatSequence( node[ 'arguments' ], state, this )
},
CallExpression( node, state ) {
const { output } = state
if ( EXPRESSIONS_PRECEDENCE[ node.callee.type ] < EXPRESSIONS_PRECEDENCE.CallExpression ) {
output.write( '(' )
this[ node.callee.type ]( node.callee, state )
output.write( ')' )
} else {
this[ node.callee.type ]( node.callee, state )
}
formatSequence( node[ 'arguments' ], state, this )
},
MemberExpression( node, state ) {
const { output } = state
if ( EXPRESSIONS_PRECEDENCE[ node.object.type ] < EXPRESSIONS_PRECEDENCE.MemberExpression ) {
output.write( '(' )
this[ node.object.type ]( node.object, state )
output.write( ')' )
} else {
this[ node.object.type ]( node.object, state )
}
if ( node.computed ) {
output.write( '[' )
this[ node.property.type ]( node.property, state )
output.write( ']' )
} else {
output.write( '.' )
this[ node.property.type ]( node.property, state )
}
},
MetaProperty( node, state ) {
state.output.write( node.meta.name + '.' + node.property.name )
},
Identifier( node, state ) {
state.output.write( node.name )
},
Literal( node, state ) {
if ( node.raw != null ) {
state.output.write( node.raw )
} else if ( node.regex != null ) {
this.RegExpLiteral( node, state )
} else {
state.output.write( stringify( node.value ) )
}
},
RegExpLiteral( node, state ) {
const { regex } = node
state.output.write( 'new RegExp(' + stringify( regex.pattern ) + ', ' + stringify( regex.flags ) + ')' )
}
}
class Stream {
constructor() {
this.data = ''
}
write( string ) {
this.data += string
}
toString() {
return this.data
}
}
export default function astring( node, options ) {
/*
Returns a string representing the rendered code of the provided AST `node`.
The `options` are:
- `indent`: string to use for indentation (defaults to `\t`)
- `lineEnd`: string to use for line endings (defaults to `\n`)
- `startingIndentLevel`: indent level to start from (default to `0`)
- `comments`: generate comments if `true` (defaults to `false`)
- `output`: output stream to write the rendered code to (defaults to `null`)
- `generator`: custom code generator (defaults to `defaultGenerator`)
*/
const state = options == null ? {
output: new Stream(),
generator: defaultGenerator,
indent: '\t',
lineEnd: '\n',
indentLevel: 0,
writeComments: false,
noTrailingSemicolon: false
} : {
// Functional options
output: options.output ? options.output : new Stream(),
generator: options.generator ? options.generator : defaultGenerator,
// Formating options
indent: options.indent != null ? options.indent : '\t',
lineEnd: options.lineEnd != null ? options.lineEnd : '\n',
indentLevel: options.startingIndentLevel != null ? options.startingIndentLevel : 0,
writeComments: options.comments ? options.comments : false,
// Internal state
noTrailingSemicolon: false
}
// Travel through the AST node and generate the code
state.generator[ node.type ]( node, state )
const { output } = state
return output.data != null ? output.data : output
}
| Add `ClassBody` as alias of `BlockStatement`
| src/astring.js | Add `ClassBody` as alias of `BlockStatement` | <ide><path>rc/astring.js
<ide> }
<ide>
<ide>
<del>let ForInStatement, FunctionDeclaration, RestElement, BinaryExpression, ArrayExpression
<add>let ForInStatement, FunctionDeclaration, RestElement, BinaryExpression, ArrayExpression, BlockStatement
<ide>
<ide>
<ide> export const defaultGenerator = {
<ide> if ( writeComments && node.trailingComments != null )
<ide> formatComments( node.trailingComments, output, indent, lineEnd )
<ide> },
<del> BlockStatement( node, state ) {
<add> BlockStatement: BlockStatement = function( node, state ) {
<ide> const indent = state.indent.repeat( state.indentLevel++ )
<ide> const { lineEnd, output, writeComments } = state
<ide> const statementIndent = indent + state.indent
<ide> output.write( '}' )
<ide> state.indentLevel--
<ide> },
<add> ClassBody: BlockStatement,
<ide> EmptyStatement( node, state ) {
<ide> state.output.write( ';' )
<ide> },
<ide> this[ node.superClass.type ]( node.superClass, state )
<ide> output.write( ' ' )
<ide> }
<del> this.BlockStatement( node.body, state )
<add> this[ node.body.type ]( node.body, state )
<ide> },
<ide> ImportDeclaration( node, state ) {
<ide> const { output } = state |
|
Java | mit | 7b53b66fab9539f4247b8c6fcdd167453c1b7aaa | 0 | Elusivehawk/HawkUtils |
package com.elusivehawk.util.math;
import com.elusivehawk.util.RNG;
import static com.elusivehawk.util.math.MathConst.*;
/**
*
* Convenience class for math functions.
*
* @author Elusivehawk
*/
public final class MathHelper
{
public static final float PI = 3.141592653589793238f;
private MathHelper(){}
public static boolean bounds(float f, float min, float max)
{
return f >= min && f <= max;
}
public static boolean bounds(int i, int min, int max)
{
return i >= min && i <= max;
}
public static boolean bounds(long l, long min, long max)
{
return l >= min && l <= max;
}
public static boolean bounds(Vector v, Vector min, Vector max)
{
int size = min(v.size(), min.size(), max.size());
for (int c = 0; c < size; c++)
{
if (!bounds(v.get(c), min.get(c), max.get(c)))
{
return false;
}
}
return true;
}
public static Vector calcNormal(Vector one, Vector two, Vector three)
{
return (Vector)cross(one.sub(two, false), one.sub(three, false)).normalize();
}
public static float clamp(float f, float min, float max)
{
return Math.min(max, Math.max(f, min));
}
public static int clamp(int i, int min, int max)
{
return Math.min(max, Math.max(i, min));
}
public static long clamp(long l, long min, long max)
{
return Math.min(max, Math.max(l, min));
}
public static Vector clamp(Vector v, Vector min, Vector max)
{
int size = min(v.size(), min.size(), max.size());
Vector ret = new Vector(size);
for (int c = 0; c < size; c++)
{
ret.set(c, clamp(v.get(c), min.get(c), max.get(c)), false);
}
return ret;
}
public static Vector cross(Vector one, Vector two)
{
assert one.size() <= 3 && two.size() <= 3;
float ax = one.get(X);
float ay = one.get(Y);
float az = one.get(Z);
float bx = two.get(X);
float by = two.get(Y);
float bz = two.get(Z);
return new Vector((ay * bz) - (az * by),
(az * bx) - (ax * bz),
(ax * by) - (ay * bx));
}
public static float dist(Vector from, Vector to)
{
return (float)Math.sqrt(distSquared(from, to));
}
public static float distSquared(Vector from, Vector to)
{
int size = Math.min(from.size(), to.size());
float ret = 0f;
for (int c = 0; c < size; c++)
{
ret += square(to.get(c) - from.get(c));
}
return ret;
}
public static float dot(Vector one, Vector two)
{
int size = Math.min(one.size(), two.size());
float ret = 0f;
for (int c = 0; c < size; c++)
{
ret += one.get(c) * two.get(c);
}
return ret;
}
public static float interpolate(float one, float two, float factor)
{
assert bounds(factor, 0.0f, 1.0f);
return ((two * factor) + ((1f - factor) * one));
}
public static Vector interpolate(Vector one, Vector two, float factor)
{
return interpolate(one, two, factor, new Vector(Math.min(one.size(), two.size())));
}
public static Vector interpolate(Vector one, Vector two, float factor, Vector dest)
{
for (int c = 0; c < dest.size(); c++)
{
dest.set(c, ((two.get(c) * factor) + ((1f - factor) * one.get(c))), false);
}
return dest;
}
public static boolean isOdd(int i)
{
return (i & 1) == 1;
}
public static float length(IMathArray<Float> m)
{
float ret = 0f;
for (int c = 0; c < m.size(); c++)
{
ret += square(m.get(c));
}
return ret;
}
public static int percent(int i, int max)
{
return (int)(((float)i / max) * 100);
}
public static float pow(float f, int pow)
{
float ret = f;
for (int c = 0; c < pow; c++)
{
ret *= f;
}
return ret;
}
public static int pow(int i, int pow)
{
int ret = i;
for (int c = 0; c < pow; c++)
{
ret *= i;
}
return ret;
}
public static boolean rollDice(float weight)
{
return weight > RNG.rng().nextFloat();
}
public static float square(float f)
{
return f * f;
}
public static int square(int i)
{
return i * i;
}
public static float toDegrees(float radian)
{
return (radian * 180) / PI;
}
public static float toRadians(float degree)
{
return (degree * PI) / 180;
}
public static Vector toRadians(Vector vec)
{
Vector ret = new Vector(vec);
for (int c = 0; c < ret.size(); c++)
{
ret.set(c, toRadians(ret.get(c)), false);
}
ret.onChanged();
return ret;
}
public static int max(int... is)
{
int ret = Integer.MIN_VALUE;
for (int i : is)
{
ret = Math.max(ret, i);
}
return ret;
}
public static int min(int... is)
{
int ret = Integer.MAX_VALUE;
for (int i : is)
{
ret = Math.min(ret, i);
}
return ret;
}
}
| src/com/elusivehawk/util/math/MathHelper.java |
package com.elusivehawk.util.math;
import com.elusivehawk.util.RNG;
import static com.elusivehawk.util.math.MathConst.*;
/**
*
* Convenience class for math functions.
*
* @author Elusivehawk
*/
public final class MathHelper
{
public static final float PI = 3.141592653589793238f;
private MathHelper(){}
public static boolean bounds(float f, float min, float max)
{
return f >= min && f <= max;
}
public static boolean bounds(int i, int min, int max)
{
return i >= min && i <= max;
}
public static boolean bounds(long l, long min, long max)
{
return l >= min && l <= max;
}
public static boolean bounds(Vector v, Vector min, Vector max)
{
int size = min(v.size(), min.size(), max.size());
for (int c = 0; c < size; c++)
{
if (!bounds(v.get(c), min.get(c), max.get(c)))
{
return false;
}
}
return true;
}
public static Vector calcNormal(Vector one, Vector two, Vector three)
{
return (Vector)cross(one.sub(two, false), one.sub(three, false)).normalize();
}
public static float clamp(float f, float min, float max)
{
return Math.min(max, Math.max(f, min));
}
public static int clamp(int i, int min, int max)
{
return Math.min(max, Math.max(i, min));
}
public static long clamp(long l, long min, long max)
{
return Math.min(max, Math.max(l, min));
}
public static Vector clamp(Vector v, Vector min, Vector max)
{
int size = min(v.size(), min.size(), max.size());
Vector ret = new Vector(size);
for (int c = 0; c < size; c++)
{
ret.set(c, clamp(v.get(c), min.get(c), max.get(c)), false);
}
return ret;
}
public static Vector cross(Vector one, Vector two)
{
assert one.size() <= 3 && two.size() <= 3;
float ax = one.get(X);
float ay = one.get(Y);
float az = one.get(Z);
float bx = two.get(X);
float by = two.get(Y);
float bz = two.get(Z);
return new Vector((ay * bz) - (az * by),
(az * bx) - (ax * bz),
(ax * by) - (ay * bx));
}
public static float dist(Vector from, Vector to)
{
return (float)Math.sqrt(distSquared(from, to));
}
public static float distSquared(Vector from, Vector to)
{
int size = Math.min(from.size(), to.size());
float ret = 0f;
for (int c = 0; c < size; c++)
{
ret += square(to.get(c) - from.get(c));
}
return ret;
}
public static float dot(Vector one, Vector two)
{
int size = Math.min(one.size(), two.size());
float ret = 0f;
for (int c = 0; c < size; c++)
{
ret += one.get(c) * two.get(c);
}
return ret;
}
public static float interpolate(float one, float two, float factor)
{
assert bounds(factor, 0.0f, 1.0f);
return ((two * factor) + ((1f - factor) * one));
}
public static Vector interpolate(Vector one, Vector two, float factor)
{
return interpolate(one, two, factor, new Vector(Math.min(one.size(), two.size())));
}
public static Vector interpolate(Vector one, Vector two, float factor, Vector dest)
{
for (int c = 0; c < dest.size(); c++)
{
dest.set(c, ((two.get(c) * factor) + ((1f - factor) * one.get(c))), false);
}
return dest;
}
public static boolean isOdd(int i)
{
return (i & 1) == 1;
}
public static float length(IMathArray<Float> m)
{
float ret = 0f;
for (int c = 0; c < m.size(); c++)
{
ret += square(m.get(c));
}
return ret;
}
public static int percent(int i, int max)
{
return (int)(((float)i / max) * 100);
}
public static boolean rollDice(float weight)
{
return weight > RNG.rng().nextFloat();
}
public static float square(float f)
{
return f * f;
}
public static int square(int i)
{
return i * i;
}
public static float toDegrees(float radian)
{
return (radian * 180) / PI;
}
public static float toRadians(float degree)
{
return (degree * PI) / 180;
}
public static Vector toRadians(Vector vec)
{
Vector ret = new Vector(vec);
for (int c = 0; c < ret.size(); c++)
{
ret.set(c, toRadians(ret.get(c)), false);
}
ret.onChanged();
return ret;
}
public static int max(int... is)
{
int ret = Integer.MIN_VALUE;
for (int i : is)
{
ret = Math.max(ret, i);
}
return ret;
}
public static int min(int... is)
{
int ret = Integer.MAX_VALUE;
for (int i : is)
{
ret = Math.min(ret, i);
}
return ret;
}
}
| Undid undocumented change in MathHelper; Turns out caret "^" in Java is a friggin' XOR.
| src/com/elusivehawk/util/math/MathHelper.java | Undid undocumented change in MathHelper; Turns out caret "^" in Java is a friggin' XOR. | <ide><path>rc/com/elusivehawk/util/math/MathHelper.java
<ide> return (int)(((float)i / max) * 100);
<ide> }
<ide>
<add> public static float pow(float f, int pow)
<add> {
<add> float ret = f;
<add>
<add> for (int c = 0; c < pow; c++)
<add> {
<add> ret *= f;
<add>
<add> }
<add>
<add> return ret;
<add> }
<add>
<add> public static int pow(int i, int pow)
<add> {
<add> int ret = i;
<add>
<add> for (int c = 0; c < pow; c++)
<add> {
<add> ret *= i;
<add>
<add> }
<add>
<add> return ret;
<add> }
<add>
<ide> public static boolean rollDice(float weight)
<ide> {
<ide> return weight > RNG.rng().nextFloat(); |
|
JavaScript | mit | 4bdfba3af699fbdc502f167795f806926dc2116e | 0 | solvers/solvers,solvers/solvers | describe('A user should be able to post a project when authenticated', function() {
var name = 'Killer Bees Mutagen';
var role = 'Expert DNA Programmer';
var description = 'This is a breeding program. We hope to code the DNA to create a mutagen strain that we will then inject into normal house bees, to produce incredible killer bees.';
var contact_name = 'Professor Eindhoven';
var contact_email = '[email protected]';
var tags = 'bees, dna, programming';
it('A user can post a project', function(done) {
// navigate to post project page
var home = $('#homeLink');
click(home[0]);
setTimeout(function() {
var button = $('#postProject');
button.click();
setTimeout(function() {
var description_input = $('#wmd-input');
assert('Description input is present', description_input.length === 1);
$('#name').val(name);
$('#role').val(role);
$('#wmd-input').val(description);
$('#contact_name').val(contact_name);
$('#contact_email').val(contact_email);
$('#tags').val(tags);
var addNewProjectBtn = $('#addNewProject');
click(addNewProjectBtn[0]);
setTimeout(function() {
assert('Project role is "Expert DNA Programmer"', $('#project_role').text() === role);
assert('Project name is "Killer Bees Mutagen"', $('#project_name').text() === name);
assert('Project description is correct', $('#project_description_p').text() === description + "\n");
assert('Project contact name is correct', $('#project_contact_name').text() === contact_name);
assert('Project contact email is correct', $('#project_contact_email').text() === contact_email);
done();
}, 100);
}, 10);
}, 10);
});
it('The latest posted project is on the home page', function(done) {
var home = $('#homeLink');
click(home[0]);
setTimeout(function() {
var firstProject = $('.showProject')[0];
assert('Posted project is the first project on the home page', $(firstProject).text() === name + ' - ' + role);
var userProfileLink = $('.projectOwner')[0];
assert('Correct name of user is in project profile link', $(userProfileLink).text() === 'testuser');
done();
}, 30);
});
});
| test/posting.spec.js | describe('A user should be able to post a project when authenticated', function() {
var name = 'Killer Bees Mutagen';
var role = 'Expert DNA Programmer';
var description = 'This is a breeding program. We hope to code the DNA to create a mutagen strain that we will then inject into normal house bees, to produce incredible killer bees.';
var contact_name = 'Professor Eindhoven';
var contact_email = '[email protected]';
var tags = 'bees, dna, programming';
it('A user can post a project', function(done) {
// navigate to post project page
var home = $('#homeLink');
click(home[0]);
setTimeout(function() {
var button = $('#postProject');
button.click();
setTimeout(function() {
var description_input = $('#wmd-input');
assert('Description input is present', description_input.length === 1);
$('#name').val(name);
$('#role').val(role);
$('#wmd-input').val(description);
$('#contact_name').val(contact_name);
$('#contact_email').val(contact_email);
$('#tags').val(tags);
var addNewProjectBtn = $('#addNewProject');
click(addNewProjectBtn[0]);
setTimeout(function() {
assert('Project role is "Expert DNA Programmer"', $('#project_role').text() === role);
assert('Project name is "Killer Bees Mutagen"', $('#project_name').text() === name);
assert('Project description is correct', $('#project_description_p').text() === description + "\n");
assert('Project contact name is correct', $('#project_contact_name').text() === contact_name);
assert('Project contact email is correct', $('#project_contact_email').text() === contact_email);
done();
}, 100);
}, 10);
}, 10);
});
it('The latest posted project is on the home page', function(done) {
var home = $('#homeLink');
click(home[0]);
setTimeout(function() {
var firstProject = $('.showProject')[0];
assert('Posted project is the first project on the home page', $(firstProject).text() === name + ' - ' + role);
var userProfileLink = $('.projectOwner')[0];
assert('Correct name of user is in project profile link', $(userProfileLink).text() === 'testuser');
done();
}, 30);
});
});
| indentation
| test/posting.spec.js | indentation | <ide><path>est/posting.spec.js
<del> describe('A user should be able to post a project when authenticated', function() {
<add>describe('A user should be able to post a project when authenticated', function() {
<ide>
<ide> var name = 'Killer Bees Mutagen';
<ide> var role = 'Expert DNA Programmer'; |
|
Java | apache-2.0 | 5b590ddec671feab17b293d56d2e6c14d532886a | 0 | bowenli86/flink,tillrohrmann/flink,aljoscha/flink,zjureel/flink,zjureel/flink,sunjincheng121/flink,lincoln-lil/flink,tony810430/flink,xccui/flink,tillrohrmann/flink,kl0u/flink,godfreyhe/flink,apache/flink,sunjincheng121/flink,kl0u/flink,twalthr/flink,tony810430/flink,GJL/flink,aljoscha/flink,darionyaphet/flink,StephanEwen/incubator-flink,zjureel/flink,jinglining/flink,kaibozhou/flink,lincoln-lil/flink,jinglining/flink,greghogan/flink,aljoscha/flink,wwjiang007/flink,sunjincheng121/flink,kaibozhou/flink,clarkyzl/flink,kaibozhou/flink,darionyaphet/flink,darionyaphet/flink,kl0u/flink,gyfora/flink,zentol/flink,lincoln-lil/flink,hequn8128/flink,lincoln-lil/flink,apache/flink,twalthr/flink,gyfora/flink,jinglining/flink,wwjiang007/flink,zentol/flink,gyfora/flink,godfreyhe/flink,GJL/flink,zentol/flink,gyfora/flink,jinglining/flink,rmetzger/flink,wwjiang007/flink,tzulitai/flink,xccui/flink,hequn8128/flink,zjureel/flink,xccui/flink,godfreyhe/flink,zjureel/flink,twalthr/flink,StephanEwen/incubator-flink,godfreyhe/flink,sunjincheng121/flink,greghogan/flink,mbode/flink,jinglining/flink,gyfora/flink,godfreyhe/flink,bowenli86/flink,xccui/flink,wwjiang007/flink,tony810430/flink,zjureel/flink,tzulitai/flink,rmetzger/flink,zentol/flink,tony810430/flink,tillrohrmann/flink,mbode/flink,greghogan/flink,hequn8128/flink,lincoln-lil/flink,jinglining/flink,clarkyzl/flink,xccui/flink,StephanEwen/incubator-flink,godfreyhe/flink,hequn8128/flink,tillrohrmann/flink,lincoln-lil/flink,bowenli86/flink,StephanEwen/incubator-flink,StephanEwen/incubator-flink,mbode/flink,apache/flink,lincoln-lil/flink,tony810430/flink,rmetzger/flink,twalthr/flink,greghogan/flink,gyfora/flink,bowenli86/flink,bowenli86/flink,zentol/flink,GJL/flink,tony810430/flink,wwjiang007/flink,bowenli86/flink,rmetzger/flink,aljoscha/flink,aljoscha/flink,wwjiang007/flink,darionyaphet/flink,tillrohrmann/flink,zjureel/flink,kaibozhou/flink,tony810430/flink,GJL/flink,rmetzger/flink,hequn8128/flink,gyfora/flink,darionyaphet/flink,kl0u/flink,greghogan/flink,mbode/flink,tzulitai/flink,clarkyzl/flink,sunjincheng121/flink,zentol/flink,aljoscha/flink,apache/flink,twalthr/flink,apache/flink,kaibozhou/flink,StephanEwen/incubator-flink,twalthr/flink,wwjiang007/flink,GJL/flink,tillrohrmann/flink,kaibozhou/flink,clarkyzl/flink,twalthr/flink,GJL/flink,zentol/flink,godfreyhe/flink,rmetzger/flink,clarkyzl/flink,hequn8128/flink,mbode/flink,rmetzger/flink,tillrohrmann/flink,tzulitai/flink,kl0u/flink,xccui/flink,sunjincheng121/flink,kl0u/flink,apache/flink,tzulitai/flink,greghogan/flink,apache/flink,tzulitai/flink,xccui/flink | /*
* 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.flink.test.misc;
import org.apache.flink.api.common.JobExecutionResult;
import org.apache.flink.api.common.accumulators.LongCounter;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.io.DiscardingOutputFormat;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.core.fs.FileSystem;
import org.apache.flink.runtime.client.JobExecutionException;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.test.util.MiniClusterWithClientResource;
import org.apache.flink.util.Collector;
import org.apache.flink.util.TestLogger;
import org.junit.ClassRule;
import org.junit.Test;
import static org.apache.flink.util.ExceptionUtils.findThrowable;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Tests for the system behavior in multiple corner cases
* - when null records are passed through the system.
* - when disjoint dataflows are executed
* - when accumulators are used chained after a non-udf operator.
*
* <p>The tests are bundled into one class to reuse the same test cluster. This speeds
* up test execution, as the majority of the test time goes usually into starting/stopping the
* test cluster.
*/
@SuppressWarnings("serial")
public class MiscellaneousIssuesITCase extends TestLogger {
@ClassRule
public static final MiniClusterWithClientResource MINI_CLUSTER_RESOURCE = new MiniClusterWithClientResource(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(2)
.setNumberSlotsPerTaskManager(3)
.build());
@Test
public void testNullValues() {
try {
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(1);
DataSet<String> data = env.fromElements("hallo")
.map(new MapFunction<String, String>() {
@Override
public String map(String value) throws Exception {
return null;
}
});
data.writeAsText("/tmp/myTest", FileSystem.WriteMode.OVERWRITE);
try {
env.execute();
fail("this should fail due to null values.");
}
catch (JobExecutionException e) {
assertTrue(findThrowable(e, NullPointerException.class).isPresent());
}
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void testDisjointDataflows() {
try {
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(5);
// generate two different flows
env.generateSequence(1, 10).output(new DiscardingOutputFormat<Long>());
env.generateSequence(1, 10).output(new DiscardingOutputFormat<Long>());
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void testAccumulatorsAfterNoOp() {
final String accName = "test_accumulator";
try {
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(6);
env.generateSequence(1, 1000000)
.rebalance()
.flatMap(new RichFlatMapFunction<Long, Long>() {
private LongCounter counter;
@Override
public void open(Configuration parameters) {
counter = getRuntimeContext().getLongCounter(accName);
}
@Override
public void flatMap(Long value, Collector<Long> out) {
counter.add(1L);
}
})
.output(new DiscardingOutputFormat<Long>());
JobExecutionResult result = env.execute();
assertEquals(1000000L, result.getAllAccumulatorResults().get(accName));
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
}
| flink-tests/src/test/java/org/apache/flink/test/misc/MiscellaneousIssuesITCase.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.flink.test.misc;
import org.apache.flink.api.common.JobExecutionResult;
import org.apache.flink.api.common.accumulators.LongCounter;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.io.DiscardingOutputFormat;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.core.fs.FileSystem;
import org.apache.flink.runtime.client.JobExecutionException;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.test.util.MiniClusterWithClientResource;
import org.apache.flink.util.Collector;
import org.apache.flink.util.TestLogger;
import org.junit.ClassRule;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Tests for the system behavior in multiple corner cases
* - when null records are passed through the system.
* - when disjoint dataflows are executed
* - when accumulators are used chained after a non-udf operator.
*
* <p>The tests are bundled into one class to reuse the same test cluster. This speeds
* up test execution, as the majority of the test time goes usually into starting/stopping the
* test cluster.
*/
@SuppressWarnings("serial")
public class MiscellaneousIssuesITCase extends TestLogger {
@ClassRule
public static final MiniClusterWithClientResource MINI_CLUSTER_RESOURCE = new MiniClusterWithClientResource(
new MiniClusterResourceConfiguration.Builder()
.setNumberTaskManagers(2)
.setNumberSlotsPerTaskManager(3)
.build());
@Test
public void testNullValues() {
try {
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(1);
DataSet<String> data = env.fromElements("hallo")
.map(new MapFunction<String, String>() {
@Override
public String map(String value) throws Exception {
return null;
}
});
data.writeAsText("/tmp/myTest", FileSystem.WriteMode.OVERWRITE);
try {
env.execute();
fail("this should fail due to null values.");
}
catch (JobExecutionException e) {
assertNotNull(e.getCause());
assertTrue(e.getCause() instanceof NullPointerException);
}
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void testDisjointDataflows() {
try {
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(5);
// generate two different flows
env.generateSequence(1, 10).output(new DiscardingOutputFormat<Long>());
env.generateSequence(1, 10).output(new DiscardingOutputFormat<Long>());
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void testAccumulatorsAfterNoOp() {
final String accName = "test_accumulator";
try {
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(6);
env.generateSequence(1, 1000000)
.rebalance()
.flatMap(new RichFlatMapFunction<Long, Long>() {
private LongCounter counter;
@Override
public void open(Configuration parameters) {
counter = getRuntimeContext().getLongCounter(accName);
}
@Override
public void flatMap(Long value, Collector<Long> out) {
counter.add(1L);
}
})
.output(new DiscardingOutputFormat<Long>());
JobExecutionResult result = env.execute();
assertEquals(1000000L, result.getAllAccumulatorResults().get(accName));
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
}
| [FLINK-14366][tests] Enable MiscellaneousIssuesITCase to pass with NG scheduler
| flink-tests/src/test/java/org/apache/flink/test/misc/MiscellaneousIssuesITCase.java | [FLINK-14366][tests] Enable MiscellaneousIssuesITCase to pass with NG scheduler | <ide><path>link-tests/src/test/java/org/apache/flink/test/misc/MiscellaneousIssuesITCase.java
<ide> import org.junit.ClassRule;
<ide> import org.junit.Test;
<ide>
<add>import static org.apache.flink.util.ExceptionUtils.findThrowable;
<ide> import static org.junit.Assert.assertEquals;
<del>import static org.junit.Assert.assertNotNull;
<ide> import static org.junit.Assert.assertTrue;
<ide> import static org.junit.Assert.fail;
<ide>
<ide> fail("this should fail due to null values.");
<ide> }
<ide> catch (JobExecutionException e) {
<del> assertNotNull(e.getCause());
<del> assertTrue(e.getCause() instanceof NullPointerException);
<add> assertTrue(findThrowable(e, NullPointerException.class).isPresent());
<ide> }
<ide> }
<ide> catch (Exception e) { |
|
Java | bsd-2-clause | 94348216832f77c07684c98ae2699fd3c4d62386 | 0 | elsteveogrande/lbd | /*
* (C) 2012 Steve O'Brien. BSD licensed.
* see http://www.opensource.org/licenses/BSD-2-Clause
* and see LICENSE in the root of this project.
*/
package cc.obrien.lbd;
import gnu.getopt.Getopt;
import java.io.*;
import java.net.*;
import java.util.LinkedList;
import cc.obrien.lbd.layer.*;
import cc.obrien.lbd.manager.Manager;
import cc.obrien.lbd.manager.Request;
import cc.obrien.lbd.server.*;
/**
* Command-line utility to build a {@link Device} and start a {@link Server} daemon.
* Currently the virtual device parameters, such as size and layers, are just hardcoded in {@link #main(String...)}.
* Should use a config file or some sort of getopt convention so all parameters come from the command line (my preference)
* @author sobrien
*/
@SuppressWarnings("all")
public final class LBD
{
/** all instantiated devices that are running; used by {@link Request.Type#SHUTDOWN} */
public static final LinkedList<Device> runningDevices = new LinkedList<Device> ();
@SuppressWarnings("javadoc")
private static final class LayerArg
{
public static enum Type { EXPANDABLE_FILE, FLAT_FILE, NBD };
public final Type type;
public final boolean writable;
public final boolean cacheEnabled;
public final String spec;
public LayerArg(Type type, boolean writable, boolean cacheEnabled, String spec) {
this.type = type;
this.writable = writable;
this.cacheEnabled = cacheEnabled;
this.spec = spec;
}
}
/**
* @param args pased into {@link Getopt}; see {@link #shortOptions}
* @throws Exception any exception that can occur is thrown: I/O, etc.
*/
public static void main(String... args) throws Exception
{
System.err.printf("LBD version %d.%d.%d\n", Version.MAJOR, Version.MINOR, Version.PATCH);
Long deviceBlockCount = null;
InetSocketAddress serverBindOn = new InetSocketAddress(NBDServer.DEFAULT_PORT);
InetSocketAddress managerBindOn = new InetSocketAddress(InetAddress.getByName("localhost"), Manager.DEFAULT_PORT);
LinkedList<LayerArg> layerArgs = new LinkedList<LayerArg> ();
String parts[];
InetAddress bindAddress;
Integer bindPort;
Getopt getOpt = new Getopt("LBD", args, "hb:s:l:a:e:E:f:F:n:N:X:");
int opt;
while((opt = getOpt.getopt()) != -1)
{
switch(opt)
{
case 'b':
deviceBlockCount = Long.parseLong(getOpt.getOptarg());
break;
case 's':
Character suffix = null;
String arg = getOpt.getOptarg().toLowerCase();
if(! arg.matches("^[0-9]+[kmgt]?$"))
throw new IllegalArgumentException("bad format for -s");
suffix = arg.charAt(arg.length() - 1);
long numPart;
long multiplier = 1L;
if(Character.isLetter(suffix))
{
switch(suffix)
{
case 'k':
multiplier = 1L<<10;
break;
case 'm':
multiplier = 1L<<20;
break;
case 'g':
multiplier = 1L<<30;
break;
case 't':
multiplier = 1L<<40;
break;
default:
// doesn't reach here
break;
}
numPart = Long.parseLong(arg.substring(0, arg.length()-1));
}
else
{
numPart = Long.parseLong(arg);
}
long byteCount = numPart * multiplier;
if(byteCount % 512 != 0)
throw new IllegalArgumentException("device size must be a multiple of 512");
deviceBlockCount = byteCount >> 9;
break;
case 'l':
parts = getOpt.getOptarg().split(":");
bindAddress = null;
bindPort = null;
if(parts.length == 1)
{
bindPort = Integer.parseInt(parts[0]);
serverBindOn = new InetSocketAddress(bindPort);
}
else if(parts.length == 2)
{
bindAddress = InetAddress.getByName(parts[0]);
bindPort = Integer.parseInt(parts[1]);
serverBindOn = new InetSocketAddress(bindAddress, bindPort);
}
else
{
throw new IllegalArgumentException("bad format for -l");
}
break;
case 'a':
parts = getOpt.getOptarg().split(":");
bindAddress = null;
bindPort = null;
if(parts.length == 1)
{
bindPort = Integer.parseInt(parts[0]);
managerBindOn = new InetSocketAddress(bindPort);
}
else if(parts.length == 2)
{
bindAddress = InetAddress.getByName(parts[0]);
bindPort = Integer.parseInt(parts[1]);
managerBindOn = new InetSocketAddress(bindAddress, bindPort);
}
else
{
throw new IllegalArgumentException("bad format for -a");
}
break;
case 'e':
layerArgs.add(new LayerArg(LayerArg.Type.EXPANDABLE_FILE, false, true, getOpt.getOptarg()));
break;
case 'E':
layerArgs.add(new LayerArg(LayerArg.Type.EXPANDABLE_FILE, true, false,getOpt.getOptarg()));
break;
case 'f':
layerArgs.add(new LayerArg(LayerArg.Type.FLAT_FILE, false, false, getOpt.getOptarg()));
break;
case 'F':
layerArgs.add(new LayerArg(LayerArg.Type.FLAT_FILE, true, false, getOpt.getOptarg()));
break;
case 'n':
layerArgs.add(new LayerArg(LayerArg.Type.NBD, false, true, getOpt.getOptarg()));
break;
case 'N':
layerArgs.add(new LayerArg(LayerArg.Type.NBD, true, false, getOpt.getOptarg()));
break;
case 'X':
layerArgs.add(new LayerArg(LayerArg.Type.NBD, true, true, getOpt.getOptarg()));
break;
case '?':
case 'h':
System.err.println();
System.err.println("general options:");
System.err.println(" -h this help");
System.err.println(" -b blockcount (-b or -s required) the size of the virtual device,");
System.err.println(" in blocks (1 block = 512 bytes)");
System.err.println(" -s bytecount (-b or -s required) the size of the virtual device,");
System.err.println(" in bytes; can use suffix like K, M, G, T");
System.err.println();
System.err.println("server options:");
System.err.println(" -l [ip:]port the TCP ip/port to listen on for NBD clients");
System.err.println(" (optional; default is 0.0.0.0:" + NBDServer.DEFAULT_PORT + ")");
System.err.println(" -a [ip:]port the TCP ip/port to listen on for manager commands");
System.err.println(" (optional; default is localhost:" + Manager.DEFAULT_PORT + ")");
System.err.println();
System.err.println("to specify layers: (at least one is required)");
System.err.println(" -e filename readonly expandable file");
System.err.println(" -E filename writable expandable file");
System.err.println(" -f filename readonly flat file (file size must == device size)");
System.err.println(" -F filename writable flat file (file size must == device size)");
System.err.println(" -n ip:port readonly remote NBD device (read cache enabled)");
System.err.println(" -N ip:port writable remote NBD host (caching disabled)");
System.err.println(" -X ip:port writable remote NBD host w/ assumed exclusive access");
System.err.println(" (since exclusive access assumed, cache is enabled)");
System.err.println();
return;
}
}
if(layerArgs.size() == 0)
throw new RuntimeException("no layers specified; see -h for help");
if(deviceBlockCount == null)
throw new RuntimeException("no device size specified; see -h for help");
// writable layer check: only the topmost layer may be writable
for(LayerArg arg : layerArgs)
{
// top can be writable or read-only, either is ok
if(arg == layerArgs.getLast())
continue;
// but layers underneath should not be writable
if(arg.writable)
throw new IllegalArgumentException("only topmost layer may be writable");
}
// the device
Device device = new Device(deviceBlockCount);
// NBD server daemon
ServerSocket serverSocket = new ServerSocket();
serverSocket.bind(serverBindOn);
Server server = new NBDServer(device, serverSocket);
device.setServer(server);
// management server daemon
ServerSocket managerSocket = new ServerSocket();
managerSocket.bind(managerBindOn);
Manager manager = new Manager(device, managerSocket);
device.setManager(manager);
for(LayerArg arg : layerArgs)
{
Layer layer;
switch(arg.type)
{
case FLAT_FILE:
layer = new FlatFile(new File(arg.spec), device, arg.writable, arg.cacheEnabled);
break;
case EXPANDABLE_FILE:
layer = new ExpandableFile(new File(arg.spec), device, arg.writable, arg.cacheEnabled);
break;
case NBD:
parts = arg.spec.split(":");
if(parts.length != 2)
throw new IllegalArgumentException("for NBD layer, format is hostnameorIP:portnumber");
InetAddress host = InetAddress.getByName(parts[0]);
int port = Integer.parseInt(parts[1]);
layer = new NBD(device, arg.writable, arg.cacheEnabled, host, port, null); // no path support yet
break;
default:
throw new RuntimeException(String.format("sorry, can't handle %s yet", arg.type));
}
device.addLayer(layer);
}
// device complete
// start up services
server.start();
manager.start();
// dump info to stdout
device.dumpInfo();
// run until NBD server termination
server.join();
}
}
| src/cc/obrien/lbd/LBD.java | /*
* (C) 2012 Steve O'Brien. BSD licensed.
* see http://www.opensource.org/licenses/BSD-2-Clause
* and see LICENSE in the root of this project.
*/
package cc.obrien.lbd;
import gnu.getopt.Getopt;
import java.io.*;
import java.net.*;
import java.util.LinkedList;
import cc.obrien.lbd.layer.*;
import cc.obrien.lbd.manager.Manager;
import cc.obrien.lbd.manager.Request;
import cc.obrien.lbd.server.*;
/**
* Command-line utility to build a {@link Device} and start a {@link Server} daemon.
* Currently the virtual device parameters, such as size and layers, are just hardcoded in {@link #main(String...)}.
* Should use a config file or some sort of getopt convention so all parameters come from the command line (my preference)
* @author sobrien
*/
@SuppressWarnings("all")
public final class LBD
{
/** all instantiated devices that are running; used by {@link Request.Type#SHUTDOWN} */
public static final LinkedList<Device> runningDevices = new LinkedList<Device> ();
@SuppressWarnings("javadoc")
private static final class LayerArg
{
public static enum Type { EXPANDABLE_FILE, FLAT_FILE, NBD };
public final Type type;
public final boolean writable;
public final boolean cacheEnabled;
public final String spec;
public LayerArg(Type type, boolean writable, boolean cacheEnabled, String spec) {
this.type = type;
this.writable = writable;
this.cacheEnabled = cacheEnabled;
this.spec = spec;
}
}
/**
* @param args pased into {@link Getopt}; see {@link #shortOptions}
* @throws Exception any exception that can occur is thrown: I/O, etc.
*/
public static void main(String... args) throws Exception
{
System.err.printf("LBD version %d.%d.%d\n", Version.MAJOR, Version.MINOR, Version.PATCH);
Long deviceBlockCount = null;
InetSocketAddress serverBindOn = new InetSocketAddress(NBDServer.DEFAULT_PORT);
InetSocketAddress managerBindOn = new InetSocketAddress(InetAddress.getByName("localhost"), Manager.DEFAULT_PORT);
LinkedList<LayerArg> layerArgs = new LinkedList<LayerArg> ();
String parts[];
InetAddress bindAddress;
Integer bindPort;
Getopt getOpt = new Getopt("LBD", args, "hb:s:l:a:e:E:f:F:n:N:X:");
int opt;
while((opt = getOpt.getopt()) != -1)
{
switch(opt)
{
case 'b':
deviceBlockCount = Long.parseLong(getOpt.getOptarg());
break;
case 's':
Character suffix = null;
String arg = getOpt.getOptarg().toLowerCase();
if(! arg.matches("^[0-9]+[kmgt]?$"))
throw new IllegalArgumentException("bad format for -s");
suffix = arg.charAt(arg.length() - 1);
long numPart;
long multiplier = 1L;
if(Character.isLetter(suffix))
{
switch(suffix)
{
case 'k':
multiplier = 1L<<10;
break;
case 'm':
multiplier = 1L<<20;
break;
case 'g':
multiplier = 1L<<30;
break;
case 't':
multiplier = 1L<<40;
break;
default:
// doesn't reach here
break;
}
numPart = Long.parseLong(arg.substring(0, arg.length()-1));
}
else
{
numPart = Long.parseLong(arg);
}
long byteCount = numPart * multiplier;
if(byteCount % 512 != 0)
throw new IllegalArgumentException("device size must be a multiple of 512");
deviceBlockCount = byteCount >> 9;
break;
case 'l':
parts = getOpt.getOptarg().split(":");
bindAddress = null;
bindPort = null;
if(parts.length == 1)
{
bindPort = Integer.parseInt(parts[0]);
serverBindOn = new InetSocketAddress(bindPort);
}
else if(parts.length == 2)
{
bindAddress = InetAddress.getByName(parts[0]);
bindPort = Integer.parseInt(parts[1]);
serverBindOn = new InetSocketAddress(bindAddress, bindPort);
}
else
{
throw new IllegalArgumentException("bad format for -l");
}
break;
case 'a':
parts = getOpt.getOptarg().split(":");
bindAddress = null;
bindPort = null;
if(parts.length == 1)
{
bindPort = Integer.parseInt(parts[0]);
managerBindOn = new InetSocketAddress(bindPort);
}
else if(parts.length == 2)
{
bindAddress = InetAddress.getByName(parts[0]);
bindPort = Integer.parseInt(parts[1]);
managerBindOn = new InetSocketAddress(bindAddress, bindPort);
}
else
{
throw new IllegalArgumentException("bad format for -a");
}
break;
case 'e':
layerArgs.add(0, new LayerArg(LayerArg.Type.EXPANDABLE_FILE, false, true, getOpt.getOptarg()));
break;
case 'E':
layerArgs.add(0, new LayerArg(LayerArg.Type.EXPANDABLE_FILE, true, false,getOpt.getOptarg()));
break;
case 'f':
layerArgs.add(0, new LayerArg(LayerArg.Type.FLAT_FILE, false, false, getOpt.getOptarg()));
break;
case 'F':
layerArgs.add(0, new LayerArg(LayerArg.Type.FLAT_FILE, true, false, getOpt.getOptarg()));
break;
case 'n':
layerArgs.add(0, new LayerArg(LayerArg.Type.NBD, false, true, getOpt.getOptarg()));
break;
case 'N':
layerArgs.add(0, new LayerArg(LayerArg.Type.NBD, true, false, getOpt.getOptarg()));
break;
case 'X':
layerArgs.add(0, new LayerArg(LayerArg.Type.NBD, true, true, getOpt.getOptarg()));
break;
case '?':
case 'h':
System.err.println();
System.err.println("general options:");
System.err.println(" -h this help");
System.err.println(" -b blockcount (-b or -s required) the size of the virtual device,");
System.err.println(" in blocks (1 block = 512 bytes)");
System.err.println(" -s bytecount (-b or -s required) the size of the virtual device,");
System.err.println(" in bytes; can use suffix like K, M, G, T");
System.err.println();
System.err.println("server options:");
System.err.println(" -l [ip:]port the TCP ip/port to listen on for NBD clients");
System.err.println(" (optional; default is 0.0.0.0:" + NBDServer.DEFAULT_PORT + ")");
System.err.println(" -a [ip:]port the TCP ip/port to listen on for manager commands");
System.err.println(" (optional; default is localhost:" + Manager.DEFAULT_PORT + ")");
System.err.println();
System.err.println("to specify layers: (at least one is required)");
System.err.println(" -e filename readonly expandable file");
System.err.println(" -E filename writable expandable file");
System.err.println(" -f filename readonly flat file (file size must == device size)");
System.err.println(" -F filename writable flat file (file size must == device size)");
System.err.println(" -n ip:port readonly remote NBD device (read cache enabled)");
System.err.println(" -N ip:port writable remote NBD host (caching disabled)");
System.err.println(" -X ip:port writable remote NBD host w/ assumed exclusive access");
System.err.println(" (since exclusive access assumed, cache is enabled)");
System.err.println();
return;
}
}
if(layerArgs.size() == 0)
throw new RuntimeException("no layers specified; see -h for help");
if(deviceBlockCount == null)
throw new RuntimeException("no device size specified; see -h for help");
// writable layer check: only the topmost layer may be writable
for(LayerArg arg : layerArgs)
{
// top can be writable or read-only, either is ok
if(arg == layerArgs.getFirst())
continue;
// but layers underneath should not be writable
if(arg.writable)
throw new IllegalArgumentException("only topmost layer may be writable");
}
// the device
Device device = new Device(deviceBlockCount);
// NBD server daemon
ServerSocket serverSocket = new ServerSocket();
serverSocket.bind(serverBindOn);
Server server = new NBDServer(device, serverSocket);
device.setServer(server);
// management server daemon
ServerSocket managerSocket = new ServerSocket();
managerSocket.bind(managerBindOn);
Manager manager = new Manager(device, managerSocket);
device.setManager(manager);
for(LayerArg arg : layerArgs)
{
Layer layer;
switch(arg.type)
{
case FLAT_FILE:
layer = new FlatFile(new File(arg.spec), device, arg.writable, arg.cacheEnabled);
break;
case EXPANDABLE_FILE:
layer = new ExpandableFile(new File(arg.spec), device, arg.writable, arg.cacheEnabled);
break;
case NBD:
parts = arg.spec.split(":");
if(parts.length != 2)
throw new IllegalArgumentException("for NBD layer, format is hostnameorIP:portnumber");
InetAddress host = InetAddress.getByName(parts[0]);
int port = Integer.parseInt(parts[1]);
layer = new NBD(device, arg.writable, arg.cacheEnabled, host, port, null); // no path support yet
break;
default:
throw new RuntimeException(String.format("sorry, can't handle %s yet", arg.type));
}
device.addLayer(layer);
}
// device complete
// start up services
server.start();
manager.start();
// dump info to stdout
device.dumpInfo();
// run until NBD server termination
server.join();
}
}
| layerArgs in correct order
| src/cc/obrien/lbd/LBD.java | layerArgs in correct order | <ide><path>rc/cc/obrien/lbd/LBD.java
<ide> break;
<ide>
<ide> case 'e':
<del> layerArgs.add(0, new LayerArg(LayerArg.Type.EXPANDABLE_FILE, false, true, getOpt.getOptarg()));
<add> layerArgs.add(new LayerArg(LayerArg.Type.EXPANDABLE_FILE, false, true, getOpt.getOptarg()));
<ide> break;
<ide>
<ide> case 'E':
<del> layerArgs.add(0, new LayerArg(LayerArg.Type.EXPANDABLE_FILE, true, false,getOpt.getOptarg()));
<add> layerArgs.add(new LayerArg(LayerArg.Type.EXPANDABLE_FILE, true, false,getOpt.getOptarg()));
<ide> break;
<ide>
<ide> case 'f':
<del> layerArgs.add(0, new LayerArg(LayerArg.Type.FLAT_FILE, false, false, getOpt.getOptarg()));
<add> layerArgs.add(new LayerArg(LayerArg.Type.FLAT_FILE, false, false, getOpt.getOptarg()));
<ide> break;
<ide>
<ide> case 'F':
<del> layerArgs.add(0, new LayerArg(LayerArg.Type.FLAT_FILE, true, false, getOpt.getOptarg()));
<add> layerArgs.add(new LayerArg(LayerArg.Type.FLAT_FILE, true, false, getOpt.getOptarg()));
<ide> break;
<ide>
<ide> case 'n':
<del> layerArgs.add(0, new LayerArg(LayerArg.Type.NBD, false, true, getOpt.getOptarg()));
<add> layerArgs.add(new LayerArg(LayerArg.Type.NBD, false, true, getOpt.getOptarg()));
<ide> break;
<ide>
<ide> case 'N':
<del> layerArgs.add(0, new LayerArg(LayerArg.Type.NBD, true, false, getOpt.getOptarg()));
<add> layerArgs.add(new LayerArg(LayerArg.Type.NBD, true, false, getOpt.getOptarg()));
<ide> break;
<ide>
<ide> case 'X':
<del> layerArgs.add(0, new LayerArg(LayerArg.Type.NBD, true, true, getOpt.getOptarg()));
<add> layerArgs.add(new LayerArg(LayerArg.Type.NBD, true, true, getOpt.getOptarg()));
<ide> break;
<ide>
<ide> case '?':
<ide> for(LayerArg arg : layerArgs)
<ide> {
<ide> // top can be writable or read-only, either is ok
<del> if(arg == layerArgs.getFirst())
<add> if(arg == layerArgs.getLast())
<ide> continue;
<ide>
<ide> // but layers underneath should not be writable |
|
Java | apache-2.0 | 844ff807789974bc733692af88a69d49bde51b99 | 0 | GlenRSmith/elasticsearch,robin13/elasticsearch,coding0011/elasticsearch,coding0011/elasticsearch,robin13/elasticsearch,HonzaKral/elasticsearch,gingerwizard/elasticsearch,coding0011/elasticsearch,robin13/elasticsearch,GlenRSmith/elasticsearch,HonzaKral/elasticsearch,robin13/elasticsearch,uschindler/elasticsearch,scorpionvicky/elasticsearch,uschindler/elasticsearch,uschindler/elasticsearch,nknize/elasticsearch,gingerwizard/elasticsearch,coding0011/elasticsearch,gingerwizard/elasticsearch,gingerwizard/elasticsearch,GlenRSmith/elasticsearch,nknize/elasticsearch,gingerwizard/elasticsearch,nknize/elasticsearch,HonzaKral/elasticsearch,uschindler/elasticsearch,uschindler/elasticsearch,gingerwizard/elasticsearch,robin13/elasticsearch,scorpionvicky/elasticsearch,GlenRSmith/elasticsearch,scorpionvicky/elasticsearch,nknize/elasticsearch,nknize/elasticsearch,scorpionvicky/elasticsearch,HonzaKral/elasticsearch,scorpionvicky/elasticsearch,coding0011/elasticsearch,GlenRSmith/elasticsearch,gingerwizard/elasticsearch | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.index.engine;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.FilterDirectoryReader;
import org.apache.lucene.index.NoMergePolicy;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.ReferenceManager;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.AlreadyClosedException;
import org.elasticsearch.common.breaker.CircuitBreaker;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.lucene.index.ElasticsearchDirectoryReader;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.core.internal.io.IOUtils;
import org.elasticsearch.index.mapper.ParsedDocument;
import org.elasticsearch.index.seqno.SequenceNumbers;
import org.elasticsearch.index.store.Store;
import org.elasticsearch.indices.breaker.HierarchyCircuitBreakerService;
import org.elasticsearch.indices.breaker.NoneCircuitBreakerService;
import org.hamcrest.Matchers;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
public class FrozenEngineTests extends EngineTestCase {
public void testAcquireReleaseReset() throws IOException {
IOUtils.close(engine, store);
final AtomicLong globalCheckpoint = new AtomicLong(SequenceNumbers.NO_OPS_PERFORMED);
try (Store store = createStore()) {
CountingRefreshListener listener = new CountingRefreshListener();
EngineConfig config = config(defaultSettings, store, createTempDir(), newMergePolicy(), null, listener, null,
globalCheckpoint::get, new NoneCircuitBreakerService());
try (InternalEngine engine = createEngine(config)) {
int numDocs = Math.min(10, addDocuments(globalCheckpoint, engine));
engine.flushAndClose();
listener.reset();
try (FrozenEngine frozenEngine = new FrozenEngine(engine.engineConfig)) {
assertFalse(frozenEngine.isReaderOpen());
Engine.Searcher searcher = frozenEngine.acquireSearcher("test");
assertEquals(config.getShardId(), ElasticsearchDirectoryReader.getElasticsearchDirectoryReader(searcher
.getDirectoryReader()).shardId());
assertTrue(frozenEngine.isReaderOpen());
TopDocs search = searcher.searcher().search(new MatchAllDocsQuery(), numDocs);
assertEquals(search.scoreDocs.length, numDocs);
assertEquals(1, listener.afterRefresh.get());
FrozenEngine.unwrapLazyReader(searcher.getDirectoryReader()).release();
assertFalse(frozenEngine.isReaderOpen());
assertEquals(1, listener.afterRefresh.get());
expectThrows(AlreadyClosedException.class, () -> searcher.searcher().search(new MatchAllDocsQuery(), numDocs));
FrozenEngine.unwrapLazyReader(searcher.getDirectoryReader()).reset();
assertEquals(2, listener.afterRefresh.get());
search = searcher.searcher().search(new MatchAllDocsQuery(), numDocs);
assertEquals(search.scoreDocs.length, numDocs);
searcher.close();
}
}
}
}
public void testAcquireReleaseResetTwoSearchers() throws IOException {
IOUtils.close(engine, store);
final AtomicLong globalCheckpoint = new AtomicLong(SequenceNumbers.NO_OPS_PERFORMED);
try (Store store = createStore()) {
CountingRefreshListener listener = new CountingRefreshListener();
EngineConfig config = config(defaultSettings, store, createTempDir(), newMergePolicy(), null, listener, null,
globalCheckpoint::get, new NoneCircuitBreakerService());
try (InternalEngine engine = createEngine(config)) {
int numDocs = Math.min(10, addDocuments(globalCheckpoint, engine));
engine.flushAndClose();
listener.reset();
try (FrozenEngine frozenEngine = new FrozenEngine(engine.engineConfig)) {
assertFalse(frozenEngine.isReaderOpen());
Engine.Searcher searcher1 = frozenEngine.acquireSearcher("test");
assertTrue(frozenEngine.isReaderOpen());
TopDocs search = searcher1.searcher().search(new MatchAllDocsQuery(), numDocs);
assertEquals(search.scoreDocs.length, numDocs);
assertEquals(1, listener.afterRefresh.get());
FrozenEngine.unwrapLazyReader(searcher1.getDirectoryReader()).release();
Engine.Searcher searcher2 = frozenEngine.acquireSearcher("test");
search = searcher2.searcher().search(new MatchAllDocsQuery(), numDocs);
assertEquals(search.scoreDocs.length, numDocs);
assertTrue(frozenEngine.isReaderOpen());
assertEquals(2, listener.afterRefresh.get());
expectThrows(AlreadyClosedException.class, () -> searcher1.searcher().search(new MatchAllDocsQuery(), numDocs));
FrozenEngine.unwrapLazyReader(searcher1.getDirectoryReader()).reset();
assertEquals(2, listener.afterRefresh.get());
search = searcher1.searcher().search(new MatchAllDocsQuery(), numDocs);
assertEquals(search.scoreDocs.length, numDocs);
searcher1.close();
searcher2.close();
}
}
}
}
public void testSegmentStats() throws IOException {
IOUtils.close(engine, store);
final AtomicLong globalCheckpoint = new AtomicLong(SequenceNumbers.NO_OPS_PERFORMED);
try (Store store = createStore()) {
CountingRefreshListener listener = new CountingRefreshListener();
EngineConfig config = config(defaultSettings, store, createTempDir(), newMergePolicy(), null, listener, null,
globalCheckpoint::get, new NoneCircuitBreakerService());
try (InternalEngine engine = createEngine(config)) {
addDocuments(globalCheckpoint, engine);
engine.flushAndClose();
listener.reset();
try (FrozenEngine frozenEngine = new FrozenEngine(engine.engineConfig)) {
Engine.Searcher searcher = frozenEngine.acquireSearcher("test");
SegmentsStats segmentsStats = frozenEngine.segmentsStats(randomBoolean());
assertEquals(frozenEngine.segments(randomBoolean()).size(), segmentsStats.getCount());
FrozenEngine.unwrapLazyReader(searcher.getDirectoryReader()).release();
assertEquals(1, listener.afterRefresh.get());
segmentsStats = frozenEngine.segmentsStats(randomBoolean());
assertEquals(0, segmentsStats.getCount());
assertEquals(1, listener.afterRefresh.get());
assertFalse(frozenEngine.isReaderOpen());
FrozenEngine.unwrapLazyReader(searcher.getDirectoryReader()).reset();
segmentsStats = frozenEngine.segmentsStats(randomBoolean());
assertEquals(frozenEngine.segments(randomBoolean()).size(), segmentsStats.getCount());
searcher.close();
}
}
}
}
public void testCircuitBreakerAccounting() throws IOException {
IOUtils.close(engine, store);
final AtomicLong globalCheckpoint = new AtomicLong(SequenceNumbers.NO_OPS_PERFORMED);
try (Store store = createStore()) {
CountingRefreshListener listener = new CountingRefreshListener();
EngineConfig config = config(defaultSettings, store, createTempDir(),
NoMergePolicy.INSTANCE, // we don't merge we want no background merges to happen to ensure we have consistent breaker stats
null, listener, null, globalCheckpoint::get, new HierarchyCircuitBreakerService(defaultSettings.getSettings(),
new ClusterSettings(defaultSettings.getNodeSettings(), ClusterSettings.BUILT_IN_CLUSTER_SETTINGS)));
CircuitBreaker breaker = config.getCircuitBreakerService().getBreaker(CircuitBreaker.ACCOUNTING);
long expectedUse;
try (InternalEngine engine = createEngine(config)) {
addDocuments(globalCheckpoint, engine);
engine.flush(false, true); // first flush to make sure we have a commit that we open in the frozen engine blow.
engine.refresh("test"); // pull the reader to account for RAM in the breaker.
expectedUse = breaker.getUsed();
}
assertTrue(expectedUse > 0);
assertEquals(0, breaker.getUsed());
listener.reset();
try (FrozenEngine frozenEngine = new FrozenEngine(config)) {
Engine.Searcher searcher = frozenEngine.acquireSearcher("test");
assertEquals(expectedUse, breaker.getUsed());
FrozenEngine.unwrapLazyReader(searcher.getDirectoryReader()).release();
assertEquals(1, listener.afterRefresh.get());
assertEquals(0, breaker.getUsed());
assertFalse(frozenEngine.isReaderOpen());
FrozenEngine.unwrapLazyReader(searcher.getDirectoryReader()).reset();
assertEquals(expectedUse, breaker.getUsed());
searcher.close();
assertEquals(0, breaker.getUsed());
}
}
}
private int addDocuments(AtomicLong globalCheckpoint, InternalEngine engine) throws IOException {
int numDocs = scaledRandomIntBetween(10, 1000);
int numDocsAdded = 0;
for (int i = 0; i < numDocs; i++) {
numDocsAdded++;
ParsedDocument doc = testParsedDocument(Integer.toString(i), null, testDocument(), new BytesArray("{}"), null);
engine.index(new Engine.Index(newUid(doc), doc, i, primaryTerm.get(), 1, null, Engine.Operation.Origin.REPLICA,
System.nanoTime(), -1, false));
if (rarely()) {
engine.flush();
}
globalCheckpoint.set(engine.getLocalCheckpoint());
}
engine.syncTranslog();
return numDocsAdded;
}
public void testSearchConcurrently() throws IOException, InterruptedException {
// even though we don't want this to be searched concurrently we better make sure we release all resources etc.
IOUtils.close(engine, store);
final AtomicLong globalCheckpoint = new AtomicLong(SequenceNumbers.NO_OPS_PERFORMED);
try (Store store = createStore()) {
EngineConfig config = config(defaultSettings, store, createTempDir(), newMergePolicy(), null, null, null, globalCheckpoint::get,
new HierarchyCircuitBreakerService(defaultSettings.getSettings(),
new ClusterSettings(defaultSettings.getNodeSettings(), ClusterSettings.BUILT_IN_CLUSTER_SETTINGS)));
CircuitBreaker breaker = config.getCircuitBreakerService().getBreaker(CircuitBreaker.ACCOUNTING);
try (InternalEngine engine = createEngine(config)) {
int numDocsAdded = addDocuments(globalCheckpoint, engine);
engine.flushAndClose();
int numIters = randomIntBetween(100, 1000);
try (FrozenEngine frozenEngine = new FrozenEngine(engine.engineConfig)) {
int numThreads = randomIntBetween(2, 4);
Thread[] threads = new Thread[numThreads];
CyclicBarrier barrier = new CyclicBarrier(numThreads);
CountDownLatch latch = new CountDownLatch(numThreads);
for (int i = 0; i < numThreads; i++) {
threads[i] = new Thread(() -> {
try (Engine.Searcher searcher = frozenEngine.acquireSearcher("test")) {
barrier.await();
FrozenEngine.unwrapLazyReader(searcher.getDirectoryReader()).release();
for (int j = 0; j < numIters; j++) {
FrozenEngine.unwrapLazyReader(searcher.getDirectoryReader()).reset();
assertTrue(frozenEngine.isReaderOpen());
TopDocs search = searcher.searcher().search(new MatchAllDocsQuery(), Math.min(10, numDocsAdded));
assertEquals(search.scoreDocs.length, Math.min(10, numDocsAdded));
FrozenEngine.unwrapLazyReader(searcher.getDirectoryReader()).release();
}
if (randomBoolean()) {
FrozenEngine.unwrapLazyReader(searcher.getDirectoryReader()).reset();
}
} catch (Exception e) {
throw new AssertionError(e);
} finally {
latch.countDown();
}
});
threads[i].start();
}
latch.await();
for (Thread t : threads) {
t.join();
}
assertFalse(frozenEngine.isReaderOpen());
assertEquals(0, breaker.getUsed());
}
}
}
}
private static void checkOverrideMethods(Class<?> clazz) throws NoSuchMethodException, SecurityException {
final Class<?> superClazz = clazz.getSuperclass();
for (Method m : superClazz.getMethods()) {
final int mods = m.getModifiers();
if (Modifier.isStatic(mods) || Modifier.isAbstract(mods) || Modifier.isFinal(mods) || m.isSynthetic()
|| m.getName().equals("attributes") || m.getName().equals("getStats")) {
continue;
}
// The point of these checks is to ensure that methods from the super class
// are overwritten to make sure we never miss a method from FilterLeafReader / FilterDirectoryReader
final Method subM = clazz.getMethod(m.getName(), m.getParameterTypes());
if (subM.getDeclaringClass() == superClazz
&& m.getDeclaringClass() != Object.class
&& m.getDeclaringClass() == subM.getDeclaringClass()) {
fail(clazz + " doesn't override" + m + " although it has been declared by it's superclass");
}
}
}
// here we make sure we catch any change to their super classes FilterLeafReader / FilterDirectoryReader
public void testOverrideMethods() throws Exception {
checkOverrideMethods(FrozenEngine.LazyDirectoryReader.class);
checkOverrideMethods(FrozenEngine.LazyLeafReader.class);
}
private class CountingRefreshListener implements ReferenceManager.RefreshListener {
final AtomicInteger afterRefresh = new AtomicInteger(0);
private final AtomicInteger beforeRefresh = new AtomicInteger(0);
@Override
public void beforeRefresh() {
beforeRefresh.incrementAndGet();
}
@Override
public void afterRefresh(boolean didRefresh) {
afterRefresh.incrementAndGet();
assertEquals(beforeRefresh.get(), afterRefresh.get());
}
void reset() {
afterRefresh.set(0);
beforeRefresh.set(0);
}
}
public void testCanMatch() throws IOException {
IOUtils.close(engine, store);
final AtomicLong globalCheckpoint = new AtomicLong(SequenceNumbers.NO_OPS_PERFORMED);
try (Store store = createStore()) {
CountingRefreshListener listener = new CountingRefreshListener();
EngineConfig config = config(defaultSettings, store, createTempDir(), newMergePolicy(), null, listener, null,
globalCheckpoint::get, new NoneCircuitBreakerService());
try (InternalEngine engine = createEngine(config)) {
addDocuments(globalCheckpoint, engine);
engine.flushAndClose();
listener.reset();
try (FrozenEngine frozenEngine = new FrozenEngine(engine.engineConfig)) {
DirectoryReader reader;
try (Engine.Searcher searcher = frozenEngine.acquireSearcher("can_match")) {
assertNotNull(ElasticsearchDirectoryReader.getElasticsearchDirectoryReader(searcher.getDirectoryReader()));
assertEquals(config.getShardId(), ElasticsearchDirectoryReader.getElasticsearchDirectoryReader(searcher
.getDirectoryReader()).shardId());
reader = searcher.getDirectoryReader();
assertNotEquals(reader, Matchers.instanceOf(FrozenEngine.LazyDirectoryReader.class));
assertEquals(0, listener.afterRefresh.get());
DirectoryReader unwrap = FilterDirectoryReader.unwrap(searcher.getDirectoryReader());
assertThat(unwrap, Matchers.instanceOf(RewriteCachingDirectoryReader.class));
assertNotNull(ElasticsearchDirectoryReader.getElasticsearchDirectoryReader(searcher.getDirectoryReader()));
}
try (Engine.Searcher searcher = frozenEngine.acquireSearcher("can_match")) {
assertSame(reader, searcher.getDirectoryReader());
assertNotEquals(reader, Matchers.instanceOf(FrozenEngine.LazyDirectoryReader.class));
assertEquals(0, listener.afterRefresh.get());
DirectoryReader unwrap = FilterDirectoryReader.unwrap(searcher.getDirectoryReader());
assertThat(unwrap, Matchers.instanceOf(RewriteCachingDirectoryReader.class));
}
}
}
}
}
}
| x-pack/plugin/core/src/test/java/org/elasticsearch/index/engine/FrozenEngineTests.java | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.index.engine;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.FilterDirectoryReader;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.ReferenceManager;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.AlreadyClosedException;
import org.elasticsearch.common.breaker.CircuitBreaker;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.lucene.index.ElasticsearchDirectoryReader;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.core.internal.io.IOUtils;
import org.elasticsearch.index.mapper.ParsedDocument;
import org.elasticsearch.index.seqno.SequenceNumbers;
import org.elasticsearch.index.store.Store;
import org.elasticsearch.indices.breaker.HierarchyCircuitBreakerService;
import org.elasticsearch.indices.breaker.NoneCircuitBreakerService;
import org.hamcrest.Matchers;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
public class FrozenEngineTests extends EngineTestCase {
public void testAcquireReleaseReset() throws IOException {
IOUtils.close(engine, store);
final AtomicLong globalCheckpoint = new AtomicLong(SequenceNumbers.NO_OPS_PERFORMED);
try (Store store = createStore()) {
CountingRefreshListener listener = new CountingRefreshListener();
EngineConfig config = config(defaultSettings, store, createTempDir(), newMergePolicy(), null, listener, null,
globalCheckpoint::get, new NoneCircuitBreakerService());
try (InternalEngine engine = createEngine(config)) {
int numDocs = Math.min(10, addDocuments(globalCheckpoint, engine));
engine.flushAndClose();
listener.reset();
try (FrozenEngine frozenEngine = new FrozenEngine(engine.engineConfig)) {
assertFalse(frozenEngine.isReaderOpen());
Engine.Searcher searcher = frozenEngine.acquireSearcher("test");
assertEquals(config.getShardId(), ElasticsearchDirectoryReader.getElasticsearchDirectoryReader(searcher
.getDirectoryReader()).shardId());
assertTrue(frozenEngine.isReaderOpen());
TopDocs search = searcher.searcher().search(new MatchAllDocsQuery(), numDocs);
assertEquals(search.scoreDocs.length, numDocs);
assertEquals(1, listener.afterRefresh.get());
FrozenEngine.unwrapLazyReader(searcher.getDirectoryReader()).release();
assertFalse(frozenEngine.isReaderOpen());
assertEquals(1, listener.afterRefresh.get());
expectThrows(AlreadyClosedException.class, () -> searcher.searcher().search(new MatchAllDocsQuery(), numDocs));
FrozenEngine.unwrapLazyReader(searcher.getDirectoryReader()).reset();
assertEquals(2, listener.afterRefresh.get());
search = searcher.searcher().search(new MatchAllDocsQuery(), numDocs);
assertEquals(search.scoreDocs.length, numDocs);
searcher.close();
}
}
}
}
public void testAcquireReleaseResetTwoSearchers() throws IOException {
IOUtils.close(engine, store);
final AtomicLong globalCheckpoint = new AtomicLong(SequenceNumbers.NO_OPS_PERFORMED);
try (Store store = createStore()) {
CountingRefreshListener listener = new CountingRefreshListener();
EngineConfig config = config(defaultSettings, store, createTempDir(), newMergePolicy(), null, listener, null,
globalCheckpoint::get, new NoneCircuitBreakerService());
try (InternalEngine engine = createEngine(config)) {
int numDocs = Math.min(10, addDocuments(globalCheckpoint, engine));
engine.flushAndClose();
listener.reset();
try (FrozenEngine frozenEngine = new FrozenEngine(engine.engineConfig)) {
assertFalse(frozenEngine.isReaderOpen());
Engine.Searcher searcher1 = frozenEngine.acquireSearcher("test");
assertTrue(frozenEngine.isReaderOpen());
TopDocs search = searcher1.searcher().search(new MatchAllDocsQuery(), numDocs);
assertEquals(search.scoreDocs.length, numDocs);
assertEquals(1, listener.afterRefresh.get());
FrozenEngine.unwrapLazyReader(searcher1.getDirectoryReader()).release();
Engine.Searcher searcher2 = frozenEngine.acquireSearcher("test");
search = searcher2.searcher().search(new MatchAllDocsQuery(), numDocs);
assertEquals(search.scoreDocs.length, numDocs);
assertTrue(frozenEngine.isReaderOpen());
assertEquals(2, listener.afterRefresh.get());
expectThrows(AlreadyClosedException.class, () -> searcher1.searcher().search(new MatchAllDocsQuery(), numDocs));
FrozenEngine.unwrapLazyReader(searcher1.getDirectoryReader()).reset();
assertEquals(2, listener.afterRefresh.get());
search = searcher1.searcher().search(new MatchAllDocsQuery(), numDocs);
assertEquals(search.scoreDocs.length, numDocs);
searcher1.close();
searcher2.close();
}
}
}
}
public void testSegmentStats() throws IOException {
IOUtils.close(engine, store);
final AtomicLong globalCheckpoint = new AtomicLong(SequenceNumbers.NO_OPS_PERFORMED);
try (Store store = createStore()) {
CountingRefreshListener listener = new CountingRefreshListener();
EngineConfig config = config(defaultSettings, store, createTempDir(), newMergePolicy(), null, listener, null,
globalCheckpoint::get, new NoneCircuitBreakerService());
try (InternalEngine engine = createEngine(config)) {
addDocuments(globalCheckpoint, engine);
engine.flushAndClose();
listener.reset();
try (FrozenEngine frozenEngine = new FrozenEngine(engine.engineConfig)) {
Engine.Searcher searcher = frozenEngine.acquireSearcher("test");
SegmentsStats segmentsStats = frozenEngine.segmentsStats(randomBoolean());
assertEquals(frozenEngine.segments(randomBoolean()).size(), segmentsStats.getCount());
FrozenEngine.unwrapLazyReader(searcher.getDirectoryReader()).release();
assertEquals(1, listener.afterRefresh.get());
segmentsStats = frozenEngine.segmentsStats(randomBoolean());
assertEquals(0, segmentsStats.getCount());
assertEquals(1, listener.afterRefresh.get());
assertFalse(frozenEngine.isReaderOpen());
FrozenEngine.unwrapLazyReader(searcher.getDirectoryReader()).reset();
segmentsStats = frozenEngine.segmentsStats(randomBoolean());
assertEquals(frozenEngine.segments(randomBoolean()).size(), segmentsStats.getCount());
searcher.close();
}
}
}
}
public void testCircuitBreakerAccounting() throws IOException {
IOUtils.close(engine, store);
final AtomicLong globalCheckpoint = new AtomicLong(SequenceNumbers.NO_OPS_PERFORMED);
try (Store store = createStore()) {
CountingRefreshListener listener = new CountingRefreshListener();
EngineConfig config = config(defaultSettings, store, createTempDir(), newMergePolicy(), null, listener, null,
globalCheckpoint::get, new HierarchyCircuitBreakerService(defaultSettings.getSettings(),
new ClusterSettings(defaultSettings.getNodeSettings(), ClusterSettings.BUILT_IN_CLUSTER_SETTINGS)));
CircuitBreaker breaker = config.getCircuitBreakerService().getBreaker(CircuitBreaker.ACCOUNTING);
long expectedUse;
try (InternalEngine engine = createEngine(config)) {
addDocuments(globalCheckpoint, engine);
engine.refresh("test"); // pull the reader
expectedUse = breaker.getUsed();
engine.flushAndClose();
}
assertTrue(expectedUse > 0);
assertEquals(0, breaker.getUsed());
listener.reset();
try (FrozenEngine frozenEngine = new FrozenEngine(config)) {
Engine.Searcher searcher = frozenEngine.acquireSearcher("test");
assertEquals(expectedUse, breaker.getUsed());
FrozenEngine.unwrapLazyReader(searcher.getDirectoryReader()).release();
assertEquals(1, listener.afterRefresh.get());
assertEquals(0, breaker.getUsed());
assertFalse(frozenEngine.isReaderOpen());
FrozenEngine.unwrapLazyReader(searcher.getDirectoryReader()).reset();
assertEquals(expectedUse, breaker.getUsed());
searcher.close();
assertEquals(0, breaker.getUsed());
}
}
}
private int addDocuments(AtomicLong globalCheckpoint, InternalEngine engine) throws IOException {
int numDocs = scaledRandomIntBetween(10, 1000);
int numDocsAdded = 0;
for (int i = 0; i < numDocs; i++) {
numDocsAdded++;
ParsedDocument doc = testParsedDocument(Integer.toString(i), null, testDocument(), new BytesArray("{}"), null);
engine.index(new Engine.Index(newUid(doc), doc, i, primaryTerm.get(), 1, null, Engine.Operation.Origin.REPLICA,
System.nanoTime(), -1, false));
if (rarely()) {
engine.flush();
}
globalCheckpoint.set(engine.getLocalCheckpoint());
}
engine.syncTranslog();
return numDocsAdded;
}
public void testSearchConcurrently() throws IOException, InterruptedException {
// even though we don't want this to be searched concurrently we better make sure we release all resources etc.
IOUtils.close(engine, store);
final AtomicLong globalCheckpoint = new AtomicLong(SequenceNumbers.NO_OPS_PERFORMED);
try (Store store = createStore()) {
EngineConfig config = config(defaultSettings, store, createTempDir(), newMergePolicy(), null, null, null, globalCheckpoint::get,
new HierarchyCircuitBreakerService(defaultSettings.getSettings(),
new ClusterSettings(defaultSettings.getNodeSettings(), ClusterSettings.BUILT_IN_CLUSTER_SETTINGS)));
CircuitBreaker breaker = config.getCircuitBreakerService().getBreaker(CircuitBreaker.ACCOUNTING);
try (InternalEngine engine = createEngine(config)) {
int numDocsAdded = addDocuments(globalCheckpoint, engine);
engine.flushAndClose();
int numIters = randomIntBetween(100, 1000);
try (FrozenEngine frozenEngine = new FrozenEngine(engine.engineConfig)) {
int numThreads = randomIntBetween(2, 4);
Thread[] threads = new Thread[numThreads];
CyclicBarrier barrier = new CyclicBarrier(numThreads);
CountDownLatch latch = new CountDownLatch(numThreads);
for (int i = 0; i < numThreads; i++) {
threads[i] = new Thread(() -> {
try (Engine.Searcher searcher = frozenEngine.acquireSearcher("test")) {
barrier.await();
FrozenEngine.unwrapLazyReader(searcher.getDirectoryReader()).release();
for (int j = 0; j < numIters; j++) {
FrozenEngine.unwrapLazyReader(searcher.getDirectoryReader()).reset();
assertTrue(frozenEngine.isReaderOpen());
TopDocs search = searcher.searcher().search(new MatchAllDocsQuery(), Math.min(10, numDocsAdded));
assertEquals(search.scoreDocs.length, Math.min(10, numDocsAdded));
FrozenEngine.unwrapLazyReader(searcher.getDirectoryReader()).release();
}
if (randomBoolean()) {
FrozenEngine.unwrapLazyReader(searcher.getDirectoryReader()).reset();
}
} catch (Exception e) {
throw new AssertionError(e);
} finally {
latch.countDown();
}
});
threads[i].start();
}
latch.await();
for (Thread t : threads) {
t.join();
}
assertFalse(frozenEngine.isReaderOpen());
assertEquals(0, breaker.getUsed());
}
}
}
}
private static void checkOverrideMethods(Class<?> clazz) throws NoSuchMethodException, SecurityException {
final Class<?> superClazz = clazz.getSuperclass();
for (Method m : superClazz.getMethods()) {
final int mods = m.getModifiers();
if (Modifier.isStatic(mods) || Modifier.isAbstract(mods) || Modifier.isFinal(mods) || m.isSynthetic()
|| m.getName().equals("attributes") || m.getName().equals("getStats")) {
continue;
}
// The point of these checks is to ensure that methods from the super class
// are overwritten to make sure we never miss a method from FilterLeafReader / FilterDirectoryReader
final Method subM = clazz.getMethod(m.getName(), m.getParameterTypes());
if (subM.getDeclaringClass() == superClazz
&& m.getDeclaringClass() != Object.class
&& m.getDeclaringClass() == subM.getDeclaringClass()) {
fail(clazz + " doesn't override" + m + " although it has been declared by it's superclass");
}
}
}
// here we make sure we catch any change to their super classes FilterLeafReader / FilterDirectoryReader
public void testOverrideMethods() throws Exception {
checkOverrideMethods(FrozenEngine.LazyDirectoryReader.class);
checkOverrideMethods(FrozenEngine.LazyLeafReader.class);
}
private class CountingRefreshListener implements ReferenceManager.RefreshListener {
final AtomicInteger afterRefresh = new AtomicInteger(0);
private final AtomicInteger beforeRefresh = new AtomicInteger(0);
@Override
public void beforeRefresh() {
beforeRefresh.incrementAndGet();
}
@Override
public void afterRefresh(boolean didRefresh) {
afterRefresh.incrementAndGet();
assertEquals(beforeRefresh.get(), afterRefresh.get());
}
void reset() {
afterRefresh.set(0);
beforeRefresh.set(0);
}
}
public void testCanMatch() throws IOException {
IOUtils.close(engine, store);
final AtomicLong globalCheckpoint = new AtomicLong(SequenceNumbers.NO_OPS_PERFORMED);
try (Store store = createStore()) {
CountingRefreshListener listener = new CountingRefreshListener();
EngineConfig config = config(defaultSettings, store, createTempDir(), newMergePolicy(), null, listener, null,
globalCheckpoint::get, new NoneCircuitBreakerService());
try (InternalEngine engine = createEngine(config)) {
addDocuments(globalCheckpoint, engine);
engine.flushAndClose();
listener.reset();
try (FrozenEngine frozenEngine = new FrozenEngine(engine.engineConfig)) {
DirectoryReader reader;
try (Engine.Searcher searcher = frozenEngine.acquireSearcher("can_match")) {
assertNotNull(ElasticsearchDirectoryReader.getElasticsearchDirectoryReader(searcher.getDirectoryReader()));
assertEquals(config.getShardId(), ElasticsearchDirectoryReader.getElasticsearchDirectoryReader(searcher
.getDirectoryReader()).shardId());
reader = searcher.getDirectoryReader();
assertNotEquals(reader, Matchers.instanceOf(FrozenEngine.LazyDirectoryReader.class));
assertEquals(0, listener.afterRefresh.get());
DirectoryReader unwrap = FilterDirectoryReader.unwrap(searcher.getDirectoryReader());
assertThat(unwrap, Matchers.instanceOf(RewriteCachingDirectoryReader.class));
assertNotNull(ElasticsearchDirectoryReader.getElasticsearchDirectoryReader(searcher.getDirectoryReader()));
}
try (Engine.Searcher searcher = frozenEngine.acquireSearcher("can_match")) {
assertSame(reader, searcher.getDirectoryReader());
assertNotEquals(reader, Matchers.instanceOf(FrozenEngine.LazyDirectoryReader.class));
assertEquals(0, listener.afterRefresh.get());
DirectoryReader unwrap = FilterDirectoryReader.unwrap(searcher.getDirectoryReader());
assertThat(unwrap, Matchers.instanceOf(RewriteCachingDirectoryReader.class));
}
}
}
}
}
}
| Harden FrozenEngineTests#testCircuitBreakerAccounting
This test tries to compare the CB stats from an InternalEngine
and a FrozenEngine but is subject to segement merges that might finish
and get committed after we read the breaker stats. This can cause
occational test failures.
Closes #36207
| x-pack/plugin/core/src/test/java/org/elasticsearch/index/engine/FrozenEngineTests.java | Harden FrozenEngineTests#testCircuitBreakerAccounting | <ide><path>-pack/plugin/core/src/test/java/org/elasticsearch/index/engine/FrozenEngineTests.java
<ide>
<ide> import org.apache.lucene.index.DirectoryReader;
<ide> import org.apache.lucene.index.FilterDirectoryReader;
<add>import org.apache.lucene.index.NoMergePolicy;
<ide> import org.apache.lucene.search.MatchAllDocsQuery;
<ide> import org.apache.lucene.search.ReferenceManager;
<ide> import org.apache.lucene.search.TopDocs;
<ide> final AtomicLong globalCheckpoint = new AtomicLong(SequenceNumbers.NO_OPS_PERFORMED);
<ide> try (Store store = createStore()) {
<ide> CountingRefreshListener listener = new CountingRefreshListener();
<del> EngineConfig config = config(defaultSettings, store, createTempDir(), newMergePolicy(), null, listener, null,
<del> globalCheckpoint::get, new HierarchyCircuitBreakerService(defaultSettings.getSettings(),
<add> EngineConfig config = config(defaultSettings, store, createTempDir(),
<add> NoMergePolicy.INSTANCE, // we don't merge we want no background merges to happen to ensure we have consistent breaker stats
<add> null, listener, null, globalCheckpoint::get, new HierarchyCircuitBreakerService(defaultSettings.getSettings(),
<ide> new ClusterSettings(defaultSettings.getNodeSettings(), ClusterSettings.BUILT_IN_CLUSTER_SETTINGS)));
<ide> CircuitBreaker breaker = config.getCircuitBreakerService().getBreaker(CircuitBreaker.ACCOUNTING);
<ide> long expectedUse;
<ide> try (InternalEngine engine = createEngine(config)) {
<ide> addDocuments(globalCheckpoint, engine);
<del> engine.refresh("test"); // pull the reader
<add> engine.flush(false, true); // first flush to make sure we have a commit that we open in the frozen engine blow.
<add> engine.refresh("test"); // pull the reader to account for RAM in the breaker.
<ide> expectedUse = breaker.getUsed();
<del> engine.flushAndClose();
<ide> }
<ide> assertTrue(expectedUse > 0);
<ide> assertEquals(0, breaker.getUsed()); |
|
JavaScript | agpl-3.0 | 37aed6197b79d9bdb13d29a071f43dbf9607be7a | 0 | gruener-campus-malchow/vertretungsplan,gruener-campus-malchow/vertretungsplan | var urlIndexhtml = "index.html";
var urlPlanhtml = "plan.html";
var parameters = {};
/**
reads parameters in URL and adds them to the parameters map
*/
function setParametersFromURL() {
var params = document.location.search.split("&");
params[0] = params[0].replace("?", "");
for (var i = 0; i < params.length; i++) {
var param = params[i];
parameters[param.substring(0, param.indexOf("="))] = param.substring(param.indexOf("=")+1, param.length);
}
}
function updateVertretungsplan() { //http://stackoverflow.com/a/22790025
/*json = {"Tag":"20.1.2017 Freitag","Time":"2017-01-20","Informationen":["Das sind Test-Informationen."],"7b":{"1":{"Stunde":"1 - 2","Fach":"DEU","Raum":"3.309","LehrerIn":"___(statt ___)","Hinweis":"\u00a0","Art":"Vertretung"},"2":{"Stunde":"3 - 4","Fach":"MA","Raum":"3.214","LehrerIn":"___","Hinweis":"\u00a0","Art":"Vertretung"},"3":{"Stunde":"5","Fach":"EN","Raum":"3.202","LehrerIn":"___","Hinweis":"\u00a0","Art":"Ausfall"}},"7a":{"1":{"Stunde":"1 - 2","Fach":"DEU","Raum":"3.309","LehrerIn":"___(statt ___)","Hinweis":"\u00a0","Art":"Vertretung"},"2":{"Stunde":"3 - 4","Fach":"MA","Raum":"3.214","LehrerIn":"___","Hinweis":"\u00a0","Art":"Vertretung"},"3":{"Stunde":"5","Fach":"EN","Raum":"3.202","LehrerIn":"___","Hinweis":"\u00a0","Art":"Ausfall"}},"9a":{"1":{"Stunde":"1 - 2","Fach":"DEU","Raum":"3.309","LehrerIn":"___(statt ___)","Hinweis":"\u00a0","Art":"Vertretung"},"2":{"Stunde":"3 - 4","Fach":"MA","Raum":"3.214","LehrerIn":"___","Hinweis":"\u00a0","Art":"Vertretung"},"3":{"Stunde":"5","Fach":"EN","Raum":"3.202","LehrerIn":"___","Hinweis":"\u00a0","Art":"Ausfall"}}};
updatePlan(json);
document.getElementById('plan').style.display='inline';
document.getElementById('wrong-pswd').style.display='none';*/
var httpreq = new XMLHttpRequest();
httpreq.open("GET", getApiUrl(), true);
httpreq.onload = function(e) {
if (httpreq.readyState === 4) {
if (httpreq.status === 200) {
try {
var responseJSON = JSON.parse(httpreq.responseText);
console.log(responseJSON);
if(noPlanOnline(responseJSON)) {
showById('kein-plan');
} else {
hideById('wrong-pswd');
//plan has to be set visible before calling updatePlan() because
//calculating the correct offset for the plan wouldn't work otherwise
showById('plan');
updatePlan(responseJSON);
finishedParsing();
}
} catch(err) {//wrong password
hideById('plan');
showById('wrong-pswd');
redirect(urlIndexhtml, 2000);
}
} else {
console.error(httpreq.statusText);
}
}
}
httpreq.onerror = function(e) {
console.error(httpreq.statusText);
}
httpreq.send(null);
return httpreq.responseText;
}
function getApiUrl() {
return "http://fbi.gruener-campus-malchow.de/cis/pupilplanapi.php" + getUrlArguments();
}
function getUrlArguments() {
var cert = parameters["cert"];
var dev = parameters["dev"];
var klasse = parameters["klasse"];
var user = parameters["user"];
var arguments = "?cert=" + cert;
if(dev) {
arguments+="&dev=" + dev;
}
if(klasse) {
arguments+="&klasse=" + klasse;
}
if(user) {
arguments+="&user=" + user;
}
return arguments;
}
function finishedParsing() {
if(parameters['user'] === 'foyer') {
startScrolling();
} else {
allClassNames = sortClassNames(allClassNames);
addClassNamesToDropdown(allClassNames);
}
}
function noPlanOnline(json) {
return json[0] === "false";
}
function redirect(url, delay) {
setTimeout(function() {window.location.replace(url);}, delay);
}
function updatePlan(plan) {
updateInfo(plan);
updatePlanPaddingTop(); //style.js
updateClasses(plan);
}
function updateClasses(plan) {
var noClass = ['Informationen', 'Tag', 'Time'];
for (var i = 0; i < plan.length; i++) {
var day = plan[i];
updateBoxDate(day['Tag']);
for (var className in day) {
if (day.hasOwnProperty(className)) {
if (noClass.indexOf(className) === -1) {
var schoolClass = day[className];
updateClass(className, schoolClass);
}
}
}
}
}
function updateClass(className, schoolClass) {
var entryNumbers = [];
for (var entryNumber in schoolClass) {
if (schoolClass.hasOwnProperty(entryNumber)) {
entryNumbers.push(entryNumber);
}
}
// eintragsNummern wie Zahlen sortieren, obwohl sie Strings sind
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
entryNumbers.sort(function (s1, s2) { return parseInt(s1) - parseInt(s2); })
// addiere Eintraege auf
var entries = [];
var lastEntry;
for (var i = 0; i < entryNumbers.length; i += 1) {
var entryNumber = entryNumbers[i];
var entry = schoolClass[entryNumber];
if (isNewEntry(entry)) {
lastEntry = {"Raum":"", "Fach":"", "Hinweis":"", "Art":"", "Stunde":""};
entries.push(lastEntry);
}
lastEntry["Raum"] += entry["Raum"] + " ";
lastEntry["Fach"] += entry["Fach"] + " ";
lastEntry["Hinweis"] += entry["Hinweis"] + " ";
lastEntry["Art"] += entry["Art"] + " ";
lastEntry["Stunde"] += entry["Stunde"] + " ";
}
// update mit addierten Eintraegen
for (var i = 0; i < entries.length; i += 1) {
var entry = entries[i];
updateBox(className,
entry["Raum"],
entry["Fach"],
entry["Stunde"],
entry["Hinweis"],
entry["Art"]);
}
}
var allSpace = new RegExp("^\\s*$");
function isAllSpace(string) {
return allSpace.exec(string) != null;
}
function isNewEntry(eintrag) {
return !isAllSpace(eintrag["Art"]);
}
//https://stackoverflow.com/questions/784539/how-do-i-replace-all-line-breaks-in-a-string-with-br-tags
function removeLineBreaks(string) {
return string.replace(/\r?\n|\r/g, "");
}
function updateInfo(plan) {
var text = '';
for (var i = 0; i < plan.length; i++) {
var day = plan[i];
var date = day['Tag'];
var informations = day['Informationen'];
if (informations!==undefined&&informations!=='') {
if (i > 0) {
text += '\n';
}
text += date + '\n';
for (var j = 0; j < informations.length; j++) {
var info = day['Informationen'][j];
info = removeLineBreaks(info);
text += info;
if(j < informations.length-1) {
text+=', ';
}
}
} else {
hideInfoText();
}
setInfoText(text);
}
}
setParametersFromURL();
updateVertretungsplan();
| js/jsonparser.js | var urlIndexhtml = "index.html";
var urlPlanhtml = "plan.html";
var parameters = {};
var infos = {};
/**
reads parameters in URL and adds them to the parameters map
*/
function setParametersFromURL() {
var params = document.location.search.split("&");
params[0] = params[0].replace("?", "");
for (var i = 0; i < params.length; i++) {
var param = params[i];
parameters[param.substring(0, param.indexOf("="))] = param.substring(param.indexOf("=")+1, param.length);
}
}
function updateVertretungsplan() { //http://stackoverflow.com/a/22790025
/*json = {"Tag":"20.1.2017 Freitag","Time":"2017-01-20","Informationen":["Das sind Test-Informationen."],"7b":{"1":{"Stunde":"1 - 2","Fach":"DEU","Raum":"3.309","LehrerIn":"___(statt ___)","Hinweis":"\u00a0","Art":"Vertretung"},"2":{"Stunde":"3 - 4","Fach":"MA","Raum":"3.214","LehrerIn":"___","Hinweis":"\u00a0","Art":"Vertretung"},"3":{"Stunde":"5","Fach":"EN","Raum":"3.202","LehrerIn":"___","Hinweis":"\u00a0","Art":"Ausfall"}},"7a":{"1":{"Stunde":"1 - 2","Fach":"DEU","Raum":"3.309","LehrerIn":"___(statt ___)","Hinweis":"\u00a0","Art":"Vertretung"},"2":{"Stunde":"3 - 4","Fach":"MA","Raum":"3.214","LehrerIn":"___","Hinweis":"\u00a0","Art":"Vertretung"},"3":{"Stunde":"5","Fach":"EN","Raum":"3.202","LehrerIn":"___","Hinweis":"\u00a0","Art":"Ausfall"}},"9a":{"1":{"Stunde":"1 - 2","Fach":"DEU","Raum":"3.309","LehrerIn":"___(statt ___)","Hinweis":"\u00a0","Art":"Vertretung"},"2":{"Stunde":"3 - 4","Fach":"MA","Raum":"3.214","LehrerIn":"___","Hinweis":"\u00a0","Art":"Vertretung"},"3":{"Stunde":"5","Fach":"EN","Raum":"3.202","LehrerIn":"___","Hinweis":"\u00a0","Art":"Ausfall"}}};
updatePlan(json);
document.getElementById('plan').style.display='inline';
document.getElementById('wrong-pswd').style.display='none';*/
var httpreq = new XMLHttpRequest();
httpreq.open("GET", getApiUrl(), true);
httpreq.onload = function(e) {
if (httpreq.readyState === 4) {
if (httpreq.status === 200) {
try {
var responseJSON = JSON.parse(httpreq.responseText);
console.log(responseJSON);
if(noPlanOnline(responseJSON)) {
showById('kein-plan');
} else {
hideById('wrong-pswd');
//plan has to be set visible before calling updatePlan() because
//calculating the correct offset for the plan wouldn't work otherwise
showById('plan');
updatePlan(responseJSON);
finishedParsing();
}
} catch(err) {//wrong password
hideById('plan');
showById('wrong-pswd');
redirect(urlIndexhtml, 2000);
}
} else {
console.error(httpreq.statusText);
}
}
}
httpreq.onerror = function(e) {
console.error(httpreq.statusText);
}
httpreq.send(null);
return httpreq.responseText;
}
function getApiUrl() {
return "http://fbi.gruener-campus-malchow.de/cis/pupilplanapi.php" + getUrlArguments();
}
function getUrlArguments() {
var cert = parameters["cert"];
var dev = parameters["dev"];
var klasse = parameters["klasse"];
var user = parameters["user"];
var arguments = "?cert=" + cert;
if(dev) {
arguments+="&dev=" + dev;
}
if(klasse) {
arguments+="&klasse=" + klasse;
}
if(user) {
arguments+="&user=" + user;
}
return arguments;
}
function finishedParsing() {
if(parameters['user'] === 'foyer') {
startScrolling();
} else {
allClassNames = sortClassNames(allClassNames);
addClassNamesToDropdown(allClassNames);
}
}
function noPlanOnline(json) {
return json[0] === "false";
}
function redirect(url, delay) {
setTimeout(function() {window.location.replace(url);}, delay);
}
function updatePlan(plan) {
updateInfo(plan);
updatePlanPaddingTop(); //style.js
updateClasses(plan);
}
function updateClasses(plan) {
var noClass = ['Informationen', 'Tag', 'Time'];
for (var i = 0; i < plan.length; i++) {
var day = plan[i];
updateBoxDate(day['Tag']);
for (var className in day) {
if (day.hasOwnProperty(className)) {
if (noClass.indexOf(className) === -1) {
var schoolClass = day[className];
updateClass(className, schoolClass);
}
}
}
}
}
function updateClass(className, schoolClass) {
var entryNumbers = [];
for (var entryNumber in schoolClass) {
if (schoolClass.hasOwnProperty(entryNumber)) {
entryNumbers.push(entryNumber);
}
}
// eintragsNummern wie Zahlen sortieren, obwohl sie Strings sind
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
entryNumbers.sort(function (s1, s2) { return parseInt(s1) - parseInt(s2); })
// addiere Eintraege auf
var entries = [];
var lastEntry;
for (var i = 0; i < entryNumbers.length; i += 1) {
var entryNumber = entryNumbers[i];
var entry = schoolClass[entryNumber];
if (isNewEntry(entry)) {
lastEntry = {"Raum":"", "Fach":"", "Hinweis":"", "Art":"", "Stunde":""};
entries.push(lastEntry);
}
lastEntry["Raum"] += entry["Raum"] + " ";
lastEntry["Fach"] += entry["Fach"] + " ";
lastEntry["Hinweis"] += entry["Hinweis"] + " ";
lastEntry["Art"] += entry["Art"] + " ";
lastEntry["Stunde"] += entry["Stunde"] + " ";
}
// update mit addierten Eintraegen
for (var i = 0; i < entries.length; i += 1) {
var entry = entries[i];
updateBox(className,
entry["Raum"],
entry["Fach"],
entry["Stunde"],
entry["Hinweis"],
entry["Art"]);
}
}
var allSpace = new RegExp("^\\s*$");
function isAllSpace(string) {
return allSpace.exec(string) != null;
}
function isNewEntry(eintrag) {
return !isAllSpace(eintrag["Art"]);
}
//https://stackoverflow.com/questions/784539/how-do-i-replace-all-line-breaks-in-a-string-with-br-tags
function removeLineBreaks(string) {
return string.replace(/\r?\n|\r/g, "");
}
function updateInfo(plan) {
var text = '';
for (var i = 0; i < plan.length; i++) {
var day = plan[i];
var date = day['Tag'];
var informations = day['Informationen'];
if (informations!==undefined&&informations!=='') {
if (i > 0) {
text += '\n';
}
text += date + '\n';
for (var j = 0; j < informations.length; j++) {
var info = day['Informationen'][j];
info = removeLineBreaks(info);
text += info;
if(j < informations.length-1) {
text+=', ';
}
}
} else {
hideInfoText();
}
setInfoText(text);
}
}
setParametersFromURL();
updateVertretungsplan();
| removed global array infos
| js/jsonparser.js | removed global array infos | <ide><path>s/jsonparser.js
<ide> var urlPlanhtml = "plan.html";
<ide>
<ide> var parameters = {};
<del>var infos = {};
<ide>
<ide> /**
<ide> reads parameters in URL and adds them to the parameters map |
|
Java | apache-2.0 | 3ddf14307a8e120b872305787f949a67ac260194 | 0 | yingyun001/ovirt-engine,yapengsong/ovirt-engine,eayun/ovirt-engine,zerodengxinchao/ovirt-engine,yapengsong/ovirt-engine,eayun/ovirt-engine,walteryang47/ovirt-engine,eayun/ovirt-engine,OpenUniversity/ovirt-engine,eayun/ovirt-engine,yapengsong/ovirt-engine,yingyun001/ovirt-engine,zerodengxinchao/ovirt-engine,walteryang47/ovirt-engine,zerodengxinchao/ovirt-engine,OpenUniversity/ovirt-engine,zerodengxinchao/ovirt-engine,yingyun001/ovirt-engine,walteryang47/ovirt-engine,halober/ovirt-engine,halober/ovirt-engine,halober/ovirt-engine,yapengsong/ovirt-engine,yingyun001/ovirt-engine,walteryang47/ovirt-engine,walteryang47/ovirt-engine,yapengsong/ovirt-engine,halober/ovirt-engine,eayun/ovirt-engine,yingyun001/ovirt-engine,OpenUniversity/ovirt-engine,OpenUniversity/ovirt-engine,OpenUniversity/ovirt-engine,zerodengxinchao/ovirt-engine | package org.ovirt.engine.core.bll;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.bll.command.utils.StorageDomainSpaceChecker;
import org.ovirt.engine.core.bll.storage.StorageHelperDirector;
import org.ovirt.engine.core.bll.utils.VmDeviceUtils;
import org.ovirt.engine.core.bll.validator.StorageDomainValidator;
import org.ovirt.engine.core.common.businessentities.BaseDisk;
import org.ovirt.engine.core.common.businessentities.Disk;
import org.ovirt.engine.core.common.businessentities.Disk.DiskStorageType;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.DiskImageBase;
import org.ovirt.engine.core.common.businessentities.DiskImageDynamic;
import org.ovirt.engine.core.common.businessentities.DiskLunMapId;
import org.ovirt.engine.core.common.businessentities.ImageStatus;
import org.ovirt.engine.core.common.businessentities.LUNs;
import org.ovirt.engine.core.common.businessentities.LunDisk;
import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotStatus;
import org.ovirt.engine.core.common.businessentities.StoragePoolStatus;
import org.ovirt.engine.core.common.businessentities.StorageType;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VMStatus;
import org.ovirt.engine.core.common.businessentities.VmDeviceId;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.businessentities.VolumeFormat;
import org.ovirt.engine.core.common.businessentities.VolumeType;
import org.ovirt.engine.core.common.businessentities.image_storage_domain_map;
import org.ovirt.engine.core.common.businessentities.StorageDomainStatic;
import org.ovirt.engine.core.common.businessentities.storage_domains;
import org.ovirt.engine.core.common.businessentities.storage_pool;
import org.ovirt.engine.core.common.businessentities.StorageServerConnections;
import org.ovirt.engine.core.common.errors.VdcBLLException;
import org.ovirt.engine.core.common.errors.VdcBllErrors;
import org.ovirt.engine.core.common.utils.ListUtils;
import org.ovirt.engine.core.common.utils.VmDeviceType;
import org.ovirt.engine.core.common.vdscommands.GetImageInfoVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.IrsBaseVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.backendcompat.Path;
import org.ovirt.engine.core.dal.VdcBllMessages;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.utils.log.Log;
import org.ovirt.engine.core.utils.log.LogFactory;
public final class ImagesHandler {
public static final String DISK = "_Disk";
public static final Guid BlankImageTemplateId = new Guid("00000000-0000-0000-0000-000000000000");
public static final String DefaultDriveName = "1";
protected static final Log log = LogFactory.getLog(ImagesHandler.class);
/**
* The following method will find all images and storages where they located for provide template and will fill an
* diskInfoDestinationMap by imageId mapping on active storage id where image is located. The second map is
* mapping of founded storage ids to storage object
* @param template
* @param diskInfoDestinationMap
* @param destStorages
* @param notCheckSize - if we need to perform a size check for storage or not
*/
public static void fillImagesMapBasedOnTemplate(VmTemplate template,
Map<Guid, DiskImage> diskInfoDestinationMap,
Map<Guid, storage_domains> destStorages, boolean notCheckSize) {
List<storage_domains> domains =
DbFacade.getInstance()
.getStorageDomainDao()
.getAllForStoragePool(template.getstorage_pool_id().getValue());
fillImagesMapBasedOnTemplate(template, domains, diskInfoDestinationMap, destStorages, notCheckSize);
}
public static void fillImagesMapBasedOnTemplate(VmTemplate template,
List<storage_domains> domains,
Map<Guid, DiskImage> diskInfoDestinationMap,
Map<Guid, storage_domains> destStorages, boolean notCheckSize) {
Map<Guid, storage_domains> storageDomainsMap = new HashMap<Guid, storage_domains>();
for (storage_domains storageDomain : domains) {
StorageDomainValidator validator = new StorageDomainValidator(storageDomain);
ArrayList<String> messages = new ArrayList<String>();
if (validator.isDomainExistAndActive(messages) && validator.domainIsValidDestination(messages)
&& (notCheckSize || StorageDomainSpaceChecker.isBelowThresholds(storageDomain))) {
storageDomainsMap.put(storageDomain.getId(), storageDomain);
}
}
for (DiskImage image : template.getDiskMap().values()) {
for (Guid storageId : image.getstorage_ids()) {
if (storageDomainsMap.containsKey(storageId)) {
ArrayList<Guid> storageIds = new ArrayList<Guid>();
storageIds.add(storageId);
image.setstorage_ids(storageIds);
diskInfoDestinationMap.put(image.getId(), image);
break;
}
}
}
if (destStorages != null) {
for (DiskImage diskImage : diskInfoDestinationMap.values()) {
Guid storageDomainId = diskImage.getstorage_ids().get(0);
destStorages.put(storageDomainId, storageDomainsMap.get(storageDomainId));
}
}
}
public static boolean setDiskAlias(BaseDisk disk, VM vm) {
if (disk != null) {
String vmName = "";
int count = 1;
if (vm != null) {
vmName = vm.getVmName();
count = vm.getDiskMapCount() + 1;
}
disk.setDiskAlias(getSuggestedDiskAlias(disk, vmName, count));
return true;
} else {
log.errorFormat("Disk object is null");
return false;
}
}
/**
* Suggests an alias for a disk.
* If the disk does not already have an alias, one will be generated for it.
* The generated alias will be formed as prefix_DiskXXX, where XXX is an ordinal.
*
* @param disk
* - The disk that (possibly) requires a new alias
* @param diskPrefix
* - The prefix for the newly generated alias
* @param count
* - The ordinal of disk to create an alias for (first, second, etc.).
* @return The suggested alias
*/
public static String getSuggestedDiskAlias(BaseDisk disk, String diskPrefix, int count) {
String diskAlias;
if (disk == null) {
diskAlias = getDefaultDiskAlias(diskPrefix, DefaultDriveName);
log.warnFormat("Disk object is null, the suggested default disk alias to be used is {0}",
diskAlias);
} else {
diskAlias = disk.getDiskAlias();
if (StringUtils.isEmpty(diskAlias)) {
diskAlias = getDefaultDiskAlias(diskPrefix, String.valueOf(count));
log.infoFormat("Disk alias retrieved from the client is null or empty, the suggested default disk alias to be used is {0}",
diskAlias);
}
}
return diskAlias;
}
public static String getDefaultDiskAlias(String prefix, String suffix) {
return prefix + DISK + suffix;
}
public static Map<Guid, List<DiskImage>> buildStorageToDiskMap(Collection<DiskImage> images,
Map<Guid, DiskImage> diskInfoDestinationMap) {
Map<Guid, List<DiskImage>> storageToDisksMap = new HashMap<Guid, List<DiskImage>>();
for (DiskImage disk : images) {
DiskImage diskImage = diskInfoDestinationMap.get(disk.getId());
Guid storageDomainId = diskImage.getstorage_ids().get(0);
List<DiskImage> diskList = storageToDisksMap.get(storageDomainId);
if (diskList == null) {
diskList = new ArrayList<DiskImage>();
storageToDisksMap.put(storageDomainId, diskList);
}
diskList.add(disk);
}
return storageToDisksMap;
}
/**
* Adds a disk image (Adds image, disk and relevant entities)
*
* @param image
* DiskImage to add
* @param active
* true if the image should be added as active
* @param imageStorageDomainMap
* storage domain map entry to map between the image and its storage domain
*/
public static void addDiskImage(DiskImage image, boolean active, image_storage_domain_map imageStorageDomainMap, Guid vmId) {
try {
addImage(image, active, imageStorageDomainMap);
addDiskToVmIfNotExists(image, vmId);
} catch (RuntimeException ex) {
log.error("Failed adding new disk image and related entities to db", ex);
throw new VdcBLLException(VdcBllErrors.DB, ex);
}
}
/**
* Gets a map of DiskImage IDs to DiskImage objects
*
* @param diskImages
* collection of DiskImage objects to create the map for
* @return map object is the collection is not null
*/
public static Map<Guid, DiskImage> getDiskImagesByIdMap(Collection<DiskImage> diskImages) {
Map<Guid, DiskImage> result = null;
if (diskImages != null) {
result = new HashMap<Guid, DiskImage>();
for (DiskImage diskImage : diskImages) {
result.put(diskImage.getImageId(), diskImage);
}
}
return result;
}
/**
* Adds a disk image (Adds image, disk, and relevant entities , but not VmDevice) This may be useful for Clone VMs,
* where besides adding images it is required to copy all vm devices (VmDeviceUtils.copyVmDevices) from the source
* VM
*
* @param image
* image to add
* @param active
* true if to add as active image
* @param imageStorageDomainMap
* entry of image storagte domain map
*/
public static void addDiskImageWithNoVmDevice(DiskImage image,
boolean active,
image_storage_domain_map imageStorageDomainMap) {
try {
addImage(image, active, imageStorageDomainMap);
addDisk(image);
} catch (RuntimeException ex) {
log.error("Failed adding new disk image and related entities to db", ex);
throw new VdcBLLException(VdcBllErrors.DB, ex);
}
}
/**
* Adds a disk image (Adds image, disk, and relevant entities , but not VmDevice) This may be useful for Clone VMs,
* where besides adding images it is required to copy all vm devices (VmDeviceUtils.copyVmDevices) from the source
* VM
*
* @param image
*/
public static void addDiskImageWithNoVmDevice(DiskImage image) {
addDiskImageWithNoVmDevice(image,
image.getactive(),
new image_storage_domain_map(image.getImageId(), image.getstorage_ids().get(0)));
}
/**
* Adds disk to a VM without creating a VmDevice entry
*
* @param disk
* disk to add
*/
public static void addDisk(BaseDisk disk) {
if (!DbFacade.getInstance().getBaseDiskDao().exists(disk.getId())) {
DbFacade.getInstance().getBaseDiskDao().save(disk);
}
}
/**
* Adds a disk image (Adds image with active flag according to the value in image, using the first storage domain in
* the storage id as entry to the storage domain map)
*
* @param image
* DiskImage to add
*/
public static void addDiskImage(DiskImage image, Guid vmId) {
addDiskImage(image, image.getactive(), new image_storage_domain_map(image.getImageId(), image.getstorage_ids()
.get(0)), vmId);
}
/**
* Add image and related entities to DB (Adds image, disk image dynamic and image storage domain map)
*
* @param image
* the image to add
* @param active
* if true the image will be active
* @param imageStorageDomainMap
* entry of mapping between the storage domain and the image
*/
public static void addImage(DiskImage image, boolean active, image_storage_domain_map imageStorageDomainMap) {
image.setactive(active);
DbFacade.getInstance().getImageDao().save(image.getImage());
DiskImageDynamic diskDynamic = new DiskImageDynamic();
diskDynamic.setId(image.getImageId());
diskDynamic.setactual_size(image.getactual_size());
DbFacade.getInstance().getDiskImageDynamicDao().save(diskDynamic);
if (imageStorageDomainMap != null) {
DbFacade.getInstance().getImageStorageDomainMapDao().save(imageStorageDomainMap);
}
}
/**
* Add disk if it does not exist to a given vm
*
* @param disk
* the disk to add
* @param vmId
* the ID of the vm to add to if the disk does not exist for this VM
*/
public static void addDiskToVmIfNotExists(BaseDisk disk, Guid vmId) {
if (!DbFacade.getInstance().getBaseDiskDao().exists(disk.getId())) {
addDiskToVm(disk, vmId);
}
}
/**
* Adds disk to vm
*
* @param disk
* the disk to add
* @param vmId
* the ID of the VM to add to
*/
public static void addDiskToVm(BaseDisk disk, Guid vmId) {
DbFacade.getInstance().getBaseDiskDao().save(disk);
VmDeviceUtils.addManagedDevice(new VmDeviceId(disk.getId(), vmId),
VmDeviceType.DISK,
VmDeviceType.DISK,
null,
true,
false);
}
/**
* This function was developed especially for GUI needs. It returns a list of all the snapshots of current image of
* a specific VM. If there are two images mapped to same VM, it's assumed that this is a TryBackToImage case and the
* function returns a list of snapshots of inactive images. In this case the parent of the active image appears to
* be trybackfrom image
*
* @param imageId
* @param imageTemplateId
* @return
*/
public static ArrayList<DiskImage> getAllImageSnapshots(Guid imageId, Guid imageTemplateId) {
ArrayList<DiskImage> snapshots = new ArrayList<DiskImage>();
Guid curImage = imageId;
while (!imageTemplateId.equals(curImage) && !curImage.equals(Guid.Empty)) {
DiskImage curDiskImage = DbFacade.getInstance().getDiskImageDao().getSnapshotById(curImage);
snapshots.add(curDiskImage);
curImage = curDiskImage.getParentId();
}
return snapshots;
}
public static String cdPathWindowsToLinux(String windowsPath, Guid storagePoolId) {
return cdPathWindowsToLinux(windowsPath, (String) Backend.getInstance()
.getResourceManager()
.RunVdsCommand(VDSCommandType.IsoPrefix, new IrsBaseVDSCommandParameters(storagePoolId))
.getReturnValue());
}
public static String cdPathWindowsToLinux(String windowsPath, String isoPrefix) {
if (StringUtils.isEmpty(windowsPath)) {
return windowsPath; // empty string is used for 'eject'.
}
String fileName = Path.GetFileName(windowsPath);
return String.format("%1$s/%2$s", isoPrefix, fileName);
}
public static boolean isImagesExists(Iterable<DiskImage> images, Guid storagePoolId, Guid storageDomainId) {
return isImagesExists(images, storagePoolId, storageDomainId, new ArrayList<DiskImage>());
}
private static boolean isImagesExists(Iterable<DiskImage> images, Guid storagePoolId, Guid domainId,
ArrayList<DiskImage> irsImages) {
boolean returnValue = true;
for (DiskImage image : images) {
Guid storageDomainId = !Guid.Empty.equals(domainId) ? domainId : image.getstorage_ids().get(0);
DiskImage fromIrs = isImageExist(storagePoolId, storageDomainId, image);
if (fromIrs == null) {
returnValue = false;
break;
} else {
irsImages.add(fromIrs);
}
}
return returnValue;
}
private static DiskImage isImageExist(Guid storagePoolId,
Guid domainId,
DiskImage image) {
DiskImage fromIrs = null;
try {
Guid storageDomainId =
image.getstorage_ids() != null && !image.getstorage_ids().isEmpty() ? image.getstorage_ids()
.get(0) : domainId;
Guid imageGroupId = image.getId() != null ? image.getId() : Guid.Empty;
fromIrs = (DiskImage) Backend
.getInstance()
.getResourceManager()
.RunVdsCommand(
VDSCommandType.GetImageInfo,
new GetImageInfoVDSCommandParameters(storagePoolId, storageDomainId, imageGroupId,
image.getImageId())).getReturnValue();
} catch (Exception e) {
}
return fromIrs;
}
public static boolean isVmInPreview(Guid vmId) {
return DbFacade.getInstance().getSnapshotDao().exists(vmId, SnapshotStatus.IN_PREVIEW);
}
public static boolean CheckImageConfiguration(StorageDomainStatic storageDomain,
DiskImageBase diskInfo, List<String> messages) {
boolean result = true;
if ((diskInfo.getvolume_type() == VolumeType.Preallocated && diskInfo.getvolume_format() == VolumeFormat.COW)
|| ((storageDomain.getstorage_type() == StorageType.FCP || storageDomain.getstorage_type() == StorageType.ISCSI) && (diskInfo
.getvolume_type() == VolumeType.Sparse && diskInfo.getvolume_format() == VolumeFormat.RAW))
|| (diskInfo.getvolume_format() == VolumeFormat.Unassigned || diskInfo.getvolume_type() == VolumeType.Unassigned)) {
// not supported
result = false;
messages.add(VdcBllMessages.ACTION_TYPE_FAILED_DISK_CONFIGURATION_NOT_SUPPORTED.toString());
}
return result;
}
public static boolean CheckImagesConfiguration(Guid storageDomainId,
Collection<? extends Disk> disksConfigList,
List<String> messages) {
boolean result = true;
StorageDomainStatic storageDomain = DbFacade.getInstance().getStorageDomainStaticDao().get(storageDomainId);
for (Disk diskInfo : disksConfigList) {
if (DiskStorageType.IMAGE == diskInfo.getDiskStorageType()) {
result = CheckImageConfiguration(storageDomain, (DiskImage) diskInfo, messages);
}
if (!result)
break;
}
return result;
}
public static boolean PerformImagesChecks(VM vm,
List<String> messages,
Guid storagePoolId,
Guid storageDomainId,
boolean diskSpaceCheck,
boolean checkImagesLocked,
boolean checkImagesIllegal,
boolean checkImagesExist,
boolean checkVmInPreview,
boolean checkVmIsDown,
boolean checkStorageDomain,
boolean checkIsValid, Collection diskImageList) {
boolean returnValue = true;;
if (checkIsValid) {
storage_pool pool = DbFacade.getInstance().getStoragePoolDao().get(
storagePoolId);
if (pool == null || pool.getstatus() != StoragePoolStatus.Up) {
returnValue = false;
ListUtils.nullSafeAdd(messages, VdcBllMessages.ACTION_TYPE_FAILED_IMAGE_REPOSITORY_NOT_FOUND.toString());
}
}
List<DiskImage> images = getImages(vm, diskImageList);
if (returnValue && checkImagesLocked) {
returnValue = checkImagesLocked(vm, messages, images);
}
if (returnValue && checkVmIsDown && vm.getStatus() != VMStatus.Down) {
returnValue = false;
ListUtils.nullSafeAdd(messages, VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_NOT_DOWN.toString());
}
if (returnValue && checkVmInPreview && isVmInPreview(vm.getId())) {
returnValue = false;
ListUtils.nullSafeAdd(messages, VdcBllMessages.ACTION_TYPE_FAILED_VM_IN_PREVIEW.toString());
}
if (returnValue && checkIsValid) {
if (images.size() > 0) {
returnValue = returnValue &&
checkDiskImages(messages,
storagePoolId,
storageDomainId,
diskSpaceCheck,
checkImagesIllegal,
checkImagesExist,
checkStorageDomain,
vm,
images);
} else if (checkImagesExist) {
returnValue = false;
ListUtils.nullSafeAdd(messages, VdcBllMessages.ACTION_TYPE_FAILED_VM_HAS_NO_DISKS.toString());
}
}
return returnValue;
}
public static boolean checkImagesLocked(VM vm, List<String> messages) {
return checkImagesLocked(vm, messages, getImages(vm, null));
}
private static boolean checkImagesLocked(VM vm, List<String> messages, List<DiskImage> images) {
boolean returnValue = true;
List<String> lockedDisksAliases = new ArrayList<String>();
for (DiskImage diskImage : images) {
if (diskImage.getimageStatus() == ImageStatus.LOCKED) {
lockedDisksAliases.add(diskImage.getDiskAlias());
returnValue = false;
}
}
if (lockedDisksAliases.size() > 0) {
ListUtils.nullSafeAdd(messages, VdcBllMessages.ACTION_TYPE_FAILED_DISKS_LOCKED.toString());
ListUtils.nullSafeAdd(messages,
String.format("$%1$s %2$s", "diskAliases", StringUtils.join(lockedDisksAliases, ", ")));
}
if (returnValue && vm.getStatus() == VMStatus.ImageLocked) {
ListUtils.nullSafeAdd(messages, VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_LOCKED.toString());
returnValue = false;
}
return returnValue;
}
private static List<DiskImage> getImages(VM vm, Collection<Disk> diskImageList) {
if (diskImageList == null) {
return filterImageDisks(DbFacade.getInstance().getDiskDao().getAllForVm(vm.getId()), true, false);
} else {
return filterImageDisks(diskImageList, true, false);
}
}
private static boolean checkDiskImages(List<String> messages,
Guid storagePoolId,
Guid storageDomainId,
boolean diskSpaceCheck,
boolean checkImagesIllegal,
boolean checkImagesExist,
boolean checkStorageDomain,
VM vm,
List<DiskImage> images) {
boolean returnValue = true;
ArrayList<DiskImage> irsImages = new ArrayList<DiskImage>();
if (diskSpaceCheck || checkStorageDomain) {
Set<Guid> domainsIds = new HashSet<Guid>();
if (!Guid.Empty.equals(storageDomainId)) {
domainsIds.add(storageDomainId);
} else {
for (DiskImage image : images) {
domainsIds.add(image.getstorage_ids().get(0));
}
}
for (Guid domainId : domainsIds) {
storage_domains domain = DbFacade.getInstance().getStorageDomainDao().getForStoragePool(
domainId, storagePoolId);
if (checkStorageDomain) {
StorageDomainValidator storageDomainValidator =
new StorageDomainValidator(domain);
returnValue = storageDomainValidator.isDomainExistAndActive(messages);
if (!returnValue) {
break;
}
}
if (diskSpaceCheck && returnValue && !StorageDomainSpaceChecker.isBelowThresholds(domain)) {
returnValue = false;
ListUtils.nullSafeAdd(messages, VdcBllMessages.ACTION_TYPE_FAILED_DISK_SPACE_LOW.toString());
break;
}
}
}
if (returnValue && checkImagesExist) {
boolean isImagesExist = isImagesExists(images, storagePoolId, storageDomainId, irsImages);
if (!isImagesExist) {
returnValue = false;
ListUtils.nullSafeAdd(messages, VdcBllMessages.ACTION_TYPE_FAILED_VM_IMAGE_DOES_NOT_EXIST.toString());
}
}
if (returnValue && checkImagesIllegal) {
returnValue = CheckImagesLegality(messages, images, vm, irsImages);
}
return returnValue;
}
private static boolean CheckImagesLegality(List<String> messages,
List<DiskImage> images, VM vm, List<DiskImage> irsImages) {
boolean returnValue = true;
if (vm.getStatus() == VMStatus.ImageIllegal) {
returnValue = false;
ListUtils.nullSafeAdd(messages, VdcBllMessages.ACTION_TYPE_FAILED_VM_IMAGE_IS_ILLEGAL.toString());
} else {
int i = 0;
for (DiskImage diskImage : images) {
if (diskImage != null) {
DiskImage image = irsImages.get(i++);
if (image.getimageStatus() != ImageStatus.OK) {
diskImage.setimageStatus(image.getimageStatus());
DbFacade.getInstance().getImageDao().update(diskImage.getImage());
returnValue = false;
ListUtils.nullSafeAdd(messages,
VdcBllMessages.ACTION_TYPE_FAILED_VM_IMAGE_IS_ILLEGAL.toString());
break;
}
}
}
}
return returnValue;
}
public static void fillImagesBySnapshots(VM vm) {
for (Disk disk : vm.getDiskMap().values()) {
if (disk.getDiskStorageType() == DiskStorageType.IMAGE) {
DiskImage diskImage = (DiskImage) disk;
diskImage.getSnapshots().addAll(
ImagesHandler.getAllImageSnapshots(diskImage.getImageId(),
diskImage.getit_guid()));
}
}
}
/**
* Filter image disks by attributes.
* @param listOfDisks - The list of disks to be filtered.
* @param filterNotShareableDisks - Indication whether to filter disks which are not shareable.
* @param filterAllowSnapshotDisks - Indication whether to filter disks which are allowed to be snapshot.
* @return - List filtered of disk images.
*/
public static List<DiskImage> filterImageDisks(Collection<Disk> listOfDisks,
boolean filterNotShareableDisks,
boolean filterAllowSnapshotDisks) {
List<DiskImage> diskImages = new ArrayList<DiskImage>();
for (Disk disk : listOfDisks) {
if ((!filterNotShareableDisks || !disk.isShareable())
&& disk.getDiskStorageType() == DiskStorageType.IMAGE &&
(!filterAllowSnapshotDisks || disk.isAllowSnapshot())) {
diskImages.add((DiskImage) disk);
}
}
return diskImages;
}
public static List<LunDisk> filterDiskBasedOnLuns(Collection<Disk> listOfDisks) {
List<LunDisk> lunDisks = new ArrayList<LunDisk>();
for (Disk disk : listOfDisks) {
if (disk.getDiskStorageType() == DiskStorageType.LUN) {
lunDisks.add((LunDisk) disk);
}
}
return lunDisks;
}
public static void removeDiskImage(DiskImage diskImage, Guid vmId) {
try {
removeDiskFromVm(vmId, diskImage.getId());
removeImage(diskImage);
} catch (RuntimeException ex) {
log.error("Failed adding new disk image and related entities to db", ex);
throw new VdcBLLException(VdcBllErrors.DB, ex);
}
}
public static void removeLunDisk(LunDisk lunDisk) {
DbFacade.getInstance()
.getVmDeviceDao()
.remove(new VmDeviceId(lunDisk.getId(),
null));
LUNs lun = lunDisk.getLun();
DbFacade.getInstance()
.getDiskLunMapDao()
.remove(new DiskLunMapId(lunDisk.getId(), lun.getLUN_id()));
DbFacade.getInstance().getBaseDiskDao().remove(lunDisk.getId());
lun.setLunConnections(new ArrayList<StorageServerConnections>(DbFacade.getInstance()
.getStorageServerConnectionDao()
.getAllForLun(lun.getLUN_id())));
if (!lun.getLunConnections().isEmpty()) {
StorageHelperDirector.getInstance().getItem(
lun.getLunConnections().get(0).getstorage_type()).removeLun(lun);
} else {
// if there are no connections then the lun is fcp.
StorageHelperDirector.getInstance().getItem(StorageType.FCP).removeLun(lun);
}
}
public static void removeImage(DiskImage diskImage) {
DbFacade.getInstance()
.getImageStorageDomainMapDao()
.remove(diskImage.getImageId());
DbFacade.getInstance().getDiskImageDynamicDao().remove(diskImage.getImageId());
DbFacade.getInstance().getImageDao().remove(diskImage.getImageId());
}
public static void removeDiskFromVm(Guid vmGuid, Guid diskId) {
DbFacade.getInstance().getVmDeviceDao().remove(new VmDeviceId(diskId, vmGuid));
DbFacade.getInstance().getBaseDiskDao().remove(diskId);
}
public static void updateImageStatus(Guid imageId, ImageStatus imageStatus) {
DbFacade.getInstance().getImageDao().updateStatus(imageId, imageStatus);
}
}
| backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/ImagesHandler.java | package org.ovirt.engine.core.bll;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.bll.command.utils.StorageDomainSpaceChecker;
import org.ovirt.engine.core.bll.storage.StorageHelperDirector;
import org.ovirt.engine.core.bll.utils.VmDeviceUtils;
import org.ovirt.engine.core.bll.validator.StorageDomainValidator;
import org.ovirt.engine.core.common.businessentities.BaseDisk;
import org.ovirt.engine.core.common.businessentities.Disk;
import org.ovirt.engine.core.common.businessentities.Disk.DiskStorageType;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.DiskImageBase;
import org.ovirt.engine.core.common.businessentities.DiskImageDynamic;
import org.ovirt.engine.core.common.businessentities.DiskLunMapId;
import org.ovirt.engine.core.common.businessentities.ImageStatus;
import org.ovirt.engine.core.common.businessentities.LUNs;
import org.ovirt.engine.core.common.businessentities.LunDisk;
import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotStatus;
import org.ovirt.engine.core.common.businessentities.StoragePoolStatus;
import org.ovirt.engine.core.common.businessentities.StorageType;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VMStatus;
import org.ovirt.engine.core.common.businessentities.VmDeviceId;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.businessentities.VolumeFormat;
import org.ovirt.engine.core.common.businessentities.VolumeType;
import org.ovirt.engine.core.common.businessentities.image_storage_domain_map;
import org.ovirt.engine.core.common.businessentities.StorageDomainStatic;
import org.ovirt.engine.core.common.businessentities.storage_domains;
import org.ovirt.engine.core.common.businessentities.storage_pool;
import org.ovirt.engine.core.common.businessentities.StorageServerConnections;
import org.ovirt.engine.core.common.errors.VdcBLLException;
import org.ovirt.engine.core.common.errors.VdcBllErrors;
import org.ovirt.engine.core.common.utils.ListUtils;
import org.ovirt.engine.core.common.utils.VmDeviceType;
import org.ovirt.engine.core.common.vdscommands.GetImageInfoVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.IrsBaseVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.backendcompat.Path;
import org.ovirt.engine.core.dal.VdcBllMessages;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.utils.log.Log;
import org.ovirt.engine.core.utils.log.LogFactory;
public final class ImagesHandler {
public static final String DISK = "_Disk";
public static final Guid BlankImageTemplateId = new Guid("00000000-0000-0000-0000-000000000000");
public static final String DefaultDriveName = "1";
protected static final Log log = LogFactory.getLog(ImagesHandler.class);
/**
* The following method will find all images and storages where they located for provide template and will fill an
* diskInfoDestinationMap by imageId mapping on active storage id where image is located. The second map is
* mapping of founded storage ids to storage object
* @param template
* @param diskInfoDestinationMap
* @param destStorages
* @param notCheckSize - if we need to perform a size check for storage or not
*/
public static void fillImagesMapBasedOnTemplate(VmTemplate template,
Map<Guid, DiskImage> diskInfoDestinationMap,
Map<Guid, storage_domains> destStorages, boolean notCheckSize) {
List<storage_domains> domains =
DbFacade.getInstance()
.getStorageDomainDao()
.getAllForStoragePool(template.getstorage_pool_id().getValue());
fillImagesMapBasedOnTemplate(template, domains, diskInfoDestinationMap, destStorages, notCheckSize);
}
public static void fillImagesMapBasedOnTemplate(VmTemplate template,
List<storage_domains> domains,
Map<Guid, DiskImage> diskInfoDestinationMap,
Map<Guid, storage_domains> destStorages, boolean notCheckSize) {
Map<Guid, storage_domains> storageDomainsMap = new HashMap<Guid, storage_domains>();
for (storage_domains storageDomain : domains) {
StorageDomainValidator validator = new StorageDomainValidator(storageDomain);
ArrayList<String> messages = new ArrayList<String>();
if (validator.isDomainExistAndActive(messages) && validator.domainIsValidDestination(messages)
&& (notCheckSize || StorageDomainSpaceChecker.isBelowThresholds(storageDomain))) {
storageDomainsMap.put(storageDomain.getId(), storageDomain);
}
}
for (DiskImage image : template.getDiskMap().values()) {
for (Guid storageId : image.getstorage_ids()) {
if (storageDomainsMap.containsKey(storageId)) {
ArrayList<Guid> storageIds = new ArrayList<Guid>();
storageIds.add(storageId);
image.setstorage_ids(storageIds);
diskInfoDestinationMap.put(image.getId(), image);
break;
}
}
}
if (destStorages != null) {
for (DiskImage diskImage : diskInfoDestinationMap.values()) {
Guid storageDomainId = diskImage.getstorage_ids().get(0);
destStorages.put(storageDomainId, storageDomainsMap.get(storageDomainId));
}
}
}
public static boolean setDiskAlias(BaseDisk disk, VM vm) {
if (disk != null) {
String vmName = "";
int count = 1;
if (vm != null) {
vmName = vm.getVmName();
count = vm.getDiskMapCount() + 1;
}
disk.setDiskAlias(getSuggestedDiskAlias(disk, vmName, count));
return true;
} else {
log.errorFormat("Disk object is null");
return false;
}
}
/**
* Suggests an alias for a disk.
* If the disk does not already have an alias, one will be generated for it.
* The generated alias will be formed as prefix_DiskXXX, where XXX is an ordinal.
*
* @param disk
* - The disk that (possibly) requires a new alias
* @param diskPrefix
* - The prefix for the newly generated alias
* @param count
* - The ordinal of disk to create an alias for (first, second, etc.).
* @return The suggested alias
*/
public static String getSuggestedDiskAlias(BaseDisk disk, String diskPrefix, int count) {
String diskAlias;
if (disk == null) {
diskAlias = getDefaultDiskAlias(diskPrefix, DefaultDriveName);
log.warnFormat("Disk object is null, the suggested default disk alias to be used is {0}",
diskAlias);
} else {
diskAlias = disk.getDiskAlias();
if (StringUtils.isEmpty(diskAlias)) {
diskAlias = getDefaultDiskAlias(diskPrefix, String.valueOf(count));
log.infoFormat("Disk alias retrieved from the client is null or empty, the suggested default disk alias to be used is {0}",
diskAlias);
}
}
return diskAlias;
}
public static String getDefaultDiskAlias(String prefix, String suffix) {
return prefix + DISK + suffix;
}
public static Map<Guid, List<DiskImage>> buildStorageToDiskMap(Collection<DiskImage> images,
Map<Guid, DiskImage> diskInfoDestinationMap) {
Map<Guid, List<DiskImage>> storageToDisksMap = new HashMap<Guid, List<DiskImage>>();
for (DiskImage disk : images) {
DiskImage diskImage = diskInfoDestinationMap.get(disk.getId());
Guid storageDomainId = diskImage.getstorage_ids().get(0);
List<DiskImage> diskList = storageToDisksMap.get(storageDomainId);
if (diskList == null) {
diskList = new ArrayList<DiskImage>();
storageToDisksMap.put(storageDomainId, diskList);
}
diskList.add(disk);
}
return storageToDisksMap;
}
/**
* Adds a disk image (Adds image, disk and relevant entities)
*
* @param image
* DiskImage to add
* @param active
* true if the image should be added as active
* @param imageStorageDomainMap
* storage domain map entry to map between the image and its storage domain
*/
public static void addDiskImage(DiskImage image, boolean active, image_storage_domain_map imageStorageDomainMap, Guid vmId) {
try {
addImage(image, active, imageStorageDomainMap);
addDiskToVmIfNotExists(image, vmId);
} catch (RuntimeException ex) {
log.error("Failed adding new disk image and related entities to db", ex);
throw new VdcBLLException(VdcBllErrors.DB, ex);
}
}
/**
* Gets a map of DiskImage IDs to DiskImage objects
*
* @param diskImages
* collection of DiskImage objects to create the map for
* @return map object is the collection is not null
*/
public static Map<Guid, DiskImage> getDiskImagesByIdMap(Collection<DiskImage> diskImages) {
Map<Guid, DiskImage> result = null;
if (diskImages != null) {
result = new HashMap<Guid, DiskImage>();
for (DiskImage diskImage : diskImages) {
result.put(diskImage.getImageId(), diskImage);
}
}
return result;
}
/**
* Adds a disk image (Adds image, disk, and relevant entities , but not VmDevice) This may be useful for Clone VMs,
* where besides adding images it is required to copy all vm devices (VmDeviceUtils.copyVmDevices) from the source
* VM
*
* @param image
* image to add
* @param active
* true if to add as active image
* @param imageStorageDomainMap
* entry of image storagte domain map
*/
public static void addDiskImageWithNoVmDevice(DiskImage image,
boolean active,
image_storage_domain_map imageStorageDomainMap) {
try {
addImage(image, active, imageStorageDomainMap);
addDisk(image);
} catch (RuntimeException ex) {
log.error("Failed adding new disk image and related entities to db", ex);
throw new VdcBLLException(VdcBllErrors.DB, ex);
}
}
/**
* Adds a disk image (Adds image, disk, and relevant entities , but not VmDevice) This may be useful for Clone VMs,
* where besides adding images it is required to copy all vm devices (VmDeviceUtils.copyVmDevices) from the source
* VM
*
* @param image
* @param active
* @param imageStorageDomainMap
*/
public static void addDiskImageWithNoVmDevice(DiskImage image) {
addDiskImageWithNoVmDevice(image,
image.getactive(),
new image_storage_domain_map(image.getImageId(), image.getstorage_ids().get(0)));
}
/**
* Adds disk to a VM without creating a VmDevice entry
*
* @param disk
* disk to add
* @param vmId
* ID of the VM the disk will be associated with
*/
public static void addDisk(BaseDisk disk) {
if (!DbFacade.getInstance().getBaseDiskDao().exists(disk.getId())) {
DbFacade.getInstance().getBaseDiskDao().save(disk);
}
}
/**
* Adds a disk image (Adds image with active flag according to the value in image, using the first storage domain in
* the storage id as entry to the storage domain map)
*
* @param image
* DiskImage to add
*/
public static void addDiskImage(DiskImage image, Guid vmId) {
addDiskImage(image, image.getactive(), new image_storage_domain_map(image.getImageId(), image.getstorage_ids()
.get(0)), vmId);
}
/**
* Add image and related entities to DB (Adds image, disk image dynamic and image storage domain map)
*
* @param image
* the image to add
* @param active
* if true the image will be active
* @param imageStorageDomainMap
* entry of mapping between the storage domain and the image
*/
public static void addImage(DiskImage image, boolean active, image_storage_domain_map imageStorageDomainMap) {
image.setactive(active);
DbFacade.getInstance().getImageDao().save(image.getImage());
DiskImageDynamic diskDynamic = new DiskImageDynamic();
diskDynamic.setId(image.getImageId());
diskDynamic.setactual_size(image.getactual_size());
DbFacade.getInstance().getDiskImageDynamicDao().save(diskDynamic);
if (imageStorageDomainMap != null) {
DbFacade.getInstance().getImageStorageDomainMapDao().save(imageStorageDomainMap);
}
}
/**
* Add disk if it does not exist to a given vm
*
* @param disk
* the disk to add
* @param vmId
* the ID of the vm to add to if the disk does not exist for this VM
*/
public static void addDiskToVmIfNotExists(BaseDisk disk, Guid vmId) {
if (!DbFacade.getInstance().getBaseDiskDao().exists(disk.getId())) {
addDiskToVm(disk, vmId);
}
}
/**
* Adds disk to vm
*
* @param disk
* the disk to add
* @param vmId
* the ID of the VM to add to
*/
public static void addDiskToVm(BaseDisk disk, Guid vmId) {
DbFacade.getInstance().getBaseDiskDao().save(disk);
VmDeviceUtils.addManagedDevice(new VmDeviceId(disk.getId(), vmId),
VmDeviceType.DISK,
VmDeviceType.DISK,
null,
true,
false);
}
/**
* This function was developed especially for GUI needs. It returns a list of all the snapshots of current image of
* a specific VM. If there are two images mapped to same VM, it's assumed that this is a TryBackToImage case and the
* function returns a list of snapshots of inactive images. In this case the parent of the active image appears to
* be trybackfrom image
*
* @param imageId
* @param imageTemplateId
* @return
*/
public static ArrayList<DiskImage> getAllImageSnapshots(Guid imageId, Guid imageTemplateId) {
ArrayList<DiskImage> snapshots = new ArrayList<DiskImage>();
Guid curImage = imageId;
while (!imageTemplateId.equals(curImage) && !curImage.equals(Guid.Empty)) {
DiskImage curDiskImage = DbFacade.getInstance().getDiskImageDao().getSnapshotById(curImage);
snapshots.add(curDiskImage);
curImage = curDiskImage.getParentId();
}
return snapshots;
}
public static String cdPathWindowsToLinux(String windowsPath, Guid storagePoolId) {
return cdPathWindowsToLinux(windowsPath, (String) Backend.getInstance()
.getResourceManager()
.RunVdsCommand(VDSCommandType.IsoPrefix, new IrsBaseVDSCommandParameters(storagePoolId))
.getReturnValue());
}
public static String cdPathWindowsToLinux(String windowsPath, String isoPrefix) {
if (StringUtils.isEmpty(windowsPath)) {
return windowsPath; // empty string is used for 'eject'.
}
String fileName = Path.GetFileName(windowsPath);
return String.format("%1$s/%2$s", isoPrefix, fileName);
}
public static boolean isImagesExists(Iterable<DiskImage> images, Guid storagePoolId, Guid storageDomainId) {
return isImagesExists(images, storagePoolId, storageDomainId, new ArrayList<DiskImage>());
}
private static boolean isImagesExists(Iterable<DiskImage> images, Guid storagePoolId, Guid domainId,
ArrayList<DiskImage> irsImages) {
boolean returnValue = true;
for (DiskImage image : images) {
Guid storageDomainId = !Guid.Empty.equals(domainId) ? domainId : image.getstorage_ids().get(0);
DiskImage fromIrs = isImageExist(storagePoolId, storageDomainId, image);
if (fromIrs == null) {
returnValue = false;
break;
} else {
irsImages.add(fromIrs);
}
}
return returnValue;
}
private static DiskImage isImageExist(Guid storagePoolId,
Guid domainId,
DiskImage image) {
DiskImage fromIrs = null;
try {
Guid storageDomainId =
image.getstorage_ids() != null && !image.getstorage_ids().isEmpty() ? image.getstorage_ids()
.get(0) : domainId;
Guid imageGroupId = image.getId() != null ? image.getId() : Guid.Empty;
fromIrs = (DiskImage) Backend
.getInstance()
.getResourceManager()
.RunVdsCommand(
VDSCommandType.GetImageInfo,
new GetImageInfoVDSCommandParameters(storagePoolId, storageDomainId, imageGroupId,
image.getImageId())).getReturnValue();
} catch (Exception e) {
}
return fromIrs;
}
public static boolean isVmInPreview(Guid vmId) {
return DbFacade.getInstance().getSnapshotDao().exists(vmId, SnapshotStatus.IN_PREVIEW);
}
public static boolean CheckImageConfiguration(StorageDomainStatic storageDomain,
DiskImageBase diskInfo, List<String> messages) {
boolean result = true;
if ((diskInfo.getvolume_type() == VolumeType.Preallocated && diskInfo.getvolume_format() == VolumeFormat.COW)
|| ((storageDomain.getstorage_type() == StorageType.FCP || storageDomain.getstorage_type() == StorageType.ISCSI) && (diskInfo
.getvolume_type() == VolumeType.Sparse && diskInfo.getvolume_format() == VolumeFormat.RAW))
|| (diskInfo.getvolume_format() == VolumeFormat.Unassigned || diskInfo.getvolume_type() == VolumeType.Unassigned)) {
// not supported
result = false;
messages.add(VdcBllMessages.ACTION_TYPE_FAILED_DISK_CONFIGURATION_NOT_SUPPORTED.toString());
}
return result;
}
public static boolean CheckImagesConfiguration(Guid storageDomainId,
Collection<? extends Disk> disksConfigList,
List<String> messages) {
boolean result = true;
StorageDomainStatic storageDomain = DbFacade.getInstance().getStorageDomainStaticDao().get(storageDomainId);
for (Disk diskInfo : disksConfigList) {
if (DiskStorageType.IMAGE == diskInfo.getDiskStorageType()) {
result = CheckImageConfiguration(storageDomain, (DiskImage) diskInfo, messages);
}
if (!result)
break;
}
return result;
}
public static boolean PerformImagesChecks(VM vm,
List<String> messages,
Guid storagePoolId,
Guid storageDomainId,
boolean diskSpaceCheck,
boolean checkImagesLocked,
boolean checkImagesIllegal,
boolean checkImagesExist,
boolean checkVmInPreview,
boolean checkVmIsDown,
boolean checkStorageDomain,
boolean checkIsValid, Collection diskImageList) {
boolean returnValue = true;;
if (checkIsValid) {
storage_pool pool = DbFacade.getInstance().getStoragePoolDao().get(
storagePoolId);
if (pool == null || pool.getstatus() != StoragePoolStatus.Up) {
returnValue = false;
ListUtils.nullSafeAdd(messages, VdcBllMessages.ACTION_TYPE_FAILED_IMAGE_REPOSITORY_NOT_FOUND.toString());
}
}
List<DiskImage> images = getImages(vm, diskImageList);
if (returnValue && checkImagesLocked) {
returnValue = checkImagesLocked(vm, messages, images);
}
if (returnValue && checkVmIsDown && vm.getStatus() != VMStatus.Down) {
returnValue = false;
ListUtils.nullSafeAdd(messages, VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_NOT_DOWN.toString());
}
if (returnValue && checkVmInPreview && isVmInPreview(vm.getId())) {
returnValue = false;
ListUtils.nullSafeAdd(messages, VdcBllMessages.ACTION_TYPE_FAILED_VM_IN_PREVIEW.toString());
}
if (returnValue && checkIsValid) {
if (images.size() > 0) {
returnValue = returnValue &&
checkDiskImages(messages,
storagePoolId,
storageDomainId,
diskSpaceCheck,
checkImagesIllegal,
checkImagesExist,
checkStorageDomain,
vm,
images);
} else if (checkImagesExist) {
returnValue = false;
ListUtils.nullSafeAdd(messages, VdcBllMessages.ACTION_TYPE_FAILED_VM_HAS_NO_DISKS.toString());
}
}
return returnValue;
}
public static boolean checkImagesLocked(VM vm, List<String> messages) {
return checkImagesLocked(vm, messages, getImages(vm, null));
}
private static boolean checkImagesLocked(VM vm, List<String> messages, List<DiskImage> images) {
boolean returnValue = true;
List<String> lockedDisksAliases = new ArrayList<String>();
for (DiskImage diskImage : images) {
if (diskImage.getimageStatus() == ImageStatus.LOCKED) {
lockedDisksAliases.add(diskImage.getDiskAlias());
returnValue = false;
}
}
if (lockedDisksAliases.size() > 0) {
ListUtils.nullSafeAdd(messages, VdcBllMessages.ACTION_TYPE_FAILED_DISKS_LOCKED.toString());
ListUtils.nullSafeAdd(messages,
String.format("$%1$s %2$s", "diskAliases", StringUtils.join(lockedDisksAliases, ", ")));
}
if (returnValue && vm.getStatus() == VMStatus.ImageLocked) {
ListUtils.nullSafeAdd(messages, VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_LOCKED.toString());
returnValue = false;
}
return returnValue;
}
private static List<DiskImage> getImages(VM vm, Collection<Disk> diskImageList) {
if (diskImageList == null) {
return filterImageDisks(DbFacade.getInstance().getDiskDao().getAllForVm(vm.getId()), true, false);
} else {
return filterImageDisks(diskImageList, true, false);
}
}
private static boolean checkDiskImages(List<String> messages,
Guid storagePoolId,
Guid storageDomainId,
boolean diskSpaceCheck,
boolean checkImagesIllegal,
boolean checkImagesExist,
boolean checkStorageDomain,
VM vm,
List<DiskImage> images) {
boolean returnValue = true;
ArrayList<DiskImage> irsImages = new ArrayList<DiskImage>();
if (diskSpaceCheck || checkStorageDomain) {
Set<Guid> domainsIds = new HashSet<Guid>();
if (!Guid.Empty.equals(storageDomainId)) {
domainsIds.add(storageDomainId);
} else {
for (DiskImage image : images) {
domainsIds.add(image.getstorage_ids().get(0));
}
}
for (Guid domainId : domainsIds) {
storage_domains domain = DbFacade.getInstance().getStorageDomainDao().getForStoragePool(
domainId, storagePoolId);
if (checkStorageDomain) {
StorageDomainValidator storageDomainValidator =
new StorageDomainValidator(domain);
returnValue = storageDomainValidator.isDomainExistAndActive(messages);
if (!returnValue) {
break;
}
}
if (diskSpaceCheck && returnValue && !StorageDomainSpaceChecker.isBelowThresholds(domain)) {
returnValue = false;
ListUtils.nullSafeAdd(messages, VdcBllMessages.ACTION_TYPE_FAILED_DISK_SPACE_LOW.toString());
break;
}
}
}
if (returnValue && checkImagesExist) {
boolean isImagesExist = isImagesExists(images, storagePoolId, storageDomainId, irsImages);
if (!isImagesExist) {
returnValue = false;
ListUtils.nullSafeAdd(messages, VdcBllMessages.ACTION_TYPE_FAILED_VM_IMAGE_DOES_NOT_EXIST.toString());
}
}
if (returnValue && checkImagesIllegal) {
returnValue = CheckImagesLegality(messages, images, vm, irsImages);
}
return returnValue;
}
private static boolean CheckImagesLegality(List<String> messages,
List<DiskImage> images, VM vm, List<DiskImage> irsImages) {
boolean returnValue = true;
if (vm.getStatus() == VMStatus.ImageIllegal) {
returnValue = false;
ListUtils.nullSafeAdd(messages, VdcBllMessages.ACTION_TYPE_FAILED_VM_IMAGE_IS_ILLEGAL.toString());
} else {
int i = 0;
for (DiskImage diskImage : images) {
if (diskImage != null) {
DiskImage image = irsImages.get(i++);
if (image.getimageStatus() != ImageStatus.OK) {
diskImage.setimageStatus(image.getimageStatus());
DbFacade.getInstance().getImageDao().update(diskImage.getImage());
returnValue = false;
ListUtils.nullSafeAdd(messages,
VdcBllMessages.ACTION_TYPE_FAILED_VM_IMAGE_IS_ILLEGAL.toString());
break;
}
}
}
}
return returnValue;
}
public static void fillImagesBySnapshots(VM vm) {
for (Disk disk : vm.getDiskMap().values()) {
if (disk.getDiskStorageType() == DiskStorageType.IMAGE) {
DiskImage diskImage = (DiskImage) disk;
diskImage.getSnapshots().addAll(
ImagesHandler.getAllImageSnapshots(diskImage.getImageId(),
diskImage.getit_guid()));
}
}
}
/**
* Filter image disks by attributes.
* @param listOfDisks - The list of disks to be filtered.
* @param filterNotShareableDisks - Indication whether to filter disks which are not shareable.
* @param filterAllowSnapshot - Indication whether to filter disks which are allowed to be snapshot.
* @return - List filtered of disk images.
*/
public static List<DiskImage> filterImageDisks(Collection<Disk> listOfDisks,
boolean filterNotShareableDisks,
boolean filterAllowSnapshotDisks) {
List<DiskImage> diskImages = new ArrayList<DiskImage>();
for (Disk disk : listOfDisks) {
if ((!filterNotShareableDisks || !disk.isShareable())
&& disk.getDiskStorageType() == DiskStorageType.IMAGE &&
(!filterAllowSnapshotDisks || disk.isAllowSnapshot())) {
diskImages.add((DiskImage) disk);
}
}
return diskImages;
}
public static List<LunDisk> filterDiskBasedOnLuns(Collection<Disk> listOfDisks) {
List<LunDisk> lunDisks = new ArrayList<LunDisk>();
for (Disk disk : listOfDisks) {
if (disk.getDiskStorageType() == DiskStorageType.LUN) {
lunDisks.add((LunDisk) disk);
}
}
return lunDisks;
}
public static void removeDiskImage(DiskImage diskImage, Guid vmId) {
try {
removeDiskFromVm(vmId, diskImage.getId());
removeImage(diskImage);
} catch (RuntimeException ex) {
log.error("Failed adding new disk image and related entities to db", ex);
throw new VdcBLLException(VdcBllErrors.DB, ex);
}
}
public static void removeLunDisk(LunDisk lunDisk) {
DbFacade.getInstance()
.getVmDeviceDao()
.remove(new VmDeviceId(lunDisk.getId(),
null));
LUNs lun = lunDisk.getLun();
DbFacade.getInstance()
.getDiskLunMapDao()
.remove(new DiskLunMapId(lunDisk.getId(), lun.getLUN_id()));
DbFacade.getInstance().getBaseDiskDao().remove(lunDisk.getId());
lun.setLunConnections(new ArrayList<StorageServerConnections>(DbFacade.getInstance()
.getStorageServerConnectionDao()
.getAllForLun(lun.getLUN_id())));
if (!lun.getLunConnections().isEmpty()) {
StorageHelperDirector.getInstance().getItem(
lun.getLunConnections().get(0).getstorage_type()).removeLun(lun);
} else {
// if there are no connections then the lun is fcp.
StorageHelperDirector.getInstance().getItem(StorageType.FCP).removeLun(lun);
}
}
public static void removeImage(DiskImage diskImage) {
DbFacade.getInstance()
.getImageStorageDomainMapDao()
.remove(diskImage.getImageId());
DbFacade.getInstance().getDiskImageDynamicDao().remove(diskImage.getImageId());
DbFacade.getInstance().getImageDao().remove(diskImage.getImageId());
}
public static void removeDiskFromVm(Guid vmGuid, Guid diskId) {
DbFacade.getInstance().getVmDeviceDao().remove(new VmDeviceId(diskId, vmGuid));
DbFacade.getInstance().getBaseDiskDao().remove(diskId);
}
public static void updateImageStatus(Guid imageId, ImageStatus imageStatus) {
DbFacade.getInstance().getImageDao().updateStatus(imageId, imageStatus);
}
}
| core: fix javadoc in ImagesHandler
Change-Id: Ie3973632d6d47dc3257e0bb7a38a1712c61c87ef
Signed-off-by: Alissa Bonas <[email protected]>
| backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/ImagesHandler.java | core: fix javadoc in ImagesHandler | <ide><path>ackend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/ImagesHandler.java
<ide> * VM
<ide> *
<ide> * @param image
<del> * @param active
<del> * @param imageStorageDomainMap
<ide> */
<ide> public static void addDiskImageWithNoVmDevice(DiskImage image) {
<ide> addDiskImageWithNoVmDevice(image,
<ide> *
<ide> * @param disk
<ide> * disk to add
<del> * @param vmId
<del> * ID of the VM the disk will be associated with
<ide> */
<ide> public static void addDisk(BaseDisk disk) {
<ide> if (!DbFacade.getInstance().getBaseDiskDao().exists(disk.getId())) {
<ide> * Filter image disks by attributes.
<ide> * @param listOfDisks - The list of disks to be filtered.
<ide> * @param filterNotShareableDisks - Indication whether to filter disks which are not shareable.
<del> * @param filterAllowSnapshot - Indication whether to filter disks which are allowed to be snapshot.
<add> * @param filterAllowSnapshotDisks - Indication whether to filter disks which are allowed to be snapshot.
<ide> * @return - List filtered of disk images.
<ide> */
<ide> public static List<DiskImage> filterImageDisks(Collection<Disk> listOfDisks, |
|
Java | apache-2.0 | 01dda312dcfe377c62ca079d4241530df93dd2c6 | 0 | MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab | package org.myrobotlab.service;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import org.myrobotlab.framework.Service;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.service.interfaces.TextPublisher;
import org.slf4j.Logger;
/**
* based on _TemplateService
*/
/**
*
* @author LunDev (github), Ma. Vo. (MyRobotlab)
*/
public class AndroidVoiceRecognition extends Service implements TextPublisher {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory
.getLogger(AndroidVoiceRecognition.class);
private ClientHandler client;
private int port = 5684;
private final static String VERSION = "2015.01.01";
public AndroidVoiceRecognition(String n) {
super(n);
// intializing variables
// Should do something useful here in future
}
@Override
public void startService() {
super.startService();
startServer();
}
@Override
public void stopService() {
super.stopService();
}
@Override
public String getDescription() {
return "utilizing Android's Voice Recognition";
}
public void setPort(int p) {
port = p;
}
public void sendToClient(String mes) {
send("fromServer=" + mes);
}
public void startRecognition() {
send("startrecognition");
}
// Server-start
private void startServer() {
try {
ServerSocket serverSock = new ServerSocket(port);
NewConnectionHandler nch = new NewConnectionHandler(serverSock);
nch.start();
} catch (IOException ex) {
System.out.println(ex);
}
}
private void send(String mes) {
try {
client.getOut().writeObject(mes);
} catch (IOException ex) {
System.out.println(ex);
}
}
private void process(String mes) {
System.out.println(mes);
if (mes.startsWith("version")) {
String[] split = mes.split("=");
boolean versionneuer = false;
String aktversion2 = VERSION.replace(".", "~");
String[] aktversionsplit = aktversion2.split("~");
int[] aktversionsplitint = new int[aktversionsplit.length];
for (int i = 0; i < aktversionsplit.length; i++) {
aktversionsplitint[i] = Integer.parseInt(aktversionsplit[i]);
}
String runversion2 = split[1].replace(".", "~");
String[] runversionsplit = runversion2.split("~");
int[] runversionsplitint = new int[runversionsplit.length];
for (int i = 0; i < runversionsplit.length; i++) {
runversionsplitint[i] = Integer.parseInt(runversionsplit[i]);
}
for (int i = 0; i < 3; i++) {
if (aktversionsplitint[i] < runversionsplitint[i]) {
// eigener Versions-Teil ist NEUER wie der aktuelleste
// Versions-Teil
break;
} else if (aktversionsplitint[i] > runversionsplitint[i]) {
// eigener Versions-Teil ist AELTER wie der aktuelleste
// Versions-Teil
versionneuer = true;
break;
} else if (aktversionsplitint[i] > runversionsplitint[i]) {
// eigener Versions-Teil ist GLEICH wie der aktuelleste
// Versions-Teil
}
}
if (versionneuer) {
send("serverversion=" + VERSION);
System.out.println("Client has an old version");
client.finish();
} else {
send("accepted");
System.out.println("Client accepted");
}
} else if (mes.startsWith("recognized")) {
String[] split = mes.split("=");
//TODO - (Python) callback
invoke("recognized",split[1]);
} else {
System.out.println("ERROR: " + mes);
}
// sendToAll(mes);
}
private class NewConnectionHandler extends Thread {
private final ServerSocket serverSock;
public NewConnectionHandler(ServerSocket ss) {
serverSock = ss;
}
@Override
public void run() {
while (true) {
try {
Socket clientSocket = serverSock.accept();
ClientHandler ch = new ClientHandler(clientSocket);
client = ch;
ch.start();
System.out.println("Client connected");
// Only accept one client
break;
} catch (IOException ex) {
System.out.println(ex);
}
}
}
}
private class ClientHandler extends Thread {
private boolean running;
private Socket clientSocket;
private ObjectInputStream in;
private ObjectOutputStream out;
public ClientHandler(Socket socket) {
try {
clientSocket = socket;
in = new ObjectInputStream(clientSocket.getInputStream());
out = new ObjectOutputStream(clientSocket.getOutputStream());
} catch (Exception ex) {
System.out.println(ex);
}
running = true;
}
public ObjectOutputStream getOut() {
return out;
}
public void finish() {
try {
in.close();
out.close();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
running = false;
}
@Override
public void run() {
try {
Object obj;
while (running && (obj = in.readObject()) != null) {
// System.out.println("got a message!");
String mes = (String) obj;
process(mes);
}
} catch (IOException | ClassNotFoundException ex) {
System.out.println(ex);
}
}
}
// Server-end
public static void main(String[] args) throws InterruptedException {
LoggingFactory.getInstance().configure();
LoggingFactory.getInstance().setLevel(Level.INFO);
try {
Runtime.start("gui", "GUIService");
Runtime.start("avr", "AndroidVoiceRecognition");
} catch (Exception e) {
Logging.logException(e);
}
}
@Override
public String publishText(String text) {
return text;
}
public String recognized(String text) {
return text;
}
}
| src/org/myrobotlab/service/AndroidVoiceRecognition.java | package org.myrobotlab.service;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import org.myrobotlab.framework.Service;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.service.interfaces.TextPublisher;
import org.slf4j.Logger;
/**
* based on _TemplateService
*/
/**
*
* @author LunDev (github), Ma. Vo. (MyRobotlab)
*/
public class AndroidVoiceRecognition extends Service implements TextPublisher {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory
.getLogger(AndroidVoiceRecognition.class);
private ClientHandler client;
private int port = 5684;
private final static String VERSION = "2014.12.31";
public AndroidVoiceRecognition(String n) {
super(n);
// intializing variables
// Should do something useful here in future
}
@Override
public void startService() {
super.startService();
startServer();
}
@Override
public void stopService() {
super.stopService();
}
@Override
public String getDescription() {
return "utilizing Android's Voice Recognition";
}
public void setPort(int p) {
port = p;
}
public void sendToClient(String mes) {
send("fromServer=" + mes);
}
public void startRecognition() {
send("startrecognition");
}
// Server-start
private void startServer() {
try {
ServerSocket serverSock = new ServerSocket(port);
NewConnectionHandler nch = new NewConnectionHandler(serverSock);
nch.start();
} catch (IOException ex) {
System.out.println(ex);
}
}
private void send(String mes) {
try {
client.getOut().writeObject(mes);
} catch (IOException ex) {
System.out.println(ex);
}
}
private void process(String mes) {
System.out.println(mes);
if (mes.startsWith("version")) {
String[] split = mes.split("=");
boolean versionneuer = false;
String aktversion2 = VERSION.replace(".", "~");
String[] aktversionsplit = aktversion2.split("~");
int[] aktversionsplitint = new int[aktversionsplit.length];
for (int i = 0; i < aktversionsplit.length; i++) {
aktversionsplitint[i] = Integer.parseInt(aktversionsplit[i]);
}
String runversion2 = split[1].replace(".", "~");
String[] runversionsplit = runversion2.split("~");
int[] runversionsplitint = new int[runversionsplit.length];
for (int i = 0; i < runversionsplit.length; i++) {
runversionsplitint[i] = Integer.parseInt(runversionsplit[i]);
}
for (int i = 0; i < 3; i++) {
if (aktversionsplitint[i] < runversionsplitint[i]) {
// eigener Versions-Teil ist NEUER wie der aktuelleste
// Versions-Teil
break;
} else if (aktversionsplitint[i] > runversionsplitint[i]) {
// eigener Versions-Teil ist AELTER wie der aktuelleste
// Versions-Teil
versionneuer = true;
break;
} else if (aktversionsplitint[i] > runversionsplitint[i]) {
// eigener Versions-Teil ist GLEICH wie der aktuelleste
// Versions-Teil
}
}
if (versionneuer) {
send("serverversion=" + VERSION);
System.out.println("Client has an old version");
client.finish();
} else {
send("accepted");
System.out.println("Client accepted");
}
} else if (mes.startsWith("recognized")) {
String[] split = mes.split("=");
//TODO - (Python) callback
invoke("recognized",split[1]);
} else {
System.out.println("ERROR: " + mes);
}
// sendToAll(mes);
}
private class NewConnectionHandler extends Thread {
private final ServerSocket serverSock;
public NewConnectionHandler(ServerSocket ss) {
serverSock = ss;
}
@Override
public void run() {
while (true) {
try {
Socket clientSocket = serverSock.accept();
ClientHandler ch = new ClientHandler(clientSocket);
client = ch;
ch.start();
System.out.println("Client connected");
// Only accept one client
break;
} catch (IOException ex) {
System.out.println(ex);
}
}
}
}
private class ClientHandler extends Thread {
private boolean running;
private Socket clientSocket;
private ObjectInputStream in;
private ObjectOutputStream out;
public ClientHandler(Socket socket) {
try {
clientSocket = socket;
in = new ObjectInputStream(clientSocket.getInputStream());
out = new ObjectOutputStream(clientSocket.getOutputStream());
} catch (Exception ex) {
System.out.println(ex);
}
running = true;
}
public ObjectOutputStream getOut() {
return out;
}
public void finish() {
try {
in.close();
out.close();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
running = false;
}
@Override
public void run() {
try {
Object obj;
while (running && (obj = in.readObject()) != null) {
// System.out.println("got a message!");
String mes = (String) obj;
process(mes);
}
} catch (IOException | ClassNotFoundException ex) {
System.out.println(ex);
}
}
}
// Server-end
public static void main(String[] args) throws InterruptedException {
LoggingFactory.getInstance().configure();
LoggingFactory.getInstance().setLevel(Level.INFO);
try {
Runtime.start("gui", "GUIService");
Runtime.start("avr", "AndroidVoiceRecognition");
} catch (Exception e) {
Logging.logException(e);
}
}
@Override
public String publishText(String text) {
return text;
}
public String recognized(String text) {
return text;
}
}
| AndroidVoiceRecognition - fix version | src/org/myrobotlab/service/AndroidVoiceRecognition.java | AndroidVoiceRecognition - fix version | <ide><path>rc/org/myrobotlab/service/AndroidVoiceRecognition.java
<ide>
<ide> private ClientHandler client;
<ide> private int port = 5684;
<del> private final static String VERSION = "2014.12.31";
<add> private final static String VERSION = "2015.01.01";
<ide>
<ide> public AndroidVoiceRecognition(String n) {
<ide> super(n); |
|
Java | mit | 13c67841ee6a77ba434412e1c2bcb7f683c22cc7 | 0 | gatzka/android-scan,gatzka/android-scan | /*
* Android Scan, an app for scanning and configuring HBM devices.
*
* The MIT License (MIT)
*
* Copyright (C) Stephan Gatzka
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.hbm.devices.scan.ui.android;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import java.net.InetSocketAddress;
import java.util.HashMap;
import com.hbm.devices.scan.announce.Announce;
import com.hbm.devices.scan.announce.Device;
import com.squareup.picasso.Picasso;
final class DeviceViewHolder extends RecyclerView.ViewHolder {
static final String DETAILS = "Details";
private final TextView tvModuleId;
private final TextView tvModuleType;
private final TextView tvModuleName;
private final ImageView devicePhoto;
private final ImageButton infoButton;
private final CardView cardView;
private final Context context;
private final Drawable blackInfo;
private final Drawable whiteInfo;
private Announce announce;
private final int cardBackgroundNotConntectable;
private final int cardBackgroundConntectable;
private final int moduleTypeTextColorNotConnectable;
private final int moduleTypeTextColorConnectable;
private final int moduleNameTextColorNotConnectable;
private final int moduleNameTextColorConnectable;
private final int moduleIdTextColorNotConnectable;
private final int moduleIdTextColorConnectable;
private final int alpha;
private static final HashMap<String, Integer> resourceCache = new HashMap<>();
public DeviceViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
tvModuleId = (TextView) itemView.findViewById(R.id.moduleID);
tvModuleType = (TextView) itemView.findViewById(R.id.moduleType);
tvModuleName = (TextView) itemView.findViewById(R.id.moduleName);
devicePhoto = (ImageView) itemView.findViewById(R.id.device_photo);
infoButton = (ImageButton) itemView.findViewById(R.id.infoButton);
cardView = (CardView) itemView;
blackInfo = ContextCompat.getDrawable(context, R.drawable.ic_info_outline_black_48dp);
alpha = context.getResources().getInteger(R.integer.text_alpha);
setImageAlpha(blackInfo, alpha);
whiteInfo = ContextCompat.getDrawable(context, R.drawable.ic_info_outline_white_48dp);
cardBackgroundNotConntectable = ContextCompat.getColor(context, R.color.color_not_connectable);
cardBackgroundConntectable = ContextCompat.getColor(context, android.R.color.background_light);
moduleTypeTextColorNotConnectable = ContextCompat.getColor(context, android.R.color.primary_text_dark);
moduleTypeTextColorConnectable = ContextCompat.getColor(context, android.R.color.primary_text_light);
moduleNameTextColorNotConnectable = ContextCompat.getColor(context, android.R.color.secondary_text_dark);
moduleNameTextColorConnectable = ContextCompat.getColor(context, android.R.color.secondary_text_light);
moduleIdTextColorNotConnectable = ContextCompat.getColor(context, android.R.color.secondary_text_dark);
moduleIdTextColorConnectable = ContextCompat.getColor(context, android.R.color.secondary_text_light);
}
public void bind(Announce a) {
this.announce = a;
final Device device = announce.getParams().getDevice();
final String displayName = getDisplayName(device);
final String moduleType = getModuleType(device);
final String uuid = device.getUuid();
if (announce.getCookie() == null) {
cardView.setCardBackgroundColor(cardBackgroundNotConntectable);
tvModuleType.setTextColor(moduleTypeTextColorNotConnectable);
tvModuleName.setTextColor(moduleNameTextColorNotConnectable);
tvModuleId.setTextColor(moduleIdTextColorNotConnectable);
infoButton.setImageDrawable(whiteInfo);
} else {
cardView.setCardBackgroundColor(cardBackgroundConntectable);
tvModuleType.setTextColor(setTextAlpha(moduleTypeTextColorConnectable, alpha));
tvModuleName.setTextColor(setTextAlpha(moduleNameTextColorConnectable, alpha));
tvModuleId.setTextColor(setTextAlpha(moduleIdTextColorConnectable, alpha));
infoButton.setImageDrawable(blackInfo);
}
tvModuleType.setText(moduleType);
tvModuleName.setText(displayName);
tvModuleId.setText(uuid);
devicePhoto.setImageDrawable(null);
Picasso picasso = Picasso.with(context);
picasso.load(getImageResourceId(a)).into(devicePhoto);
cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final InetSocketAddress address = (InetSocketAddress) announce.getCookie();
if (address != null) {
openBrowser(address);
}
}
});
infoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, DeviceDetailsActivity.class);
intent.putExtra(DETAILS, announce);
ActivityCompat.startActivity((ScanActivity) context, intent, null);
((ScanActivity) context).overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
}
});
}
private static int getImageResourceId(Announce announce) {
String key = announce.getParams().getDevice().getLabel();
if (key == null || key.isEmpty()) {
key = announce.getParams().getDevice().getType();
}
if (key == null || key.isEmpty()) {
return R.drawable.ic_no_device;
}
return getResourceFromCache(key);
}
private static int getResourceFromCache(String key) {
Integer resourceId = resourceCache.get(key);
if (resourceId == null) {
resourceId = resolveResourceId(key);
resourceCache.put(key, resourceId);
}
return resourceId;
}
private static int resolveResourceId(String key) {
if (key.equals("CX23R")) {
return R.drawable.cx23;
}
if (key.equals("MX1601") || key.equals("MX1601B")) {
return R.drawable.mx1601b;
}
if (key.equals("MX1601BR")) {
return R.drawable.mx1601br;
}
if (key.equals("MX1609KBR")) {
return R.drawable.mx1609kbr;
}
if (key.equals("MX1609") || key.equals("MX1609KB")) {
return R.drawable.mx1609kb;
}
if (key.equals("MX1609TB")) {
return R.drawable.mx1609tb;
}
if (key.equals("MX1609T")) {
return R.drawable.mx1609t;
}
if (key.equals("MX1615BR")) {
return R.drawable.mx1615br;
}
if (key.equals("MX1615B") || key.equals("MX1615")) {
return R.drawable.mx1615b;
}
if (key.equals("MX411BR")) {
return R.drawable.mx411br;
}
if (key.equals("MX411P")) {
return R.drawable.mx411p;
}
if (key.equals("MX410") || key.equals("MX410B")) {
return R.drawable.mx410b;
}
if (key.equals("MX471BR")) {
return R.drawable.mx471br;
}
if (key.equals("MX471") || key.equals("MX471B")) {
return R.drawable.mx471b;
}
if (key.equals("MX879") || key.equals("MX879B")) {
return R.drawable.mx879b;
}
if (key.equals("MX878") || key.equals("MX878B")) {
return R.drawable.mx878b;
}
if (key.equals("MX460") || key.equals("MX460B")) {
return R.drawable.mx460b;
}
if (key.equals("MX440") || key.equals("MX440A") || key.equals("MX440B")) {
return R.drawable.mx440b;
}
if (key.equals("MX403") || key.equals("MX403B")) {
return R.drawable.mx403b;
}
if (key.equals("CX27") || key.equals("CX27B")) {
return R.drawable.cx27b;
}
if (key.equals("CX22B")) {
return R.drawable.cx22b;
}
if (key.equals("CX22W")) {
return R.drawable.cx22w;
}
if (key.equals("MX840") || key.equals("MX840A") || key.equals("MX840B")) {
return R.drawable.mx840b;
}
if (key.equals("MX840BR")) {
return R.drawable.mx840br;
}
if (key.equals("MX403") || key.equals("MX430B")) {
return R.drawable.mx430b;
}
if (key.equals("MX809") || key.equals("MX809B")) {
return R.drawable.mx809b;
}
if (key.equals("MX238") || key.equals("MX238B")) {
return R.drawable.mx238b;
}
if (key.equals("PMX")) {
return R.drawable.pmx;
}
return R.drawable.ic_no_device;
}
private static void setImageAlpha(Drawable draw, int alphaPercent) {
int alpha = alphaPercent * 255 / 100;
draw.setAlpha(alpha);
}
private static int setTextAlpha(int color, int alphaPercent) {
int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);
int alpha = alphaPercent * 255 / 100;
return Color.argb(alpha, red, green, blue);
}
private String getModuleType(final Device device) {
String moduleType = device.getType();
if (moduleType == null || moduleType.length() == 0) {
moduleType = context.getString(R.string.unknown);
}
return moduleType;
}
private String getDisplayName(final Device device) {
String displayName = device.getName();
if (displayName == null || displayName.length() == 0) {
displayName = context.getString(R.string.unknown);
}
return displayName;
}
private void openBrowser(InetSocketAddress address) {
final BrowserStartTask browserTask = new BrowserStartTask(context);
browserTask.execute(address);
}
}
| src/main/java/com/hbm/devices/scan/ui/android/DeviceViewHolder.java | /*
* Android Scan, an app for scanning and configuring HBM devices.
*
* The MIT License (MIT)
*
* Copyright (C) Stephan Gatzka
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.hbm.devices.scan.ui.android;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import java.net.InetSocketAddress;
import java.util.HashMap;
import com.hbm.devices.scan.announce.Announce;
import com.hbm.devices.scan.announce.Device;
import com.squareup.picasso.Picasso;
final class DeviceViewHolder extends RecyclerView.ViewHolder {
static final String DETAILS = "Details";
private final TextView tvModuleId;
private final TextView tvModuleType;
private final TextView tvModuleName;
private final ImageView devicePhoto;
private final ImageButton infoButton;
private final CardView cardView;
private final Context context;
private final Drawable blackInfo;
private final Drawable whiteInfo;
private Announce announce;
private final int cardBackgroundNotConntectable;
private final int cardBackgroundConntectable;
private final int moduleTypeTextColorNotConnectable;
private final int moduleTypeTextColorConnectable;
private final int moduleNameTextColorNotConnectable;
private final int moduleNameTextColorConnectable;
private final int moduleIdTextColorNotConnectable;
private final int moduleIdTextColorConnectable;
private final int alpha;
private static final HashMap<String, Integer> resourceCache = new HashMap<>();
public DeviceViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
tvModuleId = (TextView) itemView.findViewById(R.id.moduleID);
tvModuleType = (TextView) itemView.findViewById(R.id.moduleType);
tvModuleName = (TextView) itemView.findViewById(R.id.moduleName);
devicePhoto = (ImageView) itemView.findViewById(R.id.device_photo);
infoButton = (ImageButton) itemView.findViewById(R.id.infoButton);
cardView = (CardView) itemView;
blackInfo = ContextCompat.getDrawable(context, R.drawable.ic_info_outline_black_48dp);
alpha = context.getResources().getInteger(R.integer.text_alpha);
setImageAlpha(blackInfo, alpha);
whiteInfo = ContextCompat.getDrawable(context, R.drawable.ic_info_outline_white_48dp);
cardBackgroundNotConntectable = ContextCompat.getColor(context, R.color.color_not_connectable);
cardBackgroundConntectable = ContextCompat.getColor(context, android.R.color.background_light);
moduleTypeTextColorNotConnectable = ContextCompat.getColor(context, android.R.color.primary_text_dark);
moduleTypeTextColorConnectable = ContextCompat.getColor(context, android.R.color.primary_text_light);
moduleNameTextColorNotConnectable = ContextCompat.getColor(context, android.R.color.secondary_text_dark);
moduleNameTextColorConnectable = ContextCompat.getColor(context, android.R.color.secondary_text_light);
moduleIdTextColorNotConnectable = ContextCompat.getColor(context, android.R.color.secondary_text_dark);
moduleIdTextColorConnectable = ContextCompat.getColor(context, android.R.color.secondary_text_light);
}
public void bind(Announce a) {
this.announce = a;
final Device device = announce.getParams().getDevice();
final String displayName = getDisplayName(device);
final String moduleType = getModuleType(device);
final String uuid = device.getUuid();
if (announce.getCookie() == null) {
cardView.setCardBackgroundColor(cardBackgroundNotConntectable);
tvModuleType.setTextColor(moduleTypeTextColorNotConnectable);
tvModuleName.setTextColor(moduleNameTextColorNotConnectable);
tvModuleId.setTextColor(moduleIdTextColorNotConnectable);
infoButton.setImageDrawable(whiteInfo);
} else {
cardView.setCardBackgroundColor(cardBackgroundConntectable);
tvModuleType.setTextColor(setTextAlpha(moduleTypeTextColorConnectable, alpha));
tvModuleName.setTextColor(setTextAlpha(moduleNameTextColorConnectable, alpha));
tvModuleId.setTextColor(setTextAlpha(moduleIdTextColorConnectable, alpha));
infoButton.setImageDrawable(blackInfo);
}
tvModuleType.setText(moduleType);
tvModuleName.setText(displayName);
tvModuleId.setText(uuid);
devicePhoto.setImageDrawable(null);
Picasso picasso = Picasso.with(context);
picasso.load(getImageResourceId(a)).into(devicePhoto);
cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final InetSocketAddress address = (InetSocketAddress) announce.getCookie();
if (address != null) {
openBrowser(address);
}
}
});
infoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, DeviceDetailsActivity.class);
intent.putExtra(DETAILS, announce);
ActivityCompat.startActivity((ScanActivity) context, intent, null);
((ScanActivity) context).overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
}
});
}
private static int getImageResourceId(Announce announce) {
String key = announce.getParams().getDevice().getLabel();
if (key == null || key.isEmpty()) {
key = announce.getParams().getDevice().getType();
}
if (key == null || key.isEmpty()) {
return R.drawable.ic_no_device;
}
return getResourceFromCache(key);
}
private static int getResourceFromCache(String key) {
Integer resourceId = resourceCache.get(key);
if (resourceId == null) {
resourceId = resolveResourceId(key);
}
return resourceId;
}
private static int resolveResourceId(String key) {
if (key.equals("CX23R")) {
return R.drawable.cx23;
}
if (key.equals("MX1601") || key.equals("MX1601B")) {
return R.drawable.mx1601b;
}
if (key.equals("MX1601BR")) {
return R.drawable.mx1601br;
}
if (key.equals("MX1609KBR")) {
return R.drawable.mx1609kbr;
}
if (key.equals("MX1609") || key.equals("MX1609KB")) {
return R.drawable.mx1609kb;
}
if (key.equals("MX1609TB")) {
return R.drawable.mx1609tb;
}
if (key.equals("MX1609T")) {
return R.drawable.mx1609t;
}
if (key.equals("MX1615BR")) {
return R.drawable.mx1615br;
}
if (key.equals("MX1615B") || key.equals("MX1615")) {
return R.drawable.mx1615b;
}
if (key.equals("MX411BR")) {
return R.drawable.mx411br;
}
if (key.equals("MX411P")) {
return R.drawable.mx411p;
}
if (key.equals("MX410") || key.equals("MX410B")) {
return R.drawable.mx410b;
}
if (key.equals("MX471BR")) {
return R.drawable.mx471br;
}
if (key.equals("MX471") || key.equals("MX471B")) {
return R.drawable.mx471b;
}
if (key.equals("MX879") || key.equals("MX879B")) {
return R.drawable.mx879b;
}
if (key.equals("MX878") || key.equals("MX878B")) {
return R.drawable.mx878b;
}
if (key.equals("MX460") || key.equals("MX460B")) {
return R.drawable.mx460b;
}
if (key.equals("MX440") || key.equals("MX440A") || key.equals("MX440B")) {
return R.drawable.mx440b;
}
if (key.equals("MX403") || key.equals("MX403B")) {
return R.drawable.mx403b;
}
if (key.equals("CX27") || key.equals("CX27B")) {
return R.drawable.cx27b;
}
if (key.equals("CX22B")) {
return R.drawable.cx22b;
}
if (key.equals("CX22W")) {
return R.drawable.cx22w;
}
if (key.equals("MX840") || key.equals("MX840A") || key.equals("MX840B")) {
return R.drawable.mx840b;
}
if (key.equals("MX840BR")) {
return R.drawable.mx840br;
}
if (key.equals("MX403") || key.equals("MX430B")) {
return R.drawable.mx430b;
}
if (key.equals("MX809") || key.equals("MX809B")) {
return R.drawable.mx809b;
}
if (key.equals("MX238") || key.equals("MX238B")) {
return R.drawable.mx238b;
}
if (key.equals("PMX")) {
return R.drawable.pmx;
}
return R.drawable.ic_no_device;
}
private static void setImageAlpha(Drawable draw, int alphaPercent) {
int alpha = alphaPercent * 255 / 100;
draw.setAlpha(alpha);
}
private static int setTextAlpha(int color, int alphaPercent) {
int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);
int alpha = alphaPercent * 255 / 100;
return Color.argb(alpha, red, green, blue);
}
private String getModuleType(final Device device) {
String moduleType = device.getType();
if (moduleType == null || moduleType.length() == 0) {
moduleType = context.getString(R.string.unknown);
}
return moduleType;
}
private String getDisplayName(final Device device) {
String displayName = device.getName();
if (displayName == null || displayName.length() == 0) {
displayName = context.getString(R.string.unknown);
}
return displayName;
}
private void openBrowser(InetSocketAddress address) {
final BrowserStartTask browserTask = new BrowserStartTask(context);
browserTask.execute(address);
}
}
| Really use the resource cache.
| src/main/java/com/hbm/devices/scan/ui/android/DeviceViewHolder.java | Really use the resource cache. | <ide><path>rc/main/java/com/hbm/devices/scan/ui/android/DeviceViewHolder.java
<ide> Integer resourceId = resourceCache.get(key);
<ide> if (resourceId == null) {
<ide> resourceId = resolveResourceId(key);
<add> resourceCache.put(key, resourceId);
<ide> }
<ide> return resourceId;
<ide> } |
|
Java | mit | 94d89f2c27364b59bea2db33d222944aeabbc112 | 0 | arvydas/blinkstick-android | package com.agileinnovative.blinkstick;
import java.util.Hashtable;
import java.util.Random;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
/**
* Class designed to communicate with BlinkStick devices.
*/
public class BlinkStick {
protected static final int STD_USB_REQUEST_GET_DESCRIPTOR = 0x06;
protected static final int LIBUSB_DT_STRING = 0x03;
/**
* USB device object to communicate directly with BlinkStick
*/
private UsbDevice device = null;
/**
* USB connection for communicating with BlinkStick
*/
private UsbDeviceConnection connection;
/**
* Cached manufacturer name
*/
private String manufacturer = null;
/**
* Cached product name
*/
private String productName = null;
/**
* Assign UsbDevice
*
* @param device object to communicate directly with BlinkStick
*/
public void setDevice(UsbDevice device) {
this.device = device;
}
/**
* Get UsbDevice
*
* @return USB device reference
*/
public UsbDevice getDevice()
{
return this.device;
}
/**
* Assign USB device connection
*
* @param con Connection object to communicate with BlinkStick device
*/
public void setConnection(UsbDeviceConnection con)
{
connection = con;
}
private int _VersionMajor = -1;
/**
* Get major version number from serial
*
* @return Major version number as int
*/
public int getVersionMajor()
{
if (_VersionMajor == -1)
{
_VersionMajor = Integer.parseInt(getSerial().substring(getSerial().length() - 3, getSerial().length() - 2));
}
return _VersionMajor;
}
private int _VersionMinor = -1;
/**
* Get minor version number from serial
*
* @return Minor version number as int
*/
public int getVersionMinor() {
if (_VersionMinor == -1)
{
_VersionMinor = Integer.parseInt(getSerial().substring(getSerial().length() - 1, getSerial().length()));
}
return _VersionMinor;
}
/**
* Check if BlinkStick is connected
*
* @return Returns true if BlinkStick is connected
*/
public boolean isConnected()
{
return connection != null;
}
/**
* Set the color of the device with separate r, g and b int values.
* The values are automatically converted to byte values
*
* @param r red int color value 0..255
* @param g gree int color value 0..255
* @param b blue int color value 0..255
*/
public void setColor(int r, int g, int b) {
this.setColor((byte) r, (byte) g, (byte) b);
}
/**
* Set the color of the device with separate r, g and b byte values
*
* @param r red byte color value 0..255
* @param g gree byte color value 0..255
* @param b blue byte color value 0..255
*/
public void setColor(byte r, byte g, byte b) {
try {
sendFeatureReport(new byte[] {1, r, g, b});
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sends feature report to BlinkStick
*
* @param buffer An array of bytes to send to the device. First byte has to be report id.
*/
private void sendFeatureReport(byte[] buffer)
{
if (connection != null)
{
connection.controlTransfer(0x20, 0x9, buffer[0], 0, buffer, buffer.length, 2000);
}
}
/**
* Get feature report from BlinkStick
*
* @param buffer An array of bytes to receive from the device. First byte has to be report id. The array must be initialized with correct size.
*
* @return Number of bytes read from the device
*/
private int getFeatureReport(byte[] buffer)
{
if (connection != null)
{
return connection.controlTransfer(0x80 | 0x20, 0x1, buffer[0], 0, buffer, buffer.length, 2000);
}
return 0;
}
/**
* Set indexed color of the device with separate r, g and b byte values for channel and LED index
*
* @param channel Channel (0 - R, 1 - G, 2 - B)
* @param index Index of the LED
* @param r red int color value 0..255
* @param g gree int color value 0..255
* @param b blue int color value 0..255
*/
public void setIndexedColor(int channel, int index, int r, int g, int b) {
this.setIndexedColor((byte)channel, (byte)index, (byte)r, (byte)g, (byte)b);
}
/**
* Set indexed color of the device with separate r, g and b byte values for channel and LED index
*
* @param channel Channel (0 - R, 1 - G, 2 - B)
* @param index Index of the LED
* @param r red byte color value 0..255
* @param g gree byte color value 0..255
* @param b blue byte color value 0..255
*/
public void setIndexedColor(byte channel, byte index, byte r, byte g, byte b) {
try {
sendFeatureReport(new byte[] {5, channel, index, r, g, b});
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Set the indexed color of BlinkStick Pro with Processing color value
*
* @param channel Channel (0 - R, 1 - G, 2 - B)
* @param index Index of the LED
* @param value color as int
*/
public void setIndexedColor(int channel, int index, int value) {
int r = (value >> 16) & 0xFF;
int g = (value >> 8) & 0xFF;
int b = value & 0xFF;
this.setIndexedColor(channel, index, r, g, b);
}
/**
* Set the indexed color of BlinkStick Pro with Processing color value for channel 0
*
* @param index Index of the LED
* @param value color as int
*/
public void setIndexedColor(int index, int value) {
int r = (value >> 16) & 0xFF;
int g = (value >> 8) & 0xFF;
int b = value & 0xFF;
this.setIndexedColor(0, index, r, g, b);
}
/**
* Set the color of the device with Processing color value
*
* @param value color as int
*/
public void setColor(int value) {
int r = (value >> 16) & 0xFF;
int g = (value >> 8) & 0xFF;
int b = value & 0xFF;
this.setColor(r, g, b);
}
/**
* Set the color of the device with string value
*
* @param value this can either be a named color "red", "green", "blue" and etc.
* or a hex color in #rrggbb format
*/
public void setColor(String value) {
if (COLORS.containsKey(value)) {
this.setColor(hex2Rgb(COLORS.get(value)));
} else {
this.setColor(hex2Rgb(value));
}
}
/**
* Set random color
*/
public void setRandomColor() {
Random random = new Random();
this.setColor(
random.nextInt(256),
random.nextInt(256),
random.nextInt(256));
}
/**
* Turn BlinkStick off
*/
public void turnOff() {
this.setColor(0, 0, 0);
}
/**
* Convert hex string to color object
*
* @param colorStr Color value as hex string #rrggbb
*
* @return color object
*/
private int hex2Rgb(String colorStr) {
int red = Integer.valueOf(colorStr.substring(1, 3), 16)+ 0;
int green = Integer.valueOf(colorStr.substring(3, 5), 16) + 0;
int blue = Integer.valueOf(colorStr.substring(5, 7), 16) + 0;
return (255 << 24) | (red << 16) | (green << 8) | blue;
}
/**
* Get the current color of the device as int
*
* @return The current color of the device as int
*/
public int getColor() {
byte[] data = new byte[33];
data[0] = 1;// First byte is ReportID
try {
int read = getFeatureReport(data);
if (read > 0) {
return (255 << 24) | (data[1] << 16) | (data[2] << 8) | data[3];
}
} catch (Exception e) {
}
return 0;
}
/**
* Get the current color of the device in #rrggbb format
*
* @return Returns the current color of the device as #rrggbb formated string
*/
public String getColorString() {
int c = getColor();
int red = (c >> 16) & 0xFF;
int green = (c >> 8) & 0xFF;
int blue = c & 0xFF;
return "#" + String.format("%02X", red)
+ String.format("%02X", green)
+ String.format("%02X", blue);
}
/**
* Get value of InfoBlocks
*
* @param id InfoBlock id, should be 1 or 2 as only supported info blocks
*/
private String getInfoBlock(int id) {
byte[] data = new byte[33];
data[0] = (byte) (id + 1);
String result = "";
try {
int read = getFeatureReport(data);
if (read > 0) {
for (int i = 1; i < data.length; i++) {
if (i == 0) {
break;
}
result += (char) data[i];
}
}
} catch (Exception e) {
}
return result;
}
/**
* Get value of InfoBlock1
*
* @return The value of info block 1
*/
public String getInfoBlock1() {
return getInfoBlock(1);
}
/**
* Get value of InfoBlock2
*
* @return The value of info block 2
*/
public String getInfoBlock2() {
return getInfoBlock(2);
}
/**
* Set value for InfoBlocks
*
* @param id InfoBlock id, should be 1 or 2 as only supported info blocks
* @param value The value to be written to the info block
*/
private void setInfoBlock(int id, String value) {
char[] charArray = value.toCharArray();
byte[] data = new byte[33];
data[0] = (byte) (id + 1);
for (int i = 0; i < charArray.length; i++) {
if (i > 32) {
break;
}
data[i + 1] = (byte) charArray[i];
}
try {
sendFeatureReport(data);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Set value for InfoBlock1
*
* @param value The value to be written to the info block 1
*/
public void setInfoBlock1(String value) {
setInfoBlock(1, value);
}
/**
* Set value for InfoBlock2
*
* @param value The value to be written to the info block 2
*/
public void setInfoBlock2(String value) {
setInfoBlock(2, value);
}
/**
* Get the manufacturer of the device
*
* @return Returns the manufacturer name of the device
*/
public String getManufacturer() {
if (manufacturer == null)
{
manufacturer = "";
byte[] rawDescs = connection.getRawDescriptors();
byte[] buffer = new byte[255];
int idxMan = rawDescs[14];
try
{
int rdo = connection.controlTransfer(UsbConstants.USB_DIR_IN
| UsbConstants.USB_TYPE_STANDARD, STD_USB_REQUEST_GET_DESCRIPTOR,
(LIBUSB_DT_STRING << 8) | idxMan, 0, buffer, 0xFF, 0);
manufacturer = new String(buffer, 2, rdo - 2, "UTF-16LE");
}
catch (Exception e)
{
}
}
return manufacturer;
}
/**
* Get the product description of the device
*
* @return Returns the product name of the device.
*/
public String getProduct() {
if (productName == null)
{
productName = "";
byte[] rawDescs = connection.getRawDescriptors();
byte[] buffer = new byte[255];
int idxPrd = rawDescs[15];
try
{
int rdo = connection.controlTransfer(UsbConstants.USB_DIR_IN
| UsbConstants.USB_TYPE_STANDARD, STD_USB_REQUEST_GET_DESCRIPTOR,
(LIBUSB_DT_STRING << 8) | idxPrd, 0, buffer, 0xFF, 0);
productName = new String(buffer, 2, rdo - 2, "UTF-16LE");
}
catch (Exception e)
{
}
}
return productName;
}
/**
* Get the serial number of the device
*
* @return Returns the serial number of device.
*/
public String getSerial() {
return connection.getSerial();
}
/**
* Determine report id for the amount of data to be sent
*
* @return Returns the report id
*/
private byte determineReportId(int length) {
byte reportId = 9;
//Automatically determine the correct report id to send the data to
if (length <= 8 * 3)
{
reportId = 6;
}
else if (length <= 16 * 3)
{
reportId = 7;
}
else if (length <= 32 * 3)
{
reportId = 8;
}
else if (length <= 64 * 3)
{
reportId = 9;
}
else if (length <= 128 * 3)
{
reportId = 10;
}
return reportId;
}
/**
* Determine the adjusted maximum amount of LED for the report
*
* @return Returns the adjusted amount of LED data
*/
private byte determineMaxLeds(int length) {
byte maxLeds = 64;
//Automatically determine the correct report id to send the data to
if (length <= 8 * 3)
{
maxLeds = 8;
}
else if (length <= 16 * 3)
{
maxLeds = 16;
}
else if (length <= 32 * 3)
{
maxLeds = 32;
}
else if (length <= 64 * 3)
{
maxLeds = 64;
}
else if (length <= 128 * 3)
{
maxLeds = 64;
}
return maxLeds;
}
/**
* Send a packet of data to LEDs on channel 0 (R)
*
* @param colorData Report data must be a byte array in the following format: [g0, r0, b0, g1, r1, b1, g2, r2, b2 ...]
*/
public void setColors(byte[] colorData)
{
this.setColors((byte)0, colorData);
}
/**
* Send a packet of data to LEDs
*
* @param channel Channel (0 - R, 1 - G, 2 - B)
* @param colorData Report data must be a byte array in the following format: [g0, r0, b0, g1, r1, b1, g2, r2, b2 ...]
*/
public void setColors(int channel, byte[] colorData)
{
this.setColors((byte)channel, colorData);
}
/**
* Send a packet of data to LEDs
*
* @param channel Channel (0 - R, 1 - G, 2 - B)
* @param colorData Report data must be a byte array in the following format: [g0, r0, b0, g1, r1, b1, g2, r2, b2 ...]
*/
public void setColors(byte channel, byte[] colorData)
{
byte leds = this.determineMaxLeds(colorData.length);
byte[] data = new byte[leds * 3 + 2];
data[0] = this.determineReportId(colorData.length);
data[1] = channel;
for (int i = 0; i < Math.min(colorData.length, data.length - 2); i++)
{
data[i + 2] = colorData[i];
}
for (int i = colorData.length + 2; i < data.length; i++)
{
data[i] = 0;
}
try {
sendFeatureReport(data);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Set the mode of BlinkStick Pro as int
*
* @param mode 0 - Normal, 1 - Inverse, 2 - WS2812, 3 - WS2812 mirror
*/
public void setMode(int mode)
{
this.setMode((byte)mode);
}
/**
* Set the mode of BlinkStick Pro as byte
*
* @param mode 0 - Normal, 1 - Inverse, 2 - WS2812, 3 - WS2812 mirror
*/
public void setMode(byte mode)
{
try {
sendFeatureReport(new byte[] {4, mode});
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Get the mode of BlinkStick Pro
*
* @return 0 - Normal, 1 - Inverse, 2 - WS2812, 3 - WS2812 mirror
*/
public byte getMode()
{
byte[] data = new byte[2];
data[0] = 4;// First byte is ReportID
try {
int read = getFeatureReport(data);
if (read > 0) {
return data[1];
}
} catch (Exception e) {
}
return -1;
}
/**
* Variable holds the list of valid CSS colors as a hashtable
*/
private static final Hashtable<String, String> COLORS = new Hashtable<String, String>() {
/**
*
*/
private static final long serialVersionUID = 1L;
{
put("aqua", "#00ffff");
put("aliceblue", "#f0f8ff");
put("antiquewhite", "#faebd7");
put("black", "#000000");
put("blue", "#0000ff");
put("cyan", "#00ffff");
put("darkblue", "#00008b");
put("darkcyan", "#008b8b");
put("darkgreen", "#006400");
put("darkturquoise", "#00ced1");
put("deepskyblue", "#00bfff");
put("green", "#008000");
put("lime", "#00ff00");
put("mediumblue", "#0000cd");
put("mediumspringgreen", "#00fa9a");
put("navy", "#000080");
put("springgreen", "#00ff7f");
put("teal", "#008080");
put("midnightblue", "#191970");
put("dodgerblue", "#1e90ff");
put("lightseagreen", "#20b2aa");
put("forestgreen", "#228b22");
put("seagreen", "#2e8b57");
put("darkslategray", "#2f4f4f");
put("darkslategrey", "#2f4f4f");
put("limegreen", "#32cd32");
put("mediumseagreen", "#3cb371");
put("turquoise", "#40e0d0");
put("royalblue", "#4169e1");
put("steelblue", "#4682b4");
put("darkslateblue", "#483d8b");
put("mediumturquoise", "#48d1cc");
put("indigo", "#4b0082");
put("darkolivegreen", "#556b2f");
put("cadetblue", "#5f9ea0");
put("cornflowerblue", "#6495ed");
put("mediumaquamarine", "#66cdaa");
put("dimgray", "#696969");
put("dimgrey", "#696969");
put("slateblue", "#6a5acd");
put("olivedrab", "#6b8e23");
put("slategray", "#708090");
put("slategrey", "#708090");
put("lightslategray", "#778899");
put("lightslategrey", "#778899");
put("mediumslateblue", "#7b68ee");
put("lawngreen", "#7cfc00");
put("aquamarine", "#7fffd4");
put("chartreuse", "#7fff00");
put("gray", "#808080");
put("grey", "#808080");
put("maroon", "#800000");
put("olive", "#808000");
put("purple", "#800080");
put("lightskyblue", "#87cefa");
put("skyblue", "#87ceeb");
put("blueviolet", "#8a2be2");
put("darkmagenta", "#8b008b");
put("darkred", "#8b0000");
put("saddlebrown", "#8b4513");
put("darkseagreen", "#8fbc8f");
put("lightgreen", "#90ee90");
put("mediumpurple", "#9370db");
put("darkviolet", "#9400d3");
put("palegreen", "#98fb98");
put("darkorchid", "#9932cc");
put("yellowgreen", "#9acd32");
put("sienna", "#a0522d");
put("brown", "#a52a2a");
put("darkgray", "#a9a9a9");
put("darkgrey", "#a9a9a9");
put("greenyellow", "#adff2f");
put("lightblue", "#add8e6");
put("paleturquoise", "#afeeee");
put("lightsteelblue", "#b0c4de");
put("powderblue", "#b0e0e6");
put("firebrick", "#b22222");
put("darkgoldenrod", "#b8860b");
put("mediumorchid", "#ba55d3");
put("rosybrown", "#bc8f8f");
put("darkkhaki", "#bdb76b");
put("silver", "#c0c0c0");
put("mediumvioletred", "#c71585");
put("indianred", "#cd5c5c");
put("peru", "#cd853f");
put("chocolate", "#d2691e");
put("tan", "#d2b48c");
put("lightgray", "#d3d3d3");
put("lightgrey", "#d3d3d3");
put("thistle", "#d8bfd8");
put("goldenrod", "#daa520");
put("orchid", "#da70d6");
put("palevioletred", "#db7093");
put("crimson", "#dc143c");
put("gainsboro", "#dcdcdc");
put("plum", "#dda0dd");
put("burlywood", "#deb887");
put("lightcyan", "#e0ffff");
put("lavender", "#e6e6fa");
put("darksalmon", "#e9967a");
put("palegoldenrod", "#eee8aa");
put("violet", "#ee82ee");
put("azure", "#f0ffff");
put("honeydew", "#f0fff0");
put("khaki", "#f0e68c");
put("lightcoral", "#f08080");
put("sandybrown", "#f4a460");
put("beige", "#f5f5dc");
put("mintcream", "#f5fffa");
put("wheat", "#f5deb3");
put("whitesmoke", "#f5f5f5");
put("ghostwhite", "#f8f8ff");
put("lightgoldenrodyellow", "#fafad2");
put("linen", "#faf0e6");
put("salmon", "#fa8072");
put("oldlace", "#fdf5e6");
put("bisque", "#ffe4c4");
put("blanchedalmond", "#ffebcd");
put("coral", "#ff7f50");
put("cornsilk", "#fff8dc");
put("darkorange", "#ff8c00");
put("deeppink", "#ff1493");
put("floralwhite", "#fffaf0");
put("fuchsia", "#ff00ff");
put("gold", "#ffd700");
put("hotpink", "#ff69b4");
put("ivory", "#fffff0");
put("lavenderblush", "#fff0f5");
put("lemonchiffon", "#fffacd");
put("lightpink", "#ffb6c1");
put("lightsalmon", "#ffa07a");
put("lightyellow", "#ffffe0");
put("magenta", "#ff00ff");
put("mistyrose", "#ffe4e1");
put("moccasin", "#ffe4b5");
put("navajowhite", "#ffdead");
put("orange", "#ffa500");
put("orangered", "#ff4500");
put("papayawhip", "#ffefd5");
put("peachpuff", "#ffdab9");
put("pink", "#ffc0cb");
put("red", "#ff0000");
put("seashell", "#fff5ee");
put("snow", "#fffafa");
put("tomato", "#ff6347");
put("white", "#ffffff");
put("yellow", "#ffff00");
}
};
}
| src/com/agileinnovative/blinkstick/BlinkStick.java | package com.agileinnovative.blinkstick;
import java.util.Hashtable;
import java.util.Random;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
/**
* Class designed to communicate with BlinkStick devices.
*/
public class BlinkStick {
protected static final int STD_USB_REQUEST_GET_DESCRIPTOR = 0x06;
protected static final int LIBUSB_DT_STRING = 0x03;
/**
* USB device object to communicate directly with BlinkStick
*/
private UsbDevice device = null;
/**
* USB connection for communicating with BlinkStick
*/
private UsbDeviceConnection connection;
/**
* Cached manufacturer name
*/
private String manufacturer = null;
/**
* Cached product name
*/
private String productName = null;
/**
* Assign UsbDevice
*
* @param device object to communicate directly with BlinkStick
*/
public void setDevice(UsbDevice device) {
this.device = device;
}
/**
* Get UsbDevice
*
* @return USB device reference
*/
public UsbDevice getDevice()
{
return this.device;
}
/**
* Assign USB device connection
*
* @param con Connection object to communicate with BlinkStick device
*/
public void setConnection(UsbDeviceConnection con)
{
connection = con;
}
/**
* Check if BlinkStick is connected
*
* @return Returns true if BlinkStick is connected
*/
public boolean isConnected()
{
return connection != null;
}
/**
* Set the color of the device with separate r, g and b int values.
* The values are automatically converted to byte values
*
* @param r red int color value 0..255
* @param g gree int color value 0..255
* @param b blue int color value 0..255
*/
public void setColor(int r, int g, int b) {
this.setColor((byte) r, (byte) g, (byte) b);
}
/**
* Set the color of the device with separate r, g and b byte values
*
* @param r red byte color value 0..255
* @param g gree byte color value 0..255
* @param b blue byte color value 0..255
*/
public void setColor(byte r, byte g, byte b) {
try {
sendFeatureReport(new byte[] {1, r, g, b});
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sends feature report to BlinkStick
*
* @param buffer An array of bytes to send to the device. First byte has to be report id.
*/
private void sendFeatureReport(byte[] buffer)
{
if (connection != null)
{
connection.controlTransfer(0x20, 0x9, buffer[0], 0, buffer, buffer.length, 2000);
}
}
/**
* Get feature report from BlinkStick
*
* @param buffer An array of bytes to receive from the device. First byte has to be report id. The array must be initialized with correct size.
*
* @return Number of bytes read from the device
*/
private int getFeatureReport(byte[] buffer)
{
if (connection != null)
{
return connection.controlTransfer(0x80 | 0x20, 0x1, buffer[0], 0, buffer, buffer.length, 2000);
}
return 0;
}
/**
* Set indexed color of the device with separate r, g and b byte values for channel and LED index
*
* @param channel Channel (0 - R, 1 - G, 2 - B)
* @param index Index of the LED
* @param r red int color value 0..255
* @param g gree int color value 0..255
* @param b blue int color value 0..255
*/
public void setIndexedColor(int channel, int index, int r, int g, int b) {
this.setIndexedColor((byte)channel, (byte)index, (byte)r, (byte)g, (byte)b);
}
/**
* Set indexed color of the device with separate r, g and b byte values for channel and LED index
*
* @param channel Channel (0 - R, 1 - G, 2 - B)
* @param index Index of the LED
* @param r red byte color value 0..255
* @param g gree byte color value 0..255
* @param b blue byte color value 0..255
*/
public void setIndexedColor(byte channel, byte index, byte r, byte g, byte b) {
try {
sendFeatureReport(new byte[] {5, channel, index, r, g, b});
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Set the indexed color of BlinkStick Pro with Processing color value
*
* @param channel Channel (0 - R, 1 - G, 2 - B)
* @param index Index of the LED
* @param value color as int
*/
public void setIndexedColor(int channel, int index, int value) {
int r = (value >> 16) & 0xFF;
int g = (value >> 8) & 0xFF;
int b = value & 0xFF;
this.setIndexedColor(channel, index, r, g, b);
}
/**
* Set the indexed color of BlinkStick Pro with Processing color value for channel 0
*
* @param index Index of the LED
* @param value color as int
*/
public void setIndexedColor(int index, int value) {
int r = (value >> 16) & 0xFF;
int g = (value >> 8) & 0xFF;
int b = value & 0xFF;
this.setIndexedColor(0, index, r, g, b);
}
/**
* Set the color of the device with Processing color value
*
* @param value color as int
*/
public void setColor(int value) {
int r = (value >> 16) & 0xFF;
int g = (value >> 8) & 0xFF;
int b = value & 0xFF;
this.setColor(r, g, b);
}
/**
* Set the color of the device with string value
*
* @param value this can either be a named color "red", "green", "blue" and etc.
* or a hex color in #rrggbb format
*/
public void setColor(String value) {
if (COLORS.containsKey(value)) {
this.setColor(hex2Rgb(COLORS.get(value)));
} else {
this.setColor(hex2Rgb(value));
}
}
/**
* Set random color
*/
public void setRandomColor() {
Random random = new Random();
this.setColor(
random.nextInt(256),
random.nextInt(256),
random.nextInt(256));
}
/**
* Turn BlinkStick off
*/
public void turnOff() {
this.setColor(0, 0, 0);
}
/**
* Convert hex string to color object
*
* @param colorStr Color value as hex string #rrggbb
*
* @return color object
*/
private int hex2Rgb(String colorStr) {
int red = Integer.valueOf(colorStr.substring(1, 3), 16)+ 0;
int green = Integer.valueOf(colorStr.substring(3, 5), 16) + 0;
int blue = Integer.valueOf(colorStr.substring(5, 7), 16) + 0;
return (255 << 24) | (red << 16) | (green << 8) | blue;
}
/**
* Get the current color of the device as int
*
* @return The current color of the device as int
*/
public int getColor() {
byte[] data = new byte[33];
data[0] = 1;// First byte is ReportID
try {
int read = getFeatureReport(data);
if (read > 0) {
return (255 << 24) | (data[1] << 16) | (data[2] << 8) | data[3];
}
} catch (Exception e) {
}
return 0;
}
/**
* Get the current color of the device in #rrggbb format
*
* @return Returns the current color of the device as #rrggbb formated string
*/
public String getColorString() {
int c = getColor();
int red = (c >> 16) & 0xFF;
int green = (c >> 8) & 0xFF;
int blue = c & 0xFF;
return "#" + String.format("%02X", red)
+ String.format("%02X", green)
+ String.format("%02X", blue);
}
/**
* Get value of InfoBlocks
*
* @param id InfoBlock id, should be 1 or 2 as only supported info blocks
*/
private String getInfoBlock(int id) {
byte[] data = new byte[33];
data[0] = (byte) (id + 1);
String result = "";
try {
int read = getFeatureReport(data);
if (read > 0) {
for (int i = 1; i < data.length; i++) {
if (i == 0) {
break;
}
result += (char) data[i];
}
}
} catch (Exception e) {
}
return result;
}
/**
* Get value of InfoBlock1
*
* @return The value of info block 1
*/
public String getInfoBlock1() {
return getInfoBlock(1);
}
/**
* Get value of InfoBlock2
*
* @return The value of info block 2
*/
public String getInfoBlock2() {
return getInfoBlock(2);
}
/**
* Set value for InfoBlocks
*
* @param id InfoBlock id, should be 1 or 2 as only supported info blocks
* @param value The value to be written to the info block
*/
private void setInfoBlock(int id, String value) {
char[] charArray = value.toCharArray();
byte[] data = new byte[33];
data[0] = (byte) (id + 1);
for (int i = 0; i < charArray.length; i++) {
if (i > 32) {
break;
}
data[i + 1] = (byte) charArray[i];
}
try {
sendFeatureReport(data);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Set value for InfoBlock1
*
* @param value The value to be written to the info block 1
*/
public void setInfoBlock1(String value) {
setInfoBlock(1, value);
}
/**
* Set value for InfoBlock2
*
* @param value The value to be written to the info block 2
*/
public void setInfoBlock2(String value) {
setInfoBlock(2, value);
}
/**
* Get the manufacturer of the device
*
* @return Returns the manufacturer name of the device
*/
public String getManufacturer() {
if (manufacturer == null)
{
manufacturer = "";
byte[] rawDescs = connection.getRawDescriptors();
byte[] buffer = new byte[255];
int idxMan = rawDescs[14];
try
{
int rdo = connection.controlTransfer(UsbConstants.USB_DIR_IN
| UsbConstants.USB_TYPE_STANDARD, STD_USB_REQUEST_GET_DESCRIPTOR,
(LIBUSB_DT_STRING << 8) | idxMan, 0, buffer, 0xFF, 0);
manufacturer = new String(buffer, 2, rdo - 2, "UTF-16LE");
}
catch (Exception e)
{
}
}
return manufacturer;
}
/**
* Get the product description of the device
*
* @return Returns the product name of the device.
*/
public String getProduct() {
if (productName == null)
{
productName = "";
byte[] rawDescs = connection.getRawDescriptors();
byte[] buffer = new byte[255];
int idxPrd = rawDescs[15];
try
{
int rdo = connection.controlTransfer(UsbConstants.USB_DIR_IN
| UsbConstants.USB_TYPE_STANDARD, STD_USB_REQUEST_GET_DESCRIPTOR,
(LIBUSB_DT_STRING << 8) | idxPrd, 0, buffer, 0xFF, 0);
productName = new String(buffer, 2, rdo - 2, "UTF-16LE");
}
catch (Exception e)
{
}
}
return productName;
}
/**
* Get the serial number of the device
*
* @return Returns the serial number of device.
*/
public String getSerial() {
return connection.getSerial();
}
/**
* Determine report id for the amount of data to be sent
*
* @return Returns the report id
*/
private byte determineReportId(int length) {
byte reportId = 9;
//Automatically determine the correct report id to send the data to
if (length <= 8 * 3)
{
reportId = 6;
}
else if (length <= 16 * 3)
{
reportId = 7;
}
else if (length <= 32 * 3)
{
reportId = 8;
}
else if (length <= 64 * 3)
{
reportId = 9;
}
else if (length <= 128 * 3)
{
reportId = 10;
}
return reportId;
}
/**
* Determine the adjusted maximum amount of LED for the report
*
* @return Returns the adjusted amount of LED data
*/
private byte determineMaxLeds(int length) {
byte maxLeds = 64;
//Automatically determine the correct report id to send the data to
if (length <= 8 * 3)
{
maxLeds = 8;
}
else if (length <= 16 * 3)
{
maxLeds = 16;
}
else if (length <= 32 * 3)
{
maxLeds = 32;
}
else if (length <= 64 * 3)
{
maxLeds = 64;
}
else if (length <= 128 * 3)
{
maxLeds = 64;
}
return maxLeds;
}
/**
* Send a packet of data to LEDs on channel 0 (R)
*
* @param colorData Report data must be a byte array in the following format: [g0, r0, b0, g1, r1, b1, g2, r2, b2 ...]
*/
public void setColors(byte[] colorData)
{
this.setColors((byte)0, colorData);
}
/**
* Send a packet of data to LEDs
*
* @param channel Channel (0 - R, 1 - G, 2 - B)
* @param colorData Report data must be a byte array in the following format: [g0, r0, b0, g1, r1, b1, g2, r2, b2 ...]
*/
public void setColors(int channel, byte[] colorData)
{
this.setColors((byte)channel, colorData);
}
/**
* Send a packet of data to LEDs
*
* @param channel Channel (0 - R, 1 - G, 2 - B)
* @param colorData Report data must be a byte array in the following format: [g0, r0, b0, g1, r1, b1, g2, r2, b2 ...]
*/
public void setColors(byte channel, byte[] colorData)
{
byte leds = this.determineMaxLeds(colorData.length);
byte[] data = new byte[leds * 3 + 2];
data[0] = this.determineReportId(colorData.length);
data[1] = channel;
for (int i = 0; i < Math.min(colorData.length, data.length - 2); i++)
{
data[i + 2] = colorData[i];
}
for (int i = colorData.length + 2; i < data.length; i++)
{
data[i] = 0;
}
try {
sendFeatureReport(data);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Set the mode of BlinkStick Pro as int
*
* @param mode 0 - Normal, 1 - Inverse, 2 - WS2812, 3 - WS2812 mirror
*/
public void setMode(int mode)
{
this.setMode((byte)mode);
}
/**
* Set the mode of BlinkStick Pro as byte
*
* @param mode 0 - Normal, 1 - Inverse, 2 - WS2812, 3 - WS2812 mirror
*/
public void setMode(byte mode)
{
try {
sendFeatureReport(new byte[] {4, mode});
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Get the mode of BlinkStick Pro
*
* @return 0 - Normal, 1 - Inverse, 2 - WS2812, 3 - WS2812 mirror
*/
public byte getMode()
{
byte[] data = new byte[2];
data[0] = 4;// First byte is ReportID
try {
int read = getFeatureReport(data);
if (read > 0) {
return data[1];
}
} catch (Exception e) {
}
return -1;
}
/**
* Variable holds the list of valid CSS colors as a hashtable
*/
private static final Hashtable<String, String> COLORS = new Hashtable<String, String>() {
/**
*
*/
private static final long serialVersionUID = 1L;
{
put("aqua", "#00ffff");
put("aliceblue", "#f0f8ff");
put("antiquewhite", "#faebd7");
put("black", "#000000");
put("blue", "#0000ff");
put("cyan", "#00ffff");
put("darkblue", "#00008b");
put("darkcyan", "#008b8b");
put("darkgreen", "#006400");
put("darkturquoise", "#00ced1");
put("deepskyblue", "#00bfff");
put("green", "#008000");
put("lime", "#00ff00");
put("mediumblue", "#0000cd");
put("mediumspringgreen", "#00fa9a");
put("navy", "#000080");
put("springgreen", "#00ff7f");
put("teal", "#008080");
put("midnightblue", "#191970");
put("dodgerblue", "#1e90ff");
put("lightseagreen", "#20b2aa");
put("forestgreen", "#228b22");
put("seagreen", "#2e8b57");
put("darkslategray", "#2f4f4f");
put("darkslategrey", "#2f4f4f");
put("limegreen", "#32cd32");
put("mediumseagreen", "#3cb371");
put("turquoise", "#40e0d0");
put("royalblue", "#4169e1");
put("steelblue", "#4682b4");
put("darkslateblue", "#483d8b");
put("mediumturquoise", "#48d1cc");
put("indigo", "#4b0082");
put("darkolivegreen", "#556b2f");
put("cadetblue", "#5f9ea0");
put("cornflowerblue", "#6495ed");
put("mediumaquamarine", "#66cdaa");
put("dimgray", "#696969");
put("dimgrey", "#696969");
put("slateblue", "#6a5acd");
put("olivedrab", "#6b8e23");
put("slategray", "#708090");
put("slategrey", "#708090");
put("lightslategray", "#778899");
put("lightslategrey", "#778899");
put("mediumslateblue", "#7b68ee");
put("lawngreen", "#7cfc00");
put("aquamarine", "#7fffd4");
put("chartreuse", "#7fff00");
put("gray", "#808080");
put("grey", "#808080");
put("maroon", "#800000");
put("olive", "#808000");
put("purple", "#800080");
put("lightskyblue", "#87cefa");
put("skyblue", "#87ceeb");
put("blueviolet", "#8a2be2");
put("darkmagenta", "#8b008b");
put("darkred", "#8b0000");
put("saddlebrown", "#8b4513");
put("darkseagreen", "#8fbc8f");
put("lightgreen", "#90ee90");
put("mediumpurple", "#9370db");
put("darkviolet", "#9400d3");
put("palegreen", "#98fb98");
put("darkorchid", "#9932cc");
put("yellowgreen", "#9acd32");
put("sienna", "#a0522d");
put("brown", "#a52a2a");
put("darkgray", "#a9a9a9");
put("darkgrey", "#a9a9a9");
put("greenyellow", "#adff2f");
put("lightblue", "#add8e6");
put("paleturquoise", "#afeeee");
put("lightsteelblue", "#b0c4de");
put("powderblue", "#b0e0e6");
put("firebrick", "#b22222");
put("darkgoldenrod", "#b8860b");
put("mediumorchid", "#ba55d3");
put("rosybrown", "#bc8f8f");
put("darkkhaki", "#bdb76b");
put("silver", "#c0c0c0");
put("mediumvioletred", "#c71585");
put("indianred", "#cd5c5c");
put("peru", "#cd853f");
put("chocolate", "#d2691e");
put("tan", "#d2b48c");
put("lightgray", "#d3d3d3");
put("lightgrey", "#d3d3d3");
put("thistle", "#d8bfd8");
put("goldenrod", "#daa520");
put("orchid", "#da70d6");
put("palevioletred", "#db7093");
put("crimson", "#dc143c");
put("gainsboro", "#dcdcdc");
put("plum", "#dda0dd");
put("burlywood", "#deb887");
put("lightcyan", "#e0ffff");
put("lavender", "#e6e6fa");
put("darksalmon", "#e9967a");
put("palegoldenrod", "#eee8aa");
put("violet", "#ee82ee");
put("azure", "#f0ffff");
put("honeydew", "#f0fff0");
put("khaki", "#f0e68c");
put("lightcoral", "#f08080");
put("sandybrown", "#f4a460");
put("beige", "#f5f5dc");
put("mintcream", "#f5fffa");
put("wheat", "#f5deb3");
put("whitesmoke", "#f5f5f5");
put("ghostwhite", "#f8f8ff");
put("lightgoldenrodyellow", "#fafad2");
put("linen", "#faf0e6");
put("salmon", "#fa8072");
put("oldlace", "#fdf5e6");
put("bisque", "#ffe4c4");
put("blanchedalmond", "#ffebcd");
put("coral", "#ff7f50");
put("cornsilk", "#fff8dc");
put("darkorange", "#ff8c00");
put("deeppink", "#ff1493");
put("floralwhite", "#fffaf0");
put("fuchsia", "#ff00ff");
put("gold", "#ffd700");
put("hotpink", "#ff69b4");
put("ivory", "#fffff0");
put("lavenderblush", "#fff0f5");
put("lemonchiffon", "#fffacd");
put("lightpink", "#ffb6c1");
put("lightsalmon", "#ffa07a");
put("lightyellow", "#ffffe0");
put("magenta", "#ff00ff");
put("mistyrose", "#ffe4e1");
put("moccasin", "#ffe4b5");
put("navajowhite", "#ffdead");
put("orange", "#ffa500");
put("orangered", "#ff4500");
put("papayawhip", "#ffefd5");
put("peachpuff", "#ffdab9");
put("pink", "#ffc0cb");
put("red", "#ff0000");
put("seashell", "#fff5ee");
put("snow", "#fffafa");
put("tomato", "#ff6347");
put("white", "#ffffff");
put("yellow", "#ffff00");
}
};
}
| New methods to get major and minor version numbers from serial number
| src/com/agileinnovative/blinkstick/BlinkStick.java | New methods to get major and minor version numbers from serial number | <ide><path>rc/com/agileinnovative/blinkstick/BlinkStick.java
<ide> public void setConnection(UsbDeviceConnection con)
<ide> {
<ide> connection = con;
<add> }
<add>
<add> private int _VersionMajor = -1;
<add>
<add> /**
<add> * Get major version number from serial
<add> *
<add> * @return Major version number as int
<add> */
<add> public int getVersionMajor()
<add> {
<add> if (_VersionMajor == -1)
<add> {
<add> _VersionMajor = Integer.parseInt(getSerial().substring(getSerial().length() - 3, getSerial().length() - 2));
<add> }
<add> return _VersionMajor;
<add> }
<add>
<add> private int _VersionMinor = -1;
<add>
<add> /**
<add> * Get minor version number from serial
<add> *
<add> * @return Minor version number as int
<add> */
<add> public int getVersionMinor() {
<add> if (_VersionMinor == -1)
<add> {
<add> _VersionMinor = Integer.parseInt(getSerial().substring(getSerial().length() - 1, getSerial().length()));
<add> }
<add> return _VersionMinor;
<ide> }
<ide>
<ide> /** |
|
JavaScript | isc | e57793fab097f4cd6fbb50ad4633cf4270b237bc | 0 | openstreetmap/iD,openstreetmap/iD,openstreetmap/iD | import { dispatch as d3_dispatch } from 'd3-dispatch';
import { select as d3_select } from 'd3-selection';
import { drag as d3_drag } from 'd3-drag';
import * as countryCoder from '@ideditor/country-coder';
import { fileFetcher } from '../../core/file_fetcher';
import { osmEntity } from '../../osm/entity';
import { t } from '../../core/localizer';
import { services } from '../../services';
import { uiCombobox } from '../combobox';
import { utilKeybinding } from '../../util/keybinding';
import { utilArrayUniq, utilGetSetValue, utilNoAuto, utilRebind, utilTotalExtent, utilUnicodeCharsCount } from '../../util';
export {
uiFieldCombo as uiFieldManyCombo,
uiFieldCombo as uiFieldMultiCombo,
uiFieldCombo as uiFieldNetworkCombo,
uiFieldCombo as uiFieldSemiCombo,
uiFieldCombo as uiFieldTypeCombo
};
export function uiFieldCombo(field, context) {
var dispatch = d3_dispatch('change');
var _isMulti = (field.type === 'multiCombo' || field.type === 'manyCombo');
var _isNetwork = (field.type === 'networkCombo');
var _isSemi = (field.type === 'semiCombo');
var _optarray = field.options;
var _showTagInfoSuggestions = field.type !== 'manyCombo' && field.autoSuggestions !== false;
var _allowCustomValues = field.type !== 'manyCombo' && field.customValues !== false;
var _snake_case = (field.snake_case || (field.snake_case === undefined));
var _combobox = uiCombobox(context, 'combo-' + field.safeid)
.caseSensitive(field.caseSensitive)
.minItems(_isMulti || _isSemi ? 1 : 2);
var _container = d3_select(null);
var _inputWrap = d3_select(null);
var _input = d3_select(null);
var _comboData = [];
var _multiData = [];
var _entityIDs = [];
var _tags;
var _countryCode;
var _staticPlaceholder;
// initialize deprecated tags array
var _dataDeprecated = [];
fileFetcher.get('deprecated')
.then(function(d) { _dataDeprecated = d; })
.catch(function() { /* ignore */ });
// ensure multiCombo field.key ends with a ':'
if (_isMulti && field.key && /[^:]$/.test(field.key)) {
field.key += ':';
}
function snake(s) {
return s.replace(/\s+/g, '_').toLowerCase();
}
function clean(s) {
return s.split(';')
.map(function(s) { return s.trim(); })
.join(';');
}
// returns the tag value for a display value
// (for multiCombo, dval should be the key suffix, not the entire key)
function tagValue(dval) {
dval = clean(dval || '');
var found = _comboData.find(function(o) {
return o.key && clean(o.value) === dval;
});
if (found) return found.key;
if (field.type === 'typeCombo' && !dval) {
return 'yes';
}
return (_snake_case ? snake(dval) : dval) || undefined;
}
// returns the display value for a tag value
// (for multiCombo, tval should be the key suffix, not the entire key)
function displayValue(tval) {
tval = tval || '';
if (field.hasTextForStringId('options.' + tval)) {
return field.t('options.' + tval, { default: tval });
}
if (field.type === 'typeCombo' && tval.toLowerCase() === 'yes') {
return '';
}
return tval;
}
// Compute the difference between arrays of objects by `value` property
//
// objectDifference([{value:1}, {value:2}, {value:3}], [{value:2}])
// > [{value:1}, {value:3}]
//
function objectDifference(a, b) {
return a.filter(function(d1) {
return !b.some(function(d2) {
return !d2.isMixed && d1.value === d2.value;
});
});
}
function initCombo(selection, attachTo) {
if (!_allowCustomValues) {
selection.attr('readonly', 'readonly');
}
if (_showTagInfoSuggestions && services.taginfo) {
selection.call(_combobox.fetcher(setTaginfoValues), attachTo);
setTaginfoValues('', setPlaceholder);
} else {
selection.call(_combobox, attachTo);
setStaticValues(setPlaceholder);
}
}
function setStaticValues(callback) {
if (!_optarray) return;
_comboData = _optarray.map(function(v) {
return {
key: v,
value: field.t('options.' + v, { default: v }),
title: v,
display: field.t.html('options.' + v, { default: v }),
klass: field.hasTextForStringId('options.' + v) ? '' : 'raw-option'
};
});
_combobox.data(objectDifference(_comboData, _multiData));
if (callback) callback(_comboData);
}
function setTaginfoValues(q, callback) {
var fn = _isMulti ? 'multikeys' : 'values';
var query = (_isMulti ? field.key : '') + q;
var hasCountryPrefix = _isNetwork && _countryCode && _countryCode.indexOf(q.toLowerCase()) === 0;
if (hasCountryPrefix) {
query = _countryCode + ':';
}
var params = {
debounce: (q !== ''),
key: field.key,
query: query
};
if (_entityIDs.length) {
params.geometry = context.graph().geometry(_entityIDs[0]);
}
services.taginfo[fn](params, function(err, data) {
if (err) return;
data = data.filter(function(d) {
if (field.type === 'typeCombo' && d.value === 'yes') {
// don't show the fallback value
return false;
}
// don't show values with very low usage
return !d.count || d.count > 10;
});
var deprecatedValues = osmEntity.deprecatedTagValuesByKey(_dataDeprecated)[field.key];
if (deprecatedValues) {
// don't suggest deprecated tag values
data = data.filter(function(d) {
return deprecatedValues.indexOf(d.value) === -1;
});
}
if (hasCountryPrefix) {
data = data.filter(function(d) {
return d.value.toLowerCase().indexOf(_countryCode + ':') === 0;
});
}
// hide the caret if there are no suggestions
_container.classed('empty-combobox', data.length === 0);
_comboData = data.map(function(d) {
var k = d.value;
if (_isMulti) k = k.replace(field.key, '');
var label = field.t('options.' + k, { default: k });
return {
key: k,
value: label,
display: field.t.html('options.' + k, { default: k }),
title: d.title || label,
klass: field.hasTextForStringId('options.' + k) ? '' : 'raw-option'
};
});
_comboData = objectDifference(_comboData, _multiData);
if (callback) callback(_comboData);
});
}
function setPlaceholder(values) {
if (_isMulti || _isSemi) {
_staticPlaceholder = field.placeholder() || t('inspector.add');
} else {
var vals = values
.map(function(d) { return d.value; })
.filter(function(s) { return s.length < 20; });
var placeholders = vals.length > 1 ? vals : values.map(function(d) { return d.key; });
_staticPlaceholder = field.placeholder() || placeholders.slice(0, 3).join(', ');
}
if (!/(…|\.\.\.)$/.test(_staticPlaceholder)) {
_staticPlaceholder += '…';
}
var ph;
if (!_isMulti && !_isSemi && _tags && Array.isArray(_tags[field.key])) {
ph = t('inspector.multiple_values');
} else {
ph = _staticPlaceholder;
}
_container.selectAll('input')
.attr('placeholder', ph);
}
function change() {
var t = {};
var val;
if (_isMulti || _isSemi) {
val = tagValue(utilGetSetValue(_input).replace(/,/g, ';')) || '';
_container.classed('active', false);
utilGetSetValue(_input, '');
var vals = val.split(';').filter(Boolean);
if (!vals.length) return;
if (_isMulti) {
utilArrayUniq(vals).forEach(function(v) {
var key = (field.key || '') + v;
if (_tags) {
// don't set a multicombo value to 'yes' if it already has a non-'no' value
// e.g. `language:de=main`
var old = _tags[key];
if (typeof old === 'string' && old.toLowerCase() !== 'no') return;
}
key = context.cleanTagKey(key);
field.keys.push(key);
t[key] = 'yes';
});
} else if (_isSemi) {
var arr = _multiData.map(function(d) { return d.key; });
arr = arr.concat(vals);
t[field.key] = context.cleanTagValue(utilArrayUniq(arr).filter(Boolean).join(';'));
}
window.setTimeout(function() { _input.node().focus(); }, 10);
} else {
var rawValue = utilGetSetValue(_input);
// don't override multiple values with blank string
if (!rawValue && Array.isArray(_tags[field.key])) return;
val = context.cleanTagValue(tagValue(rawValue));
t[field.key] = val || undefined;
}
dispatch.call('change', this, t);
}
function removeMultikey(d3_event, d) {
d3_event.preventDefault();
d3_event.stopPropagation();
var t = {};
if (_isMulti) {
t[d.key] = undefined;
} else if (_isSemi) {
var arr = _multiData.map(function(md) {
return md.key === d.key ? null : md.key;
}).filter(Boolean);
arr = utilArrayUniq(arr);
t[field.key] = arr.length ? arr.join(';') : undefined;
}
dispatch.call('change', this, t);
}
function combo(selection) {
_container = selection.selectAll('.form-field-input-wrap')
.data([0]);
var type = (_isMulti || _isSemi) ? 'multicombo': 'combo';
_container = _container.enter()
.append('div')
.attr('class', 'form-field-input-wrap form-field-input-' + type)
.merge(_container);
if (_isMulti || _isSemi) {
_container = _container.selectAll('.chiplist')
.data([0]);
var listClass = 'chiplist';
// Use a separate line for each value in the Destinations and Via fields
// to mimic highway exit signs
if (field.key === 'destination' || field.key === 'via') {
listClass += ' full-line-chips';
}
_container = _container.enter()
.append('ul')
.attr('class', listClass)
.on('click', function() {
window.setTimeout(function() { _input.node().focus(); }, 10);
})
.merge(_container);
_inputWrap = _container.selectAll('.input-wrap')
.data([0]);
_inputWrap = _inputWrap.enter()
.append('li')
.attr('class', 'input-wrap')
.merge(_inputWrap);
_input = _inputWrap.selectAll('input')
.data([0]);
} else {
_input = _container.selectAll('input')
.data([0]);
}
_input = _input.enter()
.append('input')
.attr('type', 'text')
.attr('id', field.domId)
.call(utilNoAuto)
.call(initCombo, selection)
.merge(_input);
if (_isNetwork) {
var extent = combinedEntityExtent();
var countryCode = extent && countryCoder.iso1A2Code(extent.center());
_countryCode = countryCode && countryCode.toLowerCase();
}
_input
.on('change', change)
.on('blur', change);
_input
.on('keydown.field', function(d3_event) {
switch (d3_event.keyCode) {
case 13: // ↩ Return
_input.node().blur(); // blurring also enters the value
d3_event.stopPropagation();
break;
}
});
if (_isMulti || _isSemi) {
_combobox
.on('accept', function() {
_input.node().blur();
_input.node().focus();
});
_input
.on('focus', function() { _container.classed('active', true); });
}
}
combo.tags = function(tags) {
_tags = tags;
if (_isMulti || _isSemi) {
_multiData = [];
var maxLength;
if (_isMulti) {
// Build _multiData array containing keys already set..
for (var k in tags) {
if (field.key && k.indexOf(field.key) !== 0) continue;
if (!field.key && field.keys.indexOf(k) === -1) continue;
var v = tags[k];
if (!v || (typeof v === 'string' && v.toLowerCase() === 'no')) continue;
var suffix = field.key ? k.substr(field.key.length) : k;
_multiData.push({
key: k,
value: displayValue(suffix),
isMixed: Array.isArray(v)
});
}
if (field.key) {
// Set keys for form-field modified (needed for undo and reset buttons)..
field.keys = _multiData.map(function(d) { return d.key; });
// limit the input length so it fits after prepending the key prefix
maxLength = context.maxCharsForTagKey() - utilUnicodeCharsCount(field.key);
} else {
maxLength = context.maxCharsForTagKey();
}
} else if (_isSemi) {
var allValues = [];
var commonValues;
if (Array.isArray(tags[field.key])) {
tags[field.key].forEach(function(tagVal) {
var thisVals = utilArrayUniq((tagVal || '').split(';')).filter(Boolean);
allValues = allValues.concat(thisVals);
if (!commonValues) {
commonValues = thisVals;
} else {
commonValues = commonValues.filter(value => thisVals.includes(value));
}
});
allValues = utilArrayUniq(allValues).filter(Boolean);
} else {
allValues = utilArrayUniq((tags[field.key] || '').split(';')).filter(Boolean);
commonValues = allValues;
}
_multiData = allValues.map(function(v) {
return {
key: v,
value: displayValue(v),
isMixed: !commonValues.includes(v)
};
});
var currLength = utilUnicodeCharsCount(commonValues.join(';'));
// limit the input length to the remaining available characters
maxLength = context.maxCharsForTagValue() - currLength;
if (currLength > 0) {
// account for the separator if a new value will be appended to existing
maxLength -= 1;
}
}
// a negative maxlength doesn't make sense
maxLength = Math.max(0, maxLength);
var allowDragAndDrop = _isSemi // only semiCombo values are ordered
&& !Array.isArray(tags[field.key]);
// Exclude existing multikeys from combo options..
var available = objectDifference(_comboData, _multiData);
_combobox.data(available);
// Hide 'Add' button if this field uses fixed set of
// options and they're all currently used,
// or if the field is already at its character limit
var hideAdd = (!_allowCustomValues && !available.length) || maxLength <= 0;
_container.selectAll('.chiplist .input-wrap')
.style('display', hideAdd ? 'none' : null);
// Render chips
var chips = _container.selectAll('.chip')
.data(_multiData);
chips.exit()
.remove();
var enter = chips.enter()
.insert('li', '.input-wrap')
.attr('class', 'chip');
enter.append('span');
enter.append('a');
chips = chips.merge(enter)
.order()
.classed('raw-value', function(d) {
var k = d.key;
if (_isMulti) k = k.replace(field.key, '');
return !field.hasTextForStringId('options.' + k);
})
.classed('draggable', allowDragAndDrop)
.classed('mixed', function(d) {
return d.isMixed;
})
.attr('title', function(d) {
return d.isMixed ? t('inspector.unshared_value_tooltip') : null;
});
if (allowDragAndDrop) {
registerDragAndDrop(chips);
}
chips.select('span')
.html(function(d) { return d.value; });
chips.select('a')
.attr('href', '#')
.on('click', removeMultikey)
.attr('class', 'remove')
.html('×');
} else {
var isMixed = Array.isArray(tags[field.key]);
var mixedValues = isMixed && tags[field.key].map(function(val) {
return displayValue(val);
}).filter(Boolean);
var showsValue = !isMixed && tags[field.key] && !(field.type === 'typeCombo' && tags[field.key] === 'yes');
var isRawValue = showsValue && !field.hasTextForStringId('options.' + tags[field.key]);
var isKnownValue = showsValue && !isRawValue;
var isReadOnly = !_allowCustomValues || isKnownValue;
utilGetSetValue(_input, !isMixed ? displayValue(tags[field.key]) : '')
.classed('raw-value', isRawValue)
.classed('known-value', isKnownValue)
.attr('readonly', isReadOnly ? 'readonly' : undefined)
.attr('title', isMixed ? mixedValues.join('\n') : undefined)
.attr('placeholder', isMixed ? t('inspector.multiple_values') : _staticPlaceholder || '')
.classed('mixed', isMixed)
.on('keydown.deleteCapture', function(d3_event) {
if (isReadOnly &&
isKnownValue &&
(d3_event.keyCode === utilKeybinding.keyCodes['⌫'] ||
d3_event.keyCode === utilKeybinding.keyCodes['⌦'])) {
d3_event.preventDefault();
d3_event.stopPropagation();
var t = {};
t[field.key] = undefined;
dispatch.call('change', this, t);
}
});
}
};
function registerDragAndDrop(selection) {
// allow drag and drop re-ordering of chips
var dragOrigin, targetIndex;
selection.call(d3_drag()
.on('start', function(d3_event) {
dragOrigin = {
x: d3_event.x,
y: d3_event.y
};
targetIndex = null;
})
.on('drag', function(d3_event) {
var x = d3_event.x - dragOrigin.x,
y = d3_event.y - dragOrigin.y;
if (!d3_select(this).classed('dragging') &&
// don't display drag until dragging beyond a distance threshold
Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)) <= 5) return;
var index = selection.nodes().indexOf(this);
d3_select(this)
.classed('dragging', true);
targetIndex = null;
var targetIndexOffsetTop = null;
var draggedTagWidth = d3_select(this).node().offsetWidth;
if (field.key === 'destination' || field.key === 'via') { // meaning tags are full width
_container.selectAll('.chip')
.style('transform', function(d2, index2) {
var node = d3_select(this).node();
if (index === index2) {
return 'translate(' + x + 'px, ' + y + 'px)';
// move the dragged tag up the order
} else if (index2 > index && d3_event.y > node.offsetTop) {
if (targetIndex === null || index2 > targetIndex) {
targetIndex = index2;
}
return 'translateY(-100%)';
// move the dragged tag down the order
} else if (index2 < index && d3_event.y < node.offsetTop + node.offsetHeight) {
if (targetIndex === null || index2 < targetIndex) {
targetIndex = index2;
}
return 'translateY(100%)';
}
return null;
});
} else {
_container.selectAll('.chip')
.each(function(d2, index2) {
var node = d3_select(this).node();
// check the cursor is in the bounding box
if (
index !== index2 &&
d3_event.x < node.offsetLeft + node.offsetWidth + 5 &&
d3_event.x > node.offsetLeft &&
d3_event.y < node.offsetTop + node.offsetHeight &&
d3_event.y > node.offsetTop
) {
targetIndex = index2;
targetIndexOffsetTop = node.offsetTop;
}
})
.style('transform', function(d2, index2) {
var node = d3_select(this).node();
if (index === index2) {
return 'translate(' + x + 'px, ' + y + 'px)';
}
// only translate tags in the same row
if (node.offsetTop === targetIndexOffsetTop) {
if (index2 < index && index2 >= targetIndex) {
return 'translateX(' + draggedTagWidth + 'px)';
} else if (index2 > index && index2 <= targetIndex) {
return 'translateX(-' + draggedTagWidth + 'px)';
}
}
return null;
});
}
})
.on('end', function() {
if (!d3_select(this).classed('dragging')) {
return;
}
var index = selection.nodes().indexOf(this);
d3_select(this)
.classed('dragging', false);
_container.selectAll('.chip')
.style('transform', null);
if (typeof targetIndex === 'number') {
var element = _multiData[index];
_multiData.splice(index, 1);
_multiData.splice(targetIndex, 0, element);
var t = {};
if (_multiData.length) {
t[field.key] = _multiData.map(function(element) {
return element.key;
}).join(';');
} else {
t[field.key] = undefined;
}
dispatch.call('change', this, t);
}
dragOrigin = undefined;
targetIndex = undefined;
})
);
}
combo.focus = function() {
_input.node().focus();
};
combo.entityIDs = function(val) {
if (!arguments.length) return _entityIDs;
_entityIDs = val;
return combo;
};
function combinedEntityExtent() {
return _entityIDs && _entityIDs.length && utilTotalExtent(_entityIDs, context.graph());
}
return utilRebind(combo, dispatch, 'on');
}
| modules/ui/fields/combo.js | import { dispatch as d3_dispatch } from 'd3-dispatch';
import { select as d3_select } from 'd3-selection';
import { drag as d3_drag } from 'd3-drag';
import * as countryCoder from '@ideditor/country-coder';
import { fileFetcher } from '../../core/file_fetcher';
import { osmEntity } from '../../osm/entity';
import { t } from '../../core/localizer';
import { services } from '../../services';
import { uiCombobox } from '../combobox';
import { utilKeybinding } from '../../util/keybinding';
import { utilArrayUniq, utilGetSetValue, utilNoAuto, utilRebind, utilTotalExtent, utilUnicodeCharsCount } from '../../util';
export {
uiFieldCombo as uiFieldManyCombo,
uiFieldCombo as uiFieldMultiCombo,
uiFieldCombo as uiFieldNetworkCombo,
uiFieldCombo as uiFieldSemiCombo,
uiFieldCombo as uiFieldTypeCombo
};
export function uiFieldCombo(field, context) {
var dispatch = d3_dispatch('change');
var _isMulti = (field.type === 'multiCombo' || field.type === 'manyCombo');
var _isNetwork = (field.type === 'networkCombo');
var _isSemi = (field.type === 'semiCombo');
var _optarray = field.options;
var _showTagInfoSuggestions = field.type !== 'manyCombo' && field.autoSuggestions !== false;
var _allowCustomValues = field.type !== 'manyCombo' && field.customValues !== false;
var _snake_case = (field.snake_case || (field.snake_case === undefined));
var _combobox = uiCombobox(context, 'combo-' + field.safeid)
.caseSensitive(field.caseSensitive)
.minItems(_isMulti || _isSemi ? 1 : 2);
var _container = d3_select(null);
var _inputWrap = d3_select(null);
var _input = d3_select(null);
var _comboData = [];
var _multiData = [];
var _entityIDs = [];
var _tags;
var _countryCode;
var _staticPlaceholder;
// initialize deprecated tags array
var _dataDeprecated = [];
fileFetcher.get('deprecated')
.then(function(d) { _dataDeprecated = d; })
.catch(function() { /* ignore */ });
// ensure multiCombo field.key ends with a ':'
if (_isMulti && field.key && /[^:]$/.test(field.key)) {
field.key += ':';
}
function snake(s) {
return s.replace(/\s+/g, '_').toLowerCase();
}
function clean(s) {
return s.split(';')
.map(function(s) { return s.trim(); })
.join(';');
}
// returns the tag value for a display value
// (for multiCombo, dval should be the key suffix, not the entire key)
function tagValue(dval) {
dval = clean(dval || '');
var found = _comboData.find(function(o) {
return o.key && clean(o.value) === dval;
});
if (found) return found.key;
if (field.type === 'typeCombo' && !dval) {
return 'yes';
}
return (_snake_case ? snake(dval) : dval) || undefined;
}
// returns the display value for a tag value
// (for multiCombo, tval should be the key suffix, not the entire key)
function displayValue(tval) {
tval = tval || '';
if (field.hasTextForStringId('options.' + tval)) {
return field.t('options.' + tval, { default: tval });
}
if (field.type === 'typeCombo' && tval.toLowerCase() === 'yes') {
return '';
}
return tval;
}
// Compute the difference between arrays of objects by `value` property
//
// objectDifference([{value:1}, {value:2}, {value:3}], [{value:2}])
// > [{value:1}, {value:3}]
//
function objectDifference(a, b) {
return a.filter(function(d1) {
return !b.some(function(d2) {
return !d2.isMixed && d1.value === d2.value;
});
});
}
function initCombo(selection, attachTo) {
if (!_allowCustomValues) {
selection.attr('readonly', 'readonly');
}
if (_showTagInfoSuggestions && services.taginfo) {
selection.call(_combobox.fetcher(setTaginfoValues), attachTo);
setTaginfoValues('', setPlaceholder);
} else {
selection.call(_combobox, attachTo);
setStaticValues(setPlaceholder);
}
}
function setStaticValues(callback) {
if (!_optarray) return;
_comboData = _optarray.map(function(v) {
return {
key: v,
value: field.t('options.' + v, { default: v }),
title: v,
display: field.t.html('options.' + v, { default: v }),
klass: field.hasTextForStringId('options.' + v) ? '' : 'raw-option'
};
});
_combobox.data(objectDifference(_comboData, _multiData));
if (callback) callback(_comboData);
}
function setTaginfoValues(q, callback) {
var fn = _isMulti ? 'multikeys' : 'values';
var query = (_isMulti ? field.key : '') + q;
var hasCountryPrefix = _isNetwork && _countryCode && _countryCode.indexOf(q.toLowerCase()) === 0;
if (hasCountryPrefix) {
query = _countryCode + ':';
}
var params = {
debounce: (q !== ''),
key: field.key,
query: query
};
if (_entityIDs.length) {
params.geometry = context.graph().geometry(_entityIDs[0]);
}
services.taginfo[fn](params, function(err, data) {
if (err) return;
data = data.filter(function(d) {
if (field.type === 'typeCombo' && d.value === 'yes') {
// don't show the fallback value
return false;
}
// don't show values with very low usage
return !d.count || d.count > 10;
});
var deprecatedValues = osmEntity.deprecatedTagValuesByKey(_dataDeprecated)[field.key];
if (deprecatedValues) {
// don't suggest deprecated tag values
data = data.filter(function(d) {
return deprecatedValues.indexOf(d.value) === -1;
});
}
if (hasCountryPrefix) {
data = data.filter(function(d) {
return d.value.toLowerCase().indexOf(_countryCode + ':') === 0;
});
}
// hide the caret if there are no suggestions
_container.classed('empty-combobox', data.length === 0);
_comboData = data.map(function(d) {
var k = d.value;
if (_isMulti) k = k.replace(field.key, '');
var label = field.t('options.' + k, { default: k });
return {
key: k,
value: label,
display: field.t.html('options.' + k, { default: k }),
title: d.title || label,
klass: field.hasTextForStringId('options.' + k) ? '' : 'raw-option'
};
});
_comboData = objectDifference(_comboData, _multiData);
if (callback) callback(_comboData);
});
}
function setPlaceholder(values) {
if (_isMulti || _isSemi) {
_staticPlaceholder = field.placeholder() || t('inspector.add');
} else {
var vals = values
.map(function(d) { return d.value; })
.filter(function(s) { return s.length < 20; });
var placeholders = vals.length > 1 ? vals : values.map(function(d) { return d.key; });
_staticPlaceholder = field.placeholder() || placeholders.slice(0, 3).join(', ');
}
if (!/(…|\.\.\.)$/.test(_staticPlaceholder)) {
_staticPlaceholder += '…';
}
var ph;
if (!_isMulti && !_isSemi && _tags && Array.isArray(_tags[field.key])) {
ph = t('inspector.multiple_values');
} else {
ph = _staticPlaceholder;
}
_container.selectAll('input')
.attr('placeholder', ph);
}
function change() {
var t = {};
var val;
if (_isMulti || _isSemi) {
val = tagValue(utilGetSetValue(_input).replace(/,/g, ';')) || '';
_container.classed('active', false);
utilGetSetValue(_input, '');
var vals = val.split(';').filter(Boolean);
if (!vals.length) return;
if (_isMulti) {
utilArrayUniq(vals).forEach(function(v) {
var key = (field.key || '') + v;
if (_tags) {
// don't set a multicombo value to 'yes' if it already has a non-'no' value
// e.g. `language:de=main`
var old = _tags[key];
if (typeof old === 'string' && old.toLowerCase() !== 'no') return;
}
key = context.cleanTagKey(key);
field.keys.push(key);
t[key] = 'yes';
});
} else if (_isSemi) {
var arr = _multiData.map(function(d) { return d.key; });
arr = arr.concat(vals);
t[field.key] = context.cleanTagValue(utilArrayUniq(arr).filter(Boolean).join(';'));
}
window.setTimeout(function() { _input.node().focus(); }, 10);
} else {
var rawValue = utilGetSetValue(_input);
// don't override multiple values with blank string
if (!rawValue && Array.isArray(_tags[field.key])) return;
val = context.cleanTagValue(tagValue(rawValue));
t[field.key] = val || undefined;
}
dispatch.call('change', this, t);
}
function removeMultikey(d3_event, d) {
d3_event.preventDefault();
d3_event.stopPropagation();
var t = {};
if (_isMulti) {
t[d.key] = undefined;
} else if (_isSemi) {
var arr = _multiData.map(function(md) {
return md.key === d.key ? null : md.key;
}).filter(Boolean);
arr = utilArrayUniq(arr);
t[field.key] = arr.length ? arr.join(';') : undefined;
}
dispatch.call('change', this, t);
}
function combo(selection) {
_container = selection.selectAll('.form-field-input-wrap')
.data([0]);
var type = (_isMulti || _isSemi) ? 'multicombo': 'combo';
_container = _container.enter()
.append('div')
.attr('class', 'form-field-input-wrap form-field-input-' + type)
.merge(_container);
if (_isMulti || _isSemi) {
_container = _container.selectAll('.chiplist')
.data([0]);
var listClass = 'chiplist';
// Use a separate line for each value in the Destinations field
// to mimic highway exit signs
if (field.key === 'destination') {
listClass += ' full-line-chips';
}
_container = _container.enter()
.append('ul')
.attr('class', listClass)
.on('click', function() {
window.setTimeout(function() { _input.node().focus(); }, 10);
})
.merge(_container);
_inputWrap = _container.selectAll('.input-wrap')
.data([0]);
_inputWrap = _inputWrap.enter()
.append('li')
.attr('class', 'input-wrap')
.merge(_inputWrap);
_input = _inputWrap.selectAll('input')
.data([0]);
} else {
_input = _container.selectAll('input')
.data([0]);
}
_input = _input.enter()
.append('input')
.attr('type', 'text')
.attr('id', field.domId)
.call(utilNoAuto)
.call(initCombo, selection)
.merge(_input);
if (_isNetwork) {
var extent = combinedEntityExtent();
var countryCode = extent && countryCoder.iso1A2Code(extent.center());
_countryCode = countryCode && countryCode.toLowerCase();
}
_input
.on('change', change)
.on('blur', change);
_input
.on('keydown.field', function(d3_event) {
switch (d3_event.keyCode) {
case 13: // ↩ Return
_input.node().blur(); // blurring also enters the value
d3_event.stopPropagation();
break;
}
});
if (_isMulti || _isSemi) {
_combobox
.on('accept', function() {
_input.node().blur();
_input.node().focus();
});
_input
.on('focus', function() { _container.classed('active', true); });
}
}
combo.tags = function(tags) {
_tags = tags;
if (_isMulti || _isSemi) {
_multiData = [];
var maxLength;
if (_isMulti) {
// Build _multiData array containing keys already set..
for (var k in tags) {
if (field.key && k.indexOf(field.key) !== 0) continue;
if (!field.key && field.keys.indexOf(k) === -1) continue;
var v = tags[k];
if (!v || (typeof v === 'string' && v.toLowerCase() === 'no')) continue;
var suffix = field.key ? k.substr(field.key.length) : k;
_multiData.push({
key: k,
value: displayValue(suffix),
isMixed: Array.isArray(v)
});
}
if (field.key) {
// Set keys for form-field modified (needed for undo and reset buttons)..
field.keys = _multiData.map(function(d) { return d.key; });
// limit the input length so it fits after prepending the key prefix
maxLength = context.maxCharsForTagKey() - utilUnicodeCharsCount(field.key);
} else {
maxLength = context.maxCharsForTagKey();
}
} else if (_isSemi) {
var allValues = [];
var commonValues;
if (Array.isArray(tags[field.key])) {
tags[field.key].forEach(function(tagVal) {
var thisVals = utilArrayUniq((tagVal || '').split(';')).filter(Boolean);
allValues = allValues.concat(thisVals);
if (!commonValues) {
commonValues = thisVals;
} else {
commonValues = commonValues.filter(value => thisVals.includes(value));
}
});
allValues = utilArrayUniq(allValues).filter(Boolean);
} else {
allValues = utilArrayUniq((tags[field.key] || '').split(';')).filter(Boolean);
commonValues = allValues;
}
_multiData = allValues.map(function(v) {
return {
key: v,
value: displayValue(v),
isMixed: !commonValues.includes(v)
};
});
var currLength = utilUnicodeCharsCount(commonValues.join(';'));
// limit the input length to the remaining available characters
maxLength = context.maxCharsForTagValue() - currLength;
if (currLength > 0) {
// account for the separator if a new value will be appended to existing
maxLength -= 1;
}
}
// a negative maxlength doesn't make sense
maxLength = Math.max(0, maxLength);
var allowDragAndDrop = _isSemi // only semiCombo values are ordered
&& !Array.isArray(tags[field.key]);
// Exclude existing multikeys from combo options..
var available = objectDifference(_comboData, _multiData);
_combobox.data(available);
// Hide 'Add' button if this field uses fixed set of
// options and they're all currently used,
// or if the field is already at its character limit
var hideAdd = (!_allowCustomValues && !available.length) || maxLength <= 0;
_container.selectAll('.chiplist .input-wrap')
.style('display', hideAdd ? 'none' : null);
// Render chips
var chips = _container.selectAll('.chip')
.data(_multiData);
chips.exit()
.remove();
var enter = chips.enter()
.insert('li', '.input-wrap')
.attr('class', 'chip');
enter.append('span');
enter.append('a');
chips = chips.merge(enter)
.order()
.classed('raw-value', function(d) {
var k = d.key;
if (_isMulti) k = k.replace(field.key, '');
return !field.hasTextForStringId('options.' + k);
})
.classed('draggable', allowDragAndDrop)
.classed('mixed', function(d) {
return d.isMixed;
})
.attr('title', function(d) {
return d.isMixed ? t('inspector.unshared_value_tooltip') : null;
});
if (allowDragAndDrop) {
registerDragAndDrop(chips);
}
chips.select('span')
.html(function(d) { return d.value; });
chips.select('a')
.attr('href', '#')
.on('click', removeMultikey)
.attr('class', 'remove')
.html('×');
} else {
var isMixed = Array.isArray(tags[field.key]);
var mixedValues = isMixed && tags[field.key].map(function(val) {
return displayValue(val);
}).filter(Boolean);
var showsValue = !isMixed && tags[field.key] && !(field.type === 'typeCombo' && tags[field.key] === 'yes');
var isRawValue = showsValue && !field.hasTextForStringId('options.' + tags[field.key]);
var isKnownValue = showsValue && !isRawValue;
var isReadOnly = !_allowCustomValues || isKnownValue;
utilGetSetValue(_input, !isMixed ? displayValue(tags[field.key]) : '')
.classed('raw-value', isRawValue)
.classed('known-value', isKnownValue)
.attr('readonly', isReadOnly ? 'readonly' : undefined)
.attr('title', isMixed ? mixedValues.join('\n') : undefined)
.attr('placeholder', isMixed ? t('inspector.multiple_values') : _staticPlaceholder || '')
.classed('mixed', isMixed)
.on('keydown.deleteCapture', function(d3_event) {
if (isReadOnly &&
isKnownValue &&
(d3_event.keyCode === utilKeybinding.keyCodes['⌫'] ||
d3_event.keyCode === utilKeybinding.keyCodes['⌦'])) {
d3_event.preventDefault();
d3_event.stopPropagation();
var t = {};
t[field.key] = undefined;
dispatch.call('change', this, t);
}
});
}
};
function registerDragAndDrop(selection) {
// allow drag and drop re-ordering of chips
var dragOrigin, targetIndex;
selection.call(d3_drag()
.on('start', function(d3_event) {
dragOrigin = {
x: d3_event.x,
y: d3_event.y
};
targetIndex = null;
})
.on('drag', function(d3_event) {
var x = d3_event.x - dragOrigin.x,
y = d3_event.y - dragOrigin.y;
if (!d3_select(this).classed('dragging') &&
// don't display drag until dragging beyond a distance threshold
Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)) <= 5) return;
var index = selection.nodes().indexOf(this);
d3_select(this)
.classed('dragging', true);
targetIndex = null;
var targetIndexOffsetTop = null;
var draggedTagWidth = d3_select(this).node().offsetWidth;
if (field.key === 'destination') { // meaning tags are full width
_container.selectAll('.chip')
.style('transform', function(d2, index2) {
var node = d3_select(this).node();
if (index === index2) {
return 'translate(' + x + 'px, ' + y + 'px)';
// move the dragged tag up the order
} else if (index2 > index && d3_event.y > node.offsetTop) {
if (targetIndex === null || index2 > targetIndex) {
targetIndex = index2;
}
return 'translateY(-100%)';
// move the dragged tag down the order
} else if (index2 < index && d3_event.y < node.offsetTop + node.offsetHeight) {
if (targetIndex === null || index2 < targetIndex) {
targetIndex = index2;
}
return 'translateY(100%)';
}
return null;
});
} else {
_container.selectAll('.chip')
.each(function(d2, index2) {
var node = d3_select(this).node();
// check the cursor is in the bounding box
if (
index !== index2 &&
d3_event.x < node.offsetLeft + node.offsetWidth + 5 &&
d3_event.x > node.offsetLeft &&
d3_event.y < node.offsetTop + node.offsetHeight &&
d3_event.y > node.offsetTop
) {
targetIndex = index2;
targetIndexOffsetTop = node.offsetTop;
}
})
.style('transform', function(d2, index2) {
var node = d3_select(this).node();
if (index === index2) {
return 'translate(' + x + 'px, ' + y + 'px)';
}
// only translate tags in the same row
if (node.offsetTop === targetIndexOffsetTop) {
if (index2 < index && index2 >= targetIndex) {
return 'translateX(' + draggedTagWidth + 'px)';
} else if (index2 > index && index2 <= targetIndex) {
return 'translateX(-' + draggedTagWidth + 'px)';
}
}
return null;
});
}
})
.on('end', function() {
if (!d3_select(this).classed('dragging')) {
return;
}
var index = selection.nodes().indexOf(this);
d3_select(this)
.classed('dragging', false);
_container.selectAll('.chip')
.style('transform', null);
if (typeof targetIndex === 'number') {
var element = _multiData[index];
_multiData.splice(index, 1);
_multiData.splice(targetIndex, 0, element);
var t = {};
if (_multiData.length) {
t[field.key] = _multiData.map(function(element) {
return element.key;
}).join(';');
} else {
t[field.key] = undefined;
}
dispatch.call('change', this, t);
}
dragOrigin = undefined;
targetIndex = undefined;
})
);
}
combo.focus = function() {
_input.node().focus();
};
combo.entityIDs = function(val) {
if (!arguments.length) return _entityIDs;
_entityIDs = val;
return combo;
};
function combinedEntityExtent() {
return _entityIDs && _entityIDs.length && utilTotalExtent(_entityIDs, context.graph());
}
return utilRebind(combo, dispatch, 'on');
}
| Use full width semicombo field for Via field (re: https://github.com/openstreetmap/id-tagging-schema/issues/104)
| modules/ui/fields/combo.js | Use full width semicombo field for Via field (re: https://github.com/openstreetmap/id-tagging-schema/issues/104) | <ide><path>odules/ui/fields/combo.js
<ide>
<ide> var listClass = 'chiplist';
<ide>
<del> // Use a separate line for each value in the Destinations field
<add> // Use a separate line for each value in the Destinations and Via fields
<ide> // to mimic highway exit signs
<del> if (field.key === 'destination') {
<add> if (field.key === 'destination' || field.key === 'via') {
<ide> listClass += ' full-line-chips';
<ide> }
<ide>
<ide> var targetIndexOffsetTop = null;
<ide> var draggedTagWidth = d3_select(this).node().offsetWidth;
<ide>
<del> if (field.key === 'destination') { // meaning tags are full width
<add> if (field.key === 'destination' || field.key === 'via') { // meaning tags are full width
<ide> _container.selectAll('.chip')
<ide> .style('transform', function(d2, index2) {
<ide> var node = d3_select(this).node(); |
|
Java | epl-1.0 | 9cdb2703c65499e29588c0ee4ad7819723c73e9e | 0 | docbender/openhab,aruder77/openhab,gerrieg/openhab,theoweiss/openhab,theoweiss/openhab,LaurensVanAcker/openhab,doubled-ca/openhab1-addons,svenschreier/openhab,steintore/openhab,svenschreier/openhab,vgoldman/openhab,aschor/openhab,sumnerboy12/openhab,steintore/openhab,mvolaart/openhab,kreutpet/openhab,jowiho/openhab,cvanorman/openhab,ollie-dev/openhab,doubled-ca/openhab1-addons,revenz/openhab,cdjackson/openhab,cdjackson/openhab,evansj/openhab,steintore/openhab,hmerk/openhab,netwolfuk/openhab,computergeek1507/openhab,svenschreier/openhab,berndpfrommer/openhab,rmayr/openhab,svenschreier/openhab,hmerk/openhab,watou/openhab,RafalLukawiecki/openhab1-addons,bbesser/openhab1-addons,RafalLukawiecki/openhab1-addons,svenschaefer74/openhab,watou/openhab,vgoldman/openhab,kuijp/openhab,dvanherbergen/openhab,berndpfrommer/openhab,dvanherbergen/openhab,ivanfmartinez/openhab,ollie-dev/openhab,ivanfmartinez/openhab,tomtrath/openhab,ollie-dev/openhab,querdenker2k/openhab,coolweb/openhab,berndpfrommer/openhab,coolweb/openhab,berndpfrommer/openhab,basriram/openhab,dmize/openhab,wep4you/openhab,tomtrath/openhab,bbesser/openhab1-addons,basriram/openhab,computergeek1507/openhab,kreutpet/openhab,gerrieg/openhab,TheOriginalAndrobot/openhab,andreasgebauer/openhab,QuailAutomation/openhab,revenz/openhab,jowiho/openhab,lewie/openhab,sytone/openhab,dominicdesu/openhab,bbesser/openhab1-addons,sumnerboy12/openhab,coolweb/openhab,hemantsangwan/openhab,savageautomate/openhab,aschor/openhab,dbadia/openhab,docbender/openhab,idserda/openhab,openhab/openhab,querdenker2k/openhab,beowulfe/openhab,dominicdesu/openhab,andreasgebauer/openhab,tomtrath/openhab,theoweiss/openhab,hmerk/openhab,querdenker2k/openhab,aschor/openhab,sedstef/openhab,seebag/openhab,ssalonen/openhab,kreutpet/openhab,watou/openhab,theoweiss/openhab,kreutpet/openhab,kaikreuzer/openhab,andreasgebauer/openhab,wuellueb/openhab,gerrieg/openhab,kreutpet/openhab,kaikreuzer/openhab,vgoldman/openhab,robnielsen/openhab,kaikreuzer/openhab,sytone/openhab,Mixajlo/openhab,kaikreuzer/openhab,rmayr/openhab,revenz/openhab,wep4you/openhab,doubled-ca/openhab1-addons,rmayr/openhab,RafalLukawiecki/openhab1-addons,Snickermicker/openhab,falkena/openhab,ssalonen/openhab,Mixajlo/openhab,evansj/openhab,wuellueb/openhab,wep4you/openhab,druciak/openhab,LaurensVanAcker/openhab,netwolfuk/openhab,coolweb/openhab,watou/openhab,idserda/openhab,kuijp/openhab,netwolfuk/openhab,robnielsen/openhab,docbender/openhab,openhab/openhab,kuijp/openhab,hmerk/openhab,docbender/openhab,mvolaart/openhab,jowiho/openhab,mvolaart/openhab,revenz/openhab,dbadia/openhab,ollie-dev/openhab,berndpfrommer/openhab,sedstef/openhab,dvanherbergen/openhab,idserda/openhab,Snickermicker/openhab,rmayr/openhab,evansj/openhab,mvolaart/openhab,hemantsangwan/openhab,sumnerboy12/openhab,falkena/openhab,falkena/openhab,bbesser/openhab1-addons,juri8/openhab,joek/openhab1-addons,gerrieg/openhab,doubled-ca/openhab1-addons,jowiho/openhab,ollie-dev/openhab,sumnerboy12/openhab,joek/openhab1-addons,TheNetStriker/openhab,LaurensVanAcker/openhab,bbesser/openhab1-addons,basriram/openhab,computergeek1507/openhab,netwolfuk/openhab,hemantsangwan/openhab,aruder77/openhab,sedstef/openhab,juri8/openhab,frami/openhab,lewie/openhab,cvanorman/openhab,querdenker2k/openhab,juri8/openhab,TheNetStriker/openhab,TheOriginalAndrobot/openhab,sibbi77/openhab,wep4you/openhab,evansj/openhab,joek/openhab1-addons,sedstef/openhab,tomtrath/openhab,kuijp/openhab,TheOriginalAndrobot/openhab,TheOriginalAndrobot/openhab,querdenker2k/openhab,tomtrath/openhab,juri8/openhab,openhab/openhab,coolweb/openhab,dvanherbergen/openhab,lewie/openhab,sumnerboy12/openhab,aschor/openhab,cdjackson/openhab,frami/openhab,docbender/openhab,cvanorman/openhab,rmayr/openhab,bbesser/openhab1-addons,sytone/openhab,idserda/openhab,coolweb/openhab,Snickermicker/openhab,ssalonen/openhab,aruder77/openhab,RafalLukawiecki/openhab1-addons,seebag/openhab,docbender/openhab,revenz/openhab,svenschreier/openhab,sibbi77/openhab,mvolaart/openhab,CrackerStealth/openhab,cvanorman/openhab,QuailAutomation/openhab,LaurensVanAcker/openhab,openhab/openhab,dmize/openhab,robnielsen/openhab,dominicdesu/openhab,druciak/openhab,sumnerboy12/openhab,sibbi77/openhab,beowulfe/openhab,idserda/openhab,dmize/openhab,LaurensVanAcker/openhab,TheNetStriker/openhab,Snickermicker/openhab,revenz/openhab,netwolfuk/openhab,computergeek1507/openhab,svenschaefer74/openhab,docbender/openhab,hemantsangwan/openhab,steintore/openhab,seebag/openhab,joek/openhab1-addons,jowiho/openhab,Mixajlo/openhab,falkena/openhab,Snickermicker/openhab,andreasgebauer/openhab,druciak/openhab,berndpfrommer/openhab,andreasgebauer/openhab,svenschaefer74/openhab,watou/openhab,druciak/openhab,aruder77/openhab,ssalonen/openhab,gerrieg/openhab,cvanorman/openhab,TheNetStriker/openhab,hmerk/openhab,Mixajlo/openhab,ollie-dev/openhab,lewie/openhab,dbadia/openhab,cvanorman/openhab,jowiho/openhab,dominicdesu/openhab,kaikreuzer/openhab,dmize/openhab,cdjackson/openhab,TheNetStriker/openhab,frami/openhab,dbadia/openhab,wuellueb/openhab,robnielsen/openhab,basriram/openhab,dmize/openhab,idserda/openhab,aschor/openhab,hemantsangwan/openhab,beowulfe/openhab,dvanherbergen/openhab,QuailAutomation/openhab,dvanherbergen/openhab,ssalonen/openhab,svenschaefer74/openhab,theoweiss/openhab,kreutpet/openhab,svenschaefer74/openhab,tomtrath/openhab,hemantsangwan/openhab,lewie/openhab,sytone/openhab,ivanfmartinez/openhab,falkena/openhab,CrackerStealth/openhab,dmize/openhab,wuellueb/openhab,juri8/openhab,druciak/openhab,CrackerStealth/openhab,joek/openhab1-addons,watou/openhab,Mixajlo/openhab,savageautomate/openhab,rmayr/openhab,svenschaefer74/openhab,seebag/openhab,querdenker2k/openhab,kuijp/openhab,sytone/openhab,Mixajlo/openhab,aruder77/openhab,sibbi77/openhab,watou/openhab,doubled-ca/openhab1-addons,QuailAutomation/openhab,cdjackson/openhab,dbadia/openhab,frami/openhab,computergeek1507/openhab,savageautomate/openhab,basriram/openhab,dbadia/openhab,TheNetStriker/openhab,druciak/openhab,QuailAutomation/openhab,wuellueb/openhab,computergeek1507/openhab,steintore/openhab,ivanfmartinez/openhab,theoweiss/openhab,savageautomate/openhab,hemantsangwan/openhab,hmerk/openhab,lewie/openhab,aruder77/openhab,tomtrath/openhab,robnielsen/openhab,vgoldman/openhab,andreasgebauer/openhab,mvolaart/openhab,RafalLukawiecki/openhab1-addons,ssalonen/openhab,svenschreier/openhab,RafalLukawiecki/openhab1-addons,CrackerStealth/openhab,wuellueb/openhab,QuailAutomation/openhab,savageautomate/openhab,dominicdesu/openhab,evansj/openhab,frami/openhab,seebag/openhab,netwolfuk/openhab,beowulfe/openhab,wep4you/openhab,beowulfe/openhab,sedstef/openhab,falkena/openhab,ivanfmartinez/openhab,doubled-ca/openhab1-addons,TheOriginalAndrobot/openhab,beowulfe/openhab,joek/openhab1-addons,openhab/openhab,vgoldman/openhab,CrackerStealth/openhab,TheOriginalAndrobot/openhab,kuijp/openhab,TheNetStriker/openhab,basriram/openhab,vgoldman/openhab,sytone/openhab,robnielsen/openhab,wep4you/openhab,juri8/openhab,openhab/openhab,ivanfmartinez/openhab,seebag/openhab,andreasgebauer/openhab,steintore/openhab,dominicdesu/openhab,revenz/openhab,cdjackson/openhab,savageautomate/openhab,tomtrath/openhab,falkena/openhab,sedstef/openhab,juri8/openhab,frami/openhab,LaurensVanAcker/openhab,aschor/openhab,sibbi77/openhab,lewie/openhab,kaikreuzer/openhab,sibbi77/openhab,Snickermicker/openhab,evansj/openhab,coolweb/openhab,gerrieg/openhab,CrackerStealth/openhab | /**
* Copyright (c) 2010-2016, openHAB.org 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.openhab.binding.samsungac.internal;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.binding.openhab.samsungac.communicator.AirConditioner;
import org.binding.openhab.samsungac.communicator.SsdpDiscovery;
import org.openhab.binding.samsungac.SamsungAcBindingProvider;
import org.openhab.core.binding.AbstractActiveBinding;
import org.openhab.core.binding.BindingProvider;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.StringType;
import org.openhab.core.types.Command;
import org.openhab.core.types.State;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>
* Binding listening OpenHAB bus and send commands to Samsung Air Conditioner
* devices when command is received.
*
* @author Stein Tore Tøsse
* @since 1.6.0
*/
public class SamsungAcBinding extends AbstractActiveBinding<SamsungAcBindingProvider>implements ManagedService {
private static final Logger logger = LoggerFactory.getLogger(SamsungAcBinding.class);
/**
* the refresh interval which is used to check for lost connections
* (optional, defaults to 60000ms)
*/
private long refreshInterval = 60000;
private Map<String, AirConditioner> nameHostMapper = null;
protected Map<String, Map<String, String>> deviceConfigCache = new HashMap<String, Map<String, String>>();
public SamsungAcBinding() {
}
@Override
public void activate() {
logger.debug("Started Samsung AC Binding");
}
@Override
public void deactivate() {
logger.info("deactive");
// close any open connections
if (nameHostMapper != null) {
for (AirConditioner connector : nameHostMapper.values()) {
connector.disconnect();
}
}
}
/**
* @{inheritDoc
*/
@Override
protected void internalReceiveCommand(String itemName, Command command) {
if (itemName != null && command != null) {
logger.debug("InternalReceiveCommand [" + itemName + ":" + command + "]");
String hostName = getAirConditionerInstance(itemName);
AirConditioner host = nameHostMapper.get(hostName);
if (host == null) {
logger.debug("Host with hostname:" + hostName + " not found...");
return;
}
CommandEnum property = getProperty(itemName);
String cmd = getCmdStringFromEnumValue(command, property);
if (cmd != null) {
sendCommand(host, property, cmd);
} else {
logger.warn("Not sending for itemName: '" + itemName + "' because property not implemented: '"
+ property + "'");
}
}
}
private String getCmdStringFromEnumValue(Command command, CommandEnum property) {
String cmd = null;
switch (property) {
case AC_FUN_POWER:
case AC_ADD_SPI:
case AC_ADD_AUTOCLEAN:
cmd = "ON".equals(command.toString()) ? "On" : "Off";
break;
case AC_FUN_WINDLEVEL:
cmd = WindLevelEnum.getFromValue(command).toString();
break;
case AC_FUN_OPMODE:
cmd = OperationModeEnum.getFromValue(command).toString();
break;
case AC_FUN_COMODE:
cmd = ConvenientModeEnum.getFromValue(command).toString();
break;
case AC_FUN_DIRECTION:
cmd = DirectionEnum.getFromValue(command).toString();
break;
case AC_FUN_TEMPSET:
case AC_FUN_ERROR:
default:
cmd = command.toString();
break;
}
return cmd;
}
private void sendCommand(AirConditioner aircon, CommandEnum property, String value) {
int i = 1;
boolean commandSent = false;
while (i < 5 && !commandSent) {
try {
logger.debug("[" + i + "/5] Sending command: " + value + " to property:" + property + " with ip:"
+ aircon.getIpAddress());
if (aircon.sendCommand(property, value) != null) {
commandSent = true;
logger.debug("Command[" + value + "] sent on try number " + i);
}
} catch (Exception e) {
logger.warn("Could not send value: '" + value + "' to property:'" + property + "', try " + i + "/5");
e.printStackTrace();
} finally {
i++;
}
}
}
private String getAirConditionerInstance(String itemName) {
for (BindingProvider provider : providers) {
if (provider instanceof SamsungAcBindingProvider) {
SamsungAcBindingProvider acProvider = (SamsungAcBindingProvider) provider;
if (acProvider.getItemNames().contains(itemName)) {
return acProvider.getAirConditionerInstance(itemName);
}
}
}
return null;
}
private CommandEnum getProperty(String itemName) {
for (BindingProvider provider : providers) {
if (provider instanceof SamsungAcBindingProvider) {
SamsungAcBindingProvider acProvider = (SamsungAcBindingProvider) provider;
if (acProvider.getItemNames().contains(itemName)) {
return acProvider.getProperty(itemName);
}
}
}
return null;
}
private String getItemName(String acName, CommandEnum property) {
for (BindingProvider provider : providers) {
if (provider instanceof SamsungAcBindingProvider) {
SamsungAcBindingProvider acProvider = (SamsungAcBindingProvider) provider;
return acProvider.getItemName(acName, property);
}
}
return null;
}
protected void addBindingProvider(SamsungAcBindingProvider bindingProvider) {
super.addBindingProvider(bindingProvider);
}
protected void removeBindingProvider(SamsungAcBindingProvider bindingProvider) {
super.removeBindingProvider(bindingProvider);
}
/**
* {@inheritDoc}
*/
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
Enumeration<String> keys = config.keys();
String refreshIntervalString = (String) config.get("refresh");
if (StringUtils.isNotBlank(refreshIntervalString)) {
refreshInterval = Long.parseLong(refreshIntervalString);
logger.info("Refresh interval set to " + refreshIntervalString + " ms");
} else {
logger.info("No refresh interval configured, using default: " + refreshInterval + " ms");
}
Map<String, AirConditioner> hosts = new HashMap<String, AirConditioner>();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
logger.debug("Configuration key is: " + key);
if ("service.pid".equals(key)) {
continue;
}
String[] parts = key.split("\\.");
String hostname = parts[0];
AirConditioner host = hosts.get(hostname);
if (host == null) {
host = new AirConditioner();
}
String value = ((String) config.get(key)).trim();
if ("host".equals(parts[1])) {
host.setIpAddress(value);
}
if ("mac".equals(parts[1])) {
host.setMacAddress(value);
}
if ("token".equals(parts[1])) {
host.setToken(value);
}
hosts.put(hostname, host);
}
nameHostMapper = hosts;
if (nameHostMapper == null || nameHostMapper.size() == 0) {
setProperlyConfigured(false);
Map<String, Map<String, String>> discovered = SsdpDiscovery.discover();
if (discovered != null && discovered.size() > 0) {
for (Map<String, String> ac : discovered.values()) {
if (ac.get("IP") != null && ac.get("MAC_ADDR") != null) {
logger.warn("We found air conditioner. Please put the following in your configuration file: "
+ "\r\n samsungac:<ACNAME>.host=" + ac.get("IP") + "\r\n samsungac:<ACNAME>.mac="
+ ac.get("MAC_ADDR"));
}
}
} else {
logger.warn("No Samsung Air Conditioner has been configured, and we could not find one either");
}
} else {
setProperlyConfigured(true);
}
}
@Override
protected void execute() {
if (!bindingsExist()) {
logger.debug("There is no existing Samsung AC binding configuration => refresh cycle aborted!");
return;
}
if (nameHostMapper == null) {
logger.debug("Name host mapper not yet set. Aborted refresh");
return;
}
for (Map.Entry<String, AirConditioner> entry : nameHostMapper.entrySet()) {
AirConditioner host = entry.getValue();
String acName = entry.getKey();
if (host.isConnected()) {
getAndUpdateStatusForAirConditioner(acName, host);
} else {
reconnectToAirConditioner(entry.getKey(), host);
}
}
}
private void reconnectToAirConditioner(String key, AirConditioner host) {
logger.info("Broken connection found for '{}', attempting to reconnect...", key);
try {
host.login();
logger.info("Connection to {} has succeeded", host.toString());
} catch (Exception e) {
if (e == null || e.toString() == null || e.getCause() == null) {
logger.info("Returned null-exception...");
} else {
logger.debug(e.toString() + " : " + e.getCause().toString());
}
logger.info("Reconnect failed for '{}', will retry in {}s", key, refreshInterval / 1000);
}
}
private void getAndUpdateStatusForAirConditioner(String acName, AirConditioner host) {
Map<CommandEnum, String> status = new HashMap<CommandEnum, String>();
try {
logger.info("Getting status for ac: '" + acName + "'");
status = host.getStatus();
} catch (Exception e) {
logger.info("Could not get status.. returning.., got exception: " + e.toString());
return;
}
for (CommandEnum cmd : status.keySet()) {
logger.debug("Trying to find item for: " + acName + " and cmd: " + cmd.toString());
String item = getItemName(acName, cmd);
String value = status.get(cmd);
if (item != null && value != null) {
updateItemWithValue(cmd, item, value);
}
}
}
private void updateItemWithValue(CommandEnum cmd, String item, String value) {
switch (cmd) {
case AC_FUN_TEMPNOW:
case AC_FUN_TEMPSET:
postUpdate(item, DecimalType.valueOf(value));
break;
case AC_FUN_POWER:
case AC_ADD_SPI:
case AC_ADD_AUTOCLEAN:
postUpdate(item, value.toUpperCase().equals("ON") ? OnOffType.ON : OnOffType.OFF);
break;
case AC_FUN_COMODE:
postUpdate(item, DecimalType.valueOf(Integer.toString(ConvenientModeEnum.valueOf(value).value)));
break;
case AC_FUN_OPMODE:
postUpdate(item, DecimalType.valueOf(Integer.toString(OperationModeEnum.valueOf(value).value)));
break;
case AC_FUN_WINDLEVEL:
postUpdate(item, DecimalType.valueOf(Integer.toString(WindLevelEnum.valueOf(value).value)));
break;
case AC_FUN_DIRECTION:
postUpdate(item, DecimalType.valueOf(Integer.toString(DirectionEnum.valueOf(value).value)));
break;
case AC_FUN_ERROR:
default:
postUpdate(item, StringType.valueOf(value));
break;
}
}
private void postUpdate(String item, State state) {
if (item != null && state != null) {
logger.debug(item + " gets updated to: " + state);
eventPublisher.postUpdate(item, state);
} else {
logger.debug("Could not update item: '" + item + "' with state: '" + state.toString() + "'");
}
}
@Override
protected long getRefreshInterval() {
return refreshInterval;
}
@Override
protected String getName() {
return "Samsung Air Conditioner service";
}
}
| bundles/binding/org.openhab.binding.samsungac/src/main/java/org/openhab/binding/samsungac/internal/SamsungAcBinding.java | /**
* Copyright (c) 2010-2016, openHAB.org 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.openhab.binding.samsungac.internal;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.binding.openhab.samsungac.communicator.AirConditioner;
import org.binding.openhab.samsungac.communicator.SsdpDiscovery;
import org.openhab.binding.samsungac.SamsungAcBindingProvider;
import org.openhab.core.binding.AbstractActiveBinding;
import org.openhab.core.binding.BindingProvider;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.StringType;
import org.openhab.core.types.Command;
import org.openhab.core.types.State;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>
* Binding listening OpenHAB bus and send commands to Samsung Air Conditioner
* devices when command is received.
*
* @author Stein Tore Tøsse
* @since 1.6.0
*/
public class SamsungAcBinding extends AbstractActiveBinding<SamsungAcBindingProvider>implements ManagedService {
private static final Logger logger = LoggerFactory.getLogger(SamsungAcBinding.class);
/**
* the refresh interval which is used to check for lost connections
* (optional, defaults to 60000ms)
*/
private long refreshInterval = 60000;
private Map<String, AirConditioner> nameHostMapper = null;
protected Map<String, Map<String, String>> deviceConfigCache = new HashMap<String, Map<String, String>>();
public SamsungAcBinding() {
}
@Override
public void activate() {
logger.debug("Started Samsung AC Binding");
}
@Override
public void deactivate() {
logger.info("deactive");
// close any open connections
if (nameHostMapper != null) {
for (AirConditioner connector : nameHostMapper.values()) {
connector.disconnect();
}
}
}
/**
* @{inheritDoc
*/
@Override
protected void internalReceiveCommand(String itemName, Command command) {
if (itemName != null && command != null) {
logger.debug("InternalReceiveCommand [" + itemName + ":" + command + "]");
String hostName = getAirConditionerInstance(itemName);
AirConditioner host = nameHostMapper.get(hostName);
if (host == null) {
logger.debug("Host with hostname:" + hostName + " not found...");
return;
}
CommandEnum property = getProperty(itemName);
String cmd = getCmdStringFromEnumValue(command, property);
if (cmd != null) {
sendCommand(host, property, cmd);
} else {
logger.warn("Not sending for itemName: '" + itemName + "' because property not implemented: '"
+ property + "'");
}
}
}
private String getCmdStringFromEnumValue(Command command, CommandEnum property) {
String cmd = null;
switch (property) {
case AC_FUN_POWER:
case AC_ADD_SPI:
case AC_ADD_AUTOCLEAN:
cmd = "ON".equals(command.toString()) ? "On" : "Off";
break;
case AC_FUN_WINDLEVEL:
cmd = WindLevelEnum.getFromValue(command).toString();
break;
case AC_FUN_OPMODE:
cmd = OperationModeEnum.getFromValue(command).toString();
break;
case AC_FUN_COMODE:
cmd = ConvenientModeEnum.getFromValue(command).toString();
break;
case AC_FUN_DIRECTION:
cmd = DirectionEnum.getFromValue(command).toString();
break;
case AC_FUN_TEMPSET:
case AC_FUN_ERROR:
default:
cmd = command.toString();
break;
}
return cmd;
}
private void sendCommand(AirConditioner aircon, CommandEnum property, String value) {
int i = 1;
boolean commandSent = false;
while (i < 5 && !commandSent) {
try {
logger.debug("[" + i + "/5] Sending command: " + value + " to property:" + property + " with ip:"
+ aircon.getIpAddress());
if (aircon.sendCommand(property, value) != null) {
commandSent = true;
logger.debug("Command[" + value + "] sent on try number " + i);
}
} catch (Exception e) {
logger.warn("Could not send value: '" + value + "' to property:'" + property + "', try " + i + "/5");
e.printStackTrace();
} finally {
i++;
}
}
}
private String getAirConditionerInstance(String itemName) {
for (BindingProvider provider : providers) {
if (provider instanceof SamsungAcBindingProvider) {
SamsungAcBindingProvider acProvider = (SamsungAcBindingProvider) provider;
if (acProvider.getItemNames().contains(itemName)) {
return acProvider.getAirConditionerInstance(itemName);
}
}
}
return null;
}
private CommandEnum getProperty(String itemName) {
for (BindingProvider provider : providers) {
if (provider instanceof SamsungAcBindingProvider) {
SamsungAcBindingProvider acProvider = (SamsungAcBindingProvider) provider;
if (acProvider.getItemNames().contains(itemName)) {
return acProvider.getProperty(itemName);
}
}
}
return null;
}
private String getItemName(String acName, CommandEnum property) {
for (BindingProvider provider : providers) {
if (provider instanceof SamsungAcBindingProvider) {
SamsungAcBindingProvider acProvider = (SamsungAcBindingProvider) provider;
return acProvider.getItemName(acName, property);
}
}
return null;
}
/**
* @{inheritDoc
*/
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
Enumeration<String> keys = config.keys();
String refreshIntervalString = (String) config.get("refresh");
if (StringUtils.isNotBlank(refreshIntervalString)) {
refreshInterval = Long.parseLong(refreshIntervalString);
logger.info("Refresh interval set to " + refreshIntervalString + " ms");
} else {
logger.info("No refresh interval configured, using default: " + refreshInterval + " ms");
}
Map<String, AirConditioner> hosts = new HashMap<String, AirConditioner>();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
logger.debug("Configuration key is: " + key);
if ("service.pid".equals(key)) {
continue;
}
String[] parts = key.split("\\.");
String hostname = parts[0];
AirConditioner host = hosts.get(hostname);
if (host == null) {
host = new AirConditioner();
}
String value = ((String) config.get(key)).trim();
if ("host".equals(parts[1])) {
host.setIpAddress(value);
}
if ("mac".equals(parts[1])) {
host.setMacAddress(value);
}
if ("token".equals(parts[1])) {
host.setToken(value);
}
hosts.put(hostname, host);
}
nameHostMapper = hosts;
if (nameHostMapper == null || nameHostMapper.size() == 0) {
setProperlyConfigured(false);
Map<String, Map<String, String>> discovered = SsdpDiscovery.discover();
if (discovered != null && discovered.size() > 0) {
for (Map<String, String> ac : discovered.values()) {
if (ac.get("IP") != null && ac.get("MAC_ADDR") != null) {
logger.warn("We found air conditioner. Please put the following in your configuration file: "
+ "\r\n samsungac:<ACNAME>.host=" + ac.get("IP") + "\r\n samsungac:<ACNAME>.mac="
+ ac.get("MAC_ADDR"));
}
}
} else {
logger.warn("No Samsung Air Conditioner has been configured, and we could not find one either");
}
} else {
setProperlyConfigured(true);
}
}
@Override
protected void execute() {
if (!bindingsExist()) {
logger.debug("There is no existing Samsung AC binding configuration => refresh cycle aborted!");
return;
}
if (nameHostMapper == null) {
logger.debug("Name host mapper not yet set. Aborted refresh");
return;
}
for (Map.Entry<String, AirConditioner> entry : nameHostMapper.entrySet()) {
AirConditioner host = entry.getValue();
String acName = entry.getKey();
if (host.isConnected()) {
getAndUpdateStatusForAirConditioner(acName, host);
} else {
reconnectToAirConditioner(entry.getKey(), host);
}
}
}
private void reconnectToAirConditioner(String key, AirConditioner host) {
logger.info("Broken connection found for '{}', attempting to reconnect...", key);
try {
host.login();
logger.info("Connection to {} has succeeded", host.toString());
} catch (Exception e) {
if (e == null || e.toString() == null || e.getCause() == null) {
logger.info("Returned null-exception...");
} else {
logger.debug(e.toString() + " : " + e.getCause().toString());
}
logger.info("Reconnect failed for '{}', will retry in {}s", key, refreshInterval / 1000);
}
}
private void getAndUpdateStatusForAirConditioner(String acName, AirConditioner host) {
Map<CommandEnum, String> status = new HashMap<CommandEnum, String>();
try {
logger.info("Getting status for ac: '" + acName + "'");
status = host.getStatus();
} catch (Exception e) {
logger.info("Could not get status.. returning.., got exception: " + e.toString());
return;
}
for (CommandEnum cmd : status.keySet()) {
logger.debug("Trying to find item for: " + acName + " and cmd: " + cmd.toString());
String item = getItemName(acName, cmd);
String value = status.get(cmd);
if (item != null && value != null) {
updateItemWithValue(cmd, item, value);
}
}
}
private void updateItemWithValue(CommandEnum cmd, String item, String value) {
switch (cmd) {
case AC_FUN_TEMPNOW:
case AC_FUN_TEMPSET:
postUpdate(item, DecimalType.valueOf(value));
break;
case AC_FUN_POWER:
case AC_ADD_SPI:
case AC_ADD_AUTOCLEAN:
postUpdate(item, value.toUpperCase().equals("ON") ? OnOffType.ON : OnOffType.OFF);
break;
case AC_FUN_COMODE:
postUpdate(item, DecimalType.valueOf(Integer.toString(ConvenientModeEnum.valueOf(value).value)));
break;
case AC_FUN_OPMODE:
postUpdate(item, DecimalType.valueOf(Integer.toString(OperationModeEnum.valueOf(value).value)));
break;
case AC_FUN_WINDLEVEL:
postUpdate(item, DecimalType.valueOf(Integer.toString(WindLevelEnum.valueOf(value).value)));
break;
case AC_FUN_DIRECTION:
postUpdate(item, DecimalType.valueOf(Integer.toString(DirectionEnum.valueOf(value).value)));
break;
case AC_FUN_ERROR:
default:
postUpdate(item, StringType.valueOf(value));
break;
}
}
private void postUpdate(String item, State state) {
if (item != null && state != null) {
logger.debug(item + " gets updated to: " + state);
eventPublisher.postUpdate(item, state);
} else {
logger.debug("Could not update item: '" + item + "' with state: '" + state.toString() + "'");
}
}
@Override
protected long getRefreshInterval() {
return refreshInterval;
}
@Override
protected String getName() {
return "Samsung Air Conditioner service";
}
}
| samsungac
| bundles/binding/org.openhab.binding.samsungac/src/main/java/org/openhab/binding/samsungac/internal/SamsungAcBinding.java | samsungac | <ide><path>undles/binding/org.openhab.binding.samsungac/src/main/java/org/openhab/binding/samsungac/internal/SamsungAcBinding.java
<ide> return null;
<ide> }
<ide>
<add> protected void addBindingProvider(SamsungAcBindingProvider bindingProvider) {
<add> super.addBindingProvider(bindingProvider);
<add> }
<add>
<add> protected void removeBindingProvider(SamsungAcBindingProvider bindingProvider) {
<add> super.removeBindingProvider(bindingProvider);
<add> }
<add>
<ide> /**
<del> * @{inheritDoc
<add> * {@inheritDoc}
<ide> */
<ide> public void updated(Dictionary<String, ?> config) throws ConfigurationException {
<ide> Enumeration<String> keys = config.keys(); |
|
Java | lgpl-2.1 | bfc76678137b9d2372e55271f4392257e8620299 | 0 | mediaworx/opencms-core,ggiudetti/opencms-core,it-tavis/opencms-core,serrapos/opencms-core,it-tavis/opencms-core,alkacon/opencms-core,victos/opencms-core,alkacon/opencms-core,serrapos/opencms-core,MenZil/opencms-core,sbonoc/opencms-core,serrapos/opencms-core,mediaworx/opencms-core,gallardo/opencms-core,mediaworx/opencms-core,sbonoc/opencms-core,sbonoc/opencms-core,serrapos/opencms-core,ggiudetti/opencms-core,serrapos/opencms-core,gallardo/opencms-core,ggiudetti/opencms-core,gallardo/opencms-core,it-tavis/opencms-core,mediaworx/opencms-core,MenZil/opencms-core,victos/opencms-core,MenZil/opencms-core,it-tavis/opencms-core,MenZil/opencms-core,serrapos/opencms-core,victos/opencms-core,gallardo/opencms-core,serrapos/opencms-core,alkacon/opencms-core,ggiudetti/opencms-core,victos/opencms-core,sbonoc/opencms-core,alkacon/opencms-core | /*
* File : $Source: /alkacon/cvs/opencms/src-modules/org/opencms/workplace/tools/searchindex/CmsSearchResultView.java,v $
* Date : $Date: 2008/04/11 15:26:21 $
* Version: $Revision: 1.8 $
*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) 2002 - 2008 Alkacon Software GmbH (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software GmbH, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.workplace.tools.searchindex;
import org.opencms.file.CmsProject;
import org.opencms.i18n.CmsEncoder;
import org.opencms.i18n.CmsLocaleManager;
import org.opencms.i18n.CmsMessages;
import org.opencms.jsp.CmsJspActionElement;
import org.opencms.main.CmsException;
import org.opencms.main.OpenCms;
import org.opencms.search.CmsSearch;
import org.opencms.search.CmsSearchResult;
import org.opencms.search.fields.CmsSearchField;
import org.opencms.util.CmsStringUtil;
import org.opencms.workplace.CmsWidgetDialog;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.SortedMap;
import java.util.StringTokenizer;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;
/**
* Displays the result of a <code>{@link org.opencms.search.CmsSearch}</code>.<p>
*
* Requires the following request parameters (see constructor):
* <ul>
* <li>
* index:<br>the String identifying the required search index.
* <li>
* query:<br>the search query to run.
* </ul>
* <p>
*
* @author Achim Westermann
*
* @version $Revision: 1.8 $
*
* @since 6.0.0
*/
public class CmsSearchResultView {
/** The flag that decides whether links to search result point to their exported version or not. */
private boolean m_exportLinks = false;
/**
* A small cache for the forms generated by <code>{@link #toPostParameters(String, CmsSearch)}</code> during a request. <p>
*
* Avoids duplicate forms.<p>
*/
private SortedMap m_formCache;
/** The CmsJspActionElement to use. **/
private CmsJspActionElement m_jsp;
/** The project that forces evaluation of all dynamic content. */
protected CmsProject m_offlineProject;
/** The project that allows static export. */
protected CmsProject m_onlineProject;
/** The url to a proprietary search url (different from m_jsp.getRequestContext().getUri). **/
private String m_searchRessourceUrl;
/**
* Constructor with the action element to use. <p>
*
* @param action the action element to use
*/
public CmsSearchResultView(CmsJspActionElement action) {
m_jsp = action;
m_formCache = new TreeMap();
try {
m_onlineProject = m_jsp.getCmsObject().readProject(CmsProject.ONLINE_PROJECT_ID);
m_offlineProject = m_jsp.getRequestContext().currentProject();
} catch (CmsException e) {
// failed to get online project, at least avoid NPE
m_onlineProject = m_offlineProject;
}
}
/**
* Constructor with arguments for construction of a <code>{@link CmsJspActionElement}</code>. <p>
*
* @param pageContext the page context to use
* @param request the current request
* @param response the current response
*/
public CmsSearchResultView(PageContext pageContext, HttpServletRequest request, HttpServletResponse response) {
this(new CmsJspActionElement(pageContext, request, response));
}
/**
* Returns the formatted search results.<p>
*
* @param search the pre-configured search bean
* @return the formatted search results
*/
public String displaySearchResult(CmsSearch search) {
StringBuffer result = new StringBuffer(800);
Locale locale = m_jsp.getRequestContext().getLocale();
CmsMessages messages = org.opencms.search.Messages.get().getBundle(locale);
result.append("<h3>\n");
result.append(messages.key(org.opencms.search.Messages.GUI_HELP_SEARCH_RESULT_TITLE_0));
result.append("\n</h1>\n");
List searchResult;
if (CmsStringUtil.isEmptyOrWhitespaceOnly(search.getQuery())) {
search.setQuery("");
searchResult = new ArrayList();
} else {
search.setMatchesPerPage(5);
searchResult = search.getSearchResult();
}
HttpServletRequest request = m_jsp.getRequest();
// get the action to perform from the request
String action = request.getParameter("action");
if (action != null && searchResult == null) {
result.append("<p class=\"formerror\">\n");
if (search.getLastException() != null) {
result.append(messages.key(org.opencms.search.Messages.GUI_HELP_SEARCH_UNAVAILABLE_0));
result.append("\n<!-- ").append(search.getLastException().toString());
result.append(" //-->\n");
} else {
result.append(messages.key(org.opencms.search.Messages.GUI_HELP_SEARCH_NOMATCH_1, search.getQuery()));
result.append("\n");
}
result.append("</p>\n");
} else if (action != null && searchResult.size() <= 0) {
result.append("<p class=\"formerror\">\n");
result.append(messages.key(org.opencms.search.Messages.GUI_HELP_SEARCH_NOMATCH_1, search.getQuery()));
result.append("\n");
result.append("</p>\n");
} else if (action != null && searchResult.size() > 0) {
result.append("<p>\n");
result.append(messages.key(org.opencms.search.Messages.GUI_HELP_SEARCH_RESULT_START_0));
result.append("\n");
result.append("</p>\n<p>\n");
Iterator iterator = searchResult.iterator();
try {
if (m_exportLinks) {
m_jsp.getRequestContext().setCurrentProject(m_onlineProject);
}
String name;
String path;
while (iterator.hasNext()) {
CmsSearchResult entry = (CmsSearchResult)iterator.next();
result.append("\n<div class=\"searchResult\">");
result.append("<a class=\"navhelp\" href=\"#\" onclick=\"javascript:window.open('");
// CmsJspActionElement.link() is not programmed for using from root site
// because it assumes the "default CmsSite" when no configured site matches the
// root site "/":
if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_jsp.getRequestContext().getSiteRoot())) {
// link will always cut off "/sites/default" if we are in the
// root site, this call is only used to get the scheme, host, context name and servlet name...
path = m_jsp.link(OpenCms.getSiteManager().getDefaultSite().getSiteRoot() + "/")
+ entry.getPath().substring(1);
} else {
path = m_jsp.link(entry.getPath());
}
result.append(path);
result.append("', '_blank', 'width='+screen.availWidth+', height='+ screen.availHeight+', scrollbars=yes, menubar=yes, toolbar=yes')\"");
result.append("\">\n");
name = entry.getField(CmsSearchField.FIELD_TITLE);
if (name == null) {
name = entry.getPath();
}
result.append(name);
result.append("</a>");
result.append(" (").append(entry.getScore()).append(" %)\n");
result.append("<span class=\"searchExcerpt\">\n");
String excerptString = entry.getExcerpt();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(excerptString)) {
result.append(messages.key(org.opencms.search.Messages.GUI_HELP_SEARCH_EXCERPT_UNAVAILABLE_0));
} else {
result.append(excerptString).append('\n');
}
result.append("</span>\n");
result.append("</div>\n");
}
} finally {
m_jsp.getRequestContext().setCurrentProject(m_offlineProject);
}
result.append("</p>\n");
// search page links below results
if (search.getPreviousUrl() != null || search.getNextUrl() != null) {
result.append("<p>");
if (search.getPreviousUrl() != null) {
result.append("<a class=\"searchlink\" href=\"");
result.append(getSearchPageLink(
m_jsp.link(new StringBuffer(search.getPreviousUrl()).append('&').append(
CmsLocaleManager.PARAMETER_LOCALE).append("=").append(m_jsp.getRequestContext().getLocale()).toString()),
search));
result.append("\">");
result.append(messages.key(org.opencms.search.Messages.GUI_HELP_BUTTON_BACK_0));
result.append(" <<</a> \n");
}
Map pageLinks = search.getPageLinks();
Iterator i = pageLinks.keySet().iterator();
while (i.hasNext()) {
int pageNumber = ((Integer)i.next()).intValue();
result.append(" ");
if (pageNumber != search.getSearchPage()) {
result.append("<a class=\"searchlink\" href=\"").append(
getSearchPageLink(m_jsp.link(new StringBuffer(
(String)pageLinks.get(new Integer(pageNumber))).append('&').append(
CmsLocaleManager.PARAMETER_LOCALE).append("=").append(
m_jsp.getRequestContext().getLocale()).toString()), search));
result.append("\" target=\"_self\">").append(pageNumber).append("</a>\n");
} else {
result.append(pageNumber);
}
}
if (search.getNextUrl() != null) {
result.append(" <a class=\"searchlink\" href=\"");
result.append(getSearchPageLink(
new StringBuffer(m_jsp.link(search.getNextUrl())).append('&').append(
CmsLocaleManager.PARAMETER_LOCALE).append("=").append(m_jsp.getRequestContext().getLocale()).toString(),
search));
result.append("\">>>");
result.append(messages.key(org.opencms.search.Messages.GUI_HELP_BUTTON_NEXT_0));
result.append("</a>\n");
}
result.append("</p>\n");
}
}
// include the post forms for the page links:
Iterator values = m_formCache.values().iterator();
while (values.hasNext()) {
result.append(values.next());
}
return result.toString();
}
/**
* Returns the resource uri to the search page with respect to the
* optionally configured value <code>{@link #setSearchRessourceUrl(String)}</code>
* with the request parameters of the given argument.<p>
*
* This is a workaround for Tomcat bug 35775
* (http://issues.apache.org/bugzilla/show_bug.cgi?id=35775). After it has been
* fixed the version 1.1 should be restored (or at least this codepath should be switched back.<p>
*
* @param link the suggestion of the search result bean ( a previous, next or page number url)
* @param search the search bean
*
* @return the resource uri to the search page with respect to the
* optionally configured value <code>{@link #setSearchRessourceUrl(String)}</code>
* with the request parameters of the given argument
*/
private String getSearchPageLink(String link, CmsSearch search) {
if (m_searchRessourceUrl != null) {
// for the form to generate we need params.
String pageParams = "";
int paramIndex = link.indexOf('?');
if (paramIndex > 0) {
pageParams = link.substring(paramIndex);
}
StringBuffer formurl = new StringBuffer(m_searchRessourceUrl);
if (m_searchRessourceUrl.indexOf('?') != -1) {
// the search page url already has a query string, don't start params of search-generated link
// with '?'
pageParams = new StringBuffer("&").append(pageParams.substring(1)).toString();
}
formurl.append(pageParams).toString();
String formname = toPostParameters(formurl.toString(), search);
link = new StringBuffer("javascript:document.forms['").append(formname).append("'].submit()").toString();
}
return link;
}
/**
* Returns true if the links to search results shall point to exported content, false else. <p>
* @return true if the links to search results shall point to exported content, false else
*/
public boolean isExportLinks() {
return m_exportLinks;
}
/**
* Set wether the links to search results point to exported content or not. <p>
*
* @param exportLinks The value that decides Set wether the links to search results point to exported content or not.
*/
public void setExportLinks(boolean exportLinks) {
m_exportLinks = exportLinks;
}
/**
* Set a proprietary resource uri for the search page. <p>
*
* This is optional but allows to override the standard search result links
* (for next or previous pages) that point to
* <code>getJsp().getRequestContext().getUri()</code> whenever the search
* uri is element of some template and should not be linked directly.<p>
*
* @param uri the proprietary resource uri for the search page
*/
public void setSearchRessourceUrl(String uri) {
m_searchRessourceUrl = uri;
}
/**
* Generates a html form (named form<n>) with parameters found in
* the given GET request string (appended params with "?value=param&value2=param2).
* >n< is the number of forms that already have been generated.
* This is a content-expensive bugfix for http://issues.apache.org/bugzilla/show_bug.cgi?id=35775
* and should be replaced with the 1.1 revision as soon that bug is fixed.<p>
*
* The forms action will point to the given uri's path info part: All links in the page
* that includes this generated html and that are related to the get request should
* have "src='#'" and "onclick=documents.forms['<getRequestUri>'].submit()". <p>
*
* The generated form lands in the internal <code>Map {@link #m_formCache}</code> as mapping
* from uris to Strings and has to be appended to the output at a valid position. <p>
*
* Warning: Does not work with multiple values mapped to one parameter ("key = value1,value2..").<p>
*
*
*
* @param getRequestUri a request uri with optional query, will be used as name of the form too
* @param search the search bean to get the parameters from
*
* @return the formname of the the generated form that contains the parameters of the given request uri or
* the empty String if there weren't any get parameters in the given request uri.
*/
private String toPostParameters(String getRequestUri, CmsSearch search) {
/**
* A simple wrapper around html for a form and it's name for value
* side of form cache, necessary as order in Map is arbitrary,
* SortedMap unusable as backlinks have higher order, lower formname... <p>
*/
final class HTMLForm {
/** The html of the generated form. **/
String m_formHtml;
/** The name of the generated form. **/
String m_formName;
/**
* Creates an instance with the given formname and the given html code for the form. <p>
*
* @param formName the form name of the form
* @param formHtml the form html of the form
*/
HTMLForm(String formName, String formHtml) {
m_formName = formName;
m_formHtml = formHtml;
}
/**
* Returns the form html.<p>
*
* @return the form html
*
* @see java.lang.Object#toString()
*/
public String toString() {
return m_formHtml;
}
}
StringBuffer result;
String formname = "";
if (!m_formCache.containsKey(getRequestUri)) {
result = new StringBuffer();
int index = getRequestUri.indexOf('?');
String query = "";
String path = "";
if (index > 0) {
query = getRequestUri.substring(index + 1);
path = getRequestUri.substring(0, index);
formname = new StringBuffer("searchform").append(m_formCache.size()).toString();
result.append("\n<form method=\"post\" name=\"").append(formname).append("\" action=\"");
result.append(path).append("\">\n");
// "key=value" pairs as tokens:
StringTokenizer entryTokens = new StringTokenizer(query, "&", false);
while (entryTokens.hasMoreTokens()) {
StringTokenizer keyValueToken = new StringTokenizer(entryTokens.nextToken(), "=", false);
if (keyValueToken.countTokens() != 2) {
continue;
}
// Undo the possible already performed url encoding for the given url
String key = CmsEncoder.decode(keyValueToken.nextToken());
String value = CmsEncoder.decode(keyValueToken.nextToken());
if ("action".equals(key)) {
// cannot use the "search"-action value in combination with CmsWidgetDialog: prepareCommit would be left out!
value = CmsWidgetDialog.DIALOG_SAVE;
}
result.append(" <input type=\"hidden\" name=\"");
result.append(key).append("\" value=\"");
result.append(value).append("\" />\n");
}
// custom search index code for making category widget - compatible
// this is needed for transforming e.g. the CmsSearch-generated
// "&category=a,b,c" to widget fields categories.0..categories.n.
List categories = search.getParameters().getCategories();
Iterator it = categories.iterator();
int count = 0;
while (it.hasNext()) {
result.append(" <input type=\"hidden\" name=\"");
result.append("categories.").append(count).append("\" value=\"");
result.append(it.next()).append("\" />\n");
count++;
}
List roots = search.getParameters().getRoots();
it = roots.iterator();
count = 0;
while (it.hasNext()) {
result.append(" <input type=\"hidden\" name=\"");
result.append("roots.").append(count).append("\" value=\"");
result.append(it.next()).append("\" />\n");
count++;
}
result.append(" <input type=\"hidden\" name=\"");
result.append("fields").append("\" value=\"");
result.append(CmsStringUtil.collectionAsString(search.getParameters().getFields(), ","));
result.append("\" />\n");
result.append(" <input type=\"hidden\" name=\"");
result.append("sortfields.").append(0).append("\" value=\"");
result.append(search.getParameters().getSortName()).append("\" />\n");
result.append("</form>\n");
HTMLForm form = new HTMLForm(formname, result.toString());
m_formCache.put(getRequestUri, form);
return formname;
}
// empty String for no get parameters
return formname;
} else {
HTMLForm form = (HTMLForm)m_formCache.get(getRequestUri);
return form.m_formName;
}
}
} | src-modules/org/opencms/workplace/tools/searchindex/CmsSearchResultView.java | /*
* File : $Source: /alkacon/cvs/opencms/src-modules/org/opencms/workplace/tools/searchindex/CmsSearchResultView.java,v $
* Date : $Date: 2008/04/08 14:19:29 $
* Version: $Revision: 1.7 $
*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) 2002 - 2008 Alkacon Software GmbH (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software GmbH, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.workplace.tools.searchindex;
import org.opencms.file.CmsProject;
import org.opencms.i18n.CmsEncoder;
import org.opencms.i18n.CmsLocaleManager;
import org.opencms.i18n.CmsMessages;
import org.opencms.jsp.CmsJspActionElement;
import org.opencms.main.CmsException;
import org.opencms.main.OpenCms;
import org.opencms.search.CmsSearch;
import org.opencms.search.CmsSearchResult;
import org.opencms.search.fields.CmsSearchField;
import org.opencms.util.CmsStringUtil;
import org.opencms.workplace.CmsWidgetDialog;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.SortedMap;
import java.util.StringTokenizer;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;
/**
* Displays the result of a <code>{@link org.opencms.search.CmsSearch}</code>.<p>
*
* Requires the following request parameters (see constructor):
* <ul>
* <li>
* index:<br>the String identifying the required search index.
* <li>
* query:<br>the search query to run.
* </ul>
* <p>
*
* @author Achim Westermann
*
* @version $Revision: 1.7 $
*
* @since 6.0.0
*/
public class CmsSearchResultView {
/** The flag that decides whether links to search result point to their exported version or not. */
private boolean m_exportLinks = false;
/**
* A small cache for the forms generated by <code>{@link #toPostParameters(String, CmsSearch)}</code> during a request. <p>
*
* Avoids duplicate forms.<p>
*/
private SortedMap m_formCache;
/** The CmsJspActionElement to use. **/
private CmsJspActionElement m_jsp;
/** The project that forces evaluation of all dynamic content. */
protected CmsProject m_offlineProject;
/** The project that allows static export. */
protected CmsProject m_onlineProject;
/** The url to a proprietary search url (different from m_jsp.getRequestContext().getUri). **/
private String m_searchRessourceUrl;
/**
* Constructor with the action element to use. <p>
*
* @param action the action element to use
*/
public CmsSearchResultView(CmsJspActionElement action) {
m_jsp = action;
m_formCache = new TreeMap();
try {
m_onlineProject = m_jsp.getCmsObject().readProject(CmsProject.ONLINE_PROJECT_ID);
m_offlineProject = m_jsp.getRequestContext().currentProject();
} catch (CmsException e) {
// failed to get online project, at least avoid NPE
m_onlineProject = m_offlineProject;
}
}
/**
* Constructor with arguments for construction of a <code>{@link CmsJspActionElement}</code>. <p>
*
* @param pageContext the page context to use
* @param request the current request
* @param response the current response
*/
public CmsSearchResultView(PageContext pageContext, HttpServletRequest request, HttpServletResponse response) {
this(new CmsJspActionElement(pageContext, request, response));
}
/**
* Returns the formatted search results.<p>
*
* @param search the pre-configured search bean
* @return the formatted search results
*/
public String displaySearchResult(CmsSearch search) {
StringBuffer result = new StringBuffer(800);
Locale locale = m_jsp.getRequestContext().getLocale();
CmsMessages messages = org.opencms.search.Messages.get().getBundle(locale);
result.append("<h3>\n");
result.append(messages.key(org.opencms.search.Messages.GUI_HELP_SEARCH_RESULT_TITLE_0));
result.append("\n</h1>\n");
List searchResult;
if (CmsStringUtil.isEmptyOrWhitespaceOnly(search.getQuery())) {
search.setQuery("");
searchResult = new ArrayList();
} else {
search.setMatchesPerPage(5);
searchResult = search.getSearchResult();
}
HttpServletRequest request = m_jsp.getRequest();
// get the action to perform from the request
String action = request.getParameter("action");
if (action != null && searchResult == null) {
result.append("<p class=\"formerror\">\n");
if (search.getLastException() != null) {
result.append(messages.key(org.opencms.search.Messages.GUI_HELP_SEARCH_UNAVAILABLE_0));
result.append("\n<!-- ").append(search.getLastException().toString());
result.append(" //-->\n");
} else {
result.append(messages.key(org.opencms.search.Messages.GUI_HELP_SEARCH_NOMATCH_1, search.getQuery()));
result.append("\n");
}
result.append("</p>\n");
} else if (action != null && searchResult.size() <= 0) {
result.append("<p class=\"formerror\">\n");
result.append(messages.key(org.opencms.search.Messages.GUI_HELP_SEARCH_NOMATCH_1, search.getQuery()));
result.append("\n");
result.append("</p>\n");
} else if (action != null && searchResult.size() > 0) {
result.append("<p>\n");
result.append(messages.key(org.opencms.search.Messages.GUI_HELP_SEARCH_RESULT_START_0));
result.append("\n");
result.append("</p>\n<p>\n");
Iterator iterator = searchResult.iterator();
try {
if (m_exportLinks) {
m_jsp.getRequestContext().setCurrentProject(m_onlineProject);
}
String name;
String path;
while (iterator.hasNext()) {
CmsSearchResult entry = (CmsSearchResult)iterator.next();
result.append("\n<div class=\"searchResult\">");
result.append("<a class=\"navhelp\" href=\"#\" onclick=\"javascript:window.open('");
// CmsJspActionElement.link() is not programmed for using from root site
// because it assumes the "default CmsSite" when no configured site matches the
// root site "/":
if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_jsp.getRequestContext().getSiteRoot())) {
// link will always cut off "/sites/default" if we are in the
// root site, this call is only used to get the scheme, host, context name and servlet name...
path = m_jsp.link(OpenCms.getSiteManager().getDefaultSite().getSiteRoot() + "/")
+ entry.getPath().substring(1);
} else {
path = m_jsp.link(entry.getPath());
}
result.append(path);
result.append("', '_blank', 'width='+screen.availWidth+', height='+ screen.availHeight+', scrollbars=yes, menubar=yes, toolbar=yes')\"");
result.append("\">\n");
name = entry.getField(CmsSearchField.FIELD_TITLE);
if (name == null) {
name = entry.getPath();
}
result.append(name);
result.append("</a>");
result.append(" (").append(entry.getScore()).append(" %)\n");
result.append("<span class=\"searchExcerpt\">\n");
result.append(entry.getExcerpt()).append('\n');
result.append("</span>\n");
result.append("</div>\n");
}
} finally {
m_jsp.getRequestContext().setCurrentProject(m_offlineProject);
}
result.append("</p>\n");
// search page links below results
if (search.getPreviousUrl() != null || search.getNextUrl() != null) {
result.append("<p>");
if (search.getPreviousUrl() != null) {
result.append("<a class=\"searchlink\" href=\"");
result.append(getSearchPageLink(
m_jsp.link(new StringBuffer(search.getPreviousUrl()).append('&').append(
CmsLocaleManager.PARAMETER_LOCALE).append("=").append(m_jsp.getRequestContext().getLocale()).toString()),
search));
result.append("\">");
result.append(messages.key(org.opencms.search.Messages.GUI_HELP_BUTTON_BACK_0));
result.append(" <<</a> \n");
}
Map pageLinks = search.getPageLinks();
Iterator i = pageLinks.keySet().iterator();
while (i.hasNext()) {
int pageNumber = ((Integer)i.next()).intValue();
result.append(" ");
if (pageNumber != search.getSearchPage()) {
result.append("<a class=\"searchlink\" href=\"").append(
getSearchPageLink(m_jsp.link(new StringBuffer(
(String)pageLinks.get(new Integer(pageNumber))).append('&').append(
CmsLocaleManager.PARAMETER_LOCALE).append("=").append(
m_jsp.getRequestContext().getLocale()).toString()), search));
result.append("\" target=\"_self\">").append(pageNumber).append("</a>\n");
} else {
result.append(pageNumber);
}
}
if (search.getNextUrl() != null) {
result.append(" <a class=\"searchlink\" href=\"");
result.append(getSearchPageLink(
new StringBuffer(m_jsp.link(search.getNextUrl())).append('&').append(
CmsLocaleManager.PARAMETER_LOCALE).append("=").append(m_jsp.getRequestContext().getLocale()).toString(),
search));
result.append("\">>>");
result.append(messages.key(org.opencms.search.Messages.GUI_HELP_BUTTON_NEXT_0));
result.append("</a>\n");
}
result.append("</p>\n");
}
}
// include the post forms for the page links:
Iterator values = m_formCache.values().iterator();
while (values.hasNext()) {
result.append(values.next());
}
return result.toString();
}
/**
* Returns the resource uri to the search page with respect to the
* optionally configured value <code>{@link #setSearchRessourceUrl(String)}</code>
* with the request parameters of the given argument.<p>
*
* This is a workaround for Tomcat bug 35775
* (http://issues.apache.org/bugzilla/show_bug.cgi?id=35775). After it has been
* fixed the version 1.1 should be restored (or at least this codepath should be switched back.<p>
*
* @param link the suggestion of the search result bean ( a previous, next or page number url)
* @param search the search bean
*
* @return the resource uri to the search page with respect to the
* optionally configured value <code>{@link #setSearchRessourceUrl(String)}</code>
* with the request parameters of the given argument
*/
private String getSearchPageLink(String link, CmsSearch search) {
if (m_searchRessourceUrl != null) {
// for the form to generate we need params.
String pageParams = "";
int paramIndex = link.indexOf('?');
if (paramIndex > 0) {
pageParams = link.substring(paramIndex);
}
StringBuffer formurl = new StringBuffer(m_searchRessourceUrl);
if (m_searchRessourceUrl.indexOf('?') != -1) {
// the search page url already has a query string, don't start params of search-generated link
// with '?'
pageParams = new StringBuffer("&").append(pageParams.substring(1)).toString();
}
formurl.append(pageParams).toString();
String formname = toPostParameters(formurl.toString(), search);
link = new StringBuffer("javascript:document.forms['").append(formname).append("'].submit()").toString();
}
return link;
}
/**
* Returns true if the links to search results shall point to exported content, false else. <p>
* @return true if the links to search results shall point to exported content, false else
*/
public boolean isExportLinks() {
return m_exportLinks;
}
/**
* Set wether the links to search results point to exported content or not. <p>
*
* @param exportLinks The value that decides Set wether the links to search results point to exported content or not.
*/
public void setExportLinks(boolean exportLinks) {
m_exportLinks = exportLinks;
}
/**
* Set a proprietary resource uri for the search page. <p>
*
* This is optional but allows to override the standard search result links
* (for next or previous pages) that point to
* <code>getJsp().getRequestContext().getUri()</code> whenever the search
* uri is element of some template and should not be linked directly.<p>
*
* @param uri the proprietary resource uri for the search page
*/
public void setSearchRessourceUrl(String uri) {
m_searchRessourceUrl = uri;
}
/**
* Generates a html form (named form<n>) with parameters found in
* the given GET request string (appended params with "?value=param&value2=param2).
* >n< is the number of forms that already have been generated.
* This is a content-expensive bugfix for http://issues.apache.org/bugzilla/show_bug.cgi?id=35775
* and should be replaced with the 1.1 revision as soon that bug is fixed.<p>
*
* The forms action will point to the given uri's path info part: All links in the page
* that includes this generated html and that are related to the get request should
* have "src='#'" and "onclick=documents.forms['<getRequestUri>'].submit()". <p>
*
* The generated form lands in the internal <code>Map {@link #m_formCache}</code> as mapping
* from uris to Strings and has to be appended to the output at a valid position. <p>
*
* Warning: Does not work with multiple values mapped to one parameter ("key = value1,value2..").<p>
*
*
*
* @param getRequestUri a request uri with optional query, will be used as name of the form too
* @param search the search bean to get the parameters from
*
* @return the formname of the the generated form that contains the parameters of the given request uri or
* the empty String if there weren't any get parameters in the given request uri.
*/
private String toPostParameters(String getRequestUri, CmsSearch search) {
/**
* A simple wrapper around html for a form and it's name for value
* side of form cache, necessary as order in Map is arbitrary,
* SortedMap unusable as backlinks have higher order, lower formname... <p>
*/
final class HTMLForm {
/** The html of the generated form. **/
String m_formHtml;
/** The name of the generated form. **/
String m_formName;
/**
* Creates an instance with the given formname and the given html code for the form. <p>
*
* @param formName the form name of the form
* @param formHtml the form html of the form
*/
HTMLForm(String formName, String formHtml) {
m_formName = formName;
m_formHtml = formHtml;
}
/**
* Returns the form html.<p>
*
* @return the form html
*
* @see java.lang.Object#toString()
*/
public String toString() {
return m_formHtml;
}
}
StringBuffer result;
String formname = "";
if (!m_formCache.containsKey(getRequestUri)) {
result = new StringBuffer();
int index = getRequestUri.indexOf('?');
String query = "";
String path = "";
if (index > 0) {
query = getRequestUri.substring(index + 1);
path = getRequestUri.substring(0, index);
formname = new StringBuffer("searchform").append(m_formCache.size()).toString();
result.append("\n<form method=\"post\" name=\"").append(formname).append("\" action=\"");
result.append(path).append("\">\n");
// "key=value" pairs as tokens:
StringTokenizer entryTokens = new StringTokenizer(query, "&", false);
while (entryTokens.hasMoreTokens()) {
StringTokenizer keyValueToken = new StringTokenizer(entryTokens.nextToken(), "=", false);
if (keyValueToken.countTokens() != 2) {
continue;
}
// Undo the possible already performed url encoding for the given url
String key = CmsEncoder.decode(keyValueToken.nextToken());
String value = CmsEncoder.decode(keyValueToken.nextToken());
if ("action".equals(key)) {
// cannot use the "search"-action value in combination with CmsWidgetDialog: prepareCommit would be left out!
value = CmsWidgetDialog.DIALOG_SAVE;
}
result.append(" <input type=\"hidden\" name=\"");
result.append(key).append("\" value=\"");
result.append(value).append("\" />\n");
}
// custom search index code for making category widget - compatible
// this is needed for transforming e.g. the CmsSearch-generated
// "&category=a,b,c" to widget fields categories.0..categories.n.
List categories = search.getParameters().getCategories();
Iterator it = categories.iterator();
int count = 0;
while (it.hasNext()) {
result.append(" <input type=\"hidden\" name=\"");
result.append("categories.").append(count).append("\" value=\"");
result.append(it.next()).append("\" />\n");
count++;
}
List roots = search.getParameters().getRoots();
it = roots.iterator();
count = 0;
while (it.hasNext()) {
result.append(" <input type=\"hidden\" name=\"");
result.append("roots.").append(count).append("\" value=\"");
result.append(it.next()).append("\" />\n");
count++;
}
result.append(" <input type=\"hidden\" name=\"");
result.append("fields").append("\" value=\"");
result.append(CmsStringUtil.collectionAsString(search.getParameters().getFields(), ","));
result.append("\" />\n");
result.append(" <input type=\"hidden\" name=\"");
result.append("sortfields.").append(0).append("\" value=\"");
result.append(search.getParameters().getSortName()).append("\" />\n");
result.append("</form>\n");
HTMLForm form = new HTMLForm(formname, result.toString());
m_formCache.put(getRequestUri, form);
return formname;
}
// empty String for no get parameters
return formname;
} else {
HTMLForm form = (HTMLForm)m_formCache.get(getRequestUri);
return form.m_formName;
}
}
} | * Fixed issue with 'null' in workplace admin search results if excerpt is empty.
| src-modules/org/opencms/workplace/tools/searchindex/CmsSearchResultView.java | * Fixed issue with 'null' in workplace admin search results if excerpt is empty. | <ide><path>rc-modules/org/opencms/workplace/tools/searchindex/CmsSearchResultView.java
<ide> /*
<ide> * File : $Source: /alkacon/cvs/opencms/src-modules/org/opencms/workplace/tools/searchindex/CmsSearchResultView.java,v $
<del> * Date : $Date: 2008/04/08 14:19:29 $
<del> * Version: $Revision: 1.7 $
<add> * Date : $Date: 2008/04/11 15:26:21 $
<add> * Version: $Revision: 1.8 $
<ide> *
<ide> * This library is part of OpenCms -
<ide> * the Open Source Content Management System
<ide> *
<ide> * @author Achim Westermann
<ide> *
<del> * @version $Revision: 1.7 $
<add> * @version $Revision: 1.8 $
<ide> *
<ide> * @since 6.0.0
<ide> */
<ide> result.append(name);
<ide> result.append("</a>");
<ide> result.append(" (").append(entry.getScore()).append(" %)\n");
<add>
<ide> result.append("<span class=\"searchExcerpt\">\n");
<del> result.append(entry.getExcerpt()).append('\n');
<add> String excerptString = entry.getExcerpt();
<add> if (CmsStringUtil.isEmptyOrWhitespaceOnly(excerptString)) {
<add> result.append(messages.key(org.opencms.search.Messages.GUI_HELP_SEARCH_EXCERPT_UNAVAILABLE_0));
<add> } else {
<add> result.append(excerptString).append('\n');
<add> }
<ide> result.append("</span>\n");
<ide> result.append("</div>\n");
<ide> } |
|
Java | mit | 8aadd7fec4bba2663d1126c714d893b069b36983 | 0 | Brian-Wuest/MC-Prefab | package com.wuest.prefab;
import com.wuest.prefab.Proxy.ClientProxy;
import com.wuest.prefab.Proxy.CommonProxy;
import net.minecraft.block.material.Material;
import net.minecraft.block.material.MaterialColor;
import net.minecraft.block.material.PushReaction;
import net.minecraftforge.fml.DistExecutor;
import net.minecraftforge.fml.ExtensionPoint;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.fml.network.simple.SimpleChannel;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* The starting point to load all of the blocks, items and other objects associated with this mod.
*
* @author WuestMan
*/
@Mod(Prefab.MODID)
public class Prefab {
/**
* Simulates an air block that blocks movement and cannot be moved.
*/
public static final Material SeeThroughImmovable = new Material(
MaterialColor.NONE,
false,
true,
true,
false,
false,
false,
PushReaction.IGNORE);
/**
* This is the ModID
*/
public static final String MODID = "prefab";
// Directly reference a log4j logger.
public static final Logger LOGGER = LogManager.getLogger();
public static final String PROTOCOL_VERSION = Integer.toString(1);
/**
* This is used to determine if the mod is currently being debugged.
*/
public static boolean isDebug = false;
/**
* Determines if structure items will scan their defined space or show the build gui. Default is false.
* Note: this should only be set to true during debug mode.
*/
public static boolean useScanningMode = false;
/**
* Says where the client and server 'proxy' code is loaded.
*/
public static CommonProxy proxy;
/**
* The network class used to send messages.
*/
public static SimpleChannel network;
static {
Prefab.isDebug = java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments().toString().contains("-agentlib:jdwp");
}
public Prefab() {
// Register the blocks and items for this mod.
ModRegistry.BLOCKS.register(FMLJavaModLoadingContext.get().getModEventBus());
ModRegistry.ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus());
// Register the setup method for mod-loading
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doClientStuff);
Prefab.proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new);
Prefab.proxy.RegisterEventHandler();
ModLoadingContext.get().registerExtensionPoint(ExtensionPoint.DISPLAYTEST, () -> Pair.of(() -> "ANY", (remote, isServer) -> true));
}
private void setup(final FMLCommonSetupEvent event) {
Prefab.proxy.preInit(event);
Prefab.proxy.init(event);
Prefab.proxy.postinit(event);
}
private void doClientStuff(final FMLClientSetupEvent event) {
Prefab.proxy.clientSetup(event);
}
}
| src/main/java/com/wuest/prefab/Prefab.java | package com.wuest.prefab;
import com.wuest.prefab.Config.ModConfiguration;
import com.wuest.prefab.Proxy.ClientProxy;
import com.wuest.prefab.Proxy.CommonProxy;
import net.minecraft.block.material.Material;
import net.minecraft.block.material.MaterialColor;
import net.minecraft.block.material.PushReaction;
import net.minecraftforge.common.ForgeConfigSpec;
import net.minecraftforge.fml.DistExecutor;
import net.minecraftforge.fml.ExtensionPoint;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.fml.network.simple.SimpleChannel;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.nio.file.Path;
/**
* The starting point to load all of the blocks, items and other objects associated with this mod.
*
* @author WuestMan
*/
@Mod(Prefab.MODID)
public class Prefab {
/**
* Simulates an air block that blocks movement and cannot be moved.
*/
public static final Material SeeThroughImmovable = new Material(
MaterialColor.NONE,
false,
true,
true,
false,
false,
false,
PushReaction.IGNORE);
/**
* This is the ModID
*/
public static final String MODID = "prefab";
// Directly reference a log4j logger.
public static final Logger LOGGER = LogManager.getLogger();
public static final String PROTOCOL_VERSION = Integer.toString(1);
/**
* This is used to determine if the mod is currently being debugged.
*/
public static boolean isDebug = false;
/**
* Determines if structure items will scan their defined space or show the build gui. Default is false.
* Note: this should only be set to true during debug mode.
*/
public static boolean useScanningMode = false;
/**
* Says where the client and server 'proxy' code is loaded.
*/
public static CommonProxy proxy;
/**
* The network class used to send messages.
*/
public static SimpleChannel network;
static {
Prefab.isDebug = java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments().toString().contains("-agentlib:jdwp");
}
public Prefab() {
// Register the blocks and items for this mod.
ModRegistry.BLOCKS.register(FMLJavaModLoadingContext.get().getModEventBus());
ModRegistry.ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus());
// Register the setup method for mod-loading
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doClientStuff);
Prefab.proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new);
Prefab.proxy.RegisterEventHandler();
ModLoadingContext.get().registerExtensionPoint(ExtensionPoint.DISPLAYTEST, () -> Pair.of(() -> "ANY", (remote, isServer) -> true));
}
private void setup(final FMLCommonSetupEvent event) {
Prefab.proxy.preInit(event);
Prefab.proxy.init(event);
Prefab.proxy.postinit(event);
}
private void doClientStuff(final FMLClientSetupEvent event) {
Prefab.proxy.clientSetup(event);
}
}
| Removing unnecessary imports
| src/main/java/com/wuest/prefab/Prefab.java | Removing unnecessary imports | <ide><path>rc/main/java/com/wuest/prefab/Prefab.java
<ide> package com.wuest.prefab;
<ide>
<del>import com.wuest.prefab.Config.ModConfiguration;
<ide> import com.wuest.prefab.Proxy.ClientProxy;
<ide> import com.wuest.prefab.Proxy.CommonProxy;
<ide> import net.minecraft.block.material.Material;
<ide> import net.minecraft.block.material.MaterialColor;
<ide> import net.minecraft.block.material.PushReaction;
<del>import net.minecraftforge.common.ForgeConfigSpec;
<ide> import net.minecraftforge.fml.DistExecutor;
<ide> import net.minecraftforge.fml.ExtensionPoint;
<ide> import net.minecraftforge.fml.ModLoadingContext;
<ide> import net.minecraftforge.fml.common.Mod;
<del>import net.minecraftforge.fml.config.ModConfig;
<ide> import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
<ide> import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
<ide> import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
<ide> import org.apache.commons.lang3.tuple.Pair;
<ide> import org.apache.logging.log4j.LogManager;
<ide> import org.apache.logging.log4j.Logger;
<del>
<del>import java.nio.file.Path;
<ide>
<ide> /**
<ide> * The starting point to load all of the blocks, items and other objects associated with this mod. |
|
Java | apache-2.0 | 188fffc227b2d5ebaf1351794c8a3b3938cda4cf | 0 | majordodo/Majordodo,diennea/majordodo,diennea/majordodo,diennea/majordodo,diennea/majordodo,majordodo/Majordodo | /*
Licensed to Diennea S.r.l. under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. Diennea S.r.l. 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 majordodo.task;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Handles NodeManagers
*
* @author enrico.olivelli
*/
public class Workers {
private static final Logger LOGGER = Logger.getLogger(Workers.class.getName());
private final Map<String, WorkerManager> nodeManagers = new HashMap<>();
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private final Broker broker;
private final Thread workersActivityThread;
private volatile boolean stop;
private final ExecutorService workersThreadpool;
private final Object waitForEvent = new Object();
public Workers(Broker broker) {
this.broker = broker;
this.workersActivityThread = new Thread(new Life(), "workers-life");
this.workersThreadpool = Executors.newFixedThreadPool(broker.getConfiguration().getWorkersThreadpoolSize(), new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "workers-life-thread");
}
});
}
public void start(BrokerStatus statusAtBoot, Map<String, Collection<Long>> deadWorkerTasks,
List<String> connectedAtBoot, ResourceUsageCounters globalResourceUsageCounters, Collection<Task> tasksAtBoot,
Collection<WorkerStatus> workersAtBoot) {
for (WorkerStatus workerStatus : workersAtBoot) {
String workerId = workerStatus.getWorkerId();
WorkerManager manager = getWorkerManager(workerId);
if (workerStatus.getStatus() == WorkerStatus.STATUS_CONNECTED) {
connectedAtBoot.add(workerId);
}
Set<Long> toRecoverForWorker = new HashSet<>();
deadWorkerTasks.put(workerId, toRecoverForWorker);
LOGGER.log(Level.SEVERE, "Booting workerManager for workerId:{0}, actual status: {1} {2}", new Object[]{workerStatus.getWorkerId(), workerStatus.getStatus(), WorkerStatus.statusToString(workerStatus.getStatus())});
for (Task task : tasksAtBoot) {
if (workerId.equals(task.getWorkerId())) {
if (task.getStatus() == Task.STATUS_RUNNING) {
String resources = task.getResources();
String[] resourceIds = null;
if (resources != null) {
resourceIds = resources.split(",");
}
globalResourceUsageCounters.useResources(resourceIds);
if (workerStatus.getStatus() == WorkerStatus.STATUS_DEAD) {
LOGGER.log(Level.INFO, "workerId:{0} should be running task {1}, but worker is DEAD", new Object[]{workerStatus.getWorkerId(), task.getTaskId()});
toRecoverForWorker.add(task.getTaskId());
// Even if worker is dead with its tasks, at boot time these resources are busy (they will be freed at toRecoverForWorker tasks termination)
manager.getResourceUsageCounters().useResources(resourceIds);
} else {
LOGGER.log(Level.INFO, "Booting workerId:{0} should be running task {1}, resources {2}", new Object[]{workerStatus.getWorkerId(), task.getTaskId(), resources});
manager.taskRunningDuringBrokerBoot(new AssignedTask(task.getTaskId(), resourceIds, resources));
}
} else {
LOGGER.log(Level.SEVERE, "workerId:{0} task {1} is assigned to worker, but in status {2}", new Object[]{workerStatus.getWorkerId(), task.getTaskId(), Task.statusToString(task.getStatus())});
}
}
}
}
workersActivityThread.start();
}
public void stop() {
stop = true;
wakeUp();
try {
workersActivityThread.join();
} catch (InterruptedException exit) {
}
workersThreadpool.shutdown();
}
private class Life implements Runnable {
@Override
public void run() {
try {
while (!stop) {
synchronized (waitForEvent) {
waitForEvent.wait(500);
}
List<WorkerManager> managers;
lock.readLock().lock();
try {
managers = new ArrayList<>(nodeManagers.values());
} finally {
lock.readLock().unlock();
}
Collections.shuffle(managers);
for (WorkerManager man : managers) {
if (!man.isThreadAssigned()) {
man.threadAssigned();
try {
workersThreadpool.submit(man.operation());
} catch (RejectedExecutionException rejected) {
LOGGER.log(Level.SEVERE, "workers manager rejected task", rejected);
}
}
}
}
} catch (Throwable exit) {
// exiting loop
LOGGER.log(Level.SEVERE, "workers manager is dead", exit);
broker.brokerFailed(exit);
}
}
}
public void wakeUp() {
synchronized (waitForEvent) {
waitForEvent.notify();
}
}
public WorkerManager getWorkerManagerNoCreate(String id) {
lock.readLock().lock();
try {
return nodeManagers.get(id);
} finally {
lock.readLock().unlock();
}
}
public WorkerManager getWorkerManager(String id) {
WorkerManager man;
lock.readLock().lock();
try {
man = nodeManagers.get(id);
} finally {
lock.readLock().unlock();
}
if (man == null) {
lock.writeLock().lock();
try {
man = nodeManagers.get(id);
if (man == null) {
LOGGER.log(Level.INFO, "creating WorkerManager for worker {0}", id);
man = new WorkerManager(id, broker);
nodeManagers.put(id, man);
}
} finally {
lock.writeLock().unlock();
}
}
return man;
}
}
| majordodo-core/src/main/java/majordodo/task/Workers.java | /*
Licensed to Diennea S.r.l. under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. Diennea S.r.l. 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 majordodo.task;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Handles NodeManagers
*
* @author enrico.olivelli
*/
public class Workers {
private static final Logger LOGGER = Logger.getLogger(Workers.class.getName());
private final Map<String, WorkerManager> nodeManagers = new HashMap<>();
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private final Broker broker;
private final Thread workersActivityThread;
private volatile boolean stop;
private final ExecutorService workersThreadpool;
private final Object waitForEvent = new Object();
public Workers(Broker broker) {
this.broker = broker;
this.workersActivityThread = new Thread(new Life(), "workers-life");
this.workersThreadpool = Executors.newFixedThreadPool(broker.getConfiguration().getWorkersThreadpoolSize(), new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "workers-life-thread");
}
});
}
public void start(BrokerStatus statusAtBoot, Map<String, Collection<Long>> deadWorkerTasks,
List<String> connectedAtBoot, ResourceUsageCounters globalResourceUsageCounters, Collection<Task> tasksAtBoot,
Collection<WorkerStatus> workersAtBoot) {
for (WorkerStatus workerStatus : workersAtBoot) {
String workerId = workerStatus.getWorkerId();
WorkerManager manager = getWorkerManager(workerId);
if (workerStatus.getStatus() == WorkerStatus.STATUS_CONNECTED) {
connectedAtBoot.add(workerId);
}
Set<Long> toRecoverForWorker = new HashSet<>();
deadWorkerTasks.put(workerId, toRecoverForWorker);
LOGGER.log(Level.SEVERE, "Booting workerManager for workerId:{0}, actual status: {1} {2}", new Object[]{workerStatus.getWorkerId(), workerStatus.getStatus(), WorkerStatus.statusToString(workerStatus.getStatus())});
for (Task task : tasksAtBoot) {
if (workerId.equals(task.getWorkerId())) {
if (task.getStatus() == Task.STATUS_RUNNING) {
String resources = task.getResources();
String[] resourceIds = null;
if (resources != null) {
resourceIds = resources.split(",");
}
globalResourceUsageCounters.useResources(resourceIds);
if (workerStatus.getStatus() == WorkerStatus.STATUS_DEAD) {
LOGGER.log(Level.INFO, "workerId:{0} should be running task {1}, but worker is DEAD", new Object[]{workerStatus.getWorkerId(), task.getTaskId()});
toRecoverForWorker.add(task.getTaskId());
// Even if worker is dead with its tasks, at boot time these resources are busy (they will be freed at toRecoverForWorker tasks termination)
manager.getResourceUsageCounters().useResources(resourceIds);
} else {
LOGGER.log(Level.INFO, "Booting workerId:{0} should be running task {1}, resources {2}", new Object[]{workerStatus.getWorkerId(), task.getTaskId(), resources});
manager.taskRunningDuringBrokerBoot(new AssignedTask(task.getTaskId(), resourceIds, resources));
}
} else {
LOGGER.log(Level.SEVERE, "workerId:{0} task {1} is assigned to worker, but in status {2}", new Object[]{workerStatus.getWorkerId(), task.getTaskId(), Task.statusToString(task.getStatus())});
}
}
}
}
workersActivityThread.start();
}
public void stop() {
stop = true;
wakeUp();
try {
workersActivityThread.join();
} catch (InterruptedException exit) {
}
workersThreadpool.shutdown();
}
private class Life implements Runnable {
@Override
public void run() {
try {
while (!stop) {
synchronized (waitForEvent) {
waitForEvent.wait(500);
}
Collection<WorkerManager> managers;
lock.readLock().lock();
try {
managers = new ArrayList<>(nodeManagers.values());
} finally {
lock.readLock().unlock();
}
for (WorkerManager man : managers) {
if (!man.isThreadAssigned()) {
man.threadAssigned();
try {
workersThreadpool.submit(man.operation());
} catch (RejectedExecutionException rejected) {
LOGGER.log(Level.SEVERE, "workers manager rejected task", rejected);
}
}
}
}
} catch (Throwable exit) {
// exiting loop
LOGGER.log(Level.SEVERE, "workers manager is dead", exit);
broker.brokerFailed(exit);
}
}
}
public void wakeUp() {
synchronized (waitForEvent) {
waitForEvent.notify();
}
}
public WorkerManager getWorkerManagerNoCreate(String id) {
lock.readLock().lock();
try {
return nodeManagers.get(id);
} finally {
lock.readLock().unlock();
}
}
public WorkerManager getWorkerManager(String id) {
WorkerManager man;
lock.readLock().lock();
try {
man = nodeManagers.get(id);
} finally {
lock.readLock().unlock();
}
if (man == null) {
lock.writeLock().lock();
try {
man = nodeManagers.get(id);
if (man == null) {
LOGGER.log(Level.INFO, "creating WorkerManager for worker {0}", id);
man = new WorkerManager(id, broker);
nodeManagers.put(id, man);
}
} finally {
lock.writeLock().unlock();
}
}
return man;
}
}
| Brokers seems to "prefer" some workers #139 (#140)
| majordodo-core/src/main/java/majordodo/task/Workers.java | Brokers seems to "prefer" some workers #139 (#140) | <ide><path>ajordodo-core/src/main/java/majordodo/task/Workers.java
<ide>
<ide> import java.util.ArrayList;
<ide> import java.util.Collection;
<add>import java.util.Collections;
<ide> import java.util.HashMap;
<ide> import java.util.HashSet;
<ide> import java.util.List;
<ide> synchronized (waitForEvent) {
<ide> waitForEvent.wait(500);
<ide> }
<del> Collection<WorkerManager> managers;
<add> List<WorkerManager> managers;
<ide> lock.readLock().lock();
<ide> try {
<ide> managers = new ArrayList<>(nodeManagers.values());
<ide> } finally {
<ide> lock.readLock().unlock();
<ide> }
<add> Collections.shuffle(managers);
<ide> for (WorkerManager man : managers) {
<ide> if (!man.isThreadAssigned()) {
<ide> man.threadAssigned(); |
|
Java | apache-2.0 | error: pathspec '02_arrays/src/com/codewriters/fdiba/array/homework/MaxSubSet.java' did not match any file(s) known to git
| 673b06c68702f931ecec5ef9e31fa599077a195b | 1 | powerslider/codewriters_club | import java.util.Arrays;
import java.util.Scanner;
/**
* Write a program that finds the sub-array with greatest sum within another array.
*
* @author Aleksandar Savev <[email protected]>
* @since 11-Feb-16
*/
public class MaxSubSet {
public static void main(String[] args) {
// example input: 1,2,3,-1,-2,-3,0,4,5
Scanner s = new Scanner(System.in);
String[] setString = s.nextLine().split(",");
s.close();
int[] set = new int[setString.length];
for (int i = 0; i < set.length; i++) {
set[i] = Integer.parseInt(setString[i]);
}
Arrays.sort(set);
for (int i = set.length - 1; i > set.length - 4 && i >= 0; i--) {
System.out.print(set[i] + " ");
}
}
}
| 02_arrays/src/com/codewriters/fdiba/array/homework/MaxSubSet.java | Add MaxSubSet
Write a program that finds the sub-array with greatest sum within another array. | 02_arrays/src/com/codewriters/fdiba/array/homework/MaxSubSet.java | Add MaxSubSet | <ide><path>2_arrays/src/com/codewriters/fdiba/array/homework/MaxSubSet.java
<add>import java.util.Arrays;
<add>import java.util.Scanner;
<add>
<add>
<add>/**
<add> * Write a program that finds the sub-array with greatest sum within another array.
<add> *
<add> * @author Aleksandar Savev <[email protected]>
<add> * @since 11-Feb-16
<add> */
<add>public class MaxSubSet {
<add>
<add> public static void main(String[] args) {
<add> // example input: 1,2,3,-1,-2,-3,0,4,5
<add> Scanner s = new Scanner(System.in);
<add> String[] setString = s.nextLine().split(",");
<add> s.close();
<add>
<add> int[] set = new int[setString.length];
<add> for (int i = 0; i < set.length; i++) {
<add> set[i] = Integer.parseInt(setString[i]);
<add> }
<add> Arrays.sort(set);
<add> for (int i = set.length - 1; i > set.length - 4 && i >= 0; i--) {
<add> System.out.print(set[i] + " ");
<add> }
<add> }
<add>} |
|
Java | agpl-3.0 | d46822db9df686f9ed1069d366d35e3fa0c756f6 | 0 | quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,kuali/kfs,kuali/kfs,kuali/kfs,quikkian-ua-devops/kfs,bhutchinson/kfs,ua-eas/kfs,ua-eas/kfs-devops-automation-fork,smith750/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,kkronenb/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,UniversityOfHawaii/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,kuali/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,smith750/kfs,quikkian-ua-devops/will-financials,bhutchinson/kfs,kkronenb/kfs,quikkian-ua-devops/kfs,smith750/kfs,ua-eas/kfs-devops-automation-fork,kkronenb/kfs,quikkian-ua-devops/kfs,bhutchinson/kfs,bhutchinson/kfs,ua-eas/kfs,kuali/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs,kkronenb/kfs,UniversityOfHawaii/kfs,smith750/kfs,ua-eas/kfs,UniversityOfHawaii/kfs,ua-eas/kfs | /*
* Copyright 2009 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kfs.coa.identity;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.kuali.kfs.coa.businessobject.Chart;
import org.kuali.kfs.coa.service.ChartService;
import org.kuali.kfs.sys.ConfigureContext;
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.kfs.sys.context.KualiTestBase;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.sys.identity.KfsKimAttributes;
import org.kuali.rice.kim.bo.Person;
import org.kuali.rice.kim.bo.role.dto.RoleMembershipInfo;
import org.kuali.rice.kim.bo.types.dto.AttributeSet;
import org.kuali.rice.kim.service.IdentityManagementService;
import org.kuali.rice.kim.service.PersonService;
import org.kuali.rice.kim.service.RoleManagementService;
@ConfigureContext
public class ChartManagerRoleTest extends KualiTestBase {
public void testGettingPersonForChartManagers() {
IdentityManagementService idm = SpringContext.getBean(IdentityManagementService.class);
RoleManagementService rms = SpringContext.getBean(RoleManagementService.class);
List<String> roleIds = new ArrayList<String>();
AttributeSet qualification = new AttributeSet();
for ( String chart : SpringContext.getBean(ChartService.class).getAllChartCodes() ) {
qualification.put(KfsKimAttributes.CHART_OF_ACCOUNTS_CODE, chart);
// System.out.println( chart );
roleIds.add(rms.getRoleIdByName(KFSConstants.ParameterNamespaces.KFS, "Chart Manager"));
Collection<RoleMembershipInfo> chartManagers = rms.getRoleMembers(roleIds, qualification);
// System.out.println( chartManagers );
assertEquals( "There should be only one chart manager per chart: " + chart, 1, chartManagers.size() );
for ( RoleMembershipInfo rmi : chartManagers ) {
Person chartManager = SpringContext.getBean(PersonService.class).getPerson( rmi.getMemberId() );
System.out.println( chartManager );
assertNotNull( "unable to retrieve person object for principalId: " + rmi.getMemberId(), chartManager );
assertFalse( "name should not have been blank", chartManager.getName().equals("") );
assertFalse( "campus code should not have been blank", chartManager.getCampusCode().equals("") );
}
}
}
}
| test/unit/src/org/kuali/kfs/coa/identity/ChartManagerRoleTest.java | /*
* Copyright 2009 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kfs.coa.identity;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.kuali.kfs.coa.businessobject.Chart;
import org.kuali.kfs.coa.service.ChartService;
import org.kuali.kfs.sys.ConfigureContext;
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.kfs.sys.context.KualiTestBase;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.sys.identity.KfsKimAttributes;
import org.kuali.rice.kim.bo.Person;
import org.kuali.rice.kim.bo.role.dto.RoleMembershipInfo;
import org.kuali.rice.kim.bo.types.dto.AttributeSet;
import org.kuali.rice.kim.service.IdentityManagementService;
import org.kuali.rice.kim.service.PersonService;
import org.kuali.rice.kim.service.RoleManagementService;
@ConfigureContext
public class ChartManagerRoleTest extends KualiTestBase {
public void testGettingPersonForChartManagers() {
IdentityManagementService idm = SpringContext.getBean(IdentityManagementService.class);
RoleManagementService rms = SpringContext.getBean(RoleManagementService.class);
List<String> roleIds = new ArrayList<String>();
AttributeSet qualification = new AttributeSet();
for ( String chart : SpringContext.getBean(ChartService.class).getAllChartCodes() ) {
qualification.put(KfsKimAttributes.CHART_OF_ACCOUNTS_CODE, chart);
// System.out.println( chart );
roleIds.add(rms.getRoleIdByName(KFSConstants.ParameterNamespaces.KFS, "Chart Manager"));
Collection<RoleMembershipInfo> chartManagers = rms.getRoleMembers(roleIds, qualification);
// System.out.println( chartManagers );
assertEquals( "There should be only one chart manager per chart: " + chart, 1, chartManagers.size() );
for ( RoleMembershipInfo rmi : chartManagers ) {
Person chartManager = SpringContext.getBean(PersonService.class).getPerson( rmi.getMemberId() );
assertNotNull( "unable to retrieve person object for principalId: " + rmi.getMemberId(), chartManager );
}
}
}
}
| Updated test to look at the returned object a little more thoroughly.
| test/unit/src/org/kuali/kfs/coa/identity/ChartManagerRoleTest.java | Updated test to look at the returned object a little more thoroughly. | <ide><path>est/unit/src/org/kuali/kfs/coa/identity/ChartManagerRoleTest.java
<ide>
<ide> for ( RoleMembershipInfo rmi : chartManagers ) {
<ide> Person chartManager = SpringContext.getBean(PersonService.class).getPerson( rmi.getMemberId() );
<add> System.out.println( chartManager );
<ide> assertNotNull( "unable to retrieve person object for principalId: " + rmi.getMemberId(), chartManager );
<add> assertFalse( "name should not have been blank", chartManager.getName().equals("") );
<add> assertFalse( "campus code should not have been blank", chartManager.getCampusCode().equals("") );
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | 072e8bffc2b322416eb38a25c84020dd5958185f | 0 | foam-framework/foam2,foam-framework/foam2,jacksonic/vjlofvhjfgm,foam-framework/foam2,jacksonic/vjlofvhjfgm,jacksonic/vjlofvhjfgm,foam-framework/foam2,foam-framework/foam2 | /**
* @license
* Copyright 2020 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
package foam.nanos.bench.benchmarks;
import foam.core.X;
import foam.dao.*;
import foam.nanos.auth.User;
import foam.nanos.bench.Benchmark;
public class F3FileJournalBenchmark
implements Benchmark
{
protected F3FileJournal journal_;
protected DAO dao_;
@Override
public void setup(X x) {
dao_ = new NullDAO();
journal_ = new F3FileJournal.Builder(x)
.setDao(new MDAO(User.getOwnClassInfo()))
.setFilename("journalbenchmark")
.setCreateFile(true)
.build();
}
@Override
public void teardown(X x, java.util.Map stats) {
}
@Override
public void execute(X x) {
User u = new User();
u.setId(System.currentTimeMillis());
u.setFirstName("test");
u.setLastName("testing");
journal_.put(x, "", dao_, u);
}
} | src/foam/nanos/bench/benchmarks/F3FileJournalBenchmark.java | /**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
package foam.nanos.bench.benchmarks;
import foam.core.X;
import foam.dao.*;
import foam.nanos.auth.User;
import foam.nanos.bench.Benchmark;
public class F3FileJournalBenchmark
implements Benchmark
{
protected F3FileJournal journal_;
protected DAO dao_;
@Override
public void setup(X x) {
dao_ = new NullDAO();
journal_ = new F3FileJournal.Builder(x)
.setDao(new MDAO(User.getOwnClassInfo()))
.setFilename("journalbenchmark")
.setCreateFile(true)
.build();
}
@Override
public void teardown(X x, java.util.Map stats) {
}
@Override
public void execute(X x) {
User u = new User();
u.setId(System.currentTimeMillis());
u.setFirstName("test");
u.setLastName("testing");
journal_.put(x, "", dao_, u);
}
} | change license year to 2020
| src/foam/nanos/bench/benchmarks/F3FileJournalBenchmark.java | change license year to 2020 | <ide><path>rc/foam/nanos/bench/benchmarks/F3FileJournalBenchmark.java
<ide> /**
<ide> * @license
<del> * Copyright 2019 The FOAM Authors. All Rights Reserved.
<add> * Copyright 2020 The FOAM Authors. All Rights Reserved.
<ide> * http://www.apache.org/licenses/LICENSE-2.0
<ide> */
<ide> |
|
Java | apache-2.0 | be50fb7ed0b9f382d0384cc469729834f4ed0148 | 0 | Kromzem/gdx-facebook,TomGrill/gdx-facebook | /*******************************************************************************
* Copyright 2015 See AUTHORS file.
*
* 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 de.tomgrill.gdxfacebook.ios;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.robovm.apple.foundation.NSError;
import org.robovm.objc.block.VoidBlock2;
import org.robovm.pods.facebook.core.FBSDKAccessToken;
import org.robovm.pods.facebook.login.FBSDKLoginBehavior;
import org.robovm.pods.facebook.login.FBSDKLoginManager;
import org.robovm.pods.facebook.login.FBSDKLoginManagerLoginResult;
import com.badlogic.gdx.utils.Array;
import de.tomgrill.gdxfacebook.core.GDXFacebook;
import de.tomgrill.gdxfacebook.core.GDXFacebookAccessToken;
import de.tomgrill.gdxfacebook.core.GDXFacebookCallback;
import de.tomgrill.gdxfacebook.core.GDXFacebookConfig;
import de.tomgrill.gdxfacebook.core.GDXFacebookError;
import de.tomgrill.gdxfacebook.core.GDXFacebookLoginResult;
public class IOSGDXFacebook extends GDXFacebook {
private FBSDKLoginManager loginManager;
private GDXFacebookAccessToken accessToken;
public IOSGDXFacebook(GDXFacebookConfig config) {
super(config);
loginManager = new FBSDKLoginManager();
loginManager.setLoginBehavior(FBSDKLoginBehavior.Native);
}
@Override
public void loginWithReadPermissions(Collection<String> permissions, GDXFacebookCallback<GDXFacebookLoginResult> callback) {
login(permissions, callback, false);
}
@Override
public void loginWithPublishPermissions(Collection<String> permissions, GDXFacebookCallback<GDXFacebookLoginResult> callback) {
login(permissions, callback, true);
}
private void login(Collection<String> permissions, final GDXFacebookCallback<GDXFacebookLoginResult> callback, boolean withPublishPermissions) {
if (FBSDKAccessToken.getCurrentAccessToken() != null) {
accessToken = toGDXFacebookToken(FBSDKAccessToken.getCurrentAccessToken());
if (arePermissionsGranted(permissions)) {
GDXFacebookLoginResult result = new GDXFacebookLoginResult();
accessToken = toGDXFacebookToken(FBSDKAccessToken.getCurrentAccessToken());
storeToken(accessToken);
result.setAccessToken(accessToken);
callback.onSuccess(result);
}
} else {
VoidBlock2<FBSDKLoginManagerLoginResult, NSError> result = new VoidBlock2<FBSDKLoginManagerLoginResult, NSError>() {
@Override
public void invoke(FBSDKLoginManagerLoginResult loginResult, NSError nsError) {
if (nsError != null) {
logOut();
GDXFacebookError error = new GDXFacebookError();
error.setErrorMessage(nsError.getLocalizedDescription());
callback.onError(error);
} else if (loginResult.isCancelled()) {
logOut();
callback.onCancel();
} else {
GDXFacebookLoginResult result = new GDXFacebookLoginResult();
accessToken = toGDXFacebookToken(FBSDKAccessToken.getCurrentAccessToken());
storeToken(accessToken);
result.setAccessToken(accessToken);
callback.onSuccess(result);
}
}
};
List<String> listPermissions = (List<String>) permissions;
if (withPublishPermissions) {
loginManager.logInWithPublishPermissions(listPermissions, result);
} else {
loginManager.logInWithReadPermissions(listPermissions, result);
}
}
}
@Override
public boolean isLoggedIn() {
return accessToken != null;
}
@Override
public void logOut() {
accessToken = null;
storeToken(accessToken);
loginManager.logOut();
}
@Override
public GDXFacebookAccessToken getAccessToken() {
return accessToken;
}
private GDXFacebookAccessToken toGDXFacebookToken(FBSDKAccessToken accessToken) {
return new GDXFacebookAccessToken(accessToken.getTokenString(), accessToken.getAppID(), accessToken.getUserID(), collectionToGdxArray(accessToken.getPermissions()),
collectionToGdxArray(accessToken.getDeclinedPermissions()), accessToken.getExpirationDate().toDate().getTime(), accessToken.getRefreshDate().toDate().getTime());
}
// private FBSDKAccessToken fromGDXFacebookToken(GDXFacebookAccessToken
// accessToken) {
// return new FBSDKAccessToken(accessToken.getToken(),
// gdxArrayToCollection(accessToken.getPermissions()),
// gdxArrayToCollection(accessToken.getDeclinedPermissions()),
// accessToken.getApplicationId(), accessToken.getUserId(), new
// NSDate(accessToken.getExpirationTime() / 1000L), new
// NSDate(accessToken.getLastRefreshTime() / 1000L));
// }
private Array<String> collectionToGdxArray(Collection<String> col) {
String[] arr = new String[col.size()];
col.toArray(arr);
return new Array<String>(arr);
}
private Set<String> gdxArrayToCollection(Array<String> array) {
Set<String> col = new TreeSet<String>();
for (int i = 0; i < array.size; i++) {
col.add(array.get(i));
}
if (col.size() == 0) {
return null;
}
return col;
}
}
| gdx-facebook-ios/src/de/tomgrill/gdxfacebook/ios/IOSGDXFacebook.java | /*******************************************************************************
* Copyright 2015 See AUTHORS file.
*
* 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 de.tomgrill.gdxfacebook.ios;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.robovm.apple.foundation.NSError;
import org.robovm.objc.block.VoidBlock2;
import org.robovm.pods.facebook.core.FBSDKAccessToken;
import org.robovm.pods.facebook.login.FBSDKLoginBehavior;
import org.robovm.pods.facebook.login.FBSDKLoginManager;
import org.robovm.pods.facebook.login.FBSDKLoginManagerLoginResult;
import com.badlogic.gdx.utils.Array;
import de.tomgrill.gdxfacebook.core.GDXFacebook;
import de.tomgrill.gdxfacebook.core.GDXFacebookAccessToken;
import de.tomgrill.gdxfacebook.core.GDXFacebookCallback;
import de.tomgrill.gdxfacebook.core.GDXFacebookConfig;
import de.tomgrill.gdxfacebook.core.GDXFacebookError;
import de.tomgrill.gdxfacebook.core.GDXFacebookLoginResult;
public class IOSGDXFacebook extends GDXFacebook {
private FBSDKLoginManager loginManager;
private GDXFacebookAccessToken accessToken;
public IOSGDXFacebook(GDXFacebookConfig config) {
super(config);
loginManager = new FBSDKLoginManager();
loginManager.setLoginBehavior(FBSDKLoginBehavior.Native);
}
@Override
public void loginWithReadPermissions(Collection<String> permissions, GDXFacebookCallback<GDXFacebookLoginResult> callback) {
login(permissions, callback, false);
}
@Override
public void loginWithPublishPermissions(Collection<String> permissions, GDXFacebookCallback<GDXFacebookLoginResult> callback) {
login(permissions, callback, true);
}
private void login(Collection<String> permissions, final GDXFacebookCallback<GDXFacebookLoginResult> callback, boolean withPublishPermissions) {
if (FBSDKAccessToken.getCurrentAccessToken() != null) {
accessToken = toGDXFacebookToken(FBSDKAccessToken.getCurrentAccessToken());
if (arePermissionsGranted(permissions)) {
GDXFacebookLoginResult result = new GDXFacebookLoginResult();
accessToken = toGDXFacebookToken(FBSDKAccessToken.getCurrentAccessToken());
storeToken(accessToken);
result.setAccessToken(accessToken);
callback.onSuccess(result);
}
} else {
VoidBlock2<FBSDKLoginManagerLoginResult, NSError> result = new VoidBlock2<FBSDKLoginManagerLoginResult, NSError>() {
@Override
public void invoke(FBSDKLoginManagerLoginResult loginResult, NSError nsError) {
if (nsError != null) {
accessToken = null;
storeToken(accessToken);
GDXFacebookError error = new GDXFacebookError();
error.setErrorMessage(nsError.getLocalizedDescription());
callback.onError(error);
} else if (loginResult.isCancelled()) {
accessToken = null;
storeToken(accessToken);
callback.onCancel();
} else {
GDXFacebookLoginResult result = new GDXFacebookLoginResult();
accessToken = toGDXFacebookToken(FBSDKAccessToken.getCurrentAccessToken());
storeToken(accessToken);
result.setAccessToken(accessToken);
callback.onSuccess(result);
}
}
};
List<String> listPermissions = (List<String>) permissions;
if (withPublishPermissions) {
loginManager.logInWithPublishPermissions(listPermissions, result);
} else {
loginManager.logInWithReadPermissions(listPermissions, result);
}
}
}
@Override
public boolean isLoggedIn() {
return accessToken != null;
}
@Override
public void logOut() {
accessToken = null;
storeToken(accessToken);
loginManager.logOut();
}
@Override
public GDXFacebookAccessToken getAccessToken() {
return accessToken;
}
private GDXFacebookAccessToken toGDXFacebookToken(FBSDKAccessToken accessToken) {
return new GDXFacebookAccessToken(accessToken.getTokenString(), accessToken.getAppID(), accessToken.getUserID(), collectionToGdxArray(accessToken.getPermissions()),
collectionToGdxArray(accessToken.getDeclinedPermissions()), accessToken.getExpirationDate().toDate().getTime(), accessToken.getRefreshDate().toDate().getTime());
}
// private FBSDKAccessToken fromGDXFacebookToken(GDXFacebookAccessToken
// accessToken) {
// return new FBSDKAccessToken(accessToken.getToken(),
// gdxArrayToCollection(accessToken.getPermissions()),
// gdxArrayToCollection(accessToken.getDeclinedPermissions()),
// accessToken.getApplicationId(), accessToken.getUserId(), new
// NSDate(accessToken.getExpirationTime() / 1000L), new
// NSDate(accessToken.getLastRefreshTime() / 1000L));
// }
private Array<String> collectionToGdxArray(Collection<String> col) {
String[] arr = new String[col.size()];
col.toArray(arr);
return new Array<String>(arr);
}
private Set<String> gdxArrayToCollection(Array<String> array) {
Set<String> col = new TreeSet<String>();
for (int i = 0; i < array.size; i++) {
col.add(array.get(i));
}
if (col.size() == 0) {
return null;
}
return col;
}
}
| improved logout for ios | gdx-facebook-ios/src/de/tomgrill/gdxfacebook/ios/IOSGDXFacebook.java | improved logout for ios | <ide><path>dx-facebook-ios/src/de/tomgrill/gdxfacebook/ios/IOSGDXFacebook.java
<ide> public void invoke(FBSDKLoginManagerLoginResult loginResult, NSError nsError) {
<ide>
<ide> if (nsError != null) {
<del> accessToken = null;
<del> storeToken(accessToken);
<add> logOut();
<ide> GDXFacebookError error = new GDXFacebookError();
<ide> error.setErrorMessage(nsError.getLocalizedDescription());
<add>
<ide> callback.onError(error);
<ide>
<ide> } else if (loginResult.isCancelled()) {
<del> accessToken = null;
<del> storeToken(accessToken);
<add> logOut();
<ide> callback.onCancel();
<ide> } else {
<ide> GDXFacebookLoginResult result = new GDXFacebookLoginResult();
<del>
<ide> accessToken = toGDXFacebookToken(FBSDKAccessToken.getCurrentAccessToken());
<ide> storeToken(accessToken);
<ide> result.setAccessToken(accessToken); |
|
Java | apache-2.0 | 7c43bfb2b7b5a8a3ce327b0586b1f079ae2c0233 | 0 | greeun/plankton | package com.withwiz.plankton.network;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* Network address helper class<BR/>
* Created by uni4love on 2010. 05. 27..
*/
public class AddressHelper
{
/**
* logger
*/
private Logger log = LoggerFactory.getLogger(AddressHelper.class);
/**
* return localhost IP address.<BR/>
*
* @return IP address
*/
public static StringBuffer getLocalhostAddress()
{
InetAddress iaLocalAddress = null;
try
{
iaLocalAddress = InetAddress.getLocalHost();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
if (iaLocalAddress == null)
{
return null;
}
return getIp(iaLocalAddress);
}
/**
* return IP address(xxx.xxx.xxx.xxx)<BR/>
*
* @param ia
* InetAddress instance
* @return IP address(xxx.xxx.xxx.xxx)
*/
public static StringBuffer getIp(InetAddress ia)
{
byte[] address = ia.getAddress();
StringBuffer sb = new StringBuffer();
// filtering IP
for (int i = 0; i < address.length; i++)
{
int unsignedByte = address[i] < 0 ? address[i] + 256 : address[i];
sb.append(unsignedByte);
if ((address.length - i) != 1)
sb.append(".");
}
return sb;
}
/**
* return port of the socket.<BR/>
*
* @param socket
* Socket instance
* @return port number
*/
public static int getPort(Socket socket)
{
return socket.getPort();
}
/**
* return address(IP:PORT) of remote client from socket.<BR/>
*
* @param socket
* Socket instance
* @return address
*/
public static StringBuffer getTargetAddress(Socket socket)
{
return getIp(socket.getInetAddress()).append(":")
.append(getPort(socket));
}
/**
* return IP addresses from domain name.<BR/>
*
* @param domainName
* domain name
* @return IP address array
*/
public static String[] getDomain2Ip(String domainName)
{
// A domain can have multiple IP.
InetAddress[] ip;
String[] ipAddress = null;
try
{
ip = InetAddress.getAllByName(domainName);
ipAddress = new String[ip.length];
for (int i = 0; i < ip.length; i++)
{
ipAddress[i] = ip[i].getHostAddress();
}
}
catch (Exception ex)
{
System.out.println(">>> Error : " + ex.toString());
ex.printStackTrace();
}
return ipAddress;
}
/**
* return IP addresses from domain name.<BR/>
*
* @param domainName
* domain name
* @return IP address array
*/
public static String[] nslookup(String domainName)
{
return getDomain2Ip(domainName);
}
/**
* test main
*
* @param args
*/
public static void main(String args[])
{
AddressHelper test = new AddressHelper();
System.out.println("Localhost InetAddress : "
+ AddressHelper.getLocalhostAddress());
String domain = "www.yahoo.com";
System.out.println("> Your computer's IP address is "
+ AddressHelper.getLocalhostAddress());
for (int temp = 0; temp < AddressHelper
.getDomain2Ip(domain).length; temp++)
{
System.out.println(new StringBuffer().append("> \"").append(domain)
.append("\" domain IP address No.").append(temp + 1)
.append(" is ").append(getDomain2Ip(domain)[temp]));
}
for (int temp = 0; temp < AddressHelper.nslookup(domain).length; temp++)
{
System.out.println(new StringBuffer().append("> \"").append(domain)
.append("\" nslookup result No.").append(temp + 1)
.append(" is ")
.append(AddressHelper.nslookup(domain)[temp]));
}
}
}
| src/main/java/com/withwiz/plankton/network/AddressHelper.java | package com.withwiz.plankton.network;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* Network address helper class<BR/>
* Created by uni4love on 2010. 05. 27..
*/
public class AddressHelper
{
/**
* logger
*/
private Logger log = LoggerFactory.getLogger(AddressHelper.class);
/**
* return localhost IP address.<BR/>
*
* @return IP address
*/
public static StringBuffer getLocalhostAddress()
{
InetAddress iaLocalAddress = null;
try
{
iaLocalAddress = InetAddress.getLocalHost();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
if (iaLocalAddress == null)
{
return null;
}
return getIP(iaLocalAddress);
}
/**
* return IP address(xxx.xxx.xxx.xxx)<BR/>
*
* @param ia
* InetAddress instance
* @return IP address(xxx.xxx.xxx.xxx)
*/
public static StringBuffer getIP(InetAddress ia)
{
byte[] address = ia.getAddress();
StringBuffer sb = new StringBuffer();
// filtering IP
for (int i = 0; i < address.length; i++)
{
int unsignedByte = address[i] < 0 ? address[i] + 256 : address[i];
sb.append(unsignedByte);
if ((address.length - i) != 1)
sb.append(".");
}
return sb;
}
/**
* return port of the socket.<BR/>
*
* @param socket
* Socket instance
* @return port number
*/
public static int getPORT(Socket socket)
{
return socket.getPort();
}
/**
* return address(IP:PORT) of remote client from socket.<BR/>
*
* @param socket
* Socket instance
* @return address
*/
public static StringBuffer getTargetAddress(Socket socket)
{
return getIP(socket.getInetAddress()).append(":")
.append(getPORT(socket));
}
/**
* return IP addresses from domain name.<BR/>
*
* @param domainName
* domain name
* @return IP address array
*/
public static String[] getDomain2IP(String domainName)
{
// A domain can have multiple IP.
InetAddress[] ip;
String[] ipAddress = null;
try
{
ip = InetAddress.getAllByName(domainName);
ipAddress = new String[ip.length];
for (int i = 0; i < ip.length; i++)
{
ipAddress[i] = ip[i].getHostAddress();
}
}
catch (Exception ex)
{
System.out.println(">>> Error : " + ex.toString());
ex.printStackTrace();
}
return ipAddress;
}
/**
* return IP addresses from domain name.<BR/>
*
* @param domainName
* domain name
* @return IP address array
*/
public static String[] nslookup(String domainName)
{
return getDomain2IP(domainName);
}
/**
* test main
*
* @param args
*/
public static void main(String args[])
{
AddressHelper test = new AddressHelper();
System.out.println("Localhost InetAddress : "
+ AddressHelper.getLocalhostAddress());
String domain = "www.yahoo.com";
System.out.println("> Your computer's IP address is "
+ AddressHelper.getLocalhostAddress());
for (int temp = 0; temp < AddressHelper
.getDomain2IP(domain).length; temp++)
{
System.out.println(new StringBuffer().append("> \"").append(domain)
.append("\" domain IP address No.").append(temp + 1)
.append(" is ").append(getDomain2IP(domain)[temp]));
}
for (int temp = 0; temp < AddressHelper.nslookup(domain).length; temp++)
{
System.out.println(new StringBuffer().append("> \"").append(domain)
.append("\" nslookup result No.").append(temp + 1)
.append(" is ")
.append(AddressHelper.nslookup(domain)[temp]));
}
}
}
| - method name changed.
| src/main/java/com/withwiz/plankton/network/AddressHelper.java | - method name changed. | <ide><path>rc/main/java/com/withwiz/plankton/network/AddressHelper.java
<ide> {
<ide> return null;
<ide> }
<del> return getIP(iaLocalAddress);
<add> return getIp(iaLocalAddress);
<ide> }
<ide>
<ide> /**
<ide> * InetAddress instance
<ide> * @return IP address(xxx.xxx.xxx.xxx)
<ide> */
<del> public static StringBuffer getIP(InetAddress ia)
<add> public static StringBuffer getIp(InetAddress ia)
<ide> {
<ide> byte[] address = ia.getAddress();
<ide> StringBuffer sb = new StringBuffer();
<ide> * Socket instance
<ide> * @return port number
<ide> */
<del> public static int getPORT(Socket socket)
<add> public static int getPort(Socket socket)
<ide> {
<ide> return socket.getPort();
<ide> }
<ide> */
<ide> public static StringBuffer getTargetAddress(Socket socket)
<ide> {
<del> return getIP(socket.getInetAddress()).append(":")
<del> .append(getPORT(socket));
<add> return getIp(socket.getInetAddress()).append(":")
<add> .append(getPort(socket));
<ide> }
<ide>
<ide> /**
<ide> * domain name
<ide> * @return IP address array
<ide> */
<del> public static String[] getDomain2IP(String domainName)
<add> public static String[] getDomain2Ip(String domainName)
<ide> {
<ide> // A domain can have multiple IP.
<ide> InetAddress[] ip;
<ide> */
<ide> public static String[] nslookup(String domainName)
<ide> {
<del> return getDomain2IP(domainName);
<add> return getDomain2Ip(domainName);
<ide> }
<ide>
<ide> /**
<ide> System.out.println("> Your computer's IP address is "
<ide> + AddressHelper.getLocalhostAddress());
<ide> for (int temp = 0; temp < AddressHelper
<del> .getDomain2IP(domain).length; temp++)
<add> .getDomain2Ip(domain).length; temp++)
<ide> {
<ide> System.out.println(new StringBuffer().append("> \"").append(domain)
<ide> .append("\" domain IP address No.").append(temp + 1)
<del> .append(" is ").append(getDomain2IP(domain)[temp]));
<add> .append(" is ").append(getDomain2Ip(domain)[temp]));
<ide> }
<ide> for (int temp = 0; temp < AddressHelper.nslookup(domain).length; temp++)
<ide> { |
|
Java | apache-2.0 | 9aa88448d26109cd9b6e3589bec00055c33ecdd1 | 0 | da1z/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,semonte/intellij-community,allotria/intellij-community,vvv1559/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,ibinti/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,FHannes/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,xfournet/intellij-community,asedunov/intellij-community,allotria/intellij-community,xfournet/intellij-community,da1z/intellij-community,da1z/intellij-community,signed/intellij-community,allotria/intellij-community,signed/intellij-community,ibinti/intellij-community,da1z/intellij-community,youdonghai/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,signed/intellij-community,vvv1559/intellij-community,signed/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,vvv1559/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,asedunov/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,allotria/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,FHannes/intellij-community,FHannes/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,asedunov/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,signed/intellij-community,apixandru/intellij-community,signed/intellij-community,ibinti/intellij-community,ibinti/intellij-community,semonte/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,da1z/intellij-community,xfournet/intellij-community,allotria/intellij-community,da1z/intellij-community,FHannes/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,suncycheng/intellij-community,da1z/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,apixandru/intellij-community,allotria/intellij-community,ibinti/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,asedunov/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,mglukhikh/intellij-community,signed/intellij-community,ibinti/intellij-community,allotria/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,allotria/intellij-community,ibinti/intellij-community,semonte/intellij-community,xfournet/intellij-community,semonte/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,semonte/intellij-community,da1z/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,ibinti/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,signed/intellij-community,suncycheng/intellij-community,signed/intellij-community,semonte/intellij-community,signed/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,FHannes/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,ibinti/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.ui;
import com.intellij.CommonBundle;
import com.intellij.icons.AllIcons;
import com.intellij.ide.ui.UISettings;
import com.intellij.idea.ActionsBundle;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.MnemonicHelper;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionUtil;
import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.help.HelpManager;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.util.PopupUtil;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.IdeGlassPaneUtil;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.JBColor;
import com.intellij.ui.UIBundle;
import com.intellij.ui.border.CustomLineBorder;
import com.intellij.ui.components.JBOptionButton;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.panels.NonOpaquePanel;
import com.intellij.util.Alarm;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IconUtil;
import com.intellij.util.TimeoutUtil;
import com.intellij.util.ui.DialogUtil;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.intellij.lang.annotations.MagicConstant;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.UIResource;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
/**
* The standard base class for modal dialog boxes. The dialog wrapper could be used only on event dispatch thread.
* In case when the dialog must be created from other threads use
* {@link EventQueue#invokeLater(Runnable)} or {@link EventQueue#invokeAndWait(Runnable)}.
* <p/>
* See also http://confluence.jetbrains.net/display/IDEADEV/IntelliJ+IDEA+DialogWrapper.
*/
@SuppressWarnings({"SSBasedInspection", "MethodMayBeStatic"})
public abstract class DialogWrapper {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.ui.DialogWrapper");
public enum IdeModalityType {
IDE,
PROJECT,
MODELESS;
@NotNull
public Dialog.ModalityType toAwtModality() {
switch (this) {
case IDE:
return Dialog.ModalityType.APPLICATION_MODAL;
case PROJECT:
return Dialog.ModalityType.DOCUMENT_MODAL;
case MODELESS:
return Dialog.ModalityType.MODELESS;
}
throw new IllegalStateException(toString());
}
}
/**
* The default exit code for "OK" action.
*/
public static final int OK_EXIT_CODE = 0;
/**
* The default exit code for "Cancel" action.
*/
public static final int CANCEL_EXIT_CODE = 1;
/**
* The default exit code for "Close" action. Equal to cancel.
*/
public static final int CLOSE_EXIT_CODE = CANCEL_EXIT_CODE;
/**
* If you use your own custom exit codes you have to start them with
* this constant.
*/
public static final int NEXT_USER_EXIT_CODE = 2;
/**
* If your action returned by <code>createActions</code> method has non
* <code>null</code> value for this key, then the button that corresponds to the action will be the
* default button for the dialog. It's true if you don't change this behaviour
* of <code>createJButtonForAction(Action)</code> method.
*/
@NonNls public static final String DEFAULT_ACTION = "DefaultAction";
@NonNls public static final String FOCUSED_ACTION = "FocusedAction";
@NonNls private static final String NO_AUTORESIZE = "NoAutoResizeAndFit";
private static final KeyStroke SHOW_OPTION_KEYSTROKE = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,
InputEvent.ALT_MASK | InputEvent.SHIFT_MASK);
@NotNull
private final DialogWrapperPeer myPeer;
private int myExitCode = CANCEL_EXIT_CODE;
/**
* The shared instance of default border for dialog's content pane.
*/
public static final Border ourDefaultBorder = new EmptyBorder(UIUtil.PANEL_REGULAR_INSETS);
private float myHorizontalStretch = 1.0f;
private float myVerticalStretch = 1.0f;
/**
* Defines horizontal alignment of buttons.
*/
private int myButtonAlignment = SwingConstants.RIGHT;
private boolean myCrossClosesWindow = true;
private Insets myButtonMargins = JBUI.insets(2, 16);
protected Action myOKAction;
protected Action myCancelAction;
protected Action myHelpAction;
private final Map<Action, JButton> myButtonMap = new LinkedHashMap<>();
private boolean myClosed = false;
protected boolean myPerformAction = false;
private Action myYesAction = null;
private Action myNoAction = null;
protected JCheckBox myCheckBoxDoNotShowDialog;
@Nullable
private DoNotAskOption myDoNotAsk;
protected JComponent myPreferredFocusedComponent;
private Computable<Point> myInitialLocationCallback;
@NotNull
protected final Disposable myDisposable = new Disposable() {
@Override
public String toString() {
return DialogWrapper.this.toString();
}
@Override
public void dispose() {
DialogWrapper.this.dispose();
}
};
private final List<JBOptionButton> myOptionsButtons = new ArrayList<>();
private int myCurrentOptionsButtonIndex = -1;
private boolean myResizeInProgress = false;
private ComponentAdapter myResizeListener;
@NotNull
protected String getDoNotShowMessage() {
return CommonBundle.message("dialog.options.do.not.show");
}
public void setDoNotAskOption(@Nullable DoNotAskOption doNotAsk) {
myDoNotAsk = doNotAsk;
}
private ErrorText myErrorText;
private final Alarm myErrorTextAlarm = new Alarm();
/**
* Creates modal <code>DialogWrapper</code>. The currently active window will be the dialog's parent.
*
* @param project parent window for the dialog will be calculated based on focused window for the
* specified <code>project</code>. This parameter can be <code>null</code>. In this case parent window
* will be suggested based on current focused window.
* @param canBeParent specifies whether the dialog can be parent for other windows. This parameter is used
* by <code>WindowManager</code>.
* @throws IllegalStateException if the dialog is invoked not on the event dispatch thread
*/
protected DialogWrapper(@Nullable Project project, boolean canBeParent) {
this(project, canBeParent, IdeModalityType.IDE);
}
protected DialogWrapper(@Nullable Project project, boolean canBeParent, @NotNull IdeModalityType ideModalityType) {
this(project, null, canBeParent, ideModalityType);
}
protected DialogWrapper(@Nullable Project project, @Nullable Component parentComponent, boolean canBeParent, @NotNull IdeModalityType ideModalityType) {
myPeer = parentComponent == null ? createPeer(project, canBeParent, project == null ? IdeModalityType.IDE : ideModalityType) : createPeer(parentComponent, canBeParent);
final Window window = myPeer.getWindow();
if (window != null) {
myResizeListener = new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
if (!myResizeInProgress) {
myActualSize = myPeer.getSize();
if (myErrorText != null && myErrorText.isVisible()) {
myActualSize.height -= myErrorText.myLabel.getHeight();
}
}
}
};
window.addComponentListener(myResizeListener);
}
createDefaultActions();
}
/**
* Creates modal <code>DialogWrapper</code> that can be parent for other windows.
* The currently active window will be the dialog's parent.
*
* @param project parent window for the dialog will be calculated based on focused window for the
* specified <code>project</code>. This parameter can be <code>null</code>. In this case parent window
* will be suggested based on current focused window.
* @throws IllegalStateException if the dialog is invoked not on the event dispatch thread
* @see DialogWrapper#DialogWrapper(Project, boolean)
*/
protected DialogWrapper(@Nullable Project project) {
this(project, true);
}
/**
* Creates modal <code>DialogWrapper</code>. The currently active window will be the dialog's parent.
*
* @param canBeParent specifies whether the dialog can be parent for other windows. This parameter is used
* by <code>WindowManager</code>.
* @throws IllegalStateException if the dialog is invoked not on the event dispatch thread
*/
protected DialogWrapper(boolean canBeParent) {
this((Project)null, canBeParent);
}
/**
* Typically, we should set a parent explicitly. Use WindowManager#suggestParentWindow
* method to find out the best parent for your dialog. Exceptions are cases
* when we do not have a project to figure out which window
* is more suitable as an owner for the dialog.
* <p/>
* Instead, use {@link DialogWrapper#DialogWrapper(Project, boolean, boolean)}
*/
@Deprecated
protected DialogWrapper(boolean canBeParent, boolean applicationModalIfPossible) {
this(null, canBeParent, applicationModalIfPossible);
}
protected DialogWrapper(Project project, boolean canBeParent, boolean applicationModalIfPossible) {
ensureEventDispatchThread();
if (ApplicationManager.getApplication() != null) {
myPeer = createPeer(
project != null ? WindowManager.getInstance().suggestParentWindow(project) : WindowManager.getInstance().findVisibleFrame()
, canBeParent, applicationModalIfPossible);
}
else {
myPeer = createPeer(null, canBeParent, applicationModalIfPossible);
}
createDefaultActions();
}
/**
* @param parent parent component which is used to calculate heavy weight window ancestor.
* <code>parent</code> cannot be <code>null</code> and must be showing.
* @param canBeParent can be parent
* @throws IllegalStateException if the dialog is invoked not on the event dispatch thread
*/
protected DialogWrapper(@NotNull Component parent, boolean canBeParent) {
ensureEventDispatchThread();
myPeer = createPeer(parent, canBeParent);
createDefaultActions();
}
//validation
private final Alarm myValidationAlarm = new Alarm(getValidationThreadToUse(), myDisposable);
@NotNull
protected Alarm.ThreadToUse getValidationThreadToUse() {
return Alarm.ThreadToUse.SWING_THREAD;
}
private int myValidationDelay = 300;
private boolean myDisposed = false;
private boolean myValidationStarted = false;
private final ErrorPainter myErrorPainter = new ErrorPainter();
private boolean myErrorPainterInstalled = false;
/**
* Allows to postpone first start of validation
*
* @return <code>false</code> if start validation in <code>init()</code> method
*/
protected boolean postponeValidation() {
return true;
}
/**
* Validates user input and returns <code>null</code> if everything is fine
* or validation description with component where problem has been found.
*
* @return <code>null</code> if everything is OK or validation descriptor
*/
@Nullable
protected ValidationInfo doValidate() {
return null;
}
public void setValidationDelay(int delay) {
myValidationDelay = delay;
}
private void reportProblem(@NotNull final ValidationInfo info) {
installErrorPainter();
myErrorPainter.setValidationInfo(info);
if (!myErrorText.isTextSet(info.message)) {
SwingUtilities.invokeLater(() -> {
if (myDisposed) return;
setErrorText(info.message);
myPeer.getRootPane().getGlassPane().repaint();
getOKAction().setEnabled(false);
});
}
}
private void installErrorPainter() {
if (myErrorPainterInstalled) return;
myErrorPainterInstalled = true;
UIUtil.invokeLaterIfNeeded(() -> IdeGlassPaneUtil.installPainter(getContentPanel(), myErrorPainter, myDisposable));
}
private void clearProblems() {
myErrorPainter.setValidationInfo(null);
if (!myErrorText.isTextSet(null)) {
SwingUtilities.invokeLater(() -> {
if (myDisposed) return;
setErrorText(null);
myPeer.getRootPane().getGlassPane().repaint();
getOKAction().setEnabled(true);
});
}
}
protected void createDefaultActions() {
myOKAction = new OkAction();
myCancelAction = new CancelAction();
myHelpAction = new HelpAction();
}
public void setUndecorated(boolean undecorated) {
myPeer.setUndecorated(undecorated);
}
public final void addMouseListener(@NotNull MouseListener listener) {
myPeer.addMouseListener(listener);
}
public final void addMouseListener(@NotNull MouseMotionListener listener) {
myPeer.addMouseListener(listener);
}
public final void addKeyListener(@NotNull KeyListener listener) {
myPeer.addKeyListener(listener);
}
/**
* Closes and disposes the dialog and sets the specified exit code.
*
* @param exitCode exit code
* @param isOk is OK
* @throws IllegalStateException if the dialog is invoked not on the event dispatch thread
*/
public final void close(int exitCode, boolean isOk) {
ensureEventDispatchThread();
if (myClosed) return;
myClosed = true;
myExitCode = exitCode;
Window window = getWindow();
if (window != null && myResizeListener != null) {
window.removeComponentListener(myResizeListener);
myResizeListener = null;
}
if (isOk) {
processDoNotAskOnOk(exitCode);
}
else {
processDoNotAskOnCancel();
}
Disposer.dispose(myDisposable);
}
public final void close(int exitCode) {
close(exitCode, exitCode != CANCEL_EXIT_CODE);
}
/**
* Creates border for dialog's content pane. By default content
* pane has has empty border with <code>(8,12,8,12)</code> insets. Subclasses can
* return <code>null</code> for no border.
*
* @return content pane border
*/
@Nullable
protected Border createContentPaneBorder() {
if (getStyle() == DialogStyle.COMPACT) {
return JBUI.Borders.empty();
}
return ourDefaultBorder;
}
protected static boolean isMoveHelpButtonLeft() {
return UIUtil.isUnderAquaBasedLookAndFeel() || UIUtil.isUnderDarcula() || UIUtil.isUnderWin10LookAndFeel();
}
/**
* Creates panel located at the south of the content pane. By default that
* panel contains dialog's buttons. This default implementation uses <code>createActions()</code>
* and <code>createJButtonForAction(Action)</code> methods to construct the panel.
*
* @return south panel
*/
protected JComponent createSouthPanel() {
Action[] actions = filter(createActions());
Action[] leftSideActions = createLeftSideActions();
Map<Action, JButton> buttonMap = new LinkedHashMap<>();
boolean hasHelpToMoveToLeftSide = false;
if (isMoveHelpButtonLeft() && Arrays.asList(actions).contains(getHelpAction())) {
hasHelpToMoveToLeftSide = true;
actions = ArrayUtil.remove(actions, getHelpAction());
} else if (Registry.is("ide.remove.help.button.from.dialogs")) {
actions = ArrayUtil.remove(actions, getHelpAction());
}
if (SystemInfo.isMac) {
for (Action action : actions) {
if (action instanceof MacOtherAction) {
leftSideActions = ArrayUtil.append(leftSideActions, action);
actions = ArrayUtil.remove(actions, action);
break;
}
}
}
else if (UIUtil.isUnderGTKLookAndFeel() && Arrays.asList(actions).contains(getHelpAction())) {
leftSideActions = ArrayUtil.append(leftSideActions, getHelpAction());
actions = ArrayUtil.remove(actions, getHelpAction());
}
JPanel panel = new JPanel(new BorderLayout()) {
@Override
public Color getBackground() {
final Color bg = UIManager.getColor("DialogWrapper.southPanelBackground");
if (getStyle() == DialogStyle.COMPACT && bg != null) {
return bg;
}
return super.getBackground();
}
};
final JPanel lrButtonsPanel = new NonOpaquePanel(new GridBagLayout());
//noinspection UseDPIAwareInsets
final Insets insets = SystemInfo.isMacOSLeopard ? UIUtil.isUnderIntelliJLaF() ? JBUI.insets(0, 8) : JBUI.emptyInsets() : new Insets(8, 0, 0, 0); //don't wrap to JBInsets
if (actions.length > 0 || leftSideActions.length > 0) {
int gridX = 0;
if (leftSideActions.length > 0) {
JPanel buttonsPanel = createButtons(leftSideActions, buttonMap);
if (actions.length > 0) {
buttonsPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 20)); // leave some space between button groups
}
lrButtonsPanel.add(buttonsPanel,
new GridBagConstraints(gridX++, 0, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, insets, 0,
0));
}
lrButtonsPanel.add(Box.createHorizontalGlue(), // left strut
new GridBagConstraints(gridX++, 0, 1, 1, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, insets, 0,
0));
if (actions.length > 0) {
if (SystemInfo.isMac) {
// move ok action to the right
int okNdx = ArrayUtil.indexOf(actions, getOKAction());
if (okNdx >= 0 && okNdx != actions.length - 1) {
actions = ArrayUtil.append(ArrayUtil.remove(actions, getOKAction()), getOKAction());
}
// move cancel action to the left
int cancelNdx = ArrayUtil.indexOf(actions, getCancelAction());
if (cancelNdx > 0) {
actions = ArrayUtil.mergeArrays(new Action[]{getCancelAction()}, ArrayUtil.remove(actions, getCancelAction()));
}
/*if (!hasFocusedAction(actions)) {
int ndx = ArrayUtil.find(actions, getCancelAction());
if (ndx >= 0) {
actions[ndx].putValue(FOCUSED_ACTION, Boolean.TRUE);
}
}*/
}
JPanel buttonsPanel = createButtons(actions, buttonMap);
if (shouldAddErrorNearButtons()) {
lrButtonsPanel.add(myErrorText, new GridBagConstraints(gridX++, 0, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE,
insets, 0, 0));
lrButtonsPanel.add(Box.createHorizontalStrut(10), new GridBagConstraints(gridX++, 0, 1, 1, 0, 0, GridBagConstraints.CENTER,
GridBagConstraints.NONE, insets, 0, 0));
}
lrButtonsPanel.add(buttonsPanel,
new GridBagConstraints(gridX++, 0, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, insets, 0,
0));
}
if (SwingConstants.CENTER == myButtonAlignment) {
lrButtonsPanel.add(Box.createHorizontalGlue(), // right strut
new GridBagConstraints(gridX, 0, 1, 1, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, insets, 0,
0));
}
myButtonMap.clear();
myButtonMap.putAll(buttonMap);
}
if (hasHelpToMoveToLeftSide) {
if (!(SystemInfo.isWindows && (UIUtil.isUnderDarcula() || UIUtil.isUnderIntelliJLaF()) && Registry.is("ide.win.frame.decoration"))) {
JButton helpButton = createHelpButton(insets);
panel.add(helpButton, BorderLayout.WEST);
}
}
panel.add(lrButtonsPanel, BorderLayout.CENTER);
final DoNotAskOption askOption = myDoNotAsk;
if (askOption != null) {
myCheckBoxDoNotShowDialog = new JCheckBox(askOption.getDoNotShowMessage());
JComponent southPanel = panel;
if (!askOption.canBeHidden()) {
return southPanel;
}
final JPanel withCB = addDoNotShowCheckBox(southPanel, myCheckBoxDoNotShowDialog);
myCheckBoxDoNotShowDialog.setSelected(!askOption.isToBeShown());
DialogUtil.registerMnemonic(myCheckBoxDoNotShowDialog, '&');
panel = withCB;
}
if (getStyle() == DialogStyle.COMPACT) {
final Color color = UIManager.getColor("DialogWrapper.southPanelDivider");
Border line = new CustomLineBorder(color != null ? color : OnePixelDivider.BACKGROUND, 1, 0, 0, 0);
panel.setBorder(new CompoundBorder(line, JBUI.Borders.empty(8, 12)));
} else {
panel.setBorder(JBUI.Borders.emptyTop(8));
}
return panel;
}
@NotNull
protected JButton createHelpButton(Insets insets) {
final JButton helpButton;
if ((SystemInfo.isWindows && UIUtil.isUnderIntelliJLaF() && Registry.is("ide.intellij.laf.win10.ui"))) {
helpButton = new JButton(getHelpAction()) {
@Override
public void paint(Graphics g) {
IconUtil.paintInCenterOf(this, g, AllIcons.Windows.WinHelp);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(AllIcons.Windows.WinHelp.getIconWidth(), AllIcons.Windows.WinHelp.getIconHeight());
}
};
helpButton.setOpaque(false);
} else {
helpButton = new JButton(getHelpAction());
}
helpButton.putClientProperty("JButton.buttonType", "help");
helpButton.setText("");
helpButton.setMargin(insets);
helpButton.setToolTipText(ActionsBundle.actionDescription("HelpTopics"));
return helpButton;
}
protected boolean shouldAddErrorNearButtons() {
return false;
}
@NotNull
protected DialogStyle getStyle() {
return DialogStyle.NO_STYLE;
}
@NotNull
private Action[] filter(@NotNull Action[] actions) {
ArrayList<Action> answer = new ArrayList<>();
for (Action action : actions) {
if (action != null && (ApplicationInfo.contextHelpAvailable() || action != getHelpAction())) {
answer.add(action);
}
}
return answer.toArray(new Action[answer.size()]);
}
protected boolean toBeShown() {
return !myCheckBoxDoNotShowDialog.isSelected();
}
public boolean isTypeAheadEnabled() {
return false;
}
@NotNull
public static JPanel addDoNotShowCheckBox(@NotNull JComponent southPanel, @NotNull JCheckBox checkBox) {
final JPanel panel = new JPanel(new BorderLayout());
JPanel wrapper = new JPanel(new GridBagLayout());
wrapper.add(checkBox);
panel.add(wrapper, BorderLayout.WEST);
panel.add(southPanel, BorderLayout.EAST);
checkBox.setBorder(JBUI.Borders.emptyRight(20));
if (SystemInfo.isMac || (SystemInfo.isWindows && Registry.is("ide.intellij.laf.win10.ui"))) {
JButton helpButton = null;
for (JButton button : UIUtil.findComponentsOfType(southPanel, JButton.class)) {
if ("help".equals(button.getClientProperty("JButton.buttonType"))) {
helpButton = button;
break;
}
}
if (helpButton != null) {
return JBUI.Panels.simplePanel(panel).addToLeft(helpButton);
}
}
return panel;
}
private boolean hasFocusedAction(@NotNull Action[] actions) {
for (Action action : actions) {
if (action.getValue(FOCUSED_ACTION) != null && (Boolean)action.getValue(FOCUSED_ACTION)) {
return true;
}
}
return false;
}
@NotNull
private JPanel createButtons(@NotNull Action[] actions, @NotNull Map<Action, JButton> buttons) {
if (!UISettings.getShadowInstance().ALLOW_MERGE_BUTTONS) {
final List<Action> actionList = new ArrayList<>();
for (Action action : actions) {
actionList.add(action);
if (action instanceof OptionAction) {
final Action[] options = ((OptionAction)action).getOptions();
actionList.addAll(Arrays.asList(options));
}
}
if (actionList.size() != actions.length) {
actions = actionList.toArray(actionList.toArray(new Action[actionList.size()]));
}
}
JPanel buttonsPanel = new NonOpaquePanel(new GridLayout(1, actions.length, SystemInfo.isMacOSLeopard ? UIUtil.isUnderIntelliJLaF() ? 8 : 0 : 5, 0));
for (final Action action : actions) {
JButton button = createJButtonForAction(action);
final Object value = action.getValue(Action.MNEMONIC_KEY);
if (value instanceof Integer) {
final int mnemonic = ((Integer)value).intValue();
final Object name = action.getValue(Action.NAME);
if (mnemonic == 'Y' && "Yes".equals(name)) {
myYesAction = action;
}
else if (mnemonic == 'N' && "No".equals(name)) {
myNoAction = action;
}
button.setMnemonic(mnemonic);
}
if (action.getValue(FOCUSED_ACTION) != null) {
myPreferredFocusedComponent = button;
}
buttons.put(action, button);
buttonsPanel.add(button);
}
return buttonsPanel;
}
/**
*
* @param action should be registered to find corresponding JButton
* @return button for specified action or null if it's not found
*/
@Nullable
protected JButton getButton(@NotNull Action action) {
return myButtonMap.get(action);
}
/**
* Creates <code>JButton</code> for the specified action. If the button has not <code>null</code>
* value for <code>DialogWrapper.DEFAULT_ACTION</code> key then the created button will be the
* default one for the dialog.
*
* @param action action for the button
* @return button with action specified
* @see DialogWrapper#DEFAULT_ACTION
*/
protected JButton createJButtonForAction(Action action) {
JButton button;
if (action instanceof OptionAction && UISettings.getShadowInstance().ALLOW_MERGE_BUTTONS) {
final Action[] options = ((OptionAction)action).getOptions();
button = new JBOptionButton(action, options);
final JBOptionButton eachOptionsButton = (JBOptionButton)button;
eachOptionsButton.setOkToProcessDefaultMnemonics(false);
eachOptionsButton.setOptionTooltipText(
"Press " + KeymapUtil.getKeystrokeText(SHOW_OPTION_KEYSTROKE) + " to expand or use a mnemonic of a contained action");
myOptionsButtons.add(eachOptionsButton);
final Set<JBOptionButton.OptionInfo> infos = eachOptionsButton.getOptionInfos();
for (final JBOptionButton.OptionInfo eachInfo : infos) {
if (eachInfo.getMnemonic() >= 0) {
final char mnemonic = (char)eachInfo.getMnemonic();
JRootPane rootPane = getPeer().getRootPane();
if (rootPane != null) {
new DumbAwareAction() {
@Override
public void actionPerformed(AnActionEvent e) {
final JBOptionButton buttonToActivate = eachInfo.getButton();
buttonToActivate.showPopup(eachInfo.getAction(), true);
}
}.registerCustomShortcutSet(MnemonicHelper.createShortcut(mnemonic), rootPane, myDisposable);
}
}
}
}
else {
button = new JButton(action);
}
String text = button.getText();
if (SystemInfo.isMac) {
button.putClientProperty("JButton.buttonType", "text");
}
if (text != null) {
int mnemonic = 0;
StringBuilder plainText = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if (ch == '_' || ch == '&') {
i++;
if (i >= text.length()) {
break;
}
ch = text.charAt(i);
if (ch != '_' && ch != '&') {
// Mnemonic is case insensitive.
int vk = ch;
if (vk >= 'a' && vk <= 'z') {
vk -= 'a' - 'A';
}
mnemonic = vk;
}
}
plainText.append(ch);
}
button.setText(plainText.toString());
final Object name = action.getValue(Action.NAME);
if (mnemonic == KeyEvent.VK_Y && "Yes".equals(name)) {
myYesAction = action;
}
else if (mnemonic == KeyEvent.VK_N && "No".equals(name)) {
myNoAction = action;
}
button.setMnemonic(mnemonic);
}
setMargin(button);
if (action.getValue(DEFAULT_ACTION) != null) {
if (!myPeer.isHeadless()) {
getRootPane().setDefaultButton(button);
}
}
return button;
}
private void setMargin(@NotNull JButton button) {
// Aqua LnF does a good job of setting proper margin between buttons. Setting them specifically causes them be 'square' style instead of
// 'rounded', which is expected by apple users.
if (!SystemInfo.isMac) {
if (myButtonMargins == null) {
return;
}
button.setMargin(myButtonMargins);
}
}
@NotNull
protected DialogWrapperPeer createPeer(@NotNull Component parent, final boolean canBeParent) {
return DialogWrapperPeerFactory.getInstance().createPeer(this, parent, canBeParent);
}
/**
* Dialogs with no parents are discouraged.
* Instead, use e.g. {@link DialogWrapper#createPeer(Window, boolean, boolean)}
*/
@Deprecated
@NotNull
protected DialogWrapperPeer createPeer(boolean canBeParent, boolean applicationModalIfPossible) {
return createPeer(null, canBeParent, applicationModalIfPossible);
}
@NotNull
protected DialogWrapperPeer createPeer(final Window owner, final boolean canBeParent, final IdeModalityType ideModalityType) {
return DialogWrapperPeerFactory.getInstance().createPeer(this, owner, canBeParent, ideModalityType);
}
@Deprecated
@NotNull
protected DialogWrapperPeer createPeer(final Window owner, final boolean canBeParent, final boolean applicationModalIfPossible) {
return DialogWrapperPeerFactory.getInstance()
.createPeer(this, owner, canBeParent, applicationModalIfPossible ? IdeModalityType.IDE : IdeModalityType.PROJECT);
}
@NotNull
protected DialogWrapperPeer createPeer(@Nullable final Project project,
final boolean canBeParent,
@NotNull IdeModalityType ideModalityType) {
return DialogWrapperPeerFactory.getInstance().createPeer(this, project, canBeParent, ideModalityType);
}
@NotNull
protected DialogWrapperPeer createPeer(@Nullable final Project project, final boolean canBeParent) {
return DialogWrapperPeerFactory.getInstance().createPeer(this, project, canBeParent);
}
@Nullable
protected JComponent createTitlePane() {
return null;
}
/**
* Factory method. It creates the panel located at the
* north of the dialog's content pane. The implementation can return <code>null</code>
* value. In this case there will be no input panel.
*
* @return north panel
*/
@Nullable
protected JComponent createNorthPanel() {
return null;
}
/**
* Factory method. It creates panel with dialog options. Options panel is located at the
* center of the dialog's content pane. The implementation can return <code>null</code>
* value. In this case there will be no options panel.
*
* @return center panel
*/
@Nullable
protected abstract JComponent createCenterPanel();
/**
* @see Window#toFront()
*/
public void toFront() {
myPeer.toFront();
}
/**
* @see Window#toBack()
*/
public void toBack() {
myPeer.toBack();
}
protected boolean setAutoAdjustable(boolean autoAdjustable) {
JRootPane rootPane = getRootPane();
if (rootPane == null) return false;
rootPane.putClientProperty(NO_AUTORESIZE, autoAdjustable ? null : Boolean.TRUE);
return true;
}
//true by default
public boolean isAutoAdjustable() {
JRootPane rootPane = getRootPane();
return rootPane == null || rootPane.getClientProperty(NO_AUTORESIZE) == null;
}
/**
* Dispose the wrapped and releases all resources allocated be the wrapper to help
* more efficient garbage collection. You should never invoke this method twice or
* invoke any method of the wrapper after invocation of <code>dispose</code>.
*
* @throws IllegalStateException if the dialog is disposed not on the event dispatch thread
*/
protected void dispose() {
ensureEventDispatchThread();
myErrorTextAlarm.cancelAllRequests();
myValidationAlarm.cancelAllRequests();
myDisposed = true;
if (myButtonMap != null) {
for (JButton button : myButtonMap.values()) {
button.setAction(null); // avoid memory leak via KeyboardManager
}
myButtonMap.clear();
}
final JRootPane rootPane = getRootPane();
// if rootPane = null, dialog has already been disposed
if (rootPane != null) {
unregisterKeyboardActions(rootPane);
if (myActualSize != null && isAutoAdjustable()) {
setSize(myActualSize.width, myActualSize.height);
}
myPeer.dispose();
}
}
public static void unregisterKeyboardActions(final JRootPane rootPane) {
for (JComponent eachComp : UIUtil.uiTraverser(rootPane).traverse().filter(JComponent.class)) {
ActionMap actionMap = eachComp.getActionMap();
KeyStroke[] strokes = eachComp.getRegisteredKeyStrokes();
for (KeyStroke eachStroke : strokes) {
boolean remove = true;
if (actionMap != null) {
for (int i : new int[]{JComponent.WHEN_FOCUSED, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, JComponent.WHEN_IN_FOCUSED_WINDOW}) {
final InputMap inputMap = eachComp.getInputMap(i);
final Object key = inputMap.get(eachStroke);
if (key != null) {
final Action action = actionMap.get(key);
if (action instanceof UIResource) remove = false;
}
}
}
if (remove) eachComp.unregisterKeyboardAction(eachStroke);
}
}
}
/**
* This method is invoked by default implementation of "Cancel" action. It just closes dialog
* with <code>CANCEL_EXIT_CODE</code>. This is convenient place to override functionality of "Cancel" action.
* Note that the method does nothing if "Cancel" action isn't enabled.
*/
public void doCancelAction() {
if (getCancelAction().isEnabled()) {
close(CANCEL_EXIT_CODE);
}
}
private void processDoNotAskOnCancel() {
if (myDoNotAsk != null) {
if (myDoNotAsk.shouldSaveOptionsOnCancel() && myDoNotAsk.canBeHidden()) {
myDoNotAsk.setToBeShown(toBeShown(), CANCEL_EXIT_CODE);
}
}
}
/**
* You can use this method if you want to know by which event this actions got triggered. It is called only if
* the cancel action was triggered by some input event, <code>doCancelAction</code> is called otherwise.
*
* @param source AWT event
* @see #doCancelAction
*/
public void doCancelAction(AWTEvent source) {
doCancelAction();
}
/**
* Programmatically perform a "click" of default dialog's button. The method does
* nothing if the dialog has no default button.
*/
public void clickDefaultButton() {
JButton button = getRootPane().getDefaultButton();
if (button != null) {
button.doClick();
}
}
/**
* This method is invoked by default implementation of "OK" action. It just closes dialog
* with <code>OK_EXIT_CODE</code>. This is convenient place to override functionality of "OK" action.
* Note that the method does nothing if "OK" action isn't enabled.
*/
protected void doOKAction() {
if (getOKAction().isEnabled()) {
close(OK_EXIT_CODE);
}
}
protected void processDoNotAskOnOk(int exitCode) {
if (myDoNotAsk != null) {
if (myDoNotAsk.canBeHidden()) {
myDoNotAsk.setToBeShown(toBeShown(), exitCode);
}
}
}
/**
* @return whether the native window cross button closes the window or not.
* <code>true</code> means that cross performs hide or dispose of the dialog.
*/
public boolean shouldCloseOnCross() {
return myCrossClosesWindow;
}
/**
* Creates actions for dialog.
* <p/>
* By default "OK" and "Cancel" actions are returned. The "Help" action is automatically added if
* {@link #getHelpId()} returns non-null value.
* <p/>
* Each action is represented by <code>JButton</code> created by {@link #createJButtonForAction(Action)}.
* These buttons are then placed into {@link #createSouthPanel() south panel} of dialog.
*
* @return dialog actions
* @see #createSouthPanel
* @see #createJButtonForAction
*/
@NotNull
protected Action[] createActions() {
if (getHelpId() == null) {
if (SystemInfo.isMac) {
return new Action[]{getCancelAction(), getOKAction()};
}
return new Action[]{getOKAction(), getCancelAction()};
}
else {
if (SystemInfo.isMac) {
return new Action[]{getHelpAction(), getCancelAction(), getOKAction()};
}
return new Action[]{getOKAction(), getCancelAction(), getHelpAction()};
}
}
@NotNull
protected Action[] createLeftSideActions() {
return new Action[0];
}
/**
* @return default implementation of "OK" action. This action just invokes
* <code>doOKAction()</code> method.
* @see #doOKAction
*/
@NotNull
protected Action getOKAction() {
return myOKAction;
}
/**
* @return default implementation of "Cancel" action. This action just invokes
* <code>doCancelAction()</code> method.
* @see #doCancelAction
*/
@NotNull
protected Action getCancelAction() {
return myCancelAction;
}
/**
* @return default implementation of "Help" action. This action just invokes
* <code>doHelpAction()</code> method.
* @see #doHelpAction
*/
@NotNull
protected Action getHelpAction() {
return myHelpAction;
}
protected boolean isProgressDialog() {
return false;
}
public final boolean isModalProgress() {
return isProgressDialog();
}
/**
* Returns content pane
*
* @return content pane
* @see JDialog#getContentPane
*/
public Container getContentPane() {
return myPeer.getContentPane();
}
/**
* @see JDialog#validate
*/
public void validate() {
myPeer.validate();
}
/**
* @see JDialog#repaint
*/
public void repaint() {
myPeer.repaint();
}
/**
* Returns key for persisting dialog dimensions.
* <p/>
* Default implementation returns <code>null</code> (no persisting).
*
* @return dimension service key
*/
@Nullable
@NonNls
protected String getDimensionServiceKey() {
return null;
}
@Nullable
public final String getDimensionKey() {
return getDimensionServiceKey();
}
public int getExitCode() {
return myExitCode;
}
/**
* @return component which should be focused when the dialog appears
* on the screen.
*/
@Nullable
public JComponent getPreferredFocusedComponent() {
return SystemInfo.isMac ? myPreferredFocusedComponent : null;
}
/**
* @return horizontal stretch of the dialog. It means that the dialog's horizontal size is
* the product of horizontal stretch by horizontal size of packed dialog. The default value
* is <code>1.0f</code>
*/
public final float getHorizontalStretch() {
return myHorizontalStretch;
}
/**
* @return vertical stretch of the dialog. It means that the dialog's vertical size is
* the product of vertical stretch by vertical size of packed dialog. The default value
* is <code>1.0f</code>
*/
public final float getVerticalStretch() {
return myVerticalStretch;
}
protected final void setHorizontalStretch(float hStretch) {
myHorizontalStretch = hStretch;
}
protected final void setVerticalStretch(float vStretch) {
myVerticalStretch = vStretch;
}
/**
* @return window owner
* @see Window#getOwner
*/
public Window getOwner() {
return myPeer.getOwner();
}
public Window getWindow() {
return myPeer.getWindow();
}
public JComponent getContentPanel() {
return (JComponent)myPeer.getContentPane();
}
/**
* @return root pane
* @see JDialog#getRootPane
*/
public JRootPane getRootPane() {
return myPeer.getRootPane();
}
/**
* @return dialog size
* @see Window#getSize
*/
public Dimension getSize() {
return myPeer.getSize();
}
/**
* @return dialog title
* @see Dialog#getTitle
*/
public String getTitle() {
return myPeer.getTitle();
}
protected void init() {
ensureEventDispatchThread();
myErrorText = new ErrorText(getErrorTextAlignment());
myErrorText.setVisible(false);
final ComponentAdapter resizeListener = new ComponentAdapter() {
private int myHeight;
@Override
public void componentResized(ComponentEvent event) {
int height = !myErrorText.isVisible() ? 0 : event.getComponent().getHeight();
if (height != myHeight) {
myHeight = height;
myResizeInProgress = true;
myErrorText.setMinimumSize(new Dimension(0, height));
JRootPane root = myPeer.getRootPane();
if (root != null) {
root.validate();
}
if (myActualSize != null && !shouldAddErrorNearButtons()) {
myPeer.setSize(myActualSize.width, myActualSize.height + height);
}
myErrorText.revalidate();
myResizeInProgress = false;
}
}
};
myErrorText.myLabel.addComponentListener(resizeListener);
Disposer.register(myDisposable, new Disposable() {
@Override
public void dispose() {
myErrorText.myLabel.removeComponentListener(resizeListener);
}
});
final JPanel root = new JPanel(createRootLayout());
//{
// @Override
// public void paint(Graphics g) {
// if (ApplicationManager.getApplication() != null) {
// UISettings.setupAntialiasing(g);
// }
// super.paint(g);
// }
//};
myPeer.setContentPane(root);
final CustomShortcutSet sc = new CustomShortcutSet(SHOW_OPTION_KEYSTROKE);
final AnAction toggleShowOptions = new DumbAwareAction() {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
expandNextOptionButton();
}
};
toggleShowOptions.registerCustomShortcutSet(sc, root, myDisposable);
JComponent titlePane = createTitlePane();
if (titlePane != null) {
JPanel northSection = new JPanel(new BorderLayout());
root.add(northSection, BorderLayout.NORTH);
northSection.add(titlePane, BorderLayout.CENTER);
}
JComponent centerSection = new JPanel(new BorderLayout());
root.add(centerSection, BorderLayout.CENTER);
root.setBorder(createContentPaneBorder());
final JComponent n = createNorthPanel();
if (n != null) {
centerSection.add(n, BorderLayout.NORTH);
}
final JComponent c = createCenterPanel();
if (c != null) {
centerSection.add(c, BorderLayout.CENTER);
}
final JPanel southSection = new JPanel(new BorderLayout());
root.add(southSection, BorderLayout.SOUTH);
southSection.add(myErrorText, BorderLayout.CENTER);
final JComponent south = createSouthPanel();
if (south != null) {
southSection.add(south, BorderLayout.SOUTH);
}
MnemonicHelper.init(root);
if (!postponeValidation()) {
startTrackingValidation();
}
if (SystemInfo.isWindows) {
installEnterHook(root, myDisposable);
}
myErrorTextAlarm.setActivationComponent(root);
}
protected int getErrorTextAlignment() {
return SwingConstants.LEADING;
}
@NotNull
LayoutManager createRootLayout() {
return new BorderLayout();
}
private static void installEnterHook(JComponent root, Disposable disposable) {
new DumbAwareAction() {
@Override
public void actionPerformed(AnActionEvent e) {
final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
if (owner instanceof JButton && owner.isEnabled()) {
((JButton)owner).doClick();
}
}
@Override
public void update(AnActionEvent e) {
final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
e.getPresentation().setEnabled(owner instanceof JButton && owner.isEnabled());
}
}.registerCustomShortcutSet(CustomShortcutSet.fromString("ENTER"), root, disposable);
}
private void expandNextOptionButton() {
if (myCurrentOptionsButtonIndex > 0) {
myOptionsButtons.get(myCurrentOptionsButtonIndex).closePopup();
myCurrentOptionsButtonIndex++;
}
else if (!myOptionsButtons.isEmpty()) {
myCurrentOptionsButtonIndex = 0;
}
if (myCurrentOptionsButtonIndex >= 0 && myCurrentOptionsButtonIndex < myOptionsButtons.size()) {
myOptionsButtons.get(myCurrentOptionsButtonIndex).showPopup(null, true);
}
}
void startTrackingValidation() {
SwingUtilities.invokeLater(() -> {
if (!myValidationStarted && !myDisposed) {
myValidationStarted = true;
initValidation();
}
});
}
protected final void initValidation() {
myValidationAlarm.cancelAllRequests();
final Runnable validateRequest = () -> {
if (myDisposed) return;
final ValidationInfo result = doValidate();
if (result == null) {
clearProblems();
}
else {
reportProblem(result);
}
if (!myDisposed) {
initValidation();
}
};
if (getValidationThreadToUse() == Alarm.ThreadToUse.SWING_THREAD) {
// null if headless
JRootPane rootPane = getRootPane();
myValidationAlarm.addRequest(validateRequest, myValidationDelay,
ApplicationManager.getApplication() == null
? null
: rootPane == null ? ModalityState.current() : ModalityState.stateForComponent(rootPane));
}
else {
myValidationAlarm.addRequest(validateRequest, myValidationDelay);
}
}
protected boolean isNorthStrictedToPreferredSize() {
return true;
}
protected boolean isCenterStrictedToPreferredSize() {
return false;
}
protected boolean isSouthStrictedToPreferredSize() {
return true;
}
@NotNull
protected JComponent createContentPane() {
return new JPanel();
}
/**
* @see Window#pack
*/
public void pack() {
myPeer.pack();
}
public Dimension getPreferredSize() {
return myPeer.getPreferredSize();
}
/**
* Sets horizontal alignment of dialog's buttons.
*
* @param alignment alignment of the buttons. Acceptable values are
* <code>SwingConstants.CENTER</code> and <code>SwingConstants.RIGHT</code>.
* The <code>SwingConstants.RIGHT</code> is the default value.
* @throws IllegalArgumentException if <code>alignment</code> isn't acceptable
*/
protected final void setButtonsAlignment(@MagicConstant(intValues = {SwingConstants.CENTER, SwingConstants.RIGHT}) int alignment) {
if (SwingConstants.CENTER != alignment && SwingConstants.RIGHT != alignment) {
throw new IllegalArgumentException("unknown alignment: " + alignment);
}
myButtonAlignment = alignment;
}
/**
* Sets margin for command buttons ("OK", "Cancel", "Help").
*
* @param insets buttons margin
*/
public final void setButtonsMargin(@Nullable Insets insets) {
myButtonMargins = insets;
}
public final void setCrossClosesWindow(boolean crossClosesWindow) {
myCrossClosesWindow = crossClosesWindow;
}
protected final void setCancelButtonIcon(Icon icon) {
// Setting icons causes buttons be 'square' style instead of
// 'rounded', which is expected by apple users.
if (!SystemInfo.isMac) {
myCancelAction.putValue(Action.SMALL_ICON, icon);
}
}
protected final void setCancelButtonText(String text) {
myCancelAction.putValue(Action.NAME, text);
}
public void setModal(boolean modal) {
myPeer.setModal(modal);
}
public boolean isModal() {
return myPeer.isModal();
}
public boolean isOKActionEnabled() {
return myOKAction.isEnabled();
}
public void setOKActionEnabled(boolean isEnabled) {
myOKAction.setEnabled(isEnabled);
}
protected final void setOKButtonIcon(Icon icon) {
// Setting icons causes buttons be 'square' style instead of
// 'rounded', which is expected by apple users.
if (!SystemInfo.isMac) {
myOKAction.putValue(Action.SMALL_ICON, icon);
}
}
/**
* @param text action without mnemonic. If mnemonic is set, presentation would be shifted by one to the left
* {@link AbstractButton#setText(String)}
* {@link AbstractButton#updateDisplayedMnemonicIndex(String, int)}
*/
protected final void setOKButtonText(String text) {
myOKAction.putValue(Action.NAME, text);
}
protected final void setOKButtonMnemonic(int c) {
myOKAction.putValue(Action.MNEMONIC_KEY, c);
}
/**
* @return the help identifier or null if no help is available.
*/
@Nullable
protected String getHelpId() {
return null;
}
/**
* Invoked by default implementation of "Help" action.
* Note that the method does nothing if "Help" action isn't enabled.
* <p/>
* The default implementation shows the help page with id returned
* by {@link #getHelpId()}. If that method returns null,
* a message box with message "no help available" is shown.
*/
protected void doHelpAction() {
if (myHelpAction.isEnabled()) {
String helpId = getHelpId();
if (helpId != null) {
HelpManager.getInstance().invokeHelp(helpId);
}
else {
Messages.showMessageDialog(getContentPane(), UIBundle.message("there.is.no.help.for.this.dialog.error.message"),
UIBundle.message("no.help.available.dialog.title"), Messages.getInformationIcon());
}
}
}
public boolean isOK() {
return getExitCode() == OK_EXIT_CODE;
}
/**
* @return <code>true</code> if and only if visible
* @see Component#isVisible
*/
public boolean isVisible() {
return myPeer.isVisible();
}
/**
* @return <code>true</code> if and only if showing
* @see Window#isShowing
*/
public boolean isShowing() {
return myPeer.isShowing();
}
/**
* @param width width
* @param height height
* @see JDialog#setSize
*/
public void setSize(int width, int height) {
myPeer.setSize(width, height);
}
/**
* @param title title
* @see JDialog#setTitle
*/
public void setTitle(@Nls(capitalization = Nls.Capitalization.Title) String title) {
myPeer.setTitle(title);
}
/**
* @see JDialog#isResizable
*/
public void isResizable() {
myPeer.isResizable();
}
/**
* @param resizable is resizable
* @see JDialog#setResizable
*/
public void setResizable(boolean resizable) {
myPeer.setResizable(resizable);
}
/**
* @return dialog location
* @see JDialog#getLocation
*/
@NotNull
public Point getLocation() {
return myPeer.getLocation();
}
/**
* @param p new dialog location
* @see JDialog#setLocation(Point)
*/
public void setLocation(@NotNull Point p) {
myPeer.setLocation(p);
}
/**
* @param x x
* @param y y
* @see JDialog#setLocation(int, int)
*/
public void setLocation(int x, int y) {
myPeer.setLocation(x, y);
}
public void centerRelativeToParent() {
myPeer.centerInParent();
}
/**
* Show the dialog.
*
* @throws IllegalStateException if the method is invoked not on the event dispatch thread
* @see #showAndGet()
* @see #showAndGetOk()
*/
public void show() {
invokeShow();
}
/**
* Show the modal dialog and check if it was closed with OK.
*
* @return true if the {@link #getExitCode() exit code} is {@link #OK_EXIT_CODE}.
* @throws IllegalStateException if the dialog is non-modal, or if the method is invoked not on the EDT.
* @see #show()
* @see #showAndGetOk()
*/
public boolean showAndGet() {
if (!isModal()) {
throw new IllegalStateException("The showAndGet() method is for modal dialogs only");
}
show();
return isOK();
}
/**
* You need this method ONLY for NON-MODAL dialogs. Otherwise, use {@link #show()} or {@link #showAndGet()}.
*
* @return result callback which set to "Done" on dialog close, and then its {@code getResult()} will contain {@code isOK()}
*/
@NotNull
public AsyncResult<Boolean> showAndGetOk() {
if (isModal()) {
throw new IllegalStateException("The showAndGetOk() method is for modeless dialogs only");
}
return invokeShow();
}
@NotNull
private AsyncResult<Boolean> invokeShow() {
Window window = myPeer.getWindow();
if (window instanceof JDialog && ((JDialog)window).getModalityType() == Dialog.ModalityType.DOCUMENT_MODAL) {
if (ApplicationManager.getApplication().isWriteAccessAllowed()) {
LOG.error("Project-modal dialogs should not be shown under a write action.");
}
}
final AsyncResult<Boolean> result = new AsyncResult<>();
ensureEventDispatchThread();
registerKeyboardShortcuts();
final Disposable uiParent = Disposer.get("ui");
if (uiParent != null) { // may be null if no app yet (license agreement)
Disposer.register(uiParent, myDisposable); // ensure everything is disposed on app quit
}
Disposer.register(myDisposable, new Disposable() {
@Override
public void dispose() {
result.setDone(isOK());
}
});
myPeer.show();
return result;
}
/**
* @return Location in absolute coordinates which is used when dialog has no dimension service key or no position was stored yet.
* Can return null. In that case dialog will be centered relative to its owner.
*/
@Nullable
public Point getInitialLocation() {
return myInitialLocationCallback == null ? null : myInitialLocationCallback.compute();
}
public void setInitialLocationCallback(@NotNull Computable<Point> callback) {
myInitialLocationCallback = callback;
}
private void registerKeyboardShortcuts() {
final JRootPane rootPane = getRootPane();
if (rootPane == null) return;
ActionListener cancelKeyboardAction = createCancelAction();
if (cancelKeyboardAction != null) {
rootPane
.registerKeyboardAction(cancelKeyboardAction, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionUtil.registerForEveryKeyboardShortcut(getRootPane(), cancelKeyboardAction, CommonShortcuts.getCloseActiveWindow());
}
if (ApplicationInfo.contextHelpAvailable() && !isProgressDialog()) {
ActionListener helpAction = e -> doHelpAction();
ActionUtil.registerForEveryKeyboardShortcut(getRootPane(), helpAction, CommonShortcuts.getContextHelp());
rootPane.registerKeyboardAction(helpAction, KeyStroke.getKeyStroke(KeyEvent.VK_HELP, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
}
if (myButtonMap != null) {
rootPane.registerKeyboardAction(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
focusPreviousButton();
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
rootPane.registerKeyboardAction(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
focusNextButton();
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
}
if (myYesAction != null) {
rootPane.registerKeyboardAction(myYesAction, KeyStroke.getKeyStroke(KeyEvent.VK_Y, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
}
if (myNoAction != null) {
rootPane.registerKeyboardAction(myNoAction, KeyStroke.getKeyStroke(KeyEvent.VK_N, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
}
}
/**
*
* @return null if we should ignore <Esc> for window closing
*/
@Nullable
protected ActionListener createCancelAction() {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!PopupUtil.handleEscKeyEvent()) {
doCancelAction(e);
}
}
};
}
private void focusPreviousButton() {
JButton[] myButtons = new ArrayList<>(myButtonMap.values()).toArray(new JButton[0]);
for (int i = 0; i < myButtons.length; i++) {
if (myButtons[i].hasFocus()) {
if (i == 0) {
myButtons[myButtons.length - 1].requestFocus();
return;
}
myButtons[i - 1].requestFocus();
return;
}
}
}
private void focusNextButton() {
JButton[] myButtons = new ArrayList<>(myButtonMap.values()).toArray(new JButton[0]);
for (int i = 0; i < myButtons.length; i++) {
if (myButtons[i].hasFocus()) {
if (i == myButtons.length - 1) {
myButtons[0].requestFocus();
return;
}
myButtons[i + 1].requestFocus();
return;
}
}
}
public long getTypeAheadTimeoutMs() {
return 0L;
}
public boolean isToDispatchTypeAhead() {
return isOK();
}
public static boolean isMultipleModalDialogs() {
final Component c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
if (c != null) {
final DialogWrapper wrapper = findInstance(c);
return wrapper != null && wrapper.getPeer().getCurrentModalEntities().length > 1;
}
return false;
}
/**
* Base class for dialog wrapper actions that need to ensure that only
* one action for the dialog is running.
*/
protected abstract class DialogWrapperAction extends AbstractAction {
/**
* The constructor
*
* @param name the action name (see {@link Action#NAME})
*/
protected DialogWrapperAction(@NotNull String name) {
putValue(NAME, name);
}
/**
* {@inheritDoc}
*/
@Override
public void actionPerformed(ActionEvent e) {
if (myClosed) return;
if (myPerformAction) return;
try {
myPerformAction = true;
doAction(e);
}
finally {
myPerformAction = false;
}
}
/**
* Do actual work for the action. This method is called only if no other action
* is performed in parallel (checked using {@link DialogWrapper#myPerformAction}),
* and dialog is active (checked using {@link DialogWrapper#myClosed})
*
* @param e action
*/
protected abstract void doAction(ActionEvent e);
}
protected class OkAction extends DialogWrapperAction {
protected OkAction() {
super(CommonBundle.getOkButtonText());
putValue(DEFAULT_ACTION, Boolean.TRUE);
}
@Override
protected void doAction(ActionEvent e) {
ValidationInfo info = doValidate();
if (info != null) {
if (info.component != null && info.component.isVisible()) {
IdeFocusManager.getInstance(null).requestFocus(info.component, true);
}
DialogEarthquakeShaker.shake(getPeer().getWindow());
startTrackingValidation();
return;
}
doOKAction();
}
}
protected class CancelAction extends DialogWrapperAction {
private CancelAction() {
super(CommonBundle.getCancelButtonText());
}
@Override
protected void doAction(ActionEvent e) {
doCancelAction();
}
}
/**
* The action that just closes dialog with the specified exit code
* (like the default behavior of the actions "Ok" and "Cancel").
*/
protected class DialogWrapperExitAction extends DialogWrapperAction {
/**
* The exit code for the action
*/
protected final int myExitCode;
/**
* The constructor
*
* @param name the action name
* @param exitCode the exit code for dialog
*/
public DialogWrapperExitAction(String name, int exitCode) {
super(name);
myExitCode = exitCode;
}
@Override
protected void doAction(ActionEvent e) {
if (isEnabled()) {
close(myExitCode);
}
}
}
private class HelpAction extends AbstractAction {
private HelpAction() {
putValue(NAME, CommonBundle.getHelpButtonText());
}
@Override
public void actionPerformed(ActionEvent e) {
doHelpAction();
}
}
private Dimension myActualSize = null;
private String myLastErrorText = null;
protected void setErrorText(@Nullable final String text) {
if (Comparing.equal(myLastErrorText, text)) {
return;
}
myLastErrorText = text;
myErrorTextAlarm.cancelAllRequests();
myErrorTextAlarm.addRequest(() -> {
final String text1 = myLastErrorText;
if (myActualSize == null && !myErrorText.isVisible()) {
myActualSize = getSize();
}
myErrorText.setError(text1);
}, 300, null);
}
@Nullable
public static DialogWrapper findInstance(Component c) {
while (c != null) {
if (c instanceof DialogWrapperDialog) {
return ((DialogWrapperDialog)c).getDialogWrapper();
}
c = c.getParent();
}
return null;
}
@Nullable
public static DialogWrapper findInstanceFromFocus() {
return findInstance(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner());
}
private void resizeWithAnimation(@NotNull final Dimension size) {
//todo[kb]: fix this PITA
myResizeInProgress = true;
if (!Registry.is("enable.animation.on.dialogs")) {
setSize(size.width, size.height);
myResizeInProgress = false;
return;
}
new Thread("DialogWrapper resizer") {
int time = 200;
int steps = 7;
@Override
public void run() {
int step = 0;
final Dimension cur = getSize();
int h = (size.height - cur.height) / steps;
int w = (size.width - cur.width) / steps;
while (step++ < steps) {
setSize(cur.width + w * step, cur.height + h * step);
TimeoutUtil.sleep(time / steps);
}
setSize(size.width, size.height);
//repaint();
if (myErrorText.shouldBeVisible()) {
myErrorText.setVisible(true);
}
myResizeInProgress = false;
}
}.start();
}
private static class ErrorText extends JPanel {
private final JLabel myLabel = new JLabel();
private String myText;
private ErrorText(int horizontalAlignment) {
setLayout(new BorderLayout());
myLabel.setIcon(AllIcons.Actions.Lightning);
myLabel.setBorder(JBUI.Borders.empty(4, 10, 0, 2));
myLabel.setHorizontalAlignment(horizontalAlignment);
JBScrollPane pane =
new JBScrollPane(myLabel, ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
pane.setBorder(JBUI.Borders.empty());
pane.setBackground(null);
pane.getViewport().setBackground(null);
pane.setOpaque(false);
add(pane, BorderLayout.CENTER);
}
public void setError(String text) {
myText = text;
myLabel.setBounds(0, 0, 0, 0);
setVisible(text != null);
myLabel.setText(text != null
? "<html><font color='#" + ColorUtil.toHex(JBColor.RED) + "'><left>" + text + "</left></b></font></html>"
: "");
}
public boolean shouldBeVisible() {
return !StringUtil.isEmpty(myText);
}
public boolean isTextSet(@Nullable String text) {
return StringUtil.equals(text, myText);
}
}
@NotNull
public final DialogWrapperPeer getPeer() {
return myPeer;
}
/**
* Ensure that dialog is used from even dispatch thread.
*
* @throws IllegalStateException if the dialog is invoked not on the event dispatch thread
*/
private static void ensureEventDispatchThread() {
if (!EventQueue.isDispatchThread()) {
throw new IllegalStateException("The DialogWrapper can only be used in event dispatch thread. Current thread: "+Thread.currentThread());
}
}
@NotNull
public final Disposable getDisposable() {
return myDisposable;
}
/**
* @see Adapter
*/
public interface DoNotAskOption {
abstract class Adapter implements DoNotAskOption {
/**
* Save the state of the checkbox in the settings, or perform some other related action.
* This method is called right after the dialog is {@link #close(int) closed}.
* <br/>
* Note that this method won't be called in the case when the dialog is closed by {@link #CANCEL_EXIT_CODE Cancel}
* if {@link #shouldSaveOptionsOnCancel() saving the choice on cancel is disabled} (which is by default).
*
* @param isSelected true if user selected "don't show again".
* @param exitCode the {@link #getExitCode() exit code} of the dialog.
* @see #shouldSaveOptionsOnCancel()
*/
public abstract void rememberChoice(boolean isSelected, int exitCode);
/**
* Tells whether the checkbox should be selected by default or not.
*
* @return true if the checkbox should be selected by default.
*/
public boolean isSelectedByDefault() {
return false;
}
@Override
public boolean shouldSaveOptionsOnCancel() {
return false;
}
@NotNull
@Override
public String getDoNotShowMessage() {
return CommonBundle.message("dialog.options.do.not.ask");
}
@Override
public final boolean isToBeShown() {
return !isSelectedByDefault();
}
@Override
public final void setToBeShown(boolean toBeShown, int exitCode) {
rememberChoice(!toBeShown, exitCode);
}
@Override
public final boolean canBeHidden() {
return true;
}
}
/**
* @return default selection state of checkbox (false -> checkbox selected)
*/
boolean isToBeShown();
/**
* @param toBeShown - if dialog should be shown next time (checkbox selected -> false)
* @param exitCode of corresponding DialogWrapper
*/
void setToBeShown(boolean toBeShown, int exitCode);
/**
* @return true if checkbox should be shown
*/
boolean canBeHidden();
boolean shouldSaveOptionsOnCancel();
@NotNull
String getDoNotShowMessage();
}
@NotNull
private ErrorPaintingType getErrorPaintingType() {
return ErrorPaintingType.SIGN;
}
private class ErrorPainter extends AbstractPainter {
private ValidationInfo myInfo;
@Override
public void executePaint(Component component, Graphics2D g) {
if (myInfo != null && myInfo.component != null) {
final JComponent comp = myInfo.component;
final int w = comp.getWidth();
final int h = comp.getHeight();
Point p;
switch (getErrorPaintingType()) {
case DOT:
p = SwingUtilities.convertPoint(comp, 2, h / 2, component);
AllIcons.Ide.ErrorPoint.paintIcon(component, g, p.x, p.y);
break;
case SIGN:
p = SwingUtilities.convertPoint(comp, w, 0, component);
AllIcons.General.Error.paintIcon(component, g, p.x - 8, p.y - 8);
break;
case LINE:
p = SwingUtilities.convertPoint(comp, 0, h, component);
final GraphicsConfig config = new GraphicsConfig(g);
g.setColor(new Color(255, 0, 0, 100));
g.fillRoundRect(p.x, p.y - 2, w, 4, 2, 2);
config.restore();
break;
}
}
}
@Override
public boolean needsRepaint() {
return true;
}
private void setValidationInfo(@Nullable ValidationInfo info) {
myInfo = info;
}
}
private enum ErrorPaintingType {DOT, SIGN, LINE}
public enum DialogStyle {NO_STYLE, COMPACT}
}
| platform/platform-api/src/com/intellij/openapi/ui/DialogWrapper.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.ui;
import com.intellij.CommonBundle;
import com.intellij.icons.AllIcons;
import com.intellij.ide.ui.UISettings;
import com.intellij.idea.ActionsBundle;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.MnemonicHelper;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionUtil;
import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.help.HelpManager;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.util.PopupUtil;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.IdeGlassPaneUtil;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.JBColor;
import com.intellij.ui.UIBundle;
import com.intellij.ui.border.CustomLineBorder;
import com.intellij.ui.components.JBOptionButton;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.panels.NonOpaquePanel;
import com.intellij.util.Alarm;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IconUtil;
import com.intellij.util.TimeoutUtil;
import com.intellij.util.ui.DialogUtil;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.intellij.lang.annotations.MagicConstant;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.UIResource;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
/**
* The standard base class for modal dialog boxes. The dialog wrapper could be used only on event dispatch thread.
* In case when the dialog must be created from other threads use
* {@link EventQueue#invokeLater(Runnable)} or {@link EventQueue#invokeAndWait(Runnable)}.
* <p/>
* See also http://confluence.jetbrains.net/display/IDEADEV/IntelliJ+IDEA+DialogWrapper.
*/
@SuppressWarnings({"SSBasedInspection", "MethodMayBeStatic"})
public abstract class DialogWrapper {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.ui.DialogWrapper");
public enum IdeModalityType {
IDE,
PROJECT,
MODELESS;
@NotNull
public Dialog.ModalityType toAwtModality() {
switch (this) {
case IDE:
return Dialog.ModalityType.APPLICATION_MODAL;
case PROJECT:
return Dialog.ModalityType.DOCUMENT_MODAL;
case MODELESS:
return Dialog.ModalityType.MODELESS;
}
throw new IllegalStateException(toString());
}
}
/**
* The default exit code for "OK" action.
*/
public static final int OK_EXIT_CODE = 0;
/**
* The default exit code for "Cancel" action.
*/
public static final int CANCEL_EXIT_CODE = 1;
/**
* The default exit code for "Close" action. Equal to cancel.
*/
public static final int CLOSE_EXIT_CODE = CANCEL_EXIT_CODE;
/**
* If you use your own custom exit codes you have to start them with
* this constant.
*/
public static final int NEXT_USER_EXIT_CODE = 2;
/**
* If your action returned by <code>createActions</code> method has non
* <code>null</code> value for this key, then the button that corresponds to the action will be the
* default button for the dialog. It's true if you don't change this behaviour
* of <code>createJButtonForAction(Action)</code> method.
*/
@NonNls public static final String DEFAULT_ACTION = "DefaultAction";
@NonNls public static final String FOCUSED_ACTION = "FocusedAction";
@NonNls private static final String NO_AUTORESIZE = "NoAutoResizeAndFit";
private static final KeyStroke SHOW_OPTION_KEYSTROKE = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,
InputEvent.ALT_MASK | InputEvent.SHIFT_MASK);
@NotNull
private final DialogWrapperPeer myPeer;
private int myExitCode = CANCEL_EXIT_CODE;
/**
* The shared instance of default border for dialog's content pane.
*/
public static final Border ourDefaultBorder = new EmptyBorder(UIUtil.PANEL_REGULAR_INSETS);
private float myHorizontalStretch = 1.0f;
private float myVerticalStretch = 1.0f;
/**
* Defines horizontal alignment of buttons.
*/
private int myButtonAlignment = SwingConstants.RIGHT;
private boolean myCrossClosesWindow = true;
private Insets myButtonMargins = JBUI.insets(2, 16);
protected Action myOKAction;
protected Action myCancelAction;
protected Action myHelpAction;
private final Map<Action, JButton> myButtonMap = new LinkedHashMap<>();
private boolean myClosed = false;
protected boolean myPerformAction = false;
private Action myYesAction = null;
private Action myNoAction = null;
protected JCheckBox myCheckBoxDoNotShowDialog;
@Nullable
private DoNotAskOption myDoNotAsk;
protected JComponent myPreferredFocusedComponent;
private Computable<Point> myInitialLocationCallback;
@NotNull
protected final Disposable myDisposable = new Disposable() {
@Override
public String toString() {
return DialogWrapper.this.toString();
}
@Override
public void dispose() {
DialogWrapper.this.dispose();
}
};
private final List<JBOptionButton> myOptionsButtons = new ArrayList<>();
private int myCurrentOptionsButtonIndex = -1;
private boolean myResizeInProgress = false;
private ComponentAdapter myResizeListener;
@NotNull
protected String getDoNotShowMessage() {
return CommonBundle.message("dialog.options.do.not.show");
}
public void setDoNotAskOption(@Nullable DoNotAskOption doNotAsk) {
myDoNotAsk = doNotAsk;
}
private ErrorText myErrorText;
private final Alarm myErrorTextAlarm = new Alarm();
/**
* Creates modal <code>DialogWrapper</code>. The currently active window will be the dialog's parent.
*
* @param project parent window for the dialog will be calculated based on focused window for the
* specified <code>project</code>. This parameter can be <code>null</code>. In this case parent window
* will be suggested based on current focused window.
* @param canBeParent specifies whether the dialog can be parent for other windows. This parameter is used
* by <code>WindowManager</code>.
* @throws IllegalStateException if the dialog is invoked not on the event dispatch thread
*/
protected DialogWrapper(@Nullable Project project, boolean canBeParent) {
this(project, canBeParent, IdeModalityType.IDE);
}
protected DialogWrapper(@Nullable Project project, boolean canBeParent, @NotNull IdeModalityType ideModalityType) {
this(project, null, canBeParent, ideModalityType);
}
protected DialogWrapper(@Nullable Project project, @Nullable Component parentComponent, boolean canBeParent, @NotNull IdeModalityType ideModalityType) {
myPeer = parentComponent == null ? createPeer(project, canBeParent, project == null ? IdeModalityType.IDE : ideModalityType) : createPeer(parentComponent, canBeParent);
final Window window = myPeer.getWindow();
if (window != null) {
myResizeListener = new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
if (!myResizeInProgress) {
myActualSize = myPeer.getSize();
if (myErrorText != null && myErrorText.isVisible()) {
myActualSize.height -= myErrorText.myLabel.getHeight();
}
}
}
};
window.addComponentListener(myResizeListener);
}
createDefaultActions();
}
/**
* Creates modal <code>DialogWrapper</code> that can be parent for other windows.
* The currently active window will be the dialog's parent.
*
* @param project parent window for the dialog will be calculated based on focused window for the
* specified <code>project</code>. This parameter can be <code>null</code>. In this case parent window
* will be suggested based on current focused window.
* @throws IllegalStateException if the dialog is invoked not on the event dispatch thread
* @see DialogWrapper#DialogWrapper(Project, boolean)
*/
protected DialogWrapper(@Nullable Project project) {
this(project, true);
}
/**
* Creates modal <code>DialogWrapper</code>. The currently active window will be the dialog's parent.
*
* @param canBeParent specifies whether the dialog can be parent for other windows. This parameter is used
* by <code>WindowManager</code>.
* @throws IllegalStateException if the dialog is invoked not on the event dispatch thread
*/
protected DialogWrapper(boolean canBeParent) {
this((Project)null, canBeParent);
}
/**
* Typically, we should set a parent explicitly. Use WindowManager#suggestParentWindow
* method to find out the best parent for your dialog. Exceptions are cases
* when we do not have a project to figure out which window
* is more suitable as an owner for the dialog.
* <p/>
* Instead, use {@link DialogWrapper#DialogWrapper(Project, boolean, boolean)}
*/
@Deprecated
protected DialogWrapper(boolean canBeParent, boolean applicationModalIfPossible) {
this(null, canBeParent, applicationModalIfPossible);
}
protected DialogWrapper(Project project, boolean canBeParent, boolean applicationModalIfPossible) {
ensureEventDispatchThread();
if (ApplicationManager.getApplication() != null) {
myPeer = createPeer(
project != null ? WindowManager.getInstance().suggestParentWindow(project) : WindowManager.getInstance().findVisibleFrame()
, canBeParent, applicationModalIfPossible);
}
else {
myPeer = createPeer(null, canBeParent, applicationModalIfPossible);
}
createDefaultActions();
}
/**
* @param parent parent component which is used to calculate heavy weight window ancestor.
* <code>parent</code> cannot be <code>null</code> and must be showing.
* @param canBeParent can be parent
* @throws IllegalStateException if the dialog is invoked not on the event dispatch thread
*/
protected DialogWrapper(@NotNull Component parent, boolean canBeParent) {
ensureEventDispatchThread();
myPeer = createPeer(parent, canBeParent);
createDefaultActions();
}
//validation
private final Alarm myValidationAlarm = new Alarm(getValidationThreadToUse(), myDisposable);
@NotNull
protected Alarm.ThreadToUse getValidationThreadToUse() {
return Alarm.ThreadToUse.SWING_THREAD;
}
private int myValidationDelay = 300;
private boolean myDisposed = false;
private boolean myValidationStarted = false;
private final ErrorPainter myErrorPainter = new ErrorPainter();
private boolean myErrorPainterInstalled = false;
/**
* Allows to postpone first start of validation
*
* @return <code>false</code> if start validation in <code>init()</code> method
*/
protected boolean postponeValidation() {
return true;
}
/**
* Validates user input and returns <code>null</code> if everything is fine
* or validation description with component where problem has been found.
*
* @return <code>null</code> if everything is OK or validation descriptor
*/
@Nullable
protected ValidationInfo doValidate() {
return null;
}
public void setValidationDelay(int delay) {
myValidationDelay = delay;
}
private void reportProblem(@NotNull final ValidationInfo info) {
installErrorPainter();
myErrorPainter.setValidationInfo(info);
if (!myErrorText.isTextSet(info.message)) {
SwingUtilities.invokeLater(() -> {
if (myDisposed) return;
setErrorText(info.message);
myPeer.getRootPane().getGlassPane().repaint();
getOKAction().setEnabled(false);
});
}
}
private void installErrorPainter() {
if (myErrorPainterInstalled) return;
myErrorPainterInstalled = true;
UIUtil.invokeLaterIfNeeded(() -> IdeGlassPaneUtil.installPainter(getContentPanel(), myErrorPainter, myDisposable));
}
private void clearProblems() {
myErrorPainter.setValidationInfo(null);
if (!myErrorText.isTextSet(null)) {
SwingUtilities.invokeLater(() -> {
if (myDisposed) return;
setErrorText(null);
myPeer.getRootPane().getGlassPane().repaint();
getOKAction().setEnabled(true);
});
}
}
protected void createDefaultActions() {
myOKAction = new OkAction();
myCancelAction = new CancelAction();
myHelpAction = new HelpAction();
}
public void setUndecorated(boolean undecorated) {
myPeer.setUndecorated(undecorated);
}
public final void addMouseListener(@NotNull MouseListener listener) {
myPeer.addMouseListener(listener);
}
public final void addMouseListener(@NotNull MouseMotionListener listener) {
myPeer.addMouseListener(listener);
}
public final void addKeyListener(@NotNull KeyListener listener) {
myPeer.addKeyListener(listener);
}
/**
* Closes and disposes the dialog and sets the specified exit code.
*
* @param exitCode exit code
* @param isOk is OK
* @throws IllegalStateException if the dialog is invoked not on the event dispatch thread
*/
public final void close(int exitCode, boolean isOk) {
ensureEventDispatchThread();
if (myClosed) return;
myClosed = true;
myExitCode = exitCode;
Window window = getWindow();
if (window != null && myResizeListener != null) {
window.removeComponentListener(myResizeListener);
myResizeListener = null;
}
if (isOk) {
processDoNotAskOnOk(exitCode);
}
else {
processDoNotAskOnCancel();
}
Disposer.dispose(myDisposable);
}
public final void close(int exitCode) {
close(exitCode, exitCode != CANCEL_EXIT_CODE);
}
/**
* Creates border for dialog's content pane. By default content
* pane has has empty border with <code>(8,12,8,12)</code> insets. Subclasses can
* return <code>null</code> for no border.
*
* @return content pane border
*/
@Nullable
protected Border createContentPaneBorder() {
if (getStyle() == DialogStyle.COMPACT) {
return JBUI.Borders.empty();
}
return ourDefaultBorder;
}
protected static boolean isMoveHelpButtonLeft() {
return UIUtil.isUnderAquaBasedLookAndFeel() || (SystemInfo.isWindows && Registry.is("ide.intellij.laf.win10.ui"));
}
/**
* Creates panel located at the south of the content pane. By default that
* panel contains dialog's buttons. This default implementation uses <code>createActions()</code>
* and <code>createJButtonForAction(Action)</code> methods to construct the panel.
*
* @return south panel
*/
protected JComponent createSouthPanel() {
Action[] actions = filter(createActions());
Action[] leftSideActions = createLeftSideActions();
Map<Action, JButton> buttonMap = new LinkedHashMap<>();
boolean hasHelpToMoveToLeftSide = false;
if (isMoveHelpButtonLeft() && Arrays.asList(actions).contains(getHelpAction())) {
hasHelpToMoveToLeftSide = true;
actions = ArrayUtil.remove(actions, getHelpAction());
} else if (Registry.is("ide.remove.help.button.from.dialogs")) {
actions = ArrayUtil.remove(actions, getHelpAction());
}
if (SystemInfo.isMac) {
for (Action action : actions) {
if (action instanceof MacOtherAction) {
leftSideActions = ArrayUtil.append(leftSideActions, action);
actions = ArrayUtil.remove(actions, action);
break;
}
}
}
else if (UIUtil.isUnderGTKLookAndFeel() && Arrays.asList(actions).contains(getHelpAction())) {
leftSideActions = ArrayUtil.append(leftSideActions, getHelpAction());
actions = ArrayUtil.remove(actions, getHelpAction());
}
JPanel panel = new JPanel(new BorderLayout()) {
@Override
public Color getBackground() {
final Color bg = UIManager.getColor("DialogWrapper.southPanelBackground");
if (getStyle() == DialogStyle.COMPACT && bg != null) {
return bg;
}
return super.getBackground();
}
};
final JPanel lrButtonsPanel = new NonOpaquePanel(new GridBagLayout());
//noinspection UseDPIAwareInsets
final Insets insets = SystemInfo.isMacOSLeopard ? UIUtil.isUnderIntelliJLaF() ? JBUI.insets(0, 8) : JBUI.emptyInsets() : new Insets(8, 0, 0, 0); //don't wrap to JBInsets
if (actions.length > 0 || leftSideActions.length > 0) {
int gridX = 0;
if (leftSideActions.length > 0) {
JPanel buttonsPanel = createButtons(leftSideActions, buttonMap);
if (actions.length > 0) {
buttonsPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 20)); // leave some space between button groups
}
lrButtonsPanel.add(buttonsPanel,
new GridBagConstraints(gridX++, 0, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, insets, 0,
0));
}
lrButtonsPanel.add(Box.createHorizontalGlue(), // left strut
new GridBagConstraints(gridX++, 0, 1, 1, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, insets, 0,
0));
if (actions.length > 0) {
if (SystemInfo.isMac) {
// move ok action to the right
int okNdx = ArrayUtil.indexOf(actions, getOKAction());
if (okNdx >= 0 && okNdx != actions.length - 1) {
actions = ArrayUtil.append(ArrayUtil.remove(actions, getOKAction()), getOKAction());
}
// move cancel action to the left
int cancelNdx = ArrayUtil.indexOf(actions, getCancelAction());
if (cancelNdx > 0) {
actions = ArrayUtil.mergeArrays(new Action[]{getCancelAction()}, ArrayUtil.remove(actions, getCancelAction()));
}
/*if (!hasFocusedAction(actions)) {
int ndx = ArrayUtil.find(actions, getCancelAction());
if (ndx >= 0) {
actions[ndx].putValue(FOCUSED_ACTION, Boolean.TRUE);
}
}*/
}
JPanel buttonsPanel = createButtons(actions, buttonMap);
if (shouldAddErrorNearButtons()) {
lrButtonsPanel.add(myErrorText, new GridBagConstraints(gridX++, 0, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE,
insets, 0, 0));
lrButtonsPanel.add(Box.createHorizontalStrut(10), new GridBagConstraints(gridX++, 0, 1, 1, 0, 0, GridBagConstraints.CENTER,
GridBagConstraints.NONE, insets, 0, 0));
}
lrButtonsPanel.add(buttonsPanel,
new GridBagConstraints(gridX++, 0, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, insets, 0,
0));
}
if (SwingConstants.CENTER == myButtonAlignment) {
lrButtonsPanel.add(Box.createHorizontalGlue(), // right strut
new GridBagConstraints(gridX, 0, 1, 1, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, insets, 0,
0));
}
myButtonMap.clear();
myButtonMap.putAll(buttonMap);
}
if (hasHelpToMoveToLeftSide) {
if (!(SystemInfo.isWindows && UIUtil.isUnderIntelliJLaF() && Registry.is("ide.intellij.laf.win10.ui"))) {
JButton helpButton = createHelpButton(insets);
panel.add(helpButton, BorderLayout.WEST);
}
}
panel.add(lrButtonsPanel, BorderLayout.CENTER);
final DoNotAskOption askOption = myDoNotAsk;
if (askOption != null) {
myCheckBoxDoNotShowDialog = new JCheckBox(askOption.getDoNotShowMessage());
JComponent southPanel = panel;
if (!askOption.canBeHidden()) {
return southPanel;
}
final JPanel withCB = addDoNotShowCheckBox(southPanel, myCheckBoxDoNotShowDialog);
myCheckBoxDoNotShowDialog.setSelected(!askOption.isToBeShown());
DialogUtil.registerMnemonic(myCheckBoxDoNotShowDialog, '&');
panel = withCB;
}
if (getStyle() == DialogStyle.COMPACT) {
final Color color = UIManager.getColor("DialogWrapper.southPanelDivider");
Border line = new CustomLineBorder(color != null ? color : OnePixelDivider.BACKGROUND, 1, 0, 0, 0);
panel.setBorder(new CompoundBorder(line, JBUI.Borders.empty(8, 12)));
} else {
panel.setBorder(JBUI.Borders.emptyTop(8));
}
return panel;
}
@NotNull
protected JButton createHelpButton(Insets insets) {
final JButton helpButton;
if ((SystemInfo.isWindows && UIUtil.isUnderIntelliJLaF() && Registry.is("ide.intellij.laf.win10.ui"))) {
helpButton = new JButton(getHelpAction()) {
@Override
public void paint(Graphics g) {
IconUtil.paintInCenterOf(this, g, AllIcons.Windows.WinHelp);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(AllIcons.Windows.WinHelp.getIconWidth(), AllIcons.Windows.WinHelp.getIconHeight());
}
};
helpButton.setOpaque(false);
} else {
helpButton = new JButton(getHelpAction());
}
helpButton.putClientProperty("JButton.buttonType", "help");
helpButton.setText("");
helpButton.setMargin(insets);
helpButton.setToolTipText(ActionsBundle.actionDescription("HelpTopics"));
return helpButton;
}
protected boolean shouldAddErrorNearButtons() {
return false;
}
@NotNull
protected DialogStyle getStyle() {
return DialogStyle.NO_STYLE;
}
@NotNull
private Action[] filter(@NotNull Action[] actions) {
ArrayList<Action> answer = new ArrayList<>();
for (Action action : actions) {
if (action != null && (ApplicationInfo.contextHelpAvailable() || action != getHelpAction())) {
answer.add(action);
}
}
return answer.toArray(new Action[answer.size()]);
}
protected boolean toBeShown() {
return !myCheckBoxDoNotShowDialog.isSelected();
}
public boolean isTypeAheadEnabled() {
return false;
}
@NotNull
public static JPanel addDoNotShowCheckBox(@NotNull JComponent southPanel, @NotNull JCheckBox checkBox) {
final JPanel panel = new JPanel(new BorderLayout());
JPanel wrapper = new JPanel(new GridBagLayout());
wrapper.add(checkBox);
panel.add(wrapper, BorderLayout.WEST);
panel.add(southPanel, BorderLayout.EAST);
checkBox.setBorder(JBUI.Borders.emptyRight(20));
if (SystemInfo.isMac || (SystemInfo.isWindows && Registry.is("ide.intellij.laf.win10.ui"))) {
JButton helpButton = null;
for (JButton button : UIUtil.findComponentsOfType(southPanel, JButton.class)) {
if ("help".equals(button.getClientProperty("JButton.buttonType"))) {
helpButton = button;
break;
}
}
if (helpButton != null) {
return JBUI.Panels.simplePanel(panel).addToLeft(helpButton);
}
}
return panel;
}
private boolean hasFocusedAction(@NotNull Action[] actions) {
for (Action action : actions) {
if (action.getValue(FOCUSED_ACTION) != null && (Boolean)action.getValue(FOCUSED_ACTION)) {
return true;
}
}
return false;
}
@NotNull
private JPanel createButtons(@NotNull Action[] actions, @NotNull Map<Action, JButton> buttons) {
if (!UISettings.getShadowInstance().ALLOW_MERGE_BUTTONS) {
final List<Action> actionList = new ArrayList<>();
for (Action action : actions) {
actionList.add(action);
if (action instanceof OptionAction) {
final Action[] options = ((OptionAction)action).getOptions();
actionList.addAll(Arrays.asList(options));
}
}
if (actionList.size() != actions.length) {
actions = actionList.toArray(actionList.toArray(new Action[actionList.size()]));
}
}
JPanel buttonsPanel = new NonOpaquePanel(new GridLayout(1, actions.length, SystemInfo.isMacOSLeopard ? UIUtil.isUnderIntelliJLaF() ? 8 : 0 : 5, 0));
for (final Action action : actions) {
JButton button = createJButtonForAction(action);
final Object value = action.getValue(Action.MNEMONIC_KEY);
if (value instanceof Integer) {
final int mnemonic = ((Integer)value).intValue();
final Object name = action.getValue(Action.NAME);
if (mnemonic == 'Y' && "Yes".equals(name)) {
myYesAction = action;
}
else if (mnemonic == 'N' && "No".equals(name)) {
myNoAction = action;
}
button.setMnemonic(mnemonic);
}
if (action.getValue(FOCUSED_ACTION) != null) {
myPreferredFocusedComponent = button;
}
buttons.put(action, button);
buttonsPanel.add(button);
}
return buttonsPanel;
}
/**
*
* @param action should be registered to find corresponding JButton
* @return button for specified action or null if it's not found
*/
@Nullable
protected JButton getButton(@NotNull Action action) {
return myButtonMap.get(action);
}
/**
* Creates <code>JButton</code> for the specified action. If the button has not <code>null</code>
* value for <code>DialogWrapper.DEFAULT_ACTION</code> key then the created button will be the
* default one for the dialog.
*
* @param action action for the button
* @return button with action specified
* @see DialogWrapper#DEFAULT_ACTION
*/
protected JButton createJButtonForAction(Action action) {
JButton button;
if (action instanceof OptionAction && UISettings.getShadowInstance().ALLOW_MERGE_BUTTONS) {
final Action[] options = ((OptionAction)action).getOptions();
button = new JBOptionButton(action, options);
final JBOptionButton eachOptionsButton = (JBOptionButton)button;
eachOptionsButton.setOkToProcessDefaultMnemonics(false);
eachOptionsButton.setOptionTooltipText(
"Press " + KeymapUtil.getKeystrokeText(SHOW_OPTION_KEYSTROKE) + " to expand or use a mnemonic of a contained action");
myOptionsButtons.add(eachOptionsButton);
final Set<JBOptionButton.OptionInfo> infos = eachOptionsButton.getOptionInfos();
for (final JBOptionButton.OptionInfo eachInfo : infos) {
if (eachInfo.getMnemonic() >= 0) {
final char mnemonic = (char)eachInfo.getMnemonic();
JRootPane rootPane = getPeer().getRootPane();
if (rootPane != null) {
new DumbAwareAction() {
@Override
public void actionPerformed(AnActionEvent e) {
final JBOptionButton buttonToActivate = eachInfo.getButton();
buttonToActivate.showPopup(eachInfo.getAction(), true);
}
}.registerCustomShortcutSet(MnemonicHelper.createShortcut(mnemonic), rootPane, myDisposable);
}
}
}
}
else {
button = new JButton(action);
}
String text = button.getText();
if (SystemInfo.isMac) {
button.putClientProperty("JButton.buttonType", "text");
}
if (text != null) {
int mnemonic = 0;
StringBuilder plainText = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if (ch == '_' || ch == '&') {
i++;
if (i >= text.length()) {
break;
}
ch = text.charAt(i);
if (ch != '_' && ch != '&') {
// Mnemonic is case insensitive.
int vk = ch;
if (vk >= 'a' && vk <= 'z') {
vk -= 'a' - 'A';
}
mnemonic = vk;
}
}
plainText.append(ch);
}
button.setText(plainText.toString());
final Object name = action.getValue(Action.NAME);
if (mnemonic == KeyEvent.VK_Y && "Yes".equals(name)) {
myYesAction = action;
}
else if (mnemonic == KeyEvent.VK_N && "No".equals(name)) {
myNoAction = action;
}
button.setMnemonic(mnemonic);
}
setMargin(button);
if (action.getValue(DEFAULT_ACTION) != null) {
if (!myPeer.isHeadless()) {
getRootPane().setDefaultButton(button);
}
}
return button;
}
private void setMargin(@NotNull JButton button) {
// Aqua LnF does a good job of setting proper margin between buttons. Setting them specifically causes them be 'square' style instead of
// 'rounded', which is expected by apple users.
if (!SystemInfo.isMac) {
if (myButtonMargins == null) {
return;
}
button.setMargin(myButtonMargins);
}
}
@NotNull
protected DialogWrapperPeer createPeer(@NotNull Component parent, final boolean canBeParent) {
return DialogWrapperPeerFactory.getInstance().createPeer(this, parent, canBeParent);
}
/**
* Dialogs with no parents are discouraged.
* Instead, use e.g. {@link DialogWrapper#createPeer(Window, boolean, boolean)}
*/
@Deprecated
@NotNull
protected DialogWrapperPeer createPeer(boolean canBeParent, boolean applicationModalIfPossible) {
return createPeer(null, canBeParent, applicationModalIfPossible);
}
@NotNull
protected DialogWrapperPeer createPeer(final Window owner, final boolean canBeParent, final IdeModalityType ideModalityType) {
return DialogWrapperPeerFactory.getInstance().createPeer(this, owner, canBeParent, ideModalityType);
}
@Deprecated
@NotNull
protected DialogWrapperPeer createPeer(final Window owner, final boolean canBeParent, final boolean applicationModalIfPossible) {
return DialogWrapperPeerFactory.getInstance()
.createPeer(this, owner, canBeParent, applicationModalIfPossible ? IdeModalityType.IDE : IdeModalityType.PROJECT);
}
@NotNull
protected DialogWrapperPeer createPeer(@Nullable final Project project,
final boolean canBeParent,
@NotNull IdeModalityType ideModalityType) {
return DialogWrapperPeerFactory.getInstance().createPeer(this, project, canBeParent, ideModalityType);
}
@NotNull
protected DialogWrapperPeer createPeer(@Nullable final Project project, final boolean canBeParent) {
return DialogWrapperPeerFactory.getInstance().createPeer(this, project, canBeParent);
}
@Nullable
protected JComponent createTitlePane() {
return null;
}
/**
* Factory method. It creates the panel located at the
* north of the dialog's content pane. The implementation can return <code>null</code>
* value. In this case there will be no input panel.
*
* @return north panel
*/
@Nullable
protected JComponent createNorthPanel() {
return null;
}
/**
* Factory method. It creates panel with dialog options. Options panel is located at the
* center of the dialog's content pane. The implementation can return <code>null</code>
* value. In this case there will be no options panel.
*
* @return center panel
*/
@Nullable
protected abstract JComponent createCenterPanel();
/**
* @see Window#toFront()
*/
public void toFront() {
myPeer.toFront();
}
/**
* @see Window#toBack()
*/
public void toBack() {
myPeer.toBack();
}
protected boolean setAutoAdjustable(boolean autoAdjustable) {
JRootPane rootPane = getRootPane();
if (rootPane == null) return false;
rootPane.putClientProperty(NO_AUTORESIZE, autoAdjustable ? null : Boolean.TRUE);
return true;
}
//true by default
public boolean isAutoAdjustable() {
JRootPane rootPane = getRootPane();
return rootPane == null || rootPane.getClientProperty(NO_AUTORESIZE) == null;
}
/**
* Dispose the wrapped and releases all resources allocated be the wrapper to help
* more efficient garbage collection. You should never invoke this method twice or
* invoke any method of the wrapper after invocation of <code>dispose</code>.
*
* @throws IllegalStateException if the dialog is disposed not on the event dispatch thread
*/
protected void dispose() {
ensureEventDispatchThread();
myErrorTextAlarm.cancelAllRequests();
myValidationAlarm.cancelAllRequests();
myDisposed = true;
if (myButtonMap != null) {
for (JButton button : myButtonMap.values()) {
button.setAction(null); // avoid memory leak via KeyboardManager
}
myButtonMap.clear();
}
final JRootPane rootPane = getRootPane();
// if rootPane = null, dialog has already been disposed
if (rootPane != null) {
unregisterKeyboardActions(rootPane);
if (myActualSize != null && isAutoAdjustable()) {
setSize(myActualSize.width, myActualSize.height);
}
myPeer.dispose();
}
}
public static void unregisterKeyboardActions(final JRootPane rootPane) {
for (JComponent eachComp : UIUtil.uiTraverser(rootPane).traverse().filter(JComponent.class)) {
ActionMap actionMap = eachComp.getActionMap();
KeyStroke[] strokes = eachComp.getRegisteredKeyStrokes();
for (KeyStroke eachStroke : strokes) {
boolean remove = true;
if (actionMap != null) {
for (int i : new int[]{JComponent.WHEN_FOCUSED, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, JComponent.WHEN_IN_FOCUSED_WINDOW}) {
final InputMap inputMap = eachComp.getInputMap(i);
final Object key = inputMap.get(eachStroke);
if (key != null) {
final Action action = actionMap.get(key);
if (action instanceof UIResource) remove = false;
}
}
}
if (remove) eachComp.unregisterKeyboardAction(eachStroke);
}
}
}
/**
* This method is invoked by default implementation of "Cancel" action. It just closes dialog
* with <code>CANCEL_EXIT_CODE</code>. This is convenient place to override functionality of "Cancel" action.
* Note that the method does nothing if "Cancel" action isn't enabled.
*/
public void doCancelAction() {
if (getCancelAction().isEnabled()) {
close(CANCEL_EXIT_CODE);
}
}
private void processDoNotAskOnCancel() {
if (myDoNotAsk != null) {
if (myDoNotAsk.shouldSaveOptionsOnCancel() && myDoNotAsk.canBeHidden()) {
myDoNotAsk.setToBeShown(toBeShown(), CANCEL_EXIT_CODE);
}
}
}
/**
* You can use this method if you want to know by which event this actions got triggered. It is called only if
* the cancel action was triggered by some input event, <code>doCancelAction</code> is called otherwise.
*
* @param source AWT event
* @see #doCancelAction
*/
public void doCancelAction(AWTEvent source) {
doCancelAction();
}
/**
* Programmatically perform a "click" of default dialog's button. The method does
* nothing if the dialog has no default button.
*/
public void clickDefaultButton() {
JButton button = getRootPane().getDefaultButton();
if (button != null) {
button.doClick();
}
}
/**
* This method is invoked by default implementation of "OK" action. It just closes dialog
* with <code>OK_EXIT_CODE</code>. This is convenient place to override functionality of "OK" action.
* Note that the method does nothing if "OK" action isn't enabled.
*/
protected void doOKAction() {
if (getOKAction().isEnabled()) {
close(OK_EXIT_CODE);
}
}
protected void processDoNotAskOnOk(int exitCode) {
if (myDoNotAsk != null) {
if (myDoNotAsk.canBeHidden()) {
myDoNotAsk.setToBeShown(toBeShown(), exitCode);
}
}
}
/**
* @return whether the native window cross button closes the window or not.
* <code>true</code> means that cross performs hide or dispose of the dialog.
*/
public boolean shouldCloseOnCross() {
return myCrossClosesWindow;
}
/**
* Creates actions for dialog.
* <p/>
* By default "OK" and "Cancel" actions are returned. The "Help" action is automatically added if
* {@link #getHelpId()} returns non-null value.
* <p/>
* Each action is represented by <code>JButton</code> created by {@link #createJButtonForAction(Action)}.
* These buttons are then placed into {@link #createSouthPanel() south panel} of dialog.
*
* @return dialog actions
* @see #createSouthPanel
* @see #createJButtonForAction
*/
@NotNull
protected Action[] createActions() {
if (getHelpId() == null) {
if (SystemInfo.isMac) {
return new Action[]{getCancelAction(), getOKAction()};
}
return new Action[]{getOKAction(), getCancelAction()};
}
else {
if (SystemInfo.isMac) {
return new Action[]{getHelpAction(), getCancelAction(), getOKAction()};
}
return new Action[]{getOKAction(), getCancelAction(), getHelpAction()};
}
}
@NotNull
protected Action[] createLeftSideActions() {
return new Action[0];
}
/**
* @return default implementation of "OK" action. This action just invokes
* <code>doOKAction()</code> method.
* @see #doOKAction
*/
@NotNull
protected Action getOKAction() {
return myOKAction;
}
/**
* @return default implementation of "Cancel" action. This action just invokes
* <code>doCancelAction()</code> method.
* @see #doCancelAction
*/
@NotNull
protected Action getCancelAction() {
return myCancelAction;
}
/**
* @return default implementation of "Help" action. This action just invokes
* <code>doHelpAction()</code> method.
* @see #doHelpAction
*/
@NotNull
protected Action getHelpAction() {
return myHelpAction;
}
protected boolean isProgressDialog() {
return false;
}
public final boolean isModalProgress() {
return isProgressDialog();
}
/**
* Returns content pane
*
* @return content pane
* @see JDialog#getContentPane
*/
public Container getContentPane() {
return myPeer.getContentPane();
}
/**
* @see JDialog#validate
*/
public void validate() {
myPeer.validate();
}
/**
* @see JDialog#repaint
*/
public void repaint() {
myPeer.repaint();
}
/**
* Returns key for persisting dialog dimensions.
* <p/>
* Default implementation returns <code>null</code> (no persisting).
*
* @return dimension service key
*/
@Nullable
@NonNls
protected String getDimensionServiceKey() {
return null;
}
@Nullable
public final String getDimensionKey() {
return getDimensionServiceKey();
}
public int getExitCode() {
return myExitCode;
}
/**
* @return component which should be focused when the dialog appears
* on the screen.
*/
@Nullable
public JComponent getPreferredFocusedComponent() {
return SystemInfo.isMac ? myPreferredFocusedComponent : null;
}
/**
* @return horizontal stretch of the dialog. It means that the dialog's horizontal size is
* the product of horizontal stretch by horizontal size of packed dialog. The default value
* is <code>1.0f</code>
*/
public final float getHorizontalStretch() {
return myHorizontalStretch;
}
/**
* @return vertical stretch of the dialog. It means that the dialog's vertical size is
* the product of vertical stretch by vertical size of packed dialog. The default value
* is <code>1.0f</code>
*/
public final float getVerticalStretch() {
return myVerticalStretch;
}
protected final void setHorizontalStretch(float hStretch) {
myHorizontalStretch = hStretch;
}
protected final void setVerticalStretch(float vStretch) {
myVerticalStretch = vStretch;
}
/**
* @return window owner
* @see Window#getOwner
*/
public Window getOwner() {
return myPeer.getOwner();
}
public Window getWindow() {
return myPeer.getWindow();
}
public JComponent getContentPanel() {
return (JComponent)myPeer.getContentPane();
}
/**
* @return root pane
* @see JDialog#getRootPane
*/
public JRootPane getRootPane() {
return myPeer.getRootPane();
}
/**
* @return dialog size
* @see Window#getSize
*/
public Dimension getSize() {
return myPeer.getSize();
}
/**
* @return dialog title
* @see Dialog#getTitle
*/
public String getTitle() {
return myPeer.getTitle();
}
protected void init() {
ensureEventDispatchThread();
myErrorText = new ErrorText(getErrorTextAlignment());
myErrorText.setVisible(false);
final ComponentAdapter resizeListener = new ComponentAdapter() {
private int myHeight;
@Override
public void componentResized(ComponentEvent event) {
int height = !myErrorText.isVisible() ? 0 : event.getComponent().getHeight();
if (height != myHeight) {
myHeight = height;
myResizeInProgress = true;
myErrorText.setMinimumSize(new Dimension(0, height));
JRootPane root = myPeer.getRootPane();
if (root != null) {
root.validate();
}
if (myActualSize != null && !shouldAddErrorNearButtons()) {
myPeer.setSize(myActualSize.width, myActualSize.height + height);
}
myErrorText.revalidate();
myResizeInProgress = false;
}
}
};
myErrorText.myLabel.addComponentListener(resizeListener);
Disposer.register(myDisposable, new Disposable() {
@Override
public void dispose() {
myErrorText.myLabel.removeComponentListener(resizeListener);
}
});
final JPanel root = new JPanel(createRootLayout());
//{
// @Override
// public void paint(Graphics g) {
// if (ApplicationManager.getApplication() != null) {
// UISettings.setupAntialiasing(g);
// }
// super.paint(g);
// }
//};
myPeer.setContentPane(root);
final CustomShortcutSet sc = new CustomShortcutSet(SHOW_OPTION_KEYSTROKE);
final AnAction toggleShowOptions = new DumbAwareAction() {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
expandNextOptionButton();
}
};
toggleShowOptions.registerCustomShortcutSet(sc, root, myDisposable);
JComponent titlePane = createTitlePane();
if (titlePane != null) {
JPanel northSection = new JPanel(new BorderLayout());
root.add(northSection, BorderLayout.NORTH);
northSection.add(titlePane, BorderLayout.CENTER);
}
JComponent centerSection = new JPanel(new BorderLayout());
root.add(centerSection, BorderLayout.CENTER);
root.setBorder(createContentPaneBorder());
final JComponent n = createNorthPanel();
if (n != null) {
centerSection.add(n, BorderLayout.NORTH);
}
final JComponent c = createCenterPanel();
if (c != null) {
centerSection.add(c, BorderLayout.CENTER);
}
final JPanel southSection = new JPanel(new BorderLayout());
root.add(southSection, BorderLayout.SOUTH);
southSection.add(myErrorText, BorderLayout.CENTER);
final JComponent south = createSouthPanel();
if (south != null) {
southSection.add(south, BorderLayout.SOUTH);
}
MnemonicHelper.init(root);
if (!postponeValidation()) {
startTrackingValidation();
}
if (SystemInfo.isWindows) {
installEnterHook(root, myDisposable);
}
myErrorTextAlarm.setActivationComponent(root);
}
protected int getErrorTextAlignment() {
return SwingConstants.LEADING;
}
@NotNull
LayoutManager createRootLayout() {
return new BorderLayout();
}
private static void installEnterHook(JComponent root, Disposable disposable) {
new DumbAwareAction() {
@Override
public void actionPerformed(AnActionEvent e) {
final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
if (owner instanceof JButton && owner.isEnabled()) {
((JButton)owner).doClick();
}
}
@Override
public void update(AnActionEvent e) {
final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
e.getPresentation().setEnabled(owner instanceof JButton && owner.isEnabled());
}
}.registerCustomShortcutSet(CustomShortcutSet.fromString("ENTER"), root, disposable);
}
private void expandNextOptionButton() {
if (myCurrentOptionsButtonIndex > 0) {
myOptionsButtons.get(myCurrentOptionsButtonIndex).closePopup();
myCurrentOptionsButtonIndex++;
}
else if (!myOptionsButtons.isEmpty()) {
myCurrentOptionsButtonIndex = 0;
}
if (myCurrentOptionsButtonIndex >= 0 && myCurrentOptionsButtonIndex < myOptionsButtons.size()) {
myOptionsButtons.get(myCurrentOptionsButtonIndex).showPopup(null, true);
}
}
void startTrackingValidation() {
SwingUtilities.invokeLater(() -> {
if (!myValidationStarted && !myDisposed) {
myValidationStarted = true;
initValidation();
}
});
}
protected final void initValidation() {
myValidationAlarm.cancelAllRequests();
final Runnable validateRequest = () -> {
if (myDisposed) return;
final ValidationInfo result = doValidate();
if (result == null) {
clearProblems();
}
else {
reportProblem(result);
}
if (!myDisposed) {
initValidation();
}
};
if (getValidationThreadToUse() == Alarm.ThreadToUse.SWING_THREAD) {
// null if headless
JRootPane rootPane = getRootPane();
myValidationAlarm.addRequest(validateRequest, myValidationDelay,
ApplicationManager.getApplication() == null
? null
: rootPane == null ? ModalityState.current() : ModalityState.stateForComponent(rootPane));
}
else {
myValidationAlarm.addRequest(validateRequest, myValidationDelay);
}
}
protected boolean isNorthStrictedToPreferredSize() {
return true;
}
protected boolean isCenterStrictedToPreferredSize() {
return false;
}
protected boolean isSouthStrictedToPreferredSize() {
return true;
}
@NotNull
protected JComponent createContentPane() {
return new JPanel();
}
/**
* @see Window#pack
*/
public void pack() {
myPeer.pack();
}
public Dimension getPreferredSize() {
return myPeer.getPreferredSize();
}
/**
* Sets horizontal alignment of dialog's buttons.
*
* @param alignment alignment of the buttons. Acceptable values are
* <code>SwingConstants.CENTER</code> and <code>SwingConstants.RIGHT</code>.
* The <code>SwingConstants.RIGHT</code> is the default value.
* @throws IllegalArgumentException if <code>alignment</code> isn't acceptable
*/
protected final void setButtonsAlignment(@MagicConstant(intValues = {SwingConstants.CENTER, SwingConstants.RIGHT}) int alignment) {
if (SwingConstants.CENTER != alignment && SwingConstants.RIGHT != alignment) {
throw new IllegalArgumentException("unknown alignment: " + alignment);
}
myButtonAlignment = alignment;
}
/**
* Sets margin for command buttons ("OK", "Cancel", "Help").
*
* @param insets buttons margin
*/
public final void setButtonsMargin(@Nullable Insets insets) {
myButtonMargins = insets;
}
public final void setCrossClosesWindow(boolean crossClosesWindow) {
myCrossClosesWindow = crossClosesWindow;
}
protected final void setCancelButtonIcon(Icon icon) {
// Setting icons causes buttons be 'square' style instead of
// 'rounded', which is expected by apple users.
if (!SystemInfo.isMac) {
myCancelAction.putValue(Action.SMALL_ICON, icon);
}
}
protected final void setCancelButtonText(String text) {
myCancelAction.putValue(Action.NAME, text);
}
public void setModal(boolean modal) {
myPeer.setModal(modal);
}
public boolean isModal() {
return myPeer.isModal();
}
public boolean isOKActionEnabled() {
return myOKAction.isEnabled();
}
public void setOKActionEnabled(boolean isEnabled) {
myOKAction.setEnabled(isEnabled);
}
protected final void setOKButtonIcon(Icon icon) {
// Setting icons causes buttons be 'square' style instead of
// 'rounded', which is expected by apple users.
if (!SystemInfo.isMac) {
myOKAction.putValue(Action.SMALL_ICON, icon);
}
}
/**
* @param text action without mnemonic. If mnemonic is set, presentation would be shifted by one to the left
* {@link AbstractButton#setText(String)}
* {@link AbstractButton#updateDisplayedMnemonicIndex(String, int)}
*/
protected final void setOKButtonText(String text) {
myOKAction.putValue(Action.NAME, text);
}
protected final void setOKButtonMnemonic(int c) {
myOKAction.putValue(Action.MNEMONIC_KEY, c);
}
/**
* @return the help identifier or null if no help is available.
*/
@Nullable
protected String getHelpId() {
return null;
}
/**
* Invoked by default implementation of "Help" action.
* Note that the method does nothing if "Help" action isn't enabled.
* <p/>
* The default implementation shows the help page with id returned
* by {@link #getHelpId()}. If that method returns null,
* a message box with message "no help available" is shown.
*/
protected void doHelpAction() {
if (myHelpAction.isEnabled()) {
String helpId = getHelpId();
if (helpId != null) {
HelpManager.getInstance().invokeHelp(helpId);
}
else {
Messages.showMessageDialog(getContentPane(), UIBundle.message("there.is.no.help.for.this.dialog.error.message"),
UIBundle.message("no.help.available.dialog.title"), Messages.getInformationIcon());
}
}
}
public boolean isOK() {
return getExitCode() == OK_EXIT_CODE;
}
/**
* @return <code>true</code> if and only if visible
* @see Component#isVisible
*/
public boolean isVisible() {
return myPeer.isVisible();
}
/**
* @return <code>true</code> if and only if showing
* @see Window#isShowing
*/
public boolean isShowing() {
return myPeer.isShowing();
}
/**
* @param width width
* @param height height
* @see JDialog#setSize
*/
public void setSize(int width, int height) {
myPeer.setSize(width, height);
}
/**
* @param title title
* @see JDialog#setTitle
*/
public void setTitle(@Nls(capitalization = Nls.Capitalization.Title) String title) {
myPeer.setTitle(title);
}
/**
* @see JDialog#isResizable
*/
public void isResizable() {
myPeer.isResizable();
}
/**
* @param resizable is resizable
* @see JDialog#setResizable
*/
public void setResizable(boolean resizable) {
myPeer.setResizable(resizable);
}
/**
* @return dialog location
* @see JDialog#getLocation
*/
@NotNull
public Point getLocation() {
return myPeer.getLocation();
}
/**
* @param p new dialog location
* @see JDialog#setLocation(Point)
*/
public void setLocation(@NotNull Point p) {
myPeer.setLocation(p);
}
/**
* @param x x
* @param y y
* @see JDialog#setLocation(int, int)
*/
public void setLocation(int x, int y) {
myPeer.setLocation(x, y);
}
public void centerRelativeToParent() {
myPeer.centerInParent();
}
/**
* Show the dialog.
*
* @throws IllegalStateException if the method is invoked not on the event dispatch thread
* @see #showAndGet()
* @see #showAndGetOk()
*/
public void show() {
invokeShow();
}
/**
* Show the modal dialog and check if it was closed with OK.
*
* @return true if the {@link #getExitCode() exit code} is {@link #OK_EXIT_CODE}.
* @throws IllegalStateException if the dialog is non-modal, or if the method is invoked not on the EDT.
* @see #show()
* @see #showAndGetOk()
*/
public boolean showAndGet() {
if (!isModal()) {
throw new IllegalStateException("The showAndGet() method is for modal dialogs only");
}
show();
return isOK();
}
/**
* You need this method ONLY for NON-MODAL dialogs. Otherwise, use {@link #show()} or {@link #showAndGet()}.
*
* @return result callback which set to "Done" on dialog close, and then its {@code getResult()} will contain {@code isOK()}
*/
@NotNull
public AsyncResult<Boolean> showAndGetOk() {
if (isModal()) {
throw new IllegalStateException("The showAndGetOk() method is for modeless dialogs only");
}
return invokeShow();
}
@NotNull
private AsyncResult<Boolean> invokeShow() {
Window window = myPeer.getWindow();
if (window instanceof JDialog && ((JDialog)window).getModalityType() == Dialog.ModalityType.DOCUMENT_MODAL) {
if (ApplicationManager.getApplication().isWriteAccessAllowed()) {
LOG.error("Project-modal dialogs should not be shown under a write action.");
}
}
final AsyncResult<Boolean> result = new AsyncResult<>();
ensureEventDispatchThread();
registerKeyboardShortcuts();
final Disposable uiParent = Disposer.get("ui");
if (uiParent != null) { // may be null if no app yet (license agreement)
Disposer.register(uiParent, myDisposable); // ensure everything is disposed on app quit
}
Disposer.register(myDisposable, new Disposable() {
@Override
public void dispose() {
result.setDone(isOK());
}
});
myPeer.show();
return result;
}
/**
* @return Location in absolute coordinates which is used when dialog has no dimension service key or no position was stored yet.
* Can return null. In that case dialog will be centered relative to its owner.
*/
@Nullable
public Point getInitialLocation() {
return myInitialLocationCallback == null ? null : myInitialLocationCallback.compute();
}
public void setInitialLocationCallback(@NotNull Computable<Point> callback) {
myInitialLocationCallback = callback;
}
private void registerKeyboardShortcuts() {
final JRootPane rootPane = getRootPane();
if (rootPane == null) return;
ActionListener cancelKeyboardAction = createCancelAction();
if (cancelKeyboardAction != null) {
rootPane
.registerKeyboardAction(cancelKeyboardAction, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionUtil.registerForEveryKeyboardShortcut(getRootPane(), cancelKeyboardAction, CommonShortcuts.getCloseActiveWindow());
}
if (ApplicationInfo.contextHelpAvailable() && !isProgressDialog()) {
ActionListener helpAction = e -> doHelpAction();
ActionUtil.registerForEveryKeyboardShortcut(getRootPane(), helpAction, CommonShortcuts.getContextHelp());
rootPane.registerKeyboardAction(helpAction, KeyStroke.getKeyStroke(KeyEvent.VK_HELP, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
}
if (myButtonMap != null) {
rootPane.registerKeyboardAction(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
focusPreviousButton();
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
rootPane.registerKeyboardAction(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
focusNextButton();
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
}
if (myYesAction != null) {
rootPane.registerKeyboardAction(myYesAction, KeyStroke.getKeyStroke(KeyEvent.VK_Y, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
}
if (myNoAction != null) {
rootPane.registerKeyboardAction(myNoAction, KeyStroke.getKeyStroke(KeyEvent.VK_N, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
}
}
/**
*
* @return null if we should ignore <Esc> for window closing
*/
@Nullable
protected ActionListener createCancelAction() {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!PopupUtil.handleEscKeyEvent()) {
doCancelAction(e);
}
}
};
}
private void focusPreviousButton() {
JButton[] myButtons = new ArrayList<>(myButtonMap.values()).toArray(new JButton[0]);
for (int i = 0; i < myButtons.length; i++) {
if (myButtons[i].hasFocus()) {
if (i == 0) {
myButtons[myButtons.length - 1].requestFocus();
return;
}
myButtons[i - 1].requestFocus();
return;
}
}
}
private void focusNextButton() {
JButton[] myButtons = new ArrayList<>(myButtonMap.values()).toArray(new JButton[0]);
for (int i = 0; i < myButtons.length; i++) {
if (myButtons[i].hasFocus()) {
if (i == myButtons.length - 1) {
myButtons[0].requestFocus();
return;
}
myButtons[i + 1].requestFocus();
return;
}
}
}
public long getTypeAheadTimeoutMs() {
return 0L;
}
public boolean isToDispatchTypeAhead() {
return isOK();
}
public static boolean isMultipleModalDialogs() {
final Component c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
if (c != null) {
final DialogWrapper wrapper = findInstance(c);
return wrapper != null && wrapper.getPeer().getCurrentModalEntities().length > 1;
}
return false;
}
/**
* Base class for dialog wrapper actions that need to ensure that only
* one action for the dialog is running.
*/
protected abstract class DialogWrapperAction extends AbstractAction {
/**
* The constructor
*
* @param name the action name (see {@link Action#NAME})
*/
protected DialogWrapperAction(@NotNull String name) {
putValue(NAME, name);
}
/**
* {@inheritDoc}
*/
@Override
public void actionPerformed(ActionEvent e) {
if (myClosed) return;
if (myPerformAction) return;
try {
myPerformAction = true;
doAction(e);
}
finally {
myPerformAction = false;
}
}
/**
* Do actual work for the action. This method is called only if no other action
* is performed in parallel (checked using {@link DialogWrapper#myPerformAction}),
* and dialog is active (checked using {@link DialogWrapper#myClosed})
*
* @param e action
*/
protected abstract void doAction(ActionEvent e);
}
protected class OkAction extends DialogWrapperAction {
protected OkAction() {
super(CommonBundle.getOkButtonText());
putValue(DEFAULT_ACTION, Boolean.TRUE);
}
@Override
protected void doAction(ActionEvent e) {
ValidationInfo info = doValidate();
if (info != null) {
if (info.component != null && info.component.isVisible()) {
IdeFocusManager.getInstance(null).requestFocus(info.component, true);
}
DialogEarthquakeShaker.shake(getPeer().getWindow());
startTrackingValidation();
return;
}
doOKAction();
}
}
protected class CancelAction extends DialogWrapperAction {
private CancelAction() {
super(CommonBundle.getCancelButtonText());
}
@Override
protected void doAction(ActionEvent e) {
doCancelAction();
}
}
/**
* The action that just closes dialog with the specified exit code
* (like the default behavior of the actions "Ok" and "Cancel").
*/
protected class DialogWrapperExitAction extends DialogWrapperAction {
/**
* The exit code for the action
*/
protected final int myExitCode;
/**
* The constructor
*
* @param name the action name
* @param exitCode the exit code for dialog
*/
public DialogWrapperExitAction(String name, int exitCode) {
super(name);
myExitCode = exitCode;
}
@Override
protected void doAction(ActionEvent e) {
if (isEnabled()) {
close(myExitCode);
}
}
}
private class HelpAction extends AbstractAction {
private HelpAction() {
putValue(NAME, CommonBundle.getHelpButtonText());
}
@Override
public void actionPerformed(ActionEvent e) {
doHelpAction();
}
}
private Dimension myActualSize = null;
private String myLastErrorText = null;
protected void setErrorText(@Nullable final String text) {
if (Comparing.equal(myLastErrorText, text)) {
return;
}
myLastErrorText = text;
myErrorTextAlarm.cancelAllRequests();
myErrorTextAlarm.addRequest(() -> {
final String text1 = myLastErrorText;
if (myActualSize == null && !myErrorText.isVisible()) {
myActualSize = getSize();
}
myErrorText.setError(text1);
}, 300, null);
}
@Nullable
public static DialogWrapper findInstance(Component c) {
while (c != null) {
if (c instanceof DialogWrapperDialog) {
return ((DialogWrapperDialog)c).getDialogWrapper();
}
c = c.getParent();
}
return null;
}
@Nullable
public static DialogWrapper findInstanceFromFocus() {
return findInstance(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner());
}
private void resizeWithAnimation(@NotNull final Dimension size) {
//todo[kb]: fix this PITA
myResizeInProgress = true;
if (!Registry.is("enable.animation.on.dialogs")) {
setSize(size.width, size.height);
myResizeInProgress = false;
return;
}
new Thread("DialogWrapper resizer") {
int time = 200;
int steps = 7;
@Override
public void run() {
int step = 0;
final Dimension cur = getSize();
int h = (size.height - cur.height) / steps;
int w = (size.width - cur.width) / steps;
while (step++ < steps) {
setSize(cur.width + w * step, cur.height + h * step);
TimeoutUtil.sleep(time / steps);
}
setSize(size.width, size.height);
//repaint();
if (myErrorText.shouldBeVisible()) {
myErrorText.setVisible(true);
}
myResizeInProgress = false;
}
}.start();
}
private static class ErrorText extends JPanel {
private final JLabel myLabel = new JLabel();
private String myText;
private ErrorText(int horizontalAlignment) {
setLayout(new BorderLayout());
myLabel.setIcon(AllIcons.Actions.Lightning);
myLabel.setBorder(JBUI.Borders.empty(4, 10, 0, 2));
myLabel.setHorizontalAlignment(horizontalAlignment);
JBScrollPane pane =
new JBScrollPane(myLabel, ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
pane.setBorder(JBUI.Borders.empty());
pane.setBackground(null);
pane.getViewport().setBackground(null);
pane.setOpaque(false);
add(pane, BorderLayout.CENTER);
}
public void setError(String text) {
myText = text;
myLabel.setBounds(0, 0, 0, 0);
setVisible(text != null);
myLabel.setText(text != null
? "<html><font color='#" + ColorUtil.toHex(JBColor.RED) + "'><left>" + text + "</left></b></font></html>"
: "");
}
public boolean shouldBeVisible() {
return !StringUtil.isEmpty(myText);
}
public boolean isTextSet(@Nullable String text) {
return StringUtil.equals(text, myText);
}
}
@NotNull
public final DialogWrapperPeer getPeer() {
return myPeer;
}
/**
* Ensure that dialog is used from even dispatch thread.
*
* @throws IllegalStateException if the dialog is invoked not on the event dispatch thread
*/
private static void ensureEventDispatchThread() {
if (!EventQueue.isDispatchThread()) {
throw new IllegalStateException("The DialogWrapper can only be used in event dispatch thread. Current thread: "+Thread.currentThread());
}
}
@NotNull
public final Disposable getDisposable() {
return myDisposable;
}
/**
* @see Adapter
*/
public interface DoNotAskOption {
abstract class Adapter implements DoNotAskOption {
/**
* Save the state of the checkbox in the settings, or perform some other related action.
* This method is called right after the dialog is {@link #close(int) closed}.
* <br/>
* Note that this method won't be called in the case when the dialog is closed by {@link #CANCEL_EXIT_CODE Cancel}
* if {@link #shouldSaveOptionsOnCancel() saving the choice on cancel is disabled} (which is by default).
*
* @param isSelected true if user selected "don't show again".
* @param exitCode the {@link #getExitCode() exit code} of the dialog.
* @see #shouldSaveOptionsOnCancel()
*/
public abstract void rememberChoice(boolean isSelected, int exitCode);
/**
* Tells whether the checkbox should be selected by default or not.
*
* @return true if the checkbox should be selected by default.
*/
public boolean isSelectedByDefault() {
return false;
}
@Override
public boolean shouldSaveOptionsOnCancel() {
return false;
}
@NotNull
@Override
public String getDoNotShowMessage() {
return CommonBundle.message("dialog.options.do.not.ask");
}
@Override
public final boolean isToBeShown() {
return !isSelectedByDefault();
}
@Override
public final void setToBeShown(boolean toBeShown, int exitCode) {
rememberChoice(!toBeShown, exitCode);
}
@Override
public final boolean canBeHidden() {
return true;
}
}
/**
* @return default selection state of checkbox (false -> checkbox selected)
*/
boolean isToBeShown();
/**
* @param toBeShown - if dialog should be shown next time (checkbox selected -> false)
* @param exitCode of corresponding DialogWrapper
*/
void setToBeShown(boolean toBeShown, int exitCode);
/**
* @return true if checkbox should be shown
*/
boolean canBeHidden();
boolean shouldSaveOptionsOnCancel();
@NotNull
String getDoNotShowMessage();
}
@NotNull
private ErrorPaintingType getErrorPaintingType() {
return ErrorPaintingType.SIGN;
}
private class ErrorPainter extends AbstractPainter {
private ValidationInfo myInfo;
@Override
public void executePaint(Component component, Graphics2D g) {
if (myInfo != null && myInfo.component != null) {
final JComponent comp = myInfo.component;
final int w = comp.getWidth();
final int h = comp.getHeight();
Point p;
switch (getErrorPaintingType()) {
case DOT:
p = SwingUtilities.convertPoint(comp, 2, h / 2, component);
AllIcons.Ide.ErrorPoint.paintIcon(component, g, p.x, p.y);
break;
case SIGN:
p = SwingUtilities.convertPoint(comp, w, 0, component);
AllIcons.General.Error.paintIcon(component, g, p.x - 8, p.y - 8);
break;
case LINE:
p = SwingUtilities.convertPoint(comp, 0, h, component);
final GraphicsConfig config = new GraphicsConfig(g);
g.setColor(new Color(255, 0, 0, 100));
g.fillRoundRect(p.x, p.y - 2, w, 4, 2, 2);
config.restore();
break;
}
}
}
@Override
public boolean needsRepaint() {
return true;
}
private void setValidationInfo(@Nullable ValidationInfo info) {
myInfo = info;
}
}
private enum ErrorPaintingType {DOT, SIGN, LINE}
public enum DialogStyle {NO_STYLE, COMPACT}
}
| do not show help button in dialogs if and only if there is special frame decoration
| platform/platform-api/src/com/intellij/openapi/ui/DialogWrapper.java | do not show help button in dialogs if and only if there is special frame decoration | <ide><path>latform/platform-api/src/com/intellij/openapi/ui/DialogWrapper.java
<ide> }
<ide>
<ide> protected static boolean isMoveHelpButtonLeft() {
<del> return UIUtil.isUnderAquaBasedLookAndFeel() || (SystemInfo.isWindows && Registry.is("ide.intellij.laf.win10.ui"));
<add> return UIUtil.isUnderAquaBasedLookAndFeel() || UIUtil.isUnderDarcula() || UIUtil.isUnderWin10LookAndFeel();
<ide> }
<ide>
<ide> /**
<ide> }
<ide>
<ide> if (hasHelpToMoveToLeftSide) {
<del> if (!(SystemInfo.isWindows && UIUtil.isUnderIntelliJLaF() && Registry.is("ide.intellij.laf.win10.ui"))) {
<add> if (!(SystemInfo.isWindows && (UIUtil.isUnderDarcula() || UIUtil.isUnderIntelliJLaF()) && Registry.is("ide.win.frame.decoration"))) {
<ide> JButton helpButton = createHelpButton(insets);
<ide> panel.add(helpButton, BorderLayout.WEST);
<ide> } |
|
Java | apache-2.0 | 6c69b4df02cc0c0b3fc3915d8df4d9c84dcf81ec | 0 | diegosalvi/docetproject,diegosalvi/docetproject,diennea/docetproject,diennea/docetproject,diegosalvi/docetproject,diennea/docetproject | /*
* Licensed to Diennea S.r.l. under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Diennea S.r.l. 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 docet.engine;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.MessageFormat;
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.Optional;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.map.ObjectMapper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Tag;
import org.jsoup.select.Elements;
import docet.DocetExecutionContext;
import docet.DocetPackageLocator;
import docet.DocetUtils;
import docet.SimplePackageLocator;
import docet.error.DocetDocumentSearchException;
import docet.error.DocetException;
import docet.error.DocetPackageException;
import docet.error.DocetPackageNotFoundException;
import docet.model.DocetDocument;
import docet.model.DocetPackageDescriptor;
import docet.model.PackageDescriptionResult;
import docet.model.PackageResponse;
import docet.model.PackageSearchResult;
import docet.model.SearchResponse;
import docet.model.SearchResult;
import java.net.URLEncoder;
public final class DocetManager {
private static final Logger LOGGER = Logger.getLogger(DocetManager.class.getName());
private static final String IMAGE_DOCET_EXTENSION = ".mnimg";
private static final String CSS_CLASS_DOCET_MENU = "docet-menu";
private static final String CSS_CLASS_DOCET_SUBMENU = "docet-menu-submenu";
private static final String CSS_CLASS_DOCET_MENU_HIDDEN = "docet-menu-hidden";
private static final String CSS_CLASS_DOCET_MENU_VISIBLE = "docet-menu-visible";
private static final String CSS_CLASS_DOCET_MENU_HASSUBMENU = "docet-menu-hasmenu";
private static final String CSS_CLASS_DOCET_MENU_CLOSED = "docet-menu-closed";
private static final String CSS_CLASS_DOCET_MENU_LINK = "docet-menu-link";
private static final String CSS_CLASS_DOCET_PAGE_LINK = "docet-page-link";
private static final String CSS_CLASS_DOCET_FAQ_LINK = "docet-faq-link";
private static final String CSS_CLASS_DOCET_FAQ_MAINLINK = "docet-faq-mainlink";
private static final String CSS_CLASS_DOCET_FAQ_LINK_IN_PAGE = "faq-link";
private static final String ID_DOCET_FAQ_MAIN_LINK = "docet-faq-main-link";
private static final String ID_DOCET_FAQ_MENU = "docet-faq-menu";
private static final String DOCET_HTML_ATTR_REFERENCE_LANGUAGE_NAME = "reference-language";
private final DocetConfiguration docetConf;
private final DocetPackageRuntimeManager packageRuntimeManager;
public void start() throws IOException {
this.packageRuntimeManager.start();
}
public void stop() throws InterruptedException {
this.packageRuntimeManager.stop();
}
/**
* Adopted only in DOCet standalone mode.
*
* @param docetConf
* @throws IOException
*/
public DocetManager(final DocetConfiguration docetConf) throws DocetException {
this.docetConf = docetConf;
try {
this.packageRuntimeManager = new DocetPackageRuntimeManager(new SimplePackageLocator(docetConf), docetConf);
} catch (IOException e) {
throw new DocetException(DocetException.CODE_GENERIC_ERROR, "Initializaton of package runtime manager failed", e);
}
}
public DocetManager(final DocetConfiguration docetConf, final DocetPackageLocator packageLocator) {
this.docetConf = docetConf;
this.packageRuntimeManager = new DocetPackageRuntimeManager(packageLocator, docetConf);
}
private String getPathToPackageDoc(final String packageName, final DocetExecutionContext ctx) throws DocetPackageException {
return this.packageRuntimeManager.getDocumentDirectoryForPackage(packageName, ctx).getAbsolutePath();
}
private void getImageBylangForPackage(final String imgName, final String lang, final String packageName,
final OutputStream out, final DocetExecutionContext ctx)
throws DocetException {
try {
final String basePathToPackage = this.getPathToPackageDoc(packageName, ctx);
final String pathToImg;
if (this.docetConf.isPreviewMode()) {
final String docetImgsBasePath = basePathToPackage + "/" + MessageFormat.format(this.docetConf.getPathToImages(), lang);
final Path imagePath = searchFileInBasePathByName(Paths.get(docetImgsBasePath), imgName);
if (imagePath == null) {
throw new IOException("Image " + imgName + " for language " + lang + " not found!");
} else {
pathToImg = imagePath.toString();
}
} else {
pathToImg = basePathToPackage + "/" + MessageFormat.format(this.docetConf.getPathToImages(), lang) + "/" + imgName;
}
File imgPath = new File(pathToImg);
try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(imgPath))) {
byte[] read = new byte[2048];
while (bin.available() > 0) {
bin.read(read);
out.write(read);
}
}
} catch (IOException ex) {
throw new DocetException(
DocetException.CODE_RESOURCE_NOTFOUND, "Error on loading image '" + imgName + "' package " + packageName, ex);
} catch (DocetPackageException ex) {
this.handleDocetPackageException(ex, packageName);
}
}
private void getIconForPackage(final String packageName, final OutputStream out, final DocetExecutionContext ctx)
throws DocetException {
try {
final String basePathToPackage = this.getPathToPackageDoc(packageName, ctx);
final String pathToIcon = basePathToPackage + "/icon.png";
File imgPath = new File(pathToIcon);
try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(imgPath))) {
byte[] read = new byte[2048];
while (bin.available() > 0) {
bin.read(read);
out.write(read);
}
}
} catch (IOException ex) {
throw new DocetException(
DocetException.CODE_RESOURCE_NOTFOUND, "Error on loading package icon for package " + packageName, ex);
} catch (DocetPackageException ex) {
this.handleDocetPackageException(ex, packageName);
}
}
private void handleDocetPackageException(final DocetPackageException pkgEx, final String packageid)
throws DocetException {
final DocetException res;
final String msg = pkgEx.getMessage();
if (msg.equals(DocetPackageException.MSG_ACCESS_DENIED)) {
res = new DocetException(
DocetException.CODE_PACKAGE_ACCESS_DENIED, "Access denied for package " + packageid, pkgEx);
} else {
res = new DocetException(
DocetException.CODE_PACKAGE_NOTFOUND, "Package not found " + packageid, pkgEx);
}
throw res;
}
/**
* Used to retrieve the TOC for a given language, parsing each link in the TOC so as to have params appended to it.
*
* @param packageName the name of target documentation package
*
* @param lang the language code the desired TOC refers to
*
* @param params the additional params to append to each link making up TOC
*
* @return the TOC in text format
* @throws DocetPackageNotFoundException
* @throws UnsupportedEncodingException
*
* @throws IOException in case of issues on retrieving the TOC page
*/
private String serveTableOfContentsForPackage(final String packageName, final String lang,
final Map<String, String[]> params, final DocetExecutionContext ctx)
throws DocetException {
String html = "";
try {
html = parseTocForPackage(packageName, lang, params, ctx).body().getElementsByTag("nav").first().html();
} catch (IOException ex) {
throw new DocetException(
DocetException.CODE_RESOURCE_NOTFOUND, "Error on retrieving TOC for package '" + packageName + "'", ex);
} catch (DocetPackageException ex) {
this.handleDocetPackageException(ex, packageName);
}
return DocetUtils.cleanPageText(html);
}
/**
* Retrieve a page given a page id and a reference language. Links in the page content are parsed and provided
* params appended to them.
*
* @param packageName the target documentation package
*
* @param pageId the id of the page to be served
* @param lang the reference language for this page's id
* @param faq true if the page to be served is a faq page, false in case of a "standard" documentation page
* @param params the additional params to be appended to each link in the page
*
* @return the text representation of the requested page
* @throws DocetPackageNotFoundException
*
* @throws IOException in case parsing of the page got issues
*/
private String servePageIdForLanguageForPackage(final String packageName, final String pageId, final String lang,
final boolean faq, final Map<String, String[]> params, final DocetExecutionContext ctx)
throws DocetException {
final StringBuilder html = new StringBuilder();
try {
html.append(parsePageForPackage(packageName, pageId, lang, faq, params, ctx)
.body().getElementsByTag("div").first().html());
html.append(generateFooter(lang, packageName, pageId));
} catch (IOException ex) {
throw new DocetException(DocetException.CODE_RESOURCE_NOTFOUND, "Error on retrieving page '" + pageId + "' for package '" + packageName + "'", ex);
} catch (DocetPackageException ex) {
this.handleDocetPackageException(ex, packageName);
}
return DocetUtils.cleanPageText(html.toString());
}
private Document parsePageForPackage(final String packageName, final String pageId, final String lang,
final boolean faq, final Map<String, String[]> params, final DocetExecutionContext ctx)
throws DocetPackageException, IOException {
final Document docPage = this.loadPageByIdForPackageAndLanguage(packageName, pageId, lang, faq, ctx);
final Elements imgs = docPage.getElementsByTag("img");
imgs.stream().forEach(img -> {
parseImage(packageName, img, lang, params);
});
final Elements anchors = docPage.getElementsByTag("a");
anchors.stream().filter(a -> {
final String href = a.attr("href");
return !href.startsWith("#") && !href.startsWith("http://") && !href.startsWith("https://");
}).forEach(a -> {
parseAnchorItemInPage(packageName, a, lang, params);
});
return docPage;
}
private String generateFooter(final String lang, final String packageId, final String pageId) {
String res = "";
res += "<div id='docet-debug-info' class='docet-footer'>";
res += "<span style='visibility:hidden;display:none;' id='docet-page-id'><b>Page id:</b> " + packageId + ":" + pageId + "</span>";
if (docetConf.isDebugMode()) {
res += "<br/><b>Version</b>: " + docetConf.getVersion() + " | <b>Language:</b> " + lang;
}
res += "</div>";
return res;
}
private Document loadPageByIdForPackageAndLanguage(final String packageName, final String pageId, final String lang, final boolean faq,
final DocetExecutionContext ctx) throws DocetPackageException, IOException {
final String pathToPage;
if (faq) {
pathToPage = this.getFaqPathByIdForPackageAndLanguage(packageName, pageId, lang, ctx);
} else {
pathToPage = this.getPagePathByIdForPackageAndLanguage(packageName, pageId, lang, ctx);
}
return Jsoup.parseBodyFragment(new String(DocetUtils.fastReadFile(new File(pathToPage).toPath()), "UTF-8"));
}
private String getFaqPathByIdForPackageAndLanguage(final String packageName, final String faqId, final String lang,
final DocetExecutionContext ctx) throws DocetPackageException {
final String basePath = this.getPathToPackageDoc(packageName, ctx);
final String pathToFaq = basePath + "/" + MessageFormat.format(docetConf.getPathToFaq(), lang) + "/" + faqId + ".html";
return pathToFaq;
}
private String getPagePathByIdForPackageAndLanguage(final String packageName, final String pageId, final String lang,
final DocetExecutionContext ctx)
throws DocetPackageException, IOException {
final String basePath = this.getPathToPackageDoc(packageName, ctx);
final String pathToPage;
if (this.docetConf.isPreviewMode()) {
final String docetDocsBasePath = basePath + "/" + MessageFormat.format(docetConf.getPathToPages(), lang);
final Path pagePath = searchFileInBasePathByName(Paths.get(docetDocsBasePath), pageId + ".html");
if (pagePath == null) {
throw new IOException("Page " + pageId + " for language " + lang + " not found!");
} else {
pathToPage = searchFileInBasePathByName(Paths.get(docetDocsBasePath), pageId + ".html").toString();
}
} else {
pathToPage = basePath + "/" + MessageFormat.format(docetConf.getPathToPages(), lang) + "/" + pageId + ".html";
}
return pathToPage;
}
private static Path searchFileInBasePathByName(final Path basePath, final String fileName) throws IOException {
final Holder<Path> result = new Holder<Path>();
Files.walkFileTree(basePath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
if (file.endsWith(fileName)) {
result.setValue(file);
return FileVisitResult.TERMINATE;
}
return FileVisitResult.CONTINUE;
}
});
return result.value;
}
private Document loadTocForPackage(final String packageName, final String lang, final DocetExecutionContext ctx)
throws DocetPackageException, UnsupportedEncodingException, IOException {
final String basePath = this.getPathToPackageDoc(packageName, ctx);
return Jsoup
.parseBodyFragment(new String(
DocetUtils.fastReadFile(
new File(basePath + MessageFormat.format(this.docetConf.getTocFilePath(), lang)).toPath()),
"UTF-8"), "UTF-8");
}
private Document parseTocForPackage(final String packageName, final String lang,
final Map<String, String[]> params, final DocetExecutionContext ctx)
throws UnsupportedEncodingException, DocetPackageException, IOException {
final Document docToc = loadTocForPackage(packageName, lang, ctx);
// inject default docet menu css class on main menu
docToc.select("nav > ul").addClass(CSS_CLASS_DOCET_MENU);
docToc.select("nav > ul").attr("package", packageName);
docToc.select("nav > ul").addClass(CSS_CLASS_DOCET_MENU_VISIBLE);
docToc.select("nav > ul > li").addClass(CSS_CLASS_DOCET_MENU);
if (this.docetConf.isFaqTocAtRuntime()) {
injectFaqItemsInTOC(docToc, lang);
}
final Elements anchors = docToc.getElementsByTag("a");
anchors.stream().forEach(a -> {
parseTOCItem(packageName, a, lang, params);
});
final Elements lis = docToc.getElementsByTag("li");
lis.stream().forEach(li -> {
injectClasses(li);
});
return docToc;
}
private static final String getFaqPath() {
return "<a class=\"" + CSS_CLASS_DOCET_FAQ_LINK + "\" id=\"" + ID_DOCET_FAQ_MAIN_LINK + "\" href=\"faq.html\">FAQ</a>";
}
private SearchResult convertDocetDocumentToSearchResult(final String lang, final String packageId,
final Map<String, String[]> additionalParams, final Document toc, final DocetDocument doc) {
final int docType = doc.getType();
final String pageLink;
final String pageId;
final String[] breadCrumbs;
switch (docType) {
case DocetDocument.DOCTYPE_FAQ:
pageLink = MessageFormat.format(this.docetConf.getLinkToFaqPattern(), packageId, doc.getId(), lang);
pageId = "faq_" + doc.getId() + "_" + lang;
breadCrumbs = new String[]{getFaqPath()};
break;
case DocetDocument.DOCTYPE_PAGE:
pageLink = MessageFormat.format(this.docetConf.getLinkToPagePattern(), packageId, doc.getId(), lang);
pageId = doc.getId() + "_" + lang;
breadCrumbs = createBreadcrumbsForPageFromToc(packageId, pageId, toc);
break;
default:
throw new IllegalArgumentException("Unsupported document type " + docType);
}
return SearchResult.toSearchResult(packageId, doc, pageId, appendParamsToUrl(pageLink, additionalParams), breadCrumbs);
}
private void injectFaqItemsInTOC(final Document toc, final String lang) throws IOException {
final Element faqList = toc.getElementById(ID_DOCET_FAQ_MENU);
if (faqList == null) {
return;
}
final Element faqMainLink = toc.getElementById(ID_DOCET_FAQ_MAIN_LINK);
if (faqMainLink == null) {
return;
} else {
faqMainLink.addClass(CSS_CLASS_DOCET_FAQ_MAINLINK);
}
final Holder<Integer> countFaqs = new Holder<Integer>();
countFaqs.setValue(0);
faqList.select("a").forEach(faqA -> {
faqA.addClass(CSS_CLASS_DOCET_FAQ_LINK);
countFaqs.setValue(countFaqs.getValue() + 1);
});
if (countFaqs.getValue() > 0) {
toc.select("nav > ul > li").addClass(CSS_CLASS_DOCET_MENU_HASSUBMENU);
}
}
private void injectClasses(final Element item) {
if (!item.hasClass(CSS_CLASS_DOCET_MENU)) {
item.addClass(CSS_CLASS_DOCET_SUBMENU);
}
final Elements subItems = item.getElementsByTag("ul");
subItems.stream().peek(ul -> {
ul.addClass(CSS_CLASS_DOCET_SUBMENU);
ul.addClass(CSS_CLASS_DOCET_MENU_HIDDEN);
}).count();
// add an enclosing div for each anchor within a li
final Element a = item.children().select("a").get(0);
item.prependChild(new Element(Tag.valueOf("div"), ""));
item.select("div").get(0).append(a.outerHtml());
final Element appendedA = item.select("div").get(0).select("a").get(0);
a.remove();
if (!appendedA.attr("id").equals(ID_DOCET_FAQ_MAIN_LINK) && appendedA.hasClass(CSS_CLASS_DOCET_FAQ_LINK)) {
return;
}
// if this li (item) has child then we must be confident it has a
// submenu
if (!item.children().select("ul").isEmpty()) {
item.addClass(CSS_CLASS_DOCET_MENU_HASSUBMENU);
item.select("div").get(0).addClass(CSS_CLASS_DOCET_MENU_CLOSED);
}
}
private String parsePackageIconUrl(final String packageName, final Map<String, String[]> params) {
String url = MessageFormat.format(this.docetConf.getLinkToPackageIconPattern(), packageName);
url = appendParamsToUrl(url, params);
return url;
}
private void parseImage(final String packageName, final Element item, final String lang, final Map<String, String[]> params) {
final String[] imgPathTokens = item.attr("src").split("/");
final String imgName = imgPathTokens[imgPathTokens.length - 1];
final String imgNameNormalizedExtension = imgName + IMAGE_DOCET_EXTENSION;
String href = MessageFormat.format(this.docetConf.getLinkToImagePattern(), packageName, lang, imgNameNormalizedExtension);
href = appendParamsToUrl(href, params);
item.attr("src", href);
}
private void parseTOCItem(final String packageName, final Element item, String lang, final Map<String, String[]> params) {
final String barePagename = item.attr("href").split(".html")[0];
// check if the linked document is written in another language!
final String referenceLanguage = item.attr(DOCET_HTML_ATTR_REFERENCE_LANGUAGE_NAME);
if (!referenceLanguage.isEmpty()) {
lang = referenceLanguage;
}
String href;
if (item.hasClass(CSS_CLASS_DOCET_FAQ_LINK)) {
href = MessageFormat.format(this.docetConf.getLinkToFaqPattern(), packageName, barePagename, lang);
// determine page id: if page name is samplepage_it.html
// then id will be simply samplepage_it
if (!item.attr("id").equals(ID_DOCET_FAQ_MAIN_LINK)) {
item.attr("id", "faq_" + barePagename + "_" + lang);
}
} else {
href = MessageFormat.format(this.docetConf.getLinkToPagePattern(), packageName, barePagename, lang);
// determine page id: if page name is samplepage_it.html
// then id will be simply samplepage_it
item.attr("id", barePagename + "_" + lang);
item.attr("title", item.text());
}
href = appendParamsToUrl(href, params);
item.addClass(CSS_CLASS_DOCET_MENU_LINK);
item.attr("href", href);
item.attr("package", packageName);
}
private void parseAnchorItemInPage(final String packageName, final Element item, final String lang, final Map<String, String[]> params) {
final String crossPackageId = item.attr("package");
final String[] pageNameTokens = item.attr("href").split(".html");
final String barePagename = pageNameTokens[0];
final String fragment;
if (pageNameTokens.length == 2) {
fragment = pageNameTokens[1];
} else {
fragment = "";
}
final String linkId;
String href;
final String ultimatePackageId;
if (crossPackageId.isEmpty()) {
ultimatePackageId = packageName;
} else {
ultimatePackageId = crossPackageId;
}
if (item.hasClass(CSS_CLASS_DOCET_FAQ_LINK_IN_PAGE)) {
href = MessageFormat.format(this.docetConf.getLinkToFaqPattern(), ultimatePackageId, barePagename, lang) + fragment;
linkId = "faq_" + barePagename + "_" + lang;
item.removeClass(CSS_CLASS_DOCET_FAQ_LINK_IN_PAGE);
} else {
href = MessageFormat.format(this.docetConf.getLinkToPagePattern(), ultimatePackageId, barePagename, lang) + fragment;
linkId = barePagename + "_" + lang;
}
href = appendParamsToUrl(href, params);
// determine page id: if page name is samplepage_it.html
// then id will be simply samplepage_it
item.attr("id", linkId);
item.attr("href", href);
item.attr("package", ultimatePackageId);
item.addClass(CSS_CLASS_DOCET_PAGE_LINK);
}
private String appendParamsToUrl(final String url, final Map<String, String[]> params) {
final String parsedUrl;
if (params.isEmpty()) {
parsedUrl = url;
} else {
final Holder<String> tmpUrl = new Holder<String>();
tmpUrl.setValue(url + "?");
params.entrySet().stream().filter(entry -> !entry.getKey().equals("id") && !entry.getKey().equals("lang"))
.forEach(entry -> {
try {
tmpUrl.setValue(tmpUrl.getValue() + entry.getKey()
+ "=" + URLEncoder.encode(entry.getValue()[0], "utf-8") + "&");
} catch (UnsupportedEncodingException impossibile) {}
});
final String tmpUrlValue = tmpUrl.getValue();
if (tmpUrlValue.endsWith("?")) {
parsedUrl = tmpUrlValue.substring(0, tmpUrlValue.lastIndexOf("?"));
} else {
parsedUrl = tmpUrlValue.substring(0, tmpUrlValue.lastIndexOf("&"));
}
}
return parsedUrl;
}
private String getLinkToPackageMainPage(final String packageId, final String lang, final Map<String, String[]> additionalParams) {
return this.appendParamsToUrl(
MessageFormat.format(this.docetConf.getLinkToPagePattern(), packageId, "main", lang),
additionalParams);
}
private PackageResponse servePackageDescriptionForLanguage(final String[] packagesId, final String lang,
final Map<String, String[]> additionalParams, final DocetExecutionContext ctx, final HttpServletRequest request) {
PackageResponse packageResponse;
final List<PackageDescriptionResult> results = new ArrayList<>();
for (final String packageId : packagesId) {
try {
final String pathToPackage = this.getPathToPackageDoc(packageId, ctx);
final String packageLink = getLinkToPackageMainPage(packageId, lang, additionalParams);
final Document descriptor = Jsoup.parseBodyFragment(
new String(
DocetUtils.fastReadFile(new File(pathToPackage).toPath().resolve("descriptor.html")), "UTF-8"));
final Elements divDescriptor = descriptor.select("div[lang=" + lang + "]");
final String title;
final String desc;
final String imageIcoPath;
if (divDescriptor.isEmpty()) {
LOGGER.log(Level.WARNING, "Descriptor for package '"
+ packageId + "' is empty for language '" + lang + "'. Generating an empty description...");
title = packageId;
desc = "";
} else {
title = divDescriptor.select("h1").get(0).text();
desc = divDescriptor.select("p").get(0).text();
}
imageIcoPath = this.buildPackageIconPath(packageId, pathToPackage, additionalParams, request);
final PackageDescriptionResult res
= new PackageDescriptionResult(title, packageId, packageLink, desc, imageIcoPath, lang, null);
results.add(res);
} catch (IOException | DocetPackageException ex) {
LOGGER.log(Level.SEVERE,
"Descriptor for package '" + packageId + "' not found for language '" + lang + "'", ex);
final PackageDescriptionResult res
= new PackageDescriptionResult(null, packageId, null, null, null, lang, "package_not_found");
results.add(res);
}
}
packageResponse = new PackageResponse();
packageResponse.addItems(results);
return packageResponse;
}
private String buildPackageIconPath(final String packageId, final String pathToPackage,
final Map<String, String[]> additionalParams, final HttpServletRequest request) {
final String iconPath;
final File iconFile = new File(pathToPackage).toPath().resolve("icon.png").toFile();
if (iconFile.exists()) {
iconPath = parsePackageIconUrl(packageId, additionalParams);
} else {
iconPath = request.getContextPath() + "/docetres/docet/doc-default.png";
}
return iconPath;
}
private SearchResponse searchPagesByKeywordAndLangWithRerencePackage(final String searchText, final String lang,
final String sourcePackageName, final Set<String> enabledPackages, final Map<String, String[]> additionalParams,
final DocetExecutionContext ctx)
throws DocetException {
SearchResponse searchResponse;
final List<PackageSearchResult> results = new ArrayList<>();
final Holder<PackageSearchResult> packageResForCurrentPackage = new Holder<>();
final Map<String, List<SearchResult>> docsForPackage = new HashMap<>();
final Map<String, String> errorForPackage = new HashMap<>();
final String[] exactSearchTokens = DocetUtils.parsePageIdSearchToTokens(searchText);
//choose search type: search for a specific doc rather than do an extensive search on a set of given packages
if (exactSearchTokens.length == 2) {
final String packageid = exactSearchTokens[0];
final String pageid = exactSearchTokens[1];
try {
final DocetDocumentSearcher packageSearcher
= this.packageRuntimeManager.getSearchIndexForPackage(packageid, ctx);
final DocetDocument foundDoc
= packageSearcher.searchDocumentById(pageid, lang);
final List<SearchResult> packageSearchRes = new ArrayList<>();
if (foundDoc != null) {
final Document toc
= parseTocForPackage(packageid, lang, additionalParams, ctx);
packageSearchRes
.add(this.convertDocetDocumentToSearchResult(lang, packageid, additionalParams, toc, foundDoc));
}
docsForPackage.put(packageid, packageSearchRes);
} catch (DocetPackageException | DocetDocumentSearchException | IOException ex) {
LOGGER.log(Level.WARNING, "Error on completing search '" + searchText + "' on package '"
+ packageid + "'", ex);
errorForPackage.put(packageid, ex.getMessage());
}
} else {
for (final String packageId : enabledPackages) {
final List<DocetDocument> docs = new ArrayList<>();
final List<SearchResult> packageSearchRes = new ArrayList<>();
try {
final DocetDocumentSearcher packageSearcher
= this.packageRuntimeManager.getSearchIndexForPackage(packageId, ctx);
docs.addAll(
packageSearcher
.searchForMatchingDocuments(searchText, lang, this.docetConf.getMaxSearchResultsForPackage()));
final Document toc = parseTocForPackage(packageId, lang, additionalParams, ctx);
docs.stream().sorted((d1, d2) -> d2.getRelevance() - d1.getRelevance()).forEach(e -> {
final SearchResult searchRes
= this.convertDocetDocumentToSearchResult(lang, packageId, additionalParams, toc, e);
packageSearchRes.add(searchRes);
});
docsForPackage.put(packageId, packageSearchRes);
} catch (IOException | DocetDocumentSearchException | DocetPackageException ex) {
LOGGER.log(Level.WARNING, "Error on completing search '"
+ searchText + "' on package '" + packageId + "'", ex);
errorForPackage.put(packageId, ex.getMessage());
}
}
}
docsForPackage.entrySet().stream().forEach(entry -> {
final String packageid = entry.getKey();
final List<SearchResult> searchRes = entry.getValue();
String packageName = null;
final String packageLink = getLinkToPackageMainPage(packageid, lang, additionalParams);
try {
final DocetPackageDescriptor desc = this.packageRuntimeManager.getDescriptorForPackage(packageid, ctx);
packageName = desc.getLabelForLang(lang);
} catch (DocetPackageException ex) {
LOGGER.log(Level.WARNING, "Package name not found in descriptor for package " + packageid, ex);
}
final PackageSearchResult packageRes = PackageSearchResult.toPackageSearchResult(packageid, packageName,
packageLink, searchRes, errorForPackage.get(packageid));
if (packageid.equals(sourcePackageName)) {
packageResForCurrentPackage.setValue(packageRes);
} else {
results.add(packageRes);
}
});
errorForPackage.entrySet().stream().forEach(entry -> {
final String packageid = entry.getKey();
final String errorMsg = entry.getValue();
String packageName = null;
final String packageLink = getLinkToPackageMainPage(packageid, lang, additionalParams);
try {
final DocetPackageDescriptor desc = this.packageRuntimeManager.getDescriptorForPackage(packageid, ctx);
packageName = desc.getLabelForLang(lang);
} catch (DocetPackageException ex) {
LOGGER.log(Level.WARNING, "Package name not found in descriptor for package " + packageid, ex);
}
final PackageSearchResult packageRes = PackageSearchResult.toPackageSearchResult(packageid, packageName,
packageLink, new ArrayList<>(), errorMsg);
if (packageid.equals(sourcePackageName)) {
packageResForCurrentPackage.setValue(packageRes);
} else {
results.add(packageRes);
}
});
searchResponse = new SearchResponse(sourcePackageName);
searchResponse.addResults(results);
if (packageResForCurrentPackage.value != null) {
searchResponse.setCurrentPackageResults(packageResForCurrentPackage.value);
}
return searchResponse;
}
private String[] createBreadcrumbsForPageFromToc(final String packageId, final String pageId, final Document toc) {
List<String> crumbs = new ArrayList<>();
Elements pageLinks = toc.getElementsByTag("a");
Optional<Element> pageLink = pageLinks.stream().filter(link -> link.attr("id").trim().equals(pageId)).findFirst();
if (pageLink.isPresent()) {
final Element tocLink = pageLink.get();
Element parent = null;
Element parentUl = tocLink.parent().parent().parent();
parent = parentUl.parent();
while (parent != null && parent.tagName().toLowerCase().equals("li")) {
Element anchorToAdd = parent.getElementsByTag("div").get(0).getElementsByTag("a").get(0);
anchorToAdd.attr("package", packageId);
crumbs.add(anchorToAdd.outerHtml());
// possibly a ul
Element ul = parent.parent();
if (ul == null) {
parent = null;
} else {
parent = ul.parent();
}
}
}
Collections.reverse(crumbs);
return crumbs.toArray(new String[]{});
}
private static class Holder<T> {
private T value;
Holder() {
}
T getValue() {
return value;
}
void setValue(T value) {
this.value = value;
}
}
private final String urlPattern = "^(/package)|(/search)|(/toc)|"
+ "(/main/[a-zA-Z_0-9\\-]+/index.mndoc)|"
+ "(/faq/[a-zA-Z_0-9\\-]+/[a-zA-Z_0-9\\-]+\\.mndoc)|"
+ "(/pages/[a-zA-Z_0-9\\-]+/[a-zA-Z_0-9\\-]+\\.mndoc)|"
+ "(/pages/[a-zA-Z_0-9\\-]+/[a-zA-Z_0-9\\-]+\\.pdf)|"
+ "(/icons/[a-zA-Z_0-9\\-]+)|"
+ "(/images/[a-zA-Z_0-9\\-]+/[a-zA-Z_0-9\\-]+\\.\\w{3,}\\.mnimg)";
/**
* Main integration method.
*
* @param request
* @throws ServletException
* @throws IOException
*/
public void serveRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String base = request.getContextPath() + request.getServletPath();
final String reqPath = request.getRequestURI().substring(base.length());
System.out.println("ServletPath:" + request.getServletPath() + " " + request.getContextPath() + " " + request.getRequestURI() + " reqPath:" + reqPath);
if (reqPath.matches(this.urlPattern)) {
final DocetExecutionContext ctx = new DocetExecutionContext(request);
final Map<String, String[]> additionalParams = request.getParameterMap();
String[] tokens = reqPath.substring(1).split("/");
String lang = Optional.ofNullable(request.getParameter("lang")).orElse(this.docetConf.getDefaultLanguage());
final String packageId;
if (tokens.length > 1) {
packageId = tokens[1];
} else {
packageId = null;
}
final DocetRequestType req = DocetRequestType.parseDocetRequestByName(tokens[0]);
switch (req) {
case TYPE_TOC:
final String packageIdParam = request.getParameter("packageId");
this.serveTableOfContentsRequest(packageIdParam, lang, additionalParams, ctx, response);
break;
case TYPE_FAQ:
case TYPE_MAIN:
case TYPE_PAGES:
String[] pageFields = tokens[2].split("_");
final String pageName = pageFields[1];
if (pageName.endsWith(".mndoc")) {
lang = pageName.split(".mndoc")[0];
} else if (pageName.endsWith(".pdf")) {
lang = pageName.split(".pdf")[0];
}
final String pageId = pageFields[0];
this.servePageRequest(packageId, pageId, lang, (req == DocetRequestType.TYPE_FAQ),
additionalParams, ctx, response);
break;
case TYPE_ICONS:
this.serveIconRequest(packageId, additionalParams, ctx, response);
case TYPE_IMAGES:
String[] imgFields = tokens[2].split("_");
lang = imgFields[0];
final String imgName = imgFields[1].split(".mnimg")[0];
this.serveImageRequest(packageId, imgName, lang, additionalParams, ctx, response);
break;
case TYPE_SEARCH:
final String sourcePackage = request.getParameter("sourcePkg");
final String[] packages = request.getParameterValues("enablePkg[]");
final String query = request.getParameter("q");
this.serveSearchRequest(query, lang, packages, sourcePackage, additionalParams, ctx, response);
break;
//TODO
case TYPE_PACKAGE:
final String[] packageIds = request.getParameterValues("id");
this.servePackageListRequest(lang, packageIds, additionalParams, ctx, request, response);
break;
default:
LOGGER.log(Level.SEVERE, "Request {0} for package {1} language {2} path {3} is not supported",
new Object[]{req, packageId, lang, reqPath});
throw new ServletException("Unsupported request, path " + reqPath);
}
} else {
LOGGER.log(Level.SEVERE, "Impossibile to find a matching service for request {0}", new Object[]{reqPath});
throw new ServletException("Impossible to serve request " + reqPath);
}
}
private void serveTableOfContentsRequest(final String packageId, final String lang,
final Map<String, String[]> params, final DocetExecutionContext ctx, final HttpServletResponse response)
throws IOException, ServletException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
try (PrintWriter out = response.getWriter();) {
final String html = this.serveTableOfContentsForPackage(packageId, lang, params, ctx);
out.write(html);
} catch (DocetException ex) {
LOGGER.log(Level.SEVERE, "Error on serving TOC packageid " + packageId + " lang ", ex);
throw new ServletException(ex);
}
}
private void servePageRequest(final String packageId, final String pageId, final String lang, final boolean isFaq,
final Map<String, String[]> params, final DocetExecutionContext ctx, final HttpServletResponse response)
throws IOException, ServletException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
try (PrintWriter out = response.getWriter();) {
final String html = this.servePageIdForLanguageForPackage(packageId, pageId, lang, isFaq, params, ctx);
out.write(html);
} catch (DocetException ex) {
LOGGER.log(Level.SEVERE, "Error on serving Page " + pageId + " packageid " + packageId + " lang ", ex);
throw new ServletException(ex);
}
}
private void serveSearchRequest(final String query, final String lang,
final String[] packages, String sourcePackage, final Map<String, String[]> params,
final DocetExecutionContext ctx, final HttpServletResponse response)
throws IOException, ServletException {
final Map<String, String[]> additionalParams = new HashMap<>();
params.entrySet()
.stream()
.filter(entry -> !entry.getKey().equals("q") && !entry.getKey().equals("lang")
&& !entry.getKey().equals("sourcePkg") && !entry.getKey().equals("enablePkg"))
.forEach(e -> {
additionalParams.put(e.getKey(), e.getValue());
});
final Set<String> inScopePackages = new HashSet<>();
inScopePackages.addAll(Arrays.asList(packages));
if (sourcePackage == null) {
sourcePackage = "";
} else {
inScopePackages.add(sourcePackage);
}
try (OutputStream out = response.getOutputStream();) {
final SearchResponse searchResp = this.searchPagesByKeywordAndLangWithRerencePackage(query, lang,
sourcePackage, inScopePackages, additionalParams, ctx);
String json = new ObjectMapper().writeValueAsString(searchResp);
response.setContentType("application/json;charset=utf-8");
out.write(json.getBytes("utf-8"));
} catch (DocetException ex) {
LOGGER.log(Level.SEVERE, "Error on serving search query " + query + " lang ", ex);
throw new ServletException(ex);
}
}
//TODO change
private void servePackageListRequest(final String lang, final String[] packageIds, final Map<String, String[]> params,
final DocetExecutionContext ctx, final HttpServletRequest request, final HttpServletResponse response)
throws IOException, ServletException {
final Map<String, String[]> additionalParams = new HashMap<>();
params.entrySet()
.stream()
.filter(entry -> !entry.getKey().equals("q") && !entry.getKey().equals("lang")
&& !entry.getKey().equals("sourcePkg") && !entry.getKey().equals("enablePkg"))
.forEach(e -> {
additionalParams.put(e.getKey(), e.getValue());
});
try (OutputStream out = response.getOutputStream();) {
final PackageResponse packageResp
= this.servePackageDescriptionForLanguage(packageIds, lang, additionalParams, ctx, request);
String json = new ObjectMapper().writeValueAsString(packageResp);
response.setContentType("application/json;charset=utf-8");
out.write(json.getBytes("utf-8"));
}
}
private void serveImageRequest(final String packageId, final String imageName, final String lang,
final Map<String, String[]> params, final DocetExecutionContext ctx, final HttpServletResponse response)
throws IOException, ServletException {
final String imageFormat = imageName.substring(imageName.indexOf(".") + 1);
if (!"png".equals(imageFormat)) {
throw new ServletException("Unsupported image file format " + imageFormat);
}
response.setContentType("image/png");
try (OutputStream out = response.getOutputStream();) {
this.getImageBylangForPackage(imageName, lang, packageId, out, ctx);
} catch (DocetException ex) {
LOGGER.log(Level.SEVERE, "Error on serving Image " + imageName + " packageid " + packageId + " lang ", ex);
throw new ServletException(ex);
}
}
private void serveIconRequest(final String packageId, final Map<String, String[]> params,
final DocetExecutionContext ctx, final HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("image/png");
try (OutputStream out = response.getOutputStream();) {
this.getIconForPackage(packageId, out, ctx);
} catch (DocetException ex) {
LOGGER.log(Level.SEVERE, "Error on serving Icon for package " + packageId, ex);
throw new ServletException(ex);
}
}
}
| docet-core/src/main/java/docet/engine/DocetManager.java | /*
* Licensed to Diennea S.r.l. under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Diennea S.r.l. 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 docet.engine;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.MessageFormat;
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.Optional;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.map.ObjectMapper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Tag;
import org.jsoup.select.Elements;
import docet.DocetExecutionContext;
import docet.DocetPackageLocator;
import docet.DocetUtils;
import docet.SimplePackageLocator;
import docet.error.DocetDocumentSearchException;
import docet.error.DocetException;
import docet.error.DocetPackageException;
import docet.error.DocetPackageNotFoundException;
import docet.model.DocetDocument;
import docet.model.DocetPackageDescriptor;
import docet.model.PackageDescriptionResult;
import docet.model.PackageResponse;
import docet.model.PackageSearchResult;
import docet.model.SearchResponse;
import docet.model.SearchResult;
import java.net.URLEncoder;
public final class DocetManager {
private static final Logger LOGGER = Logger.getLogger(DocetManager.class.getName());
private static final String IMAGE_DOCET_EXTENSION = ".mnimg";
private static final String CSS_CLASS_DOCET_MENU = "docet-menu";
private static final String CSS_CLASS_DOCET_SUBMENU = "docet-menu-submenu";
private static final String CSS_CLASS_DOCET_MENU_HIDDEN = "docet-menu-hidden";
private static final String CSS_CLASS_DOCET_MENU_VISIBLE = "docet-menu-visible";
private static final String CSS_CLASS_DOCET_MENU_HASSUBMENU = "docet-menu-hasmenu";
private static final String CSS_CLASS_DOCET_MENU_CLOSED = "docet-menu-closed";
private static final String CSS_CLASS_DOCET_MENU_LINK = "docet-menu-link";
private static final String CSS_CLASS_DOCET_PAGE_LINK = "docet-page-link";
private static final String CSS_CLASS_DOCET_FAQ_LINK = "docet-faq-link";
private static final String CSS_CLASS_DOCET_FAQ_MAINLINK = "docet-faq-mainlink";
private static final String CSS_CLASS_DOCET_FAQ_LINK_IN_PAGE = "faq-link";
private static final String ID_DOCET_FAQ_MAIN_LINK = "docet-faq-main-link";
private static final String ID_DOCET_FAQ_MENU = "docet-faq-menu";
private static final String DOCET_HTML_ATTR_REFERENCE_LANGUAGE_NAME = "reference-language";
private final DocetConfiguration docetConf;
private final DocetPackageRuntimeManager packageRuntimeManager;
public void start() throws IOException {
this.packageRuntimeManager.start();
}
public void stop() throws InterruptedException {
this.packageRuntimeManager.stop();
}
/**
* Adopted only in DOCet standalone mode.
*
* @param docetConf
* @throws IOException
*/
public DocetManager(final DocetConfiguration docetConf) throws DocetException {
this.docetConf = docetConf;
try {
this.packageRuntimeManager = new DocetPackageRuntimeManager(new SimplePackageLocator(docetConf), docetConf);
} catch (IOException e) {
throw new DocetException(DocetException.CODE_GENERIC_ERROR, "Initializaton of package runtime manager failed", e);
}
}
public DocetManager(final DocetConfiguration docetConf, final DocetPackageLocator packageLocator) {
this.docetConf = docetConf;
this.packageRuntimeManager = new DocetPackageRuntimeManager(packageLocator, docetConf);
}
private String getPathToPackageDoc(final String packageName, final DocetExecutionContext ctx) throws DocetPackageException {
return this.packageRuntimeManager.getDocumentDirectoryForPackage(packageName, ctx).getAbsolutePath();
}
private void getImageBylangForPackage(final String imgName, final String lang, final String packageName,
final OutputStream out, final DocetExecutionContext ctx)
throws DocetException {
try {
final String basePathToPackage = this.getPathToPackageDoc(packageName, ctx);
final String pathToImg;
if (this.docetConf.isPreviewMode()) {
final String docetImgsBasePath = basePathToPackage + "/" + MessageFormat.format(this.docetConf.getPathToImages(), lang);
final Path imagePath = searchFileInBasePathByName(Paths.get(docetImgsBasePath), imgName);
if (imagePath == null) {
throw new IOException("Image " + imgName + " for language " + lang + " not found!");
} else {
pathToImg = imagePath.toString();
}
} else {
pathToImg = basePathToPackage + "/" + MessageFormat.format(this.docetConf.getPathToImages(), lang) + "/" + imgName;
}
File imgPath = new File(pathToImg);
try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(imgPath))) {
byte[] read = new byte[2048];
while (bin.available() > 0) {
bin.read(read);
out.write(read);
}
}
} catch (IOException ex) {
throw new DocetException(
DocetException.CODE_RESOURCE_NOTFOUND, "Error on loading image '" + imgName + "' package " + packageName, ex);
} catch (DocetPackageException ex) {
this.handleDocetPackageException(ex, packageName);
}
}
private void getIconForPackage(final String packageName, final OutputStream out, final DocetExecutionContext ctx)
throws DocetException {
try {
final String basePathToPackage = this.getPathToPackageDoc(packageName, ctx);
final String pathToIcon = basePathToPackage + "/icon.png";
File imgPath = new File(pathToIcon);
try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(imgPath))) {
byte[] read = new byte[2048];
while (bin.available() > 0) {
bin.read(read);
out.write(read);
}
}
} catch (IOException ex) {
throw new DocetException(
DocetException.CODE_RESOURCE_NOTFOUND, "Error on loading package icon for package " + packageName, ex);
} catch (DocetPackageException ex) {
this.handleDocetPackageException(ex, packageName);
}
}
private void handleDocetPackageException(final DocetPackageException pkgEx, final String packageid)
throws DocetException {
final DocetException res;
final String msg = pkgEx.getMessage();
if (msg.equals(DocetPackageException.MSG_ACCESS_DENIED)) {
res = new DocetException(
DocetException.CODE_PACKAGE_ACCESS_DENIED, "Access denied for package " + packageid, pkgEx);
} else {
res = new DocetException(
DocetException.CODE_PACKAGE_NOTFOUND, "Package not found " + packageid, pkgEx);
}
throw res;
}
/**
* Used to retrieve the TOC for a given language, parsing each link in the TOC so as to have params appended to it.
*
* @param packageName the name of target documentation package
*
* @param lang the language code the desired TOC refers to
*
* @param params the additional params to append to each link making up TOC
*
* @return the TOC in text format
* @throws DocetPackageNotFoundException
* @throws UnsupportedEncodingException
*
* @throws IOException in case of issues on retrieving the TOC page
*/
private String serveTableOfContentsForPackage(final String packageName, final String lang,
final Map<String, String[]> params, final DocetExecutionContext ctx)
throws DocetException {
String html = "";
try {
html = parseTocForPackage(packageName, lang, params, ctx).body().getElementsByTag("nav").first().html();
} catch (IOException ex) {
throw new DocetException(
DocetException.CODE_RESOURCE_NOTFOUND, "Error on retrieving TOC for package '" + packageName + "'", ex);
} catch (DocetPackageException ex) {
this.handleDocetPackageException(ex, packageName);
}
return DocetUtils.cleanPageText(html);
}
/**
* Retrieve a page given a page id and a reference language. Links in the page content are parsed and provided
* params appended to them.
*
* @param packageName the target documentation package
*
* @param pageId the id of the page to be served
* @param lang the reference language for this page's id
* @param faq true if the page to be served is a faq page, false in case of a "standard" documentation page
* @param params the additional params to be appended to each link in the page
*
* @return the text representation of the requested page
* @throws DocetPackageNotFoundException
*
* @throws IOException in case parsing of the page got issues
*/
private String servePageIdForLanguageForPackage(final String packageName, final String pageId, final String lang,
final boolean faq, final Map<String, String[]> params, final DocetExecutionContext ctx)
throws DocetException {
final StringBuilder html = new StringBuilder();
try {
html.append(parsePageForPackage(packageName, pageId, lang, faq, params, ctx)
.body().getElementsByTag("div").first().html());
html.append(generateFooter(lang, packageName, pageId));
} catch (IOException ex) {
throw new DocetException(DocetException.CODE_RESOURCE_NOTFOUND, "Error on retrieving page '" + pageId + "' for package '" + packageName + "'", ex);
} catch (DocetPackageException ex) {
this.handleDocetPackageException(ex, packageName);
}
return DocetUtils.cleanPageText(html.toString());
}
private Document parsePageForPackage(final String packageName, final String pageId, final String lang,
final boolean faq, final Map<String, String[]> params, final DocetExecutionContext ctx)
throws DocetPackageException, IOException {
final Document docPage = this.loadPageByIdForPackageAndLanguage(packageName, pageId, lang, faq, ctx);
final Elements imgs = docPage.getElementsByTag("img");
imgs.stream().forEach(img -> {
parseImage(packageName, img, lang, params);
});
final Elements anchors = docPage.getElementsByTag("a");
anchors.stream().filter(a -> {
final String href = a.attr("href");
return !href.startsWith("#") && !href.startsWith("http://") && !href.startsWith("https://");
}).forEach(a -> {
parseAnchorItemInPage(packageName, a, lang, params);
});
return docPage;
}
private String generateFooter(final String lang, final String packageId, final String pageId) {
String res = "";
res += "<div id='docet-debug-info' class='docet-footer'>";
res += "<span style='visibility:hidden;display:none;' id='docet-page-id'><b>Page id:</b> " + packageId + ":" + pageId + "</span>";
if (docetConf.isDebugMode()) {
res += "<br/><b>Version</b>: " + docetConf.getVersion() + " | <b>Language:</b> " + lang;
}
res += "</div>";
return res;
}
private Document loadPageByIdForPackageAndLanguage(final String packageName, final String pageId, final String lang, final boolean faq,
final DocetExecutionContext ctx) throws DocetPackageException, IOException {
final String pathToPage;
if (faq) {
pathToPage = this.getFaqPathByIdForPackageAndLanguage(packageName, pageId, lang, ctx);
} else {
pathToPage = this.getPagePathByIdForPackageAndLanguage(packageName, pageId, lang, ctx);
}
return Jsoup.parseBodyFragment(new String(DocetUtils.fastReadFile(new File(pathToPage).toPath()), "UTF-8"));
}
private String getFaqPathByIdForPackageAndLanguage(final String packageName, final String faqId, final String lang,
final DocetExecutionContext ctx) throws DocetPackageException {
final String basePath = this.getPathToPackageDoc(packageName, ctx);
final String pathToFaq = basePath + "/" + MessageFormat.format(docetConf.getPathToFaq(), lang) + "/" + faqId + ".html";
return pathToFaq;
}
private String getPagePathByIdForPackageAndLanguage(final String packageName, final String pageId, final String lang,
final DocetExecutionContext ctx)
throws DocetPackageException, IOException {
final String basePath = this.getPathToPackageDoc(packageName, ctx);
final String pathToPage;
if (this.docetConf.isPreviewMode()) {
final String docetDocsBasePath = basePath + "/" + MessageFormat.format(docetConf.getPathToPages(), lang);
final Path pagePath = searchFileInBasePathByName(Paths.get(docetDocsBasePath), pageId + ".html");
if (pagePath == null) {
throw new IOException("Page " + pageId + " for language " + lang + " not found!");
} else {
pathToPage = searchFileInBasePathByName(Paths.get(docetDocsBasePath), pageId + ".html").toString();
}
} else {
pathToPage = basePath + "/" + MessageFormat.format(docetConf.getPathToPages(), lang) + "/" + pageId + ".html";
}
return pathToPage;
}
private static Path searchFileInBasePathByName(final Path basePath, final String fileName) throws IOException {
final Holder<Path> result = new Holder<Path>();
Files.walkFileTree(basePath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
if (file.endsWith(fileName)) {
result.setValue(file);
return FileVisitResult.TERMINATE;
}
return FileVisitResult.CONTINUE;
}
});
return result.value;
}
private Document loadTocForPackage(final String packageName, final String lang, final DocetExecutionContext ctx)
throws DocetPackageException, UnsupportedEncodingException, IOException {
final String basePath = this.getPathToPackageDoc(packageName, ctx);
return Jsoup
.parseBodyFragment(new String(
DocetUtils.fastReadFile(
new File(basePath + MessageFormat.format(this.docetConf.getTocFilePath(), lang)).toPath()),
"UTF-8"), "UTF-8");
}
private Document parseTocForPackage(final String packageName, final String lang,
final Map<String, String[]> params, final DocetExecutionContext ctx)
throws UnsupportedEncodingException, DocetPackageException, IOException {
final Document docToc = loadTocForPackage(packageName, lang, ctx);
// inject default docet menu css class on main menu
docToc.select("nav > ul").addClass(CSS_CLASS_DOCET_MENU);
docToc.select("nav > ul").attr("package", packageName);
docToc.select("nav > ul").addClass(CSS_CLASS_DOCET_MENU_VISIBLE);
docToc.select("nav > ul > li").addClass(CSS_CLASS_DOCET_MENU);
if (this.docetConf.isFaqTocAtRuntime()) {
injectFaqItemsInTOC(docToc, lang);
}
final Elements anchors = docToc.getElementsByTag("a");
anchors.stream().forEach(a -> {
parseTOCItem(packageName, a, lang, params);
});
final Elements lis = docToc.getElementsByTag("li");
lis.stream().forEach(li -> {
injectClasses(li);
});
return docToc;
}
private static final String getFaqPath() {
return "<a class=\"" + CSS_CLASS_DOCET_FAQ_LINK + "\" id=\"" + ID_DOCET_FAQ_MAIN_LINK + "\" href=\"faq.html\">FAQ</a>";
}
private SearchResult convertDocetDocumentToSearchResult(final String lang, final String packageId,
final Map<String, String[]> additionalParams, final Document toc, final DocetDocument doc) {
final int docType = doc.getType();
final String pageLink;
final String pageId;
final String[] breadCrumbs;
switch (docType) {
case DocetDocument.DOCTYPE_FAQ:
pageLink = MessageFormat.format(this.docetConf.getLinkToFaqPattern(), packageId, doc.getId(), lang);
pageId = "faq_" + doc.getId() + "_" + lang;
breadCrumbs = new String[]{getFaqPath()};
break;
case DocetDocument.DOCTYPE_PAGE:
pageLink = MessageFormat.format(this.docetConf.getLinkToPagePattern(), packageId, doc.getId(), lang);
pageId = doc.getId() + "_" + lang;
breadCrumbs = createBreadcrumbsForPageFromToc(packageId, pageId, toc);
break;
default:
throw new IllegalArgumentException("Unsupported document type " + docType);
}
return SearchResult.toSearchResult(packageId, doc, pageId, appendParamsToUrl(pageLink, additionalParams), breadCrumbs);
}
private void injectFaqItemsInTOC(final Document toc, final String lang) throws IOException {
final Element faqList = toc.getElementById(ID_DOCET_FAQ_MENU);
if (faqList == null) {
return;
}
final Element faqMainLink = toc.getElementById(ID_DOCET_FAQ_MAIN_LINK);
if (faqMainLink == null) {
return;
} else {
faqMainLink.addClass(CSS_CLASS_DOCET_FAQ_MAINLINK);
}
final Holder<Integer> countFaqs = new Holder<Integer>();
countFaqs.setValue(0);
faqList.select("a").forEach(faqA -> {
faqA.addClass(CSS_CLASS_DOCET_FAQ_LINK);
countFaqs.setValue(countFaqs.getValue() + 1);
});
if (countFaqs.getValue() > 0) {
toc.select("nav > ul > li").addClass(CSS_CLASS_DOCET_MENU_HASSUBMENU);
}
}
private void injectClasses(final Element item) {
if (!item.hasClass(CSS_CLASS_DOCET_MENU)) {
item.addClass(CSS_CLASS_DOCET_SUBMENU);
}
final Elements subItems = item.getElementsByTag("ul");
subItems.stream().peek(ul -> {
ul.addClass(CSS_CLASS_DOCET_SUBMENU);
ul.addClass(CSS_CLASS_DOCET_MENU_HIDDEN);
}).count();
// add an enclosing div for each anchor within a li
final Element a = item.children().select("a").get(0);
item.prependChild(new Element(Tag.valueOf("div"), ""));
item.select("div").get(0).append(a.outerHtml());
final Element appendedA = item.select("div").get(0).select("a").get(0);
a.remove();
if (!appendedA.attr("id").equals(ID_DOCET_FAQ_MAIN_LINK) && appendedA.hasClass(CSS_CLASS_DOCET_FAQ_LINK)) {
return;
}
// if this li (item) has child then we must be confident it has a
// submenu
if (!item.children().select("ul").isEmpty()) {
item.addClass(CSS_CLASS_DOCET_MENU_HASSUBMENU);
item.select("div").get(0).addClass(CSS_CLASS_DOCET_MENU_CLOSED);
}
}
private String parsePackageIconUrl(final String packageName, final Map<String, String[]> params) {
String url = MessageFormat.format(this.docetConf.getLinkToPackageIconPattern(), packageName);
url = appendParamsToUrl(url, params);
return url;
}
private void parseImage(final String packageName, final Element item, final String lang, final Map<String, String[]> params) {
final String[] imgPathTokens = item.attr("src").split("/");
final String imgName = imgPathTokens[imgPathTokens.length - 1];
final String imgNameNormalizedExtension = imgName + IMAGE_DOCET_EXTENSION;
String href = MessageFormat.format(this.docetConf.getLinkToImagePattern(), packageName, lang, imgNameNormalizedExtension);
href = appendParamsToUrl(href, params);
item.attr("src", href);
}
private void parseTOCItem(final String packageName, final Element item, String lang, final Map<String, String[]> params) {
final String barePagename = item.attr("href").split(".html")[0];
// check if the linked document is written in another language!
final String referenceLanguage = item.attr(DOCET_HTML_ATTR_REFERENCE_LANGUAGE_NAME);
if (!referenceLanguage.isEmpty()) {
lang = referenceLanguage;
}
String href;
if (item.hasClass(CSS_CLASS_DOCET_FAQ_LINK)) {
href = MessageFormat.format(this.docetConf.getLinkToFaqPattern(), packageName, barePagename, lang);
// determine page id: if page name is samplepage_it.html
// then id will be simply samplepage_it
if (!item.attr("id").equals(ID_DOCET_FAQ_MAIN_LINK)) {
item.attr("id", "faq_" + barePagename + "_" + lang);
}
} else {
href = MessageFormat.format(this.docetConf.getLinkToPagePattern(), packageName, barePagename, lang);
// determine page id: if page name is samplepage_it.html
// then id will be simply samplepage_it
item.attr("id", barePagename + "_" + lang);
item.attr("title", item.text());
}
href = appendParamsToUrl(href, params);
item.addClass(CSS_CLASS_DOCET_MENU_LINK);
item.attr("href", href);
item.attr("package", packageName);
}
private void parseAnchorItemInPage(final String packageName, final Element item, final String lang, final Map<String, String[]> params) {
final String crossPackageId = item.attr("package");
final String[] pageNameTokens = item.attr("href").split(".html");
final String barePagename = pageNameTokens[0];
final String fragment;
if (pageNameTokens.length == 2) {
fragment = pageNameTokens[1];
} else {
fragment = "";
}
final String linkId;
String href;
final String ultimatePackageId;
if (crossPackageId.isEmpty()) {
ultimatePackageId = packageName;
} else {
ultimatePackageId = crossPackageId;
}
if (item.hasClass(CSS_CLASS_DOCET_FAQ_LINK_IN_PAGE)) {
href = MessageFormat.format(this.docetConf.getLinkToFaqPattern(), ultimatePackageId, barePagename, lang) + fragment;
linkId = "faq_" + barePagename + "_" + lang;
item.removeClass(CSS_CLASS_DOCET_FAQ_LINK_IN_PAGE);
} else {
href = MessageFormat.format(this.docetConf.getLinkToPagePattern(), ultimatePackageId, barePagename, lang) + fragment;
linkId = barePagename + "_" + lang;
}
href = appendParamsToUrl(href, params);
// determine page id: if page name is samplepage_it.html
// then id will be simply samplepage_it
item.attr("id", linkId);
item.attr("href", href);
item.attr("package", ultimatePackageId);
item.addClass(CSS_CLASS_DOCET_PAGE_LINK);
}
private String appendParamsToUrl(final String url, final Map<String, String[]> params) {
final String parsedUrl;
if (params.isEmpty()) {
parsedUrl = url;
} else {
final Holder<String> tmpUrl = new Holder<String>();
tmpUrl.setValue(url + "?");
params.entrySet().stream().forEach(entry -> {
try {
tmpUrl.setValue(tmpUrl.getValue() + entry.getKey() + "=" + URLEncoder.encode(entry.getValue()[0], "utf-8") + "&");
} catch (UnsupportedEncodingException impossibile) {
}
});
final String tmpUrlValue = tmpUrl.getValue();
parsedUrl = tmpUrlValue.substring(0, tmpUrlValue.lastIndexOf("&"));
}
return parsedUrl;
}
private String getLinkToPackageMainPage(final String packageId, final String lang, final Map<String, String[]> additionalParams) {
return this.appendParamsToUrl(
MessageFormat.format(this.docetConf.getLinkToPagePattern(), packageId, "main", lang),
additionalParams);
}
private PackageResponse servePackageDescriptionForLanguage(final String[] packagesId, final String lang,
final Map<String, String[]> additionalParams, final DocetExecutionContext ctx, final HttpServletRequest request) {
PackageResponse packageResponse;
final List<PackageDescriptionResult> results = new ArrayList<>();
for (final String packageId : packagesId) {
try {
final String pathToPackage = this.getPathToPackageDoc(packageId, ctx);
final String packageLink = getLinkToPackageMainPage(packageId, lang, additionalParams);
final Document descriptor = Jsoup.parseBodyFragment(
new String(
DocetUtils.fastReadFile(new File(pathToPackage).toPath().resolve("descriptor.html")), "UTF-8"));
final Elements divDescriptor = descriptor.select("div[lang=" + lang + "]");
final String title;
final String desc;
final String imageIcoPath;
if (divDescriptor.isEmpty()) {
LOGGER.log(Level.WARNING, "Descriptor for package '"
+ packageId + "' is empty for language '" + lang + "'. Generating an empty description...");
title = packageId;
desc = "";
} else {
title = divDescriptor.select("h1").get(0).text();
desc = divDescriptor.select("p").get(0).text();
}
imageIcoPath = this.buildPackageIconPath(packageId, pathToPackage, additionalParams, request);
final PackageDescriptionResult res
= new PackageDescriptionResult(title, packageId, packageLink, desc, imageIcoPath, lang, null);
results.add(res);
} catch (IOException | DocetPackageException ex) {
LOGGER.log(Level.SEVERE,
"Descriptor for package '" + packageId + "' not found for language '" + lang + "'", ex);
final PackageDescriptionResult res
= new PackageDescriptionResult(null, packageId, null, null, null, lang, "package_not_found");
results.add(res);
}
}
packageResponse = new PackageResponse();
packageResponse.addItems(results);
return packageResponse;
}
private String buildPackageIconPath(final String packageId, final String pathToPackage,
final Map<String, String[]> additionalParams, final HttpServletRequest request) {
final String iconPath;
final File iconFile = new File(pathToPackage).toPath().resolve("icon.png").toFile();
if (iconFile.exists()) {
iconPath = parsePackageIconUrl(packageId, additionalParams);
} else {
iconPath = request.getContextPath() + "/docetres/docet/doc-default.png";
}
return iconPath;
}
private SearchResponse searchPagesByKeywordAndLangWithRerencePackage(final String searchText, final String lang,
final String sourcePackageName, final Set<String> enabledPackages, final Map<String, String[]> additionalParams,
final DocetExecutionContext ctx)
throws DocetException {
SearchResponse searchResponse;
final List<PackageSearchResult> results = new ArrayList<>();
final Holder<PackageSearchResult> packageResForCurrentPackage = new Holder<>();
final Map<String, List<SearchResult>> docsForPackage = new HashMap<>();
final Map<String, String> errorForPackage = new HashMap<>();
final String[] exactSearchTokens = DocetUtils.parsePageIdSearchToTokens(searchText);
//choose search type: search for a specific doc rather than do an extensive search on a set of given packages
if (exactSearchTokens.length == 2) {
final String packageid = exactSearchTokens[0];
final String pageid = exactSearchTokens[1];
try {
final DocetDocumentSearcher packageSearcher
= this.packageRuntimeManager.getSearchIndexForPackage(packageid, ctx);
final DocetDocument foundDoc
= packageSearcher.searchDocumentById(pageid, lang);
final List<SearchResult> packageSearchRes = new ArrayList<>();
if (foundDoc != null) {
final Document toc
= parseTocForPackage(packageid, lang, additionalParams, ctx);
packageSearchRes
.add(this.convertDocetDocumentToSearchResult(lang, packageid, additionalParams, toc, foundDoc));
}
docsForPackage.put(packageid, packageSearchRes);
} catch (DocetPackageException | DocetDocumentSearchException | IOException ex) {
LOGGER.log(Level.WARNING, "Error on completing search '" + searchText + "' on package '"
+ packageid + "'", ex);
errorForPackage.put(packageid, ex.getMessage());
}
} else {
for (final String packageId : enabledPackages) {
final List<DocetDocument> docs = new ArrayList<>();
final List<SearchResult> packageSearchRes = new ArrayList<>();
try {
final DocetDocumentSearcher packageSearcher
= this.packageRuntimeManager.getSearchIndexForPackage(packageId, ctx);
docs.addAll(
packageSearcher
.searchForMatchingDocuments(searchText, lang, this.docetConf.getMaxSearchResultsForPackage()));
final Document toc = parseTocForPackage(packageId, lang, additionalParams, ctx);
docs.stream().sorted((d1, d2) -> d2.getRelevance() - d1.getRelevance()).forEach(e -> {
final SearchResult searchRes
= this.convertDocetDocumentToSearchResult(lang, packageId, additionalParams, toc, e);
packageSearchRes.add(searchRes);
});
docsForPackage.put(packageId, packageSearchRes);
} catch (IOException | DocetDocumentSearchException | DocetPackageException ex) {
LOGGER.log(Level.WARNING, "Error on completing search '"
+ searchText + "' on package '" + packageId + "'", ex);
errorForPackage.put(packageId, ex.getMessage());
}
}
}
docsForPackage.entrySet().stream().forEach(entry -> {
final String packageid = entry.getKey();
final List<SearchResult> searchRes = entry.getValue();
String packageName = null;
final String packageLink = getLinkToPackageMainPage(packageid, lang, additionalParams);
try {
final DocetPackageDescriptor desc = this.packageRuntimeManager.getDescriptorForPackage(packageid, ctx);
packageName = desc.getLabelForLang(lang);
} catch (DocetPackageException ex) {
LOGGER.log(Level.WARNING, "Package name not found in descriptor for package " + packageid, ex);
}
final PackageSearchResult packageRes = PackageSearchResult.toPackageSearchResult(packageid, packageName,
packageLink, searchRes, errorForPackage.get(packageid));
if (packageid.equals(sourcePackageName)) {
packageResForCurrentPackage.setValue(packageRes);
} else {
results.add(packageRes);
}
});
errorForPackage.entrySet().stream().forEach(entry -> {
final String packageid = entry.getKey();
final String errorMsg = entry.getValue();
String packageName = null;
final String packageLink = getLinkToPackageMainPage(packageid, lang, additionalParams);
try {
final DocetPackageDescriptor desc = this.packageRuntimeManager.getDescriptorForPackage(packageid, ctx);
packageName = desc.getLabelForLang(lang);
} catch (DocetPackageException ex) {
LOGGER.log(Level.WARNING, "Package name not found in descriptor for package " + packageid, ex);
}
final PackageSearchResult packageRes = PackageSearchResult.toPackageSearchResult(packageid, packageName,
packageLink, new ArrayList<>(), errorMsg);
if (packageid.equals(sourcePackageName)) {
packageResForCurrentPackage.setValue(packageRes);
} else {
results.add(packageRes);
}
});
searchResponse = new SearchResponse(sourcePackageName);
searchResponse.addResults(results);
if (packageResForCurrentPackage.value != null) {
searchResponse.setCurrentPackageResults(packageResForCurrentPackage.value);
}
return searchResponse;
}
private String[] createBreadcrumbsForPageFromToc(final String packageId, final String pageId, final Document toc) {
List<String> crumbs = new ArrayList<>();
Elements pageLinks = toc.getElementsByTag("a");
Optional<Element> pageLink = pageLinks.stream().filter(link -> link.attr("id").trim().equals(pageId)).findFirst();
if (pageLink.isPresent()) {
final Element tocLink = pageLink.get();
Element parent = null;
Element parentUl = tocLink.parent().parent().parent();
parent = parentUl.parent();
while (parent != null && parent.tagName().toLowerCase().equals("li")) {
Element anchorToAdd = parent.getElementsByTag("div").get(0).getElementsByTag("a").get(0);
anchorToAdd.attr("package", packageId);
crumbs.add(anchorToAdd.outerHtml());
// possibly a ul
Element ul = parent.parent();
if (ul == null) {
parent = null;
} else {
parent = ul.parent();
}
}
}
Collections.reverse(crumbs);
return crumbs.toArray(new String[]{});
}
private static class Holder<T> {
private T value;
Holder() {
}
T getValue() {
return value;
}
void setValue(T value) {
this.value = value;
}
}
private final String urlPattern = "^(/package)|(/search)|(/toc)|"
+ "(/main/[a-zA-Z_0-9\\-]+/index.mndoc)|"
+ "(/faq/[a-zA-Z_0-9\\-]+/[a-zA-Z_0-9\\-]+\\.mndoc)|"
+ "(/pages/[a-zA-Z_0-9\\-]+/[a-zA-Z_0-9\\-]+\\.mndoc)|"
+ "(/pages/[a-zA-Z_0-9\\-]+/[a-zA-Z_0-9\\-]+\\.pdf)|"
+ "(/images/[a-zA-Z_0-9\\-]+/[a-zA-Z_0-9\\-]+\\.\\w{3,}\\.mnimg)";
/**
* Main integration method.
*
* @param request
* @throws ServletException
* @throws IOException
*/
public void serveRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String base = request.getContextPath() + request.getServletPath();
final String reqPath = request.getRequestURI().substring(base.length());
System.out.println("ServletPath:" + request.getServletPath() + " " + request.getContextPath() + " " + request.getRequestURI() + " reqPath:" + reqPath);
if (reqPath.matches(this.urlPattern)) {
final DocetExecutionContext ctx = new DocetExecutionContext(request);
final Map<String, String[]> additionalParams = request.getParameterMap();
String[] tokens = reqPath.substring(1).split("/");
String lang = Optional.ofNullable(request.getParameter("lang")).orElse(this.docetConf.getDefaultLanguage());
final String packageId;
if (tokens.length > 1) {
packageId = tokens[1];
} else {
packageId = null;
}
final DocetRequestType req = DocetRequestType.parseDocetRequestByName(tokens[0]);
switch (req) {
case TYPE_TOC:
final String packageIdParam = request.getParameter("packageId");
this.serveTableOfContentsRequest(packageIdParam, lang, additionalParams, ctx, response);
break;
case TYPE_FAQ:
case TYPE_MAIN:
case TYPE_PAGES:
String[] pageFields = tokens[2].split("_");
final String pageName = pageFields[1];
if (pageName.endsWith(".mndoc")) {
lang = pageName.split(".mndoc")[0];
} else if (pageName.endsWith(".pdf")) {
lang = pageName.split(".pdf")[0];
}
final String pageId = pageFields[0];
this.servePageRequest(packageId, pageId, lang, (req == DocetRequestType.TYPE_FAQ),
additionalParams, ctx, response);
break;
case TYPE_ICONS:
this.serveIconRequest(packageId, additionalParams, ctx, response);
case TYPE_IMAGES:
String[] imgFields = tokens[2].split("_");
lang = imgFields[0];
final String imgName = imgFields[1].split(".mnimg")[0];
this.serveImageRequest(packageId, imgName, lang, additionalParams, ctx, response);
break;
case TYPE_SEARCH:
final String sourcePackage = request.getParameter("sourcePkg");
final String[] packages = request.getParameterValues("enablePkg[]");
final String query = request.getParameter("q");
this.serveSearchRequest(query, lang, packages, sourcePackage, additionalParams, ctx, response);
break;
//TODO
case TYPE_PACKAGE:
final String[] packageIds = request.getParameterValues("id");
this.servePackageListRequest(lang, packageIds, additionalParams, ctx, request, response);
break;
default:
LOGGER.log(Level.SEVERE, "Request {0} for package {1} language {2} path {3} is not supported",
new Object[]{req, packageId, lang, reqPath});
throw new ServletException("Unsupported request, path " + reqPath);
}
} else {
LOGGER.log(Level.SEVERE, "Impossibile to find a matching service for request {0}", new Object[]{reqPath});
throw new ServletException("Impossible to serve request " + reqPath);
}
}
private void serveTableOfContentsRequest(final String packageId, final String lang,
final Map<String, String[]> params, final DocetExecutionContext ctx, final HttpServletResponse response)
throws IOException, ServletException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
try (PrintWriter out = response.getWriter();) {
final String html = this.serveTableOfContentsForPackage(packageId, lang, params, ctx);
out.write(html);
} catch (DocetException ex) {
LOGGER.log(Level.SEVERE, "Error on serving TOC packageid " + packageId + " lang ", ex);
throw new ServletException(ex);
}
}
private void servePageRequest(final String packageId, final String pageId, final String lang, final boolean isFaq,
final Map<String, String[]> params, final DocetExecutionContext ctx, final HttpServletResponse response)
throws IOException, ServletException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
try (PrintWriter out = response.getWriter();) {
final String html = this.servePageIdForLanguageForPackage(packageId, pageId, lang, isFaq, params, ctx);
out.write(html);
} catch (DocetException ex) {
LOGGER.log(Level.SEVERE, "Error on serving Page " + pageId + " packageid " + packageId + " lang ", ex);
throw new ServletException(ex);
}
}
private void serveSearchRequest(final String query, final String lang,
final String[] packages, String sourcePackage, final Map<String, String[]> params,
final DocetExecutionContext ctx, final HttpServletResponse response)
throws IOException, ServletException {
final Map<String, String[]> additionalParams = new HashMap<>();
params.entrySet()
.stream()
.filter(entry -> !entry.getKey().equals("q") && !entry.getKey().equals("lang")
&& !entry.getKey().equals("sourcePkg") && !entry.getKey().equals("enablePkg"))
.forEach(e -> {
additionalParams.put(e.getKey(), e.getValue());
});
final Set<String> inScopePackages = new HashSet<>();
inScopePackages.addAll(Arrays.asList(packages));
if (sourcePackage == null) {
sourcePackage = "";
} else {
inScopePackages.add(sourcePackage);
}
try (OutputStream out = response.getOutputStream();) {
final SearchResponse searchResp = this.searchPagesByKeywordAndLangWithRerencePackage(query, lang,
sourcePackage, inScopePackages, additionalParams, ctx);
String json = new ObjectMapper().writeValueAsString(searchResp);
response.setContentType("application/json;charset=utf-8");
out.write(json.getBytes("utf-8"));
} catch (DocetException ex) {
LOGGER.log(Level.SEVERE, "Error on serving search query " + query + " lang ", ex);
throw new ServletException(ex);
}
}
//TODO change
private void servePackageListRequest(final String lang, final String[] packageIds, final Map<String, String[]> params,
final DocetExecutionContext ctx, final HttpServletRequest request, final HttpServletResponse response)
throws IOException, ServletException {
final Map<String, String[]> additionalParams = new HashMap<>();
params.entrySet()
.stream()
.filter(entry -> !entry.getKey().equals("q") && !entry.getKey().equals("lang")
&& !entry.getKey().equals("sourcePkg") && !entry.getKey().equals("enablePkg"))
.forEach(e -> {
additionalParams.put(e.getKey(), e.getValue());
});
try (OutputStream out = response.getOutputStream();) {
final PackageResponse packageResp
= this.servePackageDescriptionForLanguage(packageIds, lang, additionalParams, ctx, request);
String json = new ObjectMapper().writeValueAsString(packageResp);
response.setContentType("application/json;charset=utf-8");
out.write(json.getBytes("utf-8"));
}
}
private void serveImageRequest(final String packageId, final String imageName, final String lang,
final Map<String, String[]> params, final DocetExecutionContext ctx, final HttpServletResponse response)
throws IOException, ServletException {
final String imageFormat = imageName.substring(imageName.indexOf(".") + 1);
if (!"png".equals(imageFormat)) {
throw new ServletException("Unsupported image file format " + imageFormat);
}
response.setContentType("image/png");
try (OutputStream out = response.getOutputStream();) {
this.getImageBylangForPackage(imageName, lang, packageId, out, ctx);
} catch (DocetException ex) {
LOGGER.log(Level.SEVERE, "Error on serving Image " + imageName + " packageid " + packageId + " lang ", ex);
throw new ServletException(ex);
}
}
private void serveIconRequest(final String packageId, final Map<String, String[]> params,
final DocetExecutionContext ctx, final HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("image/png");
try (OutputStream out = response.getOutputStream();) {
this.getIconForPackage(packageId, out, ctx);
} catch (DocetException ex) {
LOGGER.log(Level.SEVERE, "Error on serving Icon for package " + packageId, ex);
throw new ServletException(ex);
}
}
}
| DOCET-17
| docet-core/src/main/java/docet/engine/DocetManager.java | DOCET-17 | <ide><path>ocet-core/src/main/java/docet/engine/DocetManager.java
<ide>
<ide> final Holder<String> tmpUrl = new Holder<String>();
<ide> tmpUrl.setValue(url + "?");
<del> params.entrySet().stream().forEach(entry -> {
<del> try {
<del> tmpUrl.setValue(tmpUrl.getValue() + entry.getKey() + "=" + URLEncoder.encode(entry.getValue()[0], "utf-8") + "&");
<del> } catch (UnsupportedEncodingException impossibile) {
<del> }
<del> });
<add> params.entrySet().stream().filter(entry -> !entry.getKey().equals("id") && !entry.getKey().equals("lang"))
<add> .forEach(entry -> {
<add> try {
<add> tmpUrl.setValue(tmpUrl.getValue() + entry.getKey()
<add> + "=" + URLEncoder.encode(entry.getValue()[0], "utf-8") + "&");
<add> } catch (UnsupportedEncodingException impossibile) {}
<add> });
<ide> final String tmpUrlValue = tmpUrl.getValue();
<del> parsedUrl = tmpUrlValue.substring(0, tmpUrlValue.lastIndexOf("&"));
<del>
<add> if (tmpUrlValue.endsWith("?")) {
<add> parsedUrl = tmpUrlValue.substring(0, tmpUrlValue.lastIndexOf("?"));
<add> } else {
<add> parsedUrl = tmpUrlValue.substring(0, tmpUrlValue.lastIndexOf("&"));
<add> }
<ide> }
<ide> return parsedUrl;
<ide> }
<ide> + "(/faq/[a-zA-Z_0-9\\-]+/[a-zA-Z_0-9\\-]+\\.mndoc)|"
<ide> + "(/pages/[a-zA-Z_0-9\\-]+/[a-zA-Z_0-9\\-]+\\.mndoc)|"
<ide> + "(/pages/[a-zA-Z_0-9\\-]+/[a-zA-Z_0-9\\-]+\\.pdf)|"
<add> + "(/icons/[a-zA-Z_0-9\\-]+)|"
<ide> + "(/images/[a-zA-Z_0-9\\-]+/[a-zA-Z_0-9\\-]+\\.\\w{3,}\\.mnimg)";
<ide>
<ide> /** |
|
Java | mit | 5228b480b22ad267437c0e0d47136f6a9c36c861 | 0 | agrass/react-native-gps,agrass/react-native-gps | package com.syarul.rnlocation;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.Log;
import android.os.Bundle;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter;
public class RNLocationModule extends ReactContextBaseJavaModule{
// React Class Name as called from JS
public static final String REACT_CLASS = "RNLocation";
// Unique Name for Log TAG
public static final String TAG = RNLocationModule.class.getSimpleName();
private static final float RCT_DEFAULT_LOCATION_ACCURACY = 1;
public static int POSITION_UNAVAILABLE = 2;
// Save last Location Provided
private Location mLastLocation;
private LocationListener mLocationListener;
private LocationManager locationManager;
//The React Native Context
ReactApplicationContext mReactContext;
// Constructor Method as called in Package
public RNLocationModule(ReactApplicationContext reactContext) {
super(reactContext);
// Save Context for later use
mReactContext = reactContext;
locationManager = (LocationManager) mReactContext.getSystemService(Context.LOCATION_SERVICE);
}
@Override
public String getName() {
return REACT_CLASS;
}
private static class LocationOptions {
private final long timeout;
private final double maximumAge;
private final boolean highAccuracy;
private final float distanceFilter;
private LocationOptions(
long timeout,
double maximumAge,
boolean highAccuracy,
float distanceFilter) {
this.timeout = timeout;
this.maximumAge = maximumAge;
this.highAccuracy = highAccuracy;
this.distanceFilter = distanceFilter;
}
private static LocationOptions fromReactMap(ReadableMap map) {
// precision might be dropped on timeout (double -> int conversion), but that's OK
long timeout =
map.hasKey("timeout") ? (long) map.getDouble("timeout") : Long.MAX_VALUE;
double maximumAge =
map.hasKey("maximumAge") ? map.getDouble("maximumAge") : Double.POSITIVE_INFINITY;
boolean highAccuracy = !map.hasKey("enableHighAccuracy") || map.getBoolean("enableHighAccuracy");
float distanceFilter = map.hasKey("distanceFilter") ?
(float) map.getDouble("distanceFilter") :
RCT_DEFAULT_LOCATION_ACCURACY;
return new LocationOptions(timeout, maximumAge, highAccuracy, distanceFilter);
}
}
/*
* Location permission request (Not implemented yet)
*/
@ReactMethod
public void requestWhenInUseAuthorization(){
Log.i(TAG, "Requesting authorization");
}
@Nullable
private static String getValidProvider(LocationManager locationManager, boolean highAccuracy) {
String provider =
highAccuracy ? LocationManager.GPS_PROVIDER : LocationManager.NETWORK_PROVIDER;
if (!locationManager.isProviderEnabled(provider)) {
provider = provider.equals(LocationManager.GPS_PROVIDER)
? LocationManager.NETWORK_PROVIDER
: LocationManager.GPS_PROVIDER;
if (!locationManager.isProviderEnabled(provider)) {
return null;
}
}
return provider;
}
private void emitError(int code, String message) {
WritableMap error = Arguments.createMap();
error.putInt("code", code);
if (message != null) {
error.putString("message", message);
}
getReactApplicationContext().getJSModule(RCTDeviceEventEmitter.class)
.emit("geolocationError", error);
}
/*
* Location Callback as called by JS
*/
@ReactMethod
public void startUpdatingLocation(ReadableMap options) {
LocationOptions locationOptions = LocationOptions.fromReactMap(options);
String provider = getValidProvider(locationManager, locationOptions.highAccuracy);
if (provider == null) {
emitError(POSITION_UNAVAILABLE, "No location provider available.");
return;
}
mLocationListener = new LocationListener(){
@Override
public void onStatusChanged(String provider,int status,Bundle extras){
WritableMap params = Arguments.createMap();
params.putString("provider", provider);
params.putInt("status", status);
sendEvent(mReactContext, "providerStatusChanged", params);
}
@Override
public void onProviderEnabled(String provider){
sendEvent(mReactContext, "providerEnabled", Arguments.createMap());
}
@Override
public void onProviderDisabled(String provider){
sendEvent(mReactContext, "providerDisabled", Arguments.createMap());
}
@Override
public void onLocationChanged(Location loc){
mLastLocation = loc;
if (mLastLocation != null) {
try {
double longitude;
double latitude;
double speed;
double altitude;
double accuracy;
double course;
// Receive Longitude / Latitude from (updated) Last Location
longitude = mLastLocation.getLongitude();
latitude = mLastLocation.getLatitude();
speed = mLastLocation.getSpeed();
altitude = mLastLocation.getAltitude();
accuracy = mLastLocation.getAccuracy();
course = mLastLocation.getBearing();
Log.i(TAG, "Got new location. Lng: " +longitude+" Lat: "+latitude);
// Create Map with Parameters to send to JS
WritableMap params = Arguments.createMap();
params.putDouble("longitude", longitude);
params.putDouble("latitude", latitude);
params.putDouble("speed", speed);
params.putDouble("altitude", altitude);
params.putDouble("accuracy", accuracy);
params.putDouble("course", course);
// Send Event to JS to update Location
sendEvent(mReactContext, "locationUpdated", params);
} catch (Exception e) {
e.printStackTrace();
Log.i(TAG, "Location services disconnected.");
}
}
}
};
locationManager.requestLocationUpdates(provider, 1000, locationOptions.distanceFilter, mLocationListener);
}
@ReactMethod
public void stopUpdatingLocation() {
try {
locationManager.removeUpdates(mLocationListener);
Log.i(TAG, "Location service disabled.");
}catch(Exception e) {
e.printStackTrace();
}
}
/*
* Internal function for communicating with JS
*/
private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) {
if (reactContext.hasActiveCatalystInstance()) {
reactContext
.getJSModule(RCTDeviceEventEmitter.class)
.emit(eventName, params);
} else {
Log.i(TAG, "Waiting for CatalystInstance...");
}
}
}
| src/main/java/com/syarul/rnlocation/RNLocationModule.java | package com.syarul.rnlocation;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.Log;
import android.os.Bundle;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter;
public class RNLocationModule extends ReactContextBaseJavaModule{
// React Class Name as called from JS
public static final String REACT_CLASS = "RNLocation";
// Unique Name for Log TAG
public static final String TAG = RNLocationModule.class.getSimpleName();
private static final float RCT_DEFAULT_LOCATION_ACCURACY = 1;
public static int POSITION_UNAVAILABLE = 2;
// Save last Location Provided
private Location mLastLocation;
private LocationListener mLocationListener;
private LocationManager locationManager;
//The React Native Context
ReactApplicationContext mReactContext;
// Constructor Method as called in Package
public RNLocationModule(ReactApplicationContext reactContext) {
super(reactContext);
// Save Context for later use
mReactContext = reactContext;
locationManager = (LocationManager) mReactContext.getSystemService(Context.LOCATION_SERVICE);
mLastLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
@Override
public String getName() {
return REACT_CLASS;
}
private static class LocationOptions {
private final long timeout;
private final double maximumAge;
private final boolean highAccuracy;
private final float distanceFilter;
private LocationOptions(
long timeout,
double maximumAge,
boolean highAccuracy,
float distanceFilter) {
this.timeout = timeout;
this.maximumAge = maximumAge;
this.highAccuracy = highAccuracy;
this.distanceFilter = distanceFilter;
}
private static LocationOptions fromReactMap(ReadableMap map) {
// precision might be dropped on timeout (double -> int conversion), but that's OK
long timeout =
map.hasKey("timeout") ? (long) map.getDouble("timeout") : Long.MAX_VALUE;
double maximumAge =
map.hasKey("maximumAge") ? map.getDouble("maximumAge") : Double.POSITIVE_INFINITY;
boolean highAccuracy = !map.hasKey("enableHighAccuracy") || map.getBoolean("enableHighAccuracy");
float distanceFilter = map.hasKey("distanceFilter") ?
(float) map.getDouble("distanceFilter") :
RCT_DEFAULT_LOCATION_ACCURACY;
return new LocationOptions(timeout, maximumAge, highAccuracy, distanceFilter);
}
}
/*
* Location permission request (Not implemented yet)
*/
@ReactMethod
public void requestWhenInUseAuthorization(){
Log.i(TAG, "Requesting authorization");
}
@Nullable
private static String getValidProvider(LocationManager locationManager, boolean highAccuracy) {
String provider =
highAccuracy ? LocationManager.GPS_PROVIDER : LocationManager.NETWORK_PROVIDER;
if (!locationManager.isProviderEnabled(provider)) {
provider = provider.equals(LocationManager.GPS_PROVIDER)
? LocationManager.NETWORK_PROVIDER
: LocationManager.GPS_PROVIDER;
if (!locationManager.isProviderEnabled(provider)) {
return null;
}
}
return provider;
}
private void emitError(int code, String message) {
WritableMap error = Arguments.createMap();
error.putInt("code", code);
if (message != null) {
error.putString("message", message);
}
getReactApplicationContext().getJSModule(RCTDeviceEventEmitter.class)
.emit("geolocationError", error);
}
/*
* Location Callback as called by JS
*/
@ReactMethod
public void startUpdatingLocation(ReadableMap options) {
LocationOptions locationOptions = LocationOptions.fromReactMap(options);
String provider = getValidProvider(locationManager, locationOptions.highAccuracy);
if (provider == null) {
emitError(POSITION_UNAVAILABLE, "No location provider available.");
return;
}
mLocationListener = new LocationListener(){
@Override
public void onStatusChanged(String provider,int status,Bundle extras){
WritableMap params = Arguments.createMap();
params.putString("provider", provider);
params.putInt("status", status);
sendEvent(mReactContext, "providerStatusChanged", params);
}
@Override
public void onProviderEnabled(String provider){
sendEvent(mReactContext, "providerEnabled", Arguments.createMap());
}
@Override
public void onProviderDisabled(String provider){
sendEvent(mReactContext, "providerDisabled", Arguments.createMap());
}
@Override
public void onLocationChanged(Location loc){
mLastLocation = loc;
if (mLastLocation != null) {
try {
double longitude;
double latitude;
double speed;
double altitude;
double accuracy;
double course;
// Receive Longitude / Latitude from (updated) Last Location
longitude = mLastLocation.getLongitude();
latitude = mLastLocation.getLatitude();
speed = mLastLocation.getSpeed();
altitude = mLastLocation.getAltitude();
accuracy = mLastLocation.getAccuracy();
course = mLastLocation.getBearing();
Log.i(TAG, "Got new location. Lng: " +longitude+" Lat: "+latitude);
// Create Map with Parameters to send to JS
WritableMap params = Arguments.createMap();
params.putDouble("longitude", longitude);
params.putDouble("latitude", latitude);
params.putDouble("speed", speed);
params.putDouble("altitude", altitude);
params.putDouble("accuracy", accuracy);
params.putDouble("course", course);
// Send Event to JS to update Location
sendEvent(mReactContext, "locationUpdated", params);
} catch (Exception e) {
e.printStackTrace();
Log.i(TAG, "Location services disconnected.");
}
}
}
};
locationManager.requestLocationUpdates(provider, 1000, locationOptions.distanceFilter, mLocationListener);
}
@ReactMethod
public void stopUpdatingLocation() {
try {
locationManager.removeUpdates(mLocationListener);
Log.i(TAG, "Location service disabled.");
}catch(Exception e) {
e.printStackTrace();
}
}
/*
* Internal function for communicating with JS
*/
private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) {
if (reactContext.hasActiveCatalystInstance()) {
reactContext
.getJSModule(RCTDeviceEventEmitter.class)
.emit(eventName, params);
} else {
Log.i(TAG, "Waiting for CatalystInstance...");
}
}
}
| -remove getLastKnownLocation from constructor
| src/main/java/com/syarul/rnlocation/RNLocationModule.java | -remove getLastKnownLocation from constructor | <ide><path>rc/main/java/com/syarul/rnlocation/RNLocationModule.java
<ide> mReactContext = reactContext;
<ide>
<ide> locationManager = (LocationManager) mReactContext.getSystemService(Context.LOCATION_SERVICE);
<del> mLastLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
<ide> }
<ide>
<ide> |
|
Java | mit | 5227acb509d5650e0b76dddcb61f1dd343fe9159 | 0 | OsuCelebrity/OsuCelebrity,RedbackThomson/OsuCelebrity | package me.reddev.osucelebrity.osu;
import static me.reddev.osucelebrity.osu.QOsuIrcUser.osuIrcUser;
import static me.reddev.osucelebrity.osu.QOsuUser.osuUser;
import static me.reddev.osucelebrity.osu.QPlayerActivity.playerActivity;
import static me.reddev.osucelebrity.osuapi.QApiUser.apiUser;
import com.querydsl.jdo.JDOQuery;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import lombok.RequiredArgsConstructor;
import me.reddev.osucelebrity.core.Clock;
import me.reddev.osucelebrity.osu.OsuIrcUser;
import me.reddev.osucelebrity.osu.OsuUser;
import me.reddev.osucelebrity.osu.PlayerActivity;
import me.reddev.osucelebrity.osuapi.ApiUser;
import me.reddev.osucelebrity.osuapi.OsuApi;
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
import org.tillerino.osuApiModel.Downloader;
import org.tillerino.osuApiModel.GameModes;
import org.tillerino.osuApiModel.OsuApiScore;
import org.tillerino.osuApiModel.OsuApiUser;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.List;
import javax.inject.Inject;
import javax.jdo.PersistenceManager;
@RequiredArgsConstructor(onConstructor = @__(@Inject))
public class OsuApiImpl implements OsuApi {
@Mapper
public interface FromApiMapper {
void update(OsuApiUser user, @MappingTarget ApiUser target);
}
private final Downloader downloader;
private final Clock clock;
@Override
public OsuUser getUser(int userid, PersistenceManager pm, long maxAge) throws IOException {
try (JDOQuery<OsuUser> query = new JDOQuery<>(pm).select(osuUser).from(osuUser)) {
final OsuUser saved = query.where(osuUser.userId.eq(userid)).fetchOne();
if (saved != null && (maxAge <= 0 || saved.getDownloaded() >= clock.getTime() - maxAge)) {
return saved;
}
try {
OsuApiUser apiUser = downloader.getUser(userid, GameModes.OSU, OsuApiUser.class);
if (apiUser == null) {
return null;
}
saveModSpecific(pm, apiUser);
if (saved == null) {
return pm.makePersistent(new OsuUser(apiUser, clock.getTime()));
}
saved.update(apiUser, clock.getTime());
return saved;
} catch (SocketTimeoutException e) {
if (saved != null) {
return saved;
}
throw e;
}
}
}
@SuppressFBWarnings("TQ")
@Override
public OsuUser getUser(String userName, PersistenceManager pm, long maxAge) throws IOException {
final OsuUser saved;
try (JDOQuery<OsuUser> query = new JDOQuery<>(pm).select(osuUser).from(osuUser)) {
saved = query.where(osuUser.userName.lower().eq(userName.toLowerCase())).fetchOne();
}
if (saved != null && (maxAge <= 0 || saved.getDownloaded() >= clock.getTime() - maxAge)) {
return saved;
}
try {
OsuApiUser apiUser = downloader.getUser(userName, GameModes.OSU, OsuApiUser.class);
if (apiUser == null) {
return null;
}
saveModSpecific(pm, apiUser);
if (saved == null) {
// check if an entry exists for a different user name
final OsuUser savedRetry;
try (JDOQuery<OsuUser> queryRetry = new JDOQuery<>(pm).select(osuUser).from(osuUser)) {
savedRetry =
queryRetry.where(osuUser.userId.eq(apiUser.getUserId()))
.fetchOne();
}
if (savedRetry != null) {
savedRetry.update(apiUser, clock.getTime());
return savedRetry;
}
return pm.makePersistent(new OsuUser(apiUser, clock.getTime()));
}
saved.update(apiUser, clock.getTime());
return saved;
} catch (SocketTimeoutException e) {
if (saved != null) {
return saved;
}
throw e;
}
}
void saveModSpecific(PersistenceManager pm, OsuApiUser downloaded) {
try (JDOQuery<ApiUser> query = new JDOQuery<>(pm).select(apiUser).from(apiUser)) {
ApiUser saved =
query.where(apiUser.userId.eq(downloaded.getUserId()),
apiUser.gameMode.eq(downloaded.getMode())).fetchOne();
if (saved == null) {
saved = new ApiUser(downloaded.getUserId(), downloaded.getMode());
new FromApiMapperImpl().update(downloaded, saved);
saved.setDownloaded(clock.getTime());
pm.makePersistent(saved);
} else {
new FromApiMapperImpl().update(downloaded, saved);
saved.setDownloaded(clock.getTime());
}
}
}
void saveGeneral(PersistenceManager pm, OsuApiUser downloaded) {
try (JDOQuery<OsuUser> query = new JDOQuery<>(pm).select(osuUser).from(osuUser)) {
OsuUser saved = query.where(osuUser.userId.eq(downloaded.getUserId())).fetchOne();
if (saved == null) {
pm.makePersistent(new OsuUser(downloaded, clock.getTime()));
} else {
saved.update(downloaded, clock.getTime());
}
}
}
@SuppressFBWarnings("TQ")
@Override
public OsuIrcUser getIrcUser(String ircUserName, PersistenceManager pm, long maxAge)
throws IOException {
try (JDOQuery<OsuIrcUser> query = new JDOQuery<>(pm).select(osuIrcUser).from(osuIrcUser)) {
OsuIrcUser saved =
query.where(osuIrcUser.ircName.lower().eq(ircUserName.toLowerCase())).fetchOne();
if (saved == null) {
OsuUser user = getUser(ircUserName, pm, maxAge);
saved = new OsuIrcUser(ircUserName, user, clock.getTime());
return pm.makePersistent(saved);
}
if (maxAge <= 0 || saved.getResolved() >= clock.getTime() - maxAge) {
return saved;
}
OsuUser user;
try {
user = getUser(ircUserName, pm, maxAge);
} catch (SocketTimeoutException e) {
return saved;
}
saved.setUser(user);
if (user == null) {
saved.setResolved(clock.getTime());
} else {
saved.setResolved(user.getDownloaded());
}
return saved;
}
}
@Override
public ApiUser getUserData(int userid, int gameMode, PersistenceManager pm, long maxAge)
throws IOException {
try (JDOQuery<ApiUser> query = new JDOQuery<>(pm).select(apiUser).from(apiUser)) {
ApiUser saved =
query.where(apiUser.userId.eq(userid), apiUser.gameMode.eq(gameMode)).fetchOne();
if (saved != null && (maxAge <= 0 || saved.getDownloaded() >= clock.getTime() - maxAge)) {
return saved;
}
try {
OsuApiUser apiUser = downloader.getUser(userid, gameMode, OsuApiUser.class);
if (apiUser == null) {
return null;
}
saveGeneral(pm, apiUser);
if (saved == null) {
saved = new ApiUser(apiUser.getUserId(), apiUser.getMode());
new FromApiMapperImpl().update(apiUser, saved);
saved.setDownloaded(clock.getTime());
pm.makePersistent(saved);
} else {
new FromApiMapperImpl().update(apiUser, saved);
saved.setDownloaded(clock.getTime());
}
return saved;
} catch (SocketTimeoutException e) {
if (saved != null) {
return saved;
}
throw e;
}
}
}
@Override
public PlayerActivity getPlayerActivity(ApiUser user, PersistenceManager pm, long maxAge)
throws IOException {
try (JDOQuery<PlayerActivity> userQuery =
new JDOQuery<PlayerActivity>(pm).select(playerActivity).from(playerActivity)
.where(playerActivity.user.eq(user))) {
PlayerActivity activity = userQuery.fetchFirst();
if (activity == null) {
activity = pm.makePersistent(new PlayerActivity(user, 0, 0));
} else if (maxAge <= 0 || activity.getLastChecked() >= clock.getTime() - maxAge) {
return activity;
}
List<OsuApiScore> userRecent =
downloader.getUserRecent(activity.getUser().getUserId(),
activity.getUser().getGameMode(), OsuApiScore.class);
activity.update(userRecent, clock.getTime());
return activity;
}
}
}
| osuCelebrity-osu/src/main/java/me/reddev/osucelebrity/osu/OsuApiImpl.java | package me.reddev.osucelebrity.osu;
import static me.reddev.osucelebrity.osu.QOsuIrcUser.osuIrcUser;
import static me.reddev.osucelebrity.osu.QOsuUser.osuUser;
import static me.reddev.osucelebrity.osu.QPlayerActivity.playerActivity;
import static me.reddev.osucelebrity.osuapi.QApiUser.apiUser;
import com.querydsl.jdo.JDOQuery;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import lombok.RequiredArgsConstructor;
import me.reddev.osucelebrity.core.Clock;
import me.reddev.osucelebrity.osu.OsuIrcUser;
import me.reddev.osucelebrity.osu.OsuUser;
import me.reddev.osucelebrity.osu.PlayerActivity;
import me.reddev.osucelebrity.osuapi.ApiUser;
import me.reddev.osucelebrity.osuapi.OsuApi;
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
import org.tillerino.osuApiModel.Downloader;
import org.tillerino.osuApiModel.GameModes;
import org.tillerino.osuApiModel.OsuApiScore;
import org.tillerino.osuApiModel.OsuApiUser;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.List;
import javax.inject.Inject;
import javax.jdo.PersistenceManager;
@RequiredArgsConstructor(onConstructor = @__(@Inject))
public class OsuApiImpl implements OsuApi {
@Mapper
public interface FromApiMapper {
void update(OsuApiUser user, @MappingTarget ApiUser target);
}
private final Downloader downloader;
private final Clock clock;
@Override
public OsuUser getUser(int userid, PersistenceManager pm, long maxAge) throws IOException {
try (JDOQuery<OsuUser> query = new JDOQuery<>(pm).select(osuUser).from(osuUser)) {
final OsuUser saved = query.where(osuUser.userId.eq(userid)).fetchOne();
if (saved != null && (maxAge <= 0 || saved.getDownloaded() >= clock.getTime() - maxAge)) {
return saved;
}
try {
OsuApiUser apiUser = downloader.getUser(userid, GameModes.OSU, OsuApiUser.class);
if (apiUser == null) {
return null;
}
saveModSpecific(pm, apiUser);
if (saved == null) {
return pm.makePersistent(new OsuUser(apiUser, clock.getTime()));
}
saved.update(apiUser, clock.getTime());
return saved;
} catch (SocketTimeoutException e) {
if (saved != null) {
return saved;
}
throw e;
}
}
}
@SuppressFBWarnings("TQ")
@Override
public OsuUser getUser(String userName, PersistenceManager pm, long maxAge) throws IOException {
final OsuUser saved;
try (JDOQuery<OsuUser> query = new JDOQuery<>(pm).select(osuUser).from(osuUser)) {
saved = query.where(osuUser.userName.lower().eq(userName.toLowerCase())).fetchOne();
}
if (saved != null && (maxAge <= 0 || saved.getDownloaded() >= clock.getTime() - maxAge)) {
return saved;
}
try {
OsuApiUser apiUser = downloader.getUser(userName, GameModes.OSU, OsuApiUser.class);
if (apiUser == null) {
return null;
}
saveModSpecific(pm, apiUser);
if (saved == null) {
if (!userName.equalsIgnoreCase(apiUser.getUserName())) {
// this might have come from irc with let's make sure to save
final OsuUser savedRetry;
try (JDOQuery<OsuUser> queryRetry = new JDOQuery<>(pm).select(osuUser).from(osuUser)) {
savedRetry =
queryRetry.where(osuUser.userName.lower().eq(apiUser.getUserName().toLowerCase()))
.fetchOne();
}
if (savedRetry != null) {
savedRetry.update(apiUser, clock.getTime());
return savedRetry;
}
}
return pm.makePersistent(new OsuUser(apiUser, clock.getTime()));
}
saved.update(apiUser, clock.getTime());
return saved;
} catch (SocketTimeoutException e) {
if (saved != null) {
return saved;
}
throw e;
}
}
void saveModSpecific(PersistenceManager pm, OsuApiUser downloaded) {
try (JDOQuery<ApiUser> query = new JDOQuery<>(pm).select(apiUser).from(apiUser)) {
ApiUser saved =
query.where(apiUser.userId.eq(downloaded.getUserId()),
apiUser.gameMode.eq(downloaded.getMode())).fetchOne();
if (saved == null) {
saved = new ApiUser(downloaded.getUserId(), downloaded.getMode());
new FromApiMapperImpl().update(downloaded, saved);
saved.setDownloaded(clock.getTime());
pm.makePersistent(saved);
} else {
new FromApiMapperImpl().update(downloaded, saved);
saved.setDownloaded(clock.getTime());
}
}
}
void saveGeneral(PersistenceManager pm, OsuApiUser downloaded) {
try (JDOQuery<OsuUser> query = new JDOQuery<>(pm).select(osuUser).from(osuUser)) {
OsuUser saved = query.where(osuUser.userId.eq(downloaded.getUserId())).fetchOne();
if (saved == null) {
pm.makePersistent(new OsuUser(downloaded, clock.getTime()));
} else {
saved.update(downloaded, clock.getTime());
}
}
}
@SuppressFBWarnings("TQ")
@Override
public OsuIrcUser getIrcUser(String ircUserName, PersistenceManager pm, long maxAge)
throws IOException {
try (JDOQuery<OsuIrcUser> query = new JDOQuery<>(pm).select(osuIrcUser).from(osuIrcUser)) {
OsuIrcUser saved =
query.where(osuIrcUser.ircName.lower().eq(ircUserName.toLowerCase())).fetchOne();
if (saved == null) {
OsuUser user = getUser(ircUserName, pm, maxAge);
saved = new OsuIrcUser(ircUserName, user, clock.getTime());
return pm.makePersistent(saved);
}
if (maxAge <= 0 || saved.getResolved() >= clock.getTime() - maxAge) {
return saved;
}
OsuUser user;
try {
user = getUser(ircUserName, pm, maxAge);
} catch (SocketTimeoutException e) {
return saved;
}
saved.setUser(user);
if (user == null) {
saved.setResolved(clock.getTime());
} else {
saved.setResolved(user.getDownloaded());
}
return saved;
}
}
@Override
public ApiUser getUserData(int userid, int gameMode, PersistenceManager pm, long maxAge)
throws IOException {
try (JDOQuery<ApiUser> query = new JDOQuery<>(pm).select(apiUser).from(apiUser)) {
ApiUser saved =
query.where(apiUser.userId.eq(userid), apiUser.gameMode.eq(gameMode)).fetchOne();
if (saved != null && (maxAge <= 0 || saved.getDownloaded() >= clock.getTime() - maxAge)) {
return saved;
}
try {
OsuApiUser apiUser = downloader.getUser(userid, gameMode, OsuApiUser.class);
if (apiUser == null) {
return null;
}
saveGeneral(pm, apiUser);
if (saved == null) {
saved = new ApiUser(apiUser.getUserId(), apiUser.getMode());
new FromApiMapperImpl().update(apiUser, saved);
saved.setDownloaded(clock.getTime());
pm.makePersistent(saved);
} else {
new FromApiMapperImpl().update(apiUser, saved);
saved.setDownloaded(clock.getTime());
}
return saved;
} catch (SocketTimeoutException e) {
if (saved != null) {
return saved;
}
throw e;
}
}
}
@Override
public PlayerActivity getPlayerActivity(ApiUser user, PersistenceManager pm, long maxAge)
throws IOException {
try (JDOQuery<PlayerActivity> userQuery =
new JDOQuery<PlayerActivity>(pm).select(playerActivity).from(playerActivity)
.where(playerActivity.user.eq(user))) {
PlayerActivity activity = userQuery.fetchFirst();
if (activity == null) {
activity = pm.makePersistent(new PlayerActivity(user, 0, 0));
} else if (maxAge <= 0 || activity.getLastChecked() >= clock.getTime() - maxAge) {
return activity;
}
List<OsuApiScore> userRecent =
downloader.getUserRecent(activity.getUser().getUserId(),
activity.getUser().getGameMode(), OsuApiScore.class);
activity.update(userRecent, clock.getTime());
return activity;
}
}
}
| Handle renamed users in osu api cache. | osuCelebrity-osu/src/main/java/me/reddev/osucelebrity/osu/OsuApiImpl.java | Handle renamed users in osu api cache. | <ide><path>suCelebrity-osu/src/main/java/me/reddev/osucelebrity/osu/OsuApiImpl.java
<ide> }
<ide> saveModSpecific(pm, apiUser);
<ide> if (saved == null) {
<del> if (!userName.equalsIgnoreCase(apiUser.getUserName())) {
<del> // this might have come from irc with let's make sure to save
<del> final OsuUser savedRetry;
<del> try (JDOQuery<OsuUser> queryRetry = new JDOQuery<>(pm).select(osuUser).from(osuUser)) {
<del> savedRetry =
<del> queryRetry.where(osuUser.userName.lower().eq(apiUser.getUserName().toLowerCase()))
<del> .fetchOne();
<del> }
<del> if (savedRetry != null) {
<del> savedRetry.update(apiUser, clock.getTime());
<del> return savedRetry;
<del> }
<add> // check if an entry exists for a different user name
<add> final OsuUser savedRetry;
<add> try (JDOQuery<OsuUser> queryRetry = new JDOQuery<>(pm).select(osuUser).from(osuUser)) {
<add> savedRetry =
<add> queryRetry.where(osuUser.userId.eq(apiUser.getUserId()))
<add> .fetchOne();
<add> }
<add> if (savedRetry != null) {
<add> savedRetry.update(apiUser, clock.getTime());
<add> return savedRetry;
<ide> }
<ide> return pm.makePersistent(new OsuUser(apiUser, clock.getTime()));
<ide> } |
|
JavaScript | mit | 55697eac6b88b4ef0b6a53d7d1949fbd9b120cae | 0 | sconover/collection_functions | CollectionFunctions = function(
user__iterator, user__nothing, user__equals,
user__newCollection, user__collectionAppender, user__isCollection) {
var factory = function(
__iterator, __nothing, __equals,
__newCollection, __collectionAppender, __isCollection,
arrayCF) {
var cost = __nothing()
var breaker = {}
function lastCost(){ return cost }
function newIterator(collection) {
return __iterator(collection)
}
function each(collection, callback) {
cost = 0
var count = 0
var iteratorInstance = newIterator(collection)
while (iteratorInstance.hasNext()) {
var item=iteratorInstance.next()
cost += 1
var result = callback(item, count)
if (result === breaker) break
count += 1
}
}
function detect(collection, matcher) {
var hit = __nothing()
each(collection, function(item, i){
if (matcher(item, i)) {
hit = item
return breaker
}
})
return hit
}
function select(collection, matcher) {
var newCollection = __newCollection()
each(collection, function(item, i){
if (matcher(item, i)) __collectionAppender(newCollection, item)
})
return newCollection
}
function map(collection, transformer, newCollectionF, appenderF) {
newCollectionF = newCollectionF || __newCollection
appenderF = appenderF || __collectionAppender
var newCollection = newCollectionF()
each(collection, function(item, i){
appenderF(newCollection, transformer(item, i))
})
return newCollection
}
function include(collection, findMe) {
var index = __nothing()
detect(collection, function(item, i){
if (__equals(item, findMe)) {
index = i
return true
}
})
return index
}
function flatten(collection) {
var newCollection = __newCollection()
each(collection, function(item){
if (__isCollection(item)) {
var itemFlattened = flatten(item)
each(itemFlattened, function(item) {
__collectionAppender(newCollection, item)
})
} else {
__collectionAppender(newCollection, item)
}
})
return newCollection
}
function concat() {
var newCollection = __newCollection()
var totalCost = 0
arrayCF.each(arguments, function(collection){
each(collection, function(item){__collectionAppender(newCollection, item)})
totalCost += cost
})
cost = totalCost
return newCollection
}
function zip() {
var lastArgument = arguments[arguments.length-1]
var callback = null
var collections = arguments
if (typeof lastArgument == "function") {
callback = lastArgument
collections = arrayCF.slice(arguments, [0,-2])
}
var iteratorInstances = arrayCF.map(collections, function(collection){return arrayCF.newIterator(collection)})
var count = 0
while (arrayCF.detect(iteratorInstances, function(iterator){return iterator.hasNext()})) {
var entry = arrayCF.map(iteratorInstances, function(iterator){
return iterator.hasNext() ? iterator.next() : __nothing()
})
callback.apply(null, entry.concat([count]))
count += 1
}
}
//
// function equals(collectionA, collectionB) {
// var notEqualEntry = detect(zip(collectionA, collectionB), function(entry, i) {
// var itemA = entry[0]
// var itemB = entry[1]
// if (!__equals(itemA, itemB)) return true
// })
// return notEqualEntry == __nothing()
// }
function size(collection) {
//efficiency later
var count = 0
each(collection, function() { count += 1 })
return count
}
function slice(collection, a, b) {
function sliceStartPlusLength(collection, startPos, length) {
var newCollection = __newCollection()
each(collection, function(item, i) {
if (i>=startPos) __collectionAppender(newCollection, item)
if (i==(startPos+length-1)) return breaker
})
return newCollection
}
function sliceRange(collection, range) {
var startPos = range[0]
var endPos = range[1]
if (startPos>=0 && endPos>=0) {
return sliceStartPlusLength(collection, startPos, endPos-startPos+1)
} else {
var theSize = size(collection)
var positiveStartPos = startPos<0 ? theSize + startPos : startPos
var positiveEndPos = endPos<0 ? theSize + endPos : endPos
return sliceRange(collection, [positiveStartPos, positiveEndPos])
}
}
if (typeof a.length != "undefined") {
var range = a
return sliceRange(collection, range)
} else {
var startPos = a
var length = b
return sliceStartPlusLength(collection, startPos, length)
}
}
function splice(mainCollection, spliceInCollection, insertAtIndex, overwriteLength) {
overwriteLength = overwriteLength || 0
return concat(slice(mainCollection, [0, insertAtIndex-1]),
spliceInCollection,
slice(mainCollection, [insertAtIndex + overwriteLength, -1]))
}
function clone(collection) {
return concat(collection)
}
function specialCurry(func, collectionFunc) {
return function() {
var args = []
for(key in arguments){args[key] = arguments[key]}
args.unshift(collectionFunc.apply(this, []))
return func.apply(null, args)
}
}
var functions = {
lastCost: lastCost,
newIterator: newIterator,
each: each,
detect: detect,
select: select,
map: map,
include: include,
flatten: flatten,
concat: concat,
slice: slice,
splice: splice,
size: size,
clone: clone,
zip: zip
}
function makeObjectStyleFunctions(collectionGetter) {
var curried = {}
for(k in functions){curried[k] = specialCurry(functions[k], collectionGetter)}
return curried
}
return {
functions:functions,
decorate: function(target){for(k in functions){target[k] = functions[k]}},
makeObjectStyleFunctions: makeObjectStyleFunctions,
decorateObjectStyle: function(target, collectionGetter){
var curriedFunctions = makeObjectStyleFunctions(collectionGetter)
for(k in curriedFunctions){target[k] = curriedFunctions[k]}
}
}
} //end factory
var arrayCFResult = function() {
var arrayIterator = function(collection){
var position = 0
return {
next: function() {
var result = collection[position]
position += 1
return result
},
hasNext: function(){return position<collection.length}
}
}
var nothing = function(){
return null
}
var doubleEquals = function(a,b){
return a == b
}
var newArray = function(){
return []
}
var arrayPush = function(array, item){
array.push(item)
}
var isArray = function(thing){
return typeof thing.length != "undefined"
}
return factory(arrayIterator, nothing, doubleEquals, newArray, arrayPush, isArray)
}()
return factory(user__iterator, user__nothing, user__equals,
user__newCollection, user__collectionAppender, user__isCollection,
arrayCFResult.functions)
} | lib/collection_functions.js | CollectionFunctions = function(
user__iterator, user__nothing, user__equals,
user__newCollection, user__collectionAppender, user__isCollection) {
var factory = function(
__iterator, __nothing, __equals,
__newCollection, __collectionAppender, __isCollection,
arrayCF) {
var cost = __nothing()
var breaker = {}
function lastCost(){ return cost }
function each(collection, callback) {
cost = 0
var count = 0
var iteratorInstance = __iterator(collection)
while (iteratorInstance.hasNext()) {
var item=iteratorInstance.next()
cost += 1
var result = callback(item, count)
if (result === breaker) break
count += 1
}
}
function detect(collection, matcher) {
var hit = __nothing()
each(collection, function(item, i){
if (matcher(item, i)) {
hit = item
return breaker
}
})
return hit
}
function select(collection, matcher) {
var newCollection = __newCollection()
each(collection, function(item, i){
if (matcher(item, i)) __collectionAppender(newCollection, item)
})
return newCollection
}
function map(collection, transformer, newCollectionF, appenderF) {
newCollectionF = newCollectionF || __newCollection
appenderF = appenderF || __collectionAppender
var newCollection = newCollectionF()
each(collection, function(item, i){
appenderF(newCollection, transformer(item, i))
})
return newCollection
}
function include(collection, findMe) {
var index = __nothing()
detect(collection, function(item, i){
if (__equals(item, findMe)) {
index = i
return true
}
})
return index
}
function flatten(collection) {
var newCollection = __newCollection()
each(collection, function(item){
if (__isCollection(item)) {
var itemFlattened = flatten(item)
each(itemFlattened, function(item) {
__collectionAppender(newCollection, item)
})
} else {
__collectionAppender(newCollection, item)
}
})
return newCollection
}
function concat() {
var newCollection = __newCollection()
var totalCost = 0
arrayCF.each(arguments, function(collection){
each(collection, function(item){__collectionAppender(newCollection, item)})
totalCost += cost
})
cost = totalCost
return newCollection
}
function zip() {
var lastArgument = arguments[arguments.length-1]
var callback = null
var iteratorArgumentLength = arguments.length
if (typeof lastArgument == "function") {
callback = lastArgument
iteratorArgumentLength = arguments.length -1
}
var iteratorInstances = []
for (var i=0; i<iteratorArgumentLength; i++) {
iteratorInstances[i] = __iterator(arguments[i])
}
var count = 0
var stillGoing = true
while (stillGoing) {
stillGoing = false
var entry = []
for (var i=0; i<iteratorInstances.length; i++) {
if (iteratorInstances[i].hasNext()) {
entry.push(iteratorInstances[i].next())
if (iteratorInstances[i].hasNext()) stillGoing = true
} else {
entry.push(__nothing())
}
}
callback.apply(null, entry.concat([count]))
count += 1
}
}
//
// function equals(collectionA, collectionB) {
// var notEqualEntry = detect(zip(collectionA, collectionB), function(entry, i) {
// var itemA = entry[0]
// var itemB = entry[1]
// if (!__equals(itemA, itemB)) return true
// })
// return notEqualEntry == __nothing()
// }
function size(collection) {
//efficiency later
var count = 0
each(collection, function() { count += 1 })
return count
}
function slice(collection, a, b) {
function sliceStartPlusLength(collection, startPos, length) {
var newCollection = __newCollection()
each(collection, function(item, i) {
if (i>=startPos) __collectionAppender(newCollection, item)
if (i==(startPos+length-1)) return breaker
})
return newCollection
}
function sliceRange(collection, range) {
var startPos = range[0]
var endPos = range[1]
if (startPos>=0 && endPos>=0) {
return sliceStartPlusLength(collection, startPos, endPos-startPos+1)
} else {
var theSize = size(collection)
var positiveStartPos = startPos<0 ? theSize + startPos : startPos
var positiveEndPos = endPos<0 ? theSize + endPos : endPos
return sliceRange(collection, [positiveStartPos, positiveEndPos])
}
}
if (typeof a.length != "undefined") {
var range = a
return sliceRange(collection, range)
} else {
var startPos = a
var length = b
return sliceStartPlusLength(collection, startPos, length)
}
}
function splice(mainCollection, spliceInCollection, insertAtIndex, overwriteLength) {
overwriteLength = overwriteLength || 0
return concat(slice(mainCollection, [0, insertAtIndex-1]),
spliceInCollection,
slice(mainCollection, [insertAtIndex + overwriteLength, -1]))
}
function clone(collection) {
return concat(collection)
}
function specialCurry(func, collectionFunc) {
return function() {
var args = []
for(key in arguments){args[key] = arguments[key]}
args.unshift(collectionFunc.apply(this, []))
return func.apply(null, args)
}
}
var functions = {
lastCost: lastCost,
each: each,
detect: detect,
select: select,
map: map,
include: include,
flatten: flatten,
concat: concat,
slice: slice,
splice: splice,
size: size,
clone: clone,
zip: zip
}
function makeObjectStyleFunctions(collectionGetter) {
var curried = {}
for(k in functions){curried[k] = specialCurry(functions[k], collectionGetter)}
return curried
}
return {
functions:functions,
decorate: function(target){for(k in functions){target[k] = functions[k]}},
makeObjectStyleFunctions: makeObjectStyleFunctions,
decorateObjectStyle: function(target, collectionGetter){
var curriedFunctions = makeObjectStyleFunctions(collectionGetter)
for(k in curriedFunctions){target[k] = curriedFunctions[k]}
}
}
} //end factory
var arrayCFResult = function() {
var arrayIterator = function(collection){
var position = 0
return {
next: function() {
var result = collection[position]
position += 1
return result
},
hasNext: function(){return position<collection.length}
}
}
var nothing = function(){
return null
}
var doubleEquals = function(a,b){
return a == b
}
var newArray = function(){
return []
}
var arrayPush = function(array, item){
array.push(item)
}
var isArray = function(thing){
return typeof thing.length != "undefined"
}
return factory(arrayIterator, nothing, doubleEquals, newArray, arrayPush, isArray)
}()
return factory(user__iterator, user__nothing, user__equals,
user__newCollection, user__collectionAppender, user__isCollection,
arrayCFResult.functions)
} | more dogfood rf
| lib/collection_functions.js | more dogfood rf | <ide><path>ib/collection_functions.js
<ide>
<ide> function lastCost(){ return cost }
<ide>
<add> function newIterator(collection) {
<add> return __iterator(collection)
<add> }
<add>
<ide> function each(collection, callback) {
<ide> cost = 0
<ide> var count = 0
<ide>
<del> var iteratorInstance = __iterator(collection)
<add> var iteratorInstance = newIterator(collection)
<ide> while (iteratorInstance.hasNext()) {
<ide> var item=iteratorInstance.next()
<ide> cost += 1
<ide> function zip() {
<ide> var lastArgument = arguments[arguments.length-1]
<ide> var callback = null
<del> var iteratorArgumentLength = arguments.length
<del>
<add> var collections = arguments
<ide> if (typeof lastArgument == "function") {
<ide> callback = lastArgument
<del> iteratorArgumentLength = arguments.length -1
<del> }
<del>
<del> var iteratorInstances = []
<del> for (var i=0; i<iteratorArgumentLength; i++) {
<del> iteratorInstances[i] = __iterator(arguments[i])
<del> }
<del>
<add> collections = arrayCF.slice(arguments, [0,-2])
<add> }
<add> var iteratorInstances = arrayCF.map(collections, function(collection){return arrayCF.newIterator(collection)})
<add>
<ide> var count = 0
<del> var stillGoing = true
<del> while (stillGoing) {
<del> stillGoing = false
<del> var entry = []
<del> for (var i=0; i<iteratorInstances.length; i++) {
<del> if (iteratorInstances[i].hasNext()) {
<del> entry.push(iteratorInstances[i].next())
<del> if (iteratorInstances[i].hasNext()) stillGoing = true
<del> } else {
<del> entry.push(__nothing())
<del> }
<del> }
<add> while (arrayCF.detect(iteratorInstances, function(iterator){return iterator.hasNext()})) {
<add> var entry = arrayCF.map(iteratorInstances, function(iterator){
<add> return iterator.hasNext() ? iterator.next() : __nothing()
<add> })
<ide> callback.apply(null, entry.concat([count]))
<ide> count += 1
<ide> }
<ide>
<ide> var functions = {
<ide> lastCost: lastCost,
<add> newIterator: newIterator,
<ide> each: each,
<ide> detect: detect,
<ide> select: select, |
|
Java | mit | c307f72989b724e81c06f7a4fba80dc2cb3da38a | 0 | InseeFr/Pogues-Back-Office,InseeFr/Pogues-Back-Office | package fr.insee.pogues.transforms;
import fr.insee.eno.GenerationService;
import fr.insee.eno.generation.DDI2FRGenerator;
import fr.insee.eno.postprocessing.NoopPostprocessor;
import fr.insee.eno.preprocessing.DDIPreprocessor;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;
@Service
public class DDIToXFormImpl implements DDIToXForm {
@Override
public void transform(InputStream input, OutputStream output, Map<String, Object> params) throws Exception {
if (null == input) {
throw new NullPointerException("Null input");
}
if (null == output) {
throw new NullPointerException("Null output");
}
try {
String xform = transform(input, params);
output.write(xform.getBytes(StandardCharsets.UTF_8));
} catch(Exception e) {
throw e;
}
}
@Override
public String transform(InputStream input, Map<String, Object> params) throws Exception {
if (null == input) {
throw new NullPointerException("Null input");
}
File enoInput = null;
try {
enoInput = File.createTempFile("eno", ".xml");
FileUtils.copyInputStreamToFile(input, enoInput);
return transform(enoInput, params);
} catch(Exception e) {
throw e;
}
}
@Override
public String transform(String input, Map<String, Object> params) throws Exception {
File enoInput = null;
if (null == input) {
throw new NullPointerException("Null input");
}
try {
enoInput = File.createTempFile("eno", ".xml");
FileUtils.writeStringToFile(enoInput, input, StandardCharsets.UTF_8);
return transform(enoInput, params);
} catch(Exception e) {
throw e;
}
}
private String transform(File file, Map<String, Object> params) throws Exception {
File output = null;
try {
GenerationService genService = new GenerationService(new DDIPreprocessor(), new DDI2FRGenerator(), new NoopPostprocessor());
output = genService.generateQuestionnaire(file,null);
String response = FileUtils.readFileToString(output, Charset.forName("UTF-8"));
return response;
} catch(Exception e){
throw e;
}
}
}
| src/main/java/fr/insee/pogues/transforms/DDIToXFormImpl.java | package fr.insee.pogues.transforms;
import fr.insee.eno.GenerationService;
import fr.insee.eno.generation.DDI2FRGenerator;
import fr.insee.eno.postprocessing.NoopPostprocessor;
import fr.insee.eno.preprocessing.DDIPreprocessor;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;
@Service
public class DDIToXFormImpl implements DDIToXForm {
@Override
public void transform(InputStream input, OutputStream output, Map<String, Object> params) throws Exception {
try {
String xform = transform(input, params);
output.write(xform.getBytes(StandardCharsets.UTF_8));
} catch(Exception e) {
throw e;
}
}
@Override
public String transform(InputStream input, Map<String, Object> params) throws Exception {
File enoInput = null;
try {
enoInput = File.createTempFile("eno", ".xml");
FileUtils.copyInputStreamToFile(input, enoInput);
return transform(enoInput, params);
} catch(Exception e) {
throw e;
}
}
@Override
public String transform(String input, Map<String, Object> params) throws Exception {
File enoInput = null;
try {
enoInput = File.createTempFile("eno", ".xml");
FileUtils.writeStringToFile(enoInput, input, StandardCharsets.UTF_8);
return transform(enoInput, params);
} catch(Exception e) {
throw e;
}
}
private String transform(File file, Map<String, Object> params) throws Exception {
File output = null;
try {
GenerationService genService = new GenerationService(new DDIPreprocessor(), new DDI2FRGenerator(), new NoopPostprocessor());
output = genService.generateQuestionnaire(file,null);
String response = FileUtils.readFileToString(output, Charset.forName("UTF-8"));
return response;
} catch(Exception e){
throw e;
}
}
}
| Add TU
| src/main/java/fr/insee/pogues/transforms/DDIToXFormImpl.java | Add TU | <ide><path>rc/main/java/fr/insee/pogues/transforms/DDIToXFormImpl.java
<ide>
<ide> @Override
<ide> public void transform(InputStream input, OutputStream output, Map<String, Object> params) throws Exception {
<add> if (null == input) {
<add> throw new NullPointerException("Null input");
<add> }
<add> if (null == output) {
<add> throw new NullPointerException("Null output");
<add> }
<ide> try {
<ide> String xform = transform(input, params);
<ide> output.write(xform.getBytes(StandardCharsets.UTF_8));
<ide>
<ide> @Override
<ide> public String transform(InputStream input, Map<String, Object> params) throws Exception {
<add> if (null == input) {
<add> throw new NullPointerException("Null input");
<add> }
<ide> File enoInput = null;
<ide> try {
<ide> enoInput = File.createTempFile("eno", ".xml");
<ide> @Override
<ide> public String transform(String input, Map<String, Object> params) throws Exception {
<ide> File enoInput = null;
<add> if (null == input) {
<add> throw new NullPointerException("Null input");
<add> }
<ide> try {
<ide> enoInput = File.createTempFile("eno", ".xml");
<ide> FileUtils.writeStringToFile(enoInput, input, StandardCharsets.UTF_8); |
|
Java | mit | cdb7f6a9827b784f2d196dba69522642945c3100 | 0 | yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods | /*
* NucleotideAlignmentConstants
*/
package net.maizegenetics.pal.alignment;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author terry
*/
public final class NucleotideAlignmentConstants {
// Byte Values for Nucleotide Alleles
public static final byte A_ALLELE = (byte) 0x0;
public static final byte C_ALLELE = (byte) 0x1;
public static final byte G_ALLELE = (byte) 0x2;
public static final byte T_ALLELE = (byte) 0x3;
public static final byte INSERT_ALLELE = (byte) 0x4;
public static final byte GAP_ALLELE = (byte) 0x5;
// Diploid Byte Values for Nucleotide Alleles
public static final byte GAP_DIPLOID_ALLELE = (byte) 0x55;
// String Values for Nucleotide Alleles
public static final String INSERT_ALLELE_STR = "+";
public static final String GAP_ALLELE_STR = "-";
public static final String UNDEFINED_ALLELE_STR = "X";
public static final byte UNDEFINED_DIPLOID_ALLELE = (byte) 0x66;
public static final String[][] NUCLEOTIDE_ALLELES = new String[][]{{"A", "C", "G", "T", "+", "-",
UNDEFINED_ALLELE_STR, UNDEFINED_ALLELE_STR, UNDEFINED_ALLELE_STR, UNDEFINED_ALLELE_STR, UNDEFINED_ALLELE_STR,
UNDEFINED_ALLELE_STR, UNDEFINED_ALLELE_STR, UNDEFINED_ALLELE_STR, Alignment.RARE_ALLELE_STR, Alignment.UNKNOWN_ALLELE_STR}};
/**
* Number of nucleotide states excluding rare and unknown.
*/
public static final int NUMBER_NUCLEOTIDE_ALLELES = 6;
private static final String QUESTION_MARK = "?";
private static final Map<String, Byte> NUCLEOTIDE_DIPLOID_HASH = new HashMap<String, Byte>();
static {
NUCLEOTIDE_DIPLOID_HASH.put("AA", (byte) 0x00);
NUCLEOTIDE_DIPLOID_HASH.put("AC", (byte) 0x01);
NUCLEOTIDE_DIPLOID_HASH.put("AG", (byte) 0x02);
NUCLEOTIDE_DIPLOID_HASH.put("AT", (byte) 0x03);
NUCLEOTIDE_DIPLOID_HASH.put("A+", (byte) 0x04);
NUCLEOTIDE_DIPLOID_HASH.put("A-", (byte) 0x05);
NUCLEOTIDE_DIPLOID_HASH.put("AN", (byte) 0x0F);
NUCLEOTIDE_DIPLOID_HASH.put("AX", (byte) 0x0F);
NUCLEOTIDE_DIPLOID_HASH.put("AZ", (byte) 0x0E);
NUCLEOTIDE_DIPLOID_HASH.put("CA", (byte) 0x10);
NUCLEOTIDE_DIPLOID_HASH.put("CC", (byte) 0x11);
NUCLEOTIDE_DIPLOID_HASH.put("CG", (byte) 0x12);
NUCLEOTIDE_DIPLOID_HASH.put("CT", (byte) 0x13);
NUCLEOTIDE_DIPLOID_HASH.put("C+", (byte) 0x14);
NUCLEOTIDE_DIPLOID_HASH.put("C-", (byte) 0x15);
NUCLEOTIDE_DIPLOID_HASH.put("CN", (byte) 0x1F);
NUCLEOTIDE_DIPLOID_HASH.put("CX", (byte) 0x1F);
NUCLEOTIDE_DIPLOID_HASH.put("CZ", (byte) 0x1E);
NUCLEOTIDE_DIPLOID_HASH.put("GA", (byte) 0x20);
NUCLEOTIDE_DIPLOID_HASH.put("GC", (byte) 0x21);
NUCLEOTIDE_DIPLOID_HASH.put("GG", (byte) 0x22);
NUCLEOTIDE_DIPLOID_HASH.put("GT", (byte) 0x23);
NUCLEOTIDE_DIPLOID_HASH.put("G+", (byte) 0x24);
NUCLEOTIDE_DIPLOID_HASH.put("G-", (byte) 0x25);
NUCLEOTIDE_DIPLOID_HASH.put("GN", (byte) 0x2F);
NUCLEOTIDE_DIPLOID_HASH.put("GX", (byte) 0x2F);
NUCLEOTIDE_DIPLOID_HASH.put("GZ", (byte) 0x2E);
NUCLEOTIDE_DIPLOID_HASH.put("TA", (byte) 0x30);
NUCLEOTIDE_DIPLOID_HASH.put("TC", (byte) 0x31);
NUCLEOTIDE_DIPLOID_HASH.put("TG", (byte) 0x32);
NUCLEOTIDE_DIPLOID_HASH.put("TT", (byte) 0x33);
NUCLEOTIDE_DIPLOID_HASH.put("T+", (byte) 0x34);
NUCLEOTIDE_DIPLOID_HASH.put("T-", (byte) 0x35);
NUCLEOTIDE_DIPLOID_HASH.put("TN", (byte) 0x3F);
NUCLEOTIDE_DIPLOID_HASH.put("TX", (byte) 0x3F);
NUCLEOTIDE_DIPLOID_HASH.put("TZ", (byte) 0x3E);
NUCLEOTIDE_DIPLOID_HASH.put("+A", (byte) 0x40);
NUCLEOTIDE_DIPLOID_HASH.put("+C", (byte) 0x41);
NUCLEOTIDE_DIPLOID_HASH.put("+G", (byte) 0x42);
NUCLEOTIDE_DIPLOID_HASH.put("+T", (byte) 0x43);
NUCLEOTIDE_DIPLOID_HASH.put("++", (byte) 0x44);
NUCLEOTIDE_DIPLOID_HASH.put("+-", (byte) 0x45);
NUCLEOTIDE_DIPLOID_HASH.put("+N", (byte) 0x4F);
NUCLEOTIDE_DIPLOID_HASH.put("+X", (byte) 0x4F);
NUCLEOTIDE_DIPLOID_HASH.put("+Z", (byte) 0x4E);
NUCLEOTIDE_DIPLOID_HASH.put("-A", (byte) 0x50);
NUCLEOTIDE_DIPLOID_HASH.put("-C", (byte) 0x51);
NUCLEOTIDE_DIPLOID_HASH.put("-G", (byte) 0x52);
NUCLEOTIDE_DIPLOID_HASH.put("-T", (byte) 0x53);
NUCLEOTIDE_DIPLOID_HASH.put("-+", (byte) 0x54);
NUCLEOTIDE_DIPLOID_HASH.put("--", (byte) 0x55);
NUCLEOTIDE_DIPLOID_HASH.put("-N", (byte) 0x5F);
NUCLEOTIDE_DIPLOID_HASH.put("-X", (byte) 0x5F);
NUCLEOTIDE_DIPLOID_HASH.put("-Z", (byte) 0x5E);
NUCLEOTIDE_DIPLOID_HASH.put("NA", (byte) 0xF0);
NUCLEOTIDE_DIPLOID_HASH.put("NC", (byte) 0xF1);
NUCLEOTIDE_DIPLOID_HASH.put("NG", (byte) 0xF2);
NUCLEOTIDE_DIPLOID_HASH.put("NT", (byte) 0xF3);
NUCLEOTIDE_DIPLOID_HASH.put("N+", (byte) 0xF4);
NUCLEOTIDE_DIPLOID_HASH.put("N-", (byte) 0xF5);
NUCLEOTIDE_DIPLOID_HASH.put("NN", (byte) 0xFF);
NUCLEOTIDE_DIPLOID_HASH.put("NX", (byte) 0xFF);
NUCLEOTIDE_DIPLOID_HASH.put("NZ", (byte) 0xFE);
NUCLEOTIDE_DIPLOID_HASH.put("XA", (byte) 0xF0);
NUCLEOTIDE_DIPLOID_HASH.put("XC", (byte) 0xF1);
NUCLEOTIDE_DIPLOID_HASH.put("XG", (byte) 0xF2);
NUCLEOTIDE_DIPLOID_HASH.put("XT", (byte) 0xF3);
NUCLEOTIDE_DIPLOID_HASH.put("X+", (byte) 0xF4);
NUCLEOTIDE_DIPLOID_HASH.put("X-", (byte) 0xF5);
NUCLEOTIDE_DIPLOID_HASH.put("XN", (byte) 0xFF);
NUCLEOTIDE_DIPLOID_HASH.put("XX", (byte) 0xFF);
NUCLEOTIDE_DIPLOID_HASH.put("XZ", (byte) 0xFE);
NUCLEOTIDE_DIPLOID_HASH.put("ZA", (byte) 0xE0);
NUCLEOTIDE_DIPLOID_HASH.put("ZC", (byte) 0xE1);
NUCLEOTIDE_DIPLOID_HASH.put("ZG", (byte) 0xE2);
NUCLEOTIDE_DIPLOID_HASH.put("ZT", (byte) 0xE3);
NUCLEOTIDE_DIPLOID_HASH.put("Z+", (byte) 0xE4);
NUCLEOTIDE_DIPLOID_HASH.put("Z-", (byte) 0xE5);
NUCLEOTIDE_DIPLOID_HASH.put("ZN", (byte) 0xEF);
NUCLEOTIDE_DIPLOID_HASH.put("ZX", (byte) 0xEF);
NUCLEOTIDE_DIPLOID_HASH.put("ZZ", (byte) 0xEE);
NUCLEOTIDE_DIPLOID_HASH.put("A", (byte) 0x00); // AA
NUCLEOTIDE_DIPLOID_HASH.put("C", (byte) 0x11); // CC
NUCLEOTIDE_DIPLOID_HASH.put("G", (byte) 0x22); // GG
NUCLEOTIDE_DIPLOID_HASH.put("T", (byte) 0x33); // TT
NUCLEOTIDE_DIPLOID_HASH.put("+", (byte) 0x44); // ++
NUCLEOTIDE_DIPLOID_HASH.put("-", (byte) 0x55); // --
NUCLEOTIDE_DIPLOID_HASH.put("Z", (byte) 0xEE); // ZZ
NUCLEOTIDE_DIPLOID_HASH.put("N", (byte) 0xFF); // NN
NUCLEOTIDE_DIPLOID_HASH.put("X", (byte) 0xFF); // NN
NUCLEOTIDE_DIPLOID_HASH.put("R", (byte) 0x02); // AG
NUCLEOTIDE_DIPLOID_HASH.put("Y", (byte) 0x13); // CT
NUCLEOTIDE_DIPLOID_HASH.put("S", (byte) 0x21); // GC
NUCLEOTIDE_DIPLOID_HASH.put("W", (byte) 0x03); // AT
NUCLEOTIDE_DIPLOID_HASH.put("K", (byte) 0x23); // GT
NUCLEOTIDE_DIPLOID_HASH.put("M", (byte) 0x01); // AC
NUCLEOTIDE_DIPLOID_HASH.put("0", (byte) 0x54); // -+
}
private static final byte[] NUCLEOTIDE_DIPLOID_ARRAY = new byte[256];
static {
Arrays.fill(NUCLEOTIDE_DIPLOID_ARRAY, UNDEFINED_DIPLOID_ALLELE);
for (String temp : NUCLEOTIDE_DIPLOID_HASH.keySet()) {
NUCLEOTIDE_DIPLOID_ARRAY[getNucleotideDiploidArrayIndex(temp)] = NUCLEOTIDE_DIPLOID_HASH.get(temp);
}
}
private static final int mask = 0x2F;
private static final int mask2 = 0x81;
private static final int shift = 2;
private static int getNucleotideDiploidArrayIndex(String str) {
if (str.length() == 1) {
return str.charAt(0);
} else if (str.length() == 2) {
return ((((str.charAt(1) << shift) ^ (byte) mask2)) ^ (str.charAt(0) & (byte) mask)) & 0xFF;
} else {
throw new IllegalStateException("NucleotideAlignmentConstants: getIndex: str length: " + str.length());
}
}
public static final Map<Byte, String> NUCLEOTIDE_IUPAC_HASH = new HashMap<Byte, String>();
static {
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x00, "A"); // AA
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x01, "M"); // AC
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x02, "R"); // AG
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x03, "W"); // AT
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x04, "0"); // A+
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x05, "0"); // A-
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x0E, "A"); // AZ
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x0F, "A"); // AN
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x10, "M"); // CA
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x11, "C"); // CC
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x12, "S"); // CG
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x13, "Y"); // CT
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x14, "0"); // C+
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x15, "0"); // C-
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x1E, "C"); // CZ
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x1F, "C"); // CN
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x20, "R"); // GA
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x21, "S"); // GC
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x22, "G"); // GG
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x23, "K"); // GT
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x24, "0"); // G+
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x25, "0"); // G-
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x2E, "G"); // GZ
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x2F, "G"); // GN
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x30, "W"); // TA
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x31, "Y"); // TC
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x32, "K"); // TG
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x33, "T"); // TT
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x34, "0"); // T+
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x35, "0"); // T-
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x3E, "T"); // TZ
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x3F, "T"); // TN
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x40, "0"); // +A
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x41, "0"); // +C
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x42, "0"); // +G
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x43, "0"); // +T
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x44, "+"); // ++
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x45, "0"); // +-
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x4E, "+"); // +Z
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x4F, "+"); // +N
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x50, "0"); // -A
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x51, "0"); // -C
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x52, "0"); // -G
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x53, "0"); // -T
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x54, "0"); // -+
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x55, "-"); // --
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x5E, "-"); // -Z
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x5F, "-"); // -N
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xE0, "A"); // ZA
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xE1, "C"); // ZC
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xE2, "G"); // ZG
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xE3, "T"); // ZT
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xE4, "+"); // Z+
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xE5, "-"); // Z-
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xEE, "Z"); // ZZ
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xEF, "N"); // ZN
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xF0, "A"); // NA
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xF1, "C"); // NC
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xF2, "G"); // NG
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xF3, "T"); // NT
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xF4, "+"); // N+
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xF5, "-"); // N-
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xFE, "N"); // NZ
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xFF, "N"); // NN
}
private static final String[] NUCLEOTIDE_IUPAC_ARRAY = new String[256];
static {
Arrays.fill(NUCLEOTIDE_IUPAC_ARRAY, null);
for (Byte temp : NUCLEOTIDE_IUPAC_HASH.keySet()) {
NUCLEOTIDE_IUPAC_ARRAY[temp & 0xFF] = NUCLEOTIDE_IUPAC_HASH.get(temp);
}
}
private static final Map<String, Byte> NUCLEOTIDE_ALLELE_HASH = new HashMap<String, Byte>();
static {
NUCLEOTIDE_ALLELE_HASH.put("A", A_ALLELE); // A
NUCLEOTIDE_ALLELE_HASH.put("C", C_ALLELE); // C
NUCLEOTIDE_ALLELE_HASH.put("G", G_ALLELE); // G
NUCLEOTIDE_ALLELE_HASH.put("T", T_ALLELE); // T
NUCLEOTIDE_ALLELE_HASH.put("+", INSERT_ALLELE); // +
NUCLEOTIDE_ALLELE_HASH.put("-", GAP_ALLELE); // -
NUCLEOTIDE_ALLELE_HASH.put("N", Alignment.UNKNOWN_ALLELE); // N
}
private NucleotideAlignmentConstants() {
// do not instantiate
}
/**
* Returns diploid byte value for given nucleotide value. First four bits
* contain first allele value. And second four bits contain second allele
* value.
*
* @param value diploid allele value
*
* @return nucleotide diploid allele byte value
*/
public static byte getNucleotideDiploidByte(String value) {
try {
return NUCLEOTIDE_DIPLOID_ARRAY[getNucleotideDiploidArrayIndex(value)];
// return NUCLEOTIDE_DIPLOID_HASH.get(value).byteValue();
} catch (NullPointerException e) {
throw new IllegalArgumentException("NucleotideAlignmentConstants: getNucleotideDiploidByte: unknown allele value: " + value);
}
}
/**
* Returns haploid byte value for given nucleotide value. Only right-most
* four bits used.
*
* @param value haploid allele value
*
* @return nucleotide haploid allele byte value
*/
public static byte getNucleotideAlleleByte(String value) {
try {
return NUCLEOTIDE_ALLELE_HASH.get(value).byteValue();
} catch (NullPointerException e) {
throw new IllegalArgumentException("NucleotideAlignmentConstants: getNucleotideAlleleByte: unknown allele value: " + value);
}
}
/**
* Returns diploid byte value for given nucleotide value. First four bits
* contain first allele value. And second four bits contain second allele
* value.
*
* @param value diploid allele value
*
* @return nucleotide diploid allele byte value
*/
public static byte getNucleotideDiploidByte(char value) {
try {
return NUCLEOTIDE_DIPLOID_ARRAY[value];
// return NUCLEOTIDE_DIPLOID_HASH.get(String.valueOf(value)).byteValue();
} catch (NullPointerException e) {
throw new IllegalArgumentException("NucleotideAlignmentConstants: getNucleotideDiploidByte: unknown allele value: " + value);
}
}
/**
* Returns the IUPAC String for the given diploid allele value.
*
* @param value diploid allele value
*
* @return IUPAC String
*/
public static String getNucleotideIUPAC(byte value) {
try {
String result = NUCLEOTIDE_IUPAC_ARRAY[value & 0xFF];
if (result == null) {
return QUESTION_MARK;
} else {
return result;
}
} catch (NullPointerException e) {
return QUESTION_MARK;
}
}
/**
* Returns the Nucleotide String for the given haploid allele value.
*
* @param value haploid value
*
* @return Nucleotide String
*/
public static String getHaplotypeNucleotide(byte value) {
return NUCLEOTIDE_ALLELES[0][value];
}
/**
* Returns the Nucleotide Complement of given byte encoded nucleotide. A
* returns T. T returns A. C returns G. G returns C. Otherwise given
* nucleotide is returned.
*
* @param nucleotide nucleotide byte value
*
* @return Nucleotide Complement
*/
public static byte getNucleotideComplement(byte nucleotide) {
if (nucleotide == A_ALLELE) {
return T_ALLELE;
} else if (nucleotide == T_ALLELE) {
return A_ALLELE;
} else if (nucleotide == C_ALLELE) {
return G_ALLELE;
} else if (nucleotide == G_ALLELE) {
return C_ALLELE;
} else {
return nucleotide;
}
}
/**
* Returns the Nucleotide Complement of the given diploid byte encoded
* alleles.
*
* @param diploidAllele diploid allele value
*
* @return Nucleotide Complement
*/
public static byte getNucleotideDiploidComplement(byte diploidAllele) {
byte first = (byte) ((diploidAllele >>> 4) & 0xf);
byte second = (byte) (diploidAllele & 0xf);
first = getNucleotideComplement(first);
second = getNucleotideComplement(second);
return (byte) ((first << 4) | second);
}
/**
* Returns whether given allele encodings are for Nucleotide Data.
*
* @param alleleStates allele encodings
*
* @return true if nucleotide encodings
*/
public static boolean isNucleotideEncodings(String[][] alleleStates) {
boolean isNucleotide = false;
if (alleleStates.length == 1) {
isNucleotide = true;
if (alleleStates[0].length == NucleotideAlignmentConstants.NUCLEOTIDE_ALLELES[0].length) {
for (int i = 0; i < alleleStates.length; i++) {
if (!alleleStates[0][i].equals(NucleotideAlignmentConstants.NUCLEOTIDE_ALLELES[0][i])) {
isNucleotide = false;
}
}
}
}
return isNucleotide;
}
}
| src/net/maizegenetics/pal/alignment/NucleotideAlignmentConstants.java | /*
* NucleotideAlignmentConstants
*/
package net.maizegenetics.pal.alignment;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author terry
*/
public final class NucleotideAlignmentConstants {
// Byte Values for Nucleotide Alleles
public static final byte A_ALLELE = (byte) 0x0;
public static final byte C_ALLELE = (byte) 0x1;
public static final byte G_ALLELE = (byte) 0x2;
public static final byte T_ALLELE = (byte) 0x3;
public static final byte INSERT_ALLELE = (byte) 0x4;
public static final byte GAP_ALLELE = (byte) 0x5;
// Diploid Byte Values for Nucleotide Alleles
public static final byte GAP_DIPLOID_ALLELE = (byte) 0x55;
// String Values for Nucleotide Alleles
public static final String INSERT_ALLELE_STR = "+";
public static final String GAP_ALLELE_STR = "-";
public static final String UNDEFINED_ALLELE_STR = "X";
public static final byte UNDEFINED_DIPLOID_ALLELE = (byte) 0x66;
public static final String[][] NUCLEOTIDE_ALLELES = new String[][]{{"A", "C", "G", "T", "+", "-",
UNDEFINED_ALLELE_STR, UNDEFINED_ALLELE_STR, UNDEFINED_ALLELE_STR, UNDEFINED_ALLELE_STR, UNDEFINED_ALLELE_STR,
UNDEFINED_ALLELE_STR, UNDEFINED_ALLELE_STR, UNDEFINED_ALLELE_STR, Alignment.RARE_ALLELE_STR, Alignment.UNKNOWN_ALLELE_STR}};
/**
* Number of nucleotide states excluding rare and unknown.
*/
public static final int NUMBER_NUCLEOTIDE_ALLELES = 6;
private static final String QUESTION_MARK = "?";
private static final Map<String, Byte> NUCLEOTIDE_DIPLOID_HASH = new HashMap<String, Byte>();
static {
NUCLEOTIDE_DIPLOID_HASH.put("AA", (byte) 0x00);
NUCLEOTIDE_DIPLOID_HASH.put("AC", (byte) 0x01);
NUCLEOTIDE_DIPLOID_HASH.put("AG", (byte) 0x02);
NUCLEOTIDE_DIPLOID_HASH.put("AT", (byte) 0x03);
NUCLEOTIDE_DIPLOID_HASH.put("A+", (byte) 0x04);
NUCLEOTIDE_DIPLOID_HASH.put("A-", (byte) 0x05);
NUCLEOTIDE_DIPLOID_HASH.put("AN", (byte) 0x0F);
NUCLEOTIDE_DIPLOID_HASH.put("AX", (byte) 0x0F);
NUCLEOTIDE_DIPLOID_HASH.put("AZ", (byte) 0x0E);
NUCLEOTIDE_DIPLOID_HASH.put("CA", (byte) 0x10);
NUCLEOTIDE_DIPLOID_HASH.put("CC", (byte) 0x11);
NUCLEOTIDE_DIPLOID_HASH.put("CG", (byte) 0x12);
NUCLEOTIDE_DIPLOID_HASH.put("CT", (byte) 0x13);
NUCLEOTIDE_DIPLOID_HASH.put("C+", (byte) 0x14);
NUCLEOTIDE_DIPLOID_HASH.put("C-", (byte) 0x15);
NUCLEOTIDE_DIPLOID_HASH.put("CN", (byte) 0x1F);
NUCLEOTIDE_DIPLOID_HASH.put("CX", (byte) 0x1F);
NUCLEOTIDE_DIPLOID_HASH.put("CZ", (byte) 0x1E);
NUCLEOTIDE_DIPLOID_HASH.put("GA", (byte) 0x20);
NUCLEOTIDE_DIPLOID_HASH.put("GC", (byte) 0x21);
NUCLEOTIDE_DIPLOID_HASH.put("GG", (byte) 0x22);
NUCLEOTIDE_DIPLOID_HASH.put("GT", (byte) 0x23);
NUCLEOTIDE_DIPLOID_HASH.put("G+", (byte) 0x24);
NUCLEOTIDE_DIPLOID_HASH.put("G-", (byte) 0x25);
NUCLEOTIDE_DIPLOID_HASH.put("GN", (byte) 0x2F);
NUCLEOTIDE_DIPLOID_HASH.put("GX", (byte) 0x2F);
NUCLEOTIDE_DIPLOID_HASH.put("GZ", (byte) 0x2E);
NUCLEOTIDE_DIPLOID_HASH.put("TA", (byte) 0x30);
NUCLEOTIDE_DIPLOID_HASH.put("TC", (byte) 0x31);
NUCLEOTIDE_DIPLOID_HASH.put("TG", (byte) 0x32);
NUCLEOTIDE_DIPLOID_HASH.put("TT", (byte) 0x33);
NUCLEOTIDE_DIPLOID_HASH.put("T+", (byte) 0x34);
NUCLEOTIDE_DIPLOID_HASH.put("T-", (byte) 0x35);
NUCLEOTIDE_DIPLOID_HASH.put("TN", (byte) 0x3F);
NUCLEOTIDE_DIPLOID_HASH.put("TX", (byte) 0x3F);
NUCLEOTIDE_DIPLOID_HASH.put("TZ", (byte) 0x3E);
NUCLEOTIDE_DIPLOID_HASH.put("+A", (byte) 0x40);
NUCLEOTIDE_DIPLOID_HASH.put("+C", (byte) 0x41);
NUCLEOTIDE_DIPLOID_HASH.put("+G", (byte) 0x42);
NUCLEOTIDE_DIPLOID_HASH.put("+T", (byte) 0x43);
NUCLEOTIDE_DIPLOID_HASH.put("++", (byte) 0x44);
NUCLEOTIDE_DIPLOID_HASH.put("+-", (byte) 0x45);
NUCLEOTIDE_DIPLOID_HASH.put("+N", (byte) 0x4F);
NUCLEOTIDE_DIPLOID_HASH.put("+X", (byte) 0x4F);
NUCLEOTIDE_DIPLOID_HASH.put("+Z", (byte) 0x4E);
NUCLEOTIDE_DIPLOID_HASH.put("-A", (byte) 0x50);
NUCLEOTIDE_DIPLOID_HASH.put("-C", (byte) 0x51);
NUCLEOTIDE_DIPLOID_HASH.put("-G", (byte) 0x52);
NUCLEOTIDE_DIPLOID_HASH.put("-T", (byte) 0x53);
NUCLEOTIDE_DIPLOID_HASH.put("-+", (byte) 0x54);
NUCLEOTIDE_DIPLOID_HASH.put("--", (byte) 0x55);
NUCLEOTIDE_DIPLOID_HASH.put("-N", (byte) 0x5F);
NUCLEOTIDE_DIPLOID_HASH.put("-X", (byte) 0x5F);
NUCLEOTIDE_DIPLOID_HASH.put("-Z", (byte) 0x5E);
NUCLEOTIDE_DIPLOID_HASH.put("NA", (byte) 0xF0);
NUCLEOTIDE_DIPLOID_HASH.put("NC", (byte) 0xF1);
NUCLEOTIDE_DIPLOID_HASH.put("NG", (byte) 0xF2);
NUCLEOTIDE_DIPLOID_HASH.put("NT", (byte) 0xF3);
NUCLEOTIDE_DIPLOID_HASH.put("N+", (byte) 0xF4);
NUCLEOTIDE_DIPLOID_HASH.put("N-", (byte) 0xF5);
NUCLEOTIDE_DIPLOID_HASH.put("NN", (byte) 0xFF);
NUCLEOTIDE_DIPLOID_HASH.put("NX", (byte) 0xFF);
NUCLEOTIDE_DIPLOID_HASH.put("NZ", (byte) 0xFE);
NUCLEOTIDE_DIPLOID_HASH.put("XA", (byte) 0xF0);
NUCLEOTIDE_DIPLOID_HASH.put("XC", (byte) 0xF1);
NUCLEOTIDE_DIPLOID_HASH.put("XG", (byte) 0xF2);
NUCLEOTIDE_DIPLOID_HASH.put("XT", (byte) 0xF3);
NUCLEOTIDE_DIPLOID_HASH.put("X+", (byte) 0xF4);
NUCLEOTIDE_DIPLOID_HASH.put("X-", (byte) 0xF5);
NUCLEOTIDE_DIPLOID_HASH.put("XN", (byte) 0xFF);
NUCLEOTIDE_DIPLOID_HASH.put("XX", (byte) 0xFF);
NUCLEOTIDE_DIPLOID_HASH.put("XZ", (byte) 0xFE);
NUCLEOTIDE_DIPLOID_HASH.put("ZA", (byte) 0xE0);
NUCLEOTIDE_DIPLOID_HASH.put("ZC", (byte) 0xE1);
NUCLEOTIDE_DIPLOID_HASH.put("ZG", (byte) 0xE2);
NUCLEOTIDE_DIPLOID_HASH.put("ZT", (byte) 0xE3);
NUCLEOTIDE_DIPLOID_HASH.put("Z+", (byte) 0xE4);
NUCLEOTIDE_DIPLOID_HASH.put("Z-", (byte) 0xE5);
NUCLEOTIDE_DIPLOID_HASH.put("ZN", (byte) 0xEF);
NUCLEOTIDE_DIPLOID_HASH.put("ZX", (byte) 0xEF);
NUCLEOTIDE_DIPLOID_HASH.put("ZZ", (byte) 0xEE);
NUCLEOTIDE_DIPLOID_HASH.put("A", (byte) 0x00); // AA
NUCLEOTIDE_DIPLOID_HASH.put("C", (byte) 0x11); // CC
NUCLEOTIDE_DIPLOID_HASH.put("G", (byte) 0x22); // GG
NUCLEOTIDE_DIPLOID_HASH.put("T", (byte) 0x33); // TT
NUCLEOTIDE_DIPLOID_HASH.put("+", (byte) 0x44); // ++
NUCLEOTIDE_DIPLOID_HASH.put("-", (byte) 0x55); // --
NUCLEOTIDE_DIPLOID_HASH.put("Z", (byte) 0xEE); // ZZ
NUCLEOTIDE_DIPLOID_HASH.put("N", (byte) 0xFF); // NN
NUCLEOTIDE_DIPLOID_HASH.put("X", (byte) 0xFF); // NN
NUCLEOTIDE_DIPLOID_HASH.put("R", (byte) 0x02); // AG
NUCLEOTIDE_DIPLOID_HASH.put("Y", (byte) 0x13); // CT
NUCLEOTIDE_DIPLOID_HASH.put("S", (byte) 0x21); // GC
NUCLEOTIDE_DIPLOID_HASH.put("W", (byte) 0x03); // AT
NUCLEOTIDE_DIPLOID_HASH.put("K", (byte) 0x23); // GT
NUCLEOTIDE_DIPLOID_HASH.put("M", (byte) 0x01); // AC
NUCLEOTIDE_DIPLOID_HASH.put("0", (byte) 0x54); // -+
}
private static final byte[] NUCLEOTIDE_DIPLOID_ARRAY = new byte[256];
static {
Arrays.fill(NUCLEOTIDE_DIPLOID_ARRAY, UNDEFINED_DIPLOID_ALLELE);
for (String temp : NUCLEOTIDE_DIPLOID_HASH.keySet()) {
NUCLEOTIDE_DIPLOID_ARRAY[getNucleotideDiploidArrayIndex(temp)] = NUCLEOTIDE_DIPLOID_HASH.get(temp);
}
}
private static final int mask = 0x2F;
private static final int mask2 = 0x81;
private static final int shift = 2;
private static int getNucleotideDiploidArrayIndex(String str) {
if (str.length() == 1) {
return str.charAt(0);
} else if (str.length() == 2) {
return ((((str.charAt(1) << shift) ^ (byte) mask2)) ^ (str.charAt(0) & (byte) mask)) & 0xFF;
} else {
throw new IllegalStateException("NucleotideAlignmentConstants: getIndex: str length: " + str.length());
}
}
public static final Map<Byte, String> NUCLEOTIDE_IUPAC_HASH = new HashMap<Byte, String>();
static {
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x00, "A"); // AA
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x01, "M"); // AC
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x02, "R"); // AG
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x03, "W"); // AT
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x04, "0"); // A+
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x05, "0"); // A-
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x0E, "A"); // AZ
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x0F, "A"); // AN
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x10, "M"); // CA
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x11, "C"); // CC
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x12, "S"); // CG
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x13, "Y"); // CT
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x14, "0"); // C+
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x15, "0"); // C-
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x1E, "C"); // CZ
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x1F, "C"); // CN
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x20, "R"); // GA
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x21, "S"); // GC
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x22, "G"); // GG
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x23, "K"); // GT
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x24, "0"); // G+
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x25, "0"); // G-
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x2E, "G"); // GZ
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x2F, "G"); // GN
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x30, "W"); // TA
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x31, "Y"); // TC
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x32, "K"); // TG
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x33, "T"); // TT
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x34, "0"); // T+
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x35, "0"); // T-
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x3E, "T"); // TZ
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x3F, "T"); // TN
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x40, "0"); // +A
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x41, "0"); // +C
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x42, "0"); // +G
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x43, "0"); // +T
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x44, "+"); // ++
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x45, "0"); // +-
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x4E, "+"); // +Z
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x4F, "+"); // +N
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x50, "0"); // -A
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x51, "0"); // -C
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x52, "0"); // -G
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x53, "0"); // -T
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x54, "0"); // -+
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x55, "-"); // --
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x5E, "-"); // -Z
NUCLEOTIDE_IUPAC_HASH.put((byte) 0x5F, "-"); // -N
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xE0, "A"); // ZA
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xE1, "C"); // ZC
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xE2, "G"); // ZG
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xE3, "T"); // ZT
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xE4, "+"); // Z+
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xE5, "-"); // Z-
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xEE, "Z"); // ZZ
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xEF, "N"); // ZN
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xF0, "A"); // NA
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xF1, "C"); // NC
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xF2, "G"); // NG
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xF3, "T"); // NT
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xF4, "+"); // N+
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xF5, "-"); // N-
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xFE, "N"); // NZ
NUCLEOTIDE_IUPAC_HASH.put((byte) 0xFF, "N"); // NN
}
private static final Map<String, Byte> NUCLEOTIDE_ALLELE_HASH = new HashMap<String, Byte>();
static {
NUCLEOTIDE_ALLELE_HASH.put("A", A_ALLELE); // A
NUCLEOTIDE_ALLELE_HASH.put("C", C_ALLELE); // C
NUCLEOTIDE_ALLELE_HASH.put("G", G_ALLELE); // G
NUCLEOTIDE_ALLELE_HASH.put("T", T_ALLELE); // T
NUCLEOTIDE_ALLELE_HASH.put("+", INSERT_ALLELE); // +
NUCLEOTIDE_ALLELE_HASH.put("-", GAP_ALLELE); // -
NUCLEOTIDE_ALLELE_HASH.put("N", Alignment.UNKNOWN_ALLELE); // N
}
private NucleotideAlignmentConstants() {
// do not instantiate
}
/**
* Returns diploid byte value for given nucleotide value. First four bits
* contain first allele value. And second four bits contain second allele
* value.
*
* @param value diploid allele value
*
* @return nucleotide diploid allele byte value
*/
public static byte getNucleotideDiploidByte(String value) {
try {
return NUCLEOTIDE_DIPLOID_ARRAY[getNucleotideDiploidArrayIndex(value)];
// return NUCLEOTIDE_DIPLOID_HASH.get(value).byteValue();
} catch (NullPointerException e) {
throw new IllegalArgumentException("NucleotideAlignmentConstants: getNucleotideDiploidByte: unknown allele value: " + value);
}
}
/**
* Returns haploid byte value for given nucleotide value. Only right-most
* four bits used.
*
* @param value haploid allele value
*
* @return nucleotide haploid allele byte value
*/
public static byte getNucleotideAlleleByte(String value) {
try {
return NUCLEOTIDE_ALLELE_HASH.get(value).byteValue();
} catch (NullPointerException e) {
throw new IllegalArgumentException("NucleotideAlignmentConstants: getNucleotideAlleleByte: unknown allele value: " + value);
}
}
/**
* Returns diploid byte value for given nucleotide value. First four bits
* contain first allele value. And second four bits contain second allele
* value.
*
* @param value diploid allele value
*
* @return nucleotide diploid allele byte value
*/
public static byte getNucleotideDiploidByte(char value) {
try {
return NUCLEOTIDE_DIPLOID_ARRAY[value];
// return NUCLEOTIDE_DIPLOID_HASH.get(String.valueOf(value)).byteValue();
} catch (NullPointerException e) {
throw new IllegalArgumentException("NucleotideAlignmentConstants: getNucleotideDiploidByte: unknown allele value: " + value);
}
}
/**
* Returns the IUPAC String for the given diploid allele value.
*
* @param value diploid allele value
*
* @return IUPAC String
*/
public static String getNucleotideIUPAC(byte value) {
try {
String result = NUCLEOTIDE_IUPAC_HASH.get(value);
if (result == null) {
return QUESTION_MARK;
} else {
return result;
}
} catch (NullPointerException e) {
return QUESTION_MARK;
}
}
/**
* Returns the Nucleotide String for the given haploid allele value.
*
* @param value haploid value
*
* @return Nucleotide String
*/
public static String getHaplotypeNucleotide(byte value) {
return NUCLEOTIDE_ALLELES[0][value];
}
/**
* Returns the Nucleotide Complement of given byte encoded nucleotide. A
* returns T. T returns A. C returns G. G returns C. Otherwise given
* nucleotide is returned.
*
* @param nucleotide nucleotide byte value
*
* @return Nucleotide Complement
*/
public static byte getNucleotideComplement(byte nucleotide) {
if (nucleotide == A_ALLELE) {
return T_ALLELE;
} else if (nucleotide == T_ALLELE) {
return A_ALLELE;
} else if (nucleotide == C_ALLELE) {
return G_ALLELE;
} else if (nucleotide == G_ALLELE) {
return C_ALLELE;
} else {
return nucleotide;
}
}
/**
* Returns the Nucleotide Complement of the given diploid byte encoded
* alleles.
*
* @param diploidAllele diploid allele value
*
* @return Nucleotide Complement
*/
public static byte getNucleotideDiploidComplement(byte diploidAllele) {
byte first = (byte) ((diploidAllele >>> 4) & 0xf);
byte second = (byte) (diploidAllele & 0xf);
first = getNucleotideComplement(first);
second = getNucleotideComplement(second);
return (byte) ((first << 4) | second);
}
/**
* Returns whether given allele encodings are for Nucleotide Data.
*
* @param alleleStates allele encodings
*
* @return true if nucleotide encodings
*/
public static boolean isNucleotideEncodings(String[][] alleleStates) {
boolean isNucleotide = false;
if (alleleStates.length == 1) {
isNucleotide = true;
if (alleleStates[0].length == NucleotideAlignmentConstants.NUCLEOTIDE_ALLELES[0].length) {
for (int i = 0; i < alleleStates.length; i++) {
if (!alleleStates[0][i].equals(NucleotideAlignmentConstants.NUCLEOTIDE_ALLELES[0][i])) {
isNucleotide = false;
}
}
}
}
return isNucleotide;
}
}
| 4600x faster implementation of getNucleotideIUPAC(byte value)
| src/net/maizegenetics/pal/alignment/NucleotideAlignmentConstants.java | 4600x faster implementation of getNucleotideIUPAC(byte value) | <ide><path>rc/net/maizegenetics/pal/alignment/NucleotideAlignmentConstants.java
<ide> NUCLEOTIDE_IUPAC_HASH.put((byte) 0xFF, "N"); // NN
<ide>
<ide> }
<add> private static final String[] NUCLEOTIDE_IUPAC_ARRAY = new String[256];
<add>
<add> static {
<add> Arrays.fill(NUCLEOTIDE_IUPAC_ARRAY, null);
<add> for (Byte temp : NUCLEOTIDE_IUPAC_HASH.keySet()) {
<add> NUCLEOTIDE_IUPAC_ARRAY[temp & 0xFF] = NUCLEOTIDE_IUPAC_HASH.get(temp);
<add> }
<add> }
<ide> private static final Map<String, Byte> NUCLEOTIDE_ALLELE_HASH = new HashMap<String, Byte>();
<ide>
<ide> static {
<ide> */
<ide> public static String getNucleotideIUPAC(byte value) {
<ide> try {
<del> String result = NUCLEOTIDE_IUPAC_HASH.get(value);
<add> String result = NUCLEOTIDE_IUPAC_ARRAY[value & 0xFF];
<ide> if (result == null) {
<ide> return QUESTION_MARK;
<ide> } else { |
|
JavaScript | mit | fe0fa83ebd9620c888e0fb13682e738c9cc7bb15 | 0 | mapbender/fom,mapbender/fom,mapbender/fom | var initDropdown = function () {
var me = $(this);
var dropdownList = me.find(".dropdownList");
if (dropdownList.children().length === 0) {
me.find("option").each(function (i, e) {
$(e).addClass("opt-" + i);
var node = $('<li class="item-' + i + '"></li>');
dropdownList.append(node);
node.text($(e).text());
});
}
var select = me.find("select").val();
me.find(".dropdownValue").text(me.find('option[value="'+select+'"]').text())
};
$(function () {
// init dropdown list --------------------------------------------------------------------
var toggleList = function () {
var me = $(this);
var list = me.find(".dropdownList");
var opts = me.find(".hiddenDropdown");
if (list.css("display") == "block") {
list.hide();
} else {
$(".dropdownList").hide();
list.show();
list.find("li").one("click", function (event) {
event.stopPropagation();
list.hide().find("li").off("click");
var me2 = $(this);
var opt = me2.attr("class").replace("item", "opt");
me.find(".dropdownValue").text(me2.text());
opts.find("[selected=selected]").removeAttr("selected");
var val = opts.find("." + opt).attr("selected", "selected").val();
opts.val(val).trigger('change');
})
}
$(document).one("click", function () {
list.hide().find("li").off("mouseout").off("click");
});
return false;
}
$('.dropdown').each(function () {
initDropdown.call(this);
});
$(document).on("click", ".dropdown", toggleList);
});
| src/FOM/CoreBundle/Resources/public/js/widgets/dropdown.js | var initDropdown = function () {
var me = $(this);
var dropdownList = me.find(".dropdownList");
if (dropdownList.children().length === 0) {
me.find("option").each(function (i, e) {
$(e).addClass("opt-" + i);
dropdownList.append($('<li class="item-' + i + '">' + $(e).text() + '</li>'));
});
}
var select = me.find("select").val();
me.find(".dropdownValue").text(me.find('option[value="'+select+'"]').text())
};
$(function () {
// init dropdown list --------------------------------------------------------------------
var toggleList = function () {
var me = $(this);
var list = me.find(".dropdownList");
var opts = me.find(".hiddenDropdown");
if (list.css("display") == "block") {
list.hide();
} else {
$(".dropdownList").hide();
list.show();
list.find("li").one("click", function (event) {
event.stopPropagation();
list.hide().find("li").off("click");
var me2 = $(this);
var opt = me2.attr("class").replace("item", "opt");
me.find(".dropdownValue").text(me2.text());
opts.find("[selected=selected]").removeAttr("selected");
var val = opts.find("." + opt).attr("selected", "selected").val();
opts.val(val).trigger('change');
})
}
$(document).one("click", function () {
list.hide().find("li").off("mouseout").off("click");
});
return false;
}
$('.dropdown').each(function () {
initDropdown.call(this);
});
$(document).on("click", ".dropdown", toggleList);
});
| fixed dropdown part of vulnerability
| src/FOM/CoreBundle/Resources/public/js/widgets/dropdown.js | fixed dropdown part of vulnerability | <ide><path>rc/FOM/CoreBundle/Resources/public/js/widgets/dropdown.js
<ide> if (dropdownList.children().length === 0) {
<ide> me.find("option").each(function (i, e) {
<ide> $(e).addClass("opt-" + i);
<del> dropdownList.append($('<li class="item-' + i + '">' + $(e).text() + '</li>'));
<add> var node = $('<li class="item-' + i + '"></li>');
<add> dropdownList.append(node);
<add> node.text($(e).text());
<ide> });
<ide> }
<ide> var select = me.find("select").val(); |
|
Java | apache-2.0 | 2f3c0d5fc119de718124a16b681362d541bb5e09 | 0 | hzysoft/RxJava,hyarlagadda/RxJava,Ribeiro/RxJava,xfumihiro/RxJava,mttkay/RxJava,zsxwing/RxJava,ruhkopf/RxJava,onepavel/RxJava,srayhunter/RxJava,stevegury/RxJava,jtulach/RxJava,hyarlagadda/RxJava,Bobjoy/RxJava,java02014/RxJava,ibaca/RxJava,fjg1989/RxJava,reactivex/rxjava,Eagles2F/RxJava,ashwary/RxJava,pitatensai/RxJava,xfumihiro/RxJava,Bobjoy/RxJava,ibaca/RxJava,YlJava110/RxJava,sposam/RxJava,ypresto/RxJava,tilal6991/RxJava,weikipeng/RxJava,java02014/RxJava,duqiao/RxJava,Turbo87/RxJava,elijah513/RxJava,mattrjacobs/RxJava,ppiech/RxJava,jbripley/RxJava,ashwary/RxJava,sposam/RxJava,Godchin1990/RxJava,tombujok/RxJava,vqvu/RxJava,Shedings/RxJava,kuanghao/RxJava,tombujok/RxJava,mttkay/RxJava,TracyLu/RxJava,A-w-K/RxJava,devagul93/RxJava,runt18/RxJava,runt18/RxJava,abersnaze/RxJava,mattrjacobs/RxJava,simonbasle/RxJava,zsxwing/RxJava,onepavel/RxJava,Siddartha07/RxJava,wlrhnh-David/RxJava,abersnaze/RxJava,androidgilbert/RxJava,suclike/RxJava,Turbo87/RxJava,tilal6991/RxJava,lncosie/RxJava,akarnokd/RxJava,androidgilbert/RxJava,sunfei/RxJava,davidmoten/RxJava,forsail/RxJava,nvoron23/RxJava,nkhuyu/RxJava,lncosie/RxJava,ashwary/RxJava,ppiech/RxJava,southwolf/RxJava,marcogarcia23/RxJava,artem-zinnatullin/RxJava,cgpllx/RxJava,mobilist/RxJava,randall-mo/RxJava,aditya-chaturvedi/RxJava,bboyfeiyu/RxJava,hyleung/RxJava,shekarrex/RxJava,ChenWenHuan/RxJava,nvoron23/RxJava,pitatensai/RxJava,b-cuts/RxJava,aditya-chaturvedi/RxJava,vqvu/RxJava,duqiao/RxJava,wehjin/RxJava,randall-mo/RxJava,spoon-bot/RxJava,akarnokd/RxJava,onepavel/RxJava,ChenWenHuan/RxJava,hzysoft/RxJava,markrietveld/RxJava,AttwellBrian/RxJava,ronenhamias/RxJava,sanxieryu/RxJava,puniverse/RxJava,ayushnvijay/RxJava,YlJava110/RxJava,mattrjacobs/RxJava,simonbasle/RxJava,stevegury/RxJava,wrightm/RxJava,Siddartha07/RxJava,ronenhamias/RxJava,A-w-K/RxJava,tilal6991/RxJava,sposam/RxJava,Eagles2F/RxJava,eduardotrandafilov/RxJava,wrightm/RxJava,aditya-chaturvedi/RxJava,picnic106/RxJava,wehjin/RxJava,A-w-K/RxJava,sanxieryu/RxJava,benjchristensen/RxJava,msdgwzhy6/RxJava,AmberWhiteSky/RxJava,weikipeng/RxJava,klemzy/RxJava,androidgilbert/RxJava,tombujok/RxJava,gjesse/RxJava,shekarrex/RxJava,stevegury/RxJava,b-cuts/RxJava,Eagles2F/RxJava,cgpllx/RxJava,jbripley/RxJava,abersnaze/RxJava,marcogarcia23/RxJava,shekarrex/RxJava,zsxwing/RxJava,Shedings/RxJava,kuanghao/RxJava,KevinTCoughlin/RxJava,Ryan800/RxJava,sitexa/RxJava,picnic106/RxJava,reactivex/rxjava,wlrhnh-David/RxJava,NiteshKant/RxJava,sanxieryu/RxJava,jacek-rzrz/RxJava,androidyue/RxJava,cloudbearings/RxJava,takecy/RxJava,YlJava110/RxJava,elijah513/RxJava,ruhkopf/RxJava,eduardotrandafilov/RxJava,mttkay/RxJava,pitatensai/RxJava,jacek-rzrz/RxJava,sitexa/RxJava,Shedings/RxJava,davidmoten/RxJava,klemzy/RxJava,nurkiewicz/RxJava,ayushnvijay/RxJava,dromato/RxJava,androidyue/RxJava,hyarlagadda/RxJava,AttwellBrian/RxJava,ayushnvijay/RxJava,klemzy/RxJava,devagul93/RxJava,weikipeng/RxJava,fjg1989/RxJava,yuhuayi/RxJava,ypresto/RxJava,wehjin/RxJava,kuanghao/RxJava,AmberWhiteSky/RxJava,lijunhuayc/RxJava,jtulach/RxJava,sunfei/RxJava,KevinTCoughlin/RxJava,elijah513/RxJava,srayhunter/RxJava,Ribeiro/RxJava,NiteshKant/RxJava,hyleung/RxJava,jbripley/RxJava,androidyue/RxJava,abersnaze/RxJava,wrightm/RxJava,mobilist/RxJava,rabbitcount/RxJava,spoon-bot/RxJava,runt18/RxJava,rabbitcount/RxJava,ibaca/RxJava,HuangWenhuan0/RxJava,msdgwzhy6/RxJava,jacek-rzrz/RxJava,hyleung/RxJava,ChenWenHuan/RxJava,Godchin1990/RxJava,xfumihiro/RxJava,ronenhamias/RxJava,forsail/RxJava,frodoking/RxJava,nurkiewicz/RxJava,HuangWenhuan0/RxJava,Ryan800/RxJava,dromato/RxJava,ypresto/RxJava,nkhuyu/RxJava,Godchin1990/RxJava,suclike/RxJava,southwolf/RxJava,zjrstar/RxJava,lncosie/RxJava,puniverse/RxJava,AmberWhiteSky/RxJava,b-cuts/RxJava,takecy/RxJava,forsail/RxJava,sitexa/RxJava,yuhuayi/RxJava,Ribeiro/RxJava,artem-zinnatullin/RxJava,sunfei/RxJava,southwolf/RxJava,marcogarcia23/RxJava,zjrstar/RxJava,msdgwzhy6/RxJava,TracyLu/RxJava,srayhunter/RxJava,randall-mo/RxJava,nurkiewicz/RxJava,java02014/RxJava,zhongdj/RxJava,yuhuayi/RxJava,rabbitcount/RxJava,cloudbearings/RxJava,gjesse/RxJava,ReactiveX/RxJava,picnic106/RxJava,cloudbearings/RxJava,hzysoft/RxJava,ReactiveX/RxJava,dromato/RxJava,simonbasle/RxJava,vqvu/RxJava,ruhkopf/RxJava,bboyfeiyu/RxJava,maugomez77/RxJava,duqiao/RxJava,wlrhnh-David/RxJava,maugomez77/RxJava,lijunhuayc/RxJava,Ryan800/RxJava,Siddartha07/RxJava,davidmoten/RxJava,puniverse/RxJava,nkhuyu/RxJava,Turbo87/RxJava,markrietveld/RxJava,frodoking/RxJava,nvoron23/RxJava,zhongdj/RxJava,HuangWenhuan0/RxJava,zjrstar/RxJava,ppiech/RxJava,fjg1989/RxJava,TracyLu/RxJava,devagul93/RxJava,eduardotrandafilov/RxJava,zhongdj/RxJava,markrietveld/RxJava,Bobjoy/RxJava,suclike/RxJava,maugomez77/RxJava,KevinTCoughlin/RxJava,cgpllx/RxJava,frodoking/RxJava,gjesse/RxJava,takecy/RxJava,lijunhuayc/RxJava | /**
* Copyright 2014 Netflix, 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 rx;
import static rx.functions.Functions.alwaysFalse;
import java.util.*;
import java.util.concurrent.*;
import rx.exceptions.*;
import rx.functions.*;
import rx.observables.*;
import rx.observers.SafeSubscriber;
import rx.operators.*;
import rx.plugins.*;
import rx.schedulers.*;
import rx.subjects.*;
import rx.subscriptions.Subscriptions;
/**
* The Observable class that implements the Reactive Pattern.
* <p>
* This class provides methods for subscribing to the Observable as well as delegate methods to the various
* Observers.
* <p>
* The documentation for this class makes use of marble diagrams. The following legend explains these diagrams:
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/legend.png">
* <p>
* For more information see the <a href="https://github.com/Netflix/RxJava/wiki/Observable">RxJava Wiki</a>
*
* @param <T>
* the type of the items emitted by the Observable
*/
public class Observable<T> {
final OnSubscribe<T> onSubscribe;
/**
* Observable with Function to execute when subscribed to.
* <p>
* <em>Note:</em> Use {@link #create(OnSubscribe)} to create an Observable, instead of this constructor,
* unless you specifically have a need for inheritance.
*
* @param f
* {@link OnSubscribe} to be executed when {@link #subscribe(Subscriber)} is called
*/
protected Observable(OnSubscribe<T> f) {
this.onSubscribe = f;
}
private static final RxJavaObservableExecutionHook hook = RxJavaPlugins.getInstance().getObservableExecutionHook();
/**
* Returns an Observable that will execute the specified function when a {@link Subscriber} subscribes to
* it.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/create.png">
* <p>
* Write the function you pass to {@code create} so that it behaves as an Observable: It should invoke the
* Subscriber's {@link Subscriber#onNext onNext}, {@link Subscriber#onError onError}, and {@link Subscriber#onCompleted onCompleted} methods appropriately.
* <p>
* A well-formed Observable must invoke either the Subscriber's {@code onCompleted} method exactly once or
* its {@code onError} method exactly once.
* <p>
* See <a href="http://go.microsoft.com/fwlink/?LinkID=205219">Rx Design Guidelines (PDF)</a> for detailed
* information.
*
* @param <T>
* the type of the items that this Observable emits
* @param f
* a function that accepts an {@code Subscriber<T>}, and invokes its {@code onNext}, {@code onError}, and {@code onCompleted} methods as appropriate
* @return an Observable that, when a {@link Subscriber} subscribes to it, will execute the specified
* function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-create">RxJava Wiki: create()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.create.aspx">MSDN: Observable.Create</a>
*/
public final static <T> Observable<T> create(OnSubscribe<T> f) {
return new Observable<T>(hook.onCreate(f));
}
/**
* Invoked when Obserable.subscribe is called.
*/
public static interface OnSubscribe<T> extends Action1<Subscriber<? super T>> {
// cover for generics insanity
}
/**
* Operator function for lifting into an Observable.
*/
public interface Operator<R, T> extends Func1<Subscriber<? super R>, Subscriber<? super T>> {
// cover for generics insanity
}
/**
* @deprecated use {@link #create(OnSubscribe)}
*/
@Deprecated
public final static <T> Observable<T> create(final OnSubscribeFunc<T> f) {
return new Observable<T>(new OnSubscribe<T>() {
@Override
public void call(Subscriber<? super T> observer) {
Subscription s = f.onSubscribe(observer);
if (s != null && s != observer) {
observer.add(s);
}
}
});
}
/**
* @deprecated use {@link OnSubscribe}
*/
@Deprecated
public static interface OnSubscribeFunc<T> extends Function {
public Subscription onSubscribe(Observer<? super T> op);
}
/**
* Lift a function to the current Observable and return a new Observable that when subscribed to will pass
* the values of the current Observable through the function.
* <p>
* In other words, this allows chaining Observers together on an Observable for acting on the values within
* the Observable.
* <p> {@code
* observable.map(...).filter(...).take(5).lift(new ObserverA()).lift(new ObserverB(...)).subscribe()
* }
*
* @param lift
* @return an Observable that emits values that are the result of applying the bind function to the values
* of the current Observable
* @since 0.17
*/
public final <R> Observable<R> lift(final Operator<? extends R, ? super T> lift) {
return new Observable<R>(new OnSubscribe<R>() {
@Override
public void call(Subscriber<? super R> o) {
try {
onSubscribe.call(hook.onLift(lift).call(o));
} catch (Throwable e) {
// localized capture of errors rather than it skipping all operators
// and ending up in the try/catch of the subscribe method which then
// prevents onErrorResumeNext and other similar approaches to error handling
if (e instanceof OnErrorNotImplementedException) {
throw (OnErrorNotImplementedException) e;
}
o.onError(e);
}
}
});
}
/* *********************************************************************************************************
* Observers Below Here
* *********************************************************************************************************
*/
/**
* Mirror the one Observable in an Iterable of several Observables that first emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png">
*
* @param sources
* an Iterable of Observable sources competing to react first
* @return an Observable that emits the same sequence of items as whichever of the source Observables first
* emitted an item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-amb">RxJava Wiki: amb()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229115.aspx">MSDN: Observable.Amb</a>
*/
public final static <T> Observable<T> amb(Iterable<? extends Observable<? extends T>> sources) {
return create(OperatorAmb.amb(sources));
}
/**
* Given two Observables, mirror the one that first emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png">
*
* @param o1
* an Observable competing to react first
* @param o2
* an Observable competing to react first
* @return an Observable that emits the same sequence of items as whichever of the source Observables first
* emitted an item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-amb">RxJava Wiki: amb()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a>
*/
public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2) {
return create(OperatorAmb.amb(o1, o2));
}
/**
* Given three Observables, mirror the one that first emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png">
*
* @param o1
* an Observable competing to react first
* @param o2
* an Observable competing to react first
* @param o3
* an Observable competing to react first
* @return an Observable that emits the same sequence of items as whichever of the source Observables first
* emitted an item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-amb">RxJava Wiki: amb()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a>
*/
public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3) {
return create(OperatorAmb.amb(o1, o2, o3));
}
/**
* Given four Observables, mirror the one that first emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png">
*
* @param o1
* an Observable competing to react first
* @param o2
* an Observable competing to react first
* @param o3
* an Observable competing to react first
* @param o4
* an Observable competing to react first
* @return an Observable that emits the same sequence of items as whichever of the source Observables first
* emitted an item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-amb">RxJava Wiki: amb()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a>
*/
public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4) {
return create(OperatorAmb.amb(o1, o2, o3, o4));
}
/**
* Given five Observables, mirror the one that first emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png">
*
* @param o1
* an Observable competing to react first
* @param o2
* an Observable competing to react first
* @param o3
* an Observable competing to react first
* @param o4
* an Observable competing to react first
* @param o5
* an Observable competing to react first
* @return an Observable that emits the same sequence of items as whichever of the source Observables first
* emitted an item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-amb">RxJava Wiki: amb()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a>
*/
public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5) {
return create(OperatorAmb.amb(o1, o2, o3, o4, o5));
}
/**
* Given six Observables, mirror the one that first emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png">
*
* @param o1
* an Observable competing to react first
* @param o2
* an Observable competing to react first
* @param o3
* an Observable competing to react first
* @param o4
* an Observable competing to react first
* @param o5
* an Observable competing to react first
* @param o6
* an Observable competing to react first
* @return an Observable that emits the same sequence of items as whichever of the source Observables first
* emitted an item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-amb">RxJava Wiki: amb()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a>
*/
public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5, Observable<? extends T> o6) {
return create(OperatorAmb.amb(o1, o2, o3, o4, o5, o6));
}
/**
* Given seven Observables, mirror the one that first emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png">
*
* @param o1
* an Observable competing to react first
* @param o2
* an Observable competing to react first
* @param o3
* an Observable competing to react first
* @param o4
* an Observable competing to react first
* @param o5
* an Observable competing to react first
* @param o6
* an Observable competing to react first
* @param o7
* an Observable competing to react first
* @return an Observable that emits the same sequence of items as whichever of the source Observables first
* emitted an item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-amb">RxJava Wiki: amb()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a>
*/
public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5, Observable<? extends T> o6, Observable<? extends T> o7) {
return create(OperatorAmb.amb(o1, o2, o3, o4, o5, o6, o7));
}
/**
* Given eight Observables, mirror the one that first emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png">
*
* @param o1
* an Observable competing to react first
* @param o2
* an Observable competing to react first
* @param o3
* an Observable competing to react first
* @param o4
* an Observable competing to react first
* @param o5
* an Observable competing to react first
* @param o6
* an Observable competing to react first
* @param o7
* an Observable competing to react first
* @param o8
* an observable competing to react first
* @return an Observable that emits the same sequence of items as whichever of the source Observables first
* emitted an item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-amb">RxJava Wiki: amb()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a>
*/
public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5, Observable<? extends T> o6, Observable<? extends T> o7, Observable<? extends T> o8) {
return create(OperatorAmb.amb(o1, o2, o3, o4, o5, o6, o7, o8));
}
/**
* Given nine Observables, mirror the one that first emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png">
*
* @param o1
* an Observable competing to react first
* @param o2
* an Observable competing to react first
* @param o3
* an Observable competing to react first
* @param o4
* an Observable competing to react first
* @param o5
* an Observable competing to react first
* @param o6
* an Observable competing to react first
* @param o7
* an Observable competing to react first
* @param o8
* an Observable competing to react first
* @param o9
* an Observable competing to react first
* @return an Observable that emits the same sequence of items as whichever of the source Observables first
* emitted an item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-amb">RxJava Wiki: amb()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a>
*/
public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5, Observable<? extends T> o6, Observable<? extends T> o7, Observable<? extends T> o8, Observable<? extends T> o9) {
return create(OperatorAmb.amb(o1, o2, o3, o4, o5, o6, o7, o8, o9));
}
/**
* Combines two source Observables by emitting an item that aggregates the latest values of each of the
* source Observables each time an item is received from either of the source Observables, where this
* aggregation is defined by a specified function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/combineLatest.png">
*
* @param o1
* the first source Observable
* @param o2
* the second source Observable
* @param combineFunction
* the aggregation function used to combine the items emitted by the source Observables
* @return an Observable that emits items that are the result of combining the items emitted by the source
* Observables by means of the given aggregation function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-combinelatest">RxJava Wiki: combineLatest()</a>
*/
@SuppressWarnings("unchecked")
public static final <T1, T2, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Func2<? super T1, ? super T2, ? extends R> combineFunction) {
return combineLatest(Arrays.asList(o1, o2), Functions.fromFunc(combineFunction));
}
/**
* Combines three source Observables by emitting an item that aggregates the latest values of each of the
* source Observables each time an item is received from any of the source Observables, where this
* aggregation is defined by a specified function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/combineLatest.png">
*
* @param o1
* the first source Observable
* @param o2
* the second source Observable
* @param o3
* the third source Observable
* @param combineFunction
* the aggregation function used to combine the items emitted by the source Observables
* @return an Observable that emits items that are the result of combining the items emitted by the source
* Observables by means of the given aggregation function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-combinelatest">RxJava Wiki: combineLatest()</a>
*/
@SuppressWarnings("unchecked")
public static final <T1, T2, T3, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Func3<? super T1, ? super T2, ? super T3, ? extends R> combineFunction) {
return combineLatest(Arrays.asList(o1, o2, o3), Functions.fromFunc(combineFunction));
}
/**
* Combines four source Observables by emitting an item that aggregates the latest values of each of the
* source Observables each time an item is received from any of the source Observables, where this
* aggregation is defined by a specified function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/combineLatest.png">
*
* @param o1
* the first source Observable
* @param o2
* the second source Observable
* @param o3
* the third source Observable
* @param o4
* the fourth source Observable
* @param combineFunction
* the aggregation function used to combine the items emitted by the source Observables
* @return an Observable that emits items that are the result of combining the items emitted by the source
* Observables by means of the given aggregation function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-combinelatest">RxJava Wiki: combineLatest()</a>
*/
@SuppressWarnings("unchecked")
public static final <T1, T2, T3, T4, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4,
Func4<? super T1, ? super T2, ? super T3, ? super T4, ? extends R> combineFunction) {
return combineLatest(Arrays.asList(o1, o2, o3, o4), Functions.fromFunc(combineFunction));
}
/**
* Combines five source Observables by emitting an item that aggregates the latest values of each of the
* source Observables each time an item is received from any of the source Observables, where this
* aggregation is defined by a specified function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/combineLatest.png">
*
* @param o1
* the first source Observable
* @param o2
* the second source Observable
* @param o3
* the third source Observable
* @param o4
* the fourth source Observable
* @param o5
* the fifth source Observable
* @param combineFunction
* the aggregation function used to combine the items emitted by the source Observables
* @return an Observable that emits items that are the result of combining the items emitted by the source
* Observables by means of the given aggregation function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-combinelatest">RxJava Wiki: combineLatest()</a>
*/
@SuppressWarnings("unchecked")
public static final <T1, T2, T3, T4, T5, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5,
Func5<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? extends R> combineFunction) {
return combineLatest(Arrays.asList(o1, o2, o3, o4, o5), Functions.fromFunc(combineFunction));
}
/**
* Combines six source Observables by emitting an item that aggregates the latest values of each of the
* source Observables each time an item is received from any of the source Observables, where this
* aggregation is defined by a specified function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/combineLatest.png">
*
* @param o1
* the first source Observable
* @param o2
* the second source Observable
* @param o3
* the third source Observable
* @param o4
* the fourth source Observable
* @param o5
* the fifth source Observable
* @param o6
* the sixth source Observable
* @param combineFunction
* the aggregation function used to combine the items emitted by the source Observables
* @return an Observable that emits items that are the result of combining the items emitted by the source
* Observables by means of the given aggregation function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-combinelatest">RxJava Wiki: combineLatest()</a>
*/
@SuppressWarnings("unchecked")
public static final <T1, T2, T3, T4, T5, T6, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6,
Func6<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? extends R> combineFunction) {
return combineLatest(Arrays.asList(o1, o2, o3, o4, o5, o6), Functions.fromFunc(combineFunction));
}
/**
* Combines seven source Observables by emitting an item that aggregates the latest values of each of the
* source Observables each time an item is received from any of the source Observables, where this
* aggregation is defined by a specified function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/combineLatest.png">
*
* @param o1
* the first source Observable
* @param o2
* the second source Observable
* @param o3
* the third source Observable
* @param o4
* the fourth source Observable
* @param o5
* the fifth source Observable
* @param o6
* the sixth source Observable
* @param o7
* the seventh source Observable
* @param combineFunction
* the aggregation function used to combine the items emitted by the source Observables
* @return an Observable that emits items that are the result of combining the items emitted by the source
* Observables by means of the given aggregation function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-combinelatest">RxJava Wiki: combineLatest()</a>
*/
@SuppressWarnings("unchecked")
public static final <T1, T2, T3, T4, T5, T6, T7, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Observable<? extends T7> o7,
Func7<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? extends R> combineFunction) {
return combineLatest(Arrays.asList(o1, o2, o3, o4, o5, o6, o7), Functions.fromFunc(combineFunction));
}
/**
* Combines eight source Observables by emitting an item that aggregates the latest values of each of the
* source Observables each time an item is received from any of the source Observables, where this
* aggregation is defined by a specified function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/combineLatest.png">
*
* @param o1
* the first source Observable
* @param o2
* the second source Observable
* @param o3
* the third source Observable
* @param o4
* the fourth source Observable
* @param o5
* the fifth source Observable
* @param o6
* the sixth source Observable
* @param o7
* the seventh source Observable
* @param o8
* the eighth source Observable
* @param combineFunction
* the aggregation function used to combine the items emitted by the source Observables
* @return an Observable that emits items that are the result of combining the items emitted by the source
* Observables by means of the given aggregation function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-combinelatest">RxJava Wiki: combineLatest()</a>
*/
@SuppressWarnings("unchecked")
public static final <T1, T2, T3, T4, T5, T6, T7, T8, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Observable<? extends T7> o7, Observable<? extends T8> o8,
Func8<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? extends R> combineFunction) {
return combineLatest(Arrays.asList(o1, o2, o3, o4, o5, o6, o7, o8), Functions.fromFunc(combineFunction));
}
/**
* Combines nine source Observables by emitting an item that aggregates the latest values of each of the
* source Observables each time an item is received from any of the source Observables, where this
* aggregation is defined by a specified function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/combineLatest.png">
*
* @param o1
* the first source Observable
* @param o2
* the second source Observable
* @param o3
* the third source Observable
* @param o4
* the fourth source Observable
* @param o5
* the fifth source Observable
* @param o6
* the sixth source Observable
* @param o7
* the seventh source Observable
* @param o8
* the eighth source Observable
* @param o9
* the ninth source Observable
* @param combineFunction
* the aggregation function used to combine the items emitted by the source Observables
* @return an Observable that emits items that are the result of combining the items emitted by the source
* Observables by means of the given aggregation function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-combinelatest">RxJava Wiki: combineLatest()</a>
*/
@SuppressWarnings("unchecked")
public static final <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Observable<? extends T7> o7, Observable<? extends T8> o8,
Observable<? extends T9> o9,
Func9<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? super T9, ? extends R> combineFunction) {
return combineLatest(Arrays.asList(o1, o2, o3, o4, o5, o6, o7, o8, o9), Functions.fromFunc(combineFunction));
}
/**
* Combines nine source Observables by emitting an item that aggregates the latest values of each of the
* source Observables each time an item is received from any of the source Observables, where this
* aggregation is defined by a specified function.
* @param <T> the common base type of source values
* @param <R> the result type
* @param sources the list of observable sources
* @param combineFunction
* the aggregation function used to combine the items emitted by the source Observables
* @return an Observable that emits items that are the result of combining the items emitted by the source
* Observables by means of the given aggregation function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-combinelatest">RxJava Wiki: combineLatest()</a>
*/
public static final <T, R> Observable<R> combineLatest(List<? extends Observable<? extends T>> sources, FuncN<? extends R> combineFunction) {
return create(new OperatorCombineLatest<T, R>(sources, combineFunction));
}
/**
* Returns an Observable that emits the items emitted by each of the Observables emitted by an Observable,
* one after the other, without interleaving them.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png">
*
* @param observables
* an Observable that emits Observables
* @return an Observable that emits items all of the items emitted by the Observables emitted by {@code observables}, one after the other, without interleaving them
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-concat">RxJava Wiki: concat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a>
*/
public final static <T> Observable<T> concat(Observable<? extends Observable<? extends T>> observables) {
return observables.lift(new OperatorConcat<T>());
}
/**
* Returns an Observable that emits the items emitted by two Observables, one after the other, without
* interleaving them.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png">
*
* @param t1
* an Observable to be concatenated
* @param t2
* an Observable to be concatenated
* @return an Observable that emits items emitted by the two source Observables, one after the other,
* without interleaving them
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-concat">RxJava Wiki: concat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a>
*/
public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2) {
return concat(from(t1, t2));
}
/**
* Returns an Observable that emits the items emitted by three Observables, one after the other, without
* interleaving them.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png">
*
* @param t1
* an Observable to be concatenated
* @param t2
* an Observable to be concatenated
* @param t3
* an Observable to be concatenated
* @return an Observable that emits items emitted by the three source Observables, one after the other,
* without interleaving them
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-concat">RxJava Wiki: concat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a>
*/
public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3) {
return concat(from(t1, t2, t3));
}
/**
* Returns an Observable that emits the items emitted by four Observables, one after the other, without
* interleaving them.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png">
*
* @param t1
* an Observable to be concatenated
* @param t2
* an Observable to be concatenated
* @param t3
* an Observable to be concatenated
* @param t4
* an Observable to be concatenated
* @return an Observable that emits items emitted by the four source Observables, one after the other,
* without interleaving them
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-concat">RxJava Wiki: concat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a>
*/
public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4) {
return concat(from(t1, t2, t3, t4));
}
/**
* Returns an Observable that emits the items emitted by five Observables, one after the other, without
* interleaving them.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png">
*
* @param t1
* an Observable to be concatenated
* @param t2
* an Observable to be concatenated
* @param t3
* an Observable to be concatenated
* @param t4
* an Observable to be concatenated
* @param t5
* an Observable to be concatenated
* @return an Observable that emits items emitted by the five source Observables, one after the other,
* without interleaving them
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-concat">RxJava Wiki: concat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a>
*/
public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5) {
return concat(from(t1, t2, t3, t4, t5));
}
/**
* Returns an Observable that emits the items emitted by six Observables, one after the other, without
* interleaving them.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png">
*
* @param t1
* an Observable to be concatenated
* @param t2
* an Observable to be concatenated
* @param t3
* an Observable to be concatenated
* @param t4
* an Observable to be concatenated
* @param t5
* an Observable to be concatenated
* @param t6
* an Observable to be concatenated
* @return an Observable that emits items emitted by the six source Observables, one after the other,
* without interleaving them
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-concat">RxJava Wiki: concat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a>
*/
public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6) {
return concat(from(t1, t2, t3, t4, t5, t6));
}
/**
* Returns an Observable that emits the items emitted by seven Observables, one after the other, without
* interleaving them.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png">
*
* @param t1
* an Observable to be concatenated
* @param t2
* an Observable to be concatenated
* @param t3
* an Observable to be concatenated
* @param t4
* an Observable to be concatenated
* @param t5
* an Observable to be concatenated
* @param t6
* an Observable to be concatenated
* @param t7
* an Observable to be concatenated
* @return an Observable that emits items emitted by the seven source Observables, one after the other,
* without interleaving them
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-concat">RxJava Wiki: concat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a>
*/
public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7) {
return concat(from(t1, t2, t3, t4, t5, t6, t7));
}
/**
* Returns an Observable that emits the items emitted by eight Observables, one after the other, without
* interleaving them.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png">
*
* @param t1
* an Observable to be concatenated
* @param t2
* an Observable to be concatenated
* @param t3
* an Observable to be concatenated
* @param t4
* an Observable to be concatenated
* @param t5
* an Observable to be concatenated
* @param t6
* an Observable to be concatenated
* @param t7
* an Observable to be concatenated
* @param t8
* an Observable to be concatenated
* @return an Observable that emits items emitted by the eight source Observables, one after the other,
* without interleaving them
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-concat">RxJava Wiki: concat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a>
*/
public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7, Observable<? extends T> t8) {
return concat(from(t1, t2, t3, t4, t5, t6, t7, t8));
}
/**
* Returns an Observable that emits the items emitted by nine Observables, one after the other, without
* interleaving them.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png">
*
* @param t1
* an Observable to be concatenated
* @param t2
* an Observable to be concatenated
* @param t3
* an Observable to be concatenated
* @param t4
* an Observable to be concatenated
* @param t5
* an Observable to be concatenated
* @param t6
* an Observable to be concatenated
* @param t7
* an Observable to be concatenated
* @param t8
* an Observable to be concatenated
* @param t9
* an Observable to be concatenated
* @return an Observable that emits items emitted by the nine source Observables, one after the other,
* without interleaving them
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-concat">RxJava Wiki: concat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a>
*/
public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7, Observable<? extends T> t8, Observable<? extends T> t9) {
return concat(from(t1, t2, t3, t4, t5, t6, t7, t8, t9));
}
/**
* Returns an Observable that calls an Observable factory to create its Observable for each new Observer
* that subscribes. That is, for each subscriber, the actual Observable that subscriber observes is
* determined by the factory function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/defer.png">
* <p>
* The defer Observer allows you to defer or delay emitting items from an Observable until such time as an
* Observer subscribes to the Observable. This allows an {@link Observer} to easily obtain updates or a
* refreshed version of the sequence.
*
* @param observableFactory
* the Observable factory function to invoke for each {@link Observer} that subscribes to the
* resulting Observable
* @param <T>
* the type of the items emitted by the Observable
* @return an Observable whose {@link Observer}s' subscriptions trigger an invocation of the given
* Observable factory function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-defer">RxJava Wiki: defer()</a>
*/
public final static <T> Observable<T> defer(Func0<? extends Observable<? extends T>> observableFactory) {
return create(new OperatorDefer<T>(observableFactory));
}
/**
* Returns an Observable that emits no items to the {@link Observer} and immediately invokes its {@link Observer#onCompleted onCompleted} method.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/empty.png">
*
* @param <T>
* the type of the items (ostensibly) emitted by the Observable
* @return an Observable that emits no items to the {@link Observer} but immediately invokes the {@link Observer}'s {@link Observer#onCompleted() onCompleted} method
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-empty-error-and-never">RxJava Wiki: empty()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229670.aspx">MSDN: Observable.Empty</a>
*/
public final static <T> Observable<T> empty() {
return from(new ArrayList<T>());
}
/**
* Returns an Observable that emits no items to the {@link Observer} and immediately invokes its {@link Observer#onCompleted onCompleted} method on the specified Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/empty.s.png">
*
* @param scheduler
* the Scheduler to use to call the {@link Observer#onCompleted onCompleted} method
* @param <T>
* the type of the items (ostensibly) emitted by the Observable
* @return an Observable that emits no items to the {@link Observer} but immediately invokes the {@link Observer}'s {@link Observer#onCompleted() onCompleted} method with the specified
* {@code scheduler}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-empty-error-and-never">RxJava Wiki: empty()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229066.aspx">MSDN: Observable.Empty Method (IScheduler)</a>
*/
public final static <T> Observable<T> empty(Scheduler scheduler) {
return Observable.<T> empty().subscribeOn(scheduler);
}
/**
* Returns an Observable that invokes an {@link Observer}'s {@link Observer#onError onError} method when the
* Observer subscribes to it.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/error.png">
*
* @param exception
* the particular Throwable to pass to {@link Observer#onError onError}
* @param <T>
* the type of the items (ostensibly) emitted by the Observable
* @return an Observable that invokes the {@link Observer}'s {@link Observer#onError onError} method when
* the Observer subscribes to it
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-empty-error-and-never">RxJava Wiki: error()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh244299.aspx">MSDN: Observable.Throw</a>
*/
public final static <T> Observable<T> error(Throwable exception) {
return new ThrowObservable<T>(exception);
}
/**
* Returns an Observable that invokes an {@link Observer}'s {@link Observer#onError onError} method on the
* specified Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/error.s.png">
*
* @param exception
* the particular Throwable to pass to {@link Observer#onError onError}
* @param scheduler
* the Scheduler on which to call {@link Observer#onError onError}
* @param <T>
* the type of the items (ostensibly) emitted by the Observable
* @return an Observable that invokes the {@link Observer}'s {@link Observer#onError onError} method, on
* the specified Scheduler
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-empty-error-and-never">RxJava Wiki: error()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211711.aspx">MSDN: Observable.Throw</a>
*/
public final static <T> Observable<T> error(Throwable exception, Scheduler scheduler) {
return Observable.<T> error(exception).subscribeOn(scheduler);
}
/**
* Converts a {@link Future} into an Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.Future.png">
* <p>
* You can convert any object that supports the {@link Future} interface into an Observable that emits the
* return value of the {@link Future#get} method of that object, by passing the object into the {@code from} method.
* <p>
* <em>Important note:</em> This Observable is blocking; you cannot unsubscribe from it.
*
* @param future
* the source {@link Future}
* @param <T>
* the type of object that the {@link Future} returns, and also the type of item to be emitted by
* the resulting Observable
* @return an Observable that emits the item from the source {@link Future}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
public final static <T> Observable<T> from(Future<? extends T> future) {
return create(OperatorToObservableFuture.toObservableFuture(future));
}
/**
* Converts a {@link Future} into an Observable, with a timeout on the Future.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.Future.png">
* <p>
* You can convert any object that supports the {@link Future} interface into an Observable that emits the
* return value of the {@link Future#get} method of that object, by passing the object into the {@code from} method.
* <p>
* <em>Important note:</em> This Observable is blocking; you cannot unsubscribe from it.
*
* @param future
* the source {@link Future}
* @param timeout
* the maximum time to wait before calling {@code get()}
* @param unit
* the {@link TimeUnit} of the {@code timeout} argument
* @param <T>
* the type of object that the {@link Future} returns, and also the type of item to be emitted by
* the resulting Observable
* @return an Observable that emits the item from the source {@link Future}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
public final static <T> Observable<T> from(Future<? extends T> future, long timeout, TimeUnit unit) {
return create(OperatorToObservableFuture.toObservableFuture(future, timeout, unit));
}
/**
* Converts a {@link Future}, operating on a specified {@link Scheduler}, into an Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.Future.s.png">
* <p>
* You can convert any object that supports the {@link Future} interface into an Observable that emits the
* return value of the {@link Future#get} method of that object, by passing the object into the {@code from} method.
* <p>
*
* @param future
* the source {@link Future}
* @param scheduler
* the {@link Scheduler} to wait for the Future on. Use a Scheduler such as {@link Schedulers#io()} that can block and wait on the Future
* @param <T>
* the type of object that the {@link Future} returns, and also the type of item to be emitted by
* the resulting Observable
* @return an Observable that emits the item from the source {@link Future}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
public final static <T> Observable<T> from(Future<? extends T> future, Scheduler scheduler) {
return create(OperatorToObservableFuture.toObservableFuture(future)).subscribeOn(scheduler);
}
/**
* Converts an {@link Iterable} sequence into an Observable that emits the items in the sequence.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
*
* @param iterable
* the source {@link Iterable} sequence
* @param <T>
* the type of items in the {@link Iterable} sequence and the type of items to be emitted by the
* resulting Observable
* @return an Observable that emits each item in the source {@link Iterable} sequence
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
public final static <T> Observable<T> from(Iterable<? extends T> iterable) {
return create(new OnSubscribeFromIterable<T>(iterable));
}
/**
* Converts an {@link Iterable} sequence into an Observable that operates on the specified Scheduler,
* emitting each item from the sequence.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.s.png">
*
* @param iterable
* the source {@link Iterable} sequence
* @param scheduler
* the Scheduler on which the Observable is to emit the items of the Iterable
* @param <T>
* the type of items in the {@link Iterable} sequence and the type of items to be emitted by the
* resulting Observable
* @return an Observable that emits each item in the source {@link Iterable} sequence, on the specified
* Scheduler
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh212140.aspx">MSDN: Observable.ToObservable</a>
*/
public final static <T> Observable<T> from(Iterable<? extends T> iterable, Scheduler scheduler) {
return create(new OnSubscribeFromIterable<T>(iterable)).subscribeOn(scheduler);
}
/**
* Converts an item into an Observable that emits that item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
*
* @param t1
* the item
* @param <T>
* the type of the item
* @return an Observable that emits the item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
public final static <T> Observable<T> from(T t1) {
return just(t1);
}
/**
* Converts two items into an Observable that emits those items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
*
* @param t1
* first item
* @param t2
* second item
* @param <T>
* the type of these items
* @return an Observable that emits each item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
// suppress unchecked because we are using varargs inside the method
@SuppressWarnings("unchecked")
public final static <T> Observable<T> from(T t1, T t2) {
return from(Arrays.asList(t1, t2));
}
/**
* Converts three items into an Observable that emits those items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
*
* @param t1
* first item
* @param t2
* second item
* @param t3
* third item
* @param <T>
* the type of these items
* @return an Observable that emits each item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
// suppress unchecked because we are using varargs inside the method
@SuppressWarnings("unchecked")
public final static <T> Observable<T> from(T t1, T t2, T t3) {
return from(Arrays.asList(t1, t2, t3));
}
/**
* Converts four items into an Observable that emits those items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
*
* @param t1
* first item
* @param t2
* second item
* @param t3
* third item
* @param t4
* fourth item
* @param <T>
* the type of these items
* @return an Observable that emits each item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
// suppress unchecked because we are using varargs inside the method
@SuppressWarnings("unchecked")
public final static <T> Observable<T> from(T t1, T t2, T t3, T t4) {
return from(Arrays.asList(t1, t2, t3, t4));
}
/**
* Converts five items into an Observable that emits those items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
*
* @param t1
* first item
* @param t2
* second item
* @param t3
* third item
* @param t4
* fourth item
* @param t5
* fifth item
* @param <T>
* the type of these items
* @return an Observable that emits each item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
// suppress unchecked because we are using varargs inside the method
@SuppressWarnings("unchecked")
public final static <T> Observable<T> from(T t1, T t2, T t3, T t4, T t5) {
return from(Arrays.asList(t1, t2, t3, t4, t5));
}
/**
* Converts six items into an Observable that emits those items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
*
* @param t1
* first item
* @param t2
* second item
* @param t3
* third item
* @param t4
* fourth item
* @param t5
* fifth item
* @param t6
* sixth item
* @param <T>
* the type of these items
* @return an Observable that emits each item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
// suppress unchecked because we are using varargs inside the method
@SuppressWarnings("unchecked")
public final static <T> Observable<T> from(T t1, T t2, T t3, T t4, T t5, T t6) {
return from(Arrays.asList(t1, t2, t3, t4, t5, t6));
}
/**
* Converts seven items into an Observable that emits those items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
*
* @param t1
* first item
* @param t2
* second item
* @param t3
* third item
* @param t4
* fourth item
* @param t5
* fifth item
* @param t6
* sixth item
* @param t7
* seventh item
* @param <T>
* the type of these items
* @return an Observable that emits each item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
// suppress unchecked because we are using varargs inside the method
@SuppressWarnings("unchecked")
public final static <T> Observable<T> from(T t1, T t2, T t3, T t4, T t5, T t6, T t7) {
return from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7));
}
/**
* Converts eight items into an Observable that emits those items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
*
* @param t1
* first item
* @param t2
* second item
* @param t3
* third item
* @param t4
* fourth item
* @param t5
* fifth item
* @param t6
* sixth item
* @param t7
* seventh item
* @param t8
* eighth item
* @param <T>
* the type of these items
* @return an Observable that emits each item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
// suppress unchecked because we are using varargs inside the method
@SuppressWarnings("unchecked")
public final static <T> Observable<T> from(T t1, T t2, T t3, T t4, T t5, T t6, T t7, T t8) {
return from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7, t8));
}
/**
* Converts nine items into an Observable that emits those items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
*
* @param t1
* first item
* @param t2
* second item
* @param t3
* third item
* @param t4
* fourth item
* @param t5
* fifth item
* @param t6
* sixth item
* @param t7
* seventh item
* @param t8
* eighth item
* @param t9
* ninth item
* @param <T>
* the type of these items
* @return an Observable that emits each item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
// suppress unchecked because we are using varargs inside the method
@SuppressWarnings("unchecked")
public final static <T> Observable<T> from(T t1, T t2, T t3, T t4, T t5, T t6, T t7, T t8, T t9) {
return from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7, t8, t9));
}
/**
* Converts ten items into an Observable that emits those items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
* <p>
*
* @param t1
* first item
* @param t2
* second item
* @param t3
* third item
* @param t4
* fourth item
* @param t5
* fifth item
* @param t6
* sixth item
* @param t7
* seventh item
* @param t8
* eighth item
* @param t9
* ninth item
* @param t10
* tenth item
* @param <T>
* the type of these items
* @return an Observable that emits each item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
// suppress unchecked because we are using varargs inside the method
@SuppressWarnings("unchecked")
public final static <T> Observable<T> from(T t1, T t2, T t3, T t4, T t5, T t6, T t7, T t8, T t9, T t10) {
return from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10));
}
/**
* Converts an Array into an Observable that emits the items in the Array.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
*
* @param t1
* the source Array
* @param <T>
* the type of items in the Array and the type of items to be emitted by the resulting Observable
* @return an Observable that emits each item in the source Array
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
public final static <T> Observable<T> from(T... t1) {
return from(Arrays.asList(t1));
}
/**
* Converts an Array into an Observable that emits the items in the Array on a specified Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
*
* @param items
* the source Array
* @param scheduler
* the Scheduler on which the Observable emits the items of the Array
* @param <T>
* the type of items in the Array and the type of items to be emitted by the resulting Observable
* @return an Observable that emits each item in the source Array
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
public final static <T> Observable<T> from(T[] items, Scheduler scheduler) {
return from(Arrays.asList(items), scheduler);
}
/**
* Returns an Observable that emits a sequential number every specified interval of time.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/interval.png">
*
* @param interval
* interval size in time units (see below)
* @param unit
* time units to use for the interval size
* @return an Observable that emits a sequential number each time interval
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-interval">RxJava Wiki: interval()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229027.aspx">MSDN: Observable.Interval</a>
*/
public final static Observable<Long> interval(long interval, TimeUnit unit) {
return create(new OperatorTimerPeriodically(interval, interval, unit, Schedulers.computation()));
}
/**
* Returns an Observable that emits a sequential number every specified interval of time, on a
* specified Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/interval.s.png">
*
* @param interval
* interval size in time units (see below)
* @param unit
* time units to use for the interval size
* @param scheduler
* the Scheduler to use for scheduling the items
* @return an Observable that emits a sequential number each time interval
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-interval">RxJava Wiki: interval()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh228911.aspx">MSDN: Observable.Interval</a>
*/
public final static Observable<Long> interval(long interval, TimeUnit unit, Scheduler scheduler) {
return create(new OperatorTimerPeriodically(interval, interval, unit, scheduler));
}
/**
* Returns an Observable that emits a single item and then completes.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/just.png">
* <p>
* To convert any object into an Observable that emits that object, pass that object into the {@code just} method.
* <p>
* This is similar to the {@link #from(java.lang.Object[])} method, except that {@code from()} will convert
* an {@link Iterable} object into an Observable that emits each of the items in the Iterable, one at a
* time, while the {@code just()} method converts an Iterable into an Observable that emits the entire
* Iterable as a single item.
*
* @param value
* the item to emit
* @param <T>
* the type of that item
* @return an Observable that emits {@code value} as a single item and then completes
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-just">RxJava Wiki: just()</a>
*/
public final static <T> Observable<T> just(final T value) {
return Observable.create(new OnSubscribe<T>() {
@Override
public void call(Subscriber<? super T> s) {
if (!s.isUnsubscribed()) {
s.onNext(value);
s.onCompleted();
}
}
});
}
/**
* Returns an Observable that emits a single item and then completes, on a specified Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/just.s.png">
* <p>
* This is a scheduler version of {@link #just(Object)}.
*
* @param value
* the item to emit
* @param <T>
* the type of that item
* @param scheduler
* the Scheduler to emit the single item on
* @return an Observable that emits {@code value} as a single item and then completes, on a specified
* Scheduler
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-just">RxJava Wiki: just()</a>
*/
public final static <T> Observable<T> just(T value, Scheduler scheduler) {
return just(value).subscribeOn(scheduler);
}
/**
* Flattens an Iterable of Observables into one Observable, without any transformation.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png">
* <p>
* You can combine the items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param sequences
* the Iterable of Observables
* @return an Observable that emits items that are the result of flattening the items emitted by the
* Observables in the Iterable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229590.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> merge(Iterable<? extends Observable<? extends T>> sequences) {
return merge(from(sequences));
}
/**
* Flattens an Iterable of Observables into one Observable, without any transformation, while limiting the
* number of concurrent subscriptions to these Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png">
* <p>
* You can combine the items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param sequences
* the Iterable of Observables
* @param maxConcurrent
* the maximum number of Observables that may be subscribed to concurrently
* @return an Observable that emits items that are the result of flattening the items emitted by the
* Observables in the Iterable
* @throws IllegalArgumentException
* if {@code maxConcurrent} is less than or equal to 0
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229923.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> merge(Iterable<? extends Observable<? extends T>> sequences, int maxConcurrent) {
return merge(from(sequences), maxConcurrent);
}
/**
* Flattens an Iterable of Observables into one Observable, without any transformation, while limiting the
* number of concurrent subscriptions to these Observables, and subscribing to these Observables on a
* specified Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png">
* <p>
* You can combine the items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param sequences
* the Iterable of Observables
* @param maxConcurrent
* the maximum number of Observables that may be subscribed to concurrently
* @param scheduler
* the Scheduler on which to traverse the Iterable of Observables
* @return an Observable that emits items that are the result of flattening the items emitted by the
* Observables in the Iterable
* @throws IllegalArgumentException
* if {@code maxConcurrent} is less than or equal to 0
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh244329.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> merge(Iterable<? extends Observable<? extends T>> sequences, int maxConcurrent, Scheduler scheduler) {
return merge(from(sequences, scheduler), maxConcurrent);
}
/**
* Flattens an Iterable of Observables into one Observable, without any transformation, subscribing to these
* Observables on a specified Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png">
* <p>
* You can combine the items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param sequences
* the Iterable of Observables
* @param scheduler
* the Scheduler on which to traverse the Iterable of Observables
* @return an Observable that emits items that are the result of flattening the items emitted by the
* Observables in the Iterable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh244336.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> merge(Iterable<? extends Observable<? extends T>> sequences, Scheduler scheduler) {
return merge(from(sequences, scheduler));
}
/**
* Flattens an Observable that emits Observables into a single Observable that emits the items emitted by
* those Observables, without any transformation.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.oo.png">
* <p>
* You can combine the items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param source
* an Observable that emits Observables
* @return an Observable that emits items that are the result of flattening the Observables emitted by the {@code source} Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> merge(Observable<? extends Observable<? extends T>> source) {
return source.lift(new OperatorMerge<T>());
}
/**
* Flattens an Observable that emits Observables into a single Observable that emits the items emitted by
* those Observables, without any transformation, while limiting the maximum number of concurrent
* subscriptions to these Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.oo.png">
* <p>
* You can combine the items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param source
* an Observable that emits Observables
* @param maxConcurrent
* the maximum number of Observables that may be subscribed to concurrently
* @return an Observable that emits items that are the result of flattening the Observables emitted by the {@code source} Observable
* @throws IllegalArgumentException
* if {@code maxConcurrent} is less than or equal to 0
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211914.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> merge(Observable<? extends Observable<? extends T>> source, int maxConcurrent) {
return source.lift(new OperatorMergeMaxConcurrent<T>(maxConcurrent));
}
/**
* Flattens two Observables into a single Observable, without any transformation.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png">
* <p>
* You can combine items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @return an Observable that emits all of the items emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
@SuppressWarnings("unchecked")
public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2) {
return merge(from(Arrays.asList(t1, t2)));
}
/**
* Flattens three Observables into a single Observable, without any transformation.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png">
* <p>
* You can combine items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @return an Observable that emits all of the items emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
@SuppressWarnings("unchecked")
public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3) {
return merge(from(Arrays.asList(t1, t2, t3)));
}
/**
* Flattens four Observables into a single Observable, without any transformation.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png">
* <p>
* You can combine items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @param t4
* an Observable to be merged
* @return an Observable that emits all of the items emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
@SuppressWarnings("unchecked")
public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4) {
return merge(from(Arrays.asList(t1, t2, t3, t4)));
}
/**
* Flattens five Observables into a single Observable, without any transformation.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png">
* <p>
* You can combine items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @param t4
* an Observable to be merged
* @param t5
* an Observable to be merged
* @return an Observable that emits all of the items emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
@SuppressWarnings("unchecked")
public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5) {
return merge(from(Arrays.asList(t1, t2, t3, t4, t5)));
}
/**
* Flattens six Observables into a single Observable, without any transformation.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png">
* <p>
* You can combine items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @param t4
* an Observable to be merged
* @param t5
* an Observable to be merged
* @param t6
* an Observable to be merged
* @return an Observable that emits all of the items emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
@SuppressWarnings("unchecked")
public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6) {
return merge(from(Arrays.asList(t1, t2, t3, t4, t5, t6)));
}
/**
* Flattens seven Observables into a single Observable, without any transformation.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png">
* <p>
* You can combine items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @param t4
* an Observable to be merged
* @param t5
* an Observable to be merged
* @param t6
* an Observable to be merged
* @param t7
* an Observable to be merged
* @return an Observable that emits all of the items emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
@SuppressWarnings("unchecked")
public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7) {
return merge(from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7)));
}
/**
* Flattens eight Observables into a single Observable, without any transformation.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png">
* <p>
* You can combine items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @param t4
* an Observable to be merged
* @param t5
* an Observable to be merged
* @param t6
* an Observable to be merged
* @param t7
* an Observable to be merged
* @param t8
* an Observable to be merged
* @return an Observable that emits items that are the result of flattening
* the items emitted by the {@code source} Observables
* @return an Observable that emits all of the items emitted by the source Observables
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
@SuppressWarnings("unchecked")
public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7, Observable<? extends T> t8) {
return merge(from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7, t8)));
}
/**
* Flattens nine Observables into a single Observable, without any transformation.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png">
* <p>
* You can combine items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @param t4
* an Observable to be merged
* @param t5
* an Observable to be merged
* @param t6
* an Observable to be merged
* @param t7
* an Observable to be merged
* @param t8
* an Observable to be merged
* @param t9
* an Observable to be merged
* @return an Observable that emits all of the items emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
@SuppressWarnings("unchecked")
public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7, Observable<? extends T> t8, Observable<? extends T> t9) {
return merge(from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7, t8, t9)));
}
/**
* Flattens an Array of Observables into one Observable, without any transformation.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.io.png">
* <p>
* You can combine items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param sequences
* the Array of Observables
* @return an Observable that emits all of the items emitted by the Observables in the Array
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> merge(Observable<? extends T>[] sequences) {
return merge(from(sequences));
}
/**
* Flattens an Array of Observables into one Observable, without any transformation, traversing the array on
* a specified Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.ios.png">
* <p>
* You can combine items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param sequences
* the Array of Observables
* @param scheduler
* the Scheduler on which to traverse the Array
* @return an Observable that emits all of the items emitted by the Observables in the Array
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229061.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> merge(Observable<? extends T>[] sequences, Scheduler scheduler) {
return merge(from(sequences, scheduler));
}
/**
* A version of merge that allows an Observer to receive all successfully emitted items from all of the
* source Observables without being interrupted by an error notification from one of them.
* <p>
* This behaves like {@link #merge(Observable)} except that if any of the merged Observables notify of an
* error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from propagating that
* error notification until all of the merged Observables have finished emitting items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png">
* <p>
* Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Observers once.
*
* @param source
* an Observable that emits Observables
* @return an Observable that emits all of the items emitted by the Observables emitted by the {@code source} Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-mergedelayerror">RxJava Wiki: mergeDelayError()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> mergeDelayError(Observable<? extends Observable<? extends T>> source) {
return source.lift(new OperatorMergeDelayError<T>());
}
/**
* A version of merge that allows an Observer to receive all successfully emitted items from all of the
* source Observables without being interrupted by an error notification from one of them.
* <p>
* This behaves like {@link #merge(Observable, Observable)} except that if any of the merged Observables
* notify of an error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from
* propagating that error notification until all of the merged Observables have finished emitting items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png">
* <p>
* Even if both merged Observables send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Observers once.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @return an Observable that emits all of the items that are emitted by the two source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-mergedelayerror">RxJava Wiki: mergeDelayError()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2) {
return mergeDelayError(from(t1, t2));
}
/**
* A version of merge that allows an Observer to receive all successfully emitted items from all of the
* source Observables without being interrupted by an error notification from one of them.
* <p>
* This behaves like {@link #merge(Observable, Observable, Observable)} except that if any of the merged
* Observables notify of an error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain
* from propagating that error notification until all of the merged Observables have finished emitting
* items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png">
* <p>
* Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Observers once.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @return an Observable that emits all of the items that are emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-mergedelayerror">RxJava Wiki: mergeDelayError()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3) {
return mergeDelayError(from(t1, t2, t3));
}
/**
* A version of merge that allows an Observer to receive all successfully emitted items from all of the
* source Observables without being interrupted by an error notification from one of them.
* <p>
* This behaves like {@link #merge(Observable, Observable, Observable, Observable)} except that if any of
* the merged Observables notify of an error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from propagating that error notification until all of the merged Observables
* have finished
* emitting items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png">
* <p>
* Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Observers once.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @param t4
* an Observable to be merged
* @return an Observable that emits all of the items that are emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-mergedelayerror">RxJava Wiki: mergeDelayError()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4) {
return mergeDelayError(from(t1, t2, t3, t4));
}
/**
* A version of merge that allows an Observer to receive all successfully emitted items from all of the
* source Observables without being interrupted by an error notification from one of them.
* <p>
* This behaves like {@link #merge(Observable, Observable, Observable, Observable, Observable)} except that
* if any of the merged Observables notify of an error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from propagating that error notification until all of the merged
* Observables have finished emitting items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png">
* <p>
* Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Observers once.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @param t4
* an Observable to be merged
* @param t5
* an Observable to be merged
* @return an Observable that emits all of the items that are emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-mergedelayerror">RxJava Wiki: mergeDelayError()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5) {
return mergeDelayError(from(t1, t2, t3, t4, t5));
}
/**
* A version of merge that allows an Observer to receive all successfully emitted items from all of the
* source Observables without being interrupted by an error notification from one of them.
* <p>
* This behaves like {@link #merge(Observable, Observable, Observable, Observable, Observable, Observable)} except that if any of the merged Observables notify of an error via
* {@link Observer#onError onError}, {@code mergeDelayError} will refrain from propagating that error notification until all of the merged
* Observables have finished emitting items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png">
* <p>
* Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Observers once.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @param t4
* an Observable to be merged
* @param t5
* an Observable to be merged
* @param t6
* an Observable to be merged
* @return an Observable that emits all of the items that are emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-mergedelayerror">RxJava Wiki: mergeDelayError()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6) {
return mergeDelayError(from(t1, t2, t3, t4, t5, t6));
}
/**
* A version of merge that allows an Observer to receive all successfully emitted items from all of the
* source Observables without being interrupted by an error notification from one of them.
* <p>
* This behaves like {@link #merge(Observable, Observable, Observable, Observable, Observable, Observable, Observable)} except that if any of the merged Observables notify of an error via
* {@link Observer#onError onError}, {@code mergeDelayError} will refrain from propagating that error notification until all of the merged
* Observables have finished emitting items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png">
* <p>
* Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Observers once.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @param t4
* an Observable to be merged
* @param t5
* an Observable to be merged
* @param t6
* an Observable to be merged
* @param t7
* an Observable to be merged
* @return an Observable that emits all of the items that are emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-mergedelayerror">RxJava Wiki: mergeDelayError()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7) {
return mergeDelayError(from(t1, t2, t3, t4, t5, t6, t7));
}
/**
* A version of merge that allows an Observer to receive all successfully emitted items from all of the
* source Observables without being interrupted by an error notification from one of them.
* <p>
* This behaves like {@link #merge(Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable)} except that if any of the merged Observables notify of an error
* via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from propagating that error notification until all of the merged
* Observables have finished emitting items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png">
* <p>
* Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Observers once.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @param t4
* an Observable to be merged
* @param t5
* an Observable to be merged
* @param t6
* an Observable to be merged
* @param t7
* an Observable to be merged
* @param t8
* an Observable to be merged
* @return an Observable that emits all of the items that are emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-mergedelayerror">RxJava Wiki: mergeDelayError()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
// suppress because the types are checked by the method signature before using a vararg
public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7, Observable<? extends T> t8) {
return mergeDelayError(from(t1, t2, t3, t4, t5, t6, t7, t8));
}
/**
* A version of merge that allows an Observer to receive all successfully emitted items from all of the
* source Observables without being interrupted by an error notification from one of them.
* <p>
* This behaves like {@link #merge(Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable)} except that if any of the merged Observables notify
* of an error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from propagating that error notification until all of the merged
* Observables have finished emitting items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png">
* <p>
* Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Observers once.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @param t4
* an Observable to be merged
* @param t5
* an Observable to be merged
* @param t6
* an Observable to be merged
* @param t7
* an Observable to be merged
* @param t8
* an Observable to be merged
* @param t9
* an Observable to be merged
* @return an Observable that emits all of the items that are emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-mergedelayerror">RxJava Wiki: mergeDelayError()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7, Observable<? extends T> t8, Observable<? extends T> t9) {
return mergeDelayError(from(t1, t2, t3, t4, t5, t6, t7, t8, t9));
}
/**
* Convert the current {@code Observable<T>} into an {@code Observable<Observable<T>>}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/nest.png">
*
* @return an Observable that emits a single item: the source Observable
* @since 0.17
*/
public final Observable<Observable<T>> nest() {
return just(this);
}
/**
* Returns an Observable that never sends any items or notifications to an {@link Observer}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/never.png">
* <p>
* This Observable is useful primarily for testing purposes.
*
* @param <T>
* the type of items (not) emitted by the Observable
* @return an Observable that never emits any items or sends any notifications to an {@link Observer}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-empty-error-and-never">RxJava Wiki: never()</a>
*/
public final static <T> Observable<T> never() {
return new NeverObservable<T>();
}
/**
* Converts an {@code Observable<Observable<T>>} into another {@code Observable<Observable<T>>} whose
* emitted Observables emit the same items, but the number of such Observables is restricted by {@code parallelObservables}.
* <p>
* For example, if the original {@code Observable<Observable<T>>} emits 100 Observables and {@code parallelObservables} is 8, the items emitted by the 100 original Observables will be distributed
* among 8 Observables emitted by the resulting Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/parallelMerge.png">
* <p>
* This is a mechanism for efficiently processing <i>n</i> number of Observables on a smaller <i>m</i>
* number of resources (typically CPU cores).
*
* @param parallelObservables
* the number of Observables to merge into
* @return an Observable of Observables constrained in number by {@code parallelObservables}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-parallelmerge">RxJava Wiki: parallelMerge()</a>
*/
public final static <T> Observable<Observable<T>> parallelMerge(Observable<Observable<T>> source, int parallelObservables) {
return OperatorParallelMerge.parallelMerge(source, parallelObservables);
}
/**
* Converts an {@code Observable<Observable<T>>} into another {@code Observable<Observable<T>>} whose
* emitted Observables emit the same items, but the number of such Observables is restricted by {@code parallelObservables}, and each runs on a defined Scheduler.
* <p>
* For example, if the original {@code Observable<Observable<T>>} emits 100 Observables and {@code parallelObservables} is 8, the items emitted by the 100 original Observables will be distributed
* among 8 Observables emitted by the resulting Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/parallelMerge.png">
* <p>
* This is a mechanism for efficiently processing <i>n</i> number of Observables on a smaller <i>m</i>
* number of resources (typically CPU cores).
*
* @param parallelObservables
* the number of Observables to merge into
* @param scheduler
* the {@link Scheduler} to run each Observable on
* @return an Observable of Observables constrained in number by {@code parallelObservables}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-parallelmerge">RxJava Wiki: parallelMerge()</a>
*/
public final static <T> Observable<Observable<T>> parallelMerge(Observable<Observable<T>> source, int parallelObservables, Scheduler scheduler) {
return OperatorParallelMerge.parallelMerge(source, parallelObservables, scheduler);
}
/**
* Pivot GroupedObservable streams without serializing/synchronizing to a single stream first.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/pivot.png">
*
* For example an Observable such as this =>
*
* {@code Observable<GroupedObservable<String, GroupedObservable<Boolean, Integer>>>}:
* <ul>
* <li>o1.odd: 1, 3, 5, 7, 9 on Thread 1</li>
* <li>o1.even: 2, 4, 6, 8, 10 on Thread 1</li>
* <li>o2.odd: 11, 13, 15, 17, 19 on Thread 2</li>
* <li>o2.even: 12, 14, 16, 18, 20 on Thread 2</li>
* </ul>
* is pivoted to become this =>
*
* {@code Observable<GroupedObservable<Boolean, GroupedObservable<String, Integer>>>}:
* <ul>
* <li>odd.o1: 1, 3, 5, 7, 9 on Thread 1</li>
* <li>odd.o2: 11, 13, 15, 17, 19 on Thread 2</li>
* <li>even.o1: 2, 4, 6, 8, 10 on Thread 1</li>
* <li>even.o2: 12, 14, 16, 18, 20 on Thread 2</li>
* </ul>
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/pivot.ex.png">
*
* @param groups
* @return an Observable containing a stream of nested GroupedObservables with swapped inner-outer keys.
* @since 0.17
*/
public static final <K1, K2, T> Observable<GroupedObservable<K2, GroupedObservable<K1, T>>> pivot(Observable<GroupedObservable<K1, GroupedObservable<K2, T>>> groups) {
return groups.lift(new OperatorPivot<K1, K2, T>());
}
/**
* Returns an Observable that emits a sequence of Integers within a specified range.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/range.png">
*
* @param start
* the value of the first Integer in the sequence
* @param count
* the number of sequential Integers to generate
* @return an Observable that emits a range of sequential Integers
* @throws IllegalArgumentException
* if {@code count} is less than zero
* @throws IllegalArgumentException
* if {@code start} + {@code count} exceeds {@code Integer.MAX_VALUE}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-range">RxJava Wiki: range()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229460.aspx">MSDN: Observable.Range</a>
*/
public final static Observable<Integer> range(int start, int count) {
if (count < 0) {
throw new IllegalArgumentException("Count can not be negative");
}
if ((start + count) > Integer.MAX_VALUE) {
throw new IllegalArgumentException("start + count can not exceed Integer.MAX_VALUE");
}
return Observable.create(new OnSubscribeRange(start, start + (count - 1)));
}
/**
* Returns an Observable that emits a sequence of Integers within a specified range, on a specified
* Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/range.s.png">
*
* @param start
* the value of the first Integer in the sequence
* @param count
* the number of sequential Integers to generate
* @param scheduler
* the Scheduler to run the generator loop on
* @return an Observable that emits a range of sequential Integers
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-range">RxJava Wiki: range()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211896.aspx">MSDN: Observable.Range</a>
*/
public final static Observable<Integer> range(int start, int count, Scheduler scheduler) {
return range(start, count).subscribeOn(scheduler);
}
/**
* Returns an Observable that emits a Boolean value that indicates whether two Observable sequences are the
* same by comparing the items emitted by each Observable pairwise.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/sequenceEqual.png">
*
* @param first
* the first Observable to compare
* @param second
* the second Observable to compare
* @param <T>
* the type of items emitted by each Observable
* @return an Observable that emits a Boolean value that indicates whether the two sequences are the same
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-sequenceequal">RxJava Wiki: sequenceEqual()</a>
*/
public final static <T> Observable<Boolean> sequenceEqual(Observable<? extends T> first, Observable<? extends T> second) {
return sequenceEqual(first, second, new Func2<T, T, Boolean>() {
@Override
public final Boolean call(T first, T second) {
if (first == null) {
return second == null;
}
return first.equals(second);
}
});
}
/**
* Returns an Observable that emits a Boolean value that indicates whether two Observable sequences are the
* same by comparing the items emitted by each Observable pairwise based on the results of a specified
* equality function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/sequenceEqual.png">
*
* @param first
* the first Observable to compare
* @param second
* the second Observable to compare
* @param equality
* a function used to compare items emitted by each Observable
* @param <T>
* the type of items emitted by each Observable
* @return an Observable that emits a Boolean value that indicates whether the two Observable two sequences
* are the same according to the specified function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-sequenceequal">RxJava Wiki: sequenceEqual()</a>
*/
public final static <T> Observable<Boolean> sequenceEqual(Observable<? extends T> first, Observable<? extends T> second, Func2<? super T, ? super T, Boolean> equality) {
return OperatorSequenceEqual.sequenceEqual(first, second, equality);
}
/**
* Given an Observable that emits Observables, returns an Observable that emits the items emitted by the
* most recently emitted of those Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/switchDo.png">
* <p> {@code switchOnNext()} subscribes to an Observable that emits Observables. Each time it observes one of
* these emitted Observables, the Observable returned by {@code switchOnNext()} begins emitting the items
* emitted by that Observable. When a new Observable is emitted, {@code switchOnNext()} stops emitting items
* from the earlier-emitted Observable and begins emitting items from the new one.
*
* @param sequenceOfSequences
* the source Observable that emits Observables
* @return an Observable that emits the items emitted by the Observable most recently emitted by the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-switchonnext">RxJava Wiki: switchOnNext()</a>
*
* @param <T> the element type
*/
public final static <T> Observable<T> switchOnNext(Observable<? extends Observable<? extends T>> sequenceOfSequences) {
return sequenceOfSequences.lift(new OperatorSwitch<T>());
}
/**
* Return an Observable that emits a 0L after the {@code initialDelay} and ever increasing numbers after
* each {@code period} of time thereafter.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timer.p.png">
*
* @param initialDelay
* the initial delay time to wait before emitting the first value of 0L
* @param period
* the period of time between emissions of the subsequent numbers
* @param unit
* the time unit for both {@code initialDelay} and {@code period}
* @return an Observable that emits a 0L after the {@code initialDelay} and ever increasing numbers after
* each {@code period} of time thereafter
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-timer">RxJava Wiki: timer()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229435.aspx">MSDN: Observable.Timer</a>
*/
public final static Observable<Long> timer(long initialDelay, long period, TimeUnit unit) {
return timer(initialDelay, period, unit, Schedulers.computation());
}
/**
* Return an Observable that emits a 0L after the {@code initialDelay} and ever increasing numbers after
* each {@code period} of time thereafter, on a specified Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timer.ps.png">
*
* @param initialDelay
* the initial delay time to wait before emitting the first value of 0L
* @param period
* the period of time between emissions of the subsequent numbers
* @param unit
* the time unit for both {@code initialDelay} and {@code period}
* @param scheduler
* the Scheduler on which the waiting happens and items are emitted
* @return an Observable that emits a 0L after the {@code initialDelay} and ever increasing numbers after
* each {@code period} of time thereafter, while running on the given Scheduler
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-timer">RxJava Wiki: timer()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229652.aspx">MSDN: Observable.Timer</a>
*/
public final static Observable<Long> timer(long initialDelay, long period, TimeUnit unit, Scheduler scheduler) {
return create(new OperatorTimerPeriodically(initialDelay, period, unit, scheduler));
}
/**
* Returns an Observable that emits one item after a specified delay, and then completes.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timer.png">
*
* @param delay
* the initial delay before emitting a single 0L
* @param unit
* time units to use for {@code delay}
* @return an Observable that emits one item after a specified delay, and then completes
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-timer">RxJava wiki: timer()</a>
*/
public final static Observable<Long> timer(long delay, TimeUnit unit) {
return timer(delay, unit, Schedulers.computation());
}
/**
* Returns an Observable that emits one item after a specified delay, on a specified Scheduler, and then
* completes.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timer.s.png">
*
* @param delay
* the initial delay before emitting a single 0L
* @param unit
* time units to use for {@code delay}
* @param scheduler
* the Scheduler to use for scheduling the item
* @return Observable that emits one item after a specified delay, on a specified Scheduler, and then
* completes
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-timer">RxJava wiki: timer()</a>
*/
public final static Observable<Long> timer(long delay, TimeUnit unit, Scheduler scheduler) {
return create(new OperatorTimerOnce(delay, unit, scheduler));
}
/**
* Constructs an Observable that creates a dependent resource object.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/using.png">
*
* @param resourceFactory
* the factory function to create a resource object that depends on the Observable
* @param observableFactory
* the factory function to obtain an Observable
* @return the Observable whose lifetime controls the lifetime of the dependent resource object
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-using">RxJava Wiki: using()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229585.aspx">MSDN: Observable.Using</a>
*/
public final static <T, Resource extends Subscription> Observable<T> using(Func0<Resource> resourceFactory, Func1<Resource, ? extends Observable<? extends T>> observableFactory) {
return create(new OperatorUsing<T, Resource>(resourceFactory, observableFactory));
}
/**
* Returns an Observable that emits the results of a function of your choosing applied to combinations of
* items emitted, in sequence, by an Iterable of other Observables.
* <p> {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable
* will be the result of the function applied to the first item emitted by each of the source Observables;
* the second item emitted by the new Observable will be the result of the function applied to the second
* item emitted by each of those Observables; and so forth.
* <p>
* The resulting {@code Observable<R>} returned from {@code zip} will invoke {@code onNext} as many times as
* the number of {@code onNext} invokations of the source Observable that emits the fewest items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png">
*
* @param ws
* an Iterable of source Observables
* @param zipFunction
* a function that, when applied to an item emitted by each of the source Observables, results in
* an item that will be emitted by the resulting Observable
* @return an Observable that emits the zipped results
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-zip">RxJava Wiki: zip()</a>
*/
public final static <R> Observable<R> zip(Iterable<? extends Observable<?>> ws, FuncN<? extends R> zipFunction) {
List<Observable<?>> os = new ArrayList<Observable<?>>();
for (Observable<?> o : ws) {
os.add(o);
}
return Observable.just(os.toArray(new Observable<?>[os.size()])).lift(new OperatorZip<R>(zipFunction));
}
/**
* Returns an Observable that emits the results of a function of your choosing applied to combinations of
* <i>n</i> items emitted, in sequence, by the <i>n</i> Observables emitted by a specified Observable.
* <p> {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable
* will be the result of the function applied to the first item emitted by each of the Observables emitted
* by the source Observable; the second item emitted by the new Observable will be the result of the
* function applied to the second item emitted by each of those Observables; and so forth.
* <p>
* The resulting {@code Observable<R>} returned from {@code zip} will invoke {@code onNext} as many times as
* the number of {@code onNext} invokations of the source Observable that emits the fewest items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.o.png">
*
* @param ws
* an Observable of source Observables
* @param zipFunction
* a function that, when applied to an item emitted by each of the Observables emitted by {@code ws}, results in an item that will be emitted by the resulting Observable
* @return an Observable that emits the zipped results
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-zip">RxJava Wiki: zip()</a>
*/
public final static <R> Observable<R> zip(Observable<? extends Observable<?>> ws, final FuncN<? extends R> zipFunction) {
return ws.toList().map(new Func1<List<? extends Observable<?>>, Observable<?>[]>() {
@Override
public Observable<?>[] call(List<? extends Observable<?>> o) {
return o.toArray(new Observable<?>[o.size()]);
}
}).lift(new OperatorZip<R>(zipFunction));
}
/**
* Returns an Observable that emits the results of a function of your choosing applied to combinations of
* two items emitted, in sequence, by two other Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png">
* <p> {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable
* will be the result of the function applied to the first item emitted by {@code o1} and the first item
* emitted by {@code o2}; the second item emitted by the new Observable will be the result of the function
* applied to the second item emitted by {@code o1} and the second item emitted by {@code o2}; and so forth.
* <p>
* The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} as many times as the number of {@code onNext} invocations of the source Observable that
* emits the fewest
* items.
*
* @param o1
* the first source Observable
* @param o2
* a second source Observable
* @param zipFunction
* a function that, when applied to an item emitted by each of the source Observables, results
* in an item that will be emitted by the resulting Observable
* @return an Observable that emits the zipped results
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-zip">RxJava Wiki: zip()</a>
*/
public final static <T1, T2, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, final Func2<? super T1, ? super T2, ? extends R> zipFunction) {
return just(new Observable<?>[] { o1, o2 }).lift(new OperatorZip<R>(zipFunction));
}
/**
* Returns an Observable that emits the results of a function of your choosing applied to combinations of
* three items emitted, in sequence, by three other Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png">
* <p> {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable
* will be the result of the function applied to the first item emitted by {@code o1}, the first item
* emitted by {@code o2}, and the first item emitted by {@code o3}; the second item emitted by the new
* Observable will be the result of the function applied to the second item emitted by {@code o1}, the
* second item emitted by {@code o2}, and the second item emitted by {@code o3}; and so forth.
* <p>
* The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} as many times as the number of {@code onNext} invocations of the source Observable that
* emits the fewest
* items.
*
* @param o1
* the first source Observable
* @param o2
* a second source Observable
* @param o3
* a third source Observable
* @param zipFunction
* a function that, when applied to an item emitted by each of the source Observables, results in
* an item that will be emitted by the resulting Observable
* @return an Observable that emits the zipped results
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-zip">RxJava Wiki: zip()</a>
*/
public final static <T1, T2, T3, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Func3<? super T1, ? super T2, ? super T3, ? extends R> zipFunction) {
return just(new Observable<?>[] { o1, o2, o3 }).lift(new OperatorZip<R>(zipFunction));
}
/**
* Returns an Observable that emits the results of a function of your choosing applied to combinations of
* four items emitted, in sequence, by four other Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png">
* <p> {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable
* will be the result of the function applied to the first item emitted by {@code o1}, the first item
* emitted by {@code o2}, the first item emitted by {@code o3}, and the first item emitted by {@code 04};
* the second item emitted by the new Observable will be the result of the function applied to the second
* item emitted by each of those Observables; and so forth.
* <p>
* The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} as many times as the number of {@code onNext} invocations of the source Observable that
* emits the fewest
* items.
*
* @param o1
* the first source Observable
* @param o2
* a second source Observable
* @param o3
* a third source Observable
* @param o4
* a fourth source Observable
* @param zipFunction
* a function that, when applied to an item emitted by each of the source Observables, results in
* an item that will be emitted by the resulting Observable
* @return an Observable that emits the zipped results
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-zip">RxJava Wiki: zip()</a>
*/
public final static <T1, T2, T3, T4, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Func4<? super T1, ? super T2, ? super T3, ? super T4, ? extends R> zipFunction) {
return just(new Observable<?>[] { o1, o2, o3, o4 }).lift(new OperatorZip<R>(zipFunction));
}
/**
* Returns an Observable that emits the results of a function of your choosing applied to combinations of
* five items emitted, in sequence, by five other Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png">
* <p> {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable
* will be the result of the function applied to the first item emitted by {@code o1}, the first item
* emitted by {@code o2}, the first item emitted by {@code o3}, the first item emitted by {@code o4}, and
* the first item emitted by {@code o5}; the second item emitted by the new Observable will be the result of
* the function applied to the second item emitted by each of those Observables; and so forth.
* <p>
* The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} as many times as the number of {@code onNext} invocations of the source Observable that
* emits the fewest
* items.
*
* @param o1
* the first source Observable
* @param o2
* a second source Observable
* @param o3
* a third source Observable
* @param o4
* a fourth source Observable
* @param o5
* a fifth source Observable
* @param zipFunction
* a function that, when applied to an item emitted by each of the source Observables, results in
* an item that will be emitted by the resulting Observable
* @return an Observable that emits the zipped results
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-zip">RxJava Wiki: zip()</a>
*/
public final static <T1, T2, T3, T4, T5, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Func5<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? extends R> zipFunction) {
return just(new Observable<?>[] { o1, o2, o3, o4, o5 }).lift(new OperatorZip<R>(zipFunction));
}
/**
* Returns an Observable that emits the results of a function of your choosing applied to combinations of
* six items emitted, in sequence, by six other Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png">
* <p> {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable
* will be the result of the function applied to the first item emitted by each source Observable, the
* second item emitted by the new Observable will be the result of the function applied to the second item
* emitted by each of those Observables, and so forth.
* <p>
* The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} as many times as the number of {@code onNext} invocations of the source Observable that
* emits the fewest
* items.
*
* @param o1
* the first source Observable
* @param o2
* a second source Observable
* @param o3
* a third source Observable
* @param o4
* a fourth source Observable
* @param o5
* a fifth source Observable
* @param o6
* a sixth source Observable
* @param zipFunction
* a function that, when applied to an item emitted by each of the source Observables, results in
* an item that will be emitted by the resulting Observable
* @return an Observable that emits the zipped results
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-zip">RxJava Wiki: zip()</a>
*/
public final static <T1, T2, T3, T4, T5, T6, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6,
Func6<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? extends R> zipFunction) {
return just(new Observable<?>[] { o1, o2, o3, o4, o5, o6 }).lift(new OperatorZip<R>(zipFunction));
}
/**
* Returns an Observable that emits the results of a function of your choosing applied to combinations of
* seven items emitted, in sequence, by seven other Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png">
* <p> {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable
* will be the result of the function applied to the first item emitted by each source Observable, the
* second item emitted by the new Observable will be the result of the function applied to the second item
* emitted by each of those Observables, and so forth.
* <p>
* The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} as many times as the number of {@code onNext} invocations of the source Observable that
* emits the fewest
* items.
*
* @param o1
* the first source Observable
* @param o2
* a second source Observable
* @param o3
* a third source Observable
* @param o4
* a fourth source Observable
* @param o5
* a fifth source Observable
* @param o6
* a sixth source Observable
* @param o7
* a seventh source Observable
* @param zipFunction
* a function that, when applied to an item emitted by each of the source Observables, results in
* an item that will be emitted by the resulting Observable
* @return an Observable that emits the zipped results
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-zip">RxJava Wiki: zip()</a>
*/
public final static <T1, T2, T3, T4, T5, T6, T7, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Observable<? extends T7> o7,
Func7<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? extends R> zipFunction) {
return just(new Observable<?>[] { o1, o2, o3, o4, o5, o6, o7 }).lift(new OperatorZip<R>(zipFunction));
}
/**
* Returns an Observable that emits the results of a function of your choosing applied to combinations of
* eight items emitted, in sequence, by eight other Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png">
* <p> {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable
* will be the result of the function applied to the first item emitted by each source Observable, the
* second item emitted by the new Observable will be the result of the function applied to the second item
* emitted by each of those Observables, and so forth.
* <p>
* The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} as many times as the number of {@code onNext} invocations of the source Observable that
* emits the fewest
* items.
*
* @param o1
* the first source Observable
* @param o2
* a second source Observable
* @param o3
* a third source Observable
* @param o4
* a fourth source Observable
* @param o5
* a fifth source Observable
* @param o6
* a sixth source Observable
* @param o7
* a seventh source Observable
* @param o8
* an eighth source Observable
* @param zipFunction
* a function that, when applied to an item emitted by each of the source Observables, results in
* an item that will be emitted by the resulting Observable
* @return an Observable that emits the zipped results
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-zip">RxJava Wiki: zip()</a>
*/
public final static <T1, T2, T3, T4, T5, T6, T7, T8, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Observable<? extends T7> o7, Observable<? extends T8> o8,
Func8<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? extends R> zipFunction) {
return just(new Observable<?>[] { o1, o2, o3, o4, o5, o6, o7, o8 }).lift(new OperatorZip<R>(zipFunction));
}
/**
* Returns an Observable that emits the results of a function of your choosing applied to combinations of
* nine items emitted, in sequence, by nine other Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png">
* <p> {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable
* will be the result of the function applied to the first item emitted by each source Observable, the
* second item emitted by the new Observable will be the result of the function applied to the second item
* emitted by each of those Observables, and so forth.
* <p>
* The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} as many times as the number of {@code onNext} invocations of the source Observable that
* emits the fewest
* items.
*
* @param o1
* the first source Observable
* @param o2
* a second source Observable
* @param o3
* a third source Observable
* @param o4
* a fourth source Observable
* @param o5
* a fifth source Observable
* @param o6
* a sixth source Observable
* @param o7
* a seventh source Observable
* @param o8
* an eighth source Observable
* @param o9
* a ninth source Observable
* @param zipFunction
* a function that, when applied to an item emitted by each of the source Observables, results in
* an item that will be emitted by the resulting Observable
* @return an Observable that emits the zipped results
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-zip">RxJava Wiki: zip()</a>
*/
public final static <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Observable<? extends T7> o7, Observable<? extends T8> o8,
Observable<? extends T9> o9, Func9<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? super T9, ? extends R> zipFunction) {
return just(new Observable<?>[] { o1, o2, o3, o4, o5, o6, o7, o8, o9 }).lift(new OperatorZip<R>(zipFunction));
}
/**
* Returns an Observable that emits a Boolean that indicates whether all of the items emitted by the source
* Observable satisfy a condition.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/all.png">
*
* @param predicate
* a function that evaluates an item and returns a Boolean
* @return an Observable that emits {@code true} if all items emitted by the source Observable satisfy the
* predicate; otherwise, {@code false}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-all">RxJava Wiki: all()</a>
*/
public final Observable<Boolean> all(Func1<? super T, Boolean> predicate) {
return lift(new OperatorAll<T>(predicate));
}
/**
* Hides the identity of this Observable. Useful for instance when you have an implementation of a subclass
* of Observable but you want to hide the properties and methods of this subclass from whomever you are
* passing the Observable to.
*
* @return an Observable that hides the identity of this Observable
*/
public final Observable<T> asObservable() {
return lift(new OperatorAsObservable<T>());
}
/**
* Returns an Observable that emits buffers of items it collects from the source Observable. The resulting
* Observable emits connected, non-overlapping buffers. It emits the current buffer and replaces it with a
* new buffer when the Observable produced by the specified {@code bufferClosingSelector} emits an item. It
* then uses the {@code bufferClosingSelector} to create a new Observable to observe to indicate the end of
* the next buffer.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer1.png">
*
* @param bufferClosingSelector
* a {@link Func0} that produces an Observable for each buffer created. When this {@code Observable} emits an item, {@code buffer()} emits the associated buffer and replaces it
* with a new one
* @return an Observable that emits a connected, non-overlapping buffer of items from the source Observable
* each time the current Observable created with the {@code bufferClosingSelector} argument emits an
* item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-buffer">RxJava Wiki: buffer()</a>
*/
public final <TClosing> Observable<List<T>> buffer(Func0<? extends Observable<? extends TClosing>> bufferClosingSelector) {
return lift(new OperatorBufferWithSingleObservable<T, TClosing>(bufferClosingSelector, 16));
}
/**
* Returns an Observable that emits buffers of items it collects from the source Observable. The resulting
* Observable emits connected, non-overlapping buffers, each containing {@code count} items. When the source
* Observable completes or encounters an error, the resulting Observable emits the current buffer and
* propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer3.png">
*
* @param count
* the maximum number of items in each buffer before it should be emitted
* @return an Observable that emits connected, non-overlapping buffers, each containing at most {@code count} items from the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-buffer">RxJava Wiki: buffer()</a>
*/
public final Observable<List<T>> buffer(int count) {
return lift(new OperatorBufferWithSize<T>(count, count));
}
/**
* Returns an Observable that emits buffers of items it collects from the source Observable. The resulting
* Observable emits buffers every {@code skip} items, each containing {@code count} items. When the source
* Observable completes or encounters an error, the resulting Observable emits the current buffer and
* propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer4.png">
*
* @param count
* the maximum size of each buffer before it should be emitted
* @param skip
* how many items emitted by the source Observable should be skipped before starting a new
* buffer. Note that when {@code skip} and {@code count} are equal, this is the same operation as {@link #buffer(int)}.
* @return an Observable that emits buffers for every {@code skip} item from the source Observable and
* containing at most {@code count} items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-buffer">RxJava Wiki: buffer()</a>
*/
public final Observable<List<T>> buffer(int count, int skip) {
return lift(new OperatorBufferWithSize<T>(count, skip));
}
/**
* Returns an Observable that emits buffers of items it collects from the source Observable. The resulting
* Observable starts a new buffer periodically, as determined by the {@code timeshift} argument. It emits
* each buffer after a fixed timespan, specified by the {@code timespan} argument. When the source
* Observable completes or encounters an error, the resulting Observable emits the current buffer and
* propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer7.png">
*
* @param timespan
* the period of time each buffer collects items before it is emitted
* @param timeshift
* the period of time after which a new buffer will be created
* @param unit
* the unit of time that applies to the {@code timespan} and {@code timeshift} arguments
* @return an Observable that emits new buffers of items emitted by the source Observable periodically after
* a fixed timespan has elapsed
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-buffer">RxJava Wiki: buffer()</a>
*/
public final Observable<List<T>> buffer(long timespan, long timeshift, TimeUnit unit) {
return lift(new OperatorBufferWithTime<T>(timespan, timeshift, unit, Integer.MAX_VALUE, Schedulers.computation()));
}
/**
* Returns an Observable that emits buffers of items it collects from the source Observable. The resulting
* Observable starts a new buffer periodically, as determined by the {@code timeshift} argument, and on the
* specified {@code scheduler}. It emits each buffer after a fixed timespan, specified by the {@code timespan} argument. When the source Observable completes or encounters an error, the resulting
* Observable emits the current buffer and propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer7.s.png">
*
* @param timespan
* the period of time each buffer collects items before it is emitted
* @param timeshift
* the period of time after which a new buffer will be created
* @param unit
* the unit of time that applies to the {@code timespan} and {@code timeshift} arguments
* @param scheduler
* the {@link Scheduler} to use when determining the end and start of a buffer
* @return an Observable that emits new buffers of items emitted by the source Observable periodically after
* a fixed timespan has elapsed
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-buffer">RxJava Wiki: buffer()</a>
*/
public final Observable<List<T>> buffer(long timespan, long timeshift, TimeUnit unit, Scheduler scheduler) {
return lift(new OperatorBufferWithTime<T>(timespan, timeshift, unit, Integer.MAX_VALUE, scheduler));
}
/**
* Returns an Observable that emits buffers of items it collects from the source Observable. The resulting
* Observable emits connected, non-overlapping buffers, each of a fixed duration specified by the {@code timespan} argument. When the source Observable completes or encounters an error, the
* resulting
* Observable emits the current buffer and propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer5.png">
*
* @param timespan
* the period of time each buffer collects items before it is emitted and replaced with a new
* buffer
* @param unit
* the unit of time that applies to the {@code timespan} argument
* @return an Observable that emits connected, non-overlapping buffers of items emitted by the source
* Observable within a fixed duration
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-buffer">RxJava Wiki: buffer()</a>
*/
public final Observable<List<T>> buffer(long timespan, TimeUnit unit) {
return lift(new OperatorBufferWithTime<T>(timespan, timespan, unit, Integer.MAX_VALUE, Schedulers.computation()));
}
/**
* Returns an Observable that emits buffers of items it collects from the source Observable. The resulting
* Observable emits connected, non-overlapping buffers, each of a fixed duration specified by the {@code timespan} argument or a maximum size specified by the {@code count} argument (whichever is
* reached
* first). When the source Observable completes or encounters an error, the resulting Observable emits the
* current buffer and propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer6.png">
*
* @param timespan
* the period of time each buffer collects items before it is emitted and replaced with a new
* buffer
* @param unit
* the unit of time which applies to the {@code timespan} argument
* @param count
* the maximum size of each buffer before it is emitted
* @return an Observable that emits connected, non-overlapping buffers of items emitted by the source
* Observable, after a fixed duration or when the buffer reaches maximum capacity (whichever occurs
* first)
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-buffer">RxJava Wiki: buffer()</a>
*/
public final Observable<List<T>> buffer(long timespan, TimeUnit unit, int count) {
return lift(new OperatorBufferWithTime<T>(timespan, timespan, unit, count, Schedulers.computation()));
}
/**
* Returns an Observable that emits buffers of items it collects from the source Observable. The resulting
* Observable emits connected, non-overlapping buffers, each of a fixed duration specified by the {@code timespan} argument as measured on the specified {@code scheduler}, or a maximum size
* specified by
* the {@code count} argument (whichever is reached first). When the source Observable completes or
* encounters an error, the resulting Observable emits the current buffer and propagates the notification
* from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer6.s.png">
*
* @param timespan
* the period of time each buffer collects items before it is emitted and replaced with a new
* buffer
* @param unit
* the unit of time which applies to the {@code timespan} argument
* @param count
* the maximum size of each buffer before it is emitted
* @param scheduler
* the {@link Scheduler} to use when determining the end and start of a buffer
* @return an Observable that emits connected, non-overlapping buffers of items emitted by the source
* Observable after a fixed duration or when the buffer reaches maximum capacity (whichever occurs
* first)
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-buffer">RxJava Wiki: buffer()</a>
*/
public final Observable<List<T>> buffer(long timespan, TimeUnit unit, int count, Scheduler scheduler) {
return lift(new OperatorBufferWithTime<T>(timespan, timespan, unit, count, scheduler));
}
/**
* Returns an Observable that emits buffers of items it collects from the source Observable. The resulting
* Observable emits connected, non-overlapping buffers, each of a fixed duration specified by the {@code timespan} argument and on the specified {@code scheduler}. When the source Observable
* completes or
* encounters an error, the resulting Observable emits the current buffer and propagates the notification
* from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer5.s.png">
*
* @param timespan
* the period of time each buffer collects items before it is emitted and replaced with a new
* buffer
* @param unit
* the unit of time which applies to the {@code timespan} argument
* @param scheduler
* the {@link Scheduler} to use when determining the end and start of a buffer
* @return an Observable that emits connected, non-overlapping buffers of items emitted by the source
* Observable within a fixed duration
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-buffer">RxJava Wiki: buffer()</a>
*/
public final Observable<List<T>> buffer(long timespan, TimeUnit unit, Scheduler scheduler) {
return lift(new OperatorBufferWithTime<T>(timespan, timespan, unit, Integer.MAX_VALUE, scheduler));
}
/**
* Returns an Observable that emits buffers of items it collects from the source Observable. The resulting
* Observable emits buffers that it creates when the specified {@code bufferOpenings} Observable emits an
* item, and closes when the Observable returned from {@code bufferClosingSelector} emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer2.png">
*
* @param bufferOpenings
* the Observable that, when it emits an item, causes a new buffer to be created
* @param bufferClosingSelector
* the {@link Func1} that is used to produce an Observable for every buffer created. When this
* Observable emits an item, the associated buffer is emitted.
* @return an Observable that emits buffers, containing items from the source Observable, that are created
* and closed when the specified Observables emit items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-buffer">RxJava Wiki: buffer()</a>
*/
public final <TOpening, TClosing> Observable<List<T>> buffer(Observable<? extends TOpening> bufferOpenings, Func1<? super TOpening, ? extends Observable<? extends TClosing>> bufferClosingSelector) {
return lift(new OperatorBufferWithStartEndObservable<T, TOpening, TClosing>(bufferOpenings, bufferClosingSelector));
}
/**
* Returns an Observable that emits non-overlapping buffered items from the source Observable each time the
* specified boundary Observable emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer8.png">
* <p>
* Completion of either the source or the boundary Observable causes the returned Observable to emit the
* latest buffer and complete.
*
* @param <B>
* the boundary value type (ignored)
* @param boundary
* the boundary Observable
* @return an Observable that emits buffered items from the source Observable when the boundary Observable
* emits an item
* @see #buffer(rx.Observable, int)
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-buffer">RxJava Wiki: buffer()</a>
*/
public final <B> Observable<List<T>> buffer(Observable<B> boundary) {
return lift(new OperatorBufferWithSingleObservable<T, B>(boundary, 16));
}
/**
* Returns an Observable that emits non-overlapping buffered items from the source Observable each time the
* specified boundary Observable emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer8.png">
* <p>
* Completion of either the source or the boundary Observable causes the returned Observable to emit the
* latest buffer and complete.
*
* @param <B>
* the boundary value type (ignored)
* @param boundary
* the boundary Observable
* @param initialCapacity
* the initial capacity of each buffer chunk
* @return an Observable that emits buffered items from the source Observable when the boundary Observable
* emits an item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-buffer">RxJava Wiki: buffer()</a>
* @see #buffer(rx.Observable, int)
*/
public final <B> Observable<List<T>> buffer(Observable<B> boundary, int initialCapacity) {
return lift(new OperatorBufferWithSingleObservable<T, B>(boundary, initialCapacity));
}
/**
* This method has similar behavior to {@link #replay} except that this auto-subscribes to the source
* Observable rather than returning a {@link ConnectableObservable}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/cache.png">
* <p>
* This is useful when you want an Observable to cache responses and you can't control the
* subscribe/unsubscribe behavior of all the {@link Subscriber}s.
* <p>
* When you call {@code cache()}, it does not yet subscribe to the source Observable. This only happens when {@code subscribe} is called the first time on the Observable returned by
* {@code cache()}.
* <p>
*
* <!-- IS THE FOLLOWING NOTE STILL VALID??? -->
*
* <em>Note:</em> You sacrifice the ability to unsubscribe from the origin when you use the {@code cache()} Observer so be careful not to use this Observer on Observables that emit an infinite or
* very large number
* of items that will use up memory.
*
* @return an Observable that, when first subscribed to, caches all of its items and notifications for the
* benefit of subsequent observers
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-cache">RxJava Wiki: cache()</a>
*/
public final Observable<T> cache() {
return create(new OperatorCache<T>(this));
}
/**
* Returns an Observable that emits the items emitted by the source Observable, converted to the specified
* type.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/cast.png">
*
* @param klass
* the target class type that the items emitted by the source Observable will be converted to
* before being emitted by the resulting Observable
* @return an Observable that emits each item from the source Observable after converting it to the
* specified type
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-cast">RxJava Wiki: cast()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211842.aspx">MSDN: Observable.Cast</a>
*/
public final <R> Observable<R> cast(final Class<R> klass) {
return lift(new OperatorCast<T, R>(klass));
}
/**
* Collect values into a single mutable data structure.
* <p>
* This is a simplified version of {@code reduce} that does not need to return the state on each pass.
* <p>
*
* @param state
* FIXME FIXME FIXME
* @param collector
* FIXME FIXME FIXME
* @return FIXME FIXME FIXME
*/
public final <R> Observable<R> collect(R state, final Action2<R, ? super T> collector) {
Func2<R, T, R> accumulator = new Func2<R, T, R>() {
@Override
public final R call(R state, T value) {
collector.call(state, value);
return state;
}
};
return reduce(state, accumulator);
}
/**
* Returns a new Observable that emits items resulting from applying a function that you supply to each item
* emitted by the source Observable, where that function returns an Observable, and then emitting the items
* that result from concatinating those resulting Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concatMap.png">
*
* @param func
* a function that, when applied to an item emitted by the source Observable, returns an
* Observable
* @return an Observable that emits the result of applying the transformation function to each item emitted
* by the source Observable and concatinating the Observables obtained from this transformation
*/
public final <R> Observable<R> concatMap(Func1<? super T, ? extends Observable<? extends R>> func) {
return concat(map(func));
}
/**
* Returns an Observable that emits a Boolean that indicates whether the source Observable emitted a
* specified item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/contains.png">
*
* @param element
* the item to search for in the emissions from the source Observable
* @return an Observable that emits {@code true} if the specified item is emitted by the source Observable,
* or {@code false} if the source Observable completes without emitting that item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-contains">RxJava Wiki: contains()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh228965.aspx">MSDN: Observable.Contains</a>
*/
public final Observable<Boolean> contains(final Object element) {
return exists(new Func1<T, Boolean>() {
public final Boolean call(T t1) {
return element == null ? t1 == null : element.equals(t1);
}
});
}
/**
* Returns an Observable that emits the count of the total number of items emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/count.png">
*
* @return an Observable that emits a single item: the number of elements emitted by the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-count-and-longcount">RxJava Wiki: count()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229470.aspx">MSDN: Observable.Count</a>
* @see #longCount()
*/
public final Observable<Integer> count() {
return reduce(0, new Func2<Integer, T, Integer>() {
@Override
public final Integer call(Integer t1, T t2) {
return t1 + 1;
}
});
}
/**
* Return an Observable that mirrors the source Observable, except that it drops items emitted by the source
* Observable that are followed by another item within a computed debounce duration.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/debounce.f.png">
*
* @param <U>
* the debounce value type (ignored)
* @param debounceSelector
* function to retrieve a sequence that indicates the throttle duration for each item
* @return an Observable that omits items emitted by the source Observable that are followed by another item
* within a computed debounce duration
*/
public final <U> Observable<T> debounce(Func1<? super T, ? extends Observable<U>> debounceSelector) {
return lift(new OperatorDebounceWithSelector<T, U>(debounceSelector));
}
/**
* Return an Observable that mirrors the source Observable, except that it drops items emitted by the source
* Observable that are followed by newer items before a timeout value expires. The timer resets on each
* emission.
* <p>
* <em>Note:</em> If items keep being emitted by the source Observable faster than the timeout then no items
* will be emitted by the resulting Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/debounce.png">
* <p>
* Information on debounce vs throttle:
* <p>
* <ul>
* <li><a href="http://drupalmotion.com/article/debounce-and-throttle-visual-explanation">Debounce and Throttle: visual explanation</a></li>
* <li><a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">Debouncing: javascript methods</a></li>
* <li><a href="http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/">Javascript - don't spam your server: debounce and throttle</a></li>
* </ul>
*
* @param timeout
* the time each item has to be "the most recent" of those emitted by the source Observable to
* ensure that it's not dropped
* @param unit
* the {@link TimeUnit} for the timeout
* @return an Observable that filters out items from the source Observable that are too quickly followed by
* newer items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-throttlewithtimeout-or-debounce">RxJava Wiki: debounce()</a>
* @see #throttleWithTimeout(long, TimeUnit)
*/
public final Observable<T> debounce(long timeout, TimeUnit unit) {
return lift(new OperatorDebounceWithTime<T>(timeout, unit, Schedulers.computation()));
}
/**
* Return an Observable that mirrors the source Observable, except that it drops items emitted by the source
* Observable that are followed by newer items before a timeout value expires on a specified Scheduler. The
* timer resets on each emission.
* <p>
* <em>Note:</em> If items keep being emitted by the source Observable faster than the timeout then no items
* will be emitted by the resulting Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/debounce.s.png">
* <p>
* Information on debounce vs throttle:
* <p>
* <ul>
* <li><a href="http://drupalmotion.com/article/debounce-and-throttle-visual-explanation">Debounce and Throttle: visual explanation</a></li>
* <li><a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">Debouncing: javascript methods</a></li>
* <li><a href="http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/">Javascript - don't spam your server: debounce and throttle</a></li>
* </ul>
*
* @param timeout
* the time each item has to be "the most recent" of those emitted by the source Observable to
* ensure that it's not dropped
* @param unit
* the unit of time for the specified timeout
* @param scheduler
* the {@link Scheduler} to use internally to manage the timers that handle the timeout for each
* item
* @return an Observable that filters out items from the source Observable that are too quickly followed by
* newer items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-throttlewithtimeout-or-debounce">RxJava Wiki: debounce()</a>
* @see #throttleWithTimeout(long, TimeUnit, Scheduler)
*/
public final Observable<T> debounce(long timeout, TimeUnit unit, Scheduler scheduler) {
return lift(new OperatorDebounceWithTime<T>(timeout, unit, scheduler));
}
/**
* Returns an Observable that emits the items emitted by the source Observable or a specified default item
* if the source Observable is empty.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/defaultIfEmpty.png">
*
* @param defaultValue
* the item to emit if the source Observable emits no items
* @return an Observable that emits either the specified default item if the source Observable emits no
* items, or the items emitted by the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-defaultifempty">RxJava Wiki: defaultIfEmpty()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229624.aspx">MSDN: Observable.DefaultIfEmpty</a>
*/
public final Observable<T> defaultIfEmpty(T defaultValue) {
return lift(new OperatorDefaultIfEmpty<T>(defaultValue));
}
/**
* Returns an Observable that delays the subscription to and emissions from the souce Observable via another
* Observable on a per-item basis.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/delay.oo.png">
* <p>
* <em>Note:</em> the resulting Observable will immediately propagate any {@code onError} notification
* from the source Observable.
*
* @param <U>
* the subscription delay value type (ignored)
* @param <V>
* the item delay value type (ignored)
* @param subscriptionDelay
* a function that returns an Observable that triggers the subscription to the source Observable
* once it emits any item
* @param itemDelay
* a function that returns an Observable for each item emitted by the source Observable, which is
* then used to delay the emission of that item by the resulting Observable until the Observable
* returned from {@code itemDelay} emits an item
* @return an Observable that delays the subscription and emissions of the source Observable via another
* Observable on a per-item basis
*/
public final <U, V> Observable<T> delay(
Func0<? extends Observable<U>> subscriptionDelay,
Func1<? super T, ? extends Observable<V>> itemDelay) {
return create(new OperatorDelayWithSelector<T, U, V>(this, subscriptionDelay, itemDelay));
}
/**
* Returns an Observable that delays the emissions of the source Observable via another Observable on a
* per-item basis.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/delay.o.png">
* <p>
* <em>Note:</em> the resulting Observable will immediately propagate any {@code onError} notification
* from the source Observable.
*
* @param <U>
* the item delay value type (ignored)
* @param itemDelay
* a function that returns an Observable for each item emitted by the source Observable, which is
* then used to delay the emission of that item by the resulting Observable until the Observable
* returned from {@code itemDelay} emits an item
* @return an Observable that delays the emissions of the source Observable via another Observable on a
* per-item basis
*/
public final <U> Observable<T> delay(Func1<? super T, ? extends Observable<U>> itemDelay) {
return create(new OperatorDelayWithSelector<T, U, U>(this, itemDelay));
}
/**
* Returns an Observable that emits the items emitted by the source Observable shifted forward in time by a
* specified delay. Error notifications from the source Observable are not delayed.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/delay.png">
*
* @param delay
* the delay to shift the source by
* @param unit
* the {@link TimeUnit} in which {@code period} is defined
* @return the source Observable shifted in time by the specified delay
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-delay">RxJava Wiki: delay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229810.aspx">MSDN: Observable.Delay</a>
*/
public final Observable<T> delay(long delay, TimeUnit unit) {
return create(new OperatorDelay<T>(this, delay, unit, Schedulers.computation()));
}
/**
* Returns an Observable that emits the items emitted by the source Observable shifted forward in time by a
* specified delay. Error notifications from the source Observable are not delayed.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/delay.s.png">
*
* @param delay
* the delay to shift the source by
* @param unit
* the time unit of {@code delay}
* @param scheduler
* the {@link Scheduler} to use for delaying
* @return the source Observable shifted in time by the specified delay
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-delay">RxJava Wiki: delay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229280.aspx">MSDN: Observable.Delay</a>
*/
public final Observable<T> delay(long delay, TimeUnit unit, Scheduler scheduler) {
return create(new OperatorDelay<T>(this, delay, unit, scheduler));
}
/**
* Return an Observable that delays the subscription to the source Observable by a given amount of time.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/delaySubscription.png">
*
* @param delay
* the time to delay the subscription
* @param unit
* the time unit of {@code delay}
* @return an Observable that delays the subscription to the source Observable by the given amount
*/
public final Observable<T> delaySubscription(long delay, TimeUnit unit) {
return delaySubscription(delay, unit, Schedulers.computation());
}
/**
* Return an Observable that delays the subscription to the source Observable by a given amount of time,
* both waiting and subscribing on a given Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/delaySubscription.s.png">
*
* @param delay
* the time to delay the subscription
* @param unit
* the time unit of {@code delay}
* @param scheduler
* the Scheduler on which the waiting and subscription will happen
* @return an Observable that delays the subscription to the source Observable by a given
* amount, waiting and subscribing on the given Scheduler
*/
public final Observable<T> delaySubscription(long delay, TimeUnit unit, Scheduler scheduler) {
return create(new OperatorDelaySubscription<T>(this, delay, unit, scheduler));
}
/**
* Returns an Observable that reverses the effect of {@link #materialize materialize} by transforming the {@link Notification} objects emitted by the source Observable into the items or
* notifications they
* represent.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/dematerialize.png">
*
* @return an Observable that emits the items and notifications embedded in the {@link Notification} objects
* emitted by the source Observable
* @throws Throwable
* if the source Observable is not of type {@code Observable<Notification<T>>}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-dematerialize">RxJava Wiki: dematerialize()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229047.aspx">MSDN: Observable.dematerialize</a>
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public final <T2> Observable<T2> dematerialize() {
return lift(new OperatorDematerialize());
}
/**
* Returns an Observable that emits all items emitted by the source Observable that are distinct.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/distinct.png">
*
* @return an Observable that emits only those items emitted by the source Observable that are distinct from
* each other
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-distinct">RxJava Wiki: distinct()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229764.aspx">MSDN: Observable.distinct</a>
*/
public final Observable<T> distinct() {
return lift(new OperatorDistinct<T, T>(Functions.<T>identity()));
}
/**
* Returns an Observable that emits all items emitted by the source Observable that are distinct according
* to a key selector function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/distinct.key.png">
*
* @param keySelector
* a function that projects an emitted item to a key value that is used to decide whether an item
* is distinct from another one or not
* @return an Observable that emits those items emitted by the source Observable that have distinct keys
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-distinct">RxJava Wiki: distinct()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh244310.aspx">MSDN: Observable.distinct</a>
*/
public final <U> Observable<T> distinct(Func1<? super T, ? extends U> keySelector) {
return lift(new OperatorDistinct<T, U>(keySelector));
}
/**
* Returns an Observable that emits all items emitted by the source Observable that are distinct from their
* immediate predecessors.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/distinctUntilChanged.png">
*
* @return an Observable that emits those items from the source Observable that are distinct from their
* immediate predecessors
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-distinctuntilchanged">RxJava Wiki: distinctUntilChanged()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229494.aspx">MSDN: Observable.distinctUntilChanged</a>
*/
public final Observable<T> distinctUntilChanged() {
return lift(new OperatorDistinctUntilChanged<T, T>(Functions.<T>identity()));
}
/**
* Returns an Observable that emits all items emitted by the source Observable that are distinct from their
* immediate predecessors, according to a key selector function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/distinctUntilChanged.key.png">
*
* @param keySelector
* a function that projects an emitted item to a key value that is used to decide whether an item
* is distinct from another one or not
* @return an Observable that emits those items from the source Observable whose keys are distinct from
* those of their immediate predecessors
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-distinctuntilchanged">RxJava Wiki: distinctUntilChanged()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229508.aspx">MSDN: Observable.distinctUntilChanged</a>
*/
public final <U> Observable<T> distinctUntilChanged(Func1<? super T, ? extends U> keySelector) {
return lift(new OperatorDistinctUntilChanged<T, U>(keySelector));
}
/**
* Modifies an Observable so that it invokes an action when it calls {@code onCompleted}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/doOnCompleted.png">
*
* @param onCompleted
* the action to invoke when the source Observable calls {@code onCompleted}
* @return the source Observable with the side-effecting behavior applied
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-dooncompleted">RxJava Wiki: doOnCompleted()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229804.aspx">MSDN: Observable.Do</a>
*/
public final Observable<T> doOnCompleted(final Action0 onCompleted) {
Observer<T> observer = new Observer<T>() {
@Override
public final void onCompleted() {
onCompleted.call();
}
@Override
public final void onError(Throwable e) {
}
@Override
public final void onNext(T args) {
}
};
return lift(new OperatorDoOnEach<T>(observer));
}
/**
* Modifies an Observable so that it invokes an action for each item it emits.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/doOnEach.png">
*
* @param onNotification
* the action to invoke for each item emitted by the source Observable
* @return the source Observable with the side-effecting behavior applied
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-dooneach">RxJava Wiki: doOnEach()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229307.aspx">MSDN: Observable.Do</a>
*/
public final Observable<T> doOnEach(final Action1<Notification<? super T>> onNotification) {
Observer<T> observer = new Observer<T>() {
@Override
public final void onCompleted() {
onNotification.call(Notification.createOnCompleted());
}
@Override
public final void onError(Throwable e) {
onNotification.call(Notification.createOnError(e));
}
@Override
public final void onNext(T v) {
onNotification.call(Notification.createOnNext(v));
}
};
return lift(new OperatorDoOnEach<T>(observer));
}
/**
* Modifies an Observable so that it notifies an Observer for each item it emits.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/doOnEach.png">
*
* @param observer
* the action to invoke for each item emitted by the source Observable
* @return the source Observable with the side-effecting behavior applied
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-dooneach">RxJava Wiki: doOnEach()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229307.aspx">MSDN: Observable.Do</a>
*/
public final Observable<T> doOnEach(Observer<? super T> observer) {
return lift(new OperatorDoOnEach<T>(observer));
}
/**
* Modifies an Observable so that it invokes an action if it calls {@code onError}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/doOnError.png">
*
* @param onError
* the action to invoke if the source Observable calls {@code onError}
* @return the source Observable with the side-effecting behavior applied
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-doonerror">RxJava Wiki: doOnError()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229804.aspx">MSDN: Observable.Do</a>
*/
public final Observable<T> doOnError(final Action1<Throwable> onError) {
Observer<T> observer = new Observer<T>() {
@Override
public final void onCompleted() {
}
@Override
public final void onError(Throwable e) {
onError.call(e);
}
@Override
public final void onNext(T args) {
}
};
return lift(new OperatorDoOnEach<T>(observer));
}
/**
* Modifies an Observable so that it invokes an action when it calls {@code onNext}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/doOnNext.png">
*
* @param onNext
* the action to invoke when the source Observable calls {@code onNext}
* @return the source Observable with the side-effecting behavior applied
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-dooneach">RxJava Wiki: doOnNext()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229804.aspx">MSDN: Observable.Do</a>
*/
public final Observable<T> doOnNext(final Action1<? super T> onNext) {
Observer<T> observer = new Observer<T>() {
@Override
public final void onCompleted() {
}
@Override
public final void onError(Throwable e) {
}
@Override
public final void onNext(T args) {
onNext.call(args);
}
};
return lift(new OperatorDoOnEach<T>(observer));
}
/**
* Modifies an Observable so that it invokes an action when it calls {@code onCompleted} or {@code onError}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/doOnTerminate.png">
* <p>
* This differs from {@code finallyDo} in that this happens BEFORE onCompleted/onError are emitted.
*
* @param onTerminate
* the action to invoke when the source Observable calls {@code onCompleted} or {@code onError}
* @return the source Observable with the side-effecting behavior applied
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-doonterminate">RxJava Wiki: doOnTerminate()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229804.aspx">MSDN: Observable.Do</a>
* @since 0.17
*/
public final Observable<T> doOnTerminate(final Action0 onTerminate) {
Observer<T> observer = new Observer<T>() {
@Override
public final void onCompleted() {
onTerminate.call();
}
@Override
public final void onError(Throwable e) {
onTerminate.call();
}
@Override
public final void onNext(T args) {
}
};
return lift(new OperatorDoOnEach<T>(observer));
}
/**
* Returns an Observable that emits the single item at a specified index in a sequence of emissions from a
* source Observbable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/elementAt.png">
*
* @param index
* the zero-based index of the item to retrieve
* @return an Observable that emits a single item: the item at the specified position in the sequence of
* those emitted by the source Observable
* @throws IndexOutOfBoundsException
* if {@code index} is greater than or equal to the number of items emitted by the source
* Observable
* @throws IndexOutOfBoundsException
* if {@code index} is less than 0
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-elementat">RxJava Wiki: elementAt()</a>
*/
public final Observable<T> elementAt(int index) {
return lift(new OperatorElementAt<T>(index));
}
/**
* Returns an Observable that emits the item found at a specified index in a sequence of emissions from a
* source Observable, or a default item if that index is out of range.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/elementAtOrDefault.png">
*
* @param index
* the zero-based index of the item to retrieve
* @param defaultValue
* the default item
* @return an Observable that emits the item at the specified position in the sequence emitted by the source
* Observable, or the default item if that index is outside the bounds of the source sequence
* @throws IndexOutOfBoundsException
* if {@code index} is less than 0
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-elementatordefault">RxJava Wiki: elementAtOrDefault()</a>
*/
public final Observable<T> elementAtOrDefault(int index, T defaultValue) {
return lift(new OperatorElementAt<T>(index, defaultValue));
}
/**
* Returns an Observable that emits {@code true} if any item emitted by the source Observable satisfies a
* specified condition, otherwise {@code false}. <em>Note:</em> this always emits {@code false} if the
* source Observable is empty.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/exists.png">
* <p>
* In Rx.Net this is the {@code any} Observer but we renamed it in RxJava to better match Java naming
* idioms.
*
* @param predicate
* the condition to test items emitted by the source Observable
* @return an Observable that emits a Boolean that indicates whether any item emitted by the source
* Observable satisfies the {@code predicate}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-exists-and-isempty">RxJava Wiki: exists()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211993.aspx">MSDN: Observable.Any (Note: the description in this page was wrong at the time of this writing)</a>
*/
public final Observable<Boolean> exists(Func1<? super T, Boolean> predicate) {
return lift(new OperatorAny<T>(predicate, false));
}
/**
* Filter items emitted by an Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/filter.png">
*
* @param predicate
* a function that evaluates the items emitted by the source Observable, returning {@code true} if they pass the filter
* @return an Observable that emits only those items emitted by the source Observable that the filter
* evaluates as {@code true}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-filter-or-where">RxJava Wiki: filter()</a>
*/
public final Observable<T> filter(Func1<? super T, Boolean> predicate) {
return lift(new OperatorFilter<T>(predicate));
}
/**
* Registers an {@link Action0} to be called when this Observable invokes either {@link Observer#onCompleted onCompleted} or {@link Observer#onError onError}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/finallyDo.png">
*
* @param action
* an {@link Action0} to be invoked when the source Observable finishes
* @return an Observable that emits the same items as the source Observable, then invokes the {@link Action0}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-finallydo">RxJava Wiki: finallyDo()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh212133.aspx">MSDN: Observable.Finally</a>
*/
public final Observable<T> finallyDo(Action0 action) {
return lift(new OperatorFinally<T>(action));
}
/**
* Returns an Observable that emits only the very first item emitted by the source Observable, or raises an {@code NoSuchElementException} if the source Observable is empty.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/first.png">
*
* @return an Observable that emits only the very first item emitted by the source Observable, or raises an {@code NoSuchElementException} if the source Observable is empty
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-first">RxJava Wiki: first()</a>
* @see "MSDN: Observable.firstAsync()"
*/
public final Observable<T> first() {
return take(1).single();
}
/**
* Returns an Observable that emits only the very first item emitted by the source Observable that satisfies
* a specified condition, or raises an {@code NoSuchElementException} if no such items are emitted.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/firstN.png">
*
* @param predicate
* the condition that an item emitted by the source Observable has to satisfy
* @return an Observable that emits only the very first item emitted by the source Observable that satisfies
* the {@code predicate}, or raises an {@code NoSuchElementException} if no such items are emitted
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-first">RxJava Wiki: first()</a>
* @see "MSDN: Observable.firstAsync()"
*/
public final Observable<T> first(Func1<? super T, Boolean> predicate) {
return takeFirst(predicate).single();
}
/**
* Returns an Observable that emits only the very first item emitted by the source Observable, or a default
* item if the source Observable completes without emitting anything.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/firstOrDefault.png">
*
* @param defaultValue
* the default item to emit if the source Observable doesn't emit anything
* @return an Observable that emits only the very first item from the source, or a default item if the
* source Observable completes without emitting any items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-firstordefault">RxJava Wiki: firstOrDefault()</a>
* @see "MSDN: Observable.firstOrDefaultAsync()"
*/
public final Observable<T> firstOrDefault(T defaultValue) {
return take(1).singleOrDefault(defaultValue);
}
/**
* Returns an Observable that emits only the very first item emitted by the source Observable that satisfies
* a specified condition, or a default item if the source Observable emits no such items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/firstOrDefaultN.png">
*
* @param predicate
* the condition any item emitted by the source Observable has to satisfy
* @param defaultValue
* the default item to emit if the source Observable doesn't emit anything that satisfies the {@code predicate}
* @return an Observable that emits only the very first item emitted by the source Observable that satisfies
* the {@code predicate}, or a default item if the source Observable emits no such items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-firstordefault">RxJava Wiki: firstOrDefault()</a>
* @see "MSDN: Observable.firstOrDefaultAsync()"
*/
public final Observable<T> firstOrDefault(T defaultValue, Func1<? super T, Boolean> predicate) {
return takeFirst(predicate).singleOrDefault(defaultValue);
}
/**
* Returns an Observable that emits items based on applying a function that you supply to each item emitted
* by the source Observable, where that function returns an Observable, and then merging those resulting
* Observables and emitting the results of this merger.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/flatMap.png">
*
* @param func
* a function that, when applied to an item emitted by the source Observable, returns an
* Observable
* @return an Observable that emits the result of applying the transformation function to each item emitted
* by the source Observable and merging the results of the Observables obtained from this
* transformation
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-mapmany-or-flatmap-and-mapmanydelayerror">RxJava Wiki: flatMap()</a>
*/
public final <R> Observable<R> flatMap(Func1<? super T, ? extends Observable<? extends R>> func) {
return mergeMap(func);
}
/**
* Subscribes to the {@link Observable} and receives notifications for each element.
* <p>
* Alias to {@link #subscribe(Action1)}
*
* @param onNext
* {@link Action1} to execute for each item.
* @throws IllegalArgumentException
* if {@code onNext} is null
* @throws IllegalArgumentException
* if {@code onError} is null
* @throws IllegalArgumentException
* if {@code onComplete} is null
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable#wiki-onnext-oncompleted-and-onerror">RxJava Wiki: onNext, onCompleted, and onError</a>
* @since 0.19
*/
public final void forEach(final Action1<? super T> onNext) {
subscribe(onNext);
}
/**
* Subscribes to the {@link Observable} and receives notifications for each element and error events.
* <p>
* Alias to {@link #subscribe(Action1, Action1)}
*
* @param onNext
* {@link Action1} to execute for each item.
* @param onError
* {@link Action1} to execute when an error is emitted.
* @throws IllegalArgumentException
* if {@code onNext} is null
* @throws IllegalArgumentException
* if {@code onError} is null
* @throws IllegalArgumentException
* if {@code onComplete} is null
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable#wiki-onnext-oncompleted-and-onerror">RxJava Wiki: onNext, onCompleted, and onError</a>
* @since 0.19
*/
public final void forEach(final Action1<? super T> onNext, final Action1<Throwable> onError) {
subscribe(onNext, onError);
}
/**
* Subscribes to the {@link Observable} and receives notifications for each element and the terminal events.
* <p>
* Alias to {@link #subscribe(Action1, Action1, Action0)}
*
* @param onNext
* {@link Action1} to execute for each item.
* @param onError
* {@link Action1} to execute when an error is emitted.
* @param onComplete
* {@link Action0} to execute when completion is signalled.
* @throws IllegalArgumentException
* if {@code onNext} is null
* @throws IllegalArgumentException
* if {@code onError} is null
* @throws IllegalArgumentException
* if {@code onComplete} is null
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable#wiki-onnext-oncompleted-and-onerror">RxJava Wiki: onNext, onCompleted, and onError</a>
* @since 0.19
*/
public final void forEach(final Action1<? super T> onNext, final Action1<Throwable> onError, final Action0 onComplete) {
subscribe(onNext, onError, onComplete);
}
/**
* Groups the items emitted by an Observable according to a specified criterion, and emits these grouped
* items as {@link GroupedObservable}s, one {@code GroupedObservable} per group.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/groupBy.png">
*
* @param keySelector
* a function that extracts the key for each item
* @param <K>
* the key type
* @return an Observable that emits {@link GroupedObservable}s, each of which corresponds to a unique key
* value and each of which emits those items from the source Observable that share that key value
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-groupby-and-groupbyuntil">RxJava Wiki: groupBy</a>
*/
public final <K> Observable<GroupedObservable<K, T>> groupBy(final Func1<? super T, ? extends K> keySelector) {
return lift(new OperatorGroupBy<K, T>(keySelector));
}
/**
* Groups the items emitted by an Observable according to a specified key selector function until the
* duration Observable expires for the key.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/groupByUntil.png">
*
* @param keySelector
* a function to extract the key for each item
* @param durationSelector
* a function to signal the expiration of a group
* @return an Observable that emits {@link GroupedObservable}s, each of which corresponds to a key value and
* each of which emits all items emitted by the source Observable during that key's duration that
* share that same key value
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-groupby-and-groupbyuntil">RxJava Wiki: groupByUntil()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211932.aspx">MSDN: Observable.GroupByUntil</a>
*/
public final <TKey, TDuration> Observable<GroupedObservable<TKey, T>> groupByUntil(Func1<? super T, ? extends TKey> keySelector, Func1<? super GroupedObservable<TKey, T>, ? extends Observable<? extends TDuration>> durationSelector) {
return groupByUntil(keySelector, Functions.<T> identity(), durationSelector);
}
/**
* Groups the items emitted by an Observable (transformed by a selector) according to a specified key
* selector function until the duration Observable expires for the key.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/groupByUntil.png">
*
* @param keySelector
* a function to extract the key for each item
* @param valueSelector
* a function to map each item emitted by the source Observable to an item emitted by one of the
* resulting {@link GroupedObservable}s
* @param durationSelector
* a function to signal the expiration of a group
* @return an Observable that emits {@link GroupedObservable}s, each of which corresponds to a key value and
* each of which emits all items emitted by the source Observable during that key's duration that
* share that same key value, transformed by the value selector
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-groupby-and-groupbyuntil">RxJava Wiki: groupByUntil()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229433.aspx">MSDN: Observable.GroupByUntil</a>
*/
public final <TKey, TValue, TDuration> Observable<GroupedObservable<TKey, TValue>> groupByUntil(Func1<? super T, ? extends TKey> keySelector, Func1<? super T, ? extends TValue> valueSelector, Func1<? super GroupedObservable<TKey, TValue>, ? extends Observable<? extends TDuration>> durationSelector) {
return lift(new OperatorGroupByUntil<T, TKey, TValue, TDuration>(keySelector, valueSelector, durationSelector));
}
/**
* Return an Observable that correlates two Observables when they overlap in time and groups the results.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/groupJoin.png">
*
* @param right
* the other Observable to correlate items from the source Observable with
* @param leftDuration
* a function that returns an Observable whose emissions indicate the duration of the values of
* the source Observable
* @param rightDuration
* a function that returns an Observable whose emissions indicate the duration of the values of
* the {@code right} Observable
* @param resultSelector
* a function that takes an item emitted by each Observable and returns the value to be emitted
* by the resulting Observable
* @return an Observable that emits items based on combining those items emitted by the source Observables
* whose durations overlap
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-join-and-groupjoin">RxJava Wiiki: groupJoin</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh244235.aspx">MSDN: Observable.GroupJoin</a>
*/
public final <T2, D1, D2, R> Observable<R> groupJoin(Observable<T2> right, Func1<? super T, ? extends Observable<D1>> leftDuration,
Func1<? super T2, ? extends Observable<D2>> rightDuration,
Func2<? super T, ? super Observable<T2>, ? extends R> resultSelector) {
return create(new OperatorGroupJoin<T, T2, D1, D2, R>(this, right, leftDuration, rightDuration, resultSelector));
}
/**
* Ignores all items emitted by the source Observable and only calls {@code onCompleted} or {@code onError}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/ignoreElements.png">
*
* @return an empty Observable that only calls {@code onCompleted} or {@code onError}, based on which one is
* called by the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-ignoreelements">RxJava Wiki: ignoreElements()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229242.aspx">MSDN: Observable.IgnoreElements</a>
*/
public final Observable<T> ignoreElements() {
return filter(alwaysFalse());
}
/**
* Returns an Observable that emits {@code true} if the source Observable is empty, otherwise {@code false}.
* <p>
* In Rx.Net this is negated as the {@code any} Observer but we renamed this in RxJava to better match Java
* naming idioms.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/isEmpty.png">
*
* @return an Observable that emits a Boolean
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-exists-and-isempty">RxJava Wiki: isEmpty()</a>
* @see <a href= "http://msdn.microsoft.com/en-us/library/hh229905.aspx">MSDN: Observable.Any</a>
*/
public final Observable<Boolean> isEmpty() {
return lift(new OperatorAny<T>(Functions.alwaysTrue(), true));
}
/**
* Correlates the items emitted by two Observables based on overlapping durations.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/join_.png">
*
* @param right
* the second Observable to join items from
* @param leftDurationSelector
* a function to select a duration for each item emitted by the source Observable, used to
* determine overlap
* @param rightDurationSelector
* a function to select a duration for each item emitted by the {@code right} Observable, used to
* determine overlap
* @param resultSelector
* a function that computes an item to be emitted by the resulting Observable for any two
* overlapping items emitted by the two Observables
* @return an Observable that emits items correlating to items emitted by the source Observables that have
* overlapping durations
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-join">RxJava Wiki: join()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229750.aspx">MSDN: Observable.Join</a>
*/
public final <TRight, TLeftDuration, TRightDuration, R> Observable<R> join(Observable<TRight> right, Func1<T, Observable<TLeftDuration>> leftDurationSelector,
Func1<TRight, Observable<TRightDuration>> rightDurationSelector,
Func2<T, TRight, R> resultSelector) {
return create(new OperatorJoin<T, TRight, TLeftDuration, TRightDuration, R>(this, right, leftDurationSelector, rightDurationSelector, resultSelector));
}
/**
* Returns an Observable that emits the last item emitted by the source Observable or notifies observers of
* an {@code NoSuchElementException} if the source Observable is empty.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/last.png">
*
* @return an Observable that emits the last item from the source Observable or notifies observers of an
* error
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observable-Operators#wiki-last">RxJava Wiki: last()</a>
* @see "MSDN: Observable.lastAsync()"
*/
public final Observable<T> last() {
return takeLast(1).single();
}
/**
* Returns an Observable that emits only the last item emitted by the source Observable that satisfies a
* given condition, or an {@code NoSuchElementException} if no such items are emitted.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/last.p.png">
*
* @param predicate
* the condition any source emitted item has to satisfy
* @return an Observable that emits only the last item satisfying the given condition from the source, or an {@code NoSuchElementException} if no such items are emitted
* @throws IllegalArgumentException
* if no items that match the predicate are emitted by the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observable-Operators#wiki-last">RxJava Wiki: last()</a>
* @see "MSDN: Observable.lastAsync()"
*/
public final Observable<T> last(Func1<? super T, Boolean> predicate) {
return filter(predicate).takeLast(1).single();
}
/**
* Returns an Observable that emits only the last item emitted by the source Observable, or a default item
* if the source Observable completes without emitting any items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/lastOrDefault.png">
*
* @param defaultValue
* the default item to emit if the source Observable is empty
* @return an Observable that emits only the last item emitted by the source Observable, or a default item
* if the source Observable is empty
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-lastOrDefault">RxJava Wiki: lastOrDefault()</a>
* @see "MSDN: Observable.lastOrDefaultAsync()"
*/
public final Observable<T> lastOrDefault(T defaultValue) {
return takeLast(1).singleOrDefault(defaultValue);
}
/**
* Returns an Observable that emits only the last item emitted by the source Observable that satisfies a
* specified condition, or a default item if no such item is emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/lastOrDefault.p.png">
*
* @param defaultValue
* the default item to emit if the source Observable doesn't emit anything that satisfies the
* specified {@code predicate}
* @param predicate
* the condition any item emitted by the source Observable has to satisfy
* @return an Observable that emits only the last item emitted by the source Observable that satisfies the
* given condition, or a default item if no such item is emitted by the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-lastOrDefault">RxJava Wiki: lastOrDefault()</a>
* @see "MSDN: Observable.lastOrDefaultAsync()"
*/
public final Observable<T> lastOrDefault(T defaultValue, Func1<? super T, Boolean> predicate) {
return filter(predicate).takeLast(1).singleOrDefault(defaultValue);
}
/**
* Returns an Observable that emits only the first {@code num} items emitted by the source Observable.
* <p>
* Alias of {@link #take(int)} to match Java 8 Stream API naming convention.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/take.png">
* <p>
* This method returns an Observable that will invoke a subscribing {@link Observer}'s {@link Observer#onNext onNext} function a maximum of {@code num} times before invoking
* {@link Observer#onCompleted onCompleted}.
*
* @param num
* the maximum number of items to emit
* @return an Observable that emits only the first {@code num} items emitted by the source Observable, or
* all of the items from the source Observable if that Observable emits fewer than {@code num} items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-take">RxJava Wiki: take()</a>
* @since 0.19
*/
public final Observable<T> limit(int num) {
return take(num);
}
/**
* Returns an Observable that counts the total number of items emitted by the source Observable and emits
* this count as a 64-bit Long.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/longCount.png">
*
* @return an Observable that emits a single item: the number of items emitted by the source Observable as a
* 64-bit Long item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-count-and-longcount">RxJava Wiki: count()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229120.aspx">MSDN: Observable.LongCount</a>
* @see #count()
*/
public final Observable<Long> longCount() {
return reduce(0L, new Func2<Long, T, Long>() {
@Override
public final Long call(Long t1, T t2) {
return t1 + 1;
}
});
}
/**
* Returns an Observable that applies a specified function to each item emitted by the source Observable and
* emits the results of these function applications.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/map.png">
*
* @param func
* a function to apply to each item emitted by the Observable
* @return an Observable that emits the items from the source Observable, transformed by the specified
* function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-map">RxJava Wiki: map()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh244306.aspx">MSDN: Observable.Select</a>
*/
public final <R> Observable<R> map(Func1<? super T, ? extends R> func) {
return lift(new OperatorMap<T, R>(func));
}
/**
* Turns all of the emissions and notifications from a source Observable into emissions marked with their
* original types within {@link Notification} objects.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/materialize.png">
*
* @return an Observable that emits items that are the result of materializing the items and notifications
* of the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-materialize">RxJava Wiki: materialize()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229453.aspx">MSDN: Observable.materialize</a>
*/
public final Observable<Notification<T>> materialize() {
return lift(new OperatorMaterialize<T>());
}
/**
* Returns an Observable that emits the results of applying a specified function to each item emitted by the
* source Observable, where that function returns an Observable, and then merging those resulting
* Observables and emitting the results of this merger.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeMap.png">
*
* @param func
* a function that, when applied to an item emitted by the source Observable, returns an
* Observable
* @return an Observable that emits the result of applying the transformation function to each item emitted
* by the source Observable and merging the results of the Observables obtained from these
* transformations
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-mapmany-or-flatmap-and-mapmanydelayerror">RxJava Wiki: flatMap()</a>
* @see #flatMap(Func1)
*/
public final <R> Observable<R> mergeMap(Func1<? super T, ? extends Observable<? extends R>> func) {
return merge(map(func));
}
/**
* Returns an Observable that applies a function to each item emitted or notification raised by the source
* Observable and then flattens the Observables returned from these functions and emits the resulting items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeMap.nce.png">
*
* @param <R>
* the result type
* @param onNext
* a function that returns an Observable to merge for each item emitted by the source Observable
* @param onError
* a function that returns an Observable to merge for an onError notification from the source
* Observable
* @param onCompleted
* a function that returns an Observable to merge for an onCompleted notification from the source
* Observable
* @return an Observable that emits the results of merging the Observables returned from applying the
* specified functions to the emissions and notifications of the source Observable
*/
public final <R> Observable<R> mergeMap(
Func1<? super T, ? extends Observable<? extends R>> onNext,
Func1<? super Throwable, ? extends Observable<? extends R>> onError,
Func0<? extends Observable<? extends R>> onCompleted) {
return lift(new OperatorMergeMapTransform<T, R>(onNext, onError, onCompleted));
}
/**
* Returns an Observable that emits the results of a specified function to the pair of values emitted by the
* source Observable and a specified collection Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeMap.r.png">
*
* @param <U>
* the type of items emitted by the collection Observable
* @param <R>
* the type of items emitted by the resulting Observable
* @param collectionSelector
* a function that returns an Observable for each item emitted by the source Observable
* @param resultSelector
* a function that combines one item emitted by each of the source and collection Observables and
* returns an item to be emitted by the resulting Observable
* @return an Observable that emits the results of applying a function to a pair of values emitted by the
* source Observable and the collection Observable
*/
public final <U, R> Observable<R> mergeMap(Func1<? super T, ? extends Observable<? extends U>> collectionSelector,
Func2<? super T, ? super U, ? extends R> resultSelector) {
return lift(new OperatorMergeMapPair<T, U, R>(collectionSelector, resultSelector));
}
/**
* Returns an Observable that merges each item emitted by the source Observable with the values in an
* Iterable corresponding to that item that is generated by a selector.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeMapIterable.png">
*
* @param <R>
* the type of item emitted by the resulting Observable
* @param collectionSelector
* a function that returns an Iterable sequence of values for when given an item emitted by the
* source Observable
* @return an Observable that emits the results of merging the items emitted by the source Observable with
* the values in the Iterables corresponding to those items, as generated by {@code collectionSelector}
*/
public final <R> Observable<R> mergeMapIterable(Func1<? super T, ? extends Iterable<? extends R>> collectionSelector) {
return merge(map(OperatorMergeMapPair.convertSelector(collectionSelector)));
}
/**
* Returns an Observable that emits the results of applying a function to the pair of values from the source
* Observable and an Iterable corresponding to that item that is generated by a selector.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeMapIterable.r.png">
*
* @param <U>
* the collection element type
* @param <R>
* the type of item emited by the resulting Observable
* @param collectionSelector
* a function that returns an Iterable sequence of values for each item emitted by the source
* Observable
* @param resultSelector
* a function that returns an item based on the item emitted by the source Observable and the
* Iterable returned for that item by the {@code collectionSelector}
* @return an Observable that emits the items returned by {@code resultSelector} for each item in the source
* Observable
*/
public final <U, R> Observable<R> mergeMapIterable(Func1<? super T, ? extends Iterable<? extends U>> collectionSelector,
Func2<? super T, ? super U, ? extends R> resultSelector) {
return mergeMap(OperatorMergeMapPair.convertSelector(collectionSelector), resultSelector);
}
/**
* Returns an Observable that emits items produced by multicasting the source Observable within a selector
* function.
*
* @param subjectFactory
* the {@link Subject} factory
* @param selector
* the selector function, which can use the multicasted source Observable subject to the policies
* enforced by the created {@code Subject}
* @return an Observable that emits the items produced by multicasting the source Observable within a
* selector function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablepublish-and-observablemulticast">RxJava: Observable.publish() and Observable.multicast()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229708.aspx">MSDN: Observable.Multicast</a>
*/
public final <TIntermediate, TResult> Observable<TResult> multicast(
final Func0<? extends Subject<? super T, ? extends TIntermediate>> subjectFactory,
final Func1<? super Observable<TIntermediate>, ? extends Observable<TResult>> selector) {
return create(new OperatorMulticastSelector<T, TIntermediate, TResult>(this, subjectFactory, selector));
}
/**
* Returns a {@link ConnectableObservable} that upon connection causes the source Observable to push results
* into the specified subject. A Connectable Observable resembles an ordinary Observable, except that it
* does not begin emitting items when it is subscribed to, but only when its <code>connect()</code> method
* is called.
*
* @param subject
* the {@link Subject} for the {@link ConnectableObservable} to push source items into
* @param <R>
* the type of items emitted by the resulting {@code ConnectableObservable}
* @return a {@link ConnectableObservable} that upon connection causes the source Observable to push results
* into the specified {@link Subject}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablepublish-and-observablemulticast">RxJava Wiki: Observable.publish() and
* Observable.multicast()</a>
*/
public final <R> ConnectableObservable<R> multicast(Subject<? super T, ? extends R> subject) {
return new OperatorMulticast<T, R>(this, subject);
}
/**
* Move notifications to the specified {@link Scheduler} asynchronously with an unbounded buffer.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/observeOn.png">
*
* @param scheduler
* the {@link Scheduler} to notify {@link Observer}s on
* @return the source Observable modified so that its {@link Observer}s are notified on the specified {@link Scheduler}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-observeon">RxJava Wiki: observeOn()</a>
*/
public final Observable<T> observeOn(Scheduler scheduler) {
return lift(new OperatorObserveOn<T>(scheduler));
}
/**
* Filters the items emitted by an Observable, only emitting those of the specified type.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/ofClass.png">
*
* @param klass
* the class type to filter the items emitted by the source Observable
* @return an Observable that emits items from the source Observable of type {@code klass}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-oftype">RxJava Wiki: ofType()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229380.aspx">MSDN: Observable.OfType</a>
*/
public final <R> Observable<R> ofType(final Class<R> klass) {
return filter(new Func1<T, Boolean>() {
public final Boolean call(T t) {
return klass.isInstance(t);
}
}).cast(klass);
}
/**
* Instruct an Observable to pass control to another Observable rather than invoking {@link Observer#onError onError} if it encounters an error.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/onErrorResumeNext.png">
* <p>
* By default, when an Observable encounters an error that prevents it from emitting the expected item to
* its {@link Observer}, the Observable invokes its Observer's {@code onError} method, and then quits
* without invoking any more of its Observer's methods. The {@code onErrorResumeNext} method changes this
* behavior. If you pass a function that returns an Observable ({@code resumeFunction}) to {@code onErrorResumeNext}, if the original Observable encounters an error, instead of invoking its
* Observer's {@code onError} method, it will instead relinquish control to the Observable returned from {@code resumeFunction}, which will invoke the Observer's {@link Observer#onNext onNext}
* method if it is
* able to do so. In such a case, because no Observable necessarily invokes {@code onError}, the Observer
* may never know that an error happened.
* <p>
* You can use this to prevent errors from propagating or to supply fallback data should errors be
* encountered.
*
* @param resumeFunction
* a function that returns an Observable that will take over if the source Observable encounters
* an error
* @return the original Observable, with appropriately modified behavior
* @see <a href="https://github.com/Netflix/RxJava/wiki/Error-Handling-Operators#wiki-onerrorresumenext">RxJava Wiki: onErrorResumeNext()</a>
*/
public final Observable<T> onErrorResumeNext(final Func1<Throwable, ? extends Observable<? extends T>> resumeFunction) {
return lift(new OperatorOnErrorResumeNextViaFunction<T>(resumeFunction));
}
/**
* Instruct an Observable to pass control to another Observable rather than invoking {@link Observer#onError onError} if it encounters an error.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/onErrorResumeNext.png">
* <p>
* By default, when an Observable encounters an error that prevents it from emitting the expected item to
* its {@link Observer}, the Observable invokes its Observer's {@code onError} method, and then quits
* without invoking any more of its Observer's methods. The {@code onErrorResumeNext} method changes this
* behavior. If you pass another Observable ({@code resumeSequence}) to an Observable's {@code onErrorResumeNext} method, if the original Observable encounters an error, instead of invoking its
* Observer's {@code onError} method, it will instead relinquish control to {@code resumeSequence} which
* will invoke the Observer's {@link Observer#onNext onNext} method if it is able to do so. In such a case,
* because no Observable necessarily invokes {@code onError}, the Observer may never know that an error
* happened.
* <p>
* You can use this to prevent errors from propagating or to supply fallback data should errors be
* encountered.
*
* @param resumeSequence
* a function that returns an Observable that will take over if the source Observable encounters
* an error
* @return the original Observable, with appropriately modified behavior
* @see <a href="https://github.com/Netflix/RxJava/wiki/Error-Handling-Operators#wiki-onerrorresumenext">RxJava Wiki: onErrorResumeNext()</a>
*/
public final Observable<T> onErrorResumeNext(final Observable<? extends T> resumeSequence) {
return lift(new OperatorOnErrorResumeNextViaObservable<T>(resumeSequence));
}
/**
* Instruct an Observable to emit an item (returned by a specified function) rather than invoking {@link Observer#onError onError} if it encounters an error.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/onErrorReturn.png">
* <p>
* By default, when an Observable encounters an error that prevents it from emitting the expected item to
* its {@link Observer}, the Observable invokes its Observer's {@code onError} method, and then quits
* without invoking any more of its Observer's methods. The {@code onErrorReturn} method changes this
* behavior. If you pass a function ({@code resumeFunction}) to an Observable's {@code onErrorReturn} method, if the original Observable encounters an error, instead of invoking its Observer's
* {@code onError} method, it will instead emit the return value of {@code resumeFunction}.
* <p>
* You can use this to prevent errors from propagating or to supply fallback data should errors be
* encountered.
*
* @param resumeFunction
* a function that returns an item that the new Observable will emit if the source Observable
* encounters an error
* @return the original Observable with appropriately modified behavior
* @see <a href="https://github.com/Netflix/RxJava/wiki/Error-Handling-Operators#wiki-onerrorreturn">RxJava Wiki: onErrorReturn()</a>
*/
public final Observable<T> onErrorReturn(Func1<Throwable, ? extends T> resumeFunction) {
return lift(new OperatorOnErrorReturn<T>(resumeFunction));
}
/**
* Allows inserting onNext events into a stream when onError events are received and continuing the original
* sequence instead of terminating. Thus it allows a sequence with multiple onError events.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/onErrorFlatMap.png">
*
* @param resumeFunction
* a function that accepts an {@link OnErrorThrowable} representing the Throwable issued by the
* source Observable, and returns an Observable that issues items that will be emitted in place
* of the error
* @return the original Observable, with appropriately modified behavior
* @see <a href="https://github.com/Netflix/RxJava/wiki/Error-Handling-Operators#onerrorflatmap">RxJava Wiki: onErrorFlatMap()</a>
* @since 0.17
*/
public final Observable<T> onErrorFlatMap(final Func1<OnErrorThrowable, ? extends Observable<? extends T>> resumeFunction) {
return lift(new OperatorOnErrorFlatMap<T>(resumeFunction));
}
/**
* Instruct an Observable to pass control to another Observable rather than invoking {@link Observer#onError onError} if it encounters an {@link java.lang.Exception}.
* <p>
* This differs from {@link #onErrorResumeNext} in that this one does not handle {@link java.lang.Throwable} or {@link java.lang.Error} but lets those continue through.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/onExceptionResumeNextViaObservable.png">
* <p>
* By default, when an Observable encounters an exception that prevents it from emitting the expected item
* to its {@link Observer}, the Observable invokes its Observer's {@code onError} method, and then quits
* without invoking any more of its Observer's methods. The {@code onExceptionResumeNext} method changes
* this behavior. If you pass another Observable ({@code resumeSequence}) to an Observable's {@code onExceptionResumeNext} method, if the original Observable encounters an exception, instead of
* invoking its Observer's {@code onError} method, it will instead relinquish control to {@code resumeSequence} which will invoke the Observer's {@link Observer#onNext onNext} method if it is
* able to do so. In such a case, because no Observable necessarily invokes {@code onError}, the Observer
* may never know that an exception happened.
* <p>
* You can use this to prevent exceptions from propagating or to supply fallback data should exceptions be
* encountered.
*
* @param resumeSequence
* a function that returns an Observable that will take over if the source Observable encounters
* an exception
* @return the original Observable, with appropriately modified behavior
* @see <a href="https://github.com/Netflix/RxJava/wiki/Error-Handling-Operators#wiki-onexceptionresumenext">RxJava Wiki: onExceptionResumeNext()</a>
*/
public final Observable<T> onExceptionResumeNext(final Observable<? extends T> resumeSequence) {
return lift(new OperatorOnExceptionResumeNextViaObservable<T>(resumeSequence));
}
/**
* Perform work on the source {@code Observable<T>} in parallel by sharding it on a {@link Schedulers#computation()} {@link Scheduler}, and return the resulting {@code Observable<R>}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/parallel.png">
*
* @param f
* a {@link Func1} that applies Observable Observers to {@code Observable<T>} in parallel and
* returns an {@code Observable<R>}
* @return an Observable that emits the results of applying {@code f} to the items emitted by the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-parallel">RxJava Wiki: parallel()</a>
*/
public final <R> Observable<R> parallel(Func1<Observable<T>, Observable<R>> f) {
return lift(new OperatorParallel<T, R>(f, Schedulers.computation()));
}
/**
* Perform work on the source {@code Observable<T>} in parallel by sharding it on a {@link Scheduler}, and
* return the resulting {@code Observable<R>}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/parallel.png">
*
* @param f
* a {@link Func1} that applies Observable Observers to {@code Observable<T>} in parallel and
* returns an {@code Observable<R>}
* @param s
* a {@link Scheduler} to perform the work on
* @return an Observable that emits the results of applying {@code f} to the items emitted by the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-parallel">RxJava Wiki: parallel()</a>
*/
public final <R> Observable<R> parallel(final Func1<Observable<T>, Observable<R>> f, final Scheduler s) {
return lift(new OperatorParallel<T, R>(f, s));
}
/**
* Returns a {@link ConnectableObservable}, which waits until its
* {@link ConnectableObservable#connect connect} method is called before it begins emitting items to those
* {@link Observer}s that have subscribed to it.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/publishConnect.png">
*
* @return a {@link ConnectableObservable} that upon connection causes the source Observable to emit items
* to its {@link Observer}s
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablepublish-and-observablemulticast">RxJava Wiki: publish()</a>
*/
public final ConnectableObservable<T> publish() {
return new OperatorMulticast<T, T>(this, PublishSubject.<T> create());
}
/**
* Returns an Observable that emits the results of invoking a specified selector on items emitted by a {@link ConnectableObservable} that shares a single subscription to the underlying sequence.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/publishConnect.f.png">
*
* @param <R>
* the type of items emitted by the resulting Observable
* @param selector
* a function that can use the multicasted source sequence as many times as needed, without
* causing multiple subscriptions to the source sequence. Subscribers to the given source will
* receive all notifications of the source from the time of the subscription forward.
* @return an Observable that emits the results of invoking the selector on the items emitted by a {@link ConnectableObservable} that shares a single subscription to the underlying sequence
*/
public final <R> Observable<R> publish(Func1<? super Observable<T>, ? extends Observable<R>> selector) {
return multicast(new Func0<Subject<T, T>>() {
@Override
public final Subject<T, T> call() {
return PublishSubject.create();
}
}, selector);
}
/**
* Returns an Observable that emits {@code initialValue} followed by the results of invoking a specified
* selector on items emitted by a {@link ConnectableObservable} that shares a single subscription to the
* source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/publishConnect.if.png">
*
* @param <R>
* the type of items emitted by the resulting Observable
* @param selector
* a function that can use the multicasted source sequence as many times as needed, without
* causing multiple subscriptions to the source Observable. Subscribers to the source will
* receive all notifications of the source from the time of the subscription forward
* @param initialValue
* the initial value of the underlying {@link BehaviorSubject}
* @return an Observable that emits {@code initialValue} followed by the results of invoking the selector
* on a {@link ConnectableObservable} that shares a single subscription to the underlying Observable
*/
public final <R> Observable<R> publish(Func1<? super Observable<T>, ? extends Observable<R>> selector, final T initialValue) {
return multicast(new Func0<Subject<T, T>>() {
@Override
public final Subject<T, T> call() {
return BehaviorSubject.create(initialValue);
}
}, selector);
}
/**
* Returns a {@link ConnectableObservable} that emits {@code initialValue} followed by the items emitted by
* the source Observable. A Connectable Observable resembles an ordinary Observable, except that it does not
* begin emitting items when it is subscribed to, but only when its <code>connect()</code> method is called.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/publishConnect.i.png">
*
* @param initialValue
* the initial value to be emitted by the resulting Observable
* @return a {@link ConnectableObservable} that shares a single subscription to the underlying Observable
* and starts with {@code initialValue}
*/
public final ConnectableObservable<T> publish(T initialValue) {
return new OperatorMulticast<T, T>(this, BehaviorSubject.<T> create(initialValue));
}
/**
* Returns a {@link ConnectableObservable} that emits only the last item emitted by the source Observable.
* A Connectable Observable resembles an ordinary Observable, except that it does not begin emitting items
* when it is subscribed to, but only when its <code>connect()</code> method is called.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/publishLast.png">
*
* @return a {@link ConnectableObservable} that emits only the last item emitted by the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablepublishlast">RxJava Wiki: publishLast()</a>
*/
public final ConnectableObservable<T> publishLast() {
return new OperatorMulticast<T, T>(this, AsyncSubject.<T> create());
}
/**
* Returns an Observable that emits an item that results from invoking a specified selector on the last item
* emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/publishLast.f.png">
*
* @param <R>
* the type of items emitted by the resulting Observable
* @param selector
* a function that can use the multicasted source sequence as many times as needed, without
* causing multiple subscriptions to the source Observable. Subscribers to the source will only
* receive the last item emitted by the source.
* @return an Observable that emits an item that is the result of invoking the selector on a {@link ConnectableObservable} that shares a single subscription to the source Observable
*/
public final <R> Observable<R> publishLast(Func1<? super Observable<T>, ? extends Observable<R>> selector) {
return multicast(new Func0<Subject<T, T>>() {
@Override
public final Subject<T, T> call() {
return AsyncSubject.create();
}
}, selector);
}
/**
* Returns an Observable that applies a function of your choosing to the first item emitted by a source
* Observable, then feeds the result of that function along with the second item emitted by the source
* Observable into the same function, and so on until all items have been emitted by the source Observable,
* and emits the final result from the final call to your function as its sole item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/reduce.png">
* <p>
* This technique, which is called "reduce" here, is sometimes called "aggregate," "fold," "accumulate,"
* "compress," or "inject" in other programming contexts. Groovy, for instance, has an {@code inject()} method that does a similar operation on lists.
*
* @param accumulator
* an accumulator function to be invoked on each item emitted by the source Observable, whose
* result will be used in the next accumulator call
* @return an Observable that emits a single item that is the result of accumulating the items emitted by
* the source Observable
* @throws IllegalArgumentException
* if the source Observable emits no items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-reduce">RxJava Wiki: reduce()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229154.aspx">MSDN: Observable.Aggregate</a>
* @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a>
*/
public final Observable<T> reduce(Func2<T, T, T> accumulator) {
/*
* Discussion and confirmation of implementation at
* https://github.com/Netflix/RxJava/issues/423#issuecomment-27642532
*
* It should use last() not takeLast(1) since it needs to emit an error if the sequence is empty.
*/
return scan(accumulator).last();
}
/**
* Returns an Observable that applies a function of your choosing to the first item emitted by a source
* Observable and a specified seed value, then feeds the result of that function along with the second item
* emitted by an Observable into the same function, and so on until all items have been emitted by the
* source Observable, emitting the final result from the final call to your function as its sole item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/reduceSeed.png">
* <p>
* This technique, which is called "reduce" here, is sometimec called "aggregate," "fold," "accumulate,"
* "compress," or "inject" in other programming contexts. Groovy, for instance, has an {@code inject()} method that does a similar operation on lists.
*
* @param initialValue
* the initial (seed) accumulator value
* @param accumulator
* an accumulator function to be invoked on each item emitted by the source Observable, the
* result of which will be used in the next accumulator call
* @return an Observable that emits a single item that is the result of accumulating the output from the
* items emitted by the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-reduce">RxJava Wiki: reduce()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229154.aspx">MSDN: Observable.Aggregate</a>
* @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a>
*/
public final <R> Observable<R> reduce(R initialValue, Func2<R, ? super T, R> accumulator) {
return scan(initialValue, accumulator).takeLast(1);
}
/**
* Returns an Observable that repeats the sequence of items emitted by the source Observable indefinitely.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/repeat.o.png">
*
* @return an Observable that emits the items emitted by the source Observable repeatedly and in sequence
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-repeat">RxJava Wiki: repeat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229428.aspx">MSDN: Observable.Repeat</a>
*/
public final Observable<T> repeat() {
return nest().lift(new OperatorRepeat<T>());
}
/**
* Returns an Observable that repeats the sequence of items emitted by the source Observable indefinitely,
* on a particular Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/repeat.os.png">
*
* @param scheduler
* the Scheduler to emit the items on
* @return an Observable that emits the items emitted by the source Observable repeatedly and in sequence
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-repeat">RxJava Wiki: repeat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229428.aspx">MSDN: Observable.Repeat</a>
*/
public final Observable<T> repeat(Scheduler scheduler) {
return nest().lift(new OperatorRepeat<T>(scheduler));
}
/**
* Returns an Observable that repeats the sequence of items emitted by the source Observable at most {@code count} times.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/repeat.on.png">
*
* @param count
* the number of times the source Observable items are repeated, a count of 0 will yield an empty
* sequence
* @return an Observable that repeats the sequence of items emitted by the source Observable at most {@code count} times
* @throws IllegalArgumentException
* if {@code count} is less than zero
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-repeat">RxJava Wiki: repeat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229428.aspx">MSDN: Observable.Repeat</a>
* @since 0.17
*/
public final Observable<T> repeat(long count) {
if (count < 0) {
throw new IllegalArgumentException("count >= 0 expected");
}
return nest().lift(new OperatorRepeat<T>(count));
}
/**
* Returns an Observable that repeats the sequence of items emitted by the source Observable at most {@code count} times, on a particular Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/repeat.ons.png">
*
* @param count
* the number of times the source Observable items are repeated, a count of 0 will yield an empty
* sequence
* @param scheduler
* the {@link Scheduler} to emit the items on
* @return an Observable that repeats the sequence of items emitted by the source Observable at most {@code count} times on a particular Scheduler
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-repeat">RxJava Wiki: repeat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229428.aspx">MSDN: Observable.Repeat</a>
* @since 0.17
*/
public final Observable<T> repeat(long count, Scheduler scheduler) {
return nest().lift(new OperatorRepeat<T>(count, scheduler));
}
/**
* Returns a {@link ConnectableObservable} that shares a single subscription to the underlying Observable
* that will replay all of its items and notifications to any future {@link Observer}. A Connectable
* Observable resembles an ordinary Observable, except that it does not begin emitting items when it is
* subscribed to, but only when its <code>connect()</code> method is called.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.png">
*
* @return a {@link ConnectableObservable} that upon connection causes the source Observable to emit its
* items to its {@link Observer}s
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
*/
public final ConnectableObservable<T> replay() {
return new OperatorMulticast<T, T>(this, ReplaySubject.<T> create());
}
/**
* Returns an Observable that emits items that are the results of invoking a specified selector on the items
* emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.f.png">
*
* @param <R>
* the type of items emitted by the resulting Observable
* @param selector
* the selector function, which can use the multicasted sequence as many times as needed, without
* causing multiple subscriptions to the Observable
* @return an Observable that emits items that are the results of invoking the selector on a {@link ConnectableObservable} that shares a single subscription to the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229653.aspx">MSDN: Observable.Replay</a>
*/
public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector) {
return create(new OperatorMulticastSelector<T, T, R>(this, new Func0<Subject<T, T>>() {
@Override
public final Subject<T, T> call() {
return ReplaySubject.create();
}
}, selector));
}
/**
* Returns an Observable that emits items that are the results of invoking a specified selector on items
* emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable,
* replaying {@code bufferSize} notifications.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.fn.png">
*
* @param <R>
* the type of items emitted by the resulting Observable
* @param selector
* the selector function, which can use the multicasted sequence as many times as needed, without
* causing multiple subscriptions to the Observable
* @param bufferSize
* the buffer size that limits the number of items the connectable observable can replay
* @return an Observable that emits items that are the results of invoking the selector on items emitted by
* a {@link ConnectableObservable} that shares a single subscription to the source Observable
* replaying no more than {@code bufferSize} items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211675.aspx">MSDN: Observable.Replay</a>
*/
public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, final int bufferSize) {
return create(new OperatorMulticastSelector<T, T, R>(this, new Func0<Subject<T, T>>() {
@Override
public final Subject<T, T> call() {
return ReplaySubject.<T>createWithSize(bufferSize);
}
}, selector));
}
/**
* Returns an Observable that emits items that are the results of invoking a specified selector on items
* emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable,
* replaying no more than {@code bufferSize} items that were emitted within a specified time window.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.fnt.png">
*
* @param <R>
* the type of items emitted by the resulting Observable
* @param selector
* a selector function, which can use the multicasted sequence as many times as needed, without
* causing multiple subscriptions to the Observable
* @param bufferSize
* the buffer size that limits the number of items the connectable observable can replay
* @param time
* the duration of the window in which the replayed items must have been emitted
* @param unit
* the time unit of {@code time}
* @return an Observable that emits items that are the results of invoking the selector on items emitted by
* a {@link ConnectableObservable} that shares a single subscription to the source Observable, and
* replays no more than {@code bufferSize} items that were emitted within the window defined by {@code time}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh228952.aspx">MSDN: Observable.Replay</a>
*/
public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, int bufferSize, long time, TimeUnit unit) {
return replay(selector, bufferSize, time, unit, Schedulers.computation());
}
/**
* Returns an Observable that emits items that are the results of invoking a specified selector on items
* emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable,
* replaying no more than {@code bufferSize} items that were emitted within a specified time window.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.fnts.png">
*
* @param <R>
* the type of items emitted by the resulting Observable
* @param selector
* a selector function, which can use the multicasted sequence as many times as needed, without
* causing multiple subscriptions to the Observable
* @param bufferSize
* the buffer size that limits the number of items the connectable observable can replay
* @param time
* the duration of the window in which the replayed items must have been emitted
* @param unit
* the time unit of {@code time}
* @param scheduler
* the Scheduler that is the time source for the window
* @return an Observable that emits items that are the results of invoking the selector on items emitted by
* a {@link ConnectableObservable} that shares a single subscription to the source Observable, and
* replays no more than {@code bufferSize} items that were emitted within the window defined by {@code time}
* @throws IllegalArgumentException
* if {@code bufferSize} is less than zero
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229404.aspx">MSDN: Observable.Replay</a>
*/
public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, final int bufferSize, final long time, final TimeUnit unit, final Scheduler scheduler) {
if (bufferSize < 0) {
throw new IllegalArgumentException("bufferSize < 0");
}
return create(new OperatorMulticastSelector<T, T, R>(this, new Func0<Subject<T, T>>() {
@Override
public final Subject<T, T> call() {
return ReplaySubject.<T>createWithTimeAndSize(time, unit, bufferSize, scheduler);
}
}, selector));
}
/**
* Returns an Observable that emits items that are the results of invoking a specified selector on items
* emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable,
* replaying a maximum of {@code bufferSize} items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.fns.png">
*
* @param <R>
* the type of items emitted by the resulting Observable
* @param selector
* a selector function, which can use the multicasted sequence as many times as needed, without
* causing multiple subscriptions to the Observable
* @param bufferSize
* the buffer size that limits the number of items the connectable observable can replay
* @param scheduler
* the Scheduler on which the replay is observed
* @return an Observable that emits items that are the results of invoking the selector on items emitted by
* a {@link ConnectableObservable} that shares a single subscription to the source Observable,
* replaying no more than {@code bufferSize} notifications
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229928.aspx">MSDN: Observable.Replay</a>
*/
public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, final int bufferSize, final Scheduler scheduler) {
return create(new OperatorMulticastSelector<T, T, R>(this, new Func0<Subject<T, T>>() {
@Override
public final Subject<T, T> call() {
return OperatorReplay.<T> createScheduledSubject(ReplaySubject.<T>createWithSize(bufferSize), scheduler);
}
}, selector));
}
/**
* Returns an Observable that emits items that are the results of invoking a specified selector on items
* emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable,
* replaying all items that were emitted within a specified time window.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.ft.png">
*
* @param <R>
* the type of items emitted by the resulting Observable
* @param selector
* a selector function, which can use the multicasted sequence as many times as needed, without
* causing multiple subscriptions to the Observable
* @param time
* the duration of the window in which the replayed items must have been emitted
* @param unit
* the time unit of {@code time}
* @return an Observable that emits items that are the results of invoking the selector on items emitted by
* a {@link ConnectableObservable} that shares a single subscription to the source Observable,
* replaying all items that were emitted within the window defined by {@code time}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229526.aspx">MSDN: Observable.Replay</a>
*/
public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, long time, TimeUnit unit) {
return replay(selector, time, unit, Schedulers.computation());
}
/**
* Returns an Observable that emits items that are the results of invoking a specified selector on items
* emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable,
* replaying all items that were emitted within a specified time window.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.fts.png">
*
* @param <R>
* the type of items emitted by the resulting Observable
* @param selector
* a selector function, which can use the multicasted sequence as many times as needed, without
* causing multiple subscriptions to the Observable
* @param time
* the duration of the window in which the replayed items must have been emitted
* @param unit
* the time unit of {@code time}
* @param scheduler
* the scheduler that is the time source for the window
* @return an Observable that emits items that are the results of invoking the selector on items emitted by
* a {@link ConnectableObservable} that shares a single subscription to the source Observable,
* replaying all items that were emitted within the window defined by {@code time}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh244327.aspx">MSDN: Observable.Replay</a>
*/
public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, final long time, final TimeUnit unit, final Scheduler scheduler) {
return create(new OperatorMulticastSelector<T, T, R>(this, new Func0<Subject<T, T>>() {
@Override
public final Subject<T, T> call() {
return ReplaySubject.<T>createWithTime(time, unit, scheduler);
}
}, selector));
}
/**
* Returns an Observable that emits items that are the results of invoking a specified selector on items
* emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.fs.png">
*
* @param <R>
* the type of items emitted by the resulting Observable
* @param selector
* a selector function, which can use the multicasted sequence as many times as needed, without
* causing multiple subscriptions to the Observable
* @param scheduler
* the Scheduler where the replay is observed
* @return an Observable that emits items that are the results of invoking the selector on items emitted by
* a {@link ConnectableObservable} that shares a single subscription to the source Observable,
* replaying all items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211644.aspx">MSDN: Observable.Replay</a>
*/
public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, final Scheduler scheduler) {
return create(new OperatorMulticastSelector<T, T, R>(this, new Func0<Subject<T, T>>() {
@Override
public final Subject<T, T> call() {
return OperatorReplay.createScheduledSubject(ReplaySubject.<T> create(), scheduler);
}
}, selector));
}
/**
* Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable that
* replays at most {@code bufferSize} items emitted by that Observable. A Connectable Observable resembles
* an ordinary Observable, except that it does not begin emitting items when it is subscribed to, but only
* when its <code>connect()</code> method is called.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.n.png">
*
* @param bufferSize
* the buffer size that limits the number of items that can be replayed
* @return a {@link ConnectableObservable} that shares a single subscription to the source Observable and
* replays at most {@code bufferSize} items emitted by that Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211976.aspx">MSDN: Observable.Replay</a>
*/
public final ConnectableObservable<T> replay(int bufferSize) {
return new OperatorMulticast<T, T>(this, ReplaySubject.<T>createWithSize(bufferSize));
}
/**
* Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable and
* replays at most {@code bufferSize} items that were emitted during a specified time window. A Connectable
* Observable resembles an ordinary Observable, except that it does not begin emitting items when it is
* subscribed to, but only when its <code>connect()</code> method is called.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.nt.png">
*
* @param bufferSize
* the buffer size that limits the number of items that can be replayed
* @param time
* the duration of the window in which the replayed items must have been emitted
* @param unit
* the time unit of {@code time}
* @return a {@link ConnectableObservable} that shares a single subscription to the source Observable and
* replays at most {@code bufferSize} items that were emitted during the window defined by {@code time}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229874.aspx">MSDN: Observable.Replay</a>
*/
public final ConnectableObservable<T> replay(int bufferSize, long time, TimeUnit unit) {
return replay(bufferSize, time, unit, Schedulers.computation());
}
/**
* Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable and
* that replays a maximum of {@code bufferSize} items that are emitted within a specified time window. A
* Connectable Observable resembles an ordinary Observable, except that it does not begin emitting items
* when it is subscribed to, but only when its <code>connect()</code> method is called.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.nts.png">
*
* @param bufferSize
* the buffer size that limits the number of items that can be replayed
* @param time
* the duration of the window in which the replayed items must have been emitted
* @param unit
* the time unit of {@code time}
* @param scheduler
* the scheduler that is used as a time source for the window
* @return a {@link ConnectableObservable} that shares a single subscription to the source Observable and
* replays at most {@code bufferSize} items that were emitted during the window defined by {@code time}
* @throws IllegalArgumentException
* if {@code bufferSize} is less than zero
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211759.aspx">MSDN: Observable.Replay</a>
*/
public final ConnectableObservable<T> replay(int bufferSize, long time, TimeUnit unit, Scheduler scheduler) {
if (bufferSize < 0) {
throw new IllegalArgumentException("bufferSize < 0");
}
return new OperatorMulticast<T, T>(this, ReplaySubject.<T>createWithTimeAndSize(time, unit, bufferSize, scheduler));
}
/**
* Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable and
* replays at most {@code bufferSize} items emitted by that Observable. A Connectable Observable resembles
* an ordinary Observable, except that it does not begin emitting items when it is subscribed to, but only
* when its <code>connect()</code> method is called.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.ns.png">
*
* @param bufferSize
* the buffer size that limits the number of items that can be replayed
* @param scheduler
* the scheduler on which the Observers will observe the emitted items
* @return a {@link ConnectableObservable} that shares a single subscription to the source Observable and
* replays at most {@code bufferSize} items that were emitted by the Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229814.aspx">MSDN: Observable.Replay</a>
*/
public final ConnectableObservable<T> replay(int bufferSize, Scheduler scheduler) {
return new OperatorMulticast<T, T>(this,
OperatorReplay.createScheduledSubject(
ReplaySubject.<T>createWithSize(bufferSize), scheduler));
}
/**
* Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable and
* replays all items emitted by that Observable within a specified time window. A Connectable Observable
* resembles an ordinary Observable, except that it does not begin emitting items when it is subscribed to,
* but only when its <code>connect()</code> method is called.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.t.png">
*
* @param time
* the duration of the window in which the replayed items must have been emitted
* @param unit
* the time unit of {@code time}
* @return a {@link ConnectableObservable} that shares a single subscription to the source Observable and
* replays the items that were emitted during the window defined by {@code time}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229232.aspx">MSDN: Observable.Replay</a>
*/
public final ConnectableObservable<T> replay(long time, TimeUnit unit) {
return replay(time, unit, Schedulers.computation());
}
/**
* Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable and
* replays all items emitted by that Observable within a specified time window. A Connectable Observable
* resembles an ordinary Observable, except that it does not begin emitting items when it is subscribed to,
* but only when its <code>connect()</code> method is called.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.ts.png">
*
* @param time
* the duration of the window in which the replayed items must have been emitted
* @param unit
* the time unit of {@code time}
* @param scheduler
* the Scheduler that is the time source for the window
* @return a {@link ConnectableObservable} that shares a single subscription to the source Observable and
* replays the items that were emitted during the window defined by {@code time}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211811.aspx">MSDN: Observable.Replay</a>
*/
public final ConnectableObservable<T> replay(long time, TimeUnit unit, Scheduler scheduler) {
return new OperatorMulticast<T, T>(this, ReplaySubject.<T>createWithTime(time, unit, scheduler));
}
/**
* Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable that
* will replay all of its items and notifications to any future {@link Observer} on the given
* {@link Scheduler}. A Connectable Observable resembles an ordinary Observable, except that it does not
* begin emitting items when it is subscribed to, but only when its <code>connect()</code> method is called.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.s.png">
*
* @param scheduler
* the Scheduler on which the Observers will observe the emitted items
* @return a {@link ConnectableObservable} that shares a single subscription to the source Observable that
* will replay all of its items and notifications to any future {@link Observer} on the given {@link Scheduler}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211699.aspx">MSDN: Observable.Replay</a>
*/
public final ConnectableObservable<T> replay(Scheduler scheduler) {
return new OperatorMulticast<T, T>(this, OperatorReplay.createScheduledSubject(ReplaySubject.<T> create(), scheduler));
}
/**
* Return an Observable that mirrors the source Observable, resubscribing to it if it calls {@code onError} (infinite retry count).
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/retry.png">
* <p>
* If the source Observable calls {@link Observer#onError}, this method will resubscribe to the source
* Observable rather than propagating the {@code onError} call.
* <p>
* Any and all items emitted by the source Observable will be emitted by the resulting Observable, even
* those emitted during failed subscriptions. For example, if an Observable fails at first but emits {@code [1, 2]} then succeeds the second time and emits {@code [1, 2, 3, 4, 5]} then the
* complete sequence
* of emissions and notifications would be {@code [1, 2, 1, 2, 3, 4, 5, onCompleted]}.
*
* @return the source Observable modified with retry logic
* @see <a href="https://github.com/Netflix/RxJava/wiki/Error-Handling-Operators#wiki-retry">RxJava Wiki: retry()</a>
*/
public final Observable<T> retry() {
return nest().lift(new OperatorRetry<T>());
}
/**
* Return an Observable that mirrors the source Observable, resubscribing to it if it calls {@code onError} up to a specified number of retries.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/retry.png">
* <p>
* If the source Observable calls {@link Observer#onError}, this method will resubscribe to the source
* Observable for a maximum of {@code retryCount} resubscriptions rather than propagating the {@code onError} call.
* <p>
* Any and all items emitted by the source Observable will be emitted by the resulting Observable, even
* those emitted during failed subscriptions. For example, if an Observable fails at first but emits {@code [1, 2]} then succeeds the second time and emits {@code [1, 2, 3, 4, 5]} then the
* complete sequence
* of emissions and notifications would be {@code [1, 2, 1, 2, 3, 4, 5, onCompleted]}.
*
* @param retryCount
* number of retry attempts before failing
* @return the source Observable modified with retry logic
* @see <a href="https://github.com/Netflix/RxJava/wiki/Error-Handling-Operators#wiki-retry">RxJava Wiki: retry()</a>
*/
public final Observable<T> retry(int retryCount) {
return nest().lift(new OperatorRetry<T>(retryCount));
}
/**
* Returns an Observable that emits the most recently emitted item (if any) emitted by the source Observable
* within periodic time intervals.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/sample.png">
*
* @param period
* the sampling rate
* @param unit
* the {@link TimeUnit} in which {@code period} is defined
* @return an Observable that emits the results of sampling the items emitted by the source Observable at
* the specified time interval
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-sample-or-throttlelast">RxJava Wiki: sample()</a>
*/
public final Observable<T> sample(long period, TimeUnit unit) {
return lift(new OperatorSampleWithTime<T>(period, unit, Schedulers.computation()));
}
/**
* Returns an Observable that emits the most recently emitted item (if any) emitted by the source Observable
* within periodic time intervals, where the intervals are defined on a particular Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/sample.s.png">
*
* @param period
* the sampling rate
* @param unit
* the {@link TimeUnit} in which {@code period} is defined
* @param scheduler
* the {@link Scheduler} to use when sampling
* @return an Observable that emits the results of sampling the items emitted by the source Observable at
* the specified time interval
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-sample-or-throttlelast">RxJava Wiki: sample()</a>
*/
public final Observable<T> sample(long period, TimeUnit unit, Scheduler scheduler) {
return lift(new OperatorSampleWithTime<T>(period, unit, scheduler));
}
/**
* Returns an Observable that, when the specified {@code sampler} Observable emits an item or completes,
* emits the most recently emitted item (if any) emitted by the source Observable since the previous
* emission from the {@code sampler} Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/sample.o.png">
*
* @param sampler
* the Observable to use for sampling the source Observable
* @return an Observable that emits the results of sampling the items emitted by this Observable whenever
* the {@code sampler} Observable emits an item or completes
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-sample-or-throttlelast">RxJava Wiki: sample()</a>
*/
public final <U> Observable<T> sample(Observable<U> sampler) {
return lift(new OperatorSampleWithObservable<T, U>(sampler));
}
/**
* Returns an Observable that applies a function of your choosing to the first item emitted by a source
* Observable, then feeds the result of that function along with the second item emitted by the source
* Observable into the same function, and so on until all items have been emitted by the source Observable,
* emitting the result of each of these iterations.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/scan.png">
* <p>
* This sort of function is sometimes called an accumulator.
*
* @param accumulator
* an accumulator function to be invoked on each item emitted by the source Observable, whose
* result will be emitted to {@link Observer}s via {@link Observer#onNext onNext} and used in the
* next accumulator call
* @return an Observable that emits the results of each call to the accumulator function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-scan">RxJava Wiki: scan()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211665.aspx">MSDN: Observable.Scan</a>
*/
public final Observable<T> scan(Func2<T, T, T> accumulator) {
return lift(new OperatorScan<T, T>(accumulator));
}
/**
* Returns an Observable that applies a function of your choosing to the first item emitted by a source
* Observable and a seed value, then feeds the result of that function along with the second item emitted by
* the source Observable into the same function, and so on until all items have been emitted by the source
* Observable, emitting the result of each of these iterations.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/scanSeed.png">
* <p>
* This sort of function is sometimes called an accumulator.
* <p>
* Note that the Observable that results from this method will emit {@code initialValue} as its first
* emitted item.
*
* @param initialValue
* the initial (seed) accumulator item
* @param accumulator
* an accumulator function to be invoked on each item emitted by the source Observable, whose
* result will be emitted to {@link Observer}s via {@link Observer#onNext onNext} and used in the
* next accumulator call
* @return an Observable that emits {@code initialValue} followed by the results of each call to the
* accumulator function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-scan">RxJava Wiki: scan()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211665.aspx">MSDN: Observable.Scan</a>
*/
public final <R> Observable<R> scan(R initialValue, Func2<R, ? super T, R> accumulator) {
return lift(new OperatorScan<R, T>(initialValue, accumulator));
}
/*
* Forces an Observable to make synchronous calls and to be well-behaved.
* <p>
* It is possible for an Observable to invoke its Subscribers' methods asynchronously, perhaps in different
* threads. This could make an Observable poorly-behaved, in that it might invoke {@code onCompleted} or
* {@code onError} before one of its {@code onNext} invocations. You can force such an Observable to be
* well-behaved and synchronous by applying the {@code serialize()} method to it.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/synchronize.png">
*
* @return a {@link Observable} that is guaranteed to be well-behaved and synchronous
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#serialize">RxJava Wiki: serialize()</a>
* @since 0.17
*/
public final Observable<T> serialize() {
return lift(new OperatorSerialize<T>());
}
/**
* Returns a new {@link Observable} that multicasts (shares) the original {@link Observable}. As long as
* there is more than 1 {@link Subscriber} this {@link Observable} will be subscribed and emitting data.
* When all subscribers have unsubscribed it will unsubscribe from the source {@link Observable}.
* <p>
* This is an alias for {@link #publish().refCount()}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/publishRefCount.png">
*
* @return a {@link Observable} that upon connection causes the source Observable to emit items
* to its {@link Observer}s
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#connectableobservablerefcount">RxJava Wiki: refCount()</a>
* @since 0.19
*/
public final Observable<T> share() {
return publish().refCount();
}
/**
* If the source Observable completes after emitting a single item, return an Observable that emits that
* item. If the source Observable emits more than one item or no items, throw an {@code NoSuchElementException}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/single.png">
*
* @return an Observable that emits the single item emitted by the source Observable
* @throws IllegalArgumentException
* if the source emits more than one item
* @throws NoSuchElementException
* if the source emits no items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-single-and-singleordefault">RxJava Wiki: single()</a>
* @see "MSDN: Observable.singleAsync()"
*/
public final Observable<T> single() {
return lift(new OperatorSingle<T>());
}
/**
* If the Observable completes after emitting a single item that matches a specified predicate, return an
* Observable that emits that item. If the source Observable emits more than one such item or no such items,
* throw an {@code NoSuchElementException}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/single.p.png">
*
* @param predicate
* a predicate function to evaluate items emitted by the source Observable
* @return an Observable that emits the single item emitted by the source Observable that matches the
* predicate
* @throws IllegalArgumentException
* if the source Observable emits more than one item that matches the predicate
* @throws NoSuchElementException
* if the source Observable emits no item that matches the predicate
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-single-and-singleordefault">RxJava Wiki: single()</a>
* @see "MSDN: Observable.singleAsync()"
*/
public final Observable<T> single(Func1<? super T, Boolean> predicate) {
return filter(predicate).single();
}
/**
* If the source Observable completes after emitting a single item, return an Observable that emits that
* item; if the source Observable is empty, return an Observable that emits a default item. If the source
* Observable emits more than one item, throw an {@code IllegalArgumentException.} <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/singleOrDefault.png">
*
* @param defaultValue
* a default value to emit if the source Observable emits no item
* @return an Observable that emits the single item emitted by the source Observable, or a default item if
* the source Observable is empty
* @throws IllegalArgumentException
* if the source Observable emits more than one item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-single-and-singleordefault">RxJava Wiki: single()</a>
* @see "MSDN: Observable.singleOrDefaultAsync()"
*/
public final Observable<T> singleOrDefault(T defaultValue) {
return lift(new OperatorSingle<T>(defaultValue));
}
/**
* If the Observable completes after emitting a single item that matches a predicate, return an Observable
* that emits that item; if the source Observable emits no such item, return an Observable that emits a
* default item. If the source Observable emits more than one such item, throw an {@code IllegalArgumentException}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/singleOrDefault.p.png">
*
* @param defaultValue
* a default item to emit if the source Observable emits no matching items
* @param predicate
* a predicate function to evaluate items emitted by the source Observable
* @return an Observable that emits the single item emitted by the source Observable that matches the
* predicate, or the default item if no emitted item matches the predicate
* @throws IllegalArgumentException
* if the source Observable emits more than one item that matches the predicate
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-single-and-singleordefault">RxJava Wiki: single()</a>
* @see "MSDN: Observable.singleOrDefaultAsync()"
*/
public final Observable<T> singleOrDefault(T defaultValue, Func1<? super T, Boolean> predicate) {
return filter(predicate).singleOrDefault(defaultValue);
}
/**
* Returns an Observable that skips the first {@code num} items emitted by the source Observable and emits
* the remainder.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skip.png">
*
* @param num
* the number of items to skip
* @return an Observable that is identical to the source Observable except that it does not emit the first {@code num} items that the source Observable emits
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-skip">RxJava Wiki: skip()</a>
*/
public final Observable<T> skip(int num) {
return lift(new OperatorSkip<T>(num));
}
/**
* Returns an Observable that skips values emitted by the source Observable before a specified time window
* elapses.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skip.t.png">
*
* @param time
* the length of the time window to skip
* @param unit
* the time unit of {@code time}
* @return an Observable that skips values emitted by the source Observable before the time window defined
* by {@code time} elapses and the emits the remainder
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-skip">RxJava Wiki: skip()</a>
*/
public final Observable<T> skip(long time, TimeUnit unit) {
return skip(time, unit, Schedulers.computation());
}
/**
* Returns an Observable that skips values emitted by the source Observable before a specified time window
* on a specified {@link Scheduler} elapses.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skip.ts.png">
*
* @param time
* the length of the time window to skip
* @param unit
* the time unit of {@code time}
* @param scheduler
* the {@link Scheduler} on which the timed wait happens
* @return an Observable that skips values emitted by the source Observable before the time window defined
* by {@code time} and {@code scheduler} elapses, and then emits the remainder
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-skip">RxJava Wiki: skip()</a>
*/
public final Observable<T> skip(long time, TimeUnit unit, Scheduler scheduler) {
return lift(new OperatorSkipTimed<T>(time, unit, scheduler));
}
/**
* Returns an Observable that drops a specified number of items from the end of the sequence emitted by the
* source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skipLast.png">
* <p>
* This Observer accumulates a queue long enough to store the first {@code count} items. As more items are
* received, items are taken from the front of the queue and emitted by the returned Observable. This causes
* such items to be delayed.
*
* @param count
* number of items to drop from the end of the source sequence
* @return an Observable that emits the items emitted by the source Observable except for the dropped ones
* at the end
* @throws IndexOutOfBoundsException
* if {@code count} is less than zero
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-skiplast">RxJava Wiki: skipLast()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211750.aspx">MSDN: Observable.SkipLast</a>
*/
public final Observable<T> skipLast(int count) {
return lift(new OperatorSkipLast<T>(count));
}
/**
* Returns an Observable that drops items emitted by the source Observable during a specified time window
* before the source completes.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skipLast.t.png">
*
* Note: this action will cache the latest items arriving in the specified time window.
*
* @param time
* the length of the time window
* @param unit
* the time unit of {@code time}
* @return an Observable that drops those items emitted by the source Observable in a time window before the
* source completes defined by {@code time}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-skiplast">RxJava Wiki: skipLast()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211750.aspx">MSDN: Observable.SkipLast</a>
*/
public final Observable<T> skipLast(long time, TimeUnit unit) {
return skipLast(time, unit, Schedulers.computation());
}
/**
* Returns an Observable that drops items emitted by the source Observable during a specified time window
* (defined on a specified scheduler) before the source completes.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skipLast.ts.png">
*
* Note: this action will cache the latest items arriving in the specified time window.
*
* @param time
* the length of the time window
* @param unit
* the time unit of {@code time}
* @param scheduler
* the scheduler used as the time source
* @return an Observable that drops those items emitted by the source Observable in a time window before the
* source completes defined by {@code time} and {@code scheduler}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-skiplast">RxJava Wiki: skipLast()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211750.aspx">MSDN: Observable.SkipLast</a>
*/
public final Observable<T> skipLast(long time, TimeUnit unit, Scheduler scheduler) {
return lift(new OperatorSkipLastTimed<T>(time, unit, scheduler));
}
/**
* Returns an Observable that skips items emitted by the source Observable until a second Observable emits
* an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skipUntil.png">
*
* @param other
* the second Observable that has to emit an item before the source Observable's elements begin
* to be mirrored by the resulting Observable
* @return an Observable that skips items from the source Observable until the second Observable emits an
* item, then emits the remaining items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-skipuntil">RxJava Wiki: skipUntil()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229358.aspx">MSDN: Observable.SkipUntil</a>
*/
public final <U> Observable<T> skipUntil(Observable<U> other) {
return lift(new OperatorSkipUntil<T, U>(other));
}
/**
* Returns an Observable that skips all items emitted by the source Observable as long as a specified
* condition holds true, but emits all further source items as soon as the condition becomes false.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skipWhile.png">
*
* @param predicate
* a function to test each item emitted from the source Observable
* @return an Observable that begins emitting items emitted by the source Observable when the specified
* predicate becomes false
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-skipwhile-and-skipwhilewithindex">RxJava Wiki: skipWhile()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229685.aspx">MSDN: Observable.SkipWhile</a>
*/
public final Observable<T> skipWhile(Func1<? super T, Boolean> predicate) {
return lift(new OperatorSkipWhile<T>(OperatorSkipWhile.toPredicate2(predicate)));
}
/**
* Returns an Observable that skips all items emitted by the source Observable as long as a specified
* condition holds true, but emits all further source items as soon as the condition becomes false.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skipWhileWithIndex.png">
*
* @param predicate
* a function to test each item emitted from the source Observable. It takes the emitted item as
* the first parameter and the sequential index of the emitted item as a second parameter.
* @return an Observable that begins emitting items emitted by the source Observable when the specified
* predicate becomes false
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-skipwhile-and-skipwhilewithindex">RxJava Wiki: skipWhileWithIndex()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211631.aspx">MSDN: Observable.SkipWhile</a>
*/
public final Observable<T> skipWhileWithIndex(Func2<? super T, Integer, Boolean> predicate) {
return lift(new OperatorSkipWhile<T>(predicate));
}
/**
* Returns an Observable that emits the items in a specified {@link Observable} before it begins to emit
* items emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.o.png">
*
* @param values
* an Observable that contains the items you want the modified Observable to emit first
* @return an Observable that emits the items in the specified {@link Observable} and then emits the items
* emitted by the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
*/
public final Observable<T> startWith(Observable<T> values) {
return concat(values, this);
}
/**
* Returns an Observable that emits the items in a specified {@link Iterable} before it begins to emit items
* emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png">
*
* @param values
* an Iterable that contains the items you want the modified Observable to emit first
* @return an Observable that emits the items in the specified {@link Iterable} and then emits the items
* emitted by the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
*/
public final Observable<T> startWith(Iterable<T> values) {
return concat(Observable.<T> from(values), this);
}
/**
* Returns an Observable that emits the items in a specified {@link Iterable}, on a specified {@link Scheduler}, before it begins to emit items emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.s.png">
*
* @param values
* an Iterable that contains the items you want the modified Observable to emit first
* @param scheduler
* the Scheduler to emit the prepended values on
* @return an Observable that emits the items in the specified {@link Iterable} and then emits the items
* emitted by the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229372.aspx">MSDN: Observable.StartWith</a>
*/
public final Observable<T> startWith(Iterable<T> values, Scheduler scheduler) {
return concat(from(values, scheduler), this);
}
/**
* Returns an Observable that emits a specified item before it begins to emit items emitted by the source
* Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png">
*
* @param t1
* the item to emit
* @return an Observable that emits the specified item before it begins to emit items emitted by the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
*/
public final Observable<T> startWith(T t1) {
return concat(Observable.<T> from(t1), this);
}
/**
* Returns an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png">
*
* @param t1
* the first item to emit
* @param t2
* the second item to emit
* @return an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
*/
public final Observable<T> startWith(T t1, T t2) {
return concat(Observable.<T> from(t1, t2), this);
}
/**
* Returns an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png">
*
* @param t1
* the first item to emit
* @param t2
* the second item to emit
* @param t3
* the third item to emit
* @return an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
*/
public final Observable<T> startWith(T t1, T t2, T t3) {
return concat(Observable.<T> from(t1, t2, t3), this);
}
/**
* Returns an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png">
*
* @param t1
* the first item to emit
* @param t2
* the second item to emit
* @param t3
* the third item to emit
* @param t4
* the fourth item to emit
* @return an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
*/
public final Observable<T> startWith(T t1, T t2, T t3, T t4) {
return concat(Observable.<T> from(t1, t2, t3, t4), this);
}
/**
* Returns an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png">
*
* @param t1
* the first item to emit
* @param t2
* the second item to emit
* @param t3
* the third item to emit
* @param t4
* the fourth item to emit
* @param t5
* the fifth item to emit
* @return an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
*/
public final Observable<T> startWith(T t1, T t2, T t3, T t4, T t5) {
return concat(Observable.<T> from(t1, t2, t3, t4, t5), this);
}
/**
* Returns an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png">
*
* @param t1
* the first item to emit
* @param t2
* the second item to emit
* @param t3
* the third item to emit
* @param t4
* the fourth item to emit
* @param t5
* the fifth item to emit
* @param t6
* the sixth item to emit
* @return an Observable that emits the specified items before it begins to emit items emitted
* by the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
*/
public final Observable<T> startWith(T t1, T t2, T t3, T t4, T t5, T t6) {
return concat(Observable.<T> from(t1, t2, t3, t4, t5, t6), this);
}
/**
* Returns an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png">
*
* @param t1
* the first item to emit
* @param t2
* the second item to emit
* @param t3
* the third item to emit
* @param t4
* the fourth item to emit
* @param t5
* the fifth item to emit
* @param t6
* the sixth item to emit
* @param t7
* the seventh item to emit
* @return an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
*/
public final Observable<T> startWith(T t1, T t2, T t3, T t4, T t5, T t6, T t7) {
return concat(Observable.<T> from(t1, t2, t3, t4, t5, t6, t7), this);
}
/**
* Returns an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png">
*
* @param t1
* the first item to emit
* @param t2
* the second item to emit
* @param t3
* the third item to emit
* @param t4
* the fourth item to emit
* @param t5
* the fifth item to emit
* @param t6
* the sixth item to emit
* @param t7
* the seventh item to emit
* @param t8
* the eighth item to emit
* @return an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
*/
public final Observable<T> startWith(T t1, T t2, T t3, T t4, T t5, T t6, T t7, T t8) {
return concat(Observable.<T> from(t1, t2, t3, t4, t5, t6, t7, t8), this);
}
/**
* Returns an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png">
*
* @param t1
* the first item to emit
* @param t2
* the second item to emit
* @param t3
* the third item to emit
* @param t4
* the fourth item to emit
* @param t5
* the fifth item to emit
* @param t6
* the sixth item to emit
* @param t7
* the seventh item to emit
* @param t8
* the eighth item to emit
* @param t9
* the ninth item to emit
* @return an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
*/
public final Observable<T> startWith(T t1, T t2, T t3, T t4, T t5, T t6, T t7, T t8, T t9) {
return concat(Observable.<T> from(t1, t2, t3, t4, t5, t6, t7, t8, t9), this);
}
/**
* Returns an Observable that emits the items from a specified array, on a specified Scheduler, before it
* begins to emit items emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.s.png">
*
* @param values
* the items you want the modified Observable to emit first
* @param scheduler
* the Scheduler to emit the prepended values on
* @return an Observable that emits the items from {@code values}, on {@code scheduler}, before it begins to
* emit items emitted by the source Observable.
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229372.aspx">MSDN: Observable.StartWith</a>
*/
public final Observable<T> startWith(T[] values, Scheduler scheduler) {
return startWith(Arrays.asList(values), scheduler);
}
/**
* Subscribe and ignore all events.
*
* @return a {@link Subscription} reference with which the {@link Observer} can stop receiving items before
* the Observable has finished sending them
* @throws OnErrorNotImplementedException
* if the Observable tries to call {@code onError}
*/
public final Subscription subscribe() {
return subscribe(new Subscriber<T>() {
@Override
public final void onCompleted() {
// do nothing
}
@Override
public final void onError(Throwable e) {
throw new OnErrorNotImplementedException(e);
}
@Override
public final void onNext(T args) {
// do nothing
}
});
}
/**
* An {@link Observer} must call an Observable's {@code subscribe} method in order to receive
* items and notifications from the Observable.
*
* @param onNext
* FIXME FIXME FIXME
* @return a {@link Subscription} reference with which the {@link Observer} can stop receiving items before
* the Observable has finished sending them
* @throws IllegalArgumentException
* if {@code onNext} is null
* @throws OnErrorNotImplementedException
* if the Observable tries to call {@code onError}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable#wiki-onnext-oncompleted-and-onerror">RxJava Wiki: onNext, onCompleted, and onError</a>
*/
public final Subscription subscribe(final Action1<? super T> onNext) {
if (onNext == null) {
throw new IllegalArgumentException("onNext can not be null");
}
return subscribe(new Subscriber<T>() {
@Override
public final void onCompleted() {
// do nothing
}
@Override
public final void onError(Throwable e) {
throw new OnErrorNotImplementedException(e);
}
@Override
public final void onNext(T args) {
onNext.call(args);
}
});
}
/**
* An {@link Observer} must call an Observable's {@code subscribe} method in order to receive items and
* notifications from the Observable.
*
* @param onNext
* FIXME FIXME FIXME
* @param onError
* FIXME FIXME FIXME
* @return a {@link Subscription} reference with which the {@link Observer} can stop receiving items before
* the Observable has finished sending them
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable#wiki-onnext-oncompleted-and-onerror">RxJava Wiki: onNext, onCompleted, and onError</a>
* @throws IllegalArgumentException
* if {@code onNext} is null
* @throws IllegalArgumentException
* if {@code onError} is null
*/
public final Subscription subscribe(final Action1<? super T> onNext, final Action1<Throwable> onError) {
if (onNext == null) {
throw new IllegalArgumentException("onNext can not be null");
}
if (onError == null) {
throw new IllegalArgumentException("onError can not be null");
}
return subscribe(new Subscriber<T>() {
@Override
public final void onCompleted() {
// do nothing
}
@Override
public final void onError(Throwable e) {
onError.call(e);
}
@Override
public final void onNext(T args) {
onNext.call(args);
}
});
}
/**
* An {@link Observer} must call an Observable's {@code subscribe} method in order to receive items and
* notifications from the Observable.
*
* @param onNext
* FIXME FIXME FIXME
* @param onError
* FIXME FIXME FIXME
* @param onComplete
* FIXME FIXME FIXME
* @return a {@link Subscription} reference with which the {@link Observer} can stop receiving items before
* the Observable has finished sending them
* @throws IllegalArgumentException
* if {@code onNext} is null
* @throws IllegalArgumentException
* if {@code onError} is null
* @throws IllegalArgumentException
* if {@code onComplete} is null
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable#wiki-onnext-oncompleted-and-onerror">RxJava Wiki: onNext, onCompleted, and onError</a>
*/
public final Subscription subscribe(final Action1<? super T> onNext, final Action1<Throwable> onError, final Action0 onComplete) {
if (onNext == null) {
throw new IllegalArgumentException("onNext can not be null");
}
if (onError == null) {
throw new IllegalArgumentException("onError can not be null");
}
if (onComplete == null) {
throw new IllegalArgumentException("onComplete can not be null");
}
return subscribe(new Subscriber<T>() {
@Override
public final void onCompleted() {
onComplete.call();
}
@Override
public final void onError(Throwable e) {
onError.call(e);
}
@Override
public final void onNext(T args) {
onNext.call(args);
}
});
}
/**
* An {@link Observer} must subscribe to an Observable in order to receive items and notifications from the
* Observable.
*
* @param observer
* FIXME FIXME FIXME
* @return a {@link Subscription} reference with which the {@link Observer} can stop receiving items before
* the Observable has finished sending them
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable#wiki-onnext-oncompleted-and-onerror">RxJava Wiki: onNext, onCompleted, and onError</a>
*/
public final Subscription subscribe(final Observer<? super T> observer) {
return subscribe(new Subscriber<T>() {
@Override
public void onCompleted() {
observer.onCompleted();
}
@Override
public void onError(Throwable e) {
observer.onError(e);
}
@Override
public void onNext(T t) {
observer.onNext(t);
}
});
}
/**
* Subscribe to Observable and invoke {@link OnSubscribe} function without any
* contract protection, error handling, unsubscribe, or execution hooks.
* <p>
* This should only be used for implementing an {@link Operator} that requires nested subscriptions.
* <p>
* Normal use should use {@link #subscribe(Subscriber)} which ensures the Rx contract and other functionality.
*
* @param subscriber
* @return Subscription which is the Subscriber passed in
* @since 0.17
*/
public final Subscription unsafeSubscribe(Subscriber<? super T> subscriber) {
try {
onSubscribe.call(subscriber);
} catch (Throwable e) {
if (e instanceof OnErrorNotImplementedException) {
throw (OnErrorNotImplementedException) e;
}
// handle broken contracts: https://github.com/Netflix/RxJava/issues/1090
subscriber.onError(e);
}
return subscriber;
}
/**
* A {@link Subscriber} must call an Observable's {@code subscribe} method in order to receive items and
* notifications from the Observable.
* <p>
* A typical implementation of {@code subscribe} does the following:
* <ol>
* <li>It stores a reference to the Subscriber in a collection object, such as a {@code List<T>} object.</li>
* <li>It returns a reference to the {@link Subscription} interface. This enables Observers to unsubscribe,
* that is, to stop receiving items and notifications before the Observable stops sending them, which also
* invokes the Observer's {@link Observer#onCompleted onCompleted} method.</li>
* </ol><p>
* An {@code Observable<T>} instance is responsible for accepting all subscriptions and notifying all
* Subscribers. Unless the documentation for a particular {@code Observable<T>} implementation indicates
* otherwise, Subscriber should make no assumptions about the order in which multiple Subscribers will
* receive their notifications.
* <p>
* For more information see the
* <a href="https://github.com/Netflix/RxJava/wiki/Observable">RxJava Wiki</a>
*
* @param subscriber
* the {@link Subscriber}
* @return a {@link Subscription} reference with which Subscribers that are {@link Observer}s can
* unsubscribe from the Observable
* @throws IllegalStateException
* if {@code subscribe()} is unable to obtain an {@code OnSubscribe<>} function
* @throws IllegalArgumentException
* if the {@link Subscriber} provided as the argument to {@code subscribe()} is {@code null}
* @throws OnErrorNotImplementedException
* if the {@link Subscriber}'s {@code onError} method is null
* @throws RuntimeException
* if the {@link Subscriber}'s {@code onError} method itself threw a {@code Throwable}
*/
public final Subscription subscribe(Subscriber<? super T> subscriber) {
// allow the hook to intercept and/or decorate
OnSubscribe<T> onSubscribeFunction = hook.onSubscribeStart(this, onSubscribe);
// validate and proceed
if (subscriber == null) {
throw new IllegalArgumentException("observer can not be null");
}
if (onSubscribeFunction == null) {
throw new IllegalStateException("onSubscribe function can not be null.");
/*
* the subscribe function can also be overridden but generally that's not the appropriate approach
* so I won't mention that in the exception
*/
}
try {
/*
* See https://github.com/Netflix/RxJava/issues/216 for discussion on "Guideline 6.4: Protect calls
* to user code from within an Observer"
*/
// if not already wrapped
if (!(subscriber instanceof SafeSubscriber)) {
// assign to `observer` so we return the protected version
subscriber = new SafeSubscriber<T>(subscriber);
}
onSubscribeFunction.call(subscriber);
return hook.onSubscribeReturn(subscriber);
} catch (Throwable e) {
// special handling for certain Throwable/Error/Exception types
Exceptions.throwIfFatal(e);
// if an unhandled error occurs executing the onSubscribe we will propagate it
try {
subscriber.onError(hook.onSubscribeError(e));
} catch (OnErrorNotImplementedException e2) {
// special handling when onError is not implemented ... we just rethrow
throw e2;
} catch (Throwable e2) {
// if this happens it means the onError itself failed (perhaps an invalid function implementation)
// so we are unable to propagate the error correctly and will just throw
RuntimeException r = new RuntimeException("Error occurred attempting to subscribe [" + e.getMessage() + "] and then again while trying to pass to onError.", e2);
// TODO could the hook be the cause of the error in the on error handling.
hook.onSubscribeError(r);
// TODO why aren't we throwing the hook's return value.
throw r;
}
return Subscriptions.empty();
}
}
/**
* Asynchronously subscribes Observers to this Observable on the specified {@link Scheduler}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/subscribeOn.png">
*
* @param scheduler
* the {@link Scheduler} to perform subscription actions on
* @return the source Observable modified so that its subscriptions happen on the
* specified {@link Scheduler}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-subscribeon">RxJava Wiki: subscribeOn()</a>
*/
public final Observable<T> subscribeOn(Scheduler scheduler) {
return nest().lift(new OperatorSubscribeOn<T>(scheduler));
}
/**
* Returns a new Observable by applying a function that you supply to each item emitted by the source
* Observable that returns an Observable, and then emitting the items emitted by the most recently emitted
* of these Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/switchMap.png">
*
* @param func
* a function that, when applied to an item emitted by the source Observable, returns an
* Observable
* @return an Observable that emits the items emitted by the Observable returned from applying {@code func} to the most recently emitted item emitted by the source Observable
*/
public final <R> Observable<R> switchMap(Func1<? super T, ? extends Observable<? extends R>> func) {
return switchOnNext(map(func));
}
/**
* Returns an Observable that emits only the first {@code num} items emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/take.png">
* <p>
* This method returns an Observable that will invoke a subscribing {@link Observer}'s {@link Observer#onNext onNext} function a maximum of {@code num} times before invoking
* {@link Observer#onCompleted onCompleted}.
*
* @param num
* the maximum number of items to emit
* @return an Observable that emits only the first {@code num} items emitted by the source Observable, or
* all of the items from the source Observable if that Observable emits fewer than {@code num} items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-take">RxJava Wiki: take()</a>
*/
public final Observable<T> take(final int num) {
return lift(new OperatorTake<T>(num));
}
/**
* Returns an Observable that emits those items emitted by source Observable before a specified time runs
* out.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/take.t.png">
*
* @param time
* the length of the time window
* @param unit
* the time unit of {@code time}
* @return an Observable that emits those items emitted by the source Observable before the time runs out
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-take">RxJava Wiki: take()</a>
*/
public final Observable<T> take(long time, TimeUnit unit) {
return take(time, unit, Schedulers.computation());
}
/**
* Returns an Observable that emits those items emitted by source Observable before a specified time (on a
* specified Scheduler) runs out.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/take.ts.png">
*
* @param time
* the length of the time window
* @param unit
* the time unit of {@code time}
* @param scheduler
* the Scheduler used for time source
* @return an Observable that emits those items emitted by the source Observable before the time runs out,
* according to the specified Scheduler
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-take">RxJava Wiki: take()</a>
*/
public final Observable<T> take(long time, TimeUnit unit, Scheduler scheduler) {
return lift(new OperatorTakeTimed<T>(time, unit, scheduler));
}
/**
* Returns an Observable that emits only the very first item emitted by the source Observable that satisfies
* a specified condition.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeFirstN.png">
*
* @param predicate
* the condition any item emitted by the source Observable has to satisfy
* @return an Observable that emits only the very first item emitted by the source Observable that satisfies
* the given condition, or that completes without emitting anything if the source Observable
* completes without emitting a single condition-satisfying item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-first">RxJava Wiki: first()</a>
* @see "MSDN: Observable.firstAsync()"
*/
public final Observable<T> takeFirst(Func1<? super T, Boolean> predicate) {
return filter(predicate).take(1);
}
/**
* Returns an Observable that emits only the last {@code count} items emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLast.n.png">
*
* @param count
* the number of items to emit from the end of the sequence of items emitted by the source
* Observable
* @return an Observable that emits only the last {@code count} items emitted by the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-takelast">RxJava Wiki: takeLast()</a>
*/
public final Observable<T> takeLast(final int count) {
return lift(new OperatorTakeLast<T>(count));
}
/**
* Return an Observable that emits at most a specified number of items from the source Observable that were
* emitted in a specified window of time before the Observable completed.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLast.tn.png">
*
* @param count
* the maximum number of items to emit
* @param time
* the length of the time window
* @param unit
* the time unit of {@code time}
* @return an Observable that emits at most {@code count} items from the source Observable that were emitted
* in a specified window of time before the Observable completed
*/
public final Observable<T> takeLast(int count, long time, TimeUnit unit) {
return takeLast(count, time, unit, Schedulers.computation());
}
/**
* Return an Observable that emits at most a specified number of items from the source Observable that were
* emitted in a specified window of time before the Observable completed, where the timing information is
* provided by a given Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLast.tns.png">
*
* @param count
* the maximum number of items to emit
* @param time
* the length of the time window
* @param unit
* the time unit of {@code time}
* @param scheduler
* the Scheduler that provides the timestamps for the observed items
* @return an Observable that emits at most {@code count} items from the source Observable that were emitted
* in a specified window of time before the Observable completed, where the timing information is
* provided by the given {@code scheduler}
* @throws IllegalArgumentException
* if {@code count} is less than zero
*/
public final Observable<T> takeLast(int count, long time, TimeUnit unit, Scheduler scheduler) {
return lift(new OperatorTakeLastTimed<T>(count, time, unit, scheduler));
}
/**
* Return an Observable that emits the items from the source Observable that were emitted in a specified
* window of time before the Observable completed.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLast.t.png">
*
* @param time
* the length of the time window
* @param unit
* the time unit of {@code time}
* @return an Observable that emits the items from the source Observable that were emitted in the window of
* time before the Observable completed specified by {@code time}
*/
public final Observable<T> takeLast(long time, TimeUnit unit) {
return takeLast(time, unit, Schedulers.computation());
}
/**
* Return an Observable that emits the items from the source Observable that were emitted in a specified
* window of time before the Observable completed, where the timing information is provided by a specified
* Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLast.ts.png">
*
* @param time
* the length of the time window
* @param unit
* the time unit of {@code time}
* @param scheduler
* the Scheduler that provides the timestamps for the Observed items
* @return an Observable that emits the items from the source Observable that were emitted in the window of
* time before the Observable completed specified by {@code time}, where the timing information is
* provided by {@code scheduler}
*/
public final Observable<T> takeLast(long time, TimeUnit unit, Scheduler scheduler) {
return lift(new OperatorTakeLastTimed<T>(time, unit, scheduler));
}
/**
* Return an Observable that emits a single List containing the last {@code count} elements emitted by the
* source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLastBuffer.png">
*
* @param count
* the number of items to emit in the list
* @return an Observable that emits a single list containing the last {@code count} elements emitted by the
* source Observable
*/
public final Observable<List<T>> takeLastBuffer(int count) {
return takeLast(count).toList();
}
/**
* Return an Observable that emits a single List containing at most {@code count} items from the source
* Observable that were emitted during a specified window of time before the source Observable completed.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLastBuffer.tn.png">
*
* @param count
* the maximum number of items to emit
* @param time
* the length of the time window
* @param unit
* the time unit of {@code time}
* @return an Observable that emits a single List containing at most {@code count} items emitted by the
* source Observable during the time window defined by {@code time} before the source Observable
* completed
*/
public final Observable<List<T>> takeLastBuffer(int count, long time, TimeUnit unit) {
return takeLast(count, time, unit).toList();
}
/**
* Return an Observable that emits a single List containing at most {@code count} items from the source
* Observable that were emitted during a specified window of time (on a specified Scheduler) before the
* source Observable completed.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLastBuffer.tns.png">
*
* @param count
* the maximum number of items to emit
* @param time
* the length of the time window
* @param unit
* the time unit of {@code time}
* @param scheduler
* the Scheduler that provides the timestamps for the observed items
* @return an Observable that emits a single List containing at most {@code count} items emitted by the
* source Observable during the time window defined by {@code time} before the source Observable
* completed
*/
public final Observable<List<T>> takeLastBuffer(int count, long time, TimeUnit unit, Scheduler scheduler) {
return takeLast(count, time, unit, scheduler).toList();
}
/**
* Return an Observable that emits a single List containing those items from the source Observable that were
* emitted during a specified window of time before the source Observable completed.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLastBuffer.t.png">
*
* @param time
* the length of the time window
* @param unit
* the time unit of {@code time}
* @return an Observable that emits a single List containing the items emitted by the source Observable
* during the time window defined by {@code time} before the source Observable completed
*/
public final Observable<List<T>> takeLastBuffer(long time, TimeUnit unit) {
return takeLast(time, unit).toList();
}
/**
* Return an Observable that emits a single List containing those items from the source Observable that were
* emitted during a specified window of time before the source Observable completed, where the timing
* information is provided by the given Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLastBuffer.ts.png">
*
* @param time
* the length of the time window
* @param unit
* the time unit of {@code time}
* @param scheduler
* the Scheduler that provides the timestamps for the observed items
* @return an Observable that emits a single List containing the items emitted by the source Observable
* during the time window defined by {@code time} before the source Observable completed, where the
* timing information is provided by {@code scheduler}
*/
public final Observable<List<T>> takeLastBuffer(long time, TimeUnit unit, Scheduler scheduler) {
return takeLast(time, unit, scheduler).toList();
}
/**
* Returns an Observable that emits the items emitted by the source Observable until a second Observable
* emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeUntil.png">
*
* @param other
* the Observable whose first emitted item will cause {@code takeUntil} to stop emitting items
* from the source Observable
* @param <E>
* the type of items emitted by {@code other}
* @return an Observable that emits the items emitted by the source Observable until such time as {@code other} emits its first item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-takeuntil">RxJava Wiki: takeUntil()</a>
*/
public final <E> Observable<T> takeUntil(Observable<? extends E> other) {
return OperatorTakeUntil.takeUntil(this, other);
}
/**
* Returns an Observable that emits items emitted by the source Observable so long as each item satisfied a
* specified condition, and then completes as soon as this condition is not satisfied.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeWhile.png">
*
* @param predicate
* a function that evaluates an item emitted by the source Observable and returns a Boolean
* @return an Observable that emits the items from the source Observable so long as each item satisfies the
* condition defined by {@code predicate}, then completes
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-takewhile-and-takewhilewithindex">RxJava Wiki: takeWhile()</a>
*/
public final Observable<T> takeWhile(final Func1<? super T, Boolean> predicate) {
return lift(new OperatorTakeWhile<T>(predicate));
}
/**
* Returns an Observable that emits the items emitted by a source Observable so long as a given predicate
* remains true, where the predicate operates on both the item and its index relative to the complete
* sequence of emitted items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeWhileWithIndex.png">
*
* @param predicate
* a function to test each item emitted by the source Observable for a condition; the second
* parameter of the function represents the sequential index of the source item; it returns a
* Boolean
* @return an Observable that emits items from the source Observable so long as the predicate continues to
* return {@code true} for each item, then completes
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-takewhile-and-takewhilewithindex">RxJava Wiki: takeWhileWithIndex()</a>
*/
public final Observable<T> takeWhileWithIndex(final Func2<? super T, ? super Integer, Boolean> predicate) {
return lift(new OperatorTakeWhile<T>(predicate));
}
/**
* Returns an Observable that emits only the first item emitted by the source Observable during sequential
* time windows of a specified duration.
* <p>
* This differs from {@link #throttleLast} in that this only tracks passage of time whereas {@link #throttleLast} ticks at scheduled intervals.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/throttleFirst.png">
*
* @param windowDuration
* time to wait before emitting another item after emitting the last item
* @param unit
* the unit of time of {@code windowDuration}
* @return an Observable that performs the throttle operation
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-throttlefirst">RxJava Wiki: throttleFirst()</a>
*/
public final Observable<T> throttleFirst(long windowDuration, TimeUnit unit) {
return lift(new OperatorThrottleFirst<T>(windowDuration, unit, Schedulers.computation()));
}
/**
* Returns an Observable that emits only the first item emitted by the source Observable during sequential
* time windows of a specified duration, where the windows are managed by a specified Scheduler.
* <p>
* This differs from {@link #throttleLast} in that this only tracks passage of time whereas {@link #throttleLast} ticks at scheduled intervals.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/throttleFirst.s.png">
*
* @param skipDuration
* time to wait before emitting another item after emitting the last item
* @param unit
* the unit of time of {@code skipDuration}
* @param scheduler
* the {@link Scheduler} to use internally to manage the timers that handle timeout for each
* event
* @return an Observable that performs the throttle operation
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-throttlefirst">RxJava Wiki: throttleFirst()</a>
*/
public final Observable<T> throttleFirst(long skipDuration, TimeUnit unit, Scheduler scheduler) {
return lift(new OperatorThrottleFirst<T>(skipDuration, unit, scheduler));
}
/**
* Returns an Observable that emits only the last item emitted by the source Observable during sequential
* time windows of a specified duration.
* <p>
* This differs from {@link #throttleFirst} in that this ticks along at a scheduled interval whereas {@link #throttleFirst} does not tick, it just tracks passage of time.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/throttleLast.png">
*
* @param intervalDuration
* duration of windows within which the last item emitted by the source Observable will be
* emitted
* @param unit
* the unit of time of {@code intervalDuration}
* @return an Observable that performs the throttle operation
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-takelast">RxJava Wiki: throttleLast()</a>
* @see #sample(long, TimeUnit)
*/
public final Observable<T> throttleLast(long intervalDuration, TimeUnit unit) {
return sample(intervalDuration, unit);
}
/**
* Returns an Observable that emits only the last item emitted by the source Observable during sequential
* time windows of a specified duration, where the duration is governed by a specified Scheduler.
* <p>
* This differs from {@link #throttleFirst} in that this ticks along at a scheduled interval whereas {@link #throttleFirst} does not tick, it just tracks passage of time.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/throttleLast.s.png">
*
* @param intervalDuration
* duration of windows within which the last item emitted by the source Observable will be
* emitted
* @param unit
* the unit of time of {@code intervalDuration}
* @param scheduler
* the {@link Scheduler} to use internally to manage the timers that handle timeout for each
* event
* @return an Observable that performs the throttle operation
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-takelast">RxJava Wiki: throttleLast()</a>
* @see #sample(long, TimeUnit, Scheduler)
*/
public final Observable<T> throttleLast(long intervalDuration, TimeUnit unit, Scheduler scheduler) {
return sample(intervalDuration, unit, scheduler);
}
/**
* Returns an Observable that only emits those items emitted by the source Observable that are not followed
* by another emitted item within a specified time window.
* <p>
* <em>Note:</em> If the source Observable keeps emitting items more frequently than the length of the time
* window then no items will be emitted by the resulting Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/throttleWithTimeout.png">
* <p>
* Information on debounce vs throttle:
* <p>
* <ul>
* <li><a href="http://drupalmotion.com/article/debounce-and-throttle-visual-explanation">Debounce and Throttle: visual explanation</a></li>
* <li><a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">Debouncing: javascript methods</a></li>
* <li><a href="http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/">Javascript - don't spam your server: debounce and throttle</a></li>
* </ul>
*
* @param timeout
* the length of the window of time that must pass after the emission of an item from the source
* Observable in which that Observable emits no items in order for the item to be emitted by the
* resulting Observable
* @param unit
* the {@link TimeUnit} of {@code timeout}
* @return an Observable that filters out items that are too quickly followed by newer items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-throttlewithtimeout-or-debounce">RxJava Wiki: throttleWithTimeout()</a>
* @see #debounce(long, TimeUnit)
*/
public final Observable<T> throttleWithTimeout(long timeout, TimeUnit unit) {
return debounce(timeout, unit);
}
/**
* Returns an Observable that only emits those items emitted by the source Observable that are not followed
* by another emitted item within a specified time window, where the time window is governed by a specified
* Scheduler.
* <p>
* <em>Note:</em> If the source Observable keeps emitting items more frequently than the length of the time
* window then no items will be emitted by the resulting Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/throttleWithTimeout.s.png">
* <p>
* Information on debounce vs throttle:
* <p>
* <ul>
* <li><a href="http://drupalmotion.com/article/debounce-and-throttle-visual-explanation">Debounce and Throttle: visual explanation</a></li>
* <li><a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">Debouncing: javascript methods</a></li>
* <li><a href="http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/">Javascript - don't spam your server: debounce and throttle</a></li>
* </ul>
*
* @param timeout
* the length of the window of time that must pass after the emission of an item from the source
* Observable in which that Observable emits no items in order for the item to be emitted by the
* resulting Observable
* @param unit
* the {@link TimeUnit} of {@code timeout}
* @param scheduler
* the {@link Scheduler} to use internally to manage the timers that handle the timeout for each
* item
* @return an Observable that filters out items that are too quickly followed by newer items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-throttlewithtimeout-or-debounce">RxJava Wiki: throttleWithTimeout()</a>
* @see #debounce(long, TimeUnit, Scheduler)
*/
public final Observable<T> throttleWithTimeout(long timeout, TimeUnit unit, Scheduler scheduler) {
return debounce(timeout, unit, scheduler);
}
/**
* Returns an Observable that emits records of the time interval between consecutive items emitted by the
* source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeInterval.png">
*
* @return an Observable that emits time interval information items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-timeinterval">RxJava Wiki: timeInterval()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh212107.aspx">MSDN: Observable.TimeInterval</a>
*/
public final Observable<TimeInterval<T>> timeInterval() {
return lift(new OperatorTimeInterval<T>(Schedulers.immediate()));
}
/**
* Returns an Observable that emits records of the time interval between consecutive items emitted by the
* source Observable, where this interval is computed on a specified Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeInterval.s.png">
*
* @param scheduler
* the {@link Scheduler} used to compute time intervals
* @return an Observable that emits time interval information items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-timeinterval">RxJava Wiki: timeInterval()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh212107.aspx">MSDN: Observable.TimeInterval</a>
*/
public final Observable<TimeInterval<T>> timeInterval(Scheduler scheduler) {
return lift(new OperatorTimeInterval<T>(scheduler));
}
/**
* Returns an Observable that mirrors the source Observable, but notifies observers of a TimeoutException if
* either the first item emitted by the source Observable or any subsequent item don't arrive within time
* windows defined by other Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout5.png">
*
* @param <U>
* the first timeout value type (ignored)
* @param <V>
* the subsequent timeout value type (ignored)
* @param firstTimeoutSelector
* a function that returns an Observable that determines the timeout window for the first source
* item
* @param timeoutSelector
* a function that returns an Observable for each item emitted by the source Observable and that
* determines the timeout window in which the subsequent source item must arrive in order to
* continue the sequence
* @return an Observable that mirrors the source Observable, but notifies observers of a TimeoutException if
* either the first item or any subsequent item doesn't arrive within the time windows specified by
* the timeout selectors
*/
public final <U, V> Observable<T> timeout(Func0<? extends Observable<U>> firstTimeoutSelector, Func1<? super T, ? extends Observable<V>> timeoutSelector) {
return timeout(firstTimeoutSelector, timeoutSelector, null);
}
/**
* Returns an Observable that mirrors the source Observable, but switches to a fallback Observable if either
* the first item emitted by the source Observable or any subsequent item don't arrive within time windows
* defined by other Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout6.png">
*
* @param <U>
* the first timeout value type (ignored)
* @param <V>
* the subsequent timeout value type (ignored)
* @param firstTimeoutSelector
* a function that returns an Observable which determines the timeout window for the first source
* item
* @param timeoutSelector
* a function that returns an Observable for each item emitted by the source Observable and that
* determines the timeout window in which the subsequent source item must arrive in order to
* continue the sequence
* @param other
* the fallback Observable to switch to if the source Observable times out
* @return an Observable that mirrors the source Observable, but switches to the {@code other} Observable if
* either the first item emitted by the source Observable or any subsequent item don't arrive within
* time windows defined by the timeout selectors
* @throws NullPointerException
* if {@code timeoutSelector} is null
*/
public final <U, V> Observable<T> timeout(Func0<? extends Observable<U>> firstTimeoutSelector, Func1<? super T, ? extends Observable<V>> timeoutSelector, Observable<? extends T> other) {
if (timeoutSelector == null) {
throw new NullPointerException("timeoutSelector is null");
}
return lift(new OperatorTimeoutWithSelector<T, U, V>(firstTimeoutSelector, timeoutSelector, other));
}
/**
* Returns an Observable that mirrors the source Observable, but notifies observers of a TimeoutException if
* an item emitted by the source Observable doesn't arrive within a window of time after the emission of the
* previous item, where that period of time is measured by an Observable that is a function of the previous
* item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout3.png">
* <p>
* Note: The arrival of the first source item is never timed out.
*
* @param <V>
* the timeout value type (ignored)
* @param timeoutSelector
* a function that returns an observable for each item emitted by the source
* Observable and that determines the timeout window for the subsequent item
* @return an Observable that mirrors the source Observable, but notifies observers of a TimeoutException if
* an item emitted by the source Observable takes longer to arrive than the time window defined by
* the selector for the previously emitted item
*/
public final <V> Observable<T> timeout(Func1<? super T, ? extends Observable<V>> timeoutSelector) {
return timeout(null, timeoutSelector, null);
}
/**
* Returns an Observable that mirrors the source Observable, but that switches to a fallback Observable if
* an item emitted by the source Observable doesn't arrive within a window of time after the emission of the
* previous item, where that period of time is measured by an Observable that is a function of the previous
* item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout4.png">
* <p>
* Note: The arrival of the first source item is never timed out.
*
* @param <V>
* the timeout value type (ignored)
* @param timeoutSelector
* a function that returns an Observable, for each item emitted by the source Observable, that
* determines the timeout window for the subsequent item
* @param other
* the fallback Observable to switch to if the source Observable times out
* @return an Observable that mirrors the source Observable, but switches to mirroring a fallback Observable
* if an item emitted by the source Observable takes longer to arrive than the time window defined
* by the selector for the previously emitted item
*/
public final <V> Observable<T> timeout(Func1<? super T, ? extends Observable<V>> timeoutSelector, Observable<? extends T> other) {
return timeout(null, timeoutSelector, other);
}
/**
* Returns an Observable that mirrors the source Observable but applies a timeout policy for each emitted
* item. If the next item isn't emitted within the specified timeout duration starting from its predecessor,
* the resulting Observable terminates and notifies observers of a {@code TimeoutException}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout.1.png">
*
* @param timeout
* maximum duration between emitted items before a timeout occurs
* @param timeUnit
* the unit of time that applies to the {@code timeout} argument.
* @return the source Observable modified to notify observers of a {@code TimeoutException} in case of a
* timeout
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-timeout">RxJava Wiki: timeout()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh244283.aspx">MSDN: Observable.Timeout</a>
*/
public final Observable<T> timeout(long timeout, TimeUnit timeUnit) {
return timeout(timeout, timeUnit, null, Schedulers.computation());
}
/**
* Returns an Observable that mirrors the source Observable but applies a timeout policy for each emitted
* item. If the next item isn't emitted within the specified timeout duration starting from its predecessor,
* the resulting Observable begins instead to mirror a fallback Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout.2.png">
*
* @param timeout
* maximum duration between items before a timeout occurs
* @param timeUnit
* the unit of time that applies to the {@code timeout} argument
* @param other
* the fallback Observable to use in case of a timeout
* @return the source Observable modified to switch to the fallback Observable in case of a timeout
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-timeout">RxJava Wiki: timeout()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229512.aspx">MSDN: Observable.Timeout</a>
*/
public final Observable<T> timeout(long timeout, TimeUnit timeUnit, Observable<? extends T> other) {
return timeout(timeout, timeUnit, other, Schedulers.computation());
}
/**
* Returns an Observable that mirrors the source Observable but applies a timeout policy for each emitted
* item using a specified Scheduler. If the next item isn't emitted within the specified timeout duration
* starting from its predecessor, the resulting Observable begins instead to mirror a fallback Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout.2s.png">
*
* @param timeout
* maximum duration between items before a timeout occurs
* @param timeUnit
* the unit of time that applies to the {@code timeout} argument
* @param other
* the Observable to use as the fallback in case of a timeout
* @param scheduler
* the {@link Scheduler} to run the timeout timers on
* @return the source Observable modified so that it will switch to the fallback Observable in case of a
* timeout
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-timeout">RxJava Wiki: timeout()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211676.aspx">MSDN: Observable.Timeout</a>
*/
public final Observable<T> timeout(long timeout, TimeUnit timeUnit, Observable<? extends T> other, Scheduler scheduler) {
return lift(new OperatorTimeout<T>(timeout, timeUnit, other, scheduler));
}
/**
* Returns an Observable that mirrors the source Observable but applies a timeout policy for each emitted
* item, where this policy is governed on a specified Scheduler. If the next item isn't emitted within the
* specified timeout duration starting from its predecessor, the resulting Observable terminates and
* notifies observers of a {@code TimeoutException}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout.1s.png">
*
* @param timeout
* maximum duration between items before a timeout occurs
* @param timeUnit
* the unit of time that applies to the {@code timeout} argument
* @param scheduler
* the Scheduler to run the timeout timers on
* @return the source Observable modified to notify observers of a {@code TimeoutException} in case of a
* timeout
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-timeout">RxJava Wiki: timeout()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh228946.aspx">MSDN: Observable.Timeout</a>
*/
public final Observable<T> timeout(long timeout, TimeUnit timeUnit, Scheduler scheduler) {
return timeout(timeout, timeUnit, null, scheduler);
}
/**
* Returns an Observable that emits each item emitted by the source Observable, wrapped in a {@link Timestamped} object.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timestamp.png">
*
* @return an Observable that emits timestamped items from the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-timestamp">RxJava Wiki: timestamp()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229003.aspx">MSDN: Observable.Timestamp</a>
*/
public final Observable<Timestamped<T>> timestamp() {
return timestamp(Schedulers.immediate());
}
/**
* Returns an Observable that emits each item emitted by the source Observable, wrapped in a {@link Timestamped} object whose timestamps are provided by a specified Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timestamp.s.png">
*
* @param scheduler
* the {@link Scheduler} to use as a time source
* @return an Observable that emits timestamped items from the source Observable with timestamps provided by
* the {@code scheduler}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-timestamp">RxJava Wiki: timestamp()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229003.aspx">MSDN: Observable.Timestamp</a>
*/
public final Observable<Timestamped<T>> timestamp(Scheduler scheduler) {
return lift(new OperatorTimestamp<T>(scheduler));
}
/**
* Converts an Observable into a {@link BlockingObservable} (an Observable with blocking operators).
*
* @return a {@code BlockingObservable} version of this Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Blocking-Observable-Operators">RxJava Wiki: Blocking Observable Observers</a>
*
* @deprecated Use {@link #toBlocking()} instead.
*/
@Deprecated
public final BlockingObservable<T> toBlockingObservable() {
return BlockingObservable.from(this);
}
/**
* Converts an Observable into a {@link BlockingObservable} (an Observable with blocking operators).
*
* @return a {@code BlockingObservable} version of this Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Blocking-Observable-Operators">RxJava Wiki: Blocking Observable Observers</a>
* @since 0.19
*/
public final BlockingObservable<T> toBlocking() {
return BlockingObservable.from(this);
}
/**
* Returns an Observable that emits a single item, a list composed of all the items emitted by the source
* Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toList.png">
* <p>
* Normally, an Observable that returns multiple items will do so by invoking its {@link Observer}'s {@link Observer#onNext onNext} method for each such item. You can change this behavior,
* instructing the
* Observable to compose a list of all of these items and then to invoke the Observer's {@code onNext} function once, passing it the entire list, by calling the Observable's {@code toList} method
* prior to
* calling its {@link #subscribe} method.
* <p>
*
* <!-- IS THE FOLLOWING NOTE STILL VALID? -->
*
* Be careful not to use this operator on Observables that emit infinite or very large numbers of items, as
* you do not have the option to unsubscribe.
*
* @return an Observable that emits a single item: a List containing all of the items emitted by the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-tolist">RxJava Wiki: toList()</a>
*/
public final Observable<List<T>> toList() {
return lift(new OperatorToObservableList<T>());
}
/**
* Return an Observable that emits a single HashMap containing all items emitted by the source Observable,
* mapped by the keys returned by a specified {@code keySelector} function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toMap.png">
* <p>
* If more than one source item maps to the same key, the HashMap will contain the latest of those items.
*
* @param keySelector
* the function that extracts the key from a source item to be used in the HashMap
* @return an Observable that emits a single item: a HashMap containing the mapped items from the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-tomap-and-tomultimap">RxJava Wiki: toMap()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229137.aspx">MSDN: Observable.ToDictionary</a>
*/
public final <K> Observable<Map<K, T>> toMap(Func1<? super T, ? extends K> keySelector) {
return lift(new OperatorToMap<T, K, T>(keySelector, Functions.<T>identity()));
}
/**
* Return an Observable that emits a single HashMap containing values corresponding to items emitted by the
* source Observable, mapped by the keys returned by a specified {@code keySelector} function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toMap.png">
* <p>
* If more than one source item maps to the same key, the HashMap will contain a single entry that
* corresponds to the latest of those items.
*
* @param keySelector
* the function that extracts the key from a source item to be used in the HashMap
* @param valueSelector
* the function that extracts the value from a source item to be used in the HashMap
* @return an Observable that emits a single item: a HashMap containing the mapped items from the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-tomap-and-tomultimap">RxJava Wiki: toMap()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh212075.aspx">MSDN: Observable.ToDictionary</a>
*/
public final <K, V> Observable<Map<K, V>> toMap(Func1<? super T, ? extends K> keySelector, Func1<? super T, ? extends V> valueSelector) {
return lift(new OperatorToMap<T, K, V>(keySelector, valueSelector));
}
/**
* Return an Observable that emits a single Map, returned by a specified {@code mapFactory} function, that
* contains keys and values extracted from the items emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toMap.png">
*
* @param keySelector
* the function that extracts the key from a source item to be used in the Map
* @param valueSelector
* the function that extracts the value from the source items to be used as value in the Map
* @param mapFactory
* the function that returns a Map instance to be used
* @return an Observable that emits a single item: a Map that contains the mapped items emitted by the
* source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-tomap-and-tomultimap">RxJava Wiki: toMap()</a>
*/
public final <K, V> Observable<Map<K, V>> toMap(Func1<? super T, ? extends K> keySelector, Func1<? super T, ? extends V> valueSelector, Func0<? extends Map<K, V>> mapFactory) {
return lift(new OperatorToMap<T, K, V>(keySelector, valueSelector, mapFactory));
}
/**
* Return an Observable that emits a single HashMap that contains an ArrayList of items emitted by the
* source Observable keyed by a specified {@code keySelector} function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toMultiMap.png">
*
* @param keySelector
* the function that extracts the key from the source items to be used as key in the HashMap
* @return an Observable that emits a single item: a HashMap that contains an ArrayList of items mapped from
* the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-tomap-and-tomultimap">RxJava Wiki: toMap()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh212098.aspx">MSDN: Observable.ToLookup</a>
*/
public final <K> Observable<Map<K, Collection<T>>> toMultimap(Func1<? super T, ? extends K> keySelector) {
return lift(new OperatorToMultimap<T, K, T>(keySelector, Functions.<T>identity()));
}
/**
* Return an Observable that emits a single HashMap that contains an ArrayList of values extracted by a
* specified {@code valueSelector} function from items emitted by the source Observable, keyed by a
* specified {@code keySelector} function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toMultiMap.png">
*
* @param keySelector
* the function that extracts a key from the source items to be used as key in the HashMap
* @param valueSelector
* the function that extracts a value from the source items to be used as value in the HashMap
* @return an Observable that emits a single item: a HashMap that contains an ArrayList of items mapped from
* the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-tomap-and-tomultimap">RxJava Wiki: toMap()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229101.aspx">MSDN: Observable.ToLookup</a>
*/
public final <K, V> Observable<Map<K, Collection<V>>> toMultimap(Func1<? super T, ? extends K> keySelector, Func1<? super T, ? extends V> valueSelector) {
return lift(new OperatorToMultimap<T, K, V>(keySelector, valueSelector));
}
/**
* Return an Observable that emits a single Map, returned by a specified {@code mapFactory} function, that
* contains an ArrayList of values, extracted by a specified {@code valueSelector} function from items
* emitted by the source Observable and keyed by the {@code keySelector} function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toMultiMap.png">
*
* @param keySelector
* the function that extracts a key from the source items to be used as the key in the Map
* @param valueSelector
* the function that extracts a value from the source items to be used as the value in the Map
* @param mapFactory
* the function that returns a Map instance to be used
* @return an Observable that emits a single item: a Map that contains a list items mapped from the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-tomap-and-tomultimap">RxJava Wiki: toMap()</a>
*/
public final <K, V> Observable<Map<K, Collection<V>>> toMultimap(Func1<? super T, ? extends K> keySelector, Func1<? super T, ? extends V> valueSelector, Func0<? extends Map<K, Collection<V>>> mapFactory) {
return lift(new OperatorToMultimap<T, K, V>(keySelector, valueSelector, mapFactory));
}
/**
* Return an Observable that emits a single Map, returned by a specified {@code mapFactory} function, that
* contains a custom collection of values, extracted by a specified {@code valueSelector} function from
* items emitted by the source Observable, and keyed by the {@code keySelector} function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toMultiMap.png">
*
* @param keySelector
* the function that extracts a key from the source items to be used as the key in the Map
* @param valueSelector
* the function that extracts a value from the source items to be used as the value in the Map
* @param mapFactory
* the function that returns a Map instance to be used
* @param collectionFactory
* the function that returns a Collection instance for a particular key to be used in the Map
* @return an Observable that emits a single item: a Map that contains the collection of mapped items from
* the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-tomap-and-tomultimap">RxJava Wiki: toMap()</a>
*/
public final <K, V> Observable<Map<K, Collection<V>>> toMultimap(Func1<? super T, ? extends K> keySelector, Func1<? super T, ? extends V> valueSelector, Func0<? extends Map<K, Collection<V>>> mapFactory, Func1<? super K, ? extends Collection<V>> collectionFactory) {
return lift(new OperatorToMultimap<T, K, V>(keySelector, valueSelector, mapFactory, collectionFactory));
}
/**
* Returns an Observable that emits a list that contains the items emitted by the source Observable, in a
* sorted order. Each item emitted by the Observable must implement {@link Comparable} with respect to all
* other items in the sequence.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toSortedList.png">
*
* @throws ClassCastException
* if any item emitted by the Observable does not implement {@link Comparable} with respect to
* all other items emitted by the Observable
* @return an Observable that emits a list that contains the items emitted by the source Observable in
* sorted order
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-tosortedlist">RxJava Wiki: toSortedList()</a>
*/
public final Observable<List<T>> toSortedList() {
return lift(new OperatorToObservableSortedList<T>());
}
/**
* Returns an Observable that emits a list that contains the items emitted by the source Observable, in a
* sorted order based on a specified comparison function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toSortedList.f.png">
*
* @param sortFunction
* a function that compares two items emitted by the source Observable and returns an Integer
* that indicates their sort order
* @return an Observable that emits a list that contains the items emitted by the source Observable in
* sorted order
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-tosortedlist">RxJava Wiki: toSortedList()</a>
*/
public final Observable<List<T>> toSortedList(Func2<? super T, ? super T, Integer> sortFunction) {
return lift(new OperatorToObservableSortedList<T>(sortFunction));
}
/**
* Asynchronously unsubscribes on the specified {@link Scheduler}.
*
* @param scheduler
* the {@link Scheduler} to perform subscription and unsubscription actions on
* @return the source Observable modified so that its unsubscriptions happen on the specified {@link Scheduler}
* @since 0.17
*/
public final Observable<T> unsubscribeOn(Scheduler scheduler) {
return lift(new OperatorUnsubscribeOn<T>(scheduler));
}
/**
* Returns an Observable that emits windows of items it collects from the source Observable. The resulting
* Observable emits connected, non-overlapping windows. It emits the current window and opens a new one when
* the Observable produced by the specified {@code closingSelector} emits an item. The {@code closingSelector} then creates a new Observable to generate the closer of the next window.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window1.png">
*
* @param closingSelector
* a {@link Func0} that produces an Observable for every window created. When this Observable
* emits an item, {@code window()} emits the associated window and begins a new one.
* @return an Observable that emits connected, non-overlapping windows of items from the source Observable
* when {@code closingSelector} emits an item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-window">RxJava Wiki: window()</a>
*/
public final <TClosing> Observable<Observable<T>> window(Func0<? extends Observable<? extends TClosing>> closingSelector) {
return lift(new OperatorWindowWithObservable<T, TClosing>(closingSelector));
}
/**
* Returns an Observable that emits windows of items it collects from the source Observable. The resulting
* Observable emits connected, non-overlapping windows, each containing {@code count} items. When the source
* Observable completes or encounters an error, the resulting Observable emits the current window and
* propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window3.png">
*
* @param count
* the maximum size of each window before it should be emitted
* @return an Observable that emits connected, non-overlapping windows, each containing at most {@code count} items from the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-window">RxJava Wiki: window()</a>
*/
public final Observable<Observable<T>> window(int count) {
return lift(new OperatorWindowWithSize<T>(count, count));
}
/**
* Returns an Observable that emits windows of items it collects from the source Observable. The resulting
* Observable emits windows every {@code skip} items, each containing no more than {@code count} items. When
* the source Observable completes or encounters an error, the resulting Observable emits the current window
* and propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window4.png">
*
* @param count
* the maximum size of each window before it should be emitted
* @param skip
* how many items need to be skipped before starting a new window. Note that if {@code skip} and {@code count} are equal this is the same operation as {@link #window(int)}.
* @return an Observable that emits windows every {@code skip} items containing at most {@code count} items
* from the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-window">RxJava Wiki: window()</a>
*/
public final Observable<Observable<T>> window(int count, int skip) {
return lift(new OperatorWindowWithSize<T>(count, skip));
}
/**
* Returns an Observable that emits windows of items it collects from the source Observable. The resulting
* Observable starts a new window periodically, as determined by the {@code timeshift} argument. It emits
* each window after a fixed timespan, specified by the {@code timespan} argument. When the source
* Observable completes or Observable completes or encounters an error, the resulting Observable emits the
* current window and propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window7.png">
*
* @param timespan
* the period of time each window collects items before it should be emitted
* @param timeshift
* the period of time after which a new window will be created
* @param unit
* the unit of time that applies to the {@code timespan} and {@code timeshift} arguments
* @return an Observable that emits new windows periodically as a fixed timespan elapses
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-window">RxJava Wiki: window()</a>
*/
public final Observable<Observable<T>> window(long timespan, long timeshift, TimeUnit unit) {
return lift(new OperatorWindowWithTime<T>(timespan, timeshift, unit, Integer.MAX_VALUE, Schedulers.computation()));
}
/**
* Returns an Observable that emits windows of items it collects from the source Observable. The resulting
* Observable starts a new window periodically, as determined by the {@code timeshift} argument. It emits
* each window after a fixed timespan, specified by the {@code timespan} argument. When the source
* Observable completes or Observable completes or encounters an error, the resulting Observable emits the
* current window and propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window7.s.png">
*
* @param timespan
* the period of time each window collects items before it should be emitted
* @param timeshift
* the period of time after which a new window will be created
* @param unit
* the unit of time that applies to the {@code timespan} and {@code timeshift} arguments
* @param scheduler
* the {@link Scheduler} to use when determining the end and start of a window
* @return an Observable that emits new windows periodically as a fixed timespan elapses
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-window">RxJava Wiki: window()</a>
*/
public final Observable<Observable<T>> window(long timespan, long timeshift, TimeUnit unit, Scheduler scheduler) {
return lift(new OperatorWindowWithTime<T>(timespan, timeshift, unit, Integer.MAX_VALUE, scheduler));
}
/**
* Returns an Observable that emits windows of items it collects from the source Observable. The resulting
* Observable emits connected, non-overlapping windows, each of a fixed duration specified by the {@code timespan} argument. When the source Observable completes or encounters an error, the
* resulting
* Observable emits the current window and propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window5.png">
*
* @param timespan
* the period of time each window collects items before it should be emitted and replaced with a
* new window
* @param unit
* the unit of time that applies to the {@code timespan} argument
* @return an Observable that emits connected, non-overlapping windows represending items emitted by the
* source Observable during fixed, consecutive durations
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-window">RxJava Wiki: window()</a>
*/
public final Observable<Observable<T>> window(long timespan, TimeUnit unit) {
return lift(new OperatorWindowWithTime<T>(timespan, timespan, unit, Integer.MAX_VALUE, Schedulers.computation()));
}
/**
* Returns an Observable that emits windows of items it collects from the source Observable. The resulting
* Observable emits connected, non-overlapping windows, each of a fixed duration as specified by the {@code timespan} argument or a maximum size as specified by the {@code count} argument
* (whichever is
* reached first). When the source Observable completes or encounters an error, the resulting Observable
* emits the current window and propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window6.png">
*
* @param timespan
* the period of time each window collects items before it should be emitted and replaced with a
* new window
* @param unit
* the unit of time that applies to the {@code timespan} argument
* @param count
* the maximum size of each window before it should be emitted
* @return an Observable that emits connected, non-overlapping windows of items from the source Observable
* that were emitted during a fixed duration of time or when the window has reached maximum capacity
* (whichever occurs first)
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-window">RxJava Wiki: window()</a>
*/
public final Observable<Observable<T>> window(long timespan, TimeUnit unit, int count) {
return lift(new OperatorWindowWithTime<T>(timespan, timespan, unit, count, Schedulers.computation()));
}
/**
* Returns an Observable that emits windows of items it collects from the source Observable. The resulting
* Observable emits connected, non-overlapping windows, each of a fixed duration specified by the {@code timespan} argument or a maximum size specified by the {@code count} argument (whichever is
* reached
* first). When the source Observable completes or encounters an error, the resulting Observable emits the
* current window and propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window6.s.png">
*
* @param timespan
* the period of time each window collects items before it should be emitted and replaced with a
* new window
* @param unit
* the unit of time which applies to the {@code timespan} argument
* @param count
* the maximum size of each window before it should be emitted
* @param scheduler
* the {@link Scheduler} to use when determining the end and start of a window
* @return an Observable that emits connected, non-overlapping windows of items from the source Observable
* that were emitted during a fixed duration of time or when the window has reached maximum capacity
* (whichever occurs first)
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-window">RxJava Wiki: window()</a>
*/
public final Observable<Observable<T>> window(long timespan, TimeUnit unit, int count, Scheduler scheduler) {
return lift(new OperatorWindowWithTime<T>(timespan, timespan, unit, count, scheduler));
}
/**
* Returns an Observable that emits windows of items it collects from the source Observable. The resulting
* Observable emits connected, non-overlapping windows, each of a fixed duration as specified by the {@code timespan} argument. When the source Observable completes or encounters an error, the
* resulting
* Observable emits the current window and propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window5.s.png">
*
* @param timespan
* the period of time each window collects items before it should be emitted and replaced with a
* new window
* @param unit
* the unit of time which applies to the {@code timespan} argument
* @param scheduler
* the {@link Scheduler} to use when determining the end and start of a window
* @return an Observable that emits connected, non-overlapping windows containing items emitted by the
* source Observable within a fixed duration
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-window">RxJava Wiki: window()</a>
*/
public final Observable<Observable<T>> window(long timespan, TimeUnit unit, Scheduler scheduler) {
return lift(new OperatorWindowWithTime<T>(timespan, timespan, unit, Integer.MAX_VALUE, scheduler));
}
/**
* Returns an Observable that emits windows of items it collects from the source Observable. The resulting
* Observable emits windows that contain those items emitted by the source Observable between the time when
* the {@code windowOpenings} Observable emits an item and when the Observable returned by {@code closingSelector} emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window2.png">
*
* @param windowOpenings
* an Observable that, when it emits an item, causes another window to be created
* @param closingSelector
* a {@link Func1} that produces an Observable for every window created. When this Observable
* emits an item, the associated window is closed and emitted
* @return an Observable that emits windows of items emitted by the source Observable that are governed by
* the specified window-governing Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-window">RxJava Wiki: window()</a>
*/
public final <TOpening, TClosing> Observable<Observable<T>> window(Observable<? extends TOpening> windowOpenings, Func1<? super TOpening, ? extends Observable<? extends TClosing>> closingSelector) {
return lift(new OperatorWindowWithStartEndObservable<T, TOpening, TClosing>(windowOpenings, closingSelector));
}
/**
* Returns an Observable that emits non-overlapping windows of items it collects from the source Observable
* where the boundary of each window is determined by the items emitted from a specified boundary-governing
* Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window8.png">
*
* @param <U>
* the window element type (ignored)
* @param boundary
* an Observable whose emitted items close and open windows
* @return an Observable that emits non-overlapping windows of items it collects from the source Observable
* where the boundary of each window is determined by the items emitted from the {@code boundary} Observable
*/
public final <U> Observable<Observable<T>> window(Observable<U> boundary) {
return lift(new OperatorWindowWithObservable<T, U>(boundary));
}
/**
* Returns an Observable that emits items that are the result of applying a specified function to pairs of
* values, one each from the source Observable and a specified Iterable sequence.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.i.png">
* <p>
* Note that the {@code other} Iterable is evaluated as items are observed from the source Observable; it is
* not pre-consumed. This allows you to zip infinite streams on either side.
*
* @param <T2>
* the type of items in the {@code other} Iterable
* @param <R>
* the type of items emitted by the resulting Observable
* @param other
* the Iterable sequence
* @param zipFunction
* a function that combines the pairs of items from the Observable and the Iterable to generate
* the items to be emitted by the resulting Observable
* @return an Observable that pairs up values from the source Observable and the {@code other} Iterable
* sequence and emits the results of {@code zipFunction} applied to these pairs
*/
public final <T2, R> Observable<R> zip(Iterable<? extends T2> other, Func2<? super T, ? super T2, ? extends R> zipFunction) {
return lift(new OperatorZipIterable<T, T2, R>(other, zipFunction));
}
/**
* Returns an Observable that emits items that are the result of applying a specified function to pairs of
* values, one each from the source Observable and another specified Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png">
*
* @param <T2>
* the type of items emitted by the {@code other} Observable
* @param <R>
* the type of items emitted by the resulting Observable
* @param other
* the other Observable
* @param zipFunction
* a function that combines the pairs of items from the two Observables to generate the items to
* be emitted by the resulting Observable
* @return an Observable that pairs up values from the source Observable and the {@code other} Observable
* and emits the results of {@code zipFunction} applied to these pairs
*/
public final <T2, R> Observable<R> zip(Observable<? extends T2> other, Func2<? super T, ? super T2, ? extends R> zipFunction) {
return zip(this, other, zipFunction);
}
/**
* An Observable that never sends any information to an {@link Observer}.
*
* This Observable is useful primarily for testing purposes.
*
* @param <T>
* the type of item (not) emitted by the Observable
*/
private static class NeverObservable<T> extends Observable<T> {
public NeverObservable() {
super(new OnSubscribe<T>() {
@Override
public void call(Subscriber<? super T> observer) {
// do nothing
}
});
}
}
/**
* An Observable that invokes {@link Observer#onError onError} when the {@link Observer} subscribes to it.
*
* @param <T>
* the type of item (ostensibly) emitted by the Observable
*/
private static class ThrowObservable<T> extends Observable<T> {
public ThrowObservable(final Throwable exception) {
super(new OnSubscribe<T>() {
/**
* Accepts an {@link Observer} and calls its {@link Observer#onError onError} method.
*
* @param observer
* an {@link Observer} of this Observable
* @return a reference to the subscription
*/
@Override
public void call(Subscriber<? super T> observer) {
observer.onError(exception);
}
});
}
}
}
| rxjava-core/src/main/java/rx/Observable.java | /**
* Copyright 2014 Netflix, 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 rx;
import static rx.functions.Functions.alwaysFalse;
import java.util.*;
import java.util.concurrent.*;
import rx.exceptions.*;
import rx.functions.*;
import rx.observables.*;
import rx.observers.SafeSubscriber;
import rx.operators.*;
import rx.plugins.*;
import rx.schedulers.*;
import rx.subjects.*;
import rx.subscriptions.Subscriptions;
/**
* The Observable class that implements the Reactive Pattern.
* <p>
* This class provides methods for subscribing to the Observable as well as delegate methods to the various
* Observers.
* <p>
* The documentation for this class makes use of marble diagrams. The following legend explains these diagrams:
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/legend.png">
* <p>
* For more information see the <a href="https://github.com/Netflix/RxJava/wiki/Observable">RxJava Wiki</a>
*
* @param <T>
* the type of the items emitted by the Observable
*/
public class Observable<T> {
final OnSubscribe<T> onSubscribe;
/**
* Observable with Function to execute when subscribed to.
* <p>
* <em>Note:</em> Use {@link #create(OnSubscribe)} to create an Observable, instead of this constructor,
* unless you specifically have a need for inheritance.
*
* @param f
* {@link OnSubscribe} to be executed when {@link #subscribe(Subscriber)} is called
*/
protected Observable(OnSubscribe<T> f) {
this.onSubscribe = f;
}
private static final RxJavaObservableExecutionHook hook = RxJavaPlugins.getInstance().getObservableExecutionHook();
/**
* Returns an Observable that will execute the specified function when a {@link Subscriber} subscribes to
* it.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/create.png">
* <p>
* Write the function you pass to {@code create} so that it behaves as an Observable: It should invoke the
* Subscriber's {@link Subscriber#onNext onNext}, {@link Subscriber#onError onError}, and {@link Subscriber#onCompleted onCompleted} methods appropriately.
* <p>
* A well-formed Observable must invoke either the Subscriber's {@code onCompleted} method exactly once or
* its {@code onError} method exactly once.
* <p>
* See <a href="http://go.microsoft.com/fwlink/?LinkID=205219">Rx Design Guidelines (PDF)</a> for detailed
* information.
*
* @param <T>
* the type of the items that this Observable emits
* @param f
* a function that accepts an {@code Subscriber<T>}, and invokes its {@code onNext}, {@code onError}, and {@code onCompleted} methods as appropriate
* @return an Observable that, when a {@link Subscriber} subscribes to it, will execute the specified
* function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-create">RxJava Wiki: create()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.create.aspx">MSDN: Observable.Create</a>
*/
public final static <T> Observable<T> create(OnSubscribe<T> f) {
return new Observable<T>(hook.onCreate(f));
}
/**
* Invoked when Obserable.subscribe is called.
*/
public static interface OnSubscribe<T> extends Action1<Subscriber<? super T>> {
// cover for generics insanity
}
/**
* Operator function for lifting into an Observable.
*/
public interface Operator<R, T> extends Func1<Subscriber<? super R>, Subscriber<? super T>> {
// cover for generics insanity
}
/**
* @deprecated use {@link #create(OnSubscribe)}
*/
@Deprecated
public final static <T> Observable<T> create(final OnSubscribeFunc<T> f) {
return new Observable<T>(new OnSubscribe<T>() {
@Override
public void call(Subscriber<? super T> observer) {
Subscription s = f.onSubscribe(observer);
if (s != null && s != observer) {
observer.add(s);
}
}
});
}
/**
* @deprecated use {@link OnSubscribe}
*/
@Deprecated
public static interface OnSubscribeFunc<T> extends Function {
public Subscription onSubscribe(Observer<? super T> op);
}
/**
* Lift a function to the current Observable and return a new Observable that when subscribed to will pass
* the values of the current Observable through the function.
* <p>
* In other words, this allows chaining Observers together on an Observable for acting on the values within
* the Observable.
* <p> {@code
* observable.map(...).filter(...).take(5).lift(new ObserverA()).lift(new ObserverB(...)).subscribe()
* }
*
* @param lift
* @return an Observable that emits values that are the result of applying the bind function to the values
* of the current Observable
* @since 0.17
*/
public final <R> Observable<R> lift(final Operator<? extends R, ? super T> lift) {
return new Observable<R>(new OnSubscribe<R>() {
@Override
public void call(Subscriber<? super R> o) {
try {
onSubscribe.call(hook.onLift(lift).call(o));
} catch (Throwable e) {
// localized capture of errors rather than it skipping all operators
// and ending up in the try/catch of the subscribe method which then
// prevents onErrorResumeNext and other similar approaches to error handling
if (e instanceof OnErrorNotImplementedException) {
throw (OnErrorNotImplementedException) e;
}
o.onError(e);
}
}
});
}
/* *********************************************************************************************************
* Observers Below Here
* *********************************************************************************************************
*/
/**
* Mirror the one Observable in an Iterable of several Observables that first emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png">
*
* @param sources
* an Iterable of Observable sources competing to react first
* @return an Observable that emits the same sequence of items as whichever of the source Observables first
* emitted an item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-amb">RxJava Wiki: amb()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229115.aspx">MSDN: Observable.Amb</a>
*/
public final static <T> Observable<T> amb(Iterable<? extends Observable<? extends T>> sources) {
return create(OperatorAmb.amb(sources));
}
/**
* Given two Observables, mirror the one that first emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png">
*
* @param o1
* an Observable competing to react first
* @param o2
* an Observable competing to react first
* @return an Observable that emits the same sequence of items as whichever of the source Observables first
* emitted an item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-amb">RxJava Wiki: amb()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a>
*/
public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2) {
return create(OperatorAmb.amb(o1, o2));
}
/**
* Given three Observables, mirror the one that first emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png">
*
* @param o1
* an Observable competing to react first
* @param o2
* an Observable competing to react first
* @param o3
* an Observable competing to react first
* @return an Observable that emits the same sequence of items as whichever of the source Observables first
* emitted an item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-amb">RxJava Wiki: amb()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a>
*/
public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3) {
return create(OperatorAmb.amb(o1, o2, o3));
}
/**
* Given four Observables, mirror the one that first emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png">
*
* @param o1
* an Observable competing to react first
* @param o2
* an Observable competing to react first
* @param o3
* an Observable competing to react first
* @param o4
* an Observable competing to react first
* @return an Observable that emits the same sequence of items as whichever of the source Observables first
* emitted an item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-amb">RxJava Wiki: amb()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a>
*/
public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4) {
return create(OperatorAmb.amb(o1, o2, o3, o4));
}
/**
* Given five Observables, mirror the one that first emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png">
*
* @param o1
* an Observable competing to react first
* @param o2
* an Observable competing to react first
* @param o3
* an Observable competing to react first
* @param o4
* an Observable competing to react first
* @param o5
* an Observable competing to react first
* @return an Observable that emits the same sequence of items as whichever of the source Observables first
* emitted an item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-amb">RxJava Wiki: amb()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a>
*/
public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5) {
return create(OperatorAmb.amb(o1, o2, o3, o4, o5));
}
/**
* Given six Observables, mirror the one that first emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png">
*
* @param o1
* an Observable competing to react first
* @param o2
* an Observable competing to react first
* @param o3
* an Observable competing to react first
* @param o4
* an Observable competing to react first
* @param o5
* an Observable competing to react first
* @param o6
* an Observable competing to react first
* @return an Observable that emits the same sequence of items as whichever of the source Observables first
* emitted an item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-amb">RxJava Wiki: amb()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a>
*/
public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5, Observable<? extends T> o6) {
return create(OperatorAmb.amb(o1, o2, o3, o4, o5, o6));
}
/**
* Given seven Observables, mirror the one that first emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png">
*
* @param o1
* an Observable competing to react first
* @param o2
* an Observable competing to react first
* @param o3
* an Observable competing to react first
* @param o4
* an Observable competing to react first
* @param o5
* an Observable competing to react first
* @param o6
* an Observable competing to react first
* @param o7
* an Observable competing to react first
* @return an Observable that emits the same sequence of items as whichever of the source Observables first
* emitted an item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-amb">RxJava Wiki: amb()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a>
*/
public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5, Observable<? extends T> o6, Observable<? extends T> o7) {
return create(OperatorAmb.amb(o1, o2, o3, o4, o5, o6, o7));
}
/**
* Given eight Observables, mirror the one that first emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png">
*
* @param o1
* an Observable competing to react first
* @param o2
* an Observable competing to react first
* @param o3
* an Observable competing to react first
* @param o4
* an Observable competing to react first
* @param o5
* an Observable competing to react first
* @param o6
* an Observable competing to react first
* @param o7
* an Observable competing to react first
* @param o8
* an observable competing to react first
* @return an Observable that emits the same sequence of items as whichever of the source Observables first
* emitted an item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-amb">RxJava Wiki: amb()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a>
*/
public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5, Observable<? extends T> o6, Observable<? extends T> o7, Observable<? extends T> o8) {
return create(OperatorAmb.amb(o1, o2, o3, o4, o5, o6, o7, o8));
}
/**
* Given nine Observables, mirror the one that first emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png">
*
* @param o1
* an Observable competing to react first
* @param o2
* an Observable competing to react first
* @param o3
* an Observable competing to react first
* @param o4
* an Observable competing to react first
* @param o5
* an Observable competing to react first
* @param o6
* an Observable competing to react first
* @param o7
* an Observable competing to react first
* @param o8
* an Observable competing to react first
* @param o9
* an Observable competing to react first
* @return an Observable that emits the same sequence of items as whichever of the source Observables first
* emitted an item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-amb">RxJava Wiki: amb()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a>
*/
public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5, Observable<? extends T> o6, Observable<? extends T> o7, Observable<? extends T> o8, Observable<? extends T> o9) {
return create(OperatorAmb.amb(o1, o2, o3, o4, o5, o6, o7, o8, o9));
}
/**
* Combines two source Observables by emitting an item that aggregates the latest values of each of the
* source Observables each time an item is received from either of the source Observables, where this
* aggregation is defined by a specified function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/combineLatest.png">
*
* @param o1
* the first source Observable
* @param o2
* the second source Observable
* @param combineFunction
* the aggregation function used to combine the items emitted by the source Observables
* @return an Observable that emits items that are the result of combining the items emitted by the source
* Observables by means of the given aggregation function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-combinelatest">RxJava Wiki: combineLatest()</a>
*/
@SuppressWarnings("unchecked")
public static final <T1, T2, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Func2<? super T1, ? super T2, ? extends R> combineFunction) {
return combineLatest(Arrays.asList(o1, o2), Functions.fromFunc(combineFunction));
}
/**
* Combines three source Observables by emitting an item that aggregates the latest values of each of the
* source Observables each time an item is received from any of the source Observables, where this
* aggregation is defined by a specified function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/combineLatest.png">
*
* @param o1
* the first source Observable
* @param o2
* the second source Observable
* @param o3
* the third source Observable
* @param combineFunction
* the aggregation function used to combine the items emitted by the source Observables
* @return an Observable that emits items that are the result of combining the items emitted by the source
* Observables by means of the given aggregation function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-combinelatest">RxJava Wiki: combineLatest()</a>
*/
@SuppressWarnings("unchecked")
public static final <T1, T2, T3, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Func3<? super T1, ? super T2, ? super T3, ? extends R> combineFunction) {
return combineLatest(Arrays.asList(o1, o2, o3), Functions.fromFunc(combineFunction));
}
/**
* Combines four source Observables by emitting an item that aggregates the latest values of each of the
* source Observables each time an item is received from any of the source Observables, where this
* aggregation is defined by a specified function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/combineLatest.png">
*
* @param o1
* the first source Observable
* @param o2
* the second source Observable
* @param o3
* the third source Observable
* @param o4
* the fourth source Observable
* @param combineFunction
* the aggregation function used to combine the items emitted by the source Observables
* @return an Observable that emits items that are the result of combining the items emitted by the source
* Observables by means of the given aggregation function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-combinelatest">RxJava Wiki: combineLatest()</a>
*/
@SuppressWarnings("unchecked")
public static final <T1, T2, T3, T4, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4,
Func4<? super T1, ? super T2, ? super T3, ? super T4, ? extends R> combineFunction) {
return combineLatest(Arrays.asList(o1, o2, o3, o4), Functions.fromFunc(combineFunction));
}
/**
* Combines five source Observables by emitting an item that aggregates the latest values of each of the
* source Observables each time an item is received from any of the source Observables, where this
* aggregation is defined by a specified function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/combineLatest.png">
*
* @param o1
* the first source Observable
* @param o2
* the second source Observable
* @param o3
* the third source Observable
* @param o4
* the fourth source Observable
* @param o5
* the fifth source Observable
* @param combineFunction
* the aggregation function used to combine the items emitted by the source Observables
* @return an Observable that emits items that are the result of combining the items emitted by the source
* Observables by means of the given aggregation function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-combinelatest">RxJava Wiki: combineLatest()</a>
*/
@SuppressWarnings("unchecked")
public static final <T1, T2, T3, T4, T5, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5,
Func5<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? extends R> combineFunction) {
return combineLatest(Arrays.asList(o1, o2, o3, o4, o5), Functions.fromFunc(combineFunction));
}
/**
* Combines six source Observables by emitting an item that aggregates the latest values of each of the
* source Observables each time an item is received from any of the source Observables, where this
* aggregation is defined by a specified function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/combineLatest.png">
*
* @param o1
* the first source Observable
* @param o2
* the second source Observable
* @param o3
* the third source Observable
* @param o4
* the fourth source Observable
* @param o5
* the fifth source Observable
* @param o6
* the sixth source Observable
* @param combineFunction
* the aggregation function used to combine the items emitted by the source Observables
* @return an Observable that emits items that are the result of combining the items emitted by the source
* Observables by means of the given aggregation function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-combinelatest">RxJava Wiki: combineLatest()</a>
*/
@SuppressWarnings("unchecked")
public static final <T1, T2, T3, T4, T5, T6, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6,
Func6<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? extends R> combineFunction) {
return combineLatest(Arrays.asList(o1, o2, o3, o4, o5, o6), Functions.fromFunc(combineFunction));
}
/**
* Combines seven source Observables by emitting an item that aggregates the latest values of each of the
* source Observables each time an item is received from any of the source Observables, where this
* aggregation is defined by a specified function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/combineLatest.png">
*
* @param o1
* the first source Observable
* @param o2
* the second source Observable
* @param o3
* the third source Observable
* @param o4
* the fourth source Observable
* @param o5
* the fifth source Observable
* @param o6
* the sixth source Observable
* @param o7
* the seventh source Observable
* @param combineFunction
* the aggregation function used to combine the items emitted by the source Observables
* @return an Observable that emits items that are the result of combining the items emitted by the source
* Observables by means of the given aggregation function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-combinelatest">RxJava Wiki: combineLatest()</a>
*/
@SuppressWarnings("unchecked")
public static final <T1, T2, T3, T4, T5, T6, T7, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Observable<? extends T7> o7,
Func7<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? extends R> combineFunction) {
return combineLatest(Arrays.asList(o1, o2, o3, o4, o5, o6, o7), Functions.fromFunc(combineFunction));
}
/**
* Combines eight source Observables by emitting an item that aggregates the latest values of each of the
* source Observables each time an item is received from any of the source Observables, where this
* aggregation is defined by a specified function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/combineLatest.png">
*
* @param o1
* the first source Observable
* @param o2
* the second source Observable
* @param o3
* the third source Observable
* @param o4
* the fourth source Observable
* @param o5
* the fifth source Observable
* @param o6
* the sixth source Observable
* @param o7
* the seventh source Observable
* @param o8
* the eighth source Observable
* @param combineFunction
* the aggregation function used to combine the items emitted by the source Observables
* @return an Observable that emits items that are the result of combining the items emitted by the source
* Observables by means of the given aggregation function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-combinelatest">RxJava Wiki: combineLatest()</a>
*/
@SuppressWarnings("unchecked")
public static final <T1, T2, T3, T4, T5, T6, T7, T8, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Observable<? extends T7> o7, Observable<? extends T8> o8,
Func8<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? extends R> combineFunction) {
return combineLatest(Arrays.asList(o1, o2, o3, o4, o5, o6, o7, o8), Functions.fromFunc(combineFunction));
}
/**
* Combines nine source Observables by emitting an item that aggregates the latest values of each of the
* source Observables each time an item is received from any of the source Observables, where this
* aggregation is defined by a specified function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/combineLatest.png">
*
* @param o1
* the first source Observable
* @param o2
* the second source Observable
* @param o3
* the third source Observable
* @param o4
* the fourth source Observable
* @param o5
* the fifth source Observable
* @param o6
* the sixth source Observable
* @param o7
* the seventh source Observable
* @param o8
* the eighth source Observable
* @param o9
* the ninth source Observable
* @param combineFunction
* the aggregation function used to combine the items emitted by the source Observables
* @return an Observable that emits items that are the result of combining the items emitted by the source
* Observables by means of the given aggregation function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-combinelatest">RxJava Wiki: combineLatest()</a>
*/
@SuppressWarnings("unchecked")
public static final <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Observable<? extends T7> o7, Observable<? extends T8> o8,
Observable<? extends T9> o9,
Func9<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? super T9, ? extends R> combineFunction) {
return combineLatest(Arrays.asList(o1, o2, o3, o4, o5, o6, o7, o8, o9), Functions.fromFunc(combineFunction));
}
/**
* Combines nine source Observables by emitting an item that aggregates the latest values of each of the
* source Observables each time an item is received from any of the source Observables, where this
* aggregation is defined by a specified function.
* @param <T> the common base type of source values
* @param <R> the result type
* @param sources the list of observable sources
* @param combineFunction
* the aggregation function used to combine the items emitted by the source Observables
* @return an Observable that emits items that are the result of combining the items emitted by the source
* Observables by means of the given aggregation function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-combinelatest">RxJava Wiki: combineLatest()</a>
*/
public static final <T, R> Observable<R> combineLatest(List<? extends Observable<? extends T>> sources, FuncN<? extends R> combineFunction) {
return create(new OperatorCombineLatest<T, R>(sources, combineFunction));
}
/**
* Returns an Observable that emits the items emitted by each of the Observables emitted by an Observable,
* one after the other, without interleaving them.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png">
*
* @param observables
* an Observable that emits Observables
* @return an Observable that emits items all of the items emitted by the Observables emitted by {@code observables}, one after the other, without interleaving them
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-concat">RxJava Wiki: concat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a>
*/
public final static <T> Observable<T> concat(Observable<? extends Observable<? extends T>> observables) {
return observables.lift(new OperatorConcat<T>());
}
/**
* Returns an Observable that emits the items emitted by two Observables, one after the other, without
* interleaving them.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png">
*
* @param t1
* an Observable to be concatenated
* @param t2
* an Observable to be concatenated
* @return an Observable that emits items emitted by the two source Observables, one after the other,
* without interleaving them
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-concat">RxJava Wiki: concat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a>
*/
public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2) {
return concat(from(t1, t2));
}
/**
* Returns an Observable that emits the items emitted by three Observables, one after the other, without
* interleaving them.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png">
*
* @param t1
* an Observable to be concatenated
* @param t2
* an Observable to be concatenated
* @param t3
* an Observable to be concatenated
* @return an Observable that emits items emitted by the three source Observables, one after the other,
* without interleaving them
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-concat">RxJava Wiki: concat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a>
*/
public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3) {
return concat(from(t1, t2, t3));
}
/**
* Returns an Observable that emits the items emitted by four Observables, one after the other, without
* interleaving them.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png">
*
* @param t1
* an Observable to be concatenated
* @param t2
* an Observable to be concatenated
* @param t3
* an Observable to be concatenated
* @param t4
* an Observable to be concatenated
* @return an Observable that emits items emitted by the four source Observables, one after the other,
* without interleaving them
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-concat">RxJava Wiki: concat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a>
*/
public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4) {
return concat(from(t1, t2, t3, t4));
}
/**
* Returns an Observable that emits the items emitted by five Observables, one after the other, without
* interleaving them.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png">
*
* @param t1
* an Observable to be concatenated
* @param t2
* an Observable to be concatenated
* @param t3
* an Observable to be concatenated
* @param t4
* an Observable to be concatenated
* @param t5
* an Observable to be concatenated
* @return an Observable that emits items emitted by the five source Observables, one after the other,
* without interleaving them
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-concat">RxJava Wiki: concat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a>
*/
public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5) {
return concat(from(t1, t2, t3, t4, t5));
}
/**
* Returns an Observable that emits the items emitted by six Observables, one after the other, without
* interleaving them.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png">
*
* @param t1
* an Observable to be concatenated
* @param t2
* an Observable to be concatenated
* @param t3
* an Observable to be concatenated
* @param t4
* an Observable to be concatenated
* @param t5
* an Observable to be concatenated
* @param t6
* an Observable to be concatenated
* @return an Observable that emits items emitted by the six source Observables, one after the other,
* without interleaving them
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-concat">RxJava Wiki: concat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a>
*/
public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6) {
return concat(from(t1, t2, t3, t4, t5, t6));
}
/**
* Returns an Observable that emits the items emitted by seven Observables, one after the other, without
* interleaving them.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png">
*
* @param t1
* an Observable to be concatenated
* @param t2
* an Observable to be concatenated
* @param t3
* an Observable to be concatenated
* @param t4
* an Observable to be concatenated
* @param t5
* an Observable to be concatenated
* @param t6
* an Observable to be concatenated
* @param t7
* an Observable to be concatenated
* @return an Observable that emits items emitted by the seven source Observables, one after the other,
* without interleaving them
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-concat">RxJava Wiki: concat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a>
*/
public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7) {
return concat(from(t1, t2, t3, t4, t5, t6, t7));
}
/**
* Returns an Observable that emits the items emitted by eight Observables, one after the other, without
* interleaving them.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png">
*
* @param t1
* an Observable to be concatenated
* @param t2
* an Observable to be concatenated
* @param t3
* an Observable to be concatenated
* @param t4
* an Observable to be concatenated
* @param t5
* an Observable to be concatenated
* @param t6
* an Observable to be concatenated
* @param t7
* an Observable to be concatenated
* @param t8
* an Observable to be concatenated
* @return an Observable that emits items emitted by the eight source Observables, one after the other,
* without interleaving them
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-concat">RxJava Wiki: concat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a>
*/
public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7, Observable<? extends T> t8) {
return concat(from(t1, t2, t3, t4, t5, t6, t7, t8));
}
/**
* Returns an Observable that emits the items emitted by nine Observables, one after the other, without
* interleaving them.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png">
*
* @param t1
* an Observable to be concatenated
* @param t2
* an Observable to be concatenated
* @param t3
* an Observable to be concatenated
* @param t4
* an Observable to be concatenated
* @param t5
* an Observable to be concatenated
* @param t6
* an Observable to be concatenated
* @param t7
* an Observable to be concatenated
* @param t8
* an Observable to be concatenated
* @param t9
* an Observable to be concatenated
* @return an Observable that emits items emitted by the nine source Observables, one after the other,
* without interleaving them
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-concat">RxJava Wiki: concat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a>
*/
public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7, Observable<? extends T> t8, Observable<? extends T> t9) {
return concat(from(t1, t2, t3, t4, t5, t6, t7, t8, t9));
}
/**
* Returns an Observable that calls an Observable factory to create its Observable for each new Observer
* that subscribes. That is, for each subscriber, the actual Observable that subscriber observes is
* determined by the factory function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/defer.png">
* <p>
* The defer Observer allows you to defer or delay emitting items from an Observable until such time as an
* Observer subscribes to the Observable. This allows an {@link Observer} to easily obtain updates or a
* refreshed version of the sequence.
*
* @param observableFactory
* the Observable factory function to invoke for each {@link Observer} that subscribes to the
* resulting Observable
* @param <T>
* the type of the items emitted by the Observable
* @return an Observable whose {@link Observer}s' subscriptions trigger an invocation of the given
* Observable factory function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-defer">RxJava Wiki: defer()</a>
*/
public final static <T> Observable<T> defer(Func0<? extends Observable<? extends T>> observableFactory) {
return create(new OperatorDefer<T>(observableFactory));
}
/**
* Returns an Observable that emits no items to the {@link Observer} and immediately invokes its {@link Observer#onCompleted onCompleted} method.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/empty.png">
*
* @param <T>
* the type of the items (ostensibly) emitted by the Observable
* @return an Observable that emits no items to the {@link Observer} but immediately invokes the {@link Observer}'s {@link Observer#onCompleted() onCompleted} method
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-empty-error-and-never">RxJava Wiki: empty()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229670.aspx">MSDN: Observable.Empty</a>
*/
public final static <T> Observable<T> empty() {
return from(new ArrayList<T>());
}
/**
* Returns an Observable that emits no items to the {@link Observer} and immediately invokes its {@link Observer#onCompleted onCompleted} method on the specified Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/empty.s.png">
*
* @param scheduler
* the Scheduler to use to call the {@link Observer#onCompleted onCompleted} method
* @param <T>
* the type of the items (ostensibly) emitted by the Observable
* @return an Observable that emits no items to the {@link Observer} but immediately invokes the {@link Observer}'s {@link Observer#onCompleted() onCompleted} method with the specified
* {@code scheduler}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-empty-error-and-never">RxJava Wiki: empty()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229066.aspx">MSDN: Observable.Empty Method (IScheduler)</a>
*/
public final static <T> Observable<T> empty(Scheduler scheduler) {
return Observable.<T> empty().subscribeOn(scheduler);
}
/**
* Returns an Observable that invokes an {@link Observer}'s {@link Observer#onError onError} method when the
* Observer subscribes to it.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/error.png">
*
* @param exception
* the particular Throwable to pass to {@link Observer#onError onError}
* @param <T>
* the type of the items (ostensibly) emitted by the Observable
* @return an Observable that invokes the {@link Observer}'s {@link Observer#onError onError} method when
* the Observer subscribes to it
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-empty-error-and-never">RxJava Wiki: error()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh244299.aspx">MSDN: Observable.Throw</a>
*/
public final static <T> Observable<T> error(Throwable exception) {
return new ThrowObservable<T>(exception);
}
/**
* Returns an Observable that invokes an {@link Observer}'s {@link Observer#onError onError} method on the
* specified Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/error.s.png">
*
* @param exception
* the particular Throwable to pass to {@link Observer#onError onError}
* @param scheduler
* the Scheduler on which to call {@link Observer#onError onError}
* @param <T>
* the type of the items (ostensibly) emitted by the Observable
* @return an Observable that invokes the {@link Observer}'s {@link Observer#onError onError} method, on
* the specified Scheduler
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-empty-error-and-never">RxJava Wiki: error()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211711.aspx">MSDN: Observable.Throw</a>
*/
public final static <T> Observable<T> error(Throwable exception, Scheduler scheduler) {
return Observable.<T> error(exception).subscribeOn(scheduler);
}
/**
* Converts a {@link Future} into an Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.Future.png">
* <p>
* You can convert any object that supports the {@link Future} interface into an Observable that emits the
* return value of the {@link Future#get} method of that object, by passing the object into the {@code from} method.
* <p>
* <em>Important note:</em> This Observable is blocking; you cannot unsubscribe from it.
*
* @param future
* the source {@link Future}
* @param <T>
* the type of object that the {@link Future} returns, and also the type of item to be emitted by
* the resulting Observable
* @return an Observable that emits the item from the source {@link Future}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
public final static <T> Observable<T> from(Future<? extends T> future) {
return create(OperatorToObservableFuture.toObservableFuture(future));
}
/**
* Converts a {@link Future} into an Observable, with a timeout on the Future.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.Future.png">
* <p>
* You can convert any object that supports the {@link Future} interface into an Observable that emits the
* return value of the {@link Future#get} method of that object, by passing the object into the {@code from} method.
* <p>
* <em>Important note:</em> This Observable is blocking; you cannot unsubscribe from it.
*
* @param future
* the source {@link Future}
* @param timeout
* the maximum time to wait before calling {@code get()}
* @param unit
* the {@link TimeUnit} of the {@code timeout} argument
* @param <T>
* the type of object that the {@link Future} returns, and also the type of item to be emitted by
* the resulting Observable
* @return an Observable that emits the item from the source {@link Future}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
public final static <T> Observable<T> from(Future<? extends T> future, long timeout, TimeUnit unit) {
return create(OperatorToObservableFuture.toObservableFuture(future, timeout, unit));
}
/**
* Converts a {@link Future}, operating on a specified {@link Scheduler}, into an Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.Future.s.png">
* <p>
* You can convert any object that supports the {@link Future} interface into an Observable that emits the
* return value of the {@link Future#get} method of that object, by passing the object into the {@code from} method.
* <p>
*
* @param future
* the source {@link Future}
* @param scheduler
* the {@link Scheduler} to wait for the Future on. Use a Scheduler such as {@link Schedulers#io()} that can block and wait on the Future
* @param <T>
* the type of object that the {@link Future} returns, and also the type of item to be emitted by
* the resulting Observable
* @return an Observable that emits the item from the source {@link Future}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
public final static <T> Observable<T> from(Future<? extends T> future, Scheduler scheduler) {
return create(OperatorToObservableFuture.toObservableFuture(future)).subscribeOn(scheduler);
}
/**
* Converts an {@link Iterable} sequence into an Observable that emits the items in the sequence.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
*
* @param iterable
* the source {@link Iterable} sequence
* @param <T>
* the type of items in the {@link Iterable} sequence and the type of items to be emitted by the
* resulting Observable
* @return an Observable that emits each item in the source {@link Iterable} sequence
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
public final static <T> Observable<T> from(Iterable<? extends T> iterable) {
return create(new OnSubscribeFromIterable<T>(iterable));
}
/**
* Converts an {@link Iterable} sequence into an Observable that operates on the specified Scheduler,
* emitting each item from the sequence.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.s.png">
*
* @param iterable
* the source {@link Iterable} sequence
* @param scheduler
* the Scheduler on which the Observable is to emit the items of the Iterable
* @param <T>
* the type of items in the {@link Iterable} sequence and the type of items to be emitted by the
* resulting Observable
* @return an Observable that emits each item in the source {@link Iterable} sequence, on the specified
* Scheduler
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh212140.aspx">MSDN: Observable.ToObservable</a>
*/
public final static <T> Observable<T> from(Iterable<? extends T> iterable, Scheduler scheduler) {
return create(new OnSubscribeFromIterable<T>(iterable)).subscribeOn(scheduler);
}
/**
* Converts an item into an Observable that emits that item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
*
* @param t1
* the item
* @param <T>
* the type of the item
* @return an Observable that emits the item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
// suppress unchecked because we are using varargs inside the method
@SuppressWarnings("unchecked")
public final static <T> Observable<T> from(T t1) {
return from(Arrays.asList(t1));
}
/**
* Converts two items into an Observable that emits those items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
*
* @param t1
* first item
* @param t2
* second item
* @param <T>
* the type of these items
* @return an Observable that emits each item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
// suppress unchecked because we are using varargs inside the method
@SuppressWarnings("unchecked")
public final static <T> Observable<T> from(T t1, T t2) {
return from(Arrays.asList(t1, t2));
}
/**
* Converts three items into an Observable that emits those items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
*
* @param t1
* first item
* @param t2
* second item
* @param t3
* third item
* @param <T>
* the type of these items
* @return an Observable that emits each item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
// suppress unchecked because we are using varargs inside the method
@SuppressWarnings("unchecked")
public final static <T> Observable<T> from(T t1, T t2, T t3) {
return from(Arrays.asList(t1, t2, t3));
}
/**
* Converts four items into an Observable that emits those items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
*
* @param t1
* first item
* @param t2
* second item
* @param t3
* third item
* @param t4
* fourth item
* @param <T>
* the type of these items
* @return an Observable that emits each item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
// suppress unchecked because we are using varargs inside the method
@SuppressWarnings("unchecked")
public final static <T> Observable<T> from(T t1, T t2, T t3, T t4) {
return from(Arrays.asList(t1, t2, t3, t4));
}
/**
* Converts five items into an Observable that emits those items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
*
* @param t1
* first item
* @param t2
* second item
* @param t3
* third item
* @param t4
* fourth item
* @param t5
* fifth item
* @param <T>
* the type of these items
* @return an Observable that emits each item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
// suppress unchecked because we are using varargs inside the method
@SuppressWarnings("unchecked")
public final static <T> Observable<T> from(T t1, T t2, T t3, T t4, T t5) {
return from(Arrays.asList(t1, t2, t3, t4, t5));
}
/**
* Converts six items into an Observable that emits those items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
*
* @param t1
* first item
* @param t2
* second item
* @param t3
* third item
* @param t4
* fourth item
* @param t5
* fifth item
* @param t6
* sixth item
* @param <T>
* the type of these items
* @return an Observable that emits each item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
// suppress unchecked because we are using varargs inside the method
@SuppressWarnings("unchecked")
public final static <T> Observable<T> from(T t1, T t2, T t3, T t4, T t5, T t6) {
return from(Arrays.asList(t1, t2, t3, t4, t5, t6));
}
/**
* Converts seven items into an Observable that emits those items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
*
* @param t1
* first item
* @param t2
* second item
* @param t3
* third item
* @param t4
* fourth item
* @param t5
* fifth item
* @param t6
* sixth item
* @param t7
* seventh item
* @param <T>
* the type of these items
* @return an Observable that emits each item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
// suppress unchecked because we are using varargs inside the method
@SuppressWarnings("unchecked")
public final static <T> Observable<T> from(T t1, T t2, T t3, T t4, T t5, T t6, T t7) {
return from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7));
}
/**
* Converts eight items into an Observable that emits those items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
*
* @param t1
* first item
* @param t2
* second item
* @param t3
* third item
* @param t4
* fourth item
* @param t5
* fifth item
* @param t6
* sixth item
* @param t7
* seventh item
* @param t8
* eighth item
* @param <T>
* the type of these items
* @return an Observable that emits each item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
// suppress unchecked because we are using varargs inside the method
@SuppressWarnings("unchecked")
public final static <T> Observable<T> from(T t1, T t2, T t3, T t4, T t5, T t6, T t7, T t8) {
return from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7, t8));
}
/**
* Converts nine items into an Observable that emits those items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
*
* @param t1
* first item
* @param t2
* second item
* @param t3
* third item
* @param t4
* fourth item
* @param t5
* fifth item
* @param t6
* sixth item
* @param t7
* seventh item
* @param t8
* eighth item
* @param t9
* ninth item
* @param <T>
* the type of these items
* @return an Observable that emits each item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
// suppress unchecked because we are using varargs inside the method
@SuppressWarnings("unchecked")
public final static <T> Observable<T> from(T t1, T t2, T t3, T t4, T t5, T t6, T t7, T t8, T t9) {
return from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7, t8, t9));
}
/**
* Converts ten items into an Observable that emits those items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
* <p>
*
* @param t1
* first item
* @param t2
* second item
* @param t3
* third item
* @param t4
* fourth item
* @param t5
* fifth item
* @param t6
* sixth item
* @param t7
* seventh item
* @param t8
* eighth item
* @param t9
* ninth item
* @param t10
* tenth item
* @param <T>
* the type of these items
* @return an Observable that emits each item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
// suppress unchecked because we are using varargs inside the method
@SuppressWarnings("unchecked")
public final static <T> Observable<T> from(T t1, T t2, T t3, T t4, T t5, T t6, T t7, T t8, T t9, T t10) {
return from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10));
}
/**
* Converts an Array into an Observable that emits the items in the Array.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
*
* @param t1
* the source Array
* @param <T>
* the type of items in the Array and the type of items to be emitted by the resulting Observable
* @return an Observable that emits each item in the source Array
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
public final static <T> Observable<T> from(T... t1) {
return from(Arrays.asList(t1));
}
/**
* Converts an Array into an Observable that emits the items in the Array on a specified Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png">
*
* @param items
* the source Array
* @param scheduler
* the Scheduler on which the Observable emits the items of the Array
* @param <T>
* the type of items in the Array and the type of items to be emitted by the resulting Observable
* @return an Observable that emits each item in the source Array
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
*/
public final static <T> Observable<T> from(T[] items, Scheduler scheduler) {
return from(Arrays.asList(items), scheduler);
}
/**
* Returns an Observable that emits a sequential number every specified interval of time.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/interval.png">
*
* @param interval
* interval size in time units (see below)
* @param unit
* time units to use for the interval size
* @return an Observable that emits a sequential number each time interval
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-interval">RxJava Wiki: interval()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229027.aspx">MSDN: Observable.Interval</a>
*/
public final static Observable<Long> interval(long interval, TimeUnit unit) {
return create(new OperatorTimerPeriodically(interval, interval, unit, Schedulers.computation()));
}
/**
* Returns an Observable that emits a sequential number every specified interval of time, on a
* specified Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/interval.s.png">
*
* @param interval
* interval size in time units (see below)
* @param unit
* time units to use for the interval size
* @param scheduler
* the Scheduler to use for scheduling the items
* @return an Observable that emits a sequential number each time interval
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-interval">RxJava Wiki: interval()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh228911.aspx">MSDN: Observable.Interval</a>
*/
public final static Observable<Long> interval(long interval, TimeUnit unit, Scheduler scheduler) {
return create(new OperatorTimerPeriodically(interval, interval, unit, scheduler));
}
/**
* Returns an Observable that emits a single item and then completes.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/just.png">
* <p>
* To convert any object into an Observable that emits that object, pass that object into the {@code just} method.
* <p>
* This is similar to the {@link #from(java.lang.Object[])} method, except that {@code from()} will convert
* an {@link Iterable} object into an Observable that emits each of the items in the Iterable, one at a
* time, while the {@code just()} method converts an Iterable into an Observable that emits the entire
* Iterable as a single item.
*
* @param value
* the item to emit
* @param <T>
* the type of that item
* @return an Observable that emits {@code value} as a single item and then completes
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-just">RxJava Wiki: just()</a>
*/
public final static <T> Observable<T> just(final T value) {
return Observable.create(new OnSubscribe<T>() {
@Override
public void call(Subscriber<? super T> s) {
if (!s.isUnsubscribed()) {
s.onNext(value);
s.onCompleted();
}
}
});
}
/**
* Returns an Observable that emits a single item and then completes, on a specified Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/just.s.png">
* <p>
* This is a scheduler version of {@link #just(Object)}.
*
* @param value
* the item to emit
* @param <T>
* the type of that item
* @param scheduler
* the Scheduler to emit the single item on
* @return an Observable that emits {@code value} as a single item and then completes, on a specified
* Scheduler
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-just">RxJava Wiki: just()</a>
*/
public final static <T> Observable<T> just(T value, Scheduler scheduler) {
return just(value).subscribeOn(scheduler);
}
/**
* Flattens an Iterable of Observables into one Observable, without any transformation.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png">
* <p>
* You can combine the items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param sequences
* the Iterable of Observables
* @return an Observable that emits items that are the result of flattening the items emitted by the
* Observables in the Iterable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229590.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> merge(Iterable<? extends Observable<? extends T>> sequences) {
return merge(from(sequences));
}
/**
* Flattens an Iterable of Observables into one Observable, without any transformation, while limiting the
* number of concurrent subscriptions to these Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png">
* <p>
* You can combine the items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param sequences
* the Iterable of Observables
* @param maxConcurrent
* the maximum number of Observables that may be subscribed to concurrently
* @return an Observable that emits items that are the result of flattening the items emitted by the
* Observables in the Iterable
* @throws IllegalArgumentException
* if {@code maxConcurrent} is less than or equal to 0
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229923.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> merge(Iterable<? extends Observable<? extends T>> sequences, int maxConcurrent) {
return merge(from(sequences), maxConcurrent);
}
/**
* Flattens an Iterable of Observables into one Observable, without any transformation, while limiting the
* number of concurrent subscriptions to these Observables, and subscribing to these Observables on a
* specified Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png">
* <p>
* You can combine the items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param sequences
* the Iterable of Observables
* @param maxConcurrent
* the maximum number of Observables that may be subscribed to concurrently
* @param scheduler
* the Scheduler on which to traverse the Iterable of Observables
* @return an Observable that emits items that are the result of flattening the items emitted by the
* Observables in the Iterable
* @throws IllegalArgumentException
* if {@code maxConcurrent} is less than or equal to 0
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh244329.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> merge(Iterable<? extends Observable<? extends T>> sequences, int maxConcurrent, Scheduler scheduler) {
return merge(from(sequences, scheduler), maxConcurrent);
}
/**
* Flattens an Iterable of Observables into one Observable, without any transformation, subscribing to these
* Observables on a specified Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png">
* <p>
* You can combine the items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param sequences
* the Iterable of Observables
* @param scheduler
* the Scheduler on which to traverse the Iterable of Observables
* @return an Observable that emits items that are the result of flattening the items emitted by the
* Observables in the Iterable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh244336.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> merge(Iterable<? extends Observable<? extends T>> sequences, Scheduler scheduler) {
return merge(from(sequences, scheduler));
}
/**
* Flattens an Observable that emits Observables into a single Observable that emits the items emitted by
* those Observables, without any transformation.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.oo.png">
* <p>
* You can combine the items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param source
* an Observable that emits Observables
* @return an Observable that emits items that are the result of flattening the Observables emitted by the {@code source} Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> merge(Observable<? extends Observable<? extends T>> source) {
return source.lift(new OperatorMerge<T>());
}
/**
* Flattens an Observable that emits Observables into a single Observable that emits the items emitted by
* those Observables, without any transformation, while limiting the maximum number of concurrent
* subscriptions to these Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.oo.png">
* <p>
* You can combine the items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param source
* an Observable that emits Observables
* @param maxConcurrent
* the maximum number of Observables that may be subscribed to concurrently
* @return an Observable that emits items that are the result of flattening the Observables emitted by the {@code source} Observable
* @throws IllegalArgumentException
* if {@code maxConcurrent} is less than or equal to 0
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211914.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> merge(Observable<? extends Observable<? extends T>> source, int maxConcurrent) {
return source.lift(new OperatorMergeMaxConcurrent<T>(maxConcurrent));
}
/**
* Flattens two Observables into a single Observable, without any transformation.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png">
* <p>
* You can combine items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @return an Observable that emits all of the items emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
@SuppressWarnings("unchecked")
public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2) {
return merge(from(Arrays.asList(t1, t2)));
}
/**
* Flattens three Observables into a single Observable, without any transformation.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png">
* <p>
* You can combine items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @return an Observable that emits all of the items emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
@SuppressWarnings("unchecked")
public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3) {
return merge(from(Arrays.asList(t1, t2, t3)));
}
/**
* Flattens four Observables into a single Observable, without any transformation.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png">
* <p>
* You can combine items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @param t4
* an Observable to be merged
* @return an Observable that emits all of the items emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
@SuppressWarnings("unchecked")
public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4) {
return merge(from(Arrays.asList(t1, t2, t3, t4)));
}
/**
* Flattens five Observables into a single Observable, without any transformation.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png">
* <p>
* You can combine items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @param t4
* an Observable to be merged
* @param t5
* an Observable to be merged
* @return an Observable that emits all of the items emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
@SuppressWarnings("unchecked")
public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5) {
return merge(from(Arrays.asList(t1, t2, t3, t4, t5)));
}
/**
* Flattens six Observables into a single Observable, without any transformation.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png">
* <p>
* You can combine items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @param t4
* an Observable to be merged
* @param t5
* an Observable to be merged
* @param t6
* an Observable to be merged
* @return an Observable that emits all of the items emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
@SuppressWarnings("unchecked")
public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6) {
return merge(from(Arrays.asList(t1, t2, t3, t4, t5, t6)));
}
/**
* Flattens seven Observables into a single Observable, without any transformation.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png">
* <p>
* You can combine items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @param t4
* an Observable to be merged
* @param t5
* an Observable to be merged
* @param t6
* an Observable to be merged
* @param t7
* an Observable to be merged
* @return an Observable that emits all of the items emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
@SuppressWarnings("unchecked")
public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7) {
return merge(from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7)));
}
/**
* Flattens eight Observables into a single Observable, without any transformation.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png">
* <p>
* You can combine items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @param t4
* an Observable to be merged
* @param t5
* an Observable to be merged
* @param t6
* an Observable to be merged
* @param t7
* an Observable to be merged
* @param t8
* an Observable to be merged
* @return an Observable that emits items that are the result of flattening
* the items emitted by the {@code source} Observables
* @return an Observable that emits all of the items emitted by the source Observables
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
@SuppressWarnings("unchecked")
public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7, Observable<? extends T> t8) {
return merge(from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7, t8)));
}
/**
* Flattens nine Observables into a single Observable, without any transformation.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png">
* <p>
* You can combine items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @param t4
* an Observable to be merged
* @param t5
* an Observable to be merged
* @param t6
* an Observable to be merged
* @param t7
* an Observable to be merged
* @param t8
* an Observable to be merged
* @param t9
* an Observable to be merged
* @return an Observable that emits all of the items emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
@SuppressWarnings("unchecked")
public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7, Observable<? extends T> t8, Observable<? extends T> t9) {
return merge(from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7, t8, t9)));
}
/**
* Flattens an Array of Observables into one Observable, without any transformation.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.io.png">
* <p>
* You can combine items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param sequences
* the Array of Observables
* @return an Observable that emits all of the items emitted by the Observables in the Array
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> merge(Observable<? extends T>[] sequences) {
return merge(from(sequences));
}
/**
* Flattens an Array of Observables into one Observable, without any transformation, traversing the array on
* a specified Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.ios.png">
* <p>
* You can combine items emitted by multiple Observables so that they appear as a single Observable, by
* using the {@code merge} method.
*
* @param sequences
* the Array of Observables
* @param scheduler
* the Scheduler on which to traverse the Array
* @return an Observable that emits all of the items emitted by the Observables in the Array
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-merge">RxJava Wiki: merge()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229061.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> merge(Observable<? extends T>[] sequences, Scheduler scheduler) {
return merge(from(sequences, scheduler));
}
/**
* A version of merge that allows an Observer to receive all successfully emitted items from all of the
* source Observables without being interrupted by an error notification from one of them.
* <p>
* This behaves like {@link #merge(Observable)} except that if any of the merged Observables notify of an
* error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from propagating that
* error notification until all of the merged Observables have finished emitting items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png">
* <p>
* Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Observers once.
*
* @param source
* an Observable that emits Observables
* @return an Observable that emits all of the items emitted by the Observables emitted by the {@code source} Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-mergedelayerror">RxJava Wiki: mergeDelayError()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> mergeDelayError(Observable<? extends Observable<? extends T>> source) {
return source.lift(new OperatorMergeDelayError<T>());
}
/**
* A version of merge that allows an Observer to receive all successfully emitted items from all of the
* source Observables without being interrupted by an error notification from one of them.
* <p>
* This behaves like {@link #merge(Observable, Observable)} except that if any of the merged Observables
* notify of an error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from
* propagating that error notification until all of the merged Observables have finished emitting items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png">
* <p>
* Even if both merged Observables send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Observers once.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @return an Observable that emits all of the items that are emitted by the two source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-mergedelayerror">RxJava Wiki: mergeDelayError()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2) {
return mergeDelayError(from(t1, t2));
}
/**
* A version of merge that allows an Observer to receive all successfully emitted items from all of the
* source Observables without being interrupted by an error notification from one of them.
* <p>
* This behaves like {@link #merge(Observable, Observable, Observable)} except that if any of the merged
* Observables notify of an error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain
* from propagating that error notification until all of the merged Observables have finished emitting
* items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png">
* <p>
* Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Observers once.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @return an Observable that emits all of the items that are emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-mergedelayerror">RxJava Wiki: mergeDelayError()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3) {
return mergeDelayError(from(t1, t2, t3));
}
/**
* A version of merge that allows an Observer to receive all successfully emitted items from all of the
* source Observables without being interrupted by an error notification from one of them.
* <p>
* This behaves like {@link #merge(Observable, Observable, Observable, Observable)} except that if any of
* the merged Observables notify of an error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from propagating that error notification until all of the merged Observables
* have finished
* emitting items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png">
* <p>
* Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Observers once.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @param t4
* an Observable to be merged
* @return an Observable that emits all of the items that are emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-mergedelayerror">RxJava Wiki: mergeDelayError()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4) {
return mergeDelayError(from(t1, t2, t3, t4));
}
/**
* A version of merge that allows an Observer to receive all successfully emitted items from all of the
* source Observables without being interrupted by an error notification from one of them.
* <p>
* This behaves like {@link #merge(Observable, Observable, Observable, Observable, Observable)} except that
* if any of the merged Observables notify of an error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from propagating that error notification until all of the merged
* Observables have finished emitting items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png">
* <p>
* Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Observers once.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @param t4
* an Observable to be merged
* @param t5
* an Observable to be merged
* @return an Observable that emits all of the items that are emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-mergedelayerror">RxJava Wiki: mergeDelayError()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5) {
return mergeDelayError(from(t1, t2, t3, t4, t5));
}
/**
* A version of merge that allows an Observer to receive all successfully emitted items from all of the
* source Observables without being interrupted by an error notification from one of them.
* <p>
* This behaves like {@link #merge(Observable, Observable, Observable, Observable, Observable, Observable)} except that if any of the merged Observables notify of an error via
* {@link Observer#onError onError}, {@code mergeDelayError} will refrain from propagating that error notification until all of the merged
* Observables have finished emitting items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png">
* <p>
* Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Observers once.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @param t4
* an Observable to be merged
* @param t5
* an Observable to be merged
* @param t6
* an Observable to be merged
* @return an Observable that emits all of the items that are emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-mergedelayerror">RxJava Wiki: mergeDelayError()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6) {
return mergeDelayError(from(t1, t2, t3, t4, t5, t6));
}
/**
* A version of merge that allows an Observer to receive all successfully emitted items from all of the
* source Observables without being interrupted by an error notification from one of them.
* <p>
* This behaves like {@link #merge(Observable, Observable, Observable, Observable, Observable, Observable, Observable)} except that if any of the merged Observables notify of an error via
* {@link Observer#onError onError}, {@code mergeDelayError} will refrain from propagating that error notification until all of the merged
* Observables have finished emitting items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png">
* <p>
* Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Observers once.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @param t4
* an Observable to be merged
* @param t5
* an Observable to be merged
* @param t6
* an Observable to be merged
* @param t7
* an Observable to be merged
* @return an Observable that emits all of the items that are emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-mergedelayerror">RxJava Wiki: mergeDelayError()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7) {
return mergeDelayError(from(t1, t2, t3, t4, t5, t6, t7));
}
/**
* A version of merge that allows an Observer to receive all successfully emitted items from all of the
* source Observables without being interrupted by an error notification from one of them.
* <p>
* This behaves like {@link #merge(Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable)} except that if any of the merged Observables notify of an error
* via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from propagating that error notification until all of the merged
* Observables have finished emitting items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png">
* <p>
* Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Observers once.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @param t4
* an Observable to be merged
* @param t5
* an Observable to be merged
* @param t6
* an Observable to be merged
* @param t7
* an Observable to be merged
* @param t8
* an Observable to be merged
* @return an Observable that emits all of the items that are emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-mergedelayerror">RxJava Wiki: mergeDelayError()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
// suppress because the types are checked by the method signature before using a vararg
public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7, Observable<? extends T> t8) {
return mergeDelayError(from(t1, t2, t3, t4, t5, t6, t7, t8));
}
/**
* A version of merge that allows an Observer to receive all successfully emitted items from all of the
* source Observables without being interrupted by an error notification from one of them.
* <p>
* This behaves like {@link #merge(Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable)} except that if any of the merged Observables notify
* of an error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from propagating that error notification until all of the merged
* Observables have finished emitting items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png">
* <p>
* Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Observers once.
*
* @param t1
* an Observable to be merged
* @param t2
* an Observable to be merged
* @param t3
* an Observable to be merged
* @param t4
* an Observable to be merged
* @param t5
* an Observable to be merged
* @param t6
* an Observable to be merged
* @param t7
* an Observable to be merged
* @param t8
* an Observable to be merged
* @param t9
* an Observable to be merged
* @return an Observable that emits all of the items that are emitted by the source Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-mergedelayerror">RxJava Wiki: mergeDelayError()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
*/
public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7, Observable<? extends T> t8, Observable<? extends T> t9) {
return mergeDelayError(from(t1, t2, t3, t4, t5, t6, t7, t8, t9));
}
/**
* Convert the current {@code Observable<T>} into an {@code Observable<Observable<T>>}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/nest.png">
*
* @return an Observable that emits a single item: the source Observable
* @since 0.17
*/
public final Observable<Observable<T>> nest() {
return just(this);
}
/**
* Returns an Observable that never sends any items or notifications to an {@link Observer}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/never.png">
* <p>
* This Observable is useful primarily for testing purposes.
*
* @param <T>
* the type of items (not) emitted by the Observable
* @return an Observable that never emits any items or sends any notifications to an {@link Observer}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-empty-error-and-never">RxJava Wiki: never()</a>
*/
public final static <T> Observable<T> never() {
return new NeverObservable<T>();
}
/**
* Converts an {@code Observable<Observable<T>>} into another {@code Observable<Observable<T>>} whose
* emitted Observables emit the same items, but the number of such Observables is restricted by {@code parallelObservables}.
* <p>
* For example, if the original {@code Observable<Observable<T>>} emits 100 Observables and {@code parallelObservables} is 8, the items emitted by the 100 original Observables will be distributed
* among 8 Observables emitted by the resulting Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/parallelMerge.png">
* <p>
* This is a mechanism for efficiently processing <i>n</i> number of Observables on a smaller <i>m</i>
* number of resources (typically CPU cores).
*
* @param parallelObservables
* the number of Observables to merge into
* @return an Observable of Observables constrained in number by {@code parallelObservables}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-parallelmerge">RxJava Wiki: parallelMerge()</a>
*/
public final static <T> Observable<Observable<T>> parallelMerge(Observable<Observable<T>> source, int parallelObservables) {
return OperatorParallelMerge.parallelMerge(source, parallelObservables);
}
/**
* Converts an {@code Observable<Observable<T>>} into another {@code Observable<Observable<T>>} whose
* emitted Observables emit the same items, but the number of such Observables is restricted by {@code parallelObservables}, and each runs on a defined Scheduler.
* <p>
* For example, if the original {@code Observable<Observable<T>>} emits 100 Observables and {@code parallelObservables} is 8, the items emitted by the 100 original Observables will be distributed
* among 8 Observables emitted by the resulting Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/parallelMerge.png">
* <p>
* This is a mechanism for efficiently processing <i>n</i> number of Observables on a smaller <i>m</i>
* number of resources (typically CPU cores).
*
* @param parallelObservables
* the number of Observables to merge into
* @param scheduler
* the {@link Scheduler} to run each Observable on
* @return an Observable of Observables constrained in number by {@code parallelObservables}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-parallelmerge">RxJava Wiki: parallelMerge()</a>
*/
public final static <T> Observable<Observable<T>> parallelMerge(Observable<Observable<T>> source, int parallelObservables, Scheduler scheduler) {
return OperatorParallelMerge.parallelMerge(source, parallelObservables, scheduler);
}
/**
* Pivot GroupedObservable streams without serializing/synchronizing to a single stream first.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/pivot.png">
*
* For example an Observable such as this =>
*
* {@code Observable<GroupedObservable<String, GroupedObservable<Boolean, Integer>>>}:
* <ul>
* <li>o1.odd: 1, 3, 5, 7, 9 on Thread 1</li>
* <li>o1.even: 2, 4, 6, 8, 10 on Thread 1</li>
* <li>o2.odd: 11, 13, 15, 17, 19 on Thread 2</li>
* <li>o2.even: 12, 14, 16, 18, 20 on Thread 2</li>
* </ul>
* is pivoted to become this =>
*
* {@code Observable<GroupedObservable<Boolean, GroupedObservable<String, Integer>>>}:
* <ul>
* <li>odd.o1: 1, 3, 5, 7, 9 on Thread 1</li>
* <li>odd.o2: 11, 13, 15, 17, 19 on Thread 2</li>
* <li>even.o1: 2, 4, 6, 8, 10 on Thread 1</li>
* <li>even.o2: 12, 14, 16, 18, 20 on Thread 2</li>
* </ul>
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/pivot.ex.png">
*
* @param groups
* @return an Observable containing a stream of nested GroupedObservables with swapped inner-outer keys.
* @since 0.17
*/
public static final <K1, K2, T> Observable<GroupedObservable<K2, GroupedObservable<K1, T>>> pivot(Observable<GroupedObservable<K1, GroupedObservable<K2, T>>> groups) {
return groups.lift(new OperatorPivot<K1, K2, T>());
}
/**
* Returns an Observable that emits a sequence of Integers within a specified range.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/range.png">
*
* @param start
* the value of the first Integer in the sequence
* @param count
* the number of sequential Integers to generate
* @return an Observable that emits a range of sequential Integers
* @throws IllegalArgumentException
* if {@code count} is less than zero
* @throws IllegalArgumentException
* if {@code start} + {@code count} exceeds {@code Integer.MAX_VALUE}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-range">RxJava Wiki: range()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229460.aspx">MSDN: Observable.Range</a>
*/
public final static Observable<Integer> range(int start, int count) {
if (count < 0) {
throw new IllegalArgumentException("Count can not be negative");
}
if ((start + count) > Integer.MAX_VALUE) {
throw new IllegalArgumentException("start + count can not exceed Integer.MAX_VALUE");
}
return Observable.create(new OnSubscribeRange(start, start + (count - 1)));
}
/**
* Returns an Observable that emits a sequence of Integers within a specified range, on a specified
* Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/range.s.png">
*
* @param start
* the value of the first Integer in the sequence
* @param count
* the number of sequential Integers to generate
* @param scheduler
* the Scheduler to run the generator loop on
* @return an Observable that emits a range of sequential Integers
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-range">RxJava Wiki: range()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211896.aspx">MSDN: Observable.Range</a>
*/
public final static Observable<Integer> range(int start, int count, Scheduler scheduler) {
return range(start, count).subscribeOn(scheduler);
}
/**
* Returns an Observable that emits a Boolean value that indicates whether two Observable sequences are the
* same by comparing the items emitted by each Observable pairwise.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/sequenceEqual.png">
*
* @param first
* the first Observable to compare
* @param second
* the second Observable to compare
* @param <T>
* the type of items emitted by each Observable
* @return an Observable that emits a Boolean value that indicates whether the two sequences are the same
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-sequenceequal">RxJava Wiki: sequenceEqual()</a>
*/
public final static <T> Observable<Boolean> sequenceEqual(Observable<? extends T> first, Observable<? extends T> second) {
return sequenceEqual(first, second, new Func2<T, T, Boolean>() {
@Override
public final Boolean call(T first, T second) {
if (first == null) {
return second == null;
}
return first.equals(second);
}
});
}
/**
* Returns an Observable that emits a Boolean value that indicates whether two Observable sequences are the
* same by comparing the items emitted by each Observable pairwise based on the results of a specified
* equality function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/sequenceEqual.png">
*
* @param first
* the first Observable to compare
* @param second
* the second Observable to compare
* @param equality
* a function used to compare items emitted by each Observable
* @param <T>
* the type of items emitted by each Observable
* @return an Observable that emits a Boolean value that indicates whether the two Observable two sequences
* are the same according to the specified function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-sequenceequal">RxJava Wiki: sequenceEqual()</a>
*/
public final static <T> Observable<Boolean> sequenceEqual(Observable<? extends T> first, Observable<? extends T> second, Func2<? super T, ? super T, Boolean> equality) {
return OperatorSequenceEqual.sequenceEqual(first, second, equality);
}
/**
* Given an Observable that emits Observables, returns an Observable that emits the items emitted by the
* most recently emitted of those Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/switchDo.png">
* <p> {@code switchOnNext()} subscribes to an Observable that emits Observables. Each time it observes one of
* these emitted Observables, the Observable returned by {@code switchOnNext()} begins emitting the items
* emitted by that Observable. When a new Observable is emitted, {@code switchOnNext()} stops emitting items
* from the earlier-emitted Observable and begins emitting items from the new one.
*
* @param sequenceOfSequences
* the source Observable that emits Observables
* @return an Observable that emits the items emitted by the Observable most recently emitted by the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-switchonnext">RxJava Wiki: switchOnNext()</a>
*
* @param <T> the element type
*/
public final static <T> Observable<T> switchOnNext(Observable<? extends Observable<? extends T>> sequenceOfSequences) {
return sequenceOfSequences.lift(new OperatorSwitch<T>());
}
/**
* Return an Observable that emits a 0L after the {@code initialDelay} and ever increasing numbers after
* each {@code period} of time thereafter.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timer.p.png">
*
* @param initialDelay
* the initial delay time to wait before emitting the first value of 0L
* @param period
* the period of time between emissions of the subsequent numbers
* @param unit
* the time unit for both {@code initialDelay} and {@code period}
* @return an Observable that emits a 0L after the {@code initialDelay} and ever increasing numbers after
* each {@code period} of time thereafter
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-timer">RxJava Wiki: timer()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229435.aspx">MSDN: Observable.Timer</a>
*/
public final static Observable<Long> timer(long initialDelay, long period, TimeUnit unit) {
return timer(initialDelay, period, unit, Schedulers.computation());
}
/**
* Return an Observable that emits a 0L after the {@code initialDelay} and ever increasing numbers after
* each {@code period} of time thereafter, on a specified Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timer.ps.png">
*
* @param initialDelay
* the initial delay time to wait before emitting the first value of 0L
* @param period
* the period of time between emissions of the subsequent numbers
* @param unit
* the time unit for both {@code initialDelay} and {@code period}
* @param scheduler
* the Scheduler on which the waiting happens and items are emitted
* @return an Observable that emits a 0L after the {@code initialDelay} and ever increasing numbers after
* each {@code period} of time thereafter, while running on the given Scheduler
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-timer">RxJava Wiki: timer()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229652.aspx">MSDN: Observable.Timer</a>
*/
public final static Observable<Long> timer(long initialDelay, long period, TimeUnit unit, Scheduler scheduler) {
return create(new OperatorTimerPeriodically(initialDelay, period, unit, scheduler));
}
/**
* Returns an Observable that emits one item after a specified delay, and then completes.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timer.png">
*
* @param delay
* the initial delay before emitting a single 0L
* @param unit
* time units to use for {@code delay}
* @return an Observable that emits one item after a specified delay, and then completes
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-timer">RxJava wiki: timer()</a>
*/
public final static Observable<Long> timer(long delay, TimeUnit unit) {
return timer(delay, unit, Schedulers.computation());
}
/**
* Returns an Observable that emits one item after a specified delay, on a specified Scheduler, and then
* completes.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timer.s.png">
*
* @param delay
* the initial delay before emitting a single 0L
* @param unit
* time units to use for {@code delay}
* @param scheduler
* the Scheduler to use for scheduling the item
* @return Observable that emits one item after a specified delay, on a specified Scheduler, and then
* completes
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-timer">RxJava wiki: timer()</a>
*/
public final static Observable<Long> timer(long delay, TimeUnit unit, Scheduler scheduler) {
return create(new OperatorTimerOnce(delay, unit, scheduler));
}
/**
* Constructs an Observable that creates a dependent resource object.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/using.png">
*
* @param resourceFactory
* the factory function to create a resource object that depends on the Observable
* @param observableFactory
* the factory function to obtain an Observable
* @return the Observable whose lifetime controls the lifetime of the dependent resource object
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-using">RxJava Wiki: using()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229585.aspx">MSDN: Observable.Using</a>
*/
public final static <T, Resource extends Subscription> Observable<T> using(Func0<Resource> resourceFactory, Func1<Resource, ? extends Observable<? extends T>> observableFactory) {
return create(new OperatorUsing<T, Resource>(resourceFactory, observableFactory));
}
/**
* Returns an Observable that emits the results of a function of your choosing applied to combinations of
* items emitted, in sequence, by an Iterable of other Observables.
* <p> {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable
* will be the result of the function applied to the first item emitted by each of the source Observables;
* the second item emitted by the new Observable will be the result of the function applied to the second
* item emitted by each of those Observables; and so forth.
* <p>
* The resulting {@code Observable<R>} returned from {@code zip} will invoke {@code onNext} as many times as
* the number of {@code onNext} invokations of the source Observable that emits the fewest items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png">
*
* @param ws
* an Iterable of source Observables
* @param zipFunction
* a function that, when applied to an item emitted by each of the source Observables, results in
* an item that will be emitted by the resulting Observable
* @return an Observable that emits the zipped results
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-zip">RxJava Wiki: zip()</a>
*/
public final static <R> Observable<R> zip(Iterable<? extends Observable<?>> ws, FuncN<? extends R> zipFunction) {
List<Observable<?>> os = new ArrayList<Observable<?>>();
for (Observable<?> o : ws) {
os.add(o);
}
return Observable.just(os.toArray(new Observable<?>[os.size()])).lift(new OperatorZip<R>(zipFunction));
}
/**
* Returns an Observable that emits the results of a function of your choosing applied to combinations of
* <i>n</i> items emitted, in sequence, by the <i>n</i> Observables emitted by a specified Observable.
* <p> {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable
* will be the result of the function applied to the first item emitted by each of the Observables emitted
* by the source Observable; the second item emitted by the new Observable will be the result of the
* function applied to the second item emitted by each of those Observables; and so forth.
* <p>
* The resulting {@code Observable<R>} returned from {@code zip} will invoke {@code onNext} as many times as
* the number of {@code onNext} invokations of the source Observable that emits the fewest items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.o.png">
*
* @param ws
* an Observable of source Observables
* @param zipFunction
* a function that, when applied to an item emitted by each of the Observables emitted by {@code ws}, results in an item that will be emitted by the resulting Observable
* @return an Observable that emits the zipped results
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-zip">RxJava Wiki: zip()</a>
*/
public final static <R> Observable<R> zip(Observable<? extends Observable<?>> ws, final FuncN<? extends R> zipFunction) {
return ws.toList().map(new Func1<List<? extends Observable<?>>, Observable<?>[]>() {
@Override
public Observable<?>[] call(List<? extends Observable<?>> o) {
return o.toArray(new Observable<?>[o.size()]);
}
}).lift(new OperatorZip<R>(zipFunction));
}
/**
* Returns an Observable that emits the results of a function of your choosing applied to combinations of
* two items emitted, in sequence, by two other Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png">
* <p> {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable
* will be the result of the function applied to the first item emitted by {@code o1} and the first item
* emitted by {@code o2}; the second item emitted by the new Observable will be the result of the function
* applied to the second item emitted by {@code o1} and the second item emitted by {@code o2}; and so forth.
* <p>
* The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} as many times as the number of {@code onNext} invocations of the source Observable that
* emits the fewest
* items.
*
* @param o1
* the first source Observable
* @param o2
* a second source Observable
* @param zipFunction
* a function that, when applied to an item emitted by each of the source Observables, results
* in an item that will be emitted by the resulting Observable
* @return an Observable that emits the zipped results
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-zip">RxJava Wiki: zip()</a>
*/
public final static <T1, T2, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, final Func2<? super T1, ? super T2, ? extends R> zipFunction) {
return just(new Observable<?>[] { o1, o2 }).lift(new OperatorZip<R>(zipFunction));
}
/**
* Returns an Observable that emits the results of a function of your choosing applied to combinations of
* three items emitted, in sequence, by three other Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png">
* <p> {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable
* will be the result of the function applied to the first item emitted by {@code o1}, the first item
* emitted by {@code o2}, and the first item emitted by {@code o3}; the second item emitted by the new
* Observable will be the result of the function applied to the second item emitted by {@code o1}, the
* second item emitted by {@code o2}, and the second item emitted by {@code o3}; and so forth.
* <p>
* The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} as many times as the number of {@code onNext} invocations of the source Observable that
* emits the fewest
* items.
*
* @param o1
* the first source Observable
* @param o2
* a second source Observable
* @param o3
* a third source Observable
* @param zipFunction
* a function that, when applied to an item emitted by each of the source Observables, results in
* an item that will be emitted by the resulting Observable
* @return an Observable that emits the zipped results
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-zip">RxJava Wiki: zip()</a>
*/
public final static <T1, T2, T3, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Func3<? super T1, ? super T2, ? super T3, ? extends R> zipFunction) {
return just(new Observable<?>[] { o1, o2, o3 }).lift(new OperatorZip<R>(zipFunction));
}
/**
* Returns an Observable that emits the results of a function of your choosing applied to combinations of
* four items emitted, in sequence, by four other Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png">
* <p> {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable
* will be the result of the function applied to the first item emitted by {@code o1}, the first item
* emitted by {@code o2}, the first item emitted by {@code o3}, and the first item emitted by {@code 04};
* the second item emitted by the new Observable will be the result of the function applied to the second
* item emitted by each of those Observables; and so forth.
* <p>
* The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} as many times as the number of {@code onNext} invocations of the source Observable that
* emits the fewest
* items.
*
* @param o1
* the first source Observable
* @param o2
* a second source Observable
* @param o3
* a third source Observable
* @param o4
* a fourth source Observable
* @param zipFunction
* a function that, when applied to an item emitted by each of the source Observables, results in
* an item that will be emitted by the resulting Observable
* @return an Observable that emits the zipped results
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-zip">RxJava Wiki: zip()</a>
*/
public final static <T1, T2, T3, T4, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Func4<? super T1, ? super T2, ? super T3, ? super T4, ? extends R> zipFunction) {
return just(new Observable<?>[] { o1, o2, o3, o4 }).lift(new OperatorZip<R>(zipFunction));
}
/**
* Returns an Observable that emits the results of a function of your choosing applied to combinations of
* five items emitted, in sequence, by five other Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png">
* <p> {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable
* will be the result of the function applied to the first item emitted by {@code o1}, the first item
* emitted by {@code o2}, the first item emitted by {@code o3}, the first item emitted by {@code o4}, and
* the first item emitted by {@code o5}; the second item emitted by the new Observable will be the result of
* the function applied to the second item emitted by each of those Observables; and so forth.
* <p>
* The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} as many times as the number of {@code onNext} invocations of the source Observable that
* emits the fewest
* items.
*
* @param o1
* the first source Observable
* @param o2
* a second source Observable
* @param o3
* a third source Observable
* @param o4
* a fourth source Observable
* @param o5
* a fifth source Observable
* @param zipFunction
* a function that, when applied to an item emitted by each of the source Observables, results in
* an item that will be emitted by the resulting Observable
* @return an Observable that emits the zipped results
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-zip">RxJava Wiki: zip()</a>
*/
public final static <T1, T2, T3, T4, T5, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Func5<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? extends R> zipFunction) {
return just(new Observable<?>[] { o1, o2, o3, o4, o5 }).lift(new OperatorZip<R>(zipFunction));
}
/**
* Returns an Observable that emits the results of a function of your choosing applied to combinations of
* six items emitted, in sequence, by six other Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png">
* <p> {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable
* will be the result of the function applied to the first item emitted by each source Observable, the
* second item emitted by the new Observable will be the result of the function applied to the second item
* emitted by each of those Observables, and so forth.
* <p>
* The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} as many times as the number of {@code onNext} invocations of the source Observable that
* emits the fewest
* items.
*
* @param o1
* the first source Observable
* @param o2
* a second source Observable
* @param o3
* a third source Observable
* @param o4
* a fourth source Observable
* @param o5
* a fifth source Observable
* @param o6
* a sixth source Observable
* @param zipFunction
* a function that, when applied to an item emitted by each of the source Observables, results in
* an item that will be emitted by the resulting Observable
* @return an Observable that emits the zipped results
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-zip">RxJava Wiki: zip()</a>
*/
public final static <T1, T2, T3, T4, T5, T6, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6,
Func6<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? extends R> zipFunction) {
return just(new Observable<?>[] { o1, o2, o3, o4, o5, o6 }).lift(new OperatorZip<R>(zipFunction));
}
/**
* Returns an Observable that emits the results of a function of your choosing applied to combinations of
* seven items emitted, in sequence, by seven other Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png">
* <p> {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable
* will be the result of the function applied to the first item emitted by each source Observable, the
* second item emitted by the new Observable will be the result of the function applied to the second item
* emitted by each of those Observables, and so forth.
* <p>
* The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} as many times as the number of {@code onNext} invocations of the source Observable that
* emits the fewest
* items.
*
* @param o1
* the first source Observable
* @param o2
* a second source Observable
* @param o3
* a third source Observable
* @param o4
* a fourth source Observable
* @param o5
* a fifth source Observable
* @param o6
* a sixth source Observable
* @param o7
* a seventh source Observable
* @param zipFunction
* a function that, when applied to an item emitted by each of the source Observables, results in
* an item that will be emitted by the resulting Observable
* @return an Observable that emits the zipped results
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-zip">RxJava Wiki: zip()</a>
*/
public final static <T1, T2, T3, T4, T5, T6, T7, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Observable<? extends T7> o7,
Func7<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? extends R> zipFunction) {
return just(new Observable<?>[] { o1, o2, o3, o4, o5, o6, o7 }).lift(new OperatorZip<R>(zipFunction));
}
/**
* Returns an Observable that emits the results of a function of your choosing applied to combinations of
* eight items emitted, in sequence, by eight other Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png">
* <p> {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable
* will be the result of the function applied to the first item emitted by each source Observable, the
* second item emitted by the new Observable will be the result of the function applied to the second item
* emitted by each of those Observables, and so forth.
* <p>
* The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} as many times as the number of {@code onNext} invocations of the source Observable that
* emits the fewest
* items.
*
* @param o1
* the first source Observable
* @param o2
* a second source Observable
* @param o3
* a third source Observable
* @param o4
* a fourth source Observable
* @param o5
* a fifth source Observable
* @param o6
* a sixth source Observable
* @param o7
* a seventh source Observable
* @param o8
* an eighth source Observable
* @param zipFunction
* a function that, when applied to an item emitted by each of the source Observables, results in
* an item that will be emitted by the resulting Observable
* @return an Observable that emits the zipped results
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-zip">RxJava Wiki: zip()</a>
*/
public final static <T1, T2, T3, T4, T5, T6, T7, T8, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Observable<? extends T7> o7, Observable<? extends T8> o8,
Func8<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? extends R> zipFunction) {
return just(new Observable<?>[] { o1, o2, o3, o4, o5, o6, o7, o8 }).lift(new OperatorZip<R>(zipFunction));
}
/**
* Returns an Observable that emits the results of a function of your choosing applied to combinations of
* nine items emitted, in sequence, by nine other Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png">
* <p> {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable
* will be the result of the function applied to the first item emitted by each source Observable, the
* second item emitted by the new Observable will be the result of the function applied to the second item
* emitted by each of those Observables, and so forth.
* <p>
* The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} as many times as the number of {@code onNext} invocations of the source Observable that
* emits the fewest
* items.
*
* @param o1
* the first source Observable
* @param o2
* a second source Observable
* @param o3
* a third source Observable
* @param o4
* a fourth source Observable
* @param o5
* a fifth source Observable
* @param o6
* a sixth source Observable
* @param o7
* a seventh source Observable
* @param o8
* an eighth source Observable
* @param o9
* a ninth source Observable
* @param zipFunction
* a function that, when applied to an item emitted by each of the source Observables, results in
* an item that will be emitted by the resulting Observable
* @return an Observable that emits the zipped results
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-zip">RxJava Wiki: zip()</a>
*/
public final static <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Observable<? extends T7> o7, Observable<? extends T8> o8,
Observable<? extends T9> o9, Func9<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? super T9, ? extends R> zipFunction) {
return just(new Observable<?>[] { o1, o2, o3, o4, o5, o6, o7, o8, o9 }).lift(new OperatorZip<R>(zipFunction));
}
/**
* Returns an Observable that emits a Boolean that indicates whether all of the items emitted by the source
* Observable satisfy a condition.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/all.png">
*
* @param predicate
* a function that evaluates an item and returns a Boolean
* @return an Observable that emits {@code true} if all items emitted by the source Observable satisfy the
* predicate; otherwise, {@code false}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-all">RxJava Wiki: all()</a>
*/
public final Observable<Boolean> all(Func1<? super T, Boolean> predicate) {
return lift(new OperatorAll<T>(predicate));
}
/**
* Hides the identity of this Observable. Useful for instance when you have an implementation of a subclass
* of Observable but you want to hide the properties and methods of this subclass from whomever you are
* passing the Observable to.
*
* @return an Observable that hides the identity of this Observable
*/
public final Observable<T> asObservable() {
return lift(new OperatorAsObservable<T>());
}
/**
* Returns an Observable that emits buffers of items it collects from the source Observable. The resulting
* Observable emits connected, non-overlapping buffers. It emits the current buffer and replaces it with a
* new buffer when the Observable produced by the specified {@code bufferClosingSelector} emits an item. It
* then uses the {@code bufferClosingSelector} to create a new Observable to observe to indicate the end of
* the next buffer.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer1.png">
*
* @param bufferClosingSelector
* a {@link Func0} that produces an Observable for each buffer created. When this {@code Observable} emits an item, {@code buffer()} emits the associated buffer and replaces it
* with a new one
* @return an Observable that emits a connected, non-overlapping buffer of items from the source Observable
* each time the current Observable created with the {@code bufferClosingSelector} argument emits an
* item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-buffer">RxJava Wiki: buffer()</a>
*/
public final <TClosing> Observable<List<T>> buffer(Func0<? extends Observable<? extends TClosing>> bufferClosingSelector) {
return lift(new OperatorBufferWithSingleObservable<T, TClosing>(bufferClosingSelector, 16));
}
/**
* Returns an Observable that emits buffers of items it collects from the source Observable. The resulting
* Observable emits connected, non-overlapping buffers, each containing {@code count} items. When the source
* Observable completes or encounters an error, the resulting Observable emits the current buffer and
* propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer3.png">
*
* @param count
* the maximum number of items in each buffer before it should be emitted
* @return an Observable that emits connected, non-overlapping buffers, each containing at most {@code count} items from the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-buffer">RxJava Wiki: buffer()</a>
*/
public final Observable<List<T>> buffer(int count) {
return lift(new OperatorBufferWithSize<T>(count, count));
}
/**
* Returns an Observable that emits buffers of items it collects from the source Observable. The resulting
* Observable emits buffers every {@code skip} items, each containing {@code count} items. When the source
* Observable completes or encounters an error, the resulting Observable emits the current buffer and
* propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer4.png">
*
* @param count
* the maximum size of each buffer before it should be emitted
* @param skip
* how many items emitted by the source Observable should be skipped before starting a new
* buffer. Note that when {@code skip} and {@code count} are equal, this is the same operation as {@link #buffer(int)}.
* @return an Observable that emits buffers for every {@code skip} item from the source Observable and
* containing at most {@code count} items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-buffer">RxJava Wiki: buffer()</a>
*/
public final Observable<List<T>> buffer(int count, int skip) {
return lift(new OperatorBufferWithSize<T>(count, skip));
}
/**
* Returns an Observable that emits buffers of items it collects from the source Observable. The resulting
* Observable starts a new buffer periodically, as determined by the {@code timeshift} argument. It emits
* each buffer after a fixed timespan, specified by the {@code timespan} argument. When the source
* Observable completes or encounters an error, the resulting Observable emits the current buffer and
* propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer7.png">
*
* @param timespan
* the period of time each buffer collects items before it is emitted
* @param timeshift
* the period of time after which a new buffer will be created
* @param unit
* the unit of time that applies to the {@code timespan} and {@code timeshift} arguments
* @return an Observable that emits new buffers of items emitted by the source Observable periodically after
* a fixed timespan has elapsed
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-buffer">RxJava Wiki: buffer()</a>
*/
public final Observable<List<T>> buffer(long timespan, long timeshift, TimeUnit unit) {
return lift(new OperatorBufferWithTime<T>(timespan, timeshift, unit, Integer.MAX_VALUE, Schedulers.computation()));
}
/**
* Returns an Observable that emits buffers of items it collects from the source Observable. The resulting
* Observable starts a new buffer periodically, as determined by the {@code timeshift} argument, and on the
* specified {@code scheduler}. It emits each buffer after a fixed timespan, specified by the {@code timespan} argument. When the source Observable completes or encounters an error, the resulting
* Observable emits the current buffer and propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer7.s.png">
*
* @param timespan
* the period of time each buffer collects items before it is emitted
* @param timeshift
* the period of time after which a new buffer will be created
* @param unit
* the unit of time that applies to the {@code timespan} and {@code timeshift} arguments
* @param scheduler
* the {@link Scheduler} to use when determining the end and start of a buffer
* @return an Observable that emits new buffers of items emitted by the source Observable periodically after
* a fixed timespan has elapsed
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-buffer">RxJava Wiki: buffer()</a>
*/
public final Observable<List<T>> buffer(long timespan, long timeshift, TimeUnit unit, Scheduler scheduler) {
return lift(new OperatorBufferWithTime<T>(timespan, timeshift, unit, Integer.MAX_VALUE, scheduler));
}
/**
* Returns an Observable that emits buffers of items it collects from the source Observable. The resulting
* Observable emits connected, non-overlapping buffers, each of a fixed duration specified by the {@code timespan} argument. When the source Observable completes or encounters an error, the
* resulting
* Observable emits the current buffer and propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer5.png">
*
* @param timespan
* the period of time each buffer collects items before it is emitted and replaced with a new
* buffer
* @param unit
* the unit of time that applies to the {@code timespan} argument
* @return an Observable that emits connected, non-overlapping buffers of items emitted by the source
* Observable within a fixed duration
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-buffer">RxJava Wiki: buffer()</a>
*/
public final Observable<List<T>> buffer(long timespan, TimeUnit unit) {
return lift(new OperatorBufferWithTime<T>(timespan, timespan, unit, Integer.MAX_VALUE, Schedulers.computation()));
}
/**
* Returns an Observable that emits buffers of items it collects from the source Observable. The resulting
* Observable emits connected, non-overlapping buffers, each of a fixed duration specified by the {@code timespan} argument or a maximum size specified by the {@code count} argument (whichever is
* reached
* first). When the source Observable completes or encounters an error, the resulting Observable emits the
* current buffer and propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer6.png">
*
* @param timespan
* the period of time each buffer collects items before it is emitted and replaced with a new
* buffer
* @param unit
* the unit of time which applies to the {@code timespan} argument
* @param count
* the maximum size of each buffer before it is emitted
* @return an Observable that emits connected, non-overlapping buffers of items emitted by the source
* Observable, after a fixed duration or when the buffer reaches maximum capacity (whichever occurs
* first)
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-buffer">RxJava Wiki: buffer()</a>
*/
public final Observable<List<T>> buffer(long timespan, TimeUnit unit, int count) {
return lift(new OperatorBufferWithTime<T>(timespan, timespan, unit, count, Schedulers.computation()));
}
/**
* Returns an Observable that emits buffers of items it collects from the source Observable. The resulting
* Observable emits connected, non-overlapping buffers, each of a fixed duration specified by the {@code timespan} argument as measured on the specified {@code scheduler}, or a maximum size
* specified by
* the {@code count} argument (whichever is reached first). When the source Observable completes or
* encounters an error, the resulting Observable emits the current buffer and propagates the notification
* from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer6.s.png">
*
* @param timespan
* the period of time each buffer collects items before it is emitted and replaced with a new
* buffer
* @param unit
* the unit of time which applies to the {@code timespan} argument
* @param count
* the maximum size of each buffer before it is emitted
* @param scheduler
* the {@link Scheduler} to use when determining the end and start of a buffer
* @return an Observable that emits connected, non-overlapping buffers of items emitted by the source
* Observable after a fixed duration or when the buffer reaches maximum capacity (whichever occurs
* first)
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-buffer">RxJava Wiki: buffer()</a>
*/
public final Observable<List<T>> buffer(long timespan, TimeUnit unit, int count, Scheduler scheduler) {
return lift(new OperatorBufferWithTime<T>(timespan, timespan, unit, count, scheduler));
}
/**
* Returns an Observable that emits buffers of items it collects from the source Observable. The resulting
* Observable emits connected, non-overlapping buffers, each of a fixed duration specified by the {@code timespan} argument and on the specified {@code scheduler}. When the source Observable
* completes or
* encounters an error, the resulting Observable emits the current buffer and propagates the notification
* from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer5.s.png">
*
* @param timespan
* the period of time each buffer collects items before it is emitted and replaced with a new
* buffer
* @param unit
* the unit of time which applies to the {@code timespan} argument
* @param scheduler
* the {@link Scheduler} to use when determining the end and start of a buffer
* @return an Observable that emits connected, non-overlapping buffers of items emitted by the source
* Observable within a fixed duration
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-buffer">RxJava Wiki: buffer()</a>
*/
public final Observable<List<T>> buffer(long timespan, TimeUnit unit, Scheduler scheduler) {
return lift(new OperatorBufferWithTime<T>(timespan, timespan, unit, Integer.MAX_VALUE, scheduler));
}
/**
* Returns an Observable that emits buffers of items it collects from the source Observable. The resulting
* Observable emits buffers that it creates when the specified {@code bufferOpenings} Observable emits an
* item, and closes when the Observable returned from {@code bufferClosingSelector} emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer2.png">
*
* @param bufferOpenings
* the Observable that, when it emits an item, causes a new buffer to be created
* @param bufferClosingSelector
* the {@link Func1} that is used to produce an Observable for every buffer created. When this
* Observable emits an item, the associated buffer is emitted.
* @return an Observable that emits buffers, containing items from the source Observable, that are created
* and closed when the specified Observables emit items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-buffer">RxJava Wiki: buffer()</a>
*/
public final <TOpening, TClosing> Observable<List<T>> buffer(Observable<? extends TOpening> bufferOpenings, Func1<? super TOpening, ? extends Observable<? extends TClosing>> bufferClosingSelector) {
return lift(new OperatorBufferWithStartEndObservable<T, TOpening, TClosing>(bufferOpenings, bufferClosingSelector));
}
/**
* Returns an Observable that emits non-overlapping buffered items from the source Observable each time the
* specified boundary Observable emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer8.png">
* <p>
* Completion of either the source or the boundary Observable causes the returned Observable to emit the
* latest buffer and complete.
*
* @param <B>
* the boundary value type (ignored)
* @param boundary
* the boundary Observable
* @return an Observable that emits buffered items from the source Observable when the boundary Observable
* emits an item
* @see #buffer(rx.Observable, int)
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-buffer">RxJava Wiki: buffer()</a>
*/
public final <B> Observable<List<T>> buffer(Observable<B> boundary) {
return lift(new OperatorBufferWithSingleObservable<T, B>(boundary, 16));
}
/**
* Returns an Observable that emits non-overlapping buffered items from the source Observable each time the
* specified boundary Observable emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer8.png">
* <p>
* Completion of either the source or the boundary Observable causes the returned Observable to emit the
* latest buffer and complete.
*
* @param <B>
* the boundary value type (ignored)
* @param boundary
* the boundary Observable
* @param initialCapacity
* the initial capacity of each buffer chunk
* @return an Observable that emits buffered items from the source Observable when the boundary Observable
* emits an item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-buffer">RxJava Wiki: buffer()</a>
* @see #buffer(rx.Observable, int)
*/
public final <B> Observable<List<T>> buffer(Observable<B> boundary, int initialCapacity) {
return lift(new OperatorBufferWithSingleObservable<T, B>(boundary, initialCapacity));
}
/**
* This method has similar behavior to {@link #replay} except that this auto-subscribes to the source
* Observable rather than returning a {@link ConnectableObservable}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/cache.png">
* <p>
* This is useful when you want an Observable to cache responses and you can't control the
* subscribe/unsubscribe behavior of all the {@link Subscriber}s.
* <p>
* When you call {@code cache()}, it does not yet subscribe to the source Observable. This only happens when {@code subscribe} is called the first time on the Observable returned by
* {@code cache()}.
* <p>
*
* <!-- IS THE FOLLOWING NOTE STILL VALID??? -->
*
* <em>Note:</em> You sacrifice the ability to unsubscribe from the origin when you use the {@code cache()} Observer so be careful not to use this Observer on Observables that emit an infinite or
* very large number
* of items that will use up memory.
*
* @return an Observable that, when first subscribed to, caches all of its items and notifications for the
* benefit of subsequent observers
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-cache">RxJava Wiki: cache()</a>
*/
public final Observable<T> cache() {
return create(new OperatorCache<T>(this));
}
/**
* Returns an Observable that emits the items emitted by the source Observable, converted to the specified
* type.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/cast.png">
*
* @param klass
* the target class type that the items emitted by the source Observable will be converted to
* before being emitted by the resulting Observable
* @return an Observable that emits each item from the source Observable after converting it to the
* specified type
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-cast">RxJava Wiki: cast()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211842.aspx">MSDN: Observable.Cast</a>
*/
public final <R> Observable<R> cast(final Class<R> klass) {
return lift(new OperatorCast<T, R>(klass));
}
/**
* Collect values into a single mutable data structure.
* <p>
* This is a simplified version of {@code reduce} that does not need to return the state on each pass.
* <p>
*
* @param state
* FIXME FIXME FIXME
* @param collector
* FIXME FIXME FIXME
* @return FIXME FIXME FIXME
*/
public final <R> Observable<R> collect(R state, final Action2<R, ? super T> collector) {
Func2<R, T, R> accumulator = new Func2<R, T, R>() {
@Override
public final R call(R state, T value) {
collector.call(state, value);
return state;
}
};
return reduce(state, accumulator);
}
/**
* Returns a new Observable that emits items resulting from applying a function that you supply to each item
* emitted by the source Observable, where that function returns an Observable, and then emitting the items
* that result from concatinating those resulting Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concatMap.png">
*
* @param func
* a function that, when applied to an item emitted by the source Observable, returns an
* Observable
* @return an Observable that emits the result of applying the transformation function to each item emitted
* by the source Observable and concatinating the Observables obtained from this transformation
*/
public final <R> Observable<R> concatMap(Func1<? super T, ? extends Observable<? extends R>> func) {
return concat(map(func));
}
/**
* Returns an Observable that emits a Boolean that indicates whether the source Observable emitted a
* specified item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/contains.png">
*
* @param element
* the item to search for in the emissions from the source Observable
* @return an Observable that emits {@code true} if the specified item is emitted by the source Observable,
* or {@code false} if the source Observable completes without emitting that item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-contains">RxJava Wiki: contains()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh228965.aspx">MSDN: Observable.Contains</a>
*/
public final Observable<Boolean> contains(final Object element) {
return exists(new Func1<T, Boolean>() {
public final Boolean call(T t1) {
return element == null ? t1 == null : element.equals(t1);
}
});
}
/**
* Returns an Observable that emits the count of the total number of items emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/count.png">
*
* @return an Observable that emits a single item: the number of elements emitted by the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-count-and-longcount">RxJava Wiki: count()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229470.aspx">MSDN: Observable.Count</a>
* @see #longCount()
*/
public final Observable<Integer> count() {
return reduce(0, new Func2<Integer, T, Integer>() {
@Override
public final Integer call(Integer t1, T t2) {
return t1 + 1;
}
});
}
/**
* Return an Observable that mirrors the source Observable, except that it drops items emitted by the source
* Observable that are followed by another item within a computed debounce duration.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/debounce.f.png">
*
* @param <U>
* the debounce value type (ignored)
* @param debounceSelector
* function to retrieve a sequence that indicates the throttle duration for each item
* @return an Observable that omits items emitted by the source Observable that are followed by another item
* within a computed debounce duration
*/
public final <U> Observable<T> debounce(Func1<? super T, ? extends Observable<U>> debounceSelector) {
return lift(new OperatorDebounceWithSelector<T, U>(debounceSelector));
}
/**
* Return an Observable that mirrors the source Observable, except that it drops items emitted by the source
* Observable that are followed by newer items before a timeout value expires. The timer resets on each
* emission.
* <p>
* <em>Note:</em> If items keep being emitted by the source Observable faster than the timeout then no items
* will be emitted by the resulting Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/debounce.png">
* <p>
* Information on debounce vs throttle:
* <p>
* <ul>
* <li><a href="http://drupalmotion.com/article/debounce-and-throttle-visual-explanation">Debounce and Throttle: visual explanation</a></li>
* <li><a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">Debouncing: javascript methods</a></li>
* <li><a href="http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/">Javascript - don't spam your server: debounce and throttle</a></li>
* </ul>
*
* @param timeout
* the time each item has to be "the most recent" of those emitted by the source Observable to
* ensure that it's not dropped
* @param unit
* the {@link TimeUnit} for the timeout
* @return an Observable that filters out items from the source Observable that are too quickly followed by
* newer items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-throttlewithtimeout-or-debounce">RxJava Wiki: debounce()</a>
* @see #throttleWithTimeout(long, TimeUnit)
*/
public final Observable<T> debounce(long timeout, TimeUnit unit) {
return lift(new OperatorDebounceWithTime<T>(timeout, unit, Schedulers.computation()));
}
/**
* Return an Observable that mirrors the source Observable, except that it drops items emitted by the source
* Observable that are followed by newer items before a timeout value expires on a specified Scheduler. The
* timer resets on each emission.
* <p>
* <em>Note:</em> If items keep being emitted by the source Observable faster than the timeout then no items
* will be emitted by the resulting Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/debounce.s.png">
* <p>
* Information on debounce vs throttle:
* <p>
* <ul>
* <li><a href="http://drupalmotion.com/article/debounce-and-throttle-visual-explanation">Debounce and Throttle: visual explanation</a></li>
* <li><a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">Debouncing: javascript methods</a></li>
* <li><a href="http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/">Javascript - don't spam your server: debounce and throttle</a></li>
* </ul>
*
* @param timeout
* the time each item has to be "the most recent" of those emitted by the source Observable to
* ensure that it's not dropped
* @param unit
* the unit of time for the specified timeout
* @param scheduler
* the {@link Scheduler} to use internally to manage the timers that handle the timeout for each
* item
* @return an Observable that filters out items from the source Observable that are too quickly followed by
* newer items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-throttlewithtimeout-or-debounce">RxJava Wiki: debounce()</a>
* @see #throttleWithTimeout(long, TimeUnit, Scheduler)
*/
public final Observable<T> debounce(long timeout, TimeUnit unit, Scheduler scheduler) {
return lift(new OperatorDebounceWithTime<T>(timeout, unit, scheduler));
}
/**
* Returns an Observable that emits the items emitted by the source Observable or a specified default item
* if the source Observable is empty.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/defaultIfEmpty.png">
*
* @param defaultValue
* the item to emit if the source Observable emits no items
* @return an Observable that emits either the specified default item if the source Observable emits no
* items, or the items emitted by the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-defaultifempty">RxJava Wiki: defaultIfEmpty()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229624.aspx">MSDN: Observable.DefaultIfEmpty</a>
*/
public final Observable<T> defaultIfEmpty(T defaultValue) {
return lift(new OperatorDefaultIfEmpty<T>(defaultValue));
}
/**
* Returns an Observable that delays the subscription to and emissions from the souce Observable via another
* Observable on a per-item basis.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/delay.oo.png">
* <p>
* <em>Note:</em> the resulting Observable will immediately propagate any {@code onError} notification
* from the source Observable.
*
* @param <U>
* the subscription delay value type (ignored)
* @param <V>
* the item delay value type (ignored)
* @param subscriptionDelay
* a function that returns an Observable that triggers the subscription to the source Observable
* once it emits any item
* @param itemDelay
* a function that returns an Observable for each item emitted by the source Observable, which is
* then used to delay the emission of that item by the resulting Observable until the Observable
* returned from {@code itemDelay} emits an item
* @return an Observable that delays the subscription and emissions of the source Observable via another
* Observable on a per-item basis
*/
public final <U, V> Observable<T> delay(
Func0<? extends Observable<U>> subscriptionDelay,
Func1<? super T, ? extends Observable<V>> itemDelay) {
return create(new OperatorDelayWithSelector<T, U, V>(this, subscriptionDelay, itemDelay));
}
/**
* Returns an Observable that delays the emissions of the source Observable via another Observable on a
* per-item basis.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/delay.o.png">
* <p>
* <em>Note:</em> the resulting Observable will immediately propagate any {@code onError} notification
* from the source Observable.
*
* @param <U>
* the item delay value type (ignored)
* @param itemDelay
* a function that returns an Observable for each item emitted by the source Observable, which is
* then used to delay the emission of that item by the resulting Observable until the Observable
* returned from {@code itemDelay} emits an item
* @return an Observable that delays the emissions of the source Observable via another Observable on a
* per-item basis
*/
public final <U> Observable<T> delay(Func1<? super T, ? extends Observable<U>> itemDelay) {
return create(new OperatorDelayWithSelector<T, U, U>(this, itemDelay));
}
/**
* Returns an Observable that emits the items emitted by the source Observable shifted forward in time by a
* specified delay. Error notifications from the source Observable are not delayed.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/delay.png">
*
* @param delay
* the delay to shift the source by
* @param unit
* the {@link TimeUnit} in which {@code period} is defined
* @return the source Observable shifted in time by the specified delay
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-delay">RxJava Wiki: delay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229810.aspx">MSDN: Observable.Delay</a>
*/
public final Observable<T> delay(long delay, TimeUnit unit) {
return create(new OperatorDelay<T>(this, delay, unit, Schedulers.computation()));
}
/**
* Returns an Observable that emits the items emitted by the source Observable shifted forward in time by a
* specified delay. Error notifications from the source Observable are not delayed.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/delay.s.png">
*
* @param delay
* the delay to shift the source by
* @param unit
* the time unit of {@code delay}
* @param scheduler
* the {@link Scheduler} to use for delaying
* @return the source Observable shifted in time by the specified delay
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-delay">RxJava Wiki: delay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229280.aspx">MSDN: Observable.Delay</a>
*/
public final Observable<T> delay(long delay, TimeUnit unit, Scheduler scheduler) {
return create(new OperatorDelay<T>(this, delay, unit, scheduler));
}
/**
* Return an Observable that delays the subscription to the source Observable by a given amount of time.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/delaySubscription.png">
*
* @param delay
* the time to delay the subscription
* @param unit
* the time unit of {@code delay}
* @return an Observable that delays the subscription to the source Observable by the given amount
*/
public final Observable<T> delaySubscription(long delay, TimeUnit unit) {
return delaySubscription(delay, unit, Schedulers.computation());
}
/**
* Return an Observable that delays the subscription to the source Observable by a given amount of time,
* both waiting and subscribing on a given Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/delaySubscription.s.png">
*
* @param delay
* the time to delay the subscription
* @param unit
* the time unit of {@code delay}
* @param scheduler
* the Scheduler on which the waiting and subscription will happen
* @return an Observable that delays the subscription to the source Observable by a given
* amount, waiting and subscribing on the given Scheduler
*/
public final Observable<T> delaySubscription(long delay, TimeUnit unit, Scheduler scheduler) {
return create(new OperatorDelaySubscription<T>(this, delay, unit, scheduler));
}
/**
* Returns an Observable that reverses the effect of {@link #materialize materialize} by transforming the {@link Notification} objects emitted by the source Observable into the items or
* notifications they
* represent.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/dematerialize.png">
*
* @return an Observable that emits the items and notifications embedded in the {@link Notification} objects
* emitted by the source Observable
* @throws Throwable
* if the source Observable is not of type {@code Observable<Notification<T>>}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-dematerialize">RxJava Wiki: dematerialize()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229047.aspx">MSDN: Observable.dematerialize</a>
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public final <T2> Observable<T2> dematerialize() {
return lift(new OperatorDematerialize());
}
/**
* Returns an Observable that emits all items emitted by the source Observable that are distinct.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/distinct.png">
*
* @return an Observable that emits only those items emitted by the source Observable that are distinct from
* each other
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-distinct">RxJava Wiki: distinct()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229764.aspx">MSDN: Observable.distinct</a>
*/
public final Observable<T> distinct() {
return lift(new OperatorDistinct<T, T>(Functions.<T>identity()));
}
/**
* Returns an Observable that emits all items emitted by the source Observable that are distinct according
* to a key selector function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/distinct.key.png">
*
* @param keySelector
* a function that projects an emitted item to a key value that is used to decide whether an item
* is distinct from another one or not
* @return an Observable that emits those items emitted by the source Observable that have distinct keys
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-distinct">RxJava Wiki: distinct()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh244310.aspx">MSDN: Observable.distinct</a>
*/
public final <U> Observable<T> distinct(Func1<? super T, ? extends U> keySelector) {
return lift(new OperatorDistinct<T, U>(keySelector));
}
/**
* Returns an Observable that emits all items emitted by the source Observable that are distinct from their
* immediate predecessors.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/distinctUntilChanged.png">
*
* @return an Observable that emits those items from the source Observable that are distinct from their
* immediate predecessors
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-distinctuntilchanged">RxJava Wiki: distinctUntilChanged()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229494.aspx">MSDN: Observable.distinctUntilChanged</a>
*/
public final Observable<T> distinctUntilChanged() {
return lift(new OperatorDistinctUntilChanged<T, T>(Functions.<T>identity()));
}
/**
* Returns an Observable that emits all items emitted by the source Observable that are distinct from their
* immediate predecessors, according to a key selector function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/distinctUntilChanged.key.png">
*
* @param keySelector
* a function that projects an emitted item to a key value that is used to decide whether an item
* is distinct from another one or not
* @return an Observable that emits those items from the source Observable whose keys are distinct from
* those of their immediate predecessors
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-distinctuntilchanged">RxJava Wiki: distinctUntilChanged()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229508.aspx">MSDN: Observable.distinctUntilChanged</a>
*/
public final <U> Observable<T> distinctUntilChanged(Func1<? super T, ? extends U> keySelector) {
return lift(new OperatorDistinctUntilChanged<T, U>(keySelector));
}
/**
* Modifies an Observable so that it invokes an action when it calls {@code onCompleted}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/doOnCompleted.png">
*
* @param onCompleted
* the action to invoke when the source Observable calls {@code onCompleted}
* @return the source Observable with the side-effecting behavior applied
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-dooncompleted">RxJava Wiki: doOnCompleted()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229804.aspx">MSDN: Observable.Do</a>
*/
public final Observable<T> doOnCompleted(final Action0 onCompleted) {
Observer<T> observer = new Observer<T>() {
@Override
public final void onCompleted() {
onCompleted.call();
}
@Override
public final void onError(Throwable e) {
}
@Override
public final void onNext(T args) {
}
};
return lift(new OperatorDoOnEach<T>(observer));
}
/**
* Modifies an Observable so that it invokes an action for each item it emits.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/doOnEach.png">
*
* @param onNotification
* the action to invoke for each item emitted by the source Observable
* @return the source Observable with the side-effecting behavior applied
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-dooneach">RxJava Wiki: doOnEach()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229307.aspx">MSDN: Observable.Do</a>
*/
public final Observable<T> doOnEach(final Action1<Notification<? super T>> onNotification) {
Observer<T> observer = new Observer<T>() {
@Override
public final void onCompleted() {
onNotification.call(Notification.createOnCompleted());
}
@Override
public final void onError(Throwable e) {
onNotification.call(Notification.createOnError(e));
}
@Override
public final void onNext(T v) {
onNotification.call(Notification.createOnNext(v));
}
};
return lift(new OperatorDoOnEach<T>(observer));
}
/**
* Modifies an Observable so that it notifies an Observer for each item it emits.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/doOnEach.png">
*
* @param observer
* the action to invoke for each item emitted by the source Observable
* @return the source Observable with the side-effecting behavior applied
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-dooneach">RxJava Wiki: doOnEach()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229307.aspx">MSDN: Observable.Do</a>
*/
public final Observable<T> doOnEach(Observer<? super T> observer) {
return lift(new OperatorDoOnEach<T>(observer));
}
/**
* Modifies an Observable so that it invokes an action if it calls {@code onError}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/doOnError.png">
*
* @param onError
* the action to invoke if the source Observable calls {@code onError}
* @return the source Observable with the side-effecting behavior applied
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-doonerror">RxJava Wiki: doOnError()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229804.aspx">MSDN: Observable.Do</a>
*/
public final Observable<T> doOnError(final Action1<Throwable> onError) {
Observer<T> observer = new Observer<T>() {
@Override
public final void onCompleted() {
}
@Override
public final void onError(Throwable e) {
onError.call(e);
}
@Override
public final void onNext(T args) {
}
};
return lift(new OperatorDoOnEach<T>(observer));
}
/**
* Modifies an Observable so that it invokes an action when it calls {@code onNext}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/doOnNext.png">
*
* @param onNext
* the action to invoke when the source Observable calls {@code onNext}
* @return the source Observable with the side-effecting behavior applied
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-dooneach">RxJava Wiki: doOnNext()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229804.aspx">MSDN: Observable.Do</a>
*/
public final Observable<T> doOnNext(final Action1<? super T> onNext) {
Observer<T> observer = new Observer<T>() {
@Override
public final void onCompleted() {
}
@Override
public final void onError(Throwable e) {
}
@Override
public final void onNext(T args) {
onNext.call(args);
}
};
return lift(new OperatorDoOnEach<T>(observer));
}
/**
* Modifies an Observable so that it invokes an action when it calls {@code onCompleted} or {@code onError}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/doOnTerminate.png">
* <p>
* This differs from {@code finallyDo} in that this happens BEFORE onCompleted/onError are emitted.
*
* @param onTerminate
* the action to invoke when the source Observable calls {@code onCompleted} or {@code onError}
* @return the source Observable with the side-effecting behavior applied
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-doonterminate">RxJava Wiki: doOnTerminate()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229804.aspx">MSDN: Observable.Do</a>
* @since 0.17
*/
public final Observable<T> doOnTerminate(final Action0 onTerminate) {
Observer<T> observer = new Observer<T>() {
@Override
public final void onCompleted() {
onTerminate.call();
}
@Override
public final void onError(Throwable e) {
onTerminate.call();
}
@Override
public final void onNext(T args) {
}
};
return lift(new OperatorDoOnEach<T>(observer));
}
/**
* Returns an Observable that emits the single item at a specified index in a sequence of emissions from a
* source Observbable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/elementAt.png">
*
* @param index
* the zero-based index of the item to retrieve
* @return an Observable that emits a single item: the item at the specified position in the sequence of
* those emitted by the source Observable
* @throws IndexOutOfBoundsException
* if {@code index} is greater than or equal to the number of items emitted by the source
* Observable
* @throws IndexOutOfBoundsException
* if {@code index} is less than 0
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-elementat">RxJava Wiki: elementAt()</a>
*/
public final Observable<T> elementAt(int index) {
return lift(new OperatorElementAt<T>(index));
}
/**
* Returns an Observable that emits the item found at a specified index in a sequence of emissions from a
* source Observable, or a default item if that index is out of range.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/elementAtOrDefault.png">
*
* @param index
* the zero-based index of the item to retrieve
* @param defaultValue
* the default item
* @return an Observable that emits the item at the specified position in the sequence emitted by the source
* Observable, or the default item if that index is outside the bounds of the source sequence
* @throws IndexOutOfBoundsException
* if {@code index} is less than 0
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-elementatordefault">RxJava Wiki: elementAtOrDefault()</a>
*/
public final Observable<T> elementAtOrDefault(int index, T defaultValue) {
return lift(new OperatorElementAt<T>(index, defaultValue));
}
/**
* Returns an Observable that emits {@code true} if any item emitted by the source Observable satisfies a
* specified condition, otherwise {@code false}. <em>Note:</em> this always emits {@code false} if the
* source Observable is empty.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/exists.png">
* <p>
* In Rx.Net this is the {@code any} Observer but we renamed it in RxJava to better match Java naming
* idioms.
*
* @param predicate
* the condition to test items emitted by the source Observable
* @return an Observable that emits a Boolean that indicates whether any item emitted by the source
* Observable satisfies the {@code predicate}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-exists-and-isempty">RxJava Wiki: exists()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211993.aspx">MSDN: Observable.Any (Note: the description in this page was wrong at the time of this writing)</a>
*/
public final Observable<Boolean> exists(Func1<? super T, Boolean> predicate) {
return lift(new OperatorAny<T>(predicate, false));
}
/**
* Filter items emitted by an Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/filter.png">
*
* @param predicate
* a function that evaluates the items emitted by the source Observable, returning {@code true} if they pass the filter
* @return an Observable that emits only those items emitted by the source Observable that the filter
* evaluates as {@code true}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-filter-or-where">RxJava Wiki: filter()</a>
*/
public final Observable<T> filter(Func1<? super T, Boolean> predicate) {
return lift(new OperatorFilter<T>(predicate));
}
/**
* Registers an {@link Action0} to be called when this Observable invokes either {@link Observer#onCompleted onCompleted} or {@link Observer#onError onError}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/finallyDo.png">
*
* @param action
* an {@link Action0} to be invoked when the source Observable finishes
* @return an Observable that emits the same items as the source Observable, then invokes the {@link Action0}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-finallydo">RxJava Wiki: finallyDo()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh212133.aspx">MSDN: Observable.Finally</a>
*/
public final Observable<T> finallyDo(Action0 action) {
return lift(new OperatorFinally<T>(action));
}
/**
* Returns an Observable that emits only the very first item emitted by the source Observable, or raises an {@code NoSuchElementException} if the source Observable is empty.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/first.png">
*
* @return an Observable that emits only the very first item emitted by the source Observable, or raises an {@code NoSuchElementException} if the source Observable is empty
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-first">RxJava Wiki: first()</a>
* @see "MSDN: Observable.firstAsync()"
*/
public final Observable<T> first() {
return take(1).single();
}
/**
* Returns an Observable that emits only the very first item emitted by the source Observable that satisfies
* a specified condition, or raises an {@code NoSuchElementException} if no such items are emitted.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/firstN.png">
*
* @param predicate
* the condition that an item emitted by the source Observable has to satisfy
* @return an Observable that emits only the very first item emitted by the source Observable that satisfies
* the {@code predicate}, or raises an {@code NoSuchElementException} if no such items are emitted
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-first">RxJava Wiki: first()</a>
* @see "MSDN: Observable.firstAsync()"
*/
public final Observable<T> first(Func1<? super T, Boolean> predicate) {
return takeFirst(predicate).single();
}
/**
* Returns an Observable that emits only the very first item emitted by the source Observable, or a default
* item if the source Observable completes without emitting anything.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/firstOrDefault.png">
*
* @param defaultValue
* the default item to emit if the source Observable doesn't emit anything
* @return an Observable that emits only the very first item from the source, or a default item if the
* source Observable completes without emitting any items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-firstordefault">RxJava Wiki: firstOrDefault()</a>
* @see "MSDN: Observable.firstOrDefaultAsync()"
*/
public final Observable<T> firstOrDefault(T defaultValue) {
return take(1).singleOrDefault(defaultValue);
}
/**
* Returns an Observable that emits only the very first item emitted by the source Observable that satisfies
* a specified condition, or a default item if the source Observable emits no such items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/firstOrDefaultN.png">
*
* @param predicate
* the condition any item emitted by the source Observable has to satisfy
* @param defaultValue
* the default item to emit if the source Observable doesn't emit anything that satisfies the {@code predicate}
* @return an Observable that emits only the very first item emitted by the source Observable that satisfies
* the {@code predicate}, or a default item if the source Observable emits no such items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-firstordefault">RxJava Wiki: firstOrDefault()</a>
* @see "MSDN: Observable.firstOrDefaultAsync()"
*/
public final Observable<T> firstOrDefault(T defaultValue, Func1<? super T, Boolean> predicate) {
return takeFirst(predicate).singleOrDefault(defaultValue);
}
/**
* Returns an Observable that emits items based on applying a function that you supply to each item emitted
* by the source Observable, where that function returns an Observable, and then merging those resulting
* Observables and emitting the results of this merger.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/flatMap.png">
*
* @param func
* a function that, when applied to an item emitted by the source Observable, returns an
* Observable
* @return an Observable that emits the result of applying the transformation function to each item emitted
* by the source Observable and merging the results of the Observables obtained from this
* transformation
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-mapmany-or-flatmap-and-mapmanydelayerror">RxJava Wiki: flatMap()</a>
*/
public final <R> Observable<R> flatMap(Func1<? super T, ? extends Observable<? extends R>> func) {
return mergeMap(func);
}
/**
* Subscribes to the {@link Observable} and receives notifications for each element.
* <p>
* Alias to {@link #subscribe(Action1)}
*
* @param onNext
* {@link Action1} to execute for each item.
* @throws IllegalArgumentException
* if {@code onNext} is null
* @throws IllegalArgumentException
* if {@code onError} is null
* @throws IllegalArgumentException
* if {@code onComplete} is null
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable#wiki-onnext-oncompleted-and-onerror">RxJava Wiki: onNext, onCompleted, and onError</a>
* @since 0.19
*/
public final void forEach(final Action1<? super T> onNext) {
subscribe(onNext);
}
/**
* Subscribes to the {@link Observable} and receives notifications for each element and error events.
* <p>
* Alias to {@link #subscribe(Action1, Action1)}
*
* @param onNext
* {@link Action1} to execute for each item.
* @param onError
* {@link Action1} to execute when an error is emitted.
* @throws IllegalArgumentException
* if {@code onNext} is null
* @throws IllegalArgumentException
* if {@code onError} is null
* @throws IllegalArgumentException
* if {@code onComplete} is null
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable#wiki-onnext-oncompleted-and-onerror">RxJava Wiki: onNext, onCompleted, and onError</a>
* @since 0.19
*/
public final void forEach(final Action1<? super T> onNext, final Action1<Throwable> onError) {
subscribe(onNext, onError);
}
/**
* Subscribes to the {@link Observable} and receives notifications for each element and the terminal events.
* <p>
* Alias to {@link #subscribe(Action1, Action1, Action0)}
*
* @param onNext
* {@link Action1} to execute for each item.
* @param onError
* {@link Action1} to execute when an error is emitted.
* @param onComplete
* {@link Action0} to execute when completion is signalled.
* @throws IllegalArgumentException
* if {@code onNext} is null
* @throws IllegalArgumentException
* if {@code onError} is null
* @throws IllegalArgumentException
* if {@code onComplete} is null
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable#wiki-onnext-oncompleted-and-onerror">RxJava Wiki: onNext, onCompleted, and onError</a>
* @since 0.19
*/
public final void forEach(final Action1<? super T> onNext, final Action1<Throwable> onError, final Action0 onComplete) {
subscribe(onNext, onError, onComplete);
}
/**
* Groups the items emitted by an Observable according to a specified criterion, and emits these grouped
* items as {@link GroupedObservable}s, one {@code GroupedObservable} per group.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/groupBy.png">
*
* @param keySelector
* a function that extracts the key for each item
* @param <K>
* the key type
* @return an Observable that emits {@link GroupedObservable}s, each of which corresponds to a unique key
* value and each of which emits those items from the source Observable that share that key value
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-groupby-and-groupbyuntil">RxJava Wiki: groupBy</a>
*/
public final <K> Observable<GroupedObservable<K, T>> groupBy(final Func1<? super T, ? extends K> keySelector) {
return lift(new OperatorGroupBy<K, T>(keySelector));
}
/**
* Groups the items emitted by an Observable according to a specified key selector function until the
* duration Observable expires for the key.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/groupByUntil.png">
*
* @param keySelector
* a function to extract the key for each item
* @param durationSelector
* a function to signal the expiration of a group
* @return an Observable that emits {@link GroupedObservable}s, each of which corresponds to a key value and
* each of which emits all items emitted by the source Observable during that key's duration that
* share that same key value
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-groupby-and-groupbyuntil">RxJava Wiki: groupByUntil()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211932.aspx">MSDN: Observable.GroupByUntil</a>
*/
public final <TKey, TDuration> Observable<GroupedObservable<TKey, T>> groupByUntil(Func1<? super T, ? extends TKey> keySelector, Func1<? super GroupedObservable<TKey, T>, ? extends Observable<? extends TDuration>> durationSelector) {
return groupByUntil(keySelector, Functions.<T> identity(), durationSelector);
}
/**
* Groups the items emitted by an Observable (transformed by a selector) according to a specified key
* selector function until the duration Observable expires for the key.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/groupByUntil.png">
*
* @param keySelector
* a function to extract the key for each item
* @param valueSelector
* a function to map each item emitted by the source Observable to an item emitted by one of the
* resulting {@link GroupedObservable}s
* @param durationSelector
* a function to signal the expiration of a group
* @return an Observable that emits {@link GroupedObservable}s, each of which corresponds to a key value and
* each of which emits all items emitted by the source Observable during that key's duration that
* share that same key value, transformed by the value selector
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-groupby-and-groupbyuntil">RxJava Wiki: groupByUntil()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229433.aspx">MSDN: Observable.GroupByUntil</a>
*/
public final <TKey, TValue, TDuration> Observable<GroupedObservable<TKey, TValue>> groupByUntil(Func1<? super T, ? extends TKey> keySelector, Func1<? super T, ? extends TValue> valueSelector, Func1<? super GroupedObservable<TKey, TValue>, ? extends Observable<? extends TDuration>> durationSelector) {
return lift(new OperatorGroupByUntil<T, TKey, TValue, TDuration>(keySelector, valueSelector, durationSelector));
}
/**
* Return an Observable that correlates two Observables when they overlap in time and groups the results.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/groupJoin.png">
*
* @param right
* the other Observable to correlate items from the source Observable with
* @param leftDuration
* a function that returns an Observable whose emissions indicate the duration of the values of
* the source Observable
* @param rightDuration
* a function that returns an Observable whose emissions indicate the duration of the values of
* the {@code right} Observable
* @param resultSelector
* a function that takes an item emitted by each Observable and returns the value to be emitted
* by the resulting Observable
* @return an Observable that emits items based on combining those items emitted by the source Observables
* whose durations overlap
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-join-and-groupjoin">RxJava Wiiki: groupJoin</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh244235.aspx">MSDN: Observable.GroupJoin</a>
*/
public final <T2, D1, D2, R> Observable<R> groupJoin(Observable<T2> right, Func1<? super T, ? extends Observable<D1>> leftDuration,
Func1<? super T2, ? extends Observable<D2>> rightDuration,
Func2<? super T, ? super Observable<T2>, ? extends R> resultSelector) {
return create(new OperatorGroupJoin<T, T2, D1, D2, R>(this, right, leftDuration, rightDuration, resultSelector));
}
/**
* Ignores all items emitted by the source Observable and only calls {@code onCompleted} or {@code onError}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/ignoreElements.png">
*
* @return an empty Observable that only calls {@code onCompleted} or {@code onError}, based on which one is
* called by the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-ignoreelements">RxJava Wiki: ignoreElements()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229242.aspx">MSDN: Observable.IgnoreElements</a>
*/
public final Observable<T> ignoreElements() {
return filter(alwaysFalse());
}
/**
* Returns an Observable that emits {@code true} if the source Observable is empty, otherwise {@code false}.
* <p>
* In Rx.Net this is negated as the {@code any} Observer but we renamed this in RxJava to better match Java
* naming idioms.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/isEmpty.png">
*
* @return an Observable that emits a Boolean
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-exists-and-isempty">RxJava Wiki: isEmpty()</a>
* @see <a href= "http://msdn.microsoft.com/en-us/library/hh229905.aspx">MSDN: Observable.Any</a>
*/
public final Observable<Boolean> isEmpty() {
return lift(new OperatorAny<T>(Functions.alwaysTrue(), true));
}
/**
* Correlates the items emitted by two Observables based on overlapping durations.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/join_.png">
*
* @param right
* the second Observable to join items from
* @param leftDurationSelector
* a function to select a duration for each item emitted by the source Observable, used to
* determine overlap
* @param rightDurationSelector
* a function to select a duration for each item emitted by the {@code right} Observable, used to
* determine overlap
* @param resultSelector
* a function that computes an item to be emitted by the resulting Observable for any two
* overlapping items emitted by the two Observables
* @return an Observable that emits items correlating to items emitted by the source Observables that have
* overlapping durations
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-join">RxJava Wiki: join()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229750.aspx">MSDN: Observable.Join</a>
*/
public final <TRight, TLeftDuration, TRightDuration, R> Observable<R> join(Observable<TRight> right, Func1<T, Observable<TLeftDuration>> leftDurationSelector,
Func1<TRight, Observable<TRightDuration>> rightDurationSelector,
Func2<T, TRight, R> resultSelector) {
return create(new OperatorJoin<T, TRight, TLeftDuration, TRightDuration, R>(this, right, leftDurationSelector, rightDurationSelector, resultSelector));
}
/**
* Returns an Observable that emits the last item emitted by the source Observable or notifies observers of
* an {@code NoSuchElementException} if the source Observable is empty.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/last.png">
*
* @return an Observable that emits the last item from the source Observable or notifies observers of an
* error
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observable-Operators#wiki-last">RxJava Wiki: last()</a>
* @see "MSDN: Observable.lastAsync()"
*/
public final Observable<T> last() {
return takeLast(1).single();
}
/**
* Returns an Observable that emits only the last item emitted by the source Observable that satisfies a
* given condition, or an {@code NoSuchElementException} if no such items are emitted.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/last.p.png">
*
* @param predicate
* the condition any source emitted item has to satisfy
* @return an Observable that emits only the last item satisfying the given condition from the source, or an {@code NoSuchElementException} if no such items are emitted
* @throws IllegalArgumentException
* if no items that match the predicate are emitted by the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observable-Operators#wiki-last">RxJava Wiki: last()</a>
* @see "MSDN: Observable.lastAsync()"
*/
public final Observable<T> last(Func1<? super T, Boolean> predicate) {
return filter(predicate).takeLast(1).single();
}
/**
* Returns an Observable that emits only the last item emitted by the source Observable, or a default item
* if the source Observable completes without emitting any items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/lastOrDefault.png">
*
* @param defaultValue
* the default item to emit if the source Observable is empty
* @return an Observable that emits only the last item emitted by the source Observable, or a default item
* if the source Observable is empty
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-lastOrDefault">RxJava Wiki: lastOrDefault()</a>
* @see "MSDN: Observable.lastOrDefaultAsync()"
*/
public final Observable<T> lastOrDefault(T defaultValue) {
return takeLast(1).singleOrDefault(defaultValue);
}
/**
* Returns an Observable that emits only the last item emitted by the source Observable that satisfies a
* specified condition, or a default item if no such item is emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/lastOrDefault.p.png">
*
* @param defaultValue
* the default item to emit if the source Observable doesn't emit anything that satisfies the
* specified {@code predicate}
* @param predicate
* the condition any item emitted by the source Observable has to satisfy
* @return an Observable that emits only the last item emitted by the source Observable that satisfies the
* given condition, or a default item if no such item is emitted by the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-lastOrDefault">RxJava Wiki: lastOrDefault()</a>
* @see "MSDN: Observable.lastOrDefaultAsync()"
*/
public final Observable<T> lastOrDefault(T defaultValue, Func1<? super T, Boolean> predicate) {
return filter(predicate).takeLast(1).singleOrDefault(defaultValue);
}
/**
* Returns an Observable that emits only the first {@code num} items emitted by the source Observable.
* <p>
* Alias of {@link #take(int)} to match Java 8 Stream API naming convention.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/take.png">
* <p>
* This method returns an Observable that will invoke a subscribing {@link Observer}'s {@link Observer#onNext onNext} function a maximum of {@code num} times before invoking
* {@link Observer#onCompleted onCompleted}.
*
* @param num
* the maximum number of items to emit
* @return an Observable that emits only the first {@code num} items emitted by the source Observable, or
* all of the items from the source Observable if that Observable emits fewer than {@code num} items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-take">RxJava Wiki: take()</a>
* @since 0.19
*/
public final Observable<T> limit(int num) {
return take(num);
}
/**
* Returns an Observable that counts the total number of items emitted by the source Observable and emits
* this count as a 64-bit Long.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/longCount.png">
*
* @return an Observable that emits a single item: the number of items emitted by the source Observable as a
* 64-bit Long item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-count-and-longcount">RxJava Wiki: count()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229120.aspx">MSDN: Observable.LongCount</a>
* @see #count()
*/
public final Observable<Long> longCount() {
return reduce(0L, new Func2<Long, T, Long>() {
@Override
public final Long call(Long t1, T t2) {
return t1 + 1;
}
});
}
/**
* Returns an Observable that applies a specified function to each item emitted by the source Observable and
* emits the results of these function applications.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/map.png">
*
* @param func
* a function to apply to each item emitted by the Observable
* @return an Observable that emits the items from the source Observable, transformed by the specified
* function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-map">RxJava Wiki: map()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh244306.aspx">MSDN: Observable.Select</a>
*/
public final <R> Observable<R> map(Func1<? super T, ? extends R> func) {
return lift(new OperatorMap<T, R>(func));
}
/**
* Turns all of the emissions and notifications from a source Observable into emissions marked with their
* original types within {@link Notification} objects.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/materialize.png">
*
* @return an Observable that emits items that are the result of materializing the items and notifications
* of the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-materialize">RxJava Wiki: materialize()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229453.aspx">MSDN: Observable.materialize</a>
*/
public final Observable<Notification<T>> materialize() {
return lift(new OperatorMaterialize<T>());
}
/**
* Returns an Observable that emits the results of applying a specified function to each item emitted by the
* source Observable, where that function returns an Observable, and then merging those resulting
* Observables and emitting the results of this merger.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeMap.png">
*
* @param func
* a function that, when applied to an item emitted by the source Observable, returns an
* Observable
* @return an Observable that emits the result of applying the transformation function to each item emitted
* by the source Observable and merging the results of the Observables obtained from these
* transformations
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-mapmany-or-flatmap-and-mapmanydelayerror">RxJava Wiki: flatMap()</a>
* @see #flatMap(Func1)
*/
public final <R> Observable<R> mergeMap(Func1<? super T, ? extends Observable<? extends R>> func) {
return merge(map(func));
}
/**
* Returns an Observable that applies a function to each item emitted or notification raised by the source
* Observable and then flattens the Observables returned from these functions and emits the resulting items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeMap.nce.png">
*
* @param <R>
* the result type
* @param onNext
* a function that returns an Observable to merge for each item emitted by the source Observable
* @param onError
* a function that returns an Observable to merge for an onError notification from the source
* Observable
* @param onCompleted
* a function that returns an Observable to merge for an onCompleted notification from the source
* Observable
* @return an Observable that emits the results of merging the Observables returned from applying the
* specified functions to the emissions and notifications of the source Observable
*/
public final <R> Observable<R> mergeMap(
Func1<? super T, ? extends Observable<? extends R>> onNext,
Func1<? super Throwable, ? extends Observable<? extends R>> onError,
Func0<? extends Observable<? extends R>> onCompleted) {
return lift(new OperatorMergeMapTransform<T, R>(onNext, onError, onCompleted));
}
/**
* Returns an Observable that emits the results of a specified function to the pair of values emitted by the
* source Observable and a specified collection Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeMap.r.png">
*
* @param <U>
* the type of items emitted by the collection Observable
* @param <R>
* the type of items emitted by the resulting Observable
* @param collectionSelector
* a function that returns an Observable for each item emitted by the source Observable
* @param resultSelector
* a function that combines one item emitted by each of the source and collection Observables and
* returns an item to be emitted by the resulting Observable
* @return an Observable that emits the results of applying a function to a pair of values emitted by the
* source Observable and the collection Observable
*/
public final <U, R> Observable<R> mergeMap(Func1<? super T, ? extends Observable<? extends U>> collectionSelector,
Func2<? super T, ? super U, ? extends R> resultSelector) {
return lift(new OperatorMergeMapPair<T, U, R>(collectionSelector, resultSelector));
}
/**
* Returns an Observable that merges each item emitted by the source Observable with the values in an
* Iterable corresponding to that item that is generated by a selector.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeMapIterable.png">
*
* @param <R>
* the type of item emitted by the resulting Observable
* @param collectionSelector
* a function that returns an Iterable sequence of values for when given an item emitted by the
* source Observable
* @return an Observable that emits the results of merging the items emitted by the source Observable with
* the values in the Iterables corresponding to those items, as generated by {@code collectionSelector}
*/
public final <R> Observable<R> mergeMapIterable(Func1<? super T, ? extends Iterable<? extends R>> collectionSelector) {
return merge(map(OperatorMergeMapPair.convertSelector(collectionSelector)));
}
/**
* Returns an Observable that emits the results of applying a function to the pair of values from the source
* Observable and an Iterable corresponding to that item that is generated by a selector.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeMapIterable.r.png">
*
* @param <U>
* the collection element type
* @param <R>
* the type of item emited by the resulting Observable
* @param collectionSelector
* a function that returns an Iterable sequence of values for each item emitted by the source
* Observable
* @param resultSelector
* a function that returns an item based on the item emitted by the source Observable and the
* Iterable returned for that item by the {@code collectionSelector}
* @return an Observable that emits the items returned by {@code resultSelector} for each item in the source
* Observable
*/
public final <U, R> Observable<R> mergeMapIterable(Func1<? super T, ? extends Iterable<? extends U>> collectionSelector,
Func2<? super T, ? super U, ? extends R> resultSelector) {
return mergeMap(OperatorMergeMapPair.convertSelector(collectionSelector), resultSelector);
}
/**
* Returns an Observable that emits items produced by multicasting the source Observable within a selector
* function.
*
* @param subjectFactory
* the {@link Subject} factory
* @param selector
* the selector function, which can use the multicasted source Observable subject to the policies
* enforced by the created {@code Subject}
* @return an Observable that emits the items produced by multicasting the source Observable within a
* selector function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablepublish-and-observablemulticast">RxJava: Observable.publish() and Observable.multicast()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229708.aspx">MSDN: Observable.Multicast</a>
*/
public final <TIntermediate, TResult> Observable<TResult> multicast(
final Func0<? extends Subject<? super T, ? extends TIntermediate>> subjectFactory,
final Func1<? super Observable<TIntermediate>, ? extends Observable<TResult>> selector) {
return create(new OperatorMulticastSelector<T, TIntermediate, TResult>(this, subjectFactory, selector));
}
/**
* Returns a {@link ConnectableObservable} that upon connection causes the source Observable to push results
* into the specified subject. A Connectable Observable resembles an ordinary Observable, except that it
* does not begin emitting items when it is subscribed to, but only when its <code>connect()</code> method
* is called.
*
* @param subject
* the {@link Subject} for the {@link ConnectableObservable} to push source items into
* @param <R>
* the type of items emitted by the resulting {@code ConnectableObservable}
* @return a {@link ConnectableObservable} that upon connection causes the source Observable to push results
* into the specified {@link Subject}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablepublish-and-observablemulticast">RxJava Wiki: Observable.publish() and
* Observable.multicast()</a>
*/
public final <R> ConnectableObservable<R> multicast(Subject<? super T, ? extends R> subject) {
return new OperatorMulticast<T, R>(this, subject);
}
/**
* Move notifications to the specified {@link Scheduler} asynchronously with an unbounded buffer.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/observeOn.png">
*
* @param scheduler
* the {@link Scheduler} to notify {@link Observer}s on
* @return the source Observable modified so that its {@link Observer}s are notified on the specified {@link Scheduler}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-observeon">RxJava Wiki: observeOn()</a>
*/
public final Observable<T> observeOn(Scheduler scheduler) {
return lift(new OperatorObserveOn<T>(scheduler));
}
/**
* Filters the items emitted by an Observable, only emitting those of the specified type.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/ofClass.png">
*
* @param klass
* the class type to filter the items emitted by the source Observable
* @return an Observable that emits items from the source Observable of type {@code klass}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-oftype">RxJava Wiki: ofType()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229380.aspx">MSDN: Observable.OfType</a>
*/
public final <R> Observable<R> ofType(final Class<R> klass) {
return filter(new Func1<T, Boolean>() {
public final Boolean call(T t) {
return klass.isInstance(t);
}
}).cast(klass);
}
/**
* Instruct an Observable to pass control to another Observable rather than invoking {@link Observer#onError onError} if it encounters an error.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/onErrorResumeNext.png">
* <p>
* By default, when an Observable encounters an error that prevents it from emitting the expected item to
* its {@link Observer}, the Observable invokes its Observer's {@code onError} method, and then quits
* without invoking any more of its Observer's methods. The {@code onErrorResumeNext} method changes this
* behavior. If you pass a function that returns an Observable ({@code resumeFunction}) to {@code onErrorResumeNext}, if the original Observable encounters an error, instead of invoking its
* Observer's {@code onError} method, it will instead relinquish control to the Observable returned from {@code resumeFunction}, which will invoke the Observer's {@link Observer#onNext onNext}
* method if it is
* able to do so. In such a case, because no Observable necessarily invokes {@code onError}, the Observer
* may never know that an error happened.
* <p>
* You can use this to prevent errors from propagating or to supply fallback data should errors be
* encountered.
*
* @param resumeFunction
* a function that returns an Observable that will take over if the source Observable encounters
* an error
* @return the original Observable, with appropriately modified behavior
* @see <a href="https://github.com/Netflix/RxJava/wiki/Error-Handling-Operators#wiki-onerrorresumenext">RxJava Wiki: onErrorResumeNext()</a>
*/
public final Observable<T> onErrorResumeNext(final Func1<Throwable, ? extends Observable<? extends T>> resumeFunction) {
return lift(new OperatorOnErrorResumeNextViaFunction<T>(resumeFunction));
}
/**
* Instruct an Observable to pass control to another Observable rather than invoking {@link Observer#onError onError} if it encounters an error.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/onErrorResumeNext.png">
* <p>
* By default, when an Observable encounters an error that prevents it from emitting the expected item to
* its {@link Observer}, the Observable invokes its Observer's {@code onError} method, and then quits
* without invoking any more of its Observer's methods. The {@code onErrorResumeNext} method changes this
* behavior. If you pass another Observable ({@code resumeSequence}) to an Observable's {@code onErrorResumeNext} method, if the original Observable encounters an error, instead of invoking its
* Observer's {@code onError} method, it will instead relinquish control to {@code resumeSequence} which
* will invoke the Observer's {@link Observer#onNext onNext} method if it is able to do so. In such a case,
* because no Observable necessarily invokes {@code onError}, the Observer may never know that an error
* happened.
* <p>
* You can use this to prevent errors from propagating or to supply fallback data should errors be
* encountered.
*
* @param resumeSequence
* a function that returns an Observable that will take over if the source Observable encounters
* an error
* @return the original Observable, with appropriately modified behavior
* @see <a href="https://github.com/Netflix/RxJava/wiki/Error-Handling-Operators#wiki-onerrorresumenext">RxJava Wiki: onErrorResumeNext()</a>
*/
public final Observable<T> onErrorResumeNext(final Observable<? extends T> resumeSequence) {
return lift(new OperatorOnErrorResumeNextViaObservable<T>(resumeSequence));
}
/**
* Instruct an Observable to emit an item (returned by a specified function) rather than invoking {@link Observer#onError onError} if it encounters an error.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/onErrorReturn.png">
* <p>
* By default, when an Observable encounters an error that prevents it from emitting the expected item to
* its {@link Observer}, the Observable invokes its Observer's {@code onError} method, and then quits
* without invoking any more of its Observer's methods. The {@code onErrorReturn} method changes this
* behavior. If you pass a function ({@code resumeFunction}) to an Observable's {@code onErrorReturn} method, if the original Observable encounters an error, instead of invoking its Observer's
* {@code onError} method, it will instead emit the return value of {@code resumeFunction}.
* <p>
* You can use this to prevent errors from propagating or to supply fallback data should errors be
* encountered.
*
* @param resumeFunction
* a function that returns an item that the new Observable will emit if the source Observable
* encounters an error
* @return the original Observable with appropriately modified behavior
* @see <a href="https://github.com/Netflix/RxJava/wiki/Error-Handling-Operators#wiki-onerrorreturn">RxJava Wiki: onErrorReturn()</a>
*/
public final Observable<T> onErrorReturn(Func1<Throwable, ? extends T> resumeFunction) {
return lift(new OperatorOnErrorReturn<T>(resumeFunction));
}
/**
* Allows inserting onNext events into a stream when onError events are received and continuing the original
* sequence instead of terminating. Thus it allows a sequence with multiple onError events.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/onErrorFlatMap.png">
*
* @param resumeFunction
* a function that accepts an {@link OnErrorThrowable} representing the Throwable issued by the
* source Observable, and returns an Observable that issues items that will be emitted in place
* of the error
* @return the original Observable, with appropriately modified behavior
* @see <a href="https://github.com/Netflix/RxJava/wiki/Error-Handling-Operators#onerrorflatmap">RxJava Wiki: onErrorFlatMap()</a>
* @since 0.17
*/
public final Observable<T> onErrorFlatMap(final Func1<OnErrorThrowable, ? extends Observable<? extends T>> resumeFunction) {
return lift(new OperatorOnErrorFlatMap<T>(resumeFunction));
}
/**
* Instruct an Observable to pass control to another Observable rather than invoking {@link Observer#onError onError} if it encounters an {@link java.lang.Exception}.
* <p>
* This differs from {@link #onErrorResumeNext} in that this one does not handle {@link java.lang.Throwable} or {@link java.lang.Error} but lets those continue through.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/onExceptionResumeNextViaObservable.png">
* <p>
* By default, when an Observable encounters an exception that prevents it from emitting the expected item
* to its {@link Observer}, the Observable invokes its Observer's {@code onError} method, and then quits
* without invoking any more of its Observer's methods. The {@code onExceptionResumeNext} method changes
* this behavior. If you pass another Observable ({@code resumeSequence}) to an Observable's {@code onExceptionResumeNext} method, if the original Observable encounters an exception, instead of
* invoking its Observer's {@code onError} method, it will instead relinquish control to {@code resumeSequence} which will invoke the Observer's {@link Observer#onNext onNext} method if it is
* able to do so. In such a case, because no Observable necessarily invokes {@code onError}, the Observer
* may never know that an exception happened.
* <p>
* You can use this to prevent exceptions from propagating or to supply fallback data should exceptions be
* encountered.
*
* @param resumeSequence
* a function that returns an Observable that will take over if the source Observable encounters
* an exception
* @return the original Observable, with appropriately modified behavior
* @see <a href="https://github.com/Netflix/RxJava/wiki/Error-Handling-Operators#wiki-onexceptionresumenext">RxJava Wiki: onExceptionResumeNext()</a>
*/
public final Observable<T> onExceptionResumeNext(final Observable<? extends T> resumeSequence) {
return lift(new OperatorOnExceptionResumeNextViaObservable<T>(resumeSequence));
}
/**
* Perform work on the source {@code Observable<T>} in parallel by sharding it on a {@link Schedulers#computation()} {@link Scheduler}, and return the resulting {@code Observable<R>}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/parallel.png">
*
* @param f
* a {@link Func1} that applies Observable Observers to {@code Observable<T>} in parallel and
* returns an {@code Observable<R>}
* @return an Observable that emits the results of applying {@code f} to the items emitted by the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-parallel">RxJava Wiki: parallel()</a>
*/
public final <R> Observable<R> parallel(Func1<Observable<T>, Observable<R>> f) {
return lift(new OperatorParallel<T, R>(f, Schedulers.computation()));
}
/**
* Perform work on the source {@code Observable<T>} in parallel by sharding it on a {@link Scheduler}, and
* return the resulting {@code Observable<R>}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/parallel.png">
*
* @param f
* a {@link Func1} that applies Observable Observers to {@code Observable<T>} in parallel and
* returns an {@code Observable<R>}
* @param s
* a {@link Scheduler} to perform the work on
* @return an Observable that emits the results of applying {@code f} to the items emitted by the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-parallel">RxJava Wiki: parallel()</a>
*/
public final <R> Observable<R> parallel(final Func1<Observable<T>, Observable<R>> f, final Scheduler s) {
return lift(new OperatorParallel<T, R>(f, s));
}
/**
* Returns a {@link ConnectableObservable}, which waits until its
* {@link ConnectableObservable#connect connect} method is called before it begins emitting items to those
* {@link Observer}s that have subscribed to it.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/publishConnect.png">
*
* @return a {@link ConnectableObservable} that upon connection causes the source Observable to emit items
* to its {@link Observer}s
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablepublish-and-observablemulticast">RxJava Wiki: publish()</a>
*/
public final ConnectableObservable<T> publish() {
return new OperatorMulticast<T, T>(this, PublishSubject.<T> create());
}
/**
* Returns an Observable that emits the results of invoking a specified selector on items emitted by a {@link ConnectableObservable} that shares a single subscription to the underlying sequence.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/publishConnect.f.png">
*
* @param <R>
* the type of items emitted by the resulting Observable
* @param selector
* a function that can use the multicasted source sequence as many times as needed, without
* causing multiple subscriptions to the source sequence. Subscribers to the given source will
* receive all notifications of the source from the time of the subscription forward.
* @return an Observable that emits the results of invoking the selector on the items emitted by a {@link ConnectableObservable} that shares a single subscription to the underlying sequence
*/
public final <R> Observable<R> publish(Func1<? super Observable<T>, ? extends Observable<R>> selector) {
return multicast(new Func0<Subject<T, T>>() {
@Override
public final Subject<T, T> call() {
return PublishSubject.create();
}
}, selector);
}
/**
* Returns an Observable that emits {@code initialValue} followed by the results of invoking a specified
* selector on items emitted by a {@link ConnectableObservable} that shares a single subscription to the
* source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/publishConnect.if.png">
*
* @param <R>
* the type of items emitted by the resulting Observable
* @param selector
* a function that can use the multicasted source sequence as many times as needed, without
* causing multiple subscriptions to the source Observable. Subscribers to the source will
* receive all notifications of the source from the time of the subscription forward
* @param initialValue
* the initial value of the underlying {@link BehaviorSubject}
* @return an Observable that emits {@code initialValue} followed by the results of invoking the selector
* on a {@link ConnectableObservable} that shares a single subscription to the underlying Observable
*/
public final <R> Observable<R> publish(Func1<? super Observable<T>, ? extends Observable<R>> selector, final T initialValue) {
return multicast(new Func0<Subject<T, T>>() {
@Override
public final Subject<T, T> call() {
return BehaviorSubject.create(initialValue);
}
}, selector);
}
/**
* Returns a {@link ConnectableObservable} that emits {@code initialValue} followed by the items emitted by
* the source Observable. A Connectable Observable resembles an ordinary Observable, except that it does not
* begin emitting items when it is subscribed to, but only when its <code>connect()</code> method is called.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/publishConnect.i.png">
*
* @param initialValue
* the initial value to be emitted by the resulting Observable
* @return a {@link ConnectableObservable} that shares a single subscription to the underlying Observable
* and starts with {@code initialValue}
*/
public final ConnectableObservable<T> publish(T initialValue) {
return new OperatorMulticast<T, T>(this, BehaviorSubject.<T> create(initialValue));
}
/**
* Returns a {@link ConnectableObservable} that emits only the last item emitted by the source Observable.
* A Connectable Observable resembles an ordinary Observable, except that it does not begin emitting items
* when it is subscribed to, but only when its <code>connect()</code> method is called.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/publishLast.png">
*
* @return a {@link ConnectableObservable} that emits only the last item emitted by the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablepublishlast">RxJava Wiki: publishLast()</a>
*/
public final ConnectableObservable<T> publishLast() {
return new OperatorMulticast<T, T>(this, AsyncSubject.<T> create());
}
/**
* Returns an Observable that emits an item that results from invoking a specified selector on the last item
* emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/publishLast.f.png">
*
* @param <R>
* the type of items emitted by the resulting Observable
* @param selector
* a function that can use the multicasted source sequence as many times as needed, without
* causing multiple subscriptions to the source Observable. Subscribers to the source will only
* receive the last item emitted by the source.
* @return an Observable that emits an item that is the result of invoking the selector on a {@link ConnectableObservable} that shares a single subscription to the source Observable
*/
public final <R> Observable<R> publishLast(Func1<? super Observable<T>, ? extends Observable<R>> selector) {
return multicast(new Func0<Subject<T, T>>() {
@Override
public final Subject<T, T> call() {
return AsyncSubject.create();
}
}, selector);
}
/**
* Returns an Observable that applies a function of your choosing to the first item emitted by a source
* Observable, then feeds the result of that function along with the second item emitted by the source
* Observable into the same function, and so on until all items have been emitted by the source Observable,
* and emits the final result from the final call to your function as its sole item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/reduce.png">
* <p>
* This technique, which is called "reduce" here, is sometimes called "aggregate," "fold," "accumulate,"
* "compress," or "inject" in other programming contexts. Groovy, for instance, has an {@code inject()} method that does a similar operation on lists.
*
* @param accumulator
* an accumulator function to be invoked on each item emitted by the source Observable, whose
* result will be used in the next accumulator call
* @return an Observable that emits a single item that is the result of accumulating the items emitted by
* the source Observable
* @throws IllegalArgumentException
* if the source Observable emits no items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-reduce">RxJava Wiki: reduce()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229154.aspx">MSDN: Observable.Aggregate</a>
* @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a>
*/
public final Observable<T> reduce(Func2<T, T, T> accumulator) {
/*
* Discussion and confirmation of implementation at
* https://github.com/Netflix/RxJava/issues/423#issuecomment-27642532
*
* It should use last() not takeLast(1) since it needs to emit an error if the sequence is empty.
*/
return scan(accumulator).last();
}
/**
* Returns an Observable that applies a function of your choosing to the first item emitted by a source
* Observable and a specified seed value, then feeds the result of that function along with the second item
* emitted by an Observable into the same function, and so on until all items have been emitted by the
* source Observable, emitting the final result from the final call to your function as its sole item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/reduceSeed.png">
* <p>
* This technique, which is called "reduce" here, is sometimec called "aggregate," "fold," "accumulate,"
* "compress," or "inject" in other programming contexts. Groovy, for instance, has an {@code inject()} method that does a similar operation on lists.
*
* @param initialValue
* the initial (seed) accumulator value
* @param accumulator
* an accumulator function to be invoked on each item emitted by the source Observable, the
* result of which will be used in the next accumulator call
* @return an Observable that emits a single item that is the result of accumulating the output from the
* items emitted by the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-reduce">RxJava Wiki: reduce()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229154.aspx">MSDN: Observable.Aggregate</a>
* @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a>
*/
public final <R> Observable<R> reduce(R initialValue, Func2<R, ? super T, R> accumulator) {
return scan(initialValue, accumulator).takeLast(1);
}
/**
* Returns an Observable that repeats the sequence of items emitted by the source Observable indefinitely.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/repeat.o.png">
*
* @return an Observable that emits the items emitted by the source Observable repeatedly and in sequence
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-repeat">RxJava Wiki: repeat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229428.aspx">MSDN: Observable.Repeat</a>
*/
public final Observable<T> repeat() {
return nest().lift(new OperatorRepeat<T>());
}
/**
* Returns an Observable that repeats the sequence of items emitted by the source Observable indefinitely,
* on a particular Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/repeat.os.png">
*
* @param scheduler
* the Scheduler to emit the items on
* @return an Observable that emits the items emitted by the source Observable repeatedly and in sequence
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-repeat">RxJava Wiki: repeat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229428.aspx">MSDN: Observable.Repeat</a>
*/
public final Observable<T> repeat(Scheduler scheduler) {
return nest().lift(new OperatorRepeat<T>(scheduler));
}
/**
* Returns an Observable that repeats the sequence of items emitted by the source Observable at most {@code count} times.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/repeat.on.png">
*
* @param count
* the number of times the source Observable items are repeated, a count of 0 will yield an empty
* sequence
* @return an Observable that repeats the sequence of items emitted by the source Observable at most {@code count} times
* @throws IllegalArgumentException
* if {@code count} is less than zero
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-repeat">RxJava Wiki: repeat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229428.aspx">MSDN: Observable.Repeat</a>
* @since 0.17
*/
public final Observable<T> repeat(long count) {
if (count < 0) {
throw new IllegalArgumentException("count >= 0 expected");
}
return nest().lift(new OperatorRepeat<T>(count));
}
/**
* Returns an Observable that repeats the sequence of items emitted by the source Observable at most {@code count} times, on a particular Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/repeat.ons.png">
*
* @param count
* the number of times the source Observable items are repeated, a count of 0 will yield an empty
* sequence
* @param scheduler
* the {@link Scheduler} to emit the items on
* @return an Observable that repeats the sequence of items emitted by the source Observable at most {@code count} times on a particular Scheduler
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-repeat">RxJava Wiki: repeat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229428.aspx">MSDN: Observable.Repeat</a>
* @since 0.17
*/
public final Observable<T> repeat(long count, Scheduler scheduler) {
return nest().lift(new OperatorRepeat<T>(count, scheduler));
}
/**
* Returns a {@link ConnectableObservable} that shares a single subscription to the underlying Observable
* that will replay all of its items and notifications to any future {@link Observer}. A Connectable
* Observable resembles an ordinary Observable, except that it does not begin emitting items when it is
* subscribed to, but only when its <code>connect()</code> method is called.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.png">
*
* @return a {@link ConnectableObservable} that upon connection causes the source Observable to emit its
* items to its {@link Observer}s
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
*/
public final ConnectableObservable<T> replay() {
return new OperatorMulticast<T, T>(this, ReplaySubject.<T> create());
}
/**
* Returns an Observable that emits items that are the results of invoking a specified selector on the items
* emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.f.png">
*
* @param <R>
* the type of items emitted by the resulting Observable
* @param selector
* the selector function, which can use the multicasted sequence as many times as needed, without
* causing multiple subscriptions to the Observable
* @return an Observable that emits items that are the results of invoking the selector on a {@link ConnectableObservable} that shares a single subscription to the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229653.aspx">MSDN: Observable.Replay</a>
*/
public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector) {
return create(new OperatorMulticastSelector<T, T, R>(this, new Func0<Subject<T, T>>() {
@Override
public final Subject<T, T> call() {
return ReplaySubject.create();
}
}, selector));
}
/**
* Returns an Observable that emits items that are the results of invoking a specified selector on items
* emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable,
* replaying {@code bufferSize} notifications.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.fn.png">
*
* @param <R>
* the type of items emitted by the resulting Observable
* @param selector
* the selector function, which can use the multicasted sequence as many times as needed, without
* causing multiple subscriptions to the Observable
* @param bufferSize
* the buffer size that limits the number of items the connectable observable can replay
* @return an Observable that emits items that are the results of invoking the selector on items emitted by
* a {@link ConnectableObservable} that shares a single subscription to the source Observable
* replaying no more than {@code bufferSize} items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211675.aspx">MSDN: Observable.Replay</a>
*/
public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, final int bufferSize) {
return create(new OperatorMulticastSelector<T, T, R>(this, new Func0<Subject<T, T>>() {
@Override
public final Subject<T, T> call() {
return ReplaySubject.<T>createWithSize(bufferSize);
}
}, selector));
}
/**
* Returns an Observable that emits items that are the results of invoking a specified selector on items
* emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable,
* replaying no more than {@code bufferSize} items that were emitted within a specified time window.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.fnt.png">
*
* @param <R>
* the type of items emitted by the resulting Observable
* @param selector
* a selector function, which can use the multicasted sequence as many times as needed, without
* causing multiple subscriptions to the Observable
* @param bufferSize
* the buffer size that limits the number of items the connectable observable can replay
* @param time
* the duration of the window in which the replayed items must have been emitted
* @param unit
* the time unit of {@code time}
* @return an Observable that emits items that are the results of invoking the selector on items emitted by
* a {@link ConnectableObservable} that shares a single subscription to the source Observable, and
* replays no more than {@code bufferSize} items that were emitted within the window defined by {@code time}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh228952.aspx">MSDN: Observable.Replay</a>
*/
public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, int bufferSize, long time, TimeUnit unit) {
return replay(selector, bufferSize, time, unit, Schedulers.computation());
}
/**
* Returns an Observable that emits items that are the results of invoking a specified selector on items
* emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable,
* replaying no more than {@code bufferSize} items that were emitted within a specified time window.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.fnts.png">
*
* @param <R>
* the type of items emitted by the resulting Observable
* @param selector
* a selector function, which can use the multicasted sequence as many times as needed, without
* causing multiple subscriptions to the Observable
* @param bufferSize
* the buffer size that limits the number of items the connectable observable can replay
* @param time
* the duration of the window in which the replayed items must have been emitted
* @param unit
* the time unit of {@code time}
* @param scheduler
* the Scheduler that is the time source for the window
* @return an Observable that emits items that are the results of invoking the selector on items emitted by
* a {@link ConnectableObservable} that shares a single subscription to the source Observable, and
* replays no more than {@code bufferSize} items that were emitted within the window defined by {@code time}
* @throws IllegalArgumentException
* if {@code bufferSize} is less than zero
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229404.aspx">MSDN: Observable.Replay</a>
*/
public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, final int bufferSize, final long time, final TimeUnit unit, final Scheduler scheduler) {
if (bufferSize < 0) {
throw new IllegalArgumentException("bufferSize < 0");
}
return create(new OperatorMulticastSelector<T, T, R>(this, new Func0<Subject<T, T>>() {
@Override
public final Subject<T, T> call() {
return ReplaySubject.<T>createWithTimeAndSize(time, unit, bufferSize, scheduler);
}
}, selector));
}
/**
* Returns an Observable that emits items that are the results of invoking a specified selector on items
* emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable,
* replaying a maximum of {@code bufferSize} items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.fns.png">
*
* @param <R>
* the type of items emitted by the resulting Observable
* @param selector
* a selector function, which can use the multicasted sequence as many times as needed, without
* causing multiple subscriptions to the Observable
* @param bufferSize
* the buffer size that limits the number of items the connectable observable can replay
* @param scheduler
* the Scheduler on which the replay is observed
* @return an Observable that emits items that are the results of invoking the selector on items emitted by
* a {@link ConnectableObservable} that shares a single subscription to the source Observable,
* replaying no more than {@code bufferSize} notifications
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229928.aspx">MSDN: Observable.Replay</a>
*/
public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, final int bufferSize, final Scheduler scheduler) {
return create(new OperatorMulticastSelector<T, T, R>(this, new Func0<Subject<T, T>>() {
@Override
public final Subject<T, T> call() {
return OperatorReplay.<T> createScheduledSubject(ReplaySubject.<T>createWithSize(bufferSize), scheduler);
}
}, selector));
}
/**
* Returns an Observable that emits items that are the results of invoking a specified selector on items
* emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable,
* replaying all items that were emitted within a specified time window.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.ft.png">
*
* @param <R>
* the type of items emitted by the resulting Observable
* @param selector
* a selector function, which can use the multicasted sequence as many times as needed, without
* causing multiple subscriptions to the Observable
* @param time
* the duration of the window in which the replayed items must have been emitted
* @param unit
* the time unit of {@code time}
* @return an Observable that emits items that are the results of invoking the selector on items emitted by
* a {@link ConnectableObservable} that shares a single subscription to the source Observable,
* replaying all items that were emitted within the window defined by {@code time}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229526.aspx">MSDN: Observable.Replay</a>
*/
public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, long time, TimeUnit unit) {
return replay(selector, time, unit, Schedulers.computation());
}
/**
* Returns an Observable that emits items that are the results of invoking a specified selector on items
* emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable,
* replaying all items that were emitted within a specified time window.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.fts.png">
*
* @param <R>
* the type of items emitted by the resulting Observable
* @param selector
* a selector function, which can use the multicasted sequence as many times as needed, without
* causing multiple subscriptions to the Observable
* @param time
* the duration of the window in which the replayed items must have been emitted
* @param unit
* the time unit of {@code time}
* @param scheduler
* the scheduler that is the time source for the window
* @return an Observable that emits items that are the results of invoking the selector on items emitted by
* a {@link ConnectableObservable} that shares a single subscription to the source Observable,
* replaying all items that were emitted within the window defined by {@code time}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh244327.aspx">MSDN: Observable.Replay</a>
*/
public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, final long time, final TimeUnit unit, final Scheduler scheduler) {
return create(new OperatorMulticastSelector<T, T, R>(this, new Func0<Subject<T, T>>() {
@Override
public final Subject<T, T> call() {
return ReplaySubject.<T>createWithTime(time, unit, scheduler);
}
}, selector));
}
/**
* Returns an Observable that emits items that are the results of invoking a specified selector on items
* emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.fs.png">
*
* @param <R>
* the type of items emitted by the resulting Observable
* @param selector
* a selector function, which can use the multicasted sequence as many times as needed, without
* causing multiple subscriptions to the Observable
* @param scheduler
* the Scheduler where the replay is observed
* @return an Observable that emits items that are the results of invoking the selector on items emitted by
* a {@link ConnectableObservable} that shares a single subscription to the source Observable,
* replaying all items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211644.aspx">MSDN: Observable.Replay</a>
*/
public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, final Scheduler scheduler) {
return create(new OperatorMulticastSelector<T, T, R>(this, new Func0<Subject<T, T>>() {
@Override
public final Subject<T, T> call() {
return OperatorReplay.createScheduledSubject(ReplaySubject.<T> create(), scheduler);
}
}, selector));
}
/**
* Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable that
* replays at most {@code bufferSize} items emitted by that Observable. A Connectable Observable resembles
* an ordinary Observable, except that it does not begin emitting items when it is subscribed to, but only
* when its <code>connect()</code> method is called.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.n.png">
*
* @param bufferSize
* the buffer size that limits the number of items that can be replayed
* @return a {@link ConnectableObservable} that shares a single subscription to the source Observable and
* replays at most {@code bufferSize} items emitted by that Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211976.aspx">MSDN: Observable.Replay</a>
*/
public final ConnectableObservable<T> replay(int bufferSize) {
return new OperatorMulticast<T, T>(this, ReplaySubject.<T>createWithSize(bufferSize));
}
/**
* Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable and
* replays at most {@code bufferSize} items that were emitted during a specified time window. A Connectable
* Observable resembles an ordinary Observable, except that it does not begin emitting items when it is
* subscribed to, but only when its <code>connect()</code> method is called.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.nt.png">
*
* @param bufferSize
* the buffer size that limits the number of items that can be replayed
* @param time
* the duration of the window in which the replayed items must have been emitted
* @param unit
* the time unit of {@code time}
* @return a {@link ConnectableObservable} that shares a single subscription to the source Observable and
* replays at most {@code bufferSize} items that were emitted during the window defined by {@code time}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229874.aspx">MSDN: Observable.Replay</a>
*/
public final ConnectableObservable<T> replay(int bufferSize, long time, TimeUnit unit) {
return replay(bufferSize, time, unit, Schedulers.computation());
}
/**
* Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable and
* that replays a maximum of {@code bufferSize} items that are emitted within a specified time window. A
* Connectable Observable resembles an ordinary Observable, except that it does not begin emitting items
* when it is subscribed to, but only when its <code>connect()</code> method is called.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.nts.png">
*
* @param bufferSize
* the buffer size that limits the number of items that can be replayed
* @param time
* the duration of the window in which the replayed items must have been emitted
* @param unit
* the time unit of {@code time}
* @param scheduler
* the scheduler that is used as a time source for the window
* @return a {@link ConnectableObservable} that shares a single subscription to the source Observable and
* replays at most {@code bufferSize} items that were emitted during the window defined by {@code time}
* @throws IllegalArgumentException
* if {@code bufferSize} is less than zero
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211759.aspx">MSDN: Observable.Replay</a>
*/
public final ConnectableObservable<T> replay(int bufferSize, long time, TimeUnit unit, Scheduler scheduler) {
if (bufferSize < 0) {
throw new IllegalArgumentException("bufferSize < 0");
}
return new OperatorMulticast<T, T>(this, ReplaySubject.<T>createWithTimeAndSize(time, unit, bufferSize, scheduler));
}
/**
* Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable and
* replays at most {@code bufferSize} items emitted by that Observable. A Connectable Observable resembles
* an ordinary Observable, except that it does not begin emitting items when it is subscribed to, but only
* when its <code>connect()</code> method is called.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.ns.png">
*
* @param bufferSize
* the buffer size that limits the number of items that can be replayed
* @param scheduler
* the scheduler on which the Observers will observe the emitted items
* @return a {@link ConnectableObservable} that shares a single subscription to the source Observable and
* replays at most {@code bufferSize} items that were emitted by the Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229814.aspx">MSDN: Observable.Replay</a>
*/
public final ConnectableObservable<T> replay(int bufferSize, Scheduler scheduler) {
return new OperatorMulticast<T, T>(this,
OperatorReplay.createScheduledSubject(
ReplaySubject.<T>createWithSize(bufferSize), scheduler));
}
/**
* Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable and
* replays all items emitted by that Observable within a specified time window. A Connectable Observable
* resembles an ordinary Observable, except that it does not begin emitting items when it is subscribed to,
* but only when its <code>connect()</code> method is called.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.t.png">
*
* @param time
* the duration of the window in which the replayed items must have been emitted
* @param unit
* the time unit of {@code time}
* @return a {@link ConnectableObservable} that shares a single subscription to the source Observable and
* replays the items that were emitted during the window defined by {@code time}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229232.aspx">MSDN: Observable.Replay</a>
*/
public final ConnectableObservable<T> replay(long time, TimeUnit unit) {
return replay(time, unit, Schedulers.computation());
}
/**
* Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable and
* replays all items emitted by that Observable within a specified time window. A Connectable Observable
* resembles an ordinary Observable, except that it does not begin emitting items when it is subscribed to,
* but only when its <code>connect()</code> method is called.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.ts.png">
*
* @param time
* the duration of the window in which the replayed items must have been emitted
* @param unit
* the time unit of {@code time}
* @param scheduler
* the Scheduler that is the time source for the window
* @return a {@link ConnectableObservable} that shares a single subscription to the source Observable and
* replays the items that were emitted during the window defined by {@code time}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211811.aspx">MSDN: Observable.Replay</a>
*/
public final ConnectableObservable<T> replay(long time, TimeUnit unit, Scheduler scheduler) {
return new OperatorMulticast<T, T>(this, ReplaySubject.<T>createWithTime(time, unit, scheduler));
}
/**
* Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable that
* will replay all of its items and notifications to any future {@link Observer} on the given
* {@link Scheduler}. A Connectable Observable resembles an ordinary Observable, except that it does not
* begin emitting items when it is subscribed to, but only when its <code>connect()</code> method is called.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.s.png">
*
* @param scheduler
* the Scheduler on which the Observers will observe the emitted items
* @return a {@link ConnectableObservable} that shares a single subscription to the source Observable that
* will replay all of its items and notifications to any future {@link Observer} on the given {@link Scheduler}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#wiki-observablereplay">RxJava Wiki: replay()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211699.aspx">MSDN: Observable.Replay</a>
*/
public final ConnectableObservable<T> replay(Scheduler scheduler) {
return new OperatorMulticast<T, T>(this, OperatorReplay.createScheduledSubject(ReplaySubject.<T> create(), scheduler));
}
/**
* Return an Observable that mirrors the source Observable, resubscribing to it if it calls {@code onError} (infinite retry count).
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/retry.png">
* <p>
* If the source Observable calls {@link Observer#onError}, this method will resubscribe to the source
* Observable rather than propagating the {@code onError} call.
* <p>
* Any and all items emitted by the source Observable will be emitted by the resulting Observable, even
* those emitted during failed subscriptions. For example, if an Observable fails at first but emits {@code [1, 2]} then succeeds the second time and emits {@code [1, 2, 3, 4, 5]} then the
* complete sequence
* of emissions and notifications would be {@code [1, 2, 1, 2, 3, 4, 5, onCompleted]}.
*
* @return the source Observable modified with retry logic
* @see <a href="https://github.com/Netflix/RxJava/wiki/Error-Handling-Operators#wiki-retry">RxJava Wiki: retry()</a>
*/
public final Observable<T> retry() {
return nest().lift(new OperatorRetry<T>());
}
/**
* Return an Observable that mirrors the source Observable, resubscribing to it if it calls {@code onError} up to a specified number of retries.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/retry.png">
* <p>
* If the source Observable calls {@link Observer#onError}, this method will resubscribe to the source
* Observable for a maximum of {@code retryCount} resubscriptions rather than propagating the {@code onError} call.
* <p>
* Any and all items emitted by the source Observable will be emitted by the resulting Observable, even
* those emitted during failed subscriptions. For example, if an Observable fails at first but emits {@code [1, 2]} then succeeds the second time and emits {@code [1, 2, 3, 4, 5]} then the
* complete sequence
* of emissions and notifications would be {@code [1, 2, 1, 2, 3, 4, 5, onCompleted]}.
*
* @param retryCount
* number of retry attempts before failing
* @return the source Observable modified with retry logic
* @see <a href="https://github.com/Netflix/RxJava/wiki/Error-Handling-Operators#wiki-retry">RxJava Wiki: retry()</a>
*/
public final Observable<T> retry(int retryCount) {
return nest().lift(new OperatorRetry<T>(retryCount));
}
/**
* Returns an Observable that emits the most recently emitted item (if any) emitted by the source Observable
* within periodic time intervals.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/sample.png">
*
* @param period
* the sampling rate
* @param unit
* the {@link TimeUnit} in which {@code period} is defined
* @return an Observable that emits the results of sampling the items emitted by the source Observable at
* the specified time interval
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-sample-or-throttlelast">RxJava Wiki: sample()</a>
*/
public final Observable<T> sample(long period, TimeUnit unit) {
return lift(new OperatorSampleWithTime<T>(period, unit, Schedulers.computation()));
}
/**
* Returns an Observable that emits the most recently emitted item (if any) emitted by the source Observable
* within periodic time intervals, where the intervals are defined on a particular Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/sample.s.png">
*
* @param period
* the sampling rate
* @param unit
* the {@link TimeUnit} in which {@code period} is defined
* @param scheduler
* the {@link Scheduler} to use when sampling
* @return an Observable that emits the results of sampling the items emitted by the source Observable at
* the specified time interval
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-sample-or-throttlelast">RxJava Wiki: sample()</a>
*/
public final Observable<T> sample(long period, TimeUnit unit, Scheduler scheduler) {
return lift(new OperatorSampleWithTime<T>(period, unit, scheduler));
}
/**
* Returns an Observable that, when the specified {@code sampler} Observable emits an item or completes,
* emits the most recently emitted item (if any) emitted by the source Observable since the previous
* emission from the {@code sampler} Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/sample.o.png">
*
* @param sampler
* the Observable to use for sampling the source Observable
* @return an Observable that emits the results of sampling the items emitted by this Observable whenever
* the {@code sampler} Observable emits an item or completes
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-sample-or-throttlelast">RxJava Wiki: sample()</a>
*/
public final <U> Observable<T> sample(Observable<U> sampler) {
return lift(new OperatorSampleWithObservable<T, U>(sampler));
}
/**
* Returns an Observable that applies a function of your choosing to the first item emitted by a source
* Observable, then feeds the result of that function along with the second item emitted by the source
* Observable into the same function, and so on until all items have been emitted by the source Observable,
* emitting the result of each of these iterations.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/scan.png">
* <p>
* This sort of function is sometimes called an accumulator.
*
* @param accumulator
* an accumulator function to be invoked on each item emitted by the source Observable, whose
* result will be emitted to {@link Observer}s via {@link Observer#onNext onNext} and used in the
* next accumulator call
* @return an Observable that emits the results of each call to the accumulator function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-scan">RxJava Wiki: scan()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211665.aspx">MSDN: Observable.Scan</a>
*/
public final Observable<T> scan(Func2<T, T, T> accumulator) {
return lift(new OperatorScan<T, T>(accumulator));
}
/**
* Returns an Observable that applies a function of your choosing to the first item emitted by a source
* Observable and a seed value, then feeds the result of that function along with the second item emitted by
* the source Observable into the same function, and so on until all items have been emitted by the source
* Observable, emitting the result of each of these iterations.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/scanSeed.png">
* <p>
* This sort of function is sometimes called an accumulator.
* <p>
* Note that the Observable that results from this method will emit {@code initialValue} as its first
* emitted item.
*
* @param initialValue
* the initial (seed) accumulator item
* @param accumulator
* an accumulator function to be invoked on each item emitted by the source Observable, whose
* result will be emitted to {@link Observer}s via {@link Observer#onNext onNext} and used in the
* next accumulator call
* @return an Observable that emits {@code initialValue} followed by the results of each call to the
* accumulator function
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-scan">RxJava Wiki: scan()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211665.aspx">MSDN: Observable.Scan</a>
*/
public final <R> Observable<R> scan(R initialValue, Func2<R, ? super T, R> accumulator) {
return lift(new OperatorScan<R, T>(initialValue, accumulator));
}
/*
* Forces an Observable to make synchronous calls and to be well-behaved.
* <p>
* It is possible for an Observable to invoke its Subscribers' methods asynchronously, perhaps in different
* threads. This could make an Observable poorly-behaved, in that it might invoke {@code onCompleted} or
* {@code onError} before one of its {@code onNext} invocations. You can force such an Observable to be
* well-behaved and synchronous by applying the {@code serialize()} method to it.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/synchronize.png">
*
* @return a {@link Observable} that is guaranteed to be well-behaved and synchronous
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#serialize">RxJava Wiki: serialize()</a>
* @since 0.17
*/
public final Observable<T> serialize() {
return lift(new OperatorSerialize<T>());
}
/**
* Returns a new {@link Observable} that multicasts (shares) the original {@link Observable}. As long as
* there is more than 1 {@link Subscriber} this {@link Observable} will be subscribed and emitting data.
* When all subscribers have unsubscribed it will unsubscribe from the source {@link Observable}.
* <p>
* This is an alias for {@link #publish().refCount()}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/publishRefCount.png">
*
* @return a {@link Observable} that upon connection causes the source Observable to emit items
* to its {@link Observer}s
* @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#connectableobservablerefcount">RxJava Wiki: refCount()</a>
* @since 0.19
*/
public final Observable<T> share() {
return publish().refCount();
}
/**
* If the source Observable completes after emitting a single item, return an Observable that emits that
* item. If the source Observable emits more than one item or no items, throw an {@code NoSuchElementException}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/single.png">
*
* @return an Observable that emits the single item emitted by the source Observable
* @throws IllegalArgumentException
* if the source emits more than one item
* @throws NoSuchElementException
* if the source emits no items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-single-and-singleordefault">RxJava Wiki: single()</a>
* @see "MSDN: Observable.singleAsync()"
*/
public final Observable<T> single() {
return lift(new OperatorSingle<T>());
}
/**
* If the Observable completes after emitting a single item that matches a specified predicate, return an
* Observable that emits that item. If the source Observable emits more than one such item or no such items,
* throw an {@code NoSuchElementException}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/single.p.png">
*
* @param predicate
* a predicate function to evaluate items emitted by the source Observable
* @return an Observable that emits the single item emitted by the source Observable that matches the
* predicate
* @throws IllegalArgumentException
* if the source Observable emits more than one item that matches the predicate
* @throws NoSuchElementException
* if the source Observable emits no item that matches the predicate
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-single-and-singleordefault">RxJava Wiki: single()</a>
* @see "MSDN: Observable.singleAsync()"
*/
public final Observable<T> single(Func1<? super T, Boolean> predicate) {
return filter(predicate).single();
}
/**
* If the source Observable completes after emitting a single item, return an Observable that emits that
* item; if the source Observable is empty, return an Observable that emits a default item. If the source
* Observable emits more than one item, throw an {@code IllegalArgumentException.} <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/singleOrDefault.png">
*
* @param defaultValue
* a default value to emit if the source Observable emits no item
* @return an Observable that emits the single item emitted by the source Observable, or a default item if
* the source Observable is empty
* @throws IllegalArgumentException
* if the source Observable emits more than one item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-single-and-singleordefault">RxJava Wiki: single()</a>
* @see "MSDN: Observable.singleOrDefaultAsync()"
*/
public final Observable<T> singleOrDefault(T defaultValue) {
return lift(new OperatorSingle<T>(defaultValue));
}
/**
* If the Observable completes after emitting a single item that matches a predicate, return an Observable
* that emits that item; if the source Observable emits no such item, return an Observable that emits a
* default item. If the source Observable emits more than one such item, throw an {@code IllegalArgumentException}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/singleOrDefault.p.png">
*
* @param defaultValue
* a default item to emit if the source Observable emits no matching items
* @param predicate
* a predicate function to evaluate items emitted by the source Observable
* @return an Observable that emits the single item emitted by the source Observable that matches the
* predicate, or the default item if no emitted item matches the predicate
* @throws IllegalArgumentException
* if the source Observable emits more than one item that matches the predicate
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-single-and-singleordefault">RxJava Wiki: single()</a>
* @see "MSDN: Observable.singleOrDefaultAsync()"
*/
public final Observable<T> singleOrDefault(T defaultValue, Func1<? super T, Boolean> predicate) {
return filter(predicate).singleOrDefault(defaultValue);
}
/**
* Returns an Observable that skips the first {@code num} items emitted by the source Observable and emits
* the remainder.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skip.png">
*
* @param num
* the number of items to skip
* @return an Observable that is identical to the source Observable except that it does not emit the first {@code num} items that the source Observable emits
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-skip">RxJava Wiki: skip()</a>
*/
public final Observable<T> skip(int num) {
return lift(new OperatorSkip<T>(num));
}
/**
* Returns an Observable that skips values emitted by the source Observable before a specified time window
* elapses.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skip.t.png">
*
* @param time
* the length of the time window to skip
* @param unit
* the time unit of {@code time}
* @return an Observable that skips values emitted by the source Observable before the time window defined
* by {@code time} elapses and the emits the remainder
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-skip">RxJava Wiki: skip()</a>
*/
public final Observable<T> skip(long time, TimeUnit unit) {
return skip(time, unit, Schedulers.computation());
}
/**
* Returns an Observable that skips values emitted by the source Observable before a specified time window
* on a specified {@link Scheduler} elapses.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skip.ts.png">
*
* @param time
* the length of the time window to skip
* @param unit
* the time unit of {@code time}
* @param scheduler
* the {@link Scheduler} on which the timed wait happens
* @return an Observable that skips values emitted by the source Observable before the time window defined
* by {@code time} and {@code scheduler} elapses, and then emits the remainder
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-skip">RxJava Wiki: skip()</a>
*/
public final Observable<T> skip(long time, TimeUnit unit, Scheduler scheduler) {
return lift(new OperatorSkipTimed<T>(time, unit, scheduler));
}
/**
* Returns an Observable that drops a specified number of items from the end of the sequence emitted by the
* source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skipLast.png">
* <p>
* This Observer accumulates a queue long enough to store the first {@code count} items. As more items are
* received, items are taken from the front of the queue and emitted by the returned Observable. This causes
* such items to be delayed.
*
* @param count
* number of items to drop from the end of the source sequence
* @return an Observable that emits the items emitted by the source Observable except for the dropped ones
* at the end
* @throws IndexOutOfBoundsException
* if {@code count} is less than zero
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-skiplast">RxJava Wiki: skipLast()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211750.aspx">MSDN: Observable.SkipLast</a>
*/
public final Observable<T> skipLast(int count) {
return lift(new OperatorSkipLast<T>(count));
}
/**
* Returns an Observable that drops items emitted by the source Observable during a specified time window
* before the source completes.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skipLast.t.png">
*
* Note: this action will cache the latest items arriving in the specified time window.
*
* @param time
* the length of the time window
* @param unit
* the time unit of {@code time}
* @return an Observable that drops those items emitted by the source Observable in a time window before the
* source completes defined by {@code time}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-skiplast">RxJava Wiki: skipLast()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211750.aspx">MSDN: Observable.SkipLast</a>
*/
public final Observable<T> skipLast(long time, TimeUnit unit) {
return skipLast(time, unit, Schedulers.computation());
}
/**
* Returns an Observable that drops items emitted by the source Observable during a specified time window
* (defined on a specified scheduler) before the source completes.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skipLast.ts.png">
*
* Note: this action will cache the latest items arriving in the specified time window.
*
* @param time
* the length of the time window
* @param unit
* the time unit of {@code time}
* @param scheduler
* the scheduler used as the time source
* @return an Observable that drops those items emitted by the source Observable in a time window before the
* source completes defined by {@code time} and {@code scheduler}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-skiplast">RxJava Wiki: skipLast()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211750.aspx">MSDN: Observable.SkipLast</a>
*/
public final Observable<T> skipLast(long time, TimeUnit unit, Scheduler scheduler) {
return lift(new OperatorSkipLastTimed<T>(time, unit, scheduler));
}
/**
* Returns an Observable that skips items emitted by the source Observable until a second Observable emits
* an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skipUntil.png">
*
* @param other
* the second Observable that has to emit an item before the source Observable's elements begin
* to be mirrored by the resulting Observable
* @return an Observable that skips items from the source Observable until the second Observable emits an
* item, then emits the remaining items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-skipuntil">RxJava Wiki: skipUntil()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229358.aspx">MSDN: Observable.SkipUntil</a>
*/
public final <U> Observable<T> skipUntil(Observable<U> other) {
return lift(new OperatorSkipUntil<T, U>(other));
}
/**
* Returns an Observable that skips all items emitted by the source Observable as long as a specified
* condition holds true, but emits all further source items as soon as the condition becomes false.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skipWhile.png">
*
* @param predicate
* a function to test each item emitted from the source Observable
* @return an Observable that begins emitting items emitted by the source Observable when the specified
* predicate becomes false
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-skipwhile-and-skipwhilewithindex">RxJava Wiki: skipWhile()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229685.aspx">MSDN: Observable.SkipWhile</a>
*/
public final Observable<T> skipWhile(Func1<? super T, Boolean> predicate) {
return lift(new OperatorSkipWhile<T>(OperatorSkipWhile.toPredicate2(predicate)));
}
/**
* Returns an Observable that skips all items emitted by the source Observable as long as a specified
* condition holds true, but emits all further source items as soon as the condition becomes false.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skipWhileWithIndex.png">
*
* @param predicate
* a function to test each item emitted from the source Observable. It takes the emitted item as
* the first parameter and the sequential index of the emitted item as a second parameter.
* @return an Observable that begins emitting items emitted by the source Observable when the specified
* predicate becomes false
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-skipwhile-and-skipwhilewithindex">RxJava Wiki: skipWhileWithIndex()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211631.aspx">MSDN: Observable.SkipWhile</a>
*/
public final Observable<T> skipWhileWithIndex(Func2<? super T, Integer, Boolean> predicate) {
return lift(new OperatorSkipWhile<T>(predicate));
}
/**
* Returns an Observable that emits the items in a specified {@link Observable} before it begins to emit
* items emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.o.png">
*
* @param values
* an Observable that contains the items you want the modified Observable to emit first
* @return an Observable that emits the items in the specified {@link Observable} and then emits the items
* emitted by the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
*/
public final Observable<T> startWith(Observable<T> values) {
return concat(values, this);
}
/**
* Returns an Observable that emits the items in a specified {@link Iterable} before it begins to emit items
* emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png">
*
* @param values
* an Iterable that contains the items you want the modified Observable to emit first
* @return an Observable that emits the items in the specified {@link Iterable} and then emits the items
* emitted by the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
*/
public final Observable<T> startWith(Iterable<T> values) {
return concat(Observable.<T> from(values), this);
}
/**
* Returns an Observable that emits the items in a specified {@link Iterable}, on a specified {@link Scheduler}, before it begins to emit items emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.s.png">
*
* @param values
* an Iterable that contains the items you want the modified Observable to emit first
* @param scheduler
* the Scheduler to emit the prepended values on
* @return an Observable that emits the items in the specified {@link Iterable} and then emits the items
* emitted by the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229372.aspx">MSDN: Observable.StartWith</a>
*/
public final Observable<T> startWith(Iterable<T> values, Scheduler scheduler) {
return concat(from(values, scheduler), this);
}
/**
* Returns an Observable that emits a specified item before it begins to emit items emitted by the source
* Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png">
*
* @param t1
* the item to emit
* @return an Observable that emits the specified item before it begins to emit items emitted by the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
*/
public final Observable<T> startWith(T t1) {
return concat(Observable.<T> from(t1), this);
}
/**
* Returns an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png">
*
* @param t1
* the first item to emit
* @param t2
* the second item to emit
* @return an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
*/
public final Observable<T> startWith(T t1, T t2) {
return concat(Observable.<T> from(t1, t2), this);
}
/**
* Returns an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png">
*
* @param t1
* the first item to emit
* @param t2
* the second item to emit
* @param t3
* the third item to emit
* @return an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
*/
public final Observable<T> startWith(T t1, T t2, T t3) {
return concat(Observable.<T> from(t1, t2, t3), this);
}
/**
* Returns an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png">
*
* @param t1
* the first item to emit
* @param t2
* the second item to emit
* @param t3
* the third item to emit
* @param t4
* the fourth item to emit
* @return an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
*/
public final Observable<T> startWith(T t1, T t2, T t3, T t4) {
return concat(Observable.<T> from(t1, t2, t3, t4), this);
}
/**
* Returns an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png">
*
* @param t1
* the first item to emit
* @param t2
* the second item to emit
* @param t3
* the third item to emit
* @param t4
* the fourth item to emit
* @param t5
* the fifth item to emit
* @return an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
*/
public final Observable<T> startWith(T t1, T t2, T t3, T t4, T t5) {
return concat(Observable.<T> from(t1, t2, t3, t4, t5), this);
}
/**
* Returns an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png">
*
* @param t1
* the first item to emit
* @param t2
* the second item to emit
* @param t3
* the third item to emit
* @param t4
* the fourth item to emit
* @param t5
* the fifth item to emit
* @param t6
* the sixth item to emit
* @return an Observable that emits the specified items before it begins to emit items emitted
* by the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
*/
public final Observable<T> startWith(T t1, T t2, T t3, T t4, T t5, T t6) {
return concat(Observable.<T> from(t1, t2, t3, t4, t5, t6), this);
}
/**
* Returns an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png">
*
* @param t1
* the first item to emit
* @param t2
* the second item to emit
* @param t3
* the third item to emit
* @param t4
* the fourth item to emit
* @param t5
* the fifth item to emit
* @param t6
* the sixth item to emit
* @param t7
* the seventh item to emit
* @return an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
*/
public final Observable<T> startWith(T t1, T t2, T t3, T t4, T t5, T t6, T t7) {
return concat(Observable.<T> from(t1, t2, t3, t4, t5, t6, t7), this);
}
/**
* Returns an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png">
*
* @param t1
* the first item to emit
* @param t2
* the second item to emit
* @param t3
* the third item to emit
* @param t4
* the fourth item to emit
* @param t5
* the fifth item to emit
* @param t6
* the sixth item to emit
* @param t7
* the seventh item to emit
* @param t8
* the eighth item to emit
* @return an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
*/
public final Observable<T> startWith(T t1, T t2, T t3, T t4, T t5, T t6, T t7, T t8) {
return concat(Observable.<T> from(t1, t2, t3, t4, t5, t6, t7, t8), this);
}
/**
* Returns an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png">
*
* @param t1
* the first item to emit
* @param t2
* the second item to emit
* @param t3
* the third item to emit
* @param t4
* the fourth item to emit
* @param t5
* the fifth item to emit
* @param t6
* the sixth item to emit
* @param t7
* the seventh item to emit
* @param t8
* the eighth item to emit
* @param t9
* the ninth item to emit
* @return an Observable that emits the specified items before it begins to emit items emitted by the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
*/
public final Observable<T> startWith(T t1, T t2, T t3, T t4, T t5, T t6, T t7, T t8, T t9) {
return concat(Observable.<T> from(t1, t2, t3, t4, t5, t6, t7, t8, t9), this);
}
/**
* Returns an Observable that emits the items from a specified array, on a specified Scheduler, before it
* begins to emit items emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.s.png">
*
* @param values
* the items you want the modified Observable to emit first
* @param scheduler
* the Scheduler to emit the prepended values on
* @return an Observable that emits the items from {@code values}, on {@code scheduler}, before it begins to
* emit items emitted by the source Observable.
* @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#wiki-startwith">RxJava Wiki: startWith()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229372.aspx">MSDN: Observable.StartWith</a>
*/
public final Observable<T> startWith(T[] values, Scheduler scheduler) {
return startWith(Arrays.asList(values), scheduler);
}
/**
* Subscribe and ignore all events.
*
* @return a {@link Subscription} reference with which the {@link Observer} can stop receiving items before
* the Observable has finished sending them
* @throws OnErrorNotImplementedException
* if the Observable tries to call {@code onError}
*/
public final Subscription subscribe() {
return subscribe(new Subscriber<T>() {
@Override
public final void onCompleted() {
// do nothing
}
@Override
public final void onError(Throwable e) {
throw new OnErrorNotImplementedException(e);
}
@Override
public final void onNext(T args) {
// do nothing
}
});
}
/**
* An {@link Observer} must call an Observable's {@code subscribe} method in order to receive
* items and notifications from the Observable.
*
* @param onNext
* FIXME FIXME FIXME
* @return a {@link Subscription} reference with which the {@link Observer} can stop receiving items before
* the Observable has finished sending them
* @throws IllegalArgumentException
* if {@code onNext} is null
* @throws OnErrorNotImplementedException
* if the Observable tries to call {@code onError}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable#wiki-onnext-oncompleted-and-onerror">RxJava Wiki: onNext, onCompleted, and onError</a>
*/
public final Subscription subscribe(final Action1<? super T> onNext) {
if (onNext == null) {
throw new IllegalArgumentException("onNext can not be null");
}
return subscribe(new Subscriber<T>() {
@Override
public final void onCompleted() {
// do nothing
}
@Override
public final void onError(Throwable e) {
throw new OnErrorNotImplementedException(e);
}
@Override
public final void onNext(T args) {
onNext.call(args);
}
});
}
/**
* An {@link Observer} must call an Observable's {@code subscribe} method in order to receive items and
* notifications from the Observable.
*
* @param onNext
* FIXME FIXME FIXME
* @param onError
* FIXME FIXME FIXME
* @return a {@link Subscription} reference with which the {@link Observer} can stop receiving items before
* the Observable has finished sending them
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable#wiki-onnext-oncompleted-and-onerror">RxJava Wiki: onNext, onCompleted, and onError</a>
* @throws IllegalArgumentException
* if {@code onNext} is null
* @throws IllegalArgumentException
* if {@code onError} is null
*/
public final Subscription subscribe(final Action1<? super T> onNext, final Action1<Throwable> onError) {
if (onNext == null) {
throw new IllegalArgumentException("onNext can not be null");
}
if (onError == null) {
throw new IllegalArgumentException("onError can not be null");
}
return subscribe(new Subscriber<T>() {
@Override
public final void onCompleted() {
// do nothing
}
@Override
public final void onError(Throwable e) {
onError.call(e);
}
@Override
public final void onNext(T args) {
onNext.call(args);
}
});
}
/**
* An {@link Observer} must call an Observable's {@code subscribe} method in order to receive items and
* notifications from the Observable.
*
* @param onNext
* FIXME FIXME FIXME
* @param onError
* FIXME FIXME FIXME
* @param onComplete
* FIXME FIXME FIXME
* @return a {@link Subscription} reference with which the {@link Observer} can stop receiving items before
* the Observable has finished sending them
* @throws IllegalArgumentException
* if {@code onNext} is null
* @throws IllegalArgumentException
* if {@code onError} is null
* @throws IllegalArgumentException
* if {@code onComplete} is null
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable#wiki-onnext-oncompleted-and-onerror">RxJava Wiki: onNext, onCompleted, and onError</a>
*/
public final Subscription subscribe(final Action1<? super T> onNext, final Action1<Throwable> onError, final Action0 onComplete) {
if (onNext == null) {
throw new IllegalArgumentException("onNext can not be null");
}
if (onError == null) {
throw new IllegalArgumentException("onError can not be null");
}
if (onComplete == null) {
throw new IllegalArgumentException("onComplete can not be null");
}
return subscribe(new Subscriber<T>() {
@Override
public final void onCompleted() {
onComplete.call();
}
@Override
public final void onError(Throwable e) {
onError.call(e);
}
@Override
public final void onNext(T args) {
onNext.call(args);
}
});
}
/**
* An {@link Observer} must subscribe to an Observable in order to receive items and notifications from the
* Observable.
*
* @param observer
* FIXME FIXME FIXME
* @return a {@link Subscription} reference with which the {@link Observer} can stop receiving items before
* the Observable has finished sending them
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable#wiki-onnext-oncompleted-and-onerror">RxJava Wiki: onNext, onCompleted, and onError</a>
*/
public final Subscription subscribe(final Observer<? super T> observer) {
return subscribe(new Subscriber<T>() {
@Override
public void onCompleted() {
observer.onCompleted();
}
@Override
public void onError(Throwable e) {
observer.onError(e);
}
@Override
public void onNext(T t) {
observer.onNext(t);
}
});
}
/**
* Subscribe to Observable and invoke {@link OnSubscribe} function without any
* contract protection, error handling, unsubscribe, or execution hooks.
* <p>
* This should only be used for implementing an {@link Operator} that requires nested subscriptions.
* <p>
* Normal use should use {@link #subscribe(Subscriber)} which ensures the Rx contract and other functionality.
*
* @param subscriber
* @return Subscription which is the Subscriber passed in
* @since 0.17
*/
public final Subscription unsafeSubscribe(Subscriber<? super T> subscriber) {
try {
onSubscribe.call(subscriber);
} catch (Throwable e) {
if (e instanceof OnErrorNotImplementedException) {
throw (OnErrorNotImplementedException) e;
}
// handle broken contracts: https://github.com/Netflix/RxJava/issues/1090
subscriber.onError(e);
}
return subscriber;
}
/**
* A {@link Subscriber} must call an Observable's {@code subscribe} method in order to receive items and
* notifications from the Observable.
* <p>
* A typical implementation of {@code subscribe} does the following:
* <ol>
* <li>It stores a reference to the Subscriber in a collection object, such as a {@code List<T>} object.</li>
* <li>It returns a reference to the {@link Subscription} interface. This enables Observers to unsubscribe,
* that is, to stop receiving items and notifications before the Observable stops sending them, which also
* invokes the Observer's {@link Observer#onCompleted onCompleted} method.</li>
* </ol><p>
* An {@code Observable<T>} instance is responsible for accepting all subscriptions and notifying all
* Subscribers. Unless the documentation for a particular {@code Observable<T>} implementation indicates
* otherwise, Subscriber should make no assumptions about the order in which multiple Subscribers will
* receive their notifications.
* <p>
* For more information see the
* <a href="https://github.com/Netflix/RxJava/wiki/Observable">RxJava Wiki</a>
*
* @param subscriber
* the {@link Subscriber}
* @return a {@link Subscription} reference with which Subscribers that are {@link Observer}s can
* unsubscribe from the Observable
* @throws IllegalStateException
* if {@code subscribe()} is unable to obtain an {@code OnSubscribe<>} function
* @throws IllegalArgumentException
* if the {@link Subscriber} provided as the argument to {@code subscribe()} is {@code null}
* @throws OnErrorNotImplementedException
* if the {@link Subscriber}'s {@code onError} method is null
* @throws RuntimeException
* if the {@link Subscriber}'s {@code onError} method itself threw a {@code Throwable}
*/
public final Subscription subscribe(Subscriber<? super T> subscriber) {
// allow the hook to intercept and/or decorate
OnSubscribe<T> onSubscribeFunction = hook.onSubscribeStart(this, onSubscribe);
// validate and proceed
if (subscriber == null) {
throw new IllegalArgumentException("observer can not be null");
}
if (onSubscribeFunction == null) {
throw new IllegalStateException("onSubscribe function can not be null.");
/*
* the subscribe function can also be overridden but generally that's not the appropriate approach
* so I won't mention that in the exception
*/
}
try {
/*
* See https://github.com/Netflix/RxJava/issues/216 for discussion on "Guideline 6.4: Protect calls
* to user code from within an Observer"
*/
// if not already wrapped
if (!(subscriber instanceof SafeSubscriber)) {
// assign to `observer` so we return the protected version
subscriber = new SafeSubscriber<T>(subscriber);
}
onSubscribeFunction.call(subscriber);
return hook.onSubscribeReturn(subscriber);
} catch (Throwable e) {
// special handling for certain Throwable/Error/Exception types
Exceptions.throwIfFatal(e);
// if an unhandled error occurs executing the onSubscribe we will propagate it
try {
subscriber.onError(hook.onSubscribeError(e));
} catch (OnErrorNotImplementedException e2) {
// special handling when onError is not implemented ... we just rethrow
throw e2;
} catch (Throwable e2) {
// if this happens it means the onError itself failed (perhaps an invalid function implementation)
// so we are unable to propagate the error correctly and will just throw
RuntimeException r = new RuntimeException("Error occurred attempting to subscribe [" + e.getMessage() + "] and then again while trying to pass to onError.", e2);
// TODO could the hook be the cause of the error in the on error handling.
hook.onSubscribeError(r);
// TODO why aren't we throwing the hook's return value.
throw r;
}
return Subscriptions.empty();
}
}
/**
* Asynchronously subscribes Observers to this Observable on the specified {@link Scheduler}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/subscribeOn.png">
*
* @param scheduler
* the {@link Scheduler} to perform subscription actions on
* @return the source Observable modified so that its subscriptions happen on the
* specified {@link Scheduler}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-subscribeon">RxJava Wiki: subscribeOn()</a>
*/
public final Observable<T> subscribeOn(Scheduler scheduler) {
return nest().lift(new OperatorSubscribeOn<T>(scheduler));
}
/**
* Returns a new Observable by applying a function that you supply to each item emitted by the source
* Observable that returns an Observable, and then emitting the items emitted by the most recently emitted
* of these Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/switchMap.png">
*
* @param func
* a function that, when applied to an item emitted by the source Observable, returns an
* Observable
* @return an Observable that emits the items emitted by the Observable returned from applying {@code func} to the most recently emitted item emitted by the source Observable
*/
public final <R> Observable<R> switchMap(Func1<? super T, ? extends Observable<? extends R>> func) {
return switchOnNext(map(func));
}
/**
* Returns an Observable that emits only the first {@code num} items emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/take.png">
* <p>
* This method returns an Observable that will invoke a subscribing {@link Observer}'s {@link Observer#onNext onNext} function a maximum of {@code num} times before invoking
* {@link Observer#onCompleted onCompleted}.
*
* @param num
* the maximum number of items to emit
* @return an Observable that emits only the first {@code num} items emitted by the source Observable, or
* all of the items from the source Observable if that Observable emits fewer than {@code num} items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-take">RxJava Wiki: take()</a>
*/
public final Observable<T> take(final int num) {
return lift(new OperatorTake<T>(num));
}
/**
* Returns an Observable that emits those items emitted by source Observable before a specified time runs
* out.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/take.t.png">
*
* @param time
* the length of the time window
* @param unit
* the time unit of {@code time}
* @return an Observable that emits those items emitted by the source Observable before the time runs out
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-take">RxJava Wiki: take()</a>
*/
public final Observable<T> take(long time, TimeUnit unit) {
return take(time, unit, Schedulers.computation());
}
/**
* Returns an Observable that emits those items emitted by source Observable before a specified time (on a
* specified Scheduler) runs out.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/take.ts.png">
*
* @param time
* the length of the time window
* @param unit
* the time unit of {@code time}
* @param scheduler
* the Scheduler used for time source
* @return an Observable that emits those items emitted by the source Observable before the time runs out,
* according to the specified Scheduler
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-take">RxJava Wiki: take()</a>
*/
public final Observable<T> take(long time, TimeUnit unit, Scheduler scheduler) {
return lift(new OperatorTakeTimed<T>(time, unit, scheduler));
}
/**
* Returns an Observable that emits only the very first item emitted by the source Observable that satisfies
* a specified condition.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeFirstN.png">
*
* @param predicate
* the condition any item emitted by the source Observable has to satisfy
* @return an Observable that emits only the very first item emitted by the source Observable that satisfies
* the given condition, or that completes without emitting anything if the source Observable
* completes without emitting a single condition-satisfying item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-first">RxJava Wiki: first()</a>
* @see "MSDN: Observable.firstAsync()"
*/
public final Observable<T> takeFirst(Func1<? super T, Boolean> predicate) {
return filter(predicate).take(1);
}
/**
* Returns an Observable that emits only the last {@code count} items emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLast.n.png">
*
* @param count
* the number of items to emit from the end of the sequence of items emitted by the source
* Observable
* @return an Observable that emits only the last {@code count} items emitted by the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-takelast">RxJava Wiki: takeLast()</a>
*/
public final Observable<T> takeLast(final int count) {
return lift(new OperatorTakeLast<T>(count));
}
/**
* Return an Observable that emits at most a specified number of items from the source Observable that were
* emitted in a specified window of time before the Observable completed.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLast.tn.png">
*
* @param count
* the maximum number of items to emit
* @param time
* the length of the time window
* @param unit
* the time unit of {@code time}
* @return an Observable that emits at most {@code count} items from the source Observable that were emitted
* in a specified window of time before the Observable completed
*/
public final Observable<T> takeLast(int count, long time, TimeUnit unit) {
return takeLast(count, time, unit, Schedulers.computation());
}
/**
* Return an Observable that emits at most a specified number of items from the source Observable that were
* emitted in a specified window of time before the Observable completed, where the timing information is
* provided by a given Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLast.tns.png">
*
* @param count
* the maximum number of items to emit
* @param time
* the length of the time window
* @param unit
* the time unit of {@code time}
* @param scheduler
* the Scheduler that provides the timestamps for the observed items
* @return an Observable that emits at most {@code count} items from the source Observable that were emitted
* in a specified window of time before the Observable completed, where the timing information is
* provided by the given {@code scheduler}
* @throws IllegalArgumentException
* if {@code count} is less than zero
*/
public final Observable<T> takeLast(int count, long time, TimeUnit unit, Scheduler scheduler) {
return lift(new OperatorTakeLastTimed<T>(count, time, unit, scheduler));
}
/**
* Return an Observable that emits the items from the source Observable that were emitted in a specified
* window of time before the Observable completed.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLast.t.png">
*
* @param time
* the length of the time window
* @param unit
* the time unit of {@code time}
* @return an Observable that emits the items from the source Observable that were emitted in the window of
* time before the Observable completed specified by {@code time}
*/
public final Observable<T> takeLast(long time, TimeUnit unit) {
return takeLast(time, unit, Schedulers.computation());
}
/**
* Return an Observable that emits the items from the source Observable that were emitted in a specified
* window of time before the Observable completed, where the timing information is provided by a specified
* Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLast.ts.png">
*
* @param time
* the length of the time window
* @param unit
* the time unit of {@code time}
* @param scheduler
* the Scheduler that provides the timestamps for the Observed items
* @return an Observable that emits the items from the source Observable that were emitted in the window of
* time before the Observable completed specified by {@code time}, where the timing information is
* provided by {@code scheduler}
*/
public final Observable<T> takeLast(long time, TimeUnit unit, Scheduler scheduler) {
return lift(new OperatorTakeLastTimed<T>(time, unit, scheduler));
}
/**
* Return an Observable that emits a single List containing the last {@code count} elements emitted by the
* source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLastBuffer.png">
*
* @param count
* the number of items to emit in the list
* @return an Observable that emits a single list containing the last {@code count} elements emitted by the
* source Observable
*/
public final Observable<List<T>> takeLastBuffer(int count) {
return takeLast(count).toList();
}
/**
* Return an Observable that emits a single List containing at most {@code count} items from the source
* Observable that were emitted during a specified window of time before the source Observable completed.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLastBuffer.tn.png">
*
* @param count
* the maximum number of items to emit
* @param time
* the length of the time window
* @param unit
* the time unit of {@code time}
* @return an Observable that emits a single List containing at most {@code count} items emitted by the
* source Observable during the time window defined by {@code time} before the source Observable
* completed
*/
public final Observable<List<T>> takeLastBuffer(int count, long time, TimeUnit unit) {
return takeLast(count, time, unit).toList();
}
/**
* Return an Observable that emits a single List containing at most {@code count} items from the source
* Observable that were emitted during a specified window of time (on a specified Scheduler) before the
* source Observable completed.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLastBuffer.tns.png">
*
* @param count
* the maximum number of items to emit
* @param time
* the length of the time window
* @param unit
* the time unit of {@code time}
* @param scheduler
* the Scheduler that provides the timestamps for the observed items
* @return an Observable that emits a single List containing at most {@code count} items emitted by the
* source Observable during the time window defined by {@code time} before the source Observable
* completed
*/
public final Observable<List<T>> takeLastBuffer(int count, long time, TimeUnit unit, Scheduler scheduler) {
return takeLast(count, time, unit, scheduler).toList();
}
/**
* Return an Observable that emits a single List containing those items from the source Observable that were
* emitted during a specified window of time before the source Observable completed.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLastBuffer.t.png">
*
* @param time
* the length of the time window
* @param unit
* the time unit of {@code time}
* @return an Observable that emits a single List containing the items emitted by the source Observable
* during the time window defined by {@code time} before the source Observable completed
*/
public final Observable<List<T>> takeLastBuffer(long time, TimeUnit unit) {
return takeLast(time, unit).toList();
}
/**
* Return an Observable that emits a single List containing those items from the source Observable that were
* emitted during a specified window of time before the source Observable completed, where the timing
* information is provided by the given Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLastBuffer.ts.png">
*
* @param time
* the length of the time window
* @param unit
* the time unit of {@code time}
* @param scheduler
* the Scheduler that provides the timestamps for the observed items
* @return an Observable that emits a single List containing the items emitted by the source Observable
* during the time window defined by {@code time} before the source Observable completed, where the
* timing information is provided by {@code scheduler}
*/
public final Observable<List<T>> takeLastBuffer(long time, TimeUnit unit, Scheduler scheduler) {
return takeLast(time, unit, scheduler).toList();
}
/**
* Returns an Observable that emits the items emitted by the source Observable until a second Observable
* emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeUntil.png">
*
* @param other
* the Observable whose first emitted item will cause {@code takeUntil} to stop emitting items
* from the source Observable
* @param <E>
* the type of items emitted by {@code other}
* @return an Observable that emits the items emitted by the source Observable until such time as {@code other} emits its first item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-takeuntil">RxJava Wiki: takeUntil()</a>
*/
public final <E> Observable<T> takeUntil(Observable<? extends E> other) {
return OperatorTakeUntil.takeUntil(this, other);
}
/**
* Returns an Observable that emits items emitted by the source Observable so long as each item satisfied a
* specified condition, and then completes as soon as this condition is not satisfied.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeWhile.png">
*
* @param predicate
* a function that evaluates an item emitted by the source Observable and returns a Boolean
* @return an Observable that emits the items from the source Observable so long as each item satisfies the
* condition defined by {@code predicate}, then completes
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-takewhile-and-takewhilewithindex">RxJava Wiki: takeWhile()</a>
*/
public final Observable<T> takeWhile(final Func1<? super T, Boolean> predicate) {
return lift(new OperatorTakeWhile<T>(predicate));
}
/**
* Returns an Observable that emits the items emitted by a source Observable so long as a given predicate
* remains true, where the predicate operates on both the item and its index relative to the complete
* sequence of emitted items.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeWhileWithIndex.png">
*
* @param predicate
* a function to test each item emitted by the source Observable for a condition; the second
* parameter of the function represents the sequential index of the source item; it returns a
* Boolean
* @return an Observable that emits items from the source Observable so long as the predicate continues to
* return {@code true} for each item, then completes
* @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#wiki-takewhile-and-takewhilewithindex">RxJava Wiki: takeWhileWithIndex()</a>
*/
public final Observable<T> takeWhileWithIndex(final Func2<? super T, ? super Integer, Boolean> predicate) {
return lift(new OperatorTakeWhile<T>(predicate));
}
/**
* Returns an Observable that emits only the first item emitted by the source Observable during sequential
* time windows of a specified duration.
* <p>
* This differs from {@link #throttleLast} in that this only tracks passage of time whereas {@link #throttleLast} ticks at scheduled intervals.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/throttleFirst.png">
*
* @param windowDuration
* time to wait before emitting another item after emitting the last item
* @param unit
* the unit of time of {@code windowDuration}
* @return an Observable that performs the throttle operation
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-throttlefirst">RxJava Wiki: throttleFirst()</a>
*/
public final Observable<T> throttleFirst(long windowDuration, TimeUnit unit) {
return lift(new OperatorThrottleFirst<T>(windowDuration, unit, Schedulers.computation()));
}
/**
* Returns an Observable that emits only the first item emitted by the source Observable during sequential
* time windows of a specified duration, where the windows are managed by a specified Scheduler.
* <p>
* This differs from {@link #throttleLast} in that this only tracks passage of time whereas {@link #throttleLast} ticks at scheduled intervals.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/throttleFirst.s.png">
*
* @param skipDuration
* time to wait before emitting another item after emitting the last item
* @param unit
* the unit of time of {@code skipDuration}
* @param scheduler
* the {@link Scheduler} to use internally to manage the timers that handle timeout for each
* event
* @return an Observable that performs the throttle operation
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-throttlefirst">RxJava Wiki: throttleFirst()</a>
*/
public final Observable<T> throttleFirst(long skipDuration, TimeUnit unit, Scheduler scheduler) {
return lift(new OperatorThrottleFirst<T>(skipDuration, unit, scheduler));
}
/**
* Returns an Observable that emits only the last item emitted by the source Observable during sequential
* time windows of a specified duration.
* <p>
* This differs from {@link #throttleFirst} in that this ticks along at a scheduled interval whereas {@link #throttleFirst} does not tick, it just tracks passage of time.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/throttleLast.png">
*
* @param intervalDuration
* duration of windows within which the last item emitted by the source Observable will be
* emitted
* @param unit
* the unit of time of {@code intervalDuration}
* @return an Observable that performs the throttle operation
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-takelast">RxJava Wiki: throttleLast()</a>
* @see #sample(long, TimeUnit)
*/
public final Observable<T> throttleLast(long intervalDuration, TimeUnit unit) {
return sample(intervalDuration, unit);
}
/**
* Returns an Observable that emits only the last item emitted by the source Observable during sequential
* time windows of a specified duration, where the duration is governed by a specified Scheduler.
* <p>
* This differs from {@link #throttleFirst} in that this ticks along at a scheduled interval whereas {@link #throttleFirst} does not tick, it just tracks passage of time.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/throttleLast.s.png">
*
* @param intervalDuration
* duration of windows within which the last item emitted by the source Observable will be
* emitted
* @param unit
* the unit of time of {@code intervalDuration}
* @param scheduler
* the {@link Scheduler} to use internally to manage the timers that handle timeout for each
* event
* @return an Observable that performs the throttle operation
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-takelast">RxJava Wiki: throttleLast()</a>
* @see #sample(long, TimeUnit, Scheduler)
*/
public final Observable<T> throttleLast(long intervalDuration, TimeUnit unit, Scheduler scheduler) {
return sample(intervalDuration, unit, scheduler);
}
/**
* Returns an Observable that only emits those items emitted by the source Observable that are not followed
* by another emitted item within a specified time window.
* <p>
* <em>Note:</em> If the source Observable keeps emitting items more frequently than the length of the time
* window then no items will be emitted by the resulting Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/throttleWithTimeout.png">
* <p>
* Information on debounce vs throttle:
* <p>
* <ul>
* <li><a href="http://drupalmotion.com/article/debounce-and-throttle-visual-explanation">Debounce and Throttle: visual explanation</a></li>
* <li><a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">Debouncing: javascript methods</a></li>
* <li><a href="http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/">Javascript - don't spam your server: debounce and throttle</a></li>
* </ul>
*
* @param timeout
* the length of the window of time that must pass after the emission of an item from the source
* Observable in which that Observable emits no items in order for the item to be emitted by the
* resulting Observable
* @param unit
* the {@link TimeUnit} of {@code timeout}
* @return an Observable that filters out items that are too quickly followed by newer items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-throttlewithtimeout-or-debounce">RxJava Wiki: throttleWithTimeout()</a>
* @see #debounce(long, TimeUnit)
*/
public final Observable<T> throttleWithTimeout(long timeout, TimeUnit unit) {
return debounce(timeout, unit);
}
/**
* Returns an Observable that only emits those items emitted by the source Observable that are not followed
* by another emitted item within a specified time window, where the time window is governed by a specified
* Scheduler.
* <p>
* <em>Note:</em> If the source Observable keeps emitting items more frequently than the length of the time
* window then no items will be emitted by the resulting Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/throttleWithTimeout.s.png">
* <p>
* Information on debounce vs throttle:
* <p>
* <ul>
* <li><a href="http://drupalmotion.com/article/debounce-and-throttle-visual-explanation">Debounce and Throttle: visual explanation</a></li>
* <li><a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">Debouncing: javascript methods</a></li>
* <li><a href="http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/">Javascript - don't spam your server: debounce and throttle</a></li>
* </ul>
*
* @param timeout
* the length of the window of time that must pass after the emission of an item from the source
* Observable in which that Observable emits no items in order for the item to be emitted by the
* resulting Observable
* @param unit
* the {@link TimeUnit} of {@code timeout}
* @param scheduler
* the {@link Scheduler} to use internally to manage the timers that handle the timeout for each
* item
* @return an Observable that filters out items that are too quickly followed by newer items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-throttlewithtimeout-or-debounce">RxJava Wiki: throttleWithTimeout()</a>
* @see #debounce(long, TimeUnit, Scheduler)
*/
public final Observable<T> throttleWithTimeout(long timeout, TimeUnit unit, Scheduler scheduler) {
return debounce(timeout, unit, scheduler);
}
/**
* Returns an Observable that emits records of the time interval between consecutive items emitted by the
* source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeInterval.png">
*
* @return an Observable that emits time interval information items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-timeinterval">RxJava Wiki: timeInterval()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh212107.aspx">MSDN: Observable.TimeInterval</a>
*/
public final Observable<TimeInterval<T>> timeInterval() {
return lift(new OperatorTimeInterval<T>(Schedulers.immediate()));
}
/**
* Returns an Observable that emits records of the time interval between consecutive items emitted by the
* source Observable, where this interval is computed on a specified Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeInterval.s.png">
*
* @param scheduler
* the {@link Scheduler} used to compute time intervals
* @return an Observable that emits time interval information items
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-timeinterval">RxJava Wiki: timeInterval()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh212107.aspx">MSDN: Observable.TimeInterval</a>
*/
public final Observable<TimeInterval<T>> timeInterval(Scheduler scheduler) {
return lift(new OperatorTimeInterval<T>(scheduler));
}
/**
* Returns an Observable that mirrors the source Observable, but notifies observers of a TimeoutException if
* either the first item emitted by the source Observable or any subsequent item don't arrive within time
* windows defined by other Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout5.png">
*
* @param <U>
* the first timeout value type (ignored)
* @param <V>
* the subsequent timeout value type (ignored)
* @param firstTimeoutSelector
* a function that returns an Observable that determines the timeout window for the first source
* item
* @param timeoutSelector
* a function that returns an Observable for each item emitted by the source Observable and that
* determines the timeout window in which the subsequent source item must arrive in order to
* continue the sequence
* @return an Observable that mirrors the source Observable, but notifies observers of a TimeoutException if
* either the first item or any subsequent item doesn't arrive within the time windows specified by
* the timeout selectors
*/
public final <U, V> Observable<T> timeout(Func0<? extends Observable<U>> firstTimeoutSelector, Func1<? super T, ? extends Observable<V>> timeoutSelector) {
return timeout(firstTimeoutSelector, timeoutSelector, null);
}
/**
* Returns an Observable that mirrors the source Observable, but switches to a fallback Observable if either
* the first item emitted by the source Observable or any subsequent item don't arrive within time windows
* defined by other Observables.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout6.png">
*
* @param <U>
* the first timeout value type (ignored)
* @param <V>
* the subsequent timeout value type (ignored)
* @param firstTimeoutSelector
* a function that returns an Observable which determines the timeout window for the first source
* item
* @param timeoutSelector
* a function that returns an Observable for each item emitted by the source Observable and that
* determines the timeout window in which the subsequent source item must arrive in order to
* continue the sequence
* @param other
* the fallback Observable to switch to if the source Observable times out
* @return an Observable that mirrors the source Observable, but switches to the {@code other} Observable if
* either the first item emitted by the source Observable or any subsequent item don't arrive within
* time windows defined by the timeout selectors
* @throws NullPointerException
* if {@code timeoutSelector} is null
*/
public final <U, V> Observable<T> timeout(Func0<? extends Observable<U>> firstTimeoutSelector, Func1<? super T, ? extends Observable<V>> timeoutSelector, Observable<? extends T> other) {
if (timeoutSelector == null) {
throw new NullPointerException("timeoutSelector is null");
}
return lift(new OperatorTimeoutWithSelector<T, U, V>(firstTimeoutSelector, timeoutSelector, other));
}
/**
* Returns an Observable that mirrors the source Observable, but notifies observers of a TimeoutException if
* an item emitted by the source Observable doesn't arrive within a window of time after the emission of the
* previous item, where that period of time is measured by an Observable that is a function of the previous
* item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout3.png">
* <p>
* Note: The arrival of the first source item is never timed out.
*
* @param <V>
* the timeout value type (ignored)
* @param timeoutSelector
* a function that returns an observable for each item emitted by the source
* Observable and that determines the timeout window for the subsequent item
* @return an Observable that mirrors the source Observable, but notifies observers of a TimeoutException if
* an item emitted by the source Observable takes longer to arrive than the time window defined by
* the selector for the previously emitted item
*/
public final <V> Observable<T> timeout(Func1<? super T, ? extends Observable<V>> timeoutSelector) {
return timeout(null, timeoutSelector, null);
}
/**
* Returns an Observable that mirrors the source Observable, but that switches to a fallback Observable if
* an item emitted by the source Observable doesn't arrive within a window of time after the emission of the
* previous item, where that period of time is measured by an Observable that is a function of the previous
* item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout4.png">
* <p>
* Note: The arrival of the first source item is never timed out.
*
* @param <V>
* the timeout value type (ignored)
* @param timeoutSelector
* a function that returns an Observable, for each item emitted by the source Observable, that
* determines the timeout window for the subsequent item
* @param other
* the fallback Observable to switch to if the source Observable times out
* @return an Observable that mirrors the source Observable, but switches to mirroring a fallback Observable
* if an item emitted by the source Observable takes longer to arrive than the time window defined
* by the selector for the previously emitted item
*/
public final <V> Observable<T> timeout(Func1<? super T, ? extends Observable<V>> timeoutSelector, Observable<? extends T> other) {
return timeout(null, timeoutSelector, other);
}
/**
* Returns an Observable that mirrors the source Observable but applies a timeout policy for each emitted
* item. If the next item isn't emitted within the specified timeout duration starting from its predecessor,
* the resulting Observable terminates and notifies observers of a {@code TimeoutException}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout.1.png">
*
* @param timeout
* maximum duration between emitted items before a timeout occurs
* @param timeUnit
* the unit of time that applies to the {@code timeout} argument.
* @return the source Observable modified to notify observers of a {@code TimeoutException} in case of a
* timeout
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-timeout">RxJava Wiki: timeout()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh244283.aspx">MSDN: Observable.Timeout</a>
*/
public final Observable<T> timeout(long timeout, TimeUnit timeUnit) {
return timeout(timeout, timeUnit, null, Schedulers.computation());
}
/**
* Returns an Observable that mirrors the source Observable but applies a timeout policy for each emitted
* item. If the next item isn't emitted within the specified timeout duration starting from its predecessor,
* the resulting Observable begins instead to mirror a fallback Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout.2.png">
*
* @param timeout
* maximum duration between items before a timeout occurs
* @param timeUnit
* the unit of time that applies to the {@code timeout} argument
* @param other
* the fallback Observable to use in case of a timeout
* @return the source Observable modified to switch to the fallback Observable in case of a timeout
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-timeout">RxJava Wiki: timeout()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229512.aspx">MSDN: Observable.Timeout</a>
*/
public final Observable<T> timeout(long timeout, TimeUnit timeUnit, Observable<? extends T> other) {
return timeout(timeout, timeUnit, other, Schedulers.computation());
}
/**
* Returns an Observable that mirrors the source Observable but applies a timeout policy for each emitted
* item using a specified Scheduler. If the next item isn't emitted within the specified timeout duration
* starting from its predecessor, the resulting Observable begins instead to mirror a fallback Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout.2s.png">
*
* @param timeout
* maximum duration between items before a timeout occurs
* @param timeUnit
* the unit of time that applies to the {@code timeout} argument
* @param other
* the Observable to use as the fallback in case of a timeout
* @param scheduler
* the {@link Scheduler} to run the timeout timers on
* @return the source Observable modified so that it will switch to the fallback Observable in case of a
* timeout
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-timeout">RxJava Wiki: timeout()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211676.aspx">MSDN: Observable.Timeout</a>
*/
public final Observable<T> timeout(long timeout, TimeUnit timeUnit, Observable<? extends T> other, Scheduler scheduler) {
return lift(new OperatorTimeout<T>(timeout, timeUnit, other, scheduler));
}
/**
* Returns an Observable that mirrors the source Observable but applies a timeout policy for each emitted
* item, where this policy is governed on a specified Scheduler. If the next item isn't emitted within the
* specified timeout duration starting from its predecessor, the resulting Observable terminates and
* notifies observers of a {@code TimeoutException}.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout.1s.png">
*
* @param timeout
* maximum duration between items before a timeout occurs
* @param timeUnit
* the unit of time that applies to the {@code timeout} argument
* @param scheduler
* the Scheduler to run the timeout timers on
* @return the source Observable modified to notify observers of a {@code TimeoutException} in case of a
* timeout
* @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-timeout">RxJava Wiki: timeout()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh228946.aspx">MSDN: Observable.Timeout</a>
*/
public final Observable<T> timeout(long timeout, TimeUnit timeUnit, Scheduler scheduler) {
return timeout(timeout, timeUnit, null, scheduler);
}
/**
* Returns an Observable that emits each item emitted by the source Observable, wrapped in a {@link Timestamped} object.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timestamp.png">
*
* @return an Observable that emits timestamped items from the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-timestamp">RxJava Wiki: timestamp()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229003.aspx">MSDN: Observable.Timestamp</a>
*/
public final Observable<Timestamped<T>> timestamp() {
return timestamp(Schedulers.immediate());
}
/**
* Returns an Observable that emits each item emitted by the source Observable, wrapped in a {@link Timestamped} object whose timestamps are provided by a specified Scheduler.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timestamp.s.png">
*
* @param scheduler
* the {@link Scheduler} to use as a time source
* @return an Observable that emits timestamped items from the source Observable with timestamps provided by
* the {@code scheduler}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-timestamp">RxJava Wiki: timestamp()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229003.aspx">MSDN: Observable.Timestamp</a>
*/
public final Observable<Timestamped<T>> timestamp(Scheduler scheduler) {
return lift(new OperatorTimestamp<T>(scheduler));
}
/**
* Converts an Observable into a {@link BlockingObservable} (an Observable with blocking operators).
*
* @return a {@code BlockingObservable} version of this Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Blocking-Observable-Operators">RxJava Wiki: Blocking Observable Observers</a>
*
* @deprecated Use {@link #toBlocking()} instead.
*/
@Deprecated
public final BlockingObservable<T> toBlockingObservable() {
return BlockingObservable.from(this);
}
/**
* Converts an Observable into a {@link BlockingObservable} (an Observable with blocking operators).
*
* @return a {@code BlockingObservable} version of this Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Blocking-Observable-Operators">RxJava Wiki: Blocking Observable Observers</a>
* @since 0.19
*/
public final BlockingObservable<T> toBlocking() {
return BlockingObservable.from(this);
}
/**
* Returns an Observable that emits a single item, a list composed of all the items emitted by the source
* Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toList.png">
* <p>
* Normally, an Observable that returns multiple items will do so by invoking its {@link Observer}'s {@link Observer#onNext onNext} method for each such item. You can change this behavior,
* instructing the
* Observable to compose a list of all of these items and then to invoke the Observer's {@code onNext} function once, passing it the entire list, by calling the Observable's {@code toList} method
* prior to
* calling its {@link #subscribe} method.
* <p>
*
* <!-- IS THE FOLLOWING NOTE STILL VALID? -->
*
* Be careful not to use this operator on Observables that emit infinite or very large numbers of items, as
* you do not have the option to unsubscribe.
*
* @return an Observable that emits a single item: a List containing all of the items emitted by the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-tolist">RxJava Wiki: toList()</a>
*/
public final Observable<List<T>> toList() {
return lift(new OperatorToObservableList<T>());
}
/**
* Return an Observable that emits a single HashMap containing all items emitted by the source Observable,
* mapped by the keys returned by a specified {@code keySelector} function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toMap.png">
* <p>
* If more than one source item maps to the same key, the HashMap will contain the latest of those items.
*
* @param keySelector
* the function that extracts the key from a source item to be used in the HashMap
* @return an Observable that emits a single item: a HashMap containing the mapped items from the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-tomap-and-tomultimap">RxJava Wiki: toMap()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229137.aspx">MSDN: Observable.ToDictionary</a>
*/
public final <K> Observable<Map<K, T>> toMap(Func1<? super T, ? extends K> keySelector) {
return lift(new OperatorToMap<T, K, T>(keySelector, Functions.<T>identity()));
}
/**
* Return an Observable that emits a single HashMap containing values corresponding to items emitted by the
* source Observable, mapped by the keys returned by a specified {@code keySelector} function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toMap.png">
* <p>
* If more than one source item maps to the same key, the HashMap will contain a single entry that
* corresponds to the latest of those items.
*
* @param keySelector
* the function that extracts the key from a source item to be used in the HashMap
* @param valueSelector
* the function that extracts the value from a source item to be used in the HashMap
* @return an Observable that emits a single item: a HashMap containing the mapped items from the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-tomap-and-tomultimap">RxJava Wiki: toMap()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh212075.aspx">MSDN: Observable.ToDictionary</a>
*/
public final <K, V> Observable<Map<K, V>> toMap(Func1<? super T, ? extends K> keySelector, Func1<? super T, ? extends V> valueSelector) {
return lift(new OperatorToMap<T, K, V>(keySelector, valueSelector));
}
/**
* Return an Observable that emits a single Map, returned by a specified {@code mapFactory} function, that
* contains keys and values extracted from the items emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toMap.png">
*
* @param keySelector
* the function that extracts the key from a source item to be used in the Map
* @param valueSelector
* the function that extracts the value from the source items to be used as value in the Map
* @param mapFactory
* the function that returns a Map instance to be used
* @return an Observable that emits a single item: a Map that contains the mapped items emitted by the
* source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-tomap-and-tomultimap">RxJava Wiki: toMap()</a>
*/
public final <K, V> Observable<Map<K, V>> toMap(Func1<? super T, ? extends K> keySelector, Func1<? super T, ? extends V> valueSelector, Func0<? extends Map<K, V>> mapFactory) {
return lift(new OperatorToMap<T, K, V>(keySelector, valueSelector, mapFactory));
}
/**
* Return an Observable that emits a single HashMap that contains an ArrayList of items emitted by the
* source Observable keyed by a specified {@code keySelector} function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toMultiMap.png">
*
* @param keySelector
* the function that extracts the key from the source items to be used as key in the HashMap
* @return an Observable that emits a single item: a HashMap that contains an ArrayList of items mapped from
* the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-tomap-and-tomultimap">RxJava Wiki: toMap()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh212098.aspx">MSDN: Observable.ToLookup</a>
*/
public final <K> Observable<Map<K, Collection<T>>> toMultimap(Func1<? super T, ? extends K> keySelector) {
return lift(new OperatorToMultimap<T, K, T>(keySelector, Functions.<T>identity()));
}
/**
* Return an Observable that emits a single HashMap that contains an ArrayList of values extracted by a
* specified {@code valueSelector} function from items emitted by the source Observable, keyed by a
* specified {@code keySelector} function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toMultiMap.png">
*
* @param keySelector
* the function that extracts a key from the source items to be used as key in the HashMap
* @param valueSelector
* the function that extracts a value from the source items to be used as value in the HashMap
* @return an Observable that emits a single item: a HashMap that contains an ArrayList of items mapped from
* the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-tomap-and-tomultimap">RxJava Wiki: toMap()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229101.aspx">MSDN: Observable.ToLookup</a>
*/
public final <K, V> Observable<Map<K, Collection<V>>> toMultimap(Func1<? super T, ? extends K> keySelector, Func1<? super T, ? extends V> valueSelector) {
return lift(new OperatorToMultimap<T, K, V>(keySelector, valueSelector));
}
/**
* Return an Observable that emits a single Map, returned by a specified {@code mapFactory} function, that
* contains an ArrayList of values, extracted by a specified {@code valueSelector} function from items
* emitted by the source Observable and keyed by the {@code keySelector} function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toMultiMap.png">
*
* @param keySelector
* the function that extracts a key from the source items to be used as the key in the Map
* @param valueSelector
* the function that extracts a value from the source items to be used as the value in the Map
* @param mapFactory
* the function that returns a Map instance to be used
* @return an Observable that emits a single item: a Map that contains a list items mapped from the source
* Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-tomap-and-tomultimap">RxJava Wiki: toMap()</a>
*/
public final <K, V> Observable<Map<K, Collection<V>>> toMultimap(Func1<? super T, ? extends K> keySelector, Func1<? super T, ? extends V> valueSelector, Func0<? extends Map<K, Collection<V>>> mapFactory) {
return lift(new OperatorToMultimap<T, K, V>(keySelector, valueSelector, mapFactory));
}
/**
* Return an Observable that emits a single Map, returned by a specified {@code mapFactory} function, that
* contains a custom collection of values, extracted by a specified {@code valueSelector} function from
* items emitted by the source Observable, and keyed by the {@code keySelector} function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toMultiMap.png">
*
* @param keySelector
* the function that extracts a key from the source items to be used as the key in the Map
* @param valueSelector
* the function that extracts a value from the source items to be used as the value in the Map
* @param mapFactory
* the function that returns a Map instance to be used
* @param collectionFactory
* the function that returns a Collection instance for a particular key to be used in the Map
* @return an Observable that emits a single item: a Map that contains the collection of mapped items from
* the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-tomap-and-tomultimap">RxJava Wiki: toMap()</a>
*/
public final <K, V> Observable<Map<K, Collection<V>>> toMultimap(Func1<? super T, ? extends K> keySelector, Func1<? super T, ? extends V> valueSelector, Func0<? extends Map<K, Collection<V>>> mapFactory, Func1<? super K, ? extends Collection<V>> collectionFactory) {
return lift(new OperatorToMultimap<T, K, V>(keySelector, valueSelector, mapFactory, collectionFactory));
}
/**
* Returns an Observable that emits a list that contains the items emitted by the source Observable, in a
* sorted order. Each item emitted by the Observable must implement {@link Comparable} with respect to all
* other items in the sequence.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toSortedList.png">
*
* @throws ClassCastException
* if any item emitted by the Observable does not implement {@link Comparable} with respect to
* all other items emitted by the Observable
* @return an Observable that emits a list that contains the items emitted by the source Observable in
* sorted order
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-tosortedlist">RxJava Wiki: toSortedList()</a>
*/
public final Observable<List<T>> toSortedList() {
return lift(new OperatorToObservableSortedList<T>());
}
/**
* Returns an Observable that emits a list that contains the items emitted by the source Observable, in a
* sorted order based on a specified comparison function.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toSortedList.f.png">
*
* @param sortFunction
* a function that compares two items emitted by the source Observable and returns an Integer
* that indicates their sort order
* @return an Observable that emits a list that contains the items emitted by the source Observable in
* sorted order
* @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-tosortedlist">RxJava Wiki: toSortedList()</a>
*/
public final Observable<List<T>> toSortedList(Func2<? super T, ? super T, Integer> sortFunction) {
return lift(new OperatorToObservableSortedList<T>(sortFunction));
}
/**
* Asynchronously unsubscribes on the specified {@link Scheduler}.
*
* @param scheduler
* the {@link Scheduler} to perform subscription and unsubscription actions on
* @return the source Observable modified so that its unsubscriptions happen on the specified {@link Scheduler}
* @since 0.17
*/
public final Observable<T> unsubscribeOn(Scheduler scheduler) {
return lift(new OperatorUnsubscribeOn<T>(scheduler));
}
/**
* Returns an Observable that emits windows of items it collects from the source Observable. The resulting
* Observable emits connected, non-overlapping windows. It emits the current window and opens a new one when
* the Observable produced by the specified {@code closingSelector} emits an item. The {@code closingSelector} then creates a new Observable to generate the closer of the next window.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window1.png">
*
* @param closingSelector
* a {@link Func0} that produces an Observable for every window created. When this Observable
* emits an item, {@code window()} emits the associated window and begins a new one.
* @return an Observable that emits connected, non-overlapping windows of items from the source Observable
* when {@code closingSelector} emits an item
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-window">RxJava Wiki: window()</a>
*/
public final <TClosing> Observable<Observable<T>> window(Func0<? extends Observable<? extends TClosing>> closingSelector) {
return lift(new OperatorWindowWithObservable<T, TClosing>(closingSelector));
}
/**
* Returns an Observable that emits windows of items it collects from the source Observable. The resulting
* Observable emits connected, non-overlapping windows, each containing {@code count} items. When the source
* Observable completes or encounters an error, the resulting Observable emits the current window and
* propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window3.png">
*
* @param count
* the maximum size of each window before it should be emitted
* @return an Observable that emits connected, non-overlapping windows, each containing at most {@code count} items from the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-window">RxJava Wiki: window()</a>
*/
public final Observable<Observable<T>> window(int count) {
return lift(new OperatorWindowWithSize<T>(count, count));
}
/**
* Returns an Observable that emits windows of items it collects from the source Observable. The resulting
* Observable emits windows every {@code skip} items, each containing no more than {@code count} items. When
* the source Observable completes or encounters an error, the resulting Observable emits the current window
* and propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window4.png">
*
* @param count
* the maximum size of each window before it should be emitted
* @param skip
* how many items need to be skipped before starting a new window. Note that if {@code skip} and {@code count} are equal this is the same operation as {@link #window(int)}.
* @return an Observable that emits windows every {@code skip} items containing at most {@code count} items
* from the source Observable
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-window">RxJava Wiki: window()</a>
*/
public final Observable<Observable<T>> window(int count, int skip) {
return lift(new OperatorWindowWithSize<T>(count, skip));
}
/**
* Returns an Observable that emits windows of items it collects from the source Observable. The resulting
* Observable starts a new window periodically, as determined by the {@code timeshift} argument. It emits
* each window after a fixed timespan, specified by the {@code timespan} argument. When the source
* Observable completes or Observable completes or encounters an error, the resulting Observable emits the
* current window and propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window7.png">
*
* @param timespan
* the period of time each window collects items before it should be emitted
* @param timeshift
* the period of time after which a new window will be created
* @param unit
* the unit of time that applies to the {@code timespan} and {@code timeshift} arguments
* @return an Observable that emits new windows periodically as a fixed timespan elapses
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-window">RxJava Wiki: window()</a>
*/
public final Observable<Observable<T>> window(long timespan, long timeshift, TimeUnit unit) {
return lift(new OperatorWindowWithTime<T>(timespan, timeshift, unit, Integer.MAX_VALUE, Schedulers.computation()));
}
/**
* Returns an Observable that emits windows of items it collects from the source Observable. The resulting
* Observable starts a new window periodically, as determined by the {@code timeshift} argument. It emits
* each window after a fixed timespan, specified by the {@code timespan} argument. When the source
* Observable completes or Observable completes or encounters an error, the resulting Observable emits the
* current window and propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window7.s.png">
*
* @param timespan
* the period of time each window collects items before it should be emitted
* @param timeshift
* the period of time after which a new window will be created
* @param unit
* the unit of time that applies to the {@code timespan} and {@code timeshift} arguments
* @param scheduler
* the {@link Scheduler} to use when determining the end and start of a window
* @return an Observable that emits new windows periodically as a fixed timespan elapses
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-window">RxJava Wiki: window()</a>
*/
public final Observable<Observable<T>> window(long timespan, long timeshift, TimeUnit unit, Scheduler scheduler) {
return lift(new OperatorWindowWithTime<T>(timespan, timeshift, unit, Integer.MAX_VALUE, scheduler));
}
/**
* Returns an Observable that emits windows of items it collects from the source Observable. The resulting
* Observable emits connected, non-overlapping windows, each of a fixed duration specified by the {@code timespan} argument. When the source Observable completes or encounters an error, the
* resulting
* Observable emits the current window and propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window5.png">
*
* @param timespan
* the period of time each window collects items before it should be emitted and replaced with a
* new window
* @param unit
* the unit of time that applies to the {@code timespan} argument
* @return an Observable that emits connected, non-overlapping windows represending items emitted by the
* source Observable during fixed, consecutive durations
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-window">RxJava Wiki: window()</a>
*/
public final Observable<Observable<T>> window(long timespan, TimeUnit unit) {
return lift(new OperatorWindowWithTime<T>(timespan, timespan, unit, Integer.MAX_VALUE, Schedulers.computation()));
}
/**
* Returns an Observable that emits windows of items it collects from the source Observable. The resulting
* Observable emits connected, non-overlapping windows, each of a fixed duration as specified by the {@code timespan} argument or a maximum size as specified by the {@code count} argument
* (whichever is
* reached first). When the source Observable completes or encounters an error, the resulting Observable
* emits the current window and propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window6.png">
*
* @param timespan
* the period of time each window collects items before it should be emitted and replaced with a
* new window
* @param unit
* the unit of time that applies to the {@code timespan} argument
* @param count
* the maximum size of each window before it should be emitted
* @return an Observable that emits connected, non-overlapping windows of items from the source Observable
* that were emitted during a fixed duration of time or when the window has reached maximum capacity
* (whichever occurs first)
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-window">RxJava Wiki: window()</a>
*/
public final Observable<Observable<T>> window(long timespan, TimeUnit unit, int count) {
return lift(new OperatorWindowWithTime<T>(timespan, timespan, unit, count, Schedulers.computation()));
}
/**
* Returns an Observable that emits windows of items it collects from the source Observable. The resulting
* Observable emits connected, non-overlapping windows, each of a fixed duration specified by the {@code timespan} argument or a maximum size specified by the {@code count} argument (whichever is
* reached
* first). When the source Observable completes or encounters an error, the resulting Observable emits the
* current window and propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window6.s.png">
*
* @param timespan
* the period of time each window collects items before it should be emitted and replaced with a
* new window
* @param unit
* the unit of time which applies to the {@code timespan} argument
* @param count
* the maximum size of each window before it should be emitted
* @param scheduler
* the {@link Scheduler} to use when determining the end and start of a window
* @return an Observable that emits connected, non-overlapping windows of items from the source Observable
* that were emitted during a fixed duration of time or when the window has reached maximum capacity
* (whichever occurs first)
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-window">RxJava Wiki: window()</a>
*/
public final Observable<Observable<T>> window(long timespan, TimeUnit unit, int count, Scheduler scheduler) {
return lift(new OperatorWindowWithTime<T>(timespan, timespan, unit, count, scheduler));
}
/**
* Returns an Observable that emits windows of items it collects from the source Observable. The resulting
* Observable emits connected, non-overlapping windows, each of a fixed duration as specified by the {@code timespan} argument. When the source Observable completes or encounters an error, the
* resulting
* Observable emits the current window and propagates the notification from the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window5.s.png">
*
* @param timespan
* the period of time each window collects items before it should be emitted and replaced with a
* new window
* @param unit
* the unit of time which applies to the {@code timespan} argument
* @param scheduler
* the {@link Scheduler} to use when determining the end and start of a window
* @return an Observable that emits connected, non-overlapping windows containing items emitted by the
* source Observable within a fixed duration
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-window">RxJava Wiki: window()</a>
*/
public final Observable<Observable<T>> window(long timespan, TimeUnit unit, Scheduler scheduler) {
return lift(new OperatorWindowWithTime<T>(timespan, timespan, unit, Integer.MAX_VALUE, scheduler));
}
/**
* Returns an Observable that emits windows of items it collects from the source Observable. The resulting
* Observable emits windows that contain those items emitted by the source Observable between the time when
* the {@code windowOpenings} Observable emits an item and when the Observable returned by {@code closingSelector} emits an item.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window2.png">
*
* @param windowOpenings
* an Observable that, when it emits an item, causes another window to be created
* @param closingSelector
* a {@link Func1} that produces an Observable for every window created. When this Observable
* emits an item, the associated window is closed and emitted
* @return an Observable that emits windows of items emitted by the source Observable that are governed by
* the specified window-governing Observables
* @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#wiki-window">RxJava Wiki: window()</a>
*/
public final <TOpening, TClosing> Observable<Observable<T>> window(Observable<? extends TOpening> windowOpenings, Func1<? super TOpening, ? extends Observable<? extends TClosing>> closingSelector) {
return lift(new OperatorWindowWithStartEndObservable<T, TOpening, TClosing>(windowOpenings, closingSelector));
}
/**
* Returns an Observable that emits non-overlapping windows of items it collects from the source Observable
* where the boundary of each window is determined by the items emitted from a specified boundary-governing
* Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window8.png">
*
* @param <U>
* the window element type (ignored)
* @param boundary
* an Observable whose emitted items close and open windows
* @return an Observable that emits non-overlapping windows of items it collects from the source Observable
* where the boundary of each window is determined by the items emitted from the {@code boundary} Observable
*/
public final <U> Observable<Observable<T>> window(Observable<U> boundary) {
return lift(new OperatorWindowWithObservable<T, U>(boundary));
}
/**
* Returns an Observable that emits items that are the result of applying a specified function to pairs of
* values, one each from the source Observable and a specified Iterable sequence.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.i.png">
* <p>
* Note that the {@code other} Iterable is evaluated as items are observed from the source Observable; it is
* not pre-consumed. This allows you to zip infinite streams on either side.
*
* @param <T2>
* the type of items in the {@code other} Iterable
* @param <R>
* the type of items emitted by the resulting Observable
* @param other
* the Iterable sequence
* @param zipFunction
* a function that combines the pairs of items from the Observable and the Iterable to generate
* the items to be emitted by the resulting Observable
* @return an Observable that pairs up values from the source Observable and the {@code other} Iterable
* sequence and emits the results of {@code zipFunction} applied to these pairs
*/
public final <T2, R> Observable<R> zip(Iterable<? extends T2> other, Func2<? super T, ? super T2, ? extends R> zipFunction) {
return lift(new OperatorZipIterable<T, T2, R>(other, zipFunction));
}
/**
* Returns an Observable that emits items that are the result of applying a specified function to pairs of
* values, one each from the source Observable and another specified Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png">
*
* @param <T2>
* the type of items emitted by the {@code other} Observable
* @param <R>
* the type of items emitted by the resulting Observable
* @param other
* the other Observable
* @param zipFunction
* a function that combines the pairs of items from the two Observables to generate the items to
* be emitted by the resulting Observable
* @return an Observable that pairs up values from the source Observable and the {@code other} Observable
* and emits the results of {@code zipFunction} applied to these pairs
*/
public final <T2, R> Observable<R> zip(Observable<? extends T2> other, Func2<? super T, ? super T2, ? extends R> zipFunction) {
return zip(this, other, zipFunction);
}
/**
* An Observable that never sends any information to an {@link Observer}.
*
* This Observable is useful primarily for testing purposes.
*
* @param <T>
* the type of item (not) emitted by the Observable
*/
private static class NeverObservable<T> extends Observable<T> {
public NeverObservable() {
super(new OnSubscribe<T>() {
@Override
public void call(Subscriber<? super T> observer) {
// do nothing
}
});
}
}
/**
* An Observable that invokes {@link Observer#onError onError} when the {@link Observer} subscribes to it.
*
* @param <T>
* the type of item (ostensibly) emitted by the Observable
*/
private static class ThrowObservable<T> extends Observable<T> {
public ThrowObservable(final Throwable exception) {
super(new OnSubscribe<T>() {
/**
* Accepts an {@link Observer} and calls its {@link Observer#onError onError} method.
*
* @param observer
* an {@link Observer} of this Observable
* @return a reference to the subscription
*/
@Override
public void call(Subscriber<? super T> observer) {
observer.onError(exception);
}
});
}
}
}
| Observable.from(T) using Observable.just(T)
For code like `Observable.from(1)` Improve performance from ~3.9m to 4.5+m ops/second
Before;
```
r.u.PerfTransforms.flatMapTransformsUsingFrom 1 thrpt 5 3923845.687 46657.660 ops/s
r.u.PerfTransforms.flatMapTransformsUsingFrom 1024 thrpt 5 8924.953 1983.161 ops/s
r.u.PerfTransforms.flatMapTransformsUsingFrom 1 thrpt 5 3623228.857 490894.492 ops/s
r.u.PerfTransforms.flatMapTransformsUsingFrom 1024 thrpt 5 9176.330 923.929 ops/s
```
After:
```
Benchmark (size) Mode Samples Mean Mean error Units
r.u.PerfTransforms.flatMapTransformsUsingFrom 1 thrpt 5 4052364.587 100971.234 ops/s
r.u.PerfTransforms.flatMapTransformsUsingFrom 1024 thrpt 5 11682.783 496.656 ops/s
Benchmark (size) Mode Samples Mean Mean error Units
r.u.PerfTransforms.flatMapTransformsUsingFrom 1 thrpt 5 4700583.987 77742.037 ops/s
r.u.PerfTransforms.flatMapTransformsUsingFrom 1024 thrpt 5 12588.803 58.935 ops/s
```
Using this test:
```
../gradlew benchmarks '-Pjmh=-f 1 -tu s -bm thrpt -wi 5 -i 5 -r 5 -prof GC .*PerfTransforms.flatMapTransformsUsingFrom*'
```
| rxjava-core/src/main/java/rx/Observable.java | Observable.from(T) using Observable.just(T) | <ide><path>xjava-core/src/main/java/rx/Observable.java
<ide> * @return an Observable that emits the item
<ide> * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-from">RxJava Wiki: from()</a>
<ide> */
<del> // suppress unchecked because we are using varargs inside the method
<del> @SuppressWarnings("unchecked")
<ide> public final static <T> Observable<T> from(T t1) {
<del> return from(Arrays.asList(t1));
<add> return just(t1);
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | 25fe20db66cfa96c524111c775f9415b16917c75 | 0 | acsukesh/java-chassis,acsukesh/java-chassis,ServiceComb/java-chassis,acsukesh/java-chassis,ServiceComb/java-chassis | /*
* 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.servicecomb.config.client;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Joiner;
import com.netflix.config.ConcurrentCompositeConfiguration;
public final class ConfigCenterConfig {
public static final ConfigCenterConfig INSTANCE = new ConfigCenterConfig();
private static ConcurrentCompositeConfiguration finalConfig;
private static final String AUTO_DISCOVERY_ENABLED = "cse.service.registry.autodiscovery";
private static final String SERVER_URL_KEY = "cse.config.client.serverUri";
private static final String REFRESH_MODE = "cse.config.client.refreshMode";
private static final String REFRESH_PORT = "cse.config.client.refreshPort";
private static final String TENANT_NAME = "cse.config.client.tenantName";
private static final String DOMAIN_NAME = "cse.config.client.domainName";
private static final String TOKEN_NAME = "cse.config.client.token";
private static final String URI_API_VERSION = "cse.config.client.api.version";
private static final String REFRESH_INTERVAL = "cse.config.client.refresh_interval";
private static final String FIRST_REFRESH_INTERVAL = "cse.config.client.first_refresh_interval";
private static final String SERVICE_NAME = "service_description.name";
private static final String SERVICE_VERSION = "service_description.version";
private static final String APPLICATION_NAME = "APPLICATION_ID";
private static final String INSTANCE_TAGS = "instance_description.properties.tags";
public static final String PROXY_PRE_NAME = "cse.proxy.";
public static final String PROXY_ENABLE = PROXY_PRE_NAME + "enable";
public static final String PROXY_HOST = PROXY_PRE_NAME + "host";
public static final String PROXY_PORT = PROXY_PRE_NAME + "port";
public static final String PROXY_USERNAME = PROXY_PRE_NAME + "username";
public static final String PROXY_PASSWD = PROXY_PRE_NAME + "passwd";
private static final int DEFAULT_REFRESH_MODE = 0;
private static final int DEFAULT_REFRESH_PORT = 30104;
private static final int DEFAULT_REFRESH_INTERVAL = 30000;
private static final int DEFAULT_FIRST_REFRESH_INTERVAL = 0;
private static final int DEFAULT_TIMEOUT_IN_MS = 30000;
private ConfigCenterConfig() {
}
public static void setConcurrentCompositeConfiguration(ConcurrentCompositeConfiguration config) {
finalConfig = config;
}
public ConcurrentCompositeConfiguration getConcurrentCompositeConfiguration() {
return finalConfig;
}
public int getRefreshMode() {
return finalConfig.getInt(REFRESH_MODE, DEFAULT_REFRESH_MODE);
}
public int getRefreshPort() {
return finalConfig.getInt(REFRESH_PORT, DEFAULT_REFRESH_PORT);
}
public String getTenantName() {
return finalConfig.getString(TENANT_NAME, "default");
}
public String getDomainName() {
return finalConfig.getString(DOMAIN_NAME, "default");
}
public String getToken() {
return finalConfig.getString(TOKEN_NAME, null);
}
public String getApiVersion() {
return finalConfig.getString(URI_API_VERSION, "v3");
}
public int getRefreshInterval() {
return finalConfig.getInt(REFRESH_INTERVAL, DEFAULT_REFRESH_INTERVAL);
}
public int getFirstRefreshInterval() {
return finalConfig.getInt(FIRST_REFRESH_INTERVAL, DEFAULT_FIRST_REFRESH_INTERVAL);
}
public Boolean isProxyEnable() {
return finalConfig.getBoolean(PROXY_ENABLE, false);
}
public String getProxyHost() {
return finalConfig.getString(PROXY_HOST, "127.0.0.1");
}
public int getProxyPort() {
return finalConfig.getInt(PROXY_PORT, 8080);
}
public String getProxyUsername() {
return finalConfig.getString(PROXY_USERNAME, "");
}
public String getProxyPasswd() {
return finalConfig.getString(PROXY_PASSWD, "");
}
@SuppressWarnings("unchecked")
public String getServiceName() {
String service = finalConfig.getString(SERVICE_NAME);
String appName = finalConfig.getString(APPLICATION_NAME);
String tags;
if (appName != null) {
service = service + "@" + appName;
}
String serviceVersion = finalConfig.getString(SERVICE_VERSION);
if (serviceVersion != null) {
service = service + "#" + serviceVersion;
}
Object o = finalConfig.getProperty(INSTANCE_TAGS);
if (o == null) {
return service;
}
if (o instanceof List) {
tags = Joiner.on(",").join((List<String>) o);
} else {
tags = o.toString();
}
service += "!" + tags;
return service;
}
public List<String> getServerUri() {
String[] result = finalConfig.getStringArray(SERVER_URL_KEY);
List<String> configCenterUris = new ArrayList<>(result.length);
for (int i = 0; i < result.length; i++) {
configCenterUris.add(result[i]);
}
return configCenterUris;
}
public boolean getAutoDiscoveryEnabled() {
return finalConfig.getBoolean(AUTO_DISCOVERY_ENABLED, false);
}
public int getConnectionTimeout() {
return finalConfig.getInt("cse.config.client.timeout.connection", DEFAULT_TIMEOUT_IN_MS);
}
}
| dynamic-config/config-cc/src/main/java/org/apache/servicecomb/config/client/ConfigCenterConfig.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.servicecomb.config.client;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Joiner;
import com.netflix.config.ConcurrentCompositeConfiguration;
public final class ConfigCenterConfig {
public static final ConfigCenterConfig INSTANCE = new ConfigCenterConfig();
private static ConcurrentCompositeConfiguration finalConfig;
private static final String AUTO_DISCOVERY_ENABLED = "cse.service.registry.autodiscovery";
private static final String SERVER_URL_KEY = "cse.config.client.serverUri";
private static final String REFRESH_MODE = "cse.config.client.refreshMode";
private static final String REFRESH_PORT = "cse.config.client.refreshPort";
private static final String TENANT_NAME = "cse.config.client.tenantName";
private static final String DOMAIN_NAME = "cse.config.client.domainName";
private static final String TOKEN_NAME = "cse.config.client.token";
private static final String URI_API_VERSION = "cse.config.client.api.version";
private static final String REFRESH_INTERVAL = "cse.config.client.refresh_interval";
private static final String FIRST_REFRESH_INTERVAL = "cse.config.client.first_refresh_interval";
private static final String SERVICE_NAME = "service_description.name";
private static final String SERVICE_VERSION = "service_description.version";
private static final String APPLICATION_NAME = "APPLICATION_ID";
private static final String INSTANCE_TAGS = "instance_description.properties.tags";
public static final String PROXY_PRE_NAME = "cse.proxy.";
public static final String PROXY_ENABLE = PROXY_PRE_NAME + "enable";
public static final String PROXY_HOST = PROXY_PRE_NAME + "host";
public static final String PROXY_PORT = PROXY_PRE_NAME + "port";
public static final String PROXY_USERNAME = PROXY_PRE_NAME + "username";
public static final String PROXY_PASSWD = PROXY_PRE_NAME + "passwd";
private static final int DEFAULT_REFRESH_MODE = 0;
private static final int DEFAULT_REFRESH_PORT = 30104;
private static final int DEFAULT_REFRESH_INTERVAL = 30000;
private static final int DEFAULT_FIRST_REFRESH_INTERVAL = 0;
private static final int DEFAULT_TIMEOUT_IN_MS = 30000;
private ConfigCenterConfig() {
}
public static void setConcurrentCompositeConfiguration(ConcurrentCompositeConfiguration config) {
finalConfig = config;
}
public ConcurrentCompositeConfiguration getConcurrentCompositeConfiguration() {
return finalConfig;
}
public int getRefreshMode() {
return finalConfig.getInt(REFRESH_MODE, DEFAULT_REFRESH_MODE);
}
public int getRefreshPort() {
return finalConfig.getInt(REFRESH_PORT, DEFAULT_REFRESH_PORT);
}
public String getTenantName() {
return finalConfig.getString(TENANT_NAME, "default");
}
public String getDomainName() {
return finalConfig.getString(DOMAIN_NAME, "default");
}
public String getToken() {
return finalConfig.getString(TOKEN_NAME, null);
}
public String getApiVersion() {
return finalConfig.getString(URI_API_VERSION, "v3");
}
public int getRefreshInterval() {
return finalConfig.getInt(REFRESH_INTERVAL, DEFAULT_REFRESH_INTERVAL);
}
public int getFirstRefreshInterval() {
return finalConfig.getInt(FIRST_REFRESH_INTERVAL, DEFAULT_FIRST_REFRESH_INTERVAL);
}
public Boolean isProxyEnable() {
return finalConfig.getBoolean(PROXY_ENABLE, false);
}
public String getProxyHost() {
return finalConfig.getString(PROXY_HOST, "127.0.0.1");
}
public int getProxyPort() {
return finalConfig.getInt(PROXY_PORT, 8080);
}
public String getProxyUsername() {
return finalConfig.getString(PROXY_USERNAME, "user");
}
public String getProxyPasswd() {
return finalConfig.getString(PROXY_PASSWD, "passwd");
}
@SuppressWarnings("unchecked")
public String getServiceName() {
String service = finalConfig.getString(SERVICE_NAME);
String appName = finalConfig.getString(APPLICATION_NAME);
String tags;
if (appName != null) {
service = service + "@" + appName;
}
String serviceVersion = finalConfig.getString(SERVICE_VERSION);
if (serviceVersion != null) {
service = service + "#" + serviceVersion;
}
Object o = finalConfig.getProperty(INSTANCE_TAGS);
if (o == null) {
return service;
}
if (o instanceof List) {
tags = Joiner.on(",").join((List<String>) o);
} else {
tags = o.toString();
}
service += "!" + tags;
return service;
}
public List<String> getServerUri() {
String[] result = finalConfig.getStringArray(SERVER_URL_KEY);
List<String> configCenterUris = new ArrayList<>(result.length);
for (int i = 0; i < result.length; i++) {
configCenterUris.add(result[i]);
}
return configCenterUris;
}
public boolean getAutoDiscoveryEnabled() {
return finalConfig.getBoolean(AUTO_DISCOVERY_ENABLED, false);
}
public int getConnectionTimeout() {
return finalConfig.getInt("cse.config.client.timeout.connection", DEFAULT_TIMEOUT_IN_MS);
}
}
| [SCB-322] use empty string as default PROXY_USER and PROXY_PASSWD
| dynamic-config/config-cc/src/main/java/org/apache/servicecomb/config/client/ConfigCenterConfig.java | [SCB-322] use empty string as default PROXY_USER and PROXY_PASSWD | <ide><path>ynamic-config/config-cc/src/main/java/org/apache/servicecomb/config/client/ConfigCenterConfig.java
<ide> }
<ide>
<ide> public String getProxyUsername() {
<del> return finalConfig.getString(PROXY_USERNAME, "user");
<add> return finalConfig.getString(PROXY_USERNAME, "");
<ide> }
<ide>
<ide> public String getProxyPasswd() {
<del> return finalConfig.getString(PROXY_PASSWD, "passwd");
<add> return finalConfig.getString(PROXY_PASSWD, "");
<ide> }
<ide>
<ide> @SuppressWarnings("unchecked") |
|
Java | apache-2.0 | 5b05547585bdf2914b727d25d30894f40643ea66 | 0 | HashEngineering/megacoinj,HashEngineering/megacoinj,HashEngineering/megacoinj | package com.google.bitcoin.core;
import java.math.BigInteger;
import java.util.Date;
import java.util.Map;
import java.util.Vector;
/**
* Created with IntelliJ IDEA.
* User: HashEngineering
* Date: 8/13/13
* Time: 7:23 PM
* To change this template use File | Settings | File Templates.
*/
public class CoinDefinition {
public static final String coinName = "Megacoin";
public static final String coinTicker = "MEC";
public static final String coinURIScheme = "megacoin";
public static final String cryptsyMarketId = "45";
public static final String cryptsyMarketCurrency = "BTC";
public static final String BLOCKEXPLORER_BASE_URL_PROD = "https://coinplorer.com/MEC/";
public static final String BLOCKEXPLORER_BASE_URL_TEST = "https://coinplorer.com/MEC/";
public static final String DONATION_ADDRESS = "MVB27rjvdL36pszWVeBgRMUbc2hQB2Scsz"; //HashEngineering donation DGC address
enum CoinHash {
SHA256,
scrypt
};
public static final CoinHash coinHash = CoinHash.scrypt;
//Original Values
public static final int TARGET_TIMESPAN_0 = (int)(6 * 60 * 3 * 20); // 3.5 days per difficulty cycle, on average.
public static final int TARGET_SPACING_0 = (int)(150); // 2.5 minutes per block.
public static final int INTERVAL_0 = TARGET_TIMESPAN_0 / TARGET_SPACING_0; //2016 blocks
public static final int TARGET_TIMESPAN = (int)(150 * 9); // 22.5 minutes per difficulty cycle, on average.
public static final int TARGET_SPACING = (int)(150); // 2.5 minutes per block.
public static final int INTERVAL = TARGET_TIMESPAN / TARGET_SPACING; //9 blocks
public static final int TARGET_TIMESPAN_3 = 150; // 22.5 minutes per difficulty cycle, on average.
public static final int TARGET_SPACING_3 = (int)(150); // 2.5 minutes per block.
public static final int INTERVAL_3 = TARGET_TIMESPAN_3 / TARGET_SPACING_3; //9 blocks
static final long nTargetSpacing = 150; // 2.5 minutes
static final long nOriginalInterval = 2016;
static final long nFilteredInterval = 9;
static final long nOriginalTargetTimespan = nOriginalInterval * nTargetSpacing; // 3.5 days
static final long nFilteredTargetTimespan = nFilteredInterval * nTargetSpacing; // 22.5 minutes
public static int DIFF_FILTER_THRESHOLD_TESTNET = 8192;
public static int DIFF_FILTER_THRESHOLD = 8192;
public static int nDifficultySwitchHeight = 8192;
public static int nDifficultySwitchHeightTwo = 62773;
public static final int getInterval(int height, boolean testNet) {
if(height < nDifficultySwitchHeight)
return (int)nOriginalInterval; //1080
else if(height < nDifficultySwitchHeightTwo)
return (int)nFilteredInterval; //108
else return INTERVAL_3;
}
public static final int getIntervalForCheckpoints(int height, boolean testNet) {
if(height < 8050)
return (int)nOriginalInterval; //2016
else if(height < nDifficultySwitchHeightTwo)
return (int)nOriginalInterval; //2016
else return (int)nOriginalInterval / 4; //504
}
public static final int getTargetTimespan(int height, boolean testNet) {
if(height < nDifficultySwitchHeight)
return TARGET_TIMESPAN_0; //3.5 days
else
return TARGET_TIMESPAN; //72 min
}
public static int getMaxTimeSpan(int value, int height, boolean testNet)
{
if(height < nDifficultySwitchHeight)
return value * 4;
else
return value * 1; // not used
}
public static int getMinTimeSpan(int value, int height, boolean testNet)
{
if(height < nDifficultySwitchHeight)
return value / 4;
else
return value * 1; //not used
}
public static int spendableCoinbaseDepth = 100; //main.h: static const int COINBASE_MATURITY
public static final int MAX_MONEY = 42000000; //main.h: MAX_MONEY
public static final String MAX_MONEY_STRING = "42000000"; //main.h: MAX_MONEY
public static final BigInteger DEFAULT_MIN_TX_FEE = BigInteger.valueOf(10000); // MIN_TX_FEE
public static final BigInteger DUST_LIMIT = Utils.CENT; //main.h CTransaction::GetMinFee 0.01 coins
public static final int PROTOCOL_VERSION = 70001; //version.h PROTOCOL_VERSION
public static final int MIN_PROTOCOL_VERSION = 209; //version.h MIN_PROTO_VERSION
public static final boolean supportsBloomFiltering = true; //Requires PROTOCOL_VERSION 70000 in the client
public static final int Port = 7951; //protocol.h GetDefaultPort(testnet=false)
public static final int TestPort = 17951; //protocol.h GetDefaultPort(testnet=true)
//
// Production
//
public static final int AddressHeader = 50; //base58.h CBitcoinAddress::PUBKEY_ADDRESS
public static final int p2shHeader = 5; //base58.h CBitcoinAddress::SCRIPT_ADDRESS
public static final int dumpedPrivateKeyHeader = 128; //common to all coins
public static final long PacketMagic = 0xede0e4ee; //0xfb, 0xc0, 0xb6, 0xdb
//Genesis Block Information from main.cpp: LoadBlockIndex
static public long genesisBlockDifficultyTarget = (0x1e0ffff0L); //main.cpp: LoadBlockIndex
static public long genesisBlockTime = 1369197853L; //main.cpp: LoadBlockIndex
static public long genesisBlockNonce = (2084576387); //main.cpp: LoadBlockIndex
static public String genesisHash = "7520788e2d99eec7cf6cf7315577e1268e177fff94cb0a7caf6a458ceeea9ac2"; //main.cpp: hashGenesisBlock
static public int genesisBlockValue = 500; //main.cpp: LoadBlockIndex
//taken from the raw data of the block explorer
static public String genesisXInBytes = "04ffff001d01044c4c426f73746f6e20486572616c64202d2032312f4d61792f32303133202d20495253204f6666696369616c20746f2054616b6520466966746820746f2041766f69642054657374696679696e67"; //"Boston Herald - 21/May/2013 - IRS Official to Take Fifth to Avoid Testifying"
static public String genessiXOutBytes = "0411582e4e718df82c9d75a4886ab7602f0a1b866d81a4e44acba04e847ccd0514b97bee4a61fa73b1474d12851422b01565f244f722f318f1608258b74a3f3fe6";
//net.cpp strDNSSeed
static public String[] dnsSeeds = new String[] {
"144.76.166.163",
"192.99.9.229",
"54.186.9.232",
"mega.rapta.net",
"minepool.net",
"78.46.22.103",
"67.238.163.221",
"217.65.56.200",
"67.210.249.29",
};
//
// TestNet - digitalcoin - not tested
//
public static final boolean supportsTestNet = false;
public static final int testnetAddressHeader = 111; //base58.h CBitcoinAddress::PUBKEY_ADDRESS_TEST
public static final int testnetp2shHeader = 196; //base58.h CBitcoinAddress::SCRIPT_ADDRESS_TEST
public static final long testnetPacketMagic = 0xfdf0f4fe; //0xfc, 0xc1, 0xb7, 0xdc
public static final String testnetGenesisHash = "5e039e1ca1dbf128973bf6cff98169e40a1b194c3b91463ab74956f413b2f9c8";
static public long testnetGenesisBlockDifficultyTarget = (0x1e0ffff0L); //main.cpp: LoadBlockIndex
static public long testnetGenesisBlockTime = 1369198853L; //main.cpp: LoadBlockIndex
static public long testnetGenesisBlockNonce = (386245382); //main.cpp: LoadBlockIndex
//main.cpp GetBlockValue(height, fee)
public static BigInteger GetBlockReward(int height)
{
int COIN = 1;
BigInteger nSubsidy = Utils.toNanoCoins(500,0);
/*
Total Coins: 42 Million
* 1st 5 Months, 21 Million Coins will be generated
Every 21,000 Blocks (1 Month) the reward steps down from 500, 250, 125, 75, 50.
* Through the next few decades the Remaining 21 Million will be generated
Every 420,000 Blocks (2 Years), The reward starts at 25 and is Halved each period
10.5 Million come from first 2 Years of 420K Blocks
*/
int BlockCountA = 21000;
int BlockCountB = 420000;
if (height >= BlockCountA * 5)
{
nSubsidy = Utils.toNanoCoins(25 * COIN, 0);
nSubsidy = nSubsidy.shiftRight(((height - (BlockCountA * 5)) / (BlockCountB))); // Subsidy is cut in half every 420000 blocks
}
else if (height >= BlockCountA * 4) { nSubsidy = Utils.toNanoCoins(50 * COIN, 0); }
else if (height >= BlockCountA * 3) { nSubsidy = Utils.toNanoCoins(75 * COIN, 0); }
else if (height >= BlockCountA * 2) { nSubsidy = Utils.toNanoCoins(125 * COIN, 0); }
else if (height >= BlockCountA) { nSubsidy = Utils.toNanoCoins(250 * COIN, 0); }
else { nSubsidy = Utils.toNanoCoins(500,0); }
return nSubsidy;
}
public static int subsidyDecreaseBlockCount = 420000; //main.cpp GetBlockValue(height, fee)
public static BigInteger proofOfWorkLimit = Utils.decodeCompactBits(0x1e0fffffL); //main.cpp bnProofOfWorkLimit (~uint256(0) >> 20); // digitalcoin: starting difficulty is 1 / 2^12
static public String[] testnetDnsSeeds = new String[] {
"not supported"
};
//from main.h: CAlert::CheckSignature
public static final String SATOSHI_KEY = "04680D5270D3E6BA9E2671D889778FC4A0753FF036171D553A179635DDE67146481AB4EA7A6856CBB6A97AE16E7820F2F318E88F21E9BCFB0380E52BD63306C05C";
public static final String TESTNET_SATOSHI_KEY = "04826AC11FCF383A1E0F21E2A76807D082FF4E7F139111A7768E4F5A35A5653A2D44A8E19BC8B55AEDC9F9238D424BDC5EBD6D2BAF9CB3D30CEDEA35C47C8350A0";
/** The string returned by getId() for the main, production network where people trade things. */
public static final String ID_MAINNET = "org.megacoin.production";
/** The string returned by getId() for the testnet. */
public static final String ID_TESTNET = "org.megacoin.test";
/** Unit test network. */
public static final String ID_UNITTESTNET = "com.google.megacoin.unittest";
//checkpoints.cpp Checkpoints::mapCheckpoints
public static void initCheckpoints(Map<Integer, Sha256Hash> checkpoints)
{
checkpoints.put( 5215, new Sha256Hash("f8a7fec79eeee3228499601c614b179d09b1b08bd58515be8a2795f6baafb493"));
checkpoints.put( 7333, new Sha256Hash("f798f245214a5ed83c69d362a88c48047c82675d3bf84b0c88d6f1c71ed4b372"));
checkpoints.put( 9850, new Sha256Hash("03359392dab8f47cd70626bb978c7658a385a49570bd953a1c9f8ceed4ff8be6"));
checkpoints.put( 10000, new Sha256Hash("e17057f2114a45827acbcfe2a55b273ccabd3dc8982765f7a3fbca166811909b"));
checkpoints.put( 15480, new Sha256Hash("f682a44431fff21c5d412f97e92f3340c59527626f6b5a4c6b85de78e009f177"));
checkpoints.put( 17625, new Sha256Hash("5c4df33d72bef0c9e95bcce997e0c1d5985e957a16aebbf463a8bbee1ab9eb4b"));
checkpoints.put( 21190, new Sha256Hash("e960216ff0e3ebae632af05792f0a11bf8a8f61e4f5ef43fcfd84b6e8053ec59"));
checkpoints.put( 35500, new Sha256Hash("b88a54ce5d247a46166ff28228c62efc495cfb8d0dadfa895bced191cb261c90"));
checkpoints.put( 39500, new Sha256Hash("3eb61d9897009caa6ed492fc154121849166d7a627f26322eae9cf32c7dc753b"));
checkpoints.put( 44400, new Sha256Hash("eb5af032f88981810f31f13e38e33c86585dbf963ea6de199382706dc5b3aee4"));
checkpoints.put( 59300, new Sha256Hash("558cf1f1fe31eb0816f9fc73900133564c29b50b626cbf82c69860fd3583653c"));
checkpoints.put( 62767, new Sha256Hash("5bd5d25c8a19b764634435b9ab1121b4678fbf6e6ad771b252f75f3cdfa82131"));
checkpoints.put( 96800, new Sha256Hash("f972b9421ac790af82cd63f5db1dbbee114ce3476486d4335f46c6d7d8897671"));
}
}
| core/src/main/java/com/google/bitcoin/core/CoinDefinition.java | package com.google.bitcoin.core;
import java.math.BigInteger;
import java.util.Date;
import java.util.Map;
import java.util.Vector;
/**
* Created with IntelliJ IDEA.
* User: HashEngineering
* Date: 8/13/13
* Time: 7:23 PM
* To change this template use File | Settings | File Templates.
*/
public class CoinDefinition {
public static final String coinName = "Megacoin";
public static final String coinTicker = "MEC";
public static final String coinURIScheme = "megacoin";
public static final String cryptsyMarketId = "45";
public static final String cryptsyMarketCurrency = "BTC";
public static final String BLOCKEXPLORER_BASE_URL_PROD = "https://coinplorer.com/MEC/";
public static final String BLOCKEXPLORER_BASE_URL_TEST = "https://coinplorer.com/MEC/";
public static final String DONATION_ADDRESS = "MVB27rjvdL36pszWVeBgRMUbc2hQB2Scsz"; //HashEngineering donation DGC address
enum CoinHash {
SHA256,
scrypt
};
public static final CoinHash coinHash = CoinHash.scrypt;
//Original Values
public static final int TARGET_TIMESPAN_0 = (int)(6 * 60 * 3 * 20); // 3.5 days per difficulty cycle, on average.
public static final int TARGET_SPACING_0 = (int)(150); // 2.5 minutes per block.
public static final int INTERVAL_0 = TARGET_TIMESPAN_0 / TARGET_SPACING_0; //2016 blocks
public static final int TARGET_TIMESPAN = (int)(150 * 9); // 22.5 minutes per difficulty cycle, on average.
public static final int TARGET_SPACING = (int)(150); // 2.5 minutes per block.
public static final int INTERVAL = TARGET_TIMESPAN / TARGET_SPACING; //9 blocks
public static final int TARGET_TIMESPAN_3 = 150; // 22.5 minutes per difficulty cycle, on average.
public static final int TARGET_SPACING_3 = (int)(150); // 2.5 minutes per block.
public static final int INTERVAL_3 = TARGET_TIMESPAN_3 / TARGET_SPACING_3; //9 blocks
static final long nTargetSpacing = 150; // 2.5 minutes
static final long nOriginalInterval = 2016;
static final long nFilteredInterval = 9;
static final long nOriginalTargetTimespan = nOriginalInterval * nTargetSpacing; // 3.5 days
static final long nFilteredTargetTimespan = nFilteredInterval * nTargetSpacing; // 22.5 minutes
public static int DIFF_FILTER_THRESHOLD_TESTNET = 8192;
public static int DIFF_FILTER_THRESHOLD = 8192;
public static int nDifficultySwitchHeight = 8192;
public static int nDifficultySwitchHeightTwo = 62773;
public static final int getInterval(int height, boolean testNet) {
if(height < nDifficultySwitchHeight)
return (int)nOriginalInterval; //1080
else if(height < nDifficultySwitchHeightTwo)
return (int)nFilteredInterval; //108
else return INTERVAL_3;
}
public static final int getIntervalForCheckpoints(int height, boolean testNet) {
if(height < 8050)
return (int)nOriginalInterval; //2016
else if(height < nDifficultySwitchHeightTwo)
return (int)nOriginalInterval; //2016
else return (int)nOriginalInterval / 4; //504
}
public static final int getTargetTimespan(int height, boolean testNet) {
if(height < nDifficultySwitchHeight)
return TARGET_TIMESPAN_0; //3.5 days
else
return TARGET_TIMESPAN; //72 min
}
public static int getMaxTimeSpan(int value, int height, boolean testNet)
{
if(height < nDifficultySwitchHeight)
return value * 4;
else
return value * 1; // not used
}
public static int getMinTimeSpan(int value, int height, boolean testNet)
{
if(height < nDifficultySwitchHeight)
return value / 4;
else
return value * 1; //not used
}
public static int spendableCoinbaseDepth = 100; //main.h: static const int COINBASE_MATURITY
public static final int MAX_MONEY = 42000000; //main.h: MAX_MONEY
public static final String MAX_MONEY_STRING = "42000000"; //main.h: MAX_MONEY
public static final BigInteger DEFAULT_MIN_TX_FEE = BigInteger.valueOf(10000); // MIN_TX_FEE
public static final BigInteger DUST_LIMIT = Utils.CENT; //main.h CTransaction::GetMinFee 0.01 coins
public static final int PROTOCOL_VERSION = 70001; //version.h PROTOCOL_VERSION
public static final int MIN_PROTOCOL_VERSION = 209; //version.h MIN_PROTO_VERSION
public static final boolean supportsBloomFiltering = true; //Requires PROTOCOL_VERSION 70000 in the client
public static final int Port = 7951; //protocol.h GetDefaultPort(testnet=false)
public static final int TestPort = 17951; //protocol.h GetDefaultPort(testnet=true)
//
// Production
//
public static final int AddressHeader = 50; //base58.h CBitcoinAddress::PUBKEY_ADDRESS
public static final int p2shHeader = 5; //base58.h CBitcoinAddress::SCRIPT_ADDRESS
public static final int dumpedPrivateKeyHeader = 128; //common to all coins
public static final long PacketMagic = 0xede0e4ee; //0xfb, 0xc0, 0xb6, 0xdb
//Genesis Block Information from main.cpp: LoadBlockIndex
static public long genesisBlockDifficultyTarget = (0x1e0ffff0L); //main.cpp: LoadBlockIndex
static public long genesisBlockTime = 1369197853L; //main.cpp: LoadBlockIndex
static public long genesisBlockNonce = (2084576387); //main.cpp: LoadBlockIndex
static public String genesisHash = "7520788e2d99eec7cf6cf7315577e1268e177fff94cb0a7caf6a458ceeea9ac2"; //main.cpp: hashGenesisBlock
static public int genesisBlockValue = 500; //main.cpp: LoadBlockIndex
//taken from the raw data of the block explorer
static public String genesisXInBytes = "04ffff001d01044c4c426f73746f6e20486572616c64202d2032312f4d61792f32303133202d20495253204f6666696369616c20746f2054616b6520466966746820746f2041766f69642054657374696679696e67"; //"Boston Herald - 21/May/2013 - IRS Official to Take Fifth to Avoid Testifying"
static public String genessiXOutBytes = "0411582e4e718df82c9d75a4886ab7602f0a1b866d81a4e44acba04e847ccd0514b97bee4a61fa73b1474d12851422b01565f244f722f318f1608258b74a3f3fe6";
//net.cpp strDNSSeed
static public String[] dnsSeeds = new String[] {
"67.238.163.221",
"217.65.56.200",
"67.210.249.29",
"144.76.166.163",
"78.46.22.103",
"192.99.9.229",
};
//
// TestNet - digitalcoin - not tested
//
public static final boolean supportsTestNet = false;
public static final int testnetAddressHeader = 111; //base58.h CBitcoinAddress::PUBKEY_ADDRESS_TEST
public static final int testnetp2shHeader = 196; //base58.h CBitcoinAddress::SCRIPT_ADDRESS_TEST
public static final long testnetPacketMagic = 0xfdf0f4fe; //0xfc, 0xc1, 0xb7, 0xdc
public static final String testnetGenesisHash = "5e039e1ca1dbf128973bf6cff98169e40a1b194c3b91463ab74956f413b2f9c8";
static public long testnetGenesisBlockDifficultyTarget = (0x1e0ffff0L); //main.cpp: LoadBlockIndex
static public long testnetGenesisBlockTime = 1369198853L; //main.cpp: LoadBlockIndex
static public long testnetGenesisBlockNonce = (386245382); //main.cpp: LoadBlockIndex
//main.cpp GetBlockValue(height, fee)
public static BigInteger GetBlockReward(int height)
{
int COIN = 1;
BigInteger nSubsidy = Utils.toNanoCoins(500,0);
/*
Total Coins: 42 Million
* 1st 5 Months, 21 Million Coins will be generated
Every 21,000 Blocks (1 Month) the reward steps down from 500, 250, 125, 75, 50.
* Through the next few decades the Remaining 21 Million will be generated
Every 420,000 Blocks (2 Years), The reward starts at 25 and is Halved each period
10.5 Million come from first 2 Years of 420K Blocks
*/
int BlockCountA = 21000;
int BlockCountB = 420000;
if (height >= BlockCountA * 5)
{
nSubsidy = Utils.toNanoCoins(25 * COIN, 0);
nSubsidy = nSubsidy.shiftRight(((height - (BlockCountA * 5)) / (BlockCountB))); // Subsidy is cut in half every 420000 blocks
}
else if (height >= BlockCountA * 4) { nSubsidy = Utils.toNanoCoins(50 * COIN, 0); }
else if (height >= BlockCountA * 3) { nSubsidy = Utils.toNanoCoins(75 * COIN, 0); }
else if (height >= BlockCountA * 2) { nSubsidy = Utils.toNanoCoins(125 * COIN, 0); }
else if (height >= BlockCountA) { nSubsidy = Utils.toNanoCoins(250 * COIN, 0); }
else { nSubsidy = Utils.toNanoCoins(500,0); }
return nSubsidy;
}
public static int subsidyDecreaseBlockCount = 420000; //main.cpp GetBlockValue(height, fee)
public static BigInteger proofOfWorkLimit = Utils.decodeCompactBits(0x1e0fffffL); //main.cpp bnProofOfWorkLimit (~uint256(0) >> 20); // digitalcoin: starting difficulty is 1 / 2^12
static public String[] testnetDnsSeeds = new String[] {
"not supported"
};
//from main.h: CAlert::CheckSignature
public static final String SATOSHI_KEY = "04680D5270D3E6BA9E2671D889778FC4A0753FF036171D553A179635DDE67146481AB4EA7A6856CBB6A97AE16E7820F2F318E88F21E9BCFB0380E52BD63306C05C";
public static final String TESTNET_SATOSHI_KEY = "04826AC11FCF383A1E0F21E2A76807D082FF4E7F139111A7768E4F5A35A5653A2D44A8E19BC8B55AEDC9F9238D424BDC5EBD6D2BAF9CB3D30CEDEA35C47C8350A0";
/** The string returned by getId() for the main, production network where people trade things. */
public static final String ID_MAINNET = "org.megacoin.production";
/** The string returned by getId() for the testnet. */
public static final String ID_TESTNET = "org.megacoin.test";
/** Unit test network. */
public static final String ID_UNITTESTNET = "com.google.megacoin.unittest";
//checkpoints.cpp Checkpoints::mapCheckpoints
public static void initCheckpoints(Map<Integer, Sha256Hash> checkpoints)
{
checkpoints.put( 5215, new Sha256Hash("f8a7fec79eeee3228499601c614b179d09b1b08bd58515be8a2795f6baafb493"));
checkpoints.put( 7333, new Sha256Hash("f798f245214a5ed83c69d362a88c48047c82675d3bf84b0c88d6f1c71ed4b372"));
checkpoints.put( 9850, new Sha256Hash("03359392dab8f47cd70626bb978c7658a385a49570bd953a1c9f8ceed4ff8be6"));
checkpoints.put( 10000, new Sha256Hash("e17057f2114a45827acbcfe2a55b273ccabd3dc8982765f7a3fbca166811909b"));
checkpoints.put( 15480, new Sha256Hash("f682a44431fff21c5d412f97e92f3340c59527626f6b5a4c6b85de78e009f177"));
checkpoints.put( 17625, new Sha256Hash("5c4df33d72bef0c9e95bcce997e0c1d5985e957a16aebbf463a8bbee1ab9eb4b"));
checkpoints.put( 21190, new Sha256Hash("e960216ff0e3ebae632af05792f0a11bf8a8f61e4f5ef43fcfd84b6e8053ec59"));
checkpoints.put( 35500, new Sha256Hash("b88a54ce5d247a46166ff28228c62efc495cfb8d0dadfa895bced191cb261c90"));
checkpoints.put( 39500, new Sha256Hash("3eb61d9897009caa6ed492fc154121849166d7a627f26322eae9cf32c7dc753b"));
checkpoints.put( 44400, new Sha256Hash("eb5af032f88981810f31f13e38e33c86585dbf963ea6de199382706dc5b3aee4"));
checkpoints.put( 59300, new Sha256Hash("558cf1f1fe31eb0816f9fc73900133564c29b50b626cbf82c69860fd3583653c"));
checkpoints.put( 62767, new Sha256Hash("5bd5d25c8a19b764634435b9ab1121b4678fbf6e6ad771b252f75f3cdfa82131"));
checkpoints.put( 96800, new Sha256Hash("f972b9421ac790af82cd63f5db1dbbee114ce3476486d4335f46c6d7d8897671"));
}
}
| Updated DNS Seeds
| core/src/main/java/com/google/bitcoin/core/CoinDefinition.java | Updated DNS Seeds | <ide><path>ore/src/main/java/com/google/bitcoin/core/CoinDefinition.java
<ide>
<ide> //net.cpp strDNSSeed
<ide> static public String[] dnsSeeds = new String[] {
<del> "67.238.163.221",
<del> "217.65.56.200",
<add> "144.76.166.163",
<add> "192.99.9.229",
<add> "54.186.9.232",
<add> "mega.rapta.net",
<add> "minepool.net",
<add> "78.46.22.103",
<add> "67.238.163.221",
<add> "217.65.56.200",
<ide> "67.210.249.29",
<del> "144.76.166.163",
<del> "78.46.22.103",
<del> "192.99.9.229",
<add>
<add>
<ide>
<ide> };
<ide> |
|
Java | apache-2.0 | 9b7d630ae78dc5abbcaff663eef58a4212498d4f | 0 | darranl/undertow,baranowb/undertow,pferraro/undertow,n1hility/undertow,golovnin/undertow,n1hility/undertow,rhusar/undertow,aldaris/undertow,Karm/undertow,msfm/undertow,stuartwdouglas/undertow,jamezp/undertow,aldaris/undertow,msfm/undertow,undertow-io/undertow,ctomc/undertow,Karm/undertow,baranowb/undertow,rhusar/undertow,darranl/undertow,jstourac/undertow,n1hility/undertow,pferraro/undertow,undertow-io/undertow,soul2zimate/undertow,soul2zimate/undertow,rhusar/undertow,jamezp/undertow,ctomc/undertow,stuartwdouglas/undertow,jstourac/undertow,jstourac/undertow,stuartwdouglas/undertow,baranowb/undertow,soul2zimate/undertow,darranl/undertow,msfm/undertow,Karm/undertow,ctomc/undertow,golovnin/undertow,golovnin/undertow,pferraro/undertow,undertow-io/undertow,jamezp/undertow,aldaris/undertow | /*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.undertow;
import io.undertow.protocols.ssl.UndertowXnioSsl;
import io.undertow.server.ConnectorStatistics;
import io.undertow.server.DefaultByteBufferPool;
import io.undertow.server.HttpHandler;
import io.undertow.server.OpenListener;
import io.undertow.server.protocol.ajp.AjpOpenListener;
import io.undertow.server.protocol.http.AlpnOpenListener;
import io.undertow.server.protocol.http.HttpOpenListener;
import io.undertow.server.protocol.http2.Http2OpenListener;
import org.xnio.ChannelListener;
import org.xnio.ChannelListeners;
import org.xnio.IoUtils;
import org.xnio.Option;
import org.xnio.OptionMap;
import org.xnio.Options;
import io.undertow.connector.ByteBufferPool;
import org.xnio.StreamConnection;
import org.xnio.Xnio;
import org.xnio.XnioWorker;
import org.xnio.channels.AcceptingChannel;
import org.xnio.ssl.JsseSslUtils;
import org.xnio.ssl.SslConnection;
import org.xnio.ssl.XnioSsl;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Convenience class used to build an Undertow server.
* <p>
*
* @author Stuart Douglas
*/
public final class Undertow {
private final int bufferSize;
private final int ioThreads;
private final int workerThreads;
private final boolean directBuffers;
private final List<ListenerConfig> listeners = new ArrayList<>();
private volatile List<ListenerInfo> listenerInfo;
private final HttpHandler rootHandler;
private final OptionMap workerOptions;
private final OptionMap socketOptions;
private final OptionMap serverOptions;
/**
* Will be true when a {@link XnioWorker} instance was NOT provided to the {@link Builder}.
* When true, a new worker will be created during {@link Undertow#start()},
* and shutdown when {@link Undertow#stop()} is called.
*
* Will be false when a {@link XnioWorker} instance was provided to the {@link Builder}.
* When false, the provided {@link #worker} will be used instead of creating a new one in {@link Undertow#start()}.
* Also, when false, the {@link #worker} will NOT be shutdown when {@link Undertow#stop()} is called.
*/
private final boolean internalWorker;
private XnioWorker worker;
private List<AcceptingChannel<? extends StreamConnection>> channels;
private Xnio xnio;
private Undertow(Builder builder) {
this.bufferSize = builder.bufferSize;
this.ioThreads = builder.ioThreads;
this.workerThreads = builder.workerThreads;
this.directBuffers = builder.directBuffers;
this.listeners.addAll(builder.listeners);
this.rootHandler = builder.handler;
this.worker = builder.worker;
this.internalWorker = builder.worker == null;
this.workerOptions = builder.workerOptions.getMap();
this.socketOptions = builder.socketOptions.getMap();
this.serverOptions = builder.serverOptions.getMap();
}
/**
* @return A builder that can be used to create an Undertow server instance
*/
public static Builder builder() {
return new Builder();
}
public synchronized void start() {
UndertowLogger.ROOT_LOGGER.debugf("starting undertow server %s", this);
xnio = Xnio.getInstance(Undertow.class.getClassLoader());
channels = new ArrayList<>();
try {
if (internalWorker) {
worker = xnio.createWorker(OptionMap.builder()
.set(Options.WORKER_IO_THREADS, ioThreads)
.set(Options.CONNECTION_HIGH_WATER, 1000000)
.set(Options.CONNECTION_LOW_WATER, 1000000)
.set(Options.WORKER_TASK_CORE_THREADS, workerThreads)
.set(Options.WORKER_TASK_MAX_THREADS, workerThreads)
.set(Options.TCP_NODELAY, true)
.set(Options.CORK, true)
.addAll(workerOptions)
.getMap());
}
OptionMap socketOptions = OptionMap.builder()
.set(Options.WORKER_IO_THREADS, worker.getIoThreadCount())
.set(Options.TCP_NODELAY, true)
.set(Options.REUSE_ADDRESSES, true)
.set(Options.BALANCING_TOKENS, 1)
.set(Options.BALANCING_CONNECTIONS, 2)
.set(Options.BACKLOG, 1000)
.addAll(this.socketOptions)
.getMap();
OptionMap serverOptions = OptionMap.builder()
.set(UndertowOptions.NO_REQUEST_TIMEOUT, 60 * 1000)
.addAll(this.serverOptions)
.getMap();
ByteBufferPool buffers = new DefaultByteBufferPool(directBuffers, bufferSize, -1, 4);
listenerInfo = new ArrayList<>();
for (ListenerConfig listener : listeners) {
UndertowLogger.ROOT_LOGGER.debugf("Configuring listener with protocol %s for interface %s and port %s", listener.type, listener.host, listener.port);
final HttpHandler rootHandler = listener.rootHandler != null ? listener.rootHandler : this.rootHandler;
if (listener.type == ListenerType.AJP) {
AjpOpenListener openListener = new AjpOpenListener(buffers, serverOptions);
openListener.setRootHandler(rootHandler);
ChannelListener<AcceptingChannel<StreamConnection>> acceptListener = ChannelListeners.openListenerAdapter(openListener);
AcceptingChannel<? extends StreamConnection> server = worker.createStreamConnectionServer(new InetSocketAddress(Inet4Address.getByName(listener.host), listener.port), acceptListener, socketOptions);
server.resumeAccepts();
channels.add(server);
listenerInfo.add(new ListenerInfo("ajp", server.getLocalAddress(), null, openListener));
} else {
OptionMap undertowOptions = OptionMap.builder().set(UndertowOptions.BUFFER_PIPELINED_DATA, true).addAll(serverOptions).getMap();
if (listener.type == ListenerType.HTTP) {
HttpOpenListener openListener = new HttpOpenListener(buffers, undertowOptions);
openListener.setRootHandler(rootHandler);
ChannelListener<AcceptingChannel<StreamConnection>> acceptListener = ChannelListeners.openListenerAdapter(openListener);
AcceptingChannel<? extends StreamConnection> server = worker.createStreamConnectionServer(new InetSocketAddress(Inet4Address.getByName(listener.host), listener.port), acceptListener, socketOptions);
server.resumeAccepts();
channels.add(server);
listenerInfo.add(new ListenerInfo("http", server.getLocalAddress(), null, openListener));
} else if (listener.type == ListenerType.HTTPS) {
OpenListener openListener;
HttpOpenListener httpOpenListener = new HttpOpenListener(buffers, undertowOptions);
httpOpenListener.setRootHandler(rootHandler);
boolean http2 = serverOptions.get(UndertowOptions.ENABLE_HTTP2, false);
if(http2) {
AlpnOpenListener alpn = new AlpnOpenListener(buffers, undertowOptions, httpOpenListener);
if(http2) {
Http2OpenListener http2Listener = new Http2OpenListener(buffers, undertowOptions);
http2Listener.setRootHandler(rootHandler);
alpn.addProtocol(Http2OpenListener.HTTP2, http2Listener, 10);
alpn.addProtocol(Http2OpenListener.HTTP2_14, http2Listener, 7);
}
openListener = alpn;
} else {
openListener = httpOpenListener;
}
ChannelListener<AcceptingChannel<StreamConnection>> acceptListener = ChannelListeners.openListenerAdapter(openListener);
XnioSsl xnioSsl;
if (listener.sslContext != null) {
xnioSsl = new UndertowXnioSsl(xnio, OptionMap.create(Options.USE_DIRECT_BUFFERS, true), listener.sslContext);
} else {
xnioSsl = new UndertowXnioSsl(xnio, OptionMap.create(Options.USE_DIRECT_BUFFERS, true), JsseSslUtils.createSSLContext(listener.keyManagers, listener.trustManagers, new SecureRandom(), OptionMap.create(Options.USE_DIRECT_BUFFERS, true)));
}
AcceptingChannel<SslConnection> sslServer = xnioSsl.createSslConnectionServer(worker, new InetSocketAddress(Inet4Address.getByName(listener.host), listener.port), (ChannelListener) acceptListener, socketOptions);
sslServer.resumeAccepts();
channels.add(sslServer);
listenerInfo.add(new ListenerInfo("https", sslServer.getLocalAddress(), listener.sslContext, openListener));
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public synchronized void stop() {
UndertowLogger.ROOT_LOGGER.debugf("stopping undertow server %s", this);
if (channels != null) {
for (AcceptingChannel<? extends StreamConnection> channel : channels) {
IoUtils.safeClose(channel);
}
channels = null;
}
/*
* Only shutdown the worker if it was created during start()
*/
if (internalWorker && worker != null) {
worker.shutdownNow();
worker = null;
}
xnio = null;
listenerInfo = null;
}
public Xnio getXnio() {
return xnio;
}
public XnioWorker getWorker() {
return worker;
}
public List<ListenerInfo> getListenerInfo() {
if(listenerInfo == null) {
throw UndertowMessages.MESSAGES.serverNotStarted();
}
return Collections.unmodifiableList(listenerInfo);
}
public enum ListenerType {
HTTP,
HTTPS,
AJP
}
private static class ListenerConfig {
final ListenerType type;
final int port;
final String host;
final KeyManager[] keyManagers;
final TrustManager[] trustManagers;
final SSLContext sslContext;
final HttpHandler rootHandler;
private ListenerConfig(final ListenerType type, final int port, final String host, KeyManager[] keyManagers, TrustManager[] trustManagers, HttpHandler rootHandler) {
this.type = type;
this.port = port;
this.host = host;
this.keyManagers = keyManagers;
this.trustManagers = trustManagers;
this.rootHandler = rootHandler;
this.sslContext = null;
}
private ListenerConfig(final ListenerType type, final int port, final String host, SSLContext sslContext, HttpHandler rootHandler) {
this.type = type;
this.port = port;
this.host = host;
this.rootHandler = rootHandler;
this.keyManagers = null;
this.trustManagers = null;
this.sslContext = sslContext;
}
}
public static final class Builder {
private int bufferSize;
private int ioThreads;
private int workerThreads;
private boolean directBuffers;
private final List<ListenerConfig> listeners = new ArrayList<>();
private HttpHandler handler;
private XnioWorker worker;
private final OptionMap.Builder workerOptions = OptionMap.builder();
private final OptionMap.Builder socketOptions = OptionMap.builder();
private final OptionMap.Builder serverOptions = OptionMap.builder();
private Builder() {
ioThreads = Math.max(Runtime.getRuntime().availableProcessors(), 2);
workerThreads = ioThreads * 8;
long maxMemory = Runtime.getRuntime().maxMemory();
//smaller than 64mb of ram we use 512b buffers
if (maxMemory < 64 * 1024 * 1024) {
//use 512b buffers
directBuffers = false;
bufferSize = 512;
} else if (maxMemory < 128 * 1024 * 1024) {
//use 1k buffers
directBuffers = true;
bufferSize = 1024;
} else {
//use 16k buffers for best performance
//as 16k is generally the max amount of data that can be sent in a single write() call
directBuffers = true;
bufferSize = 1024 * 16;
}
}
public Undertow build() {
return new Undertow(this);
}
@Deprecated
public Builder addListener(int port, String host) {
listeners.add(new ListenerConfig(ListenerType.HTTP, port, host, null, null, null));
return this;
}
@Deprecated
public Builder addListener(int port, String host, ListenerType listenerType) {
listeners.add(new ListenerConfig(listenerType, port, host, null, null, null));
return this;
}
public Builder addHttpListener(int port, String host) {
listeners.add(new ListenerConfig(ListenerType.HTTP, port, host, null, null, null));
return this;
}
public Builder addHttpsListener(int port, String host, KeyManager[] keyManagers, TrustManager[] trustManagers) {
listeners.add(new ListenerConfig(ListenerType.HTTPS, port, host, keyManagers, trustManagers, null));
return this;
}
public Builder addHttpsListener(int port, String host, SSLContext sslContext) {
listeners.add(new ListenerConfig(ListenerType.HTTPS, port, host, sslContext, null));
return this;
}
public Builder addAjpListener(int port, String host) {
listeners.add(new ListenerConfig(ListenerType.AJP, port, host, null, null, null));
return this;
}
public Builder addHttpListener(int port, String host, HttpHandler rootHandler) {
listeners.add(new ListenerConfig(ListenerType.HTTP, port, host, null, null, rootHandler));
return this;
}
public Builder addHttpsListener(int port, String host, KeyManager[] keyManagers, TrustManager[] trustManagers, HttpHandler rootHandler) {
listeners.add(new ListenerConfig(ListenerType.HTTPS, port, host, keyManagers, trustManagers, rootHandler));
return this;
}
public Builder addHttpsListener(int port, String host, SSLContext sslContext, HttpHandler rootHandler) {
listeners.add(new ListenerConfig(ListenerType.HTTPS, port, host, sslContext, rootHandler));
return this;
}
public Builder addAjpListener(int port, String host, HttpHandler rootHandler) {
listeners.add(new ListenerConfig(ListenerType.AJP, port, host, null, null, rootHandler));
return this;
}
public Builder setBufferSize(final int bufferSize) {
this.bufferSize = bufferSize;
return this;
}
@Deprecated
public Builder setBuffersPerRegion(final int buffersPerRegion) {
return this;
}
public Builder setIoThreads(final int ioThreads) {
this.ioThreads = ioThreads;
return this;
}
public Builder setWorkerThreads(final int workerThreads) {
this.workerThreads = workerThreads;
return this;
}
public Builder setDirectBuffers(final boolean directBuffers) {
this.directBuffers = directBuffers;
return this;
}
public Builder setHandler(final HttpHandler handler) {
this.handler = handler;
return this;
}
public <T> Builder setServerOption(final Option<T> option, final T value) {
serverOptions.set(option, value);
return this;
}
public <T> Builder setSocketOption(final Option<T> option, final T value) {
socketOptions.set(option, value);
return this;
}
public <T> Builder setWorkerOption(final Option<T> option, final T value) {
workerOptions.set(option, value);
return this;
}
/**
* When null (the default), a new {@link XnioWorker} will be created according
* to the various worker-related configuration (ioThreads, workerThreads, workerOptions)
* when {@link Undertow#start()} is called.
* Additionally, this newly created worker will be shutdown when {@link Undertow#stop()} is called.
* <br/>
*
* When non-null, the provided {@link XnioWorker} will be reused instead of creating a new {@link XnioWorker}
* when {@link Undertow#start()} is called.
* Additionally, the provided {@link XnioWorker} will NOT be shutdown when {@link Undertow#stop()} is called.
* Essentially, the lifecycle of the provided worker must be maintained outside of the {@link Undertow} instance.
*/
public <T> Builder setWorker(XnioWorker worker) {
this.worker = worker;
return this;
}
}
public static class ListenerInfo {
private final String protcol;
private final SocketAddress address;
private final SSLContext sslContext;
private final OpenListener openListener;
public ListenerInfo(String protcol, SocketAddress address, SSLContext sslContext, OpenListener openListener) {
this.protcol = protcol;
this.address = address;
this.sslContext = sslContext;
this.openListener = openListener;
}
public String getProtcol() {
return protcol;
}
public SocketAddress getAddress() {
return address;
}
public SSLContext getSslContext() {
return sslContext;
}
public ConnectorStatistics getConnectorStatistics() {
return openListener.getConnectorStatistics();
}
@Override
public String toString() {
return "ListenerInfo{" +
"protcol='" + protcol + '\'' +
", address=" + address +
", sslContext=" + sslContext +
'}';
}
}
}
| core/src/main/java/io/undertow/Undertow.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.undertow;
import io.undertow.protocols.ssl.UndertowXnioSsl;
import io.undertow.server.ConnectorStatistics;
import io.undertow.server.DefaultByteBufferPool;
import io.undertow.server.HttpHandler;
import io.undertow.server.OpenListener;
import io.undertow.server.protocol.ajp.AjpOpenListener;
import io.undertow.server.protocol.http.AlpnOpenListener;
import io.undertow.server.protocol.http.HttpOpenListener;
import io.undertow.server.protocol.http2.Http2OpenListener;
import org.xnio.ChannelListener;
import org.xnio.ChannelListeners;
import org.xnio.IoUtils;
import org.xnio.Option;
import org.xnio.OptionMap;
import org.xnio.Options;
import io.undertow.connector.ByteBufferPool;
import org.xnio.StreamConnection;
import org.xnio.Xnio;
import org.xnio.XnioWorker;
import org.xnio.channels.AcceptingChannel;
import org.xnio.ssl.SslConnection;
import org.xnio.ssl.XnioSsl;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Convenience class used to build an Undertow server.
* <p>
*
* @author Stuart Douglas
*/
public final class Undertow {
private final int bufferSize;
private final int ioThreads;
private final int workerThreads;
private final boolean directBuffers;
private final List<ListenerConfig> listeners = new ArrayList<>();
private volatile List<ListenerInfo> listenerInfo;
private final HttpHandler rootHandler;
private final OptionMap workerOptions;
private final OptionMap socketOptions;
private final OptionMap serverOptions;
/**
* Will be true when a {@link XnioWorker} instance was NOT provided to the {@link Builder}.
* When true, a new worker will be created during {@link Undertow#start()},
* and shutdown when {@link Undertow#stop()} is called.
*
* Will be false when a {@link XnioWorker} instance was provided to the {@link Builder}.
* When false, the provided {@link #worker} will be used instead of creating a new one in {@link Undertow#start()}.
* Also, when false, the {@link #worker} will NOT be shutdown when {@link Undertow#stop()} is called.
*/
private final boolean internalWorker;
private XnioWorker worker;
private List<AcceptingChannel<? extends StreamConnection>> channels;
private Xnio xnio;
private Undertow(Builder builder) {
this.bufferSize = builder.bufferSize;
this.ioThreads = builder.ioThreads;
this.workerThreads = builder.workerThreads;
this.directBuffers = builder.directBuffers;
this.listeners.addAll(builder.listeners);
this.rootHandler = builder.handler;
this.worker = builder.worker;
this.internalWorker = builder.worker == null;
this.workerOptions = builder.workerOptions.getMap();
this.socketOptions = builder.socketOptions.getMap();
this.serverOptions = builder.serverOptions.getMap();
}
/**
* @return A builder that can be used to create an Undertow server instance
*/
public static Builder builder() {
return new Builder();
}
public synchronized void start() {
UndertowLogger.ROOT_LOGGER.debugf("starting undertow server %s", this);
xnio = Xnio.getInstance(Undertow.class.getClassLoader());
channels = new ArrayList<>();
try {
if (internalWorker) {
worker = xnio.createWorker(OptionMap.builder()
.set(Options.WORKER_IO_THREADS, ioThreads)
.set(Options.CONNECTION_HIGH_WATER, 1000000)
.set(Options.CONNECTION_LOW_WATER, 1000000)
.set(Options.WORKER_TASK_CORE_THREADS, workerThreads)
.set(Options.WORKER_TASK_MAX_THREADS, workerThreads)
.set(Options.TCP_NODELAY, true)
.set(Options.CORK, true)
.addAll(workerOptions)
.getMap());
}
OptionMap socketOptions = OptionMap.builder()
.set(Options.WORKER_IO_THREADS, worker.getIoThreadCount())
.set(Options.TCP_NODELAY, true)
.set(Options.REUSE_ADDRESSES, true)
.set(Options.BALANCING_TOKENS, 1)
.set(Options.BALANCING_CONNECTIONS, 2)
.set(Options.BACKLOG, 1000)
.addAll(this.socketOptions)
.getMap();
OptionMap serverOptions = OptionMap.builder()
.set(UndertowOptions.NO_REQUEST_TIMEOUT, 60 * 1000)
.addAll(this.serverOptions)
.getMap();
ByteBufferPool buffers = new DefaultByteBufferPool(directBuffers, bufferSize, -1, 4);
listenerInfo = new ArrayList<>();
for (ListenerConfig listener : listeners) {
UndertowLogger.ROOT_LOGGER.debugf("Configuring listener with protocol %s for interface %s and port %s", listener.type, listener.host, listener.port);
final HttpHandler rootHandler = listener.rootHandler != null ? listener.rootHandler : this.rootHandler;
if (listener.type == ListenerType.AJP) {
AjpOpenListener openListener = new AjpOpenListener(buffers, serverOptions);
openListener.setRootHandler(rootHandler);
ChannelListener<AcceptingChannel<StreamConnection>> acceptListener = ChannelListeners.openListenerAdapter(openListener);
AcceptingChannel<? extends StreamConnection> server = worker.createStreamConnectionServer(new InetSocketAddress(Inet4Address.getByName(listener.host), listener.port), acceptListener, socketOptions);
server.resumeAccepts();
channels.add(server);
listenerInfo.add(new ListenerInfo("ajp", server.getLocalAddress(), null, openListener));
} else {
OptionMap undertowOptions = OptionMap.builder().set(UndertowOptions.BUFFER_PIPELINED_DATA, true).addAll(serverOptions).getMap();
if (listener.type == ListenerType.HTTP) {
HttpOpenListener openListener = new HttpOpenListener(buffers, undertowOptions);
openListener.setRootHandler(rootHandler);
ChannelListener<AcceptingChannel<StreamConnection>> acceptListener = ChannelListeners.openListenerAdapter(openListener);
AcceptingChannel<? extends StreamConnection> server = worker.createStreamConnectionServer(new InetSocketAddress(Inet4Address.getByName(listener.host), listener.port), acceptListener, socketOptions);
server.resumeAccepts();
channels.add(server);
listenerInfo.add(new ListenerInfo("http", server.getLocalAddress(), null, openListener));
} else if (listener.type == ListenerType.HTTPS) {
OpenListener openListener;
HttpOpenListener httpOpenListener = new HttpOpenListener(buffers, undertowOptions);
httpOpenListener.setRootHandler(rootHandler);
boolean http2 = serverOptions.get(UndertowOptions.ENABLE_HTTP2, false);
if(http2) {
AlpnOpenListener alpn = new AlpnOpenListener(buffers, undertowOptions, httpOpenListener);
if(http2) {
Http2OpenListener http2Listener = new Http2OpenListener(buffers, undertowOptions);
http2Listener.setRootHandler(rootHandler);
alpn.addProtocol(Http2OpenListener.HTTP2, http2Listener, 10);
alpn.addProtocol(Http2OpenListener.HTTP2_14, http2Listener, 7);
}
openListener = alpn;
} else {
openListener = httpOpenListener;
}
ChannelListener<AcceptingChannel<StreamConnection>> acceptListener = ChannelListeners.openListenerAdapter(openListener);
XnioSsl xnioSsl;
if (listener.sslContext != null) {
xnioSsl = new UndertowXnioSsl(xnio, OptionMap.create(Options.USE_DIRECT_BUFFERS, true), listener.sslContext);
} else {
xnioSsl = xnio.getSslProvider(listener.keyManagers, listener.trustManagers, OptionMap.create(Options.USE_DIRECT_BUFFERS, true));
}
AcceptingChannel<SslConnection> sslServer = xnioSsl.createSslConnectionServer(worker, new InetSocketAddress(Inet4Address.getByName(listener.host), listener.port), (ChannelListener) acceptListener, socketOptions);
sslServer.resumeAccepts();
channels.add(sslServer);
listenerInfo.add(new ListenerInfo("https", sslServer.getLocalAddress(), listener.sslContext, openListener));
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public synchronized void stop() {
UndertowLogger.ROOT_LOGGER.debugf("stopping undertow server %s", this);
if (channels != null) {
for (AcceptingChannel<? extends StreamConnection> channel : channels) {
IoUtils.safeClose(channel);
}
channels = null;
}
/*
* Only shutdown the worker if it was created during start()
*/
if (internalWorker && worker != null) {
worker.shutdownNow();
worker = null;
}
xnio = null;
listenerInfo = null;
}
public Xnio getXnio() {
return xnio;
}
public XnioWorker getWorker() {
return worker;
}
public List<ListenerInfo> getListenerInfo() {
if(listenerInfo == null) {
throw UndertowMessages.MESSAGES.serverNotStarted();
}
return Collections.unmodifiableList(listenerInfo);
}
public enum ListenerType {
HTTP,
HTTPS,
AJP
}
private static class ListenerConfig {
final ListenerType type;
final int port;
final String host;
final KeyManager[] keyManagers;
final TrustManager[] trustManagers;
final SSLContext sslContext;
final HttpHandler rootHandler;
private ListenerConfig(final ListenerType type, final int port, final String host, KeyManager[] keyManagers, TrustManager[] trustManagers, HttpHandler rootHandler) {
this.type = type;
this.port = port;
this.host = host;
this.keyManagers = keyManagers;
this.trustManagers = trustManagers;
this.rootHandler = rootHandler;
this.sslContext = null;
}
private ListenerConfig(final ListenerType type, final int port, final String host, SSLContext sslContext, HttpHandler rootHandler) {
this.type = type;
this.port = port;
this.host = host;
this.rootHandler = rootHandler;
this.keyManagers = null;
this.trustManagers = null;
this.sslContext = sslContext;
}
}
public static final class Builder {
private int bufferSize;
private int ioThreads;
private int workerThreads;
private boolean directBuffers;
private final List<ListenerConfig> listeners = new ArrayList<>();
private HttpHandler handler;
private XnioWorker worker;
private final OptionMap.Builder workerOptions = OptionMap.builder();
private final OptionMap.Builder socketOptions = OptionMap.builder();
private final OptionMap.Builder serverOptions = OptionMap.builder();
private Builder() {
ioThreads = Math.max(Runtime.getRuntime().availableProcessors(), 2);
workerThreads = ioThreads * 8;
long maxMemory = Runtime.getRuntime().maxMemory();
//smaller than 64mb of ram we use 512b buffers
if (maxMemory < 64 * 1024 * 1024) {
//use 512b buffers
directBuffers = false;
bufferSize = 512;
} else if (maxMemory < 128 * 1024 * 1024) {
//use 1k buffers
directBuffers = true;
bufferSize = 1024;
} else {
//use 16k buffers for best performance
//as 16k is generally the max amount of data that can be sent in a single write() call
directBuffers = true;
bufferSize = 1024 * 16;
}
}
public Undertow build() {
return new Undertow(this);
}
@Deprecated
public Builder addListener(int port, String host) {
listeners.add(new ListenerConfig(ListenerType.HTTP, port, host, null, null, null));
return this;
}
@Deprecated
public Builder addListener(int port, String host, ListenerType listenerType) {
listeners.add(new ListenerConfig(listenerType, port, host, null, null, null));
return this;
}
public Builder addHttpListener(int port, String host) {
listeners.add(new ListenerConfig(ListenerType.HTTP, port, host, null, null, null));
return this;
}
public Builder addHttpsListener(int port, String host, KeyManager[] keyManagers, TrustManager[] trustManagers) {
listeners.add(new ListenerConfig(ListenerType.HTTPS, port, host, keyManagers, trustManagers, null));
return this;
}
public Builder addHttpsListener(int port, String host, SSLContext sslContext) {
listeners.add(new ListenerConfig(ListenerType.HTTPS, port, host, sslContext, null));
return this;
}
public Builder addAjpListener(int port, String host) {
listeners.add(new ListenerConfig(ListenerType.AJP, port, host, null, null, null));
return this;
}
public Builder addHttpListener(int port, String host, HttpHandler rootHandler) {
listeners.add(new ListenerConfig(ListenerType.HTTP, port, host, null, null, rootHandler));
return this;
}
public Builder addHttpsListener(int port, String host, KeyManager[] keyManagers, TrustManager[] trustManagers, HttpHandler rootHandler) {
listeners.add(new ListenerConfig(ListenerType.HTTPS, port, host, keyManagers, trustManagers, rootHandler));
return this;
}
public Builder addHttpsListener(int port, String host, SSLContext sslContext, HttpHandler rootHandler) {
listeners.add(new ListenerConfig(ListenerType.HTTPS, port, host, sslContext, rootHandler));
return this;
}
public Builder addAjpListener(int port, String host, HttpHandler rootHandler) {
listeners.add(new ListenerConfig(ListenerType.AJP, port, host, null, null, rootHandler));
return this;
}
public Builder setBufferSize(final int bufferSize) {
this.bufferSize = bufferSize;
return this;
}
@Deprecated
public Builder setBuffersPerRegion(final int buffersPerRegion) {
return this;
}
public Builder setIoThreads(final int ioThreads) {
this.ioThreads = ioThreads;
return this;
}
public Builder setWorkerThreads(final int workerThreads) {
this.workerThreads = workerThreads;
return this;
}
public Builder setDirectBuffers(final boolean directBuffers) {
this.directBuffers = directBuffers;
return this;
}
public Builder setHandler(final HttpHandler handler) {
this.handler = handler;
return this;
}
public <T> Builder setServerOption(final Option<T> option, final T value) {
serverOptions.set(option, value);
return this;
}
public <T> Builder setSocketOption(final Option<T> option, final T value) {
socketOptions.set(option, value);
return this;
}
public <T> Builder setWorkerOption(final Option<T> option, final T value) {
workerOptions.set(option, value);
return this;
}
/**
* When null (the default), a new {@link XnioWorker} will be created according
* to the various worker-related configuration (ioThreads, workerThreads, workerOptions)
* when {@link Undertow#start()} is called.
* Additionally, this newly created worker will be shutdown when {@link Undertow#stop()} is called.
* <br/>
*
* When non-null, the provided {@link XnioWorker} will be reused instead of creating a new {@link XnioWorker}
* when {@link Undertow#start()} is called.
* Additionally, the provided {@link XnioWorker} will NOT be shutdown when {@link Undertow#stop()} is called.
* Essentially, the lifecycle of the provided worker must be maintained outside of the {@link Undertow} instance.
*/
public <T> Builder setWorker(XnioWorker worker) {
this.worker = worker;
return this;
}
}
public static class ListenerInfo {
private final String protcol;
private final SocketAddress address;
private final SSLContext sslContext;
private final OpenListener openListener;
public ListenerInfo(String protcol, SocketAddress address, SSLContext sslContext, OpenListener openListener) {
this.protcol = protcol;
this.address = address;
this.sslContext = sslContext;
this.openListener = openListener;
}
public String getProtcol() {
return protcol;
}
public SocketAddress getAddress() {
return address;
}
public SSLContext getSslContext() {
return sslContext;
}
public ConnectorStatistics getConnectorStatistics() {
return openListener.getConnectorStatistics();
}
@Override
public String toString() {
return "ListenerInfo{" +
"protcol='" + protcol + '\'' +
", address=" + address +
", sslContext=" + sslContext +
'}';
}
}
}
| UNDERTOW-927 Undertow builder does not work for HTTP if the SslContext is not specified
| core/src/main/java/io/undertow/Undertow.java | UNDERTOW-927 Undertow builder does not work for HTTP if the SslContext is not specified | <ide><path>ore/src/main/java/io/undertow/Undertow.java
<ide> import org.xnio.Xnio;
<ide> import org.xnio.XnioWorker;
<ide> import org.xnio.channels.AcceptingChannel;
<add>import org.xnio.ssl.JsseSslUtils;
<ide> import org.xnio.ssl.SslConnection;
<ide> import org.xnio.ssl.XnioSsl;
<ide>
<ide> import java.net.Inet4Address;
<ide> import java.net.InetSocketAddress;
<ide> import java.net.SocketAddress;
<add>import java.security.SecureRandom;
<ide> import java.util.ArrayList;
<ide> import java.util.Collections;
<ide> import java.util.List;
<ide> if (listener.sslContext != null) {
<ide> xnioSsl = new UndertowXnioSsl(xnio, OptionMap.create(Options.USE_DIRECT_BUFFERS, true), listener.sslContext);
<ide> } else {
<del> xnioSsl = xnio.getSslProvider(listener.keyManagers, listener.trustManagers, OptionMap.create(Options.USE_DIRECT_BUFFERS, true));
<add>
<add> xnioSsl = new UndertowXnioSsl(xnio, OptionMap.create(Options.USE_DIRECT_BUFFERS, true), JsseSslUtils.createSSLContext(listener.keyManagers, listener.trustManagers, new SecureRandom(), OptionMap.create(Options.USE_DIRECT_BUFFERS, true)));
<ide> }
<ide> AcceptingChannel<SslConnection> sslServer = xnioSsl.createSslConnectionServer(worker, new InetSocketAddress(Inet4Address.getByName(listener.host), listener.port), (ChannelListener) acceptListener, socketOptions);
<ide> sslServer.resumeAccepts(); |
|
Java | apache-2.0 | 64765d9a93deaf27c52fb88a1379d358055b63ab | 0 | fabric8io/kubernetes-client,fabric8io/kubernetes-client,fabric8io/kubernetes-client | /**
* Copyright (C) 2015 Red Hat, 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 io.fabric8.kubernetes.examples.crds;
import io.fabric8.kubernetes.api.model.KubernetesResource;
import io.fabric8.kubernetes.api.model.Namespaced;
import io.fabric8.kubernetes.client.CustomResource;
import io.fabric8.kubernetes.model.annotation.ApiGroup;
import io.fabric8.kubernetes.model.annotation.ApiVersion;
@ApiVersion(Dummy.VERSION)
@ApiGroup(Dummy.GROUP)
public class Dummy extends CustomResource<DummySpec, KubernetesResource> implements Namespaced {
public static final String GROUP = "demo.fabric8.io";
public static final String VERSION = "v1";
}
| kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/crds/Dummy.java | /**
* Copyright (C) 2015 Red Hat, 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 io.fabric8.kubernetes.examples.crds;
import io.fabric8.kubernetes.api.model.KubernetesResource;
import io.fabric8.kubernetes.api.model.Namespaced;
import io.fabric8.kubernetes.api.model.ObjectMeta;
import io.fabric8.kubernetes.client.CustomResource;
import io.fabric8.kubernetes.model.annotation.ApiGroup;
import io.fabric8.kubernetes.model.annotation.ApiVersion;
import io.fabric8.kubernetes.model.annotation.Plural;
@ApiVersion(Dummy.VERSION)
@ApiGroup(Dummy.GROUP)
public class Dummy extends CustomResource<DummySpec, KubernetesResource> implements Namespaced {
public static final String GROUP = "demo.fabric8.io";
public static final String VERSION = "v1";
}
| chore: remove unused imports
| kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/crds/Dummy.java | chore: remove unused imports | <ide><path>ubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/crds/Dummy.java
<ide>
<ide> import io.fabric8.kubernetes.api.model.KubernetesResource;
<ide> import io.fabric8.kubernetes.api.model.Namespaced;
<del>import io.fabric8.kubernetes.api.model.ObjectMeta;
<ide> import io.fabric8.kubernetes.client.CustomResource;
<ide> import io.fabric8.kubernetes.model.annotation.ApiGroup;
<ide> import io.fabric8.kubernetes.model.annotation.ApiVersion;
<del>import io.fabric8.kubernetes.model.annotation.Plural;
<ide>
<ide> @ApiVersion(Dummy.VERSION)
<ide> @ApiGroup(Dummy.GROUP) |
|
Java | mpl-2.0 | 0432a5a6b789733f462aa39010b42d910d7d61c1 | 0 | Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV | package org.helioviewer.jhv;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.util.Locale;
import java.util.TimeZone;
import javax.swing.JComponent;
import org.helioviewer.jhv.base.FileUtils;
import org.helioviewer.jhv.base.logging.Log;
import org.helioviewer.jhv.base.logging.LogSettings;
import org.helioviewer.jhv.base.message.Message;
import org.helioviewer.jhv.base.plugin.controller.PluginManager;
import org.helioviewer.jhv.base.time.TimeUtils;
import org.helioviewer.jhv.gui.ImageViewerGui;
import org.helioviewer.jhv.gui.UIGlobals;
import org.helioviewer.jhv.io.CommandLineProcessor;
import org.helioviewer.jhv.resourceloader.SystemProperties;
import org.helioviewer.jhv.viewmodel.view.jp2view.kakadu.KakaduEngine;
import org.helioviewer.jhv.threads.JHVExecutor;
/**
* This class starts the applications.
*
* @author caplins
* @author Benjamin Wamsler
* @author Markus Langenberg
* @author Stephan Pagel
* @author Andre Dau
* @author Helge Dietert
*
*/
public class JavaHelioViewer {
public static void main(String[] args) {
// Prints the usage message
if (args.length == 1 && (args[0].equals("-h") || args[0].equals("--help"))) {
System.out.println(CommandLineProcessor.getUsageMessage());
return;
}
// Uncaught runtime errors are displayed in a dialog box in addition
JHVUncaughtExceptionHandler.setupHandlerForThread();
// Save command line arguments
CommandLineProcessor.setArguments(args);
// Save current default system timezone in user.timezone
System.setProperty("user.timezone", TimeZone.getDefault().getID());
// Per default all times should be given in GMT
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
// Save current default locale to user.locale
System.setProperty("user.locale", Locale.getDefault().toString());
// Per default, the us locale should be used
Locale.setDefault(Locale.US);
// init log
LogSettings.init("/settings/log4j.initial.properties", JHVDirectory.SETTINGS.getPath() + "log4j.properties", JHVDirectory.LOGS.getPath(), CommandLineProcessor.isOptionSet("--use-existing-log-time-stamp"));
// Information log message
String argString = "";
for (int i = 0; i < args.length; ++i) {
argString += " " + args[i];
}
Log.info("JHelioviewer started with command-line options:" + argString);
// This attempts to create the necessary directories for the application
Log.info("Create directories...");
JHVGlobals.createDirs();
// Save the log settings. Must be done AFTER the directories are created
LogSettings.getSingletonInstance().update();
// Read the version and revision from the JAR metafile
JHVGlobals.determineVersionAndRevision();
Log.info("Initializing JHelioviewer");
// Load settings from file but do not apply them yet
// The settings must not be applied before the kakadu engine has been
// initialized
Log.info("Load settings");
Settings.getSingletonInstance().load();
// Set the platform system properties
SystemProperties.setPlatform();
Log.info("OS: " + System.getProperty("jhv.os") + " - arch: " + System.getProperty("jhv.arch") + " - java arch: " + System.getProperty("jhv.java.arch"));
Log.debug("Instantiate Kakadu engine");
try {
JHVLoader.copyKDULibs();
KakaduEngine engine = new KakaduEngine();
engine.startKduMessageSystem();
} catch (Exception e) {
Message.err("Failed to setup Kakadu", e.getMessage(), true);
return;
}
FileUtils.deleteDir(JHVDirectory.PLUGINSCACHE.getFile());
JHVDirectory.PLUGINSCACHE.getFile().mkdirs();
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JHVExecutor.getWorkersExecutorService(20); // tbd
TimeUtils.getSingletonInstance(); // instantiate class
UIGlobals.getSingletonInstance().setUIFont(UIGlobals.UIFont);
Settings.getSingletonInstance().setLookAndFeelEverywhere(null, null); // for Windows and testing
Log.info("Start main window");
ExitHooks.attach();
ImageViewerGui.prepareGui();
ImageViewerGui.loadImagesAtStartup();
Log.info("Load plugin settings");
PluginManager.getSingletonInstance().loadSettings(JHVDirectory.PLUGINS.getPath());
try {
if (theArgs.length != 0 && theArgs[0].equals("--exclude-plugins")) {
Log.info("Do not load plugins");
} else if (theArgs.length != 0 && theArgs[0].equals("--remote-plugins")) {
Log.info("Load remote plugins -- not recommended");
JHVLoader.loadRemotePlugins(theArgs);
} else {
Log.info("Load bundled plugins");
JHVLoader.loadBundledPlugin("EVEPlugin.jar");
JHVLoader.loadBundledPlugin("SWEKPlugin.jar");
JHVLoader.loadBundledPlugin("PfssPlugin.jar");
JHVLoader.loadBundledPlugin("SWHVHEKPlugin.jar");
}
} catch (Exception ex) {
ex.printStackTrace();
}
// after loading plugins fix the minimum width of left pane
JComponent leftScrollPane = ImageViewerGui.getLeftScrollPane();
leftScrollPane.setMinimumSize(new Dimension(leftScrollPane.getPreferredSize().width + ImageViewerGui.SIDE_PANEL_WIDTH_EXTRA, -1));
ImageViewerGui.getMainFrame().pack();
}
private String[] theArgs;
public Runnable init(String[] _args) {
theArgs = _args;
return this;
}
}.init(args));
}
}
| src/jhv/src/org/helioviewer/jhv/JavaHelioViewer.java | package org.helioviewer.jhv;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.util.Locale;
import java.util.TimeZone;
import javax.swing.JComponent;
import org.helioviewer.jhv.base.FileUtils;
import org.helioviewer.jhv.base.logging.Log;
import org.helioviewer.jhv.base.logging.LogSettings;
import org.helioviewer.jhv.base.message.Message;
import org.helioviewer.jhv.base.plugin.controller.PluginManager;
import org.helioviewer.jhv.base.time.TimeUtils;
import org.helioviewer.jhv.gui.ImageViewerGui;
import org.helioviewer.jhv.gui.UIGlobals;
import org.helioviewer.jhv.io.CommandLineProcessor;
import org.helioviewer.jhv.resourceloader.SystemProperties;
import org.helioviewer.jhv.viewmodel.view.jp2view.kakadu.KakaduEngine;
/**
* This class starts the applications.
*
* @author caplins
* @author Benjamin Wamsler
* @author Markus Langenberg
* @author Stephan Pagel
* @author Andre Dau
* @author Helge Dietert
*
*/
public class JavaHelioViewer {
public static void main(String[] args) {
// Prints the usage message
if (args.length == 1 && (args[0].equals("-h") || args[0].equals("--help"))) {
System.out.println(CommandLineProcessor.getUsageMessage());
return;
}
// Uncaught runtime errors are displayed in a dialog box in addition
JHVUncaughtExceptionHandler.setupHandlerForThread();
// Save command line arguments
CommandLineProcessor.setArguments(args);
// Save current default system timezone in user.timezone
System.setProperty("user.timezone", TimeZone.getDefault().getID());
// Per default all times should be given in GMT
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
// Save current default locale to user.locale
System.setProperty("user.locale", Locale.getDefault().toString());
// Per default, the us locale should be used
Locale.setDefault(Locale.US);
// init log
LogSettings.init("/settings/log4j.initial.properties", JHVDirectory.SETTINGS.getPath() + "log4j.properties", JHVDirectory.LOGS.getPath(), CommandLineProcessor.isOptionSet("--use-existing-log-time-stamp"));
// Information log message
String argString = "";
for (int i = 0; i < args.length; ++i) {
argString += " " + args[i];
}
Log.info("JHelioviewer started with command-line options:" + argString);
// This attempts to create the necessary directories for the application
Log.info("Create directories...");
JHVGlobals.createDirs();
// Save the log settings. Must be done AFTER the directories are created
LogSettings.getSingletonInstance().update();
// Read the version and revision from the JAR metafile
JHVGlobals.determineVersionAndRevision();
Log.info("Initializing JHelioviewer");
// Load settings from file but do not apply them yet
// The settings must not be applied before the kakadu engine has been
// initialized
Log.info("Load settings");
Settings.getSingletonInstance().load();
// Set the platform system properties
SystemProperties.setPlatform();
Log.info("OS: " + System.getProperty("jhv.os") + " - arch: " + System.getProperty("jhv.arch") + " - java arch: " + System.getProperty("jhv.java.arch"));
Log.debug("Instantiate Kakadu engine");
try {
JHVLoader.copyKDULibs();
KakaduEngine engine = new KakaduEngine();
engine.startKduMessageSystem();
} catch (Exception e) {
Message.err("Failed to setup Kakadu", e.getMessage(), true);
return;
}
FileUtils.deleteDir(JHVDirectory.PLUGINSCACHE.getFile());
JHVDirectory.PLUGINSCACHE.getFile().mkdirs();
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
TimeUtils.getSingletonInstance(); // instantiate class
UIGlobals.getSingletonInstance().setUIFont(UIGlobals.UIFont);
Settings.getSingletonInstance().setLookAndFeelEverywhere(null, null); // for Windows and testing
Log.info("Start main window");
ExitHooks.attach();
ImageViewerGui.prepareGui();
ImageViewerGui.loadImagesAtStartup();
Log.info("Load plugin settings");
PluginManager.getSingletonInstance().loadSettings(JHVDirectory.PLUGINS.getPath());
try {
if (theArgs.length != 0 && theArgs[0].equals("--exclude-plugins")) {
Log.info("Do not load plugins");
} else if (theArgs.length != 0 && theArgs[0].equals("--remote-plugins")) {
Log.info("Load remote plugins -- not recommended");
JHVLoader.loadRemotePlugins(theArgs);
} else {
Log.info("Load bundled plugins");
JHVLoader.loadBundledPlugin("EVEPlugin.jar");
JHVLoader.loadBundledPlugin("SWEKPlugin.jar");
JHVLoader.loadBundledPlugin("PfssPlugin.jar");
JHVLoader.loadBundledPlugin("SWHVHEKPlugin.jar");
}
} catch (Exception ex) {
ex.printStackTrace();
}
// after loading plugins fix the minimum width of left pane
JComponent leftScrollPane = ImageViewerGui.getLeftScrollPane();
leftScrollPane.setMinimumSize(new Dimension(leftScrollPane.getPreferredSize().width + ImageViewerGui.SIDE_PANEL_WIDTH_EXTRA, -1));
ImageViewerGui.getMainFrame().pack();
}
private String[] theArgs;
public Runnable init(String[] _args) {
theArgs = _args;
return this;
}
}.init(args));
}
}
| Replace standard Swing executor (tbd)
git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@5922 b4e469a2-07ce-4b26-9273-4d7d95a670c7
| src/jhv/src/org/helioviewer/jhv/JavaHelioViewer.java | Replace standard Swing executor (tbd) | <ide><path>rc/jhv/src/org/helioviewer/jhv/JavaHelioViewer.java
<ide> import org.helioviewer.jhv.io.CommandLineProcessor;
<ide> import org.helioviewer.jhv.resourceloader.SystemProperties;
<ide> import org.helioviewer.jhv.viewmodel.view.jp2view.kakadu.KakaduEngine;
<add>import org.helioviewer.jhv.threads.JHVExecutor;
<ide>
<ide> /**
<ide> * This class starts the applications.
<ide> EventQueue.invokeLater(new Runnable() {
<ide> @Override
<ide> public void run() {
<add> JHVExecutor.getWorkersExecutorService(20); // tbd
<ide> TimeUtils.getSingletonInstance(); // instantiate class
<ide> UIGlobals.getSingletonInstance().setUIFont(UIGlobals.UIFont);
<ide> Settings.getSingletonInstance().setLookAndFeelEverywhere(null, null); // for Windows and testing |
|
Java | mit | c0721f501aa149d743211531dd9a30f9e9075ec6 | 0 | aterai/java-swing-tips,aterai/java-swing-tips,aterai/java-swing-tips,aterai/java-swing-tips | // -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.util.EventObject;
import java.util.Objects;
import javax.swing.*;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
public final class MainPanel extends JPanel {
private final JTextArea textArea = new JTextArea();
private MainPanel() {
super(new BorderLayout());
JInternalFrame frame = new JInternalFrame("title", true, true, true, true);
frame.addPropertyChangeListener(e -> {
String prop = e.getPropertyName();
if (Objects.equals(JInternalFrame.IS_MAXIMUM_PROPERTY, prop)) {
String str = Objects.equals(e.getNewValue(), Boolean.TRUE) ? "maximized" : "minimized";
textArea.append(String.format("* Internal frame %s: %s%n", str, e.getSource()));
textArea.setCaretPosition(textArea.getDocument().getLength());
}
});
frame.addInternalFrameListener(new InternalFrameListener() {
@Override public void internalFrameClosing(InternalFrameEvent e) {
displayMessage("Internal frame closing", e);
}
@Override public void internalFrameClosed(InternalFrameEvent e) {
displayMessage("Internal frame closed", e);
}
@Override public void internalFrameOpened(InternalFrameEvent e) {
displayMessage("Internal frame opened", e);
}
@Override public void internalFrameIconified(InternalFrameEvent e) {
displayMessage("Internal frame iconified", e);
}
@Override public void internalFrameDeiconified(InternalFrameEvent e) {
displayMessage("Internal frame deiconified", e);
}
@Override public void internalFrameActivated(InternalFrameEvent e) {
displayMessage("Internal frame activated", e);
}
@Override public void internalFrameDeactivated(InternalFrameEvent e) {
displayMessage("Internal frame deactivated", e);
}
private void displayMessage(String prefix, EventObject e) {
String s = prefix + ": " + e.getSource();
textArea.append(s + "\n");
textArea.setCaretPosition(textArea.getDocument().getLength());
}
});
frame.setBounds(10, 10, 160, 100);
JDesktopPane desktop = new JDesktopPane();
desktop.add(frame);
frame.setVisible(true);
JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
sp.setTopComponent(desktop);
sp.setBottomComponent(new JScrollPane(textArea));
sp.setResizeWeight(.8);
add(sp);
setPreferredSize(new Dimension(320, 240));
}
// private JMenuBar createMenuBar() {
// JMenuBar menuBar = new JMenuBar();
// JMenu menu = new JMenu("Window");
// menu.setMnemonic(KeyEvent.VK_W);
// menuBar.add(menu);
// JMenuItem menuItem = new JMenuItem("New");
// menuItem.setMnemonic(KeyEvent.VK_N);
// menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.ALT_DOWN_MASK));
// menuItem.setActionCommand("new");
// menuItem.addActionListener(new ActionListener() {
// @Override public void actionPerformed(ActionEvent e) {
// JInternalFrame frame = createInternalFrame();
// desktop.add(frame);
// frame.setVisible(true);
// // desktop.getDesktopManager().activateFrame(frame);
// }
// });
// menu.add(menuItem);
// return menuBar;
// }
// private static JInternalFrame createInternalFrame() {
// String title = String.format("Document #%s", openFrameCount.getAndIncrement());
// JInternalFrame f = new JInternalFrame(title, true, true, true, true);
// f.setSize(160, 100);
// f.setLocation(OFFSET * openFrameCount.intValue(), OFFSET * openFrameCount.intValue());
// return f;
// }
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
| InternalFrameMaximizedListener/src/java/example/MainPanel.java | // -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.util.EventObject;
import java.util.Objects;
import javax.swing.*;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
public class MainPanel extends JPanel {
private final JDesktopPane desktop = new JDesktopPane();
private final JInternalFrame iframe = new JInternalFrame("title", true, true, true, true);
private final JTextArea textArea = new JTextArea();
private final transient InternalFrameListener handler = new InternalFrameListener() {
@Override public void internalFrameClosing(InternalFrameEvent e) {
displayMessage("Internal frame closing", e);
}
@Override public void internalFrameClosed(InternalFrameEvent e) {
displayMessage("Internal frame closed", e);
}
@Override public void internalFrameOpened(InternalFrameEvent e) {
displayMessage("Internal frame opened", e);
}
@Override public void internalFrameIconified(InternalFrameEvent e) {
displayMessage("Internal frame iconified", e);
}
@Override public void internalFrameDeiconified(InternalFrameEvent e) {
displayMessage("Internal frame deiconified", e);
}
@Override public void internalFrameActivated(InternalFrameEvent e) {
displayMessage("Internal frame activated", e);
}
@Override public void internalFrameDeactivated(InternalFrameEvent e) {
displayMessage("Internal frame deactivated", e);
}
};
public MainPanel() {
super(new BorderLayout());
iframe.addPropertyChangeListener(e -> {
String prop = e.getPropertyName();
if (Objects.equals(JInternalFrame.IS_MAXIMUM_PROPERTY, prop)) {
if (Objects.equals(e.getNewValue(), Boolean.TRUE)) {
displayMessage("* Internal frame maximized", e);
} else {
displayMessage("* Internal frame minimized", e);
}
}
});
iframe.addInternalFrameListener(handler);
iframe.setBounds(10, 10, 160, 100);
desktop.add(iframe);
iframe.setVisible(true);
JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
sp.setTopComponent(desktop);
sp.setBottomComponent(new JScrollPane(textArea));
sp.setResizeWeight(.8);
add(sp);
setPreferredSize(new Dimension(320, 240));
}
protected final void displayMessage(String prefix, EventObject e) {
String s = prefix + ": " + e.getSource();
textArea.append(s + "\n");
textArea.setCaretPosition(textArea.getDocument().getLength());
}
// private JMenuBar createMenuBar() {
// JMenuBar menuBar = new JMenuBar();
// JMenu menu = new JMenu("Window");
// menu.setMnemonic(KeyEvent.VK_W);
// menuBar.add(menu);
// JMenuItem menuItem = new JMenuItem("New");
// menuItem.setMnemonic(KeyEvent.VK_N);
// menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.ALT_DOWN_MASK));
// menuItem.setActionCommand("new");
// menuItem.addActionListener(new ActionListener() {
// @Override public void actionPerformed(ActionEvent e) {
// JInternalFrame frame = createInternalFrame();
// desktop.add(frame);
// frame.setVisible(true);
// // desktop.getDesktopManager().activateFrame(frame);
// }
// });
// menu.add(menuItem);
// return menuBar;
// }
// private static JInternalFrame createInternalFrame() {
// String title = String.format("Document #%s", openFrameCount.getAndIncrement());
// JInternalFrame f = new JInternalFrame(title, true, true, true, true);
// f.setSize(160, 100);
// f.setLocation(XOFFSET * openFrameCount.intValue(), YOFFSET * openFrameCount.intValue());
// return f;
// }
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
| refactor: field can be converted to a local variable
| InternalFrameMaximizedListener/src/java/example/MainPanel.java | refactor: field can be converted to a local variable | <ide><path>nternalFrameMaximizedListener/src/java/example/MainPanel.java
<ide> import javax.swing.event.InternalFrameEvent;
<ide> import javax.swing.event.InternalFrameListener;
<ide>
<del>public class MainPanel extends JPanel {
<del> private final JDesktopPane desktop = new JDesktopPane();
<del> private final JInternalFrame iframe = new JInternalFrame("title", true, true, true, true);
<add>public final class MainPanel extends JPanel {
<ide> private final JTextArea textArea = new JTextArea();
<del> private final transient InternalFrameListener handler = new InternalFrameListener() {
<del> @Override public void internalFrameClosing(InternalFrameEvent e) {
<del> displayMessage("Internal frame closing", e);
<del> }
<ide>
<del> @Override public void internalFrameClosed(InternalFrameEvent e) {
<del> displayMessage("Internal frame closed", e);
<del> }
<del>
<del> @Override public void internalFrameOpened(InternalFrameEvent e) {
<del> displayMessage("Internal frame opened", e);
<del> }
<del>
<del> @Override public void internalFrameIconified(InternalFrameEvent e) {
<del> displayMessage("Internal frame iconified", e);
<del> }
<del>
<del> @Override public void internalFrameDeiconified(InternalFrameEvent e) {
<del> displayMessage("Internal frame deiconified", e);
<del> }
<del>
<del> @Override public void internalFrameActivated(InternalFrameEvent e) {
<del> displayMessage("Internal frame activated", e);
<del> }
<del>
<del> @Override public void internalFrameDeactivated(InternalFrameEvent e) {
<del> displayMessage("Internal frame deactivated", e);
<del> }
<del> };
<del>
<del> public MainPanel() {
<add> private MainPanel() {
<ide> super(new BorderLayout());
<del>
<del> iframe.addPropertyChangeListener(e -> {
<add> JInternalFrame frame = new JInternalFrame("title", true, true, true, true);
<add> frame.addPropertyChangeListener(e -> {
<ide> String prop = e.getPropertyName();
<ide> if (Objects.equals(JInternalFrame.IS_MAXIMUM_PROPERTY, prop)) {
<del> if (Objects.equals(e.getNewValue(), Boolean.TRUE)) {
<del> displayMessage("* Internal frame maximized", e);
<del> } else {
<del> displayMessage("* Internal frame minimized", e);
<del> }
<add> String str = Objects.equals(e.getNewValue(), Boolean.TRUE) ? "maximized" : "minimized";
<add> textArea.append(String.format("* Internal frame %s: %s%n", str, e.getSource()));
<add> textArea.setCaretPosition(textArea.getDocument().getLength());
<ide> }
<ide> });
<del> iframe.addInternalFrameListener(handler);
<del> iframe.setBounds(10, 10, 160, 100);
<del> desktop.add(iframe);
<del> iframe.setVisible(true);
<add> frame.addInternalFrameListener(new InternalFrameListener() {
<add> @Override public void internalFrameClosing(InternalFrameEvent e) {
<add> displayMessage("Internal frame closing", e);
<add> }
<add>
<add> @Override public void internalFrameClosed(InternalFrameEvent e) {
<add> displayMessage("Internal frame closed", e);
<add> }
<add>
<add> @Override public void internalFrameOpened(InternalFrameEvent e) {
<add> displayMessage("Internal frame opened", e);
<add> }
<add>
<add> @Override public void internalFrameIconified(InternalFrameEvent e) {
<add> displayMessage("Internal frame iconified", e);
<add> }
<add>
<add> @Override public void internalFrameDeiconified(InternalFrameEvent e) {
<add> displayMessage("Internal frame deiconified", e);
<add> }
<add>
<add> @Override public void internalFrameActivated(InternalFrameEvent e) {
<add> displayMessage("Internal frame activated", e);
<add> }
<add>
<add> @Override public void internalFrameDeactivated(InternalFrameEvent e) {
<add> displayMessage("Internal frame deactivated", e);
<add> }
<add>
<add> private void displayMessage(String prefix, EventObject e) {
<add> String s = prefix + ": " + e.getSource();
<add> textArea.append(s + "\n");
<add> textArea.setCaretPosition(textArea.getDocument().getLength());
<add> }
<add> });
<add> frame.setBounds(10, 10, 160, 100);
<add>
<add> JDesktopPane desktop = new JDesktopPane();
<add> desktop.add(frame);
<add> frame.setVisible(true);
<ide>
<ide> JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
<ide> sp.setTopComponent(desktop);
<ide> sp.setResizeWeight(.8);
<ide> add(sp);
<ide> setPreferredSize(new Dimension(320, 240));
<del> }
<del>
<del> protected final void displayMessage(String prefix, EventObject e) {
<del> String s = prefix + ": " + e.getSource();
<del> textArea.append(s + "\n");
<del> textArea.setCaretPosition(textArea.getDocument().getLength());
<ide> }
<ide>
<ide> // private JMenuBar createMenuBar() {
<ide> // String title = String.format("Document #%s", openFrameCount.getAndIncrement());
<ide> // JInternalFrame f = new JInternalFrame(title, true, true, true, true);
<ide> // f.setSize(160, 100);
<del> // f.setLocation(XOFFSET * openFrameCount.intValue(), YOFFSET * openFrameCount.intValue());
<add> // f.setLocation(OFFSET * openFrameCount.intValue(), OFFSET * openFrameCount.intValue());
<ide> // return f;
<ide> // }
<ide> |
|
JavaScript | mit | b93a64b35aaffed1b6af407a890b6679dddf30e0 | 0 | mjackson/history,mjackson/history,reactjs/history,ReactJSTraining/history,rackt/history,reactjs/history,ReactJSTraining/history,ReactTraining/history,rackt/history | import { createLocation } from './LocationUtils'
import { addEventListener, removeEventListener } from './DOMUtils'
import { saveState, readState } from './DOMStateStorage'
import { createPath } from './PathUtils'
const PopStateEvent = 'popstate'
const _createLocation = (historyState) => {
const key = historyState && historyState.key
return createLocation({
pathname: window.location.pathname,
search: window.location.search,
hash: window.location.hash,
state: (key ? readState(key) : undefined)
}, undefined, key)
}
export const getCurrentLocation = () => {
let historyState
try {
historyState = window.history.state || {}
} catch (error) {
// IE 11 sometimes throws when accessing window.history.state
// See https://github.com/ReactTraining/history/pull/289
historyState = {}
}
return _createLocation(historyState)
}
export const getUserConfirmation = (message, callback) =>
callback(window.confirm(message)) // eslint-disable-line no-alert
export const startListener = (listener) => {
const handlePopState = (event) => {
if (event.state !== undefined) // Ignore extraneous popstate events in WebKit
listener(_createLocation(event.state))
}
addEventListener(window, PopStateEvent, handlePopState)
return () =>
removeEventListener(window, PopStateEvent, handlePopState)
}
const updateLocation = (location, updateState) => {
const { state, key } = location
if (state !== undefined)
saveState(key, state)
updateState({ key }, createPath(location))
}
export const pushLocation = (location) =>
updateLocation(location, (state, path) =>
window.history.pushState(state, null, path)
)
export const replaceLocation = (location) =>
updateLocation(location, (state, path) =>
window.history.replaceState(state, null, path)
)
export const go = (n) => {
if (n)
window.history.go(n)
}
| modules/BrowserProtocol.js | /* eslint-disable no-alert */
import { createLocation } from './LocationUtils'
import { addEventListener, removeEventListener } from './DOMUtils'
import { saveState, readState } from './DOMStateStorage'
import { createPath } from './PathUtils'
const PopStateEvent = 'popstate'
const _createLocation = (historyState) => {
const key = historyState && historyState.key
return createLocation({
pathname: window.location.pathname,
search: window.location.search,
hash: window.location.hash,
state: (key ? readState(key) : undefined)
}, undefined, key)
}
export const getCurrentLocation = () => {
let historyState
try {
historyState = window.history.state || {}
} catch (error) {
// IE 11 sometimes throws when accessing window.history.state
// See https://github.com/ReactTraining/history/pull/289
historyState = {}
}
return _createLocation(historyState)
}
export const getUserConfirmation = (message, callback) =>
callback(window.confirm(message))
export const startListener = (listener) => {
const handlePopState = (event) => {
if (event.state !== undefined) // Ignore extraneous popstate events in WebKit
listener(_createLocation(event.state))
}
addEventListener(window, PopStateEvent, handlePopState)
return () =>
removeEventListener(window, PopStateEvent, handlePopState)
}
const updateLocation = (location, updateState) => {
const { state, key } = location
if (state !== undefined)
saveState(key, state)
updateState({ key }, createPath(location))
}
export const pushLocation = (location) =>
updateLocation(location, (state, path) =>
window.history.pushState(state, null, path)
)
export const replaceLocation = (location) =>
updateLocation(location, (state, path) =>
window.history.replaceState(state, null, path)
)
export const go = (n) => {
if (n)
window.history.go(n)
}
| Inline eslint instruction
| modules/BrowserProtocol.js | Inline eslint instruction | <ide><path>odules/BrowserProtocol.js
<del>/* eslint-disable no-alert */
<ide> import { createLocation } from './LocationUtils'
<ide> import { addEventListener, removeEventListener } from './DOMUtils'
<ide> import { saveState, readState } from './DOMStateStorage'
<ide> }
<ide>
<ide> export const getUserConfirmation = (message, callback) =>
<del> callback(window.confirm(message))
<add> callback(window.confirm(message)) // eslint-disable-line no-alert
<ide>
<ide> export const startListener = (listener) => {
<ide> const handlePopState = (event) => { |
|
Java | apache-2.0 | a374ac0cc8c0109a3e1bc79ed21ce123ecd4866f | 0 | xmpace/jetty-read,xmpace/jetty-read,xmpace/jetty-read,xmpace/jetty-read | //
// ========================================================================
// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.client;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousCloseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.jetty.client.api.Connection;
import org.eclipse.jetty.client.api.Destination;
import org.eclipse.jetty.client.api.ProxyConfiguration;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.api.Result;
import org.eclipse.jetty.client.util.TimedResponseListener;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpScheme;
import org.eclipse.jetty.util.BlockingArrayQueue;
import org.eclipse.jetty.util.FuturePromise;
import org.eclipse.jetty.util.Promise;
import org.eclipse.jetty.util.component.ContainerLifeCycle;
import org.eclipse.jetty.util.component.Dumpable;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
public class HttpDestination implements Destination, AutoCloseable, Dumpable
{
private static final Logger LOG = Log.getLogger(HttpDestination.class);
private final AtomicInteger connectionCount = new AtomicInteger();
private final HttpClient client;
private final String scheme;
private final String host;
private final InetSocketAddress address;
private final Queue<RequestContext> requests;
private final BlockingQueue<Connection> idleConnections;
private final BlockingQueue<Connection> activeConnections;
private final RequestNotifier requestNotifier;
private final ResponseNotifier responseNotifier;
private final InetSocketAddress proxyAddress;
private final HttpField hostField;
public HttpDestination(HttpClient client, String scheme, String host, int port)
{
this.client = client;
this.scheme = scheme;
this.host = host;
this.address = new InetSocketAddress(host, port);
int maxRequestsQueued = client.getMaxRequestsQueuedPerDestination();
int capacity = Math.min(32, maxRequestsQueued);
this.requests = new BlockingArrayQueue<>(capacity, capacity, maxRequestsQueued);
int maxConnections = client.getMaxConnectionsPerDestination();
capacity = Math.min(8, maxConnections);
this.idleConnections = new BlockingArrayQueue<>(capacity, capacity, maxConnections);
this.activeConnections = new BlockingArrayQueue<>(capacity, capacity, maxConnections);
this.requestNotifier = new RequestNotifier(client);
this.responseNotifier = new ResponseNotifier(client);
ProxyConfiguration proxyConfig = client.getProxyConfiguration();
proxyAddress = proxyConfig != null && proxyConfig.matches(host, port) ?
new InetSocketAddress(proxyConfig.getHost(), proxyConfig.getPort()) : null;
String hostValue = host;
if ("https".equalsIgnoreCase(scheme) && port != 443 ||
"http".equalsIgnoreCase(scheme) && port != 80)
hostValue += ":" + port;
hostField = new HttpField(HttpHeader.HOST, hostValue);
}
protected BlockingQueue<Connection> getIdleConnections()
{
return idleConnections;
}
protected BlockingQueue<Connection> getActiveConnections()
{
return activeConnections;
}
@Override
public String getScheme()
{
return scheme;
}
@Override
public String getHost()
{
// InetSocketAddress.getHostString() transforms the host string
// in case of IPv6 addresses, so we return the original host string
return host;
}
@Override
public int getPort()
{
return address.getPort();
}
public InetSocketAddress getConnectAddress()
{
return isProxied() ? proxyAddress : address;
}
public boolean isProxied()
{
return proxyAddress != null;
}
public HttpField getHostField()
{
return hostField;
}
public void send(Request request, List<Response.ResponseListener> listeners)
{
if (!scheme.equals(request.getScheme()))
throw new IllegalArgumentException("Invalid request scheme " + request.getScheme() + " for destination " + this);
if (!getHost().equals(request.getHost()))
throw new IllegalArgumentException("Invalid request host " + request.getHost() + " for destination " + this);
int port = request.getPort();
if (port >= 0 && getPort() != port)
throw new IllegalArgumentException("Invalid request port " + port + " for destination " + this);
RequestContext requestContext = new RequestContext(request, listeners);
if (client.isRunning())
{
if (requests.offer(requestContext))
{
if (!client.isRunning() && requests.remove(requestContext))
{
throw new RejectedExecutionException(client + " is stopping");
}
else
{
LOG.debug("Queued {}", request);
requestNotifier.notifyQueued(request);
Connection connection = acquire();
if (connection != null)
process(connection, false);
}
}
else
{
throw new RejectedExecutionException("Max requests per destination " + client.getMaxRequestsQueuedPerDestination() + " exceeded");
}
}
else
{
throw new RejectedExecutionException(client + " is stopped");
}
}
public Future<Connection> newConnection()
{
FuturePromise<Connection> result = new FuturePromise<>();
newConnection(new ProxyPromise(result));
return result;
}
protected void newConnection(Promise<Connection> promise)
{
client.newConnection(this, promise);
}
protected Connection acquire()
{
Connection result = idleConnections.poll();
if (result != null)
return result;
final int maxConnections = client.getMaxConnectionsPerDestination();
while (true)
{
int current = connectionCount.get();
final int next = current + 1;
if (next > maxConnections)
{
LOG.debug("Max connections {} reached for {}", current, this);
// Try again the idle connections
return idleConnections.poll();
}
if (connectionCount.compareAndSet(current, next))
{
LOG.debug("Creating connection {}/{} for {}", next, maxConnections, this);
// This is the promise that is being called when a connection (eventually proxied) succeeds or fails.
Promise<Connection> promise = new Promise<Connection>()
{
@Override
public void succeeded(Connection connection)
{
process(connection, true);
}
@Override
public void failed(final Throwable x)
{
client.getExecutor().execute(new Runnable()
{
@Override
public void run()
{
drain(x);
}
});
}
};
// Create a new connection, and pass a ProxyPromise to establish a proxy tunnel, if needed.
// Differently from the case where the connection is created explicitly by applications, here
// we need to do a bit more logging and keep track of the connection count in case of failures.
newConnection(new ProxyPromise(promise)
{
@Override
public void succeeded(Connection connection)
{
LOG.debug("Created connection {}/{} {} for {}", next, maxConnections, connection, HttpDestination.this);
super.succeeded(connection);
}
@Override
public void failed(Throwable x)
{
LOG.debug("Connection failed {} for {}", x, HttpDestination.this);
connectionCount.decrementAndGet();
super.failed(x);
}
});
// Try again the idle connections
return idleConnections.poll();
}
}
}
private void drain(Throwable x)
{
RequestContext requestContext;
while ((requestContext = requests.poll()) != null)
{
Request request = requestContext.request;
requestNotifier.notifyFailure(request, x);
List<Response.ResponseListener> listeners = requestContext.listeners;
HttpResponse response = new HttpResponse(request, listeners);
responseNotifier.notifyFailure(listeners, response, x);
responseNotifier.notifyComplete(listeners, new Result(request, x, response, x));
}
}
/**
* <p>Processes a new connection making it idle or active depending on whether requests are waiting to be sent.</p>
* <p>A new connection is created when a request needs to be executed; it is possible that the request that
* triggered the request creation is executed by another connection that was just released, so the new connection
* may become idle.</p>
* <p>If a request is waiting to be executed, it will be dequeued and executed by the new connection.</p>
*
* @param connection the new connection
*/
protected void process(Connection connection, boolean dispatch)
{
// Ugly cast, but lack of generic reification forces it
final HttpConnection httpConnection = (HttpConnection)connection;
RequestContext requestContext = requests.poll();
if (requestContext == null)
{
LOG.debug("{} idle", httpConnection);
if (!idleConnections.offer(httpConnection))
{
LOG.debug("{} idle overflow");
httpConnection.close();
}
if (!client.isRunning())
{
LOG.debug("{} is stopping", client);
remove(httpConnection);
httpConnection.close();
}
}
else
{
final Request request = requestContext.request;
final List<Response.ResponseListener> listeners = requestContext.listeners;
Throwable cause = request.getAbortCause();
if (cause != null)
{
abort(request, listeners, cause);
LOG.debug("Aborted {} before processing", request);
}
else
{
LOG.debug("{} active", httpConnection);
if (!activeConnections.offer(httpConnection))
{
LOG.warn("{} active overflow");
}
if (dispatch)
{
client.getExecutor().execute(new Runnable()
{
@Override
public void run()
{
httpConnection.send(request, listeners);
}
});
}
else
{
httpConnection.send(request, listeners);
}
}
}
}
public void release(Connection connection)
{
LOG.debug("{} released", connection);
if (client.isRunning())
{
boolean removed = activeConnections.remove(connection);
if (removed)
process(connection, false);
else
LOG.debug("{} explicit", connection);
}
else
{
LOG.debug("{} is stopped", client);
remove(connection);
connection.close();
}
}
public void remove(Connection connection)
{
boolean removed = activeConnections.remove(connection);
removed |= idleConnections.remove(connection);
if (removed)
{
int open = connectionCount.decrementAndGet();
LOG.info("Removed connection {} for {} - open: {}", connection, this, open);
}
// We need to execute queued requests even if this connection failed.
// We may create a connection that is not needed, but it will eventually
// idle timeout, so no worries
if (!requests.isEmpty())
{
connection = acquire();
if (connection != null)
process(connection, false);
}
}
public void close()
{
for (Connection connection : idleConnections)
connection.close();
idleConnections.clear();
// A bit drastic, but we cannot wait for all requests to complete
for (Connection connection : activeConnections)
connection.close();
activeConnections.clear();
drain(new AsynchronousCloseException());
connectionCount.set(0);
LOG.debug("Closed {}", this);
}
public boolean abort(Request request, Throwable cause)
{
for (RequestContext requestContext : requests)
{
if (requestContext.request == request)
{
if (requests.remove(requestContext))
{
// We were able to remove the pair, so it won't be processed
abort(request, requestContext.listeners, cause);
LOG.debug("Aborted {} while queued", request);
return true;
}
}
}
return false;
}
private void abort(Request request, List<Response.ResponseListener> listeners, Throwable cause)
{
HttpResponse response = new HttpResponse(request, listeners);
responseNotifier.notifyFailure(listeners, response, cause);
responseNotifier.notifyComplete(listeners, new Result(request, cause, response, cause));
}
@Override
public String dump()
{
return ContainerLifeCycle.dump(this);
}
@Override
public void dump(Appendable out, String indent) throws IOException
{
ContainerLifeCycle.dumpObject(out, this + " - requests queued: " + requests.size());
List<String> connections = new ArrayList<>();
for (Connection connection : idleConnections)
connections.add(connection + " - IDLE");
for (Connection connection : activeConnections)
connections.add(connection + " - ACTIVE");
ContainerLifeCycle.dump(out, indent, connections);
}
@Override
public String toString()
{
return String.format("%s(%s://%s:%d)%s",
HttpDestination.class.getSimpleName(),
getScheme(),
getHost(),
getPort(),
proxyAddress == null ? "" : " via " + proxyAddress.getHostString() + ":" + proxyAddress.getPort());
}
private static class RequestContext
{
private final Request request;
private final List<Response.ResponseListener> listeners;
private RequestContext(Request request, List<Response.ResponseListener> listeners)
{
this.request = request;
this.listeners = listeners;
}
}
/**
* Decides whether to establish a proxy tunnel using HTTP CONNECT.
* It is implemented as a promise because it needs to establish the tunnel
* when the TCP connection is succeeded, and needs to notify another
* promise when the tunnel is established (or failed).
*/
private class ProxyPromise implements Promise<Connection>
{
private final Promise<Connection> delegate;
private ProxyPromise(Promise<Connection> delegate)
{
this.delegate = delegate;
}
@Override
public void succeeded(Connection connection)
{
boolean tunnel = isProxied() &&
"https".equalsIgnoreCase(getScheme()) &&
client.getSslContextFactory() != null;
if (tunnel)
tunnel(connection);
else
delegate.succeeded(connection);
}
@Override
public void failed(Throwable x)
{
delegate.failed(x);
}
private void tunnel(final Connection connection)
{
String target = address.getHostString() + ":" + address.getPort();
Request connect = client.newRequest(proxyAddress.getHostString(), proxyAddress.getPort())
.scheme(HttpScheme.HTTP.asString())
.method(HttpMethod.CONNECT)
.path(target)
.header(HttpHeader.HOST.asString(), target);
connection.send(connect, new TimedResponseListener(client.getConnectTimeout(), TimeUnit.MILLISECONDS, connect, new Response.CompleteListener()
{
@Override
public void onComplete(Result result)
{
if (result.isFailed())
{
failed(result.getFailure());
connection.close();
}
else
{
Response response = result.getResponse();
if (response.getStatus() == 200)
{
delegate.succeeded(connection);
}
else
{
failed(new HttpResponseException("Received " + response + " for " + result.getRequest(), response));
connection.close();
}
}
}
}));
}
}
}
| jetty-client/src/main/java/org/eclipse/jetty/client/HttpDestination.java | //
// ========================================================================
// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.client;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousCloseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.jetty.client.api.Connection;
import org.eclipse.jetty.client.api.Destination;
import org.eclipse.jetty.client.api.ProxyConfiguration;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.api.Result;
import org.eclipse.jetty.client.util.TimedResponseListener;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpScheme;
import org.eclipse.jetty.util.BlockingArrayQueue;
import org.eclipse.jetty.util.FuturePromise;
import org.eclipse.jetty.util.Promise;
import org.eclipse.jetty.util.component.ContainerLifeCycle;
import org.eclipse.jetty.util.component.Dumpable;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
public class HttpDestination implements Destination, AutoCloseable, Dumpable
{
private static final Logger LOG = Log.getLogger(HttpDestination.class);
private final AtomicInteger connectionCount = new AtomicInteger();
private final HttpClient client;
private final String scheme;
private final String host;
private final InetSocketAddress address;
private final Queue<RequestContext> requests;
private final BlockingQueue<Connection> idleConnections;
private final BlockingQueue<Connection> activeConnections;
private final RequestNotifier requestNotifier;
private final ResponseNotifier responseNotifier;
private final InetSocketAddress proxyAddress;
private final HttpField hostField;
public HttpDestination(HttpClient client, String scheme, String host, int port)
{
this.client = client;
this.scheme = scheme;
this.host = host;
this.address = new InetSocketAddress(host, port);
int maxRequestsQueued = client.getMaxRequestsQueuedPerDestination();
int capacity = Math.min(32, maxRequestsQueued);
this.requests = new BlockingArrayQueue<>(capacity, capacity, maxRequestsQueued);
int maxConnections = client.getMaxConnectionsPerDestination();
capacity = Math.min(8, maxConnections);
this.idleConnections = new BlockingArrayQueue<>(capacity, capacity, maxConnections);
this.activeConnections = new BlockingArrayQueue<>(capacity, capacity, maxConnections);
this.requestNotifier = new RequestNotifier(client);
this.responseNotifier = new ResponseNotifier(client);
ProxyConfiguration proxyConfig = client.getProxyConfiguration();
proxyAddress = proxyConfig != null && proxyConfig.matches(host, port) ?
new InetSocketAddress(proxyConfig.getHost(), proxyConfig.getPort()) : null;
String hostValue = host;
if ("https".equalsIgnoreCase(scheme) && port != 443 ||
"http".equalsIgnoreCase(scheme) && port != 80)
hostValue += ":" + port;
hostField = new HttpField(HttpHeader.HOST, hostValue);
}
protected BlockingQueue<Connection> getIdleConnections()
{
return idleConnections;
}
protected BlockingQueue<Connection> getActiveConnections()
{
return activeConnections;
}
@Override
public String getScheme()
{
return scheme;
}
@Override
public String getHost()
{
// InetSocketAddress.getHostString() transforms the host string
// in case of IPv6 addresses, so we return the original host string
return host;
}
@Override
public int getPort()
{
return address.getPort();
}
public InetSocketAddress getConnectAddress()
{
return isProxied() ? proxyAddress : address;
}
public boolean isProxied()
{
return proxyAddress != null;
}
public HttpField getHostField()
{
return hostField;
}
public void send(Request request, List<Response.ResponseListener> listeners)
{
if (!scheme.equals(request.getScheme()))
throw new IllegalArgumentException("Invalid request scheme " + request.getScheme() + " for destination " + this);
if (!getHost().equals(request.getHost()))
throw new IllegalArgumentException("Invalid request host " + request.getHost() + " for destination " + this);
int port = request.getPort();
if (port >= 0 && getPort() != port)
throw new IllegalArgumentException("Invalid request port " + port + " for destination " + this);
RequestContext requestContext = new RequestContext(request, listeners);
if (client.isRunning())
{
if (requests.offer(requestContext))
{
if (!client.isRunning() && requests.remove(requestContext))
{
throw new RejectedExecutionException(client + " is stopping");
}
else
{
LOG.debug("Queued {}", request);
requestNotifier.notifyQueued(request);
Connection connection = acquire();
if (connection != null)
process(connection, false);
}
}
else
{
throw new RejectedExecutionException("Max requests per destination " + client.getMaxRequestsQueuedPerDestination() + " exceeded");
}
}
else
{
throw new RejectedExecutionException(client + " is stopped");
}
}
public Future<Connection> newConnection()
{
FuturePromise<Connection> result = new FuturePromise<>();
newConnection(new ProxyPromise(result));
return result;
}
protected void newConnection(Promise<Connection> promise)
{
client.newConnection(this, promise);
}
protected Connection acquire()
{
Connection result = idleConnections.poll();
if (result != null)
return result;
final int maxConnections = client.getMaxConnectionsPerDestination();
while (true)
{
int current = connectionCount.get();
final int next = current + 1;
if (next > maxConnections)
{
LOG.debug("Max connections {} reached for {}", current, this);
// Try again the idle connections
return idleConnections.poll();
}
if (connectionCount.compareAndSet(current, next))
{
LOG.debug("Creating connection {}/{} for {}", next, maxConnections, this);
// This is the promise that is being called when a connection (eventually proxied) succeeds or fails.
Promise<Connection> promise = new Promise<Connection>()
{
@Override
public void succeeded(Connection connection)
{
process(connection, true);
}
@Override
public void failed(final Throwable x)
{
client.getExecutor().execute(new Runnable()
{
@Override
public void run()
{
drain(x);
}
});
}
};
// Create a new connection, and pass a ProxyPromise to establish a proxy tunnel, if needed.
// Differently from the case where the connection is created explicitly by applications, here
// we need to do a bit more logging and keep track of the connection count in case of failures.
newConnection(new ProxyPromise(promise)
{
@Override
public void succeeded(Connection connection)
{
LOG.debug("Created connection {}/{} {} for {}", next, maxConnections, connection, HttpDestination.this);
super.succeeded(connection);
}
@Override
public void failed(Throwable x)
{
LOG.debug("Connection failed {} for {}", x, HttpDestination.this);
connectionCount.decrementAndGet();
super.failed(x);
}
});
// Try again the idle connections
return idleConnections.poll();
}
}
}
private void drain(Throwable x)
{
RequestContext requestContext;
while ((requestContext = requests.poll()) != null)
{
Request request = requestContext.request;
requestNotifier.notifyFailure(request, x);
List<Response.ResponseListener> listeners = requestContext.listeners;
HttpResponse response = new HttpResponse(request, listeners);
responseNotifier.notifyFailure(listeners, response, x);
responseNotifier.notifyComplete(listeners, new Result(request, x, response, x));
}
}
/**
* <p>Processes a new connection making it idle or active depending on whether requests are waiting to be sent.</p>
* <p>A new connection is created when a request needs to be executed; it is possible that the request that
* triggered the request creation is executed by another connection that was just released, so the new connection
* may become idle.</p>
* <p>If a request is waiting to be executed, it will be dequeued and executed by the new connection.</p>
*
* @param connection the new connection
*/
protected void process(Connection connection, boolean dispatch)
{
// Ugly cast, but lack of generic reification forces it
final HttpConnection httpConnection = (HttpConnection)connection;
RequestContext requestContext = requests.poll();
if (requestContext == null)
{
LOG.debug("{} idle", httpConnection);
if (!idleConnections.offer(httpConnection))
{
LOG.debug("{} idle overflow");
httpConnection.close();
}
if (!client.isRunning())
{
LOG.debug("{} is stopping", client);
remove(httpConnection);
httpConnection.close();
}
}
else
{
final Request request = requestContext.request;
final List<Response.ResponseListener> listeners = requestContext.listeners;
Throwable cause = request.getAbortCause();
if (cause != null)
{
abort(request, listeners, cause);
LOG.debug("Aborted {} before processing", request);
}
else
{
LOG.debug("{} active", httpConnection);
if (!activeConnections.offer(httpConnection))
{
LOG.warn("{} active overflow");
}
if (dispatch)
{
client.getExecutor().execute(new Runnable()
{
@Override
public void run()
{
httpConnection.send(request, listeners);
}
});
}
else
{
httpConnection.send(request, listeners);
}
}
}
}
public void release(Connection connection)
{
LOG.debug("{} released", connection);
if (client.isRunning())
{
boolean removed = activeConnections.remove(connection);
if (removed)
process(connection, false);
else
LOG.debug("{} explicit", connection);
}
else
{
LOG.debug("{} is stopped", client);
remove(connection);
connection.close();
}
}
public void remove(Connection connection)
{
boolean removed = activeConnections.remove(connection);
removed |= idleConnections.remove(connection);
if (removed)
{
LOG.debug("{} removed", connection);
connectionCount.decrementAndGet();
}
// We need to execute queued requests even if this connection failed.
// We may create a connection that is not needed, but it will eventually
// idle timeout, so no worries
if (!requests.isEmpty())
{
connection = acquire();
if (connection != null)
process(connection, false);
}
}
public void close()
{
for (Connection connection : idleConnections)
connection.close();
idleConnections.clear();
// A bit drastic, but we cannot wait for all requests to complete
for (Connection connection : activeConnections)
connection.close();
activeConnections.clear();
drain(new AsynchronousCloseException());
connectionCount.set(0);
LOG.debug("Closed {}", this);
}
public boolean abort(Request request, Throwable cause)
{
for (RequestContext requestContext : requests)
{
if (requestContext.request == request)
{
if (requests.remove(requestContext))
{
// We were able to remove the pair, so it won't be processed
abort(request, requestContext.listeners, cause);
LOG.debug("Aborted {} while queued", request);
return true;
}
}
}
return false;
}
private void abort(Request request, List<Response.ResponseListener> listeners, Throwable cause)
{
HttpResponse response = new HttpResponse(request, listeners);
responseNotifier.notifyFailure(listeners, response, cause);
responseNotifier.notifyComplete(listeners, new Result(request, cause, response, cause));
}
@Override
public String dump()
{
return ContainerLifeCycle.dump(this);
}
@Override
public void dump(Appendable out, String indent) throws IOException
{
ContainerLifeCycle.dumpObject(out, this + " - requests queued: " + requests.size());
List<String> connections = new ArrayList<>();
for (Connection connection : idleConnections)
connections.add(connection + " - IDLE");
for (Connection connection : activeConnections)
connections.add(connection + " - ACTIVE");
ContainerLifeCycle.dump(out, indent, connections);
}
@Override
public String toString()
{
return String.format("%s(%s://%s:%d)%s",
HttpDestination.class.getSimpleName(),
getScheme(),
getHost(),
getPort(),
proxyAddress == null ? "" : " via " + proxyAddress.getHostString() + ":" + proxyAddress.getPort());
}
private static class RequestContext
{
private final Request request;
private final List<Response.ResponseListener> listeners;
private RequestContext(Request request, List<Response.ResponseListener> listeners)
{
this.request = request;
this.listeners = listeners;
}
}
/**
* Decides whether to establish a proxy tunnel using HTTP CONNECT.
* It is implemented as a promise because it needs to establish the tunnel
* when the TCP connection is succeeded, and needs to notify another
* promise when the tunnel is established (or failed).
*/
private class ProxyPromise implements Promise<Connection>
{
private final Promise<Connection> delegate;
private ProxyPromise(Promise<Connection> delegate)
{
this.delegate = delegate;
}
@Override
public void succeeded(Connection connection)
{
boolean tunnel = isProxied() &&
"https".equalsIgnoreCase(getScheme()) &&
client.getSslContextFactory() != null;
if (tunnel)
tunnel(connection);
else
delegate.succeeded(connection);
}
@Override
public void failed(Throwable x)
{
delegate.failed(x);
}
private void tunnel(final Connection connection)
{
String target = address.getHostString() + ":" + address.getPort();
Request connect = client.newRequest(proxyAddress.getHostString(), proxyAddress.getPort())
.scheme(HttpScheme.HTTP.asString())
.method(HttpMethod.CONNECT)
.path(target)
.header(HttpHeader.HOST.asString(), target);
connection.send(connect, new TimedResponseListener(client.getConnectTimeout(), TimeUnit.MILLISECONDS, connect, new Response.CompleteListener()
{
@Override
public void onComplete(Result result)
{
if (result.isFailed())
{
failed(result.getFailure());
connection.close();
}
else
{
Response response = result.getResponse();
if (response.getStatus() == 200)
{
delegate.succeeded(connection);
}
else
{
failed(new HttpResponseException("Received " + response + " for " + result.getRequest(), response));
connection.close();
}
}
}
}));
}
}
}
| Improved logging of removed connections.
| jetty-client/src/main/java/org/eclipse/jetty/client/HttpDestination.java | Improved logging of removed connections. | <ide><path>etty-client/src/main/java/org/eclipse/jetty/client/HttpDestination.java
<ide> removed |= idleConnections.remove(connection);
<ide> if (removed)
<ide> {
<del> LOG.debug("{} removed", connection);
<del> connectionCount.decrementAndGet();
<add> int open = connectionCount.decrementAndGet();
<add> LOG.info("Removed connection {} for {} - open: {}", connection, this, open);
<ide> }
<ide>
<ide> // We need to execute queued requests even if this connection failed. |
|
Java | apache-2.0 | 1e9d8a22550775d9aed64cac10e31b7693b67ad3 | 0 | SpineEventEngine/base,SpineEventEngine/base,SpineEventEngine/base | /*
* Copyright 2018, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.tools.reflections;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.Files;
import io.spine.tools.gradle.GradleTask;
import io.spine.tools.gradle.SpinePlugin;
import org.gradle.api.Action;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.scanners.TypeAnnotationsScanner;
import org.reflections.serializers.Serializer;
import org.reflections.serializers.XmlSerializer;
import org.reflections.util.ConfigurationBuilder;
import org.slf4j.Logger;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Set;
import static io.spine.tools.gradle.TaskName.BUILD;
import static io.spine.tools.gradle.TaskName.CLASSES;
import static io.spine.tools.gradle.TaskName.SCAN_CLASS_PATH;
import static io.spine.tools.reflections.Extension.REFLECTIONS_PLUGIN_EXTENSION;
import static io.spine.util.Exceptions.newIllegalArgumentException;
import static io.spine.util.Exceptions.newIllegalStateException;
import static java.io.File.separatorChar;
/**
* Gradle port for Maven Reflections Plugin.
*
* <p>Uses reflections embedded scanners to build it's serialized config. This
* serialized config is required for Reflections framework to run.
*
* <p>Corresponding Maven plugin does just the same.
*
* @author Alex Tymchenko
*/
public class ReflectionsPlugin extends SpinePlugin {
/**
* Applied to project.
*
* <p>The plugin runs after `:classes` task and before `:processResources`.
*/
@Override
public void apply(Project project) {
Logger log = log();
log.debug("Applying the Reflections plugin");
project.getExtensions()
.create(REFLECTIONS_PLUGIN_EXTENSION, Extension.class);
Action<Task> scanClassPathAction = task -> scanClassPath(project);
GradleTask task = newTask(SCAN_CLASS_PATH, scanClassPathAction)
.insertAfterTask(CLASSES)
.insertBeforeTask(BUILD)
.applyNowTo(project);
log.debug("Reflection Gradle plugin initialized with the Gradle task: {}", task);
}
private void scanClassPath(Project project) {
log().debug("Scanning the classpath");
String outputDirPath = project.getProjectDir() + "/build";
File outputDir = new File(outputDirPath);
ensureFolderCreated(outputDir);
String targetDirPath = Extension.getTargetDir(project);
File reflectionsOutputDir = new File(targetDirPath);
ensureFolderCreated(reflectionsOutputDir);
ConfigurationBuilder config = new ConfigurationBuilder();
config.setUrls(toUrls(outputDir));
config.setScanners(new SubTypesScanner(), new TypeAnnotationsScanner());
Serializer serializerInstance = new XmlSerializer();
config.setSerializer(serializerInstance);
Reflections reflections = new Reflections(config);
String reflectionsOutputFilePath =
targetDirPath + separatorChar + project.getName() + "-reflections.xml";
reflections.save(reflectionsOutputFilePath);
}
private static Set<URL> toUrls(File outputDir) {
// because they are file URIs, they will not cause any network-related issues.
@SuppressWarnings({"CollectionContainsUrl", "URLEqualsHashCode"})
ImmutableSet.Builder<URL> urls = ImmutableSet.builder();
try {
urls.add(outputDir.toURI()
.toURL());
} catch (MalformedURLException e) {
throw newIllegalArgumentException(
e, "Cannot parse an output directory: %s", outputDir.getAbsolutePath()
);
}
return urls.build();
}
private static void ensureFolderCreated(File folder) {
try {
Files.createParentDirs(folder);
} catch (IOException e) {
throw newIllegalStateException(
e, "Cannot create a folder: %s", folder.getAbsolutePath()
);
}
}
}
| tools/reflections-plugin/src/main/java/io/spine/tools/reflections/ReflectionsPlugin.java | /*
* Copyright 2018, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.tools.reflections;
import com.google.common.io.Files;
import io.spine.tools.gradle.GradleTask;
import io.spine.tools.gradle.SpinePlugin;
import org.gradle.api.Action;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.scanners.TypeAnnotationsScanner;
import org.reflections.serializers.Serializer;
import org.reflections.serializers.XmlSerializer;
import org.reflections.util.ConfigurationBuilder;
import org.slf4j.Logger;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;
import static io.spine.tools.gradle.TaskName.BUILD;
import static io.spine.tools.gradle.TaskName.CLASSES;
import static io.spine.tools.gradle.TaskName.SCAN_CLASS_PATH;
import static io.spine.tools.reflections.Extension.REFLECTIONS_PLUGIN_EXTENSION;
import static io.spine.util.Exceptions.newIllegalArgumentException;
import static io.spine.util.Exceptions.newIllegalStateException;
import static java.io.File.separatorChar;
/**
* Gradle port for Maven Reflections Plugin.
*
* <p>Uses reflections embedded scanners to build it's serialized config. This
* serialized config is required for Reflections framework to run.
*
* <p>Corresponding Maven plugin does just the same.
*
* @author Alex Tymchenko
*/
public class ReflectionsPlugin extends SpinePlugin {
/**
* Applied to project.
*
* <p>The plugin runs after `:classes` task and before `:processResources`.
*/
@Override
public void apply(Project project) {
Logger log = log();
log.debug("Applying the Reflections plugin");
project.getExtensions()
.create(REFLECTIONS_PLUGIN_EXTENSION, Extension.class);
Action<Task> scanClassPathAction = task -> scanClassPath(project);
GradleTask task = newTask(SCAN_CLASS_PATH, scanClassPathAction).insertAfterTask(CLASSES)
.insertBeforeTask(BUILD)
.applyNowTo(project);
log.debug("Reflection Gradle plugin initialized with the Gradle task: {}", task);
}
private void scanClassPath(Project project) {
log().debug("Scanning the classpath");
String outputDirPath = project.getProjectDir() + "/build";
File outputDir = new File(outputDirPath);
ensureFolderCreated(outputDir);
String targetDirPath = Extension.getTargetDir(project);
File reflectionsOutputDir = new File(targetDirPath);
ensureFolderCreated(reflectionsOutputDir);
ConfigurationBuilder config = new ConfigurationBuilder();
config.setUrls(toUrls(outputDir));
config.setScanners(new SubTypesScanner(), new TypeAnnotationsScanner());
Serializer serializerInstance = new XmlSerializer();
config.setSerializer(serializerInstance);
Reflections reflections = new Reflections(config);
String reflectionsOutputFilePath =
targetDirPath + separatorChar + project.getName() + "-reflections.xml";
reflections.save(reflectionsOutputFilePath);
}
private static Set<URL> toUrls(File outputDir) {
// because they are file URIs, they will not cause any network-related issues.
@SuppressWarnings({"CollectionContainsUrl", "URLEqualsHashCode"})
Set<URL> urls = new HashSet<>();
try {
urls.add(outputDir.toURI()
.toURL());
} catch (MalformedURLException e) {
throw newIllegalArgumentException(
e, "Cannot parse an output directory: %s", outputDir.getAbsolutePath()
);
}
return urls;
}
private static void ensureFolderCreated(File folder) {
try {
Files.createParentDirs(folder);
} catch (IOException e) {
throw newIllegalStateException(
e, "Cannot create a folder: %s", folder.getAbsolutePath()
);
}
}
}
| Use immutable set
| tools/reflections-plugin/src/main/java/io/spine/tools/reflections/ReflectionsPlugin.java | Use immutable set | <ide><path>ools/reflections-plugin/src/main/java/io/spine/tools/reflections/ReflectionsPlugin.java
<ide> */
<ide> package io.spine.tools.reflections;
<ide>
<add>import com.google.common.collect.ImmutableSet;
<ide> import com.google.common.io.Files;
<ide> import io.spine.tools.gradle.GradleTask;
<ide> import io.spine.tools.gradle.SpinePlugin;
<ide> import java.io.IOException;
<ide> import java.net.MalformedURLException;
<ide> import java.net.URL;
<del>import java.util.HashSet;
<ide> import java.util.Set;
<ide>
<ide> import static io.spine.tools.gradle.TaskName.BUILD;
<ide> .create(REFLECTIONS_PLUGIN_EXTENSION, Extension.class);
<ide>
<ide> Action<Task> scanClassPathAction = task -> scanClassPath(project);
<del> GradleTask task = newTask(SCAN_CLASS_PATH, scanClassPathAction).insertAfterTask(CLASSES)
<del> .insertBeforeTask(BUILD)
<del> .applyNowTo(project);
<add> GradleTask task = newTask(SCAN_CLASS_PATH, scanClassPathAction)
<add> .insertAfterTask(CLASSES)
<add> .insertBeforeTask(BUILD)
<add> .applyNowTo(project);
<ide>
<ide> log.debug("Reflection Gradle plugin initialized with the Gradle task: {}", task);
<ide> }
<ide> private static Set<URL> toUrls(File outputDir) {
<ide> // because they are file URIs, they will not cause any network-related issues.
<ide> @SuppressWarnings({"CollectionContainsUrl", "URLEqualsHashCode"})
<del> Set<URL> urls = new HashSet<>();
<add> ImmutableSet.Builder<URL> urls = ImmutableSet.builder();
<ide> try {
<ide> urls.add(outputDir.toURI()
<ide> .toURL());
<ide> e, "Cannot parse an output directory: %s", outputDir.getAbsolutePath()
<ide> );
<ide> }
<del> return urls;
<add> return urls.build();
<ide> }
<ide>
<ide> private static void ensureFolderCreated(File folder) { |
|
Java | apache-2.0 | 2d56a930ddc126adc94f3bbb8dcabe3fb5086f66 | 0 | jhaynie/titanium_mobile,formalin14/titanium_mobile,bhatfield/titanium_mobile,bhatfield/titanium_mobile,prop/titanium_mobile,smit1625/titanium_mobile,KoketsoMabuela92/titanium_mobile,sriks/titanium_mobile,FokkeZB/titanium_mobile,prop/titanium_mobile,linearhub/titanium_mobile,pinnamur/titanium_mobile,csg-coder/titanium_mobile,taoger/titanium_mobile,AngelkPetkov/titanium_mobile,kopiro/titanium_mobile,formalin14/titanium_mobile,perdona/titanium_mobile,sriks/titanium_mobile,falkolab/titanium_mobile,jvkops/titanium_mobile,FokkeZB/titanium_mobile,taoger/titanium_mobile,emilyvon/titanium_mobile,pec1985/titanium_mobile,rblalock/titanium_mobile,collinprice/titanium_mobile,FokkeZB/titanium_mobile,FokkeZB/titanium_mobile,peymanmortazavi/titanium_mobile,jvkops/titanium_mobile,bright-sparks/titanium_mobile,benbahrenburg/titanium_mobile,shopmium/titanium_mobile,collinprice/titanium_mobile,collinprice/titanium_mobile,csg-coder/titanium_mobile,KangaCoders/titanium_mobile,linearhub/titanium_mobile,kopiro/titanium_mobile,emilyvon/titanium_mobile,taoger/titanium_mobile,benbahrenburg/titanium_mobile,pinnamur/titanium_mobile,mvitr/titanium_mobile,taoger/titanium_mobile,benbahrenburg/titanium_mobile,FokkeZB/titanium_mobile,sriks/titanium_mobile,collinprice/titanium_mobile,KoketsoMabuela92/titanium_mobile,mvitr/titanium_mobile,KoketsoMabuela92/titanium_mobile,KoketsoMabuela92/titanium_mobile,mvitr/titanium_mobile,perdona/titanium_mobile,mano-mykingdom/titanium_mobile,openbaoz/titanium_mobile,shopmium/titanium_mobile,shopmium/titanium_mobile,collinprice/titanium_mobile,prop/titanium_mobile,benbahrenburg/titanium_mobile,peymanmortazavi/titanium_mobile,indera/titanium_mobile,mvitr/titanium_mobile,csg-coder/titanium_mobile,jvkops/titanium_mobile,shopmium/titanium_mobile,FokkeZB/titanium_mobile,perdona/titanium_mobile,mano-mykingdom/titanium_mobile,indera/titanium_mobile,formalin14/titanium_mobile,openbaoz/titanium_mobile,rblalock/titanium_mobile,pinnamur/titanium_mobile,peymanmortazavi/titanium_mobile,jhaynie/titanium_mobile,jvkops/titanium_mobile,emilyvon/titanium_mobile,benbahrenburg/titanium_mobile,cheekiatng/titanium_mobile,benbahrenburg/titanium_mobile,falkolab/titanium_mobile,csg-coder/titanium_mobile,arnaudsj/titanium_mobile,pec1985/titanium_mobile,formalin14/titanium_mobile,cheekiatng/titanium_mobile,jhaynie/titanium_mobile,mvitr/titanium_mobile,bhatfield/titanium_mobile,bright-sparks/titanium_mobile,pinnamur/titanium_mobile,taoger/titanium_mobile,indera/titanium_mobile,csg-coder/titanium_mobile,linearhub/titanium_mobile,bright-sparks/titanium_mobile,peymanmortazavi/titanium_mobile,ashcoding/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile,pinnamur/titanium_mobile,KangaCoders/titanium_mobile,perdona/titanium_mobile,bhatfield/titanium_mobile,jhaynie/titanium_mobile,csg-coder/titanium_mobile,KangaCoders/titanium_mobile,bhatfield/titanium_mobile,linearhub/titanium_mobile,mano-mykingdom/titanium_mobile,hieupham007/Titanium_Mobile,csg-coder/titanium_mobile,sriks/titanium_mobile,ashcoding/titanium_mobile,perdona/titanium_mobile,csg-coder/titanium_mobile,cheekiatng/titanium_mobile,prop/titanium_mobile,sriks/titanium_mobile,smit1625/titanium_mobile,KoketsoMabuela92/titanium_mobile,shopmium/titanium_mobile,pec1985/titanium_mobile,linearhub/titanium_mobile,smit1625/titanium_mobile,falkolab/titanium_mobile,KangaCoders/titanium_mobile,falkolab/titanium_mobile,shopmium/titanium_mobile,ashcoding/titanium_mobile,smit1625/titanium_mobile,shopmium/titanium_mobile,collinprice/titanium_mobile,FokkeZB/titanium_mobile,ashcoding/titanium_mobile,AngelkPetkov/titanium_mobile,linearhub/titanium_mobile,arnaudsj/titanium_mobile,jhaynie/titanium_mobile,KoketsoMabuela92/titanium_mobile,perdona/titanium_mobile,sriks/titanium_mobile,benbahrenburg/titanium_mobile,bright-sparks/titanium_mobile,cheekiatng/titanium_mobile,rblalock/titanium_mobile,taoger/titanium_mobile,openbaoz/titanium_mobile,pinnamur/titanium_mobile,prop/titanium_mobile,kopiro/titanium_mobile,emilyvon/titanium_mobile,taoger/titanium_mobile,bhatfield/titanium_mobile,bright-sparks/titanium_mobile,linearhub/titanium_mobile,bright-sparks/titanium_mobile,sriks/titanium_mobile,falkolab/titanium_mobile,KangaCoders/titanium_mobile,openbaoz/titanium_mobile,jvkops/titanium_mobile,arnaudsj/titanium_mobile,ashcoding/titanium_mobile,KoketsoMabuela92/titanium_mobile,indera/titanium_mobile,pec1985/titanium_mobile,linearhub/titanium_mobile,hieupham007/Titanium_Mobile,rblalock/titanium_mobile,AngelkPetkov/titanium_mobile,FokkeZB/titanium_mobile,hieupham007/Titanium_Mobile,kopiro/titanium_mobile,KoketsoMabuela92/titanium_mobile,hieupham007/Titanium_Mobile,prop/titanium_mobile,kopiro/titanium_mobile,AngelkPetkov/titanium_mobile,jhaynie/titanium_mobile,indera/titanium_mobile,cheekiatng/titanium_mobile,rblalock/titanium_mobile,falkolab/titanium_mobile,benbahrenburg/titanium_mobile,pec1985/titanium_mobile,smit1625/titanium_mobile,emilyvon/titanium_mobile,taoger/titanium_mobile,KangaCoders/titanium_mobile,pinnamur/titanium_mobile,jvkops/titanium_mobile,ashcoding/titanium_mobile,mano-mykingdom/titanium_mobile,sriks/titanium_mobile,ashcoding/titanium_mobile,formalin14/titanium_mobile,cheekiatng/titanium_mobile,mvitr/titanium_mobile,peymanmortazavi/titanium_mobile,perdona/titanium_mobile,KangaCoders/titanium_mobile,prop/titanium_mobile,falkolab/titanium_mobile,pec1985/titanium_mobile,smit1625/titanium_mobile,arnaudsj/titanium_mobile,mvitr/titanium_mobile,formalin14/titanium_mobile,pinnamur/titanium_mobile,pinnamur/titanium_mobile,rblalock/titanium_mobile,emilyvon/titanium_mobile,pec1985/titanium_mobile,cheekiatng/titanium_mobile,jhaynie/titanium_mobile,perdona/titanium_mobile,AngelkPetkov/titanium_mobile,collinprice/titanium_mobile,bhatfield/titanium_mobile,pec1985/titanium_mobile,hieupham007/Titanium_Mobile,falkolab/titanium_mobile,openbaoz/titanium_mobile,indera/titanium_mobile,KangaCoders/titanium_mobile,bright-sparks/titanium_mobile,emilyvon/titanium_mobile,kopiro/titanium_mobile,openbaoz/titanium_mobile,AngelkPetkov/titanium_mobile,jvkops/titanium_mobile,jhaynie/titanium_mobile,peymanmortazavi/titanium_mobile,arnaudsj/titanium_mobile,mano-mykingdom/titanium_mobile,hieupham007/Titanium_Mobile,openbaoz/titanium_mobile,emilyvon/titanium_mobile,rblalock/titanium_mobile,formalin14/titanium_mobile,pec1985/titanium_mobile,cheekiatng/titanium_mobile,mvitr/titanium_mobile,kopiro/titanium_mobile,ashcoding/titanium_mobile,hieupham007/Titanium_Mobile,arnaudsj/titanium_mobile,bright-sparks/titanium_mobile,AngelkPetkov/titanium_mobile,AngelkPetkov/titanium_mobile,prop/titanium_mobile,smit1625/titanium_mobile,jvkops/titanium_mobile,indera/titanium_mobile,formalin14/titanium_mobile,peymanmortazavi/titanium_mobile,shopmium/titanium_mobile,peymanmortazavi/titanium_mobile,bhatfield/titanium_mobile,indera/titanium_mobile,hieupham007/Titanium_Mobile,openbaoz/titanium_mobile,smit1625/titanium_mobile,collinprice/titanium_mobile,mano-mykingdom/titanium_mobile,rblalock/titanium_mobile,kopiro/titanium_mobile | /**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2010 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package ti.modules.titanium.ui.widget;
import java.util.ArrayList;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollProxy;
import org.appcelerator.titanium.proxy.TiViewProxy;
import org.appcelerator.titanium.util.TiConvert;
import org.appcelerator.titanium.view.TiCompositeLayout;
import org.appcelerator.titanium.view.TiUIView;
import ti.modules.titanium.ui.ScrollableViewProxy;
import android.os.Handler;
public class TiUIScrollableView extends TiUIView
{
public TiUIScrollableView(ScrollableViewProxy proxy, Handler handler)
{
super(proxy);
TiScrollableView view = new TiScrollableView(proxy, handler);
TiCompositeLayout.LayoutParams params = getLayoutParams();
params.autoFillsHeight = true;
params.autoFillsWidth = true;
setNativeView(view);
}
private TiScrollableView getView() {
return (TiScrollableView)getNativeView();
}
@Override
public void processProperties(KrollDict d) {
if (d.containsKey("views")) {
getView().setViews(d.get("views"));
}
if (d.containsKey("showPagingControls")) {
getView().setShowPagingControl(TiConvert.toBoolean(d, "showPagingControls"));
}
if (d.containsKey("currentPage")) {
setCurrentPage(TiConvert.toInt(d, "currentPage"));
}
super.processProperties(d);
}
@Override
public void propertyChanged(String key, Object oldValue, Object newValue, KrollProxy proxy) {
if("currentPage".equals(key)) {
setCurrentPage(TiConvert.toInt(newValue));
} else {
super.propertyChanged(key, oldValue, newValue, proxy);
}
}
public ArrayList<TiViewProxy> getViews() {
return getView().getViews();
}
public void setViews(Object viewsObject) {
getView().setViews(viewsObject);
if (proxy.hasProperty("currentPage")) {
setCurrentPage(TiConvert.toInt(proxy.getProperty("currentPage")));
}
}
public void addView(TiViewProxy proxy) {
getView().addView(proxy);
}
public void removeView(TiViewProxy proxy) {
getView().removeView(proxy);
}
public void showPager()
{
Object showPagingControlProperty = proxy.getProperty("showPagingControl");
if (showPagingControlProperty != null) {
boolean showPagingControl = TiConvert.toBoolean(showPagingControlProperty);
if (showPagingControl) {
getView().showPager();
}
}
}
public void hidePager()
{
getView().hidePager();
}
public void doMoveNext()
{
getView().doMoveNext();
}
public void doMovePrevious()
{
getView().doMovePrevious();
}
public void doScrollToView(Object view)
{
if (view instanceof Number) {
getView().doScrollToView(((Number)view).intValue());
} else if (view instanceof TiViewProxy) {
getView().doScrollToView((TiViewProxy)view);
}
}
public void setShowPagingControl(boolean showPagingControl)
{
getView().setShowPagingControl(showPagingControl);
}
public int getCurrentPage()
{
return getView().getSelectedItemPosition();
}
public void setCurrentPage(int page)
{
getView().doSetCurrentPage(page);
}
public void doSetCurrentPage(Object view) {
if (view instanceof Number) {
getView().doSetCurrentPage(((Number) view).intValue());
} else if (view instanceof TiViewProxy) {
getView().doSetCurrentPage((TiViewProxy) view);
}
}
}
| android/modules/ui/src/ti/modules/titanium/ui/widget/TiUIScrollableView.java | /**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2010 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package ti.modules.titanium.ui.widget;
import java.util.ArrayList;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollProxy;
import org.appcelerator.titanium.proxy.TiViewProxy;
import org.appcelerator.titanium.util.TiConvert;
import org.appcelerator.titanium.view.TiCompositeLayout;
import org.appcelerator.titanium.view.TiUIView;
import ti.modules.titanium.ui.ScrollableViewProxy;
import android.os.Handler;
public class TiUIScrollableView extends TiUIView
{
public TiUIScrollableView(ScrollableViewProxy proxy, Handler handler)
{
super(proxy);
TiScrollableView view = new TiScrollableView(proxy, handler);
TiCompositeLayout.LayoutParams params = getLayoutParams();
params.autoFillsHeight = true;
params.autoFillsWidth = true;
setNativeView(view);
}
private TiScrollableView getView() {
return (TiScrollableView)getNativeView();
}
@Override
public void processProperties(KrollDict d) {
if (d.containsKey("views")) {
getView().setViews(d.get("views"));
}
if (d.containsKey("showPagingControls")) {
getView().setShowPagingControl(TiConvert.toBoolean(d, "showPagingControls"));
}
if (d.containsKey("currentPage")) {
setCurrentPage(TiConvert.toInt(d, "currentPage"));
}
super.processProperties(d);
}
@Override
public void propertyChanged(String key, Object oldValue, Object newValue, KrollProxy proxy) {
if("currentPage".equals(key)) {
setCurrentPage(TiConvert.toInt(newValue));
} else {
super.propertyChanged(key, oldValue, newValue, proxy);
}
}
public ArrayList<TiViewProxy> getViews() {
return getView().getViews();
}
public void setViews(Object viewsObject) {
getView().setViews(viewsObject);
if (proxy.hasProperty("currentPage")) {
setCurrentPage(TiConvert.toInt(proxy.getProperty("currentPage")));
}
}
public void addView(TiViewProxy proxy) {
getView().addView(proxy);
}
public void removeView(TiViewProxy proxy) {
getView().removeView(proxy);
}
public void showPager()
{
boolean showPagingControl = TiConvert.toBoolean(proxy.getProperty("showPagingControl"));
if (showPagingControl) {
getView().showPager();
}
}
public void hidePager()
{
getView().hidePager();
}
public void doMoveNext()
{
getView().doMoveNext();
}
public void doMovePrevious()
{
getView().doMovePrevious();
}
public void doScrollToView(Object view)
{
if (view instanceof Number) {
getView().doScrollToView(((Number)view).intValue());
} else if (view instanceof TiViewProxy) {
getView().doScrollToView((TiViewProxy)view);
}
}
public void setShowPagingControl(boolean showPagingControl)
{
getView().setShowPagingControl(showPagingControl);
}
public int getCurrentPage()
{
return getView().getSelectedItemPosition();
}
public void setCurrentPage(int page)
{
getView().doSetCurrentPage(page);
}
public void doSetCurrentPage(Object view) {
if (view instanceof Number) {
getView().doSetCurrentPage(((Number) view).intValue());
} else if (view instanceof TiViewProxy) {
getView().doSetCurrentPage((TiViewProxy) view);
}
}
}
| [#2237 state:fixed-in-qa] updated ScrollableView to check for null view
scrollableView checks for null view before trying to show pagingControl
| android/modules/ui/src/ti/modules/titanium/ui/widget/TiUIScrollableView.java | [#2237 state:fixed-in-qa] updated ScrollableView to check for null view | <ide><path>ndroid/modules/ui/src/ti/modules/titanium/ui/widget/TiUIScrollableView.java
<ide>
<ide> public void showPager()
<ide> {
<del> boolean showPagingControl = TiConvert.toBoolean(proxy.getProperty("showPagingControl"));
<del> if (showPagingControl) {
<del> getView().showPager();
<add> Object showPagingControlProperty = proxy.getProperty("showPagingControl");
<add>
<add> if (showPagingControlProperty != null) {
<add> boolean showPagingControl = TiConvert.toBoolean(showPagingControlProperty);
<add> if (showPagingControl) {
<add> getView().showPager();
<add> }
<ide> }
<ide> }
<ide> |
|
Java | unlicense | ac2eefc278a701ba83205af85275bcaca9392112 | 0 | Phylogeny/ExtraBitManipulation | package com.phylogeny.extrabitmanipulation.packet;
import com.phylogeny.extrabitmanipulation.helper.BitAreaHelper;
import com.phylogeny.extrabitmanipulation.helper.ItemStackHelper;
import com.phylogeny.extrabitmanipulation.helper.BitToolSettingsHelper.ModelReadData;
import io.netty.buffer.ByteBuf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3i;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.IThreadListener;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.WorldServer;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
public class PacketReadBlockStates extends PacketBlockInteraction implements IMessage
{
private Vec3i drawnStartPoint;
private ModelReadData modelingData = new ModelReadData();
public PacketReadBlockStates() {}
public PacketReadBlockStates(BlockPos pos, Vec3d hit, Vec3i drawnStartPoint, ModelReadData modelingData)
{
super(pos, EnumFacing.UP, hit);
this.drawnStartPoint = drawnStartPoint;
this.modelingData = modelingData;
}
@Override
public void toBytes(ByteBuf buffer)
{
super.toBytes(buffer);
boolean notNull = drawnStartPoint != null;
buffer.writeBoolean(notNull);
if (notNull)
{
buffer.writeInt(drawnStartPoint.getX());
buffer.writeInt(drawnStartPoint.getY());
buffer.writeInt(drawnStartPoint.getZ());
}
modelingData.toBytes(buffer);
}
@Override
public void fromBytes(ByteBuf buffer)
{
super.fromBytes(buffer);
if (buffer.readBoolean())
drawnStartPoint = new Vec3i(buffer.readInt(), buffer.readInt(), buffer.readInt());
modelingData.fromBytes(buffer);
}
public static class Handler implements IMessageHandler<PacketReadBlockStates, IMessage>
{
@Override
public IMessage onMessage(final PacketReadBlockStates message, final MessageContext ctx)
{
IThreadListener mainThread = (WorldServer) ctx.getServerHandler().playerEntity.worldObj;
mainThread.addScheduledTask(new Runnable()
{
@Override
public void run()
{
EntityPlayer player = ctx.getServerHandler().playerEntity;
ItemStack stack = player.getHeldItemMainhand();
if (ItemStackHelper.isModelingToolStack(stack) && (!player.isSneaking() || message.drawnStartPoint != null))
BitAreaHelper.readBlockStates(stack, player, player.worldObj, message.getPos(),
message.getHit(), message.drawnStartPoint, message.modelingData);
}
});
return null;
}
}
} | src/main/java/com/phylogeny/extrabitmanipulation/packet/PacketReadBlockStates.java | package com.phylogeny.extrabitmanipulation.packet;
import com.phylogeny.extrabitmanipulation.helper.BitAreaHelper;
import com.phylogeny.extrabitmanipulation.helper.ItemStackHelper;
import com.phylogeny.extrabitmanipulation.helper.BitToolSettingsHelper.ModelReadData;
import io.netty.buffer.ByteBuf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3i;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.IThreadListener;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.WorldServer;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
public class PacketReadBlockStates extends PacketBlockInteraction implements IMessage
{
private Vec3i drawnStartPoint;
private ModelReadData modelingData = new ModelReadData();
public PacketReadBlockStates() {}
public PacketReadBlockStates(BlockPos pos, Vec3d hit, Vec3i drawnStartPoint, ModelReadData modelingData)
{
super(pos, EnumFacing.UP, hit);
this.drawnStartPoint = drawnStartPoint;
this.modelingData = modelingData;
}
@Override
public void toBytes(ByteBuf buffer)
{
super.toBytes(buffer);
boolean notNull = drawnStartPoint != null;
buffer.writeBoolean(notNull);
if (notNull)
{
buffer.writeInt(drawnStartPoint.getX());
buffer.writeInt(drawnStartPoint.getY());
buffer.writeInt(drawnStartPoint.getZ());
}
modelingData.toBytes(buffer);
}
@Override
public void fromBytes(ByteBuf buffer)
{
super.fromBytes(buffer);
if (buffer.readBoolean())
drawnStartPoint = new Vec3i(buffer.readInt(), buffer.readInt(), buffer.readInt());
modelingData.fromBytes(buffer);
}
public static class Handler implements IMessageHandler<PacketReadBlockStates, IMessage>
{
@Override
public IMessage onMessage(final PacketReadBlockStates message, final MessageContext ctx)
{
IThreadListener mainThread = (WorldServer) ctx.getServerHandler().playerEntity.worldObj;
mainThread.addScheduledTask(new Runnable()
{
@Override
public void run()
{
EntityPlayer player = ctx.getServerHandler().playerEntity;
ItemStack stack = player.getHeldItemMainhand();
if (ItemStackHelper.isModelingToolStack(stack) || message.drawnStartPoint != null)
BitAreaHelper.readBlockStates(stack, player, player.worldObj, message.getPos(),
message.getHit(), message.drawnStartPoint, message.modelingData);
}
});
return null;
}
}
} | Replaced accidentally deleted code.
| src/main/java/com/phylogeny/extrabitmanipulation/packet/PacketReadBlockStates.java | Replaced accidentally deleted code. | <ide><path>rc/main/java/com/phylogeny/extrabitmanipulation/packet/PacketReadBlockStates.java
<ide> {
<ide> EntityPlayer player = ctx.getServerHandler().playerEntity;
<ide> ItemStack stack = player.getHeldItemMainhand();
<del> if (ItemStackHelper.isModelingToolStack(stack) || message.drawnStartPoint != null)
<add> if (ItemStackHelper.isModelingToolStack(stack) && (!player.isSneaking() || message.drawnStartPoint != null))
<ide> BitAreaHelper.readBlockStates(stack, player, player.worldObj, message.getPos(),
<ide> message.getHit(), message.drawnStartPoint, message.modelingData);
<ide> } |
|
Java | apache-2.0 | addbda8f67733ce85744e3128f2fa406aacc1e7c | 0 | apache/solr,apache/solr,apache/solr,apache/solr,apache/solr | package org.apache.solr.search.function.distance;
/**
* 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.lucene.index.IndexReader;
import org.apache.lucene.search.Searcher;
import org.apache.solr.search.function.DocValues;
import org.apache.solr.search.function.ValueSource;
import java.io.IOException;
import java.util.Map;
/**
* Calculate the Haversine formula (distance) between any two points on a sphere
* Takes in four value sources: (latA, lonA); (latB, lonB).
* <p/>
* Assumes the value sources are in radians
* <p/>
* See http://en.wikipedia.org/wiki/Great-circle_distance and
* http://en.wikipedia.org/wiki/Haversine_formula for the actual formula and
* also http://www.movable-type.co.uk/scripts/latlong.html
*
* @see org.apache.solr.search.function.RadianFunction
*/
public class HaversineFunction extends ValueSource {
private ValueSource x1;
private ValueSource y1;
private ValueSource x2;
private ValueSource y2;
private double radius;
public HaversineFunction(ValueSource x1, ValueSource y1, ValueSource x2, ValueSource y2, double radius) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.radius = radius;
}
protected String name() {
return "hsin";
}
/**
* @param doc The doc to score
* @param x1DV
* @param y1DV
* @param x2DV
* @param y2DV
* @return The haversine distance formula
*/
protected double distance(int doc, DocValues x1DV, DocValues y1DV, DocValues x2DV, DocValues y2DV) {
double result = 0;
double x1 = x1DV.doubleVal(doc); //in radians
double y1 = y1DV.doubleVal(doc);
double x2 = x2DV.doubleVal(doc);
double y2 = y2DV.doubleVal(doc);
//make sure they aren't all the same, as then we can just return 0
result = DistanceUtils.haversine(x1, y1, x2, y2, radius);
return result;
}
@Override
public DocValues getValues(Map context, IndexReader reader) throws IOException {
final DocValues x1DV = x1.getValues(context, reader);
final DocValues y1DV = y1.getValues(context, reader);
final DocValues x2DV = x2.getValues(context, reader);
final DocValues y2DV = y2.getValues(context, reader);
return new DocValues() {
public float floatVal(int doc) {
return (float) doubleVal(doc);
}
public int intVal(int doc) {
return (int) doubleVal(doc);
}
public long longVal(int doc) {
return (long) doubleVal(doc);
}
public double doubleVal(int doc) {
return (double) distance(doc, x1DV, y1DV, x2DV, y2DV);
}
public String strVal(int doc) {
return Double.toString(doubleVal(doc));
}
@Override
public String toString(int doc) {
StringBuilder sb = new StringBuilder();
sb.append(name()).append('(');
sb.append(x1DV.toString(doc)).append(',').append(y1DV.toString(doc)).append(',')
.append(x2DV.toString(doc)).append(',').append(y2DV.toString(doc));
sb.append(')');
return sb.toString();
}
};
}
@Override
public void createWeight(Map context, Searcher searcher) throws IOException {
x1.createWeight(context, searcher);
x2.createWeight(context, searcher);
y1.createWeight(context, searcher);
y2.createWeight(context, searcher);
}
public boolean equals(Object o) {
if (this.getClass() != o.getClass()) return false;
HaversineFunction other = (HaversineFunction) o;
return this.name().equals(other.name())
&& x1.equals(other.x1) &&
y1.equals(other.y1) &&
x2.equals(other.x2) &&
y2.equals(other.y2) && radius == other.radius;
}
@Override
public int hashCode() {
int result;
long temp;
result = x1.hashCode();
result = 31 * result + y1.hashCode();
result = 31 * result + x2.hashCode();
result = 31 * result + y2.hashCode();
result = 31 * result + name().hashCode();
temp = radius != +0.0d ? Double.doubleToLongBits(radius) : 0L;
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
public String description() {
StringBuilder sb = new StringBuilder();
sb.append(name()).append('(');
sb.append(x1).append(',').append(y1).append(',').append(x2).append(',').append(y2);
sb.append(')');
return sb.toString();
}
}
| src/java/org/apache/solr/search/function/distance/HaversineFunction.java | package org.apache.solr.search.function.distance;
/**
* 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.lucene.index.IndexReader;
import org.apache.lucene.search.Searcher;
import org.apache.solr.search.function.DocValues;
import org.apache.solr.search.function.ValueSource;
import java.io.IOException;
import java.util.Map;
/**
* Calculate the Haversine formula (distance) between any two points on a sphere
* Takes in four value sources: (latA, lonA); (latB, lonB).
* <p/>
* Assumes the value sources are in radians
* <p/>
* See http://en.wikipedia.org/wiki/Great-circle_distance and
* http://en.wikipedia.org/wiki/Haversine_formula for the actual formula and
* also http://www.movable-type.co.uk/scripts/latlong.html
*
* @see org.apache.solr.search.function.RadianFunction
*/
public class HaversineFunction extends ValueSource {
private ValueSource x1;
private ValueSource y1;
private ValueSource x2;
private ValueSource y2;
private double radius;
public HaversineFunction(ValueSource x1, ValueSource y1, ValueSource x2, ValueSource y2, double radius) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.radius = radius;
}
protected String name() {
return "hsin";
}
/**
* @param doc The doc to score
* @param x1DV
* @param y1DV
* @param x2DV
* @param y2DV
* @return The haversine distance formula
*/
protected double distance(int doc, DocValues x1DV, DocValues y1DV, DocValues x2DV, DocValues y2DV) {
double result = 0;
double x1 = x1DV.doubleVal(doc); //in radians
double y1 = y1DV.doubleVal(doc);
double x2 = x2DV.doubleVal(doc);
double y2 = y2DV.doubleVal(doc);
//make sure they aren't all the same, as then we can just return 0
result = DistanceUtils.haversine(x1, y1, x2, y2, radius);
return result;
}
@Override
public DocValues getValues(Map context, IndexReader reader) throws IOException {
final DocValues x1DV = x1.getValues(context, reader);
final DocValues y1DV = y1.getValues(context, reader);
final DocValues x2DV = x2.getValues(context, reader);
final DocValues y2DV = y2.getValues(context, reader);
return new DocValues() {
public float floatVal(int doc) {
return (float) doubleVal(doc);
}
public int intVal(int doc) {
return (int) doubleVal(doc);
}
public long longVal(int doc) {
return (long) doubleVal(doc);
}
public double doubleVal(int doc) {
return (double) distance(doc, x1DV, y1DV, x2DV, y2DV);
}
public String strVal(int doc) {
return Double.toString(doubleVal(doc));
}
@Override
public String toString(int doc) {
StringBuilder sb = new StringBuilder();
sb.append(name()).append('(');
sb.append(x1DV.toString(doc)).append(',').append(y1DV.toString(doc)).append(',')
.append(x2DV.toString(doc)).append(',').append(y2DV.toString(doc));
sb.append(')');
return sb.toString();
}
};
}
@Override
public void createWeight(Map context, Searcher searcher) throws IOException {
x1.createWeight(context, searcher);
x2.createWeight(context, searcher);
y1.createWeight(context, searcher);
y2.createWeight(context, searcher);
}
public boolean equals(Object o) {
if (this.getClass() != o.getClass()) return false;
HaversineFunction other = (HaversineFunction) o;
return this.name().equals(other.name())
&& x1.equals(other.x1) &&
y1.equals(other.y1) &&
x2.equals(other.x2) &&
y2.equals(other.y2);
}
public int hashCode() {
return x1.hashCode() + x2.hashCode() + y1.hashCode() + y2.hashCode() + name().hashCode();
}
public String description() {
StringBuilder sb = new StringBuilder();
sb.append(name()).append('(');
sb.append(x1).append(',').append(y1).append(',').append(x2).append(',').append(y2);
sb.append(')');
return sb.toString();
}
}
| SOLR-1302: clean up hashcode.
git-svn-id: 3b1ff1236863b4d63a22e4dae568675c2e247730@881308 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/solr/search/function/distance/HaversineFunction.java | SOLR-1302: clean up hashcode. | <ide><path>rc/java/org/apache/solr/search/function/distance/HaversineFunction.java
<ide> && x1.equals(other.x1) &&
<ide> y1.equals(other.y1) &&
<ide> x2.equals(other.x2) &&
<del> y2.equals(other.y2);
<add> y2.equals(other.y2) && radius == other.radius;
<ide> }
<ide>
<add> @Override
<ide> public int hashCode() {
<del>
<del> return x1.hashCode() + x2.hashCode() + y1.hashCode() + y2.hashCode() + name().hashCode();
<add> int result;
<add> long temp;
<add> result = x1.hashCode();
<add> result = 31 * result + y1.hashCode();
<add> result = 31 * result + x2.hashCode();
<add> result = 31 * result + y2.hashCode();
<add> result = 31 * result + name().hashCode();
<add> temp = radius != +0.0d ? Double.doubleToLongBits(radius) : 0L;
<add> result = 31 * result + (int) (temp ^ (temp >>> 32));
<add> return result;
<ide> }
<ide>
<ide> public String description() { |
|
Java | mit | eec5d22ca03026a2bfde3fe50d781198e25a7166 | 0 | freeuni-sdp/xo-rooms | package ge.edu.freeuni.sdp.xo.rooms.service;
import java.util.*;
import ge.edu.freeuni.sdp.xo.rooms.data.*;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
@Path("")
@Produces( { MediaType.APPLICATION_JSON})
public class RoomsService {
public Repository getRepository(){
return FakeRepositoryFactory.createInMemoryRepository();
}
@GET
public List<Room> getAllRooms(@QueryParam("token") String token){
final ArrayList<Room> result = new ArrayList<Room>();
for (Room room : getRepository().getAll())
result.add(room);
return result;
}
@GET
@Path("{room_id}")
public Response getConcreteRoom(@PathParam("room_id") int id, @QueryParam("token") String token){
Room room = getRepository().find(id);
if(room == null){
return Response.status(Status.NOT_FOUND).build();
}
return Response.ok(room).build();
}
@POST
@Path("{room_id}")
public Response joinRoom(@PathParam("room_id") int id, @QueryParam("token") String token){
Room room = getRepository().find(id);
if(room == null){
return Response.status(Status.NOT_FOUND).build();
}
if(room.getx_user() == null){
int x_user = 1; //TODO get real userID from auth service
room.setx_user(x_user);
return Response.ok(room).build();
}else if(room.geto_user() == null){
int o_user = 2; //TODO get real userID from auth service
room.seto_user(o_user);
return Response.ok(room).build();
}else{
return Response.status(Status.CONFLICT).build();
}
}
@Path("{room_id}/{user_id}")
@DELETE
public Response leaveRoom(
@PathParam("room_id") int roomId,
@PathParam("user_id") int userId,
@QueryParam("token") String token){
Room room = getRepository().find(roomId);
if(room == null)
return Response.status(Status.NOT_FOUND).build();
if(room.getx_user() == userId){
room.setx_user(null);
return Response.ok().build();
}else if(room.geto_user() == userId){
room.seto_user(null);
return Response.ok().build();
}else
return Response.status(Status.NOT_FOUND).build();
}
} | src/main/java/ge/edu/freeuni/sdp/xo/rooms/service/RoomsService.java | package ge.edu.freeuni.sdp.xo.rooms.service;
import java.util.*;
import ge.edu.freeuni.sdp.xo.rooms.data.*;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
@Path("")
@Produces( { MediaType.APPLICATION_JSON})
public class RoomsService {
public Repository getRepository(){
return FakeRepositoryFactory.createInMemoryRepository();
}
@GET
public List<Room> getAllRooms(@QueryParam("token") String token){
final ArrayList<Room> result = new ArrayList<Room>();
for (Room room : getRepository().getAll())
result.add(room);
return result;
}
@GET
@Path("{room_id}")
public Response getConcreteRoom(@PathParam("room_id") int id, @QueryParam("token") String token){
Room room = getRepository().find(id);
if(room == null){
return Response.status(Status.NOT_FOUND).build();
}
return Response.ok(room).build();
}
@POST
@Path("{room_id}")
public Response joinRoom(@PathParam("room_id") int id, @QueryParam("token") String token){
Room room = getRepository().find(id);
if(room == null){
return Response.status(Status.NOT_FOUND).build();
}
if(room.getx_user() == null){
int x_user = 1; //TODO get real userID from auth service
room.setx_user(x_user);
return Response.ok().build();
}else if(room.geto_user() == null){
int o_user = 2; //TODO get real userID from auth service
room.seto_user(o_user);
return Response.ok().build();
}else{
return Response.status(Status.CONFLICT).build();
}
}
@Path("{room_id}/{user_id}")
@DELETE
public Response leaveRoom(
@PathParam("room_id") int roomId,
@PathParam("user_id") int userId,
@QueryParam("token") String token){
Room room = getRepository().find(roomId);
if(room == null)
return Response.status(Status.NOT_FOUND).build();
if(room.getx_user() == userId){
room.setx_user(null);
return Response.ok().build();
}else if(room.geto_user() == userId){
room.seto_user(null);
return Response.ok().build();
}else
return Response.status(Status.NOT_FOUND).build();
}
} | update api #16
| src/main/java/ge/edu/freeuni/sdp/xo/rooms/service/RoomsService.java | update api #16 | <ide><path>rc/main/java/ge/edu/freeuni/sdp/xo/rooms/service/RoomsService.java
<ide> if(room.getx_user() == null){
<ide> int x_user = 1; //TODO get real userID from auth service
<ide> room.setx_user(x_user);
<del> return Response.ok().build();
<add> return Response.ok(room).build();
<ide> }else if(room.geto_user() == null){
<ide> int o_user = 2; //TODO get real userID from auth service
<ide> room.seto_user(o_user);
<del> return Response.ok().build();
<add> return Response.ok(room).build();
<ide> }else{
<ide> return Response.status(Status.CONFLICT).build();
<ide> } |
|
Java | apache-2.0 | 725da3d2b3c4e4410ccbd661e83230b357428fab | 0 | Thog/enigma,Thog/enigma,jamierocks/enigma,Thog/enigma,jamierocks/enigma,jamierocks/enigma | /*******************************************************************************
* Copyright (c) 2014 Jeff Martin.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* Jeff Martin - initial API and implementation
******************************************************************************/
package cuchaz.enigma.analysis;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarFile;
import javassist.CannotCompileException;
import javassist.CtBehavior;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtMethod;
import javassist.NotFoundException;
import javassist.bytecode.AccessFlag;
import javassist.bytecode.Descriptor;
import javassist.bytecode.FieldInfo;
import javassist.expr.ConstructorCall;
import javassist.expr.ExprEditor;
import javassist.expr.FieldAccess;
import javassist.expr.MethodCall;
import javassist.expr.NewExpr;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import cuchaz.enigma.Constants;
import cuchaz.enigma.bytecode.ClassRenamer;
import cuchaz.enigma.mapping.BehaviorEntry;
import cuchaz.enigma.mapping.ClassEntry;
import cuchaz.enigma.mapping.ConstructorEntry;
import cuchaz.enigma.mapping.Entry;
import cuchaz.enigma.mapping.FieldEntry;
import cuchaz.enigma.mapping.MethodEntry;
import cuchaz.enigma.mapping.Translator;
public class JarIndex
{
private Set<ClassEntry> m_obfClassEntries;
private TranslationIndex m_translationIndex;
private Multimap<String,String> m_interfaces;
private Map<Entry,Access> m_access;
private Multimap<String,MethodEntry> m_methodImplementations;
private Multimap<BehaviorEntry,EntryReference<BehaviorEntry,BehaviorEntry>> m_behaviorReferences;
private Multimap<FieldEntry,EntryReference<FieldEntry,BehaviorEntry>> m_fieldReferences;
private Multimap<String,String> m_innerClasses;
private Map<String,String> m_outerClasses;
private Set<String> m_anonymousClasses;
private Map<MethodEntry,MethodEntry> m_bridgeMethods;
public JarIndex( )
{
m_obfClassEntries = Sets.newHashSet();
m_translationIndex = new TranslationIndex();
m_interfaces = HashMultimap.create();
m_access = Maps.newHashMap();
m_methodImplementations = HashMultimap.create();
m_behaviorReferences = HashMultimap.create();
m_fieldReferences = HashMultimap.create();
m_innerClasses = HashMultimap.create();
m_outerClasses = Maps.newHashMap();
m_anonymousClasses = Sets.newHashSet();
m_bridgeMethods = Maps.newHashMap();
}
public void indexJar( JarFile jar, boolean buildInnerClasses )
{
// step 1: read the class names
for( ClassEntry classEntry : JarClassIterator.getClassEntries( jar ) )
{
if( classEntry.isInDefaultPackage() )
{
// move out of default package
classEntry = new ClassEntry( Constants.NonePackage + "/" + classEntry.getName() );
}
m_obfClassEntries.add( classEntry );
}
// step 2: index method/field access
for( CtClass c : JarClassIterator.classes( jar ) )
{
ClassRenamer.moveAllClassesOutOfDefaultPackage( c, Constants.NonePackage );
ClassEntry classEntry = new ClassEntry( Descriptor.toJvmName( c.getName() ) );
for( CtField field : c.getDeclaredFields() )
{
FieldEntry fieldEntry = new FieldEntry( classEntry, field.getName() );
m_access.put( fieldEntry, Access.get( field ) );
}
for( CtBehavior behavior : c.getDeclaredBehaviors() )
{
MethodEntry methodEntry = new MethodEntry( classEntry, behavior.getName(), behavior.getSignature() );
m_access.put( methodEntry, Access.get( behavior ) );
}
}
// step 3: index extends, implements, fields, and methods
for( CtClass c : JarClassIterator.classes( jar ) )
{
ClassRenamer.moveAllClassesOutOfDefaultPackage( c, Constants.NonePackage );
String className = Descriptor.toJvmName( c.getName() );
m_translationIndex.addSuperclass( className, Descriptor.toJvmName( c.getClassFile().getSuperclass() ) );
for( String interfaceName : c.getClassFile().getInterfaces() )
{
className = Descriptor.toJvmName( className );
interfaceName = Descriptor.toJvmName( interfaceName );
if( className.equals( interfaceName ) )
{
throw new IllegalArgumentException( "Class cannot be its own interface! " + className );
}
m_interfaces.put( className, interfaceName );
}
for( CtField field : c.getDeclaredFields() )
{
m_translationIndex.addField( className, field.getName() );
}
for( CtBehavior behavior : c.getDeclaredBehaviors() )
{
indexBehavior( behavior );
}
}
// step 4: index field, method, constructor references
for( CtClass c : JarClassIterator.classes( jar ) )
{
ClassRenamer.moveAllClassesOutOfDefaultPackage( c, Constants.NonePackage );
for( CtBehavior behavior : c.getDeclaredBehaviors() )
{
indexBehaviorReferences( behavior );
}
}
if( buildInnerClasses )
{
// step 5: index inner classes and anonymous classes
for( CtClass c : JarClassIterator.classes( jar ) )
{
ClassRenamer.moveAllClassesOutOfDefaultPackage( c, Constants.NonePackage );
String outerClassName = findOuterClass( c );
if( outerClassName != null )
{
String innerClassName = Descriptor.toJvmName( c.getName() );
m_innerClasses.put( outerClassName, innerClassName );
m_outerClasses.put( innerClassName, outerClassName );
if( isAnonymousClass( c, outerClassName ) )
{
m_anonymousClasses.add( innerClassName );
// DEBUG
//System.out.println( "ANONYMOUS: " + outerClassName + "$" + innerClassName );
}
else
{
// DEBUG
//System.out.println( "INNER: " + outerClassName + "$" + innerClassName );
}
}
}
// step 6: update other indices with inner class info
Map<String,String> renames = Maps.newHashMap();
for( Map.Entry<String,String> entry : m_outerClasses.entrySet() )
{
renames.put( entry.getKey(), entry.getValue() + "$" + new ClassEntry( entry.getKey() ).getSimpleName() );
}
EntryRenamer.renameClassesInSet( renames, m_obfClassEntries );
m_translationIndex.renameClasses( renames );
EntryRenamer.renameClassesInMultimap( renames, m_interfaces );
EntryRenamer.renameClassesInMultimap( renames, m_methodImplementations );
EntryRenamer.renameClassesInMultimap( renames, m_behaviorReferences );
EntryRenamer.renameClassesInMultimap( renames, m_fieldReferences );
}
// step 6: update other indices with bridge method info
EntryRenamer.renameMethodsInMultimap( m_bridgeMethods, m_methodImplementations );
EntryRenamer.renameMethodsInMultimap( m_bridgeMethods, m_behaviorReferences );
EntryRenamer.renameMethodsInMultimap( m_bridgeMethods, m_fieldReferences );
}
private void indexBehavior( CtBehavior behavior )
{
// get the behavior entry
String className = Descriptor.toJvmName( behavior.getDeclaringClass().getName() );
final BehaviorEntry behaviorEntry = getBehaviorEntry( behavior );
if( behaviorEntry instanceof MethodEntry )
{
MethodEntry methodEntry = (MethodEntry)behaviorEntry;
// index implementation
m_methodImplementations.put( className, methodEntry );
// look for bridge methods
CtMethod bridgedMethod = getBridgedMethod( (CtMethod)behavior );
if( bridgedMethod != null )
{
MethodEntry bridgedMethodEntry = new MethodEntry(
new ClassEntry( className ),
bridgedMethod.getName(),
bridgedMethod.getSignature()
);
m_bridgeMethods.put( bridgedMethodEntry, methodEntry );
}
}
// looks like we don't care about constructors here
}
private void indexBehaviorReferences( CtBehavior behavior )
{
// index method calls
final BehaviorEntry behaviorEntry = getBehaviorEntry( behavior );
try
{
behavior.instrument( new ExprEditor( )
{
@Override
public void edit( MethodCall call )
{
String className = Descriptor.toJvmName( call.getClassName() );
MethodEntry calledMethodEntry = new MethodEntry(
new ClassEntry( className ),
call.getMethodName(),
call.getSignature()
);
calledMethodEntry = resolveMethodClass( calledMethodEntry );
EntryReference<BehaviorEntry,BehaviorEntry> reference = new EntryReference<BehaviorEntry,BehaviorEntry>(
calledMethodEntry,
behaviorEntry
);
m_behaviorReferences.put( calledMethodEntry, reference );
}
@Override
public void edit( FieldAccess call )
{
String className = Descriptor.toJvmName( call.getClassName() );
FieldEntry calledFieldEntry = new FieldEntry(
new ClassEntry( className ),
call.getFieldName()
);
EntryReference<FieldEntry,BehaviorEntry> reference = new EntryReference<FieldEntry,BehaviorEntry>(
calledFieldEntry,
behaviorEntry
);
m_fieldReferences.put( calledFieldEntry, reference );
}
@Override
public void edit( ConstructorCall call )
{
// TODO: save isSuper in the reference somehow
boolean isSuper = call.getMethodName().equals( "super" );
String className = Descriptor.toJvmName( call.getClassName() );
ConstructorEntry calledConstructorEntry = new ConstructorEntry(
new ClassEntry( className ),
call.getSignature()
);
EntryReference<BehaviorEntry,BehaviorEntry> reference = new EntryReference<BehaviorEntry,BehaviorEntry>(
calledConstructorEntry,
behaviorEntry
);
m_behaviorReferences.put( calledConstructorEntry, reference );
}
@Override
public void edit( NewExpr call )
{
String className = Descriptor.toJvmName( call.getClassName() );
ConstructorEntry calledConstructorEntry = new ConstructorEntry(
new ClassEntry( className ),
call.getSignature()
);
EntryReference<BehaviorEntry,BehaviorEntry> reference = new EntryReference<BehaviorEntry,BehaviorEntry>(
calledConstructorEntry,
behaviorEntry
);
m_behaviorReferences.put( calledConstructorEntry, reference );
}
} );
}
catch( CannotCompileException ex )
{
throw new Error( ex );
}
}
private BehaviorEntry getBehaviorEntry( CtBehavior behavior )
{
String className = Descriptor.toJvmName( behavior.getDeclaringClass().getName() );
if( behavior instanceof CtMethod )
{
return new MethodEntry(
new ClassEntry( className ),
behavior.getName(),
behavior.getSignature()
);
}
else if( behavior instanceof CtConstructor )
{
boolean isStatic = behavior.getName().equals( "<clinit>" );
if( isStatic )
{
return new ConstructorEntry( new ClassEntry( className ) );
}
else
{
return new ConstructorEntry( new ClassEntry( className ), behavior.getSignature() );
}
}
else
{
throw new IllegalArgumentException( "behavior must be a method or a constructor!" );
}
}
private MethodEntry resolveMethodClass( MethodEntry methodEntry )
{
// this entry could refer to a method on a class where the method is not actually implemented
// travel up the inheritance tree to find the closest implementation
while( !isMethodImplemented( methodEntry ) )
{
// is there a parent class?
String superclassName = m_translationIndex.getSuperclassName( methodEntry.getClassName() );
if( superclassName == null )
{
// this is probably a method from a class in a library
// we can't trace the implementation up any higher unless we index the library
return methodEntry;
}
// move up to the parent class
methodEntry = new MethodEntry(
new ClassEntry( superclassName ),
methodEntry.getName(),
methodEntry.getSignature()
);
}
return methodEntry;
}
private CtMethod getBridgedMethod( CtMethod method )
{
// bridge methods just call another method, cast it to the return type, and return the result
// let's see if we can detect this scenario
// skip non-synthetic methods
if( ( method.getModifiers() & AccessFlag.SYNTHETIC ) == 0 )
{
return null;
}
// get all the called methods
final List<MethodCall> methodCalls = Lists.newArrayList();
try
{
method.instrument( new ExprEditor( )
{
@Override
public void edit( MethodCall call )
{
methodCalls.add( call );
}
} );
}
catch( CannotCompileException ex )
{
// this is stupid... we're not even compiling anything
throw new Error( ex );
}
// is there just one?
if( methodCalls.size() != 1 )
{
return null;
}
MethodCall call = methodCalls.get( 0 );
try
{
// we have a bridge method!
return call.getMethod();
}
catch( NotFoundException ex )
{
// can't find the type? not a bridge method
return null;
}
}
private String findOuterClass( CtClass c )
{
// inner classes:
// have constructors that can (illegally) set synthetic fields
// the outer class is the only class that calls constructors
// use the synthetic fields to find the synthetic constructors
for( CtConstructor constructor : c.getDeclaredConstructors() )
{
if( !isIllegalConstructor( constructor ) )
{
continue;
}
ClassEntry classEntry = new ClassEntry( Descriptor.toJvmName( c.getName() ) );
ConstructorEntry constructorEntry = new ConstructorEntry( classEntry, constructor.getMethodInfo().getDescriptor() );
// who calls this constructor?
Set<ClassEntry> callerClasses = Sets.newHashSet();
for( EntryReference<BehaviorEntry,BehaviorEntry> reference : getBehaviorReferences( constructorEntry ) )
{
callerClasses.add( reference.context.getClassEntry() );
}
// is this called by exactly one class?
if( callerClasses.size() == 1 )
{
ClassEntry callerClassEntry = callerClasses.iterator().next();
// does this class make sense as an outer class?
if( !callerClassEntry.equals( classEntry ) )
{
return callerClassEntry.getName();
}
}
else if( callerClasses.size() > 1 )
{
System.out.println( "WARNING: Illegal constructor called by more than one class!" + callerClasses );
}
}
return null;
}
@SuppressWarnings( "unchecked" )
private boolean isIllegalConstructor( CtConstructor constructor )
{
// illegal constructors only set synthetic member fields, then call super()
String className = constructor.getDeclaringClass().getName();
// collect all the field accesses, constructor calls, and method calls
final List<FieldAccess> illegalFieldWrites = Lists.newArrayList();
final List<ConstructorCall> constructorCalls = Lists.newArrayList();
final List<MethodCall> methodCalls = Lists.newArrayList();
try
{
constructor.instrument( new ExprEditor( )
{
@Override
public void edit( FieldAccess fieldAccess )
{
if( fieldAccess.isWriter() && constructorCalls.isEmpty() )
{
illegalFieldWrites.add( fieldAccess );
}
}
@Override
public void edit( ConstructorCall constructorCall )
{
constructorCalls.add( constructorCall );
}
@Override
public void edit( MethodCall methodCall )
{
methodCalls.add( methodCall );
}
} );
}
catch( CannotCompileException ex )
{
// we're not compiling anything... this is stupid
throw new Error( ex );
}
// method calls are not allowed
if( !methodCalls.isEmpty() )
{
return false;
}
// is there only one constructor call?
if( constructorCalls.size() != 1 )
{
return false;
}
// is the call to super?
ConstructorCall constructorCall = constructorCalls.get( 0 );
if( !constructorCall.getMethodName().equals( "super" ) )
{
return false;
}
// are there any illegal field writes?
if( illegalFieldWrites.isEmpty() )
{
return false;
}
// are all the writes to synthetic fields?
for( FieldAccess fieldWrite : illegalFieldWrites )
{
// all illegal writes have to be to the local class
if( !fieldWrite.getClassName().equals( className ) )
{
System.err.println( String.format( "WARNING: illegal write to non-member field %s.%s", fieldWrite.getClassName(), fieldWrite.getFieldName() ) );
return false;
}
// find the field
FieldInfo fieldInfo = null;
for( FieldInfo info : (List<FieldInfo>)constructor.getDeclaringClass().getClassFile().getFields() )
{
if( info.getName().equals( fieldWrite.getFieldName() ) )
{
fieldInfo = info;
break;
}
}
if( fieldInfo == null )
{
// field is in a superclass or something, can't be a local synthetic member
return false;
}
// is this field synthetic?
boolean isSynthetic = (fieldInfo.getAccessFlags() & AccessFlag.SYNTHETIC) != 0;
if( !isSynthetic )
{
System.err.println( String.format( "WARNING: illegal write to non synthetic field %s.%s", className, fieldInfo.getName() ) );
return false;
}
}
// we passed all the tests!
return true;
}
private boolean isAnonymousClass( CtClass c, String outerClassName )
{
String innerClassName = Descriptor.toJvmName( c.getName() );
// anonymous classes:
// can't be abstract
// have only one constructor
// it's called exactly once by the outer class
// type of inner class not referenced anywhere in outer class
// is absract?
if( Modifier.isAbstract( c.getModifiers() ) )
{
return false;
}
// is there exactly one constructor?
if( c.getDeclaredConstructors().length != 1 )
{
return false;
}
CtConstructor constructor = c.getDeclaredConstructors()[0];
// is this constructor called exactly once?
ConstructorEntry constructorEntry = new ConstructorEntry(
new ClassEntry( innerClassName ),
constructor.getMethodInfo().getDescriptor()
);
if( getBehaviorReferences( constructorEntry ).size() != 1 )
{
return false;
}
// TODO: check outer class doesn't reference type
// except this is hard because we can't just load the outer class now
// we'd have to pre-index those references in the JarIndex
return true;
}
public Set<ClassEntry> getObfClassEntries( )
{
return m_obfClassEntries;
}
public TranslationIndex getTranslationIndex( )
{
return m_translationIndex;
}
public Access getAccess( Entry entry )
{
return m_access.get( entry );
}
public boolean isMethodImplemented( MethodEntry methodEntry )
{
Collection<MethodEntry> implementations = m_methodImplementations.get( methodEntry.getClassName() );
if( implementations == null )
{
return false;
}
return implementations.contains( methodEntry );
}
public ClassInheritanceTreeNode getClassInheritance( Translator deobfuscatingTranslator, ClassEntry obfClassEntry )
{
// get the root node
List<String> ancestry = Lists.newArrayList();
ancestry.add( obfClassEntry.getName() );
ancestry.addAll( m_translationIndex.getAncestry( obfClassEntry.getName() ) );
ClassInheritanceTreeNode rootNode = new ClassInheritanceTreeNode( deobfuscatingTranslator, ancestry.get( ancestry.size() - 1 ) );
// expand all children recursively
rootNode.load( m_translationIndex, true );
return rootNode;
}
public ClassImplementationsTreeNode getClassImplementations( Translator deobfuscatingTranslator, ClassEntry obfClassEntry )
{
// is this even an interface?
if( isInterface( obfClassEntry.getClassName() ) )
{
ClassImplementationsTreeNode node = new ClassImplementationsTreeNode( deobfuscatingTranslator, obfClassEntry );
node.load( this );
return node;
}
return null;
}
public MethodInheritanceTreeNode getMethodInheritance( Translator deobfuscatingTranslator, MethodEntry obfMethodEntry )
{
// travel to the ancestor implementation
String baseImplementationClassName = obfMethodEntry.getClassName();
for( String ancestorClassName : m_translationIndex.getAncestry( obfMethodEntry.getClassName() ) )
{
MethodEntry ancestorMethodEntry = new MethodEntry(
new ClassEntry( ancestorClassName ),
obfMethodEntry.getName(),
obfMethodEntry.getSignature()
);
if( isMethodImplemented( ancestorMethodEntry ) )
{
baseImplementationClassName = ancestorClassName;
}
}
// make a root node at the base
MethodEntry methodEntry = new MethodEntry(
new ClassEntry( baseImplementationClassName ),
obfMethodEntry.getName(),
obfMethodEntry.getSignature()
);
MethodInheritanceTreeNode rootNode = new MethodInheritanceTreeNode(
deobfuscatingTranslator,
methodEntry,
isMethodImplemented( methodEntry )
);
// expand the full tree
rootNode.load( this, true );
return rootNode;
}
public MethodImplementationsTreeNode getMethodImplementations( Translator deobfuscatingTranslator, MethodEntry obfMethodEntry )
{
MethodEntry interfaceMethodEntry;
// is this method on an interface?
if( isInterface( obfMethodEntry.getClassName() ) )
{
interfaceMethodEntry = obfMethodEntry;
}
else
{
// get the interface class
List<MethodEntry> methodInterfaces = Lists.newArrayList();
for( String interfaceName : getInterfaces( obfMethodEntry.getClassName() ) )
{
// is this method defined in this interface?
MethodEntry methodInterface = new MethodEntry(
new ClassEntry( interfaceName ),
obfMethodEntry.getName(),
obfMethodEntry.getSignature()
);
if( isMethodImplemented( methodInterface ) )
{
methodInterfaces.add( methodInterface );
}
}
if( methodInterfaces.isEmpty() )
{
return null;
}
if( methodInterfaces.size() > 1 )
{
throw new Error( "Too many interfaces define this method! This is not yet supported by Enigma!" );
}
interfaceMethodEntry = methodInterfaces.get( 0 );
}
MethodImplementationsTreeNode rootNode = new MethodImplementationsTreeNode( deobfuscatingTranslator, interfaceMethodEntry );
rootNode.load( this );
return rootNode;
}
public Set<MethodEntry> getRelatedMethodImplementations( MethodEntry obfMethodEntry )
{
Set<MethodEntry> methodEntries = Sets.newHashSet();
getRelatedMethodImplementations( methodEntries, getMethodInheritance( null, obfMethodEntry ) );
return methodEntries;
}
private void getRelatedMethodImplementations( Set<MethodEntry> methodEntries, MethodInheritanceTreeNode node )
{
MethodEntry methodEntry = node.getMethodEntry();
if( isMethodImplemented( methodEntry ) )
{
// collect the entry
methodEntries.add( methodEntry );
}
// look at interface methods too
MethodImplementationsTreeNode implementations = getMethodImplementations( null, methodEntry );
if( implementations != null )
{
getRelatedMethodImplementations( methodEntries, implementations );
}
// recurse
for( int i=0; i<node.getChildCount(); i++ )
{
getRelatedMethodImplementations( methodEntries, (MethodInheritanceTreeNode)node.getChildAt( i ) );
}
}
private void getRelatedMethodImplementations( Set<MethodEntry> methodEntries, MethodImplementationsTreeNode node )
{
MethodEntry methodEntry = node.getMethodEntry();
if( isMethodImplemented( methodEntry ) )
{
// collect the entry
methodEntries.add( methodEntry );
}
// recurse
for( int i=0; i<node.getChildCount(); i++ )
{
getRelatedMethodImplementations( methodEntries, (MethodImplementationsTreeNode)node.getChildAt( i ) );
}
}
public Collection<EntryReference<FieldEntry,BehaviorEntry>> getFieldReferences( FieldEntry fieldEntry )
{
return m_fieldReferences.get( fieldEntry );
}
public Collection<EntryReference<BehaviorEntry,BehaviorEntry>> getBehaviorReferences( BehaviorEntry behaviorEntry )
{
return m_behaviorReferences.get( behaviorEntry );
}
public Collection<String> getInnerClasses( String obfOuterClassName )
{
return m_innerClasses.get( obfOuterClassName );
}
public String getOuterClass( String obfInnerClassName )
{
return m_outerClasses.get( obfInnerClassName );
}
public boolean isAnonymousClass( String obfInnerClassName )
{
return m_anonymousClasses.contains( obfInnerClassName );
}
public Set<String> getInterfaces( String className )
{
Set<String> interfaceNames = new HashSet<String>();
interfaceNames.addAll( m_interfaces.get( className ) );
for( String ancestor : m_translationIndex.getAncestry( className ) )
{
interfaceNames.addAll( m_interfaces.get( ancestor ) );
}
return interfaceNames;
}
public Set<String> getImplementingClasses( String targetInterfaceName )
{
// linear search is fast enough for now
Set<String> classNames = Sets.newHashSet();
for( Map.Entry<String,String> entry : m_interfaces.entries() )
{
String className = entry.getKey();
String interfaceName = entry.getValue();
if( interfaceName.equals( targetInterfaceName ) )
{
classNames.add( className );
m_translationIndex.getSubclassNamesRecursively( classNames, className );
}
}
return classNames;
}
public boolean isInterface( String className )
{
return m_interfaces.containsValue( className );
}
public MethodEntry getBridgeMethod( MethodEntry methodEntry )
{
return m_bridgeMethods.get( methodEntry );
}
public boolean containsObfClass( ClassEntry obfClassEntry )
{
return m_obfClassEntries.contains( obfClassEntry );
}
public boolean containsObfField( FieldEntry obfFieldEntry )
{
return m_access.containsKey( obfFieldEntry );
}
public boolean containsObfMethod( MethodEntry obfMethodEntry )
{
return m_access.containsKey( obfMethodEntry );
}
}
| src/cuchaz/enigma/analysis/JarIndex.java | /*******************************************************************************
* Copyright (c) 2014 Jeff Martin.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* Jeff Martin - initial API and implementation
******************************************************************************/
package cuchaz.enigma.analysis;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarFile;
import javassist.CannotCompileException;
import javassist.CtBehavior;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtMethod;
import javassist.NotFoundException;
import javassist.bytecode.AccessFlag;
import javassist.bytecode.Descriptor;
import javassist.bytecode.FieldInfo;
import javassist.expr.ConstructorCall;
import javassist.expr.ExprEditor;
import javassist.expr.FieldAccess;
import javassist.expr.MethodCall;
import javassist.expr.NewExpr;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import cuchaz.enigma.Constants;
import cuchaz.enigma.bytecode.ClassRenamer;
import cuchaz.enigma.mapping.BehaviorEntry;
import cuchaz.enigma.mapping.ClassEntry;
import cuchaz.enigma.mapping.ConstructorEntry;
import cuchaz.enigma.mapping.Entry;
import cuchaz.enigma.mapping.FieldEntry;
import cuchaz.enigma.mapping.MethodEntry;
import cuchaz.enigma.mapping.Translator;
public class JarIndex
{
private Set<ClassEntry> m_obfClassEntries;
private TranslationIndex m_translationIndex;
private Multimap<String,String> m_interfaces;
private Map<Entry,Access> m_access;
private Multimap<String,MethodEntry> m_methodImplementations;
private Multimap<BehaviorEntry,EntryReference<BehaviorEntry,BehaviorEntry>> m_behaviorReferences;
private Multimap<FieldEntry,EntryReference<FieldEntry,BehaviorEntry>> m_fieldReferences;
private Multimap<String,String> m_innerClasses;
private Map<String,String> m_outerClasses;
private Set<String> m_anonymousClasses;
private Map<MethodEntry,MethodEntry> m_bridgeMethods;
public JarIndex( )
{
m_obfClassEntries = Sets.newHashSet();
m_translationIndex = new TranslationIndex();
m_interfaces = HashMultimap.create();
m_access = Maps.newHashMap();
m_methodImplementations = HashMultimap.create();
m_behaviorReferences = HashMultimap.create();
m_fieldReferences = HashMultimap.create();
m_innerClasses = HashMultimap.create();
m_outerClasses = Maps.newHashMap();
m_anonymousClasses = Sets.newHashSet();
m_bridgeMethods = Maps.newHashMap();
}
public void indexJar( JarFile jar, boolean buildInnerClasses )
{
// step 1: read the class names
for( ClassEntry classEntry : JarClassIterator.getClassEntries( jar ) )
{
if( classEntry.isInDefaultPackage() )
{
// move out of default package
classEntry = new ClassEntry( Constants.NonePackage + "/" + classEntry.getName() );
}
m_obfClassEntries.add( classEntry );
}
// step 2: index method/field access
for( CtClass c : JarClassIterator.classes( jar ) )
{
ClassRenamer.moveAllClassesOutOfDefaultPackage( c, Constants.NonePackage );
ClassEntry classEntry = new ClassEntry( Descriptor.toJvmName( c.getName() ) );
for( CtField field : c.getDeclaredFields() )
{
FieldEntry fieldEntry = new FieldEntry( classEntry, field.getName() );
m_access.put( fieldEntry, Access.get( field ) );
}
for( CtBehavior behavior : c.getDeclaredBehaviors() )
{
MethodEntry methodEntry = new MethodEntry( classEntry, behavior.getName(), behavior.getSignature() );
m_access.put( methodEntry, Access.get( behavior ) );
}
}
// step 3: index extends, implements, fields, and methods
for( CtClass c : JarClassIterator.classes( jar ) )
{
ClassRenamer.moveAllClassesOutOfDefaultPackage( c, Constants.NonePackage );
String className = Descriptor.toJvmName( c.getName() );
m_translationIndex.addSuperclass( className, Descriptor.toJvmName( c.getClassFile().getSuperclass() ) );
for( String interfaceName : c.getClassFile().getInterfaces() )
{
className = Descriptor.toJvmName( className );
interfaceName = Descriptor.toJvmName( interfaceName );
if( className.equals( interfaceName ) )
{
throw new IllegalArgumentException( "Class cannot be its own interface! " + className );
}
m_interfaces.put( className, interfaceName );
}
for( CtField field : c.getDeclaredFields() )
{
m_translationIndex.addField( className, field.getName() );
}
for( CtBehavior behavior : c.getDeclaredBehaviors() )
{
indexBehavior( behavior );
}
}
// step 4: index field, method, constructor references
for( CtClass c : JarClassIterator.classes( jar ) )
{
ClassRenamer.moveAllClassesOutOfDefaultPackage( c, Constants.NonePackage );
for( CtBehavior behavior : c.getDeclaredBehaviors() )
{
indexBehaviorReferences( behavior );
}
}
if( buildInnerClasses )
{
// step 5: index inner classes and anonymous classes
for( CtClass c : JarClassIterator.classes( jar ) )
{
ClassRenamer.moveAllClassesOutOfDefaultPackage( c, Constants.NonePackage );
String outerClassName = findOuterClass( c );
if( outerClassName != null )
{
String innerClassName = Descriptor.toJvmName( c.getName() );
m_innerClasses.put( outerClassName, innerClassName );
m_outerClasses.put( innerClassName, outerClassName );
if( isAnonymousClass( c, outerClassName ) )
{
m_anonymousClasses.add( innerClassName );
// DEBUG
//System.out.println( "ANONYMOUS: " + outerClassName + "$" + innerClassName );
}
else
{
// DEBUG
//System.out.println( "INNER: " + outerClassName + "$" + innerClassName );
}
}
}
// step 6: update other indices with inner class info
Map<String,String> renames = Maps.newHashMap();
for( Map.Entry<String,String> entry : m_outerClasses.entrySet() )
{
renames.put( entry.getKey(), entry.getValue() + "$" + new ClassEntry( entry.getKey() ).getSimpleName() );
}
EntryRenamer.renameClassesInSet( renames, m_obfClassEntries );
m_translationIndex.renameClasses( renames );
EntryRenamer.renameClassesInMultimap( renames, m_interfaces );
EntryRenamer.renameClassesInMultimap( renames, m_methodImplementations );
EntryRenamer.renameClassesInMultimap( renames, m_behaviorReferences );
EntryRenamer.renameClassesInMultimap( renames, m_fieldReferences );
}
// step 6: update other indices with bridge method info
EntryRenamer.renameMethodsInMultimap( m_bridgeMethods, m_methodImplementations );
EntryRenamer.renameMethodsInMultimap( m_bridgeMethods, m_behaviorReferences );
EntryRenamer.renameMethodsInMultimap( m_bridgeMethods, m_fieldReferences );
}
private void indexBehavior( CtBehavior behavior )
{
// get the behavior entry
String className = Descriptor.toJvmName( behavior.getDeclaringClass().getName() );
final BehaviorEntry behaviorEntry = getBehaviorEntry( behavior );
if( behaviorEntry instanceof MethodEntry )
{
MethodEntry methodEntry = (MethodEntry)behaviorEntry;
// index implementation
m_methodImplementations.put( className, methodEntry );
// look for bridge methods
CtMethod bridgedMethod = getBridgedMethod( (CtMethod)behavior );
if( bridgedMethod != null )
{
MethodEntry bridgedMethodEntry = new MethodEntry(
new ClassEntry( className ),
bridgedMethod.getName(),
bridgedMethod.getSignature()
);
m_bridgeMethods.put( bridgedMethodEntry, methodEntry );
}
}
// looks like we don't care about constructors here
}
private void indexBehaviorReferences( CtBehavior behavior )
{
// index method calls
final BehaviorEntry behaviorEntry = getBehaviorEntry( behavior );
try
{
behavior.instrument( new ExprEditor( )
{
@Override
public void edit( MethodCall call )
{
String className = Descriptor.toJvmName( call.getClassName() );
MethodEntry calledMethodEntry = new MethodEntry(
new ClassEntry( className ),
call.getMethodName(),
call.getSignature()
);
calledMethodEntry = resolveMethodClass( calledMethodEntry );
EntryReference<BehaviorEntry,BehaviorEntry> reference = new EntryReference<BehaviorEntry,BehaviorEntry>(
calledMethodEntry,
behaviorEntry
);
m_behaviorReferences.put( calledMethodEntry, reference );
}
@Override
public void edit( FieldAccess call )
{
String className = Descriptor.toJvmName( call.getClassName() );
FieldEntry calledFieldEntry = new FieldEntry(
new ClassEntry( className ),
call.getFieldName()
);
EntryReference<FieldEntry,BehaviorEntry> reference = new EntryReference<FieldEntry,BehaviorEntry>(
calledFieldEntry,
behaviorEntry
);
m_fieldReferences.put( calledFieldEntry, reference );
}
@Override
public void edit( ConstructorCall call )
{
// TODO: save isSuper in the reference somehow
boolean isSuper = call.getMethodName().equals( "super" );
String className = Descriptor.toJvmName( call.getClassName() );
ConstructorEntry calledConstructorEntry = new ConstructorEntry(
new ClassEntry( className ),
call.getSignature()
);
EntryReference<BehaviorEntry,BehaviorEntry> reference = new EntryReference<BehaviorEntry,BehaviorEntry>(
calledConstructorEntry,
behaviorEntry
);
m_behaviorReferences.put( calledConstructorEntry, reference );
}
@Override
public void edit( NewExpr call )
{
String className = Descriptor.toJvmName( call.getClassName() );
ConstructorEntry calledConstructorEntry = new ConstructorEntry(
new ClassEntry( className ),
call.getSignature()
);
EntryReference<BehaviorEntry,BehaviorEntry> reference = new EntryReference<BehaviorEntry,BehaviorEntry>(
calledConstructorEntry,
behaviorEntry
);
m_behaviorReferences.put( calledConstructorEntry, reference );
}
} );
}
catch( CannotCompileException ex )
{
throw new Error( ex );
}
}
private BehaviorEntry getBehaviorEntry( CtBehavior behavior )
{
String className = Descriptor.toJvmName( behavior.getDeclaringClass().getName() );
if( behavior instanceof CtMethod )
{
return new MethodEntry(
new ClassEntry( className ),
behavior.getName(),
behavior.getSignature()
);
}
else if( behavior instanceof CtConstructor )
{
boolean isStatic = behavior.getName().equals( "<clinit>" );
if( isStatic )
{
return new ConstructorEntry( new ClassEntry( className ) );
}
else
{
return new ConstructorEntry( new ClassEntry( className ), behavior.getSignature() );
}
}
else
{
throw new IllegalArgumentException( "behavior must be a method or a constructor!" );
}
}
private MethodEntry resolveMethodClass( MethodEntry methodEntry )
{
// this entry could refer to a method on a class where the method is not actually implemented
// travel up the inheritance tree to find the closest implementation
while( !isMethodImplemented( methodEntry ) )
{
// is there a parent class?
String superclassName = m_translationIndex.getSuperclassName( methodEntry.getClassName() );
if( superclassName == null )
{
// this is probably a method from a class in a library
// we can't trace the implementation up any higher unless we index the library
return methodEntry;
}
// move up to the parent class
methodEntry = new MethodEntry(
new ClassEntry( superclassName ),
methodEntry.getName(),
methodEntry.getSignature()
);
}
return methodEntry;
}
private CtMethod getBridgedMethod( CtMethod method )
{
// bridge methods just call another method, cast it to the return type, and return the result
// let's see if we can detect this scenario
// skip non-synthetic methods
if( ( method.getModifiers() & AccessFlag.SYNTHETIC ) == 0 )
{
return null;
}
// get all the called methods
final List<MethodCall> methodCalls = Lists.newArrayList();
try
{
method.instrument( new ExprEditor( )
{
@Override
public void edit( MethodCall call )
{
methodCalls.add( call );
}
} );
}
catch( CannotCompileException ex )
{
// this is stupid... we're not even compiling anything
throw new Error( ex );
}
// is there just one?
if( methodCalls.size() != 1 )
{
return null;
}
MethodCall call = methodCalls.get( 0 );
try
{
// we have a bridge method!
return call.getMethod();
}
catch( NotFoundException ex )
{
// can't find the type? not a bridge method
return null;
}
}
private String findOuterClass( CtClass c )
{
// inner classes:
// have constructors that can (illegally) set synthetic fields
// the outer class is the only class that calls constructors
// use the synthetic fields to find the synthetic constructors
for( CtConstructor constructor : c.getDeclaredConstructors() )
{
if( !isIllegalConstructor( constructor ) )
{
continue;
}
// who calls this constructor?
Set<ClassEntry> callerClasses = Sets.newHashSet();
ConstructorEntry constructorEntry = new ConstructorEntry(
new ClassEntry( Descriptor.toJvmName( c.getName() ) ),
constructor.getMethodInfo().getDescriptor()
);
for( EntryReference<BehaviorEntry,BehaviorEntry> reference : getBehaviorReferences( constructorEntry ) )
{
callerClasses.add( reference.context.getClassEntry() );
}
// is this called by exactly one class?
if( callerClasses.size() == 1 )
{
return callerClasses.iterator().next().getName();
}
else if( callerClasses.size() > 1 )
{
System.out.println( "WARNING: Illegal constructor called by more than one class!" + callerClasses );
}
}
return null;
}
@SuppressWarnings( "unchecked" )
private boolean isIllegalConstructor( CtConstructor constructor )
{
// illegal constructors only set synthetic member fields, then call super()
String className = constructor.getDeclaringClass().getName();
// collect all the field accesses, constructor calls, and method calls
final List<FieldAccess> illegalFieldWrites = Lists.newArrayList();
final List<ConstructorCall> constructorCalls = Lists.newArrayList();
final List<MethodCall> methodCalls = Lists.newArrayList();
try
{
constructor.instrument( new ExprEditor( )
{
@Override
public void edit( FieldAccess fieldAccess )
{
if( fieldAccess.isWriter() && constructorCalls.isEmpty() )
{
illegalFieldWrites.add( fieldAccess );
}
}
@Override
public void edit( ConstructorCall constructorCall )
{
constructorCalls.add( constructorCall );
}
@Override
public void edit( MethodCall methodCall )
{
methodCalls.add( methodCall );
}
} );
}
catch( CannotCompileException ex )
{
// we're not compiling anything... this is stupid
throw new Error( ex );
}
// method calls are not allowed
if( !methodCalls.isEmpty() )
{
return false;
}
// is there only one constructor call?
if( constructorCalls.size() != 1 )
{
return false;
}
// is the call to super?
ConstructorCall constructorCall = constructorCalls.get( 0 );
if( !constructorCall.getMethodName().equals( "super" ) )
{
return false;
}
// are there any illegal field writes?
if( illegalFieldWrites.isEmpty() )
{
return false;
}
// are all the writes to synthetic fields?
for( FieldAccess fieldWrite : illegalFieldWrites )
{
// all illegal writes have to be to the local class
if( !fieldWrite.getClassName().equals( className ) )
{
System.err.println( String.format( "WARNING: illegal write to non-member field %s.%s", fieldWrite.getClassName(), fieldWrite.getFieldName() ) );
return false;
}
// find the field
FieldInfo fieldInfo = null;
for( FieldInfo info : (List<FieldInfo>)constructor.getDeclaringClass().getClassFile().getFields() )
{
if( info.getName().equals( fieldWrite.getFieldName() ) )
{
fieldInfo = info;
break;
}
}
if( fieldInfo == null )
{
// field is in a superclass or something, can't be a local synthetic member
return false;
}
// is this field synthetic?
boolean isSynthetic = (fieldInfo.getAccessFlags() & AccessFlag.SYNTHETIC) != 0;
if( !isSynthetic )
{
System.err.println( String.format( "WARNING: illegal write to non synthetic field %s.%s", className, fieldInfo.getName() ) );
return false;
}
}
// we passed all the tests!
return true;
}
private boolean isAnonymousClass( CtClass c, String outerClassName )
{
String innerClassName = Descriptor.toJvmName( c.getName() );
// anonymous classes:
// can't be abstract
// have only one constructor
// it's called exactly once by the outer class
// type of inner class not referenced anywhere in outer class
// is absract?
if( Modifier.isAbstract( c.getModifiers() ) )
{
return false;
}
// is there exactly one constructor?
if( c.getDeclaredConstructors().length != 1 )
{
return false;
}
CtConstructor constructor = c.getDeclaredConstructors()[0];
// is this constructor called exactly once?
ConstructorEntry constructorEntry = new ConstructorEntry(
new ClassEntry( innerClassName ),
constructor.getMethodInfo().getDescriptor()
);
if( getBehaviorReferences( constructorEntry ).size() != 1 )
{
return false;
}
// TODO: check outer class doesn't reference type
// except this is hard because we can't just load the outer class now
// we'd have to pre-index those references in the JarIndex
return true;
}
public Set<ClassEntry> getObfClassEntries( )
{
return m_obfClassEntries;
}
public TranslationIndex getTranslationIndex( )
{
return m_translationIndex;
}
public Access getAccess( Entry entry )
{
return m_access.get( entry );
}
public boolean isMethodImplemented( MethodEntry methodEntry )
{
Collection<MethodEntry> implementations = m_methodImplementations.get( methodEntry.getClassName() );
if( implementations == null )
{
return false;
}
return implementations.contains( methodEntry );
}
public ClassInheritanceTreeNode getClassInheritance( Translator deobfuscatingTranslator, ClassEntry obfClassEntry )
{
// get the root node
List<String> ancestry = Lists.newArrayList();
ancestry.add( obfClassEntry.getName() );
ancestry.addAll( m_translationIndex.getAncestry( obfClassEntry.getName() ) );
ClassInheritanceTreeNode rootNode = new ClassInheritanceTreeNode( deobfuscatingTranslator, ancestry.get( ancestry.size() - 1 ) );
// expand all children recursively
rootNode.load( m_translationIndex, true );
return rootNode;
}
public ClassImplementationsTreeNode getClassImplementations( Translator deobfuscatingTranslator, ClassEntry obfClassEntry )
{
// is this even an interface?
if( isInterface( obfClassEntry.getClassName() ) )
{
ClassImplementationsTreeNode node = new ClassImplementationsTreeNode( deobfuscatingTranslator, obfClassEntry );
node.load( this );
return node;
}
return null;
}
public MethodInheritanceTreeNode getMethodInheritance( Translator deobfuscatingTranslator, MethodEntry obfMethodEntry )
{
// travel to the ancestor implementation
String baseImplementationClassName = obfMethodEntry.getClassName();
for( String ancestorClassName : m_translationIndex.getAncestry( obfMethodEntry.getClassName() ) )
{
MethodEntry ancestorMethodEntry = new MethodEntry(
new ClassEntry( ancestorClassName ),
obfMethodEntry.getName(),
obfMethodEntry.getSignature()
);
if( isMethodImplemented( ancestorMethodEntry ) )
{
baseImplementationClassName = ancestorClassName;
}
}
// make a root node at the base
MethodEntry methodEntry = new MethodEntry(
new ClassEntry( baseImplementationClassName ),
obfMethodEntry.getName(),
obfMethodEntry.getSignature()
);
MethodInheritanceTreeNode rootNode = new MethodInheritanceTreeNode(
deobfuscatingTranslator,
methodEntry,
isMethodImplemented( methodEntry )
);
// expand the full tree
rootNode.load( this, true );
return rootNode;
}
public MethodImplementationsTreeNode getMethodImplementations( Translator deobfuscatingTranslator, MethodEntry obfMethodEntry )
{
MethodEntry interfaceMethodEntry;
// is this method on an interface?
if( isInterface( obfMethodEntry.getClassName() ) )
{
interfaceMethodEntry = obfMethodEntry;
}
else
{
// get the interface class
List<MethodEntry> methodInterfaces = Lists.newArrayList();
for( String interfaceName : getInterfaces( obfMethodEntry.getClassName() ) )
{
// is this method defined in this interface?
MethodEntry methodInterface = new MethodEntry(
new ClassEntry( interfaceName ),
obfMethodEntry.getName(),
obfMethodEntry.getSignature()
);
if( isMethodImplemented( methodInterface ) )
{
methodInterfaces.add( methodInterface );
}
}
if( methodInterfaces.isEmpty() )
{
return null;
}
if( methodInterfaces.size() > 1 )
{
throw new Error( "Too many interfaces define this method! This is not yet supported by Enigma!" );
}
interfaceMethodEntry = methodInterfaces.get( 0 );
}
MethodImplementationsTreeNode rootNode = new MethodImplementationsTreeNode( deobfuscatingTranslator, interfaceMethodEntry );
rootNode.load( this );
return rootNode;
}
public Set<MethodEntry> getRelatedMethodImplementations( MethodEntry obfMethodEntry )
{
Set<MethodEntry> methodEntries = Sets.newHashSet();
getRelatedMethodImplementations( methodEntries, getMethodInheritance( null, obfMethodEntry ) );
return methodEntries;
}
private void getRelatedMethodImplementations( Set<MethodEntry> methodEntries, MethodInheritanceTreeNode node )
{
MethodEntry methodEntry = node.getMethodEntry();
if( isMethodImplemented( methodEntry ) )
{
// collect the entry
methodEntries.add( methodEntry );
}
// look at interface methods too
MethodImplementationsTreeNode implementations = getMethodImplementations( null, methodEntry );
if( implementations != null )
{
getRelatedMethodImplementations( methodEntries, implementations );
}
// recurse
for( int i=0; i<node.getChildCount(); i++ )
{
getRelatedMethodImplementations( methodEntries, (MethodInheritanceTreeNode)node.getChildAt( i ) );
}
}
private void getRelatedMethodImplementations( Set<MethodEntry> methodEntries, MethodImplementationsTreeNode node )
{
MethodEntry methodEntry = node.getMethodEntry();
if( isMethodImplemented( methodEntry ) )
{
// collect the entry
methodEntries.add( methodEntry );
}
// recurse
for( int i=0; i<node.getChildCount(); i++ )
{
getRelatedMethodImplementations( methodEntries, (MethodImplementationsTreeNode)node.getChildAt( i ) );
}
}
public Collection<EntryReference<FieldEntry,BehaviorEntry>> getFieldReferences( FieldEntry fieldEntry )
{
return m_fieldReferences.get( fieldEntry );
}
public Collection<EntryReference<BehaviorEntry,BehaviorEntry>> getBehaviorReferences( BehaviorEntry behaviorEntry )
{
return m_behaviorReferences.get( behaviorEntry );
}
public Collection<String> getInnerClasses( String obfOuterClassName )
{
return m_innerClasses.get( obfOuterClassName );
}
public String getOuterClass( String obfInnerClassName )
{
return m_outerClasses.get( obfInnerClassName );
}
public boolean isAnonymousClass( String obfInnerClassName )
{
return m_anonymousClasses.contains( obfInnerClassName );
}
public Set<String> getInterfaces( String className )
{
Set<String> interfaceNames = new HashSet<String>();
interfaceNames.addAll( m_interfaces.get( className ) );
for( String ancestor : m_translationIndex.getAncestry( className ) )
{
interfaceNames.addAll( m_interfaces.get( ancestor ) );
}
return interfaceNames;
}
public Set<String> getImplementingClasses( String targetInterfaceName )
{
// linear search is fast enough for now
Set<String> classNames = Sets.newHashSet();
for( Map.Entry<String,String> entry : m_interfaces.entries() )
{
String className = entry.getKey();
String interfaceName = entry.getValue();
if( interfaceName.equals( targetInterfaceName ) )
{
classNames.add( className );
m_translationIndex.getSubclassNamesRecursively( classNames, className );
}
}
return classNames;
}
public boolean isInterface( String className )
{
return m_interfaces.containsValue( className );
}
public MethodEntry getBridgeMethod( MethodEntry methodEntry )
{
return m_bridgeMethods.get( methodEntry );
}
public boolean containsObfClass( ClassEntry obfClassEntry )
{
return m_obfClassEntries.contains( obfClassEntry );
}
public boolean containsObfField( FieldEntry obfFieldEntry )
{
return m_access.containsKey( obfFieldEntry );
}
public boolean containsObfMethod( MethodEntry obfMethodEntry )
{
return m_access.containsKey( obfMethodEntry );
}
}
| fixed issue with inner class detection
| src/cuchaz/enigma/analysis/JarIndex.java | fixed issue with inner class detection | <ide><path>rc/cuchaz/enigma/analysis/JarIndex.java
<ide> continue;
<ide> }
<ide>
<add> ClassEntry classEntry = new ClassEntry( Descriptor.toJvmName( c.getName() ) );
<add> ConstructorEntry constructorEntry = new ConstructorEntry( classEntry, constructor.getMethodInfo().getDescriptor() );
<add>
<ide> // who calls this constructor?
<ide> Set<ClassEntry> callerClasses = Sets.newHashSet();
<del> ConstructorEntry constructorEntry = new ConstructorEntry(
<del> new ClassEntry( Descriptor.toJvmName( c.getName() ) ),
<del> constructor.getMethodInfo().getDescriptor()
<del> );
<ide> for( EntryReference<BehaviorEntry,BehaviorEntry> reference : getBehaviorReferences( constructorEntry ) )
<ide> {
<ide> callerClasses.add( reference.context.getClassEntry() );
<ide> // is this called by exactly one class?
<ide> if( callerClasses.size() == 1 )
<ide> {
<del> return callerClasses.iterator().next().getName();
<add> ClassEntry callerClassEntry = callerClasses.iterator().next();
<add>
<add> // does this class make sense as an outer class?
<add> if( !callerClassEntry.equals( classEntry ) )
<add> {
<add> return callerClassEntry.getName();
<add> }
<ide> }
<ide> else if( callerClasses.size() > 1 )
<ide> { |
|
Java | apache-2.0 | 70112dff7c80b03e8ec52ff6278f955124df8347 | 0 | shelsonjava/memcached-session-manager,KihwanCheon/memcached-session-manager,hongzhenglin/memcached-session-manager-1,shelsonjava/memcached-session-manager,hongzhenglin/memcached-session-manager-1,xloye/memcached-session-manager,magro/memcached-session-manager,fengshao0907/memcached-session-manager,xloye/memcached-session-manager,fengshao0907/memcached-session-manager,zhangwei5095/memcached-session-manager,KihwanCheon/memcached-session-manager,zhangwei5095/memcached-session-manager,mosoft521/memcached-session-manager,magro/memcached-session-manager,mosoft521/memcached-session-manager | /*
* Copyright 2010 Martin Grotzke
*
* 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 de.javakaffee.web.msm.serializer;
import java.util.Calendar;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.loader.WebappLoader;
import de.javakaffee.web.msm.JavaSerializationTranscoder;
import de.javakaffee.web.msm.MemcachedBackupSession;
import de.javakaffee.web.msm.MemcachedBackupSessionManager;
import de.javakaffee.web.msm.SessionAttributesTranscoder;
import de.javakaffee.web.msm.TranscoderService;
import de.javakaffee.web.msm.serializer.TestClasses.Address;
import de.javakaffee.web.msm.serializer.TestClasses.Component;
import de.javakaffee.web.msm.serializer.TestClasses.Person;
import de.javakaffee.web.msm.serializer.TestClasses.Person.Gender;
import de.javakaffee.web.msm.serializer.javolution.JavolutionTranscoder;
import de.javakaffee.web.msm.serializer.kryo.KryoTranscoder;
/**
* A simple benchmark for existing serialization strategies.
*
* @author <a href="mailto:[email protected]">Martin Grotzke</a>
*/
public class Benchmark {
/*
* 50000:
* -- JavaSerializationTranscoder --
Serializing 1000 sessions took 156863 msec.
serialized size is 59016 bytes.
-- JavolutionTranscoder --
Serializing 1000 sessions took 251870 msec.
serialized size is 138374 bytes.
-- KryoTranscoder --
Serializing 1000 sessions took 154816 msec.
serialized size is 70122 bytes.
*/
public static void main( final String[] args ) throws InterruptedException {
//Thread.sleep( 1000 );
final MemcachedBackupSessionManager manager = createManager();
// some warmup
final int warmupCycles = 100000;
warmup( manager, new JavaSerializationTranscoder(), warmupCycles, 100, 3 );
warmup( manager, new JavolutionTranscoder( Thread.currentThread().getContextClassLoader(), false ), warmupCycles, 100, 3 );
warmup( manager, new KryoTranscoder(), warmupCycles, 100, 3 );
recover();
benchmark( manager, 10, 500, 4 /* 4^4 = 256 */ );
benchmark( manager, 10, 100, 3 /* 3^3 = 27 */ );
benchmark( manager, 10, 10, 2 /* 2^2 = 4 */ );
// Thread.sleep( Integer.MAX_VALUE );
}
private static void benchmark( final MemcachedBackupSessionManager manager, final int rounds, final int countPersons,
final int nodesPerEdge ) throws InterruptedException {
final Stats javaSerStats = new Stats();
final Stats javaDeSerStats = new Stats();
benchmark( manager, new JavaSerializationTranscoder(), javaSerStats, javaDeSerStats, rounds, countPersons, nodesPerEdge );
recover();
final Stats javolutionSerStats = new Stats();
final Stats javolutionDeSerStats = new Stats();
benchmark( manager, new JavolutionTranscoder( Thread.currentThread().getContextClassLoader(), false ), javolutionSerStats,
javolutionDeSerStats, rounds, countPersons, nodesPerEdge );
recover();
final Stats kryoSerStats = new Stats();
final Stats kryoDeSerStats = new Stats();
benchmark( manager, new KryoTranscoder(), kryoSerStats, kryoDeSerStats, rounds, countPersons, nodesPerEdge );
System.out.println( "Serialization,Size,Ser-Min,Ser-Avg,Ser-Max,Deser-Min,Deser-Avg,Deser-Max");
System.out.println( toCSV( "Java", javaSerStats, javaDeSerStats ) );
System.out.println( toCSV( "Javolution", javolutionSerStats, javolutionDeSerStats ) );
System.out.println( toCSV( "Kryo", kryoSerStats, kryoDeSerStats ) );
}
private static String toCSV( final String name, final Stats serStats, final Stats deSerStats ) {
return name + "," + serStats.size +","+ minAvgMax( serStats ) + "," + minAvgMax( deSerStats );
}
private static String minAvgMax( final Stats stats ) {
return stats.min +","+ stats.avg +","+ stats.max;
}
private static void recover() throws InterruptedException {
Thread.sleep( 200 );
System.gc();
Thread.sleep( 200 );
}
private static void benchmark( final MemcachedBackupSessionManager manager, final SessionAttributesTranscoder transcoder,
final Stats serializationStats,
final Stats deserializationStats,
final int rounds, final int countPersons, final int nodesPerEdge ) throws InterruptedException {
System.out.println( "Running benchmark for " + transcoder.getClass().getSimpleName() + "..." +
" (rounds: "+ rounds +", persons: "+ countPersons +", nodes: "+ ((int)Math.pow( nodesPerEdge, nodesPerEdge ) + nodesPerEdge + 1 ) +")" );
final TranscoderService transcoderService = new TranscoderService( transcoder );
final MemcachedBackupSession session = createSession( manager, "123456789abcdefghijk987654321", countPersons, nodesPerEdge );
final byte[] data = transcoderService.serialize( session );
final int size = data.length;
for( int r = 0; r < rounds; r++ ) {
final long start = System.currentTimeMillis();
for( int i = 0; i < 500; i++ ) {
transcoderService.serialize( session );
}
serializationStats.registerSince( start );
serializationStats.setSize( size );
}
System.gc();
Thread.sleep( 100 );
// deserialization
for( int r = 0; r < rounds; r++ ) {
final long start = System.currentTimeMillis();
for( int i = 0; i < 500; i++ ) {
transcoderService.deserialize( data, null, null );
}
deserializationStats.registerSince( start );
deserializationStats.setSize( size );
}
}
private static void warmup( final MemcachedBackupSessionManager manager, final SessionAttributesTranscoder transcoder,
final int loops, final int countPersons, final int nodesPerEdge )
throws InterruptedException {
final TranscoderService transcoderService = new TranscoderService( transcoder );
final MemcachedBackupSession session = createSession( manager, "123456789abcdefghijk987654321", countPersons, nodesPerEdge );
System.out.print("Performing warmup for serialization using "+ transcoder.getClass().getSimpleName() +"...");
final long serWarmupStart = System.currentTimeMillis();
for( int i = 0; i < loops; i++ ) transcoderService.serialize( session );
System.out.println(" (" + (System.currentTimeMillis() - serWarmupStart) + " ms)");
System.out.print("Performing warmup for deserialization...");
final byte[] data = transcoderService.serialize( session );
final long deserWarmupStart = System.currentTimeMillis();
for( int i = 0; i < loops; i++ ) transcoderService.deserialize( data, null, null );
System.out.println(" (" + (System.currentTimeMillis() - deserWarmupStart) + " ms)");
}
private static MemcachedBackupSession createSession( final MemcachedBackupSessionManager manager, final String id,
final int countPersons, final int countNodesPerEdge ) {
final MemcachedBackupSession session = manager.createEmptySession();
session.setId( id );
session.setValid( true );
session.setAttribute( "stringbuffer", new StringBuffer( "<string\n&buffer/>" ) );
session.setAttribute( "stringbuilder", new StringBuilder( "<string\n&buffer/>" ) );
session.setAttribute( "persons", createPersons( countPersons ) );
session.setAttribute( "mycontainer", new TestClasses.MyContainer() );
session.setAttribute( "component", createComponents( countNodesPerEdge ) );
return session;
}
private static Component createComponents( final int countNodesPerEdge ) {
final Component root = new Component( "root" );
for ( int i = 0; i < countNodesPerEdge; i++ ) {
final Component node = new Component( "child" + i );
addChildren( node, countNodesPerEdge );
root.addChild( node );
}
return root;
}
private static void addChildren( final Component node, final int count ) {
for ( int i = 0; i < count; i++ ) {
node.addChild( new Component( node.getName() + "-" + i ) );
}
}
private static Person[] createPersons( final int countPersons ) {
final Person[] persons = new Person[countPersons];
for( int i = 0; i < countPersons; i++ ) {
final Calendar dateOfBirth = Calendar.getInstance();
dateOfBirth.set( Calendar.YEAR, dateOfBirth.get( Calendar.YEAR ) - 42 );
final Person person = TestClasses.createPerson( "Firstname" + i + " Lastname" + i,
i % 2 == 0 ? Gender.FEMALE : Gender.MALE,
dateOfBirth,
"email" + i + "[email protected]", "email" + i + "[email protected]", "email" + i + "[email protected]" );
person.addAddress( new Address( "route66", "123456", "sincity", "sincountry" ) );
if ( i > 0 ) {
person.addFriend( persons[i - 1] );
}
persons[i] = person;
}
return persons;
}
private static MemcachedBackupSessionManager createManager() {
final MemcachedBackupSessionManager manager = new MemcachedBackupSessionManager();
final StandardContext container = new StandardContext();
manager.setContainer( container );
final WebappLoader webappLoader = new WebappLoader() {
/**
* {@inheritDoc}
*/
@Override
public ClassLoader getClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
};
manager.getContainer().setLoader( webappLoader );
return manager;
}
static class Stats {
long min;
long max;
double avg;
int size;
private boolean _first = true;
private final AtomicInteger _count = new AtomicInteger();
/**
* A utility method that calculates the difference of the time
* between the given <code>startInMillis</code> and {@link System#currentTimeMillis()}
* and registers the difference via {@link #register(long)}.
* @param startInMillis the time in millis that shall be subtracted from {@link System#currentTimeMillis()}.
*/
public void registerSince( final long startInMillis ) {
register( System.currentTimeMillis() - startInMillis );
}
public void setSize( final int size ) {
this.size = size;
}
/**
* Register the given value.
* @param value the value to register.
*/
public void register( final long value ) {
if ( value < min || _first ) {
min = value;
}
if ( value > max || _first ) {
max = value;
}
avg = ( avg * _count.get() + value ) / _count.incrementAndGet();
_first = false;
}
/**
* Returns a string array with labels and values of count, min, avg and max.
* @return a String array.
*/
public String[] getInfo() {
return new String[] {
"Count = " + _count.get(),
"Min = "+ min,
"Avg = "+ avg,
"Max = "+ max
};
}
}
}
| serializer-benchmark/src/main/java/de/javakaffee/web/msm/serializer/Benchmark.java | /*
* Copyright 2010 Martin Grotzke
*
* 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 de.javakaffee.web.msm.serializer;
import java.util.Calendar;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.loader.WebappLoader;
import de.javakaffee.web.msm.JavaSerializationTranscoder;
import de.javakaffee.web.msm.MemcachedBackupSession;
import de.javakaffee.web.msm.MemcachedBackupSessionManager;
import de.javakaffee.web.msm.SessionAttributesTranscoder;
import de.javakaffee.web.msm.TranscoderService;
import de.javakaffee.web.msm.serializer.TestClasses.Address;
import de.javakaffee.web.msm.serializer.TestClasses.Component;
import de.javakaffee.web.msm.serializer.TestClasses.Person;
import de.javakaffee.web.msm.serializer.TestClasses.Person.Gender;
import de.javakaffee.web.msm.serializer.javolution.JavolutionTranscoder;
import de.javakaffee.web.msm.serializer.kryo.KryoTranscoder;
/**
* A simple benchmark for existing serialization strategies.
*
* @author <a href="mailto:[email protected]">Martin Grotzke</a>
*/
public class Benchmark {
/*
* 50000:
* -- JavaSerializationTranscoder --
Serializing 1000 sessions took 156863 msec.
serialized size is 59016 bytes.
-- JavolutionTranscoder --
Serializing 1000 sessions took 251870 msec.
serialized size is 138374 bytes.
-- KryoTranscoder --
Serializing 1000 sessions took 154816 msec.
serialized size is 70122 bytes.
*/
public static void main( final String[] args ) throws InterruptedException {
//Thread.sleep( 1000 );
final MemcachedBackupSessionManager manager = createManager();
benchmark( manager, 10, 10, 2 /* 2^2 = 4 */ );
benchmark( manager, 10, 100, 3 /* 3^3 = 27 */ );
benchmark( manager, 10, 500, 4 /* 4^4 = 256 */ );
// Thread.sleep( Integer.MAX_VALUE );
}
private static void benchmark( final MemcachedBackupSessionManager manager, final int rounds, final int countPersons,
final int nodesPerEdge ) throws InterruptedException {
final Stats javaSerStats = new Stats();
final Stats javaDeSerStats = new Stats();
benchmark( manager, new JavaSerializationTranscoder(), javaSerStats, javaDeSerStats, rounds, countPersons, nodesPerEdge );
recover();
final Stats javolutionSerStats = new Stats();
final Stats javolutionDeSerStats = new Stats();
benchmark( manager, new JavolutionTranscoder( Thread.currentThread().getContextClassLoader(), false ), javolutionSerStats,
javolutionDeSerStats, rounds, countPersons, nodesPerEdge );
recover();
final Stats kryoSerStats = new Stats();
final Stats kryoDeSerStats = new Stats();
benchmark( manager, new KryoTranscoder(), kryoSerStats, kryoDeSerStats, rounds, countPersons, nodesPerEdge );
System.out.println( "Serialization,Size,Ser-Min,Ser-Avg,Ser-Max,Deser-Min,Deser-Avg,Deser-Max");
System.out.println( toCSV( "Java", javaSerStats, javaDeSerStats ) );
System.out.println( toCSV( "Javolution", javolutionSerStats, javolutionDeSerStats ) );
System.out.println( toCSV( "Kryo", kryoSerStats, kryoDeSerStats ) );
}
private static String toCSV( final String name, final Stats serStats, final Stats deSerStats ) {
return name + "," + serStats.size +","+ minAvgMax( serStats ) + "," + minAvgMax( deSerStats );
}
private static String minAvgMax( final Stats stats ) {
return stats.min +","+ stats.avg +","+ stats.max;
}
private static void recover() throws InterruptedException {
Thread.sleep( 200 );
System.gc();
Thread.sleep( 200 );
}
private static void benchmark( final MemcachedBackupSessionManager manager, final SessionAttributesTranscoder transcoder,
final Stats serializationStats,
final Stats deserializationStats,
final int rounds, final int countPersons, final int nodesPerEdge ) throws InterruptedException {
System.out.println( "Running benchmark for " + transcoder.getClass().getSimpleName() + "..." +
" (rounds: "+ rounds +", persons: "+ countPersons +", nodes: "+ ((int)Math.pow( nodesPerEdge, nodesPerEdge ) + nodesPerEdge + 1 ) +")" );
final TranscoderService transcoderService = new TranscoderService( transcoder );
final MemcachedBackupSession session = createSession( manager, "123456789abcdefghijk987654321", countPersons, nodesPerEdge );
final byte[] data = transcoderService.serialize( session );
final int size = data.length;
for( int r = 0; r < rounds; r++ ) {
final long start = System.currentTimeMillis();
for( int i = 0; i < 500; i++ ) {
transcoderService.serialize( session );
}
serializationStats.registerSince( start );
serializationStats.setSize( size );
}
System.gc();
Thread.sleep( 100 );
// deserialization
for( int r = 0; r < rounds; r++ ) {
final long start = System.currentTimeMillis();
for( int i = 0; i < 500; i++ ) {
transcoderService.deserialize( data, null, null );
}
deserializationStats.registerSince( start );
deserializationStats.setSize( size );
}
}
private static MemcachedBackupSession createSession( final MemcachedBackupSessionManager manager, final String id,
final int countPersons, final int countNodesPerEdge ) {
final MemcachedBackupSession session = manager.createEmptySession();
session.setId( id );
session.setValid( true );
session.setAttribute( "stringbuffer", new StringBuffer( "<string\n&buffer/>" ) );
session.setAttribute( "stringbuilder", new StringBuilder( "<string\n&buffer/>" ) );
session.setAttribute( "persons", createPersons( countPersons ) );
session.setAttribute( "mycontainer", new TestClasses.MyContainer() );
session.setAttribute( "component", createComponents( countNodesPerEdge ) );
return session;
}
private static Component createComponents( final int countNodesPerEdge ) {
final Component root = new Component( "root" );
for ( int i = 0; i < countNodesPerEdge; i++ ) {
final Component node = new Component( "child" + i );
addChildren( node, countNodesPerEdge );
root.addChild( node );
}
return root;
}
private static void addChildren( final Component node, final int count ) {
for ( int i = 0; i < count; i++ ) {
node.addChild( new Component( node.getName() + "-" + i ) );
}
}
private static Person[] createPersons( final int countPersons ) {
final Person[] persons = new Person[countPersons];
for( int i = 0; i < countPersons; i++ ) {
final Calendar dateOfBirth = Calendar.getInstance();
dateOfBirth.set( Calendar.YEAR, dateOfBirth.get( Calendar.YEAR ) - 42 );
final Person person = TestClasses.createPerson( "Firstname" + i + " Lastname" + i,
i % 2 == 0 ? Gender.FEMALE : Gender.MALE,
dateOfBirth,
"email" + i + "[email protected]", "email" + i + "[email protected]", "email" + i + "[email protected]" );
person.addAddress( new Address( "route66", "123456", "sincity", "sincountry" ) );
if ( i > 0 ) {
person.addFriend( persons[i - 1] );
}
persons[i] = person;
}
return persons;
}
private static MemcachedBackupSessionManager createManager() {
final MemcachedBackupSessionManager manager = new MemcachedBackupSessionManager();
final StandardContext container = new StandardContext();
manager.setContainer( container );
final WebappLoader webappLoader = new WebappLoader() {
/**
* {@inheritDoc}
*/
@Override
public ClassLoader getClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
};
manager.getContainer().setLoader( webappLoader );
return manager;
}
static class Stats {
long min;
long max;
double avg;
int size;
private boolean _first = true;
private final AtomicInteger _count = new AtomicInteger();
/**
* A utility method that calculates the difference of the time
* between the given <code>startInMillis</code> and {@link System#currentTimeMillis()}
* and registers the difference via {@link #register(long)}.
* @param startInMillis the time in millis that shall be subtracted from {@link System#currentTimeMillis()}.
*/
public void registerSince( final long startInMillis ) {
register( System.currentTimeMillis() - startInMillis );
}
public void setSize( final int size ) {
this.size = size;
}
/**
* Register the given value.
* @param value the value to register.
*/
public void register( final long value ) {
if ( value < min || _first ) {
min = value;
}
if ( value > max || _first ) {
max = value;
}
avg = ( avg * _count.get() + value ) / _count.incrementAndGet();
_first = false;
}
/**
* Returns a string array with labels and values of count, min, avg and max.
* @return a String array.
*/
public String[] getInfo() {
return new String[] {
"Count = " + _count.get(),
"Min = "+ min,
"Avg = "+ avg,
"Max = "+ max
};
}
}
}
| Added warmup phase before running benchmarks. Charts and wiki page http://code.google.com/p/memcached-session-manager/wiki/SerializationStrategyBenchmark are updated, warmup times for the benchmark run:
Performing warmup for serialization using JavaSerializationTranscoder... (152425 ms)
Performing warmup for deserialization... (242905 ms)
Performing warmup for serialization using JavolutionTranscoder... (340135 ms)
Performing warmup for deserialization... (835926 ms)
Performing warmup for serialization using KryoTranscoder... (59988 ms)
Performing warmup for deserialization... (130425 ms)
| serializer-benchmark/src/main/java/de/javakaffee/web/msm/serializer/Benchmark.java | Added warmup phase before running benchmarks. Charts and wiki page http://code.google.com/p/memcached-session-manager/wiki/SerializationStrategyBenchmark are updated, warmup times for the benchmark run: Performing warmup for serialization using JavaSerializationTranscoder... (152425 ms) Performing warmup for deserialization... (242905 ms) Performing warmup for serialization using JavolutionTranscoder... (340135 ms) Performing warmup for deserialization... (835926 ms) Performing warmup for serialization using KryoTranscoder... (59988 ms) Performing warmup for deserialization... (130425 ms) | <ide><path>erializer-benchmark/src/main/java/de/javakaffee/web/msm/serializer/Benchmark.java
<ide>
<ide> final MemcachedBackupSessionManager manager = createManager();
<ide>
<add> // some warmup
<add> final int warmupCycles = 100000;
<add> warmup( manager, new JavaSerializationTranscoder(), warmupCycles, 100, 3 );
<add> warmup( manager, new JavolutionTranscoder( Thread.currentThread().getContextClassLoader(), false ), warmupCycles, 100, 3 );
<add> warmup( manager, new KryoTranscoder(), warmupCycles, 100, 3 );
<add> recover();
<add>
<add> benchmark( manager, 10, 500, 4 /* 4^4 = 256 */ );
<add> benchmark( manager, 10, 100, 3 /* 3^3 = 27 */ );
<ide> benchmark( manager, 10, 10, 2 /* 2^2 = 4 */ );
<del> benchmark( manager, 10, 100, 3 /* 3^3 = 27 */ );
<del> benchmark( manager, 10, 500, 4 /* 4^4 = 256 */ );
<ide>
<ide> // Thread.sleep( Integer.MAX_VALUE );
<ide> }
<ide> final int size = data.length;
<ide>
<ide> for( int r = 0; r < rounds; r++ ) {
<del>
<ide> final long start = System.currentTimeMillis();
<ide> for( int i = 0; i < 500; i++ ) {
<ide> transcoderService.serialize( session );
<ide> }
<ide> serializationStats.registerSince( start );
<ide> serializationStats.setSize( size );
<del>
<ide> }
<ide>
<ide> System.gc();
<ide> deserializationStats.setSize( size );
<ide> }
<ide>
<add> }
<add>
<add> private static void warmup( final MemcachedBackupSessionManager manager, final SessionAttributesTranscoder transcoder,
<add> final int loops, final int countPersons, final int nodesPerEdge )
<add> throws InterruptedException {
<add>
<add> final TranscoderService transcoderService = new TranscoderService( transcoder );
<add> final MemcachedBackupSession session = createSession( manager, "123456789abcdefghijk987654321", countPersons, nodesPerEdge );
<add>
<add> System.out.print("Performing warmup for serialization using "+ transcoder.getClass().getSimpleName() +"...");
<add> final long serWarmupStart = System.currentTimeMillis();
<add> for( int i = 0; i < loops; i++ ) transcoderService.serialize( session );
<add> System.out.println(" (" + (System.currentTimeMillis() - serWarmupStart) + " ms)");
<add>
<add> System.out.print("Performing warmup for deserialization...");
<add> final byte[] data = transcoderService.serialize( session );
<add> final long deserWarmupStart = System.currentTimeMillis();
<add> for( int i = 0; i < loops; i++ ) transcoderService.deserialize( data, null, null );
<add> System.out.println(" (" + (System.currentTimeMillis() - deserWarmupStart) + " ms)");
<add>
<ide> }
<ide>
<ide> private static MemcachedBackupSession createSession( final MemcachedBackupSessionManager manager, final String id, |
|
Java | apache-2.0 | e85421a7681e8c1fd1d0b82ffb9e681a124becfd | 0 | shypl/common-java | package org.shypl.common.util;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public final class RandomUtils {
public static int getInt() {
return ThreadLocalRandom.current().nextInt();
}
public static int getInt(int bound) {
return ThreadLocalRandom.current().nextInt(bound);
}
public static int getInt(int min, int max) {
return getInt(max + 1 - min) + min;
}
public static int getIndex(int[] weights) {
return getIndex(weights, ArrayUtils.sum(weights));
}
public static int getIndex(int[] weights, int weightsSum) {
int rnd = getInt(weightsSum);
int i = 0;
weightsSum = 0;
for (; i < weights.length; ++i) {
if (weights[i] != 0) {
weightsSum += weights[i];
if (weightsSum > rnd) {
return i;
}
}
}
return i;
}
public static long getLong() {
return ThreadLocalRandom.current().nextLong();
}
public static boolean getBoolean() {
return ThreadLocalRandom.current().nextBoolean();
}
public static boolean getElement(boolean[] array) {
return array[getInt(array.length)];
}
public static byte getElement(byte[] array) {
return array[getInt(array.length)];
}
public static char getElement(char[] array) {
return array[getInt(array.length)];
}
public static short getElement(short[] array) {
return array[getInt(array.length)];
}
public static int getElement(int[] array) {
return array[getInt(array.length)];
}
public static long getElement(long[] array) {
return array[getInt(array.length)];
}
public static float getElement(float[] array) {
return array[getInt(array.length)];
}
public static double getElement(double[] array) {
return array[getInt(array.length)];
}
public static <E> E getElement(E[] array) {
return array[getInt(array.length)];
}
public static <E> E getElement(List<E> list) {
return list.get(getInt(list.size()));
}
}
| src/main/java/org/shypl/common/util/RandomUtils.java | package org.shypl.common.util;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public final class RandomUtils {
public static int getInt() {
return ThreadLocalRandom.current().nextInt();
}
public static int getInt(int bound) {
return ThreadLocalRandom.current().nextInt(bound);
}
public static int getInt(int min, int max) {
return getInt(max + 1 - min) + min;
}
public static int getIndex(int[] weights) {
return getIndex(weights, ArrayUtils.sum(weights));
}
public static int getIndex(int[] weights, int weightsSum) {
int rnd = getInt(weightsSum);
int i = 0;
weightsSum = 0;
for (; i < weights.length; ++i) {
if (weights[i] != 0) {
weightsSum += weights[i];
if (weightsSum >= rnd) {
return i;
}
}
}
return i;
}
public static long getLong() {
return ThreadLocalRandom.current().nextLong();
}
public static boolean getBoolean() {
return ThreadLocalRandom.current().nextBoolean();
}
public static boolean getElement(boolean[] array) {
return array[getInt(array.length)];
}
public static byte getElement(byte[] array) {
return array[getInt(array.length)];
}
public static char getElement(char[] array) {
return array[getInt(array.length)];
}
public static short getElement(short[] array) {
return array[getInt(array.length)];
}
public static int getElement(int[] array) {
return array[getInt(array.length)];
}
public static long getElement(long[] array) {
return array[getInt(array.length)];
}
public static float getElement(float[] array) {
return array[getInt(array.length)];
}
public static double getElement(double[] array) {
return array[getInt(array.length)];
}
public static <E> E getElement(E[] array) {
return array[getInt(array.length)];
}
public static <E> E getElement(List<E> list) {
return list.get(getInt(list.size()));
}
}
| Улучьшение RandomUtils
| src/main/java/org/shypl/common/util/RandomUtils.java | Улучьшение RandomUtils | <ide><path>rc/main/java/org/shypl/common/util/RandomUtils.java
<ide> for (; i < weights.length; ++i) {
<ide> if (weights[i] != 0) {
<ide> weightsSum += weights[i];
<del> if (weightsSum >= rnd) {
<add> if (weightsSum > rnd) {
<ide> return i;
<ide> }
<ide> } |
|
Java | apache-2.0 | 737ba00a1b3fd9d2dc43dec07d35959986055575 | 0 | gumartinm/AndroidWeatherInformation,gumartinm/AndroidWeatherInformation | package de.example.exampletdd;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Calendar;
import java.util.Locale;
import org.apache.http.client.ClientProtocolException;
import android.app.IntentService;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.net.http.AndroidHttpClient;
import android.preference.PreferenceManager;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.widget.RemoteViews;
import com.fasterxml.jackson.core.JsonParseException;
import de.example.exampletdd.httpclient.CustomHTTPClient;
import de.example.exampletdd.model.DatabaseQueries;
import de.example.exampletdd.model.WeatherLocation;
import de.example.exampletdd.model.currentweather.Current;
import de.example.exampletdd.parser.JPOSWeatherParser;
import de.example.exampletdd.service.IconsList;
import de.example.exampletdd.service.PermanentStorage;
import de.example.exampletdd.service.ServiceParser;
import de.example.exampletdd.widget.WidgetConfigure;
public class WidgetIntentService extends IntentService {
private static final String TAG = "WidgetIntentService";
public WidgetIntentService() {
super("WIS-Thread");
}
@Override
protected void onHandleIntent(final Intent intent) {
Log.i(TAG, "onHandleIntent");
final int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
final boolean isUpdateByApp = intent.getBooleanExtra("updateByApp", false);
if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
// Nothing to do. Something went wrong. Show error.
return;
}
final DatabaseQueries query = new DatabaseQueries(this.getApplicationContext());
final WeatherLocation weatherLocation = query.queryDataBase();
if (weatherLocation == null) {
// Nothing to do. Show error.
final RemoteViews view = this.makeErrorView(appWidgetId);
this.updateWidget(view, appWidgetId);
return;
}
if (isUpdateByApp) {
this.updateByApp(weatherLocation, appWidgetId);
} else {
this.updateByTimeout(weatherLocation, appWidgetId);
}
}
private void updateByApp(final WeatherLocation weatherLocation, final int appWidgetId) {
final PermanentStorage store = new PermanentStorage(this.getApplicationContext());
final Current current = store.getCurrent();
this.updateWidget(current, weatherLocation, appWidgetId);
}
private void updateByTimeout(final WeatherLocation weatherLocation, final int appWidgetId) {
final Current current = this.getRemoteCurrent(weatherLocation);
this.updateWidget(current, weatherLocation, appWidgetId);
}
private void updateWidget(final Current current, final WeatherLocation weatherLocation, final int appWidgetId) {
if (current != null) {
final RemoteViews view = this.makeView(current, weatherLocation, appWidgetId);
this.updateWidget(view, appWidgetId);
} else {
// Show error.
final RemoteViews view = this.makeErrorView(appWidgetId);
this.updateWidget(view, appWidgetId);
}
}
private Current getRemoteCurrent(final WeatherLocation weatherLocation) {
final ServiceParser weatherService = new ServiceParser(new JPOSWeatherParser());
final CustomHTTPClient HTTPClient = new CustomHTTPClient(
AndroidHttpClient.newInstance("Android 4.3 WeatherInformation Agent"));
try {
return this.getRemoteCurrentThrowable(weatherLocation, HTTPClient, weatherService);
} catch (final JsonParseException e) {
Log.e(TAG, "doInBackground exception: ", e);
} catch (final ClientProtocolException e) {
Log.e(TAG, "doInBackground exception: ", e);
} catch (final MalformedURLException e) {
Log.e(TAG, "doInBackground exception: ", e);
} catch (final URISyntaxException e) {
Log.e(TAG, "doInBackground exception: ", e);
} catch (final IOException e) {
// logger infrastructure swallows UnknownHostException :/
Log.e(TAG, "doInBackground exception: " + e.getMessage(), e);
} finally {
HTTPClient.close();
}
return null;
}
private Current getRemoteCurrentThrowable(final WeatherLocation weatherLocation,
final CustomHTTPClient HTTPClient, final ServiceParser weatherService)
throws ClientProtocolException, MalformedURLException, URISyntaxException,
JsonParseException, IOException {
final String APIVersion = this.getResources().getString(R.string.api_version);
final String urlAPI = this.getResources().getString(R.string.uri_api_weather_today);
final String url = weatherService.createURIAPICurrent(urlAPI, APIVersion,
weatherLocation.getLatitude(), weatherLocation.getLongitude());
final String urlWithoutCache = url.concat("&time=" + System.currentTimeMillis());
final String jsonData = HTTPClient.retrieveDataAsString(new URL(urlWithoutCache));
final Current current = weatherService.retrieveCurrentFromJPOS(jsonData);
// TODO: what is this for? I guess I could skip it :/
final Calendar now = Calendar.getInstance();
current.setDate(now.getTime());
return current;
}
private interface UnitsConversor {
public double doConversion(final double value);
}
private RemoteViews makeView(final Current current, final WeatherLocation weatherLocation, final int appWidgetId) {
final SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
// TODO: repeating the same code in Overview, Specific and Current!!!
// 1. Update units of measurement.
// 1.1 Temperature
String tempSymbol;
UnitsConversor tempUnitsConversor;
String keyPreference = this.getResources().getString(R.string.weather_preferences_temperature_key);
String unitsPreferenceValue = sharedPreferences.getString(keyPreference, "");
String[] values = this.getResources().getStringArray(R.array.weather_preferences_temperature);
if (unitsPreferenceValue.equals(values[0])) {
tempSymbol = values[0];
tempUnitsConversor = new UnitsConversor(){
@Override
public double doConversion(final double value) {
return value - 273.15;
}
};
} else if (unitsPreferenceValue.equals(values[1])) {
tempSymbol = values[1];
tempUnitsConversor = new UnitsConversor(){
@Override
public double doConversion(final double value) {
return (value * 1.8) - 459.67;
}
};
} else {
tempSymbol = values[2];
tempUnitsConversor = new UnitsConversor(){
@Override
public double doConversion(final double value) {
return value;
}
};
}
// 2. Formatters
final DecimalFormat tempFormatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
tempFormatter.applyPattern("#####.#####");
// 3. Prepare data for RemoteViews.
String tempMax = "";
if (current.getMain().getTemp_max() != null) {
double conversion = (Double) current.getMain().getTemp_max();
conversion = tempUnitsConversor.doConversion(conversion);
tempMax = tempFormatter.format(conversion) + tempSymbol;
}
String tempMin = "";
if (current.getMain().getTemp_min() != null) {
double conversion = (Double) current.getMain().getTemp_min();
conversion = tempUnitsConversor.doConversion(conversion);
tempMin = tempFormatter.format(conversion) + tempSymbol;
}
Bitmap picture;
if ((current.getWeather().size() > 0)
&& (current.getWeather().get(0).getIcon() != null)
&& (IconsList.getIcon(current.getWeather().get(0).getIcon()) != null)) {
final String icon = current.getWeather().get(0).getIcon();
picture = BitmapFactory.decodeResource(this.getResources(), IconsList.getIcon(icon)
.getResourceDrawable());
} else {
picture = BitmapFactory.decodeResource(this.getResources(),
R.drawable.weather_severe_alert);
}
final String city = weatherLocation.getCity();
final String country = weatherLocation.getCountry();
// 4. Insert data in RemoteViews.
final RemoteViews remoteView = new RemoteViews(this.getApplicationContext().getPackageName(), R.layout.appwidget);
remoteView.setImageViewBitmap(R.id.weather_appwidget_image, picture);
remoteView.setTextViewText(R.id.weather_appwidget_temperature_max, tempMax);
remoteView.setTextViewText(R.id.weather_appwidget_temperature_min, tempMin);
remoteView.setTextViewText(R.id.weather_appwidget_city, city);
remoteView.setTextViewText(R.id.weather_appwidget_country, country);
// 5. Activity launcher.
final Intent resultIntent = new Intent(this.getApplicationContext(), WidgetConfigure.class);
resultIntent.putExtra("actionFromUser", true);
resultIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
// resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK );
// From: http://stackoverflow.com/questions/4011178/multiple-instances-of-widget-only-updating-last-widget
final Uri data = Uri.withAppendedPath(Uri.parse("PAIN" + "://widget/id/") ,String.valueOf(appWidgetId));
resultIntent.setData(data);
final TaskStackBuilder stackBuilder = TaskStackBuilder.create(this.getApplicationContext());
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(WidgetConfigure.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
final PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
remoteView.setOnClickPendingIntent(R.id.weather_appwidget, resultPendingIntent);
// final PendingIntent resultPendingIntent = PendingIntent.getActivity(
// this.getApplicationContext(),
// 0,
// resultIntent,
// PendingIntent.FLAG_UPDATE_CURRENT);
// remoteView.setOnClickPendingIntent(R.id.weather_appwidget, resultPendingIntent);
return remoteView;
}
private RemoteViews makeErrorView(final int appWidgetId) {
final RemoteViews remoteView = new RemoteViews(this.getApplicationContext().getPackageName(), R.layout.appwidget_error);
// 5. Activity launcher.
final Intent resultIntent = new Intent(this.getApplicationContext(), WidgetConfigure.class);
resultIntent.putExtra("actionFromUser", true);
resultIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
// resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK );
// From: http://stackoverflow.com/questions/4011178/multiple-instances-of-widget-only-updating-last-widget
final Uri data = Uri.withAppendedPath(Uri.parse("PAIN" + "://widget/id/") ,String.valueOf(appWidgetId));
resultIntent.setData(data);
final TaskStackBuilder stackBuilder = TaskStackBuilder.create(this.getApplicationContext());
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(WidgetConfigure.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
final PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
remoteView.setOnClickPendingIntent(R.id.weather_appwidget_error, resultPendingIntent);
// final PendingIntent resultPendingIntent = PendingIntent.getActivity(
// this.getApplicationContext(),
// 0,
// resultIntent,
// PendingIntent.FLAG_UPDATE_CURRENT);
// remoteView.setOnClickPendingIntent(R.id.weather_appwidget_error, resultPendingIntent);
return remoteView;
}
private void updateWidget(final RemoteViews remoteView, final int appWidgetId) {
final AppWidgetManager manager = AppWidgetManager.getInstance(this.getApplicationContext());
manager.updateAppWidget(appWidgetId, remoteView);
}
// private void updateWidgets(final RemoteViews remoteView) {
//
// final ComponentName widgets = new ComponentName(this.getApplicationContext(), WidgetProvider.class);
// final AppWidgetManager manager = AppWidgetManager.getInstance(this.getApplicationContext());
// manager.updateAppWidget(widgets, remoteView);
// }
}
| app/src/main/java/de/example/exampletdd/WidgetIntentService.java | package de.example.exampletdd;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Calendar;
import java.util.Locale;
import org.apache.http.client.ClientProtocolException;
import android.app.IntentService;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.net.http.AndroidHttpClient;
import android.preference.PreferenceManager;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.widget.RemoteViews;
import com.fasterxml.jackson.core.JsonParseException;
import de.example.exampletdd.httpclient.CustomHTTPClient;
import de.example.exampletdd.model.DatabaseQueries;
import de.example.exampletdd.model.WeatherLocation;
import de.example.exampletdd.model.currentweather.Current;
import de.example.exampletdd.parser.JPOSWeatherParser;
import de.example.exampletdd.service.IconsList;
import de.example.exampletdd.service.PermanentStorage;
import de.example.exampletdd.service.ServiceParser;
import de.example.exampletdd.widget.WidgetConfigure;
public class WidgetIntentService extends IntentService {
private static final String TAG = "WidgetIntentService";
public WidgetIntentService() {
super("WIS-Thread");
}
@Override
protected void onHandleIntent(final Intent intent) {
Log.i(TAG, "onHandleIntent");
final int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
final boolean isUpdateByApp = intent.getBooleanExtra("updateByApp", false);
if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
// Nothing to do. Something went wrong. Show error.
return;
}
final DatabaseQueries query = new DatabaseQueries(this.getApplicationContext());
final WeatherLocation weatherLocation = query.queryDataBase();
if (weatherLocation == null) {
// Nothing to do. Show error.
final RemoteViews view = this.makeErrorView(appWidgetId);
this.updateWidget(view, appWidgetId);
return;
}
if (isUpdateByApp) {
this.updateByApp(weatherLocation, appWidgetId);
} else {
this.updateByTimeout(weatherLocation, appWidgetId);
}
}
private void updateByApp(final WeatherLocation weatherLocation, final int appWidgetId) {
final PermanentStorage store = new PermanentStorage(this.getApplicationContext());
final Current current = store.getCurrent();
this.updateWidget(current, weatherLocation, appWidgetId);
}
private void updateByTimeout(final WeatherLocation weatherLocation, final int appWidgetId) {
final Current current = this.getRemoteCurrent(weatherLocation);
this.updateWidget(current, weatherLocation, appWidgetId);
}
private void updateWidget(final Current current, final WeatherLocation weatherLocation, final int appWidgetId) {
if (current != null) {
final RemoteViews view = this.makeView(current, weatherLocation, appWidgetId);
this.updateWidget(view, appWidgetId);
} else {
// Show error.
final RemoteViews view = this.makeErrorView(appWidgetId);
this.updateWidget(view, appWidgetId);
}
}
private Current getRemoteCurrent(final WeatherLocation weatherLocation) {
final ServiceParser weatherService = new ServiceParser(new JPOSWeatherParser());
final CustomHTTPClient HTTPClient = new CustomHTTPClient(
AndroidHttpClient.newInstance("Android 4.3 WeatherInformation Agent"));
try {
return this.getRemoteCurrentThrowable(weatherLocation, HTTPClient, weatherService);
} catch (final JsonParseException e) {
Log.e(TAG, "doInBackground exception: ", e);
} catch (final ClientProtocolException e) {
Log.e(TAG, "doInBackground exception: ", e);
} catch (final MalformedURLException e) {
Log.e(TAG, "doInBackground exception: ", e);
} catch (final URISyntaxException e) {
Log.e(TAG, "doInBackground exception: ", e);
} catch (final IOException e) {
// logger infrastructure swallows UnknownHostException :/
Log.e(TAG, "doInBackground exception: " + e.getMessage(), e);
} finally {
HTTPClient.close();
}
return null;
}
private Current getRemoteCurrentThrowable(final WeatherLocation weatherLocation,
final CustomHTTPClient HTTPClient, final ServiceParser weatherService)
throws ClientProtocolException, MalformedURLException, URISyntaxException,
JsonParseException, IOException {
final String APIVersion = this.getResources().getString(R.string.api_version);
final String urlAPI = this.getResources().getString(R.string.uri_api_weather_today);
final String url = weatherService.createURIAPICurrent(urlAPI, APIVersion,
weatherLocation.getLatitude(), weatherLocation.getLongitude());
final String urlWithoutCache = url.concat("&time=" + System.currentTimeMillis());
final String jsonData = HTTPClient.retrieveDataAsString(new URL(urlWithoutCache));
final Current current = weatherService.retrieveCurrentFromJPOS(jsonData);
// TODO: what is this for? I guess I could skip it :/
final Calendar now = Calendar.getInstance();
current.setDate(now.getTime());
return current;
}
private interface UnitsConversor {
public double doConversion(final double value);
}
private RemoteViews makeView(final Current current, final WeatherLocation weatherLocation, final int appWidgetId) {
final SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
// TODO: repeating the same code in Overview, Specific and Current!!!
// 1. Update units of measurement.
// 1.1 Temperature
String tempSymbol;
UnitsConversor tempUnitsConversor;
String keyPreference = this.getResources().getString(R.string.weather_preferences_temperature_key);
String unitsPreferenceValue = sharedPreferences.getString(keyPreference, "");
String[] values = this.getResources().getStringArray(R.array.weather_preferences_temperature);
if (unitsPreferenceValue.equals(values[0])) {
tempSymbol = values[0];
tempUnitsConversor = new UnitsConversor(){
@Override
public double doConversion(final double value) {
return value - 273.15;
}
};
} else if (unitsPreferenceValue.equals(values[1])) {
tempSymbol = values[1];
tempUnitsConversor = new UnitsConversor(){
@Override
public double doConversion(final double value) {
return (value * 1.8) - 459.67;
}
};
} else {
tempSymbol = values[2];
tempUnitsConversor = new UnitsConversor(){
@Override
public double doConversion(final double value) {
return value;
}
};
}
// 2. Formatters
final DecimalFormat tempFormatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
tempFormatter.applyPattern("#####.#####");
// 3. Prepare data for RemoteViews.
String tempMax = "";
if (current.getMain().getTemp_max() != null) {
double conversion = (Double) current.getMain().getTemp_max();
conversion = tempUnitsConversor.doConversion(conversion);
tempMax = tempFormatter.format(conversion) + tempSymbol;
}
String tempMin = "";
if (current.getMain().getTemp_min() != null) {
double conversion = (Double) current.getMain().getTemp_min();
conversion = tempUnitsConversor.doConversion(conversion);
tempMin = tempFormatter.format(conversion) + tempSymbol;
}
Bitmap picture;
if ((current.getWeather().size() > 0)
&& (current.getWeather().get(0).getIcon() != null)
&& (IconsList.getIcon(current.getWeather().get(0).getIcon()) != null)) {
final String icon = current.getWeather().get(0).getIcon();
picture = BitmapFactory.decodeResource(this.getResources(), IconsList.getIcon(icon)
.getResourceDrawable());
} else {
picture = BitmapFactory.decodeResource(this.getResources(),
R.drawable.weather_severe_alert);
}
final String city = weatherLocation.getCity();
final String country = weatherLocation.getCountry();
// 4. Insert data in RemoteViews.
final RemoteViews remoteView = new RemoteViews(this.getApplicationContext().getPackageName(), R.layout.appwidget);
remoteView.setImageViewBitmap(R.id.weather_appwidget_image, picture);
remoteView.setTextViewText(R.id.weather_appwidget_temperature_max, tempMax);
remoteView.setTextViewText(R.id.weather_appwidget_temperature_min, tempMin);
remoteView.setTextViewText(R.id.weather_appwidget_city, city);
remoteView.setTextViewText(R.id.weather_appwidget_country, country);
// 5. Activity launcher.
final Intent resultIntent = new Intent(this.getApplicationContext(), WidgetConfigure.class);
resultIntent.putExtra("actionFromUser", true);
resultIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
// resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK );
// From: http://stackoverflow.com/questions/4011178/multiple-instances-of-widget-only-updating-last-widget
final Uri data = Uri.withAppendedPath(Uri.parse("PAIN" + "://widget/id/") ,String.valueOf(appWidgetId));
resultIntent.setData(data);
final TaskStackBuilder stackBuilder = TaskStackBuilder.create(this.getApplicationContext());
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(WidgetConfigure.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
final PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
remoteView.setOnClickPendingIntent(R.id.weather_appwidget, resultPendingIntent);
// final PendingIntent resultPendingIntent = PendingIntent.getActivity(
// this.getApplicationContext(),
// 0,
// resultIntent,
// PendingIntent.FLAG_UPDATE_CURRENT);
// remoteView.setOnClickPendingIntent(R.id.weather_appwidget, resultPendingIntent);
return remoteView;
}
private RemoteViews makeErrorView(final int appWidgetId) {
final RemoteViews remoteView = new RemoteViews(this.getApplicationContext().getPackageName(), R.layout.appwidget_error);
// 5. Activity launcher.
final Intent resultIntent = new Intent(this.getApplicationContext(), WidgetConfigure.class);
resultIntent.putExtra("actionFromUser", true);
resultIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
// resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK );
// From: http://stackoverflow.com/questions/4011178/multiple-instances-of-widget-only-updating-last-widget
final Uri data = Uri.withAppendedPath(Uri.parse("PAIN" + "://widget/id/") ,String.valueOf(appWidgetId));
resultIntent.setData(data);
final TaskStackBuilder stackBuilder = TaskStackBuilder.create(this.getApplicationContext());
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(WidgetConfigure.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
final PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
// final PendingIntent resultPendingIntent = PendingIntent.getActivity(
// this.getApplicationContext(),
// 0,
// resultIntent,
// PendingIntent.FLAG_UPDATE_CURRENT);
// remoteView.setOnClickPendingIntent(R.id.weather_appwidget_error, resultPendingIntent);
return remoteView;
}
private void updateWidget(final RemoteViews remoteView, final int appWidgetId) {
final AppWidgetManager manager = AppWidgetManager.getInstance(this.getApplicationContext());
manager.updateAppWidget(appWidgetId, remoteView);
}
// private void updateWidgets(final RemoteViews remoteView) {
//
// final ComponentName widgets = new ComponentName(this.getApplicationContext(), WidgetProvider.class);
// final AppWidgetManager manager = AppWidgetManager.getInstance(this.getApplicationContext());
// manager.updateAppWidget(widgets, remoteView);
// }
}
| WeatherInformation: no time for comments
| app/src/main/java/de/example/exampletdd/WidgetIntentService.java | WeatherInformation: no time for comments | <ide><path>pp/src/main/java/de/example/exampletdd/WidgetIntentService.java
<ide> 0,
<ide> PendingIntent.FLAG_UPDATE_CURRENT
<ide> );
<add> remoteView.setOnClickPendingIntent(R.id.weather_appwidget_error, resultPendingIntent);
<ide> // final PendingIntent resultPendingIntent = PendingIntent.getActivity(
<ide> // this.getApplicationContext(),
<ide> // 0, |
|
JavaScript | bsd-3-clause | ed1cf6b19405d32ce12f5a2765832e20579446d8 | 0 | Mermade/bbcparse | /*
List programmes by aggregation (category, format, or search)
*/
'use strict';
var fs = require('fs');
var util = require('util');
var url = require('url');
var getopt = require('node-getopt');
var j2x = require('jgexml/json2xml');
var giUtils = require('./giUtils');
var nitro = require('./nitroSdk');
var api = require('./nitroApi/api');
const colours = process.stdout.isTTY;
if (process.env.NODE_DISABLE_COLORS) colours = false;
var red = colours ? '\x1b[31m' : '';
var green = colours ? '\x1b[32m' : '';
var normal = colours ? '\x1b[0m' : '';
var programme_cache = [];
var download_history = [];
var showAll = false;
var dumpMediaSets = false;
var upcoming = false;
var pidList = [];
var indexBase = 10000;
var channel = '';
var partner_pid = '';
var sid = '';
var search = '';
var children = false;
var embargoed = '';
var tag = '';
// bbc seem to use int(ernal),test,stage and live
// http://programmes.api.bbc.com
// http://nitro.api.bbci.co.uk - deprecated since 24/12/2015
// http://nitro.stage.api.bbci.co.uk/nitro/api/
// http://d.bbc.co.uk/nitro/api/ - deprecated since 24/12/2015
// http://d.bbc.co.uk/stage/nitro/api/
// http://data.bbc.co.uk/nitro/api/ - deprecated since 24/12/2015
// https://api.live.bbc.co.uk/nitro/api/
// https://api.test.bbc.co.uk/nitro/api/
// http://nitro-e2e.api.bbci.co.uk/nitro-e2e/api/ - locked down?
// http://nitro-slave-1.cloud.bbc.co.uk/nitro/api
var host = 'programmes.api.bbc.com';
var domain = '/nitro/api';
var feed = '/programmes';
var mediaSet = 'pc';
var payment_type = 'free';
var api_key = '';
var service = 'radio';
var media_type = 'audio';
const pageSize = 30;
var debuglog = util.debuglog('bbc');
//----------------------------------------------------------------------------
var add_programme = function(obj,parent) {
var seen = false;
for (var i in programme_cache) {
var check = programme_cache[i];
if (check.pid == obj.pid) {
seen = true;
if (check.x_parent && !check.x_parent.pid && parent) check.x_parent = parent;
break;
}
}
if (!seen) {
if (parent) {
obj.x_parent = parent;
}
programme_cache.push(obj);
}
};
//-----------------------------------------------------------------------------
function pad(str, padding, padRight) {
if (typeof str === 'undefined')
return padding;
if (padRight) {
return (str + padding).substring(0, padding.length);
} else {
return (padding + str).slice(-padding.length);
}
}
//-----------------------------------------------------------------------------
function toArray(obj) {
if (Array.isArray(obj)) return obj;
var a = [];
a.push(obj);
return a;
}
//-----------------------------------------------------------------------------
function pc_export() {
var hidden = 0;
console.log('\n* Programme Cache:');
var index = indexBase;
for (var i in programme_cache) {
index++;
var p = programme_cache[i];
var present = giUtils.binarySearch(download_history,p.pid)>=0;
var title = p.title;
var subtitle = (p.display_titles && p.display_titles.subtitle ? p.display_titles.subtitle : p.presentation_title);
var available = ((p.available_versions) && (p.available_versions.available > 0));
var position = p.episode_of ? p.episode_of.position : 1;
var totaleps = 1;
var series = 1;
var len = (p.version && p.version.duration) ? nitro.iso8601durationToSeconds(p.version.duration) : '0';
var thumb = p.image.template_url.replace('$recipe','150x84');
//#index|type|name|pid|available|episode|seriesnum|episodenum|versions|duration|desc|channel|categories|thumbnail|timeadded|guidance|web
if (i==programme_cache.length-1) {
debuglog(JSON.stringify(p,null,2));
}
console.log(index+'|'+(p.media_type == 'Video' ? 'tv' : 'radio')+'|'+title+'|'+p.pid+'|'+
(available ? 'Available' : 'Unavailable')+'|'+subtitle+'|'+'|'+series+'|'+position+'|'+'default'+'|'+
len+'||'+(p.master_brand ? p.master_brand.mid : 'unknown')+'|'+category[0]+'|'+thumb+'|'+Math.floor(Date.now()/1000)+
'||'+'http://bbc.co.uk/programmes/'+p.pid+'|');
}
}
//-----------------------------------------------------------------------------
function pc_dump() {
var hidden = 0;
console.log('\n* Programme Cache:');
for (var i in programme_cache) {
var p = programme_cache[i];
var present = giUtils.binarySearch(download_history,p.pid)>=0;
var title = (p.title ? p.title : p.presentation_title);
var parents = '';
var ancestor_titles = '';
for (var at in p.ancestor_titles) {
present = present || (download_history.indexOf(p.ancestor_titles[at].pid)>=0);
var t = '';
if (p.ancestor_titles[at].title) {
t = p.ancestor_titles[at].title;
}
else if (p.ancestor_titles[at].presentation_title) {
t = p.ancestor_titles[at].presentation_title;
}
if (p.ancestor_titles[at].ancestor_type != 'episode') {
ancestor_titles += t + ' : ';
}
else if (!title) {
title = t;
}
parents += ' ' + p.ancestor_titles[at].pid + ' ('+t+') ';
}
title = ancestor_titles + title;
if (p.version && p.version.pid) {
parents += ' ' + p.version.pid + ' (vPID)';
}
var available = ((p.available_versions) && (p.available_versions.available > 0));
if ((!present && available) || (pidList.indexOf(p.pid)>=0) || showAll) {
if (programme_cache.length==1) {
debuglog(JSON.stringify(p,null,2));
}
var position = p.episode_of ? p.episode_of.position : 1;
var totaleps = p.x_parent && p.x_parent.expected_child_count ? p.x_parent.expected_child_count : 1;
var series = 1;
console.log(p.pid+' '+pad(p.item_type,' ',true)+' '+
(p.media_type ? p.media_type : 'Audio')+' '+(available ? 'Available' : 'Unavailable')+' '+green+title+normal);
var len = (p.version && p.version.duration) ? p.version.duration : '0s';
if (p.available_versions) {
for (var v in p.available_versions.version) {
var version = p.available_versions.version[v];
if (len == '0s') {
len = version.duration;
}
parents += ' ' + version.pid + ' (vPID '+version.types.type[0]+')';
for (var va in p.available_versions.version[v].availabilities) {
var a = p.available_versions.version[v].availabilities[va];
// dump mediasets
if (dumpMediaSets) {
for (var vaa in a) {
var vaaa = a[vaa];
for (var ms in vaaa.media_sets.media_set) {
console.log(p.available_versions.version[v].pid+' '+vaaa.status+' '+vaaa.media_sets.media_set[ms].name);
}
}
}
}
}
}
if (!len) len = '';
len = len.replace('PT','').toLocaleLowerCase(); // ISO 8601 duration
console.log(' '+len+' S'+pad(series,'00')+'E'+pad(position,'00')+
'/'+pad(totaleps,'00')+' '+(p.synopses && p.synopses.short ? p.synopses.short : 'No description'));
if (parents) console.log(parents);
if (p.master_brand) {
console.log(' '+p.master_brand.mid+' @ '+(p.release_date ? p.release_date :
(p.release_year ? p.release_year : p.updated_time)));
}
if (p.contributions) {
console.log();
var contribution = toArray(p.contributions.contribution);
for (var cont of contribution) {
console.log((cont.character_name ? cont.character_name : (cont.credit_role ? cont.credit_role.$ : 'Unknown'))+' - '+
(cont.contributor && cont.contributor.name ? (cont.contributor.name.given ? cont.contributor.name.given+' '+cont.contributor.name.family :
cont.contributor.name.presentation) : 'Unknown'));
}
}
//if (p.x_parent) {
// console.log(JSON.stringify(p.x_parent,null,2));
//}
}
else {
hidden++;
}
}
if (programme_cache.length == 1) {
var item = programme_cache[0];
if (item.synopses && (item.synopses.long || item.synopses.medium)) {
console.log();
console.log(item.synopses.long ? item.synopses.long : item.synopses.medium);
}
}
console.log();
console.log('Cache has '+programme_cache.length+' entries, '+hidden+' hidden');
}
//_____________________________________________________________________________
var processResponse = function(obj,payload) {
var nextHref = '';
if ((obj.nitro.pagination) && (obj.nitro.pagination.next)) {
nextHref = obj.nitro.pagination.next.href;
//console.log(nextHref);
}
var pageNo = obj.nitro.results.page;
var top = obj.nitro.results.total;
if (!top) {
top = obj.nitro.results.more_than+1;
}
var last = Math.ceil(top/obj.nitro.results.page_size);
process.stdout.write('.');
var length = 0;
if (obj.nitro.results.items) {
length = obj.nitro.results.items.length;
}
if (length==0) {
//console.log('No results returned');
}
else {
for (var i in obj.nitro.results.items) {
var p = obj.nitro.results.items[i];
//debuglog(JSON.stringify(p,null,2));
if ((p.item_type == 'episode') || (p.item_type == 'clip') || (p.item_type == episode_type)) {
add_programme(p,payload);
}
else if ((p.item_type == 'series') || (p.item_type == 'brand')) {
var path = domain+feed;
var query = nitro.newQuery(api.fProgrammesDescendantsOf,p.pid,true)
.add(api.fProgrammesAvailabilityAvailable)
.add(api.fProgrammesAvailabilityEntityTypeEpisode)
.add(api.fProgrammesAvailabilityTypeOndemand)
.add(api.fProgrammesPaymentType,payment_type)
.add(api.fProgrammesMediaSet,mediaSet)
.add(api.mProgrammesDuration)
.add(api.mProgrammesAncestorTitles)
.add(api.mProgrammesAvailability)
.add(api.mProgrammesAvailableVersions)
.add(api.fProgrammesEntityTypeEpisode)
.add(api.fProgrammesPageSize,pageSize);
if (media_type) {
query.add(api.fProgrammesMediaType,media_type);
}
process.stdout.write('>');
var settings = {};
settings.payload = p;
nitro.make_request(host,path,api_key,query,settings,processResponse);
}
else {
console.log('Unhandled type: '+p.type);
console.log(p);
}
}
}
var dest = {};
if (pageNo<last) {
dest.path = domain+feed;
dest.query = nitro.queryFrom(nextHref,true); // TODO
dest.callback = processResponse;
}
// if we need to go somewhere else, e.g. after all pages received set callback and/or path
nitro.setReturn(dest);
return true;
}
//_____________________________________________________________________________
function dispatch(obj,payload) {
if (obj.nitro) {
processResponse(obj,payload);
}
else if (obj.fault) {
nitro.logFault(obj);
}
else if (obj.errors) {
nitro.logError(obj);
}
else {
console.log(obj);
}
return {};
}
//_____________________________________________________________________________
function processPid(host,path,api_key,pid) {
var query = nitro.newQuery();
query.add(api.fProgrammesPageSize,pageSize,true)
.add(api.mProgrammesContributions)
.add(api.mProgrammesDuration)
.add(api.mProgrammesAncestorTitles)
.add(api.mProgrammesAvailableVersions)
.add(api.mProgrammesGenreGroupings)
if (upcoming || children) {
query.add(api.fProgrammesDescendantsOf,pid)
.add(api.fProgrammesAvailabilityPending);
}
else {
query.add(api.fProgrammesPid,pid)
}
if (partner_pid != '') {
query.add(api.fProgrammesPartnerPid,partner_pid);
}
else {
if (pending) {
query.add(api.fProgrammesAvailability,'P30D');
}
else {
query.add(api.fProgrammesAvailabilityAvailable);
}
query.add(api.mProgrammesAvailability); // has a dependency on 'availability'
}
if (episode_type == 'clip') {
query.add(api.fProgrammesAvailabilityEntityTypeClip);
}
else if ((episode_type == 'brand') || (episode_type == 'series')) {
query.add(api.fProgrammesEntityType,episode_type);
}
else {
query.add(api.fProgrammesAvailabilityEntityTypeEpisode);
}
if (embargoed) {
query.add(api.xProgrammesEmbargoed,embargoed);
}
if (payment_type) {
query.add(api.fProgrammesPaymentType,payment_type);
}
nitro.make_request(host,path,api_key,query,{},function(obj){
return dispatch(obj);
});
}
//_____________________________________________________________________________
function processVpid(host,path,api_key,vpid) {
var query = nitro.newQuery();
query.add(api.fVersionsPid,vpid,true);
if (partner_pid != '') {
query.add(api.fVersionsPartnerPid,partner_pid);
}
else {
if (pending) {
query.add(api.fVersionsAvailability,'P30D');
}
else {
query.add(api.fVersionsAvailabilityAvailable);
}
}
if (embargoed) {
query.add(api.xProgrammesEmbargoed,embargoed);
}
nitro.make_request(host,api.nitroVersions,api_key,query,{},function(obj){
for (var i in obj.nitro.results.items) {
var item = obj.nitro.results.items[i];
var pid = item.version_of.pid;
processPid(host,path,api_key,pid)
}
});
}
//_____________________________________________________________________________
var scheduleResponse = function(obj) {
var nextHref = '';
if ((obj.nitro.pagination) && (obj.nitro.pagination.next)) {
nextHref = obj.nitro.pagination.next.href;
//console.log(nextHref);
}
var pageNo = obj.nitro.results.page;
var top = obj.nitro.results.total;
if (!top) {
top = obj.nitro.results.more_than+1;
}
var last = Math.ceil(top/obj.nitro.results.page_size);
//console.log('page '+pageNo+' of '+last);
process.stdout.write('.');
var length = 0;
if (obj.nitro.results.items) {
length = obj.nitro.results.items.length;
}
if (length==0) {
console.log('No results returned');
}
else {
for (var i in obj.nitro.results.items) {
var item = obj.nitro.results.items[i];
debuglog(item);
// minimally convert a broadcast into a programme for display
var p = {};
p.ancestor_titles = item.ancestor_titles;
p.available_versions = {};
p.available_versions.available = 1;
p.version = {};
p.version.duration = (item.published_time ? item.published_time.duration : '');
p.synopses = {};
p.media_type = (item.service.sid.indexOf('radio')>=0 ? 'Audio' : 'Video');
p.image = item.image;
p.master_brand = {};
p.master_brand.mid = item.service.sid; //!
p.release_date = item.published_time.start;
for (var b in item.broadcast_of) {
var bof = item.broadcast_of[b];
if ((bof.result_type == 'episode') || (bof.result_type == 'clip')) {
p.item_type = bof.result_type;
p.pid = bof.pid;
}
else if (bof.result_type == 'version') {
p.version.pid = bof.pid;
}
}
for (var a in item.ancestor_titles) {
var at = item.ancestor_titles[a];
if ((at.ancestor_type == 'episode') || (at.ancestor_type == 'clip')) {
p.title = at.title;
}
}
// item.ids.id is an array of submissions(?) to broadcast schedule services
var present = false;
for (var pc in programme_cache) {
var pci = programme_cache[pc];
if (pci.pid == p.pid) present = true;
}
if (!present) programme_cache.push(p);
}
}
var dest = {};
if (pageNo<last) {
dest.path = '/nitro/api/schedules';
dest.query = nitro.queryFrom(nextHref,true); // TODO
dest.callback = scheduleResponse;
}
// if we need to go somewhere else, e.g. after all pages received set callback and/or path
nitro.setReturn(dest);
return true;
}
//_____________________________________________________________________________
function processSchedule(host,api_key,category,format,mode,pid) {
var path = '/nitro/api/schedules';
var today = new Date();
var todayStr = today.toISOString();
var query = nitro.newQuery();
query.add(api.fSchedulesStartFrom,todayStr,true);
if (mode == 'genre') {
for (var c in category) {
query.add(api.fSchedulesGenre,category[c]);
}
}
for (var f in format) {
query.add(api.fSchedulesFormat,format[f]);
}
if (search != '') {
query.add(api.fSchedulesQ,search);
}
if (mode == 'pid') {
query.add(api.fSchedulesDescendantsOf,pid);
}
if (channel != '') {
query.add(api.fSchedulesServiceMasterBrand,channel);
}
if (partner_pid) {
query.add(api.fSchedulesPartnerPid,partner_pid);
}
if (sid) {
query.add(api.fSchedulesSid,sid);
}
query.add(api.mSchedulesAncestorTitles)
.add(api.fSchedulesPageSize,pageSize);
nitro.make_request(host,path,api_key,query,{},function(obj){
var result = scheduleResponse(obj);
var dest = nitro.getReturn();
if (dest.callback) {
// call the callback's next required destination
// e.g. second and subsequent pages
if (dest.path) {
nitro.make_request(host,dest.path,api_key,dest.query,{},dest.callback);
}
else {
dest.callback();
}
}
});
}
//------------------------------------------------------------------------[main]
// https://developer.bbc.co.uk/nitropubliclicence
// https://admin.live.bbc.co.uk/nitro/admin/servicestatus
// https://api.live.bbc.co.uk/nitro/api/schema
// https://confluence.dev.bbc.co.uk/display/nitro/Nitro+run+book
// http://www.bbc.co.uk/academy/technology/article/art20141013145843465
var defcat = 'all';
try {
var config = require('./config.json');
host = config.nitro.host;
api_key = config.nitro.api_key;
mediaSet = config.nitro.mediaset;
defcat = config.nitro.category;
}
catch (e) {
console.log('Please rename config.json.example to config.json and edit for your setup');
process.exit(2);
}
var category = [];
var format = [];
var query = nitro.newQuery();
var pid = '';
var mode = '';
var pending = false;
var episode_type = '';
var duration = '';
var path = domain+feed;
var options = getopt.create([
['h','help','display this help'],
['b','index_base','get_iplayer index base, defaults to 10000'],
['c','channel=ARG','Filter by channel (masterbrand) id'],
['d','domain=ARG','Set domain = radio,tv or both'],
['f','format=ARG+','Filter by format id'],
['g','genre=ARG+','Filter by genre id. all to reset'],
['l','linear=ARG','Set linear service id, works with -u only'],
['r','run=ARG','run-length, short,medium or long'],
['s','search=ARG','Search metadata. Can use title: or synopsis: prefix'],
['w','with=ARG','Filter with tag'],
['p','pid=ARG+','Query by individual pid(s), ignores options above'],
['v','version=ARG+','Query by individual version pid(s), ignores options above'],
['a','all','Show programme regardless of presence in download_history'],
['e','episode=ARG','Set programme type to episode*,clip,brand or series'],
['i','imminent','Set availability to future (default is available)'],
['k','children','Include children of given pid'],
['m','mediaset','Dump mediaset information, most useful with -p'],
['o','output','output in get_iplayer cache format'],
['t','payment_type=ARG','Set payment_type to free*,bbcstore,uscansvod'],
['u','upcoming','Show programme schedule information not history'],
['x','partner_pid=ARG','Set partner pid, defaults to s0000001'],
['z','embargoed=ARG','Set embargoed to include, exclude* or only']
]);
var o = options.bindHelp();
query.add(api.fProgrammesMediaSet,mediaSet,true);
options.on('all',function(){
showAll = true;
});
options.on('imminent',function(){
pending = true;
});
options.on('children',function(){
children = true;
});
options.on('domain',function(argv,options){
service = options.domain;
if (service == 'tv') {
media_type = 'audio_video';
}
else if (service == 'both') {
media_type = '';
}
});
options.on('version',function(argv,options){
mode = 'version';
});
options.on('upcoming',function(){
feed = 'schedules';
upcoming = true;
});
options.on('channel',function(argv,options){
channel = options.channel;
query.add(api.fProgrammesMasterBrand,channel).add(api.sProgrammesTitleAscending);
});
options.on('search',function(argv,options){
search = options.search;
query.add(api.fProgrammesQ,search).add(api.sProgrammesTitleAscending);
});
options.on('format',function(argv,options){
format = options.format;
for (var f in format) {
query.add(api.fProgrammesFormat,format[f]);
}
});
options.on('genre',function(argv,options){
mode = 'genre';
for (var g in options.genre) {
var genre = options.genre[g];
if (genre == 'all') {
category = [];
}
else {
category.push(genre);
query.add(api.fProgrammesGenre,genre);
}
}
});
options.on('mediaset',function(){
dumpMediaSets = true;
});
options.on('payment_type',function(argv,options){
payment_type = options.payment_type;
});
options.on('pid',function(argv,options){
mode = 'pid';
});
options.on('partner_pid',function(argv,options){
partner_pid = options.partner_pid;
});
options.on('linear',function(argv,options){
sid = options.linear;
});
options.on('embargoed',function(argv,options){
embargoed = options.embargoed;
});
options.on('with',function(argv,options){
tag = options.with;
});
options.on('episode',function(argv,options){
episode_type = options.episode;
if ((episode_type == 'brand') || (episode_type == 'series')) {
showAll = true;
}
});
options.on('run',function(argv,options){
duration = options.run;
});
var o = options.parseSystem();
if (!showAll && config.download_history) {
download_history = giUtils.downloadHistory(config.download_history);
}
if (partner_pid) {
query.add(api.fProgrammesPartnerPid,partner_pid)
.add(api.mProgrammesAvailability)
.add(api.mProgrammesAvailableVersions)
.add(api.fProgrammesAvailabilityAvailable);
}
else {
if (pending) {
query.add(api.fProgrammesAvailability,'P30D');
}
else {
query.add(api.fProgrammesAvailabilityAvailable);
}
query.add(api.mProgrammesAvailability)
.add(api.mProgrammesAvailableVersions)
.add(api.fProgrammesPaymentType,payment_type)
.add(api.fProgrammesAvailabilityTypeOndemand);
}
if (episode_type == 'clip') {
query.add(api.fProgrammesAvailabilityEntityTypeClip);
}
else if ((episode_type == 'brand') || (episode_type == 'series')) {
query.add(api.fProgrammesEntityType,episode_type);
}
else {
query.add(api.fProgrammesAvailabilityEntityTypeEpisode);
}
if (media_type) {
query.add(api.fProgrammesMediaType,media_type);
}
if (duration) {
query.add(api.fProgrammesDuration,duration);
}
if (embargoed) {
query.add(api.xProgrammesEmbargoed,embargoed);
}
if (tag) {
query.add(api.fProgrammesTagName,tag);
}
query.add(api.mProgrammesDuration)
.add(api.mProgrammesAncestorTitles)
.add(api.fProgrammesPageSize,pageSize);
if (mode=='') {
mode = 'genre';
category.push(defcat);
query.add(api.fProgrammesGenre,defcat);
}
if (mode == 'version') {
for (var p in o.options.version) {
pid = o.options.version[p];
if (pid.indexOf('@')==0) {
pid = pid.substr(1);
var s = fs.readFileSync(pid,'utf8');
pidList = pidList.concat(s.split('\n'));
}
else {
pidList.push(pid);
}
}
for (var p in pidList) {
processVpid(host,path,api_key,pidList[p]);
}
}
else if (mode == 'pid') {
for (var p in o.options.pid) {
pid = o.options.pid[p];
if (pid.indexOf('@')==0) {
pid = pid.substr(1);
var s = fs.readFileSync(pid,'utf8');
pidList = pidList.concat(s.split('\n'));
}
else {
pidList.push(pid);
}
}
for (var p in pidList) {
if (upcoming) {
processSchedule(host,api_key,category,format,mode,pidList[p]);
}
else {
processPid(host,path,api_key,pidList[p]);
}
}
}
else if (feed == 'schedules') {
processSchedule(host,api_key,category,format,mode);
}
else {
if (mode=='genre') {
// parallelize the queries by 36 times
var letters = '0123456789abcdefghijklmnopqrstuvwxyz';
for (var l in letters) {
if (letters.hasOwnProperty(l)) {
var lQuery = query.clone();
lQuery.add(api.fProgrammesInitialLetter,letters[l]);
nitro.make_request(host,path,api_key,lQuery,{},function(obj,payload){
return dispatch(obj,payload);
});
}
}
}
}
process.on('exit', function(code) {
if (o.options.output) {
pc_export();
}
else {
pc_dump();
if (nitro.getRateLimitEvents()>0) {
console.log('Got '+nitro.getRateLimitEvents()+' rate-limit events');
}
}
});
| nitro.js | /*
List programmes by aggregation (category, format, or search)
*/
'use strict';
var fs = require('fs');
var util = require('util');
var url = require('url');
var getopt = require('node-getopt');
var j2x = require('jgexml/json2xml');
var giUtils = require('./giUtils');
var nitro = require('./nitroSdk');
var api = require('./nitroApi/api');
var red = process.env.NODE_DISABLE_COLORS ? '' : '\x1b[31m';
var green = process.env.NODE_DISABLE_COLORS ? '' : '\x1b[32m';
var normal = process.env.NODE_DISABLE_COLORS ? '' : '\x1b[0m';
var programme_cache = [];
var download_history = [];
var showAll = false;
var dumpMediaSets = false;
var upcoming = false;
var pidList = [];
var indexBase = 10000;
var channel = '';
var partner_pid = '';
var sid = '';
var search = '';
var children = false;
var embargoed = '';
var tag = '';
// bbc seem to use int(ernal),test,stage and live
// http://programmes.api.bbc.com
// http://nitro.api.bbci.co.uk - deprecated since 24/12/2015
// http://nitro.stage.api.bbci.co.uk/nitro/api/
// http://d.bbc.co.uk/nitro/api/ - deprecated since 24/12/2015
// http://d.bbc.co.uk/stage/nitro/api/
// http://data.bbc.co.uk/nitro/api/ - deprecated since 24/12/2015
// https://api.live.bbc.co.uk/nitro/api/
// https://api.test.bbc.co.uk/nitro/api/
// http://nitro-e2e.api.bbci.co.uk/nitro-e2e/api/ - locked down?
// http://nitro-slave-1.cloud.bbc.co.uk/nitro/api
var host = 'programmes.api.bbc.com';
var domain = '/nitro/api';
var feed = '/programmes';
var mediaSet = 'pc';
var payment_type = 'free';
var api_key = '';
var service = 'radio';
var media_type = 'audio';
const pageSize = 30;
var debuglog = util.debuglog('bbc');
//----------------------------------------------------------------------------
var add_programme = function(obj,parent) {
var seen = false;
for (var i in programme_cache) {
var check = programme_cache[i];
if (check.pid == obj.pid) {
seen = true;
if (check.x_parent && !check.x_parent.pid && parent) check.x_parent = parent;
break;
}
}
if (!seen) {
if (parent) {
obj.x_parent = parent;
}
programme_cache.push(obj);
}
};
//-----------------------------------------------------------------------------
function pad(str, padding, padRight) {
if (typeof str === 'undefined')
return padding;
if (padRight) {
return (str + padding).substring(0, padding.length);
} else {
return (padding + str).slice(-padding.length);
}
}
//-----------------------------------------------------------------------------
function toArray(obj) {
if (Array.isArray(obj)) return obj;
var a = [];
a.push(obj);
return a;
}
//-----------------------------------------------------------------------------
function pc_export() {
var hidden = 0;
console.log('\n* Programme Cache:');
var index = indexBase;
for (var i in programme_cache) {
index++;
var p = programme_cache[i];
var present = giUtils.binarySearch(download_history,p.pid)>=0;
var title = p.title;
var subtitle = (p.display_titles && p.display_titles.subtitle ? p.display_titles.subtitle : p.presentation_title);
var available = ((p.available_versions) && (p.available_versions.available > 0));
var position = p.episode_of ? p.episode_of.position : 1;
var totaleps = 1;
var series = 1;
var len = (p.version && p.version.duration) ? nitro.iso8601durationToSeconds(p.version.duration) : '0';
var thumb = p.image.template_url.replace('$recipe','150x84');
//#index|type|name|pid|available|episode|seriesnum|episodenum|versions|duration|desc|channel|categories|thumbnail|timeadded|guidance|web
if (i==programme_cache.length-1) {
debuglog(JSON.stringify(p,null,2));
}
console.log(index+'|'+(p.media_type == 'Video' ? 'tv' : 'radio')+'|'+title+'|'+p.pid+'|'+
(available ? 'Available' : 'Unavailable')+'|'+subtitle+'|'+'|'+series+'|'+position+'|'+'default'+'|'+
len+'||'+(p.master_brand ? p.master_brand.mid : 'unknown')+'|'+category[0]+'|'+thumb+'|'+Math.floor(Date.now()/1000)+
'||'+'http://bbc.co.uk/programmes/'+p.pid+'|');
}
}
//-----------------------------------------------------------------------------
function pc_dump() {
var hidden = 0;
console.log('\n* Programme Cache:');
for (var i in programme_cache) {
var p = programme_cache[i];
var present = giUtils.binarySearch(download_history,p.pid)>=0;
var title = (p.title ? p.title : p.presentation_title);
var parents = '';
var ancestor_titles = '';
for (var at in p.ancestor_titles) {
present = present || (download_history.indexOf(p.ancestor_titles[at].pid)>=0);
var t = '';
if (p.ancestor_titles[at].title) {
t = p.ancestor_titles[at].title;
}
else if (p.ancestor_titles[at].presentation_title) {
t = p.ancestor_titles[at].presentation_title;
}
if (p.ancestor_titles[at].ancestor_type != 'episode') {
ancestor_titles += t + ' : ';
}
else if (!title) {
title = t;
}
parents += ' ' + p.ancestor_titles[at].pid + ' ('+t+') ';
}
title = ancestor_titles + title;
if (p.version && p.version.pid) {
parents += ' ' + p.version.pid + ' (vPID)';
}
var available = ((p.available_versions) && (p.available_versions.available > 0));
if ((!present && available) || (pidList.indexOf(p.pid)>=0) || showAll) {
if (programme_cache.length==1) {
debuglog(JSON.stringify(p,null,2));
}
var position = p.episode_of ? p.episode_of.position : 1;
var totaleps = p.x_parent && p.x_parent.expected_child_count ? p.x_parent.expected_child_count : 1;
var series = 1;
console.log(p.pid+' '+pad(p.item_type,' ',true)+' '+
(p.media_type ? p.media_type : 'Audio')+' '+(available ? 'Available' : 'Unavailable')+' '+green+title+normal);
var len = (p.version && p.version.duration) ? p.version.duration : '0s';
if (p.available_versions) {
for (var v in p.available_versions.version) {
var version = p.available_versions.version[v];
if (len == '0s') {
len = version.duration;
}
parents += ' ' + version.pid + ' (vPID '+version.types.type[0]+')';
for (var va in p.available_versions.version[v].availabilities) {
var a = p.available_versions.version[v].availabilities[va];
// dump mediasets
if (dumpMediaSets) {
for (var vaa in a) {
var vaaa = a[vaa];
for (var ms in vaaa.media_sets.media_set) {
console.log(p.available_versions.version[v].pid+' '+vaaa.status+' '+vaaa.media_sets.media_set[ms].name);
}
}
}
}
}
}
if (!len) len = '';
len = len.replace('PT','').toLocaleLowerCase(); // ISO 8601 duration
console.log(' '+len+' S'+pad(series,'00')+'E'+pad(position,'00')+
'/'+pad(totaleps,'00')+' '+(p.synopses && p.synopses.short ? p.synopses.short : 'No description'));
if (parents) console.log(parents);
if (p.master_brand) {
console.log(' '+p.master_brand.mid+' @ '+(p.release_date ? p.release_date :
(p.release_year ? p.release_year : p.updated_time)));
}
if (p.contributions) {
console.log();
var contribution = toArray(p.contributions.contribution);
for (var cont of contribution) {
console.log((cont.character_name ? cont.character_name : (cont.credit_role ? cont.credit_role.$ : 'Unknown'))+' - '+
(cont.contributor && cont.contributor.name ? (cont.contributor.name.given ? cont.contributor.name.given+' '+cont.contributor.name.family :
cont.contributor.name.presentation) : 'Unknown'));
}
}
//if (p.x_parent) {
// console.log(JSON.stringify(p.x_parent,null,2));
//}
}
else {
hidden++;
}
}
if (programme_cache.length == 1) {
var item = programme_cache[0];
if (item.synopses && (item.synopses.long || item.synopses.medium)) {
console.log();
console.log(item.synopses.long ? item.synopses.long : item.synopses.medium);
}
}
console.log();
console.log('Cache has '+programme_cache.length+' entries, '+hidden+' hidden');
}
//_____________________________________________________________________________
var processResponse = function(obj,payload) {
var nextHref = '';
if ((obj.nitro.pagination) && (obj.nitro.pagination.next)) {
nextHref = obj.nitro.pagination.next.href;
//console.log(nextHref);
}
var pageNo = obj.nitro.results.page;
var top = obj.nitro.results.total;
if (!top) {
top = obj.nitro.results.more_than+1;
}
var last = Math.ceil(top/obj.nitro.results.page_size);
process.stdout.write('.');
var length = 0;
if (obj.nitro.results.items) {
length = obj.nitro.results.items.length;
}
if (length==0) {
//console.log('No results returned');
}
else {
for (var i in obj.nitro.results.items) {
var p = obj.nitro.results.items[i];
//debuglog(JSON.stringify(p,null,2));
if ((p.item_type == 'episode') || (p.item_type == 'clip') || (p.item_type == episode_type)) {
add_programme(p,payload);
}
else if ((p.item_type == 'series') || (p.item_type == 'brand')) {
var path = domain+feed;
var query = nitro.newQuery(api.fProgrammesDescendantsOf,p.pid,true)
.add(api.fProgrammesAvailabilityAvailable)
.add(api.fProgrammesAvailabilityEntityTypeEpisode)
.add(api.fProgrammesAvailabilityTypeOndemand)
.add(api.fProgrammesPaymentType,payment_type)
.add(api.fProgrammesMediaSet,mediaSet)
.add(api.mProgrammesDuration)
.add(api.mProgrammesAncestorTitles)
.add(api.mProgrammesAvailability)
.add(api.mProgrammesAvailableVersions)
.add(api.fProgrammesEntityTypeEpisode)
.add(api.fProgrammesPageSize,pageSize);
if (media_type) {
query.add(api.fProgrammesMediaType,media_type);
}
process.stdout.write('>');
var settings = {};
settings.payload = p;
nitro.make_request(host,path,api_key,query,settings,processResponse);
}
else {
console.log('Unhandled type: '+p.type);
console.log(p);
}
}
}
var dest = {};
if (pageNo<last) {
dest.path = domain+feed;
dest.query = nitro.queryFrom(nextHref,true); // TODO
dest.callback = processResponse;
}
// if we need to go somewhere else, e.g. after all pages received set callback and/or path
nitro.setReturn(dest);
return true;
}
//_____________________________________________________________________________
function dispatch(obj,payload) {
if (obj.nitro) {
processResponse(obj,payload);
}
else if (obj.fault) {
nitro.logFault(obj);
}
else if (obj.errors) {
nitro.logError(obj);
}
else {
console.log(obj);
}
return {};
}
//_____________________________________________________________________________
function processPid(host,path,api_key,pid) {
var query = nitro.newQuery();
query.add(api.fProgrammesPageSize,pageSize,true)
.add(api.mProgrammesContributions)
.add(api.mProgrammesDuration)
.add(api.mProgrammesAncestorTitles)
.add(api.mProgrammesAvailableVersions)
.add(api.mProgrammesGenreGroupings)
if (upcoming || children) {
query.add(api.fProgrammesDescendantsOf,pid)
.add(api.fProgrammesAvailabilityPending);
}
else {
query.add(api.fProgrammesPid,pid)
}
if (partner_pid != '') {
query.add(api.fProgrammesPartnerPid,partner_pid);
}
else {
if (pending) {
query.add(api.fProgrammesAvailability,'P30D');
}
else {
query.add(api.fProgrammesAvailabilityAvailable);
}
query.add(api.mProgrammesAvailability); // has a dependency on 'availability'
}
if (episode_type == 'clip') {
query.add(api.fProgrammesAvailabilityEntityTypeClip);
}
else if ((episode_type == 'brand') || (episode_type == 'series')) {
query.add(api.fProgrammesEntityType,episode_type);
}
else {
query.add(api.fProgrammesAvailabilityEntityTypeEpisode);
}
if (embargoed) {
query.add(api.xProgrammesEmbargoed,embargoed);
}
if (payment_type) {
query.add(api.fProgrammesPaymentType,payment_type);
}
nitro.make_request(host,path,api_key,query,{},function(obj){
return dispatch(obj);
});
}
//_____________________________________________________________________________
function processVpid(host,path,api_key,vpid) {
var query = nitro.newQuery();
query.add(api.fVersionsPid,vpid,true);
if (partner_pid != '') {
query.add(api.fVersionsPartnerPid,partner_pid);
}
else {
if (pending) {
query.add(api.fVersionsAvailability,'P30D');
}
else {
query.add(api.fVersionsAvailabilityAvailable);
}
}
if (embargoed) {
query.add(api.xProgrammesEmbargoed,embargoed);
}
nitro.make_request(host,api.nitroVersions,api_key,query,{},function(obj){
for (var i in obj.nitro.results.items) {
var item = obj.nitro.results.items[i];
var pid = item.version_of.pid;
processPid(host,path,api_key,pid)
}
});
}
//_____________________________________________________________________________
var scheduleResponse = function(obj) {
var nextHref = '';
if ((obj.nitro.pagination) && (obj.nitro.pagination.next)) {
nextHref = obj.nitro.pagination.next.href;
//console.log(nextHref);
}
var pageNo = obj.nitro.results.page;
var top = obj.nitro.results.total;
if (!top) {
top = obj.nitro.results.more_than+1;
}
var last = Math.ceil(top/obj.nitro.results.page_size);
//console.log('page '+pageNo+' of '+last);
process.stdout.write('.');
var length = 0;
if (obj.nitro.results.items) {
length = obj.nitro.results.items.length;
}
if (length==0) {
console.log('No results returned');
}
else {
for (var i in obj.nitro.results.items) {
var item = obj.nitro.results.items[i];
debuglog(item);
// minimally convert a broadcast into a programme for display
var p = {};
p.ancestor_titles = item.ancestor_titles;
p.available_versions = {};
p.available_versions.available = 1;
p.version = {};
p.version.duration = (item.published_time ? item.published_time.duration : '');
p.synopses = {};
p.media_type = (item.service.sid.indexOf('radio')>=0 ? 'Audio' : 'Video');
p.image = item.image;
p.master_brand = {};
p.master_brand.mid = item.service.sid; //!
p.release_date = item.published_time.start;
for (var b in item.broadcast_of) {
var bof = item.broadcast_of[b];
if ((bof.result_type == 'episode') || (bof.result_type == 'clip')) {
p.item_type = bof.result_type;
p.pid = bof.pid;
}
else if (bof.result_type == 'version') {
p.version.pid = bof.pid;
}
}
for (var a in item.ancestor_titles) {
var at = item.ancestor_titles[a];
if ((at.ancestor_type == 'episode') || (at.ancestor_type == 'clip')) {
p.title = at.title;
}
}
// item.ids.id is an array of submissions(?) to broadcast schedule services
var present = false;
for (var pc in programme_cache) {
var pci = programme_cache[pc];
if (pci.pid == p.pid) present = true;
}
if (!present) programme_cache.push(p);
}
}
var dest = {};
if (pageNo<last) {
dest.path = '/nitro/api/schedules';
dest.query = nitro.queryFrom(nextHref,true); // TODO
dest.callback = scheduleResponse;
}
// if we need to go somewhere else, e.g. after all pages received set callback and/or path
nitro.setReturn(dest);
return true;
}
//_____________________________________________________________________________
function processSchedule(host,api_key,category,format,mode,pid) {
var path = '/nitro/api/schedules';
var today = new Date();
var todayStr = today.toISOString();
var query = nitro.newQuery();
query.add(api.fSchedulesStartFrom,todayStr,true);
if (mode == 'genre') {
for (var c in category) {
query.add(api.fSchedulesGenre,category[c]);
}
}
for (var f in format) {
query.add(api.fSchedulesFormat,format[f]);
}
if (search != '') {
query.add(api.fSchedulesQ,search);
}
if (mode == 'pid') {
query.add(api.fSchedulesDescendantsOf,pid);
}
if (channel != '') {
query.add(api.fSchedulesServiceMasterBrand,channel);
}
if (partner_pid) {
query.add(api.fSchedulesPartnerPid,partner_pid);
}
if (sid) {
query.add(api.fSchedulesSid,sid);
}
query.add(api.mSchedulesAncestorTitles)
.add(api.fSchedulesPageSize,pageSize);
nitro.make_request(host,path,api_key,query,{},function(obj){
var result = scheduleResponse(obj);
var dest = nitro.getReturn();
if (dest.callback) {
// call the callback's next required destination
// e.g. second and subsequent pages
if (dest.path) {
nitro.make_request(host,dest.path,api_key,dest.query,{},dest.callback);
}
else {
dest.callback();
}
}
});
}
//------------------------------------------------------------------------[main]
// https://developer.bbc.co.uk/nitropubliclicence
// https://admin.live.bbc.co.uk/nitro/admin/servicestatus
// https://api.live.bbc.co.uk/nitro/api/schema
// https://confluence.dev.bbc.co.uk/display/nitro/Nitro+run+book
// http://www.bbc.co.uk/academy/technology/article/art20141013145843465
var defcat = 'all';
try {
var config = require('./config.json');
host = config.nitro.host;
api_key = config.nitro.api_key;
mediaSet = config.nitro.mediaset;
defcat = config.nitro.category;
}
catch (e) {
console.log('Please rename config.json.example to config.json and edit for your setup');
process.exit(2);
}
var category = [];
var format = [];
var query = nitro.newQuery();
var pid = '';
var mode = '';
var pending = false;
var episode_type = '';
var duration = '';
var path = domain+feed;
var options = getopt.create([
['h','help','display this help'],
['b','index_base','get_iplayer index base, defaults to 10000'],
['c','channel=ARG','Filter by channel (masterbrand) id'],
['d','domain=ARG','Set domain = radio,tv or both'],
['f','format=ARG+','Filter by format id'],
['g','genre=ARG+','Filter by genre id. all to reset'],
['l','linear=ARG','Set linear service id, works with -u only'],
['r','run=ARG','run-length, short,medium or long'],
['s','search=ARG','Search metadata. Can use title: or synopsis: prefix'],
['w','with=ARG','Filter with tag'],
['p','pid=ARG+','Query by individual pid(s), ignores options above'],
['v','version=ARG+','Query by individual version pid(s), ignores options above'],
['a','all','Show programme regardless of presence in download_history'],
['e','episode=ARG','Set programme type to episode*,clip,brand or series'],
['i','imminent','Set availability to future (default is available)'],
['k','children','Include children of given pid'],
['m','mediaset','Dump mediaset information, most useful with -p'],
['o','output','output in get_iplayer cache format'],
['t','payment_type=ARG','Set payment_type to free*,bbcstore,uscansvod'],
['u','upcoming','Show programme schedule information not history'],
['x','partner_pid=ARG','Set partner pid, defaults to s0000001'],
['z','embargoed=ARG','Set embargoed to include, exclude* or only']
]);
var o = options.bindHelp();
query.add(api.fProgrammesMediaSet,mediaSet,true);
options.on('all',function(){
showAll = true;
});
options.on('imminent',function(){
pending = true;
});
options.on('children',function(){
children = true;
});
options.on('domain',function(argv,options){
service = options.domain;
if (service == 'tv') {
media_type = 'audio_video';
}
else if (service == 'both') {
media_type = '';
}
});
options.on('version',function(argv,options){
mode = 'version';
});
options.on('upcoming',function(){
feed = 'schedules';
upcoming = true;
});
options.on('channel',function(argv,options){
channel = options.channel;
query.add(api.fProgrammesMasterBrand,channel).add(api.sProgrammesTitleAscending);
});
options.on('search',function(argv,options){
search = options.search;
query.add(api.fProgrammesQ,search).add(api.sProgrammesTitleAscending);
});
options.on('format',function(argv,options){
format = options.format;
for (var f in format) {
query.add(api.fProgrammesFormat,format[f]);
}
});
options.on('genre',function(argv,options){
mode = 'genre';
for (var g in options.genre) {
var genre = options.genre[g];
if (genre == 'all') {
category = [];
}
else {
category.push(genre);
query.add(api.fProgrammesGenre,genre);
}
}
});
options.on('mediaset',function(){
dumpMediaSets = true;
});
options.on('payment_type',function(argv,options){
payment_type = options.payment_type;
});
options.on('pid',function(argv,options){
mode = 'pid';
});
options.on('partner_pid',function(argv,options){
partner_pid = options.partner_pid;
});
options.on('linear',function(argv,options){
sid = options.linear;
});
options.on('embargoed',function(argv,options){
embargoed = options.embargoed;
});
options.on('with',function(argv,options){
tag = options.with;
});
options.on('episode',function(argv,options){
episode_type = options.episode;
if ((episode_type == 'brand') || (episode_type == 'series')) {
showAll = true;
}
});
options.on('run',function(argv,options){
duration = options.run;
});
var o = options.parseSystem();
if (!showAll && config.download_history) {
download_history = giUtils.downloadHistory(config.download_history);
}
if (partner_pid) {
query.add(api.fProgrammesPartnerPid,partner_pid)
.add(api.mProgrammesAvailability)
.add(api.mProgrammesAvailableVersions)
.add(api.fProgrammesAvailabilityAvailable);
}
else {
if (pending) {
query.add(api.fProgrammesAvailability,'P30D');
}
else {
query.add(api.fProgrammesAvailabilityAvailable);
}
query.add(api.mProgrammesAvailability)
.add(api.mProgrammesAvailableVersions)
.add(api.fProgrammesPaymentType,payment_type)
.add(api.fProgrammesAvailabilityTypeOndemand);
}
if (episode_type == 'clip') {
query.add(api.fProgrammesAvailabilityEntityTypeClip);
}
else if ((episode_type == 'brand') || (episode_type == 'series')) {
query.add(api.fProgrammesEntityType,episode_type);
}
else {
query.add(api.fProgrammesAvailabilityEntityTypeEpisode);
}
if (media_type) {
query.add(api.fProgrammesMediaType,media_type);
}
if (duration) {
query.add(api.fProgrammesDuration,duration);
}
if (embargoed) {
query.add(api.xProgrammesEmbargoed,embargoed);
}
if (tag) {
query.add(api.fProgrammesTagName,tag);
}
query.add(api.mProgrammesDuration)
.add(api.mProgrammesAncestorTitles)
.add(api.fProgrammesPageSize,pageSize);
if (mode=='') {
mode = 'genre';
category.push(defcat);
query.add(api.fProgrammesGenre,defcat);
}
if (mode == 'version') {
for (var p in o.options.version) {
pid = o.options.version[p];
if (pid.indexOf('@')==0) {
pid = pid.substr(1);
var s = fs.readFileSync(pid,'utf8');
pidList = pidList.concat(s.split('\n'));
}
else {
pidList.push(pid);
}
}
for (var p in pidList) {
processVpid(host,path,api_key,pidList[p]);
}
}
else if (mode == 'pid') {
for (var p in o.options.pid) {
pid = o.options.pid[p];
if (pid.indexOf('@')==0) {
pid = pid.substr(1);
var s = fs.readFileSync(pid,'utf8');
pidList = pidList.concat(s.split('\n'));
}
else {
pidList.push(pid);
}
}
for (var p in pidList) {
if (upcoming) {
processSchedule(host,api_key,category,format,mode,pidList[p]);
}
else {
processPid(host,path,api_key,pidList[p]);
}
}
}
else if (feed == 'schedules') {
processSchedule(host,api_key,category,format,mode);
}
else {
if (mode=='genre') {
// parallelize the queries by 36 times
var letters = '0123456789abcdefghijklmnopqrstuvwxyz';
for (var l in letters) {
if (letters.hasOwnProperty(l)) {
var lQuery = query.clone();
lQuery.add(api.fProgrammesInitialLetter,letters[l]);
nitro.make_request(host,path,api_key,lQuery,{},function(obj,payload){
return dispatch(obj,payload);
});
}
}
}
}
process.on('exit', function(code) {
if (o.options.output) {
pc_export();
}
else {
pc_dump();
if (nitro.getRateLimitEvents()>0) {
console.log('Got '+nitro.getRateLimitEvents()+' rate-limit events');
}
}
});
| fix: squash colours if output not a TTY
| nitro.js | fix: squash colours if output not a TTY | <ide><path>itro.js
<ide> var nitro = require('./nitroSdk');
<ide> var api = require('./nitroApi/api');
<ide>
<del>var red = process.env.NODE_DISABLE_COLORS ? '' : '\x1b[31m';
<del>var green = process.env.NODE_DISABLE_COLORS ? '' : '\x1b[32m';
<del>var normal = process.env.NODE_DISABLE_COLORS ? '' : '\x1b[0m';
<add>const colours = process.stdout.isTTY;
<add>if (process.env.NODE_DISABLE_COLORS) colours = false;
<add>
<add>var red = colours ? '\x1b[31m' : '';
<add>var green = colours ? '\x1b[32m' : '';
<add>var normal = colours ? '\x1b[0m' : '';
<ide>
<ide> var programme_cache = [];
<ide> var download_history = []; |
|
Java | bsd-3-clause | 364959e81ce79eae3bf33c05d316f7b64dd51953 | 0 | ncaripsl/esgf-security,ncaripsl/esgf-security,ncaripsl/esgf-security | /***************************************************************************
* *
* Organization: Lawrence Livermore National Lab (LLNL) *
* Directorate: Computation *
* Department: Computing Applications and Research *
* Division: S&T Global Security *
* Matrix: Atmospheric, Earth and Energy Division *
* Program: PCMDI *
* Project: Earth Systems Grid Federation (ESGF) Data Node Software *
* First Author: Gavin M. Bell ([email protected]) *
* *
****************************************************************************
* *
* Copyright (c) 2009, Lawrence Livermore National Security, LLC. *
* Produced at the Lawrence Livermore National Laboratory *
* Written by: Gavin M. Bell ([email protected]) *
* LLNL-CODE-420962 *
* *
* All rights reserved. This file is part of the: *
* Earth System Grid Federation (ESGF) Data Node Software Stack *
* *
* For details, see http://esgf.org/esg-node/ *
* Please also read this link *
* http://esgf.org/LICENSE *
* *
* * 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 disclaimer below. *
* *
* * Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the disclaimer (as noted below) *
* in the documentation and/or other materials provided with the *
* distribution. *
* *
* Neither the name of the LLNS/LLNL 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 LAWRENCE *
* LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR *
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, *
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT *
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF *
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND *
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, *
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT *
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF *
* SUCH DAMAGE. *
* *
***************************************************************************/
package esg.node.security.shell.cmds;
/**
Description:
ESGF's "realize" command..."
This command takes a dataset directory and inspects its catalog to
find missing files (files listed in the dataset catalog but not
locally present on the filesystem) and brings them local. The
second half of the 'replication' process - for a single dataset.
**/
import esg.common.shell.*;
import esg.common.shell.cmds.*;
import esg.security.utils.encryption.PasswordEncoder;
import org.apache.commons.cli.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.impl.*;
public class ESGFpasswd extends ESGFCommand {
private static Log log = LogFactory.getLog(ESGFpasswd.class);
public ESGFpasswd() {
super();
getOptions().addOption("i", "prompt", false, "request confirmation before performing action");
getOptions().addOption("d", "disable", false, "disable this account");
Option user =
OptionBuilder.withArgName("user")
.hasArg(true)
.withDescription("User for which you wish to change password")
.withLongOpt("user")
.create("u");
getOptions().addOption(user);
}
public String getCommandName() { return "passwd"; }
public ESGFEnv doEval(CommandLine line, ESGFEnv env) {
log.trace("inside the \"passwd\" command's doEval");
//TODO: Query for options and perform execution logic
boolean prompt = line.hasOption( "i" );
boolean disable = line.hasOption( "d" );
String username = null;
if(line.hasOption( "u" )) {
username = line.getOptionValue( "u" );
if(prompt) env.getWriter().println("username: ["+username+"]");
}
int i=0;
for(String arg : line.getArgs()) {
log.info("arg("+(i++)+"): "+arg);
}
//Scrubbing... (need to go into cli code and toss in some regex's to clean this type of shit up)
java.util.List<String> argsList = new java.util.ArrayList<String>();
String[] args = null;
for(String arg : line.getArgs()) {
if(!arg.isEmpty()) {
argsList.add(arg);
}
}
args = argsList.toArray(new String[]{});
if(disable || prompt) {
env.getWriter().println("disable: ["+disable+"]");
}
String origPassword = null;
String newPassword = null;
if(args.length == 1) {
newPassword = args[0];
if(prompt) env.getWriter().println("*new password: ["+((newPassword != null) ? "*********" : newPassword)+"]");
}
if(args.length == 2) {
origPassword = args[0];
newPassword = args[1];
if(prompt) env.getWriter().println("new password: ["+((newPassword != null) ? "*********" : newPassword)+"]");
}
//------------------
//NOW DO SOME LOGIC
//------------------
String whoami = (String)env.getContext(ESGFEnv.SYS,"user.name");
//------------------
//Check access privs and setup resource object
//------------------
//UserInfoCredentialedDAO userDAO = null;
//if (!(userDAO = getUserDAO(env)).checkCredentials()) {
// userDAO = null;
// throw new ESGFCommandPermissionException("Credentials are not sufficient, sorry...");
//}
////------------------
//
//UserInfo user = null;
//if(username != null) user = userDAO.getUserById(username);
//
//if(null == user) {
// throw new esg.common.ESGRuntimeException("Sorry, the username ["+username+"] was not well formed");
//}
//
//if(user.isValid()) {
//
// if((origPassword == null) && (newPassword != null)) {
// if(userDAO.setPassword(user.getOpenid(),newPassword)) {
// env.getWriter().println("password updated :-)");
// }else {
// throw new esg.common.ESGRuntimeException("Sorry, could not update your password");
// }
// }
//
// if(user.getUserName().equals("rootAdmin")) {
// if(userDAO.setPassword(user.getOpenid(),origPassword,newPassword)) {
// env.getWriter().println("password updated :-)");
// }else {
// throw new esg.common.ESGRuntimeException("Sorry, could not update your password");
// }
//
// userDAO.changePassword(user.getOpenid(),origPassword,newPassword);
// }
//
//}else {
// throw new esg.common.ESGRuntimeException("The user you specified ["+username+"] is invalid");
//}
env.getWriter().flush();
//------------------
return env;
}
}
| src/java/main/esg/node/security/shell/cmds/ESGFpasswd.java | /***************************************************************************
* *
* Organization: Lawrence Livermore National Lab (LLNL) *
* Directorate: Computation *
* Department: Computing Applications and Research *
* Division: S&T Global Security *
* Matrix: Atmospheric, Earth and Energy Division *
* Program: PCMDI *
* Project: Earth Systems Grid Federation (ESGF) Data Node Software *
* First Author: Gavin M. Bell ([email protected]) *
* *
****************************************************************************
* *
* Copyright (c) 2009, Lawrence Livermore National Security, LLC. *
* Produced at the Lawrence Livermore National Laboratory *
* Written by: Gavin M. Bell ([email protected]) *
* LLNL-CODE-420962 *
* *
* All rights reserved. This file is part of the: *
* Earth System Grid Federation (ESGF) Data Node Software Stack *
* *
* For details, see http://esgf.org/esg-node/ *
* Please also read this link *
* http://esgf.org/LICENSE *
* *
* * 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 disclaimer below. *
* *
* * Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the disclaimer (as noted below) *
* in the documentation and/or other materials provided with the *
* distribution. *
* *
* Neither the name of the LLNS/LLNL 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 LAWRENCE *
* LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR *
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, *
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT *
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF *
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND *
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, *
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT *
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF *
* SUCH DAMAGE. *
* *
***************************************************************************/
package esg.node.security.shell.cmds;
/**
Description:
ESGF's "realize" command..."
This command takes a dataset directory and inspects its catalog to
find missing files (files listed in the dataset catalog but not
locally present on the filesystem) and brings them local. The
second half of the 'replication' process - for a single dataset.
**/
import esg.common.shell.*;
import esg.common.shell.cmds.*;
import esg.security.utils.encryption.PasswordEncoder;
import org.apache.commons.cli.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.impl.*;
public class ESGFpasswd extends ESGFCommand {
private static Log log = LogFactory.getLog(ESGFpasswd.class);
public ESGFpasswd() {
super();
getOptions().addOption("i", "prompt", false, "request confirmation before performing action");
getOptions().addOption("d", "disable", false, "disable this account");
Option user =
OptionBuilder.withArgName("user")
.hasArg(true)
.withDescription("User for which you wish to change password")
.withLongOpt("user")
.create("u");
getOptions().addOption(user);
}
public String getCommandName() { return "passwd"; }
public ESGFEnv doEval(CommandLine line, ESGFEnv env) {
log.trace("inside the \"passwd\" command's doEval");
//TODO: Query for options and perform execution logic
boolean prompt = line.hasOption( "i" );
boolean disable = line.hasOption( "d" );
String username = null;
if(line.hasOption( "u" )) {
username = line.getOptionValue( "u" );
if(prompt) env.getWriter().println("username: ["+username+"]");
}
int i=0;
for(String arg : line.getArgs()) {
log.info("arg("+(i++)+"): "+arg);
}
//Scrubbing... (need to go into cli code and toss in some regex's to clean this type of shit up)
java.util.List<String> argsList = new java.util.ArrayList<String>();
String[] args = null;
for(String arg : line.getArgs()) {
if(!arg.isEmpty()) {
argsList.add(arg);
}
}
args = argsList.toArray(new String[]{});
if(disable || prompt) {
env.getWriter().println("disable: ["+disable+"]");
}
String origPassword = null;
String newPassword = null;
if(args.length == 1) {
newPassword = args[0];
if(prompt) env.getWriter().println("*new password: ["+((newPassword != null) ? "*********" : newPassword)+"]");
}
if(args.length == 2) {
origPassword = args[0];
newPassword = args[1];
if(prompt) env.getWriter().println("new password: ["+((newPassword != null) ? "*********" : newPassword)+"]");
}
//------------------
//NOW DO SOME LOGIC
//------------------
String whoami = (String)env.getContext(SYS,"user.name");
//------------------
//Check access privs and setup resource object
//------------------
//UserInfoCredentialedDAO userDAO = null;
//if (!(userDAO = getUserDAO(env)).checkCredentials()) {
// userDAO = null;
// throw new ESGFCommandPermissionException("Credentials are not sufficient, sorry...");
//}
////------------------
//
//UserInfo user = null;
//if(username != null) user = userDAO.getUserById(username);
//
//if(null == user) {
// throw new esg.common.ESGRuntimeException("Sorry, the username ["+username+"] was not well formed");
//}
//
//if(user.isValid()) {
//
// if((origPassword == null) && (newPassword != null)) {
// if(userDAO.setPassword(user.getOpenid(),newPassword)) {
// env.getWriter().println("password updated :-)");
// }else {
// throw new esg.common.ESGRuntimeException("Sorry, could not update your password");
// }
// }
//
// if(user.getUserName().equals("rootAdmin")) {
// if(userDAO.setPassword(user.getOpenid(),origPassword,newPassword)) {
// env.getWriter().println("password updated :-)");
// }else {
// throw new esg.common.ESGRuntimeException("Sorry, could not update your password");
// }
//
// userDAO.changePassword(user.getOpenid(),origPassword,newPassword);
// }
//
//}else {
// throw new esg.common.ESGRuntimeException("The user you specified ["+username+"] is invalid");
//}
env.getWriter().flush();
//------------------
return env;
}
}
| (place holder for whoami (fixed))
| src/java/main/esg/node/security/shell/cmds/ESGFpasswd.java | (place holder for whoami (fixed)) | <ide><path>rc/java/main/esg/node/security/shell/cmds/ESGFpasswd.java
<ide> //NOW DO SOME LOGIC
<ide> //------------------
<ide>
<del> String whoami = (String)env.getContext(SYS,"user.name");
<add> String whoami = (String)env.getContext(ESGFEnv.SYS,"user.name");
<ide>
<ide> //------------------
<ide> //Check access privs and setup resource object |
|
Java | apache-2.0 | 685893ca3f02ed6b7bbf2c1951a379444c346bd2 | 0 | consulo/consulo-javascript,consulo/consulo-javascript,consulo/consulo-javascript | /*
* Copyright 2000-2005 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.javascript.documentation;
import java.io.File;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.mustbe.consulo.RequiredReadAction;
import com.intellij.lang.ASTNode;
import com.intellij.lang.documentation.CodeDocumentationProvider;
import com.intellij.lang.documentation.DocumentationProvider;
import com.intellij.lang.javascript.JSTokenTypes;
import com.intellij.lang.javascript.JavaScriptSupportLoader;
import com.intellij.lang.javascript.index.JavaScriptIndex;
import com.intellij.lang.javascript.psi.*;
import com.intellij.lang.javascript.psi.impl.JSPsiImplUtils;
import com.intellij.lang.javascript.psi.resolve.BaseJSSymbolProcessor;
import com.intellij.lang.javascript.psi.resolve.JSImportHandlingUtil;
import com.intellij.lang.javascript.psi.resolve.JSResolveUtil;
import com.intellij.navigation.ItemPresentation;
import com.intellij.navigation.NavigationItem;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.PsiNamedElement;
import com.intellij.psi.PsiWhiteSpace;
import com.intellij.psi.ResolveResult;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlToken;
/**
* Created by IntelliJ IDEA.
* User: Maxim.Mossienko
* Date: Nov 4, 2005
* Time: 5:04:28 PM
*/
public class JSDocumentationProvider implements CodeDocumentationProvider
{
private DocumentationProvider cssProvider;
@NonNls
private static final String OBJECT_NAME = "Object";
protected static final String SEE_PLAIN_TEXT_CHARS = "\t \"-\\/<>*";
@NonNls
protected static final String PACKAGE = "package";
@NonNls
protected static final String HTML_EXTENSION = ".html";
@NonNls
protected static final String PACKAGE_FILE = PACKAGE + HTML_EXTENSION;
protected static final Map<String, String> DOCUMENTED_ATTRIBUTES;
static
{
DOCUMENTED_ATTRIBUTES = new HashMap<String, String>();
DOCUMENTED_ATTRIBUTES.put("Event", "event:");
DOCUMENTED_ATTRIBUTES.put("Style", "style:");
DOCUMENTED_ATTRIBUTES.put("Effect", "effect:");
}
private DocumentationProvider getCssProvider(Project project) throws Exception
{
if(cssProvider == null)
{
final Class<?> aClass = Class.forName("com.intellij.psi.css.impl.util.CssDocumentationProvider");
cssProvider = (DocumentationProvider) aClass.getConstructor(new Class[]{}).newInstance(new Object[]{});
}
return cssProvider;
}
@Nullable
public String getQuickNavigateInfo(PsiElement element, PsiElement element2)
{
if(element instanceof JSFunction)
{
final JSFunction function = (JSFunction) element;
final PsiElement parent = element.getParent();
if(function.isConstructor())
{
if(parent instanceof JSClass)
{
return createQuickNavigateForClazz((JSClass) parent);
}
}
return createQuickNavigateForFunction(function);
}
else if(element instanceof JSClass)
{
return createQuickNavigateForClazz((JSClass) element);
}
else if(element instanceof JSVariable)
{
return createQuickNavigateForVariable((JSVariable) element);
}
else if(element instanceof JSAttributeNameValuePair)
{
return createQuickNavigateForAnnotationDerived(element);
}
else if(element instanceof XmlToken)
{
BaseJSSymbolProcessor.TagContextBuilder builder = new BaseJSSymbolProcessor.TagContextBuilder(element, "XmlTag");
return StringUtil.stripQuotesAroundValue(element.getText()) + ":" + builder.typeName;
}
else if(element instanceof JSNamespaceDeclaration)
{
return createQuickNavigateForNamespace((JSNamespaceDeclaration) element);
}
return null;
}
private static String createQuickNavigateForAnnotationDerived(final PsiElement element)
{
final JSAttributeNameValuePair valuePair = (JSAttributeNameValuePair) element;
final JSAttribute parent = (JSAttribute) valuePair.getParent();
final StringBuilder builder = new StringBuilder();
final JSClass clazz = PsiTreeUtil.getParentOfType(valuePair, JSClass.class);
appendParentInfo(clazz != null ? clazz : parent.getContainingFile(), builder, parent);
builder.append(parent.getName()).append(" ").append(valuePair.getSimpleValue());
return builder.toString();
}
private static
@Nullable
String createQuickNavigateForFunction(final JSFunction function)
{
final PsiElement parent = JSResolveUtil.findParent(function);
final StringBuilder result = new StringBuilder();
appendParentInfo(parent, result, function);
appendAttrList(function, result);
final boolean get = function.isGetProperty();
final boolean set = function.isSetProperty();
result.append(get || set ? "property " : "function ");
result.append(function.getName());
if(!get && !set)
{
result.append('(');
final JSParameterList jsParameterList = function.getParameterList();
if(jsParameterList != null)
{
final int start = result.length();
for(JSParameter p : jsParameterList.getParameters())
{
if(start != result.length())
{
result.append(", ");
}
result.append(p.getName());
appendVarType(p, result);
}
}
result.append(')');
}
String varType = null;
if(get || !set)
{
varType = JSImportHandlingUtil.resolveTypeName(function.getReturnTypeString(), function);
}
else
{
final JSParameterList jsParameterList = function.getParameterList();
if(jsParameterList != null)
{
final JSParameter[] jsParameters = jsParameterList.getParameters();
if(jsParameters != null && jsParameters.length > 0)
{
varType = JSImportHandlingUtil.resolveTypeName(jsParameters[0].getTypeString(), function);
}
}
}
if(varType != null)
{
result.append(':').append(varType);
}
return result.toString();
}
private static void appendParentInfo(final PsiElement parent, final StringBuilder builder, PsiNamedElement element)
{
if(parent instanceof JSClass)
{
builder.append(((JSClass) parent).getQualifiedName()).append("\n");
}
else if(parent instanceof JSPackageStatement)
{
builder.append(((JSPackageStatement) parent).getQualifiedName()).append("\n");
}
else if(parent instanceof JSFile)
{
if(parent.getContext() != null)
{
final String mxmlPackage = JSResolveUtil.findPackageForMxml(parent);
if(mxmlPackage != null)
{
builder.append(mxmlPackage).append(mxmlPackage.length() > 0 ? "." : "").append(parent.getContext().getContainingFile().getName()).append("\n");
}
}
else
{
boolean foundQualified = false;
if(element instanceof JSNamedElement)
{
ASTNode node = ((JSNamedElement) element).findNameIdentifier();
if(node != null)
{
final String s = node.getText();
int i = s.lastIndexOf('.');
if(i != -1)
{
builder.append(s.substring(0, i)).append("\n");
foundQualified = true;
}
}
}
if(!foundQualified)
{
builder.append(parent.getContainingFile().getName()).append("\n");
}
}
}
}
@Nullable
@RequiredReadAction
private static String createQuickNavigateForVariable(final JSVariable variable)
{
final PsiElement parent = JSResolveUtil.findParent(variable);
final StringBuilder result = new StringBuilder();
appendParentInfo(parent, result, variable);
appendAttrList(variable, result);
result.append(variable.isConst() ? "const " : "var ");
result.append(variable.getName());
appendVarType(variable, result);
JSExpression initializer = variable.getInitializer();
if(initializer != null)
{
result.append(" = ");
if(initializer instanceof JSLiteralExpression)
{
result.append(initializer.getText());
}
else if(initializer instanceof JSObjectLiteralExpression)
{
result.append("{...}");
}
else
{
result.append("...");
}
}
return result.toString();
}
private static void appendVarType(final JSVariable variable, final StringBuilder builder)
{
final String varType = variable.getTypeString();
if(varType != null)
{
builder.append(':').append(varType);
}
}
private static
@Nullable
String createQuickNavigateForClazz(final JSClass jsClass)
{
final String qName = jsClass.getQualifiedName();
if(qName == null)
{
return null;
}
StringBuilder result = new StringBuilder();
String packageName = StringUtil.getPackageName(qName);
if(packageName.length() > 0)
{
result.append(packageName).append("\n");
}
appendAttrList(jsClass, result);
if(jsClass.isInterface())
{
result.append("interface");
}
else
{
result.append("class");
}
final String name = jsClass.getName();
result.append(" ").append(name);
String s = generateReferenceTargetList(jsClass.getExtendsList(), packageName);
if(s == null && !OBJECT_NAME.equals(name))
{
s = OBJECT_NAME;
}
if(s != null)
{
result.append(" extends ").append(s);
}
s = generateReferenceTargetList(jsClass.getImplementsList(), packageName);
if(s != null)
{
result.append("\nimplements ").append(s);
}
return result.toString();
}
private static
@Nullable
String createQuickNavigateForNamespace(final JSNamespaceDeclaration ns)
{
final String qName = ns.getQualifiedName();
if(qName == null)
{
return null;
}
StringBuilder result = new StringBuilder();
String packageName = StringUtil.getPackageName(qName);
if(packageName.length() > 0)
{
result.append(packageName).append("\n");
}
result.append("namespace");
final String name = ns.getName();
result.append(" ").append(name);
String s = ns.getInitialValueString();
if(s != null)
{
result.append(" = ").append(s);
}
return result.toString();
}
private static void appendAttrList(final JSAttributeListOwner jsClass, final StringBuilder result)
{
final JSAttributeList attributeList = jsClass.getAttributeList();
if(attributeList != null)
{
if(attributeList.hasModifier(JSAttributeList.ModifierType.OVERRIDE))
{
result.append("override ");
}
JSAttributeList.AccessType type = attributeList.getAccessType();
String ns = attributeList.getNamespace();
if(type != JSAttributeList.AccessType.PACKAGE_LOCAL || ns == null)
{
result.append(type.toString().toLowerCase());
}
else
{
result.append(ns);
}
result.append(" ");
if(attributeList.hasModifier(JSAttributeList.ModifierType.STATIC))
{
result.append("static ");
}
if(attributeList.hasModifier(JSAttributeList.ModifierType.FINAL))
{
result.append("final ");
}
if(attributeList.hasModifier(JSAttributeList.ModifierType.DYNAMIC))
{
result.append("dynamic ");
}
if(attributeList.hasModifier(JSAttributeList.ModifierType.NATIVE))
{
result.append("native ");
}
}
}
private static
@Nullable
String generateReferenceTargetList(final @Nullable JSReferenceList implementsList, @NotNull String packageName)
{
if(implementsList == null)
{
return null;
}
StringBuilder result = null;
final String[] referenceExpressionTexts = implementsList.getReferenceTexts();
for(String refExprText : referenceExpressionTexts)
{
refExprText = JSImportHandlingUtil.resolveTypeName(refExprText, implementsList);
if(result == null)
{
result = new StringBuilder();
}
else
{
result.append(",");
}
final String referencedPackageName = StringUtil.getPackageName(refExprText);
result.append(referencedPackageName.equals(packageName) ? refExprText.substring(refExprText.lastIndexOf('.') + 1) : refExprText);
}
return result == null ? null : result.toString();
}
@Override
public List<String> getUrlFor(PsiElement element, PsiElement originalElement)
{
String possibleCssName = findPossibleCssName(element);
if(possibleCssName != null)
{
try
{
final DocumentationProvider documentationProvider = getCssProvider(element.getProject());
final Method method = documentationProvider.getClass().getMethod("getUrlFor", new Class[]{String.class});
final Object o = method.invoke(null, new Object[]{possibleCssName});
if(o instanceof String)
{
return Collections.singletonList((String) o);
}
}
catch(Exception e)
{
}
}
return null;
}
@Override
public String generateDoc(PsiElement _element, PsiElement originalElement)
{
if(_element instanceof JSReferenceExpression)
{
StringBuilder buffer = null;
// ambigious reference
final JSReferenceExpression expression = (JSReferenceExpression) _element;
for(ResolveResult r : expression.multiResolve(false))
{
if(buffer == null)
{
buffer = new StringBuilder();
}
final PsiElement element = r.getElement();
final ItemPresentation presentation = ((NavigationItem) element).getPresentation();
JSDocumentationUtils.appendHyperLinkToElement(element, expression.getReferencedName(), buffer, presentation.getPresentableText(),
presentation.getLocationString());
buffer.append("<br/>\n");
}
return buffer != null ? buffer.toString() : "have no idea :)";
}
_element = _element.getNavigationElement();
PsiElement element = findElementForWhichPreviousCommentWillBeSearched(_element);
final boolean parameterDoc = element instanceof JSParameter;
if(parameterDoc)
{
element = findElementForWhichPreviousCommentWillBeSearched(PsiTreeUtil.getParentOfType(element, JSFunction.class));
}
if(element != null)
{
PsiElement docComment = JSDocumentationUtils.findDocComment(element, _element instanceof JSAttributeNameValuePair ? originalElement : null);
if(docComment != null)
{
docComment = findFirstDocComment(docComment);
element = findTargetElement(_element, element);
final JSDocumentationBuilder builder = new JSDocumentationBuilder(element, originalElement);
JSDocumentationUtils.processDocumentationTextFromComment(docComment.getNode(), builder);
return parameterDoc ? builder.getParameterDoc(((JSParameter) _element).getName()) : builder.getDoc();
}
element = findTargetElement(_element, element);
if(element instanceof JSFunction)
{
ASTNode initialComment = JSDocumentationUtils.findLeadingCommentInFunctionBody(element);
if(initialComment != null)
{
final JSDocumentationBuilder builder = new JSDocumentationBuilder(element, originalElement);
JSDocumentationUtils.processDocumentationTextFromComment(initialComment, builder);
return builder.getDoc();
}
}
}
String possibleCssName = findPossibleCssName(_element);
if(possibleCssName != null)
{
try
{
final DocumentationProvider documentationProvider = getCssProvider(_element.getProject());
final Method declaredMethod = documentationProvider.getClass().getDeclaredMethod("generateDoc", String.class, PsiElement.class);
final Object o = declaredMethod.invoke(null, possibleCssName, null);
if(o instanceof String)
{
return (String) o;
}
}
catch(Exception e)
{
}
}
return null;
}
private static PsiElement findTargetElement(final PsiElement _element, PsiElement element)
{
if(_element instanceof JSDefinitionExpression)
{
final PsiElement parentElement = _element.getParent();
if(parentElement instanceof JSAssignmentExpression)
{
final JSExpression rOperand = ((JSAssignmentExpression) parentElement).getROperand();
if(rOperand instanceof JSFunctionExpression)
{
element = rOperand;
}
else
{
element = _element;
}
}
}
else if(_element instanceof JSFunctionExpression)
{
element = _element;
}
else if(_element instanceof JSProperty)
{
final JSExpression expression = ((JSProperty) _element).getValue();
if(expression instanceof JSFunction)
{
element = expression;
}
}
else if(_element instanceof JSVariable)
{
if(_element instanceof JSParameter)
{
return PsiTreeUtil.getParentOfType(_element, JSFunction.class);
}
element = _element;
}
else if(_element instanceof JSAttributeNameValuePair)
{
return _element;
}
return element;
}
private static PsiElement findFirstDocComment(PsiElement docComment)
{
if(docComment.getNode().getElementType() == JSTokenTypes.END_OF_LINE_COMMENT)
{
while(true)
{
PsiElement prev = docComment.getPrevSibling();
if(prev instanceof PsiWhiteSpace)
{
prev = prev.getPrevSibling();
}
if(prev == null)
{
break;
}
if(prev.getNode().getElementType() != JSTokenTypes.END_OF_LINE_COMMENT)
{
break;
}
docComment = prev;
}
}
return docComment;
}
private static String findPossibleCssName(PsiElement _element)
{
if(_element instanceof JSDefinitionExpression)
{
final JSExpression expression = ((JSDefinitionExpression) _element).getExpression();
if(expression instanceof JSReferenceExpression)
{
final String text = ((JSReferenceExpression) expression).getReferencedName();
if(text == null)
{
return null;
}
final StringBuffer buf = new StringBuffer(text.length());
for(int i = 0; i < text.length(); ++i)
{
final char ch = text.charAt(i);
if(Character.isUpperCase(ch))
{
buf.append('-').append(Character.toLowerCase(ch));
}
else
{
buf.append(ch);
}
}
return buf.toString();
}
}
return null;
}
@Override
public PsiElement getDocumentationElementForLookupItem(PsiManager psiManager, Object object, PsiElement element)
{
final PsiElement psiElement = findElementForWhichPreviousCommentWillBeSearched(object);
if(psiElement != null && JSDocumentationUtils.findDocComment(psiElement) != null)
{
return psiElement;
}
if(object instanceof PsiElement)
{
return (PsiElement) object;
}
return null;
}
public static PsiElement findElementForWhichPreviousCommentWillBeSearched(Object object)
{
if(object instanceof JSFunction)
{
PsiElement psiElement = (PsiElement) object;
PsiElement parent = psiElement.getParent();
if(parent instanceof JSNewExpression)
{
parent = parent.getParent();
}
if(parent instanceof JSProperty)
{
psiElement = parent;
}
else if(parent instanceof JSAssignmentExpression)
{
psiElement = parent.getParent();
}
JSFunction function = (JSFunction) object;
if(function.isSetProperty() || function.isGetProperty())
{
for(PsiElement el = function.getPrevSibling(); el != null; el = el.getPrevSibling())
{
if(!(el instanceof PsiWhiteSpace) && !(el instanceof PsiComment))
{
if(el instanceof JSFunction)
{
JSFunction prevFunction = (JSFunction) el;
String name = prevFunction.getName();
if(name != null &&
name.equals(function.getName()) &&
((prevFunction.isGetProperty() && function.isSetProperty()) || prevFunction.isSetProperty() && function.isGetProperty()))
{
PsiElement doc = JSDocumentationUtils.findDocComment(prevFunction);
if(doc != null)
{
return prevFunction;
}
}
}
break;
}
}
}
return psiElement;
}
else if(object instanceof JSProperty || object instanceof JSStatement || object instanceof JSClass)
{
return (PsiElement) object;
}
else if(object instanceof PsiElement)
{
final PsiElement parent = ((PsiElement) object).getParent();
if(parent instanceof JSAssignmentExpression)
{
return parent.getParent();
}
else if(parent instanceof JSVarStatement)
{
final PsiElement firstChild = parent.getFirstChild();
if(firstChild instanceof JSAttributeList)
{
if(JSDocumentationUtils.findDocComment((PsiElement) object) != null)
{
return (PsiElement) object;
}
}
return parent;
}
else if(parent instanceof JSAttribute)
{
final PsiElement grandParent = parent.getParent();
if(grandParent.getFirstChild() == parent)
{
final PsiElement element = grandParent.getParent();
if(element instanceof JSFile)
{
return grandParent;
}
return element;
}
return parent;
}
else if(parent instanceof JSSuppressionHolder)
{
return parent;
}
else
{
return (PsiElement) object;
}
}
return null;
}
@Override
@Nullable
public PsiElement getDocumentationElementForLink(final PsiManager psiManager, String link, final PsiElement context)
{
return getDocumentationElementForLinkStatic(psiManager, link, context);
}
@Nullable
private static PsiElement getDocumentationElementForLinkStatic(final PsiManager psiManager, String link, @NotNull PsiElement context)
{
final int delimiterIndex = link.lastIndexOf(':');
String attributeType = null;
String attributeName = null;
for(Map.Entry<String, String> e : DOCUMENTED_ATTRIBUTES.entrySet())
{
final String pattern = "." + e.getValue();
if(link.contains(pattern))
{
attributeType = e.getKey();
attributeName = link.substring(link.indexOf(pattern) + pattern.length());
link = link.substring(0, link.indexOf(pattern));
break;
}
}
if(delimiterIndex != -1 && attributeType == null)
{
final int delimiterIndex2 = link.lastIndexOf(':', delimiterIndex - 1);
String fileName = link.substring(0, delimiterIndex2).replace(File.separatorChar, '/');
String name = link.substring(delimiterIndex2 + 1, delimiterIndex);
int offset = Integer.parseInt(link.substring(delimiterIndex + 1));
return JavaScriptIndex.findSymbolByFileAndNameAndOffset(fileName, name, offset);
}
else if(attributeType != null)
{
PsiElement clazz = JSResolveUtil.findClassByQName(link, context.getResolveScope(), psiManager.getProject());
if(!(clazz instanceof JSClass))
{
return null;
}
return findNamedAttribute((JSClass) clazz, attributeType, attributeName);
}
else
{
PsiElement clazz = JSResolveUtil.findClassByQName(link, context.getResolveScope(), psiManager.getProject());
if(clazz == null && link.contains("."))
{
String qname = link.substring(0, link.lastIndexOf('.'));
clazz = JSResolveUtil.findClassByQName(qname, context.getResolveScope(), psiManager.getProject());
if(clazz instanceof JSClass)
{
JSClass jsClass = (JSClass) clazz;
String member = link.substring(link.lastIndexOf('.') + 1);
if(member.endsWith("()"))
{
member = member.substring(0, member.length() - 2);
PsiElement result = findMethod(jsClass, member);
if(result == null)
{
result = findProperty(jsClass, member); // user might refer to a property
}
return result;
}
else
{
PsiElement result = jsClass.findFieldByName(member);
if(result == null)
{
result = findProperty(jsClass, member);
}
if(result == null)
{
result = findMethod(jsClass, member); // user might forget brackets
}
return result;
}
}
}
if(clazz instanceof JSVariable)
{
return clazz;
}
if(link.endsWith("()"))
{
link = link.substring(0, link.length() - 2);
clazz = JSResolveUtil.findClassByQName(link, context.getResolveScope(), psiManager.getProject());
if(clazz instanceof JSFunction)
{
return clazz;
}
}
return clazz;
}
}
@Nullable
protected static JSAttributeNameValuePair findNamedAttribute(JSClass clazz, final String type, final String name)
{
final Ref<JSAttributeNameValuePair> attribute = new Ref<JSAttributeNameValuePair>();
JSResolveUtil.processMetaAttributesForClass(clazz, new JSResolveUtil.MetaDataProcessor()
{
@Override
public boolean process(@NotNull JSAttribute jsAttribute)
{
if(type.equals(jsAttribute.getName()))
{
final JSAttributeNameValuePair jsAttributeNameValuePair = jsAttribute.getValueByName("name");
if(jsAttributeNameValuePair != null && name.equals(jsAttributeNameValuePair.getSimpleValue()))
{
attribute.set(jsAttributeNameValuePair);
return false;
}
}
return true;
}
@Override
public boolean handleOtherElement(PsiElement el, PsiElement context, @Nullable Ref<PsiElement> continuePassElement)
{
return true;
}
});
return attribute.get();
}
private static PsiElement findProperty(JSClass jsClass, String name)
{
PsiElement result = jsClass.findFunctionByNameAndKind(name, JSFunction.FunctionKind.GETTER);
if(result == null)
{
result = jsClass.findFunctionByNameAndKind(name, JSFunction.FunctionKind.SETTER);
}
return result;
}
private static PsiElement findMethod(JSClass jsClass, String name)
{
PsiElement result = jsClass.findFunctionByNameAndKind(name, JSFunction.FunctionKind.CONSTRUCTOR);
if(result == null)
{
result = jsClass.findFunctionByNameAndKind(name, JSFunction.FunctionKind.SIMPLE);
}
return result;
}
@Override
@Nullable
public PsiComment findExistingDocComment(PsiComment contextElement)
{
return contextElement;
}
@Nullable
@Override
public Pair<PsiElement, PsiComment> parseContext(@NotNull PsiElement element)
{
return null;
}
@Override
@Nullable
public String generateDocumentationContentStub(PsiComment contextComment)
{
for(PsiElement el = contextComment.getParent(); el != null; el = el.getNextSibling())
{
if(el instanceof JSProperty)
{
final JSExpression propertyValue = ((JSProperty) el).getValue();
if(propertyValue instanceof JSFunction)
{
return doGenerateDoc((JSFunction) propertyValue);
}
}
else if(el instanceof JSFunction)
{
final JSFunction function = ((JSFunction) el);
return doGenerateDoc(function);
}
else if(el instanceof JSExpressionStatement)
{
final JSExpression expression = ((JSExpressionStatement) el).getExpression();
if(expression instanceof JSAssignmentExpression)
{
final JSExpression rOperand = ((JSAssignmentExpression) expression).getROperand();
if(rOperand instanceof JSFunctionExpression)
{
return doGenerateDoc(((JSFunctionExpression) rOperand).getFunction());
}
}
}
else if(el instanceof JSVarStatement)
{
JSVariable[] variables = ((JSVarStatement) el).getVariables();
if(variables.length > 0)
{
JSExpression expression = variables[0].getInitializer();
if(expression instanceof JSFunctionExpression)
{
return doGenerateDoc(((JSFunctionExpression) expression).getFunction());
}
}
break;
}
}
return null;
}
private static String doGenerateDoc(final JSFunction function)
{
StringBuilder builder = new StringBuilder();
final JSParameterList parameterList = function.getParameterList();
final PsiFile containingFile = function.getContainingFile();
final boolean ecma = containingFile.getLanguage() == JavaScriptSupportLoader.ECMA_SCRIPT_L4;
if(parameterList != null)
{
for(JSParameter parameter : parameterList.getParameters())
{
builder.append("* @param ").append(parameter.getName());
//String s = JSPsiImplUtils.getTypeFromDeclaration(parameter);
//if (s != null) builder.append(" : ").append(s);
builder.append("\n");
}
}
if(ecma)
{
String s = JSPsiImplUtils.getTypeFromDeclaration(function);
if(s != null && !"void".equals(s))
{
builder.append("* @return ");
//builder.append(s);
builder.append("\n");
}
}
return builder.toString();
}
@Nullable
protected static String getSeeAlsoLinkResolved(PsiElement originElement, String link)
{
JSQualifiedNamedElement qualifiedElement = findParentQualifiedElement(originElement);
if(qualifiedElement == null)
{
return null;
}
String linkToResolve = getLinkToResolve(qualifiedElement, link);
final PsiElement resolvedElement = getDocumentationElementForLinkStatic(originElement.getManager(), linkToResolve, originElement);
if(resolvedElement != null)
{
return linkToResolve;
}
return null;
}
private static String getLinkToResolve(JSQualifiedNamedElement origin, String link)
{
String originQname = origin.getQualifiedName();
if(link.length() == 0)
{
return originQname;
}
else if(StringUtil.startsWithChar(link, '#'))
{
if(origin instanceof JSClass)
{
return originQname + "." + link.substring(1);
}
else
{
String aPackage = StringUtil.getPackageName(originQname);
return aPackage + "." + link.substring(1);
}
}
else
{
String linkFile = link.contains("#") ? link.substring(0, link.lastIndexOf('#')) : link;
String linkAnchor = link.contains("#") ? link.substring(link.lastIndexOf('#') + 1) : null;
final String qname;
if(StringUtil.endsWithIgnoreCase(linkFile, HTML_EXTENSION))
{
String prefix = StringUtil.getPackageName(originQname);
while(linkFile.startsWith("../"))
{
linkFile = linkFile.substring("../".length());
prefix = StringUtil.getPackageName(prefix);
}
String linkFilename;
if(linkFile.endsWith(PACKAGE_FILE))
{
linkFilename = StringUtil.trimEnd(linkFile, PACKAGE_FILE);
linkFilename = StringUtil.trimEnd(linkFilename, "/");
}
else
{
linkFilename = linkFile.substring(0, linkFile.lastIndexOf("."));
}
if(linkFilename.length() > 0)
{
qname = (prefix.length() > 0 ? prefix + "." : prefix) + linkFilename.replaceAll("/", ".");
}
else
{
qname = prefix;
}
}
else
{
qname = linkFile;
}
return linkAnchor != null ? (qname.length() > 0 ? qname + "." : qname) + linkAnchor : qname;
}
}
@Nullable
protected static JSQualifiedNamedElement findParentQualifiedElement(PsiElement element)
{
if(element instanceof JSClass)
{
return (JSClass) element;
}
if(element instanceof JSFunction || element instanceof JSVariable)
{
final PsiElement parent = JSResolveUtil.findParent(element);
if(parent instanceof JSClass)
{
return (JSClass) parent;
}
else if(parent instanceof JSFile)
{
return (JSQualifiedNamedElement) element;
}
}
JSAttribute attribute = null;
if(element instanceof JSAttribute)
{
attribute = (JSAttribute) element;
}
else if(element instanceof JSAttributeNameValuePair)
{
attribute = (JSAttribute) element.getParent();
}
if(attribute != null && DOCUMENTED_ATTRIBUTES.containsKey(attribute.getName()))
{
final JSClass jsClass = PsiTreeUtil.getParentOfType(element, JSClass.class);
if(jsClass != null)
{
return jsClass;
}
}
return null;
}
}
| src/com/intellij/javascript/documentation/JSDocumentationProvider.java | /*
* Copyright 2000-2005 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.javascript.documentation;
import java.io.File;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import com.intellij.lang.ASTNode;
import com.intellij.lang.documentation.CodeDocumentationProvider;
import com.intellij.lang.documentation.DocumentationProvider;
import com.intellij.lang.javascript.JSTokenTypes;
import com.intellij.lang.javascript.JavaScriptSupportLoader;
import com.intellij.lang.javascript.index.JavaScriptIndex;
import com.intellij.lang.javascript.psi.*;
import com.intellij.lang.javascript.psi.impl.JSPsiImplUtils;
import com.intellij.lang.javascript.psi.resolve.BaseJSSymbolProcessor;
import com.intellij.lang.javascript.psi.resolve.JSImportHandlingUtil;
import com.intellij.lang.javascript.psi.resolve.JSResolveUtil;
import com.intellij.navigation.ItemPresentation;
import com.intellij.navigation.NavigationItem;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.PsiNamedElement;
import com.intellij.psi.PsiWhiteSpace;
import com.intellij.psi.ResolveResult;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlToken;
/**
* Created by IntelliJ IDEA.
* User: Maxim.Mossienko
* Date: Nov 4, 2005
* Time: 5:04:28 PM
*/
public class JSDocumentationProvider implements CodeDocumentationProvider
{
private DocumentationProvider cssProvider;
@NonNls
private static final String OBJECT_NAME = "Object";
protected static final String SEE_PLAIN_TEXT_CHARS = "\t \"-\\/<>*";
@NonNls
protected static final String PACKAGE = "package";
@NonNls
protected static final String HTML_EXTENSION = ".html";
@NonNls
protected static final String PACKAGE_FILE = PACKAGE + HTML_EXTENSION;
protected static final Map<String, String> DOCUMENTED_ATTRIBUTES;
static
{
DOCUMENTED_ATTRIBUTES = new HashMap<String, String>();
DOCUMENTED_ATTRIBUTES.put("Event", "event:");
DOCUMENTED_ATTRIBUTES.put("Style", "style:");
DOCUMENTED_ATTRIBUTES.put("Effect", "effect:");
}
private DocumentationProvider getCssProvider(Project project) throws Exception
{
if(cssProvider == null)
{
final Class<?> aClass = Class.forName("com.intellij.psi.css.impl.util.CssDocumentationProvider");
cssProvider = (DocumentationProvider) aClass.getConstructor(new Class[]{}).newInstance(new Object[]{});
}
return cssProvider;
}
@Nullable
public String getQuickNavigateInfo(PsiElement element, PsiElement element2)
{
if(element instanceof JSFunction)
{
final JSFunction function = (JSFunction) element;
final PsiElement parent = element.getParent();
if(function.isConstructor())
{
if(parent instanceof JSClass)
{
return createQuickNavigateForClazz((JSClass) parent);
}
}
return createQuickNavigateForFunction(function);
}
else if(element instanceof JSClass)
{
return createQuickNavigateForClazz((JSClass) element);
}
else if(element instanceof JSVariable)
{
return createQuickNavigateForVariable((JSVariable) element);
}
else if(element instanceof JSAttributeNameValuePair)
{
return createQuickNavigateForAnnotationDerived(element);
}
else if(element instanceof XmlToken)
{
BaseJSSymbolProcessor.TagContextBuilder builder = new BaseJSSymbolProcessor.TagContextBuilder(element, "XmlTag");
return StringUtil.stripQuotesAroundValue(element.getText()) + ":" + builder.typeName;
}
else if(element instanceof JSNamespaceDeclaration)
{
return createQuickNavigateForNamespace((JSNamespaceDeclaration) element);
}
return null;
}
private static String createQuickNavigateForAnnotationDerived(final PsiElement element)
{
final JSAttributeNameValuePair valuePair = (JSAttributeNameValuePair) element;
final JSAttribute parent = (JSAttribute) valuePair.getParent();
final StringBuilder builder = new StringBuilder();
final JSClass clazz = PsiTreeUtil.getParentOfType(valuePair, JSClass.class);
appendParentInfo(clazz != null ? clazz : parent.getContainingFile(), builder, parent);
builder.append(parent.getName()).append(" ").append(valuePair.getSimpleValue());
return builder.toString();
}
private static
@Nullable
String createQuickNavigateForFunction(final JSFunction function)
{
final PsiElement parent = JSResolveUtil.findParent(function);
final StringBuilder result = new StringBuilder();
appendParentInfo(parent, result, function);
appendAttrList(function, result);
final boolean get = function.isGetProperty();
final boolean set = function.isSetProperty();
result.append(get || set ? "property " : "function ");
result.append(function.getName());
if(!get && !set)
{
result.append('(');
final JSParameterList jsParameterList = function.getParameterList();
if(jsParameterList != null)
{
final int start = result.length();
for(JSParameter p : jsParameterList.getParameters())
{
if(start != result.length())
{
result.append(", ");
}
result.append(p.getName());
appendVarType(p, result);
}
}
result.append(')');
}
String varType = null;
if(get || !set)
{
varType = JSImportHandlingUtil.resolveTypeName(function.getReturnTypeString(), function);
}
else
{
final JSParameterList jsParameterList = function.getParameterList();
if(jsParameterList != null)
{
final JSParameter[] jsParameters = jsParameterList.getParameters();
if(jsParameters != null && jsParameters.length > 0)
{
varType = JSImportHandlingUtil.resolveTypeName(jsParameters[0].getTypeString(), function);
}
}
}
if(varType != null)
{
result.append(':').append(varType);
}
return result.toString();
}
private static void appendParentInfo(final PsiElement parent, final StringBuilder builder, PsiNamedElement element)
{
if(parent instanceof JSClass)
{
builder.append(((JSClass) parent).getQualifiedName()).append("\n");
}
else if(parent instanceof JSPackageStatement)
{
builder.append(((JSPackageStatement) parent).getQualifiedName()).append("\n");
}
else if(parent instanceof JSFile)
{
if(parent.getContext() != null)
{
final String mxmlPackage = JSResolveUtil.findPackageForMxml(parent);
if(mxmlPackage != null)
{
builder.append(mxmlPackage).append(mxmlPackage.length() > 0 ? "." : "").append(parent.getContext().getContainingFile().getName()).append("\n");
}
}
else
{
boolean foundQualified = false;
if(element instanceof JSNamedElement)
{
ASTNode node = ((JSNamedElement) element).findNameIdentifier();
if(node != null)
{
final String s = node.getText();
int i = s.lastIndexOf('.');
if(i != -1)
{
builder.append(s.substring(0, i)).append("\n");
foundQualified = true;
}
}
}
if(!foundQualified)
{
builder.append(parent.getContainingFile().getName()).append("\n");
}
}
}
}
private static
@Nullable
String createQuickNavigateForVariable(final JSVariable variable)
{
final PsiElement parent = JSResolveUtil.findParent(variable);
final StringBuilder result = new StringBuilder();
appendParentInfo(parent, result, variable);
appendAttrList(variable, result);
result.append(variable.isConst() ? "const " : "var ");
result.append(variable.getName());
appendVarType(variable, result);
final String s = variable.getInitializerText();
if(s != null)
{
result.append(" = ").append(s);
}
return result.toString();
}
private static void appendVarType(final JSVariable variable, final StringBuilder builder)
{
final String varType = variable.getTypeString();
if(varType != null)
{
builder.append(':').append(varType);
}
}
private static
@Nullable
String createQuickNavigateForClazz(final JSClass jsClass)
{
final String qName = jsClass.getQualifiedName();
if(qName == null)
{
return null;
}
StringBuilder result = new StringBuilder();
String packageName = StringUtil.getPackageName(qName);
if(packageName.length() > 0)
{
result.append(packageName).append("\n");
}
appendAttrList(jsClass, result);
if(jsClass.isInterface())
{
result.append("interface");
}
else
{
result.append("class");
}
final String name = jsClass.getName();
result.append(" ").append(name);
String s = generateReferenceTargetList(jsClass.getExtendsList(), packageName);
if(s == null && !OBJECT_NAME.equals(name))
{
s = OBJECT_NAME;
}
if(s != null)
{
result.append(" extends ").append(s);
}
s = generateReferenceTargetList(jsClass.getImplementsList(), packageName);
if(s != null)
{
result.append("\nimplements ").append(s);
}
return result.toString();
}
private static
@Nullable
String createQuickNavigateForNamespace(final JSNamespaceDeclaration ns)
{
final String qName = ns.getQualifiedName();
if(qName == null)
{
return null;
}
StringBuilder result = new StringBuilder();
String packageName = StringUtil.getPackageName(qName);
if(packageName.length() > 0)
{
result.append(packageName).append("\n");
}
result.append("namespace");
final String name = ns.getName();
result.append(" ").append(name);
String s = ns.getInitialValueString();
if(s != null)
{
result.append(" = ").append(s);
}
return result.toString();
}
private static void appendAttrList(final JSAttributeListOwner jsClass, final StringBuilder result)
{
final JSAttributeList attributeList = jsClass.getAttributeList();
if(attributeList != null)
{
if(attributeList.hasModifier(JSAttributeList.ModifierType.OVERRIDE))
{
result.append("override ");
}
JSAttributeList.AccessType type = attributeList.getAccessType();
String ns = attributeList.getNamespace();
if(type != JSAttributeList.AccessType.PACKAGE_LOCAL || ns == null)
{
result.append(type.toString().toLowerCase());
}
else
{
result.append(ns);
}
result.append(" ");
if(attributeList.hasModifier(JSAttributeList.ModifierType.STATIC))
{
result.append("static ");
}
if(attributeList.hasModifier(JSAttributeList.ModifierType.FINAL))
{
result.append("final ");
}
if(attributeList.hasModifier(JSAttributeList.ModifierType.DYNAMIC))
{
result.append("dynamic ");
}
if(attributeList.hasModifier(JSAttributeList.ModifierType.NATIVE))
{
result.append("native ");
}
}
}
private static
@Nullable
String generateReferenceTargetList(final @Nullable JSReferenceList implementsList, @NotNull String packageName)
{
if(implementsList == null)
{
return null;
}
StringBuilder result = null;
final String[] referenceExpressionTexts = implementsList.getReferenceTexts();
for(String refExprText : referenceExpressionTexts)
{
refExprText = JSImportHandlingUtil.resolveTypeName(refExprText, implementsList);
if(result == null)
{
result = new StringBuilder();
}
else
{
result.append(",");
}
final String referencedPackageName = StringUtil.getPackageName(refExprText);
result.append(referencedPackageName.equals(packageName) ? refExprText.substring(refExprText.lastIndexOf('.') + 1) : refExprText);
}
return result == null ? null : result.toString();
}
@Override
public List<String> getUrlFor(PsiElement element, PsiElement originalElement)
{
String possibleCssName = findPossibleCssName(element);
if(possibleCssName != null)
{
try
{
final DocumentationProvider documentationProvider = getCssProvider(element.getProject());
final Method method = documentationProvider.getClass().getMethod("getUrlFor", new Class[]{String.class});
final Object o = method.invoke(null, new Object[]{possibleCssName});
if(o instanceof String)
{
return Collections.singletonList((String) o);
}
}
catch(Exception e)
{
}
}
return null;
}
@Override
public String generateDoc(PsiElement _element, PsiElement originalElement)
{
if(_element instanceof JSReferenceExpression)
{
StringBuilder buffer = null;
// ambigious reference
final JSReferenceExpression expression = (JSReferenceExpression) _element;
for(ResolveResult r : expression.multiResolve(false))
{
if(buffer == null)
{
buffer = new StringBuilder();
}
final PsiElement element = r.getElement();
final ItemPresentation presentation = ((NavigationItem) element).getPresentation();
JSDocumentationUtils.appendHyperLinkToElement(element, expression.getReferencedName(), buffer, presentation.getPresentableText(),
presentation.getLocationString());
buffer.append("<br/>\n");
}
return buffer != null ? buffer.toString() : "have no idea :)";
}
_element = _element.getNavigationElement();
PsiElement element = findElementForWhichPreviousCommentWillBeSearched(_element);
final boolean parameterDoc = element instanceof JSParameter;
if(parameterDoc)
{
element = findElementForWhichPreviousCommentWillBeSearched(PsiTreeUtil.getParentOfType(element, JSFunction.class));
}
if(element != null)
{
PsiElement docComment = JSDocumentationUtils.findDocComment(element, _element instanceof JSAttributeNameValuePair ? originalElement : null);
if(docComment != null)
{
docComment = findFirstDocComment(docComment);
element = findTargetElement(_element, element);
final JSDocumentationBuilder builder = new JSDocumentationBuilder(element, originalElement);
JSDocumentationUtils.processDocumentationTextFromComment(docComment.getNode(), builder);
return parameterDoc ? builder.getParameterDoc(((JSParameter) _element).getName()) : builder.getDoc();
}
element = findTargetElement(_element, element);
if(element instanceof JSFunction)
{
ASTNode initialComment = JSDocumentationUtils.findLeadingCommentInFunctionBody(element);
if(initialComment != null)
{
final JSDocumentationBuilder builder = new JSDocumentationBuilder(element, originalElement);
JSDocumentationUtils.processDocumentationTextFromComment(initialComment, builder);
return builder.getDoc();
}
}
}
String possibleCssName = findPossibleCssName(_element);
if(possibleCssName != null)
{
try
{
final DocumentationProvider documentationProvider = getCssProvider(_element.getProject());
final Method declaredMethod = documentationProvider.getClass().getDeclaredMethod("generateDoc", String.class, PsiElement.class);
final Object o = declaredMethod.invoke(null, possibleCssName, null);
if(o instanceof String)
{
return (String) o;
}
}
catch(Exception e)
{
}
}
return null;
}
private static PsiElement findTargetElement(final PsiElement _element, PsiElement element)
{
if(_element instanceof JSDefinitionExpression)
{
final PsiElement parentElement = _element.getParent();
if(parentElement instanceof JSAssignmentExpression)
{
final JSExpression rOperand = ((JSAssignmentExpression) parentElement).getROperand();
if(rOperand instanceof JSFunctionExpression)
{
element = rOperand;
}
else
{
element = _element;
}
}
}
else if(_element instanceof JSFunctionExpression)
{
element = _element;
}
else if(_element instanceof JSProperty)
{
final JSExpression expression = ((JSProperty) _element).getValue();
if(expression instanceof JSFunction)
{
element = expression;
}
}
else if(_element instanceof JSVariable)
{
if(_element instanceof JSParameter)
{
return PsiTreeUtil.getParentOfType(_element, JSFunction.class);
}
element = _element;
}
else if(_element instanceof JSAttributeNameValuePair)
{
return _element;
}
return element;
}
private static PsiElement findFirstDocComment(PsiElement docComment)
{
if(docComment.getNode().getElementType() == JSTokenTypes.END_OF_LINE_COMMENT)
{
while(true)
{
PsiElement prev = docComment.getPrevSibling();
if(prev instanceof PsiWhiteSpace)
{
prev = prev.getPrevSibling();
}
if(prev == null)
{
break;
}
if(prev.getNode().getElementType() != JSTokenTypes.END_OF_LINE_COMMENT)
{
break;
}
docComment = prev;
}
}
return docComment;
}
private static String findPossibleCssName(PsiElement _element)
{
if(_element instanceof JSDefinitionExpression)
{
final JSExpression expression = ((JSDefinitionExpression) _element).getExpression();
if(expression instanceof JSReferenceExpression)
{
final String text = ((JSReferenceExpression) expression).getReferencedName();
if(text == null)
{
return null;
}
final StringBuffer buf = new StringBuffer(text.length());
for(int i = 0; i < text.length(); ++i)
{
final char ch = text.charAt(i);
if(Character.isUpperCase(ch))
{
buf.append('-').append(Character.toLowerCase(ch));
}
else
{
buf.append(ch);
}
}
return buf.toString();
}
}
return null;
}
@Override
public PsiElement getDocumentationElementForLookupItem(PsiManager psiManager, Object object, PsiElement element)
{
final PsiElement psiElement = findElementForWhichPreviousCommentWillBeSearched(object);
if(psiElement != null && JSDocumentationUtils.findDocComment(psiElement) != null)
{
return psiElement;
}
if(object instanceof PsiElement)
{
return (PsiElement) object;
}
return null;
}
public static PsiElement findElementForWhichPreviousCommentWillBeSearched(Object object)
{
if(object instanceof JSFunction)
{
PsiElement psiElement = (PsiElement) object;
PsiElement parent = psiElement.getParent();
if(parent instanceof JSNewExpression)
{
parent = parent.getParent();
}
if(parent instanceof JSProperty)
{
psiElement = parent;
}
else if(parent instanceof JSAssignmentExpression)
{
psiElement = parent.getParent();
}
JSFunction function = (JSFunction) object;
if(function.isSetProperty() || function.isGetProperty())
{
for(PsiElement el = function.getPrevSibling(); el != null; el = el.getPrevSibling())
{
if(!(el instanceof PsiWhiteSpace) && !(el instanceof PsiComment))
{
if(el instanceof JSFunction)
{
JSFunction prevFunction = (JSFunction) el;
String name = prevFunction.getName();
if(name != null &&
name.equals(function.getName()) &&
((prevFunction.isGetProperty() && function.isSetProperty()) || prevFunction.isSetProperty() && function.isGetProperty()))
{
PsiElement doc = JSDocumentationUtils.findDocComment(prevFunction);
if(doc != null)
{
return prevFunction;
}
}
}
break;
}
}
}
return psiElement;
}
else if(object instanceof JSProperty || object instanceof JSStatement || object instanceof JSClass)
{
return (PsiElement) object;
}
else if(object instanceof PsiElement)
{
final PsiElement parent = ((PsiElement) object).getParent();
if(parent instanceof JSAssignmentExpression)
{
return parent.getParent();
}
else if(parent instanceof JSVarStatement)
{
final PsiElement firstChild = parent.getFirstChild();
if(firstChild instanceof JSAttributeList)
{
if(JSDocumentationUtils.findDocComment((PsiElement) object) != null)
{
return (PsiElement) object;
}
}
return parent;
}
else if(parent instanceof JSAttribute)
{
final PsiElement grandParent = parent.getParent();
if(grandParent.getFirstChild() == parent)
{
final PsiElement element = grandParent.getParent();
if(element instanceof JSFile)
{
return grandParent;
}
return element;
}
return parent;
}
else if(parent instanceof JSSuppressionHolder)
{
return parent;
}
else
{
return (PsiElement) object;
}
}
return null;
}
@Override
@Nullable
public PsiElement getDocumentationElementForLink(final PsiManager psiManager, String link, final PsiElement context)
{
return getDocumentationElementForLinkStatic(psiManager, link, context);
}
@Nullable
private static PsiElement getDocumentationElementForLinkStatic(final PsiManager psiManager, String link, @NotNull PsiElement context)
{
final int delimiterIndex = link.lastIndexOf(':');
String attributeType = null;
String attributeName = null;
for(Map.Entry<String, String> e : DOCUMENTED_ATTRIBUTES.entrySet())
{
final String pattern = "." + e.getValue();
if(link.contains(pattern))
{
attributeType = e.getKey();
attributeName = link.substring(link.indexOf(pattern) + pattern.length());
link = link.substring(0, link.indexOf(pattern));
break;
}
}
if(delimiterIndex != -1 && attributeType == null)
{
final int delimiterIndex2 = link.lastIndexOf(':', delimiterIndex - 1);
String fileName = link.substring(0, delimiterIndex2).replace(File.separatorChar, '/');
String name = link.substring(delimiterIndex2 + 1, delimiterIndex);
int offset = Integer.parseInt(link.substring(delimiterIndex + 1));
return JavaScriptIndex.findSymbolByFileAndNameAndOffset(fileName, name, offset);
}
else if(attributeType != null)
{
PsiElement clazz = JSResolveUtil.findClassByQName(link, context.getResolveScope(), psiManager.getProject());
if(!(clazz instanceof JSClass))
{
return null;
}
return findNamedAttribute((JSClass) clazz, attributeType, attributeName);
}
else
{
PsiElement clazz = JSResolveUtil.findClassByQName(link, context.getResolveScope(), psiManager.getProject());
if(clazz == null && link.contains("."))
{
String qname = link.substring(0, link.lastIndexOf('.'));
clazz = JSResolveUtil.findClassByQName(qname, context.getResolveScope(), psiManager.getProject());
if(clazz instanceof JSClass)
{
JSClass jsClass = (JSClass) clazz;
String member = link.substring(link.lastIndexOf('.') + 1);
if(member.endsWith("()"))
{
member = member.substring(0, member.length() - 2);
PsiElement result = findMethod(jsClass, member);
if(result == null)
{
result = findProperty(jsClass, member); // user might refer to a property
}
return result;
}
else
{
PsiElement result = jsClass.findFieldByName(member);
if(result == null)
{
result = findProperty(jsClass, member);
}
if(result == null)
{
result = findMethod(jsClass, member); // user might forget brackets
}
return result;
}
}
}
if(clazz instanceof JSVariable)
{
return clazz;
}
if(link.endsWith("()"))
{
link = link.substring(0, link.length() - 2);
clazz = JSResolveUtil.findClassByQName(link, context.getResolveScope(), psiManager.getProject());
if(clazz instanceof JSFunction)
{
return clazz;
}
}
return clazz;
}
}
@Nullable
protected static JSAttributeNameValuePair findNamedAttribute(JSClass clazz, final String type, final String name)
{
final Ref<JSAttributeNameValuePair> attribute = new Ref<JSAttributeNameValuePair>();
JSResolveUtil.processMetaAttributesForClass(clazz, new JSResolveUtil.MetaDataProcessor()
{
@Override
public boolean process(@NotNull JSAttribute jsAttribute)
{
if(type.equals(jsAttribute.getName()))
{
final JSAttributeNameValuePair jsAttributeNameValuePair = jsAttribute.getValueByName("name");
if(jsAttributeNameValuePair != null && name.equals(jsAttributeNameValuePair.getSimpleValue()))
{
attribute.set(jsAttributeNameValuePair);
return false;
}
}
return true;
}
@Override
public boolean handleOtherElement(PsiElement el, PsiElement context, @Nullable Ref<PsiElement> continuePassElement)
{
return true;
}
});
return attribute.get();
}
private static PsiElement findProperty(JSClass jsClass, String name)
{
PsiElement result = jsClass.findFunctionByNameAndKind(name, JSFunction.FunctionKind.GETTER);
if(result == null)
{
result = jsClass.findFunctionByNameAndKind(name, JSFunction.FunctionKind.SETTER);
}
return result;
}
private static PsiElement findMethod(JSClass jsClass, String name)
{
PsiElement result = jsClass.findFunctionByNameAndKind(name, JSFunction.FunctionKind.CONSTRUCTOR);
if(result == null)
{
result = jsClass.findFunctionByNameAndKind(name, JSFunction.FunctionKind.SIMPLE);
}
return result;
}
@Override
@Nullable
public PsiComment findExistingDocComment(PsiComment contextElement)
{
return contextElement;
}
@Nullable
@Override
public Pair<PsiElement, PsiComment> parseContext(@NotNull PsiElement element)
{
return null;
}
@Override
@Nullable
public String generateDocumentationContentStub(PsiComment contextComment)
{
for(PsiElement el = contextComment.getParent(); el != null; el = el.getNextSibling())
{
if(el instanceof JSProperty)
{
final JSExpression propertyValue = ((JSProperty) el).getValue();
if(propertyValue instanceof JSFunction)
{
return doGenerateDoc((JSFunction) propertyValue);
}
}
else if(el instanceof JSFunction)
{
final JSFunction function = ((JSFunction) el);
return doGenerateDoc(function);
}
else if(el instanceof JSExpressionStatement)
{
final JSExpression expression = ((JSExpressionStatement) el).getExpression();
if(expression instanceof JSAssignmentExpression)
{
final JSExpression rOperand = ((JSAssignmentExpression) expression).getROperand();
if(rOperand instanceof JSFunctionExpression)
{
return doGenerateDoc(((JSFunctionExpression) rOperand).getFunction());
}
}
}
else if(el instanceof JSVarStatement)
{
JSVariable[] variables = ((JSVarStatement) el).getVariables();
if(variables.length > 0)
{
JSExpression expression = variables[0].getInitializer();
if(expression instanceof JSFunctionExpression)
{
return doGenerateDoc(((JSFunctionExpression) expression).getFunction());
}
}
break;
}
}
return null;
}
private static String doGenerateDoc(final JSFunction function)
{
StringBuilder builder = new StringBuilder();
final JSParameterList parameterList = function.getParameterList();
final PsiFile containingFile = function.getContainingFile();
final boolean ecma = containingFile.getLanguage() == JavaScriptSupportLoader.ECMA_SCRIPT_L4;
if(parameterList != null)
{
for(JSParameter parameter : parameterList.getParameters())
{
builder.append("* @param ").append(parameter.getName());
//String s = JSPsiImplUtils.getTypeFromDeclaration(parameter);
//if (s != null) builder.append(" : ").append(s);
builder.append("\n");
}
}
if(ecma)
{
String s = JSPsiImplUtils.getTypeFromDeclaration(function);
if(s != null && !"void".equals(s))
{
builder.append("* @return ");
//builder.append(s);
builder.append("\n");
}
}
return builder.toString();
}
@Nullable
protected static String getSeeAlsoLinkResolved(PsiElement originElement, String link)
{
JSQualifiedNamedElement qualifiedElement = findParentQualifiedElement(originElement);
if(qualifiedElement == null)
{
return null;
}
String linkToResolve = getLinkToResolve(qualifiedElement, link);
final PsiElement resolvedElement = getDocumentationElementForLinkStatic(originElement.getManager(), linkToResolve, originElement);
if(resolvedElement != null)
{
return linkToResolve;
}
return null;
}
private static String getLinkToResolve(JSQualifiedNamedElement origin, String link)
{
String originQname = origin.getQualifiedName();
if(link.length() == 0)
{
return originQname;
}
else if(StringUtil.startsWithChar(link, '#'))
{
if(origin instanceof JSClass)
{
return originQname + "." + link.substring(1);
}
else
{
String aPackage = StringUtil.getPackageName(originQname);
return aPackage + "." + link.substring(1);
}
}
else
{
String linkFile = link.contains("#") ? link.substring(0, link.lastIndexOf('#')) : link;
String linkAnchor = link.contains("#") ? link.substring(link.lastIndexOf('#') + 1) : null;
final String qname;
if(StringUtil.endsWithIgnoreCase(linkFile, HTML_EXTENSION))
{
String prefix = StringUtil.getPackageName(originQname);
while(linkFile.startsWith("../"))
{
linkFile = linkFile.substring("../".length());
prefix = StringUtil.getPackageName(prefix);
}
String linkFilename;
if(linkFile.endsWith(PACKAGE_FILE))
{
linkFilename = StringUtil.trimEnd(linkFile, PACKAGE_FILE);
linkFilename = StringUtil.trimEnd(linkFilename, "/");
}
else
{
linkFilename = linkFile.substring(0, linkFile.lastIndexOf("."));
}
if(linkFilename.length() > 0)
{
qname = (prefix.length() > 0 ? prefix + "." : prefix) + linkFilename.replaceAll("/", ".");
}
else
{
qname = prefix;
}
}
else
{
qname = linkFile;
}
return linkAnchor != null ? (qname.length() > 0 ? qname + "." : qname) + linkAnchor : qname;
}
}
@Nullable
protected static JSQualifiedNamedElement findParentQualifiedElement(PsiElement element)
{
if(element instanceof JSClass)
{
return (JSClass) element;
}
if(element instanceof JSFunction || element instanceof JSVariable)
{
final PsiElement parent = JSResolveUtil.findParent(element);
if(parent instanceof JSClass)
{
return (JSClass) parent;
}
else if(parent instanceof JSFile)
{
return (JSQualifiedNamedElement) element;
}
}
JSAttribute attribute = null;
if(element instanceof JSAttribute)
{
attribute = (JSAttribute) element;
}
else if(element instanceof JSAttributeNameValuePair)
{
attribute = (JSAttribute) element.getParent();
}
if(attribute != null && DOCUMENTED_ATTRIBUTES.containsKey(attribute.getName()))
{
final JSClass jsClass = PsiTreeUtil.getParentOfType(element, JSClass.class);
if(jsClass != null)
{
return jsClass;
}
}
return null;
}
}
| better quick doc for variables, dont need generate doc for whole monitor
| src/com/intellij/javascript/documentation/JSDocumentationProvider.java | better quick doc for variables, dont need generate doc for whole monitor | <ide><path>rc/com/intellij/javascript/documentation/JSDocumentationProvider.java
<ide> import org.jetbrains.annotations.NonNls;
<ide> import org.jetbrains.annotations.NotNull;
<ide> import org.jetbrains.annotations.Nullable;
<add>import org.mustbe.consulo.RequiredReadAction;
<ide> import com.intellij.lang.ASTNode;
<ide> import com.intellij.lang.documentation.CodeDocumentationProvider;
<ide> import com.intellij.lang.documentation.DocumentationProvider;
<ide> }
<ide> }
<ide>
<del> private static
<del> @Nullable
<del> String createQuickNavigateForVariable(final JSVariable variable)
<add> @Nullable
<add> @RequiredReadAction
<add> private static String createQuickNavigateForVariable(final JSVariable variable)
<ide> {
<ide> final PsiElement parent = JSResolveUtil.findParent(variable);
<ide> final StringBuilder result = new StringBuilder();
<ide> result.append(variable.isConst() ? "const " : "var ");
<ide> result.append(variable.getName());
<ide> appendVarType(variable, result);
<del> final String s = variable.getInitializerText();
<del> if(s != null)
<del> {
<del> result.append(" = ").append(s);
<add>
<add> JSExpression initializer = variable.getInitializer();
<add> if(initializer != null)
<add> {
<add> result.append(" = ");
<add> if(initializer instanceof JSLiteralExpression)
<add> {
<add> result.append(initializer.getText());
<add> }
<add> else if(initializer instanceof JSObjectLiteralExpression)
<add> {
<add> result.append("{...}");
<add> }
<add> else
<add> {
<add> result.append("...");
<add> }
<ide> }
<ide> return result.toString();
<ide> } |
|
Java | mit | 95ce4c4d27673b7c07c117699a7f3e208946c5fe | 0 | DMDirc/DMDirc,DMDirc/DMDirc,csmith/DMDirc,greboid/DMDirc,ShaneMcC/DMDirc-Client,greboid/DMDirc,csmith/DMDirc,DMDirc/DMDirc,csmith/DMDirc,greboid/DMDirc,DMDirc/DMDirc,greboid/DMDirc,ShaneMcC/DMDirc-Client,ShaneMcC/DMDirc-Client,ShaneMcC/DMDirc-Client,csmith/DMDirc | /*
* Copyright (c) 2006-2007 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package uk.org.ownage.dmdirc;
import java.awt.Color;
import java.beans.PropertyVetoException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JInternalFrame;
import javax.swing.SwingUtilities;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
import uk.org.ownage.dmdirc.commandparser.CommandManager;
import uk.org.ownage.dmdirc.commandparser.CommandWindow;
import uk.org.ownage.dmdirc.logger.ErrorLevel;
import uk.org.ownage.dmdirc.logger.Logger;
import uk.org.ownage.dmdirc.parser.ChannelClientInfo;
import uk.org.ownage.dmdirc.parser.ChannelInfo;
import uk.org.ownage.dmdirc.parser.ClientInfo;
import uk.org.ownage.dmdirc.parser.IRCParser;
import uk.org.ownage.dmdirc.parser.callbacks.CallbackManager;
import uk.org.ownage.dmdirc.parser.callbacks.CallbackNotFound;
import uk.org.ownage.dmdirc.parser.callbacks.interfaces.IChannelAction;
import uk.org.ownage.dmdirc.parser.callbacks.interfaces.IChannelGotNames;
import uk.org.ownage.dmdirc.parser.callbacks.interfaces.IChannelJoin;
import uk.org.ownage.dmdirc.parser.callbacks.interfaces.IChannelKick;
import uk.org.ownage.dmdirc.parser.callbacks.interfaces.IChannelMessage;
import uk.org.ownage.dmdirc.parser.callbacks.interfaces.IChannelModeChanged;
import uk.org.ownage.dmdirc.parser.callbacks.interfaces.IChannelNickChanged;
import uk.org.ownage.dmdirc.parser.callbacks.interfaces.IChannelPart;
import uk.org.ownage.dmdirc.parser.callbacks.interfaces.IChannelQuit;
import uk.org.ownage.dmdirc.parser.callbacks.interfaces.IChannelTopic;
import uk.org.ownage.dmdirc.parser.callbacks.interfaces.IChannelUserModeChanged;
import uk.org.ownage.dmdirc.ui.ChannelFrame;
import uk.org.ownage.dmdirc.ui.MainFrame;
import uk.org.ownage.dmdirc.ui.input.TabCompleter;
import uk.org.ownage.dmdirc.ui.messages.ColourManager;
import uk.org.ownage.dmdirc.ui.messages.Formatter;
import uk.org.ownage.dmdirc.ui.messages.Styliser;
/**
* The Channel class represents the client's view of the channel. It handles
* callbacks for channel events from the parser, maintains the corresponding
* ChannelFrame, and handles user input to a ChannelFrame.
* @author chris
*/
public class Channel implements IChannelMessage, IChannelGotNames, IChannelTopic,
IChannelJoin, IChannelPart, IChannelKick, IChannelQuit, IChannelAction,
IChannelNickChanged, IChannelModeChanged, IChannelUserModeChanged,
InternalFrameListener, FrameContainer {
/** The parser's pChannel class. */
private ChannelInfo channelInfo;
/** The server this channel is on. */
private Server server;
/** The ChannelFrame used for this channel. */
private ChannelFrame frame;
/**
* The tabcompleter used for this channel.
*/
private TabCompleter tabCompleter;
/**
* The icon being used for this channel.
*/
private ImageIcon imageIcon;
/**
* Creates a new instance of Channel.
* @param newServer The server object that this channel belongs to
* @param newChannelInfo The parser's channel object that corresponds to this channel
*/
public Channel(final Server newServer, final ChannelInfo newChannelInfo) {
channelInfo = newChannelInfo;
server = newServer;
final ClassLoader cldr = this.getClass().getClassLoader();
final URL imageURL = cldr.getResource("uk/org/ownage/dmdirc/res/channel.png");
imageIcon = new ImageIcon(imageURL);
tabCompleter = new TabCompleter(server.getTabCompleter());
tabCompleter.addEntries(CommandManager.getChannelCommandNames());
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
frame = new ChannelFrame(Channel.this);
MainFrame.getMainFrame().addChild(frame);
frame.addInternalFrameListener(Channel.this);
frame.setFrameIcon(imageIcon);
frame.setTabCompleter(tabCompleter);
}
});
} catch (InvocationTargetException ex) {
Logger.error(ErrorLevel.FATAL, ex);
} catch (InterruptedException ex) {
Logger.error(ErrorLevel.FATAL, ex);
}
try {
final CallbackManager callbackManager = server.getParser().getCallbackManager();
final String channel = channelInfo.getName();
callbackManager.addCallback("OnChannelGotNames", this, channel);
callbackManager.addCallback("OnChannelTopic", this, channel);
callbackManager.addCallback("OnChannelMessage", this, channel);
callbackManager.addCallback("OnChannelJoin", this, channel);
callbackManager.addCallback("OnChannelPart", this, channel);
callbackManager.addCallback("OnChannelQuit", this, channel);
callbackManager.addCallback("OnChannelKick", this, channel);
callbackManager.addCallback("OnChannelAction", this, channel);
callbackManager.addCallback("OnChannelNickChanged", this, channel);
callbackManager.addCallback("OnChannelModeChanged", this, channel);
callbackManager.addCallback("OnChannelUserModeChanged", this, channel);
} catch (CallbackNotFound ex) {
Logger.error(ErrorLevel.FATAL, ex);
}
updateTitle();
selfJoin();
}
/**
* Shows this channel's frame.
*/
public void show() {
frame.open();
}
/**
* Sends the specified line as a message to the channel that this object
* represents.
* @param line The message to send
*/
public void sendLine(final String line) {
channelInfo.sendMessage(line);
final ClientInfo me = server.getParser().getMyself();
final String modes = channelInfo.getUser(me).getImportantModePrefix();
frame.addLine("channelSelfMessage", modes, me.getNickname(), me.getIdent(),
me.getHost(), line, channelInfo);
sendNotification();
}
/**
* Sends the specified string as an action (CTCP) to the channel that this object
* represents.
* @param action The action to send
*/
public void sendAction(final String action) {
channelInfo.sendAction(action);
final ClientInfo me = server.getParser().getMyself();
final String modes = channelInfo.getUser(me).getImportantModePrefix();
frame.addLine("channelSelfAction", modes, me.getNickname(), me.getIdent(),
me.getHost(), action, channelInfo);
sendNotification();
}
/**
* Returns the server object that this channel belongs to.
* @return The server object
*/
public Server getServer() {
return server;
}
/**
* Returns the parser's ChannelInfo object that this object is associated with.
* @return The ChannelInfo object associated with this object
*/
public ChannelInfo getChannelInfo() {
return channelInfo;
}
/**
* Sets this object's ChannelInfo reference to the one supplied. This only needs
* to be done if the channel window (and hence this channel object) has stayed
* open while the user has been out of the channel.
* @param newChannelInfo The new ChannelInfo object
*/
public void setChannelInfo(final ChannelInfo newChannelInfo) {
channelInfo = newChannelInfo;
}
/**
* Returns the internal frame belonging to this object
* @return This object's internal frame
*/
public CommandWindow getFrame() {
return frame;
}
/**
* Called when we join this channel. Just needs to output a message.
*/
public void selfJoin() {
final ClientInfo me = server.getParser().getMyself();
frame.addLine("channelSelfJoin", "", me.getNickname(), me.getIdent(),
me.getHost(), channelInfo.getName());
sendNotification();
}
/**
* Updates the title of the channel frame, and of the main frame if appropriate.
*/
private void updateTitle() {
final String title = Styliser.stipControlCodes(channelInfo.getName()
+ " - " + channelInfo.getTopic());
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.setTitle(title);
if (frame.isMaximum() && frame.equals(MainFrame.getMainFrame().getActiveFrame())) {
MainFrame.getMainFrame().setTitle(MainFrame.getMainFrame().getTitlePrefix() + " - " + title);
}
}
});
}
/**
* Joins the specified channel. This only makes sense if used after a call to
* part().
*/
public void join() {
server.getParser().joinChannel(channelInfo.getName());
}
/**
* Parts this channel with the specified message. Parting does NOT close the
* channel window.
* @param reason The reason for parting the channel
*/
public void part(final String reason) {
server.getParser().partChannel(channelInfo.getName(), reason);
}
/**
* Parts the channel and then closes the frame.
*/
public void close() {
part(Config.getOption("general", "partmessage"));
closeWindow();
}
/**
* Closes the window without parting the channel.
*/
public void closeWindow() {
final CallbackManager callbackManager = server.getParser().getCallbackManager();
callbackManager.delCallback("OnChannelMessage", this);
callbackManager.delCallback("OnChannelTopic", this);
callbackManager.delCallback("OnChannelGotNames", this);
callbackManager.delCallback("OnChannelJoin", this);
callbackManager.delCallback("OnChannelPart", this);
callbackManager.delCallback("OnChannelQuit", this);
callbackManager.delCallback("OnChannelKick", this);
callbackManager.delCallback("OnChannelAction", this);
callbackManager.delCallback("OnChannelNickChanged", this);
callbackManager.delCallback("OnChannelModeChanged", this);
callbackManager.delCallback("OnChannelUserModeChanged", this);
server.delChannel(channelInfo.getName());
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.setVisible(false);
MainFrame.getMainFrame().delChild(frame);
frame = null;
server = null;
}
});
}
/**
* Determines if the specified frame is owned by this object.
*
* @param target JInternalFrame to check ownership of
* @return boolean whether this object owns the specified frame
*/
public boolean ownsFrame(final JInternalFrame target) {
return frame.equals(target);
}
/**
* Called whenever a message is sent to this channel. NB that the ChannelClient
* passed may be null if the message was not sent by a client on the channel
* (i.e., it was sent by a server, or a client outside of the channel). In these
* cases the full host is used instead.
* @param tParser A reference to the IRC Parser for this server
* @param cChannel A reference to the ChannelInfo object for this channel
* @param cChannelClient A reference to the ChannelClient object that sent the message
* @param sMessage The message that was sent
* @param sHost The full host of the sender.
*/
public void onChannelMessage(final IRCParser tParser, final ChannelInfo cChannel,
final ChannelClientInfo cChannelClient, final String sMessage, final String sHost) {
final String[] parts = ClientInfo.parseHostFull(sHost);
final String modes = getModes(cChannelClient, sHost);
String type = "channelMessage";
if (parts[0].equals(tParser.getMyself().getNickname())) {
type = "channelSelfExternalMessage";
}
frame.addLine(type, modes, parts[0], parts[1], parts[2], sMessage, cChannel);
sendNotification();
}
/**
* Called when an action is sent to the channel.
* @param tParser A reference to the IRC Parser for this server
* @param cChannel A reference to the ChannelInfo object for this channel
* @param cChannelClient A reference to the client that sent the action
* @param sMessage The text of the action
* @param sHost The host of the performer (lest it wasn't an actual client)
*/
public void onChannelAction(final IRCParser tParser, final ChannelInfo cChannel,
final ChannelClientInfo cChannelClient, final String sMessage, final String sHost) {
final String[] parts = ClientInfo.parseHostFull(sHost);
final String modes = getModes(cChannelClient, sHost);
String type = "channelAction";
if (parts[0].equals(tParser.getMyself().getNickname())) {
type = "channelSelfExternalAction";
}
frame.addLine(type, modes, parts[0], parts[1], parts[2], sMessage, cChannel);
sendNotification();
}
/**
* Called when the parser receives a NAMES reply from the server. This means that
* the nicklist in the ChannelFrame needs to be updated.
* @param tParser A reference to the IRC Parser for this server
* @param cChannel A reference to the ChannelInfo object for this channel
*/
public void onChannelGotNames(final IRCParser tParser, final ChannelInfo cChannel) {
frame.updateNames(channelInfo.getChannelClients());
final ArrayList<String> names = new ArrayList<String>();
for (ChannelClientInfo channelClient : cChannel.getChannelClients()) {
names.add(channelClient.getNickname());
}
tabCompleter.replaceEntries(names);
tabCompleter.addEntries(CommandManager.getChannelCommandNames());
}
/**
* Called when the channel topic is changed. Changes the title of the channel
* frame, and also of the main frame if the channel is maximised and active.
* @param tParser A reference to the IRC Parser for this server
* @param cChannel A reference to the ChannelInfo object for this channel
* @param bIsJoinTopic Whether this is the topic received when we joined the
* channel or not
*/
public void onChannelTopic(final IRCParser tParser, final ChannelInfo cChannel,
final boolean bIsJoinTopic) {
if (bIsJoinTopic) {
frame.addLine("channelJoinTopic", cChannel.getTopic(),
cChannel.getTopicUser(), 1000 * cChannel.getTopicTime(), cChannel);
} else {
final ChannelClientInfo user = cChannel.getUser(cChannel.getTopicUser());
final String[] parts = ClientInfo.parseHostFull(cChannel.getTopicUser());
final String modes = getModes(user, cChannel.getTopicUser());
final String topic = cChannel.getTopic();
frame.addLine("channelTopicChange", modes, parts[0], parts[1], parts[2], topic, cChannel);
}
sendNotification();
updateTitle();
}
/**
* Called when a new client joins the channel. Adds the client to the listbox
* in the channel frame.
* @param tParser A reference to the IRC Parser for this server
* @param cChannel A reference to the ChannelInfo object for this channel
* @param cChannelClient The client that has just joined
*/
public void onChannelJoin(final IRCParser tParser, final ChannelInfo cChannel,
final ChannelClientInfo cChannelClient) {
final ClientInfo client = cChannelClient.getClient();
frame.addLine("channelJoin", "", client.getNickname(), client.getIdent(),
client.getHost(), cChannel);
frame.addName(cChannelClient);
tabCompleter.addEntry(cChannelClient.getNickname());
sendNotification();
}
/**
* Called when a client parts the channel. Removes the client from the listbox
* in the channel frame.
* @param tParser A reference to the IRC Parser for this server
* @param cChannel A reference to the ChannelInfo object for this channel
* @param cChannelClient The client that just parted
* @param sReason The reason specified when the client parted
*/
public void onChannelPart(final IRCParser tParser, final ChannelInfo cChannel,
final ChannelClientInfo cChannelClient, final String sReason) {
final ClientInfo client = cChannelClient.getClient();
final String nick = cChannelClient.getNickname();
final String ident = client.getIdent();
final String host = client.getHost();
final String modes = cChannelClient.getImportantModePrefix();
if (nick.equals(tParser.getMyself().getNickname())) {
if (sReason.equals("")) {
frame.addLine("channelSelfPart", modes, nick, ident, host, cChannel);
} else {
frame.addLine("channelSelfPartReason", modes, nick, ident, host, cChannel, sReason);
}
} else {
if (sReason.equals("")) {
frame.addLine("channelPart", modes, nick, ident, host, cChannel);
} else {
frame.addLine("channelPartReason", modes, nick, ident, host, sReason, cChannel);
}
}
frame.removeName(cChannelClient);
tabCompleter.removeEntry(cChannelClient.getNickname());
sendNotification();
}
/**
* Called when a client is kicked from the channel. The victim is removed
* from the channelframe's listbox.
* @param tParser A reference to the IRC Parser for this server
* @param cChannel A reference to the ChannelInfo object for this channel
* @param cKickedClient A reference to the client that was kicked
* @param cKickedByClient A reference to the client that did the kicking
* @param sReason The reason specified in the kick message
* @param sKickedByHost The host of the kicker (in case it wasn't an actual client)
*/
public void onChannelKick(final IRCParser tParser, final ChannelInfo cChannel,
final ChannelClientInfo cKickedClient, final ChannelClientInfo cKickedByClient,
final String sReason, final String sKickedByHost) {
final String[] kicker = ClientInfo.parseHostFull(sKickedByHost);
final String kickermodes = getModes(cKickedByClient, sKickedByHost);
final String victim = cKickedClient.getNickname();
final String victimmodes = cKickedClient.getImportantModePrefix();
final String victimident = cKickedClient.getClient().getIdent();
final String victimhost = cKickedClient.getClient().getHost();
if (sReason.equals("")) {
frame.addLine("channelKick", kickermodes, kicker[0], kicker[1], kicker[2], victimmodes,
victim, victimident, victimhost, cChannel.getName());
} else {
frame.addLine("channelKickReason", kickermodes, kicker[0], kicker[1], kicker[2], victimmodes,
victim, victimident, victimhost, sReason, cChannel.getName());
}
frame.removeName(cKickedClient);
tabCompleter.removeEntry(cKickedClient.getNickname());
sendNotification();
}
/**
* Called when a client that was present on this channel has disconnected
* from the IRC server (or been netsplit).
* @param tParser A reference to the IRC Parser for this server
* @param cChannel A reference to the ChannelInfo object for this channel
* @param cChannelClient A reference to the client that has quit
* @param sReason The reason specified in the client's quit message
*/
public void onChannelQuit(final IRCParser tParser, final ChannelInfo cChannel,
final ChannelClientInfo cChannelClient, final String sReason) {
final ClientInfo client = cChannelClient.getClient();
final String source = cChannelClient.getNickname();
final String modes = cChannelClient.getImportantModePrefix();
if (sReason.equals("")) {
frame.addLine("channelQuit", modes, source, client.getIdent(),
client.getHost(), cChannel);
} else {
frame.addLine("channelQuitReason", modes, source, client.getIdent(),
client.getHost(), sReason, cChannel);
}
frame.removeName(cChannelClient);
sendNotification();
}
/**
* Called when someone on the channel changes their nickname.
* @param tParser A reference to the IRC parser for this server
* @param cChannel A reference to the CHannelInfo object for this channel
* @param cChannelClient The client that changed nickname
* @param sOldNick The old nickname of the client
*/
public void onChannelNickChanged(final IRCParser tParser, final ChannelInfo cChannel,
final ChannelClientInfo cChannelClient, final String sOldNick) {
final String modes = cChannelClient.getImportantModePrefix();
final String nick = cChannelClient.getNickname();
final String ident = cChannelClient.getClient().getIdent();
final String host = cChannelClient.getClient().getHost();
String type = "channelNickChange";
if (nick.equals(tParser.getMyself().getNickname())) {
type = "channelSelfNickChange";
}
frame.addLine(type, modes, sOldNick, ident, host, nick, cChannel);
sendNotification();
}
/**
* Called when modes are changed on the channel.
* @param tParser A reference to the IRC parser for this server
* @param cChannel A reference to the ChannelInfo object for this channel
* @param cChannelClient The client that set the modes
* @param sHost the host of the client that set the modes
* @param sModes the modes that were set
*/
public void onChannelModeChanged(final IRCParser tParser, final ChannelInfo cChannel,
final ChannelClientInfo cChannelClient, final String sHost, final String sModes) {
if (sHost.equals("")) {
frame.addLine("channelModeDiscovered", sModes, cChannel.getName());
} else {
final String modes = getModes(cChannelClient, sHost);
final String[] details = getDetails(cChannelClient, sHost);
final String myNick = tParser.getMyself().getNickname();
String type = "channelModeChange";
if (cChannelClient != null && myNick.equals(cChannelClient.getNickname())) {
type = "channelSelfModeChange";
}
frame.addLine(type, modes, details[0], details[1],
details[2], sModes, cChannel.getName());
}
frame.updateNames();
sendNotification();
}
/**
* Called when a mode has been changed on a user. Used for custom mode
* formats.
* @param tParser A reference to the IRC parser for this server
* @param cChannel A reference to the ChannelInfo object for this channel
* @param cChangedClient The client whose mode was changed
* @param cSetByClient The client who made the change
* @param sHost The hostname of the setter
* @param sMode The mode that has been changed
*/
public void onChannelUserModeChanged(final IRCParser tParser,
final ChannelInfo cChannel, final ChannelClientInfo cChangedClient,
final ChannelClientInfo cSetByClient, final String sHost,
final String sMode) {
if (Boolean.parseBoolean(Config.getOption("channel", "splitusermodes"))) {
final String sourceModes = getModes(cSetByClient, sHost);
final String[] sourceHost = getDetails(cSetByClient, sHost);
final String targetModes = cChangedClient.getImportantModePrefix();
final String targetNick = cChangedClient.getClient().getNickname();
final String targetIdent = cChangedClient.getClient().getIdent();
final String targetHost = cChangedClient.getClient().getHost();
String format = "channelUserMode_" + sMode;
if (!Formatter.hasFormat(format)) {
format = "channelUserMode_default";
}
frame.addLine(format, sourceModes, sourceHost[0], sourceHost[1],
sourceHost[2], targetModes, targetNick, targetIdent,
targetHost, sMode, cChannel);
}
}
/**
* Returns a string containing the most important mode for the specified client.
* @param channelClient The channel client to check.
* @param host The hostname to check if the channel client doesn't exist
* @return A string containing the most important mode, or an empty string
* if there are no (known) modes.
*/
private String getModes(final ChannelClientInfo channelClient, final String host) {
if (channelClient == null) {
return "";
} else {
return channelClient.getImportantModePrefix();
}
}
/**
* Returns a string containing the nickname, or other appropriate portion
* of the host for displaying (e.g. server name).
* @param channelClient The channel client to check
* @param host The hostname to check if the channel client doesn't exist
* @return A string containing a displayable name
*/
private String getNick(final ChannelClientInfo channelClient, final String host) {
if (channelClient == null) {
return ClientInfo.parseHost(host);
} else {
return channelClient.getNickname();
}
}
/**
* Returns a string[] containing the nickname/ident/host of the client, or
* server, where applicable.
* @param channelClient The channel client to check
* @param host The hostname to check if the channel client doesn't exist
* @return A string[] containing displayable components
*/
private String[] getDetails(final ChannelClientInfo channelClient, final String host) {
if (channelClient == null) {
return ClientInfo.parseHostFull(host);
} else {
String[] res = new String[3];
res[0] = channelClient.getNickname();
res[1] = channelClient.getClient().getIdent();
res[2] = channelClient.getClient().getHost();
return res;
}
}
/**
* Called when the channel frame is opened. Checks config settings to
* determine if the window should be maximised.
* @param internalFrameEvent The event that triggered this callback
*/
public void internalFrameOpened(final InternalFrameEvent internalFrameEvent) {
final Boolean pref = Boolean.parseBoolean(Config.getOption("ui", "maximisewindows"));
if (pref.equals(Boolean.TRUE) || MainFrame.getMainFrame().getMaximised()) {
try {
frame.setMaximum(true);
} catch (PropertyVetoException ex) {
Logger.error(ErrorLevel.WARNING, ex);
}
}
}
/**
* Called when the channel frame is being closed. Has the parser part the
* channel, and frees all resources associated with the channel.
* @param internalFrameEvent The event that triggered this callback
*/
public void internalFrameClosing(final InternalFrameEvent internalFrameEvent) {
part(Config.getOption("general", "partmessage"));
close();
}
/**
* Called when the channel frame is actually closed. Not implemented.
* @param internalFrameEvent The event that triggered this callback
*/
public void internalFrameClosed(final InternalFrameEvent internalFrameEvent) {
}
/**
* Called when the channel frame is iconified. Not implemented.
* @param internalFrameEvent The event that triggered this callback
*/
public void internalFrameIconified(final InternalFrameEvent internalFrameEvent) {
}
/**
* Called when the channel frame is deiconified. Not implemented.
* @param internalFrameEvent The event that triggered this callback
*/
public void internalFrameDeiconified(final InternalFrameEvent internalFrameEvent) {
}
/**
* Called when the channel frame is activated. Maximises the frame if it
* needs to be.
* @param internalFrameEvent The event that triggered this callback
*/
public void internalFrameActivated(final InternalFrameEvent internalFrameEvent) {
if (MainFrame.getMainFrame().getMaximised()) {
try {
frame.setMaximum(true);
} catch (PropertyVetoException ex) {
Logger.error(ErrorLevel.WARNING, ex);
}
}
MainFrame.getMainFrame().getFrameManager().setSelected(this);
server.setActiveFrame(this);
clearNotification();
}
/**
* Called when the channel frame is deactivated. Not implemented.
* @param internalFrameEvent The event that triggered this callback
*/
public void internalFrameDeactivated(final InternalFrameEvent internalFrameEvent) {
}
/**
* Returns this channel's name.
* @return A string representation of this channel (i.e., its name)
*/
public String toString() {
return channelInfo.getName();
}
/**
* Requests that this object's frame be activated.
*/
public void activateFrame() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MainFrame.getMainFrame().setActiveFrame(frame);
}
});
}
/**
* Adds a line of text to the main text area of the channel frame.
* @param line The line to add
*/
public void addLine(final String line) {
frame.addLine(line);
}
/**
* Formats the specified arguments using the supplied message type, and
* outputs to the main text area.
* @param messageType the message type to use
* @param args the arguments to pass
*/
public void addLine(final String messageType, final Object... args) {
frame.addLine(messageType, args);
}
/**
* Retrieves the icon used by the channel frame.
* @return The channel frame's icon
*/
public ImageIcon getIcon() {
return imageIcon;
}
/**
* Sends a notification to the frame manager if this frame isn't active.
*/
public void sendNotification() {
JInternalFrame activeFrame = MainFrame.getMainFrame().getActiveFrame();
if (activeFrame != null && activeFrame.equals(frame)) {
final Color c = ColourManager.getColour(4);
MainFrame.getMainFrame().getFrameManager().showNotification(this, c);
}
}
/**
* Clears any outstanding notifications this frame has set.
*/
private void clearNotification() {
MainFrame.getMainFrame().getFrameManager().clearNotification(this);
}
}
| src/uk/org/ownage/dmdirc/Channel.java | /*
* Copyright (c) 2006-2007 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package uk.org.ownage.dmdirc;
import java.awt.Color;
import java.beans.PropertyVetoException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JInternalFrame;
import javax.swing.SwingUtilities;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
import uk.org.ownage.dmdirc.commandparser.CommandManager;
import uk.org.ownage.dmdirc.commandparser.CommandWindow;
import uk.org.ownage.dmdirc.logger.ErrorLevel;
import uk.org.ownage.dmdirc.logger.Logger;
import uk.org.ownage.dmdirc.parser.ChannelClientInfo;
import uk.org.ownage.dmdirc.parser.ChannelInfo;
import uk.org.ownage.dmdirc.parser.ClientInfo;
import uk.org.ownage.dmdirc.parser.IRCParser;
import uk.org.ownage.dmdirc.parser.callbacks.CallbackManager;
import uk.org.ownage.dmdirc.parser.callbacks.CallbackNotFound;
import uk.org.ownage.dmdirc.parser.callbacks.interfaces.IChannelAction;
import uk.org.ownage.dmdirc.parser.callbacks.interfaces.IChannelGotNames;
import uk.org.ownage.dmdirc.parser.callbacks.interfaces.IChannelJoin;
import uk.org.ownage.dmdirc.parser.callbacks.interfaces.IChannelKick;
import uk.org.ownage.dmdirc.parser.callbacks.interfaces.IChannelMessage;
import uk.org.ownage.dmdirc.parser.callbacks.interfaces.IChannelModeChanged;
import uk.org.ownage.dmdirc.parser.callbacks.interfaces.IChannelNickChanged;
import uk.org.ownage.dmdirc.parser.callbacks.interfaces.IChannelPart;
import uk.org.ownage.dmdirc.parser.callbacks.interfaces.IChannelQuit;
import uk.org.ownage.dmdirc.parser.callbacks.interfaces.IChannelTopic;
import uk.org.ownage.dmdirc.parser.callbacks.interfaces.IChannelUserModeChanged;
import uk.org.ownage.dmdirc.ui.ChannelFrame;
import uk.org.ownage.dmdirc.ui.MainFrame;
import uk.org.ownage.dmdirc.ui.input.TabCompleter;
import uk.org.ownage.dmdirc.ui.messages.ColourManager;
import uk.org.ownage.dmdirc.ui.messages.Formatter;
import uk.org.ownage.dmdirc.ui.messages.Styliser;
/**
* The Channel class represents the client's view of the channel. It handles
* callbacks for channel events from the parser, maintains the corresponding
* ChannelFrame, and handles user input to a ChannelFrame.
* @author chris
*/
public class Channel implements IChannelMessage, IChannelGotNames, IChannelTopic,
IChannelJoin, IChannelPart, IChannelKick, IChannelQuit, IChannelAction,
IChannelNickChanged, IChannelModeChanged, IChannelUserModeChanged,
InternalFrameListener, FrameContainer {
/** The parser's pChannel class. */
private ChannelInfo channelInfo;
/** The server this channel is on. */
private Server server;
/** The ChannelFrame used for this channel. */
private ChannelFrame frame;
/**
* The tabcompleter used for this channel.
*/
private TabCompleter tabCompleter;
/**
* The icon being used for this channel.
*/
private ImageIcon imageIcon;
/**
* Creates a new instance of Channel.
* @param newServer The server object that this channel belongs to
* @param newChannelInfo The parser's channel object that corresponds to this channel
*/
public Channel(final Server newServer, final ChannelInfo newChannelInfo) {
channelInfo = newChannelInfo;
server = newServer;
final ClassLoader cldr = this.getClass().getClassLoader();
final URL imageURL = cldr.getResource("uk/org/ownage/dmdirc/res/channel.png");
imageIcon = new ImageIcon(imageURL);
tabCompleter = new TabCompleter(server.getTabCompleter());
tabCompleter.addEntries(CommandManager.getChannelCommandNames());
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
frame = new ChannelFrame(Channel.this);
MainFrame.getMainFrame().addChild(frame);
frame.addInternalFrameListener(Channel.this);
frame.setFrameIcon(imageIcon);
frame.setTabCompleter(tabCompleter);
}
});
} catch (InvocationTargetException ex) {
Logger.error(ErrorLevel.FATAL, ex);
} catch (InterruptedException ex) {
Logger.error(ErrorLevel.FATAL, ex);
}
try {
final CallbackManager callbackManager = server.getParser().getCallbackManager();
final String channel = channelInfo.getName();
callbackManager.addCallback("OnChannelGotNames", this, channel);
callbackManager.addCallback("OnChannelTopic", this, channel);
callbackManager.addCallback("OnChannelMessage", this, channel);
callbackManager.addCallback("OnChannelJoin", this, channel);
callbackManager.addCallback("OnChannelPart", this, channel);
callbackManager.addCallback("OnChannelQuit", this, channel);
callbackManager.addCallback("OnChannelKick", this, channel);
callbackManager.addCallback("OnChannelAction", this, channel);
callbackManager.addCallback("OnChannelNickChanged", this, channel);
callbackManager.addCallback("OnChannelModeChanged", this, channel);
callbackManager.addCallback("OnChannelUserModeChanged", this, channel);
} catch (CallbackNotFound ex) {
Logger.error(ErrorLevel.FATAL, ex);
}
updateTitle();
selfJoin();
}
/**
* Shows this channel's frame.
*/
public void show() {
frame.open();
}
/**
* Sends the specified line as a message to the channel that this object
* represents.
* @param line The message to send
*/
public void sendLine(final String line) {
channelInfo.sendMessage(line);
final ClientInfo me = server.getParser().getMyself();
final String modes = channelInfo.getUser(me).getImportantModePrefix();
frame.addLine("channelSelfMessage", modes, me.getNickname(), me.getIdent(),
me.getHost(), line, channelInfo);
sendNotification();
}
/**
* Sends the specified string as an action (CTCP) to the channel that this object
* represents.
* @param action The action to send
*/
public void sendAction(final String action) {
channelInfo.sendAction(action);
final ClientInfo me = server.getParser().getMyself();
final String modes = channelInfo.getUser(me).getImportantModePrefix();
frame.addLine("channelSelfAction", modes, me.getNickname(), me.getIdent(),
me.getHost(), action, channelInfo);
sendNotification();
}
/**
* Returns the server object that this channel belongs to.
* @return The server object
*/
public Server getServer() {
return server;
}
/**
* Returns the parser's ChannelInfo object that this object is associated with.
* @return The ChannelInfo object associated with this object
*/
public ChannelInfo getChannelInfo() {
return channelInfo;
}
/**
* Sets this object's ChannelInfo reference to the one supplied. This only needs
* to be done if the channel window (and hence this channel object) has stayed
* open while the user has been out of the channel.
* @param newChannelInfo The new ChannelInfo object
*/
public void setChannelInfo(final ChannelInfo newChannelInfo) {
channelInfo = newChannelInfo;
}
/**
* Returns the internal frame belonging to this object
* @return This object's internal frame
*/
public CommandWindow getFrame() {
return frame;
}
/**
* Called when we join this channel. Just needs to output a message.
*/
public void selfJoin() {
final ClientInfo me = server.getParser().getMyself();
frame.addLine("channelSelfJoin", "", me.getNickname(), me.getIdent(),
me.getHost(), channelInfo.getName());
sendNotification();
}
/**
* Updates the title of the channel frame, and of the main frame if appropriate.
*/
private void updateTitle() {
final String title = Styliser.stipControlCodes(channelInfo.getName()
+ " - " + channelInfo.getTopic());
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.setTitle(title);
if (frame.isMaximum() && frame.equals(MainFrame.getMainFrame().getActiveFrame())) {
MainFrame.getMainFrame().setTitle(MainFrame.getMainFrame().getTitlePrefix() + " - " + title);
}
}
});
}
/**
* Joins the specified channel. This only makes sense if used after a call to
* part().
*/
public void join() {
server.getParser().joinChannel(channelInfo.getName());
}
/**
* Parts this channel with the specified message. Parting does NOT close the
* channel window.
* @param reason The reason for parting the channel
*/
public void part(final String reason) {
server.getParser().partChannel(channelInfo.getName(), reason);
}
/**
* Parts the channel and then closes the frame.
*/
public void close() {
part(Config.getOption("general", "partmessage"));
closeWindow();
}
/**
* Closes the window without parting the channel.
*/
public void closeWindow() {
final CallbackManager callbackManager = server.getParser().getCallbackManager();
callbackManager.delCallback("OnChannelMessage", this);
callbackManager.delCallback("OnChannelTopic", this);
callbackManager.delCallback("OnChannelGotNames", this);
callbackManager.delCallback("OnChannelJoin", this);
callbackManager.delCallback("OnChannelPart", this);
callbackManager.delCallback("OnChannelQuit", this);
callbackManager.delCallback("OnChannelKick", this);
callbackManager.delCallback("OnChannelAction", this);
callbackManager.delCallback("OnChannelNickChanged", this);
callbackManager.delCallback("OnChannelModeChanged", this);
callbackManager.delCallback("OnChannelUserModeChanged", this);
server.delChannel(channelInfo.getName());
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.setVisible(false);
MainFrame.getMainFrame().delChild(frame);
frame = null;
server = null;
}
});
}
/**
* Determines if the specified frame is owned by this object.
*
* @param target JInternalFrame to check ownership of
* @return boolean whether this object owns the specified frame
*/
public boolean ownsFrame(final JInternalFrame target) {
return frame.equals(target);
}
/**
* Called whenever a message is sent to this channel. NB that the ChannelClient
* passed may be null if the message was not sent by a client on the channel
* (i.e., it was sent by a server, or a client outside of the channel). In these
* cases the full host is used instead.
* @param tParser A reference to the IRC Parser for this server
* @param cChannel A reference to the ChannelInfo object for this channel
* @param cChannelClient A reference to the ChannelClient object that sent the message
* @param sMessage The message that was sent
* @param sHost The full host of the sender.
*/
public void onChannelMessage(final IRCParser tParser, final ChannelInfo cChannel,
final ChannelClientInfo cChannelClient, final String sMessage, final String sHost) {
final String[] parts = ClientInfo.parseHostFull(sHost);
final String modes = getModes(cChannelClient, sHost);
String type = "channelMessage";
if (parts[0].equals(tParser.getMyself().getNickname())) {
type = "channelSelfExternalMessage";
}
frame.addLine(type, modes, parts[0], parts[1], parts[2], sMessage, cChannel);
sendNotification();
}
/**
* Called when an action is sent to the channel.
* @param tParser A reference to the IRC Parser for this server
* @param cChannel A reference to the ChannelInfo object for this channel
* @param cChannelClient A reference to the client that sent the action
* @param sMessage The text of the action
* @param sHost The host of the performer (lest it wasn't an actual client)
*/
public void onChannelAction(final IRCParser tParser, final ChannelInfo cChannel,
final ChannelClientInfo cChannelClient, final String sMessage, final String sHost) {
final String[] parts = ClientInfo.parseHostFull(sHost);
final String modes = getModes(cChannelClient, sHost);
String type = "channelAction";
if (parts[0].equals(tParser.getMyself().getNickname())) {
type = "channelSelfExternalAction";
}
frame.addLine(type, modes, parts[0], parts[1], parts[2], sMessage, cChannel);
sendNotification();
}
/**
* Called when the parser receives a NAMES reply from the server. This means that
* the nicklist in the ChannelFrame needs to be updated.
* @param tParser A reference to the IRC Parser for this server
* @param cChannel A reference to the ChannelInfo object for this channel
*/
public void onChannelGotNames(final IRCParser tParser, final ChannelInfo cChannel) {
frame.updateNames(channelInfo.getChannelClients());
final ArrayList<String> names = new ArrayList<String>();
for (ChannelClientInfo channelClient : cChannel.getChannelClients()) {
names.add(channelClient.getNickname());
}
tabCompleter.replaceEntries(names);
tabCompleter.addEntries(CommandManager.getChannelCommandNames());
}
/**
* Called when the channel topic is changed. Changes the title of the channel
* frame, and also of the main frame if the channel is maximised and active.
* @param tParser A reference to the IRC Parser for this server
* @param cChannel A reference to the ChannelInfo object for this channel
* @param bIsJoinTopic Whether this is the topic received when we joined the
* channel or not
*/
public void onChannelTopic(final IRCParser tParser, final ChannelInfo cChannel,
final boolean bIsJoinTopic) {
if (bIsJoinTopic) {
frame.addLine("channelJoinTopic", cChannel.getTopic(),
cChannel.getTopicUser(), 1000 * cChannel.getTopicTime(), cChannel);
} else {
final ChannelClientInfo user = cChannel.getUser(cChannel.getTopicUser());
final String[] parts = ClientInfo.parseHostFull(cChannel.getTopicUser());
final String modes = getModes(user, cChannel.getTopicUser());
final String topic = cChannel.getTopic();
frame.addLine("channelTopicChange", modes, parts[0], parts[1], parts[2], topic, cChannel);
}
sendNotification();
updateTitle();
}
/**
* Called when a new client joins the channel. Adds the client to the listbox
* in the channel frame.
* @param tParser A reference to the IRC Parser for this server
* @param cChannel A reference to the ChannelInfo object for this channel
* @param cChannelClient The client that has just joined
*/
public void onChannelJoin(final IRCParser tParser, final ChannelInfo cChannel,
final ChannelClientInfo cChannelClient) {
final ClientInfo client = cChannelClient.getClient();
frame.addLine("channelJoin", "", client.getNickname(), client.getIdent(),
client.getHost(), cChannel);
frame.addName(cChannelClient);
tabCompleter.addEntry(cChannelClient.getNickname());
sendNotification();
}
/**
* Called when a client parts the channel. Removes the client from the listbox
* in the channel frame.
* @param tParser A reference to the IRC Parser for this server
* @param cChannel A reference to the ChannelInfo object for this channel
* @param cChannelClient The client that just parted
* @param sReason The reason specified when the client parted
*/
public void onChannelPart(final IRCParser tParser, final ChannelInfo cChannel,
final ChannelClientInfo cChannelClient, final String sReason) {
final ClientInfo client = cChannelClient.getClient();
final String nick = cChannelClient.getNickname();
final String ident = client.getIdent();
final String host = client.getHost();
final String modes = cChannelClient.getImportantModePrefix();
if (nick.equals(tParser.getMyself().getNickname())) {
if (sReason.equals("")) {
frame.addLine("channelSelfPart", modes, nick, ident, host, cChannel);
} else {
frame.addLine("channelSelfPartReason", modes, nick, ident, host, cChannel, sReason);
}
} else {
if (sReason.equals("")) {
frame.addLine("channelPart", modes, nick, ident, host, cChannel);
} else {
frame.addLine("channelPartReason", modes, nick, ident, host, sReason, cChannel);
}
}
frame.removeName(cChannelClient);
tabCompleter.removeEntry(cChannelClient.getNickname());
sendNotification();
}
/**
* Called when a client is kicked from the channel. The victim is removed
* from the channelframe's listbox.
* @param tParser A reference to the IRC Parser for this server
* @param cChannel A reference to the ChannelInfo object for this channel
* @param cKickedClient A reference to the client that was kicked
* @param cKickedByClient A reference to the client that did the kicking
* @param sReason The reason specified in the kick message
* @param sKickedByHost The host of the kicker (in case it wasn't an actual client)
*/
public void onChannelKick(final IRCParser tParser, final ChannelInfo cChannel,
final ChannelClientInfo cKickedClient, final ChannelClientInfo cKickedByClient,
final String sReason, final String sKickedByHost) {
final String[] kicker = ClientInfo.parseHostFull(sKickedByHost);
final String kickermodes = getModes(cKickedByClient, sKickedByHost);
final String victim = cKickedClient.getNickname();
final String victimmodes = cKickedClient.getImportantModePrefix();
final String victimident = cKickedClient.getClient().getIdent();
final String victimhost = cKickedClient.getClient().getHost();
if (sReason.equals("")) {
frame.addLine("channelKick", kickermodes, kicker[0], kicker[1], kicker[2], victimmodes,
victim, victimident, victimhost, cChannel.getName());
} else {
frame.addLine("channelKickReason", kickermodes, kicker[0], kicker[1], kicker[2], victimmodes,
victim, victimident, victimhost, sReason, cChannel.getName());
}
frame.removeName(cKickedClient);
tabCompleter.removeEntry(cKickedClient.getNickname());
sendNotification();
}
/**
* Called when a client that was present on this channel has disconnected
* from the IRC server (or been netsplit).
* @param tParser A reference to the IRC Parser for this server
* @param cChannel A reference to the ChannelInfo object for this channel
* @param cChannelClient A reference to the client that has quit
* @param sReason The reason specified in the client's quit message
*/
public void onChannelQuit(final IRCParser tParser, final ChannelInfo cChannel,
final ChannelClientInfo cChannelClient, final String sReason) {
final ClientInfo client = cChannelClient.getClient();
final String source = cChannelClient.getNickname();
final String modes = cChannelClient.getImportantModePrefix();
if (sReason.equals("")) {
frame.addLine("channelQuit", modes, source, client.getIdent(),
client.getHost(), cChannel);
} else {
frame.addLine("channelQuitReason", modes, source, client.getIdent(),
client.getHost(), sReason, cChannel);
}
frame.removeName(cChannelClient);
sendNotification();
}
/**
* Called when someone on the channel changes their nickname.
* @param tParser A reference to the IRC parser for this server
* @param cChannel A reference to the CHannelInfo object for this channel
* @param cChannelClient The client that changed nickname
* @param sOldNick The old nickname of the client
*/
public void onChannelNickChanged(final IRCParser tParser, final ChannelInfo cChannel,
final ChannelClientInfo cChannelClient, final String sOldNick) {
final String modes = cChannelClient.getImportantModePrefix();
final String nick = cChannelClient.getNickname();
final String ident = cChannelClient.getClient().getIdent();
final String host = cChannelClient.getClient().getHost();
String type = "channelNickChange";
if (nick.equals(tParser.getMyself().getNickname())) {
type = "channelSelfNickChange";
}
frame.addLine(type, modes, sOldNick, ident, host, nick, cChannel);
sendNotification();
}
/**
* Called when modes are changed on the channel.
* @param tParser A reference to the IRC parser for this server
* @param cChannel A reference to the ChannelInfo object for this channel
* @param cChannelClient The client that set the modes
* @param sHost the host of the client that set the modes
* @param sModes the modes that were set
*/
public void onChannelModeChanged(final IRCParser tParser, final ChannelInfo cChannel,
final ChannelClientInfo cChannelClient, final String sHost, final String sModes) {
if (sHost.equals("")) {
frame.addLine("channelModeDiscovered", sModes, cChannel.getName());
} else {
final String modes = getModes(cChannelClient, sHost);
final String[] details = getDetails(cChannelClient, sHost);
final String myNick = tParser.getMyself().getNickname();
String type = "channelModeChange";
if (cChannelClient != null && myNick.equals(cChannelClient.getNickname())) {
type = "channelSelfModeChange";
}
frame.addLine(type, modes, details[0], details[1],
details[2], sModes, cChannel.getName());
}
frame.updateNames();
sendNotification();
}
/**
* Called when a mode has been changed on a user. Used for custom mode
* formats.
* @param tParser A reference to the IRC parser for this server
* @param cChannel A reference to the ChannelInfo object for this channel
* @param cChangedClient The client whose mode was changed
* @param cSetByClient The client who made the change
* @param sHost The hostname of the setter
* @param sMode The mode that has been changed
*/
public void onChannelUserModeChanged(final IRCParser tParser,
final ChannelInfo cChannel, final ChannelClientInfo cChangedClient,
final ChannelClientInfo cSetByClient, final String sHost,
final String sMode) {
if (Boolean.parseBoolean(Config.getOption("channel", "splitusermodes"))) {
final String sourceModes = getModes(cSetByClient, sHost);
final String[] sourceHost = getDetails(cSetByClient, sHost);
final String targetModes = cChangedClient.getImportantModePrefix();
final String targetNick = cChangedClient.getClient().getNickname();
final String targetIdent = cChangedClient.getClient().getIdent();
final String targetHost = cChangedClient.getClient().getHost();
String format = "channelUserMode_" + sMode;
if (!Formatter.hasFormat(format)) {
format = "channelUserMode_default";
}
frame.addLine(format, sourceModes, sourceHost[0], sourceHost[1],
sourceHost[2], targetModes, targetNick, targetIdent,
targetHost, sMode, cChannel);
}
}
/**
* Returns a string containing the most important mode for the specified client.
* @param channelClient The channel client to check.
* @param host The hostname to check if the channel client doesn't exist
* @return A string containing the most important mode, or an empty string
* if there are no (known) modes.
*/
private String getModes(final ChannelClientInfo channelClient, final String host) {
if (channelClient == null) {
return "";
} else {
return channelClient.getImportantModePrefix();
}
}
/**
* Returns a string containing the nickname, or other appropriate portion
* of the host for displaying (e.g. server name).
* @param channelClient The channel client to check
* @param host The hostname to check if the channel client doesn't exist
* @return A string containing a displayable name
*/
private String getNick(final ChannelClientInfo channelClient, final String host) {
if (channelClient == null) {
return ClientInfo.parseHost(host);
} else {
return channelClient.getNickname();
}
}
/**
* Returns a string[] containing the nickname/ident/host of the client, or
* server, where applicable.
* @param channelClient The channel client to check
* @param host The hostname to check if the channel client doesn't exist
* @return A string[] containing displayable components
*/
private String[] getDetails(final ChannelClientInfo channelClient, final String host) {
if (channelClient == null) {
return ClientInfo.parseHostFull(host);
} else {
String[] res = new String[3];
res[0] = channelClient.getNickname();
res[1] = channelClient.getClient().getIdent();
res[2] = channelClient.getClient().getHost();
return res;
}
}
/**
* Called when the channel frame is opened. Checks config settings to
* determine if the window should be maximised.
* @param internalFrameEvent The event that triggered this callback
*/
public void internalFrameOpened(final InternalFrameEvent internalFrameEvent) {
final Boolean pref = Boolean.parseBoolean(Config.getOption("ui", "maximisewindows"));
if (pref.equals(Boolean.TRUE) || MainFrame.getMainFrame().getMaximised()) {
try {
frame.setMaximum(true);
} catch (PropertyVetoException ex) {
Logger.error(ErrorLevel.WARNING, ex);
}
}
}
/**
* Called when the channel frame is being closed. Has the parser part the
* channel, and frees all resources associated with the channel.
* @param internalFrameEvent The event that triggered this callback
*/
public void internalFrameClosing(final InternalFrameEvent internalFrameEvent) {
part(Config.getOption("general", "partmessage"));
close();
}
/**
* Called when the channel frame is actually closed. Not implemented.
* @param internalFrameEvent The event that triggered this callback
*/
public void internalFrameClosed(final InternalFrameEvent internalFrameEvent) {
}
/**
* Called when the channel frame is iconified. Not implemented.
* @param internalFrameEvent The event that triggered this callback
*/
public void internalFrameIconified(final InternalFrameEvent internalFrameEvent) {
}
/**
* Called when the channel frame is deiconified. Not implemented.
* @param internalFrameEvent The event that triggered this callback
*/
public void internalFrameDeiconified(final InternalFrameEvent internalFrameEvent) {
}
/**
* Called when the channel frame is activated. Maximises the frame if it
* needs to be.
* @param internalFrameEvent The event that triggered this callback
*/
public void internalFrameActivated(final InternalFrameEvent internalFrameEvent) {
if (MainFrame.getMainFrame().getMaximised()) {
try {
frame.setMaximum(true);
} catch (PropertyVetoException ex) {
Logger.error(ErrorLevel.WARNING, ex);
}
}
MainFrame.getMainFrame().getFrameManager().setSelected(this);
server.setActiveFrame(this);
clearNotification();
}
/**
* Called when the channel frame is deactivated. Not implemented.
* @param internalFrameEvent The event that triggered this callback
*/
public void internalFrameDeactivated(final InternalFrameEvent internalFrameEvent) {
}
/**
* Returns this channel's name.
* @return A string representation of this channel (i.e., its name)
*/
public String toString() {
return channelInfo.getName();
}
/**
* Requests that this object's frame be activated.
*/
public void activateFrame() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MainFrame.getMainFrame().setActiveFrame(frame);
}
});
}
/**
* Adds a line of text to the main text area of the channel frame.
* @param line The line to add
*/
public void addLine(final String line) {
frame.addLine(line);
}
/**
* Formats the specified arguments using the supplied message type, and
* outputs to the main text area.
* @param messageType the message type to use
* @param args the arguments to pass
*/
public void addLine(final String messageType, final Object... args) {
frame.addLine(messageType, args);
}
/**
* Retrieves the icon used by the channel frame.
* @return The channel frame's icon
*/
public ImageIcon getIcon() {
return imageIcon;
}
/**
* Sends a notification to the frame manager if this frame isn't active.
*/
public void sendNotification() {
if (!MainFrame.getMainFrame().getActiveFrame().equals(frame)) {
final Color c = ColourManager.getColour(4);
MainFrame.getMainFrame().getFrameManager().showNotification(this, c);
}
}
/**
* Clears any outstanding notifications this frame has set.
*/
private void clearNotification() {
MainFrame.getMainFrame().getFrameManager().clearNotification(this);
}
}
| Fixed NPE in Channel.sendNotification
git-svn-id: 50f83ef66c13f323b544ac924010c921a9f4a0f7@527 00569f92-eb28-0410-84fd-f71c24880f43
| src/uk/org/ownage/dmdirc/Channel.java | Fixed NPE in Channel.sendNotification | <ide><path>rc/uk/org/ownage/dmdirc/Channel.java
<ide> * Sends a notification to the frame manager if this frame isn't active.
<ide> */
<ide> public void sendNotification() {
<del> if (!MainFrame.getMainFrame().getActiveFrame().equals(frame)) {
<add> JInternalFrame activeFrame = MainFrame.getMainFrame().getActiveFrame();
<add> if (activeFrame != null && activeFrame.equals(frame)) {
<ide> final Color c = ColourManager.getColour(4);
<ide> MainFrame.getMainFrame().getFrameManager().showNotification(this, c);
<ide> } |
|
JavaScript | mit | 83c88e601b7f3ffa70f806725752085ec5bbd9f7 | 0 | 4dn-dcic/fourfront,hms-dbmi/fourfront,hms-dbmi/fourfront,4dn-dcic/fourfront,4dn-dcic/fourfront,hms-dbmi/fourfront,hms-dbmi/fourfront,hms-dbmi/fourfront,4dn-dcic/fourfront | 'use strict';
import React from 'react';
import PropTypes from 'prop-types';
import _ from 'underscore';
import { ajax, console } from './../../../util';
import { requestAnimationFrame } from './../../../viz/utilities';
let HiGlassComponent = null; // Loaded after componentDidMount as not supported server-side.
export class HiGlassPlainContainer extends React.PureComponent {
static does2DTrackExist(viewConfig){
var found = false;
_.forEach(viewConfig.views || [], function(view){
if (found) return;
_.forEach((view.tracks && view.tracks.center) || [], function(centerTrack){
if (found) return;
if (centerTrack.position === 'center') {
found = true;
}
});
});
return found;
}
static getPrimaryViewID(viewConfig){
if (!viewConfig || !Array.isArray(viewConfig.views) || viewConfig.views.length === 0){
return null;
}
return _.uniq(_.pluck(viewConfig.views, 'uid'))[0];
}
static correctTrackDimensions(hiGlassComponent){
requestAnimationFrame(()=>{
_.forEach(hiGlassComponent.tiledPlots, (tp) => tp && tp.measureSize());
});
}
static propTypes = {
'viewConfig' : PropTypes.object.isRequired,
'isValidating' : PropTypes.bool,
'height' : PropTypes.number,
'mountDelay' : PropTypes.number.isRequired
};
static defaultProps = {
'options' : { 'bounded' : true },
'isValidating' : false,
'disabled' : false,
'height' : 500,
'viewConfig' : null,
'mountDelay' : 500,
'placeholder' : (
<React.Fragment>
<h3>
<i className="icon icon-lg icon-television"/>
</h3>
Initializing
</React.Fragment>
)
};
constructor(props){
super(props);
this.instanceContainerRefFunction = this.instanceContainerRefFunction.bind(this);
this.correctTrackDimensions = this.correctTrackDimensions.bind(this);
this.getHiGlassComponent = this.getHiGlassComponent.bind(this);
this.state = {
'mounted' : false,
'mountCount' : 0,
'hasRuntimeError' : false
};
this.hgcRef = React.createRef();
}
componentDidMount(){
const finish = () => {
this.setState(function(currState){
return { 'mounted' : true, 'mountCount' : currState.mountCount + 1 };
}, () => {
setTimeout(this.correctTrackDimensions, 500);
});
};
setTimeout(()=>{ // Allow tab CSS transition to finish (the render afterwards lags browser a little bit).
if (!HiGlassComponent) {
window.fetch = window.fetch || ajax.fetchPolyfill; // Browser compatibility polyfill
// Load in HiGlass libraries as separate JS file due to large size.
// @see https://webpack.js.org/api/module-methods/#requireensure
require.ensure(['higlass/dist/hglib'], (require) => {
const hglib = require('higlass/dist/hglib');
HiGlassComponent = hglib.HiGlassComponent;
finish();
}, "higlass-utils-bundle");
// Alternative, newer version of above -- currently the 'magic comments' are
// not being picked up (?) though so the above is used to set name of JS file.
//import(
// /* webpackChunkName: "higlass-bundle" */
// 'higlass/dist/hglib'
//).then((hglib) =>{
// HiGlassComponent = hglib.HiGlassComponent;
// finish();
//});
} else {
finish();
}
}, this.props.mountDelay || 500);
}
correctTrackDimensions(){
var hgc = this.getHiGlassComponent();
if (hgc){
HiGlassPlainContainer.correctTrackDimensions(hgc);
} else {
console.error('NO HGC');
}
}
componentWillUnmount(){
this.setState({ 'mounted' : false });
}
componentDidCatch(){
this.setState({ 'hasRuntimeError' : true });
}
/**
* Fade in div element containing HiGlassComponent after HiGlass initiates & loads in first tile etc. (about 500ms).
* For prettiness only.
*/
instanceContainerRefFunction(element){
if (element){
setTimeout(function(){
requestAnimationFrame(function(){
element.style.transition = null; // Use transition as defined in stylesheet
element.style.opacity = 1;
});
}, 500);
}
}
getHiGlassComponent(){
return (this && this.hgcRef && this.hgcRef.current) || null;
}
/**
* This returns the viewconfig currently stored in PlainContainer _state_.
* We should adjust this to instead return `JSON.parse(hgc.api.exportViewConfigAsString())`,
* most likely, to be of any use because HiGlassComponent keeps its own representation of the
* viewConfig.
*
* @todo Change to the above once needed. Don't rely on until then.
*/
getCurrentViewConfig(){
var hgc = this.getHiGlassComponent();
return (hgc && hgc.state.viewConfig) || null;
}
render(){
var { disabled, isValidating, tilesetUid, height, width, options, style,
className, viewConfig, placeholder
} = this.props,
hiGlassInstance = null,
mounted = (this.state && this.state.mounted) || false,
outerKey = "mount-number-" + this.state.mountCount;
if (isValidating || !mounted){
var placeholderStyle = {};
if (typeof height === 'number' && height >= 140){
placeholderStyle.height = height;
placeholderStyle.paddingTop = (height / 2) - 40;
}
hiGlassInstance = <div className="text-center" style={placeholderStyle} key={outerKey}>{ placeholder }</div>;
} else if (disabled) {
hiGlassInstance = (
<div className="text-center" key={outerKey} style={placeholderStyle}>
<h4 className="text-400">Not Available</h4>
</div>
);
} else if (this.state.hasRuntimeError) {
hiGlassInstance = (
<div className="text-center" key={outerKey} style={placeholderStyle}>
<h4 className="text-400">Runtime Error</h4>
</div>
);
} else {
hiGlassInstance = (
<div key={outerKey} className="higlass-instance" style={{ 'transition' : 'none', 'height' : height, 'width' : width || null }} ref={this.instanceContainerRefFunction}>
<HiGlassComponent {...{ options, viewConfig, width, height }} ref={this.hgcRef} />
</div>
);
}
/**
* TODO: Some state + UI functions to make higlass view full screen.
* Should try to make as common as possible between one for workflow tab & this. Won't be 100% compatible since adjust workflow detail tab inner elem styles, but maybe some common func for at least width, height, etc.
*/
return (
<div className={"higlass-view-container" + (className ? ' ' + className : '')} style={style}>
<link type="text/css" rel="stylesheet" href="https://unpkg.com/[email protected]/dist/hglib.css" crossOrigin="true" />
{/*<script src="https://unpkg.com/[email protected]/dist/scripts/hglib.js"/>*/}
<div className="higlass-wrapper row">{ hiGlassInstance }</div>
</div>
);
}
}
| src/encoded/static/components/item-pages/components/HiGlass/HiGlassPlainContainer.js | 'use strict';
import React from 'react';
import PropTypes from 'prop-types';
import _ from 'underscore';
import { ajax, console } from './../../../util';
import { requestAnimationFrame } from './../../../viz/utilities';
let HiGlassComponent = null; // Loaded after componentDidMount as not supported server-side.
export class HiGlassPlainContainer extends React.PureComponent {
static does2DTrackExist(viewConfig){
var found = false;
_.forEach(viewConfig.views || [], function(view){
if (found) return;
_.forEach((view.tracks && view.tracks.center) || [], function(centerTrack){
if (found) return;
if (centerTrack.position === 'center') {
found = true;
}
});
});
return found;
}
static getPrimaryViewID(viewConfig){
if (!viewConfig || !Array.isArray(viewConfig.views) || viewConfig.views.length === 0){
return null;
}
return _.uniq(_.pluck(viewConfig.views, 'uid'))[0];
}
static correctTrackDimensions(hiGlassComponent){
requestAnimationFrame(()=>{
_.forEach(hiGlassComponent.tiledPlots, (tp) => tp && tp.measureSize());
});
}
static propTypes = {
'viewConfig' : PropTypes.object.isRequired,
'isValidating' : PropTypes.bool,
'height' : PropTypes.number,
'mountDelay' : PropTypes.number.isRequired
};
static defaultProps = {
'options' : { 'bounded' : true },
'isValidating' : false,
'disabled' : false,
'height' : 500,
'viewConfig' : null,
'mountDelay' : 500,
'placeholder' : (
<React.Fragment>
<h3>
<i className="icon icon-lg icon-television"/>
</h3>
Initializing
</React.Fragment>
)
};
constructor(props){
super(props);
this.instanceContainerRefFunction = this.instanceContainerRefFunction.bind(this);
this.correctTrackDimensions = this.correctTrackDimensions.bind(this);
this.getHiGlassComponent = this.getHiGlassComponent.bind(this);
this.state = {
'mounted' : false,
'mountCount' : 0,
'hasRuntimeError' : false
};
this.hgcRef = React.createRef();
}
componentDidMount(){
const finish = () => {
this.setState(function(currState){
return { 'mounted' : true, 'mountCount' : currState.mountCount + 1 };
}, () => {
setTimeout(this.correctTrackDimensions, 500);
});
};
setTimeout(()=>{ // Allow tab CSS transition to finish (the render afterwards lags browser a little bit).
if (!HiGlassComponent) {
window.fetch = window.fetch || ajax.fetchPolyfill; // Browser compatibility polyfill
require.ensure(['higlass/dist/hglib'], (require) => {
const hglib = require('higlass/dist/hglib');
HiGlassComponent = hglib.HiGlassComponent;
finish();
}, "higlass-utils-bundle");
} else {
finish();
}
}, this.props.mountDelay);
}
correctTrackDimensions(){
var hgc = this.getHiGlassComponent();
if (hgc){
HiGlassPlainContainer.correctTrackDimensions(hgc);
} else {
console.error('NO HGC');
}
}
componentWillUnmount(){
this.setState({ 'mounted' : false });
}
componentDidCatch(){
this.setState({ 'hasRuntimeError' : true });
}
/**
* Fade in div element containing HiGlassComponent after HiGlass initiates & loads in first tile etc. (about 500ms).
* For prettiness only.
*/
instanceContainerRefFunction(element){
if (element){
setTimeout(function(){
requestAnimationFrame(function(){
element.style.transition = null; // Use transition as defined in stylesheet
element.style.opacity = 1;
});
}, 500);
}
}
getHiGlassComponent(){
return (this && this.hgcRef && this.hgcRef.current) || null;
}
/**
* This returns the viewconfig currently stored in PlainContainer _state_.
* We should adjust this to instead return `JSON.parse(hgc.api.exportViewConfigAsString())`,
* most likely, to be of any use because HiGlassComponent keeps its own representation of the
* viewConfig.
*
* @todo Change to the above once needed. Don't rely on until then.
*/
getCurrentViewConfig(){
var hgc = this.getHiGlassComponent();
return (hgc && hgc.state.viewConfig) || null;
}
render(){
var { disabled, isValidating, tilesetUid, height, width, options, style,
className, viewConfig, placeholder
} = this.props,
hiGlassInstance = null,
mounted = (this.state && this.state.mounted) || false,
outerKey = "mount-number-" + this.state.mountCount;
if (isValidating || !mounted){
var placeholderStyle = {};
if (typeof height === 'number' && height >= 140){
placeholderStyle.height = height;
placeholderStyle.paddingTop = (height / 2) - 40;
}
hiGlassInstance = <div className="text-center" style={placeholderStyle} key={outerKey}>{ placeholder }</div>;
} else if (disabled) {
hiGlassInstance = (
<div className="text-center" key={outerKey} style={placeholderStyle}>
<h4 className="text-400">Not Available</h4>
</div>
);
} else if (this.state.hasRuntimeError) {
hiGlassInstance = (
<div className="text-center" key={outerKey} style={placeholderStyle}>
<h4 className="text-400">Runtime Error</h4>
</div>
);
} else {
hiGlassInstance = (
<div key={outerKey} className="higlass-instance" style={{ 'transition' : 'none', 'height' : height, 'width' : width || null }} ref={this.instanceContainerRefFunction}>
<HiGlassComponent {...{ options, viewConfig, width, height }} ref={this.hgcRef} />
</div>
);
}
/**
* TODO: Some state + UI functions to make higlass view full screen.
* Should try to make as common as possible between one for workflow tab & this. Won't be 100% compatible since adjust workflow detail tab inner elem styles, but maybe some common func for at least width, height, etc.
*/
return (
<div className={"higlass-view-container" + (className ? ' ' + className : '')} style={style}>
<link type="text/css" rel="stylesheet" href="https://unpkg.com/[email protected]/dist/hglib.css" crossOrigin="true" />
{/*<script src="https://unpkg.com/[email protected]/dist/scripts/hglib.js"/>*/}
<div className="higlass-wrapper row" children={hiGlassInstance} />
</div>
);
}
}
| Few more comments
| src/encoded/static/components/item-pages/components/HiGlass/HiGlassPlainContainer.js | Few more comments | <ide><path>rc/encoded/static/components/item-pages/components/HiGlass/HiGlassPlainContainer.js
<ide> });
<ide> };
<ide>
<del>
<ide> setTimeout(()=>{ // Allow tab CSS transition to finish (the render afterwards lags browser a little bit).
<ide> if (!HiGlassComponent) {
<ide> window.fetch = window.fetch || ajax.fetchPolyfill; // Browser compatibility polyfill
<ide>
<add> // Load in HiGlass libraries as separate JS file due to large size.
<add> // @see https://webpack.js.org/api/module-methods/#requireensure
<ide> require.ensure(['higlass/dist/hglib'], (require) => {
<ide> const hglib = require('higlass/dist/hglib');
<ide> HiGlassComponent = hglib.HiGlassComponent;
<ide> finish();
<ide> }, "higlass-utils-bundle");
<add>
<add> // Alternative, newer version of above -- currently the 'magic comments' are
<add> // not being picked up (?) though so the above is used to set name of JS file.
<add> //import(
<add> // /* webpackChunkName: "higlass-bundle" */
<add> // 'higlass/dist/hglib'
<add> //).then((hglib) =>{
<add> // HiGlassComponent = hglib.HiGlassComponent;
<add> // finish();
<add> //});
<add>
<ide> } else {
<ide> finish();
<ide> }
<ide>
<del> }, this.props.mountDelay);
<add> }, this.props.mountDelay || 500);
<ide> }
<ide>
<ide> correctTrackDimensions(){
<ide> <div className={"higlass-view-container" + (className ? ' ' + className : '')} style={style}>
<ide> <link type="text/css" rel="stylesheet" href="https://unpkg.com/[email protected]/dist/hglib.css" crossOrigin="true" />
<ide> {/*<script src="https://unpkg.com/[email protected]/dist/scripts/hglib.js"/>*/}
<del> <div className="higlass-wrapper row" children={hiGlassInstance} />
<add> <div className="higlass-wrapper row">{ hiGlassInstance }</div>
<ide> </div>
<ide> );
<ide> }
<ide>
<del>
<ide> } |
|
Java | apache-2.0 | ea594f10f895885d4bffdb2c374e0713cba5cd0c | 0 | idea4bsd/idea4bsd,apixandru/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,FHannes/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,allotria/intellij-community,asedunov/intellij-community,signed/intellij-community,ibinti/intellij-community,FHannes/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,samthor/intellij-community,hurricup/intellij-community,clumsy/intellij-community,kdwink/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,signed/intellij-community,fnouama/intellij-community,xfournet/intellij-community,apixandru/intellij-community,apixandru/intellij-community,slisson/intellij-community,blademainer/intellij-community,ibinti/intellij-community,vladmm/intellij-community,semonte/intellij-community,nicolargo/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,allotria/intellij-community,jagguli/intellij-community,ibinti/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,da1z/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,vladmm/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,ibinti/intellij-community,hurricup/intellij-community,fitermay/intellij-community,slisson/intellij-community,orekyuu/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,signed/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,ibinti/intellij-community,apixandru/intellij-community,retomerz/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,apixandru/intellij-community,fnouama/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,samthor/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,slisson/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,semonte/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,semonte/intellij-community,xfournet/intellij-community,retomerz/intellij-community,fnouama/intellij-community,slisson/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,asedunov/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,orekyuu/intellij-community,slisson/intellij-community,apixandru/intellij-community,FHannes/intellij-community,retomerz/intellij-community,vladmm/intellij-community,semonte/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,hurricup/intellij-community,allotria/intellij-community,fnouama/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,FHannes/intellij-community,signed/intellij-community,vladmm/intellij-community,apixandru/intellij-community,amith01994/intellij-community,semonte/intellij-community,vvv1559/intellij-community,kool79/intellij-community,hurricup/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,hurricup/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,apixandru/intellij-community,signed/intellij-community,amith01994/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,da1z/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,hurricup/intellij-community,kool79/intellij-community,signed/intellij-community,signed/intellij-community,allotria/intellij-community,kdwink/intellij-community,samthor/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,semonte/intellij-community,vladmm/intellij-community,FHannes/intellij-community,allotria/intellij-community,wreckJ/intellij-community,kool79/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,signed/intellij-community,xfournet/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,semonte/intellij-community,youdonghai/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,semonte/intellij-community,retomerz/intellij-community,FHannes/intellij-community,signed/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,allotria/intellij-community,slisson/intellij-community,semonte/intellij-community,allotria/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,fitermay/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,FHannes/intellij-community,xfournet/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,semonte/intellij-community,clumsy/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,amith01994/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,vladmm/intellij-community,vladmm/intellij-community,jagguli/intellij-community,da1z/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,hurricup/intellij-community,fitermay/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,fnouama/intellij-community,signed/intellij-community,kdwink/intellij-community,da1z/intellij-community,blademainer/intellij-community,allotria/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,semonte/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,samthor/intellij-community,jagguli/intellij-community,blademainer/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,blademainer/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,clumsy/intellij-community,hurricup/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,xfournet/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,allotria/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,kdwink/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,jagguli/intellij-community,samthor/intellij-community,clumsy/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,FHannes/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,slisson/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,signed/intellij-community | /*
* Copyright 2000-2015 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.editor.impl;
import com.intellij.application.options.OptionsConstants;
import com.intellij.codeInsight.hint.DocumentFragmentTooltipRenderer;
import com.intellij.codeInsight.hint.EditorFragmentComponent;
import com.intellij.codeInsight.hint.TooltipController;
import com.intellij.codeInsight.hint.TooltipGroup;
import com.intellij.concurrency.JobScheduler;
import com.intellij.diagnostic.Dumpable;
import com.intellij.diagnostic.LogMessageEx;
import com.intellij.ide.*;
import com.intellij.ide.dnd.DnDManager;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.ide.ui.UISettings;
import com.intellij.ide.ui.customization.CustomActionsSchema;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.actionSystem.ex.AnActionListener;
import com.intellij.openapi.actionSystem.impl.MouseGestureManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.UndoConfirmationPolicy;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.actionSystem.*;
import com.intellij.openapi.editor.actions.*;
import com.intellij.openapi.editor.colors.*;
import com.intellij.openapi.editor.colors.impl.DelegateColorScheme;
import com.intellij.openapi.editor.event.*;
import com.intellij.openapi.editor.ex.*;
import com.intellij.openapi.editor.ex.util.EditorUIUtil;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.editor.ex.util.EmptyEditorHighlighter;
import com.intellij.openapi.editor.ex.util.LexerEditorHighlighter;
import com.intellij.openapi.editor.highlighter.EditorHighlighter;
import com.intellij.openapi.editor.highlighter.HighlighterClient;
import com.intellij.openapi.editor.impl.event.MarkupModelListener;
import com.intellij.openapi.editor.impl.softwrap.SoftWrapAppliancePlaces;
import com.intellij.openapi.editor.impl.softwrap.SoftWrapDrawingType;
import com.intellij.openapi.editor.impl.view.EditorView;
import com.intellij.openapi.editor.markup.*;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory;
import com.intellij.openapi.fileEditor.impl.EditorsSplitters;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Queryable;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.IdeGlassPane;
import com.intellij.openapi.wm.ToolWindowAnchor;
import com.intellij.openapi.wm.ex.ToolWindowManagerEx;
import com.intellij.openapi.wm.impl.IdeBackgroundUtil;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.ui.*;
import com.intellij.ui.components.JBLayeredPane;
import com.intellij.ui.components.JBScrollBar;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.util.*;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.ContainerUtilRt;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.text.CharArrayCharSequence;
import com.intellij.util.text.CharArrayUtil;
import com.intellij.util.ui.*;
import com.intellij.util.ui.update.Activatable;
import com.intellij.util.ui.update.UiNotifyConnector;
import gnu.trove.TIntArrayList;
import gnu.trove.TIntFunction;
import gnu.trove.TIntHashSet;
import gnu.trove.TIntIntHashMap;
import org.intellij.lang.annotations.JdkConstants;
import org.intellij.lang.annotations.MagicConstant;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import javax.swing.*;
import javax.swing.Timer;
import javax.swing.border.Border;
import javax.swing.plaf.ScrollBarUI;
import javax.swing.plaf.basic.BasicScrollBarUI;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetAdapter;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.event.*;
import java.awt.font.TextHitInfo;
import java.awt.im.InputMethodRequests;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.lang.reflect.Field;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.text.CharacterIterator;
import java.util.*;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public final class EditorImpl extends UserDataHolderBase implements EditorEx, HighlighterClient, Queryable, Dumpable {
private static final boolean isOracleRetina = UIUtil.isRetina() && SystemInfo.isOracleJvm;
private static final int MIN_FONT_SIZE = 8;
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.editor.impl.EditorImpl");
private static final Key DND_COMMAND_KEY = Key.create("DndCommand");
@NonNls
public static final Object IGNORE_MOUSE_TRACKING = "ignore_mouse_tracking";
private static final Key<JComponent> PERMANENT_HEADER = Key.create("PERMANENT_HEADER");
public static final Key<Boolean> DO_DOCUMENT_UPDATE_TEST = Key.create("DoDocumentUpdateTest");
public static final Key<Boolean> FORCED_SOFT_WRAPS = Key.create("forced.soft.wraps");
private static final boolean HONOR_CAMEL_HUMPS_ON_TRIPLE_CLICK = Boolean.parseBoolean(System.getProperty("idea.honor.camel.humps.on.triple.click"));
private static final Key<BufferedImage> BUFFER = Key.create("buffer");
private static final Color CURSOR_FOREGROUND_LIGHT = Gray._255;
private static final Color CURSOR_FOREGROUND_DARK = Gray._0;
@NotNull private final DocumentEx myDocument;
private final JPanel myPanel;
@NotNull private final JScrollPane myScrollPane;
@NotNull private final EditorComponentImpl myEditorComponent;
@NotNull private final EditorGutterComponentImpl myGutterComponent;
private final TraceableDisposable myTraceableDisposable = new TraceableDisposable(new Throwable());
private int myLinePaintersWidth;
static {
ComplementaryFontsRegistry.getFontAbleToDisplay(' ', 0, 0, UIManager.getFont("Label.font").getFamily()); // load costly font info
}
private final CommandProcessor myCommandProcessor;
@NotNull private final MyScrollBar myVerticalScrollBar;
private final List<EditorMouseListener> myMouseListeners = ContainerUtil.createLockFreeCopyOnWriteList();
@NotNull private final List<EditorMouseMotionListener> myMouseMotionListeners = ContainerUtil.createLockFreeCopyOnWriteList();
private int myCharHeight = -1;
private int myLineHeight = -1;
private int myDescent = -1;
private boolean myIsInsertMode = true;
@NotNull private final CaretCursor myCaretCursor;
private final ScrollingTimer myScrollingTimer = new ScrollingTimer();
@SuppressWarnings("RedundantStringConstructorCall")
private final Object MOUSE_DRAGGED_GROUP = new String("MouseDraggedGroup");
@NotNull private final SettingsImpl mySettings;
private boolean isReleased;
@Nullable private MouseEvent myMousePressedEvent;
@Nullable private MouseEvent myMouseMovedEvent;
/**
* Holds information about area where mouse was pressed.
*/
@Nullable private EditorMouseEventArea myMousePressArea;
private int mySavedSelectionStart = -1;
private int mySavedSelectionEnd = -1;
private int myLastColumnNumber;
private final PropertyChangeSupport myPropertyChangeSupport = new PropertyChangeSupport(this);
private MyEditable myEditable;
@NotNull
private EditorColorsScheme myScheme;
private ArrowPainter myTabPainter;
private boolean myIsViewer;
@NotNull private final SelectionModelImpl mySelectionModel;
@NotNull private final EditorMarkupModelImpl myMarkupModel;
@NotNull private final FoldingModelImpl myFoldingModel;
@NotNull private final ScrollingModelImpl myScrollingModel;
@NotNull private final CaretModelImpl myCaretModel;
@NotNull private final SoftWrapModelImpl mySoftWrapModel;
@NotNull private static final RepaintCursorCommand ourCaretBlinkingCommand = new RepaintCursorCommand();
private MessageBusConnection myConnection;
@MouseSelectionState
private int myMouseSelectionState;
@Nullable private FoldRegion myMouseSelectedRegion;
@MagicConstant(intValues = {MOUSE_SELECTION_STATE_NONE, MOUSE_SELECTION_STATE_LINE_SELECTED, MOUSE_SELECTION_STATE_WORD_SELECTED})
private @interface MouseSelectionState {}
private static final int MOUSE_SELECTION_STATE_NONE = 0;
private static final int MOUSE_SELECTION_STATE_WORD_SELECTED = 1;
private static final int MOUSE_SELECTION_STATE_LINE_SELECTED = 2;
private EditorHighlighter myHighlighter;
private Disposable myHighlighterDisposable = Disposer.newDisposable();
private final TextDrawingCallback myTextDrawingCallback = new MyTextDrawingCallback();
@MagicConstant(intValues = {VERTICAL_SCROLLBAR_LEFT, VERTICAL_SCROLLBAR_RIGHT})
private int myScrollBarOrientation;
private boolean myMousePressedInsideSelection;
private FontMetrics myPlainFontMetrics;
private FontMetrics myBoldFontMetrics;
private FontMetrics myItalicFontMetrics;
private FontMetrics myBoldItalicFontMetrics;
private static final int CACHED_CHARS_BUFFER_SIZE = 300;
private final ArrayList<CachedFontContent> myFontCache = new ArrayList<CachedFontContent>();
@Nullable private FontInfo myCurrentFontType;
private final EditorSizeContainer mySizeContainer = new EditorSizeContainer();
private boolean myUpdateCursor;
private int myCaretUpdateVShift;
@Nullable
private final Project myProject;
private long myMouseSelectionChangeTimestamp;
private int mySavedCaretOffsetForDNDUndoHack;
private final List<FocusChangeListener> myFocusListeners = ContainerUtil.createLockFreeCopyOnWriteList();
private MyInputMethodHandler myInputMethodRequestsHandler;
private InputMethodRequests myInputMethodRequestsSwingWrapper;
private boolean myIsOneLineMode;
private boolean myIsRendererMode;
private VirtualFile myVirtualFile;
private boolean myIsColumnMode;
@Nullable private Color myForcedBackground;
@Nullable private Dimension myPreferredSize;
private int myVirtualPageHeight;
private final Alarm myMouseSelectionStateAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD);
private Runnable myMouseSelectionStateResetRunnable;
private boolean myEmbeddedIntoDialogWrapper;
@Nullable private CachedFontContent myLastCache;
private int myDragOnGutterSelectionStartLine = -1;
private RangeMarker myDraggedRange;
private boolean mySoftWrapsChanged;
// transient fields used during painting
private VisualPosition mySelectionStartPosition;
private VisualPosition mySelectionEndPosition;
private Color myLastBackgroundColor;
private Point myLastBackgroundPosition;
private int myLastBackgroundWidth;
private static final boolean ourIsUnitTestMode = ApplicationManager.getApplication().isUnitTestMode();
@NotNull private final JPanel myHeaderPanel;
@Nullable private MouseEvent myInitialMouseEvent;
private boolean myIgnoreMouseEventsConsecutiveToInitial;
private EditorDropHandler myDropHandler;
private char[] myPrefixText;
private TextAttributes myPrefixAttributes;
private int myPrefixWidthInPixels;
@NotNull private final IndentsModel myIndentsModel;
@Nullable
private CharSequence myPlaceholderText;
@Nullable private TextAttributes myPlaceholderAttributes;
private int myLastPaintedPlaceholderWidth;
private boolean myShowPlaceholderWhenFocused;
private boolean myStickySelection;
private int myStickySelectionStart;
private boolean myScrollToCaret = true;
private boolean myPurePaintingMode;
private boolean myPaintSelection;
private final EditorSizeAdjustmentStrategy mySizeAdjustmentStrategy = new EditorSizeAdjustmentStrategy();
private final Disposable myDisposable = Disposer.newDisposable();
private List<CaretState> myCaretStateBeforeLastPress;
private LogicalPosition myLastMousePressedLocation;
private VisualPosition myTargetMultiSelectionPosition;
private boolean myMultiSelectionInProgress;
private boolean myRectangularSelectionInProgress;
private boolean myLastPressCreatedCaret;
// Set when the selection (normal or block one) initiated by mouse drag becomes noticeable (at least one character is selected).
// Reset on mouse press event.
private boolean myCurrentDragIsSubstantial;
private CaretImpl myPrimaryCaret;
public final boolean myDisableRtl = Registry.is("editor.disable.rtl");
public final boolean myUseNewRendering = Registry.is("editor.new.rendering");
final EditorView myView;
private boolean myCharKeyPressed;
private boolean myNeedToSelectPreviousChar;
private boolean myDocumentChangeInProgress;
private boolean myErrorStripeNeedsRepaint;
private String myContextMenuGroupId = IdeActions.GROUP_BASIC_EDITOR_POPUP;
// Characters that excluded from zero-latency painting after key typing
private static final Set<Character> KEY_CHARS_TO_SKIP = new HashSet<Character>(Arrays.asList('\n', '\t', '(', ')', '[', ']', '{', '}', '"', '\''));
// Characters that excluded from zero-latency painting after document update
private static final Set<Character> DOCUMENT_CHARS_TO_SKIP = new HashSet<Character>(Arrays.asList(')', ']', '}', '"', '\''));
// Although it's possible to paint arbitrary line changes immediately,
// our primary interest is direct user editing actions, where visual delay is crucial.
// Moreover, as many subsystems (like PsiToDocumentSynchronizer, UndoManager, etc.) don't enforce bulk document updates,
// and can trigger multiple write actions / document changes sequentially, we need to avoid possible flickering during such an activity.
// There seems to be no other way to determine whether particular document change is triggered by direct user editing
// (raw character typing is handled separately, even before write action).
private static final Set<Class> IMMEDIATE_EDITING_ACTIONS = new HashSet<Class>(Arrays.asList(BackspaceAction.class,
DeleteAction.class,
DeleteToWordStartAction.class,
DeleteToWordEndAction.class,
DeleteToWordStartInDifferentHumpsModeAction.class,
DeleteToWordEndInDifferentHumpsModeAction.class,
DeleteToLineStartAction.class,
DeleteToLineEndAction.class,
CutAction.class,
PasteAction.class));
private Rectangle myOldArea = new Rectangle(0, 0, 0, 0);
private Rectangle myOldTailArea = new Rectangle(0, 0, 0, 0);
private boolean myImmediateEditingInProgress;
// TODO Should be removed when IDEA adopts typing without starting write actions.
private static final boolean VIM_PLUGIN_LOADED = isPluginLoaded("IdeaVIM");
static {
ourCaretBlinkingCommand.start();
}
private int myExpectedCaretOffset = -1;
EditorImpl(@NotNull Document document, boolean viewer, @Nullable Project project) {
assertIsDispatchThread();
myProject = project;
myDocument = (DocumentEx)document;
if (myDocument instanceof DocumentImpl) {
((DocumentImpl)myDocument).requestTabTracking();
}
myScheme = createBoundColorSchemeDelegate(null);
initTabPainter();
myIsViewer = viewer;
mySettings = new SettingsImpl(this, project);
if (shouldSoftWrapsBeForced()) {
mySettings.setUseSoftWrapsQuiet();
putUserData(FORCED_SOFT_WRAPS, Boolean.TRUE);
}
mySelectionModel = new SelectionModelImpl(this);
myMarkupModel = new EditorMarkupModelImpl(this);
myFoldingModel = new FoldingModelImpl(this);
myCaretModel = new CaretModelImpl(this);
mySoftWrapModel = new SoftWrapModelImpl(this);
if (!myUseNewRendering) mySizeContainer.reset();
myCommandProcessor = CommandProcessor.getInstance();
if (project != null) {
myConnection = project.getMessageBus().connect();
myConnection.subscribe(DocumentBulkUpdateListener.TOPIC, new EditorDocumentBulkUpdateAdapter());
}
MarkupModelListener markupModelListener = new MarkupModelListener() {
private boolean areRenderersInvolved(@NotNull RangeHighlighterEx highlighter) {
return highlighter.getCustomRenderer() != null ||
highlighter.getGutterIconRenderer() != null ||
highlighter.getLineMarkerRenderer() != null ||
highlighter.getLineSeparatorRenderer() != null;
}
@Override
public void afterAdded(@NotNull RangeHighlighterEx highlighter) {
attributesChanged(highlighter, areRenderersInvolved(highlighter));
}
@Override
public void beforeRemoved(@NotNull RangeHighlighterEx highlighter) {
attributesChanged(highlighter, areRenderersInvolved(highlighter));
}
@Override
public void attributesChanged(@NotNull RangeHighlighterEx highlighter, boolean renderersChanged) {
if (myDocument.isInBulkUpdate()) return; // bulkUpdateFinished() will repaint anything
if (myUseNewRendering && renderersChanged) {
updateGutterSize();
}
boolean errorStripeNeedsRepaint = renderersChanged || highlighter.getErrorStripeMarkColor() != null;
if (myUseNewRendering && myDocumentChangeInProgress) {
// postpone repaint request, as folding model can be in inconsistent state and so coordinate
// conversions might give incorrect results
myErrorStripeNeedsRepaint |= errorStripeNeedsRepaint;
return;
}
int textLength = myDocument.getTextLength();
clearTextWidthCache();
int start = Math.min(Math.max(highlighter.getAffectedAreaStartOffset(), 0), textLength);
int end = Math.min(Math.max(highlighter.getAffectedAreaEndOffset(), 0), textLength);
int startLine = start == -1 ? 0 : myDocument.getLineNumber(start);
int endLine = end == -1 ? myDocument.getLineCount() : myDocument.getLineNumber(end);
TextAttributes attributes = highlighter.getTextAttributes();
if (myUseNewRendering && start != end && attributes != null && attributes.getFontType() != Font.PLAIN) {
myView.invalidateRange(start, end);
}
repaintLines(Math.max(0, startLine - 1), Math.min(endLine + 1, getDocument().getLineCount()));
// optimization: there is no need to repaint error stripe if the highlighter is invisible on it
if (errorStripeNeedsRepaint) {
((EditorMarkupModelImpl)getMarkupModel()).repaint(start, end);
}
if (!myUseNewRendering && renderersChanged) {
updateGutterSize();
}
updateCaretCursor();
}
};
((MarkupModelEx)DocumentMarkupModel.forDocument(myDocument, myProject, true)).addMarkupModelListener(myCaretModel, markupModelListener);
getMarkupModel().addMarkupModelListener(myCaretModel, markupModelListener);
myDocument.addDocumentListener(myFoldingModel, myCaretModel);
myDocument.addDocumentListener(myCaretModel, myCaretModel);
myDocument.addDocumentListener(mySelectionModel, myCaretModel);
myDocument.addDocumentListener(new EditorDocumentAdapter(), myCaretModel);
myDocument.addDocumentListener(mySoftWrapModel, myCaretModel);
myFoldingModel.addListener(mySoftWrapModel, myCaretModel);
myIndentsModel = new IndentsModelImpl(this);
myCaretModel.addCaretListener(new CaretListener() {
@Nullable private LightweightHint myCurrentHint;
@Nullable private IndentGuideDescriptor myCurrentCaretGuide;
@Override
public void caretPositionChanged(CaretEvent e) {
if (myStickySelection) {
int selectionStart = Math.min(myStickySelectionStart, getDocument().getTextLength() - 1);
mySelectionModel.setSelection(selectionStart, myCaretModel.getVisualPosition(), myCaretModel.getOffset());
}
final IndentGuideDescriptor newGuide = myIndentsModel.getCaretIndentGuide();
if (!Comparing.equal(myCurrentCaretGuide, newGuide)) {
repaintGuide(newGuide);
repaintGuide(myCurrentCaretGuide);
myCurrentCaretGuide = newGuide;
if (myCurrentHint != null) {
myCurrentHint.hide();
myCurrentHint = null;
}
if (newGuide != null) {
final Rectangle visibleArea = getScrollingModel().getVisibleArea();
final int line = newGuide.startLine;
if (logicalLineToY(line) < visibleArea.y) {
TextRange textRange = new TextRange(myDocument.getLineStartOffset(line), myDocument.getLineEndOffset(line));
myCurrentHint = EditorFragmentComponent.showEditorFragmentHint(EditorImpl.this, textRange, false, false);
}
}
}
}
@Override
public void caretAdded(CaretEvent e) {
if (myPrimaryCaret != null) {
myPrimaryCaret.updateVisualPosition(); // repainting old primary caret's row background
}
repaintCaretRegion(e);
myPrimaryCaret = myCaretModel.getPrimaryCaret();
}
@Override
public void caretRemoved(CaretEvent e) {
repaintCaretRegion(e);
myPrimaryCaret = myCaretModel.getPrimaryCaret(); // repainting new primary caret's row background
myPrimaryCaret.updateVisualPosition();
}
});
myCaretCursor = new CaretCursor();
myFoldingModel.flushCaretShift();
myScrollBarOrientation = VERTICAL_SCROLLBAR_RIGHT;
mySoftWrapModel.addSoftWrapChangeListener(new SoftWrapChangeListenerAdapter() {
@Override
public void recalculationEnds() {
if (myCaretModel.isUpToDate()) {
myCaretModel.updateVisualPosition();
}
}
@Override
public void softWrapsChanged() {
mySoftWrapsChanged = true;
}
});
if (!myUseNewRendering) {
mySoftWrapModel.addVisualSizeChangeListener(new VisualSizeChangeListener() {
@Override
public void onLineWidthsChange(int startLine, int oldEndLine, int newEndLine, @NotNull TIntIntHashMap lineWidths) {
mySizeContainer.update(startLine, newEndLine, oldEndLine);
for (int i = startLine; i <= newEndLine; i++) {
if (lineWidths.contains(i)) {
int width = lineWidths.get(i);
if (width >= 0) {
mySizeContainer.updateLineWidthIfNecessary(i, width);
}
}
}
}
});
}
EditorHighlighter highlighter = new EmptyEditorHighlighter(myScheme.getAttributes(HighlighterColors.TEXT));
setHighlighter(highlighter);
myEditorComponent = new EditorComponentImpl(this);
myScrollPane = new MyScrollPane();
if (SystemInfo.isMac && SystemInfo.isJavaVersionAtLeast("1.7") && Registry.is("editor.mac.smooth.scrolling")) {
PreciseMouseWheelScroller.install(myScrollPane);
}
myVerticalScrollBar = (MyScrollBar)myScrollPane.getVerticalScrollBar();
myVerticalScrollBar.setOpaque(false);
myPanel = new JPanel();
UIUtil.putClientProperty(
myPanel, UIUtil.NOT_IN_HIERARCHY_COMPONENTS, new Iterable<JComponent>() {
@NotNull
@Override
public Iterator<JComponent> iterator() {
JComponent component = getPermanentHeaderComponent();
if (component != null && !component.isValid()) {
return Collections.singleton(component).iterator();
}
return ContainerUtil.emptyIterator();
}
});
myHeaderPanel = new MyHeaderPanel();
myGutterComponent = new EditorGutterComponentImpl(this);
initComponent();
myScrollingModel = new ScrollingModelImpl(this);
if (myUseNewRendering) {
myView = new EditorView(this);
myView.reinitSettings();
}
else {
myView = null;
}
if (UISettings.getInstance().PRESENTATION_MODE) {
setFontSize(UISettings.getInstance().PRESENTATION_MODE_FONT_SIZE);
}
myGutterComponent.setLineNumberAreaWidthFunction(new TIntFunction() {
@Override
public int execute(int lineNumber) {
return getFontMetrics(Font.PLAIN).stringWidth(Integer.toString(lineNumber + 1));
}
});
myGutterComponent.updateSize();
Dimension preferredSize = getPreferredSize();
myEditorComponent.setSize(preferredSize);
updateCaretCursor();
addEditorMouseListener(new MyEditorPopupHandler());
// This hacks context layout problem where editor appears scrolled to the right just after it is created.
if (!ourIsUnitTestMode) {
UiNotifyConnector.doWhenFirstShown(myEditorComponent, new Runnable() {
@Override
public void run() {
if (!isDisposed() && !myScrollingModel.isScrollingNow()) {
myScrollingModel.disableAnimation();
myScrollingModel.scrollHorizontally(0);
myScrollingModel.enableAnimation();
}
}
});
}
}
private boolean shouldSoftWrapsBeForced() {
if (mySettings.isUseSoftWraps() ||
// Disable checking for files in intermediate states - e.g. for files during refactoring.
myProject != null && PsiDocumentManager.getInstance(myProject).isDocumentBlockedByPsi(myDocument)) {
return false;
}
int lineWidthLimit = Registry.intValue("editor.soft.wrap.force.limit");
for (int i = 0; i < myDocument.getLineCount(); i++) {
if (myDocument.getLineEndOffset(i) - myDocument.getLineStartOffset(i) > lineWidthLimit) {
return true;
}
}
return false;
}
@NotNull
static Color adjustThumbColor(@NotNull Color base, boolean dark) {
return dark ? ColorUtil.withAlpha(ColorUtil.shift(base, 1.35), 0.5)
: ColorUtil.withAlpha(ColorUtil.shift(base, 0.68), 0.4);
}
boolean isDarkEnough() {
return ColorUtil.isDark(getBackgroundColor());
}
private void repaintCaretRegion(CaretEvent e) {
CaretImpl caretImpl = (CaretImpl)e.getCaret();
if (caretImpl != null) {
caretImpl.updateVisualPosition();
if (caretImpl.hasSelection()) {
repaint(caretImpl.getSelectionStart(), caretImpl.getSelectionEnd(), false);
}
}
}
@NotNull
@Override
public EditorColorsScheme createBoundColorSchemeDelegate(@Nullable final EditorColorsScheme customGlobalScheme) {
return new MyColorSchemeDelegate(customGlobalScheme);
}
private void repaintGuide(@Nullable IndentGuideDescriptor guide) {
if (guide != null) {
repaintLines(guide.startLine, guide.endLine);
}
}
@Override
public int getPrefixTextWidthInPixels() {
return myUseNewRendering ? (int)myView.getPrefixTextWidthInPixels() : myPrefixWidthInPixels;
}
@Override
public void setPrefixTextAndAttributes(@Nullable String prefixText, @Nullable TextAttributes attributes) {
myPrefixText = prefixText == null ? null : prefixText.toCharArray();
myPrefixAttributes = attributes;
myPrefixWidthInPixels = 0;
if (myPrefixText != null) {
for (char c : myPrefixText) {
LOG.assertTrue(myPrefixAttributes != null);
if (myPrefixAttributes != null) {
myPrefixWidthInPixels += EditorUtil.charWidth(c, myPrefixAttributes.getFontType(), this);
}
}
}
mySoftWrapModel.recalculate();
if (myUseNewRendering) myView.setPrefix(prefixText, attributes);
}
@Override
public boolean isPurePaintingMode() {
return myPurePaintingMode;
}
@Override
public void setPurePaintingMode(boolean enabled) {
myPurePaintingMode = enabled;
}
@Override
public void registerScrollBarRepaintCallback(@Nullable ButtonlessScrollBarUI.ScrollbarRepaintCallback callback) {
myVerticalScrollBar.registerRepaintCallback(callback);
}
@Override
public int getExpectedCaretOffset() {
return myExpectedCaretOffset == -1 ? getCaretModel().getOffset() : myExpectedCaretOffset;
}
@Override
public void setContextMenuGroupId(@Nullable String groupId) {
myContextMenuGroupId = groupId;
}
@Nullable
@Override
public String getContextMenuGroupId() {
return myContextMenuGroupId;
}
@Override
public void setViewer(boolean isViewer) {
myIsViewer = isViewer;
}
@Override
public boolean isViewer() {
return myIsViewer || myIsRendererMode;
}
@Override
public boolean isRendererMode() {
return myIsRendererMode;
}
@Override
public void setRendererMode(boolean isRendererMode) {
myIsRendererMode = isRendererMode;
}
@Override
public void setFile(VirtualFile vFile) {
myVirtualFile = vFile;
reinitSettings();
}
@Override
public VirtualFile getVirtualFile() {
return myVirtualFile;
}
@Override
public void setSoftWrapAppliancePlace(@NotNull SoftWrapAppliancePlaces place) {
mySettings.setSoftWrapAppliancePlace(place);
}
@Override
@NotNull
public SelectionModelImpl getSelectionModel() {
return mySelectionModel;
}
@Override
@NotNull
public MarkupModelEx getMarkupModel() {
return myMarkupModel;
}
@Override
@NotNull
public FoldingModelImpl getFoldingModel() {
return myFoldingModel;
}
@Override
@NotNull
public CaretModelImpl getCaretModel() {
return myCaretModel;
}
@Override
@NotNull
public ScrollingModelEx getScrollingModel() {
return myScrollingModel;
}
@Override
@NotNull
public SoftWrapModelImpl getSoftWrapModel() {
return mySoftWrapModel;
}
@Override
@NotNull
public EditorSettings getSettings() {
assertReadAccess();
return mySettings;
}
public void resetSizes() {
if (myUseNewRendering) {
myView.reset();
}
else {
mySizeContainer.reset();
}
}
@Override
public void reinitSettings() {
assertIsDispatchThread();
clearSettingsCache();
for (EditorColorsScheme scheme = myScheme; scheme instanceof DelegateColorScheme; scheme = ((DelegateColorScheme)scheme).getDelegate()) {
if (scheme instanceof MyColorSchemeDelegate) {
((MyColorSchemeDelegate)scheme).updateGlobalScheme();
break;
}
}
boolean softWrapsUsedBefore = mySoftWrapModel.isSoftWrappingEnabled();
mySettings.reinitSettings();
mySoftWrapModel.reinitSettings();
myCaretModel.reinitSettings();
mySelectionModel.reinitSettings();
ourCaretBlinkingCommand.setBlinkCaret(mySettings.isBlinkCaret());
ourCaretBlinkingCommand.setBlinkPeriod(mySettings.getCaretBlinkPeriod());
if (myUseNewRendering) {
myView.reinitSettings();
}
else {
mySizeContainer.reset();
}
myFoldingModel.rebuild();
if (softWrapsUsedBefore ^ mySoftWrapModel.isSoftWrappingEnabled()) {
mySizeContainer.reset();
validateSize();
}
myHighlighter.setColorScheme(myScheme);
myFoldingModel.refreshSettings();
myGutterComponent.reinitSettings();
myGutterComponent.revalidate();
myEditorComponent.repaint();
initTabPainter();
updateCaretCursor();
if (myInitialMouseEvent != null) {
myIgnoreMouseEventsConsecutiveToInitial = true;
}
myCaretModel.updateVisualPosition();
// make sure carets won't appear at invalid positions (e.g. on Tab width change)
for (Caret caret : getCaretModel().getAllCarets()) {
caret.moveToOffset(caret.getOffset());
}
}
private void clearSettingsCache() {
myCharHeight = -1;
myLineHeight = -1;
myDescent = -1;
myPlainFontMetrics = null;
clearTextWidthCache();
}
private void initTabPainter() {
myTabPainter = new ArrowPainter(
ColorProvider.byColorsScheme(myScheme, EditorColors.WHITESPACES_COLOR),
new Computable.PredefinedValueComputable<Integer>(EditorUtil.getSpaceWidth(Font.PLAIN, this)),
new Computable<Integer>() {
@Override
public Integer compute() {
return getCharHeight();
}
}
);
}
public void throwDisposalError(@NonNls @NotNull String msg) {
myTraceableDisposable.throwDisposalError(msg);
}
public void release() {
assertIsDispatchThread();
if (isReleased) {
throwDisposalError("Double release of editor:");
}
myTraceableDisposable.kill(null);
isReleased = true;
clearSettingsCache();
myFoldingModel.dispose();
mySoftWrapModel.release();
myMarkupModel.dispose();
myScrollingModel.dispose();
myGutterComponent.dispose();
myMousePressedEvent = null;
myMouseMovedEvent = null;
Disposer.dispose(myCaretModel);
Disposer.dispose(mySoftWrapModel);
if (myUseNewRendering) Disposer.dispose(myView);
clearCaretThread();
myFocusListeners.clear();
myMouseListeners.clear();
myMouseMotionListeners.clear();
if (myConnection != null) {
myConnection.disconnect();
}
if (myDocument instanceof DocumentImpl) {
((DocumentImpl)myDocument).giveUpTabTracking();
}
Disposer.dispose(myDisposable);
}
private void clearCaretThread() {
synchronized (ourCaretBlinkingCommand) {
if (ourCaretBlinkingCommand.myEditor == this) {
ourCaretBlinkingCommand.myEditor = null;
}
}
}
private void initComponent() {
myPanel.setLayout(new BorderLayout());
myPanel.add(myHeaderPanel, BorderLayout.NORTH);
myGutterComponent.setOpaque(true);
myScrollPane.setViewportView(myEditorComponent);
//myScrollPane.setBorder(null);
myScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
myScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
myScrollPane.setRowHeaderView(myGutterComponent);
myEditorComponent.setTransferHandler(new MyTransferHandler());
myEditorComponent.setAutoscrolls(true);
/* Default mode till 1.4.0
* myScrollPane.getViewport().setScrollMode(JViewport.BLIT_SCROLL_MODE);
*/
if (mayShowToolbar()) {
JLayeredPane layeredPane = new JBLayeredPane() {
@Override
public void doLayout() {
final Component[] components = getComponents();
final Rectangle r = getBounds();
for (Component c : components) {
if (c instanceof JScrollPane) {
c.setBounds(0, 0, r.width, r.height);
}
else {
final Dimension d = c.getPreferredSize();
final MyScrollBar scrollBar = getVerticalScrollBar();
c.setBounds(r.width - d.width - scrollBar.getWidth() - 30, 20, d.width, d.height);
}
}
}
@Override
public Dimension getPreferredSize() {
return myScrollPane.getPreferredSize();
}
};
layeredPane.add(myScrollPane, JLayeredPane.DEFAULT_LAYER);
myPanel.add(layeredPane);
new ContextMenuImpl(layeredPane, myScrollPane, this);
}
else {
myPanel.add(myScrollPane);
}
final AnActionListener.Adapter actionListener = new AnActionListener.Adapter() {
@Override
public void beforeActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event) {
if (isZeroLatencyTypingEnabled() && IMMEDIATE_EDITING_ACTIONS.contains(action.getClass())) {
myImmediateEditingInProgress = true;
}
}
@Override
public void afterActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event) {
if (isZeroLatencyTypingEnabled()) {
myImmediateEditingInProgress = false;
}
}
};
ActionManager.getInstance().addAnActionListener(actionListener);
Disposer.register(myDisposable, new Disposable() {
@Override
public void dispose() {
ActionManager.getInstance().removeAnActionListener(actionListener);
}
});
myEditorComponent.addKeyListener(new KeyListener() {
@Override
public void keyPressed(@NotNull KeyEvent e) {
if (e.getKeyCode() >= KeyEvent.VK_A && e.getKeyCode() <= KeyEvent.VK_Z) {
myCharKeyPressed = true;
}
KeyboardInternationalizationNotificationManager.showNotification();
}
@Override
public void keyTyped(@NotNull KeyEvent event) {
myNeedToSelectPreviousChar = false;
if (event.isConsumed()) {
return;
}
if (processKeyTyped(event)) {
event.consume();
}
}
@Override
public void keyReleased(KeyEvent e) {
myCharKeyPressed = false;
}
});
MyMouseAdapter mouseAdapter = new MyMouseAdapter();
myEditorComponent.addMouseListener(mouseAdapter);
myGutterComponent.addMouseListener(mouseAdapter);
MyMouseMotionListener mouseMotionListener = new MyMouseMotionListener();
myEditorComponent.addMouseMotionListener(mouseMotionListener);
myGutterComponent.addMouseMotionListener(mouseMotionListener);
myEditorComponent.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(@NotNull FocusEvent e) {
myCaretCursor.activate();
for (Caret caret : myCaretModel.getAllCarets()) {
int caretLine = caret.getLogicalPosition().line;
repaintLines(caretLine, caretLine);
}
fireFocusGained();
}
@Override
public void focusLost(@NotNull FocusEvent e) {
clearCaretThread();
for (Caret caret : myCaretModel.getAllCarets()) {
int caretLine = caret.getLogicalPosition().line;
repaintLines(caretLine, caretLine);
}
fireFocusLost();
}
});
UiNotifyConnector connector = new UiNotifyConnector(myEditorComponent, new Activatable.Adapter() {
@Override
public void showNotify() {
myGutterComponent.updateSize();
}
});
Disposer.register(getDisposable(), connector);
try {
final DropTarget dropTarget = myEditorComponent.getDropTarget();
if (dropTarget != null) { // might be null in headless environment
dropTarget.addDropTargetListener(new DropTargetAdapter() {
@Override
public void drop(@NotNull DropTargetDropEvent e) {
}
@Override
public void dragOver(@NotNull DropTargetDragEvent e) {
Point location = e.getLocation();
if (myUseNewRendering) {
getCaretModel().moveToVisualPosition(getTargetPosition(location.x, location.y, true));
}
else {
getCaretModel().moveToLogicalPosition(getLogicalPositionForScreenPos(location.x, location.y, true));
}
getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
requestFocus();
}
});
}
}
catch (TooManyListenersException e) {
LOG.error(e);
}
myPanel.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(@NotNull ComponentEvent e) {
myMarkupModel.recalcEditorDimensions();
myMarkupModel.repaint(-1, -1);
}
});
}
private boolean mayShowToolbar() {
return !isEmbeddedIntoDialogWrapper() && !isOneLineMode() && ContextMenuImpl.mayShowToolbar(myDocument);
}
@Override
public void setFontSize(final int fontSize) {
setFontSize(fontSize, null);
}
/**
* Changes editor font size, attempting to keep a given point unmoved. If point is not given, top left screen corner is assumed.
*
* @param fontSize new font size
* @param zoomCenter zoom point, relative to viewport
*/
private void setFontSize(final int fontSize, @Nullable Point zoomCenter) {
int oldFontSize = myScheme.getEditorFontSize();
Rectangle visibleArea = myScrollingModel.getVisibleArea();
Point zoomCenterRelative = zoomCenter == null ? new Point() : zoomCenter;
Point zoomCenterAbsolute = new Point(visibleArea.x + zoomCenterRelative.x, visibleArea.y + zoomCenterRelative.y);
LogicalPosition zoomCenterLogical = xyToLogicalPosition(zoomCenterAbsolute).withoutVisualPositionInfo();
int oldLineHeight = getLineHeight();
int intraLineOffset = zoomCenterAbsolute.y % oldLineHeight;
myScheme.setEditorFontSize(fontSize);
myPropertyChangeSupport.firePropertyChange(PROP_FONT_SIZE, oldFontSize, fontSize);
// Update vertical scroll bar bounds if necessary (we had a problem that use increased editor font size and it was not possible
// to scroll to the bottom of the document).
myScrollPane.getViewport().invalidate();
Point shiftedZoomCenterAbsolute = logicalPositionToXY(zoomCenterLogical);
myScrollingModel.disableAnimation();
try {
myScrollingModel.scrollToOffsets(visibleArea.x == 0 ? 0 : shiftedZoomCenterAbsolute.x - zoomCenterRelative.x, // stick to left border if it's visible
shiftedZoomCenterAbsolute.y - zoomCenterRelative.y + (intraLineOffset * getLineHeight() + oldLineHeight / 2) / oldLineHeight);
} finally {
myScrollingModel.enableAnimation();
}
}
public int getFontSize() {
return myScheme.getEditorFontSize();
}
@NotNull
public ActionCallback type(@NotNull final String text) {
final ActionCallback result = new ActionCallback();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
for (int i = 0; i < text.length(); i++) {
if (!processKeyTyped(text.charAt(i))) {
result.setRejected();
return;
}
}
result.setDone();
}
});
return result;
}
private boolean processKeyTyped(char c) {
// [vova] This is patch for Mac OS X. Under Mac "input methods"
// is handled before our EventQueue consume upcoming KeyEvents.
IdeEventQueue queue = IdeEventQueue.getInstance();
if (queue.shouldNotTypeInEditor() || ProgressManager.getInstance().hasModalProgressIndicator()) {
return false;
}
FileDocumentManager manager = FileDocumentManager.getInstance();
final VirtualFile file = manager.getFile(myDocument);
if (file != null && !file.isValid()) {
return false;
}
ActionManagerEx actionManager = ActionManagerEx.getInstanceEx();
DataContext dataContext = getDataContext();
if (isZeroLatencyTypingEnabled() && myDocument.isWritable() && !isViewer() && canPaintImmediately(c)) {
for (Caret caret : myCaretModel.getAllCarets()) {
paintImmediately(caret.getOffset(), c, myIsInsertMode);
}
}
actionManager.fireBeforeEditorTyping(c, dataContext);
MacUIUtil.hideCursor();
EditorActionManager.getInstance().getTypedAction().actionPerformed(this, c, dataContext);
return true;
}
private void fireFocusLost() {
for (FocusChangeListener listener : myFocusListeners) {
listener.focusLost(this);
}
}
private void fireFocusGained() {
for (FocusChangeListener listener : myFocusListeners) {
listener.focusGained(this);
}
}
@Override
public void setHighlighter(@NotNull final EditorHighlighter highlighter) {
assertIsDispatchThread();
final Document document = getDocument();
Disposer.dispose(myHighlighterDisposable);
document.addDocumentListener(highlighter);
myHighlighter = highlighter;
myHighlighterDisposable = new Disposable() {
@Override
public void dispose() {
document.removeDocumentListener(highlighter);
}
};
Disposer.register(myDisposable, myHighlighterDisposable);
highlighter.setEditor(this);
highlighter.setText(document.getImmutableCharSequence());
EditorHighlighterCache.rememberEditorHighlighterForCachesOptimization(document, highlighter);
if (myPanel != null) {
reinitSettings();
}
}
@NotNull
@Override
public EditorHighlighter getHighlighter() {
assertReadAccess();
return myHighlighter;
}
@Override
@NotNull
public EditorComponentImpl getContentComponent() {
return myEditorComponent;
}
@NotNull
@Override
public EditorGutterComponentImpl getGutterComponentEx() {
return myGutterComponent;
}
@Override
public void addPropertyChangeListener(@NotNull PropertyChangeListener listener) {
myPropertyChangeSupport.addPropertyChangeListener(listener);
}
@Override
public void addPropertyChangeListener(@NotNull final PropertyChangeListener listener, @NotNull Disposable parentDisposable) {
addPropertyChangeListener(listener);
Disposer.register(parentDisposable, new Disposable() {
@Override
public void dispose() {
removePropertyChangeListener(listener);
}
});
}
@Override
public void removePropertyChangeListener(@NotNull PropertyChangeListener listener) {
myPropertyChangeSupport.removePropertyChangeListener(listener);
}
@Override
public void setInsertMode(boolean mode) {
assertIsDispatchThread();
boolean oldValue = myIsInsertMode;
myIsInsertMode = mode;
myPropertyChangeSupport.firePropertyChange(PROP_INSERT_MODE, oldValue, mode);
myCaretCursor.repaint();
}
@Override
public boolean isInsertMode() {
return myIsInsertMode;
}
@Override
public void setColumnMode(boolean mode) {
assertIsDispatchThread();
boolean oldValue = myIsColumnMode;
myIsColumnMode = mode;
myPropertyChangeSupport.firePropertyChange(PROP_COLUMN_MODE, oldValue, mode);
}
@Override
public boolean isColumnMode() {
return myIsColumnMode;
}
private int yPositionToVisibleLine(int y) {
if (myUseNewRendering) return myView.yToVisualLine(y);
assert y >= 0 : y;
return y / getLineHeight();
}
@Override
@NotNull
public VisualPosition xyToVisualPosition(@NotNull Point p) {
if (myUseNewRendering) return myView.xyToVisualPosition(p);
int line = yPositionToVisibleLine(Math.max(p.y, 0));
int px = p.x;
if (line == 0 && myPrefixText != null) {
px -= myPrefixWidthInPixels;
}
if (px < 0) {
px = 0;
}
int textLength = myDocument.getTextLength();
LogicalPosition logicalPosition = visualToLogicalPosition(new VisualPosition(line, 0));
int offset = logicalPositionToOffset(logicalPosition);
int plainSpaceSize = EditorUtil.getSpaceWidth(Font.PLAIN, this);
if (offset >= textLength) return new VisualPosition(line, EditorUtil.columnsNumber(px, plainSpaceSize));
// There is a possible case that starting logical line is split by soft-wraps and it's part after the split should be drawn.
// We mark that we're under such circumstances then.
boolean activeSoftWrapProcessed = logicalPosition.softWrapLinesOnCurrentLogicalLine <= 0;
CharSequence text = myDocument.getImmutableCharSequence();
LogicalPosition endLogicalPosition = visualToLogicalPosition(new VisualPosition(line + 1, 0));
int endOffset = logicalPositionToOffset(endLogicalPosition);
if (offset > endOffset) {
LogMessageEx.error(LOG, "Detected invalid (x; y)->VisualPosition processing", String.format(
"Given point: %s, mapped to visual line %d. Visual(%d; %d) is mapped to "
+ "logical position '%s' which is mapped to offset %d (start offset). Visual(%d; %d) is mapped to logical '%s' which is mapped "
+ "to offset %d (end offset). State: %s",
p, line, line, 0, logicalPosition, offset, line + 1, 0, endLogicalPosition, endOffset, dumpState()
));
return new VisualPosition(line, EditorUtil.columnsNumber(px, plainSpaceSize));
}
IterationState state = new IterationState(this, offset, endOffset, false);
int fontType = state.getMergedAttributes().getFontType();
int x = 0;
int charWidth;
boolean onSoftWrapDrawing = false;
char c = ' ';
int prevX = 0;
int column = 0;
outer:
while (true) {
charWidth = -1;
if (offset >= textLength) {
break;
}
if (offset >= state.getEndOffset()) {
state.advance();
fontType = state.getMergedAttributes().getFontType();
}
SoftWrap softWrap = mySoftWrapModel.getSoftWrap(offset);
if (softWrap != null) {
if (activeSoftWrapProcessed) {
prevX = x;
charWidth = getSoftWrapModel().getMinDrawingWidthInPixels(SoftWrapDrawingType.BEFORE_SOFT_WRAP_LINE_FEED);
x += charWidth;
if (x >= px) {
onSoftWrapDrawing = true;
}
else {
column++;
}
break;
}
else {
CharSequence softWrapText = softWrap.getText();
for (int i = 1/*Assuming line feed is located at the first position*/; i < softWrapText.length(); i++) {
c = softWrapText.charAt(i);
prevX = x;
charWidth = charToVisibleWidth(c, fontType, x);
x += charWidth;
if (x >= px) {
break outer;
}
column += EditorUtil.columnsNumber(c, x, prevX, plainSpaceSize);
}
// Process 'after soft wrap' sign.
prevX = x;
charWidth = mySoftWrapModel.getMinDrawingWidthInPixels(SoftWrapDrawingType.AFTER_SOFT_WRAP);
x += charWidth;
if (x >= px) {
onSoftWrapDrawing = true;
break;
}
column++;
activeSoftWrapProcessed = true;
}
}
FoldRegion region = state.getCurrentFold();
if (region != null) {
char[] placeholder = region.getPlaceholderText().toCharArray();
for (char aPlaceholder : placeholder) {
c = aPlaceholder;
x += EditorUtil.charWidth(c, fontType, this);
if (x >= px) {
break outer;
}
column++;
}
offset = region.getEndOffset();
}
else {
prevX = x;
c = text.charAt(offset);
if (c == '\n') {
break;
}
charWidth = charToVisibleWidth(c, fontType, x);
x += charWidth;
if (x >= px) {
break;
}
column += EditorUtil.columnsNumber(c, x, prevX, plainSpaceSize);
offset++;
}
}
if (charWidth < 0) {
charWidth = EditorUtil.charWidth(c, fontType, this);
}
if (charWidth < 0) {
charWidth = plainSpaceSize;
}
if (x >= px && c == '\t' && !onSoftWrapDrawing) {
if (mySettings.isCaretInsideTabs()) {
column += (px - prevX) / plainSpaceSize;
if ((px - prevX) % plainSpaceSize > plainSpaceSize / 2) column++;
}
else if ((x - px) * 2 < x - prevX) {
column += EditorUtil.columnsNumber(c, x, prevX, plainSpaceSize);
}
}
else {
if (x >= px) {
if (c != '\n' && (x - px) * 2 < charWidth) column++;
}
else {
int diff = px - x;
column += diff / plainSpaceSize;
if (diff % plainSpaceSize * 2 >= plainSpaceSize) {
column++;
}
}
}
return new VisualPosition(line, column);
}
/**
* Allows to answer how much width requires given char to be represented on a screen.
*
* @param c target character
* @param fontType font type to use for representation of the given character
* @param currentX current <code>'x'</code> position on a line where given character should be displayed
* @return width required to represent given char with the given settings on a screen;
* <code>'0'</code> if given char is a line break
*/
private int charToVisibleWidth(char c, @JdkConstants.FontStyle int fontType, int currentX) {
if (c == '\n') {
return 0;
}
if (c == '\t') {
return EditorUtil.nextTabStop(currentX, this) - currentX;
}
return EditorUtil.charWidth(c, fontType, this);
}
@NotNull
public Point offsetToXY(int offset, boolean leanTowardsLargerOffsets) {
return myUseNewRendering ? myView.offsetToXY(offset, leanTowardsLargerOffsets, false) :
visualPositionToXY(offsetToVisualPosition(offset, leanTowardsLargerOffsets, false));
}
@Override
@NotNull
public VisualPosition offsetToVisualPosition(int offset) {
return offsetToVisualPosition(offset, false, false);
}
@Override
@NotNull
public VisualPosition offsetToVisualPosition(int offset, boolean leanForward, boolean beforeSoftWrap) {
if (myUseNewRendering) return myView.offsetToVisualPosition(offset, leanForward, beforeSoftWrap);
return logicalToVisualPosition(offsetToLogicalPosition(offset));
}
@Override
@NotNull
public LogicalPosition offsetToLogicalPosition(int offset) {
return offsetToLogicalPosition(offset, true);
}
@NotNull
@Override
public LogicalPosition offsetToLogicalPosition(int offset, boolean softWrapAware) {
if (myUseNewRendering) return myView.offsetToLogicalPosition(offset);
if (softWrapAware) {
return mySoftWrapModel.offsetToLogicalPosition(offset);
}
int line = offsetToLogicalLine(offset);
int column = calcColumnNumber(offset, line, false, myDocument.getImmutableCharSequence());
return new LogicalPosition(line, column);
}
@TestOnly
public void setCaretActive() {
synchronized (ourCaretBlinkingCommand) {
ourCaretBlinkingCommand.myEditor = this;
}
}
// optimization: do not do column calculations here since we are interested in line number only
public int offsetToVisualLine(int offset) {
if (myUseNewRendering) return myView.offsetToVisualLine(offset, false);
int textLength = getDocument().getTextLength();
if (offset >= textLength) {
return Math.max(0, getVisibleLineCount() - 1); // lines are 0 based
}
int line = offsetToLogicalLine(offset);
int lineStartOffset = line >= myDocument.getLineCount() ? myDocument.getTextLength() : myDocument.getLineStartOffset(line);
int result = logicalToVisualLine(line);
// There is a possible case that logical line that contains target offset is soft-wrapped (represented in more than one visual
// line). Hence, we need to perform necessary adjustments to the visual line that is used to show logical line start if necessary.
int i = getSoftWrapModel().getSoftWrapIndex(lineStartOffset);
if (i < 0) {
i = -i - 1;
}
List<? extends SoftWrap> softWraps = getSoftWrapModel().getRegisteredSoftWraps();
for (; i < softWraps.size(); i++) {
SoftWrap softWrap = softWraps.get(i);
if (softWrap.getStart() > offset) {
break;
}
result++; // Assuming that every soft wrap contains only one virtual line feed symbol
}
return result;
}
private int logicalToVisualLine(int line) {
assertReadAccess();
return logicalToVisualPosition(new LogicalPosition(line, 0)).line;
}
@Override
@NotNull
public LogicalPosition xyToLogicalPosition(@NotNull Point p) {
Point pp = p.x >= 0 && p.y >= 0 ? p : new Point(Math.max(p.x, 0), Math.max(p.y, 0));
return visualToLogicalPosition(xyToVisualPosition(pp));
}
private int logicalLineToY(int line) {
VisualPosition visible = logicalToVisualPosition(new LogicalPosition(line, 0));
return visibleLineToY(visible.line);
}
@Override
@NotNull
public Point logicalPositionToXY(@NotNull LogicalPosition pos) {
VisualPosition visible = logicalToVisualPosition(pos);
return visualPositionToXY(visible);
}
@Override
@NotNull
public Point visualPositionToXY(@NotNull VisualPosition visible) {
if (myUseNewRendering) return myView.visualPositionToXY(visible);
int y = visibleLineToY(visible.line);
LogicalPosition logical = visualToLogicalPosition(new VisualPosition(visible.line, 0));
int logLine = logical.line;
int lineStartOffset = -1;
int reserved = 0;
int column = visible.column;
if (logical.softWrapLinesOnCurrentLogicalLine > 0) {
int linesToSkip = logical.softWrapLinesOnCurrentLogicalLine;
List<? extends SoftWrap> softWraps = getSoftWrapModel().getSoftWrapsForLine(logLine);
for (SoftWrap softWrap : softWraps) {
if (myFoldingModel.isOffsetCollapsed(softWrap.getStart()) && myFoldingModel.isOffsetCollapsed(softWrap.getStart() - 1)) {
continue;
}
linesToSkip--; // Assuming here that every soft wrap has exactly one line feed
if (linesToSkip > 0) {
continue;
}
lineStartOffset = softWrap.getStart();
int widthInColumns = softWrap.getIndentInColumns();
int widthInPixels = softWrap.getIndentInPixels();
if (widthInColumns <= column) {
column -= widthInColumns;
reserved = widthInPixels;
}
else {
char[] softWrapChars = softWrap.getChars();
int i = CharArrayUtil.lastIndexOf(softWrapChars, '\n', 0, softWrapChars.length);
int start = 0;
if (i >= 0) {
start = i + 1;
}
return new Point(EditorUtil.textWidth(this, softWrap.getText(), start, column + 1, Font.PLAIN, 0), y);
}
break;
}
}
if (logLine < 0) {
lineStartOffset = 0;
}
else if (lineStartOffset < 0) {
lineStartOffset = logLine >= myDocument.getLineCount() ? myDocument.getTextLength() : myDocument.getLineStartOffset(logLine);
}
int x = getTabbedTextWidth(lineStartOffset, column, reserved);
return new Point(x, y);
}
private int calcEndOffset(int startOffset, int visualColumn) {
FoldRegion[] regions = myFoldingModel.fetchTopLevel();
if (regions == null) {
return startOffset + visualColumn;
}
int low = 0;
int high = regions.length - 1;
int i = -1;
while (low <= high) {
int mid = low + high >>> 1;
FoldRegion midVal = regions[mid];
if (midVal.getStartOffset() <= startOffset && midVal.getEndOffset() > startOffset) {
i = mid;
break;
}
if (midVal.getStartOffset() < startOffset)
low = mid + 1;
else if (midVal.getStartOffset() > startOffset)
high = mid - 1;
}
if (i < 0) {
i = low;
}
int result = startOffset;
int columnsToProcess = visualColumn;
for (; i < regions.length; i++) {
FoldRegion region = regions[i];
// Process text between the last fold region end and current fold region start.
int nonFoldTextColumnsNumber = region.getStartOffset() - result;
if (nonFoldTextColumnsNumber >= columnsToProcess) {
return result + columnsToProcess;
}
columnsToProcess -= nonFoldTextColumnsNumber;
// Process fold region.
int placeHolderLength = region.getPlaceholderText().length();
if (placeHolderLength >= columnsToProcess) {
return region.getEndOffset();
}
result = region.getEndOffset();
columnsToProcess -= placeHolderLength;
}
return result + columnsToProcess;
}
public int findNearestDirectionBoundary(int offset, boolean lookForward) {
return myUseNewRendering ? myView.findNearestDirectionBoundary(offset, lookForward) : -1;
}
// TODO: tabbed text width is additive, it should be possible to have buckets, containing arguments / values to start with
private final int[] myLastStartOffsets = new int[2];
private final int[] myLastTargetColumns = new int[myLastStartOffsets.length];
private final int[] myLastXOffsets = new int[myLastStartOffsets.length];
private final int[] myLastXs = new int[myLastStartOffsets.length];
private int myCurrentCachePosition;
private int myLastCacheHits;
private int myTotalRequests; // todo remove
private int getTabbedTextWidth(int startOffset, int targetColumn, int xOffset) {
int x = xOffset;
if (startOffset == 0 && myPrefixText != null) {
x += myPrefixWidthInPixels;
}
if (targetColumn <= 0) return x;
++myTotalRequests;
for(int i = 0; i < myLastStartOffsets.length; ++i) {
if (startOffset == myLastStartOffsets[i] && targetColumn == myLastTargetColumns[i] && xOffset == myLastXOffsets[i]) {
++myLastCacheHits;
if ((myLastCacheHits & 0xFFF) == 0) { // todo remove
PsiFile file = myProject != null ? PsiDocumentManager.getInstance(myProject).getCachedPsiFile(myDocument):null;
LOG.info("Cache hits:" + myLastCacheHits + ", total requests:" +
myTotalRequests + "," + (file != null ? file.getViewProvider().getVirtualFile():null));
}
return myLastXs[i];
}
}
int offset = startOffset;
CharSequence text = myDocument.getImmutableCharSequence();
int textLength = myDocument.getTextLength();
// We need to calculate max offset to provide to the IterationState here based on the given start offset and target
// visual column. The problem is there is a possible case that there is a collapsed fold region at the target interval,
// so, we can't just use 'startOffset + targetColumn' as a max end offset.
IterationState state = new IterationState(this, startOffset, calcEndOffset(startOffset, targetColumn), false);
int fontType = state.getMergedAttributes().getFontType();
int plainSpaceSize = EditorUtil.getSpaceWidth(Font.PLAIN, this);
int column = 0;
outer:
while (column < targetColumn) {
if (offset >= textLength) break;
if (offset >= state.getEndOffset()) {
state.advance();
fontType = state.getMergedAttributes().getFontType();
}
// We need to consider 'before soft wrap drawing'.
SoftWrap softWrap = getSoftWrapModel().getSoftWrap(offset);
if (softWrap != null && offset > startOffset) {
column++;
x += getSoftWrapModel().getMinDrawingWidthInPixels(SoftWrapDrawingType.BEFORE_SOFT_WRAP_LINE_FEED);
// Assuming that first soft wrap symbol is line feed or all soft wrap symbols before the first line feed are spaces.
break;
}
FoldRegion region = state.getCurrentFold();
if (region != null) {
char[] placeholder = region.getPlaceholderText().toCharArray();
for (char aPlaceholder : placeholder) {
x += EditorUtil.charWidth(aPlaceholder, fontType, this);
column++;
if (column >= targetColumn) break outer;
}
offset = region.getEndOffset();
}
else {
char c = text.charAt(offset);
if (c == '\n') {
break;
}
if (c == '\t') {
int prevX = x;
x = EditorUtil.nextTabStop(x, this);
int columnDiff = (x - prevX) / plainSpaceSize;
if ((x - prevX) % plainSpaceSize > 0) {
// There is a possible case that tabulation symbol takes more than one visual column to represent and it's shown at
// soft-wrapped line. Soft wrap sign width may be not divisible by space size, hence, part of tabulation symbol represented
// as a separate visual column may take less space than space width.
columnDiff++;
}
column += columnDiff;
}
else {
x += EditorUtil.charWidth(c, fontType, this);
column++;
}
offset++;
}
}
if (column != targetColumn) {
x += EditorUtil.getSpaceWidth(fontType, this) * (targetColumn - column);
}
myLastTargetColumns[myCurrentCachePosition] = targetColumn;
myLastStartOffsets[myCurrentCachePosition] = startOffset;
myLastXs[myCurrentCachePosition] = x;
myLastXOffsets[myCurrentCachePosition] = xOffset;
myCurrentCachePosition = (myCurrentCachePosition + 1) % myLastStartOffsets.length;
return x;
}
private void clearTextWidthCache() {
for(int i = 0; i < myLastStartOffsets.length; ++i) {
myLastTargetColumns[i] = -1;
myLastStartOffsets[i] = - 1;
myLastXs[i] = -1;
myLastXOffsets[i] = -1;
}
}
public int visibleLineToY(int line) {
if (myUseNewRendering) return myView.visualLineToY(line);
if (line < 0) throw new IndexOutOfBoundsException("Wrong line: " + line);
return line * getLineHeight();
}
@Override
public void repaint(int startOffset, int endOffset) {
repaint(startOffset, endOffset, true);
}
void repaint(int startOffset, int endOffset, boolean invalidateTextLayout) {
if (myDocument.isInBulkUpdate()) {
return;
}
if (myUseNewRendering) {
assertIsDispatchThread();
endOffset = Math.min(endOffset, myDocument.getTextLength());
if (invalidateTextLayout) {
myView.invalidateRange(startOffset, endOffset);
}
if (!isShowing()) {
return;
}
}
else {
if (!isShowing()) {
return;
}
endOffset = Math.min(endOffset, myDocument.getTextLength());
assertIsDispatchThread();
}
// We do repaint in case of equal offsets because there is a possible case that there is a soft wrap at the same offset and
// it does occupy particular amount of visual space that may be necessary to repaint.
if (startOffset <= endOffset) {
int startLine = myDocument.getLineNumber(startOffset);
int endLine = myDocument.getLineNumber(endOffset);
repaintLines(startLine, endLine);
}
}
private boolean isShowing() {
return myGutterComponent.isShowing();
}
private void repaintToScreenBottom(int startLine) {
Rectangle visibleArea = getScrollingModel().getVisibleArea();
int yStartLine = logicalLineToY(startLine);
int yEndLine = visibleArea.y + visibleArea.height;
myEditorComponent.repaintEditorComponent(visibleArea.x, yStartLine, visibleArea.x + visibleArea.width, yEndLine - yStartLine);
myGutterComponent.repaint(0, yStartLine, myGutterComponent.getWidth(), yEndLine - yStartLine);
((EditorMarkupModelImpl)getMarkupModel()).repaint(-1, -1);
}
/**
* Asks to repaint all logical lines from the given <code>[start; end]</code> range.
*
* @param startLine start logical line to repaint (inclusive)
* @param endLine end logical line to repaint (inclusive)
*/
private void repaintLines(int startLine, int endLine) {
if (!isShowing()) return;
Rectangle visibleArea = getScrollingModel().getVisibleArea();
int yStartLine = logicalLineToY(startLine);
int endVisLine = myDocument.getTextLength() <= 0
? 0
: offsetToVisualLine(myDocument.getLineEndOffset(Math.min(myDocument.getLineCount() - 1, endLine)));
int height = endVisLine * getLineHeight() - yStartLine + getLineHeight() + 2;
myEditorComponent.repaintEditorComponent(visibleArea.x, yStartLine, visibleArea.x + visibleArea.width, height);
myGutterComponent.repaint(0, yStartLine, myGutterComponent.getWidth(), height);
}
private void bulkUpdateStarted() {
saveCaretRelativePosition();
myCaretModel.onBulkDocumentUpdateStarted();
mySoftWrapModel.onBulkDocumentUpdateStarted();
myFoldingModel.onBulkDocumentUpdateStarted();
}
private void bulkUpdateFinished() {
myFoldingModel.onBulkDocumentUpdateFinished();
mySoftWrapModel.onBulkDocumentUpdateFinished();
myCaretModel.onBulkDocumentUpdateFinished();
clearTextWidthCache();
setMouseSelectionState(MOUSE_SELECTION_STATE_NONE);
if (myUseNewRendering) {
myView.reset();
}
else {
mySizeContainer.reset();
}
validateSize();
updateGutterSize();
repaintToScreenBottom(0);
updateCaretCursor();
restoreCaretRelativePosition();
}
private void beforeChangedUpdate(@NotNull DocumentEvent e) {
myDocumentChangeInProgress = true;
if (isStickySelection()) {
setStickySelection(false);
}
if (myDocument.isInBulkUpdate()) {
// Assuming that the job is done at bulk listener callback methods.
return;
}
saveCaretRelativePosition();
// We assume that size container is already notified with the visual line widths during soft wraps processing
if (!mySoftWrapModel.isSoftWrappingEnabled() && !myUseNewRendering) {
mySizeContainer.beforeChange(e);
}
if (isZeroLatencyTypingEnabled() && myImmediateEditingInProgress && canPaintImmediately(e)) {
int offset = e.getOffset();
int length = e.getOldLength();
myOldArea = lineRectangleBetween(offset, offset + length);
myOldTailArea = lineRectangleBetween(offset + length, myDocument.getLineEndOffset(myDocument.getLineNumber(offset)));
if (myOldTailArea.isEmpty()) {
myOldTailArea.width += EditorUtil.getSpaceWidth(Font.PLAIN, this); // include possible caret
}
}
}
private void changedUpdate(DocumentEvent e) {
myDocumentChangeInProgress = false;
if (myDocument.isInBulkUpdate()) return;
if (isZeroLatencyTypingEnabled() && myImmediateEditingInProgress && canPaintImmediately(e)) {
paintImmediately(e);
}
if (myErrorStripeNeedsRepaint) {
myMarkupModel.repaint(e.getOffset(), e.getOffset() + e.getNewLength());
myErrorStripeNeedsRepaint = false;
}
clearTextWidthCache();
setMouseSelectionState(MOUSE_SELECTION_STATE_NONE);
// We assume that size container is already notified with the visual line widths during soft wraps processing
if (!mySoftWrapModel.isSoftWrappingEnabled() && !myUseNewRendering) {
mySizeContainer.changedUpdate(e);
}
validateSize();
int startLine = offsetToLogicalLine(e.getOffset());
int endLine = offsetToLogicalLine(e.getOffset() + e.getNewLength());
boolean painted = false;
if (myDocument.getTextLength() > 0) {
int startDocLine = myDocument.getLineNumber(e.getOffset());
int endDocLine = myDocument.getLineNumber(e.getOffset() + e.getNewLength());
if (e.getOldLength() > e.getNewLength() || startDocLine != endDocLine || StringUtil.indexOf(e.getOldFragment(), '\n') != -1) {
updateGutterSize();
}
if (countLineFeeds(e.getOldFragment()) != countLineFeeds(e.getNewFragment())) {
// Lines removed. Need to repaint till the end of the screen
repaintToScreenBottom(startLine);
painted = true;
}
}
updateCaretCursor();
if (!painted) {
repaintLines(startLine, endLine);
}
if (getCaretModel().getOffset() < e.getOffset() || getCaretModel().getOffset() > e.getOffset() + e.getNewLength()){
restoreCaretRelativePosition();
}
}
private void saveCaretRelativePosition() {
Rectangle visibleArea = getScrollingModel().getVisibleArea();
Point pos = visualPositionToXY(getCaretModel().getVisualPosition());
myCaretUpdateVShift = pos.y - visibleArea.y;
}
private void restoreCaretRelativePosition() {
Point caretLocation = visualPositionToXY(getCaretModel().getVisualPosition());
int scrollOffset = caretLocation.y - myCaretUpdateVShift;
getScrollingModel().disableAnimation();
getScrollingModel().scrollVertically(scrollOffset);
getScrollingModel().enableAnimation();
}
public boolean hasTabs() {
return !(myDocument instanceof DocumentImpl) || ((DocumentImpl)myDocument).mightContainTabs();
}
public boolean isScrollToCaret() {
return myScrollToCaret;
}
public void setScrollToCaret(boolean scrollToCaret) {
myScrollToCaret = scrollToCaret;
}
@NotNull
public Disposable getDisposable() {
return myDisposable;
}
private static int countLineFeeds(@NotNull CharSequence c) {
return StringUtil.countNewLines(c);
}
private boolean updatingSize; // accessed from EDT only
private void updateGutterSize() {
assertIsDispatchThread();
if (!updatingSize) {
updatingSize = true;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
if (!isDisposed()) {
myGutterComponent.updateSize();
}
}
finally {
updatingSize = false;
}
}
});
}
}
void validateSize() {
Dimension dim = getPreferredSize();
if (!dim.equals(myPreferredSize) && !myDocument.isInBulkUpdate()) {
dim = mySizeAdjustmentStrategy.adjust(dim, myPreferredSize, this);
if (dim == null) {
return;
}
myPreferredSize = dim;
myGutterComponent.updateSize();
myEditorComponent.setSize(dim);
myEditorComponent.fireResized();
myMarkupModel.recalcEditorDimensions();
myMarkupModel.repaint(-1, -1);
}
}
void recalculateSizeAndRepaint() {
if (!myUseNewRendering) mySizeContainer.reset();
validateSize();
myEditorComponent.repaintEditorComponent();
}
@Override
@NotNull
public DocumentEx getDocument() {
return myDocument;
}
@Override
@NotNull
public JComponent getComponent() {
return myPanel;
}
@Override
public void addEditorMouseListener(@NotNull EditorMouseListener listener) {
myMouseListeners.add(listener);
}
@Override
public void removeEditorMouseListener(@NotNull EditorMouseListener listener) {
boolean success = myMouseListeners.remove(listener);
LOG.assertTrue(success || isReleased);
}
@Override
public void addEditorMouseMotionListener(@NotNull EditorMouseMotionListener listener) {
myMouseMotionListeners.add(listener);
}
@Override
public void removeEditorMouseMotionListener(@NotNull EditorMouseMotionListener listener) {
boolean success = myMouseMotionListeners.remove(listener);
LOG.assertTrue(success || isReleased);
}
@Override
public boolean isStickySelection() {
return myStickySelection;
}
@Override
public void setStickySelection(boolean enable) {
myStickySelection = enable;
if (enable) {
myStickySelectionStart = getCaretModel().getOffset();
}
else {
mySelectionModel.removeSelection();
}
}
@Override
public boolean isDisposed() {
return isReleased;
}
public void stopDumbLater() {
if (ApplicationManager.getApplication().isUnitTestMode()) return;
final Runnable stopDumbRunnable = new Runnable() {
@Override
public void run() {
stopDumb();
}
};
ApplicationManager.getApplication().invokeLater(stopDumbRunnable, ModalityState.current());
}
void resetPaintersWidth() {
myLinePaintersWidth = 0;
}
private void stopDumb() {
putUserData(BUFFER, null);
}
/**
* {@link #stopDumbLater} or {@link #stopDumb} must be performed in finally
*/
public void startDumb() {
if (ApplicationManager.getApplication().isUnitTestMode()) return;
Rectangle rect = ((JViewport)myEditorComponent.getParent()).getViewRect();
BufferedImage image = UIUtil.createImage(rect.width, rect.height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = image.createGraphics();
graphics.translate(-rect.x, -rect.y);
graphics.setClip(rect.x, rect.y, rect.width, rect.height);
myEditorComponent.paintComponent(graphics);
graphics.dispose();
putUserData(BUFFER, image);
}
private static boolean isZeroLatencyTypingEnabled() {
// Zero-latency typing is suppressed when Idea VIM plugin is loaded, because of VIM-1007.
// That issue will be resolved automatically when IDEA adopts typing without starting write actions.
return !VIM_PLUGIN_LOADED && Registry.is("editor.zero.latency.typing");
}
private static boolean isPluginLoaded(@NotNull String id) {
PluginId pluginId = PluginId.findId(id);
if (pluginId == null) return false;
IdeaPluginDescriptor plugin = PluginManager.getPlugin(pluginId);
if (plugin == null) return false;
return plugin.isEnabled();
}
private boolean canPaintImmediately(char c) {
return myDocument instanceof DocumentImpl &&
myHighlighter instanceof LexerEditorHighlighter &&
!mySelectionModel.hasSelection() &&
arePositionsWithinDocument(myCaretModel.getAllCarets()) &&
areVisualLinesUnique(myCaretModel.getAllCarets()) &&
!isInplaceRenamerActive() &&
!KEY_CHARS_TO_SKIP.contains(c);
}
private static boolean areVisualLinesUnique(List<Caret> carets) {
if (carets.size() > 1) {
TIntHashSet lines = new TIntHashSet(carets.size());
for (Caret caret : carets) {
if (!lines.add(caret.getVisualLineStart())) {
return false;
}
}
}
return true;
}
// Checks whether all the carets are within document or some of them are in a so called "virtual space".
private boolean arePositionsWithinDocument(List<Caret> carets) {
for (Caret caret : carets) {
if (caret.getLogicalPosition().compareTo(offsetToLogicalPosition(caret.getOffset())) != 0) {
return false;
}
}
return true;
}
// TODO Improve the approach - handle such cases in a more general way.
private boolean isInplaceRenamerActive() {
Key<?> key = Key.findKeyByName("EditorInplaceRenamer");
return key != null && key.isIn(this);
}
// Called to display a single character insertion before starting a write action and the general painting routine.
// Bypasses RepaintManager (c.repaint, c.paintComponent) and double buffering (g.paintImmediately) to minimize visual lag.
// TODO Should be replaced with the generic paintImmediately(event) call when we implement typing without starting write actions.
private void paintImmediately(int offset, char c, boolean insert) {
Graphics g = myEditorComponent.getGraphics();
if (g == null) return; // editor component is currently not displayable
TextAttributes attributes = ((LexerEditorHighlighter)myHighlighter).getAttributes((DocumentImpl)myDocument, offset, c);
int fontType = attributes.getFontType();
FontInfo fontInfo = EditorUtil.fontForChar(c, attributes.getFontType(), this);
Font font = fontInfo.getFont();
// it's more reliable to query actual font metrics
FontMetrics fontMetrics = getFontMetrics(fontType);
int charWidth = fontMetrics.charWidth(c);
int delta = charWidth;
if (!insert && offset < myDocument.getTextLength()) {
delta -= fontMetrics.charWidth(myDocument.getCharsSequence().charAt(offset));
}
Rectangle tailArea = lineRectangleBetween(offset, myDocument.getLineEndOffset(offsetToLogicalLine(offset)));
if (tailArea.isEmpty()) {
tailArea.width += EditorUtil.getSpaceWidth(fontType, this); // include caret
}
Color lineColor = getCaretRowBackground();
Rectangle newArea = lineRectangleBetween(offset, offset);
newArea.width += charWidth;
String newText = Character.toString(c);
Point point = newArea.getLocation();
int ascent = getAscent();
Color color = attributes.getForegroundColor() == null ? getForegroundColor() : attributes.getForegroundColor();
EditorUIUtil.setupAntialiasing(g);
// pre-compute all the arguments beforehand to minimize delays between the calls (as there's no double-buffering)
if (delta != 0) {
shift(g, tailArea, delta);
}
fill(g, newArea, lineColor);
print(g, newText, point, ascent, font, color);
}
private boolean canPaintImmediately(@NotNull DocumentEvent e) {
return myDocument instanceof DocumentImpl &&
!isInplaceRenamerActive() &&
!contains(e.getOldFragment(), '\n') &&
!contains(e.getNewFragment(), '\n') &&
!(e.getNewLength() == 1 && DOCUMENT_CHARS_TO_SKIP.contains(e.getNewFragment().charAt(0)));
}
private static boolean contains(@NotNull CharSequence chars, char c) {
for (int i = 0; i < chars.length(); i++) {
if (chars.charAt(i) == c) {
return true;
}
}
return false;
}
// Called to display insertion / deletion / replacement within a single line before the general painting routine.
// Bypasses RepaintManager (c.repaint, c.paintComponent) and double buffering (g.paintImmediately) to minimize visual lag.
private void paintImmediately(@NotNull DocumentEvent e) {
Graphics g = myEditorComponent.getGraphics();
if (g == null) return; // editor component is currently not displayable
int offset = e.getOffset();
String newText = e.getNewFragment().toString();
Rectangle newArea = lineRectangleBetween(offset, offset + newText.length());
int delta = newArea.width - myOldArea.width;
Color lineColor = getCaretRowBackground();
if (delta != 0) {
if (delta < 0) {
// Pre-paint carets at new positions, if needed, before shifting the tail area (to avoid flickering),
// because painting takes some time while copyArea is almost instantaneous.
CaretRectangle[] caretRectangles = myCaretCursor.getCaretLocations(true);
if (caretRectangles != null) {
for (CaretRectangle it : caretRectangles) {
Rectangle r = toRectangle(it);
if (myOldArea.contains(r) && !newArea.contains(r)) {
myCaretCursor.paintAt(g, it.myPoint.x - delta, it.myPoint.y, it.myWidth, it.myCaret);
}
}
}
}
shift(g, myOldTailArea, delta);
if (delta < 0) {
Rectangle remainingArea = new Rectangle(myOldTailArea.x + myOldTailArea.width + delta,
myOldTailArea.y, -delta, myOldTailArea.height);
fill(g, remainingArea, lineColor);
}
}
if (!newArea.isEmpty()) {
TextAttributes attributes = myHighlighter.createIterator(offset).getTextAttributes();
Point point = newArea.getLocation();
int ascent = getAscent();
// simplified font selection (based on the first character)
FontInfo fontInfo = EditorUtil.fontForChar(newText.charAt(0), attributes.getFontType(), this);
Font font = fontInfo.getFont();
Color color = attributes.getForegroundColor() == null ? getForegroundColor() : attributes.getForegroundColor();
EditorUIUtil.setupAntialiasing(g);
// pre-compute all the arguments beforehand to minimize delay between the calls (as there's no double-buffering)
fill(g, newArea, lineColor);
print(g, newText, point, ascent, font, color);
}
}
@NotNull
private Rectangle lineRectangleBetween(int begin, int end) {
Point p1 = offsetToXY(begin, false);
Point p2 = offsetToXY(end, false);
// When soft wrap is present, handle only the first visual line (for simplicity, yet it works reasonably well)
int x2 = p1.y == p2.y ? p2.x : Math.max(p1.x, myEditorComponent.getWidth() - getVerticalScrollBar().getWidth());
return new Rectangle(p1.x, p1.y, x2 - p1.x, getLineHeight());
}
@NotNull
private Rectangle toRectangle(@NotNull CaretRectangle caretRectangle) {
Point p = caretRectangle.myPoint;
return new Rectangle(p.x, p.y, caretRectangle.myWidth, getLineHeight());
}
@NotNull
private Color getCaretRowBackground() {
Color color = myScheme.getColor(EditorColors.CARET_ROW_COLOR);
return color == null ? getBackgroundColor() : color;
}
private static void shift(@NotNull Graphics g, @NotNull Rectangle r, int delta) {
g.copyArea(r.x, r.y, r.width, r.height, delta, 0);
}
private static void fill(@NotNull Graphics g, @NotNull Rectangle r, @NotNull Color color) {
g.setColor(color);
g.fillRect(r.x, r.y, r.width, r.height);
}
private static void print(@NotNull Graphics g, @NotNull String text, @NotNull Point point,
int ascent, @NotNull Font font, @NotNull Color color) {
g.setFont(font);
g.setColor(color);
g.drawString(text, point.x, point.y + ascent);
}
void paint(@NotNull Graphics2D g) {
Rectangle clip = g.getClipBounds();
if (clip == null) {
return;
}
if (Registry.is("editor.dumb.mode.available")) {
final BufferedImage buffer = getUserData(BUFFER);
if (buffer != null) {
final Rectangle rect = getContentComponent().getVisibleRect();
UIUtil.drawImage(g, buffer, null, rect.x, rect.y);
return;
}
}
if (myUpdateCursor) {
setCursorPosition();
myUpdateCursor = false;
}
if (isReleased) {
g.setColor(new JBColor(new Color(128, 255, 128), new Color(128, 255, 128)));
g.fillRect(clip.x, clip.y, clip.width, clip.height);
return;
}
if (myProject != null && myProject.isDisposed()) return;
if (myUseNewRendering) {
myView.paint(g);
}
else {
VisualPosition clipStartVisualPos = xyToVisualPosition(new Point(0, clip.y));
LogicalPosition clipStartPosition = visualToLogicalPosition(clipStartVisualPos);
int clipStartOffset = logicalPositionToOffset(clipStartPosition);
LogicalPosition clipEndPosition = xyToLogicalPosition(new Point(0, clip.y + clip.height + getLineHeight()));
int clipEndOffset = logicalPositionToOffset(clipEndPosition);
paintBackgrounds(g, clip, clipStartPosition, clipStartVisualPos, clipStartOffset, clipEndOffset);
if (paintPlaceholderText(g, clip)) {
paintCaretCursor(g);
return;
}
paintRightMargin(g, clip);
paintCustomRenderers(g, clipStartOffset, clipEndOffset);
MarkupModelEx docMarkup = (MarkupModelEx)DocumentMarkupModel.forDocument(myDocument, myProject, true);
paintLineMarkersSeparators(g, clip, docMarkup, clipStartOffset, clipEndOffset);
paintLineMarkersSeparators(g, clip, myMarkupModel, clipStartOffset, clipEndOffset);
paintText(g, clip, clipStartPosition, clipStartOffset, clipEndOffset);
paintSegmentHighlightersBorderAndAfterEndOfLine(g, clip, clipStartOffset, clipEndOffset, docMarkup);
BorderEffect borderEffect = new BorderEffect(this, g, clipStartOffset, clipEndOffset);
borderEffect.paintHighlighters(getHighlighter());
borderEffect.paintHighlighters(docMarkup);
borderEffect.paintHighlighters(myMarkupModel);
paintCaretCursor(g);
paintComposedTextDecoration(g);
}
}
private static final char IDEOGRAPHIC_SPACE = '\u3000'; // http://www.marathon-studios.com/unicode/U3000/Ideographic_Space
private static final String WHITESPACE_CHARS = " \t" + IDEOGRAPHIC_SPACE;
private void paintCustomRenderers(@NotNull final Graphics2D g, final int clipStartOffset, final int clipEndOffset) {
myMarkupModel.processRangeHighlightersOverlappingWith(clipStartOffset, clipEndOffset, new Processor<RangeHighlighterEx>() {
@Override
public boolean process(@NotNull RangeHighlighterEx highlighter) {
if (!highlighter.getEditorFilter().avaliableIn(EditorImpl.this)) return true;
final CustomHighlighterRenderer customRenderer = highlighter.getCustomRenderer();
if (customRenderer != null && clipStartOffset < highlighter.getEndOffset() && highlighter.getStartOffset() < clipEndOffset) {
customRenderer.paint(EditorImpl.this, highlighter, g);
}
return true;
}
});
}
@NotNull
@Override
public IndentsModel getIndentsModel() {
return myIndentsModel;
}
@Override
public void setHeaderComponent(JComponent header) {
myHeaderPanel.removeAll();
header = header == null ? getPermanentHeaderComponent() : header;
if (header != null) {
myHeaderPanel.add(header);
}
myHeaderPanel.revalidate();
}
@Override
public boolean hasHeaderComponent() {
JComponent header = getHeaderComponent();
return header != null && header != getPermanentHeaderComponent();
}
@Override
@Nullable
public JComponent getPermanentHeaderComponent() {
return getUserData(PERMANENT_HEADER);
}
@Override
public void setPermanentHeaderComponent(@Nullable JComponent component) {
putUserData(PERMANENT_HEADER, component);
}
@Override
@Nullable
public JComponent getHeaderComponent() {
if (myHeaderPanel.getComponentCount() > 0) {
return (JComponent)myHeaderPanel.getComponent(0);
}
return null;
}
@Override
public void setBackgroundColor(Color color) {
myScrollPane.setBackground(color);
if (getBackgroundIgnoreForced().equals(color)) {
myForcedBackground = null;
return;
}
myForcedBackground = color;
}
@NotNull
private Color getForegroundColor() {
return myScheme.getDefaultForeground();
}
@NotNull
@Override
public Color getBackgroundColor() {
if (myForcedBackground != null) return myForcedBackground;
return getBackgroundIgnoreForced();
}
@NotNull
@Override
public TextDrawingCallback getTextDrawingCallback() {
return myTextDrawingCallback;
}
@Override
public void setPlaceholder(@Nullable CharSequence text) {
myPlaceholderText = text;
}
@Override
public void setPlaceholderAttributes(@Nullable TextAttributes attributes) {
myPlaceholderAttributes = attributes;
}
public CharSequence getPlaceholder() {
return myPlaceholderText;
}
@Override
public void setShowPlaceholderWhenFocused(boolean show) {
myShowPlaceholderWhenFocused = show;
}
public boolean getShowPlaceholderWhenFocused() {
return myShowPlaceholderWhenFocused;
}
Color getBackgroundColor(@NotNull final TextAttributes attributes) {
final Color attrColor = attributes.getBackgroundColor();
return Comparing.equal(attrColor, myScheme.getDefaultBackground()) ? getBackgroundColor() : attrColor;
}
@NotNull
private Color getBackgroundIgnoreForced() {
Color color = myScheme.getDefaultBackground();
if (myDocument.isWritable()) {
return color;
}
Color readOnlyColor = myScheme.getColor(EditorColors.READONLY_BACKGROUND_COLOR);
return readOnlyColor != null ? readOnlyColor : color;
}
private void paintComposedTextDecoration(@NotNull Graphics2D g) {
TextRange composedTextRange = getComposedTextRange();
if (composedTextRange != null) {
VisualPosition visStart = offsetToVisualPosition(Math.min(composedTextRange.getStartOffset(), myDocument.getTextLength()));
int y = visibleLineToY(visStart.line) + getAscent() + 1;
Point p1 = visualPositionToXY(visStart);
Point p2 = logicalPositionToXY(offsetToLogicalPosition(Math.min(composedTextRange.getEndOffset(), myDocument.getTextLength())));
Stroke saved = g.getStroke();
BasicStroke dotted = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, new float[]{0, 2, 0, 2}, 0);
g.setStroke(dotted);
UIUtil.drawLine(g, p1.x, y, p2.x, y);
g.setStroke(saved);
}
}
@Nullable
public TextRange getComposedTextRange() {
return myInputMethodRequestsHandler == null || myInputMethodRequestsHandler.composedText == null ?
null : myInputMethodRequestsHandler.composedTextRange;
}
private void paintRightMargin(@NotNull Graphics g, @NotNull Rectangle clip) {
Color rightMargin = myScheme.getColor(EditorColors.RIGHT_MARGIN_COLOR);
if (!mySettings.isRightMarginShown() || rightMargin == null) {
return;
}
int x = mySettings.getRightMargin(myProject) * EditorUtil.getSpaceWidth(Font.PLAIN, this);
if (x >= clip.x && x < clip.x + clip.width) {
g.setColor(rightMargin);
UIUtil.drawLine(g, x, clip.y, x, clip.y + clip.height);
}
}
private void paintSegmentHighlightersBorderAndAfterEndOfLine(@NotNull final Graphics g,
@NotNull Rectangle clip,
int clipStartOffset,
int clipEndOffset,
@NotNull MarkupModelEx docMarkup) {
if (myDocument.getLineCount() == 0) return;
final int startLine = yPositionToVisibleLine(clip.y);
final int endLine = yPositionToVisibleLine(clip.y + clip.height) + 1;
Processor<RangeHighlighterEx> paintProcessor = new Processor<RangeHighlighterEx>() {
@Override
public boolean process(@NotNull RangeHighlighterEx highlighter) {
if (!highlighter.getEditorFilter().avaliableIn(EditorImpl.this)) return true;
paintSegmentHighlighterAfterEndOfLine(g, highlighter, startLine, endLine);
return true;
}
};
docMarkup.processRangeHighlightersOverlappingWith(clipStartOffset, clipEndOffset, paintProcessor);
myMarkupModel.processRangeHighlightersOverlappingWith(clipStartOffset, clipEndOffset, paintProcessor);
}
private void paintSegmentHighlighterAfterEndOfLine(@NotNull Graphics g,
@NotNull RangeHighlighterEx segmentHighlighter,
int startLine,
int endLine) {
if (!segmentHighlighter.isAfterEndOfLine()) {
return;
}
int startOffset = segmentHighlighter.getStartOffset();
int visibleStartLine = offsetToVisualLine(startOffset);
if (getFoldingModel().isOffsetCollapsed(startOffset)) {
return;
}
if (visibleStartLine >= startLine && visibleStartLine <= endLine) {
int logStartLine = offsetToLogicalLine(startOffset);
if (logStartLine >= myDocument.getLineCount()) {
return;
}
LogicalPosition logPosition = offsetToLogicalPosition(myDocument.getLineEndOffset(logStartLine));
Point end = logicalPositionToXY(logPosition);
int charWidth = EditorUtil.getSpaceWidth(Font.PLAIN, this);
int lineHeight = getLineHeight();
TextAttributes attributes = segmentHighlighter.getTextAttributes();
if (attributes != null && getBackgroundColor(attributes) != null) {
g.setColor(getBackgroundColor(attributes));
g.fillRect(end.x, end.y, charWidth, lineHeight);
}
if (attributes != null && attributes.getEffectColor() != null) {
int y = visibleLineToY(visibleStartLine) + getAscent() + 1;
g.setColor(attributes.getEffectColor());
if (attributes.getEffectType() == EffectType.WAVE_UNDERSCORE) {
UIUtil.drawWave((Graphics2D)g, new Rectangle(end.x, y, charWidth - 1, getDescent()- 1));
}
else if (attributes.getEffectType() == EffectType.BOLD_DOTTED_LINE) {
final int dottedAt = SystemInfo.isMac ? y - 1 : y;
UIUtil.drawBoldDottedLine((Graphics2D)g, end.x, end.x + charWidth - 1, dottedAt,
getBackgroundColor(attributes), attributes.getEffectColor(), false);
}
else if (attributes.getEffectType() == EffectType.STRIKEOUT) {
int y1 = y - getCharHeight() / 2 - 1;
UIUtil.drawLine(g, end.x, y1, end.x + charWidth - 1, y1);
}
else if (attributes.getEffectType() == EffectType.BOLD_LINE_UNDERSCORE) {
drawBoldLineUnderScore(g, end.x, y - 1, charWidth - 1);
}
else if (attributes.getEffectType() != EffectType.BOXED) {
UIUtil.drawLine(g, end.x, y, end.x + charWidth - 1, y);
}
}
}
}
private static void drawBoldLineUnderScore(Graphics g, int x, int y, int width) {
int height = JBUI.scale(Registry.intValue("editor.bold.underline.height", 2));
g.fillRect(x, y, width, height);
}
@Override
public int getMaxWidthInRange(int startOffset, int endOffset) {
if (myUseNewRendering) return myView.getMaxWidthInRange(startOffset, endOffset);
int width = 0;
int start = offsetToVisualLine(startOffset);
int end = offsetToVisualLine(endOffset);
for (int i = start; i <= end; i++) {
int lastColumn = EditorUtil.getLastVisualLineColumnNumber(this, i) + 1;
int lineWidth = visualPositionToXY(new VisualPosition(i, lastColumn)).x;
if (lineWidth > width) {
width = lineWidth;
}
}
return width;
}
private void paintBackgrounds(@NotNull Graphics g,
@NotNull Rectangle clip,
@NotNull LogicalPosition clipStartPosition,
@NotNull VisualPosition clipStartVisualPos,
int clipStartOffset, int clipEndOffset) {
Color defaultBackground = getBackgroundColor();
if (myEditorComponent.isOpaque()) {
g.setColor(defaultBackground);
g.fillRect(clip.x, clip.y, clip.width, clip.height);
}
Color prevBackColor = null;
int lineHeight = getLineHeight();
int visibleLine = yPositionToVisibleLine(clip.y);
Point position = new Point(0, visibleLine * lineHeight);
CharSequence prefixText = myPrefixText == null ? null : new CharArrayCharSequence(myPrefixText);
if (clipStartVisualPos.line == 0 && prefixText != null) {
Color backColor = myPrefixAttributes.getBackgroundColor();
position.x = drawBackground(g, backColor, prefixText, 0, prefixText.length(), position,
myPrefixAttributes.getFontType(),
defaultBackground, clip);
prevBackColor = backColor;
}
if (clipStartPosition.line >= myDocument.getLineCount() || clipStartPosition.line < 0) {
if (position.x > 0) flushBackground(g, clip);
return;
}
myLastBackgroundPosition = null;
myLastBackgroundColor = null;
mySelectionStartPosition = null;
mySelectionEndPosition = null;
int start = clipStartOffset;
if (!myPurePaintingMode) {
getSoftWrapModel().registerSoftWrapsIfNecessary();
}
LineIterator lIterator = createLineIterator();
lIterator.start(start);
if (lIterator.atEnd()) {
return;
}
IterationState iterationState = new IterationState(this, start, clipEndOffset, isPaintSelection());
TextAttributes attributes = iterationState.getMergedAttributes();
Color backColor = getBackgroundColor(attributes);
int fontType = attributes.getFontType();
int lastLineIndex = Math.max(0, myDocument.getLineCount() - 1);
// There is a possible case that we need to draw background from the start of soft wrap-introduced visual line. Given position
// has valid 'y' coordinate then at it shouldn't be affected by soft wrap that corresponds to the visual line start offset.
// Hence, we store information about soft wrap to be skipped for further processing and adjust 'x' coordinate value if necessary.
TIntHashSet softWrapsToSkip = new TIntHashSet();
SoftWrap softWrap = getSoftWrapModel().getSoftWrap(start);
if (softWrap != null) {
softWrapsToSkip.add(softWrap.getStart());
Color color = null;
if (backColor != null && !backColor.equals(defaultBackground)) {
color = backColor;
}
// There is a possible case that target clip points to soft wrap-introduced visual line and that it's an active
// line (caret cursor is located on it). We want to draw corresponding 'caret line' background for soft wraps-introduced
// virtual space then.
if (color == null && position.y == getCaretModel().getVisualPosition().line * getLineHeight()) {
color = mySettings.isCaretRowShown() ? getColorsScheme().getColor(EditorColors.CARET_ROW_COLOR) : null;
}
if (color != null) {
drawBackground(g, color, softWrap.getIndentInPixels(), position, defaultBackground, clip);
prevBackColor = color;
}
position.x = softWrap.getIndentInPixels();
}
// There is a possible case that caret is located at soft-wrapped line. We don't need to paint caret row background
// on a last visual line of that soft-wrapped line then. Below is a holder for the flag that indicates if caret row
// background is already drawn.
boolean[] caretRowPainted = new boolean[1];
CharSequence text = myDocument.getImmutableCharSequence();
while (!iterationState.atEnd() && !lIterator.atEnd()) {
int hEnd = iterationState.getEndOffset();
int lEnd = lIterator.getEnd();
if (hEnd >= lEnd) {
FoldRegion collapsedFolderAt = myFoldingModel.getCollapsedRegionAtOffset(start);
if (collapsedFolderAt == null) {
position.x = drawSoftWrapAwareBackground(g, backColor, prevBackColor, text, start, lEnd - lIterator.getSeparatorLength(),
position, fontType, defaultBackground, clip, softWrapsToSkip, caretRowPainted);
prevBackColor = backColor;
paintAfterLineEndBackgroundSegments(g, iterationState, position, defaultBackground, lineHeight);
if (lIterator.getLineNumber() < lastLineIndex) {
if (backColor != null && !backColor.equals(defaultBackground)) {
g.setColor(backColor);
g.fillRect(position.x, position.y, clip.x + clip.width - position.x, lineHeight);
}
}
else {
if (iterationState.hasPastFileEndBackgroundSegments()) {
paintAfterLineEndBackgroundSegments(g, iterationState, position, defaultBackground, lineHeight);
}
paintAfterFileEndBackground(iterationState,
g,
position, clip,
lineHeight, defaultBackground, caretRowPainted);
break;
}
position.x = 0;
if (position.y > clip.y + clip.height) break;
position.y += lineHeight;
start = lEnd;
}
else if (collapsedFolderAt.getEndOffset() == clipEndOffset) {
drawCollapsedFolderBackground(g, clip, defaultBackground, prevBackColor, position, backColor, fontType, softWrapsToSkip, caretRowPainted, text,
collapsedFolderAt);
prevBackColor = backColor;
}
lIterator.advance();
}
else {
FoldRegion collapsedFolderAt = iterationState.getCurrentFold();
if (collapsedFolderAt != null) {
drawCollapsedFolderBackground(g, clip, defaultBackground, prevBackColor, position, backColor, fontType, softWrapsToSkip, caretRowPainted, text,
collapsedFolderAt);
prevBackColor = backColor;
}
else if (hEnd > lEnd - lIterator.getSeparatorLength()) {
position.x = drawSoftWrapAwareBackground(
g, backColor, prevBackColor, text, start, lEnd - lIterator.getSeparatorLength(), position, fontType,
defaultBackground, clip, softWrapsToSkip, caretRowPainted
);
prevBackColor = backColor;
}
else {
position.x = drawSoftWrapAwareBackground(
g, backColor, prevBackColor, text, start, hEnd, position, fontType, defaultBackground, clip, softWrapsToSkip, caretRowPainted
);
prevBackColor = backColor;
}
iterationState.advance();
attributes = iterationState.getMergedAttributes();
backColor = getBackgroundColor(attributes);
fontType = attributes.getFontType();
start = iterationState.getStartOffset();
}
}
flushBackground(g, clip);
if (lIterator.getLineNumber() >= lastLineIndex && position.y <= clip.y + clip.height) {
paintAfterFileEndBackground(iterationState, g, position, clip, lineHeight, defaultBackground, caretRowPainted);
}
// Perform additional activity if soft wrap is added or removed during repainting.
if (mySoftWrapsChanged) {
mySoftWrapsChanged = false;
clearTextWidthCache();
validateSize();
// Repaint editor to the bottom in order to ensure that its content is shown correctly after new soft wrap introduction.
repaintToScreenBottom(EditorUtil.yPositionToLogicalLine(this, position));
// Repaint gutter at all space that is located after active clip in order to ensure that line numbers are correctly redrawn
// in accordance with the newly introduced soft wrap(s).
myGutterComponent.repaint(0, clip.y, myGutterComponent.getWidth(), myGutterComponent.getHeight() - clip.y);
}
}
private void drawCollapsedFolderBackground(@NotNull Graphics g,
@NotNull Rectangle clip,
@NotNull Color defaultBackground,
@Nullable Color prevBackColor,
@NotNull Point position,
@NotNull Color backColor,
int fontType,
@NotNull TIntHashSet softWrapsToSkip,
@NotNull boolean[] caretRowPainted,
@NotNull CharSequence text,
@NotNull FoldRegion collapsedFolderAt) {
SoftWrap softWrap = mySoftWrapModel.getSoftWrap(collapsedFolderAt.getStartOffset());
if (softWrap != null) {
position.x = drawSoftWrapAwareBackground(
g, backColor, prevBackColor, text, collapsedFolderAt.getStartOffset(), collapsedFolderAt.getStartOffset(), position, fontType,
defaultBackground, clip, softWrapsToSkip, caretRowPainted
);
}
CharSequence chars = collapsedFolderAt.getPlaceholderText();
position.x = drawBackground(g, backColor, chars, 0, chars.length(), position, fontType, defaultBackground, clip);
}
private void paintAfterLineEndBackgroundSegments(@NotNull Graphics g,
@NotNull IterationState iterationState,
@NotNull Point position,
@NotNull Color defaultBackground,
int lineHeight) {
while (iterationState.hasPastLineEndBackgroundSegment()) {
TextAttributes backgroundAttributes = iterationState.getPastLineEndBackgroundAttributes();
int width = EditorUtil.getSpaceWidth(backgroundAttributes.getFontType(), this) * iterationState.getPastLineEndBackgroundSegmentWidth();
Color color = getBackgroundColor(backgroundAttributes);
if (color != null && !color.equals(defaultBackground)) {
g.setColor(color);
g.fillRect(position.x, position.y, width, lineHeight);
}
position.x += width;
iterationState.advanceToNextPastLineEndBackgroundSegment();
}
}
private void paintAfterFileEndBackground(@NotNull IterationState iterationState,
@NotNull Graphics g,
@NotNull Point position,
@NotNull Rectangle clip,
int lineHeight,
@NotNull Color defaultBackground,
@NotNull boolean[] caretRowPainted) {
Color backColor = iterationState.getPastFileEndBackground();
if (backColor == null || backColor.equals(defaultBackground)) {
return;
}
if (caretRowPainted[0] && backColor.equals(getColorsScheme().getColor(EditorColors.CARET_ROW_COLOR))) {
return;
}
g.setColor(backColor);
g.fillRect(position.x, position.y, clip.x + clip.width - position.x, lineHeight);
}
private int drawSoftWrapAwareBackground(@NotNull Graphics g,
@Nullable Color backColor,
@Nullable Color prevBackColor,
@NotNull CharSequence text,
int start,
int end,
@NotNull Point position,
@JdkConstants.FontStyle int fontType,
@NotNull Color defaultBackground,
@NotNull Rectangle clip,
@NotNull TIntHashSet softWrapsToSkip,
@NotNull boolean[] caretRowPainted) {
int startToUse = start;
// Given 'end' offset is exclusive though SoftWrapModel.getSoftWrapsForRange() uses inclusive end offset.
// Hence, we decrement it if necessary. Please note that we don't do that if start is equal to end. That is the case,
// for example, for soft-wrapped collapsed fold region - we need to draw soft wrap before it.
int softWrapRetrievalEndOffset = end;
if (end > start) {
softWrapRetrievalEndOffset--;
}
List<? extends SoftWrap> softWraps = getSoftWrapModel().getSoftWrapsForRange(start, softWrapRetrievalEndOffset);
for (SoftWrap softWrap : softWraps) {
int softWrapStart = softWrap.getStart();
if (softWrapsToSkip.contains(softWrapStart)) {
continue;
}
if (startToUse < softWrapStart) {
position.x = drawBackground(g, backColor, text, startToUse, softWrapStart, position, fontType, defaultBackground, clip);
}
boolean drawCustomBackgroundAtSoftWrapVirtualSpace =
!Comparing.equal(backColor, defaultBackground) && (softWrapStart > start || Comparing.equal(prevBackColor, backColor));
drawSoftWrap(
g, softWrap, position, fontType, backColor, drawCustomBackgroundAtSoftWrapVirtualSpace, defaultBackground, clip, caretRowPainted
);
startToUse = softWrapStart;
}
if (startToUse < end) {
position.x = drawBackground(g, backColor, text, startToUse, end, position, fontType, defaultBackground, clip);
}
return position.x;
}
private void drawSoftWrap(@NotNull Graphics g,
@NotNull SoftWrap softWrap,
@NotNull Point position,
@JdkConstants.FontStyle int fontType,
@Nullable Color backColor,
boolean drawCustomBackgroundAtSoftWrapVirtualSpace,
@NotNull Color defaultBackground,
@NotNull Rectangle clip,
@NotNull boolean[] caretRowPainted) {
// The main idea is to to do the following:
// *) update given drawing position coordinates in accordance with the current soft wrap;
// *) draw background at soft wrap-introduced virtual space if necessary;
CharSequence softWrapText = softWrap.getText();
int activeRowY = getCaretModel().getVisualPosition().line * getLineHeight();
int afterSoftWrapWidth = clip.x + clip.width - position.x;
if (drawCustomBackgroundAtSoftWrapVirtualSpace && backColor != null) {
drawBackground(g, backColor, afterSoftWrapWidth, position, defaultBackground, clip);
}
else if (position.y == activeRowY) {
// Draw 'active line' background after soft wrap.
Color caretRowColor = mySettings.isCaretRowShown()? getColorsScheme().getColor(EditorColors.CARET_ROW_COLOR) : null;
drawBackground(g, caretRowColor, afterSoftWrapWidth, position, defaultBackground, clip);
caretRowPainted[0] = true;
}
paintSelectionOnFirstSoftWrapLineIfNecessary(g, position, clip, defaultBackground, fontType);
int i = CharArrayUtil.lastIndexOf(softWrapText, "\n", softWrapText.length()) + 1;
int width = getTextSegmentWidth(softWrapText, i, softWrapText.length(), 0, fontType, clip)
+ getSoftWrapModel().getMinDrawingWidthInPixels(SoftWrapDrawingType.AFTER_SOFT_WRAP);
position.x = 0;
position.y += getLineHeight();
if (drawCustomBackgroundAtSoftWrapVirtualSpace && backColor != null) {
drawBackground(g, backColor, width, position, defaultBackground, clip);
}
else if (position.y == activeRowY) {
// Draw 'active line' background for the soft wrap-introduced virtual space.
Color caretRowColor = mySettings.isCaretRowShown()? getColorsScheme().getColor(EditorColors.CARET_ROW_COLOR) : null;
drawBackground(g, caretRowColor, width, position, defaultBackground, clip);
}
position.x = 0;
paintSelectionOnSecondSoftWrapLineIfNecessary(g, position, clip, defaultBackground, fontType, softWrap);
position.x = width;
}
private VisualPosition getSelectionStartPositionForPaint() {
if (mySelectionStartPosition == null) {
// We cache the value to avoid repeated invocations of Editor.logicalPositionToOffset which is currently slow for long lines
mySelectionStartPosition = getSelectionModel().getSelectionStartPosition();
}
return mySelectionStartPosition;
}
private VisualPosition getSelectionEndPositionForPaint() {
if (mySelectionEndPosition == null) {
// We cache the value to avoid repeated invocations of Editor.logicalPositionToOffset which is currently slow for long lines
mySelectionEndPosition = getSelectionModel().getSelectionEndPosition();
}
return mySelectionEndPosition;
}
/**
* End user is allowed to perform selection by visual coordinates (e.g. by dragging mouse with left button hold). There is a possible
* case that such a move intersects with soft wrap introduced virtual space. We want to draw corresponding selection background
* there then.
* <p/>
* This method encapsulates functionality of drawing selection background on the first soft wrap line (e.g. on a visual line where
* it is applied).
*
* @param g graphics to draw on
* @param position current position (assumed to be position of soft wrap appliance)
* @param clip target drawing area boundaries
* @param defaultBackground default background
* @param fontType current font type
*/
private void paintSelectionOnFirstSoftWrapLineIfNecessary(@NotNull Graphics g,
@NotNull Point position,
@NotNull Rectangle clip,
@NotNull Color defaultBackground,
@JdkConstants.FontStyle int fontType) {
// There is a possible case that the user performed selection at soft wrap virtual space. We need to paint corresponding background
// there then.
VisualPosition selectionStartPosition = getSelectionStartPositionForPaint();
VisualPosition selectionEndPosition = getSelectionEndPositionForPaint();
if (selectionStartPosition.equals(selectionEndPosition)) {
return;
}
int currentVisualLine = position.y / getLineHeight();
int lastColumn = EditorUtil.getLastVisualLineColumnNumber(this, currentVisualLine);
// Check if the first soft wrap line is within the visual selection.
if (currentVisualLine < selectionStartPosition.line || currentVisualLine > selectionEndPosition.line
|| currentVisualLine == selectionEndPosition.line && selectionEndPosition.column <= lastColumn) {
return;
}
// Adjust 'x' if selection starts at soft wrap virtual space.
final int columnsToSkip = selectionStartPosition.column - lastColumn;
if (columnsToSkip > 0) {
position.x += getSoftWrapModel().getMinDrawingWidthInPixels(SoftWrapDrawingType.BEFORE_SOFT_WRAP_LINE_FEED);
position.x += (columnsToSkip - 1) * EditorUtil.getSpaceWidth(Font.PLAIN, this);
}
// Calculate selection width.
final int width;
if (selectionEndPosition.line > currentVisualLine) {
width = clip.x + clip.width - position.x;
}
else if (selectionStartPosition.line < currentVisualLine || selectionStartPosition.column <= lastColumn) {
width = getSoftWrapModel().getMinDrawingWidthInPixels(SoftWrapDrawingType.BEFORE_SOFT_WRAP_LINE_FEED)
+ (selectionEndPosition.column - lastColumn - 1) * EditorUtil.getSpaceWidth(fontType, this);
}
else {
width = (selectionEndPosition.column - selectionStartPosition.column) * EditorUtil.getSpaceWidth(fontType, this);
}
drawBackground(g, getColorsScheme().getColor(EditorColors.SELECTION_BACKGROUND_COLOR), width, position, defaultBackground, clip);
}
/**
* End user is allowed to perform selection by visual coordinates (e.g. by dragging mouse with left button hold). There is a possible
* case that such a move intersects with soft wrap introduced virtual space. We want to draw corresponding selection background
* there then.
* <p/>
* This method encapsulates functionality of drawing selection background on the second soft wrap line (e.g. on a visual line after
* the one where it is applied).
*
* @param g graphics to draw on
* @param position current position (assumed to be position of soft wrap appliance)
* @param clip target drawing area boundaries
* @param defaultBackground default background
* @param fontType current font type
* @param softWrap target soft wrap which second line virtual space may contain selection
*/
private void paintSelectionOnSecondSoftWrapLineIfNecessary(@NotNull Graphics g,
@NotNull Point position,
@NotNull Rectangle clip,
@NotNull Color defaultBackground,
@JdkConstants.FontStyle int fontType,
@NotNull SoftWrap softWrap) {
// There is a possible case that the user performed selection at soft wrap virtual space. We need to paint corresponding background
// there then.
VisualPosition selectionStartPosition = getSelectionStartPositionForPaint();
VisualPosition selectionEndPosition = getSelectionEndPositionForPaint();
if (selectionStartPosition.equals(selectionEndPosition)) {
return;
}
int currentVisualLine = position.y / getLineHeight();
// Check if the second soft wrap line is within the visual selection.
if (currentVisualLine < selectionStartPosition.line || currentVisualLine > selectionEndPosition.line
|| currentVisualLine == selectionStartPosition.line && selectionStartPosition.column >= softWrap.getIndentInColumns()) {
return;
}
// Adjust 'x' if selection starts at soft wrap virtual space.
if (selectionStartPosition.line == currentVisualLine && selectionStartPosition.column > 0) {
position.x += selectionStartPosition.column * EditorUtil.getSpaceWidth(fontType, this);
}
// Calculate selection width.
final int width;
if (selectionEndPosition.line > currentVisualLine || selectionEndPosition.column >= softWrap.getIndentInColumns()) {
width = softWrap.getIndentInPixels() - position.x;
}
else {
width = selectionEndPosition.column * EditorUtil.getSpaceWidth(fontType, this) - position.x;
}
drawBackground(g, getColorsScheme().getColor(EditorColors.SELECTION_BACKGROUND_COLOR), width, position, defaultBackground, clip);
}
private int drawBackground(@NotNull Graphics g,
Color backColor,
@NotNull CharSequence text,
int start,
int end,
@NotNull Point position,
@JdkConstants.FontStyle int fontType,
@NotNull Color defaultBackground,
@NotNull Rectangle clip) {
int width = getTextSegmentWidth(text, start, end, position.x, fontType, clip);
return drawBackground(g, backColor, width, position, defaultBackground, clip);
}
private int drawBackground(@NotNull Graphics g,
@Nullable Color backColor,
int width,
@NotNull Point position,
@NotNull Color defaultBackground,
@NotNull Rectangle clip) {
if (backColor != null && !backColor.equals(defaultBackground) && clip.intersects(position.x, position.y, width, getLineHeight())) {
if (backColor.equals(myLastBackgroundColor) && myLastBackgroundPosition.y == position.y &&
myLastBackgroundPosition.x + myLastBackgroundWidth == position.x) {
myLastBackgroundWidth += width;
}
else {
flushBackground(g, clip);
myLastBackgroundColor = backColor;
myLastBackgroundPosition = new Point(position);
myLastBackgroundWidth = width;
}
}
return position.x + width;
}
private void flushBackground(@NotNull Graphics g, @NotNull final Rectangle clip) {
if (myLastBackgroundColor != null) {
final Point position = myLastBackgroundPosition;
final int w = myLastBackgroundWidth;
final int height = getLineHeight();
if (clip.intersects(position.x, position.y, w, height)) {
g.setColor(myLastBackgroundColor);
g.fillRect(position.x, position.y, w, height);
}
myLastBackgroundColor = null;
}
}
@NotNull
private LineIterator createLineIterator() {
return myDocument.createLineIterator();
}
private void paintText(@NotNull Graphics g,
@NotNull Rectangle clip,
@NotNull LogicalPosition clipStartPosition,
int clipStartOffset,
int clipEndOffset) {
myCurrentFontType = null;
myLastCache = null;
int lineHeight = getLineHeight();
int visibleLine = clip.y / lineHeight;
int startLine = clipStartPosition.line;
int start = clipStartOffset;
Point position = new Point(0, visibleLine * lineHeight);
if (startLine == 0 && myPrefixText != null) {
position.x = drawStringWithSoftWraps(g, new CharArrayCharSequence(myPrefixText), 0, myPrefixText.length, position, clip,
myPrefixAttributes.getEffectColor(), myPrefixAttributes.getEffectType(),
myPrefixAttributes.getFontType(), myPrefixAttributes.getForegroundColor(), -1,
PAINT_NO_WHITESPACE);
}
if (startLine >= myDocument.getLineCount() || startLine < 0) {
if (position.x > 0) flushCachedChars(g);
return;
}
LineIterator lIterator = createLineIterator();
lIterator.start(start);
if (lIterator.atEnd()) {
return;
}
IterationState iterationState = new IterationState(this, start, clipEndOffset, isPaintSelection());
TextAttributes attributes = iterationState.getMergedAttributes();
Color currentColor = attributes.getForegroundColor();
if (currentColor == null) {
currentColor = getForegroundColor();
}
Color effectColor = attributes.getEffectColor();
EffectType effectType = attributes.getEffectType();
int fontType = attributes.getFontType();
g.setColor(currentColor);
CharSequence chars = myDocument.getImmutableCharSequence();
LineWhitespacePaintingStrategy context = new LineWhitespacePaintingStrategy();
context.update(chars, lIterator);
while (!iterationState.atEnd() && !lIterator.atEnd()) {
int hEnd = iterationState.getEndOffset();
int lEnd = lIterator.getEnd();
if (hEnd >= lEnd) {
FoldRegion collapsedFolderAt = myFoldingModel.getCollapsedRegionAtOffset(start);
if (collapsedFolderAt == null) {
drawStringWithSoftWraps(g, chars, start, lEnd - lIterator.getSeparatorLength(), position, clip, effectColor,
effectType, fontType, currentColor, clipStartOffset, context);
final VirtualFile file = getVirtualFile();
if (myProject != null && file != null && !isOneLineMode()) {
int offset = position.x;
for (EditorLinePainter painter : EditorLinePainter.EP_NAME.getExtensions()) {
Collection<LineExtensionInfo> extensions = painter.getLineExtensions(myProject, file, lIterator.getLineNumber());
if (extensions != null && !extensions.isEmpty()) {
for (LineExtensionInfo info : extensions) {
final String text = info.getText();
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
offset += EditorUtil.charWidth(ch, Font.ITALIC, this);
}
position.x = drawString(g, text, 0, text.length(), position, clip,
info.getEffectColor() == null ? effectColor : info.getEffectColor(),
info.getEffectType() == null ? effectType : info.getEffectType(),
info.getFontType(),
info.getColor() == null ? currentColor : info.getColor(),
context);
}
}
}
myLinePaintersWidth = Math.max(myLinePaintersWidth, offset);
}
position.x = 0;
if (position.y > clip.y + clip.height) {
break;
}
position.y += lineHeight;
start = lEnd;
}
// myBorderEffect.eolReached(g, this);
lIterator.advance();
if (!lIterator.atEnd()) {
context.update(chars, lIterator);
}
}
else {
FoldRegion collapsedFolderAt = iterationState.getCurrentFold();
if (collapsedFolderAt != null) {
SoftWrap softWrap = mySoftWrapModel.getSoftWrap(collapsedFolderAt.getStartOffset());
if (softWrap != null) {
position.x = drawStringWithSoftWraps(
g, chars, collapsedFolderAt.getStartOffset(), collapsedFolderAt.getStartOffset(), position, clip, effectColor, effectType,
fontType, currentColor, clipStartOffset, context
);
}
int foldingXStart = position.x;
position.x = drawString(
g, collapsedFolderAt.getPlaceholderText(), position, clip, effectColor, effectType, fontType, currentColor,
PAINT_NO_WHITESPACE);
//drawStringWithSoftWraps(g, collapsedFolderAt.getPlaceholderText(), position, clip, effectColor, effectType,
// fontType, currentColor, logicalPosition);
BorderEffect.paintFoldedEffect(g, foldingXStart, position.y, position.x, getLineHeight(), effectColor, effectType);
}
else {
position.x = drawStringWithSoftWraps(g, chars, start, Math.min(hEnd, lEnd - lIterator.getSeparatorLength()), position, clip,
effectColor, effectType, fontType, currentColor, clipStartOffset, context);
}
iterationState.advance();
attributes = iterationState.getMergedAttributes();
currentColor = attributes.getForegroundColor();
if (currentColor == null) {
currentColor = getForegroundColor();
}
effectColor = attributes.getEffectColor();
effectType = attributes.getEffectType();
fontType = attributes.getFontType();
start = iterationState.getStartOffset();
}
}
FoldRegion collapsedFolderAt = iterationState.getCurrentFold();
if (collapsedFolderAt != null) {
int foldingXStart = position.x;
int foldingXEnd = drawStringWithSoftWraps(
g, collapsedFolderAt.getPlaceholderText(), position, clip, effectColor, effectType, fontType, currentColor, clipStartOffset,
PAINT_NO_WHITESPACE);
BorderEffect.paintFoldedEffect(g, foldingXStart, position.y, foldingXEnd, getLineHeight(), effectColor, effectType);
// myBorderEffect.collapsedFolderReached(g, this);
}
final SoftWrap softWrap = mySoftWrapModel.getSoftWrap(clipEndOffset);
if (softWrap != null) {
mySoftWrapModel.paint(g, SoftWrapDrawingType.BEFORE_SOFT_WRAP_LINE_FEED, position.x, position.y, getLineHeight());
}
flushCachedChars(g);
}
private boolean paintPlaceholderText(@NotNull Graphics g, @NotNull Rectangle clip) {
CharSequence hintText = myPlaceholderText;
if (myDocument.getTextLength() > 0 || hintText == null || hintText.length() == 0) {
return false;
}
if (KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() == myEditorComponent && !myShowPlaceholderWhenFocused) {
// There is a possible case that placeholder text was painted and the editor gets focus now. We want to over-paint previously
// used placeholder text then.
myLastBackgroundColor = getBackgroundColor();
myLastBackgroundPosition = new Point(0, 0);
myLastBackgroundWidth = myLastPaintedPlaceholderWidth;
flushBackground(g, clip);
return false;
}
else {
hintText = SwingUtilities.layoutCompoundLabel(g.getFontMetrics(), hintText.toString(), null, 0, 0, 0, 0,
myEditorComponent.getBounds(), new Rectangle(), new Rectangle(), 0);
myLastPaintedPlaceholderWidth = drawString(
g, hintText, 0, hintText.length(), new Point(0, 0), clip, null, null,
myPlaceholderAttributes == null ? Font.PLAIN : myPlaceholderAttributes.getFontType(),
myPlaceholderAttributes == null ? myFoldingModel.getPlaceholderAttributes().getForegroundColor() :
myPlaceholderAttributes.getForegroundColor(),
PAINT_NO_WHITESPACE
);
flushCachedChars(g);
return true;
}
}
private boolean isPaintSelection() {
return myPaintSelection || !isOneLineMode() || IJSwingUtilities.hasFocus(getContentComponent());
}
public void setPaintSelection(boolean paintSelection) {
myPaintSelection = paintSelection;
}
@Override
@NotNull
@NonNls
public String dumpState() {
return "prefix: '" + (myPrefixText == null ? "none" : new String(myPrefixText))
+ "', allow caret inside tab: " + mySettings.isCaretInsideTabs()
+ ", allow caret after line end: " + mySettings.isVirtualSpace()
+ ", soft wraps: " + (mySoftWrapModel.isSoftWrappingEnabled() ? "on" : "off")
+ ", soft wraps data: " + getSoftWrapModel().dumpState()
+ "\n\nfolding data: " + getFoldingModel().dumpState()
+ (myDocument instanceof DocumentImpl ? "\n\ndocument info: " + ((DocumentImpl)myDocument).dumpState() : "")
+ "\nfont preferences: " + myScheme.getFontPreferences();
}
private class CachedFontContent {
private final CharSequence[] data = new CharSequence[CACHED_CHARS_BUFFER_SIZE];
private final int[] starts = new int[CACHED_CHARS_BUFFER_SIZE];
private final int[] ends = new int[CACHED_CHARS_BUFFER_SIZE];
private final int[] x = new int[CACHED_CHARS_BUFFER_SIZE];
private final int[] y = new int[CACHED_CHARS_BUFFER_SIZE];
private final Color[] color = new Color[CACHED_CHARS_BUFFER_SIZE];
private final boolean[] whitespaceShown = new boolean[CACHED_CHARS_BUFFER_SIZE];
private int myCount;
@NotNull private final FontInfo myFontType;
private final boolean myHasBreakSymbols;
private final int spaceWidth;
@Nullable private CharSequence myLastData;
private CachedFontContent(@NotNull FontInfo fontInfo) {
myFontType = fontInfo;
spaceWidth = fontInfo.charWidth(' ');
myHasBreakSymbols = fontInfo.hasGlyphsToBreakDrawingIteration();
}
private void flushContent(@NotNull Graphics g) {
if (myCount != 0) {
if (myCurrentFontType != myFontType) {
myCurrentFontType = myFontType;
g.setFont(myFontType.getFont());
}
Color currentColor = null;
for (int i = 0; i < myCount; i++) {
if (!Comparing.equal(color[i], currentColor)) {
currentColor = color[i] != null ? color[i] : JBColor.black;
g.setColor(currentColor);
}
drawChars(g, data[i], starts[i], ends[i], x[i], y[i], whitespaceShown[i]);
color[i] = null;
data[i] = null;
}
myCount = 0;
myLastData = null;
}
}
private void addContent(@NotNull Graphics g, CharSequence _data, int _start, int _end, int _x, int _y, @Nullable Color _color, boolean drawWhitespace) {
final int count = myCount;
if (count > 0) {
final int lastCount = count - 1;
final Color lastColor = color[lastCount];
if (_data == myLastData && _start == ends[lastCount] && (_color == null || lastColor == null || _color.equals(lastColor))
&& _y == y[lastCount] /* there is a possible case that vertical position is adjusted because of soft wrap */
&& (!myHasBreakSymbols || !myFontType.getSymbolsToBreakDrawingIteration().contains(_data.charAt(ends[lastCount] - 1)))
&& (!myDisableRtl || _start < 1 || _start >= _data.length() || !isRtlCharacter(_data.charAt(_start)) && !isRtlCharacter(_data.charAt(_start - 1)))
&& drawWhitespace == whitespaceShown[lastCount]) {
ends[lastCount] = _end;
if (lastColor == null) color[lastCount] = _color;
return;
}
}
myLastData = _data;
data[count] = _data;
x[count] = _x;
y[count] = _y;
starts[count] = _start;
ends[count] = _end;
color[count] = _color;
whitespaceShown[count] = drawWhitespace;
myCount++;
if (count >= CACHED_CHARS_BUFFER_SIZE - 1) {
flushContent(g);
}
}
}
private static boolean isRtlCharacter(char c) {
byte directionality = Character.getDirectionality(c);
return directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT
|| directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC
|| directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING
|| directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE;
}
private void flushCachedChars(@NotNull Graphics g) {
for (CachedFontContent cache : myFontCache) {
cache.flushContent(g);
}
myLastCache = null;
}
private void paintCaretCursor(@NotNull Graphics g) {
// There is a possible case that visual caret position is changed because of newly added or removed soft wraps.
// We check if that's the case and ask caret model to recalculate visual position if necessary.
myCaretCursor.paint(g);
}
@Nullable
public CaretRectangle[] getCaretLocations(boolean onlyIfShown) {
return myCaretCursor.getCaretLocations(onlyIfShown);
}
private void paintLineMarkersSeparators(@NotNull final Graphics g,
@NotNull final Rectangle clip,
@NotNull MarkupModelEx markupModel,
int clipStartOffset,
int clipEndOffset) {
markupModel.processRangeHighlightersOverlappingWith(clipStartOffset, clipEndOffset, new Processor<RangeHighlighterEx>() {
@Override
public boolean process(@NotNull RangeHighlighterEx lineMarker) {
if (!lineMarker.getEditorFilter().avaliableIn(EditorImpl.this)) return true;
paintLineMarkerSeparator(lineMarker, clip, g);
return true;
}
});
}
private void paintLineMarkerSeparator(@NotNull RangeHighlighter marker, @NotNull Rectangle clip, @NotNull Graphics g) {
Color separatorColor = marker.getLineSeparatorColor();
LineSeparatorRenderer lineSeparatorRenderer = marker.getLineSeparatorRenderer();
if (separatorColor == null && lineSeparatorRenderer == null) {
return;
}
int line = marker.getLineSeparatorPlacement() == SeparatorPlacement.TOP ? marker.getDocument()
.getLineNumber(marker.getStartOffset()) : marker.getDocument().getLineNumber(marker.getEndOffset());
if (line < 0 || line >= myDocument.getLineCount()) {
return;
}
// There is a possible case that particular logical line occupies more than one visual line (because of soft wraps processing),
// hence, we need to consider that during calculating 'y' position for the last visual line used for the target logical
// line representation.
int y;
SeparatorPlacement placement = marker.getLineSeparatorPlacement();
if (placement == SeparatorPlacement.TOP) {
y = visibleLineToY(logicalToVisualLine(line));
}
else if (line + 1 >= myDocument.getLineCount()) {
y = visibleLineToY(offsetToVisualLine(myDocument.getTextLength()) + 1);
}
else {
y = logicalLineToY(line + 1);
}
y -= 1;
if (y + getLineHeight() < clip.y || y > clip.y + clip.height) return;
int endShift = clip.x + clip.width;
g.setColor(separatorColor);
if (mySettings.isRightMarginShown() && myScheme.getColor(EditorColors.RIGHT_MARGIN_COLOR) != null) {
endShift = Math.min(endShift, mySettings.getRightMargin(myProject) * EditorUtil.getSpaceWidth(Font.PLAIN, this));
}
if (lineSeparatorRenderer != null) {
lineSeparatorRenderer.drawLine(g, 0, endShift, y);
}
else {
UIUtil.drawLine(g, 0, y, endShift, y);
}
}
private int drawStringWithSoftWraps(@NotNull Graphics g,
@NotNull final String text,
@NotNull Point position,
@NotNull Rectangle clip,
Color effectColor,
EffectType effectType,
@JdkConstants.FontStyle int fontType,
Color fontColor,
int startDrawingOffset,
WhitespacePaintingStrategy context) {
return drawStringWithSoftWraps(g, text, 0, text.length(), position, clip, effectColor, effectType,
fontType, fontColor, startDrawingOffset, context);
}
private int drawStringWithSoftWraps(@NotNull Graphics g,
final CharSequence text,
int start,
final int end,
@NotNull Point position,
@NotNull Rectangle clip,
Color effectColor,
EffectType effectType,
@JdkConstants.FontStyle int fontType,
Color fontColor,
int startDrawingOffset,
WhitespacePaintingStrategy context) {
if (start >= end && getSoftWrapModel().getSoftWrap(start) == null) {
return position.x;
}
// Given 'end' offset is exclusive though SoftWrapModel.getSoftWrapsForRange() uses inclusive end offset.
// Hence, we decrement it if necessary. Please note that we don't do that if start is equal to end. That is the case,
// for example, for soft-wrapped collapsed fold region - we need to draw soft wrap before it.
int softWrapRetrievalEndOffset = end;
if (start < end) {
softWrapRetrievalEndOffset--;
}
outer:
for (SoftWrap softWrap : getSoftWrapModel().getSoftWrapsForRange(start, softWrapRetrievalEndOffset)) {
char[] softWrapChars = softWrap.getChars();
CharArrayCharSequence softWrapSeq = new CharArrayCharSequence(softWrapChars);
if (softWrap.getStart() == startDrawingOffset) {
// If we are here that means that we are located on soft wrap-introduced visual line just after soft wrap. Hence, we need
// to draw soft wrap indent if any and 'after soft wrap' sign.
int i = CharArrayUtil.lastIndexOf(softWrapChars, '\n', 0, softWrapChars.length);
if (i < softWrapChars.length - 1) {
position.x = 0; // Soft wrap starts new visual line
position.x = drawString(
g, softWrapSeq, i + 1, softWrapChars.length, position, clip, null, null, fontType, fontColor, context
);
}
position.x += mySoftWrapModel.paint(g, SoftWrapDrawingType.AFTER_SOFT_WRAP, position.x, position.y, getLineHeight());
continue;
}
// Draw token text before the wrap.
if (softWrap.getStart() > start) {
position.x = drawString(
g, text, start, softWrap.getStart(), position, clip, null, null, fontType, fontColor, context
);
}
start = softWrap.getStart();
// We don't draw every soft wrap symbol one-by-one but whole visual line. Current variable holds index that points
// to the first soft wrap symbol that is not drawn yet.
int softWrapSegmentStartIndex = 0;
for (int i = 0; i < softWrapChars.length; i++) {
// Delay soft wraps symbols drawing until EOL is found.
if (softWrapChars[i] != '\n') {
continue;
}
// Draw soft wrap symbols on current visual line if any.
if (i - softWrapSegmentStartIndex > 0) {
drawString(
g, softWrapSeq, softWrapSegmentStartIndex, i, position, clip, null, null, fontType, fontColor, context
);
}
mySoftWrapModel.paint(g, SoftWrapDrawingType.BEFORE_SOFT_WRAP_LINE_FEED, position.x, position.y, getLineHeight());
// Reset 'x' coordinate because of new line start.
position.x = 0;
// Stop the processing if we drew the whole clip.
if (position.y > clip.y + clip.height) {
break outer;
}
position.y += getLineHeight();
softWrapSegmentStartIndex = i + 1;
}
// Draw remaining soft wrap symbols from its last line if any.
if (softWrapSegmentStartIndex < softWrapChars.length) {
position.x += drawString(
g, softWrapSeq, softWrapSegmentStartIndex, softWrapChars.length, position, clip, null, null, fontType, fontColor, context
);
}
position.x += mySoftWrapModel.paint(g, SoftWrapDrawingType.AFTER_SOFT_WRAP, position.x, position.y, getLineHeight());
}
return position.x = drawString(g, text, start, end, position, clip, effectColor, effectType, fontType, fontColor, context);
}
private int drawString(@NotNull Graphics g,
final CharSequence text,
int start,
int end,
@NotNull Point position,
@NotNull Rectangle clip,
@Nullable Color effectColor,
@Nullable EffectType effectType,
@JdkConstants.FontStyle int fontType,
Color fontColor,
WhitespacePaintingStrategy context) {
if (start >= end) return position.x;
boolean isInClip = getLineHeight() + position.y >= clip.y && position.y <= clip.y + clip.height;
if (!isInClip) return position.x;
int y = getAscent() + position.y;
int x = position.x;
return drawTabbedString(g, text, start, end, x, y, effectColor, effectType, fontType, fontColor, clip, context);
}
public int getAscent() {
if (myUseNewRendering) return myView.getAscent();
return getLineHeight() - getDescent();
}
private int drawString(@NotNull Graphics g,
@NotNull String text,
@NotNull Point position,
@NotNull Rectangle clip,
Color effectColor,
EffectType effectType,
@JdkConstants.FontStyle int fontType,
Color fontColor,
WhitespacePaintingStrategy context) {
boolean isInClip = getLineHeight() + position.y >= clip.y && position.y <= clip.y + clip.height;
if (!isInClip) return position.x;
int y = getAscent() + position.y;
int x = position.x;
return drawTabbedString(g, text, 0, text.length(), x, y, effectColor, effectType, fontType, fontColor, clip, context);
}
private int drawTabbedString(@NotNull Graphics g,
CharSequence text,
int start,
int end,
int x,
int y,
@Nullable Color effectColor,
EffectType effectType,
@JdkConstants.FontStyle int fontType,
Color fontColor,
@NotNull final Rectangle clip,
WhitespacePaintingStrategy context) {
int xStart = x;
for (int i = start; i < end; i++) {
if (text.charAt(i) != '\t') continue;
x = drawTablessString(text, start, i, g, x, y, fontType, fontColor, clip, context);
int x1 = EditorUtil.nextTabStop(x, this);
drawTabPlacer(g, y, x, x1, i, context);
x = x1;
start = i + 1;
}
x = drawTablessString(text, start, end, g, x, y, fontType, fontColor, clip, context);
if (effectColor != null) {
final Color savedColor = g.getColor();
// myBorderEffect.flushIfCantProlong(g, this, effectType, effectColor);
int xEnd = x;
if (xStart < clip.x && xEnd < clip.x || xStart > clip.x + clip.width && xEnd > clip.x + clip.width) {
return x;
}
if (xEnd > clip.x + clip.width) {
xEnd = clip.x + clip.width;
}
if (xStart < clip.x) {
xStart = clip.x;
}
if (effectType == EffectType.LINE_UNDERSCORE) {
g.setColor(effectColor);
UIUtil.drawLine(g, xStart, y + 1, xEnd, y + 1);
g.setColor(savedColor);
}
else if (effectType == EffectType.BOLD_LINE_UNDERSCORE) {
g.setColor(effectColor);
drawBoldLineUnderScore(g, xStart, y, xEnd-xStart);
g.setColor(savedColor);
}
else if (effectType == EffectType.STRIKEOUT) {
g.setColor(effectColor);
int y1 = y - getCharHeight() / 2;
UIUtil.drawLine(g, xStart, y1, xEnd, y1);
g.setColor(savedColor);
}
else if (effectType == EffectType.WAVE_UNDERSCORE) {
g.setColor(effectColor);
UIUtil.drawWave((Graphics2D)g, new Rectangle(xStart, y+1, xEnd - xStart, getDescent() - 1));
g.setColor(savedColor);
}
else if (effectType == EffectType.BOLD_DOTTED_LINE) {
final Color bgColor = getBackgroundColor();
final int dottedAt = SystemInfo.isMac ? y : y + 1;
UIUtil.drawBoldDottedLine((Graphics2D)g, xStart, xEnd, dottedAt, bgColor, effectColor, false);
}
}
return x;
}
private int drawTablessString(final CharSequence text,
int start,
final int end,
@NotNull final Graphics g,
int x,
final int y,
@JdkConstants.FontStyle final int fontType,
final Color fontColor,
@NotNull final Rectangle clip,
WhitespacePaintingStrategy context) {
int endX = x;
if (start < end) {
FontInfo font = null;
boolean drawWhitespace = false;
for (int j = start; j < end; j++) {
if (x > clip.x + clip.width) {
return endX;
}
final char c = text.charAt(j);
FontInfo newFont = EditorUtil.fontForChar(c, fontType, this);
boolean newDrawWhitespace = context.showWhitespaceAtOffset(j);
boolean isRtlChar = myDisableRtl && isRtlCharacter(c);
if (j > start && (endX < clip.x || endX > clip.x + clip.width || newFont != font || newDrawWhitespace != drawWhitespace || isRtlChar)) {
if (isOverlappingRange(clip, x, endX)) {
drawCharsCached(g, text, start, j, x, y, fontType, fontColor, drawWhitespace);
}
start = j;
x = endX;
}
font = newFont;
drawWhitespace = newDrawWhitespace;
endX += font.charWidth(c);
if (font.hasGlyphsToBreakDrawingIteration() && font.getSymbolsToBreakDrawingIteration().contains(c) || isRtlChar) {
drawCharsCached(g, text, start, j + 1, x, y, fontType, fontColor, drawWhitespace);
start = j + 1;
x = endX;
}
}
if (isOverlappingRange(clip, x, endX)) {
drawCharsCached(g, text, start, end, x, y, fontType, fontColor, drawWhitespace);
}
}
return endX;
}
private static boolean isOverlappingRange(Rectangle clip, int xStart, int xEnd) {
return !(xStart < clip.x && xEnd < clip.x || xStart > clip.x + clip.width && xEnd > clip.x + clip.width);
}
private void drawTabPlacer(Graphics g, int y, int start, int stop, int offset, WhitespacePaintingStrategy context) {
if (context.showWhitespaceAtOffset(offset)) {
myTabPainter.paint(g, y, start, stop);
}
}
private void drawCharsCached(@NotNull Graphics g,
CharSequence data,
int start,
int end,
int x,
int y,
@JdkConstants.FontStyle int fontType,
Color color,
boolean drawWhitespace) {
FontInfo fnt = EditorUtil.fontForChar(data.charAt(start), fontType, this);
if (myLastCache != null && spacesOnly(data, start, end) && fnt.charWidth(' ') == myLastCache.spaceWidth) {
// we don't care about font if we only need to paint spaces and space width matches
myLastCache.addContent(g, data, start, end, x, y, null, drawWhitespace);
}
else {
drawCharsCached(g, data, start, end, x, y, fnt, color, drawWhitespace);
}
}
private void drawCharsCached(@NotNull Graphics g,
@NotNull CharSequence data,
int start,
int end,
int x,
int y,
@NotNull FontInfo fnt,
Color color,
boolean drawWhitespace) {
CachedFontContent cache = null;
for (CachedFontContent fontCache : myFontCache) {
if (fontCache.myFontType == fnt) {
cache = fontCache;
break;
}
}
if (cache == null) {
cache = new CachedFontContent(fnt);
myFontCache.add(cache);
}
myLastCache = cache;
cache.addContent(g, data, start, end, x, y, color, drawWhitespace);
}
private static boolean spacesOnly(CharSequence chars, int start, int end) {
for (int i = start; i < end; i++) {
if (chars.charAt(i) != ' ') return false;
}
return true;
}
private void drawChars(@NotNull Graphics g, CharSequence data, int start, int end, int x, int y, boolean drawWhitespace) {
g.drawString(data.subSequence(start, end).toString(), x, y);
if (drawWhitespace) {
Color oldColor = g.getColor();
g.setColor(myScheme.getColor(EditorColors.WHITESPACES_COLOR));
final FontMetrics metrics = g.getFontMetrics();
for (int i = start; i < end; i++) {
final char c = data.charAt(i);
final int charWidth = isOracleRetina ? GraphicsUtil.charWidth(c, g.getFont()) : metrics.charWidth(c);
if (c == ' ') {
g.fillRect(x + (charWidth >> 1), y, 1, 1);
} else if (c == IDEOGRAPHIC_SPACE) {
final int charHeight = getCharHeight();
g.drawRect(x + 2, y - charHeight, charWidth - 4, charHeight);
}
x += charWidth;
}
g.setColor(oldColor);
}
}
private int getTextSegmentWidth(@NotNull CharSequence text,
int start,
int end,
int xStart,
@JdkConstants.FontStyle int fontType,
@NotNull Rectangle clip) {
int x = xStart;
for (int i = start; i < end && xStart < clip.x + clip.width; i++) {
char c = text.charAt(i);
if (c == '\t') {
x = EditorUtil.nextTabStop(x, this);
}
else {
x += EditorUtil.charWidth(c, fontType, this);
}
if (x > clip.x + clip.width) {
break;
}
}
return x - xStart;
}
@Override
public int getLineHeight() {
if (myUseNewRendering) return myView.getLineHeight();
assertReadAccess();
int lineHeight = myLineHeight;
if (lineHeight < 0) {
FontMetrics fontMetrics = myEditorComponent.getFontMetrics(myScheme.getFont(EditorFontType.PLAIN));
int fontMetricsHeight = fontMetrics.getHeight();
lineHeight = (int)(fontMetricsHeight * (isOneLineMode() ? 1 : myScheme.getLineSpacing()));
if (lineHeight <= 0) {
lineHeight = fontMetricsHeight;
if (lineHeight <= 0) {
lineHeight = 12;
}
}
assert lineHeight > 0 : lineHeight;
myLineHeight = lineHeight;
}
return lineHeight;
}
public int getDescent() {
if (myUseNewRendering) return myView.getDescent();
if (myDescent != -1) {
return myDescent;
}
FontMetrics fontMetrics = myEditorComponent.getFontMetrics(myScheme.getFont(EditorFontType.PLAIN));
myDescent = fontMetrics.getDescent();
return myDescent;
}
@NotNull
public FontMetrics getFontMetrics(@JdkConstants.FontStyle int fontType) {
if (myPlainFontMetrics == null) {
assertIsDispatchThread();
myPlainFontMetrics = myEditorComponent.getFontMetrics(myScheme.getFont(EditorFontType.PLAIN));
myBoldFontMetrics = myEditorComponent.getFontMetrics(myScheme.getFont(EditorFontType.BOLD));
myItalicFontMetrics = myEditorComponent.getFontMetrics(myScheme.getFont(EditorFontType.ITALIC));
myBoldItalicFontMetrics = myEditorComponent.getFontMetrics(myScheme.getFont(EditorFontType.BOLD_ITALIC));
}
if (fontType == Font.PLAIN) return myPlainFontMetrics;
if (fontType == Font.BOLD) return myBoldFontMetrics;
if (fontType == Font.ITALIC) return myItalicFontMetrics;
if (fontType == (Font.BOLD | Font.ITALIC)) return myBoldItalicFontMetrics;
LOG.error("Unknown font type: " + fontType);
return myPlainFontMetrics;
}
private int getCharHeight() {
if (myUseNewRendering) return myView.getCharHeight();
if (myCharHeight == -1) {
assertIsDispatchThread();
FontMetrics fontMetrics = myEditorComponent.getFontMetrics(myScheme.getFont(EditorFontType.PLAIN));
myCharHeight = fontMetrics.charWidth('a');
}
return myCharHeight;
}
public int getPreferredHeight() {
if (ourIsUnitTestMode && getUserData(DO_DOCUMENT_UPDATE_TEST) == null) {
return 1;
}
if (isOneLineMode()) return getLineHeight();
// Preferred height of less than a single line height doesn't make sense:
// at least a single line with a blinking caret on it is to be displayed
int size = Math.max(getVisibleLineCount(), 1) * getLineHeight();
if (mySettings.isAdditionalPageAtBottom()) {
int lineHeight = getLineHeight();
int visibleAreaHeight = getScrollingModel().getVisibleArea().height;
// There is a possible case that user with 'show additional page at bottom' scrolls to that virtual page; switched to another
// editor (another tab); and then returns to the previously used editor (the one scrolled to virtual page). We want to preserve
// correct view size then because viewport position is set to the end of the original text otherwise.
if (visibleAreaHeight > 0 || myVirtualPageHeight <= 0) {
myVirtualPageHeight = Math.max(visibleAreaHeight - 2 * lineHeight, lineHeight);
}
return size + Math.max(myVirtualPageHeight, 0);
}
return size + mySettings.getAdditionalLinesCount() * getLineHeight();
}
public Dimension getPreferredSize() {
if (myUseNewRendering) return myView.getPreferredSize();
if (ourIsUnitTestMode && getUserData(DO_DOCUMENT_UPDATE_TEST) == null) {
return new Dimension(1, 1);
}
final Dimension draft = getSizeWithoutCaret();
final int additionalSpace = shouldRespectAdditionalColumns()
? mySettings.getAdditionalColumnsCount() * EditorUtil.getSpaceWidth(Font.PLAIN, this)
: 0;
if (!myDocument.isInBulkUpdate()) {
for (Caret caret : myCaretModel.getAllCarets()) {
if (caret.isUpToDate()) {
int caretX = visualPositionToXY(caret.getVisualPosition()).x;
draft.width = Math.max(caretX, draft.width);
}
}
}
draft.width += additionalSpace;
return draft;
}
private boolean shouldRespectAdditionalColumns() {
return !mySoftWrapModel.isSoftWrappingEnabled()
|| mySoftWrapModel.isRespectAdditionalColumns()
|| mySizeContainer.getContentSize().getWidth() > myScrollingModel.getVisibleArea().getWidth();
}
private Dimension getSizeWithoutCaret() {
Dimension size = mySizeContainer.getContentSize();
return new Dimension(size.width, getPreferredHeight());
}
@NotNull
@Override
public Dimension getContentSize() {
if (myUseNewRendering) return myView.getPreferredSize();
Dimension size = mySizeContainer.getContentSize();
return new Dimension(size.width, size.height + mySettings.getAdditionalLinesCount() * getLineHeight());
}
@NotNull
@Override
public JScrollPane getScrollPane() {
return myScrollPane;
}
@Override
public void setBorder(Border border) {
myScrollPane.setBorder(border);
}
@Override
public Insets getInsets() {
return myScrollPane.getInsets();
}
@Override
public int logicalPositionToOffset(@NotNull LogicalPosition pos) {
return logicalPositionToOffset(pos, true);
}
@Override
public int logicalPositionToOffset(@NotNull LogicalPosition pos, boolean softWrapAware) {
if (myUseNewRendering) return myView.logicalPositionToOffset(pos);
if (softWrapAware) {
return mySoftWrapModel.logicalPositionToOffset(pos);
}
assertReadAccess();
if (myDocument.getLineCount() == 0) return 0;
if (pos.line < 0) throw new IndexOutOfBoundsException("Wrong line: " + pos.line);
if (pos.column < 0) throw new IndexOutOfBoundsException("Wrong column:" + pos.column);
if (pos.line >= myDocument.getLineCount()) {
return myDocument.getTextLength();
}
int start = myDocument.getLineStartOffset(pos.line);
if (pos.column == 0) return start;
int end = myDocument.getLineEndOffset(pos.line);
int x = getDocument().getLineNumber(start) == 0 ? getPrefixTextWidthInPixels() : 0;
int result = EditorUtil.calcSoftWrapUnawareOffset(this, myDocument.getImmutableCharSequence(), start, end, pos.column,
EditorUtil.getTabSize(this), x, new int[]{0}, null);
if (result >= 0) {
return result;
}
return end;
}
@Override
public void setLastColumnNumber(int val) {
assertIsDispatchThread();
myLastColumnNumber = val;
}
@Override
public int getLastColumnNumber() {
assertReadAccess();
return myLastColumnNumber;
}
/**
* @return information about total number of lines that can be viewed by user. I.e. this is a number of all document
* lines (considering that single logical document line may be represented on multiple visual lines because of
* soft wraps appliance) minus number of folded lines
*/
public int getVisibleLineCount() {
return getVisibleLogicalLinesCount() + getSoftWrapModel().getSoftWrapsIntroducedLinesNumber();
}
/**
* @return number of visible logical lines. Generally, that is a total logical lines number minus number of folded lines
*/
private int getVisibleLogicalLinesCount() {
return getDocument().getLineCount() - myFoldingModel.getFoldedLinesCountBefore(getDocument().getTextLength() + 1);
}
@Override
@NotNull
public VisualPosition logicalToVisualPosition(@NotNull LogicalPosition logicalPos) {
return logicalToVisualPosition(logicalPos, true);
}
@Override
@NotNull
public VisualPosition logicalToVisualPosition(@NotNull LogicalPosition logicalPos, boolean softWrapAware) {
if (myUseNewRendering) return myView.logicalToVisualPosition(logicalPos, false);
return doLogicalToVisualPosition(logicalPos, softWrapAware,0);
}
@NotNull
private VisualPosition doLogicalToVisualPosition(@NotNull LogicalPosition logicalPos, boolean softWrapAware,
// TODO den remove as soon as the problem is fixed.
int stackDepth) {
assertReadAccess();
if (!myFoldingModel.isFoldingEnabled() && !mySoftWrapModel.isSoftWrappingEnabled()) {
return new VisualPosition(logicalPos.line, logicalPos.column);
}
int offset = logicalPositionToOffset(logicalPos);
FoldRegion outermostCollapsed = myFoldingModel.getCollapsedRegionAtOffset(offset);
if (outermostCollapsed != null && offset > outermostCollapsed.getStartOffset()) {
if (offset < getDocument().getTextLength()) {
offset = outermostCollapsed.getStartOffset();
LogicalPosition foldStart = offsetToLogicalPosition(offset);
// TODO den remove as soon as the problem is fixed.
if (stackDepth > 15) {
LOG.error("Detected potential StackOverflowError at logical->visual position mapping. Given logical position: '" +
logicalPos + "'. State: " + dumpState());
stackDepth = -1;
}
return doLogicalToVisualPosition(foldStart, true, stackDepth+1);
}
else {
offset = outermostCollapsed.getEndOffset() + 3; // WTF?
}
}
int line = logicalPos.line;
int column = logicalPos.column;
int foldedLinesCountBefore = myFoldingModel.getFoldedLinesCountBefore(offset);
line -= foldedLinesCountBefore;
if (line < 0) {
LogMessageEx.error(
LOG, "Invalid LogicalPosition -> VisualPosition processing", String.format(
"Given logical position: %s; matched line: %d; fold lines before: %d, state: %s",
logicalPos, line, foldedLinesCountBefore, dumpState()
));
}
FoldRegion[] topLevel = myFoldingModel.fetchTopLevel();
LogicalPosition anchorFoldingPosition = logicalPos;
for (int idx = myFoldingModel.getLastCollapsedRegionBefore(offset); idx >= 0 && topLevel != null; idx--) {
FoldRegion region = topLevel[idx];
if (region.isValid()) {
if (region.getDocument().getLineNumber(region.getEndOffset()) == anchorFoldingPosition.line && region.getEndOffset() <= offset) {
LogicalPosition foldStart = offsetToLogicalPosition(region.getStartOffset());
LogicalPosition foldEnd = offsetToLogicalPosition(region.getEndOffset());
column += foldStart.column + region.getPlaceholderText().length() - foldEnd.column;
offset = region.getStartOffset();
anchorFoldingPosition = foldStart;
}
else {
break;
}
}
}
VisualPosition softWrapUnawarePosition = new VisualPosition(line, Math.max(0, column));
if (softWrapAware) {
return mySoftWrapModel.adjustVisualPosition(logicalPos, softWrapUnawarePosition);
}
return softWrapUnawarePosition;
}
@Nullable
private FoldRegion getLastCollapsedBeforePosition(@NotNull VisualPosition visualPos) {
FoldRegion[] topLevelCollapsed = myFoldingModel.fetchTopLevel();
if (topLevelCollapsed == null) return null;
int start = 0;
int end = topLevelCollapsed.length - 1;
int i = 0;
while (start <= end) {
i = (start + end) / 2;
FoldRegion region = topLevelCollapsed[i];
if (!region.isValid()) {
// Folding model is inconsistent (update in progress).
return null;
}
int regionVisualLine = offsetToVisualLine(region.getEndOffset() - 1);
if (regionVisualLine < visualPos.line) {
start = i + 1;
}
else {
if (regionVisualLine > visualPos.line) {
end = i - 1;
}
else {
VisualPosition visFoldEnd = offsetToVisualPosition(region.getEndOffset() - 1);
if (visFoldEnd.column < visualPos.column) {
start = i + 1;
}
else {
if (visFoldEnd.column > visualPos.column) {
end = i - 1;
}
else {
i--;
break;
}
}
}
}
}
while (i >= 0 && i < topLevelCollapsed.length) {
if (topLevelCollapsed[i].isValid()) break;
i--;
}
if (i >= 0 && i < topLevelCollapsed.length) {
FoldRegion region = topLevelCollapsed[i];
VisualPosition visFoldEnd = offsetToVisualPosition(region.getEndOffset() - 1);
if (visFoldEnd.line > visualPos.line || visFoldEnd.line == visualPos.line && visFoldEnd.column > visualPos.column) {
i--;
if (i >= 0) {
return topLevelCollapsed[i];
}
return null;
}
return region;
}
return null;
}
@Override
@NotNull
public LogicalPosition visualToLogicalPosition(@NotNull VisualPosition visiblePos) {
return visualToLogicalPosition(visiblePos, true);
}
@Override
@NotNull
public LogicalPosition visualToLogicalPosition(@NotNull VisualPosition visiblePos, boolean softWrapAware) {
if (myUseNewRendering) return myView.visualToLogicalPosition(visiblePos);
assertReadAccess();
if (softWrapAware) {
return mySoftWrapModel.visualToLogicalPosition(visiblePos);
}
if (!myFoldingModel.isFoldingEnabled()) return new LogicalPosition(visiblePos.line, visiblePos.column);
int line = visiblePos.line;
int column = visiblePos.column;
FoldRegion lastCollapsedBefore = getLastCollapsedBeforePosition(visiblePos);
if (lastCollapsedBefore != null) {
int logFoldEndLine = offsetToLogicalLine(lastCollapsedBefore.getEndOffset());
int visFoldEndLine = logicalToVisualLine(logFoldEndLine);
line = logFoldEndLine + visiblePos.line - visFoldEndLine;
if (visFoldEndLine == visiblePos.line) {
LogicalPosition logFoldEnd = offsetToLogicalPosition(lastCollapsedBefore.getEndOffset(), false);
VisualPosition visFoldEnd = logicalToVisualPosition(logFoldEnd, false);
if (visiblePos.column >= visFoldEnd.column) {
column = logFoldEnd.column + visiblePos.column - visFoldEnd.column;
}
else {
return offsetToLogicalPosition(lastCollapsedBefore.getStartOffset(), false);
}
}
}
if (column < 0) column = 0;
return new LogicalPosition(line, column);
}
int offsetToLogicalLine(int offset) {
int textLength = myDocument.getTextLength();
if (textLength == 0) return 0;
if (offset > textLength || offset < 0) {
throw new IndexOutOfBoundsException("Wrong offset: " + offset + " textLength: " + textLength);
}
int lineIndex = myDocument.getLineNumber(offset);
LOG.assertTrue(lineIndex >= 0 && lineIndex < myDocument.getLineCount());
return lineIndex;
}
@Override
public int calcColumnNumber(int offset, int lineIndex) {
return calcColumnNumber(offset, lineIndex, true, myDocument.getImmutableCharSequence());
}
public int calcColumnNumber(int offset, int lineIndex, boolean softWrapAware, @NotNull CharSequence documentCharSequence) {
if (myUseNewRendering) return myView.offsetToLogicalPosition(offset).column;
if (myDocument.getTextLength() == 0) return 0;
int lineStartOffset = myDocument.getLineStartOffset(lineIndex);
if (lineStartOffset == offset) return 0;
int lineEndOffset = myDocument.getLineEndOffset(lineIndex);
if (lineEndOffset < offset) offset = lineEndOffset; // handling the case when offset is inside non-normalized line terminator
int column = EditorUtil.calcColumnNumber(this, documentCharSequence, lineStartOffset, offset);
if (softWrapAware) {
int line = offsetToLogicalLine(offset);
return mySoftWrapModel.adjustLogicalPosition(new LogicalPosition(line, column), offset).column;
}
else {
return column;
}
}
private LogicalPosition getLogicalPositionForScreenPos(int x, int y, boolean trimToLineWidth) {
if (x < 0) {
x = 0;
}
LogicalPosition pos = xyToLogicalPosition(new Point(x, y));
int column = pos.column;
int line = pos.line;
int softWrapLinesBeforeTargetLogicalLine = pos.softWrapLinesBeforeCurrentLogicalLine;
int softWrapLinesOnTargetLogicalLine = pos.softWrapLinesOnCurrentLogicalLine;
int softWrapColumns = pos.softWrapColumnDiff;
boolean leansForward = pos.leansForward;
boolean leansRight = pos.visualPositionLeansRight;
final int totalLines = myDocument.getLineCount();
if (totalLines <= 0) {
return new LogicalPosition(0, 0);
}
if (line >= totalLines && totalLines > 0) {
int visibleLineCount = getVisibleLineCount();
int newY = visibleLineCount > 0 ? visibleLineToY(visibleLineCount - 1) : 0;
if (newY > 0 && newY == y) {
newY = visibleLineToY(getVisibleLogicalLinesCount());
}
if (newY >= y) {
LogMessageEx.error(LOG, "cycled moveCaretToScreenPos() detected",
String.format("x=%d, y=%d\nvisibleLineCount=%d, newY=%d\nstate=%s", x, y, visibleLineCount, newY, dumpState()));
throw new IllegalStateException("cycled moveCaretToScreenPos() detected");
}
return getLogicalPositionForScreenPos(x, newY, trimToLineWidth);
}
if (!mySettings.isVirtualSpace() && trimToLineWidth) {
int lineEndOffset = myDocument.getLineEndOffset(line);
int lineEndColumn = calcColumnNumber(lineEndOffset, line);
if (column > lineEndColumn) {
column = lineEndColumn;
leansForward = true;
leansRight = true;
if (softWrapColumns != 0) {
softWrapColumns -= column - lineEndColumn;
}
}
}
if (!mySettings.isCaretInsideTabs()) {
int offset = logicalPositionToOffset(new LogicalPosition(line, column));
CharSequence text = myDocument.getImmutableCharSequence();
if (offset >= 0 && offset < myDocument.getTextLength()) {
if (text.charAt(offset) == '\t') {
column = calcColumnNumber(offset, line);
}
}
}
return pos.visualPositionAware ?
new LogicalPosition(
line, column, softWrapLinesBeforeTargetLogicalLine, softWrapLinesOnTargetLogicalLine, softWrapColumns,
pos.foldedLines, pos.foldingColumnDiff, leansForward, leansRight
) :
new LogicalPosition(line, column, leansForward);
}
private VisualPosition getTargetPosition(int x, int y, boolean trimToLineWidth) {
if (myDocument.getLineCount() == 0) {
return new VisualPosition(0, 0);
}
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
int visualLineCount = getVisibleLineCount();
if (yPositionToVisibleLine(y) >= visualLineCount) {
y = visibleLineToY(Math.max(0, visualLineCount - 1));
}
VisualPosition visualPosition = xyToVisualPosition(new Point(x, y));
if (trimToLineWidth && !mySettings.isVirtualSpace()) {
LogicalPosition logicalPosition = visualToLogicalPosition(visualPosition);
LogicalPosition lineEndPosition = offsetToLogicalPosition(myDocument.getLineEndOffset(logicalPosition.line));
if (logicalPosition.column > lineEndPosition.column) {
visualPosition = logicalToVisualPosition(lineEndPosition.leanForward(true));
}
}
return visualPosition;
}
private boolean checkIgnore(@NotNull MouseEvent e, boolean isFinalCheck) {
if (!myIgnoreMouseEventsConsecutiveToInitial) {
myInitialMouseEvent = null;
return false;
}
if (myInitialMouseEvent!= null && (e.getComponent() != myInitialMouseEvent.getComponent() || !e.getPoint().equals(myInitialMouseEvent.getPoint()))) {
myIgnoreMouseEventsConsecutiveToInitial = false;
myInitialMouseEvent = null;
return false;
}
if (isFinalCheck) {
myIgnoreMouseEventsConsecutiveToInitial = false;
myInitialMouseEvent = null;
}
e.consume();
return true;
}
private void processMouseReleased(@NotNull MouseEvent e) {
if (checkIgnore(e, true)) return;
if (e.getSource() == myGutterComponent && !(myMousePressedEvent != null && myMousePressedEvent.isConsumed())) {
myGutterComponent.mouseReleased(e);
}
if (getMouseEventArea(e) != EditorMouseEventArea.EDITING_AREA || e.getY() < 0 || e.getX() < 0) {
return;
}
// if (myMousePressedInsideSelection) getSelectionModel().removeSelection();
final FoldRegion region = getFoldingModel().getFoldingPlaceholderAt(e.getPoint());
if (e.getX() >= 0 && e.getY() >= 0 && region != null && region == myMouseSelectedRegion) {
getFoldingModel().runBatchFoldingOperation(new Runnable() {
@Override
public void run() {
myFoldingModel.flushCaretShift();
region.setExpanded(true);
}
});
// The call below is performed because gutter's height is not updated sometimes, i.e. it sticks to the value that corresponds
// to the situation when fold region is collapsed. That causes bottom of the gutter to not be repainted and that looks really ugly.
myGutterComponent.updateSize();
}
// The general idea is to check if the user performed 'caret position change click' (left click most of the time) inside selection
// and, in the case of the positive answer, clear selection. Please note that there is a possible case that mouse click
// is performed inside selection but it triggers context menu. We don't want to drop the selection then.
if (myMousePressedEvent != null && myMousePressedEvent.getClickCount() == 1 && myMousePressedInsideSelection
&& !myMousePressedEvent.isShiftDown()
&& !myMousePressedEvent.isPopupTrigger()
&& !isToggleCaretEvent(myMousePressedEvent)
&& !isCreateRectangularSelectionEvent(myMousePressedEvent)) {
getSelectionModel().removeSelection();
}
}
@NotNull
@Override
public DataContext getDataContext() {
return getProjectAwareDataContext(DataManager.getInstance().getDataContext(getContentComponent()));
}
@NotNull
private DataContext getProjectAwareDataContext(@NotNull final DataContext original) {
if (CommonDataKeys.PROJECT.getData(original) == myProject) return original;
return new DataContext() {
@Override
public Object getData(String dataId) {
if (CommonDataKeys.PROJECT.is(dataId)) {
return myProject;
}
return original.getData(dataId);
}
};
}
@Override
public EditorMouseEventArea getMouseEventArea(@NotNull MouseEvent e) {
if (myGutterComponent != e.getSource()) return EditorMouseEventArea.EDITING_AREA;
int x = myGutterComponent.convertX(e.getX());
return myGutterComponent.getEditorMouseAreaByOffset(x);
}
private void requestFocus() {
final IdeFocusManager focusManager = IdeFocusManager.getInstance(myProject);
if (focusManager.getFocusOwner() != myEditorComponent) { //IDEA-64501
focusManager.requestFocus(myEditorComponent, true);
}
}
private void validateMousePointer(@NotNull MouseEvent e) {
if (e.getSource() == myGutterComponent) {
myGutterComponent.validateMousePointer(e);
}
else {
myGutterComponent.setActiveFoldRegion(null);
if (getSelectionModel().hasSelection() && (e.getModifiersEx() & (InputEvent.BUTTON1_DOWN_MASK | InputEvent.BUTTON2_DOWN_MASK)) == 0) {
int offset = logicalPositionToOffset(xyToLogicalPosition(e.getPoint()));
if (getSelectionModel().getSelectionStart() <= offset && offset < getSelectionModel().getSelectionEnd()) {
myEditorComponent.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
return;
}
}
myEditorComponent.setCursor(UIUtil.getTextCursor(getBackgroundColor()));
}
}
private void runMouseDraggedCommand(@NotNull final MouseEvent e) {
if (myCommandProcessor == null || myMousePressedEvent != null && myMousePressedEvent.isConsumed()) {
return;
}
myCommandProcessor.executeCommand(myProject, new Runnable() {
@Override
public void run() {
processMouseDragged(e);
}
}, "", MOUSE_DRAGGED_GROUP, UndoConfirmationPolicy.DEFAULT, getDocument());
}
private void processMouseDragged(@NotNull MouseEvent e) {
if (!JBSwingUtilities.isLeftMouseButton(e) && !JBSwingUtilities.isMiddleMouseButton(e)) {
return;
}
if (getMouseEventArea(e) == EditorMouseEventArea.LINE_MARKERS_AREA) {
// The general idea is that we don't want to change caret position on gutter marker area click (e.g. on setting a breakpoint)
// but do want to allow bulk selection on gutter marker mouse drag. However, when a drag is performed, the first event is
// a 'mouse pressed' event, that's why we remember target line on 'mouse pressed' processing and use that information on
// further dragging (if any).
if (myDragOnGutterSelectionStartLine >= 0) {
mySelectionModel.removeSelection();
myCaretModel.moveToOffset(myDragOnGutterSelectionStartLine < myDocument.getLineCount()
? myDocument.getLineStartOffset(myDragOnGutterSelectionStartLine) : myDocument.getTextLength());
}
myDragOnGutterSelectionStartLine = - 1;
}
boolean columnSelectionDragEvent = isColumnSelectionDragEvent(e);
boolean toggleCaretEvent = isToggleCaretEvent(e);
boolean addRectangularSelectionEvent = isAddRectangularSelectionEvent(e);
boolean columnSelectionDrag = isColumnMode() && !myLastPressCreatedCaret || columnSelectionDragEvent;
if (!columnSelectionDragEvent && toggleCaretEvent && !myLastPressCreatedCaret) {
return; // ignoring drag after removing a caret
}
Rectangle visibleArea = getScrollingModel().getVisibleArea();
int x = e.getX();
if (e.getSource() == myGutterComponent) {
x = 0;
}
int dx = 0;
if (x < visibleArea.x && visibleArea.x > 0) {
dx = x - visibleArea.x;
}
else {
if (x > visibleArea.x + visibleArea.width) {
dx = x - visibleArea.x - visibleArea.width;
}
}
int dy = 0;
int y = e.getY();
if (y < visibleArea.y && visibleArea.y > 0) {
dy = y - visibleArea.y;
}
else {
if (y > visibleArea.y + visibleArea.height) {
dy = y - visibleArea.y - visibleArea.height;
}
}
if (dx == 0 && dy == 0) {
myScrollingTimer.stop();
SelectionModel selectionModel = getSelectionModel();
Caret leadCaret = getLeadCaret();
int oldSelectionStart = leadCaret.getLeadSelectionOffset();
VisualPosition oldVisLeadSelectionStart = leadCaret.getLeadSelectionPosition();
int oldCaretOffset = getCaretModel().getOffset();
boolean multiCaretSelection = columnSelectionDrag || toggleCaretEvent;
VisualPosition newVisualCaret = myUseNewRendering ? getTargetPosition(x, y, !multiCaretSelection) : null;
LogicalPosition newLogicalCaret = myUseNewRendering ? visualToLogicalPosition(newVisualCaret) :
getLogicalPositionForScreenPos(x, y, !multiCaretSelection);
if (multiCaretSelection) {
myMultiSelectionInProgress = true;
myRectangularSelectionInProgress = columnSelectionDrag || addRectangularSelectionEvent;
myTargetMultiSelectionPosition = xyToVisualPosition(new Point(Math.max(x, 0), Math.max(y, 0)));
}
else {
if (myUseNewRendering) {
getCaretModel().moveToVisualPosition(newVisualCaret);
}
else {
getCaretModel().moveToLogicalPosition(newLogicalCaret);
}
}
int newCaretOffset = getCaretModel().getOffset();
newVisualCaret = getCaretModel().getVisualPosition();
int caretShift = newCaretOffset - mySavedSelectionStart;
if (myMousePressedEvent != null && getMouseEventArea(myMousePressedEvent) != EditorMouseEventArea.EDITING_AREA &&
getMouseEventArea(myMousePressedEvent) != EditorMouseEventArea.LINE_NUMBERS_AREA) {
selectionModel.setSelection(oldSelectionStart, newCaretOffset);
}
else {
if (multiCaretSelection) {
if (myLastMousePressedLocation != null && (myCurrentDragIsSubstantial || !newLogicalCaret.equals(myLastMousePressedLocation))) {
createSelectionTill(newLogicalCaret);
blockActionsIfNeeded(e, myLastMousePressedLocation, newLogicalCaret);
}
}
else {
if (getMouseSelectionState() != MOUSE_SELECTION_STATE_NONE) {
if (caretShift < 0) {
int newSelection = newCaretOffset;
if (getMouseSelectionState() == MOUSE_SELECTION_STATE_WORD_SELECTED) {
newSelection = myCaretModel.getWordAtCaretStart();
}
else {
if (getMouseSelectionState() == MOUSE_SELECTION_STATE_LINE_SELECTED) {
newSelection =
logicalPositionToOffset(visualToLogicalPosition(new VisualPosition(getCaretModel().getVisualPosition().line, 0)));
}
}
if (newSelection < 0) newSelection = newCaretOffset;
selectionModel.setSelection(mySavedSelectionEnd, newSelection);
getCaretModel().moveToOffset(newSelection);
}
else {
int newSelection = newCaretOffset;
if (getMouseSelectionState() == MOUSE_SELECTION_STATE_WORD_SELECTED) {
newSelection = myCaretModel.getWordAtCaretEnd();
}
else {
if (getMouseSelectionState() == MOUSE_SELECTION_STATE_LINE_SELECTED) {
newSelection =
logicalPositionToOffset(visualToLogicalPosition(new VisualPosition(getCaretModel().getVisualPosition().line + 1, 0)));
}
}
if (newSelection < 0) newSelection = newCaretOffset;
selectionModel.setSelection(mySavedSelectionStart, newSelection);
getCaretModel().moveToOffset(newSelection);
}
cancelAutoResetForMouseSelectionState();
return;
}
if (!myMousePressedInsideSelection) {
// There is a possible case that lead selection position should be adjusted in accordance with the mouse move direction.
// E.g. consider situation when user selects the whole line by clicking at 'line numbers' area. 'Line end' is considered
// to be lead selection point then. However, when mouse is dragged down we want to consider 'line start' to be
// lead selection point.
if ((myMousePressArea == EditorMouseEventArea.LINE_NUMBERS_AREA
|| myMousePressArea == EditorMouseEventArea.LINE_MARKERS_AREA)
&& selectionModel.hasSelection()) {
if (newCaretOffset >= selectionModel.getSelectionEnd()) {
oldSelectionStart = selectionModel.getSelectionStart();
oldVisLeadSelectionStart = selectionModel.getSelectionStartPosition();
}
else if (newCaretOffset <= selectionModel.getSelectionStart()) {
oldSelectionStart = selectionModel.getSelectionEnd();
oldVisLeadSelectionStart = selectionModel.getSelectionEndPosition();
}
}
if (oldVisLeadSelectionStart != null) {
setSelectionAndBlockActions(e, oldVisLeadSelectionStart, oldSelectionStart, newVisualCaret, newCaretOffset);
}
else {
setSelectionAndBlockActions(e, oldSelectionStart, newCaretOffset);
}
cancelAutoResetForMouseSelectionState();
}
else {
if (caretShift != 0) {
if (myMousePressedEvent != null) {
if (mySettings.isDndEnabled()) {
if (myDraggedRange == null) {
boolean isCopy = UIUtil.isControlKeyDown(e) || isViewer() || !getDocument().isWritable();
mySavedCaretOffsetForDNDUndoHack = oldCaretOffset;
getContentComponent().getTransferHandler()
.exportAsDrag(getContentComponent(), e, isCopy ? TransferHandler.COPY : TransferHandler.MOVE);
}
}
else {
selectionModel.removeSelection();
}
}
}
}
}
}
}
else {
myScrollingTimer.start(dx, dy);
onSubstantialDrag(e);
}
}
private void clearDraggedRange() {
if (myDraggedRange != null) {
myDraggedRange.dispose();
myDraggedRange = null;
}
}
private void createSelectionTill(@NotNull LogicalPosition targetPosition) {
List<CaretState> caretStates = new ArrayList<CaretState>(myCaretStateBeforeLastPress);
if (myRectangularSelectionInProgress) {
caretStates.addAll(EditorModificationUtil.calcBlockSelectionState(this, myLastMousePressedLocation, targetPosition));
}
else {
LogicalPosition selectionStart = myLastMousePressedLocation;
LogicalPosition selectionEnd = targetPosition;
if (getMouseSelectionState() != MOUSE_SELECTION_STATE_NONE) {
int newCaretOffset = logicalPositionToOffset(targetPosition);
if (newCaretOffset < mySavedSelectionStart) {
selectionStart = offsetToLogicalPosition(mySavedSelectionEnd);
if (getMouseSelectionState() == MOUSE_SELECTION_STATE_LINE_SELECTED) {
targetPosition = selectionEnd = visualToLogicalPosition(new VisualPosition(offsetToVisualLine(newCaretOffset), 0));
}
}
else {
selectionStart = offsetToLogicalPosition(mySavedSelectionStart);
int selectionEndOffset = Math.max(newCaretOffset, mySavedSelectionEnd);
if (getMouseSelectionState() == MOUSE_SELECTION_STATE_WORD_SELECTED) {
targetPosition = selectionEnd = offsetToLogicalPosition(selectionEndOffset);
}
else if (getMouseSelectionState() == MOUSE_SELECTION_STATE_LINE_SELECTED) {
targetPosition = selectionEnd = visualToLogicalPosition(new VisualPosition(offsetToVisualLine(selectionEndOffset) + 1, 0));
}
}
cancelAutoResetForMouseSelectionState();
}
caretStates.add(new CaretState(targetPosition, selectionStart, selectionEnd));
}
myCaretModel.setCaretsAndSelections(caretStates);
}
private Caret getLeadCaret() {
List<Caret> allCarets = myCaretModel.getAllCarets();
Caret firstCaret = allCarets.get(0);
if (firstCaret == myCaretModel.getPrimaryCaret()) {
return allCarets.get(allCarets.size() - 1);
}
return firstCaret;
}
private void setSelectionAndBlockActions(@NotNull MouseEvent mouseDragEvent, int startOffset, int endOffset) {
mySelectionModel.setSelection(startOffset, endOffset);
if (myCurrentDragIsSubstantial || startOffset != endOffset) {
onSubstantialDrag(mouseDragEvent);
}
}
private void setSelectionAndBlockActions(@NotNull MouseEvent mouseDragEvent, VisualPosition startPosition, int startOffset, VisualPosition endPosition, int endOffset) {
mySelectionModel.setSelection(startPosition, startOffset, endPosition, endOffset);
if (myCurrentDragIsSubstantial || startOffset != endOffset || !Comparing.equal(startPosition, endPosition)) {
onSubstantialDrag(mouseDragEvent);
}
}
private void blockActionsIfNeeded(@NotNull MouseEvent mouseDragEvent, @NotNull LogicalPosition startPosition, @NotNull LogicalPosition endPosition) {
if (myCurrentDragIsSubstantial || !startPosition.equals(endPosition)) {
onSubstantialDrag(mouseDragEvent);
}
}
private void onSubstantialDrag(@NotNull MouseEvent mouseDragEvent) {
IdeEventQueue.getInstance().blockNextEvents(mouseDragEvent, IdeEventQueue.BlockMode.ACTIONS);
myCurrentDragIsSubstantial = true;
}
private static class RepaintCursorCommand implements Runnable {
private long mySleepTime = 500;
private boolean myIsBlinkCaret = true;
@Nullable private EditorImpl myEditor;
@NotNull private final MyRepaintRunnable myRepaintRunnable;
private ScheduledFuture<?> mySchedulerHandle;
private RepaintCursorCommand() {
myRepaintRunnable = new MyRepaintRunnable();
}
private class MyRepaintRunnable implements Runnable {
@Override
public void run() {
if (myEditor != null) {
myEditor.myCaretCursor.repaint();
}
}
}
public void start() {
if (mySchedulerHandle != null) {
mySchedulerHandle.cancel(false);
}
mySchedulerHandle = JobScheduler.getScheduler().scheduleWithFixedDelay(this, mySleepTime, mySleepTime, TimeUnit.MILLISECONDS);
}
private void setBlinkPeriod(int blinkPeriod) {
mySleepTime = blinkPeriod > 10 ? blinkPeriod : 10;
start();
}
private void setBlinkCaret(boolean value) {
myIsBlinkCaret = value;
}
@Override
public void run() {
if (myEditor != null) {
CaretCursor activeCursor = myEditor.myCaretCursor;
long time = System.currentTimeMillis();
time -= activeCursor.myStartTime;
if (time > mySleepTime) {
boolean toRepaint = true;
if (myIsBlinkCaret) {
activeCursor.myIsShown = !activeCursor.myIsShown;
}
else {
toRepaint = !activeCursor.myIsShown;
activeCursor.myIsShown = true;
}
if (toRepaint) {
SwingUtilities.invokeLater(myRepaintRunnable);
}
}
}
}
}
void updateCaretCursor() {
myUpdateCursor = true;
}
private void setCursorPosition() {
final List<CaretRectangle> caretPoints = new ArrayList<CaretRectangle>();
for (Caret caret : getCaretModel().getAllCarets()) {
boolean isRtl = caret.isAtRtlLocation();
VisualPosition caretPosition = caret.getVisualPosition();
Point pos1 = visualPositionToXY(caretPosition);
Point pos2 = visualPositionToXY(new VisualPosition(caretPosition.line, Math.max(0, caretPosition.column + (isRtl ? -1 : 1))));
caretPoints.add(new CaretRectangle(pos1, Math.abs(pos2.x - pos1.x), caret, isRtl));
}
myCaretCursor.setPositions(caretPoints.toArray(new CaretRectangle[caretPoints.size()]));
}
@Override
public boolean setCaretVisible(boolean b) {
boolean old = myCaretCursor.isActive();
if (b) {
myCaretCursor.activate();
}
else {
myCaretCursor.passivate();
}
return old;
}
@Override
public boolean setCaretEnabled(boolean enabled) {
boolean old = myCaretCursor.isEnabled();
myCaretCursor.setEnabled(enabled);
return old;
}
@Override
public void addFocusListener(@NotNull FocusChangeListener listener) {
myFocusListeners.add(listener);
}
@Override
public void addFocusListener(@NotNull FocusChangeListener listener, @NotNull Disposable parentDisposable) {
ContainerUtil.add(listener, myFocusListeners, parentDisposable);
}
@Override
@Nullable
public Project getProject() {
return myProject;
}
@Override
public boolean isOneLineMode() {
return myIsOneLineMode;
}
@Override
public boolean isEmbeddedIntoDialogWrapper() {
return myEmbeddedIntoDialogWrapper;
}
@Override
public void setEmbeddedIntoDialogWrapper(boolean b) {
assertIsDispatchThread();
myEmbeddedIntoDialogWrapper = b;
myScrollPane.setFocusable(!b);
myEditorComponent.setFocusCycleRoot(!b);
myEditorComponent.setFocusable(b);
}
@Override
public void setOneLineMode(boolean isOneLineMode) {
myIsOneLineMode = isOneLineMode;
getScrollPane().setInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null);
reinitSettings();
}
public static class CaretRectangle {
public final Point myPoint;
public final int myWidth;
public final Caret myCaret;
public final boolean myIsRtl;
private CaretRectangle(Point point, int width, Caret caret, boolean isRtl) {
myPoint = point;
myWidth = Math.max(width, 2);
myCaret = caret;
myIsRtl = isRtl;
}
}
private class CaretCursor {
private CaretRectangle[] myLocations;
private boolean myEnabled;
@SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized")
private boolean myIsShown;
private long myStartTime;
private CaretCursor() {
myLocations = new CaretRectangle[] {new CaretRectangle(new Point(0, 0), 0, null, false)};
setEnabled(true);
}
public boolean isEnabled() {
return myEnabled;
}
public void setEnabled(boolean enabled) {
myEnabled = enabled;
}
private void activate() {
final boolean blink = mySettings.isBlinkCaret();
final int blinkPeriod = mySettings.getCaretBlinkPeriod();
synchronized (ourCaretBlinkingCommand) {
ourCaretBlinkingCommand.myEditor = EditorImpl.this;
ourCaretBlinkingCommand.setBlinkCaret(blink);
ourCaretBlinkingCommand.setBlinkPeriod(blinkPeriod);
myIsShown = true;
}
}
public boolean isActive() {
synchronized (ourCaretBlinkingCommand) {
return myIsShown;
}
}
private void passivate() {
synchronized (ourCaretBlinkingCommand) {
myIsShown = false;
}
}
private void setPositions(CaretRectangle[] locations) {
myStartTime = System.currentTimeMillis();
myLocations = locations;
myIsShown = true;
if (!myUseNewRendering) {
repaint();
}
}
private void repaint() {
if (myUseNewRendering) {
myView.repaintCarets();
}
else {
for (CaretRectangle location : myLocations) {
myEditorComponent.repaintEditorComponent(location.myPoint.x, location.myPoint.y, location.myWidth, getLineHeight());
}
}
}
@Nullable
CaretRectangle[] getCaretLocations(boolean onlyIfShown) {
if (onlyIfShown && (!isEnabled() || !myIsShown || isRendererMode() || !IJSwingUtilities.hasFocus(getContentComponent()))) return null;
return myLocations;
}
private void paint(@NotNull Graphics g) {
CaretRectangle[] locations = getCaretLocations(true);
if (locations == null) return;
for (CaretRectangle location : myLocations) {
paintAt(g, location.myPoint.x, location.myPoint.y, location.myWidth, location.myCaret);
}
}
void paintAt(@NotNull Graphics g, int x, int y, int width, Caret caret) {
int lineHeight = getLineHeight();
Rectangle viewRectangle = getScrollingModel().getVisibleArea();
if (x - viewRectangle.x < 0) {
return;
}
g.setColor(myScheme.getColor(EditorColors.CARET_COLOR));
Graphics2D originalG = IdeBackgroundUtil.getOriginalGraphics(g);
if (!paintBlockCaret()) {
if (UIUtil.isRetina()) {
originalG.fillRect(x, y, mySettings.getLineCursorWidth(), lineHeight);
}
else {
g.fillRect(x, y, JBUI.scale(mySettings.getLineCursorWidth()), lineHeight);
}
}
else {
Color caretColor = myScheme.getColor(EditorColors.CARET_COLOR);
if (caretColor == null) caretColor = new JBColor(Gray._0, Gray._255);
g.setColor(caretColor);
originalG.fillRect(x, y, width, lineHeight - 1);
final LogicalPosition startPosition = caret == null ? getCaretModel().getLogicalPosition() : caret.getLogicalPosition();
final int offset = logicalPositionToOffset(startPosition);
CharSequence chars = myDocument.getImmutableCharSequence();
if (chars.length() > offset && myDocument.getTextLength() > offset) {
FoldRegion folding = myFoldingModel.getCollapsedRegionAtOffset(offset);
final char ch;
if (folding == null || folding.isExpanded()) {
ch = chars.charAt(offset);
}
else {
VisualPosition visual = caret == null ? getCaretModel().getVisualPosition() : caret.getVisualPosition();
VisualPosition foldingPosition = offsetToVisualPosition(folding.getStartOffset());
if (visual.line == foldingPosition.line) {
ch = folding.getPlaceholderText().charAt(visual.column - foldingPosition.column);
}
else {
ch = chars.charAt(offset);
}
}
//don't worry it's cheap. Cache is not required
IterationState state = new IterationState(EditorImpl.this, offset, offset + 1, true);
TextAttributes attributes = state.getMergedAttributes();
FontInfo info = EditorUtil.fontForChar(ch, attributes.getFontType(), EditorImpl.this);
g.setFont(info.getFont());
//todo[kb]
//in case of italic style we paint out of the cursor block. Painting the symbol to a dedicated buffered image
//solves the problem, but still looks weird because it leaves colored pixels at right.
g.setColor(ColorUtil.isDark(caretColor) ? CURSOR_FOREGROUND_LIGHT : CURSOR_FOREGROUND_DARK);
g.drawChars(new char[]{ch}, 0, 1, x, y + getAscent());
}
}
}
}
private boolean paintBlockCaret() {
return myIsInsertMode == mySettings.isBlockCursor();
}
private class ScrollingTimer {
private Timer myTimer;
private static final int TIMER_PERIOD = 100;
private static final int CYCLE_SIZE = 20;
private int myXCycles;
private int myYCycles;
private int myDx;
private int myDy;
private int xPassedCycles;
private int yPassedCycles;
private void start(int dx, int dy) {
myDx = 0;
myDy = 0;
if (dx > 0) {
myXCycles = CYCLE_SIZE / dx + 1;
myDx = 1 + dx / CYCLE_SIZE;
}
else {
if (dx < 0) {
myXCycles = -CYCLE_SIZE / dx + 1;
myDx = -1 + dx / CYCLE_SIZE;
}
}
if (dy > 0) {
myYCycles = CYCLE_SIZE / dy + 1;
myDy = 1 + dy / CYCLE_SIZE;
}
else {
if (dy < 0) {
myYCycles = -CYCLE_SIZE / dy + 1;
myDy = -1 + dy / CYCLE_SIZE;
}
}
if (myTimer != null) {
return;
}
myTimer = UIUtil.createNamedTimer("Editor scroll timer", TIMER_PERIOD, new ActionListener() {
@Override
public void actionPerformed(@NotNull ActionEvent e) {
myCommandProcessor.executeCommand(myProject, new DocumentRunnable(myDocument, myProject) {
@Override
public void run() {
// We experienced situation when particular editor was disposed but the timer was still on.
if (isDisposed()) {
myTimer.stop();
return;
}
int oldSelectionStart = mySelectionModel.getLeadSelectionOffset();
VisualPosition caretPosition = myMultiSelectionInProgress ? myTargetMultiSelectionPosition : getCaretModel().getVisualPosition();
int column = caretPosition.column;
xPassedCycles++;
if (xPassedCycles >= myXCycles) {
xPassedCycles = 0;
column += myDx;
}
int line = caretPosition.line;
yPassedCycles++;
if (yPassedCycles >= myYCycles) {
yPassedCycles = 0;
line += myDy;
}
line = Math.max(0, line);
column = Math.max(0, column);
VisualPosition pos = new VisualPosition(line, column);
if (!myMultiSelectionInProgress) {
getCaretModel().moveToVisualPosition(pos);
getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
}
int newCaretOffset = getCaretModel().getOffset();
int caretShift = newCaretOffset - mySavedSelectionStart;
if (getMouseSelectionState() != MOUSE_SELECTION_STATE_NONE) {
if (caretShift < 0) {
int newSelection = newCaretOffset;
if (getMouseSelectionState() == MOUSE_SELECTION_STATE_WORD_SELECTED) {
newSelection = myCaretModel.getWordAtCaretStart();
}
else {
if (getMouseSelectionState() == MOUSE_SELECTION_STATE_LINE_SELECTED) {
newSelection =
logicalPositionToOffset(visualToLogicalPosition(new VisualPosition(getCaretModel().getVisualPosition().line, 0)));
}
}
if (newSelection < 0) newSelection = newCaretOffset;
mySelectionModel.setSelection(validateOffset(mySavedSelectionEnd), newSelection);
getCaretModel().moveToOffset(newSelection);
}
else {
int newSelection = newCaretOffset;
if (getMouseSelectionState() == MOUSE_SELECTION_STATE_WORD_SELECTED) {
newSelection = myCaretModel.getWordAtCaretEnd();
}
else {
if (getMouseSelectionState() == MOUSE_SELECTION_STATE_LINE_SELECTED) {
newSelection = logicalPositionToOffset(
visualToLogicalPosition(new VisualPosition(getCaretModel().getVisualPosition().line + 1, 0)));
}
}
if (newSelection < 0) newSelection = newCaretOffset;
mySelectionModel.setSelection(validateOffset(mySavedSelectionStart), newSelection);
getCaretModel().moveToOffset(newSelection);
}
return;
}
if (myMultiSelectionInProgress && myLastMousePressedLocation != null) {
myTargetMultiSelectionPosition = pos;
LogicalPosition newLogicalPosition = visualToLogicalPosition(pos);
getScrollingModel().scrollTo(newLogicalPosition, ScrollType.RELATIVE);
createSelectionTill(newLogicalPosition);
}
else {
mySelectionModel.setSelection(oldSelectionStart, getCaretModel().getOffset());
}
}
}, EditorBundle.message("move.cursor.command.name"), DocCommandGroupId.noneGroupId(getDocument()), UndoConfirmationPolicy.DEFAULT,
getDocument());
}
});
myTimer.start();
}
private void stop() {
if (myTimer != null) {
myTimer.stop();
myTimer = null;
}
}
private int validateOffset(int offset) {
if (offset < 0) return 0;
if (offset > myDocument.getTextLength()) return myDocument.getTextLength();
return offset;
}
}
private static final Field decrButtonField = ReflectionUtil.getDeclaredField(BasicScrollBarUI.class, "decrButton");
private static final Field incrButtonField = ReflectionUtil.getDeclaredField(BasicScrollBarUI.class, "incrButton");
class MyScrollBar extends JBScrollBar implements IdeGlassPane.TopComponent {
@NonNls private static final String APPLE_LAF_AQUA_SCROLL_BAR_UI_CLASS = "apple.laf.AquaScrollBarUI";
private ScrollBarUI myPersistentUI;
private MyScrollBar(@JdkConstants.AdjustableOrientation int orientation) {
super(orientation);
}
void setPersistentUI(ScrollBarUI ui) {
myPersistentUI = ui;
setUI(ui);
}
@Override
public boolean canBePreprocessed(MouseEvent e) {
return JBScrollPane.canBePreprocessed(e, this);
}
@Override
public void setUI(ScrollBarUI ui) {
if (myPersistentUI == null) myPersistentUI = ui;
super.setUI(myPersistentUI);
setOpaque(false);
}
/**
* This is helper method. It returns height of the top (decrease) scroll bar
* button. Please note, that it's possible to return real height only if scroll bar
* is instance of BasicScrollBarUI. Otherwise it returns fake (but good enough :) )
* value.
*/
int getDecScrollButtonHeight() {
ScrollBarUI barUI = getUI();
Insets insets = getInsets();
int top = Math.max(0, insets.top);
if (barUI instanceof ButtonlessScrollBarUI) {
return top + ((ButtonlessScrollBarUI)barUI).getDecrementButtonHeight();
}
if (barUI instanceof BasicScrollBarUI) {
try {
JButton decrButtonValue = (JButton)decrButtonField.get(barUI);
LOG.assertTrue(decrButtonValue != null);
return top + decrButtonValue.getHeight();
}
catch (Exception exc) {
throw new IllegalStateException(exc);
}
}
return top + 15;
}
/**
* This is helper method. It returns height of the bottom (increase) scroll bar
* button. Please note, that it's possible to return real height only if scroll bar
* is instance of BasicScrollBarUI. Otherwise it returns fake (but good enough :) )
* value.
*/
int getIncScrollButtonHeight() {
ScrollBarUI barUI = getUI();
Insets insets = getInsets();
if (barUI instanceof ButtonlessScrollBarUI) {
return insets.top + ((ButtonlessScrollBarUI)barUI).getIncrementButtonHeight();
}
if (barUI instanceof BasicScrollBarUI) {
try {
JButton incrButtonValue = (JButton)incrButtonField.get(barUI);
LOG.assertTrue(incrButtonValue != null);
return insets.bottom + incrButtonValue.getHeight();
}
catch (Exception exc) {
throw new IllegalStateException(exc);
}
}
if (APPLE_LAF_AQUA_SCROLL_BAR_UI_CLASS.equals(barUI.getClass().getName())) {
return insets.bottom + 30;
}
return insets.bottom + 15;
}
@Override
public int getUnitIncrement(int direction) {
JViewport vp = myScrollPane.getViewport();
Rectangle vr = vp.getViewRect();
return myEditorComponent.getScrollableUnitIncrement(vr, SwingConstants.VERTICAL, direction);
}
@Override
public int getBlockIncrement(int direction) {
JViewport vp = myScrollPane.getViewport();
Rectangle vr = vp.getViewRect();
return myEditorComponent.getScrollableBlockIncrement(vr, SwingConstants.VERTICAL, direction);
}
private void registerRepaintCallback(@Nullable ButtonlessScrollBarUI.ScrollbarRepaintCallback callback) {
if (myPersistentUI instanceof ButtonlessScrollBarUI) {
((ButtonlessScrollBarUI)myPersistentUI).registerRepaintCallback(callback);
}
}
}
private MyEditable getViewer() {
if (myEditable == null) {
myEditable = new MyEditable();
}
return myEditable;
}
@Override
public CopyProvider getCopyProvider() {
return getViewer();
}
@Override
public CutProvider getCutProvider() {
return getViewer();
}
@Override
public PasteProvider getPasteProvider() {
return getViewer();
}
@Override
public DeleteProvider getDeleteProvider() {
return getViewer();
}
private class MyEditable implements CutProvider, CopyProvider, PasteProvider, DeleteProvider {
@Override
public void performCopy(@NotNull DataContext dataContext) {
executeAction(IdeActions.ACTION_EDITOR_COPY, dataContext);
}
@Override
public boolean isCopyEnabled(@NotNull DataContext dataContext) {
return true;
}
@Override
public boolean isCopyVisible(@NotNull DataContext dataContext) {
return getSelectionModel().hasSelection(true);
}
@Override
public void performCut(@NotNull DataContext dataContext) {
executeAction(IdeActions.ACTION_EDITOR_CUT, dataContext);
}
@Override
public boolean isCutEnabled(@NotNull DataContext dataContext) {
return !isViewer();
}
@Override
public boolean isCutVisible(@NotNull DataContext dataContext) {
return isCutEnabled(dataContext) && getSelectionModel().hasSelection(true);
}
@Override
public void performPaste(@NotNull DataContext dataContext) {
executeAction(IdeActions.ACTION_EDITOR_PASTE, dataContext);
}
@Override
public boolean isPastePossible(@NotNull DataContext dataContext) {
// Copy of isPasteEnabled. See interface method javadoc.
return !isViewer();
}
@Override
public boolean isPasteEnabled(@NotNull DataContext dataContext) {
return !isViewer();
}
@Override
public void deleteElement(@NotNull DataContext dataContext) {
executeAction(IdeActions.ACTION_EDITOR_DELETE, dataContext);
}
@Override
public boolean canDeleteElement(@NotNull DataContext dataContext) {
return !isViewer();
}
private void executeAction(@NotNull String actionId, @NotNull DataContext dataContext) {
EditorAction action = (EditorAction)ActionManager.getInstance().getAction(actionId);
if (action != null) {
action.actionPerformed(EditorImpl.this, dataContext);
}
}
}
@Override
public void setColorsScheme(@NotNull EditorColorsScheme scheme) {
assertIsDispatchThread();
myScheme = scheme;
reinitSettings();
}
@Override
@NotNull
public EditorColorsScheme getColorsScheme() {
return myScheme;
}
static void assertIsDispatchThread() {
ApplicationManager.getApplication().assertIsDispatchThread();
}
private static void assertReadAccess() {
ApplicationManager.getApplication().assertReadAccessAllowed();
}
@Override
public void setVerticalScrollbarOrientation(int type) {
assertIsDispatchThread();
int currentHorOffset = myScrollingModel.getHorizontalScrollOffset();
myScrollBarOrientation = type;
if (type == VERTICAL_SCROLLBAR_LEFT) {
myScrollPane.setLayout(new LeftHandScrollbarLayout());
}
else {
myScrollPane.setLayout(new ScrollPaneLayout());
}
myScrollingModel.scrollHorizontally(currentHorOffset);
}
@Override
public void setVerticalScrollbarVisible(boolean b) {
myScrollPane
.setVerticalScrollBarPolicy(b ? ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS : ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
}
@Override
public void setHorizontalScrollbarVisible(boolean b) {
myScrollPane.setHorizontalScrollBarPolicy(
b ? ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED : ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
}
@Override
public int getVerticalScrollbarOrientation() {
return myScrollBarOrientation;
}
public boolean isMirrored() {
return myScrollBarOrientation != EditorEx.VERTICAL_SCROLLBAR_RIGHT;
}
@NotNull
MyScrollBar getVerticalScrollBar() {
return myVerticalScrollBar;
}
@NotNull
MyScrollBar getHorizontalScrollBar() {
return (MyScrollBar)myScrollPane.getHorizontalScrollBar();
}
@MouseSelectionState
private int getMouseSelectionState() {
return myMouseSelectionState;
}
private void setMouseSelectionState(@MouseSelectionState int mouseSelectionState) {
if (getMouseSelectionState() == mouseSelectionState) return;
myMouseSelectionState = mouseSelectionState;
myMouseSelectionChangeTimestamp = System.currentTimeMillis();
myMouseSelectionStateAlarm.cancelAllRequests();
if (myMouseSelectionState != MOUSE_SELECTION_STATE_NONE) {
if (myMouseSelectionStateResetRunnable == null) {
myMouseSelectionStateResetRunnable = new Runnable() {
@Override
public void run() {
resetMouseSelectionState(null);
}
};
}
myMouseSelectionStateAlarm.addRequest(myMouseSelectionStateResetRunnable, Registry.intValue("editor.mouseSelectionStateResetTimeout"),
ModalityState.stateForComponent(myEditorComponent));
}
}
private void resetMouseSelectionState(@Nullable MouseEvent event) {
setMouseSelectionState(MOUSE_SELECTION_STATE_NONE);
MouseEvent e = event != null ? event : myMouseMovedEvent;
if (e != null) {
validateMousePointer(e);
}
}
private void cancelAutoResetForMouseSelectionState() {
myMouseSelectionStateAlarm.cancelAllRequests();
}
void replaceInputMethodText(@NotNull InputMethodEvent e) {
getInputMethodRequests();
myInputMethodRequestsHandler.replaceInputMethodText(e);
}
void inputMethodCaretPositionChanged(@NotNull InputMethodEvent e) {
getInputMethodRequests();
myInputMethodRequestsHandler.setInputMethodCaretPosition(e);
}
@NotNull
InputMethodRequests getInputMethodRequests() {
if (myInputMethodRequestsHandler == null) {
myInputMethodRequestsHandler = new MyInputMethodHandler();
myInputMethodRequestsSwingWrapper = new MyInputMethodHandleSwingThreadWrapper(myInputMethodRequestsHandler);
}
return myInputMethodRequestsSwingWrapper;
}
@Override
public boolean processKeyTyped(@NotNull KeyEvent e) {
if (e.getID() != KeyEvent.KEY_TYPED) return false;
char c = e.getKeyChar();
if (UIUtil.isReallyTypedEvent(e)) { // Hack just like in javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction
processKeyTyped(c);
return true;
}
else {
return false;
}
}
void beforeModalityStateChanged() {
myScrollingModel.beforeModalityStateChanged();
}
public EditorDropHandler getDropHandler() {
return myDropHandler;
}
public void setDropHandler(@NotNull EditorDropHandler dropHandler) {
myDropHandler = dropHandler;
}
private static class MyInputMethodHandleSwingThreadWrapper implements InputMethodRequests {
private final InputMethodRequests myDelegate;
private MyInputMethodHandleSwingThreadWrapper(InputMethodRequests delegate) {
myDelegate = delegate;
}
@NotNull
@Override
public Rectangle getTextLocation(final TextHitInfo offset) {
return execute(new Computable<Rectangle>() {
@Override
public Rectangle compute() {
return myDelegate.getTextLocation(offset);
}
});
}
@Override
public TextHitInfo getLocationOffset(final int x, final int y) {
return execute(new Computable<TextHitInfo>() {
@Override
public TextHitInfo compute() {
return myDelegate.getLocationOffset(x, y);
}
});
}
@Override
public int getInsertPositionOffset() {
return execute(new Computable<Integer>() {
@Override
public Integer compute() {
return myDelegate.getInsertPositionOffset();
}
});
}
@NotNull
@Override
public AttributedCharacterIterator getCommittedText(final int beginIndex, final int endIndex,
final AttributedCharacterIterator.Attribute[] attributes) {
return execute(new Computable<AttributedCharacterIterator>() {
@Override
public AttributedCharacterIterator compute() {
return myDelegate.getCommittedText(beginIndex, endIndex, attributes);
}
});
}
@Override
public int getCommittedTextLength() {
return execute(new Computable<Integer>() {
@Override
public Integer compute() {
return myDelegate.getCommittedTextLength();
}
});
}
@Override
@Nullable
public AttributedCharacterIterator cancelLatestCommittedText(AttributedCharacterIterator.Attribute[] attributes) {
return null;
}
@Override
public AttributedCharacterIterator getSelectedText(final AttributedCharacterIterator.Attribute[] attributes) {
return execute(new Computable<AttributedCharacterIterator>() {
@Override
public AttributedCharacterIterator compute() {
return myDelegate.getSelectedText(attributes);
}
});
}
private static <T> T execute(final Computable<T> computable) {
return UIUtil.invokeAndWaitIfNeeded(computable);
}
}
private class MyInputMethodHandler implements InputMethodRequests {
private String composedText;
private ProperTextRange composedTextRange;
@NotNull
@Override
public Rectangle getTextLocation(TextHitInfo offset) {
Point caret = logicalPositionToXY(getCaretModel().getLogicalPosition());
Rectangle r = new Rectangle(caret, new Dimension(1, getLineHeight()));
Point p = getContentComponent().getLocationOnScreen();
r.translate(p.x, p.y);
return r;
}
@Override
@Nullable
public TextHitInfo getLocationOffset(int x, int y) {
if (composedText != null) {
Point p = getContentComponent().getLocationOnScreen();
p.x = x - p.x;
p.y = y - p.y;
int pos = logicalPositionToOffset(xyToLogicalPosition(p));
if (composedTextRange.containsOffset(pos)) {
return TextHitInfo.leading(pos - composedTextRange.getStartOffset());
}
}
return null;
}
@Override
public int getInsertPositionOffset() {
int composedStartIndex = 0;
int composedEndIndex = 0;
if (composedText != null) {
composedStartIndex = composedTextRange.getStartOffset();
composedEndIndex = composedTextRange.getEndOffset();
}
int caretIndex = getCaretModel().getOffset();
if (caretIndex < composedStartIndex) {
return caretIndex;
}
if (caretIndex < composedEndIndex) {
return composedStartIndex;
}
return caretIndex - (composedEndIndex - composedStartIndex);
}
private String getText(int startIdx, int endIdx) {
if (startIdx >= 0 && endIdx > startIdx) {
CharSequence chars = getDocument().getImmutableCharSequence();
return chars.subSequence(startIdx, endIdx).toString();
}
return "";
}
@NotNull
@Override
public AttributedCharacterIterator getCommittedText(int beginIndex, int endIndex, AttributedCharacterIterator.Attribute[] attributes) {
int composedStartIndex = 0;
int composedEndIndex = 0;
if (composedText != null) {
composedStartIndex = composedTextRange.getStartOffset();
composedEndIndex = composedTextRange.getEndOffset();
}
String committed;
if (beginIndex < composedStartIndex) {
if (endIndex <= composedStartIndex) {
committed = getText(beginIndex, endIndex - beginIndex);
}
else {
int firstPartLength = composedStartIndex - beginIndex;
committed = getText(beginIndex, firstPartLength) + getText(composedEndIndex, endIndex - beginIndex - firstPartLength);
}
}
else {
committed = getText(beginIndex + composedEndIndex - composedStartIndex, endIndex - beginIndex);
}
return new AttributedString(committed).getIterator();
}
@Override
public int getCommittedTextLength() {
int length = getDocument().getTextLength();
if (composedText != null) {
length -= composedText.length();
}
return length;
}
@Override
@Nullable
public AttributedCharacterIterator cancelLatestCommittedText(AttributedCharacterIterator.Attribute[] attributes) {
return null;
}
@Override
@Nullable
public AttributedCharacterIterator getSelectedText(AttributedCharacterIterator.Attribute[] attributes) {
if (myCharKeyPressed) {
myNeedToSelectPreviousChar = true;
}
String text = getSelectionModel().getSelectedText();
return text == null ? null : new AttributedString(text).getIterator();
}
private void createComposedString(int composedIndex, @NotNull AttributedCharacterIterator text) {
StringBuffer strBuf = new StringBuffer();
// create attributed string with no attributes
for (char c = text.setIndex(composedIndex); c != CharacterIterator.DONE; c = text.next()) {
strBuf.append(c);
}
composedText = new String(strBuf);
}
private void setInputMethodCaretPosition(@NotNull InputMethodEvent e) {
if (composedText != null) {
int dot = composedTextRange.getStartOffset();
TextHitInfo caretPos = e.getCaret();
if (caretPos != null) {
dot += caretPos.getInsertionIndex();
}
getCaretModel().moveToOffset(dot);
getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
}
}
private void runUndoTransparent(@NotNull final Runnable runnable) {
CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() {
@Override
public void run() {
CommandProcessor.getInstance().executeCommand(myProject, new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(runnable);
}
}, "", getDocument(), UndoConfirmationPolicy.DEFAULT, getDocument());
}
});
}
private void replaceInputMethodText(@NotNull InputMethodEvent e) {
if (myNeedToSelectPreviousChar && SystemInfo.isMac &&
(Registry.is("ide.mac.pressAndHold.brute.workaround") || Registry.is("ide.mac.pressAndHold.workaround") &&
(e.getCommittedCharacterCount() > 0 || e.getCaret() == null))) {
// This is required to support input of accented characters using press-and-hold method (http://support.apple.com/kb/PH11264).
// JDK currently properly supports this functionality only for TextComponent/JTextComponent descendants.
// For our editor component we need this workaround.
// After https://bugs.openjdk.java.net/browse/JDK-8074882 is fixed, this workaround should be replaced with a proper solution.
myNeedToSelectPreviousChar = false;
getCaretModel().runForEachCaret(new CaretAction() {
@Override
public void perform(Caret caret) {
int caretOffset = caret.getOffset();
if (caretOffset > 0) {
caret.setSelection(caretOffset - 1, caretOffset);
}
}
});
}
int commitCount = e.getCommittedCharacterCount();
AttributedCharacterIterator text = e.getText();
// old composed text deletion
final Document doc = getDocument();
if (composedText != null) {
if (!isViewer() && doc.isWritable()) {
runUndoTransparent(new Runnable() {
@Override
public void run() {
int docLength = doc.getTextLength();
ProperTextRange range = composedTextRange.intersection(new TextRange(0, docLength));
if (range != null) {
doc.deleteString(range.getStartOffset(), range.getEndOffset());
}
}
});
}
composedText = null;
}
if (text != null) {
text.first();
// committed text insertion
if (commitCount > 0) {
//noinspection ForLoopThatDoesntUseLoopVariable
for (char c = text.current(); commitCount > 0; c = text.next(), commitCount--) {
if (c >= 0x20 && c != 0x7F) { // Hack just like in javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction
processKeyTyped(c);
}
}
}
// new composed text insertion
if (!isViewer() && doc.isWritable()) {
int composedTextIndex = text.getIndex();
if (composedTextIndex < text.getEndIndex()) {
createComposedString(composedTextIndex, text);
runUndoTransparent(new Runnable() {
@Override
public void run() {
EditorModificationUtil.insertStringAtCaret(EditorImpl.this, composedText, false, false);
}
});
composedTextRange = ProperTextRange.from(getCaretModel().getOffset(), composedText.length());
}
}
}
}
}
private class MyMouseAdapter extends MouseAdapter {
private boolean mySelectionTweaked;
@Override
public void mousePressed(@NotNull MouseEvent e) {
requestFocus();
runMousePressedCommand(e);
}
@Override
public void mouseReleased(@NotNull MouseEvent e) {
myMousePressArea = null;
runMouseReleasedCommand(e);
if (!e.isConsumed() && myMousePressedEvent != null && !myMousePressedEvent.isConsumed() &&
Math.abs(e.getX() - myMousePressedEvent.getX()) < EditorUtil.getSpaceWidth(Font.PLAIN, EditorImpl.this) &&
Math.abs(e.getY() - myMousePressedEvent.getY()) < getLineHeight()) {
runMouseClickedCommand(e);
}
}
@Override
public void mouseEntered(@NotNull MouseEvent e) {
runMouseEnteredCommand(e);
}
@Override
public void mouseExited(@NotNull MouseEvent e) {
runMouseExitedCommand(e);
EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e));
if (event.getArea() == EditorMouseEventArea.LINE_MARKERS_AREA) {
myGutterComponent.mouseExited(e);
}
TooltipController.getInstance().cancelTooltip(FOLDING_TOOLTIP_GROUP, e, true);
}
private void runMousePressedCommand(@NotNull final MouseEvent e) {
myLastMousePressedLocation = xyToLogicalPosition(e.getPoint());
myCaretStateBeforeLastPress = isToggleCaretEvent(e) ? myCaretModel.getCaretsAndSelections() : Collections.<CaretState>emptyList();
myCurrentDragIsSubstantial = false;
clearDraggedRange();
mySelectionTweaked = false;
myMousePressedEvent = e;
EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e));
myExpectedCaretOffset = logicalPositionToOffset(myLastMousePressedLocation);
try {
for (EditorMouseListener mouseListener : myMouseListeners) {
mouseListener.mousePressed(event);
}
}
finally {
myExpectedCaretOffset = -1;
}
if (event.getArea() == EditorMouseEventArea.LINE_MARKERS_AREA) {
myDragOnGutterSelectionStartLine = EditorUtil.yPositionToLogicalLine(EditorImpl.this, e);
}
// On some systems (for example on Linux) popup trigger is MOUSE_PRESSED event.
// But this trigger is always consumed by popup handler. In that case we have to
// also move caret.
if (event.isConsumed() && !(event.getMouseEvent().isPopupTrigger() || event.getArea() == EditorMouseEventArea.EDITING_AREA)) {
return;
}
if (myCommandProcessor != null) {
Runnable runnable = new Runnable() {
@Override
public void run() {
if (processMousePressed(e) && myProject != null && !myProject.isDefault()) {
IdeDocumentHistory.getInstance(myProject).includeCurrentCommandAsNavigation();
}
}
};
myCommandProcessor
.executeCommand(myProject, runnable, "", DocCommandGroupId.noneGroupId(getDocument()), UndoConfirmationPolicy.DEFAULT,
getDocument());
}
else {
processMousePressed(e);
}
}
private void runMouseClickedCommand(@NotNull final MouseEvent e) {
EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e));
for (EditorMouseListener listener : myMouseListeners) {
listener.mouseClicked(event);
if (event.isConsumed()) {
e.consume();
return;
}
}
}
private void runMouseReleasedCommand(@NotNull final MouseEvent e) {
myMultiSelectionInProgress = false;
myDragOnGutterSelectionStartLine = -1;
if (!mySelectionTweaked) {
tweakSelectionIfNecessary(e);
}
if (e.isConsumed()) {
return;
}
myScrollingTimer.stop();
EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e));
for (EditorMouseListener listener : myMouseListeners) {
listener.mouseReleased(event);
if (event.isConsumed()) {
e.consume();
return;
}
}
if (myCommandProcessor != null) {
Runnable runnable = new Runnable() {
@Override
public void run() {
processMouseReleased(e);
}
};
myCommandProcessor
.executeCommand(myProject, runnable, "", DocCommandGroupId.noneGroupId(getDocument()), UndoConfirmationPolicy.DEFAULT,
getDocument());
}
else {
processMouseReleased(e);
}
}
private void runMouseEnteredCommand(@NotNull MouseEvent e) {
EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e));
for (EditorMouseListener listener : myMouseListeners) {
listener.mouseEntered(event);
if (event.isConsumed()) {
e.consume();
return;
}
}
}
private void runMouseExitedCommand(@NotNull MouseEvent e) {
EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e));
for (EditorMouseListener listener : myMouseListeners) {
listener.mouseExited(event);
if (event.isConsumed()) {
e.consume();
return;
}
}
}
private boolean processMousePressed(@NotNull final MouseEvent e) {
myInitialMouseEvent = e;
if (myMouseSelectionState != MOUSE_SELECTION_STATE_NONE &&
System.currentTimeMillis() - myMouseSelectionChangeTimestamp > Registry.intValue(
"editor.mouseSelectionStateResetTimeout")) {
resetMouseSelectionState(e);
}
int x = e.getX();
int y = e.getY();
if (x < 0) x = 0;
if (y < 0) y = 0;
final EditorMouseEventArea eventArea = getMouseEventArea(e);
myMousePressArea = eventArea;
if (eventArea == EditorMouseEventArea.FOLDING_OUTLINE_AREA) {
final FoldRegion range = myGutterComponent.findFoldingAnchorAt(x, y);
if (range != null) {
final boolean expansion = !range.isExpanded();
int scrollShift = y - getScrollingModel().getVerticalScrollOffset();
Runnable processor = new Runnable() {
@Override
public void run() {
myFoldingModel.flushCaretShift();
range.setExpanded(expansion);
if (e.isAltDown()) {
for (FoldRegion region : myFoldingModel.getAllFoldRegions()) {
if (region.getStartOffset() >= range.getStartOffset() && region.getEndOffset() <= range.getEndOffset()) {
region.setExpanded(expansion);
}
}
}
}
};
getFoldingModel().runBatchFoldingOperation(processor);
y = myGutterComponent.getHeadCenterY(range);
getScrollingModel().scrollVertically(y - scrollShift);
myGutterComponent.updateSize();
validateMousePointer(e);
e.consume();
return false;
}
}
if (e.getSource() == myGutterComponent) {
if (eventArea == EditorMouseEventArea.LINE_MARKERS_AREA ||
eventArea == EditorMouseEventArea.ANNOTATIONS_AREA ||
eventArea == EditorMouseEventArea.LINE_NUMBERS_AREA) {
if (tweakSelectionIfNecessary(e)) {
mySelectionTweaked = true;
}
else {
myGutterComponent.mousePressed(e);
}
if (e.isConsumed()) return false;
}
x = 0;
}
int oldSelectionStart = mySelectionModel.getLeadSelectionOffset();
final int oldStart = mySelectionModel.getSelectionStart();
final int oldEnd = mySelectionModel.getSelectionEnd();
boolean toggleCaret = e.getSource() != myGutterComponent && isToggleCaretEvent(e);
boolean lastPressCreatedCaret = myLastPressCreatedCaret;
if (e.getClickCount() == 1) {
myLastPressCreatedCaret = false;
}
// Don't move caret on mouse press above gutter line markers area (a place where break points, 'override', 'implements' etc icons
// are drawn) and annotations area. E.g. we don't want to change caret position if a user sets new break point (clicks
// at 'line markers' area).
if (e.getSource() != myGutterComponent ||
eventArea != EditorMouseEventArea.LINE_MARKERS_AREA && eventArea != EditorMouseEventArea.ANNOTATIONS_AREA)
{
VisualPosition visualPosition = myUseNewRendering ? getTargetPosition(x, y, true) : null;
LogicalPosition pos = myUseNewRendering ? visualToLogicalPosition(visualPosition) : getLogicalPositionForScreenPos(x, y, true);
if (toggleCaret) {
if (!myUseNewRendering) {
visualPosition = logicalToVisualPosition(pos);
}
Caret caret = getCaretModel().getCaretAt(visualPosition);
if (e.getClickCount() == 1) {
if (caret == null) {
myLastPressCreatedCaret = getCaretModel().addCaret(visualPosition) != null;
}
else {
getCaretModel().removeCaret(caret);
}
}
else if (e.getClickCount() == 3 && lastPressCreatedCaret) {
if (myUseNewRendering) {
getCaretModel().moveToVisualPosition(visualPosition);
}
else {
getCaretModel().moveToLogicalPosition(pos);
}
}
}
else if (myCaretModel.supportsMultipleCarets() && e.getSource() != myGutterComponent && isCreateRectangularSelectionEvent(e)) {
mySelectionModel.setBlockSelection(myCaretModel.getLogicalPosition(), pos);
}
else {
getCaretModel().removeSecondaryCarets();
if (myUseNewRendering) {
getCaretModel().moveToVisualPosition(visualPosition);
}
else {
getCaretModel().moveToLogicalPosition(pos);
}
}
}
if (e.isPopupTrigger()) return false;
requestFocus();
int caretOffset = getCaretModel().getOffset();
int newStart = mySelectionModel.getSelectionStart();
int newEnd = mySelectionModel.getSelectionEnd();
boolean isNavigation = oldStart == oldEnd && newStart == newEnd && oldStart != newStart;
myMouseSelectedRegion = myFoldingModel.getFoldingPlaceholderAt(new Point(x, y));
myMousePressedInsideSelection = mySelectionModel.hasSelection() && caretOffset >= mySelectionModel.getSelectionStart() &&
caretOffset <= mySelectionModel.getSelectionEnd();
if (getMouseEventArea(e) == EditorMouseEventArea.LINE_NUMBERS_AREA && e.getClickCount() == 1) {
mySelectionModel.selectLineAtCaret();
setMouseSelectionState(MOUSE_SELECTION_STATE_LINE_SELECTED);
mySavedSelectionStart = mySelectionModel.getSelectionStart();
mySavedSelectionEnd = mySelectionModel.getSelectionEnd();
return isNavigation;
}
if (e.isShiftDown() && !e.isControlDown() && !e.isAltDown()) {
if (getMouseSelectionState() != MOUSE_SELECTION_STATE_NONE) {
if (caretOffset < mySavedSelectionStart) {
mySelectionModel.setSelection(mySavedSelectionEnd, caretOffset);
}
else {
mySelectionModel.setSelection(mySavedSelectionStart, caretOffset);
}
}
else {
int startToUse = oldSelectionStart;
if (mySelectionModel.isUnknownDirection() && caretOffset > startToUse) {
startToUse = Math.min(oldStart, oldEnd);
}
mySelectionModel.setSelection(startToUse, caretOffset);
}
}
else {
if (!myMousePressedInsideSelection && getSelectionModel().hasSelection()) {
setMouseSelectionState(MOUSE_SELECTION_STATE_NONE);
mySelectionModel.setSelection(caretOffset, caretOffset);
}
else {
if (!e.isPopupTrigger()
&& (eventArea == EditorMouseEventArea.EDITING_AREA || eventArea == EditorMouseEventArea.LINE_NUMBERS_AREA)
&& (!toggleCaret || lastPressCreatedCaret))
{
switch (e.getClickCount()) {
case 2:
selectWordAtCaret(mySettings.isMouseClickSelectionHonorsCamelWords() && mySettings.isCamelWords());
break;
case 3:
if (HONOR_CAMEL_HUMPS_ON_TRIPLE_CLICK && mySettings.isCamelWords()) {
// We want to differentiate between triple and quadruple clicks when 'select by camel humps' is on. The former
// is assumed to select 'hump' while the later points to the whole word.
selectWordAtCaret(false);
break;
}
//noinspection fallthrough
case 4:
mySelectionModel.selectLineAtCaret();
setMouseSelectionState(MOUSE_SELECTION_STATE_LINE_SELECTED);
mySavedSelectionStart = mySelectionModel.getSelectionStart();
mySavedSelectionEnd = mySelectionModel.getSelectionEnd();
mySelectionModel.setUnknownDirection(true);
break;
}
}
}
}
return isNavigation;
}
}
private static boolean isColumnSelectionDragEvent(@NotNull MouseEvent e) {
return e.isAltDown() && !e.isShiftDown() && !e.isControlDown() && !e.isMetaDown();
}
private static boolean isToggleCaretEvent(@NotNull MouseEvent e) {
return KeymapUtil.isMouseActionEvent(e, IdeActions.ACTION_EDITOR_ADD_OR_REMOVE_CARET) || isAddRectangularSelectionEvent(e);
}
private static boolean isAddRectangularSelectionEvent(@NotNull MouseEvent e) {
return KeymapUtil.isMouseActionEvent(e, IdeActions.ACTION_EDITOR_ADD_RECTANGULAR_SELECTION_ON_MOUSE_DRAG);
}
private static boolean isCreateRectangularSelectionEvent(@NotNull MouseEvent e) {
return KeymapUtil.isMouseActionEvent(e, IdeActions.ACTION_EDITOR_CREATE_RECTANGULAR_SELECTION);
}
private void selectWordAtCaret(boolean honorCamelCase) {
mySelectionModel.selectWordAtCaret(honorCamelCase);
setMouseSelectionState(MOUSE_SELECTION_STATE_WORD_SELECTED);
mySavedSelectionStart = mySelectionModel.getSelectionStart();
mySavedSelectionEnd = mySelectionModel.getSelectionEnd();
getCaretModel().moveToOffset(mySavedSelectionEnd);
}
/**
* Allows to answer if given event should tweak editor selection.
*
* @param e event for occurred mouse action
* @return <code>true</code> if action that produces given event will trigger editor selection change; <code>false</code> otherwise
*/
private boolean tweakSelectionEvent(@NotNull MouseEvent e) {
return getSelectionModel().hasSelection() && e.getButton() == MouseEvent.BUTTON1 && e.isShiftDown()
&& getMouseEventArea(e) == EditorMouseEventArea.LINE_NUMBERS_AREA;
}
/**
* Checks if editor selection should be changed because of click at the given point at gutter and proceeds if necessary.
* <p/>
* The main idea is that selection can be changed during left mouse clicks on the gutter line numbers area with hold
* <code>Shift</code> button. The selection should be adjusted if necessary.
*
* @param e event for mouse click on gutter area
* @return <code>true</code> if editor's selection is changed because of the click; <code>false</code> otherwise
*/
private boolean tweakSelectionIfNecessary(@NotNull MouseEvent e) {
if (!tweakSelectionEvent(e)) {
return false;
}
int startSelectionOffset = getSelectionModel().getSelectionStart();
int startVisLine = offsetToVisualLine(startSelectionOffset);
int endSelectionOffset = getSelectionModel().getSelectionEnd();
int endVisLine = offsetToVisualLine(endSelectionOffset - 1);
int clickVisLine = yPositionToVisibleLine(e.getPoint().y);
if (clickVisLine < startVisLine) {
// Expand selection at backward direction.
int startOffset = logicalPositionToOffset(visualToLogicalPosition(new VisualPosition(clickVisLine, 0)));
getSelectionModel().setSelection(startOffset, endSelectionOffset);
getCaretModel().moveToOffset(startOffset);
}
else if (clickVisLine > endVisLine) {
// Expand selection at forward direction.
int endLineOffset = EditorUtil.getVisualLineEndOffset(this, clickVisLine);
getSelectionModel().setSelection(getSelectionModel().getSelectionStart(), endLineOffset);
getCaretModel().moveToOffset(endLineOffset, true);
}
else if (startVisLine == endVisLine) {
// Remove selection
getSelectionModel().removeSelection();
}
else {
// Reduce selection in backward direction.
if (getSelectionModel().getLeadSelectionOffset() == endSelectionOffset) {
if (clickVisLine == startVisLine) {
clickVisLine++;
}
int startOffset = logicalPositionToOffset(visualToLogicalPosition(new VisualPosition(clickVisLine, 0)));
getSelectionModel().setSelection(startOffset, endSelectionOffset);
getCaretModel().moveToOffset(startOffset);
}
else {
// Reduce selection is forward direction.
if (clickVisLine == endVisLine) {
clickVisLine--;
}
int endLineOffset = EditorUtil.getVisualLineEndOffset(this, clickVisLine);
getSelectionModel().setSelection(startSelectionOffset, endLineOffset);
getCaretModel().moveToOffset(endLineOffset);
}
}
e.consume();
return true;
}
private static final TooltipGroup FOLDING_TOOLTIP_GROUP = new TooltipGroup("FOLDING_TOOLTIP_GROUP", 10);
private class MyMouseMotionListener implements MouseMotionListener {
@Override
public void mouseDragged(@NotNull MouseEvent e) {
validateMousePointer(e);
runMouseDraggedCommand(e);
EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e));
if (event.getArea() == EditorMouseEventArea.LINE_MARKERS_AREA) {
myGutterComponent.mouseDragged(e);
}
for (EditorMouseMotionListener listener : myMouseMotionListeners) {
listener.mouseDragged(event);
}
}
@Override
public void mouseMoved(@NotNull MouseEvent e) {
if (getMouseSelectionState() != MOUSE_SELECTION_STATE_NONE) {
if (myMousePressedEvent != null && myMousePressedEvent.getComponent() == e.getComponent()) {
Point lastPoint = myMousePressedEvent.getPoint();
Point point = e.getPoint();
int deadZone = Registry.intValue("editor.mouseSelectionStateResetDeadZone");
if (Math.abs(lastPoint.x - point.x) >= deadZone || Math.abs(lastPoint.y - point.y) >= deadZone) {
resetMouseSelectionState(e);
}
}
else {
validateMousePointer(e);
}
}
else {
validateMousePointer(e);
}
myMouseMovedEvent = e;
EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e));
if (e.getSource() == myGutterComponent) {
myGutterComponent.mouseMoved(e);
}
if (event.getArea() == EditorMouseEventArea.EDITING_AREA) {
FoldRegion fold = myFoldingModel.getFoldingPlaceholderAt(e.getPoint());
TooltipController controller = TooltipController.getInstance();
if (fold != null && !fold.shouldNeverExpand()) {
DocumentFragment range = createDocumentFragment(fold);
final Point p =
SwingUtilities.convertPoint((Component)e.getSource(), e.getPoint(), getComponent().getRootPane().getLayeredPane());
controller.showTooltip(EditorImpl.this, p, new DocumentFragmentTooltipRenderer(range), false, FOLDING_TOOLTIP_GROUP);
}
else {
controller.cancelTooltip(FOLDING_TOOLTIP_GROUP, e, true);
}
}
for (EditorMouseMotionListener listener : myMouseMotionListeners) {
listener.mouseMoved(event);
}
}
@NotNull
private DocumentFragment createDocumentFragment(@NotNull FoldRegion fold) {
final FoldingGroup group = fold.getGroup();
final int foldStart = fold.getStartOffset();
if (group != null) {
final int endOffset = myFoldingModel.getEndOffset(group);
if (offsetToVisualLine(endOffset) == offsetToVisualLine(foldStart)) {
return new DocumentFragment(myDocument, foldStart, endOffset);
}
}
final int oldEnd = fold.getEndOffset();
return new DocumentFragment(myDocument, foldStart, oldEnd);
}
}
private class MyColorSchemeDelegate extends DelegateColorScheme {
private final FontPreferences myFontPreferences = new FontPreferences();
private final FontPreferences myConsoleFontPreferences = new FontPreferences();
private final Map<TextAttributesKey, TextAttributes> myOwnAttributes = ContainerUtilRt.newHashMap();
private final Map<ColorKey, Color> myOwnColors = ContainerUtilRt.newHashMap();
private final EditorColorsScheme myCustomGlobalScheme;
private Map<EditorFontType, Font> myFontsMap;
private int myMaxFontSize = OptionsConstants.MAX_EDITOR_FONT_SIZE;
private int myFontSize = -1;
private int myConsoleFontSize = -1;
private String myFaceName;
private MyColorSchemeDelegate(@Nullable EditorColorsScheme globalScheme) {
super(globalScheme == null ? EditorColorsManager.getInstance().getGlobalScheme() : globalScheme);
myCustomGlobalScheme = globalScheme;
updateGlobalScheme();
}
private void reinitFonts() {
EditorColorsScheme delegate = getDelegate();
String editorFontName = getEditorFontName();
int editorFontSize = getEditorFontSize();
updatePreferences(myFontPreferences, editorFontName, editorFontSize,
delegate == null ? null : delegate.getFontPreferences());
String consoleFontName = getConsoleFontName();
int consoleFontSize = getConsoleFontSize();
updatePreferences(myConsoleFontPreferences, consoleFontName, consoleFontSize,
delegate == null ? null : delegate.getConsoleFontPreferences());
myFontsMap = new EnumMap<EditorFontType, Font>(EditorFontType.class);
myFontsMap.put(EditorFontType.PLAIN, new Font(editorFontName, Font.PLAIN, editorFontSize));
myFontsMap.put(EditorFontType.BOLD, new Font(editorFontName, Font.BOLD, editorFontSize));
myFontsMap.put(EditorFontType.ITALIC, new Font(editorFontName, Font.ITALIC, editorFontSize));
myFontsMap.put(EditorFontType.BOLD_ITALIC, new Font(editorFontName, Font.BOLD | Font.ITALIC, editorFontSize));
myFontsMap.put(EditorFontType.CONSOLE_PLAIN, new Font(consoleFontName, Font.PLAIN, consoleFontSize));
myFontsMap.put(EditorFontType.CONSOLE_BOLD, new Font(consoleFontName, Font.BOLD, consoleFontSize));
myFontsMap.put(EditorFontType.CONSOLE_ITALIC, new Font(consoleFontName, Font.ITALIC, consoleFontSize));
myFontsMap.put(EditorFontType.CONSOLE_BOLD_ITALIC, new Font(consoleFontName, Font.BOLD | Font.ITALIC, consoleFontSize));
}
private void updatePreferences(FontPreferences preferences, String fontName, int fontSize, FontPreferences delegatePreferences) {
preferences.clear();
preferences.register(fontName, fontSize);
if (delegatePreferences != null) {
boolean first = true; //skip delegate's primary font
for (String font : delegatePreferences.getRealFontFamilies()) {
if (!first) {
preferences.register(font, fontSize);
}
first = false;
}
}
}
private void reinitFontsAndSettings() {
reinitFonts();
reinitSettings();
}
@Override
public TextAttributes getAttributes(TextAttributesKey key) {
if (myOwnAttributes.containsKey(key)) return myOwnAttributes.get(key);
return getDelegate().getAttributes(key);
}
@Override
public void setAttributes(TextAttributesKey key, TextAttributes attributes) {
myOwnAttributes.put(key, attributes);
}
@Nullable
@Override
public Color getColor(ColorKey key) {
if (myOwnColors.containsKey(key)) return myOwnColors.get(key);
return getDelegate().getColor(key);
}
@Override
public void setColor(ColorKey key, Color color) {
myOwnColors.put(key, color);
// These two are here because those attributes are cached and I do not whant the clients to call editor's reinit
// settings in this case.
myCaretModel.reinitSettings();
mySelectionModel.reinitSettings();
}
@Override
public int getEditorFontSize() {
if (myFontSize == -1) {
return getDelegate().getEditorFontSize();
}
return myFontSize;
}
@Override
public void setEditorFontSize(int fontSize) {
if (fontSize < MIN_FONT_SIZE) fontSize = MIN_FONT_SIZE;
if (fontSize > myMaxFontSize) fontSize = myMaxFontSize;
if (fontSize == myFontSize) return;
myFontSize = fontSize;
reinitFontsAndSettings();
}
@NotNull
@Override
public FontPreferences getFontPreferences() {
return myFontPreferences.getEffectiveFontFamilies().isEmpty() ? getDelegate().getFontPreferences() : myFontPreferences;
}
@Override
public void setFontPreferences(@NotNull FontPreferences preferences) {
if (Comparing.equal(preferences, myFontPreferences)) return;
preferences.copyTo(myFontPreferences);
reinitFontsAndSettings();
}
@NotNull
@Override
public FontPreferences getConsoleFontPreferences() {
return myConsoleFontPreferences.getEffectiveFontFamilies().isEmpty() ?
getDelegate().getConsoleFontPreferences() : myConsoleFontPreferences;
}
@Override
public void setConsoleFontPreferences(@NotNull FontPreferences preferences) {
if (Comparing.equal(preferences, myConsoleFontPreferences)) return;
preferences.copyTo(myConsoleFontPreferences);
reinitFontsAndSettings();
}
@Override
public String getEditorFontName() {
if (myFaceName == null) {
return getDelegate().getEditorFontName();
}
return myFaceName;
}
@Override
public void setEditorFontName(String fontName) {
if (Comparing.equal(fontName, myFaceName)) return;
myFaceName = fontName;
reinitFontsAndSettings();
}
@Override
public Font getFont(EditorFontType key) {
if (myFontsMap != null) {
Font font = myFontsMap.get(key);
if (font != null) return font;
}
return getDelegate().getFont(key);
}
@Override
public void setFont(EditorFontType key, Font font) {
if (myFontsMap == null) {
reinitFontsAndSettings();
}
myFontsMap.put(key, font);
reinitSettings();
}
@Override
@Nullable
public Object clone() {
return null;
}
private void updateGlobalScheme() {
setDelegate(myCustomGlobalScheme == null ? EditorColorsManager.getInstance().getGlobalScheme() : myCustomGlobalScheme);
}
@Override
public void setDelegate(@NotNull EditorColorsScheme delegate) {
super.setDelegate(delegate);
int globalFontSize = getDelegate().getEditorFontSize();
myMaxFontSize = Math.max(OptionsConstants.MAX_EDITOR_FONT_SIZE, globalFontSize);
reinitFonts();
clearSettingsCache();
}
@Override
public void setConsoleFontSize(int fontSize) {
myConsoleFontSize = fontSize;
reinitFontsAndSettings();
}
@Override
public int getConsoleFontSize() {
return myConsoleFontSize == -1 ? super.getConsoleFontSize() : myConsoleFontSize;
}
}
private static class MyTransferHandler extends TransferHandler {
private static EditorImpl getEditor(@NotNull JComponent comp) {
EditorComponentImpl editorComponent = (EditorComponentImpl)comp;
return editorComponent.getEditor();
}
@Override
public boolean importData(@NotNull final JComponent comp, @NotNull final Transferable t) {
final EditorImpl editor = getEditor(comp);
final EditorDropHandler dropHandler = editor.getDropHandler();
if (dropHandler != null && dropHandler.canHandleDrop(t.getTransferDataFlavors())) {
dropHandler.handleDrop(t, editor.getProject(), null);
return true;
}
final int caretOffset = editor.getCaretModel().getOffset();
if (editor.myDraggedRange != null
&& editor.myDraggedRange.getStartOffset() <= caretOffset && caretOffset < editor.myDraggedRange.getEndOffset()) {
return false;
}
if (editor.myDraggedRange != null) {
editor.getCaretModel().moveToOffset(editor.mySavedCaretOffsetForDNDUndoHack);
}
CommandProcessor.getInstance().executeCommand(editor.myProject, new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
try {
editor.getSelectionModel().removeSelection();
final int offset;
if (editor.myDraggedRange != null) {
editor.getCaretModel().moveToOffset(caretOffset);
offset = caretOffset;
}
else {
offset = editor.getCaretModel().getOffset();
}
if (editor.getDocument().getRangeGuard(offset, offset) != null) {
return;
}
editor.putUserData(LAST_PASTED_REGION, null);
EditorActionHandler pasteHandler = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_PASTE);
LOG.assertTrue(pasteHandler instanceof EditorTextInsertHandler);
((EditorTextInsertHandler)pasteHandler).execute(editor, editor.getDataContext(), new Producer<Transferable>() {
@Override
public Transferable produce() {
return t;
}
});
TextRange range = editor.getUserData(LAST_PASTED_REGION);
if (range != null) {
editor.getCaretModel().moveToOffset(range.getStartOffset());
editor.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset());
}
}
catch (Exception exception) {
LOG.error(exception);
}
}
});
}
}, EditorBundle.message("paste.command.name"), DND_COMMAND_KEY, UndoConfirmationPolicy.DEFAULT, editor.getDocument());
return true;
}
@Override
public boolean canImport(@NotNull JComponent comp, @NotNull DataFlavor[] transferFlavors) {
Editor editor = getEditor(comp);
final EditorDropHandler dropHandler = ((EditorImpl)editor).getDropHandler();
if (dropHandler != null && dropHandler.canHandleDrop(transferFlavors)) {
return true;
}
if (editor.isViewer()) return false;
int offset = editor.getCaretModel().getOffset();
if (editor.getDocument().getRangeGuard(offset, offset) != null) return false;
for (DataFlavor transferFlavor : transferFlavors) {
if (transferFlavor.equals(DataFlavor.stringFlavor)) return true;
}
return false;
}
@Override
@Nullable
protected Transferable createTransferable(JComponent c) {
EditorImpl editor = getEditor(c);
String s = editor.getSelectionModel().getSelectedText();
if (s == null) return null;
int selectionStart = editor.getSelectionModel().getSelectionStart();
int selectionEnd = editor.getSelectionModel().getSelectionEnd();
editor.myDraggedRange = editor.getDocument().createRangeMarker(selectionStart, selectionEnd);
return new StringSelection(s);
}
@Override
public int getSourceActions(@NotNull JComponent c) {
return COPY_OR_MOVE;
}
@Override
protected void exportDone(@NotNull final JComponent source, @Nullable Transferable data, int action) {
if (data == null) return;
final Component last = DnDManager.getInstance().getLastDropHandler();
if (last != null && !(last instanceof EditorComponentImpl)) return;
final EditorImpl editor = getEditor(source);
if (action == MOVE && !editor.isViewer() && editor.myDraggedRange != null) {
if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), editor.getProject())) {
return;
}
CommandProcessor.getInstance().executeCommand(editor.myProject, new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
Document doc = editor.getDocument();
doc.startGuardedBlockChecking();
try {
doc.deleteString(editor.myDraggedRange.getStartOffset(), editor.myDraggedRange.getEndOffset());
}
catch (ReadOnlyFragmentModificationException e) {
EditorActionManager.getInstance().getReadonlyFragmentModificationHandler(doc).handle(e);
}
finally {
doc.stopGuardedBlockChecking();
}
}
});
}
}, EditorBundle.message("move.selection.command.name"), DND_COMMAND_KEY, UndoConfirmationPolicy.DEFAULT, editor.getDocument());
}
editor.clearDraggedRange();
}
}
private class EditorDocumentAdapter implements PrioritizedDocumentListener {
@Override
public void beforeDocumentChange(@NotNull DocumentEvent e) {
beforeChangedUpdate(e);
}
@Override
public void documentChanged(@NotNull DocumentEvent e) {
changedUpdate(e);
}
@Override
public int getPriority() {
return EditorDocumentPriorities.EDITOR_DOCUMENT_ADAPTER;
}
}
private class EditorDocumentBulkUpdateAdapter implements DocumentBulkUpdateListener {
@Override
public void updateStarted(@NotNull Document doc) {
if (doc != getDocument()) return;
bulkUpdateStarted();
}
@Override
public void updateFinished(@NotNull Document doc) {
if (doc != getDocument()) return;
bulkUpdateFinished();
}
}
@SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized")
private class EditorSizeContainer {
/**
* Holds logical line widths in pixels.
*/
private TIntArrayList myLineWidths;
private int maxCalculatedLine = -1;
/**
* Holds value that indicates if line widths recalculation should be performed.
*/
private volatile boolean myIsDirty;
/**
* Holds number of the last logical line affected by the last document change.
*/
private int myOldEndLine;
private Dimension mySize;
private int myMaxWidth = -1;
public synchronized void reset() {
int lineCount = getDocument().getLineCount();
myLineWidths = new TIntArrayList(lineCount + 300);
insertNewLines(lineCount, 0);
maxCalculatedLine = -1;
myIsDirty = true;
}
private void insertNewLines(int lineCount, int index) {
int[] values = new int[lineCount];
Arrays.fill(values, -1);
myLineWidths.insert(index, values);
if (index <= maxCalculatedLine) {
maxCalculatedLine += lineCount;
}
}
@SuppressWarnings("NonPrivateFieldAccessedInSynchronizedContext")
public synchronized void beforeChange(@NotNull DocumentEvent e) {
if (myDocument.isInBulkUpdate()) {
myMaxWidth = mySize == null ? -1 : mySize.width;
}
myOldEndLine = offsetToLogicalLine(e.getOffset() + e.getOldLength());
}
/**
* Notifies current size container about document content change.
* <p/>
* Every change is assumed to be identified by three characteristics - start, ole end and new end lines.
* <b>Example:</b>
* <pre>
* <ol>
* <li>
* Consider that we have the following document initially:
* <pre>
* line 1
* line 2
* line 3
* </pre>
* </li>
* <li>
* Let's assume that the user selected the last two lines and typed 'new line' (that effectively removed selected text).
* Current document state:
* <pre>
* line 1
* new line
* </pre>
* </li>
* <li>
* Current method is expected to be called with the following parameters:
* <ul>
* <li><b>startLine</b> is 1'</li>
* <li><b>oldEndLine</b> is 2'</li>
* <li><b>newEndLine</b> is 1'</li>
* </ul>
* </li>
* </ol>
* </pre>
*
* @param startLine logical line that contains changed fragment start offset
* @param newEndLine logical line that contains changed fragment end
* @param oldEndLine logical line that contained changed fragment end
*/
public synchronized void update(int startLine, int newEndLine, int oldEndLine) {
final int lineWidthSize = myLineWidths.size();
if (lineWidthSize == 0 || myDocument.getTextLength() <= 0) {
reset();
}
else {
final int min = Math.min(oldEndLine, newEndLine);
final boolean toAddNewLines = min >= lineWidthSize;
if (toAddNewLines) {
insertNewLines(min - lineWidthSize + 1, lineWidthSize);
}
for (int i = min; i > startLine - 1; i--) {
myLineWidths.set(i, -1);
if (maxCalculatedLine == i) maxCalculatedLine--;
}
if (newEndLine > oldEndLine) {
insertNewLines(newEndLine - oldEndLine, oldEndLine + 1);
}
else if (oldEndLine > newEndLine && !toAddNewLines && newEndLine + 1 < lineWidthSize) {
int length = Math.min(oldEndLine, lineWidthSize) - newEndLine - 1;
int index = newEndLine + 1;
myLineWidths.remove(index, length);
if (index <= maxCalculatedLine) {
maxCalculatedLine -= length;
}
}
myIsDirty = true;
}
}
/**
* Notifies current container about visual width change of the target logical line.
* <p/>
* Please note that there is a possible case that particular logical line is represented in more than one visual lines,
* hence, this method may be called multiple times with the same logical line argument but different with values. Current
* container is expected to store max of the given values then.
*
* @param logicalLine logical line which visual width is changed
* @param widthInPixels visual width of the given logical line
*/
public synchronized void updateLineWidthIfNecessary(int logicalLine, int widthInPixels) {
if (logicalLine < myLineWidths.size()) {
int currentWidth = myLineWidths.get(logicalLine);
if (widthInPixels > currentWidth) {
myLineWidths.set(logicalLine, widthInPixels);
}
if (widthInPixels > myMaxWidth) {
myMaxWidth = widthInPixels;
}
maxCalculatedLine = Math.max(maxCalculatedLine, logicalLine);
}
}
public synchronized void changedUpdate(@NotNull DocumentEvent e) {
int startLine = e.getOldLength() == 0 ? myOldEndLine : myDocument.getLineNumber(e.getOffset());
int newEndLine = e.getNewLength() == 0 ? startLine : myDocument.getLineNumber(e.getOffset() + e.getNewLength());
int oldEndLine = myOldEndLine;
update(startLine, newEndLine, oldEndLine);
}
@SuppressWarnings({"NonPrivateFieldAccessedInSynchronizedContext", "AssignmentToForLoopParameter"})
private void validateSizes() {
if (!myIsDirty && !(myLinePaintersWidth > myMaxWidth)) return;
synchronized (this) {
if (!myIsDirty) return;
int lineCount = Math.min(myLineWidths.size(), myDocument.getLineCount());
if (myMaxWidth != -1 && myDocument.isInBulkUpdate()) {
mySize = new Dimension(myMaxWidth, getLineHeight() * lineCount);
myIsDirty = false;
return;
}
final CharSequence text = myDocument.getImmutableCharSequence();
int documentLength = myDocument.getTextLength();
int x = 0;
boolean lastLineLengthCalculated = false;
List<? extends SoftWrap> softWraps = getSoftWrapModel().getRegisteredSoftWraps();
int softWrapsIndex = -1;
CharWidthCache charWidthCache = new CharWidthCache(EditorImpl.this);
for (int line = 0; line < lineCount; line++) {
if (myLineWidths.getQuick(line) != -1) continue;
if (line == lineCount - 1) {
lastLineLengthCalculated = true;
}
x = 0;
int offset = myDocument.getLineStartOffset(line);
if (offset >= myDocument.getTextLength()) {
myLineWidths.set(line, 0);
maxCalculatedLine = Math.max(maxCalculatedLine, line);
break;
}
if (softWrapsIndex < 0) {
softWrapsIndex = getSoftWrapModel().getSoftWrapIndex(offset);
if (softWrapsIndex < 0) {
softWrapsIndex = -softWrapsIndex - 1;
}
}
int endLine;
if (maxCalculatedLine < line + 1) {
endLine = lineCount;
}
else {
for (endLine = line + 1; endLine < maxCalculatedLine; endLine++) {
if (myLineWidths.getQuick(endLine) != -1) {
break;
}
}
}
int endOffset = endLine >= lineCount ? documentLength : myDocument.getLineEndOffset(endLine);
for (
FoldRegion region = myFoldingModel.getCollapsedRegionAtOffset(endOffset);
region != null && endOffset < myDocument.getTextLength();
region = myFoldingModel.getCollapsedRegionAtOffset(endOffset))
{
final int lineNumber = myDocument.getLineNumber(region.getEndOffset());
endOffset = myDocument.getLineEndOffset(lineNumber);
}
if (endOffset > myDocument.getTextLength()) {
break;
}
IterationState state = new IterationState(EditorImpl.this, offset, endOffset, false);
int fontType = state.getMergedAttributes().getFontType();
int maxPreviousSoftWrappedWidth = -1;
while (offset < documentLength && line < lineCount) {
char c = text.charAt(offset);
if (offset >= state.getEndOffset()) {
state.advance();
fontType = state.getMergedAttributes().getFontType();
}
while (softWrapsIndex < softWraps.size() && line < lineCount) {
SoftWrap softWrap = softWraps.get(softWrapsIndex);
if (softWrap.getStart() > offset) {
break;
}
softWrapsIndex++;
if (softWrap.getStart() == offset) {
maxPreviousSoftWrappedWidth = Math.max(maxPreviousSoftWrappedWidth, x);
x = softWrap.getIndentInPixels();
}
}
FoldRegion collapsed = state.getCurrentFold();
if (collapsed != null) {
String placeholder = collapsed.getPlaceholderText();
for (int i = 0; i < placeholder.length(); i++) {
x += charWidthCache.charWidth(placeholder.charAt(i), fontType);
}
offset = collapsed.getEndOffset();
line = myDocument.getLineNumber(offset);
}
else if (c == '\t') {
x = EditorUtil.nextTabStop(x, EditorImpl.this);
offset++;
}
else if (c == '\n') {
int width = Math.max(x, maxPreviousSoftWrappedWidth);
myLineWidths.set(line, width);
maxCalculatedLine = Math.max(maxCalculatedLine, line);
if (line + 1 >= lineCount || myLineWidths.getQuick(line + 1) != -1) break;
offset++;
x = 0;
//noinspection AssignmentToForLoopParameter
line++;
if (line == lineCount - 1) {
lastLineLengthCalculated = true;
}
}
else {
x += charWidthCache.charWidth(c, fontType);
offset++;
}
}
}
if (lineCount > 0 && lastLineLengthCalculated) {
myLineWidths.set(lineCount - 1,
x); // Last line can be non-zero length and won't be caught by in-loop procedure since latter only react on \n's
maxCalculatedLine = Math.max(maxCalculatedLine, lineCount - 1);
}
// There is a following possible situation:
// 1. Big document is opened at editor;
// 2. Soft wraps are calculated for the current visible area;
// 2. The user scrolled down;
// 3. The user significantly reduced visible area width (say, reduced it twice);
// 4. Soft wraps are calculated for the current visible area;
// We need to consider only the widths for the logical lines that are completely shown at the current visible area then.
// I.e. we shouldn't use widths of the lines that are not shown for max width calculation because previous widths are calculated
// for another visible area width.
int startToUse = 0;
int endToUse = Math.min(lineCount, myLineWidths.size());
if (endToUse > 0 && getSoftWrapModel().isSoftWrappingEnabled()) {
Rectangle visibleArea = getScrollingModel().getVisibleArea();
startToUse = EditorUtil.yPositionToLogicalLine(EditorImpl.this, visibleArea.getLocation());
endToUse = Math.min(endToUse, EditorUtil.yPositionToLogicalLine(EditorImpl.this, visibleArea.y + visibleArea.height));
if (endToUse <= startToUse) {
// There is a possible case that there is the only soft-wrapped line, i.e. end == start. We still want to update the
// size container's width then.
endToUse = Math.min(myLineWidths.size(), startToUse + 1);
}
}
int maxWidth = 0;
for (int i = startToUse; i < endToUse; i++) {
maxWidth = Math.max(maxWidth, myLineWidths.getQuick(i));
}
mySize = new Dimension(maxWidth, getLineHeight() * Math.max(getVisibleLineCount(), 1));
myIsDirty = false;
}
}
@NotNull
private Dimension getContentSize() {
validateSizes();
return new Dimension(Math.max(mySize.width, myLinePaintersWidth), mySize.height);
}
}
@Override
@NotNull
public EditorGutter getGutter() {
return getGutterComponentEx();
}
@Override
public int calcColumnNumber(@NotNull CharSequence text, int start, int offset, int tabSize) {
if (myUseNewRendering) return myView.offsetToLogicalPosition(offset).column;
IterationState state = new IterationState(this, start, offset, false);
int fontType = state.getMergedAttributes().getFontType();
int column = 0;
int x = 0;
int plainSpaceSize = EditorUtil.getSpaceWidth(Font.PLAIN, this);
for (int i = start; i < offset; i++) {
if (i >= state.getEndOffset()) {
state.advance();
fontType = state.getMergedAttributes().getFontType();
}
SoftWrap softWrap = getSoftWrapModel().getSoftWrap(i);
if (softWrap != null) {
x = softWrap.getIndentInPixels();
}
char c = text.charAt(i);
if (c == '\t') {
int prevX = x;
x = EditorUtil.nextTabStop(x, this);
column += EditorUtil.columnsNumber(c, x, prevX, plainSpaceSize);
}
else {
x += EditorUtil.charWidth(c, fontType, this);
column++;
}
}
return column;
}
boolean isInDistractionFreeMode() {
return EditorUtil.isRealFileEditor(this)
&& (Registry.is("editor.distraction.free.mode") || isInPresentationMode());
}
boolean isInPresentationMode() {
return UISettings.getInstance().PRESENTATION_MODE && EditorUtil.isRealFileEditor(this);
}
@Override
public void putInfo(@NotNull Map<String, String> info) {
final VisualPosition visual = getCaretModel().getVisualPosition();
info.put("caret", visual.getLine() + ":" + visual.getColumn());
}
private class MyScrollPane extends JBScrollPane {
private MyScrollPane() {
super(0);
setupCorners();
}
@Override
public void layout() {
if (isInDistractionFreeMode()) {
// re-calc gutter extra size after editor size is set
// & layout once again to avoid blinking
myGutterComponent.updateSize(true);
}
super.layout();
}
@Override
protected void processMouseWheelEvent(@NotNull MouseWheelEvent e) {
if (mySettings.isWheelFontChangeEnabled() && !MouseGestureManager.getInstance().hasTrackpad()) {
if (EditorUtil.isChangeFontSize(e)) {
int size = myScheme.getEditorFontSize() - e.getWheelRotation();
if (size >= MIN_FONT_SIZE) {
setFontSize(size, SwingUtilities.convertPoint(this, e.getPoint(), getViewport()));
}
return;
}
}
super.processMouseWheelEvent(e);
}
@NotNull
@Override
public JScrollBar createVerticalScrollBar() {
return new MyScrollBar(Adjustable.VERTICAL);
}
@NotNull
@Override
public JScrollBar createHorizontalScrollBar() {
return new MyScrollBar(Adjustable.HORIZONTAL);
}
@Override
protected void setupCorners() {
super.setupCorners();
setBorder(new TablessBorder());
}
@Override
protected boolean isOverlaidScrollbar(@Nullable JScrollBar scrollbar) {
ScrollBarUI vsbUI = scrollbar == null ? null : scrollbar.getUI();
return vsbUI instanceof ButtonlessScrollBarUI && !((ButtonlessScrollBarUI)vsbUI).alwaysShowTrack();
}
}
private class TablessBorder extends SideBorder {
private TablessBorder() {
super(JBColor.border(), SideBorder.ALL);
}
@Override
public void paintBorder(@NotNull Component c, @NotNull Graphics g, int x, int y, int width, int height) {
if (c instanceof JComponent) {
Insets insets = ((JComponent)c).getInsets();
if (insets.left > 0) {
super.paintBorder(c, g, x, y, width, height);
}
else {
g.setColor(UIUtil.getPanelBackground());
g.fillRect(x, y, width, 1);
g.setColor(Gray._50.withAlpha(90));
g.fillRect(x, y, width, 1);
}
}
}
@NotNull
@Override
public Insets getBorderInsets(Component c) {
Container splitters = SwingUtilities.getAncestorOfClass(EditorsSplitters.class, c);
boolean thereIsSomethingAbove = !SystemInfo.isMac || UISettings.getInstance().SHOW_MAIN_TOOLBAR || UISettings.getInstance().SHOW_NAVIGATION_BAR ||
toolWindowIsNotEmpty();
//noinspection ConstantConditions
Component header = myHeaderPanel == null ? null : ArrayUtil.getFirstElement(myHeaderPanel.getComponents());
boolean paintTop = thereIsSomethingAbove && header == null && UISettings.getInstance().EDITOR_TAB_PLACEMENT != SwingConstants.TOP;
return splitters == null ? super.getBorderInsets(c) : new Insets(paintTop ? 1 : 0, 0, 0, 0);
}
private boolean toolWindowIsNotEmpty() {
if (myProject == null) return false;
ToolWindowManagerEx m = ToolWindowManagerEx.getInstanceEx(myProject);
return m != null && !m.getIdsOn(ToolWindowAnchor.TOP).isEmpty();
}
@Override
public boolean isBorderOpaque() {
return true;
}
}
private class MyHeaderPanel extends JPanel {
private int myOldHeight;
private MyHeaderPanel() {
super(new BorderLayout());
}
@Override
public void revalidate() {
myOldHeight = getHeight();
super.revalidate();
}
@Override
protected void validateTree() {
int height = myOldHeight;
super.validateTree();
height -= getHeight();
if (height != 0) {
myVerticalScrollBar.setValue(myVerticalScrollBar.getValue() - height);
}
myOldHeight = getHeight();
}
}
private class MyTextDrawingCallback implements TextDrawingCallback {
@Override
public void drawChars(@NotNull Graphics g,
@NotNull char[] data,
int start,
int end,
int x,
int y,
Color color,
@NotNull FontInfo fontInfo)
{
if (myUseNewRendering) {
myView.drawChars(g, data, start, end, x, y, color, fontInfo);
}
else {
drawCharsCached(g, new CharArrayCharSequence(data), start, end, x, y, fontInfo, color, false);
}
}
}
private interface WhitespacePaintingStrategy {
boolean showWhitespaceAtOffset(int offset);
}
private static final WhitespacePaintingStrategy PAINT_NO_WHITESPACE = new WhitespacePaintingStrategy() {
@Override
public boolean showWhitespaceAtOffset(int offset) {
return false;
}
};
// Strategy, controlled by current editor settings. Usable only for the current line.
public class LineWhitespacePaintingStrategy implements WhitespacePaintingStrategy {
private final boolean myWhitespaceShown = mySettings.isWhitespacesShown();
private final boolean myLeadingWhitespaceShown = mySettings.isLeadingWhitespaceShown();
private final boolean myInnerWhitespaceShown = mySettings.isInnerWhitespaceShown();
private final boolean myTrailingWhitespaceShown = mySettings.isTrailingWhitespaceShown();
// Offsets on current line where leading whitespace ends and trailing whitespace starts correspondingly.
private int currentLeadingEdge;
private int currentTrailingEdge;
// Updates the state, to be used for the line, iterator is currently at.
public void update(CharSequence chars, LineIterator iterator) {
int lineStart = iterator.getStart();
int lineEnd = iterator.getEnd() - iterator.getSeparatorLength();
update(chars, lineStart, lineEnd);
}
public void update(CharSequence chars, int lineStart, int lineEnd) {
if (myWhitespaceShown
&& (myLeadingWhitespaceShown || myInnerWhitespaceShown || myTrailingWhitespaceShown)
&& !(myLeadingWhitespaceShown && myInnerWhitespaceShown && myTrailingWhitespaceShown)) {
currentTrailingEdge = CharArrayUtil.shiftBackward(chars, lineStart, lineEnd - 1, WHITESPACE_CHARS) + 1;
currentLeadingEdge = CharArrayUtil.shiftForward(chars, lineStart, currentTrailingEdge, WHITESPACE_CHARS);
}
}
@Override
public boolean showWhitespaceAtOffset(int offset) {
return myWhitespaceShown
&& (offset < currentLeadingEdge ? myLeadingWhitespaceShown :
offset >= currentTrailingEdge ? myTrailingWhitespaceShown :
myInnerWhitespaceShown);
}
}
private class MyEditorPopupHandler extends EditorMouseAdapter {
@Override
public void mouseReleased(EditorMouseEvent e) {
invokePopupIfNeeded(e);
}
@Override
public void mousePressed(EditorMouseEvent e) {
invokePopupIfNeeded(e);
}
@Override
public void mouseClicked(EditorMouseEvent e) {
invokePopupIfNeeded(e);
}
private void invokePopupIfNeeded(EditorMouseEvent event) {
if (myContextMenuGroupId != null &&
event.getArea() == EditorMouseEventArea.EDITING_AREA &&
event.getMouseEvent().isPopupTrigger() &&
!event.isConsumed()) {
AnAction action = CustomActionsSchema.getInstance().getCorrectedAction(myContextMenuGroupId);
if (action instanceof ActionGroup) {
ActionPopupMenu popupMenu = ActionManager.getInstance().createActionPopupMenu(ActionPlaces.EDITOR_POPUP, (ActionGroup)action);
MouseEvent e = event.getMouseEvent();
final Component c = e.getComponent();
if (c != null && c.isShowing()) {
popupMenu.getComponent().show(c, e.getX(), e.getY());
}
e.consume();
}
}
}
}
}
| platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java | /*
* Copyright 2000-2015 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.editor.impl;
import com.intellij.application.options.OptionsConstants;
import com.intellij.codeInsight.hint.DocumentFragmentTooltipRenderer;
import com.intellij.codeInsight.hint.EditorFragmentComponent;
import com.intellij.codeInsight.hint.TooltipController;
import com.intellij.codeInsight.hint.TooltipGroup;
import com.intellij.concurrency.JobScheduler;
import com.intellij.diagnostic.Dumpable;
import com.intellij.diagnostic.LogMessageEx;
import com.intellij.ide.*;
import com.intellij.ide.dnd.DnDManager;
import com.intellij.ide.ui.UISettings;
import com.intellij.ide.ui.customization.CustomActionsSchema;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.actionSystem.ex.AnActionListener;
import com.intellij.openapi.actionSystem.impl.MouseGestureManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.UndoConfirmationPolicy;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.actionSystem.*;
import com.intellij.openapi.editor.actions.*;
import com.intellij.openapi.editor.colors.*;
import com.intellij.openapi.editor.colors.impl.DelegateColorScheme;
import com.intellij.openapi.editor.event.*;
import com.intellij.openapi.editor.ex.*;
import com.intellij.openapi.editor.ex.util.EditorUIUtil;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.editor.ex.util.EmptyEditorHighlighter;
import com.intellij.openapi.editor.ex.util.LexerEditorHighlighter;
import com.intellij.openapi.editor.highlighter.EditorHighlighter;
import com.intellij.openapi.editor.highlighter.HighlighterClient;
import com.intellij.openapi.editor.impl.event.MarkupModelListener;
import com.intellij.openapi.editor.impl.softwrap.SoftWrapAppliancePlaces;
import com.intellij.openapi.editor.impl.softwrap.SoftWrapDrawingType;
import com.intellij.openapi.editor.impl.view.EditorView;
import com.intellij.openapi.editor.markup.*;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory;
import com.intellij.openapi.fileEditor.impl.EditorsSplitters;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Queryable;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.IdeGlassPane;
import com.intellij.openapi.wm.ToolWindowAnchor;
import com.intellij.openapi.wm.ex.ToolWindowManagerEx;
import com.intellij.openapi.wm.impl.IdeBackgroundUtil;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.ui.*;
import com.intellij.ui.components.JBLayeredPane;
import com.intellij.ui.components.JBScrollBar;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.util.*;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.ContainerUtilRt;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.text.CharArrayCharSequence;
import com.intellij.util.text.CharArrayUtil;
import com.intellij.util.ui.*;
import com.intellij.util.ui.update.Activatable;
import com.intellij.util.ui.update.UiNotifyConnector;
import gnu.trove.TIntArrayList;
import gnu.trove.TIntFunction;
import gnu.trove.TIntHashSet;
import gnu.trove.TIntIntHashMap;
import org.intellij.lang.annotations.JdkConstants;
import org.intellij.lang.annotations.MagicConstant;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import javax.swing.*;
import javax.swing.Timer;
import javax.swing.border.Border;
import javax.swing.plaf.ScrollBarUI;
import javax.swing.plaf.basic.BasicScrollBarUI;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetAdapter;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.event.*;
import java.awt.font.TextHitInfo;
import java.awt.im.InputMethodRequests;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.lang.reflect.Field;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.text.CharacterIterator;
import java.util.*;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public final class EditorImpl extends UserDataHolderBase implements EditorEx, HighlighterClient, Queryable, Dumpable {
private static final boolean isOracleRetina = UIUtil.isRetina() && SystemInfo.isOracleJvm;
private static final int MIN_FONT_SIZE = 8;
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.editor.impl.EditorImpl");
private static final Key DND_COMMAND_KEY = Key.create("DndCommand");
@NonNls
public static final Object IGNORE_MOUSE_TRACKING = "ignore_mouse_tracking";
private static final Key<JComponent> PERMANENT_HEADER = Key.create("PERMANENT_HEADER");
public static final Key<Boolean> DO_DOCUMENT_UPDATE_TEST = Key.create("DoDocumentUpdateTest");
public static final Key<Boolean> FORCED_SOFT_WRAPS = Key.create("forced.soft.wraps");
private static final boolean HONOR_CAMEL_HUMPS_ON_TRIPLE_CLICK = Boolean.parseBoolean(System.getProperty("idea.honor.camel.humps.on.triple.click"));
private static final Key<BufferedImage> BUFFER = Key.create("buffer");
private static final Color CURSOR_FOREGROUND_LIGHT = Gray._255;
private static final Color CURSOR_FOREGROUND_DARK = Gray._0;
@NotNull private final DocumentEx myDocument;
private final JPanel myPanel;
@NotNull private final JScrollPane myScrollPane;
@NotNull private final EditorComponentImpl myEditorComponent;
@NotNull private final EditorGutterComponentImpl myGutterComponent;
private final TraceableDisposable myTraceableDisposable = new TraceableDisposable(new Throwable());
private int myLinePaintersWidth;
static {
ComplementaryFontsRegistry.getFontAbleToDisplay(' ', 0, 0, UIManager.getFont("Label.font").getFamily()); // load costly font info
}
private final CommandProcessor myCommandProcessor;
@NotNull private final MyScrollBar myVerticalScrollBar;
private final List<EditorMouseListener> myMouseListeners = ContainerUtil.createLockFreeCopyOnWriteList();
@NotNull private final List<EditorMouseMotionListener> myMouseMotionListeners = ContainerUtil.createLockFreeCopyOnWriteList();
private int myCharHeight = -1;
private int myLineHeight = -1;
private int myDescent = -1;
private boolean myIsInsertMode = true;
@NotNull private final CaretCursor myCaretCursor;
private final ScrollingTimer myScrollingTimer = new ScrollingTimer();
@SuppressWarnings("RedundantStringConstructorCall")
private final Object MOUSE_DRAGGED_GROUP = new String("MouseDraggedGroup");
@NotNull private final SettingsImpl mySettings;
private boolean isReleased;
@Nullable private MouseEvent myMousePressedEvent;
@Nullable private MouseEvent myMouseMovedEvent;
/**
* Holds information about area where mouse was pressed.
*/
@Nullable private EditorMouseEventArea myMousePressArea;
private int mySavedSelectionStart = -1;
private int mySavedSelectionEnd = -1;
private int myLastColumnNumber;
private final PropertyChangeSupport myPropertyChangeSupport = new PropertyChangeSupport(this);
private MyEditable myEditable;
@NotNull
private EditorColorsScheme myScheme;
private ArrowPainter myTabPainter;
private boolean myIsViewer;
@NotNull private final SelectionModelImpl mySelectionModel;
@NotNull private final EditorMarkupModelImpl myMarkupModel;
@NotNull private final FoldingModelImpl myFoldingModel;
@NotNull private final ScrollingModelImpl myScrollingModel;
@NotNull private final CaretModelImpl myCaretModel;
@NotNull private final SoftWrapModelImpl mySoftWrapModel;
@NotNull private static final RepaintCursorCommand ourCaretBlinkingCommand = new RepaintCursorCommand();
private MessageBusConnection myConnection;
@MouseSelectionState
private int myMouseSelectionState;
@Nullable private FoldRegion myMouseSelectedRegion;
@MagicConstant(intValues = {MOUSE_SELECTION_STATE_NONE, MOUSE_SELECTION_STATE_LINE_SELECTED, MOUSE_SELECTION_STATE_WORD_SELECTED})
private @interface MouseSelectionState {}
private static final int MOUSE_SELECTION_STATE_NONE = 0;
private static final int MOUSE_SELECTION_STATE_WORD_SELECTED = 1;
private static final int MOUSE_SELECTION_STATE_LINE_SELECTED = 2;
private EditorHighlighter myHighlighter;
private Disposable myHighlighterDisposable = Disposer.newDisposable();
private final TextDrawingCallback myTextDrawingCallback = new MyTextDrawingCallback();
@MagicConstant(intValues = {VERTICAL_SCROLLBAR_LEFT, VERTICAL_SCROLLBAR_RIGHT})
private int myScrollBarOrientation;
private boolean myMousePressedInsideSelection;
private FontMetrics myPlainFontMetrics;
private FontMetrics myBoldFontMetrics;
private FontMetrics myItalicFontMetrics;
private FontMetrics myBoldItalicFontMetrics;
private static final int CACHED_CHARS_BUFFER_SIZE = 300;
private final ArrayList<CachedFontContent> myFontCache = new ArrayList<CachedFontContent>();
@Nullable private FontInfo myCurrentFontType;
private final EditorSizeContainer mySizeContainer = new EditorSizeContainer();
private boolean myUpdateCursor;
private int myCaretUpdateVShift;
@Nullable
private final Project myProject;
private long myMouseSelectionChangeTimestamp;
private int mySavedCaretOffsetForDNDUndoHack;
private final List<FocusChangeListener> myFocusListeners = ContainerUtil.createLockFreeCopyOnWriteList();
private MyInputMethodHandler myInputMethodRequestsHandler;
private InputMethodRequests myInputMethodRequestsSwingWrapper;
private boolean myIsOneLineMode;
private boolean myIsRendererMode;
private VirtualFile myVirtualFile;
private boolean myIsColumnMode;
@Nullable private Color myForcedBackground;
@Nullable private Dimension myPreferredSize;
private int myVirtualPageHeight;
private final Alarm myMouseSelectionStateAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD);
private Runnable myMouseSelectionStateResetRunnable;
private boolean myEmbeddedIntoDialogWrapper;
@Nullable private CachedFontContent myLastCache;
private int myDragOnGutterSelectionStartLine = -1;
private RangeMarker myDraggedRange;
private boolean mySoftWrapsChanged;
// transient fields used during painting
private VisualPosition mySelectionStartPosition;
private VisualPosition mySelectionEndPosition;
private Color myLastBackgroundColor;
private Point myLastBackgroundPosition;
private int myLastBackgroundWidth;
private static final boolean ourIsUnitTestMode = ApplicationManager.getApplication().isUnitTestMode();
@NotNull private final JPanel myHeaderPanel;
@Nullable private MouseEvent myInitialMouseEvent;
private boolean myIgnoreMouseEventsConsecutiveToInitial;
private EditorDropHandler myDropHandler;
private char[] myPrefixText;
private TextAttributes myPrefixAttributes;
private int myPrefixWidthInPixels;
@NotNull private final IndentsModel myIndentsModel;
@Nullable
private CharSequence myPlaceholderText;
@Nullable private TextAttributes myPlaceholderAttributes;
private int myLastPaintedPlaceholderWidth;
private boolean myShowPlaceholderWhenFocused;
private boolean myStickySelection;
private int myStickySelectionStart;
private boolean myScrollToCaret = true;
private boolean myPurePaintingMode;
private boolean myPaintSelection;
private final EditorSizeAdjustmentStrategy mySizeAdjustmentStrategy = new EditorSizeAdjustmentStrategy();
private final Disposable myDisposable = Disposer.newDisposable();
private List<CaretState> myCaretStateBeforeLastPress;
private LogicalPosition myLastMousePressedLocation;
private VisualPosition myTargetMultiSelectionPosition;
private boolean myMultiSelectionInProgress;
private boolean myRectangularSelectionInProgress;
private boolean myLastPressCreatedCaret;
// Set when the selection (normal or block one) initiated by mouse drag becomes noticeable (at least one character is selected).
// Reset on mouse press event.
private boolean myCurrentDragIsSubstantial;
private CaretImpl myPrimaryCaret;
public final boolean myDisableRtl = Registry.is("editor.disable.rtl");
public final boolean myUseNewRendering = Registry.is("editor.new.rendering");
final EditorView myView;
private boolean myCharKeyPressed;
private boolean myNeedToSelectPreviousChar;
private boolean myDocumentChangeInProgress;
private boolean myErrorStripeNeedsRepaint;
private String myContextMenuGroupId = IdeActions.GROUP_BASIC_EDITOR_POPUP;
// Characters that excluded from zero-latency painting after key typing
private static final Set<Character> KEY_CHARS_TO_SKIP = new HashSet<Character>(Arrays.asList('\n', '\t', '(', ')', '[', ']', '{', '}', '"', '\''));
// Characters that excluded from zero-latency painting after document update
private static final Set<Character> DOCUMENT_CHARS_TO_SKIP = new HashSet<Character>(Arrays.asList(')', ']', '}', '"', '\''));
// Although it's possible to paint arbitrary line changes immediately,
// our primary interest is direct user editing actions, where visual delay is crucial.
// Moreover, as many subsystems (like PsiToDocumentSynchronizer, UndoManager, etc.) don't enforce bulk document updates,
// and can trigger multiple write actions / document changes sequentially, we need to avoid possible flickering during such an activity.
// There seems to be no other way to determine whether particular document change is triggered by direct user editing
// (raw character typing is handled separately, even before write action).
private static final Set<Class> IMMEDIATE_EDITING_ACTIONS = new HashSet<Class>(Arrays.asList(BackspaceAction.class,
DeleteAction.class,
DeleteToWordStartAction.class,
DeleteToWordEndAction.class,
DeleteToWordStartInDifferentHumpsModeAction.class,
DeleteToWordEndInDifferentHumpsModeAction.class,
DeleteToLineStartAction.class,
DeleteToLineEndAction.class,
CutAction.class,
PasteAction.class));
private Rectangle myOldArea = new Rectangle(0, 0, 0, 0);
private Rectangle myOldTailArea = new Rectangle(0, 0, 0, 0);
private boolean myImmediateEditingInProgress;
static {
ourCaretBlinkingCommand.start();
}
private int myExpectedCaretOffset = -1;
EditorImpl(@NotNull Document document, boolean viewer, @Nullable Project project) {
assertIsDispatchThread();
myProject = project;
myDocument = (DocumentEx)document;
if (myDocument instanceof DocumentImpl) {
((DocumentImpl)myDocument).requestTabTracking();
}
myScheme = createBoundColorSchemeDelegate(null);
initTabPainter();
myIsViewer = viewer;
mySettings = new SettingsImpl(this, project);
if (shouldSoftWrapsBeForced()) {
mySettings.setUseSoftWrapsQuiet();
putUserData(FORCED_SOFT_WRAPS, Boolean.TRUE);
}
mySelectionModel = new SelectionModelImpl(this);
myMarkupModel = new EditorMarkupModelImpl(this);
myFoldingModel = new FoldingModelImpl(this);
myCaretModel = new CaretModelImpl(this);
mySoftWrapModel = new SoftWrapModelImpl(this);
if (!myUseNewRendering) mySizeContainer.reset();
myCommandProcessor = CommandProcessor.getInstance();
if (project != null) {
myConnection = project.getMessageBus().connect();
myConnection.subscribe(DocumentBulkUpdateListener.TOPIC, new EditorDocumentBulkUpdateAdapter());
}
MarkupModelListener markupModelListener = new MarkupModelListener() {
private boolean areRenderersInvolved(@NotNull RangeHighlighterEx highlighter) {
return highlighter.getCustomRenderer() != null ||
highlighter.getGutterIconRenderer() != null ||
highlighter.getLineMarkerRenderer() != null ||
highlighter.getLineSeparatorRenderer() != null;
}
@Override
public void afterAdded(@NotNull RangeHighlighterEx highlighter) {
attributesChanged(highlighter, areRenderersInvolved(highlighter));
}
@Override
public void beforeRemoved(@NotNull RangeHighlighterEx highlighter) {
attributesChanged(highlighter, areRenderersInvolved(highlighter));
}
@Override
public void attributesChanged(@NotNull RangeHighlighterEx highlighter, boolean renderersChanged) {
if (myDocument.isInBulkUpdate()) return; // bulkUpdateFinished() will repaint anything
if (myUseNewRendering && renderersChanged) {
updateGutterSize();
}
boolean errorStripeNeedsRepaint = renderersChanged || highlighter.getErrorStripeMarkColor() != null;
if (myUseNewRendering && myDocumentChangeInProgress) {
// postpone repaint request, as folding model can be in inconsistent state and so coordinate
// conversions might give incorrect results
myErrorStripeNeedsRepaint |= errorStripeNeedsRepaint;
return;
}
int textLength = myDocument.getTextLength();
clearTextWidthCache();
int start = Math.min(Math.max(highlighter.getAffectedAreaStartOffset(), 0), textLength);
int end = Math.min(Math.max(highlighter.getAffectedAreaEndOffset(), 0), textLength);
int startLine = start == -1 ? 0 : myDocument.getLineNumber(start);
int endLine = end == -1 ? myDocument.getLineCount() : myDocument.getLineNumber(end);
TextAttributes attributes = highlighter.getTextAttributes();
if (myUseNewRendering && start != end && attributes != null && attributes.getFontType() != Font.PLAIN) {
myView.invalidateRange(start, end);
}
repaintLines(Math.max(0, startLine - 1), Math.min(endLine + 1, getDocument().getLineCount()));
// optimization: there is no need to repaint error stripe if the highlighter is invisible on it
if (errorStripeNeedsRepaint) {
((EditorMarkupModelImpl)getMarkupModel()).repaint(start, end);
}
if (!myUseNewRendering && renderersChanged) {
updateGutterSize();
}
updateCaretCursor();
}
};
((MarkupModelEx)DocumentMarkupModel.forDocument(myDocument, myProject, true)).addMarkupModelListener(myCaretModel, markupModelListener);
getMarkupModel().addMarkupModelListener(myCaretModel, markupModelListener);
myDocument.addDocumentListener(myFoldingModel, myCaretModel);
myDocument.addDocumentListener(myCaretModel, myCaretModel);
myDocument.addDocumentListener(mySelectionModel, myCaretModel);
myDocument.addDocumentListener(new EditorDocumentAdapter(), myCaretModel);
myDocument.addDocumentListener(mySoftWrapModel, myCaretModel);
myFoldingModel.addListener(mySoftWrapModel, myCaretModel);
myIndentsModel = new IndentsModelImpl(this);
myCaretModel.addCaretListener(new CaretListener() {
@Nullable private LightweightHint myCurrentHint;
@Nullable private IndentGuideDescriptor myCurrentCaretGuide;
@Override
public void caretPositionChanged(CaretEvent e) {
if (myStickySelection) {
int selectionStart = Math.min(myStickySelectionStart, getDocument().getTextLength() - 1);
mySelectionModel.setSelection(selectionStart, myCaretModel.getVisualPosition(), myCaretModel.getOffset());
}
final IndentGuideDescriptor newGuide = myIndentsModel.getCaretIndentGuide();
if (!Comparing.equal(myCurrentCaretGuide, newGuide)) {
repaintGuide(newGuide);
repaintGuide(myCurrentCaretGuide);
myCurrentCaretGuide = newGuide;
if (myCurrentHint != null) {
myCurrentHint.hide();
myCurrentHint = null;
}
if (newGuide != null) {
final Rectangle visibleArea = getScrollingModel().getVisibleArea();
final int line = newGuide.startLine;
if (logicalLineToY(line) < visibleArea.y) {
TextRange textRange = new TextRange(myDocument.getLineStartOffset(line), myDocument.getLineEndOffset(line));
myCurrentHint = EditorFragmentComponent.showEditorFragmentHint(EditorImpl.this, textRange, false, false);
}
}
}
}
@Override
public void caretAdded(CaretEvent e) {
if (myPrimaryCaret != null) {
myPrimaryCaret.updateVisualPosition(); // repainting old primary caret's row background
}
repaintCaretRegion(e);
myPrimaryCaret = myCaretModel.getPrimaryCaret();
}
@Override
public void caretRemoved(CaretEvent e) {
repaintCaretRegion(e);
myPrimaryCaret = myCaretModel.getPrimaryCaret(); // repainting new primary caret's row background
myPrimaryCaret.updateVisualPosition();
}
});
myCaretCursor = new CaretCursor();
myFoldingModel.flushCaretShift();
myScrollBarOrientation = VERTICAL_SCROLLBAR_RIGHT;
mySoftWrapModel.addSoftWrapChangeListener(new SoftWrapChangeListenerAdapter() {
@Override
public void recalculationEnds() {
if (myCaretModel.isUpToDate()) {
myCaretModel.updateVisualPosition();
}
}
@Override
public void softWrapsChanged() {
mySoftWrapsChanged = true;
}
});
if (!myUseNewRendering) {
mySoftWrapModel.addVisualSizeChangeListener(new VisualSizeChangeListener() {
@Override
public void onLineWidthsChange(int startLine, int oldEndLine, int newEndLine, @NotNull TIntIntHashMap lineWidths) {
mySizeContainer.update(startLine, newEndLine, oldEndLine);
for (int i = startLine; i <= newEndLine; i++) {
if (lineWidths.contains(i)) {
int width = lineWidths.get(i);
if (width >= 0) {
mySizeContainer.updateLineWidthIfNecessary(i, width);
}
}
}
}
});
}
EditorHighlighter highlighter = new EmptyEditorHighlighter(myScheme.getAttributes(HighlighterColors.TEXT));
setHighlighter(highlighter);
myEditorComponent = new EditorComponentImpl(this);
myScrollPane = new MyScrollPane();
if (SystemInfo.isMac && SystemInfo.isJavaVersionAtLeast("1.7") && Registry.is("editor.mac.smooth.scrolling")) {
PreciseMouseWheelScroller.install(myScrollPane);
}
myVerticalScrollBar = (MyScrollBar)myScrollPane.getVerticalScrollBar();
myVerticalScrollBar.setOpaque(false);
myPanel = new JPanel();
UIUtil.putClientProperty(
myPanel, UIUtil.NOT_IN_HIERARCHY_COMPONENTS, new Iterable<JComponent>() {
@NotNull
@Override
public Iterator<JComponent> iterator() {
JComponent component = getPermanentHeaderComponent();
if (component != null && !component.isValid()) {
return Collections.singleton(component).iterator();
}
return ContainerUtil.emptyIterator();
}
});
myHeaderPanel = new MyHeaderPanel();
myGutterComponent = new EditorGutterComponentImpl(this);
initComponent();
myScrollingModel = new ScrollingModelImpl(this);
if (myUseNewRendering) {
myView = new EditorView(this);
myView.reinitSettings();
}
else {
myView = null;
}
if (UISettings.getInstance().PRESENTATION_MODE) {
setFontSize(UISettings.getInstance().PRESENTATION_MODE_FONT_SIZE);
}
myGutterComponent.setLineNumberAreaWidthFunction(new TIntFunction() {
@Override
public int execute(int lineNumber) {
return getFontMetrics(Font.PLAIN).stringWidth(Integer.toString(lineNumber + 1));
}
});
myGutterComponent.updateSize();
Dimension preferredSize = getPreferredSize();
myEditorComponent.setSize(preferredSize);
updateCaretCursor();
addEditorMouseListener(new MyEditorPopupHandler());
// This hacks context layout problem where editor appears scrolled to the right just after it is created.
if (!ourIsUnitTestMode) {
UiNotifyConnector.doWhenFirstShown(myEditorComponent, new Runnable() {
@Override
public void run() {
if (!isDisposed() && !myScrollingModel.isScrollingNow()) {
myScrollingModel.disableAnimation();
myScrollingModel.scrollHorizontally(0);
myScrollingModel.enableAnimation();
}
}
});
}
}
private boolean shouldSoftWrapsBeForced() {
if (mySettings.isUseSoftWraps() ||
// Disable checking for files in intermediate states - e.g. for files during refactoring.
myProject != null && PsiDocumentManager.getInstance(myProject).isDocumentBlockedByPsi(myDocument)) {
return false;
}
int lineWidthLimit = Registry.intValue("editor.soft.wrap.force.limit");
for (int i = 0; i < myDocument.getLineCount(); i++) {
if (myDocument.getLineEndOffset(i) - myDocument.getLineStartOffset(i) > lineWidthLimit) {
return true;
}
}
return false;
}
@NotNull
static Color adjustThumbColor(@NotNull Color base, boolean dark) {
return dark ? ColorUtil.withAlpha(ColorUtil.shift(base, 1.35), 0.5)
: ColorUtil.withAlpha(ColorUtil.shift(base, 0.68), 0.4);
}
boolean isDarkEnough() {
return ColorUtil.isDark(getBackgroundColor());
}
private void repaintCaretRegion(CaretEvent e) {
CaretImpl caretImpl = (CaretImpl)e.getCaret();
if (caretImpl != null) {
caretImpl.updateVisualPosition();
if (caretImpl.hasSelection()) {
repaint(caretImpl.getSelectionStart(), caretImpl.getSelectionEnd(), false);
}
}
}
@NotNull
@Override
public EditorColorsScheme createBoundColorSchemeDelegate(@Nullable final EditorColorsScheme customGlobalScheme) {
return new MyColorSchemeDelegate(customGlobalScheme);
}
private void repaintGuide(@Nullable IndentGuideDescriptor guide) {
if (guide != null) {
repaintLines(guide.startLine, guide.endLine);
}
}
@Override
public int getPrefixTextWidthInPixels() {
return myUseNewRendering ? (int)myView.getPrefixTextWidthInPixels() : myPrefixWidthInPixels;
}
@Override
public void setPrefixTextAndAttributes(@Nullable String prefixText, @Nullable TextAttributes attributes) {
myPrefixText = prefixText == null ? null : prefixText.toCharArray();
myPrefixAttributes = attributes;
myPrefixWidthInPixels = 0;
if (myPrefixText != null) {
for (char c : myPrefixText) {
LOG.assertTrue(myPrefixAttributes != null);
if (myPrefixAttributes != null) {
myPrefixWidthInPixels += EditorUtil.charWidth(c, myPrefixAttributes.getFontType(), this);
}
}
}
mySoftWrapModel.recalculate();
if (myUseNewRendering) myView.setPrefix(prefixText, attributes);
}
@Override
public boolean isPurePaintingMode() {
return myPurePaintingMode;
}
@Override
public void setPurePaintingMode(boolean enabled) {
myPurePaintingMode = enabled;
}
@Override
public void registerScrollBarRepaintCallback(@Nullable ButtonlessScrollBarUI.ScrollbarRepaintCallback callback) {
myVerticalScrollBar.registerRepaintCallback(callback);
}
@Override
public int getExpectedCaretOffset() {
return myExpectedCaretOffset == -1 ? getCaretModel().getOffset() : myExpectedCaretOffset;
}
@Override
public void setContextMenuGroupId(@Nullable String groupId) {
myContextMenuGroupId = groupId;
}
@Nullable
@Override
public String getContextMenuGroupId() {
return myContextMenuGroupId;
}
@Override
public void setViewer(boolean isViewer) {
myIsViewer = isViewer;
}
@Override
public boolean isViewer() {
return myIsViewer || myIsRendererMode;
}
@Override
public boolean isRendererMode() {
return myIsRendererMode;
}
@Override
public void setRendererMode(boolean isRendererMode) {
myIsRendererMode = isRendererMode;
}
@Override
public void setFile(VirtualFile vFile) {
myVirtualFile = vFile;
reinitSettings();
}
@Override
public VirtualFile getVirtualFile() {
return myVirtualFile;
}
@Override
public void setSoftWrapAppliancePlace(@NotNull SoftWrapAppliancePlaces place) {
mySettings.setSoftWrapAppliancePlace(place);
}
@Override
@NotNull
public SelectionModelImpl getSelectionModel() {
return mySelectionModel;
}
@Override
@NotNull
public MarkupModelEx getMarkupModel() {
return myMarkupModel;
}
@Override
@NotNull
public FoldingModelImpl getFoldingModel() {
return myFoldingModel;
}
@Override
@NotNull
public CaretModelImpl getCaretModel() {
return myCaretModel;
}
@Override
@NotNull
public ScrollingModelEx getScrollingModel() {
return myScrollingModel;
}
@Override
@NotNull
public SoftWrapModelImpl getSoftWrapModel() {
return mySoftWrapModel;
}
@Override
@NotNull
public EditorSettings getSettings() {
assertReadAccess();
return mySettings;
}
public void resetSizes() {
if (myUseNewRendering) {
myView.reset();
}
else {
mySizeContainer.reset();
}
}
@Override
public void reinitSettings() {
assertIsDispatchThread();
clearSettingsCache();
for (EditorColorsScheme scheme = myScheme; scheme instanceof DelegateColorScheme; scheme = ((DelegateColorScheme)scheme).getDelegate()) {
if (scheme instanceof MyColorSchemeDelegate) {
((MyColorSchemeDelegate)scheme).updateGlobalScheme();
break;
}
}
boolean softWrapsUsedBefore = mySoftWrapModel.isSoftWrappingEnabled();
mySettings.reinitSettings();
mySoftWrapModel.reinitSettings();
myCaretModel.reinitSettings();
mySelectionModel.reinitSettings();
ourCaretBlinkingCommand.setBlinkCaret(mySettings.isBlinkCaret());
ourCaretBlinkingCommand.setBlinkPeriod(mySettings.getCaretBlinkPeriod());
if (myUseNewRendering) {
myView.reinitSettings();
}
else {
mySizeContainer.reset();
}
myFoldingModel.rebuild();
if (softWrapsUsedBefore ^ mySoftWrapModel.isSoftWrappingEnabled()) {
mySizeContainer.reset();
validateSize();
}
myHighlighter.setColorScheme(myScheme);
myFoldingModel.refreshSettings();
myGutterComponent.reinitSettings();
myGutterComponent.revalidate();
myEditorComponent.repaint();
initTabPainter();
updateCaretCursor();
if (myInitialMouseEvent != null) {
myIgnoreMouseEventsConsecutiveToInitial = true;
}
myCaretModel.updateVisualPosition();
// make sure carets won't appear at invalid positions (e.g. on Tab width change)
for (Caret caret : getCaretModel().getAllCarets()) {
caret.moveToOffset(caret.getOffset());
}
}
private void clearSettingsCache() {
myCharHeight = -1;
myLineHeight = -1;
myDescent = -1;
myPlainFontMetrics = null;
clearTextWidthCache();
}
private void initTabPainter() {
myTabPainter = new ArrowPainter(
ColorProvider.byColorsScheme(myScheme, EditorColors.WHITESPACES_COLOR),
new Computable.PredefinedValueComputable<Integer>(EditorUtil.getSpaceWidth(Font.PLAIN, this)),
new Computable<Integer>() {
@Override
public Integer compute() {
return getCharHeight();
}
}
);
}
public void throwDisposalError(@NonNls @NotNull String msg) {
myTraceableDisposable.throwDisposalError(msg);
}
public void release() {
assertIsDispatchThread();
if (isReleased) {
throwDisposalError("Double release of editor:");
}
myTraceableDisposable.kill(null);
isReleased = true;
clearSettingsCache();
myFoldingModel.dispose();
mySoftWrapModel.release();
myMarkupModel.dispose();
myScrollingModel.dispose();
myGutterComponent.dispose();
myMousePressedEvent = null;
myMouseMovedEvent = null;
Disposer.dispose(myCaretModel);
Disposer.dispose(mySoftWrapModel);
if (myUseNewRendering) Disposer.dispose(myView);
clearCaretThread();
myFocusListeners.clear();
myMouseListeners.clear();
myMouseMotionListeners.clear();
if (myConnection != null) {
myConnection.disconnect();
}
if (myDocument instanceof DocumentImpl) {
((DocumentImpl)myDocument).giveUpTabTracking();
}
Disposer.dispose(myDisposable);
}
private void clearCaretThread() {
synchronized (ourCaretBlinkingCommand) {
if (ourCaretBlinkingCommand.myEditor == this) {
ourCaretBlinkingCommand.myEditor = null;
}
}
}
private void initComponent() {
myPanel.setLayout(new BorderLayout());
myPanel.add(myHeaderPanel, BorderLayout.NORTH);
myGutterComponent.setOpaque(true);
myScrollPane.setViewportView(myEditorComponent);
//myScrollPane.setBorder(null);
myScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
myScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
myScrollPane.setRowHeaderView(myGutterComponent);
myEditorComponent.setTransferHandler(new MyTransferHandler());
myEditorComponent.setAutoscrolls(true);
/* Default mode till 1.4.0
* myScrollPane.getViewport().setScrollMode(JViewport.BLIT_SCROLL_MODE);
*/
if (mayShowToolbar()) {
JLayeredPane layeredPane = new JBLayeredPane() {
@Override
public void doLayout() {
final Component[] components = getComponents();
final Rectangle r = getBounds();
for (Component c : components) {
if (c instanceof JScrollPane) {
c.setBounds(0, 0, r.width, r.height);
}
else {
final Dimension d = c.getPreferredSize();
final MyScrollBar scrollBar = getVerticalScrollBar();
c.setBounds(r.width - d.width - scrollBar.getWidth() - 30, 20, d.width, d.height);
}
}
}
@Override
public Dimension getPreferredSize() {
return myScrollPane.getPreferredSize();
}
};
layeredPane.add(myScrollPane, JLayeredPane.DEFAULT_LAYER);
myPanel.add(layeredPane);
new ContextMenuImpl(layeredPane, myScrollPane, this);
}
else {
myPanel.add(myScrollPane);
}
final AnActionListener.Adapter actionListener = new AnActionListener.Adapter() {
@Override
public void beforeActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event) {
if (isZeroLatencyTypingEnabled() && IMMEDIATE_EDITING_ACTIONS.contains(action.getClass())) {
myImmediateEditingInProgress = true;
}
}
@Override
public void afterActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event) {
if (isZeroLatencyTypingEnabled()) {
myImmediateEditingInProgress = false;
}
}
};
ActionManager.getInstance().addAnActionListener(actionListener);
Disposer.register(myDisposable, new Disposable() {
@Override
public void dispose() {
ActionManager.getInstance().removeAnActionListener(actionListener);
}
});
myEditorComponent.addKeyListener(new KeyListener() {
@Override
public void keyPressed(@NotNull KeyEvent e) {
if (e.getKeyCode() >= KeyEvent.VK_A && e.getKeyCode() <= KeyEvent.VK_Z) {
myCharKeyPressed = true;
}
KeyboardInternationalizationNotificationManager.showNotification();
}
@Override
public void keyTyped(@NotNull KeyEvent event) {
myNeedToSelectPreviousChar = false;
if (event.isConsumed()) {
return;
}
if (processKeyTyped(event)) {
event.consume();
}
}
@Override
public void keyReleased(KeyEvent e) {
myCharKeyPressed = false;
}
});
MyMouseAdapter mouseAdapter = new MyMouseAdapter();
myEditorComponent.addMouseListener(mouseAdapter);
myGutterComponent.addMouseListener(mouseAdapter);
MyMouseMotionListener mouseMotionListener = new MyMouseMotionListener();
myEditorComponent.addMouseMotionListener(mouseMotionListener);
myGutterComponent.addMouseMotionListener(mouseMotionListener);
myEditorComponent.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(@NotNull FocusEvent e) {
myCaretCursor.activate();
for (Caret caret : myCaretModel.getAllCarets()) {
int caretLine = caret.getLogicalPosition().line;
repaintLines(caretLine, caretLine);
}
fireFocusGained();
}
@Override
public void focusLost(@NotNull FocusEvent e) {
clearCaretThread();
for (Caret caret : myCaretModel.getAllCarets()) {
int caretLine = caret.getLogicalPosition().line;
repaintLines(caretLine, caretLine);
}
fireFocusLost();
}
});
UiNotifyConnector connector = new UiNotifyConnector(myEditorComponent, new Activatable.Adapter() {
@Override
public void showNotify() {
myGutterComponent.updateSize();
}
});
Disposer.register(getDisposable(), connector);
try {
final DropTarget dropTarget = myEditorComponent.getDropTarget();
if (dropTarget != null) { // might be null in headless environment
dropTarget.addDropTargetListener(new DropTargetAdapter() {
@Override
public void drop(@NotNull DropTargetDropEvent e) {
}
@Override
public void dragOver(@NotNull DropTargetDragEvent e) {
Point location = e.getLocation();
if (myUseNewRendering) {
getCaretModel().moveToVisualPosition(getTargetPosition(location.x, location.y, true));
}
else {
getCaretModel().moveToLogicalPosition(getLogicalPositionForScreenPos(location.x, location.y, true));
}
getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
requestFocus();
}
});
}
}
catch (TooManyListenersException e) {
LOG.error(e);
}
myPanel.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(@NotNull ComponentEvent e) {
myMarkupModel.recalcEditorDimensions();
myMarkupModel.repaint(-1, -1);
}
});
}
private boolean mayShowToolbar() {
return !isEmbeddedIntoDialogWrapper() && !isOneLineMode() && ContextMenuImpl.mayShowToolbar(myDocument);
}
@Override
public void setFontSize(final int fontSize) {
setFontSize(fontSize, null);
}
/**
* Changes editor font size, attempting to keep a given point unmoved. If point is not given, top left screen corner is assumed.
*
* @param fontSize new font size
* @param zoomCenter zoom point, relative to viewport
*/
private void setFontSize(final int fontSize, @Nullable Point zoomCenter) {
int oldFontSize = myScheme.getEditorFontSize();
Rectangle visibleArea = myScrollingModel.getVisibleArea();
Point zoomCenterRelative = zoomCenter == null ? new Point() : zoomCenter;
Point zoomCenterAbsolute = new Point(visibleArea.x + zoomCenterRelative.x, visibleArea.y + zoomCenterRelative.y);
LogicalPosition zoomCenterLogical = xyToLogicalPosition(zoomCenterAbsolute).withoutVisualPositionInfo();
int oldLineHeight = getLineHeight();
int intraLineOffset = zoomCenterAbsolute.y % oldLineHeight;
myScheme.setEditorFontSize(fontSize);
myPropertyChangeSupport.firePropertyChange(PROP_FONT_SIZE, oldFontSize, fontSize);
// Update vertical scroll bar bounds if necessary (we had a problem that use increased editor font size and it was not possible
// to scroll to the bottom of the document).
myScrollPane.getViewport().invalidate();
Point shiftedZoomCenterAbsolute = logicalPositionToXY(zoomCenterLogical);
myScrollingModel.disableAnimation();
try {
myScrollingModel.scrollToOffsets(visibleArea.x == 0 ? 0 : shiftedZoomCenterAbsolute.x - zoomCenterRelative.x, // stick to left border if it's visible
shiftedZoomCenterAbsolute.y - zoomCenterRelative.y + (intraLineOffset * getLineHeight() + oldLineHeight / 2) / oldLineHeight);
} finally {
myScrollingModel.enableAnimation();
}
}
public int getFontSize() {
return myScheme.getEditorFontSize();
}
@NotNull
public ActionCallback type(@NotNull final String text) {
final ActionCallback result = new ActionCallback();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
for (int i = 0; i < text.length(); i++) {
if (!processKeyTyped(text.charAt(i))) {
result.setRejected();
return;
}
}
result.setDone();
}
});
return result;
}
private boolean processKeyTyped(char c) {
// [vova] This is patch for Mac OS X. Under Mac "input methods"
// is handled before our EventQueue consume upcoming KeyEvents.
IdeEventQueue queue = IdeEventQueue.getInstance();
if (queue.shouldNotTypeInEditor() || ProgressManager.getInstance().hasModalProgressIndicator()) {
return false;
}
FileDocumentManager manager = FileDocumentManager.getInstance();
final VirtualFile file = manager.getFile(myDocument);
if (file != null && !file.isValid()) {
return false;
}
ActionManagerEx actionManager = ActionManagerEx.getInstanceEx();
DataContext dataContext = getDataContext();
if (isZeroLatencyTypingEnabled() && myDocument.isWritable() && !isViewer() && canPaintImmediately(c)) {
for (Caret caret : myCaretModel.getAllCarets()) {
paintImmediately(caret.getOffset(), c, myIsInsertMode);
}
}
actionManager.fireBeforeEditorTyping(c, dataContext);
MacUIUtil.hideCursor();
EditorActionManager.getInstance().getTypedAction().actionPerformed(this, c, dataContext);
return true;
}
private void fireFocusLost() {
for (FocusChangeListener listener : myFocusListeners) {
listener.focusLost(this);
}
}
private void fireFocusGained() {
for (FocusChangeListener listener : myFocusListeners) {
listener.focusGained(this);
}
}
@Override
public void setHighlighter(@NotNull final EditorHighlighter highlighter) {
assertIsDispatchThread();
final Document document = getDocument();
Disposer.dispose(myHighlighterDisposable);
document.addDocumentListener(highlighter);
myHighlighter = highlighter;
myHighlighterDisposable = new Disposable() {
@Override
public void dispose() {
document.removeDocumentListener(highlighter);
}
};
Disposer.register(myDisposable, myHighlighterDisposable);
highlighter.setEditor(this);
highlighter.setText(document.getImmutableCharSequence());
EditorHighlighterCache.rememberEditorHighlighterForCachesOptimization(document, highlighter);
if (myPanel != null) {
reinitSettings();
}
}
@NotNull
@Override
public EditorHighlighter getHighlighter() {
assertReadAccess();
return myHighlighter;
}
@Override
@NotNull
public EditorComponentImpl getContentComponent() {
return myEditorComponent;
}
@NotNull
@Override
public EditorGutterComponentImpl getGutterComponentEx() {
return myGutterComponent;
}
@Override
public void addPropertyChangeListener(@NotNull PropertyChangeListener listener) {
myPropertyChangeSupport.addPropertyChangeListener(listener);
}
@Override
public void addPropertyChangeListener(@NotNull final PropertyChangeListener listener, @NotNull Disposable parentDisposable) {
addPropertyChangeListener(listener);
Disposer.register(parentDisposable, new Disposable() {
@Override
public void dispose() {
removePropertyChangeListener(listener);
}
});
}
@Override
public void removePropertyChangeListener(@NotNull PropertyChangeListener listener) {
myPropertyChangeSupport.removePropertyChangeListener(listener);
}
@Override
public void setInsertMode(boolean mode) {
assertIsDispatchThread();
boolean oldValue = myIsInsertMode;
myIsInsertMode = mode;
myPropertyChangeSupport.firePropertyChange(PROP_INSERT_MODE, oldValue, mode);
myCaretCursor.repaint();
}
@Override
public boolean isInsertMode() {
return myIsInsertMode;
}
@Override
public void setColumnMode(boolean mode) {
assertIsDispatchThread();
boolean oldValue = myIsColumnMode;
myIsColumnMode = mode;
myPropertyChangeSupport.firePropertyChange(PROP_COLUMN_MODE, oldValue, mode);
}
@Override
public boolean isColumnMode() {
return myIsColumnMode;
}
private int yPositionToVisibleLine(int y) {
if (myUseNewRendering) return myView.yToVisualLine(y);
assert y >= 0 : y;
return y / getLineHeight();
}
@Override
@NotNull
public VisualPosition xyToVisualPosition(@NotNull Point p) {
if (myUseNewRendering) return myView.xyToVisualPosition(p);
int line = yPositionToVisibleLine(Math.max(p.y, 0));
int px = p.x;
if (line == 0 && myPrefixText != null) {
px -= myPrefixWidthInPixels;
}
if (px < 0) {
px = 0;
}
int textLength = myDocument.getTextLength();
LogicalPosition logicalPosition = visualToLogicalPosition(new VisualPosition(line, 0));
int offset = logicalPositionToOffset(logicalPosition);
int plainSpaceSize = EditorUtil.getSpaceWidth(Font.PLAIN, this);
if (offset >= textLength) return new VisualPosition(line, EditorUtil.columnsNumber(px, plainSpaceSize));
// There is a possible case that starting logical line is split by soft-wraps and it's part after the split should be drawn.
// We mark that we're under such circumstances then.
boolean activeSoftWrapProcessed = logicalPosition.softWrapLinesOnCurrentLogicalLine <= 0;
CharSequence text = myDocument.getImmutableCharSequence();
LogicalPosition endLogicalPosition = visualToLogicalPosition(new VisualPosition(line + 1, 0));
int endOffset = logicalPositionToOffset(endLogicalPosition);
if (offset > endOffset) {
LogMessageEx.error(LOG, "Detected invalid (x; y)->VisualPosition processing", String.format(
"Given point: %s, mapped to visual line %d. Visual(%d; %d) is mapped to "
+ "logical position '%s' which is mapped to offset %d (start offset). Visual(%d; %d) is mapped to logical '%s' which is mapped "
+ "to offset %d (end offset). State: %s",
p, line, line, 0, logicalPosition, offset, line + 1, 0, endLogicalPosition, endOffset, dumpState()
));
return new VisualPosition(line, EditorUtil.columnsNumber(px, plainSpaceSize));
}
IterationState state = new IterationState(this, offset, endOffset, false);
int fontType = state.getMergedAttributes().getFontType();
int x = 0;
int charWidth;
boolean onSoftWrapDrawing = false;
char c = ' ';
int prevX = 0;
int column = 0;
outer:
while (true) {
charWidth = -1;
if (offset >= textLength) {
break;
}
if (offset >= state.getEndOffset()) {
state.advance();
fontType = state.getMergedAttributes().getFontType();
}
SoftWrap softWrap = mySoftWrapModel.getSoftWrap(offset);
if (softWrap != null) {
if (activeSoftWrapProcessed) {
prevX = x;
charWidth = getSoftWrapModel().getMinDrawingWidthInPixels(SoftWrapDrawingType.BEFORE_SOFT_WRAP_LINE_FEED);
x += charWidth;
if (x >= px) {
onSoftWrapDrawing = true;
}
else {
column++;
}
break;
}
else {
CharSequence softWrapText = softWrap.getText();
for (int i = 1/*Assuming line feed is located at the first position*/; i < softWrapText.length(); i++) {
c = softWrapText.charAt(i);
prevX = x;
charWidth = charToVisibleWidth(c, fontType, x);
x += charWidth;
if (x >= px) {
break outer;
}
column += EditorUtil.columnsNumber(c, x, prevX, plainSpaceSize);
}
// Process 'after soft wrap' sign.
prevX = x;
charWidth = mySoftWrapModel.getMinDrawingWidthInPixels(SoftWrapDrawingType.AFTER_SOFT_WRAP);
x += charWidth;
if (x >= px) {
onSoftWrapDrawing = true;
break;
}
column++;
activeSoftWrapProcessed = true;
}
}
FoldRegion region = state.getCurrentFold();
if (region != null) {
char[] placeholder = region.getPlaceholderText().toCharArray();
for (char aPlaceholder : placeholder) {
c = aPlaceholder;
x += EditorUtil.charWidth(c, fontType, this);
if (x >= px) {
break outer;
}
column++;
}
offset = region.getEndOffset();
}
else {
prevX = x;
c = text.charAt(offset);
if (c == '\n') {
break;
}
charWidth = charToVisibleWidth(c, fontType, x);
x += charWidth;
if (x >= px) {
break;
}
column += EditorUtil.columnsNumber(c, x, prevX, plainSpaceSize);
offset++;
}
}
if (charWidth < 0) {
charWidth = EditorUtil.charWidth(c, fontType, this);
}
if (charWidth < 0) {
charWidth = plainSpaceSize;
}
if (x >= px && c == '\t' && !onSoftWrapDrawing) {
if (mySettings.isCaretInsideTabs()) {
column += (px - prevX) / plainSpaceSize;
if ((px - prevX) % plainSpaceSize > plainSpaceSize / 2) column++;
}
else if ((x - px) * 2 < x - prevX) {
column += EditorUtil.columnsNumber(c, x, prevX, plainSpaceSize);
}
}
else {
if (x >= px) {
if (c != '\n' && (x - px) * 2 < charWidth) column++;
}
else {
int diff = px - x;
column += diff / plainSpaceSize;
if (diff % plainSpaceSize * 2 >= plainSpaceSize) {
column++;
}
}
}
return new VisualPosition(line, column);
}
/**
* Allows to answer how much width requires given char to be represented on a screen.
*
* @param c target character
* @param fontType font type to use for representation of the given character
* @param currentX current <code>'x'</code> position on a line where given character should be displayed
* @return width required to represent given char with the given settings on a screen;
* <code>'0'</code> if given char is a line break
*/
private int charToVisibleWidth(char c, @JdkConstants.FontStyle int fontType, int currentX) {
if (c == '\n') {
return 0;
}
if (c == '\t') {
return EditorUtil.nextTabStop(currentX, this) - currentX;
}
return EditorUtil.charWidth(c, fontType, this);
}
@NotNull
public Point offsetToXY(int offset, boolean leanTowardsLargerOffsets) {
return myUseNewRendering ? myView.offsetToXY(offset, leanTowardsLargerOffsets, false) :
visualPositionToXY(offsetToVisualPosition(offset, leanTowardsLargerOffsets, false));
}
@Override
@NotNull
public VisualPosition offsetToVisualPosition(int offset) {
return offsetToVisualPosition(offset, false, false);
}
@Override
@NotNull
public VisualPosition offsetToVisualPosition(int offset, boolean leanForward, boolean beforeSoftWrap) {
if (myUseNewRendering) return myView.offsetToVisualPosition(offset, leanForward, beforeSoftWrap);
return logicalToVisualPosition(offsetToLogicalPosition(offset));
}
@Override
@NotNull
public LogicalPosition offsetToLogicalPosition(int offset) {
return offsetToLogicalPosition(offset, true);
}
@NotNull
@Override
public LogicalPosition offsetToLogicalPosition(int offset, boolean softWrapAware) {
if (myUseNewRendering) return myView.offsetToLogicalPosition(offset);
if (softWrapAware) {
return mySoftWrapModel.offsetToLogicalPosition(offset);
}
int line = offsetToLogicalLine(offset);
int column = calcColumnNumber(offset, line, false, myDocument.getImmutableCharSequence());
return new LogicalPosition(line, column);
}
@TestOnly
public void setCaretActive() {
synchronized (ourCaretBlinkingCommand) {
ourCaretBlinkingCommand.myEditor = this;
}
}
// optimization: do not do column calculations here since we are interested in line number only
public int offsetToVisualLine(int offset) {
if (myUseNewRendering) return myView.offsetToVisualLine(offset, false);
int textLength = getDocument().getTextLength();
if (offset >= textLength) {
return Math.max(0, getVisibleLineCount() - 1); // lines are 0 based
}
int line = offsetToLogicalLine(offset);
int lineStartOffset = line >= myDocument.getLineCount() ? myDocument.getTextLength() : myDocument.getLineStartOffset(line);
int result = logicalToVisualLine(line);
// There is a possible case that logical line that contains target offset is soft-wrapped (represented in more than one visual
// line). Hence, we need to perform necessary adjustments to the visual line that is used to show logical line start if necessary.
int i = getSoftWrapModel().getSoftWrapIndex(lineStartOffset);
if (i < 0) {
i = -i - 1;
}
List<? extends SoftWrap> softWraps = getSoftWrapModel().getRegisteredSoftWraps();
for (; i < softWraps.size(); i++) {
SoftWrap softWrap = softWraps.get(i);
if (softWrap.getStart() > offset) {
break;
}
result++; // Assuming that every soft wrap contains only one virtual line feed symbol
}
return result;
}
private int logicalToVisualLine(int line) {
assertReadAccess();
return logicalToVisualPosition(new LogicalPosition(line, 0)).line;
}
@Override
@NotNull
public LogicalPosition xyToLogicalPosition(@NotNull Point p) {
Point pp = p.x >= 0 && p.y >= 0 ? p : new Point(Math.max(p.x, 0), Math.max(p.y, 0));
return visualToLogicalPosition(xyToVisualPosition(pp));
}
private int logicalLineToY(int line) {
VisualPosition visible = logicalToVisualPosition(new LogicalPosition(line, 0));
return visibleLineToY(visible.line);
}
@Override
@NotNull
public Point logicalPositionToXY(@NotNull LogicalPosition pos) {
VisualPosition visible = logicalToVisualPosition(pos);
return visualPositionToXY(visible);
}
@Override
@NotNull
public Point visualPositionToXY(@NotNull VisualPosition visible) {
if (myUseNewRendering) return myView.visualPositionToXY(visible);
int y = visibleLineToY(visible.line);
LogicalPosition logical = visualToLogicalPosition(new VisualPosition(visible.line, 0));
int logLine = logical.line;
int lineStartOffset = -1;
int reserved = 0;
int column = visible.column;
if (logical.softWrapLinesOnCurrentLogicalLine > 0) {
int linesToSkip = logical.softWrapLinesOnCurrentLogicalLine;
List<? extends SoftWrap> softWraps = getSoftWrapModel().getSoftWrapsForLine(logLine);
for (SoftWrap softWrap : softWraps) {
if (myFoldingModel.isOffsetCollapsed(softWrap.getStart()) && myFoldingModel.isOffsetCollapsed(softWrap.getStart() - 1)) {
continue;
}
linesToSkip--; // Assuming here that every soft wrap has exactly one line feed
if (linesToSkip > 0) {
continue;
}
lineStartOffset = softWrap.getStart();
int widthInColumns = softWrap.getIndentInColumns();
int widthInPixels = softWrap.getIndentInPixels();
if (widthInColumns <= column) {
column -= widthInColumns;
reserved = widthInPixels;
}
else {
char[] softWrapChars = softWrap.getChars();
int i = CharArrayUtil.lastIndexOf(softWrapChars, '\n', 0, softWrapChars.length);
int start = 0;
if (i >= 0) {
start = i + 1;
}
return new Point(EditorUtil.textWidth(this, softWrap.getText(), start, column + 1, Font.PLAIN, 0), y);
}
break;
}
}
if (logLine < 0) {
lineStartOffset = 0;
}
else if (lineStartOffset < 0) {
lineStartOffset = logLine >= myDocument.getLineCount() ? myDocument.getTextLength() : myDocument.getLineStartOffset(logLine);
}
int x = getTabbedTextWidth(lineStartOffset, column, reserved);
return new Point(x, y);
}
private int calcEndOffset(int startOffset, int visualColumn) {
FoldRegion[] regions = myFoldingModel.fetchTopLevel();
if (regions == null) {
return startOffset + visualColumn;
}
int low = 0;
int high = regions.length - 1;
int i = -1;
while (low <= high) {
int mid = low + high >>> 1;
FoldRegion midVal = regions[mid];
if (midVal.getStartOffset() <= startOffset && midVal.getEndOffset() > startOffset) {
i = mid;
break;
}
if (midVal.getStartOffset() < startOffset)
low = mid + 1;
else if (midVal.getStartOffset() > startOffset)
high = mid - 1;
}
if (i < 0) {
i = low;
}
int result = startOffset;
int columnsToProcess = visualColumn;
for (; i < regions.length; i++) {
FoldRegion region = regions[i];
// Process text between the last fold region end and current fold region start.
int nonFoldTextColumnsNumber = region.getStartOffset() - result;
if (nonFoldTextColumnsNumber >= columnsToProcess) {
return result + columnsToProcess;
}
columnsToProcess -= nonFoldTextColumnsNumber;
// Process fold region.
int placeHolderLength = region.getPlaceholderText().length();
if (placeHolderLength >= columnsToProcess) {
return region.getEndOffset();
}
result = region.getEndOffset();
columnsToProcess -= placeHolderLength;
}
return result + columnsToProcess;
}
public int findNearestDirectionBoundary(int offset, boolean lookForward) {
return myUseNewRendering ? myView.findNearestDirectionBoundary(offset, lookForward) : -1;
}
// TODO: tabbed text width is additive, it should be possible to have buckets, containing arguments / values to start with
private final int[] myLastStartOffsets = new int[2];
private final int[] myLastTargetColumns = new int[myLastStartOffsets.length];
private final int[] myLastXOffsets = new int[myLastStartOffsets.length];
private final int[] myLastXs = new int[myLastStartOffsets.length];
private int myCurrentCachePosition;
private int myLastCacheHits;
private int myTotalRequests; // todo remove
private int getTabbedTextWidth(int startOffset, int targetColumn, int xOffset) {
int x = xOffset;
if (startOffset == 0 && myPrefixText != null) {
x += myPrefixWidthInPixels;
}
if (targetColumn <= 0) return x;
++myTotalRequests;
for(int i = 0; i < myLastStartOffsets.length; ++i) {
if (startOffset == myLastStartOffsets[i] && targetColumn == myLastTargetColumns[i] && xOffset == myLastXOffsets[i]) {
++myLastCacheHits;
if ((myLastCacheHits & 0xFFF) == 0) { // todo remove
PsiFile file = myProject != null ? PsiDocumentManager.getInstance(myProject).getCachedPsiFile(myDocument):null;
LOG.info("Cache hits:" + myLastCacheHits + ", total requests:" +
myTotalRequests + "," + (file != null ? file.getViewProvider().getVirtualFile():null));
}
return myLastXs[i];
}
}
int offset = startOffset;
CharSequence text = myDocument.getImmutableCharSequence();
int textLength = myDocument.getTextLength();
// We need to calculate max offset to provide to the IterationState here based on the given start offset and target
// visual column. The problem is there is a possible case that there is a collapsed fold region at the target interval,
// so, we can't just use 'startOffset + targetColumn' as a max end offset.
IterationState state = new IterationState(this, startOffset, calcEndOffset(startOffset, targetColumn), false);
int fontType = state.getMergedAttributes().getFontType();
int plainSpaceSize = EditorUtil.getSpaceWidth(Font.PLAIN, this);
int column = 0;
outer:
while (column < targetColumn) {
if (offset >= textLength) break;
if (offset >= state.getEndOffset()) {
state.advance();
fontType = state.getMergedAttributes().getFontType();
}
// We need to consider 'before soft wrap drawing'.
SoftWrap softWrap = getSoftWrapModel().getSoftWrap(offset);
if (softWrap != null && offset > startOffset) {
column++;
x += getSoftWrapModel().getMinDrawingWidthInPixels(SoftWrapDrawingType.BEFORE_SOFT_WRAP_LINE_FEED);
// Assuming that first soft wrap symbol is line feed or all soft wrap symbols before the first line feed are spaces.
break;
}
FoldRegion region = state.getCurrentFold();
if (region != null) {
char[] placeholder = region.getPlaceholderText().toCharArray();
for (char aPlaceholder : placeholder) {
x += EditorUtil.charWidth(aPlaceholder, fontType, this);
column++;
if (column >= targetColumn) break outer;
}
offset = region.getEndOffset();
}
else {
char c = text.charAt(offset);
if (c == '\n') {
break;
}
if (c == '\t') {
int prevX = x;
x = EditorUtil.nextTabStop(x, this);
int columnDiff = (x - prevX) / plainSpaceSize;
if ((x - prevX) % plainSpaceSize > 0) {
// There is a possible case that tabulation symbol takes more than one visual column to represent and it's shown at
// soft-wrapped line. Soft wrap sign width may be not divisible by space size, hence, part of tabulation symbol represented
// as a separate visual column may take less space than space width.
columnDiff++;
}
column += columnDiff;
}
else {
x += EditorUtil.charWidth(c, fontType, this);
column++;
}
offset++;
}
}
if (column != targetColumn) {
x += EditorUtil.getSpaceWidth(fontType, this) * (targetColumn - column);
}
myLastTargetColumns[myCurrentCachePosition] = targetColumn;
myLastStartOffsets[myCurrentCachePosition] = startOffset;
myLastXs[myCurrentCachePosition] = x;
myLastXOffsets[myCurrentCachePosition] = xOffset;
myCurrentCachePosition = (myCurrentCachePosition + 1) % myLastStartOffsets.length;
return x;
}
private void clearTextWidthCache() {
for(int i = 0; i < myLastStartOffsets.length; ++i) {
myLastTargetColumns[i] = -1;
myLastStartOffsets[i] = - 1;
myLastXs[i] = -1;
myLastXOffsets[i] = -1;
}
}
public int visibleLineToY(int line) {
if (myUseNewRendering) return myView.visualLineToY(line);
if (line < 0) throw new IndexOutOfBoundsException("Wrong line: " + line);
return line * getLineHeight();
}
@Override
public void repaint(int startOffset, int endOffset) {
repaint(startOffset, endOffset, true);
}
void repaint(int startOffset, int endOffset, boolean invalidateTextLayout) {
if (myDocument.isInBulkUpdate()) {
return;
}
if (myUseNewRendering) {
assertIsDispatchThread();
endOffset = Math.min(endOffset, myDocument.getTextLength());
if (invalidateTextLayout) {
myView.invalidateRange(startOffset, endOffset);
}
if (!isShowing()) {
return;
}
}
else {
if (!isShowing()) {
return;
}
endOffset = Math.min(endOffset, myDocument.getTextLength());
assertIsDispatchThread();
}
// We do repaint in case of equal offsets because there is a possible case that there is a soft wrap at the same offset and
// it does occupy particular amount of visual space that may be necessary to repaint.
if (startOffset <= endOffset) {
int startLine = myDocument.getLineNumber(startOffset);
int endLine = myDocument.getLineNumber(endOffset);
repaintLines(startLine, endLine);
}
}
private boolean isShowing() {
return myGutterComponent.isShowing();
}
private void repaintToScreenBottom(int startLine) {
Rectangle visibleArea = getScrollingModel().getVisibleArea();
int yStartLine = logicalLineToY(startLine);
int yEndLine = visibleArea.y + visibleArea.height;
myEditorComponent.repaintEditorComponent(visibleArea.x, yStartLine, visibleArea.x + visibleArea.width, yEndLine - yStartLine);
myGutterComponent.repaint(0, yStartLine, myGutterComponent.getWidth(), yEndLine - yStartLine);
((EditorMarkupModelImpl)getMarkupModel()).repaint(-1, -1);
}
/**
* Asks to repaint all logical lines from the given <code>[start; end]</code> range.
*
* @param startLine start logical line to repaint (inclusive)
* @param endLine end logical line to repaint (inclusive)
*/
private void repaintLines(int startLine, int endLine) {
if (!isShowing()) return;
Rectangle visibleArea = getScrollingModel().getVisibleArea();
int yStartLine = logicalLineToY(startLine);
int endVisLine = myDocument.getTextLength() <= 0
? 0
: offsetToVisualLine(myDocument.getLineEndOffset(Math.min(myDocument.getLineCount() - 1, endLine)));
int height = endVisLine * getLineHeight() - yStartLine + getLineHeight() + 2;
myEditorComponent.repaintEditorComponent(visibleArea.x, yStartLine, visibleArea.x + visibleArea.width, height);
myGutterComponent.repaint(0, yStartLine, myGutterComponent.getWidth(), height);
}
private void bulkUpdateStarted() {
saveCaretRelativePosition();
myCaretModel.onBulkDocumentUpdateStarted();
mySoftWrapModel.onBulkDocumentUpdateStarted();
myFoldingModel.onBulkDocumentUpdateStarted();
}
private void bulkUpdateFinished() {
myFoldingModel.onBulkDocumentUpdateFinished();
mySoftWrapModel.onBulkDocumentUpdateFinished();
myCaretModel.onBulkDocumentUpdateFinished();
clearTextWidthCache();
setMouseSelectionState(MOUSE_SELECTION_STATE_NONE);
if (myUseNewRendering) {
myView.reset();
}
else {
mySizeContainer.reset();
}
validateSize();
updateGutterSize();
repaintToScreenBottom(0);
updateCaretCursor();
restoreCaretRelativePosition();
}
private void beforeChangedUpdate(@NotNull DocumentEvent e) {
myDocumentChangeInProgress = true;
if (isStickySelection()) {
setStickySelection(false);
}
if (myDocument.isInBulkUpdate()) {
// Assuming that the job is done at bulk listener callback methods.
return;
}
saveCaretRelativePosition();
// We assume that size container is already notified with the visual line widths during soft wraps processing
if (!mySoftWrapModel.isSoftWrappingEnabled() && !myUseNewRendering) {
mySizeContainer.beforeChange(e);
}
if (isZeroLatencyTypingEnabled() && myImmediateEditingInProgress && canPaintImmediately(e)) {
int offset = e.getOffset();
int length = e.getOldLength();
myOldArea = lineRectangleBetween(offset, offset + length);
myOldTailArea = lineRectangleBetween(offset + length, myDocument.getLineEndOffset(myDocument.getLineNumber(offset)));
if (myOldTailArea.isEmpty()) {
myOldTailArea.width += EditorUtil.getSpaceWidth(Font.PLAIN, this); // include possible caret
}
}
}
private void changedUpdate(DocumentEvent e) {
myDocumentChangeInProgress = false;
if (myDocument.isInBulkUpdate()) return;
if (isZeroLatencyTypingEnabled() && myImmediateEditingInProgress && canPaintImmediately(e)) {
paintImmediately(e);
}
if (myErrorStripeNeedsRepaint) {
myMarkupModel.repaint(e.getOffset(), e.getOffset() + e.getNewLength());
myErrorStripeNeedsRepaint = false;
}
clearTextWidthCache();
setMouseSelectionState(MOUSE_SELECTION_STATE_NONE);
// We assume that size container is already notified with the visual line widths during soft wraps processing
if (!mySoftWrapModel.isSoftWrappingEnabled() && !myUseNewRendering) {
mySizeContainer.changedUpdate(e);
}
validateSize();
int startLine = offsetToLogicalLine(e.getOffset());
int endLine = offsetToLogicalLine(e.getOffset() + e.getNewLength());
boolean painted = false;
if (myDocument.getTextLength() > 0) {
int startDocLine = myDocument.getLineNumber(e.getOffset());
int endDocLine = myDocument.getLineNumber(e.getOffset() + e.getNewLength());
if (e.getOldLength() > e.getNewLength() || startDocLine != endDocLine || StringUtil.indexOf(e.getOldFragment(), '\n') != -1) {
updateGutterSize();
}
if (countLineFeeds(e.getOldFragment()) != countLineFeeds(e.getNewFragment())) {
// Lines removed. Need to repaint till the end of the screen
repaintToScreenBottom(startLine);
painted = true;
}
}
updateCaretCursor();
if (!painted) {
repaintLines(startLine, endLine);
}
if (getCaretModel().getOffset() < e.getOffset() || getCaretModel().getOffset() > e.getOffset() + e.getNewLength()){
restoreCaretRelativePosition();
}
}
private void saveCaretRelativePosition() {
Rectangle visibleArea = getScrollingModel().getVisibleArea();
Point pos = visualPositionToXY(getCaretModel().getVisualPosition());
myCaretUpdateVShift = pos.y - visibleArea.y;
}
private void restoreCaretRelativePosition() {
Point caretLocation = visualPositionToXY(getCaretModel().getVisualPosition());
int scrollOffset = caretLocation.y - myCaretUpdateVShift;
getScrollingModel().disableAnimation();
getScrollingModel().scrollVertically(scrollOffset);
getScrollingModel().enableAnimation();
}
public boolean hasTabs() {
return !(myDocument instanceof DocumentImpl) || ((DocumentImpl)myDocument).mightContainTabs();
}
public boolean isScrollToCaret() {
return myScrollToCaret;
}
public void setScrollToCaret(boolean scrollToCaret) {
myScrollToCaret = scrollToCaret;
}
@NotNull
public Disposable getDisposable() {
return myDisposable;
}
private static int countLineFeeds(@NotNull CharSequence c) {
return StringUtil.countNewLines(c);
}
private boolean updatingSize; // accessed from EDT only
private void updateGutterSize() {
assertIsDispatchThread();
if (!updatingSize) {
updatingSize = true;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
if (!isDisposed()) {
myGutterComponent.updateSize();
}
}
finally {
updatingSize = false;
}
}
});
}
}
void validateSize() {
Dimension dim = getPreferredSize();
if (!dim.equals(myPreferredSize) && !myDocument.isInBulkUpdate()) {
dim = mySizeAdjustmentStrategy.adjust(dim, myPreferredSize, this);
if (dim == null) {
return;
}
myPreferredSize = dim;
myGutterComponent.updateSize();
myEditorComponent.setSize(dim);
myEditorComponent.fireResized();
myMarkupModel.recalcEditorDimensions();
myMarkupModel.repaint(-1, -1);
}
}
void recalculateSizeAndRepaint() {
if (!myUseNewRendering) mySizeContainer.reset();
validateSize();
myEditorComponent.repaintEditorComponent();
}
@Override
@NotNull
public DocumentEx getDocument() {
return myDocument;
}
@Override
@NotNull
public JComponent getComponent() {
return myPanel;
}
@Override
public void addEditorMouseListener(@NotNull EditorMouseListener listener) {
myMouseListeners.add(listener);
}
@Override
public void removeEditorMouseListener(@NotNull EditorMouseListener listener) {
boolean success = myMouseListeners.remove(listener);
LOG.assertTrue(success || isReleased);
}
@Override
public void addEditorMouseMotionListener(@NotNull EditorMouseMotionListener listener) {
myMouseMotionListeners.add(listener);
}
@Override
public void removeEditorMouseMotionListener(@NotNull EditorMouseMotionListener listener) {
boolean success = myMouseMotionListeners.remove(listener);
LOG.assertTrue(success || isReleased);
}
@Override
public boolean isStickySelection() {
return myStickySelection;
}
@Override
public void setStickySelection(boolean enable) {
myStickySelection = enable;
if (enable) {
myStickySelectionStart = getCaretModel().getOffset();
}
else {
mySelectionModel.removeSelection();
}
}
@Override
public boolean isDisposed() {
return isReleased;
}
public void stopDumbLater() {
if (ApplicationManager.getApplication().isUnitTestMode()) return;
final Runnable stopDumbRunnable = new Runnable() {
@Override
public void run() {
stopDumb();
}
};
ApplicationManager.getApplication().invokeLater(stopDumbRunnable, ModalityState.current());
}
void resetPaintersWidth() {
myLinePaintersWidth = 0;
}
private void stopDumb() {
putUserData(BUFFER, null);
}
/**
* {@link #stopDumbLater} or {@link #stopDumb} must be performed in finally
*/
public void startDumb() {
if (ApplicationManager.getApplication().isUnitTestMode()) return;
Rectangle rect = ((JViewport)myEditorComponent.getParent()).getViewRect();
BufferedImage image = UIUtil.createImage(rect.width, rect.height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = image.createGraphics();
graphics.translate(-rect.x, -rect.y);
graphics.setClip(rect.x, rect.y, rect.width, rect.height);
myEditorComponent.paintComponent(graphics);
graphics.dispose();
putUserData(BUFFER, image);
}
private static boolean isZeroLatencyTypingEnabled() {
return Registry.is("editor.zero.latency.typing");
}
private boolean canPaintImmediately(char c) {
return myDocument instanceof DocumentImpl &&
myHighlighter instanceof LexerEditorHighlighter &&
!mySelectionModel.hasSelection() &&
arePositionsWithinDocument(myCaretModel.getAllCarets()) &&
areVisualLinesUnique(myCaretModel.getAllCarets()) &&
!isInplaceRenamerActive() &&
!KEY_CHARS_TO_SKIP.contains(c);
}
private static boolean areVisualLinesUnique(List<Caret> carets) {
if (carets.size() > 1) {
TIntHashSet lines = new TIntHashSet(carets.size());
for (Caret caret : carets) {
if (!lines.add(caret.getVisualLineStart())) {
return false;
}
}
}
return true;
}
// Checks whether all the carets are within document or some of them are in a so called "virtual space".
private boolean arePositionsWithinDocument(List<Caret> carets) {
for (Caret caret : carets) {
if (caret.getLogicalPosition().compareTo(offsetToLogicalPosition(caret.getOffset())) != 0) {
return false;
}
}
return true;
}
// TODO Improve the approach - handle such cases in a more general way.
private boolean isInplaceRenamerActive() {
Key<?> key = Key.findKeyByName("EditorInplaceRenamer");
return key != null && key.isIn(this);
}
// Called to display a single character insertion before starting a write action and the general painting routine.
// Bypasses RepaintManager (c.repaint, c.paintComponent) and double buffering (g.paintImmediately) to minimize visual lag.
// TODO Should be replaced with the generic paintImmediately(event) call when we implement typing without starting write actions.
private void paintImmediately(int offset, char c, boolean insert) {
Graphics g = myEditorComponent.getGraphics();
if (g == null) return; // editor component is currently not displayable
TextAttributes attributes = ((LexerEditorHighlighter)myHighlighter).getAttributes((DocumentImpl)myDocument, offset, c);
int fontType = attributes.getFontType();
FontInfo fontInfo = EditorUtil.fontForChar(c, attributes.getFontType(), this);
Font font = fontInfo.getFont();
// it's more reliable to query actual font metrics
FontMetrics fontMetrics = getFontMetrics(fontType);
int charWidth = fontMetrics.charWidth(c);
int delta = charWidth;
if (!insert && offset < myDocument.getTextLength()) {
delta -= fontMetrics.charWidth(myDocument.getCharsSequence().charAt(offset));
}
Rectangle tailArea = lineRectangleBetween(offset, myDocument.getLineEndOffset(offsetToLogicalLine(offset)));
if (tailArea.isEmpty()) {
tailArea.width += EditorUtil.getSpaceWidth(fontType, this); // include caret
}
Color lineColor = getCaretRowBackground();
Rectangle newArea = lineRectangleBetween(offset, offset);
newArea.width += charWidth;
String newText = Character.toString(c);
Point point = newArea.getLocation();
int ascent = getAscent();
Color color = attributes.getForegroundColor() == null ? getForegroundColor() : attributes.getForegroundColor();
EditorUIUtil.setupAntialiasing(g);
// pre-compute all the arguments beforehand to minimize delays between the calls (as there's no double-buffering)
if (delta != 0) {
shift(g, tailArea, delta);
}
fill(g, newArea, lineColor);
print(g, newText, point, ascent, font, color);
}
private boolean canPaintImmediately(@NotNull DocumentEvent e) {
return myDocument instanceof DocumentImpl &&
!isInplaceRenamerActive() &&
!contains(e.getOldFragment(), '\n') &&
!contains(e.getNewFragment(), '\n') &&
!(e.getNewLength() == 1 && DOCUMENT_CHARS_TO_SKIP.contains(e.getNewFragment().charAt(0)));
}
private static boolean contains(@NotNull CharSequence chars, char c) {
for (int i = 0; i < chars.length(); i++) {
if (chars.charAt(i) == c) {
return true;
}
}
return false;
}
// Called to display insertion / deletion / replacement within a single line before the general painting routine.
// Bypasses RepaintManager (c.repaint, c.paintComponent) and double buffering (g.paintImmediately) to minimize visual lag.
private void paintImmediately(@NotNull DocumentEvent e) {
Graphics g = myEditorComponent.getGraphics();
if (g == null) return; // editor component is currently not displayable
int offset = e.getOffset();
String newText = e.getNewFragment().toString();
Rectangle newArea = lineRectangleBetween(offset, offset + newText.length());
int delta = newArea.width - myOldArea.width;
Color lineColor = getCaretRowBackground();
if (delta != 0) {
if (delta < 0) {
// Pre-paint carets at new positions, if needed, before shifting the tail area (to avoid flickering),
// because painting takes some time while copyArea is almost instantaneous.
CaretRectangle[] caretRectangles = myCaretCursor.getCaretLocations(true);
if (caretRectangles != null) {
for (CaretRectangle it : caretRectangles) {
Rectangle r = toRectangle(it);
if (myOldArea.contains(r) && !newArea.contains(r)) {
myCaretCursor.paintAt(g, it.myPoint.x - delta, it.myPoint.y, it.myWidth, it.myCaret);
}
}
}
}
shift(g, myOldTailArea, delta);
if (delta < 0) {
Rectangle remainingArea = new Rectangle(myOldTailArea.x + myOldTailArea.width + delta,
myOldTailArea.y, -delta, myOldTailArea.height);
fill(g, remainingArea, lineColor);
}
}
if (!newArea.isEmpty()) {
TextAttributes attributes = myHighlighter.createIterator(offset).getTextAttributes();
Point point = newArea.getLocation();
int ascent = getAscent();
// simplified font selection (based on the first character)
FontInfo fontInfo = EditorUtil.fontForChar(newText.charAt(0), attributes.getFontType(), this);
Font font = fontInfo.getFont();
Color color = attributes.getForegroundColor() == null ? getForegroundColor() : attributes.getForegroundColor();
EditorUIUtil.setupAntialiasing(g);
// pre-compute all the arguments beforehand to minimize delay between the calls (as there's no double-buffering)
fill(g, newArea, lineColor);
print(g, newText, point, ascent, font, color);
}
}
@NotNull
private Rectangle lineRectangleBetween(int begin, int end) {
Point p1 = offsetToXY(begin, false);
Point p2 = offsetToXY(end, false);
// When soft wrap is present, handle only the first visual line (for simplicity, yet it works reasonably well)
int x2 = p1.y == p2.y ? p2.x : Math.max(p1.x, myEditorComponent.getWidth() - getVerticalScrollBar().getWidth());
return new Rectangle(p1.x, p1.y, x2 - p1.x, getLineHeight());
}
@NotNull
private Rectangle toRectangle(@NotNull CaretRectangle caretRectangle) {
Point p = caretRectangle.myPoint;
return new Rectangle(p.x, p.y, caretRectangle.myWidth, getLineHeight());
}
@NotNull
private Color getCaretRowBackground() {
Color color = myScheme.getColor(EditorColors.CARET_ROW_COLOR);
return color == null ? getBackgroundColor() : color;
}
private static void shift(@NotNull Graphics g, @NotNull Rectangle r, int delta) {
g.copyArea(r.x, r.y, r.width, r.height, delta, 0);
}
private static void fill(@NotNull Graphics g, @NotNull Rectangle r, @NotNull Color color) {
g.setColor(color);
g.fillRect(r.x, r.y, r.width, r.height);
}
private static void print(@NotNull Graphics g, @NotNull String text, @NotNull Point point,
int ascent, @NotNull Font font, @NotNull Color color) {
g.setFont(font);
g.setColor(color);
g.drawString(text, point.x, point.y + ascent);
}
void paint(@NotNull Graphics2D g) {
Rectangle clip = g.getClipBounds();
if (clip == null) {
return;
}
if (Registry.is("editor.dumb.mode.available")) {
final BufferedImage buffer = getUserData(BUFFER);
if (buffer != null) {
final Rectangle rect = getContentComponent().getVisibleRect();
UIUtil.drawImage(g, buffer, null, rect.x, rect.y);
return;
}
}
if (myUpdateCursor) {
setCursorPosition();
myUpdateCursor = false;
}
if (isReleased) {
g.setColor(new JBColor(new Color(128, 255, 128), new Color(128, 255, 128)));
g.fillRect(clip.x, clip.y, clip.width, clip.height);
return;
}
if (myProject != null && myProject.isDisposed()) return;
if (myUseNewRendering) {
myView.paint(g);
}
else {
VisualPosition clipStartVisualPos = xyToVisualPosition(new Point(0, clip.y));
LogicalPosition clipStartPosition = visualToLogicalPosition(clipStartVisualPos);
int clipStartOffset = logicalPositionToOffset(clipStartPosition);
LogicalPosition clipEndPosition = xyToLogicalPosition(new Point(0, clip.y + clip.height + getLineHeight()));
int clipEndOffset = logicalPositionToOffset(clipEndPosition);
paintBackgrounds(g, clip, clipStartPosition, clipStartVisualPos, clipStartOffset, clipEndOffset);
if (paintPlaceholderText(g, clip)) {
paintCaretCursor(g);
return;
}
paintRightMargin(g, clip);
paintCustomRenderers(g, clipStartOffset, clipEndOffset);
MarkupModelEx docMarkup = (MarkupModelEx)DocumentMarkupModel.forDocument(myDocument, myProject, true);
paintLineMarkersSeparators(g, clip, docMarkup, clipStartOffset, clipEndOffset);
paintLineMarkersSeparators(g, clip, myMarkupModel, clipStartOffset, clipEndOffset);
paintText(g, clip, clipStartPosition, clipStartOffset, clipEndOffset);
paintSegmentHighlightersBorderAndAfterEndOfLine(g, clip, clipStartOffset, clipEndOffset, docMarkup);
BorderEffect borderEffect = new BorderEffect(this, g, clipStartOffset, clipEndOffset);
borderEffect.paintHighlighters(getHighlighter());
borderEffect.paintHighlighters(docMarkup);
borderEffect.paintHighlighters(myMarkupModel);
paintCaretCursor(g);
paintComposedTextDecoration(g);
}
}
private static final char IDEOGRAPHIC_SPACE = '\u3000'; // http://www.marathon-studios.com/unicode/U3000/Ideographic_Space
private static final String WHITESPACE_CHARS = " \t" + IDEOGRAPHIC_SPACE;
private void paintCustomRenderers(@NotNull final Graphics2D g, final int clipStartOffset, final int clipEndOffset) {
myMarkupModel.processRangeHighlightersOverlappingWith(clipStartOffset, clipEndOffset, new Processor<RangeHighlighterEx>() {
@Override
public boolean process(@NotNull RangeHighlighterEx highlighter) {
if (!highlighter.getEditorFilter().avaliableIn(EditorImpl.this)) return true;
final CustomHighlighterRenderer customRenderer = highlighter.getCustomRenderer();
if (customRenderer != null && clipStartOffset < highlighter.getEndOffset() && highlighter.getStartOffset() < clipEndOffset) {
customRenderer.paint(EditorImpl.this, highlighter, g);
}
return true;
}
});
}
@NotNull
@Override
public IndentsModel getIndentsModel() {
return myIndentsModel;
}
@Override
public void setHeaderComponent(JComponent header) {
myHeaderPanel.removeAll();
header = header == null ? getPermanentHeaderComponent() : header;
if (header != null) {
myHeaderPanel.add(header);
}
myHeaderPanel.revalidate();
}
@Override
public boolean hasHeaderComponent() {
JComponent header = getHeaderComponent();
return header != null && header != getPermanentHeaderComponent();
}
@Override
@Nullable
public JComponent getPermanentHeaderComponent() {
return getUserData(PERMANENT_HEADER);
}
@Override
public void setPermanentHeaderComponent(@Nullable JComponent component) {
putUserData(PERMANENT_HEADER, component);
}
@Override
@Nullable
public JComponent getHeaderComponent() {
if (myHeaderPanel.getComponentCount() > 0) {
return (JComponent)myHeaderPanel.getComponent(0);
}
return null;
}
@Override
public void setBackgroundColor(Color color) {
myScrollPane.setBackground(color);
if (getBackgroundIgnoreForced().equals(color)) {
myForcedBackground = null;
return;
}
myForcedBackground = color;
}
@NotNull
private Color getForegroundColor() {
return myScheme.getDefaultForeground();
}
@NotNull
@Override
public Color getBackgroundColor() {
if (myForcedBackground != null) return myForcedBackground;
return getBackgroundIgnoreForced();
}
@NotNull
@Override
public TextDrawingCallback getTextDrawingCallback() {
return myTextDrawingCallback;
}
@Override
public void setPlaceholder(@Nullable CharSequence text) {
myPlaceholderText = text;
}
@Override
public void setPlaceholderAttributes(@Nullable TextAttributes attributes) {
myPlaceholderAttributes = attributes;
}
public CharSequence getPlaceholder() {
return myPlaceholderText;
}
@Override
public void setShowPlaceholderWhenFocused(boolean show) {
myShowPlaceholderWhenFocused = show;
}
public boolean getShowPlaceholderWhenFocused() {
return myShowPlaceholderWhenFocused;
}
Color getBackgroundColor(@NotNull final TextAttributes attributes) {
final Color attrColor = attributes.getBackgroundColor();
return Comparing.equal(attrColor, myScheme.getDefaultBackground()) ? getBackgroundColor() : attrColor;
}
@NotNull
private Color getBackgroundIgnoreForced() {
Color color = myScheme.getDefaultBackground();
if (myDocument.isWritable()) {
return color;
}
Color readOnlyColor = myScheme.getColor(EditorColors.READONLY_BACKGROUND_COLOR);
return readOnlyColor != null ? readOnlyColor : color;
}
private void paintComposedTextDecoration(@NotNull Graphics2D g) {
TextRange composedTextRange = getComposedTextRange();
if (composedTextRange != null) {
VisualPosition visStart = offsetToVisualPosition(Math.min(composedTextRange.getStartOffset(), myDocument.getTextLength()));
int y = visibleLineToY(visStart.line) + getAscent() + 1;
Point p1 = visualPositionToXY(visStart);
Point p2 = logicalPositionToXY(offsetToLogicalPosition(Math.min(composedTextRange.getEndOffset(), myDocument.getTextLength())));
Stroke saved = g.getStroke();
BasicStroke dotted = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, new float[]{0, 2, 0, 2}, 0);
g.setStroke(dotted);
UIUtil.drawLine(g, p1.x, y, p2.x, y);
g.setStroke(saved);
}
}
@Nullable
public TextRange getComposedTextRange() {
return myInputMethodRequestsHandler == null || myInputMethodRequestsHandler.composedText == null ?
null : myInputMethodRequestsHandler.composedTextRange;
}
private void paintRightMargin(@NotNull Graphics g, @NotNull Rectangle clip) {
Color rightMargin = myScheme.getColor(EditorColors.RIGHT_MARGIN_COLOR);
if (!mySettings.isRightMarginShown() || rightMargin == null) {
return;
}
int x = mySettings.getRightMargin(myProject) * EditorUtil.getSpaceWidth(Font.PLAIN, this);
if (x >= clip.x && x < clip.x + clip.width) {
g.setColor(rightMargin);
UIUtil.drawLine(g, x, clip.y, x, clip.y + clip.height);
}
}
private void paintSegmentHighlightersBorderAndAfterEndOfLine(@NotNull final Graphics g,
@NotNull Rectangle clip,
int clipStartOffset,
int clipEndOffset,
@NotNull MarkupModelEx docMarkup) {
if (myDocument.getLineCount() == 0) return;
final int startLine = yPositionToVisibleLine(clip.y);
final int endLine = yPositionToVisibleLine(clip.y + clip.height) + 1;
Processor<RangeHighlighterEx> paintProcessor = new Processor<RangeHighlighterEx>() {
@Override
public boolean process(@NotNull RangeHighlighterEx highlighter) {
if (!highlighter.getEditorFilter().avaliableIn(EditorImpl.this)) return true;
paintSegmentHighlighterAfterEndOfLine(g, highlighter, startLine, endLine);
return true;
}
};
docMarkup.processRangeHighlightersOverlappingWith(clipStartOffset, clipEndOffset, paintProcessor);
myMarkupModel.processRangeHighlightersOverlappingWith(clipStartOffset, clipEndOffset, paintProcessor);
}
private void paintSegmentHighlighterAfterEndOfLine(@NotNull Graphics g,
@NotNull RangeHighlighterEx segmentHighlighter,
int startLine,
int endLine) {
if (!segmentHighlighter.isAfterEndOfLine()) {
return;
}
int startOffset = segmentHighlighter.getStartOffset();
int visibleStartLine = offsetToVisualLine(startOffset);
if (getFoldingModel().isOffsetCollapsed(startOffset)) {
return;
}
if (visibleStartLine >= startLine && visibleStartLine <= endLine) {
int logStartLine = offsetToLogicalLine(startOffset);
if (logStartLine >= myDocument.getLineCount()) {
return;
}
LogicalPosition logPosition = offsetToLogicalPosition(myDocument.getLineEndOffset(logStartLine));
Point end = logicalPositionToXY(logPosition);
int charWidth = EditorUtil.getSpaceWidth(Font.PLAIN, this);
int lineHeight = getLineHeight();
TextAttributes attributes = segmentHighlighter.getTextAttributes();
if (attributes != null && getBackgroundColor(attributes) != null) {
g.setColor(getBackgroundColor(attributes));
g.fillRect(end.x, end.y, charWidth, lineHeight);
}
if (attributes != null && attributes.getEffectColor() != null) {
int y = visibleLineToY(visibleStartLine) + getAscent() + 1;
g.setColor(attributes.getEffectColor());
if (attributes.getEffectType() == EffectType.WAVE_UNDERSCORE) {
UIUtil.drawWave((Graphics2D)g, new Rectangle(end.x, y, charWidth - 1, getDescent()- 1));
}
else if (attributes.getEffectType() == EffectType.BOLD_DOTTED_LINE) {
final int dottedAt = SystemInfo.isMac ? y - 1 : y;
UIUtil.drawBoldDottedLine((Graphics2D)g, end.x, end.x + charWidth - 1, dottedAt,
getBackgroundColor(attributes), attributes.getEffectColor(), false);
}
else if (attributes.getEffectType() == EffectType.STRIKEOUT) {
int y1 = y - getCharHeight() / 2 - 1;
UIUtil.drawLine(g, end.x, y1, end.x + charWidth - 1, y1);
}
else if (attributes.getEffectType() == EffectType.BOLD_LINE_UNDERSCORE) {
drawBoldLineUnderScore(g, end.x, y - 1, charWidth - 1);
}
else if (attributes.getEffectType() != EffectType.BOXED) {
UIUtil.drawLine(g, end.x, y, end.x + charWidth - 1, y);
}
}
}
}
private static void drawBoldLineUnderScore(Graphics g, int x, int y, int width) {
int height = JBUI.scale(Registry.intValue("editor.bold.underline.height", 2));
g.fillRect(x, y, width, height);
}
@Override
public int getMaxWidthInRange(int startOffset, int endOffset) {
if (myUseNewRendering) return myView.getMaxWidthInRange(startOffset, endOffset);
int width = 0;
int start = offsetToVisualLine(startOffset);
int end = offsetToVisualLine(endOffset);
for (int i = start; i <= end; i++) {
int lastColumn = EditorUtil.getLastVisualLineColumnNumber(this, i) + 1;
int lineWidth = visualPositionToXY(new VisualPosition(i, lastColumn)).x;
if (lineWidth > width) {
width = lineWidth;
}
}
return width;
}
private void paintBackgrounds(@NotNull Graphics g,
@NotNull Rectangle clip,
@NotNull LogicalPosition clipStartPosition,
@NotNull VisualPosition clipStartVisualPos,
int clipStartOffset, int clipEndOffset) {
Color defaultBackground = getBackgroundColor();
if (myEditorComponent.isOpaque()) {
g.setColor(defaultBackground);
g.fillRect(clip.x, clip.y, clip.width, clip.height);
}
Color prevBackColor = null;
int lineHeight = getLineHeight();
int visibleLine = yPositionToVisibleLine(clip.y);
Point position = new Point(0, visibleLine * lineHeight);
CharSequence prefixText = myPrefixText == null ? null : new CharArrayCharSequence(myPrefixText);
if (clipStartVisualPos.line == 0 && prefixText != null) {
Color backColor = myPrefixAttributes.getBackgroundColor();
position.x = drawBackground(g, backColor, prefixText, 0, prefixText.length(), position,
myPrefixAttributes.getFontType(),
defaultBackground, clip);
prevBackColor = backColor;
}
if (clipStartPosition.line >= myDocument.getLineCount() || clipStartPosition.line < 0) {
if (position.x > 0) flushBackground(g, clip);
return;
}
myLastBackgroundPosition = null;
myLastBackgroundColor = null;
mySelectionStartPosition = null;
mySelectionEndPosition = null;
int start = clipStartOffset;
if (!myPurePaintingMode) {
getSoftWrapModel().registerSoftWrapsIfNecessary();
}
LineIterator lIterator = createLineIterator();
lIterator.start(start);
if (lIterator.atEnd()) {
return;
}
IterationState iterationState = new IterationState(this, start, clipEndOffset, isPaintSelection());
TextAttributes attributes = iterationState.getMergedAttributes();
Color backColor = getBackgroundColor(attributes);
int fontType = attributes.getFontType();
int lastLineIndex = Math.max(0, myDocument.getLineCount() - 1);
// There is a possible case that we need to draw background from the start of soft wrap-introduced visual line. Given position
// has valid 'y' coordinate then at it shouldn't be affected by soft wrap that corresponds to the visual line start offset.
// Hence, we store information about soft wrap to be skipped for further processing and adjust 'x' coordinate value if necessary.
TIntHashSet softWrapsToSkip = new TIntHashSet();
SoftWrap softWrap = getSoftWrapModel().getSoftWrap(start);
if (softWrap != null) {
softWrapsToSkip.add(softWrap.getStart());
Color color = null;
if (backColor != null && !backColor.equals(defaultBackground)) {
color = backColor;
}
// There is a possible case that target clip points to soft wrap-introduced visual line and that it's an active
// line (caret cursor is located on it). We want to draw corresponding 'caret line' background for soft wraps-introduced
// virtual space then.
if (color == null && position.y == getCaretModel().getVisualPosition().line * getLineHeight()) {
color = mySettings.isCaretRowShown() ? getColorsScheme().getColor(EditorColors.CARET_ROW_COLOR) : null;
}
if (color != null) {
drawBackground(g, color, softWrap.getIndentInPixels(), position, defaultBackground, clip);
prevBackColor = color;
}
position.x = softWrap.getIndentInPixels();
}
// There is a possible case that caret is located at soft-wrapped line. We don't need to paint caret row background
// on a last visual line of that soft-wrapped line then. Below is a holder for the flag that indicates if caret row
// background is already drawn.
boolean[] caretRowPainted = new boolean[1];
CharSequence text = myDocument.getImmutableCharSequence();
while (!iterationState.atEnd() && !lIterator.atEnd()) {
int hEnd = iterationState.getEndOffset();
int lEnd = lIterator.getEnd();
if (hEnd >= lEnd) {
FoldRegion collapsedFolderAt = myFoldingModel.getCollapsedRegionAtOffset(start);
if (collapsedFolderAt == null) {
position.x = drawSoftWrapAwareBackground(g, backColor, prevBackColor, text, start, lEnd - lIterator.getSeparatorLength(),
position, fontType, defaultBackground, clip, softWrapsToSkip, caretRowPainted);
prevBackColor = backColor;
paintAfterLineEndBackgroundSegments(g, iterationState, position, defaultBackground, lineHeight);
if (lIterator.getLineNumber() < lastLineIndex) {
if (backColor != null && !backColor.equals(defaultBackground)) {
g.setColor(backColor);
g.fillRect(position.x, position.y, clip.x + clip.width - position.x, lineHeight);
}
}
else {
if (iterationState.hasPastFileEndBackgroundSegments()) {
paintAfterLineEndBackgroundSegments(g, iterationState, position, defaultBackground, lineHeight);
}
paintAfterFileEndBackground(iterationState,
g,
position, clip,
lineHeight, defaultBackground, caretRowPainted);
break;
}
position.x = 0;
if (position.y > clip.y + clip.height) break;
position.y += lineHeight;
start = lEnd;
}
else if (collapsedFolderAt.getEndOffset() == clipEndOffset) {
drawCollapsedFolderBackground(g, clip, defaultBackground, prevBackColor, position, backColor, fontType, softWrapsToSkip, caretRowPainted, text,
collapsedFolderAt);
prevBackColor = backColor;
}
lIterator.advance();
}
else {
FoldRegion collapsedFolderAt = iterationState.getCurrentFold();
if (collapsedFolderAt != null) {
drawCollapsedFolderBackground(g, clip, defaultBackground, prevBackColor, position, backColor, fontType, softWrapsToSkip, caretRowPainted, text,
collapsedFolderAt);
prevBackColor = backColor;
}
else if (hEnd > lEnd - lIterator.getSeparatorLength()) {
position.x = drawSoftWrapAwareBackground(
g, backColor, prevBackColor, text, start, lEnd - lIterator.getSeparatorLength(), position, fontType,
defaultBackground, clip, softWrapsToSkip, caretRowPainted
);
prevBackColor = backColor;
}
else {
position.x = drawSoftWrapAwareBackground(
g, backColor, prevBackColor, text, start, hEnd, position, fontType, defaultBackground, clip, softWrapsToSkip, caretRowPainted
);
prevBackColor = backColor;
}
iterationState.advance();
attributes = iterationState.getMergedAttributes();
backColor = getBackgroundColor(attributes);
fontType = attributes.getFontType();
start = iterationState.getStartOffset();
}
}
flushBackground(g, clip);
if (lIterator.getLineNumber() >= lastLineIndex && position.y <= clip.y + clip.height) {
paintAfterFileEndBackground(iterationState, g, position, clip, lineHeight, defaultBackground, caretRowPainted);
}
// Perform additional activity if soft wrap is added or removed during repainting.
if (mySoftWrapsChanged) {
mySoftWrapsChanged = false;
clearTextWidthCache();
validateSize();
// Repaint editor to the bottom in order to ensure that its content is shown correctly after new soft wrap introduction.
repaintToScreenBottom(EditorUtil.yPositionToLogicalLine(this, position));
// Repaint gutter at all space that is located after active clip in order to ensure that line numbers are correctly redrawn
// in accordance with the newly introduced soft wrap(s).
myGutterComponent.repaint(0, clip.y, myGutterComponent.getWidth(), myGutterComponent.getHeight() - clip.y);
}
}
private void drawCollapsedFolderBackground(@NotNull Graphics g,
@NotNull Rectangle clip,
@NotNull Color defaultBackground,
@Nullable Color prevBackColor,
@NotNull Point position,
@NotNull Color backColor,
int fontType,
@NotNull TIntHashSet softWrapsToSkip,
@NotNull boolean[] caretRowPainted,
@NotNull CharSequence text,
@NotNull FoldRegion collapsedFolderAt) {
SoftWrap softWrap = mySoftWrapModel.getSoftWrap(collapsedFolderAt.getStartOffset());
if (softWrap != null) {
position.x = drawSoftWrapAwareBackground(
g, backColor, prevBackColor, text, collapsedFolderAt.getStartOffset(), collapsedFolderAt.getStartOffset(), position, fontType,
defaultBackground, clip, softWrapsToSkip, caretRowPainted
);
}
CharSequence chars = collapsedFolderAt.getPlaceholderText();
position.x = drawBackground(g, backColor, chars, 0, chars.length(), position, fontType, defaultBackground, clip);
}
private void paintAfterLineEndBackgroundSegments(@NotNull Graphics g,
@NotNull IterationState iterationState,
@NotNull Point position,
@NotNull Color defaultBackground,
int lineHeight) {
while (iterationState.hasPastLineEndBackgroundSegment()) {
TextAttributes backgroundAttributes = iterationState.getPastLineEndBackgroundAttributes();
int width = EditorUtil.getSpaceWidth(backgroundAttributes.getFontType(), this) * iterationState.getPastLineEndBackgroundSegmentWidth();
Color color = getBackgroundColor(backgroundAttributes);
if (color != null && !color.equals(defaultBackground)) {
g.setColor(color);
g.fillRect(position.x, position.y, width, lineHeight);
}
position.x += width;
iterationState.advanceToNextPastLineEndBackgroundSegment();
}
}
private void paintAfterFileEndBackground(@NotNull IterationState iterationState,
@NotNull Graphics g,
@NotNull Point position,
@NotNull Rectangle clip,
int lineHeight,
@NotNull Color defaultBackground,
@NotNull boolean[] caretRowPainted) {
Color backColor = iterationState.getPastFileEndBackground();
if (backColor == null || backColor.equals(defaultBackground)) {
return;
}
if (caretRowPainted[0] && backColor.equals(getColorsScheme().getColor(EditorColors.CARET_ROW_COLOR))) {
return;
}
g.setColor(backColor);
g.fillRect(position.x, position.y, clip.x + clip.width - position.x, lineHeight);
}
private int drawSoftWrapAwareBackground(@NotNull Graphics g,
@Nullable Color backColor,
@Nullable Color prevBackColor,
@NotNull CharSequence text,
int start,
int end,
@NotNull Point position,
@JdkConstants.FontStyle int fontType,
@NotNull Color defaultBackground,
@NotNull Rectangle clip,
@NotNull TIntHashSet softWrapsToSkip,
@NotNull boolean[] caretRowPainted) {
int startToUse = start;
// Given 'end' offset is exclusive though SoftWrapModel.getSoftWrapsForRange() uses inclusive end offset.
// Hence, we decrement it if necessary. Please note that we don't do that if start is equal to end. That is the case,
// for example, for soft-wrapped collapsed fold region - we need to draw soft wrap before it.
int softWrapRetrievalEndOffset = end;
if (end > start) {
softWrapRetrievalEndOffset--;
}
List<? extends SoftWrap> softWraps = getSoftWrapModel().getSoftWrapsForRange(start, softWrapRetrievalEndOffset);
for (SoftWrap softWrap : softWraps) {
int softWrapStart = softWrap.getStart();
if (softWrapsToSkip.contains(softWrapStart)) {
continue;
}
if (startToUse < softWrapStart) {
position.x = drawBackground(g, backColor, text, startToUse, softWrapStart, position, fontType, defaultBackground, clip);
}
boolean drawCustomBackgroundAtSoftWrapVirtualSpace =
!Comparing.equal(backColor, defaultBackground) && (softWrapStart > start || Comparing.equal(prevBackColor, backColor));
drawSoftWrap(
g, softWrap, position, fontType, backColor, drawCustomBackgroundAtSoftWrapVirtualSpace, defaultBackground, clip, caretRowPainted
);
startToUse = softWrapStart;
}
if (startToUse < end) {
position.x = drawBackground(g, backColor, text, startToUse, end, position, fontType, defaultBackground, clip);
}
return position.x;
}
private void drawSoftWrap(@NotNull Graphics g,
@NotNull SoftWrap softWrap,
@NotNull Point position,
@JdkConstants.FontStyle int fontType,
@Nullable Color backColor,
boolean drawCustomBackgroundAtSoftWrapVirtualSpace,
@NotNull Color defaultBackground,
@NotNull Rectangle clip,
@NotNull boolean[] caretRowPainted) {
// The main idea is to to do the following:
// *) update given drawing position coordinates in accordance with the current soft wrap;
// *) draw background at soft wrap-introduced virtual space if necessary;
CharSequence softWrapText = softWrap.getText();
int activeRowY = getCaretModel().getVisualPosition().line * getLineHeight();
int afterSoftWrapWidth = clip.x + clip.width - position.x;
if (drawCustomBackgroundAtSoftWrapVirtualSpace && backColor != null) {
drawBackground(g, backColor, afterSoftWrapWidth, position, defaultBackground, clip);
}
else if (position.y == activeRowY) {
// Draw 'active line' background after soft wrap.
Color caretRowColor = mySettings.isCaretRowShown()? getColorsScheme().getColor(EditorColors.CARET_ROW_COLOR) : null;
drawBackground(g, caretRowColor, afterSoftWrapWidth, position, defaultBackground, clip);
caretRowPainted[0] = true;
}
paintSelectionOnFirstSoftWrapLineIfNecessary(g, position, clip, defaultBackground, fontType);
int i = CharArrayUtil.lastIndexOf(softWrapText, "\n", softWrapText.length()) + 1;
int width = getTextSegmentWidth(softWrapText, i, softWrapText.length(), 0, fontType, clip)
+ getSoftWrapModel().getMinDrawingWidthInPixels(SoftWrapDrawingType.AFTER_SOFT_WRAP);
position.x = 0;
position.y += getLineHeight();
if (drawCustomBackgroundAtSoftWrapVirtualSpace && backColor != null) {
drawBackground(g, backColor, width, position, defaultBackground, clip);
}
else if (position.y == activeRowY) {
// Draw 'active line' background for the soft wrap-introduced virtual space.
Color caretRowColor = mySettings.isCaretRowShown()? getColorsScheme().getColor(EditorColors.CARET_ROW_COLOR) : null;
drawBackground(g, caretRowColor, width, position, defaultBackground, clip);
}
position.x = 0;
paintSelectionOnSecondSoftWrapLineIfNecessary(g, position, clip, defaultBackground, fontType, softWrap);
position.x = width;
}
private VisualPosition getSelectionStartPositionForPaint() {
if (mySelectionStartPosition == null) {
// We cache the value to avoid repeated invocations of Editor.logicalPositionToOffset which is currently slow for long lines
mySelectionStartPosition = getSelectionModel().getSelectionStartPosition();
}
return mySelectionStartPosition;
}
private VisualPosition getSelectionEndPositionForPaint() {
if (mySelectionEndPosition == null) {
// We cache the value to avoid repeated invocations of Editor.logicalPositionToOffset which is currently slow for long lines
mySelectionEndPosition = getSelectionModel().getSelectionEndPosition();
}
return mySelectionEndPosition;
}
/**
* End user is allowed to perform selection by visual coordinates (e.g. by dragging mouse with left button hold). There is a possible
* case that such a move intersects with soft wrap introduced virtual space. We want to draw corresponding selection background
* there then.
* <p/>
* This method encapsulates functionality of drawing selection background on the first soft wrap line (e.g. on a visual line where
* it is applied).
*
* @param g graphics to draw on
* @param position current position (assumed to be position of soft wrap appliance)
* @param clip target drawing area boundaries
* @param defaultBackground default background
* @param fontType current font type
*/
private void paintSelectionOnFirstSoftWrapLineIfNecessary(@NotNull Graphics g,
@NotNull Point position,
@NotNull Rectangle clip,
@NotNull Color defaultBackground,
@JdkConstants.FontStyle int fontType) {
// There is a possible case that the user performed selection at soft wrap virtual space. We need to paint corresponding background
// there then.
VisualPosition selectionStartPosition = getSelectionStartPositionForPaint();
VisualPosition selectionEndPosition = getSelectionEndPositionForPaint();
if (selectionStartPosition.equals(selectionEndPosition)) {
return;
}
int currentVisualLine = position.y / getLineHeight();
int lastColumn = EditorUtil.getLastVisualLineColumnNumber(this, currentVisualLine);
// Check if the first soft wrap line is within the visual selection.
if (currentVisualLine < selectionStartPosition.line || currentVisualLine > selectionEndPosition.line
|| currentVisualLine == selectionEndPosition.line && selectionEndPosition.column <= lastColumn) {
return;
}
// Adjust 'x' if selection starts at soft wrap virtual space.
final int columnsToSkip = selectionStartPosition.column - lastColumn;
if (columnsToSkip > 0) {
position.x += getSoftWrapModel().getMinDrawingWidthInPixels(SoftWrapDrawingType.BEFORE_SOFT_WRAP_LINE_FEED);
position.x += (columnsToSkip - 1) * EditorUtil.getSpaceWidth(Font.PLAIN, this);
}
// Calculate selection width.
final int width;
if (selectionEndPosition.line > currentVisualLine) {
width = clip.x + clip.width - position.x;
}
else if (selectionStartPosition.line < currentVisualLine || selectionStartPosition.column <= lastColumn) {
width = getSoftWrapModel().getMinDrawingWidthInPixels(SoftWrapDrawingType.BEFORE_SOFT_WRAP_LINE_FEED)
+ (selectionEndPosition.column - lastColumn - 1) * EditorUtil.getSpaceWidth(fontType, this);
}
else {
width = (selectionEndPosition.column - selectionStartPosition.column) * EditorUtil.getSpaceWidth(fontType, this);
}
drawBackground(g, getColorsScheme().getColor(EditorColors.SELECTION_BACKGROUND_COLOR), width, position, defaultBackground, clip);
}
/**
* End user is allowed to perform selection by visual coordinates (e.g. by dragging mouse with left button hold). There is a possible
* case that such a move intersects with soft wrap introduced virtual space. We want to draw corresponding selection background
* there then.
* <p/>
* This method encapsulates functionality of drawing selection background on the second soft wrap line (e.g. on a visual line after
* the one where it is applied).
*
* @param g graphics to draw on
* @param position current position (assumed to be position of soft wrap appliance)
* @param clip target drawing area boundaries
* @param defaultBackground default background
* @param fontType current font type
* @param softWrap target soft wrap which second line virtual space may contain selection
*/
private void paintSelectionOnSecondSoftWrapLineIfNecessary(@NotNull Graphics g,
@NotNull Point position,
@NotNull Rectangle clip,
@NotNull Color defaultBackground,
@JdkConstants.FontStyle int fontType,
@NotNull SoftWrap softWrap) {
// There is a possible case that the user performed selection at soft wrap virtual space. We need to paint corresponding background
// there then.
VisualPosition selectionStartPosition = getSelectionStartPositionForPaint();
VisualPosition selectionEndPosition = getSelectionEndPositionForPaint();
if (selectionStartPosition.equals(selectionEndPosition)) {
return;
}
int currentVisualLine = position.y / getLineHeight();
// Check if the second soft wrap line is within the visual selection.
if (currentVisualLine < selectionStartPosition.line || currentVisualLine > selectionEndPosition.line
|| currentVisualLine == selectionStartPosition.line && selectionStartPosition.column >= softWrap.getIndentInColumns()) {
return;
}
// Adjust 'x' if selection starts at soft wrap virtual space.
if (selectionStartPosition.line == currentVisualLine && selectionStartPosition.column > 0) {
position.x += selectionStartPosition.column * EditorUtil.getSpaceWidth(fontType, this);
}
// Calculate selection width.
final int width;
if (selectionEndPosition.line > currentVisualLine || selectionEndPosition.column >= softWrap.getIndentInColumns()) {
width = softWrap.getIndentInPixels() - position.x;
}
else {
width = selectionEndPosition.column * EditorUtil.getSpaceWidth(fontType, this) - position.x;
}
drawBackground(g, getColorsScheme().getColor(EditorColors.SELECTION_BACKGROUND_COLOR), width, position, defaultBackground, clip);
}
private int drawBackground(@NotNull Graphics g,
Color backColor,
@NotNull CharSequence text,
int start,
int end,
@NotNull Point position,
@JdkConstants.FontStyle int fontType,
@NotNull Color defaultBackground,
@NotNull Rectangle clip) {
int width = getTextSegmentWidth(text, start, end, position.x, fontType, clip);
return drawBackground(g, backColor, width, position, defaultBackground, clip);
}
private int drawBackground(@NotNull Graphics g,
@Nullable Color backColor,
int width,
@NotNull Point position,
@NotNull Color defaultBackground,
@NotNull Rectangle clip) {
if (backColor != null && !backColor.equals(defaultBackground) && clip.intersects(position.x, position.y, width, getLineHeight())) {
if (backColor.equals(myLastBackgroundColor) && myLastBackgroundPosition.y == position.y &&
myLastBackgroundPosition.x + myLastBackgroundWidth == position.x) {
myLastBackgroundWidth += width;
}
else {
flushBackground(g, clip);
myLastBackgroundColor = backColor;
myLastBackgroundPosition = new Point(position);
myLastBackgroundWidth = width;
}
}
return position.x + width;
}
private void flushBackground(@NotNull Graphics g, @NotNull final Rectangle clip) {
if (myLastBackgroundColor != null) {
final Point position = myLastBackgroundPosition;
final int w = myLastBackgroundWidth;
final int height = getLineHeight();
if (clip.intersects(position.x, position.y, w, height)) {
g.setColor(myLastBackgroundColor);
g.fillRect(position.x, position.y, w, height);
}
myLastBackgroundColor = null;
}
}
@NotNull
private LineIterator createLineIterator() {
return myDocument.createLineIterator();
}
private void paintText(@NotNull Graphics g,
@NotNull Rectangle clip,
@NotNull LogicalPosition clipStartPosition,
int clipStartOffset,
int clipEndOffset) {
myCurrentFontType = null;
myLastCache = null;
int lineHeight = getLineHeight();
int visibleLine = clip.y / lineHeight;
int startLine = clipStartPosition.line;
int start = clipStartOffset;
Point position = new Point(0, visibleLine * lineHeight);
if (startLine == 0 && myPrefixText != null) {
position.x = drawStringWithSoftWraps(g, new CharArrayCharSequence(myPrefixText), 0, myPrefixText.length, position, clip,
myPrefixAttributes.getEffectColor(), myPrefixAttributes.getEffectType(),
myPrefixAttributes.getFontType(), myPrefixAttributes.getForegroundColor(), -1,
PAINT_NO_WHITESPACE);
}
if (startLine >= myDocument.getLineCount() || startLine < 0) {
if (position.x > 0) flushCachedChars(g);
return;
}
LineIterator lIterator = createLineIterator();
lIterator.start(start);
if (lIterator.atEnd()) {
return;
}
IterationState iterationState = new IterationState(this, start, clipEndOffset, isPaintSelection());
TextAttributes attributes = iterationState.getMergedAttributes();
Color currentColor = attributes.getForegroundColor();
if (currentColor == null) {
currentColor = getForegroundColor();
}
Color effectColor = attributes.getEffectColor();
EffectType effectType = attributes.getEffectType();
int fontType = attributes.getFontType();
g.setColor(currentColor);
CharSequence chars = myDocument.getImmutableCharSequence();
LineWhitespacePaintingStrategy context = new LineWhitespacePaintingStrategy();
context.update(chars, lIterator);
while (!iterationState.atEnd() && !lIterator.atEnd()) {
int hEnd = iterationState.getEndOffset();
int lEnd = lIterator.getEnd();
if (hEnd >= lEnd) {
FoldRegion collapsedFolderAt = myFoldingModel.getCollapsedRegionAtOffset(start);
if (collapsedFolderAt == null) {
drawStringWithSoftWraps(g, chars, start, lEnd - lIterator.getSeparatorLength(), position, clip, effectColor,
effectType, fontType, currentColor, clipStartOffset, context);
final VirtualFile file = getVirtualFile();
if (myProject != null && file != null && !isOneLineMode()) {
int offset = position.x;
for (EditorLinePainter painter : EditorLinePainter.EP_NAME.getExtensions()) {
Collection<LineExtensionInfo> extensions = painter.getLineExtensions(myProject, file, lIterator.getLineNumber());
if (extensions != null && !extensions.isEmpty()) {
for (LineExtensionInfo info : extensions) {
final String text = info.getText();
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
offset += EditorUtil.charWidth(ch, Font.ITALIC, this);
}
position.x = drawString(g, text, 0, text.length(), position, clip,
info.getEffectColor() == null ? effectColor : info.getEffectColor(),
info.getEffectType() == null ? effectType : info.getEffectType(),
info.getFontType(),
info.getColor() == null ? currentColor : info.getColor(),
context);
}
}
}
myLinePaintersWidth = Math.max(myLinePaintersWidth, offset);
}
position.x = 0;
if (position.y > clip.y + clip.height) {
break;
}
position.y += lineHeight;
start = lEnd;
}
// myBorderEffect.eolReached(g, this);
lIterator.advance();
if (!lIterator.atEnd()) {
context.update(chars, lIterator);
}
}
else {
FoldRegion collapsedFolderAt = iterationState.getCurrentFold();
if (collapsedFolderAt != null) {
SoftWrap softWrap = mySoftWrapModel.getSoftWrap(collapsedFolderAt.getStartOffset());
if (softWrap != null) {
position.x = drawStringWithSoftWraps(
g, chars, collapsedFolderAt.getStartOffset(), collapsedFolderAt.getStartOffset(), position, clip, effectColor, effectType,
fontType, currentColor, clipStartOffset, context
);
}
int foldingXStart = position.x;
position.x = drawString(
g, collapsedFolderAt.getPlaceholderText(), position, clip, effectColor, effectType, fontType, currentColor,
PAINT_NO_WHITESPACE);
//drawStringWithSoftWraps(g, collapsedFolderAt.getPlaceholderText(), position, clip, effectColor, effectType,
// fontType, currentColor, logicalPosition);
BorderEffect.paintFoldedEffect(g, foldingXStart, position.y, position.x, getLineHeight(), effectColor, effectType);
}
else {
position.x = drawStringWithSoftWraps(g, chars, start, Math.min(hEnd, lEnd - lIterator.getSeparatorLength()), position, clip,
effectColor, effectType, fontType, currentColor, clipStartOffset, context);
}
iterationState.advance();
attributes = iterationState.getMergedAttributes();
currentColor = attributes.getForegroundColor();
if (currentColor == null) {
currentColor = getForegroundColor();
}
effectColor = attributes.getEffectColor();
effectType = attributes.getEffectType();
fontType = attributes.getFontType();
start = iterationState.getStartOffset();
}
}
FoldRegion collapsedFolderAt = iterationState.getCurrentFold();
if (collapsedFolderAt != null) {
int foldingXStart = position.x;
int foldingXEnd = drawStringWithSoftWraps(
g, collapsedFolderAt.getPlaceholderText(), position, clip, effectColor, effectType, fontType, currentColor, clipStartOffset,
PAINT_NO_WHITESPACE);
BorderEffect.paintFoldedEffect(g, foldingXStart, position.y, foldingXEnd, getLineHeight(), effectColor, effectType);
// myBorderEffect.collapsedFolderReached(g, this);
}
final SoftWrap softWrap = mySoftWrapModel.getSoftWrap(clipEndOffset);
if (softWrap != null) {
mySoftWrapModel.paint(g, SoftWrapDrawingType.BEFORE_SOFT_WRAP_LINE_FEED, position.x, position.y, getLineHeight());
}
flushCachedChars(g);
}
private boolean paintPlaceholderText(@NotNull Graphics g, @NotNull Rectangle clip) {
CharSequence hintText = myPlaceholderText;
if (myDocument.getTextLength() > 0 || hintText == null || hintText.length() == 0) {
return false;
}
if (KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() == myEditorComponent && !myShowPlaceholderWhenFocused) {
// There is a possible case that placeholder text was painted and the editor gets focus now. We want to over-paint previously
// used placeholder text then.
myLastBackgroundColor = getBackgroundColor();
myLastBackgroundPosition = new Point(0, 0);
myLastBackgroundWidth = myLastPaintedPlaceholderWidth;
flushBackground(g, clip);
return false;
}
else {
hintText = SwingUtilities.layoutCompoundLabel(g.getFontMetrics(), hintText.toString(), null, 0, 0, 0, 0,
myEditorComponent.getBounds(), new Rectangle(), new Rectangle(), 0);
myLastPaintedPlaceholderWidth = drawString(
g, hintText, 0, hintText.length(), new Point(0, 0), clip, null, null,
myPlaceholderAttributes == null ? Font.PLAIN : myPlaceholderAttributes.getFontType(),
myPlaceholderAttributes == null ? myFoldingModel.getPlaceholderAttributes().getForegroundColor() :
myPlaceholderAttributes.getForegroundColor(),
PAINT_NO_WHITESPACE
);
flushCachedChars(g);
return true;
}
}
private boolean isPaintSelection() {
return myPaintSelection || !isOneLineMode() || IJSwingUtilities.hasFocus(getContentComponent());
}
public void setPaintSelection(boolean paintSelection) {
myPaintSelection = paintSelection;
}
@Override
@NotNull
@NonNls
public String dumpState() {
return "prefix: '" + (myPrefixText == null ? "none" : new String(myPrefixText))
+ "', allow caret inside tab: " + mySettings.isCaretInsideTabs()
+ ", allow caret after line end: " + mySettings.isVirtualSpace()
+ ", soft wraps: " + (mySoftWrapModel.isSoftWrappingEnabled() ? "on" : "off")
+ ", soft wraps data: " + getSoftWrapModel().dumpState()
+ "\n\nfolding data: " + getFoldingModel().dumpState()
+ (myDocument instanceof DocumentImpl ? "\n\ndocument info: " + ((DocumentImpl)myDocument).dumpState() : "")
+ "\nfont preferences: " + myScheme.getFontPreferences();
}
private class CachedFontContent {
private final CharSequence[] data = new CharSequence[CACHED_CHARS_BUFFER_SIZE];
private final int[] starts = new int[CACHED_CHARS_BUFFER_SIZE];
private final int[] ends = new int[CACHED_CHARS_BUFFER_SIZE];
private final int[] x = new int[CACHED_CHARS_BUFFER_SIZE];
private final int[] y = new int[CACHED_CHARS_BUFFER_SIZE];
private final Color[] color = new Color[CACHED_CHARS_BUFFER_SIZE];
private final boolean[] whitespaceShown = new boolean[CACHED_CHARS_BUFFER_SIZE];
private int myCount;
@NotNull private final FontInfo myFontType;
private final boolean myHasBreakSymbols;
private final int spaceWidth;
@Nullable private CharSequence myLastData;
private CachedFontContent(@NotNull FontInfo fontInfo) {
myFontType = fontInfo;
spaceWidth = fontInfo.charWidth(' ');
myHasBreakSymbols = fontInfo.hasGlyphsToBreakDrawingIteration();
}
private void flushContent(@NotNull Graphics g) {
if (myCount != 0) {
if (myCurrentFontType != myFontType) {
myCurrentFontType = myFontType;
g.setFont(myFontType.getFont());
}
Color currentColor = null;
for (int i = 0; i < myCount; i++) {
if (!Comparing.equal(color[i], currentColor)) {
currentColor = color[i] != null ? color[i] : JBColor.black;
g.setColor(currentColor);
}
drawChars(g, data[i], starts[i], ends[i], x[i], y[i], whitespaceShown[i]);
color[i] = null;
data[i] = null;
}
myCount = 0;
myLastData = null;
}
}
private void addContent(@NotNull Graphics g, CharSequence _data, int _start, int _end, int _x, int _y, @Nullable Color _color, boolean drawWhitespace) {
final int count = myCount;
if (count > 0) {
final int lastCount = count - 1;
final Color lastColor = color[lastCount];
if (_data == myLastData && _start == ends[lastCount] && (_color == null || lastColor == null || _color.equals(lastColor))
&& _y == y[lastCount] /* there is a possible case that vertical position is adjusted because of soft wrap */
&& (!myHasBreakSymbols || !myFontType.getSymbolsToBreakDrawingIteration().contains(_data.charAt(ends[lastCount] - 1)))
&& (!myDisableRtl || _start < 1 || _start >= _data.length() || !isRtlCharacter(_data.charAt(_start)) && !isRtlCharacter(_data.charAt(_start - 1)))
&& drawWhitespace == whitespaceShown[lastCount]) {
ends[lastCount] = _end;
if (lastColor == null) color[lastCount] = _color;
return;
}
}
myLastData = _data;
data[count] = _data;
x[count] = _x;
y[count] = _y;
starts[count] = _start;
ends[count] = _end;
color[count] = _color;
whitespaceShown[count] = drawWhitespace;
myCount++;
if (count >= CACHED_CHARS_BUFFER_SIZE - 1) {
flushContent(g);
}
}
}
private static boolean isRtlCharacter(char c) {
byte directionality = Character.getDirectionality(c);
return directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT
|| directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC
|| directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING
|| directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE;
}
private void flushCachedChars(@NotNull Graphics g) {
for (CachedFontContent cache : myFontCache) {
cache.flushContent(g);
}
myLastCache = null;
}
private void paintCaretCursor(@NotNull Graphics g) {
// There is a possible case that visual caret position is changed because of newly added or removed soft wraps.
// We check if that's the case and ask caret model to recalculate visual position if necessary.
myCaretCursor.paint(g);
}
@Nullable
public CaretRectangle[] getCaretLocations(boolean onlyIfShown) {
return myCaretCursor.getCaretLocations(onlyIfShown);
}
private void paintLineMarkersSeparators(@NotNull final Graphics g,
@NotNull final Rectangle clip,
@NotNull MarkupModelEx markupModel,
int clipStartOffset,
int clipEndOffset) {
markupModel.processRangeHighlightersOverlappingWith(clipStartOffset, clipEndOffset, new Processor<RangeHighlighterEx>() {
@Override
public boolean process(@NotNull RangeHighlighterEx lineMarker) {
if (!lineMarker.getEditorFilter().avaliableIn(EditorImpl.this)) return true;
paintLineMarkerSeparator(lineMarker, clip, g);
return true;
}
});
}
private void paintLineMarkerSeparator(@NotNull RangeHighlighter marker, @NotNull Rectangle clip, @NotNull Graphics g) {
Color separatorColor = marker.getLineSeparatorColor();
LineSeparatorRenderer lineSeparatorRenderer = marker.getLineSeparatorRenderer();
if (separatorColor == null && lineSeparatorRenderer == null) {
return;
}
int line = marker.getLineSeparatorPlacement() == SeparatorPlacement.TOP ? marker.getDocument()
.getLineNumber(marker.getStartOffset()) : marker.getDocument().getLineNumber(marker.getEndOffset());
if (line < 0 || line >= myDocument.getLineCount()) {
return;
}
// There is a possible case that particular logical line occupies more than one visual line (because of soft wraps processing),
// hence, we need to consider that during calculating 'y' position for the last visual line used for the target logical
// line representation.
int y;
SeparatorPlacement placement = marker.getLineSeparatorPlacement();
if (placement == SeparatorPlacement.TOP) {
y = visibleLineToY(logicalToVisualLine(line));
}
else if (line + 1 >= myDocument.getLineCount()) {
y = visibleLineToY(offsetToVisualLine(myDocument.getTextLength()) + 1);
}
else {
y = logicalLineToY(line + 1);
}
y -= 1;
if (y + getLineHeight() < clip.y || y > clip.y + clip.height) return;
int endShift = clip.x + clip.width;
g.setColor(separatorColor);
if (mySettings.isRightMarginShown() && myScheme.getColor(EditorColors.RIGHT_MARGIN_COLOR) != null) {
endShift = Math.min(endShift, mySettings.getRightMargin(myProject) * EditorUtil.getSpaceWidth(Font.PLAIN, this));
}
if (lineSeparatorRenderer != null) {
lineSeparatorRenderer.drawLine(g, 0, endShift, y);
}
else {
UIUtil.drawLine(g, 0, y, endShift, y);
}
}
private int drawStringWithSoftWraps(@NotNull Graphics g,
@NotNull final String text,
@NotNull Point position,
@NotNull Rectangle clip,
Color effectColor,
EffectType effectType,
@JdkConstants.FontStyle int fontType,
Color fontColor,
int startDrawingOffset,
WhitespacePaintingStrategy context) {
return drawStringWithSoftWraps(g, text, 0, text.length(), position, clip, effectColor, effectType,
fontType, fontColor, startDrawingOffset, context);
}
private int drawStringWithSoftWraps(@NotNull Graphics g,
final CharSequence text,
int start,
final int end,
@NotNull Point position,
@NotNull Rectangle clip,
Color effectColor,
EffectType effectType,
@JdkConstants.FontStyle int fontType,
Color fontColor,
int startDrawingOffset,
WhitespacePaintingStrategy context) {
if (start >= end && getSoftWrapModel().getSoftWrap(start) == null) {
return position.x;
}
// Given 'end' offset is exclusive though SoftWrapModel.getSoftWrapsForRange() uses inclusive end offset.
// Hence, we decrement it if necessary. Please note that we don't do that if start is equal to end. That is the case,
// for example, for soft-wrapped collapsed fold region - we need to draw soft wrap before it.
int softWrapRetrievalEndOffset = end;
if (start < end) {
softWrapRetrievalEndOffset--;
}
outer:
for (SoftWrap softWrap : getSoftWrapModel().getSoftWrapsForRange(start, softWrapRetrievalEndOffset)) {
char[] softWrapChars = softWrap.getChars();
CharArrayCharSequence softWrapSeq = new CharArrayCharSequence(softWrapChars);
if (softWrap.getStart() == startDrawingOffset) {
// If we are here that means that we are located on soft wrap-introduced visual line just after soft wrap. Hence, we need
// to draw soft wrap indent if any and 'after soft wrap' sign.
int i = CharArrayUtil.lastIndexOf(softWrapChars, '\n', 0, softWrapChars.length);
if (i < softWrapChars.length - 1) {
position.x = 0; // Soft wrap starts new visual line
position.x = drawString(
g, softWrapSeq, i + 1, softWrapChars.length, position, clip, null, null, fontType, fontColor, context
);
}
position.x += mySoftWrapModel.paint(g, SoftWrapDrawingType.AFTER_SOFT_WRAP, position.x, position.y, getLineHeight());
continue;
}
// Draw token text before the wrap.
if (softWrap.getStart() > start) {
position.x = drawString(
g, text, start, softWrap.getStart(), position, clip, null, null, fontType, fontColor, context
);
}
start = softWrap.getStart();
// We don't draw every soft wrap symbol one-by-one but whole visual line. Current variable holds index that points
// to the first soft wrap symbol that is not drawn yet.
int softWrapSegmentStartIndex = 0;
for (int i = 0; i < softWrapChars.length; i++) {
// Delay soft wraps symbols drawing until EOL is found.
if (softWrapChars[i] != '\n') {
continue;
}
// Draw soft wrap symbols on current visual line if any.
if (i - softWrapSegmentStartIndex > 0) {
drawString(
g, softWrapSeq, softWrapSegmentStartIndex, i, position, clip, null, null, fontType, fontColor, context
);
}
mySoftWrapModel.paint(g, SoftWrapDrawingType.BEFORE_SOFT_WRAP_LINE_FEED, position.x, position.y, getLineHeight());
// Reset 'x' coordinate because of new line start.
position.x = 0;
// Stop the processing if we drew the whole clip.
if (position.y > clip.y + clip.height) {
break outer;
}
position.y += getLineHeight();
softWrapSegmentStartIndex = i + 1;
}
// Draw remaining soft wrap symbols from its last line if any.
if (softWrapSegmentStartIndex < softWrapChars.length) {
position.x += drawString(
g, softWrapSeq, softWrapSegmentStartIndex, softWrapChars.length, position, clip, null, null, fontType, fontColor, context
);
}
position.x += mySoftWrapModel.paint(g, SoftWrapDrawingType.AFTER_SOFT_WRAP, position.x, position.y, getLineHeight());
}
return position.x = drawString(g, text, start, end, position, clip, effectColor, effectType, fontType, fontColor, context);
}
private int drawString(@NotNull Graphics g,
final CharSequence text,
int start,
int end,
@NotNull Point position,
@NotNull Rectangle clip,
@Nullable Color effectColor,
@Nullable EffectType effectType,
@JdkConstants.FontStyle int fontType,
Color fontColor,
WhitespacePaintingStrategy context) {
if (start >= end) return position.x;
boolean isInClip = getLineHeight() + position.y >= clip.y && position.y <= clip.y + clip.height;
if (!isInClip) return position.x;
int y = getAscent() + position.y;
int x = position.x;
return drawTabbedString(g, text, start, end, x, y, effectColor, effectType, fontType, fontColor, clip, context);
}
public int getAscent() {
if (myUseNewRendering) return myView.getAscent();
return getLineHeight() - getDescent();
}
private int drawString(@NotNull Graphics g,
@NotNull String text,
@NotNull Point position,
@NotNull Rectangle clip,
Color effectColor,
EffectType effectType,
@JdkConstants.FontStyle int fontType,
Color fontColor,
WhitespacePaintingStrategy context) {
boolean isInClip = getLineHeight() + position.y >= clip.y && position.y <= clip.y + clip.height;
if (!isInClip) return position.x;
int y = getAscent() + position.y;
int x = position.x;
return drawTabbedString(g, text, 0, text.length(), x, y, effectColor, effectType, fontType, fontColor, clip, context);
}
private int drawTabbedString(@NotNull Graphics g,
CharSequence text,
int start,
int end,
int x,
int y,
@Nullable Color effectColor,
EffectType effectType,
@JdkConstants.FontStyle int fontType,
Color fontColor,
@NotNull final Rectangle clip,
WhitespacePaintingStrategy context) {
int xStart = x;
for (int i = start; i < end; i++) {
if (text.charAt(i) != '\t') continue;
x = drawTablessString(text, start, i, g, x, y, fontType, fontColor, clip, context);
int x1 = EditorUtil.nextTabStop(x, this);
drawTabPlacer(g, y, x, x1, i, context);
x = x1;
start = i + 1;
}
x = drawTablessString(text, start, end, g, x, y, fontType, fontColor, clip, context);
if (effectColor != null) {
final Color savedColor = g.getColor();
// myBorderEffect.flushIfCantProlong(g, this, effectType, effectColor);
int xEnd = x;
if (xStart < clip.x && xEnd < clip.x || xStart > clip.x + clip.width && xEnd > clip.x + clip.width) {
return x;
}
if (xEnd > clip.x + clip.width) {
xEnd = clip.x + clip.width;
}
if (xStart < clip.x) {
xStart = clip.x;
}
if (effectType == EffectType.LINE_UNDERSCORE) {
g.setColor(effectColor);
UIUtil.drawLine(g, xStart, y + 1, xEnd, y + 1);
g.setColor(savedColor);
}
else if (effectType == EffectType.BOLD_LINE_UNDERSCORE) {
g.setColor(effectColor);
drawBoldLineUnderScore(g, xStart, y, xEnd-xStart);
g.setColor(savedColor);
}
else if (effectType == EffectType.STRIKEOUT) {
g.setColor(effectColor);
int y1 = y - getCharHeight() / 2;
UIUtil.drawLine(g, xStart, y1, xEnd, y1);
g.setColor(savedColor);
}
else if (effectType == EffectType.WAVE_UNDERSCORE) {
g.setColor(effectColor);
UIUtil.drawWave((Graphics2D)g, new Rectangle(xStart, y+1, xEnd - xStart, getDescent() - 1));
g.setColor(savedColor);
}
else if (effectType == EffectType.BOLD_DOTTED_LINE) {
final Color bgColor = getBackgroundColor();
final int dottedAt = SystemInfo.isMac ? y : y + 1;
UIUtil.drawBoldDottedLine((Graphics2D)g, xStart, xEnd, dottedAt, bgColor, effectColor, false);
}
}
return x;
}
private int drawTablessString(final CharSequence text,
int start,
final int end,
@NotNull final Graphics g,
int x,
final int y,
@JdkConstants.FontStyle final int fontType,
final Color fontColor,
@NotNull final Rectangle clip,
WhitespacePaintingStrategy context) {
int endX = x;
if (start < end) {
FontInfo font = null;
boolean drawWhitespace = false;
for (int j = start; j < end; j++) {
if (x > clip.x + clip.width) {
return endX;
}
final char c = text.charAt(j);
FontInfo newFont = EditorUtil.fontForChar(c, fontType, this);
boolean newDrawWhitespace = context.showWhitespaceAtOffset(j);
boolean isRtlChar = myDisableRtl && isRtlCharacter(c);
if (j > start && (endX < clip.x || endX > clip.x + clip.width || newFont != font || newDrawWhitespace != drawWhitespace || isRtlChar)) {
if (isOverlappingRange(clip, x, endX)) {
drawCharsCached(g, text, start, j, x, y, fontType, fontColor, drawWhitespace);
}
start = j;
x = endX;
}
font = newFont;
drawWhitespace = newDrawWhitespace;
endX += font.charWidth(c);
if (font.hasGlyphsToBreakDrawingIteration() && font.getSymbolsToBreakDrawingIteration().contains(c) || isRtlChar) {
drawCharsCached(g, text, start, j + 1, x, y, fontType, fontColor, drawWhitespace);
start = j + 1;
x = endX;
}
}
if (isOverlappingRange(clip, x, endX)) {
drawCharsCached(g, text, start, end, x, y, fontType, fontColor, drawWhitespace);
}
}
return endX;
}
private static boolean isOverlappingRange(Rectangle clip, int xStart, int xEnd) {
return !(xStart < clip.x && xEnd < clip.x || xStart > clip.x + clip.width && xEnd > clip.x + clip.width);
}
private void drawTabPlacer(Graphics g, int y, int start, int stop, int offset, WhitespacePaintingStrategy context) {
if (context.showWhitespaceAtOffset(offset)) {
myTabPainter.paint(g, y, start, stop);
}
}
private void drawCharsCached(@NotNull Graphics g,
CharSequence data,
int start,
int end,
int x,
int y,
@JdkConstants.FontStyle int fontType,
Color color,
boolean drawWhitespace) {
FontInfo fnt = EditorUtil.fontForChar(data.charAt(start), fontType, this);
if (myLastCache != null && spacesOnly(data, start, end) && fnt.charWidth(' ') == myLastCache.spaceWidth) {
// we don't care about font if we only need to paint spaces and space width matches
myLastCache.addContent(g, data, start, end, x, y, null, drawWhitespace);
}
else {
drawCharsCached(g, data, start, end, x, y, fnt, color, drawWhitespace);
}
}
private void drawCharsCached(@NotNull Graphics g,
@NotNull CharSequence data,
int start,
int end,
int x,
int y,
@NotNull FontInfo fnt,
Color color,
boolean drawWhitespace) {
CachedFontContent cache = null;
for (CachedFontContent fontCache : myFontCache) {
if (fontCache.myFontType == fnt) {
cache = fontCache;
break;
}
}
if (cache == null) {
cache = new CachedFontContent(fnt);
myFontCache.add(cache);
}
myLastCache = cache;
cache.addContent(g, data, start, end, x, y, color, drawWhitespace);
}
private static boolean spacesOnly(CharSequence chars, int start, int end) {
for (int i = start; i < end; i++) {
if (chars.charAt(i) != ' ') return false;
}
return true;
}
private void drawChars(@NotNull Graphics g, CharSequence data, int start, int end, int x, int y, boolean drawWhitespace) {
g.drawString(data.subSequence(start, end).toString(), x, y);
if (drawWhitespace) {
Color oldColor = g.getColor();
g.setColor(myScheme.getColor(EditorColors.WHITESPACES_COLOR));
final FontMetrics metrics = g.getFontMetrics();
for (int i = start; i < end; i++) {
final char c = data.charAt(i);
final int charWidth = isOracleRetina ? GraphicsUtil.charWidth(c, g.getFont()) : metrics.charWidth(c);
if (c == ' ') {
g.fillRect(x + (charWidth >> 1), y, 1, 1);
} else if (c == IDEOGRAPHIC_SPACE) {
final int charHeight = getCharHeight();
g.drawRect(x + 2, y - charHeight, charWidth - 4, charHeight);
}
x += charWidth;
}
g.setColor(oldColor);
}
}
private int getTextSegmentWidth(@NotNull CharSequence text,
int start,
int end,
int xStart,
@JdkConstants.FontStyle int fontType,
@NotNull Rectangle clip) {
int x = xStart;
for (int i = start; i < end && xStart < clip.x + clip.width; i++) {
char c = text.charAt(i);
if (c == '\t') {
x = EditorUtil.nextTabStop(x, this);
}
else {
x += EditorUtil.charWidth(c, fontType, this);
}
if (x > clip.x + clip.width) {
break;
}
}
return x - xStart;
}
@Override
public int getLineHeight() {
if (myUseNewRendering) return myView.getLineHeight();
assertReadAccess();
int lineHeight = myLineHeight;
if (lineHeight < 0) {
FontMetrics fontMetrics = myEditorComponent.getFontMetrics(myScheme.getFont(EditorFontType.PLAIN));
int fontMetricsHeight = fontMetrics.getHeight();
lineHeight = (int)(fontMetricsHeight * (isOneLineMode() ? 1 : myScheme.getLineSpacing()));
if (lineHeight <= 0) {
lineHeight = fontMetricsHeight;
if (lineHeight <= 0) {
lineHeight = 12;
}
}
assert lineHeight > 0 : lineHeight;
myLineHeight = lineHeight;
}
return lineHeight;
}
public int getDescent() {
if (myUseNewRendering) return myView.getDescent();
if (myDescent != -1) {
return myDescent;
}
FontMetrics fontMetrics = myEditorComponent.getFontMetrics(myScheme.getFont(EditorFontType.PLAIN));
myDescent = fontMetrics.getDescent();
return myDescent;
}
@NotNull
public FontMetrics getFontMetrics(@JdkConstants.FontStyle int fontType) {
if (myPlainFontMetrics == null) {
assertIsDispatchThread();
myPlainFontMetrics = myEditorComponent.getFontMetrics(myScheme.getFont(EditorFontType.PLAIN));
myBoldFontMetrics = myEditorComponent.getFontMetrics(myScheme.getFont(EditorFontType.BOLD));
myItalicFontMetrics = myEditorComponent.getFontMetrics(myScheme.getFont(EditorFontType.ITALIC));
myBoldItalicFontMetrics = myEditorComponent.getFontMetrics(myScheme.getFont(EditorFontType.BOLD_ITALIC));
}
if (fontType == Font.PLAIN) return myPlainFontMetrics;
if (fontType == Font.BOLD) return myBoldFontMetrics;
if (fontType == Font.ITALIC) return myItalicFontMetrics;
if (fontType == (Font.BOLD | Font.ITALIC)) return myBoldItalicFontMetrics;
LOG.error("Unknown font type: " + fontType);
return myPlainFontMetrics;
}
private int getCharHeight() {
if (myUseNewRendering) return myView.getCharHeight();
if (myCharHeight == -1) {
assertIsDispatchThread();
FontMetrics fontMetrics = myEditorComponent.getFontMetrics(myScheme.getFont(EditorFontType.PLAIN));
myCharHeight = fontMetrics.charWidth('a');
}
return myCharHeight;
}
public int getPreferredHeight() {
if (ourIsUnitTestMode && getUserData(DO_DOCUMENT_UPDATE_TEST) == null) {
return 1;
}
if (isOneLineMode()) return getLineHeight();
// Preferred height of less than a single line height doesn't make sense:
// at least a single line with a blinking caret on it is to be displayed
int size = Math.max(getVisibleLineCount(), 1) * getLineHeight();
if (mySettings.isAdditionalPageAtBottom()) {
int lineHeight = getLineHeight();
int visibleAreaHeight = getScrollingModel().getVisibleArea().height;
// There is a possible case that user with 'show additional page at bottom' scrolls to that virtual page; switched to another
// editor (another tab); and then returns to the previously used editor (the one scrolled to virtual page). We want to preserve
// correct view size then because viewport position is set to the end of the original text otherwise.
if (visibleAreaHeight > 0 || myVirtualPageHeight <= 0) {
myVirtualPageHeight = Math.max(visibleAreaHeight - 2 * lineHeight, lineHeight);
}
return size + Math.max(myVirtualPageHeight, 0);
}
return size + mySettings.getAdditionalLinesCount() * getLineHeight();
}
public Dimension getPreferredSize() {
if (myUseNewRendering) return myView.getPreferredSize();
if (ourIsUnitTestMode && getUserData(DO_DOCUMENT_UPDATE_TEST) == null) {
return new Dimension(1, 1);
}
final Dimension draft = getSizeWithoutCaret();
final int additionalSpace = shouldRespectAdditionalColumns()
? mySettings.getAdditionalColumnsCount() * EditorUtil.getSpaceWidth(Font.PLAIN, this)
: 0;
if (!myDocument.isInBulkUpdate()) {
for (Caret caret : myCaretModel.getAllCarets()) {
if (caret.isUpToDate()) {
int caretX = visualPositionToXY(caret.getVisualPosition()).x;
draft.width = Math.max(caretX, draft.width);
}
}
}
draft.width += additionalSpace;
return draft;
}
private boolean shouldRespectAdditionalColumns() {
return !mySoftWrapModel.isSoftWrappingEnabled()
|| mySoftWrapModel.isRespectAdditionalColumns()
|| mySizeContainer.getContentSize().getWidth() > myScrollingModel.getVisibleArea().getWidth();
}
private Dimension getSizeWithoutCaret() {
Dimension size = mySizeContainer.getContentSize();
return new Dimension(size.width, getPreferredHeight());
}
@NotNull
@Override
public Dimension getContentSize() {
if (myUseNewRendering) return myView.getPreferredSize();
Dimension size = mySizeContainer.getContentSize();
return new Dimension(size.width, size.height + mySettings.getAdditionalLinesCount() * getLineHeight());
}
@NotNull
@Override
public JScrollPane getScrollPane() {
return myScrollPane;
}
@Override
public void setBorder(Border border) {
myScrollPane.setBorder(border);
}
@Override
public Insets getInsets() {
return myScrollPane.getInsets();
}
@Override
public int logicalPositionToOffset(@NotNull LogicalPosition pos) {
return logicalPositionToOffset(pos, true);
}
@Override
public int logicalPositionToOffset(@NotNull LogicalPosition pos, boolean softWrapAware) {
if (myUseNewRendering) return myView.logicalPositionToOffset(pos);
if (softWrapAware) {
return mySoftWrapModel.logicalPositionToOffset(pos);
}
assertReadAccess();
if (myDocument.getLineCount() == 0) return 0;
if (pos.line < 0) throw new IndexOutOfBoundsException("Wrong line: " + pos.line);
if (pos.column < 0) throw new IndexOutOfBoundsException("Wrong column:" + pos.column);
if (pos.line >= myDocument.getLineCount()) {
return myDocument.getTextLength();
}
int start = myDocument.getLineStartOffset(pos.line);
if (pos.column == 0) return start;
int end = myDocument.getLineEndOffset(pos.line);
int x = getDocument().getLineNumber(start) == 0 ? getPrefixTextWidthInPixels() : 0;
int result = EditorUtil.calcSoftWrapUnawareOffset(this, myDocument.getImmutableCharSequence(), start, end, pos.column,
EditorUtil.getTabSize(this), x, new int[]{0}, null);
if (result >= 0) {
return result;
}
return end;
}
@Override
public void setLastColumnNumber(int val) {
assertIsDispatchThread();
myLastColumnNumber = val;
}
@Override
public int getLastColumnNumber() {
assertReadAccess();
return myLastColumnNumber;
}
/**
* @return information about total number of lines that can be viewed by user. I.e. this is a number of all document
* lines (considering that single logical document line may be represented on multiple visual lines because of
* soft wraps appliance) minus number of folded lines
*/
public int getVisibleLineCount() {
return getVisibleLogicalLinesCount() + getSoftWrapModel().getSoftWrapsIntroducedLinesNumber();
}
/**
* @return number of visible logical lines. Generally, that is a total logical lines number minus number of folded lines
*/
private int getVisibleLogicalLinesCount() {
return getDocument().getLineCount() - myFoldingModel.getFoldedLinesCountBefore(getDocument().getTextLength() + 1);
}
@Override
@NotNull
public VisualPosition logicalToVisualPosition(@NotNull LogicalPosition logicalPos) {
return logicalToVisualPosition(logicalPos, true);
}
@Override
@NotNull
public VisualPosition logicalToVisualPosition(@NotNull LogicalPosition logicalPos, boolean softWrapAware) {
if (myUseNewRendering) return myView.logicalToVisualPosition(logicalPos, false);
return doLogicalToVisualPosition(logicalPos, softWrapAware,0);
}
@NotNull
private VisualPosition doLogicalToVisualPosition(@NotNull LogicalPosition logicalPos, boolean softWrapAware,
// TODO den remove as soon as the problem is fixed.
int stackDepth) {
assertReadAccess();
if (!myFoldingModel.isFoldingEnabled() && !mySoftWrapModel.isSoftWrappingEnabled()) {
return new VisualPosition(logicalPos.line, logicalPos.column);
}
int offset = logicalPositionToOffset(logicalPos);
FoldRegion outermostCollapsed = myFoldingModel.getCollapsedRegionAtOffset(offset);
if (outermostCollapsed != null && offset > outermostCollapsed.getStartOffset()) {
if (offset < getDocument().getTextLength()) {
offset = outermostCollapsed.getStartOffset();
LogicalPosition foldStart = offsetToLogicalPosition(offset);
// TODO den remove as soon as the problem is fixed.
if (stackDepth > 15) {
LOG.error("Detected potential StackOverflowError at logical->visual position mapping. Given logical position: '" +
logicalPos + "'. State: " + dumpState());
stackDepth = -1;
}
return doLogicalToVisualPosition(foldStart, true, stackDepth+1);
}
else {
offset = outermostCollapsed.getEndOffset() + 3; // WTF?
}
}
int line = logicalPos.line;
int column = logicalPos.column;
int foldedLinesCountBefore = myFoldingModel.getFoldedLinesCountBefore(offset);
line -= foldedLinesCountBefore;
if (line < 0) {
LogMessageEx.error(
LOG, "Invalid LogicalPosition -> VisualPosition processing", String.format(
"Given logical position: %s; matched line: %d; fold lines before: %d, state: %s",
logicalPos, line, foldedLinesCountBefore, dumpState()
));
}
FoldRegion[] topLevel = myFoldingModel.fetchTopLevel();
LogicalPosition anchorFoldingPosition = logicalPos;
for (int idx = myFoldingModel.getLastCollapsedRegionBefore(offset); idx >= 0 && topLevel != null; idx--) {
FoldRegion region = topLevel[idx];
if (region.isValid()) {
if (region.getDocument().getLineNumber(region.getEndOffset()) == anchorFoldingPosition.line && region.getEndOffset() <= offset) {
LogicalPosition foldStart = offsetToLogicalPosition(region.getStartOffset());
LogicalPosition foldEnd = offsetToLogicalPosition(region.getEndOffset());
column += foldStart.column + region.getPlaceholderText().length() - foldEnd.column;
offset = region.getStartOffset();
anchorFoldingPosition = foldStart;
}
else {
break;
}
}
}
VisualPosition softWrapUnawarePosition = new VisualPosition(line, Math.max(0, column));
if (softWrapAware) {
return mySoftWrapModel.adjustVisualPosition(logicalPos, softWrapUnawarePosition);
}
return softWrapUnawarePosition;
}
@Nullable
private FoldRegion getLastCollapsedBeforePosition(@NotNull VisualPosition visualPos) {
FoldRegion[] topLevelCollapsed = myFoldingModel.fetchTopLevel();
if (topLevelCollapsed == null) return null;
int start = 0;
int end = topLevelCollapsed.length - 1;
int i = 0;
while (start <= end) {
i = (start + end) / 2;
FoldRegion region = topLevelCollapsed[i];
if (!region.isValid()) {
// Folding model is inconsistent (update in progress).
return null;
}
int regionVisualLine = offsetToVisualLine(region.getEndOffset() - 1);
if (regionVisualLine < visualPos.line) {
start = i + 1;
}
else {
if (regionVisualLine > visualPos.line) {
end = i - 1;
}
else {
VisualPosition visFoldEnd = offsetToVisualPosition(region.getEndOffset() - 1);
if (visFoldEnd.column < visualPos.column) {
start = i + 1;
}
else {
if (visFoldEnd.column > visualPos.column) {
end = i - 1;
}
else {
i--;
break;
}
}
}
}
}
while (i >= 0 && i < topLevelCollapsed.length) {
if (topLevelCollapsed[i].isValid()) break;
i--;
}
if (i >= 0 && i < topLevelCollapsed.length) {
FoldRegion region = topLevelCollapsed[i];
VisualPosition visFoldEnd = offsetToVisualPosition(region.getEndOffset() - 1);
if (visFoldEnd.line > visualPos.line || visFoldEnd.line == visualPos.line && visFoldEnd.column > visualPos.column) {
i--;
if (i >= 0) {
return topLevelCollapsed[i];
}
return null;
}
return region;
}
return null;
}
@Override
@NotNull
public LogicalPosition visualToLogicalPosition(@NotNull VisualPosition visiblePos) {
return visualToLogicalPosition(visiblePos, true);
}
@Override
@NotNull
public LogicalPosition visualToLogicalPosition(@NotNull VisualPosition visiblePos, boolean softWrapAware) {
if (myUseNewRendering) return myView.visualToLogicalPosition(visiblePos);
assertReadAccess();
if (softWrapAware) {
return mySoftWrapModel.visualToLogicalPosition(visiblePos);
}
if (!myFoldingModel.isFoldingEnabled()) return new LogicalPosition(visiblePos.line, visiblePos.column);
int line = visiblePos.line;
int column = visiblePos.column;
FoldRegion lastCollapsedBefore = getLastCollapsedBeforePosition(visiblePos);
if (lastCollapsedBefore != null) {
int logFoldEndLine = offsetToLogicalLine(lastCollapsedBefore.getEndOffset());
int visFoldEndLine = logicalToVisualLine(logFoldEndLine);
line = logFoldEndLine + visiblePos.line - visFoldEndLine;
if (visFoldEndLine == visiblePos.line) {
LogicalPosition logFoldEnd = offsetToLogicalPosition(lastCollapsedBefore.getEndOffset(), false);
VisualPosition visFoldEnd = logicalToVisualPosition(logFoldEnd, false);
if (visiblePos.column >= visFoldEnd.column) {
column = logFoldEnd.column + visiblePos.column - visFoldEnd.column;
}
else {
return offsetToLogicalPosition(lastCollapsedBefore.getStartOffset(), false);
}
}
}
if (column < 0) column = 0;
return new LogicalPosition(line, column);
}
int offsetToLogicalLine(int offset) {
int textLength = myDocument.getTextLength();
if (textLength == 0) return 0;
if (offset > textLength || offset < 0) {
throw new IndexOutOfBoundsException("Wrong offset: " + offset + " textLength: " + textLength);
}
int lineIndex = myDocument.getLineNumber(offset);
LOG.assertTrue(lineIndex >= 0 && lineIndex < myDocument.getLineCount());
return lineIndex;
}
@Override
public int calcColumnNumber(int offset, int lineIndex) {
return calcColumnNumber(offset, lineIndex, true, myDocument.getImmutableCharSequence());
}
public int calcColumnNumber(int offset, int lineIndex, boolean softWrapAware, @NotNull CharSequence documentCharSequence) {
if (myUseNewRendering) return myView.offsetToLogicalPosition(offset).column;
if (myDocument.getTextLength() == 0) return 0;
int lineStartOffset = myDocument.getLineStartOffset(lineIndex);
if (lineStartOffset == offset) return 0;
int lineEndOffset = myDocument.getLineEndOffset(lineIndex);
if (lineEndOffset < offset) offset = lineEndOffset; // handling the case when offset is inside non-normalized line terminator
int column = EditorUtil.calcColumnNumber(this, documentCharSequence, lineStartOffset, offset);
if (softWrapAware) {
int line = offsetToLogicalLine(offset);
return mySoftWrapModel.adjustLogicalPosition(new LogicalPosition(line, column), offset).column;
}
else {
return column;
}
}
private LogicalPosition getLogicalPositionForScreenPos(int x, int y, boolean trimToLineWidth) {
if (x < 0) {
x = 0;
}
LogicalPosition pos = xyToLogicalPosition(new Point(x, y));
int column = pos.column;
int line = pos.line;
int softWrapLinesBeforeTargetLogicalLine = pos.softWrapLinesBeforeCurrentLogicalLine;
int softWrapLinesOnTargetLogicalLine = pos.softWrapLinesOnCurrentLogicalLine;
int softWrapColumns = pos.softWrapColumnDiff;
boolean leansForward = pos.leansForward;
boolean leansRight = pos.visualPositionLeansRight;
final int totalLines = myDocument.getLineCount();
if (totalLines <= 0) {
return new LogicalPosition(0, 0);
}
if (line >= totalLines && totalLines > 0) {
int visibleLineCount = getVisibleLineCount();
int newY = visibleLineCount > 0 ? visibleLineToY(visibleLineCount - 1) : 0;
if (newY > 0 && newY == y) {
newY = visibleLineToY(getVisibleLogicalLinesCount());
}
if (newY >= y) {
LogMessageEx.error(LOG, "cycled moveCaretToScreenPos() detected",
String.format("x=%d, y=%d\nvisibleLineCount=%d, newY=%d\nstate=%s", x, y, visibleLineCount, newY, dumpState()));
throw new IllegalStateException("cycled moveCaretToScreenPos() detected");
}
return getLogicalPositionForScreenPos(x, newY, trimToLineWidth);
}
if (!mySettings.isVirtualSpace() && trimToLineWidth) {
int lineEndOffset = myDocument.getLineEndOffset(line);
int lineEndColumn = calcColumnNumber(lineEndOffset, line);
if (column > lineEndColumn) {
column = lineEndColumn;
leansForward = true;
leansRight = true;
if (softWrapColumns != 0) {
softWrapColumns -= column - lineEndColumn;
}
}
}
if (!mySettings.isCaretInsideTabs()) {
int offset = logicalPositionToOffset(new LogicalPosition(line, column));
CharSequence text = myDocument.getImmutableCharSequence();
if (offset >= 0 && offset < myDocument.getTextLength()) {
if (text.charAt(offset) == '\t') {
column = calcColumnNumber(offset, line);
}
}
}
return pos.visualPositionAware ?
new LogicalPosition(
line, column, softWrapLinesBeforeTargetLogicalLine, softWrapLinesOnTargetLogicalLine, softWrapColumns,
pos.foldedLines, pos.foldingColumnDiff, leansForward, leansRight
) :
new LogicalPosition(line, column, leansForward);
}
private VisualPosition getTargetPosition(int x, int y, boolean trimToLineWidth) {
if (myDocument.getLineCount() == 0) {
return new VisualPosition(0, 0);
}
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
int visualLineCount = getVisibleLineCount();
if (yPositionToVisibleLine(y) >= visualLineCount) {
y = visibleLineToY(Math.max(0, visualLineCount - 1));
}
VisualPosition visualPosition = xyToVisualPosition(new Point(x, y));
if (trimToLineWidth && !mySettings.isVirtualSpace()) {
LogicalPosition logicalPosition = visualToLogicalPosition(visualPosition);
LogicalPosition lineEndPosition = offsetToLogicalPosition(myDocument.getLineEndOffset(logicalPosition.line));
if (logicalPosition.column > lineEndPosition.column) {
visualPosition = logicalToVisualPosition(lineEndPosition.leanForward(true));
}
}
return visualPosition;
}
private boolean checkIgnore(@NotNull MouseEvent e, boolean isFinalCheck) {
if (!myIgnoreMouseEventsConsecutiveToInitial) {
myInitialMouseEvent = null;
return false;
}
if (myInitialMouseEvent!= null && (e.getComponent() != myInitialMouseEvent.getComponent() || !e.getPoint().equals(myInitialMouseEvent.getPoint()))) {
myIgnoreMouseEventsConsecutiveToInitial = false;
myInitialMouseEvent = null;
return false;
}
if (isFinalCheck) {
myIgnoreMouseEventsConsecutiveToInitial = false;
myInitialMouseEvent = null;
}
e.consume();
return true;
}
private void processMouseReleased(@NotNull MouseEvent e) {
if (checkIgnore(e, true)) return;
if (e.getSource() == myGutterComponent && !(myMousePressedEvent != null && myMousePressedEvent.isConsumed())) {
myGutterComponent.mouseReleased(e);
}
if (getMouseEventArea(e) != EditorMouseEventArea.EDITING_AREA || e.getY() < 0 || e.getX() < 0) {
return;
}
// if (myMousePressedInsideSelection) getSelectionModel().removeSelection();
final FoldRegion region = getFoldingModel().getFoldingPlaceholderAt(e.getPoint());
if (e.getX() >= 0 && e.getY() >= 0 && region != null && region == myMouseSelectedRegion) {
getFoldingModel().runBatchFoldingOperation(new Runnable() {
@Override
public void run() {
myFoldingModel.flushCaretShift();
region.setExpanded(true);
}
});
// The call below is performed because gutter's height is not updated sometimes, i.e. it sticks to the value that corresponds
// to the situation when fold region is collapsed. That causes bottom of the gutter to not be repainted and that looks really ugly.
myGutterComponent.updateSize();
}
// The general idea is to check if the user performed 'caret position change click' (left click most of the time) inside selection
// and, in the case of the positive answer, clear selection. Please note that there is a possible case that mouse click
// is performed inside selection but it triggers context menu. We don't want to drop the selection then.
if (myMousePressedEvent != null && myMousePressedEvent.getClickCount() == 1 && myMousePressedInsideSelection
&& !myMousePressedEvent.isShiftDown()
&& !myMousePressedEvent.isPopupTrigger()
&& !isToggleCaretEvent(myMousePressedEvent)
&& !isCreateRectangularSelectionEvent(myMousePressedEvent)) {
getSelectionModel().removeSelection();
}
}
@NotNull
@Override
public DataContext getDataContext() {
return getProjectAwareDataContext(DataManager.getInstance().getDataContext(getContentComponent()));
}
@NotNull
private DataContext getProjectAwareDataContext(@NotNull final DataContext original) {
if (CommonDataKeys.PROJECT.getData(original) == myProject) return original;
return new DataContext() {
@Override
public Object getData(String dataId) {
if (CommonDataKeys.PROJECT.is(dataId)) {
return myProject;
}
return original.getData(dataId);
}
};
}
@Override
public EditorMouseEventArea getMouseEventArea(@NotNull MouseEvent e) {
if (myGutterComponent != e.getSource()) return EditorMouseEventArea.EDITING_AREA;
int x = myGutterComponent.convertX(e.getX());
return myGutterComponent.getEditorMouseAreaByOffset(x);
}
private void requestFocus() {
final IdeFocusManager focusManager = IdeFocusManager.getInstance(myProject);
if (focusManager.getFocusOwner() != myEditorComponent) { //IDEA-64501
focusManager.requestFocus(myEditorComponent, true);
}
}
private void validateMousePointer(@NotNull MouseEvent e) {
if (e.getSource() == myGutterComponent) {
myGutterComponent.validateMousePointer(e);
}
else {
myGutterComponent.setActiveFoldRegion(null);
if (getSelectionModel().hasSelection() && (e.getModifiersEx() & (InputEvent.BUTTON1_DOWN_MASK | InputEvent.BUTTON2_DOWN_MASK)) == 0) {
int offset = logicalPositionToOffset(xyToLogicalPosition(e.getPoint()));
if (getSelectionModel().getSelectionStart() <= offset && offset < getSelectionModel().getSelectionEnd()) {
myEditorComponent.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
return;
}
}
myEditorComponent.setCursor(UIUtil.getTextCursor(getBackgroundColor()));
}
}
private void runMouseDraggedCommand(@NotNull final MouseEvent e) {
if (myCommandProcessor == null || myMousePressedEvent != null && myMousePressedEvent.isConsumed()) {
return;
}
myCommandProcessor.executeCommand(myProject, new Runnable() {
@Override
public void run() {
processMouseDragged(e);
}
}, "", MOUSE_DRAGGED_GROUP, UndoConfirmationPolicy.DEFAULT, getDocument());
}
private void processMouseDragged(@NotNull MouseEvent e) {
if (!JBSwingUtilities.isLeftMouseButton(e) && !JBSwingUtilities.isMiddleMouseButton(e)) {
return;
}
if (getMouseEventArea(e) == EditorMouseEventArea.LINE_MARKERS_AREA) {
// The general idea is that we don't want to change caret position on gutter marker area click (e.g. on setting a breakpoint)
// but do want to allow bulk selection on gutter marker mouse drag. However, when a drag is performed, the first event is
// a 'mouse pressed' event, that's why we remember target line on 'mouse pressed' processing and use that information on
// further dragging (if any).
if (myDragOnGutterSelectionStartLine >= 0) {
mySelectionModel.removeSelection();
myCaretModel.moveToOffset(myDragOnGutterSelectionStartLine < myDocument.getLineCount()
? myDocument.getLineStartOffset(myDragOnGutterSelectionStartLine) : myDocument.getTextLength());
}
myDragOnGutterSelectionStartLine = - 1;
}
boolean columnSelectionDragEvent = isColumnSelectionDragEvent(e);
boolean toggleCaretEvent = isToggleCaretEvent(e);
boolean addRectangularSelectionEvent = isAddRectangularSelectionEvent(e);
boolean columnSelectionDrag = isColumnMode() && !myLastPressCreatedCaret || columnSelectionDragEvent;
if (!columnSelectionDragEvent && toggleCaretEvent && !myLastPressCreatedCaret) {
return; // ignoring drag after removing a caret
}
Rectangle visibleArea = getScrollingModel().getVisibleArea();
int x = e.getX();
if (e.getSource() == myGutterComponent) {
x = 0;
}
int dx = 0;
if (x < visibleArea.x && visibleArea.x > 0) {
dx = x - visibleArea.x;
}
else {
if (x > visibleArea.x + visibleArea.width) {
dx = x - visibleArea.x - visibleArea.width;
}
}
int dy = 0;
int y = e.getY();
if (y < visibleArea.y && visibleArea.y > 0) {
dy = y - visibleArea.y;
}
else {
if (y > visibleArea.y + visibleArea.height) {
dy = y - visibleArea.y - visibleArea.height;
}
}
if (dx == 0 && dy == 0) {
myScrollingTimer.stop();
SelectionModel selectionModel = getSelectionModel();
Caret leadCaret = getLeadCaret();
int oldSelectionStart = leadCaret.getLeadSelectionOffset();
VisualPosition oldVisLeadSelectionStart = leadCaret.getLeadSelectionPosition();
int oldCaretOffset = getCaretModel().getOffset();
boolean multiCaretSelection = columnSelectionDrag || toggleCaretEvent;
VisualPosition newVisualCaret = myUseNewRendering ? getTargetPosition(x, y, !multiCaretSelection) : null;
LogicalPosition newLogicalCaret = myUseNewRendering ? visualToLogicalPosition(newVisualCaret) :
getLogicalPositionForScreenPos(x, y, !multiCaretSelection);
if (multiCaretSelection) {
myMultiSelectionInProgress = true;
myRectangularSelectionInProgress = columnSelectionDrag || addRectangularSelectionEvent;
myTargetMultiSelectionPosition = xyToVisualPosition(new Point(Math.max(x, 0), Math.max(y, 0)));
}
else {
if (myUseNewRendering) {
getCaretModel().moveToVisualPosition(newVisualCaret);
}
else {
getCaretModel().moveToLogicalPosition(newLogicalCaret);
}
}
int newCaretOffset = getCaretModel().getOffset();
newVisualCaret = getCaretModel().getVisualPosition();
int caretShift = newCaretOffset - mySavedSelectionStart;
if (myMousePressedEvent != null && getMouseEventArea(myMousePressedEvent) != EditorMouseEventArea.EDITING_AREA &&
getMouseEventArea(myMousePressedEvent) != EditorMouseEventArea.LINE_NUMBERS_AREA) {
selectionModel.setSelection(oldSelectionStart, newCaretOffset);
}
else {
if (multiCaretSelection) {
if (myLastMousePressedLocation != null && (myCurrentDragIsSubstantial || !newLogicalCaret.equals(myLastMousePressedLocation))) {
createSelectionTill(newLogicalCaret);
blockActionsIfNeeded(e, myLastMousePressedLocation, newLogicalCaret);
}
}
else {
if (getMouseSelectionState() != MOUSE_SELECTION_STATE_NONE) {
if (caretShift < 0) {
int newSelection = newCaretOffset;
if (getMouseSelectionState() == MOUSE_SELECTION_STATE_WORD_SELECTED) {
newSelection = myCaretModel.getWordAtCaretStart();
}
else {
if (getMouseSelectionState() == MOUSE_SELECTION_STATE_LINE_SELECTED) {
newSelection =
logicalPositionToOffset(visualToLogicalPosition(new VisualPosition(getCaretModel().getVisualPosition().line, 0)));
}
}
if (newSelection < 0) newSelection = newCaretOffset;
selectionModel.setSelection(mySavedSelectionEnd, newSelection);
getCaretModel().moveToOffset(newSelection);
}
else {
int newSelection = newCaretOffset;
if (getMouseSelectionState() == MOUSE_SELECTION_STATE_WORD_SELECTED) {
newSelection = myCaretModel.getWordAtCaretEnd();
}
else {
if (getMouseSelectionState() == MOUSE_SELECTION_STATE_LINE_SELECTED) {
newSelection =
logicalPositionToOffset(visualToLogicalPosition(new VisualPosition(getCaretModel().getVisualPosition().line + 1, 0)));
}
}
if (newSelection < 0) newSelection = newCaretOffset;
selectionModel.setSelection(mySavedSelectionStart, newSelection);
getCaretModel().moveToOffset(newSelection);
}
cancelAutoResetForMouseSelectionState();
return;
}
if (!myMousePressedInsideSelection) {
// There is a possible case that lead selection position should be adjusted in accordance with the mouse move direction.
// E.g. consider situation when user selects the whole line by clicking at 'line numbers' area. 'Line end' is considered
// to be lead selection point then. However, when mouse is dragged down we want to consider 'line start' to be
// lead selection point.
if ((myMousePressArea == EditorMouseEventArea.LINE_NUMBERS_AREA
|| myMousePressArea == EditorMouseEventArea.LINE_MARKERS_AREA)
&& selectionModel.hasSelection()) {
if (newCaretOffset >= selectionModel.getSelectionEnd()) {
oldSelectionStart = selectionModel.getSelectionStart();
oldVisLeadSelectionStart = selectionModel.getSelectionStartPosition();
}
else if (newCaretOffset <= selectionModel.getSelectionStart()) {
oldSelectionStart = selectionModel.getSelectionEnd();
oldVisLeadSelectionStart = selectionModel.getSelectionEndPosition();
}
}
if (oldVisLeadSelectionStart != null) {
setSelectionAndBlockActions(e, oldVisLeadSelectionStart, oldSelectionStart, newVisualCaret, newCaretOffset);
}
else {
setSelectionAndBlockActions(e, oldSelectionStart, newCaretOffset);
}
cancelAutoResetForMouseSelectionState();
}
else {
if (caretShift != 0) {
if (myMousePressedEvent != null) {
if (mySettings.isDndEnabled()) {
if (myDraggedRange == null) {
boolean isCopy = UIUtil.isControlKeyDown(e) || isViewer() || !getDocument().isWritable();
mySavedCaretOffsetForDNDUndoHack = oldCaretOffset;
getContentComponent().getTransferHandler()
.exportAsDrag(getContentComponent(), e, isCopy ? TransferHandler.COPY : TransferHandler.MOVE);
}
}
else {
selectionModel.removeSelection();
}
}
}
}
}
}
}
else {
myScrollingTimer.start(dx, dy);
onSubstantialDrag(e);
}
}
private void clearDraggedRange() {
if (myDraggedRange != null) {
myDraggedRange.dispose();
myDraggedRange = null;
}
}
private void createSelectionTill(@NotNull LogicalPosition targetPosition) {
List<CaretState> caretStates = new ArrayList<CaretState>(myCaretStateBeforeLastPress);
if (myRectangularSelectionInProgress) {
caretStates.addAll(EditorModificationUtil.calcBlockSelectionState(this, myLastMousePressedLocation, targetPosition));
}
else {
LogicalPosition selectionStart = myLastMousePressedLocation;
LogicalPosition selectionEnd = targetPosition;
if (getMouseSelectionState() != MOUSE_SELECTION_STATE_NONE) {
int newCaretOffset = logicalPositionToOffset(targetPosition);
if (newCaretOffset < mySavedSelectionStart) {
selectionStart = offsetToLogicalPosition(mySavedSelectionEnd);
if (getMouseSelectionState() == MOUSE_SELECTION_STATE_LINE_SELECTED) {
targetPosition = selectionEnd = visualToLogicalPosition(new VisualPosition(offsetToVisualLine(newCaretOffset), 0));
}
}
else {
selectionStart = offsetToLogicalPosition(mySavedSelectionStart);
int selectionEndOffset = Math.max(newCaretOffset, mySavedSelectionEnd);
if (getMouseSelectionState() == MOUSE_SELECTION_STATE_WORD_SELECTED) {
targetPosition = selectionEnd = offsetToLogicalPosition(selectionEndOffset);
}
else if (getMouseSelectionState() == MOUSE_SELECTION_STATE_LINE_SELECTED) {
targetPosition = selectionEnd = visualToLogicalPosition(new VisualPosition(offsetToVisualLine(selectionEndOffset) + 1, 0));
}
}
cancelAutoResetForMouseSelectionState();
}
caretStates.add(new CaretState(targetPosition, selectionStart, selectionEnd));
}
myCaretModel.setCaretsAndSelections(caretStates);
}
private Caret getLeadCaret() {
List<Caret> allCarets = myCaretModel.getAllCarets();
Caret firstCaret = allCarets.get(0);
if (firstCaret == myCaretModel.getPrimaryCaret()) {
return allCarets.get(allCarets.size() - 1);
}
return firstCaret;
}
private void setSelectionAndBlockActions(@NotNull MouseEvent mouseDragEvent, int startOffset, int endOffset) {
mySelectionModel.setSelection(startOffset, endOffset);
if (myCurrentDragIsSubstantial || startOffset != endOffset) {
onSubstantialDrag(mouseDragEvent);
}
}
private void setSelectionAndBlockActions(@NotNull MouseEvent mouseDragEvent, VisualPosition startPosition, int startOffset, VisualPosition endPosition, int endOffset) {
mySelectionModel.setSelection(startPosition, startOffset, endPosition, endOffset);
if (myCurrentDragIsSubstantial || startOffset != endOffset || !Comparing.equal(startPosition, endPosition)) {
onSubstantialDrag(mouseDragEvent);
}
}
private void blockActionsIfNeeded(@NotNull MouseEvent mouseDragEvent, @NotNull LogicalPosition startPosition, @NotNull LogicalPosition endPosition) {
if (myCurrentDragIsSubstantial || !startPosition.equals(endPosition)) {
onSubstantialDrag(mouseDragEvent);
}
}
private void onSubstantialDrag(@NotNull MouseEvent mouseDragEvent) {
IdeEventQueue.getInstance().blockNextEvents(mouseDragEvent, IdeEventQueue.BlockMode.ACTIONS);
myCurrentDragIsSubstantial = true;
}
private static class RepaintCursorCommand implements Runnable {
private long mySleepTime = 500;
private boolean myIsBlinkCaret = true;
@Nullable private EditorImpl myEditor;
@NotNull private final MyRepaintRunnable myRepaintRunnable;
private ScheduledFuture<?> mySchedulerHandle;
private RepaintCursorCommand() {
myRepaintRunnable = new MyRepaintRunnable();
}
private class MyRepaintRunnable implements Runnable {
@Override
public void run() {
if (myEditor != null) {
myEditor.myCaretCursor.repaint();
}
}
}
public void start() {
if (mySchedulerHandle != null) {
mySchedulerHandle.cancel(false);
}
mySchedulerHandle = JobScheduler.getScheduler().scheduleWithFixedDelay(this, mySleepTime, mySleepTime, TimeUnit.MILLISECONDS);
}
private void setBlinkPeriod(int blinkPeriod) {
mySleepTime = blinkPeriod > 10 ? blinkPeriod : 10;
start();
}
private void setBlinkCaret(boolean value) {
myIsBlinkCaret = value;
}
@Override
public void run() {
if (myEditor != null) {
CaretCursor activeCursor = myEditor.myCaretCursor;
long time = System.currentTimeMillis();
time -= activeCursor.myStartTime;
if (time > mySleepTime) {
boolean toRepaint = true;
if (myIsBlinkCaret) {
activeCursor.myIsShown = !activeCursor.myIsShown;
}
else {
toRepaint = !activeCursor.myIsShown;
activeCursor.myIsShown = true;
}
if (toRepaint) {
SwingUtilities.invokeLater(myRepaintRunnable);
}
}
}
}
}
void updateCaretCursor() {
myUpdateCursor = true;
}
private void setCursorPosition() {
final List<CaretRectangle> caretPoints = new ArrayList<CaretRectangle>();
for (Caret caret : getCaretModel().getAllCarets()) {
boolean isRtl = caret.isAtRtlLocation();
VisualPosition caretPosition = caret.getVisualPosition();
Point pos1 = visualPositionToXY(caretPosition);
Point pos2 = visualPositionToXY(new VisualPosition(caretPosition.line, Math.max(0, caretPosition.column + (isRtl ? -1 : 1))));
caretPoints.add(new CaretRectangle(pos1, Math.abs(pos2.x - pos1.x), caret, isRtl));
}
myCaretCursor.setPositions(caretPoints.toArray(new CaretRectangle[caretPoints.size()]));
}
@Override
public boolean setCaretVisible(boolean b) {
boolean old = myCaretCursor.isActive();
if (b) {
myCaretCursor.activate();
}
else {
myCaretCursor.passivate();
}
return old;
}
@Override
public boolean setCaretEnabled(boolean enabled) {
boolean old = myCaretCursor.isEnabled();
myCaretCursor.setEnabled(enabled);
return old;
}
@Override
public void addFocusListener(@NotNull FocusChangeListener listener) {
myFocusListeners.add(listener);
}
@Override
public void addFocusListener(@NotNull FocusChangeListener listener, @NotNull Disposable parentDisposable) {
ContainerUtil.add(listener, myFocusListeners, parentDisposable);
}
@Override
@Nullable
public Project getProject() {
return myProject;
}
@Override
public boolean isOneLineMode() {
return myIsOneLineMode;
}
@Override
public boolean isEmbeddedIntoDialogWrapper() {
return myEmbeddedIntoDialogWrapper;
}
@Override
public void setEmbeddedIntoDialogWrapper(boolean b) {
assertIsDispatchThread();
myEmbeddedIntoDialogWrapper = b;
myScrollPane.setFocusable(!b);
myEditorComponent.setFocusCycleRoot(!b);
myEditorComponent.setFocusable(b);
}
@Override
public void setOneLineMode(boolean isOneLineMode) {
myIsOneLineMode = isOneLineMode;
getScrollPane().setInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null);
reinitSettings();
}
public static class CaretRectangle {
public final Point myPoint;
public final int myWidth;
public final Caret myCaret;
public final boolean myIsRtl;
private CaretRectangle(Point point, int width, Caret caret, boolean isRtl) {
myPoint = point;
myWidth = Math.max(width, 2);
myCaret = caret;
myIsRtl = isRtl;
}
}
private class CaretCursor {
private CaretRectangle[] myLocations;
private boolean myEnabled;
@SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized")
private boolean myIsShown;
private long myStartTime;
private CaretCursor() {
myLocations = new CaretRectangle[] {new CaretRectangle(new Point(0, 0), 0, null, false)};
setEnabled(true);
}
public boolean isEnabled() {
return myEnabled;
}
public void setEnabled(boolean enabled) {
myEnabled = enabled;
}
private void activate() {
final boolean blink = mySettings.isBlinkCaret();
final int blinkPeriod = mySettings.getCaretBlinkPeriod();
synchronized (ourCaretBlinkingCommand) {
ourCaretBlinkingCommand.myEditor = EditorImpl.this;
ourCaretBlinkingCommand.setBlinkCaret(blink);
ourCaretBlinkingCommand.setBlinkPeriod(blinkPeriod);
myIsShown = true;
}
}
public boolean isActive() {
synchronized (ourCaretBlinkingCommand) {
return myIsShown;
}
}
private void passivate() {
synchronized (ourCaretBlinkingCommand) {
myIsShown = false;
}
}
private void setPositions(CaretRectangle[] locations) {
myStartTime = System.currentTimeMillis();
myLocations = locations;
myIsShown = true;
if (!myUseNewRendering) {
repaint();
}
}
private void repaint() {
if (myUseNewRendering) {
myView.repaintCarets();
}
else {
for (CaretRectangle location : myLocations) {
myEditorComponent.repaintEditorComponent(location.myPoint.x, location.myPoint.y, location.myWidth, getLineHeight());
}
}
}
@Nullable
CaretRectangle[] getCaretLocations(boolean onlyIfShown) {
if (onlyIfShown && (!isEnabled() || !myIsShown || isRendererMode() || !IJSwingUtilities.hasFocus(getContentComponent()))) return null;
return myLocations;
}
private void paint(@NotNull Graphics g) {
CaretRectangle[] locations = getCaretLocations(true);
if (locations == null) return;
for (CaretRectangle location : myLocations) {
paintAt(g, location.myPoint.x, location.myPoint.y, location.myWidth, location.myCaret);
}
}
void paintAt(@NotNull Graphics g, int x, int y, int width, Caret caret) {
int lineHeight = getLineHeight();
Rectangle viewRectangle = getScrollingModel().getVisibleArea();
if (x - viewRectangle.x < 0) {
return;
}
g.setColor(myScheme.getColor(EditorColors.CARET_COLOR));
Graphics2D originalG = IdeBackgroundUtil.getOriginalGraphics(g);
if (!paintBlockCaret()) {
if (UIUtil.isRetina()) {
originalG.fillRect(x, y, mySettings.getLineCursorWidth(), lineHeight);
}
else {
g.fillRect(x, y, JBUI.scale(mySettings.getLineCursorWidth()), lineHeight);
}
}
else {
Color caretColor = myScheme.getColor(EditorColors.CARET_COLOR);
if (caretColor == null) caretColor = new JBColor(Gray._0, Gray._255);
g.setColor(caretColor);
originalG.fillRect(x, y, width, lineHeight - 1);
final LogicalPosition startPosition = caret == null ? getCaretModel().getLogicalPosition() : caret.getLogicalPosition();
final int offset = logicalPositionToOffset(startPosition);
CharSequence chars = myDocument.getImmutableCharSequence();
if (chars.length() > offset && myDocument.getTextLength() > offset) {
FoldRegion folding = myFoldingModel.getCollapsedRegionAtOffset(offset);
final char ch;
if (folding == null || folding.isExpanded()) {
ch = chars.charAt(offset);
}
else {
VisualPosition visual = caret == null ? getCaretModel().getVisualPosition() : caret.getVisualPosition();
VisualPosition foldingPosition = offsetToVisualPosition(folding.getStartOffset());
if (visual.line == foldingPosition.line) {
ch = folding.getPlaceholderText().charAt(visual.column - foldingPosition.column);
}
else {
ch = chars.charAt(offset);
}
}
//don't worry it's cheap. Cache is not required
IterationState state = new IterationState(EditorImpl.this, offset, offset + 1, true);
TextAttributes attributes = state.getMergedAttributes();
FontInfo info = EditorUtil.fontForChar(ch, attributes.getFontType(), EditorImpl.this);
g.setFont(info.getFont());
//todo[kb]
//in case of italic style we paint out of the cursor block. Painting the symbol to a dedicated buffered image
//solves the problem, but still looks weird because it leaves colored pixels at right.
g.setColor(ColorUtil.isDark(caretColor) ? CURSOR_FOREGROUND_LIGHT : CURSOR_FOREGROUND_DARK);
g.drawChars(new char[]{ch}, 0, 1, x, y + getAscent());
}
}
}
}
private boolean paintBlockCaret() {
return myIsInsertMode == mySettings.isBlockCursor();
}
private class ScrollingTimer {
private Timer myTimer;
private static final int TIMER_PERIOD = 100;
private static final int CYCLE_SIZE = 20;
private int myXCycles;
private int myYCycles;
private int myDx;
private int myDy;
private int xPassedCycles;
private int yPassedCycles;
private void start(int dx, int dy) {
myDx = 0;
myDy = 0;
if (dx > 0) {
myXCycles = CYCLE_SIZE / dx + 1;
myDx = 1 + dx / CYCLE_SIZE;
}
else {
if (dx < 0) {
myXCycles = -CYCLE_SIZE / dx + 1;
myDx = -1 + dx / CYCLE_SIZE;
}
}
if (dy > 0) {
myYCycles = CYCLE_SIZE / dy + 1;
myDy = 1 + dy / CYCLE_SIZE;
}
else {
if (dy < 0) {
myYCycles = -CYCLE_SIZE / dy + 1;
myDy = -1 + dy / CYCLE_SIZE;
}
}
if (myTimer != null) {
return;
}
myTimer = UIUtil.createNamedTimer("Editor scroll timer", TIMER_PERIOD, new ActionListener() {
@Override
public void actionPerformed(@NotNull ActionEvent e) {
myCommandProcessor.executeCommand(myProject, new DocumentRunnable(myDocument, myProject) {
@Override
public void run() {
// We experienced situation when particular editor was disposed but the timer was still on.
if (isDisposed()) {
myTimer.stop();
return;
}
int oldSelectionStart = mySelectionModel.getLeadSelectionOffset();
VisualPosition caretPosition = myMultiSelectionInProgress ? myTargetMultiSelectionPosition : getCaretModel().getVisualPosition();
int column = caretPosition.column;
xPassedCycles++;
if (xPassedCycles >= myXCycles) {
xPassedCycles = 0;
column += myDx;
}
int line = caretPosition.line;
yPassedCycles++;
if (yPassedCycles >= myYCycles) {
yPassedCycles = 0;
line += myDy;
}
line = Math.max(0, line);
column = Math.max(0, column);
VisualPosition pos = new VisualPosition(line, column);
if (!myMultiSelectionInProgress) {
getCaretModel().moveToVisualPosition(pos);
getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
}
int newCaretOffset = getCaretModel().getOffset();
int caretShift = newCaretOffset - mySavedSelectionStart;
if (getMouseSelectionState() != MOUSE_SELECTION_STATE_NONE) {
if (caretShift < 0) {
int newSelection = newCaretOffset;
if (getMouseSelectionState() == MOUSE_SELECTION_STATE_WORD_SELECTED) {
newSelection = myCaretModel.getWordAtCaretStart();
}
else {
if (getMouseSelectionState() == MOUSE_SELECTION_STATE_LINE_SELECTED) {
newSelection =
logicalPositionToOffset(visualToLogicalPosition(new VisualPosition(getCaretModel().getVisualPosition().line, 0)));
}
}
if (newSelection < 0) newSelection = newCaretOffset;
mySelectionModel.setSelection(validateOffset(mySavedSelectionEnd), newSelection);
getCaretModel().moveToOffset(newSelection);
}
else {
int newSelection = newCaretOffset;
if (getMouseSelectionState() == MOUSE_SELECTION_STATE_WORD_SELECTED) {
newSelection = myCaretModel.getWordAtCaretEnd();
}
else {
if (getMouseSelectionState() == MOUSE_SELECTION_STATE_LINE_SELECTED) {
newSelection = logicalPositionToOffset(
visualToLogicalPosition(new VisualPosition(getCaretModel().getVisualPosition().line + 1, 0)));
}
}
if (newSelection < 0) newSelection = newCaretOffset;
mySelectionModel.setSelection(validateOffset(mySavedSelectionStart), newSelection);
getCaretModel().moveToOffset(newSelection);
}
return;
}
if (myMultiSelectionInProgress && myLastMousePressedLocation != null) {
myTargetMultiSelectionPosition = pos;
LogicalPosition newLogicalPosition = visualToLogicalPosition(pos);
getScrollingModel().scrollTo(newLogicalPosition, ScrollType.RELATIVE);
createSelectionTill(newLogicalPosition);
}
else {
mySelectionModel.setSelection(oldSelectionStart, getCaretModel().getOffset());
}
}
}, EditorBundle.message("move.cursor.command.name"), DocCommandGroupId.noneGroupId(getDocument()), UndoConfirmationPolicy.DEFAULT,
getDocument());
}
});
myTimer.start();
}
private void stop() {
if (myTimer != null) {
myTimer.stop();
myTimer = null;
}
}
private int validateOffset(int offset) {
if (offset < 0) return 0;
if (offset > myDocument.getTextLength()) return myDocument.getTextLength();
return offset;
}
}
private static final Field decrButtonField = ReflectionUtil.getDeclaredField(BasicScrollBarUI.class, "decrButton");
private static final Field incrButtonField = ReflectionUtil.getDeclaredField(BasicScrollBarUI.class, "incrButton");
class MyScrollBar extends JBScrollBar implements IdeGlassPane.TopComponent {
@NonNls private static final String APPLE_LAF_AQUA_SCROLL_BAR_UI_CLASS = "apple.laf.AquaScrollBarUI";
private ScrollBarUI myPersistentUI;
private MyScrollBar(@JdkConstants.AdjustableOrientation int orientation) {
super(orientation);
}
void setPersistentUI(ScrollBarUI ui) {
myPersistentUI = ui;
setUI(ui);
}
@Override
public boolean canBePreprocessed(MouseEvent e) {
return JBScrollPane.canBePreprocessed(e, this);
}
@Override
public void setUI(ScrollBarUI ui) {
if (myPersistentUI == null) myPersistentUI = ui;
super.setUI(myPersistentUI);
setOpaque(false);
}
/**
* This is helper method. It returns height of the top (decrease) scroll bar
* button. Please note, that it's possible to return real height only if scroll bar
* is instance of BasicScrollBarUI. Otherwise it returns fake (but good enough :) )
* value.
*/
int getDecScrollButtonHeight() {
ScrollBarUI barUI = getUI();
Insets insets = getInsets();
int top = Math.max(0, insets.top);
if (barUI instanceof ButtonlessScrollBarUI) {
return top + ((ButtonlessScrollBarUI)barUI).getDecrementButtonHeight();
}
if (barUI instanceof BasicScrollBarUI) {
try {
JButton decrButtonValue = (JButton)decrButtonField.get(barUI);
LOG.assertTrue(decrButtonValue != null);
return top + decrButtonValue.getHeight();
}
catch (Exception exc) {
throw new IllegalStateException(exc);
}
}
return top + 15;
}
/**
* This is helper method. It returns height of the bottom (increase) scroll bar
* button. Please note, that it's possible to return real height only if scroll bar
* is instance of BasicScrollBarUI. Otherwise it returns fake (but good enough :) )
* value.
*/
int getIncScrollButtonHeight() {
ScrollBarUI barUI = getUI();
Insets insets = getInsets();
if (barUI instanceof ButtonlessScrollBarUI) {
return insets.top + ((ButtonlessScrollBarUI)barUI).getIncrementButtonHeight();
}
if (barUI instanceof BasicScrollBarUI) {
try {
JButton incrButtonValue = (JButton)incrButtonField.get(barUI);
LOG.assertTrue(incrButtonValue != null);
return insets.bottom + incrButtonValue.getHeight();
}
catch (Exception exc) {
throw new IllegalStateException(exc);
}
}
if (APPLE_LAF_AQUA_SCROLL_BAR_UI_CLASS.equals(barUI.getClass().getName())) {
return insets.bottom + 30;
}
return insets.bottom + 15;
}
@Override
public int getUnitIncrement(int direction) {
JViewport vp = myScrollPane.getViewport();
Rectangle vr = vp.getViewRect();
return myEditorComponent.getScrollableUnitIncrement(vr, SwingConstants.VERTICAL, direction);
}
@Override
public int getBlockIncrement(int direction) {
JViewport vp = myScrollPane.getViewport();
Rectangle vr = vp.getViewRect();
return myEditorComponent.getScrollableBlockIncrement(vr, SwingConstants.VERTICAL, direction);
}
private void registerRepaintCallback(@Nullable ButtonlessScrollBarUI.ScrollbarRepaintCallback callback) {
if (myPersistentUI instanceof ButtonlessScrollBarUI) {
((ButtonlessScrollBarUI)myPersistentUI).registerRepaintCallback(callback);
}
}
}
private MyEditable getViewer() {
if (myEditable == null) {
myEditable = new MyEditable();
}
return myEditable;
}
@Override
public CopyProvider getCopyProvider() {
return getViewer();
}
@Override
public CutProvider getCutProvider() {
return getViewer();
}
@Override
public PasteProvider getPasteProvider() {
return getViewer();
}
@Override
public DeleteProvider getDeleteProvider() {
return getViewer();
}
private class MyEditable implements CutProvider, CopyProvider, PasteProvider, DeleteProvider {
@Override
public void performCopy(@NotNull DataContext dataContext) {
executeAction(IdeActions.ACTION_EDITOR_COPY, dataContext);
}
@Override
public boolean isCopyEnabled(@NotNull DataContext dataContext) {
return true;
}
@Override
public boolean isCopyVisible(@NotNull DataContext dataContext) {
return getSelectionModel().hasSelection(true);
}
@Override
public void performCut(@NotNull DataContext dataContext) {
executeAction(IdeActions.ACTION_EDITOR_CUT, dataContext);
}
@Override
public boolean isCutEnabled(@NotNull DataContext dataContext) {
return !isViewer();
}
@Override
public boolean isCutVisible(@NotNull DataContext dataContext) {
return isCutEnabled(dataContext) && getSelectionModel().hasSelection(true);
}
@Override
public void performPaste(@NotNull DataContext dataContext) {
executeAction(IdeActions.ACTION_EDITOR_PASTE, dataContext);
}
@Override
public boolean isPastePossible(@NotNull DataContext dataContext) {
// Copy of isPasteEnabled. See interface method javadoc.
return !isViewer();
}
@Override
public boolean isPasteEnabled(@NotNull DataContext dataContext) {
return !isViewer();
}
@Override
public void deleteElement(@NotNull DataContext dataContext) {
executeAction(IdeActions.ACTION_EDITOR_DELETE, dataContext);
}
@Override
public boolean canDeleteElement(@NotNull DataContext dataContext) {
return !isViewer();
}
private void executeAction(@NotNull String actionId, @NotNull DataContext dataContext) {
EditorAction action = (EditorAction)ActionManager.getInstance().getAction(actionId);
if (action != null) {
action.actionPerformed(EditorImpl.this, dataContext);
}
}
}
@Override
public void setColorsScheme(@NotNull EditorColorsScheme scheme) {
assertIsDispatchThread();
myScheme = scheme;
reinitSettings();
}
@Override
@NotNull
public EditorColorsScheme getColorsScheme() {
return myScheme;
}
static void assertIsDispatchThread() {
ApplicationManager.getApplication().assertIsDispatchThread();
}
private static void assertReadAccess() {
ApplicationManager.getApplication().assertReadAccessAllowed();
}
@Override
public void setVerticalScrollbarOrientation(int type) {
assertIsDispatchThread();
int currentHorOffset = myScrollingModel.getHorizontalScrollOffset();
myScrollBarOrientation = type;
if (type == VERTICAL_SCROLLBAR_LEFT) {
myScrollPane.setLayout(new LeftHandScrollbarLayout());
}
else {
myScrollPane.setLayout(new ScrollPaneLayout());
}
myScrollingModel.scrollHorizontally(currentHorOffset);
}
@Override
public void setVerticalScrollbarVisible(boolean b) {
myScrollPane
.setVerticalScrollBarPolicy(b ? ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS : ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
}
@Override
public void setHorizontalScrollbarVisible(boolean b) {
myScrollPane.setHorizontalScrollBarPolicy(
b ? ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED : ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
}
@Override
public int getVerticalScrollbarOrientation() {
return myScrollBarOrientation;
}
public boolean isMirrored() {
return myScrollBarOrientation != EditorEx.VERTICAL_SCROLLBAR_RIGHT;
}
@NotNull
MyScrollBar getVerticalScrollBar() {
return myVerticalScrollBar;
}
@NotNull
MyScrollBar getHorizontalScrollBar() {
return (MyScrollBar)myScrollPane.getHorizontalScrollBar();
}
@MouseSelectionState
private int getMouseSelectionState() {
return myMouseSelectionState;
}
private void setMouseSelectionState(@MouseSelectionState int mouseSelectionState) {
if (getMouseSelectionState() == mouseSelectionState) return;
myMouseSelectionState = mouseSelectionState;
myMouseSelectionChangeTimestamp = System.currentTimeMillis();
myMouseSelectionStateAlarm.cancelAllRequests();
if (myMouseSelectionState != MOUSE_SELECTION_STATE_NONE) {
if (myMouseSelectionStateResetRunnable == null) {
myMouseSelectionStateResetRunnable = new Runnable() {
@Override
public void run() {
resetMouseSelectionState(null);
}
};
}
myMouseSelectionStateAlarm.addRequest(myMouseSelectionStateResetRunnable, Registry.intValue("editor.mouseSelectionStateResetTimeout"),
ModalityState.stateForComponent(myEditorComponent));
}
}
private void resetMouseSelectionState(@Nullable MouseEvent event) {
setMouseSelectionState(MOUSE_SELECTION_STATE_NONE);
MouseEvent e = event != null ? event : myMouseMovedEvent;
if (e != null) {
validateMousePointer(e);
}
}
private void cancelAutoResetForMouseSelectionState() {
myMouseSelectionStateAlarm.cancelAllRequests();
}
void replaceInputMethodText(@NotNull InputMethodEvent e) {
getInputMethodRequests();
myInputMethodRequestsHandler.replaceInputMethodText(e);
}
void inputMethodCaretPositionChanged(@NotNull InputMethodEvent e) {
getInputMethodRequests();
myInputMethodRequestsHandler.setInputMethodCaretPosition(e);
}
@NotNull
InputMethodRequests getInputMethodRequests() {
if (myInputMethodRequestsHandler == null) {
myInputMethodRequestsHandler = new MyInputMethodHandler();
myInputMethodRequestsSwingWrapper = new MyInputMethodHandleSwingThreadWrapper(myInputMethodRequestsHandler);
}
return myInputMethodRequestsSwingWrapper;
}
@Override
public boolean processKeyTyped(@NotNull KeyEvent e) {
if (e.getID() != KeyEvent.KEY_TYPED) return false;
char c = e.getKeyChar();
if (UIUtil.isReallyTypedEvent(e)) { // Hack just like in javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction
processKeyTyped(c);
return true;
}
else {
return false;
}
}
void beforeModalityStateChanged() {
myScrollingModel.beforeModalityStateChanged();
}
public EditorDropHandler getDropHandler() {
return myDropHandler;
}
public void setDropHandler(@NotNull EditorDropHandler dropHandler) {
myDropHandler = dropHandler;
}
private static class MyInputMethodHandleSwingThreadWrapper implements InputMethodRequests {
private final InputMethodRequests myDelegate;
private MyInputMethodHandleSwingThreadWrapper(InputMethodRequests delegate) {
myDelegate = delegate;
}
@NotNull
@Override
public Rectangle getTextLocation(final TextHitInfo offset) {
return execute(new Computable<Rectangle>() {
@Override
public Rectangle compute() {
return myDelegate.getTextLocation(offset);
}
});
}
@Override
public TextHitInfo getLocationOffset(final int x, final int y) {
return execute(new Computable<TextHitInfo>() {
@Override
public TextHitInfo compute() {
return myDelegate.getLocationOffset(x, y);
}
});
}
@Override
public int getInsertPositionOffset() {
return execute(new Computable<Integer>() {
@Override
public Integer compute() {
return myDelegate.getInsertPositionOffset();
}
});
}
@NotNull
@Override
public AttributedCharacterIterator getCommittedText(final int beginIndex, final int endIndex,
final AttributedCharacterIterator.Attribute[] attributes) {
return execute(new Computable<AttributedCharacterIterator>() {
@Override
public AttributedCharacterIterator compute() {
return myDelegate.getCommittedText(beginIndex, endIndex, attributes);
}
});
}
@Override
public int getCommittedTextLength() {
return execute(new Computable<Integer>() {
@Override
public Integer compute() {
return myDelegate.getCommittedTextLength();
}
});
}
@Override
@Nullable
public AttributedCharacterIterator cancelLatestCommittedText(AttributedCharacterIterator.Attribute[] attributes) {
return null;
}
@Override
public AttributedCharacterIterator getSelectedText(final AttributedCharacterIterator.Attribute[] attributes) {
return execute(new Computable<AttributedCharacterIterator>() {
@Override
public AttributedCharacterIterator compute() {
return myDelegate.getSelectedText(attributes);
}
});
}
private static <T> T execute(final Computable<T> computable) {
return UIUtil.invokeAndWaitIfNeeded(computable);
}
}
private class MyInputMethodHandler implements InputMethodRequests {
private String composedText;
private ProperTextRange composedTextRange;
@NotNull
@Override
public Rectangle getTextLocation(TextHitInfo offset) {
Point caret = logicalPositionToXY(getCaretModel().getLogicalPosition());
Rectangle r = new Rectangle(caret, new Dimension(1, getLineHeight()));
Point p = getContentComponent().getLocationOnScreen();
r.translate(p.x, p.y);
return r;
}
@Override
@Nullable
public TextHitInfo getLocationOffset(int x, int y) {
if (composedText != null) {
Point p = getContentComponent().getLocationOnScreen();
p.x = x - p.x;
p.y = y - p.y;
int pos = logicalPositionToOffset(xyToLogicalPosition(p));
if (composedTextRange.containsOffset(pos)) {
return TextHitInfo.leading(pos - composedTextRange.getStartOffset());
}
}
return null;
}
@Override
public int getInsertPositionOffset() {
int composedStartIndex = 0;
int composedEndIndex = 0;
if (composedText != null) {
composedStartIndex = composedTextRange.getStartOffset();
composedEndIndex = composedTextRange.getEndOffset();
}
int caretIndex = getCaretModel().getOffset();
if (caretIndex < composedStartIndex) {
return caretIndex;
}
if (caretIndex < composedEndIndex) {
return composedStartIndex;
}
return caretIndex - (composedEndIndex - composedStartIndex);
}
private String getText(int startIdx, int endIdx) {
if (startIdx >= 0 && endIdx > startIdx) {
CharSequence chars = getDocument().getImmutableCharSequence();
return chars.subSequence(startIdx, endIdx).toString();
}
return "";
}
@NotNull
@Override
public AttributedCharacterIterator getCommittedText(int beginIndex, int endIndex, AttributedCharacterIterator.Attribute[] attributes) {
int composedStartIndex = 0;
int composedEndIndex = 0;
if (composedText != null) {
composedStartIndex = composedTextRange.getStartOffset();
composedEndIndex = composedTextRange.getEndOffset();
}
String committed;
if (beginIndex < composedStartIndex) {
if (endIndex <= composedStartIndex) {
committed = getText(beginIndex, endIndex - beginIndex);
}
else {
int firstPartLength = composedStartIndex - beginIndex;
committed = getText(beginIndex, firstPartLength) + getText(composedEndIndex, endIndex - beginIndex - firstPartLength);
}
}
else {
committed = getText(beginIndex + composedEndIndex - composedStartIndex, endIndex - beginIndex);
}
return new AttributedString(committed).getIterator();
}
@Override
public int getCommittedTextLength() {
int length = getDocument().getTextLength();
if (composedText != null) {
length -= composedText.length();
}
return length;
}
@Override
@Nullable
public AttributedCharacterIterator cancelLatestCommittedText(AttributedCharacterIterator.Attribute[] attributes) {
return null;
}
@Override
@Nullable
public AttributedCharacterIterator getSelectedText(AttributedCharacterIterator.Attribute[] attributes) {
if (myCharKeyPressed) {
myNeedToSelectPreviousChar = true;
}
String text = getSelectionModel().getSelectedText();
return text == null ? null : new AttributedString(text).getIterator();
}
private void createComposedString(int composedIndex, @NotNull AttributedCharacterIterator text) {
StringBuffer strBuf = new StringBuffer();
// create attributed string with no attributes
for (char c = text.setIndex(composedIndex); c != CharacterIterator.DONE; c = text.next()) {
strBuf.append(c);
}
composedText = new String(strBuf);
}
private void setInputMethodCaretPosition(@NotNull InputMethodEvent e) {
if (composedText != null) {
int dot = composedTextRange.getStartOffset();
TextHitInfo caretPos = e.getCaret();
if (caretPos != null) {
dot += caretPos.getInsertionIndex();
}
getCaretModel().moveToOffset(dot);
getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
}
}
private void runUndoTransparent(@NotNull final Runnable runnable) {
CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() {
@Override
public void run() {
CommandProcessor.getInstance().executeCommand(myProject, new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(runnable);
}
}, "", getDocument(), UndoConfirmationPolicy.DEFAULT, getDocument());
}
});
}
private void replaceInputMethodText(@NotNull InputMethodEvent e) {
if (myNeedToSelectPreviousChar && SystemInfo.isMac &&
(Registry.is("ide.mac.pressAndHold.brute.workaround") || Registry.is("ide.mac.pressAndHold.workaround") &&
(e.getCommittedCharacterCount() > 0 || e.getCaret() == null))) {
// This is required to support input of accented characters using press-and-hold method (http://support.apple.com/kb/PH11264).
// JDK currently properly supports this functionality only for TextComponent/JTextComponent descendants.
// For our editor component we need this workaround.
// After https://bugs.openjdk.java.net/browse/JDK-8074882 is fixed, this workaround should be replaced with a proper solution.
myNeedToSelectPreviousChar = false;
getCaretModel().runForEachCaret(new CaretAction() {
@Override
public void perform(Caret caret) {
int caretOffset = caret.getOffset();
if (caretOffset > 0) {
caret.setSelection(caretOffset - 1, caretOffset);
}
}
});
}
int commitCount = e.getCommittedCharacterCount();
AttributedCharacterIterator text = e.getText();
// old composed text deletion
final Document doc = getDocument();
if (composedText != null) {
if (!isViewer() && doc.isWritable()) {
runUndoTransparent(new Runnable() {
@Override
public void run() {
int docLength = doc.getTextLength();
ProperTextRange range = composedTextRange.intersection(new TextRange(0, docLength));
if (range != null) {
doc.deleteString(range.getStartOffset(), range.getEndOffset());
}
}
});
}
composedText = null;
}
if (text != null) {
text.first();
// committed text insertion
if (commitCount > 0) {
//noinspection ForLoopThatDoesntUseLoopVariable
for (char c = text.current(); commitCount > 0; c = text.next(), commitCount--) {
if (c >= 0x20 && c != 0x7F) { // Hack just like in javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction
processKeyTyped(c);
}
}
}
// new composed text insertion
if (!isViewer() && doc.isWritable()) {
int composedTextIndex = text.getIndex();
if (composedTextIndex < text.getEndIndex()) {
createComposedString(composedTextIndex, text);
runUndoTransparent(new Runnable() {
@Override
public void run() {
EditorModificationUtil.insertStringAtCaret(EditorImpl.this, composedText, false, false);
}
});
composedTextRange = ProperTextRange.from(getCaretModel().getOffset(), composedText.length());
}
}
}
}
}
private class MyMouseAdapter extends MouseAdapter {
private boolean mySelectionTweaked;
@Override
public void mousePressed(@NotNull MouseEvent e) {
requestFocus();
runMousePressedCommand(e);
}
@Override
public void mouseReleased(@NotNull MouseEvent e) {
myMousePressArea = null;
runMouseReleasedCommand(e);
if (!e.isConsumed() && myMousePressedEvent != null && !myMousePressedEvent.isConsumed() &&
Math.abs(e.getX() - myMousePressedEvent.getX()) < EditorUtil.getSpaceWidth(Font.PLAIN, EditorImpl.this) &&
Math.abs(e.getY() - myMousePressedEvent.getY()) < getLineHeight()) {
runMouseClickedCommand(e);
}
}
@Override
public void mouseEntered(@NotNull MouseEvent e) {
runMouseEnteredCommand(e);
}
@Override
public void mouseExited(@NotNull MouseEvent e) {
runMouseExitedCommand(e);
EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e));
if (event.getArea() == EditorMouseEventArea.LINE_MARKERS_AREA) {
myGutterComponent.mouseExited(e);
}
TooltipController.getInstance().cancelTooltip(FOLDING_TOOLTIP_GROUP, e, true);
}
private void runMousePressedCommand(@NotNull final MouseEvent e) {
myLastMousePressedLocation = xyToLogicalPosition(e.getPoint());
myCaretStateBeforeLastPress = isToggleCaretEvent(e) ? myCaretModel.getCaretsAndSelections() : Collections.<CaretState>emptyList();
myCurrentDragIsSubstantial = false;
clearDraggedRange();
mySelectionTweaked = false;
myMousePressedEvent = e;
EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e));
myExpectedCaretOffset = logicalPositionToOffset(myLastMousePressedLocation);
try {
for (EditorMouseListener mouseListener : myMouseListeners) {
mouseListener.mousePressed(event);
}
}
finally {
myExpectedCaretOffset = -1;
}
if (event.getArea() == EditorMouseEventArea.LINE_MARKERS_AREA) {
myDragOnGutterSelectionStartLine = EditorUtil.yPositionToLogicalLine(EditorImpl.this, e);
}
// On some systems (for example on Linux) popup trigger is MOUSE_PRESSED event.
// But this trigger is always consumed by popup handler. In that case we have to
// also move caret.
if (event.isConsumed() && !(event.getMouseEvent().isPopupTrigger() || event.getArea() == EditorMouseEventArea.EDITING_AREA)) {
return;
}
if (myCommandProcessor != null) {
Runnable runnable = new Runnable() {
@Override
public void run() {
if (processMousePressed(e) && myProject != null && !myProject.isDefault()) {
IdeDocumentHistory.getInstance(myProject).includeCurrentCommandAsNavigation();
}
}
};
myCommandProcessor
.executeCommand(myProject, runnable, "", DocCommandGroupId.noneGroupId(getDocument()), UndoConfirmationPolicy.DEFAULT,
getDocument());
}
else {
processMousePressed(e);
}
}
private void runMouseClickedCommand(@NotNull final MouseEvent e) {
EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e));
for (EditorMouseListener listener : myMouseListeners) {
listener.mouseClicked(event);
if (event.isConsumed()) {
e.consume();
return;
}
}
}
private void runMouseReleasedCommand(@NotNull final MouseEvent e) {
myMultiSelectionInProgress = false;
myDragOnGutterSelectionStartLine = -1;
if (!mySelectionTweaked) {
tweakSelectionIfNecessary(e);
}
if (e.isConsumed()) {
return;
}
myScrollingTimer.stop();
EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e));
for (EditorMouseListener listener : myMouseListeners) {
listener.mouseReleased(event);
if (event.isConsumed()) {
e.consume();
return;
}
}
if (myCommandProcessor != null) {
Runnable runnable = new Runnable() {
@Override
public void run() {
processMouseReleased(e);
}
};
myCommandProcessor
.executeCommand(myProject, runnable, "", DocCommandGroupId.noneGroupId(getDocument()), UndoConfirmationPolicy.DEFAULT,
getDocument());
}
else {
processMouseReleased(e);
}
}
private void runMouseEnteredCommand(@NotNull MouseEvent e) {
EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e));
for (EditorMouseListener listener : myMouseListeners) {
listener.mouseEntered(event);
if (event.isConsumed()) {
e.consume();
return;
}
}
}
private void runMouseExitedCommand(@NotNull MouseEvent e) {
EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e));
for (EditorMouseListener listener : myMouseListeners) {
listener.mouseExited(event);
if (event.isConsumed()) {
e.consume();
return;
}
}
}
private boolean processMousePressed(@NotNull final MouseEvent e) {
myInitialMouseEvent = e;
if (myMouseSelectionState != MOUSE_SELECTION_STATE_NONE &&
System.currentTimeMillis() - myMouseSelectionChangeTimestamp > Registry.intValue(
"editor.mouseSelectionStateResetTimeout")) {
resetMouseSelectionState(e);
}
int x = e.getX();
int y = e.getY();
if (x < 0) x = 0;
if (y < 0) y = 0;
final EditorMouseEventArea eventArea = getMouseEventArea(e);
myMousePressArea = eventArea;
if (eventArea == EditorMouseEventArea.FOLDING_OUTLINE_AREA) {
final FoldRegion range = myGutterComponent.findFoldingAnchorAt(x, y);
if (range != null) {
final boolean expansion = !range.isExpanded();
int scrollShift = y - getScrollingModel().getVerticalScrollOffset();
Runnable processor = new Runnable() {
@Override
public void run() {
myFoldingModel.flushCaretShift();
range.setExpanded(expansion);
if (e.isAltDown()) {
for (FoldRegion region : myFoldingModel.getAllFoldRegions()) {
if (region.getStartOffset() >= range.getStartOffset() && region.getEndOffset() <= range.getEndOffset()) {
region.setExpanded(expansion);
}
}
}
}
};
getFoldingModel().runBatchFoldingOperation(processor);
y = myGutterComponent.getHeadCenterY(range);
getScrollingModel().scrollVertically(y - scrollShift);
myGutterComponent.updateSize();
validateMousePointer(e);
e.consume();
return false;
}
}
if (e.getSource() == myGutterComponent) {
if (eventArea == EditorMouseEventArea.LINE_MARKERS_AREA ||
eventArea == EditorMouseEventArea.ANNOTATIONS_AREA ||
eventArea == EditorMouseEventArea.LINE_NUMBERS_AREA) {
if (tweakSelectionIfNecessary(e)) {
mySelectionTweaked = true;
}
else {
myGutterComponent.mousePressed(e);
}
if (e.isConsumed()) return false;
}
x = 0;
}
int oldSelectionStart = mySelectionModel.getLeadSelectionOffset();
final int oldStart = mySelectionModel.getSelectionStart();
final int oldEnd = mySelectionModel.getSelectionEnd();
boolean toggleCaret = e.getSource() != myGutterComponent && isToggleCaretEvent(e);
boolean lastPressCreatedCaret = myLastPressCreatedCaret;
if (e.getClickCount() == 1) {
myLastPressCreatedCaret = false;
}
// Don't move caret on mouse press above gutter line markers area (a place where break points, 'override', 'implements' etc icons
// are drawn) and annotations area. E.g. we don't want to change caret position if a user sets new break point (clicks
// at 'line markers' area).
if (e.getSource() != myGutterComponent ||
eventArea != EditorMouseEventArea.LINE_MARKERS_AREA && eventArea != EditorMouseEventArea.ANNOTATIONS_AREA)
{
VisualPosition visualPosition = myUseNewRendering ? getTargetPosition(x, y, true) : null;
LogicalPosition pos = myUseNewRendering ? visualToLogicalPosition(visualPosition) : getLogicalPositionForScreenPos(x, y, true);
if (toggleCaret) {
if (!myUseNewRendering) {
visualPosition = logicalToVisualPosition(pos);
}
Caret caret = getCaretModel().getCaretAt(visualPosition);
if (e.getClickCount() == 1) {
if (caret == null) {
myLastPressCreatedCaret = getCaretModel().addCaret(visualPosition) != null;
}
else {
getCaretModel().removeCaret(caret);
}
}
else if (e.getClickCount() == 3 && lastPressCreatedCaret) {
if (myUseNewRendering) {
getCaretModel().moveToVisualPosition(visualPosition);
}
else {
getCaretModel().moveToLogicalPosition(pos);
}
}
}
else if (myCaretModel.supportsMultipleCarets() && e.getSource() != myGutterComponent && isCreateRectangularSelectionEvent(e)) {
mySelectionModel.setBlockSelection(myCaretModel.getLogicalPosition(), pos);
}
else {
getCaretModel().removeSecondaryCarets();
if (myUseNewRendering) {
getCaretModel().moveToVisualPosition(visualPosition);
}
else {
getCaretModel().moveToLogicalPosition(pos);
}
}
}
if (e.isPopupTrigger()) return false;
requestFocus();
int caretOffset = getCaretModel().getOffset();
int newStart = mySelectionModel.getSelectionStart();
int newEnd = mySelectionModel.getSelectionEnd();
boolean isNavigation = oldStart == oldEnd && newStart == newEnd && oldStart != newStart;
myMouseSelectedRegion = myFoldingModel.getFoldingPlaceholderAt(new Point(x, y));
myMousePressedInsideSelection = mySelectionModel.hasSelection() && caretOffset >= mySelectionModel.getSelectionStart() &&
caretOffset <= mySelectionModel.getSelectionEnd();
if (getMouseEventArea(e) == EditorMouseEventArea.LINE_NUMBERS_AREA && e.getClickCount() == 1) {
mySelectionModel.selectLineAtCaret();
setMouseSelectionState(MOUSE_SELECTION_STATE_LINE_SELECTED);
mySavedSelectionStart = mySelectionModel.getSelectionStart();
mySavedSelectionEnd = mySelectionModel.getSelectionEnd();
return isNavigation;
}
if (e.isShiftDown() && !e.isControlDown() && !e.isAltDown()) {
if (getMouseSelectionState() != MOUSE_SELECTION_STATE_NONE) {
if (caretOffset < mySavedSelectionStart) {
mySelectionModel.setSelection(mySavedSelectionEnd, caretOffset);
}
else {
mySelectionModel.setSelection(mySavedSelectionStart, caretOffset);
}
}
else {
int startToUse = oldSelectionStart;
if (mySelectionModel.isUnknownDirection() && caretOffset > startToUse) {
startToUse = Math.min(oldStart, oldEnd);
}
mySelectionModel.setSelection(startToUse, caretOffset);
}
}
else {
if (!myMousePressedInsideSelection && getSelectionModel().hasSelection()) {
setMouseSelectionState(MOUSE_SELECTION_STATE_NONE);
mySelectionModel.setSelection(caretOffset, caretOffset);
}
else {
if (!e.isPopupTrigger()
&& (eventArea == EditorMouseEventArea.EDITING_AREA || eventArea == EditorMouseEventArea.LINE_NUMBERS_AREA)
&& (!toggleCaret || lastPressCreatedCaret))
{
switch (e.getClickCount()) {
case 2:
selectWordAtCaret(mySettings.isMouseClickSelectionHonorsCamelWords() && mySettings.isCamelWords());
break;
case 3:
if (HONOR_CAMEL_HUMPS_ON_TRIPLE_CLICK && mySettings.isCamelWords()) {
// We want to differentiate between triple and quadruple clicks when 'select by camel humps' is on. The former
// is assumed to select 'hump' while the later points to the whole word.
selectWordAtCaret(false);
break;
}
//noinspection fallthrough
case 4:
mySelectionModel.selectLineAtCaret();
setMouseSelectionState(MOUSE_SELECTION_STATE_LINE_SELECTED);
mySavedSelectionStart = mySelectionModel.getSelectionStart();
mySavedSelectionEnd = mySelectionModel.getSelectionEnd();
mySelectionModel.setUnknownDirection(true);
break;
}
}
}
}
return isNavigation;
}
}
private static boolean isColumnSelectionDragEvent(@NotNull MouseEvent e) {
return e.isAltDown() && !e.isShiftDown() && !e.isControlDown() && !e.isMetaDown();
}
private static boolean isToggleCaretEvent(@NotNull MouseEvent e) {
return KeymapUtil.isMouseActionEvent(e, IdeActions.ACTION_EDITOR_ADD_OR_REMOVE_CARET) || isAddRectangularSelectionEvent(e);
}
private static boolean isAddRectangularSelectionEvent(@NotNull MouseEvent e) {
return KeymapUtil.isMouseActionEvent(e, IdeActions.ACTION_EDITOR_ADD_RECTANGULAR_SELECTION_ON_MOUSE_DRAG);
}
private static boolean isCreateRectangularSelectionEvent(@NotNull MouseEvent e) {
return KeymapUtil.isMouseActionEvent(e, IdeActions.ACTION_EDITOR_CREATE_RECTANGULAR_SELECTION);
}
private void selectWordAtCaret(boolean honorCamelCase) {
mySelectionModel.selectWordAtCaret(honorCamelCase);
setMouseSelectionState(MOUSE_SELECTION_STATE_WORD_SELECTED);
mySavedSelectionStart = mySelectionModel.getSelectionStart();
mySavedSelectionEnd = mySelectionModel.getSelectionEnd();
getCaretModel().moveToOffset(mySavedSelectionEnd);
}
/**
* Allows to answer if given event should tweak editor selection.
*
* @param e event for occurred mouse action
* @return <code>true</code> if action that produces given event will trigger editor selection change; <code>false</code> otherwise
*/
private boolean tweakSelectionEvent(@NotNull MouseEvent e) {
return getSelectionModel().hasSelection() && e.getButton() == MouseEvent.BUTTON1 && e.isShiftDown()
&& getMouseEventArea(e) == EditorMouseEventArea.LINE_NUMBERS_AREA;
}
/**
* Checks if editor selection should be changed because of click at the given point at gutter and proceeds if necessary.
* <p/>
* The main idea is that selection can be changed during left mouse clicks on the gutter line numbers area with hold
* <code>Shift</code> button. The selection should be adjusted if necessary.
*
* @param e event for mouse click on gutter area
* @return <code>true</code> if editor's selection is changed because of the click; <code>false</code> otherwise
*/
private boolean tweakSelectionIfNecessary(@NotNull MouseEvent e) {
if (!tweakSelectionEvent(e)) {
return false;
}
int startSelectionOffset = getSelectionModel().getSelectionStart();
int startVisLine = offsetToVisualLine(startSelectionOffset);
int endSelectionOffset = getSelectionModel().getSelectionEnd();
int endVisLine = offsetToVisualLine(endSelectionOffset - 1);
int clickVisLine = yPositionToVisibleLine(e.getPoint().y);
if (clickVisLine < startVisLine) {
// Expand selection at backward direction.
int startOffset = logicalPositionToOffset(visualToLogicalPosition(new VisualPosition(clickVisLine, 0)));
getSelectionModel().setSelection(startOffset, endSelectionOffset);
getCaretModel().moveToOffset(startOffset);
}
else if (clickVisLine > endVisLine) {
// Expand selection at forward direction.
int endLineOffset = EditorUtil.getVisualLineEndOffset(this, clickVisLine);
getSelectionModel().setSelection(getSelectionModel().getSelectionStart(), endLineOffset);
getCaretModel().moveToOffset(endLineOffset, true);
}
else if (startVisLine == endVisLine) {
// Remove selection
getSelectionModel().removeSelection();
}
else {
// Reduce selection in backward direction.
if (getSelectionModel().getLeadSelectionOffset() == endSelectionOffset) {
if (clickVisLine == startVisLine) {
clickVisLine++;
}
int startOffset = logicalPositionToOffset(visualToLogicalPosition(new VisualPosition(clickVisLine, 0)));
getSelectionModel().setSelection(startOffset, endSelectionOffset);
getCaretModel().moveToOffset(startOffset);
}
else {
// Reduce selection is forward direction.
if (clickVisLine == endVisLine) {
clickVisLine--;
}
int endLineOffset = EditorUtil.getVisualLineEndOffset(this, clickVisLine);
getSelectionModel().setSelection(startSelectionOffset, endLineOffset);
getCaretModel().moveToOffset(endLineOffset);
}
}
e.consume();
return true;
}
private static final TooltipGroup FOLDING_TOOLTIP_GROUP = new TooltipGroup("FOLDING_TOOLTIP_GROUP", 10);
private class MyMouseMotionListener implements MouseMotionListener {
@Override
public void mouseDragged(@NotNull MouseEvent e) {
validateMousePointer(e);
runMouseDraggedCommand(e);
EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e));
if (event.getArea() == EditorMouseEventArea.LINE_MARKERS_AREA) {
myGutterComponent.mouseDragged(e);
}
for (EditorMouseMotionListener listener : myMouseMotionListeners) {
listener.mouseDragged(event);
}
}
@Override
public void mouseMoved(@NotNull MouseEvent e) {
if (getMouseSelectionState() != MOUSE_SELECTION_STATE_NONE) {
if (myMousePressedEvent != null && myMousePressedEvent.getComponent() == e.getComponent()) {
Point lastPoint = myMousePressedEvent.getPoint();
Point point = e.getPoint();
int deadZone = Registry.intValue("editor.mouseSelectionStateResetDeadZone");
if (Math.abs(lastPoint.x - point.x) >= deadZone || Math.abs(lastPoint.y - point.y) >= deadZone) {
resetMouseSelectionState(e);
}
}
else {
validateMousePointer(e);
}
}
else {
validateMousePointer(e);
}
myMouseMovedEvent = e;
EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e));
if (e.getSource() == myGutterComponent) {
myGutterComponent.mouseMoved(e);
}
if (event.getArea() == EditorMouseEventArea.EDITING_AREA) {
FoldRegion fold = myFoldingModel.getFoldingPlaceholderAt(e.getPoint());
TooltipController controller = TooltipController.getInstance();
if (fold != null && !fold.shouldNeverExpand()) {
DocumentFragment range = createDocumentFragment(fold);
final Point p =
SwingUtilities.convertPoint((Component)e.getSource(), e.getPoint(), getComponent().getRootPane().getLayeredPane());
controller.showTooltip(EditorImpl.this, p, new DocumentFragmentTooltipRenderer(range), false, FOLDING_TOOLTIP_GROUP);
}
else {
controller.cancelTooltip(FOLDING_TOOLTIP_GROUP, e, true);
}
}
for (EditorMouseMotionListener listener : myMouseMotionListeners) {
listener.mouseMoved(event);
}
}
@NotNull
private DocumentFragment createDocumentFragment(@NotNull FoldRegion fold) {
final FoldingGroup group = fold.getGroup();
final int foldStart = fold.getStartOffset();
if (group != null) {
final int endOffset = myFoldingModel.getEndOffset(group);
if (offsetToVisualLine(endOffset) == offsetToVisualLine(foldStart)) {
return new DocumentFragment(myDocument, foldStart, endOffset);
}
}
final int oldEnd = fold.getEndOffset();
return new DocumentFragment(myDocument, foldStart, oldEnd);
}
}
private class MyColorSchemeDelegate extends DelegateColorScheme {
private final FontPreferences myFontPreferences = new FontPreferences();
private final FontPreferences myConsoleFontPreferences = new FontPreferences();
private final Map<TextAttributesKey, TextAttributes> myOwnAttributes = ContainerUtilRt.newHashMap();
private final Map<ColorKey, Color> myOwnColors = ContainerUtilRt.newHashMap();
private final EditorColorsScheme myCustomGlobalScheme;
private Map<EditorFontType, Font> myFontsMap;
private int myMaxFontSize = OptionsConstants.MAX_EDITOR_FONT_SIZE;
private int myFontSize = -1;
private int myConsoleFontSize = -1;
private String myFaceName;
private MyColorSchemeDelegate(@Nullable EditorColorsScheme globalScheme) {
super(globalScheme == null ? EditorColorsManager.getInstance().getGlobalScheme() : globalScheme);
myCustomGlobalScheme = globalScheme;
updateGlobalScheme();
}
private void reinitFonts() {
EditorColorsScheme delegate = getDelegate();
String editorFontName = getEditorFontName();
int editorFontSize = getEditorFontSize();
updatePreferences(myFontPreferences, editorFontName, editorFontSize,
delegate == null ? null : delegate.getFontPreferences());
String consoleFontName = getConsoleFontName();
int consoleFontSize = getConsoleFontSize();
updatePreferences(myConsoleFontPreferences, consoleFontName, consoleFontSize,
delegate == null ? null : delegate.getConsoleFontPreferences());
myFontsMap = new EnumMap<EditorFontType, Font>(EditorFontType.class);
myFontsMap.put(EditorFontType.PLAIN, new Font(editorFontName, Font.PLAIN, editorFontSize));
myFontsMap.put(EditorFontType.BOLD, new Font(editorFontName, Font.BOLD, editorFontSize));
myFontsMap.put(EditorFontType.ITALIC, new Font(editorFontName, Font.ITALIC, editorFontSize));
myFontsMap.put(EditorFontType.BOLD_ITALIC, new Font(editorFontName, Font.BOLD | Font.ITALIC, editorFontSize));
myFontsMap.put(EditorFontType.CONSOLE_PLAIN, new Font(consoleFontName, Font.PLAIN, consoleFontSize));
myFontsMap.put(EditorFontType.CONSOLE_BOLD, new Font(consoleFontName, Font.BOLD, consoleFontSize));
myFontsMap.put(EditorFontType.CONSOLE_ITALIC, new Font(consoleFontName, Font.ITALIC, consoleFontSize));
myFontsMap.put(EditorFontType.CONSOLE_BOLD_ITALIC, new Font(consoleFontName, Font.BOLD | Font.ITALIC, consoleFontSize));
}
private void updatePreferences(FontPreferences preferences, String fontName, int fontSize, FontPreferences delegatePreferences) {
preferences.clear();
preferences.register(fontName, fontSize);
if (delegatePreferences != null) {
boolean first = true; //skip delegate's primary font
for (String font : delegatePreferences.getRealFontFamilies()) {
if (!first) {
preferences.register(font, fontSize);
}
first = false;
}
}
}
private void reinitFontsAndSettings() {
reinitFonts();
reinitSettings();
}
@Override
public TextAttributes getAttributes(TextAttributesKey key) {
if (myOwnAttributes.containsKey(key)) return myOwnAttributes.get(key);
return getDelegate().getAttributes(key);
}
@Override
public void setAttributes(TextAttributesKey key, TextAttributes attributes) {
myOwnAttributes.put(key, attributes);
}
@Nullable
@Override
public Color getColor(ColorKey key) {
if (myOwnColors.containsKey(key)) return myOwnColors.get(key);
return getDelegate().getColor(key);
}
@Override
public void setColor(ColorKey key, Color color) {
myOwnColors.put(key, color);
// These two are here because those attributes are cached and I do not whant the clients to call editor's reinit
// settings in this case.
myCaretModel.reinitSettings();
mySelectionModel.reinitSettings();
}
@Override
public int getEditorFontSize() {
if (myFontSize == -1) {
return getDelegate().getEditorFontSize();
}
return myFontSize;
}
@Override
public void setEditorFontSize(int fontSize) {
if (fontSize < MIN_FONT_SIZE) fontSize = MIN_FONT_SIZE;
if (fontSize > myMaxFontSize) fontSize = myMaxFontSize;
if (fontSize == myFontSize) return;
myFontSize = fontSize;
reinitFontsAndSettings();
}
@NotNull
@Override
public FontPreferences getFontPreferences() {
return myFontPreferences.getEffectiveFontFamilies().isEmpty() ? getDelegate().getFontPreferences() : myFontPreferences;
}
@Override
public void setFontPreferences(@NotNull FontPreferences preferences) {
if (Comparing.equal(preferences, myFontPreferences)) return;
preferences.copyTo(myFontPreferences);
reinitFontsAndSettings();
}
@NotNull
@Override
public FontPreferences getConsoleFontPreferences() {
return myConsoleFontPreferences.getEffectiveFontFamilies().isEmpty() ?
getDelegate().getConsoleFontPreferences() : myConsoleFontPreferences;
}
@Override
public void setConsoleFontPreferences(@NotNull FontPreferences preferences) {
if (Comparing.equal(preferences, myConsoleFontPreferences)) return;
preferences.copyTo(myConsoleFontPreferences);
reinitFontsAndSettings();
}
@Override
public String getEditorFontName() {
if (myFaceName == null) {
return getDelegate().getEditorFontName();
}
return myFaceName;
}
@Override
public void setEditorFontName(String fontName) {
if (Comparing.equal(fontName, myFaceName)) return;
myFaceName = fontName;
reinitFontsAndSettings();
}
@Override
public Font getFont(EditorFontType key) {
if (myFontsMap != null) {
Font font = myFontsMap.get(key);
if (font != null) return font;
}
return getDelegate().getFont(key);
}
@Override
public void setFont(EditorFontType key, Font font) {
if (myFontsMap == null) {
reinitFontsAndSettings();
}
myFontsMap.put(key, font);
reinitSettings();
}
@Override
@Nullable
public Object clone() {
return null;
}
private void updateGlobalScheme() {
setDelegate(myCustomGlobalScheme == null ? EditorColorsManager.getInstance().getGlobalScheme() : myCustomGlobalScheme);
}
@Override
public void setDelegate(@NotNull EditorColorsScheme delegate) {
super.setDelegate(delegate);
int globalFontSize = getDelegate().getEditorFontSize();
myMaxFontSize = Math.max(OptionsConstants.MAX_EDITOR_FONT_SIZE, globalFontSize);
reinitFonts();
clearSettingsCache();
}
@Override
public void setConsoleFontSize(int fontSize) {
myConsoleFontSize = fontSize;
reinitFontsAndSettings();
}
@Override
public int getConsoleFontSize() {
return myConsoleFontSize == -1 ? super.getConsoleFontSize() : myConsoleFontSize;
}
}
private static class MyTransferHandler extends TransferHandler {
private static EditorImpl getEditor(@NotNull JComponent comp) {
EditorComponentImpl editorComponent = (EditorComponentImpl)comp;
return editorComponent.getEditor();
}
@Override
public boolean importData(@NotNull final JComponent comp, @NotNull final Transferable t) {
final EditorImpl editor = getEditor(comp);
final EditorDropHandler dropHandler = editor.getDropHandler();
if (dropHandler != null && dropHandler.canHandleDrop(t.getTransferDataFlavors())) {
dropHandler.handleDrop(t, editor.getProject(), null);
return true;
}
final int caretOffset = editor.getCaretModel().getOffset();
if (editor.myDraggedRange != null
&& editor.myDraggedRange.getStartOffset() <= caretOffset && caretOffset < editor.myDraggedRange.getEndOffset()) {
return false;
}
if (editor.myDraggedRange != null) {
editor.getCaretModel().moveToOffset(editor.mySavedCaretOffsetForDNDUndoHack);
}
CommandProcessor.getInstance().executeCommand(editor.myProject, new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
try {
editor.getSelectionModel().removeSelection();
final int offset;
if (editor.myDraggedRange != null) {
editor.getCaretModel().moveToOffset(caretOffset);
offset = caretOffset;
}
else {
offset = editor.getCaretModel().getOffset();
}
if (editor.getDocument().getRangeGuard(offset, offset) != null) {
return;
}
editor.putUserData(LAST_PASTED_REGION, null);
EditorActionHandler pasteHandler = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_PASTE);
LOG.assertTrue(pasteHandler instanceof EditorTextInsertHandler);
((EditorTextInsertHandler)pasteHandler).execute(editor, editor.getDataContext(), new Producer<Transferable>() {
@Override
public Transferable produce() {
return t;
}
});
TextRange range = editor.getUserData(LAST_PASTED_REGION);
if (range != null) {
editor.getCaretModel().moveToOffset(range.getStartOffset());
editor.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset());
}
}
catch (Exception exception) {
LOG.error(exception);
}
}
});
}
}, EditorBundle.message("paste.command.name"), DND_COMMAND_KEY, UndoConfirmationPolicy.DEFAULT, editor.getDocument());
return true;
}
@Override
public boolean canImport(@NotNull JComponent comp, @NotNull DataFlavor[] transferFlavors) {
Editor editor = getEditor(comp);
final EditorDropHandler dropHandler = ((EditorImpl)editor).getDropHandler();
if (dropHandler != null && dropHandler.canHandleDrop(transferFlavors)) {
return true;
}
if (editor.isViewer()) return false;
int offset = editor.getCaretModel().getOffset();
if (editor.getDocument().getRangeGuard(offset, offset) != null) return false;
for (DataFlavor transferFlavor : transferFlavors) {
if (transferFlavor.equals(DataFlavor.stringFlavor)) return true;
}
return false;
}
@Override
@Nullable
protected Transferable createTransferable(JComponent c) {
EditorImpl editor = getEditor(c);
String s = editor.getSelectionModel().getSelectedText();
if (s == null) return null;
int selectionStart = editor.getSelectionModel().getSelectionStart();
int selectionEnd = editor.getSelectionModel().getSelectionEnd();
editor.myDraggedRange = editor.getDocument().createRangeMarker(selectionStart, selectionEnd);
return new StringSelection(s);
}
@Override
public int getSourceActions(@NotNull JComponent c) {
return COPY_OR_MOVE;
}
@Override
protected void exportDone(@NotNull final JComponent source, @Nullable Transferable data, int action) {
if (data == null) return;
final Component last = DnDManager.getInstance().getLastDropHandler();
if (last != null && !(last instanceof EditorComponentImpl)) return;
final EditorImpl editor = getEditor(source);
if (action == MOVE && !editor.isViewer() && editor.myDraggedRange != null) {
if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), editor.getProject())) {
return;
}
CommandProcessor.getInstance().executeCommand(editor.myProject, new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
Document doc = editor.getDocument();
doc.startGuardedBlockChecking();
try {
doc.deleteString(editor.myDraggedRange.getStartOffset(), editor.myDraggedRange.getEndOffset());
}
catch (ReadOnlyFragmentModificationException e) {
EditorActionManager.getInstance().getReadonlyFragmentModificationHandler(doc).handle(e);
}
finally {
doc.stopGuardedBlockChecking();
}
}
});
}
}, EditorBundle.message("move.selection.command.name"), DND_COMMAND_KEY, UndoConfirmationPolicy.DEFAULT, editor.getDocument());
}
editor.clearDraggedRange();
}
}
private class EditorDocumentAdapter implements PrioritizedDocumentListener {
@Override
public void beforeDocumentChange(@NotNull DocumentEvent e) {
beforeChangedUpdate(e);
}
@Override
public void documentChanged(@NotNull DocumentEvent e) {
changedUpdate(e);
}
@Override
public int getPriority() {
return EditorDocumentPriorities.EDITOR_DOCUMENT_ADAPTER;
}
}
private class EditorDocumentBulkUpdateAdapter implements DocumentBulkUpdateListener {
@Override
public void updateStarted(@NotNull Document doc) {
if (doc != getDocument()) return;
bulkUpdateStarted();
}
@Override
public void updateFinished(@NotNull Document doc) {
if (doc != getDocument()) return;
bulkUpdateFinished();
}
}
@SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized")
private class EditorSizeContainer {
/**
* Holds logical line widths in pixels.
*/
private TIntArrayList myLineWidths;
private int maxCalculatedLine = -1;
/**
* Holds value that indicates if line widths recalculation should be performed.
*/
private volatile boolean myIsDirty;
/**
* Holds number of the last logical line affected by the last document change.
*/
private int myOldEndLine;
private Dimension mySize;
private int myMaxWidth = -1;
public synchronized void reset() {
int lineCount = getDocument().getLineCount();
myLineWidths = new TIntArrayList(lineCount + 300);
insertNewLines(lineCount, 0);
maxCalculatedLine = -1;
myIsDirty = true;
}
private void insertNewLines(int lineCount, int index) {
int[] values = new int[lineCount];
Arrays.fill(values, -1);
myLineWidths.insert(index, values);
if (index <= maxCalculatedLine) {
maxCalculatedLine += lineCount;
}
}
@SuppressWarnings("NonPrivateFieldAccessedInSynchronizedContext")
public synchronized void beforeChange(@NotNull DocumentEvent e) {
if (myDocument.isInBulkUpdate()) {
myMaxWidth = mySize == null ? -1 : mySize.width;
}
myOldEndLine = offsetToLogicalLine(e.getOffset() + e.getOldLength());
}
/**
* Notifies current size container about document content change.
* <p/>
* Every change is assumed to be identified by three characteristics - start, ole end and new end lines.
* <b>Example:</b>
* <pre>
* <ol>
* <li>
* Consider that we have the following document initially:
* <pre>
* line 1
* line 2
* line 3
* </pre>
* </li>
* <li>
* Let's assume that the user selected the last two lines and typed 'new line' (that effectively removed selected text).
* Current document state:
* <pre>
* line 1
* new line
* </pre>
* </li>
* <li>
* Current method is expected to be called with the following parameters:
* <ul>
* <li><b>startLine</b> is 1'</li>
* <li><b>oldEndLine</b> is 2'</li>
* <li><b>newEndLine</b> is 1'</li>
* </ul>
* </li>
* </ol>
* </pre>
*
* @param startLine logical line that contains changed fragment start offset
* @param newEndLine logical line that contains changed fragment end
* @param oldEndLine logical line that contained changed fragment end
*/
public synchronized void update(int startLine, int newEndLine, int oldEndLine) {
final int lineWidthSize = myLineWidths.size();
if (lineWidthSize == 0 || myDocument.getTextLength() <= 0) {
reset();
}
else {
final int min = Math.min(oldEndLine, newEndLine);
final boolean toAddNewLines = min >= lineWidthSize;
if (toAddNewLines) {
insertNewLines(min - lineWidthSize + 1, lineWidthSize);
}
for (int i = min; i > startLine - 1; i--) {
myLineWidths.set(i, -1);
if (maxCalculatedLine == i) maxCalculatedLine--;
}
if (newEndLine > oldEndLine) {
insertNewLines(newEndLine - oldEndLine, oldEndLine + 1);
}
else if (oldEndLine > newEndLine && !toAddNewLines && newEndLine + 1 < lineWidthSize) {
int length = Math.min(oldEndLine, lineWidthSize) - newEndLine - 1;
int index = newEndLine + 1;
myLineWidths.remove(index, length);
if (index <= maxCalculatedLine) {
maxCalculatedLine -= length;
}
}
myIsDirty = true;
}
}
/**
* Notifies current container about visual width change of the target logical line.
* <p/>
* Please note that there is a possible case that particular logical line is represented in more than one visual lines,
* hence, this method may be called multiple times with the same logical line argument but different with values. Current
* container is expected to store max of the given values then.
*
* @param logicalLine logical line which visual width is changed
* @param widthInPixels visual width of the given logical line
*/
public synchronized void updateLineWidthIfNecessary(int logicalLine, int widthInPixels) {
if (logicalLine < myLineWidths.size()) {
int currentWidth = myLineWidths.get(logicalLine);
if (widthInPixels > currentWidth) {
myLineWidths.set(logicalLine, widthInPixels);
}
if (widthInPixels > myMaxWidth) {
myMaxWidth = widthInPixels;
}
maxCalculatedLine = Math.max(maxCalculatedLine, logicalLine);
}
}
public synchronized void changedUpdate(@NotNull DocumentEvent e) {
int startLine = e.getOldLength() == 0 ? myOldEndLine : myDocument.getLineNumber(e.getOffset());
int newEndLine = e.getNewLength() == 0 ? startLine : myDocument.getLineNumber(e.getOffset() + e.getNewLength());
int oldEndLine = myOldEndLine;
update(startLine, newEndLine, oldEndLine);
}
@SuppressWarnings({"NonPrivateFieldAccessedInSynchronizedContext", "AssignmentToForLoopParameter"})
private void validateSizes() {
if (!myIsDirty && !(myLinePaintersWidth > myMaxWidth)) return;
synchronized (this) {
if (!myIsDirty) return;
int lineCount = Math.min(myLineWidths.size(), myDocument.getLineCount());
if (myMaxWidth != -1 && myDocument.isInBulkUpdate()) {
mySize = new Dimension(myMaxWidth, getLineHeight() * lineCount);
myIsDirty = false;
return;
}
final CharSequence text = myDocument.getImmutableCharSequence();
int documentLength = myDocument.getTextLength();
int x = 0;
boolean lastLineLengthCalculated = false;
List<? extends SoftWrap> softWraps = getSoftWrapModel().getRegisteredSoftWraps();
int softWrapsIndex = -1;
CharWidthCache charWidthCache = new CharWidthCache(EditorImpl.this);
for (int line = 0; line < lineCount; line++) {
if (myLineWidths.getQuick(line) != -1) continue;
if (line == lineCount - 1) {
lastLineLengthCalculated = true;
}
x = 0;
int offset = myDocument.getLineStartOffset(line);
if (offset >= myDocument.getTextLength()) {
myLineWidths.set(line, 0);
maxCalculatedLine = Math.max(maxCalculatedLine, line);
break;
}
if (softWrapsIndex < 0) {
softWrapsIndex = getSoftWrapModel().getSoftWrapIndex(offset);
if (softWrapsIndex < 0) {
softWrapsIndex = -softWrapsIndex - 1;
}
}
int endLine;
if (maxCalculatedLine < line + 1) {
endLine = lineCount;
}
else {
for (endLine = line + 1; endLine < maxCalculatedLine; endLine++) {
if (myLineWidths.getQuick(endLine) != -1) {
break;
}
}
}
int endOffset = endLine >= lineCount ? documentLength : myDocument.getLineEndOffset(endLine);
for (
FoldRegion region = myFoldingModel.getCollapsedRegionAtOffset(endOffset);
region != null && endOffset < myDocument.getTextLength();
region = myFoldingModel.getCollapsedRegionAtOffset(endOffset))
{
final int lineNumber = myDocument.getLineNumber(region.getEndOffset());
endOffset = myDocument.getLineEndOffset(lineNumber);
}
if (endOffset > myDocument.getTextLength()) {
break;
}
IterationState state = new IterationState(EditorImpl.this, offset, endOffset, false);
int fontType = state.getMergedAttributes().getFontType();
int maxPreviousSoftWrappedWidth = -1;
while (offset < documentLength && line < lineCount) {
char c = text.charAt(offset);
if (offset >= state.getEndOffset()) {
state.advance();
fontType = state.getMergedAttributes().getFontType();
}
while (softWrapsIndex < softWraps.size() && line < lineCount) {
SoftWrap softWrap = softWraps.get(softWrapsIndex);
if (softWrap.getStart() > offset) {
break;
}
softWrapsIndex++;
if (softWrap.getStart() == offset) {
maxPreviousSoftWrappedWidth = Math.max(maxPreviousSoftWrappedWidth, x);
x = softWrap.getIndentInPixels();
}
}
FoldRegion collapsed = state.getCurrentFold();
if (collapsed != null) {
String placeholder = collapsed.getPlaceholderText();
for (int i = 0; i < placeholder.length(); i++) {
x += charWidthCache.charWidth(placeholder.charAt(i), fontType);
}
offset = collapsed.getEndOffset();
line = myDocument.getLineNumber(offset);
}
else if (c == '\t') {
x = EditorUtil.nextTabStop(x, EditorImpl.this);
offset++;
}
else if (c == '\n') {
int width = Math.max(x, maxPreviousSoftWrappedWidth);
myLineWidths.set(line, width);
maxCalculatedLine = Math.max(maxCalculatedLine, line);
if (line + 1 >= lineCount || myLineWidths.getQuick(line + 1) != -1) break;
offset++;
x = 0;
//noinspection AssignmentToForLoopParameter
line++;
if (line == lineCount - 1) {
lastLineLengthCalculated = true;
}
}
else {
x += charWidthCache.charWidth(c, fontType);
offset++;
}
}
}
if (lineCount > 0 && lastLineLengthCalculated) {
myLineWidths.set(lineCount - 1,
x); // Last line can be non-zero length and won't be caught by in-loop procedure since latter only react on \n's
maxCalculatedLine = Math.max(maxCalculatedLine, lineCount - 1);
}
// There is a following possible situation:
// 1. Big document is opened at editor;
// 2. Soft wraps are calculated for the current visible area;
// 2. The user scrolled down;
// 3. The user significantly reduced visible area width (say, reduced it twice);
// 4. Soft wraps are calculated for the current visible area;
// We need to consider only the widths for the logical lines that are completely shown at the current visible area then.
// I.e. we shouldn't use widths of the lines that are not shown for max width calculation because previous widths are calculated
// for another visible area width.
int startToUse = 0;
int endToUse = Math.min(lineCount, myLineWidths.size());
if (endToUse > 0 && getSoftWrapModel().isSoftWrappingEnabled()) {
Rectangle visibleArea = getScrollingModel().getVisibleArea();
startToUse = EditorUtil.yPositionToLogicalLine(EditorImpl.this, visibleArea.getLocation());
endToUse = Math.min(endToUse, EditorUtil.yPositionToLogicalLine(EditorImpl.this, visibleArea.y + visibleArea.height));
if (endToUse <= startToUse) {
// There is a possible case that there is the only soft-wrapped line, i.e. end == start. We still want to update the
// size container's width then.
endToUse = Math.min(myLineWidths.size(), startToUse + 1);
}
}
int maxWidth = 0;
for (int i = startToUse; i < endToUse; i++) {
maxWidth = Math.max(maxWidth, myLineWidths.getQuick(i));
}
mySize = new Dimension(maxWidth, getLineHeight() * Math.max(getVisibleLineCount(), 1));
myIsDirty = false;
}
}
@NotNull
private Dimension getContentSize() {
validateSizes();
return new Dimension(Math.max(mySize.width, myLinePaintersWidth), mySize.height);
}
}
@Override
@NotNull
public EditorGutter getGutter() {
return getGutterComponentEx();
}
@Override
public int calcColumnNumber(@NotNull CharSequence text, int start, int offset, int tabSize) {
if (myUseNewRendering) return myView.offsetToLogicalPosition(offset).column;
IterationState state = new IterationState(this, start, offset, false);
int fontType = state.getMergedAttributes().getFontType();
int column = 0;
int x = 0;
int plainSpaceSize = EditorUtil.getSpaceWidth(Font.PLAIN, this);
for (int i = start; i < offset; i++) {
if (i >= state.getEndOffset()) {
state.advance();
fontType = state.getMergedAttributes().getFontType();
}
SoftWrap softWrap = getSoftWrapModel().getSoftWrap(i);
if (softWrap != null) {
x = softWrap.getIndentInPixels();
}
char c = text.charAt(i);
if (c == '\t') {
int prevX = x;
x = EditorUtil.nextTabStop(x, this);
column += EditorUtil.columnsNumber(c, x, prevX, plainSpaceSize);
}
else {
x += EditorUtil.charWidth(c, fontType, this);
column++;
}
}
return column;
}
boolean isInDistractionFreeMode() {
return EditorUtil.isRealFileEditor(this)
&& (Registry.is("editor.distraction.free.mode") || isInPresentationMode());
}
boolean isInPresentationMode() {
return UISettings.getInstance().PRESENTATION_MODE && EditorUtil.isRealFileEditor(this);
}
@Override
public void putInfo(@NotNull Map<String, String> info) {
final VisualPosition visual = getCaretModel().getVisualPosition();
info.put("caret", visual.getLine() + ":" + visual.getColumn());
}
private class MyScrollPane extends JBScrollPane {
private MyScrollPane() {
super(0);
setupCorners();
}
@Override
public void layout() {
if (isInDistractionFreeMode()) {
// re-calc gutter extra size after editor size is set
// & layout once again to avoid blinking
myGutterComponent.updateSize(true);
}
super.layout();
}
@Override
protected void processMouseWheelEvent(@NotNull MouseWheelEvent e) {
if (mySettings.isWheelFontChangeEnabled() && !MouseGestureManager.getInstance().hasTrackpad()) {
if (EditorUtil.isChangeFontSize(e)) {
int size = myScheme.getEditorFontSize() - e.getWheelRotation();
if (size >= MIN_FONT_SIZE) {
setFontSize(size, SwingUtilities.convertPoint(this, e.getPoint(), getViewport()));
}
return;
}
}
super.processMouseWheelEvent(e);
}
@NotNull
@Override
public JScrollBar createVerticalScrollBar() {
return new MyScrollBar(Adjustable.VERTICAL);
}
@NotNull
@Override
public JScrollBar createHorizontalScrollBar() {
return new MyScrollBar(Adjustable.HORIZONTAL);
}
@Override
protected void setupCorners() {
super.setupCorners();
setBorder(new TablessBorder());
}
@Override
protected boolean isOverlaidScrollbar(@Nullable JScrollBar scrollbar) {
ScrollBarUI vsbUI = scrollbar == null ? null : scrollbar.getUI();
return vsbUI instanceof ButtonlessScrollBarUI && !((ButtonlessScrollBarUI)vsbUI).alwaysShowTrack();
}
}
private class TablessBorder extends SideBorder {
private TablessBorder() {
super(JBColor.border(), SideBorder.ALL);
}
@Override
public void paintBorder(@NotNull Component c, @NotNull Graphics g, int x, int y, int width, int height) {
if (c instanceof JComponent) {
Insets insets = ((JComponent)c).getInsets();
if (insets.left > 0) {
super.paintBorder(c, g, x, y, width, height);
}
else {
g.setColor(UIUtil.getPanelBackground());
g.fillRect(x, y, width, 1);
g.setColor(Gray._50.withAlpha(90));
g.fillRect(x, y, width, 1);
}
}
}
@NotNull
@Override
public Insets getBorderInsets(Component c) {
Container splitters = SwingUtilities.getAncestorOfClass(EditorsSplitters.class, c);
boolean thereIsSomethingAbove = !SystemInfo.isMac || UISettings.getInstance().SHOW_MAIN_TOOLBAR || UISettings.getInstance().SHOW_NAVIGATION_BAR ||
toolWindowIsNotEmpty();
//noinspection ConstantConditions
Component header = myHeaderPanel == null ? null : ArrayUtil.getFirstElement(myHeaderPanel.getComponents());
boolean paintTop = thereIsSomethingAbove && header == null && UISettings.getInstance().EDITOR_TAB_PLACEMENT != SwingConstants.TOP;
return splitters == null ? super.getBorderInsets(c) : new Insets(paintTop ? 1 : 0, 0, 0, 0);
}
private boolean toolWindowIsNotEmpty() {
if (myProject == null) return false;
ToolWindowManagerEx m = ToolWindowManagerEx.getInstanceEx(myProject);
return m != null && !m.getIdsOn(ToolWindowAnchor.TOP).isEmpty();
}
@Override
public boolean isBorderOpaque() {
return true;
}
}
private class MyHeaderPanel extends JPanel {
private int myOldHeight;
private MyHeaderPanel() {
super(new BorderLayout());
}
@Override
public void revalidate() {
myOldHeight = getHeight();
super.revalidate();
}
@Override
protected void validateTree() {
int height = myOldHeight;
super.validateTree();
height -= getHeight();
if (height != 0) {
myVerticalScrollBar.setValue(myVerticalScrollBar.getValue() - height);
}
myOldHeight = getHeight();
}
}
private class MyTextDrawingCallback implements TextDrawingCallback {
@Override
public void drawChars(@NotNull Graphics g,
@NotNull char[] data,
int start,
int end,
int x,
int y,
Color color,
@NotNull FontInfo fontInfo)
{
if (myUseNewRendering) {
myView.drawChars(g, data, start, end, x, y, color, fontInfo);
}
else {
drawCharsCached(g, new CharArrayCharSequence(data), start, end, x, y, fontInfo, color, false);
}
}
}
private interface WhitespacePaintingStrategy {
boolean showWhitespaceAtOffset(int offset);
}
private static final WhitespacePaintingStrategy PAINT_NO_WHITESPACE = new WhitespacePaintingStrategy() {
@Override
public boolean showWhitespaceAtOffset(int offset) {
return false;
}
};
// Strategy, controlled by current editor settings. Usable only for the current line.
public class LineWhitespacePaintingStrategy implements WhitespacePaintingStrategy {
private final boolean myWhitespaceShown = mySettings.isWhitespacesShown();
private final boolean myLeadingWhitespaceShown = mySettings.isLeadingWhitespaceShown();
private final boolean myInnerWhitespaceShown = mySettings.isInnerWhitespaceShown();
private final boolean myTrailingWhitespaceShown = mySettings.isTrailingWhitespaceShown();
// Offsets on current line where leading whitespace ends and trailing whitespace starts correspondingly.
private int currentLeadingEdge;
private int currentTrailingEdge;
// Updates the state, to be used for the line, iterator is currently at.
public void update(CharSequence chars, LineIterator iterator) {
int lineStart = iterator.getStart();
int lineEnd = iterator.getEnd() - iterator.getSeparatorLength();
update(chars, lineStart, lineEnd);
}
public void update(CharSequence chars, int lineStart, int lineEnd) {
if (myWhitespaceShown
&& (myLeadingWhitespaceShown || myInnerWhitespaceShown || myTrailingWhitespaceShown)
&& !(myLeadingWhitespaceShown && myInnerWhitespaceShown && myTrailingWhitespaceShown)) {
currentTrailingEdge = CharArrayUtil.shiftBackward(chars, lineStart, lineEnd - 1, WHITESPACE_CHARS) + 1;
currentLeadingEdge = CharArrayUtil.shiftForward(chars, lineStart, currentTrailingEdge, WHITESPACE_CHARS);
}
}
@Override
public boolean showWhitespaceAtOffset(int offset) {
return myWhitespaceShown
&& (offset < currentLeadingEdge ? myLeadingWhitespaceShown :
offset >= currentTrailingEdge ? myTrailingWhitespaceShown :
myInnerWhitespaceShown);
}
}
private class MyEditorPopupHandler extends EditorMouseAdapter {
@Override
public void mouseReleased(EditorMouseEvent e) {
invokePopupIfNeeded(e);
}
@Override
public void mousePressed(EditorMouseEvent e) {
invokePopupIfNeeded(e);
}
@Override
public void mouseClicked(EditorMouseEvent e) {
invokePopupIfNeeded(e);
}
private void invokePopupIfNeeded(EditorMouseEvent event) {
if (myContextMenuGroupId != null &&
event.getArea() == EditorMouseEventArea.EDITING_AREA &&
event.getMouseEvent().isPopupTrigger() &&
!event.isConsumed()) {
AnAction action = CustomActionsSchema.getInstance().getCorrectedAction(myContextMenuGroupId);
if (action instanceof ActionGroup) {
ActionPopupMenu popupMenu = ActionManager.getInstance().createActionPopupMenu(ActionPlaces.EDITOR_POPUP, (ActionGroup)action);
MouseEvent e = event.getMouseEvent();
final Component c = e.getComponent();
if (c != null && c.isShowing()) {
popupMenu.getComponent().show(c, e.getX(), e.getY());
}
e.consume();
}
}
}
}
}
| Zero-latency typing: workaround for VIM-1007
| platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java | Zero-latency typing: workaround for VIM-1007 | <ide><path>latform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java
<ide> import com.intellij.diagnostic.LogMessageEx;
<ide> import com.intellij.ide.*;
<ide> import com.intellij.ide.dnd.DnDManager;
<add>import com.intellij.ide.plugins.IdeaPluginDescriptor;
<add>import com.intellij.ide.plugins.PluginManager;
<ide> import com.intellij.ide.ui.UISettings;
<ide> import com.intellij.ide.ui.customization.CustomActionsSchema;
<ide> import com.intellij.openapi.Disposable;
<ide> import com.intellij.openapi.editor.impl.softwrap.SoftWrapDrawingType;
<ide> import com.intellij.openapi.editor.impl.view.EditorView;
<ide> import com.intellij.openapi.editor.markup.*;
<add>import com.intellij.openapi.extensions.PluginId;
<ide> import com.intellij.openapi.fileEditor.FileDocumentManager;
<ide> import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory;
<ide> import com.intellij.openapi.fileEditor.impl.EditorsSplitters;
<ide> private Rectangle myOldTailArea = new Rectangle(0, 0, 0, 0);
<ide> private boolean myImmediateEditingInProgress;
<ide>
<add> // TODO Should be removed when IDEA adopts typing without starting write actions.
<add> private static final boolean VIM_PLUGIN_LOADED = isPluginLoaded("IdeaVIM");
<add>
<ide> static {
<ide> ourCaretBlinkingCommand.start();
<ide> }
<ide> }
<ide>
<ide> private static boolean isZeroLatencyTypingEnabled() {
<del> return Registry.is("editor.zero.latency.typing");
<add> // Zero-latency typing is suppressed when Idea VIM plugin is loaded, because of VIM-1007.
<add> // That issue will be resolved automatically when IDEA adopts typing without starting write actions.
<add> return !VIM_PLUGIN_LOADED && Registry.is("editor.zero.latency.typing");
<add> }
<add>
<add> private static boolean isPluginLoaded(@NotNull String id) {
<add> PluginId pluginId = PluginId.findId(id);
<add> if (pluginId == null) return false;
<add> IdeaPluginDescriptor plugin = PluginManager.getPlugin(pluginId);
<add> if (plugin == null) return false;
<add> return plugin.isEnabled();
<ide> }
<ide>
<ide> private boolean canPaintImmediately(char c) { |
|
Java | apache-2.0 | 5f05589a4738e8fa6f9007edde40e8012db2edd0 | 0 | androidx/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx | /*
* Copyright 2019 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 androidx.fragment.app;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.graphics.Rect;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.collection.ArrayMap;
import androidx.core.app.SharedElementCallback;
import androidx.core.os.CancellationSignal;
import androidx.core.util.Preconditions;
import androidx.core.view.OneShotPreDrawListener;
import androidx.core.view.ViewCompat;
import androidx.core.view.ViewGroupCompat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* A SpecialEffectsController that hooks into the existing Fragment APIs to run
* animations and transitions.
*/
class DefaultSpecialEffectsController extends SpecialEffectsController {
DefaultSpecialEffectsController(@NonNull ViewGroup container) {
super(container);
}
@Override
void executeOperations(@NonNull List<Operation> operations, boolean isPop) {
// Shared element transitions are done between the first fragment leaving and
// the last fragment coming in. Finding these operations is the first priority
Operation firstOut = null;
Operation lastIn = null;
for (final Operation operation : operations) {
Operation.State currentState = Operation.State.from(operation.getFragment().mView);
switch (operation.getFinalState()) {
case GONE:
case INVISIBLE:
case REMOVED:
if (currentState == Operation.State.VISIBLE && firstOut == null) {
// The firstOut Operation is the first Operation moving from VISIBLE
firstOut = operation;
}
break;
case VISIBLE:
if (currentState != Operation.State.VISIBLE) {
// The last Operation that moves to VISIBLE is the lastIn Operation
lastIn = operation;
}
break;
}
}
// Now iterate through the operations, collecting the set of animations
// and transitions that need to be executed
List<AnimationInfo> animations = new ArrayList<>();
List<TransitionInfo> transitions = new ArrayList<>();
final List<Operation> awaitingContainerChanges = new ArrayList<>(operations);
for (final Operation operation : operations) {
// Create the animation CancellationSignal
CancellationSignal animCancellationSignal = new CancellationSignal();
operation.markStartedSpecialEffect(animCancellationSignal);
// Add the animation special effect
animations.add(new AnimationInfo(operation, animCancellationSignal, isPop));
// Create the transition CancellationSignal
CancellationSignal transitionCancellationSignal = new CancellationSignal();
operation.markStartedSpecialEffect(transitionCancellationSignal);
// Add the transition special effect
transitions.add(new TransitionInfo(operation, transitionCancellationSignal, isPop,
isPop ? operation == firstOut : operation == lastIn));
// Ensure that if the Operation is synchronously complete, we still
// apply the container changes before the Operation completes
operation.addCompletionListener(new Runnable() {
@Override
public void run() {
if (awaitingContainerChanges.contains(operation)) {
awaitingContainerChanges.remove(operation);
applyContainerChanges(operation);
}
}
});
}
// Start transition special effects
Map<Operation, Boolean> startedTransitions = startTransitions(transitions,
awaitingContainerChanges, isPop, firstOut, lastIn);
boolean startedAnyTransition = startedTransitions.containsValue(true);
// Start animation special effects
startAnimations(animations, awaitingContainerChanges,
startedAnyTransition, startedTransitions);
for (final Operation operation : awaitingContainerChanges) {
applyContainerChanges(operation);
}
awaitingContainerChanges.clear();
}
private void startAnimations(@NonNull List<AnimationInfo> animationInfos,
@NonNull List<Operation> awaitingContainerChanges,
boolean startedAnyTransition, @NonNull Map<Operation, Boolean> startedTransitions) {
final ViewGroup container = getContainer();
final Context context = container.getContext();
ArrayList<AnimationInfo> animationsToRun = new ArrayList<>();
// First run Animators
boolean startedAnyAnimator = false;
for (final AnimationInfo animationInfo : animationInfos) {
if (animationInfo.isVisibilityUnchanged()) {
// No change in visibility, so we can immediately complete the animation
animationInfo.completeSpecialEffect();
continue;
}
FragmentAnim.AnimationOrAnimator anim = animationInfo.getAnimation(context);
if (anim == null) {
// No Animator or Animation, so we can immediately complete the animation
animationInfo.completeSpecialEffect();
continue;
}
final Animator animator = anim.animator;
if (animator == null) {
// We must have an Animation to run. Save those for a second pass
animationsToRun.add(animationInfo);
continue;
}
// First make sure we haven't already started a Transition for this Operation
final Operation operation = animationInfo.getOperation();
final Fragment fragment = operation.getFragment();
boolean startedTransition = Boolean.TRUE.equals(startedTransitions.get(operation));
if (startedTransition) {
if (FragmentManager.isLoggingEnabled(Log.VERBOSE)) {
Log.v(FragmentManager.TAG, "Ignoring Animator set on "
+ fragment + " as this Fragment was involved in a Transition.");
}
animationInfo.completeSpecialEffect();
continue;
}
// Okay, let's run the Animator!
startedAnyAnimator = true;
final boolean isHideOperation = operation.getFinalState() == Operation.State.GONE;
if (isHideOperation) {
// We don't want to immediately applyState() to hide operations as that
// immediately stops the Animator. Instead we'll applyState() manually
// when the Animator ends.
awaitingContainerChanges.remove(operation);
}
final View viewToAnimate = fragment.mView;
container.startViewTransition(viewToAnimate);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator anim) {
container.endViewTransition(viewToAnimate);
if (isHideOperation) {
// Specifically for hide operations with Animator, we can't
// applyState until the Animator finishes
operation.getFinalState().applyState(viewToAnimate);
}
animationInfo.completeSpecialEffect();
}
});
animator.setTarget(viewToAnimate);
animator.start();
// Listen for cancellation and use that to cancel the Animator
CancellationSignal signal = animationInfo.getSignal();
signal.setOnCancelListener(new CancellationSignal.OnCancelListener() {
@Override
public void onCancel() {
animator.end();
}
});
}
// Now run Animations
for (final AnimationInfo animationInfo : animationsToRun) {
// First make sure we haven't already started any Transition
final Operation operation = animationInfo.getOperation();
final Fragment fragment = operation.getFragment();
if (startedAnyTransition) {
if (FragmentManager.isLoggingEnabled(Log.VERBOSE)) {
Log.v(FragmentManager.TAG, "Ignoring Animation set on "
+ fragment + " as Animations cannot run alongside Transitions.");
}
animationInfo.completeSpecialEffect();
continue;
}
// Then make sure we haven't already started any Animator
if (startedAnyAnimator) {
if (FragmentManager.isLoggingEnabled(Log.VERBOSE)) {
Log.v(FragmentManager.TAG, "Ignoring Animation set on "
+ fragment + " as Animations cannot run alongside Animators.");
}
animationInfo.completeSpecialEffect();
continue;
}
// Okay, let's run the Animation!
final View viewToAnimate = fragment.mView;
Animation anim = Preconditions.checkNotNull(
Preconditions.checkNotNull(animationInfo.getAnimation(context)).animation);
Operation.State finalState = operation.getFinalState();
if (finalState != Operation.State.REMOVED) {
// If the operation does not remove the view, we can't use a
// AnimationSet due that causing the introduction of visual artifacts (b/163084315).
viewToAnimate.startAnimation(anim);
// This means we can't use setAnimationListener() without overriding
// any listener that the Fragment has set themselves, so we
// just mark the special effect as complete immediately.
animationInfo.completeSpecialEffect();
} else {
container.startViewTransition(viewToAnimate);
final Animation animation = new FragmentAnim.EndViewTransitionAnimation(
anim, container, viewToAnimate);
animation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
// onAnimationEnd() comes during draw(), so there can still be some
// draw events happening after this call. We don't want to complete the
// animation until after the onAnimationEnd()
container.post(new Runnable() {
@Override
public void run() {
container.endViewTransition(viewToAnimate);
animationInfo.completeSpecialEffect();
}
});
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
viewToAnimate.startAnimation(animation);
}
// Listen for cancellation and use that to cancel the Animation
CancellationSignal signal = animationInfo.getSignal();
signal.setOnCancelListener(new CancellationSignal.OnCancelListener() {
@Override
public void onCancel() {
viewToAnimate.clearAnimation();
container.endViewTransition(viewToAnimate);
animationInfo.completeSpecialEffect();
}
});
}
}
@NonNull
private Map<Operation, Boolean> startTransitions(@NonNull List<TransitionInfo> transitionInfos,
@NonNull List<Operation> awaitingContainerChanges,
final boolean isPop, @Nullable final Operation firstOut,
@Nullable final Operation lastIn) {
Map<Operation, Boolean> startedTransitions = new HashMap<>();
// First verify that we can run all transitions together
FragmentTransitionImpl transitionImpl = null;
for (TransitionInfo transitionInfo : transitionInfos) {
if (transitionInfo.isVisibilityUnchanged()) {
// No change in visibility, so we can skip this TransitionInfo
continue;
}
FragmentTransitionImpl handlingImpl = transitionInfo.getHandlingImpl();
if (transitionImpl == null) {
transitionImpl = handlingImpl;
} else if (handlingImpl != null && transitionImpl != handlingImpl) {
throw new IllegalArgumentException("Mixing framework transitions and "
+ "AndroidX transitions is not allowed. Fragment "
+ transitionInfo.getOperation().getFragment() + " returned Transition "
+ transitionInfo.getTransition() + " which uses a different Transition "
+ " type than other Fragments.");
}
}
if (transitionImpl == null) {
// There were no transitions at all so we can just complete all of them
for (TransitionInfo transitionInfo : transitionInfos) {
startedTransitions.put(transitionInfo.getOperation(), false);
transitionInfo.completeSpecialEffect();
}
return startedTransitions;
}
// Every transition needs to target at least one View so that they
// don't interfere with one another. This is the view we use
// in cases where there are no real views to target
final View nonExistentView = new View(getContainer().getContext());
// Now find the shared element transition if it exists
Object sharedElementTransition = null;
View firstOutEpicenterView = null;
boolean hasLastInEpicenter = false;
final Rect lastInEpicenterRect = new Rect();
ArrayList<View> sharedElementFirstOutViews = new ArrayList<>();
ArrayList<View> sharedElementLastInViews = new ArrayList<>();
ArrayMap<String, String> sharedElementNameMapping = new ArrayMap<>();
for (final TransitionInfo transitionInfo : transitionInfos) {
boolean hasSharedElementTransition = transitionInfo.hasSharedElementTransition();
// Compute the shared element transition between the firstOut and lastIn Fragments
if (hasSharedElementTransition && firstOut != null && lastIn != null) {
// swapSharedElementTargets requires wrapping this in a TransitionSet
sharedElementTransition = transitionImpl.wrapTransitionInSet(
transitionImpl.cloneTransition(
transitionInfo.getSharedElementTransition()));
// The exiting shared elements default to the source names from the
// last in fragment
ArrayList<String> exitingNames = lastIn.getFragment()
.getSharedElementSourceNames();
// But if we're doing multiple transactions, we may need to re-map
// the names from the first out fragment
ArrayList<String> firstOutSourceNames = firstOut.getFragment()
.getSharedElementSourceNames();
ArrayList<String> firstOutTargetNames = firstOut.getFragment()
.getSharedElementTargetNames();
// We do this by iterating through each first out target,
// seeing if there is a match from the last in sources
for (int index = 0; index < firstOutTargetNames.size(); index++) {
int nameIndex = exitingNames.indexOf(firstOutTargetNames.get(index));
if (nameIndex != -1) {
// If we found a match, replace the last in source name
// with the first out source name
exitingNames.set(nameIndex, firstOutSourceNames.get(index));
}
}
ArrayList<String> enteringNames = lastIn.getFragment()
.getSharedElementTargetNames();
SharedElementCallback exitingCallback;
SharedElementCallback enteringCallback;
if (!isPop) {
// Forward transitions have firstOut fragment exiting and the
// lastIn fragment entering
exitingCallback = firstOut.getFragment().getExitTransitionCallback();
enteringCallback = lastIn.getFragment().getEnterTransitionCallback();
} else {
// A pop is the reverse: the firstOut fragment is entering and the
// lastIn fragment is exiting
exitingCallback = firstOut.getFragment().getEnterTransitionCallback();
enteringCallback = lastIn.getFragment().getExitTransitionCallback();
}
int numSharedElements = exitingNames.size();
for (int i = 0; i < numSharedElements; i++) {
String exitingName = exitingNames.get(i);
String enteringName = enteringNames.get(i);
sharedElementNameMapping.put(exitingName, enteringName);
}
// Find all of the Views from the firstOut fragment that are
// part of the shared element transition
final ArrayMap<String, View> firstOutViews = new ArrayMap<>();
findNamedViews(firstOutViews, firstOut.getFragment().mView);
firstOutViews.retainAll(exitingNames);
if (exitingCallback != null) {
// Give the SharedElementCallback a chance to override the default mapping
exitingCallback.onMapSharedElements(exitingNames, firstOutViews);
for (int i = exitingNames.size() - 1; i >= 0; i--) {
String name = exitingNames.get(i);
View view = firstOutViews.get(name);
if (view == null) {
sharedElementNameMapping.remove(name);
} else if (!name.equals(ViewCompat.getTransitionName(view))) {
String targetValue = sharedElementNameMapping.remove(name);
sharedElementNameMapping.put(ViewCompat.getTransitionName(view),
targetValue);
}
}
} else {
// Only keep the mapping of elements that were found in the firstOut Fragment
sharedElementNameMapping.retainAll(firstOutViews.keySet());
}
// Find all of the Views from the lastIn fragment that are
// part of the shared element transition
final ArrayMap<String, View> lastInViews = new ArrayMap<>();
findNamedViews(lastInViews, lastIn.getFragment().mView);
lastInViews.retainAll(enteringNames);
lastInViews.retainAll(sharedElementNameMapping.values());
if (enteringCallback != null) {
// Give the SharedElementCallback a chance to override the default mapping
enteringCallback.onMapSharedElements(enteringNames, lastInViews);
for (int i = enteringNames.size() - 1; i >= 0; i--) {
String name = enteringNames.get(i);
View view = lastInViews.get(name);
if (view == null) {
String key = FragmentTransition.findKeyForValue(
sharedElementNameMapping, name);
if (key != null) {
sharedElementNameMapping.remove(key);
}
} else if (!name.equals(ViewCompat.getTransitionName(view))) {
String key = FragmentTransition.findKeyForValue(
sharedElementNameMapping, name);
if (key != null) {
sharedElementNameMapping.put(key,
ViewCompat.getTransitionName(view));
}
}
}
} else {
// Only keep the mapping of elements that were found in the lastIn Fragment
FragmentTransition.retainValues(sharedElementNameMapping, lastInViews);
}
// Now make a final pass through the Views list to ensure they
// don't still have elements that were removed from the mapping
retainMatchingViews(firstOutViews, sharedElementNameMapping.keySet());
retainMatchingViews(lastInViews, sharedElementNameMapping.values());
if (sharedElementNameMapping.isEmpty()) {
// We couldn't find any valid shared element mappings, so clear out
// the shared element transition information entirely
sharedElementTransition = null;
sharedElementFirstOutViews.clear();
sharedElementLastInViews.clear();
} else {
// Call through to onSharedElementStart() before capturing the
// starting values for the shared element transition
FragmentTransition.callSharedElementStartEnd(
lastIn.getFragment(), firstOut.getFragment(), isPop,
firstOutViews, true);
// Trigger the onSharedElementEnd callback in the next frame after
// the starting values are captured and before capturing the end states
OneShotPreDrawListener.add(getContainer(), new Runnable() {
@Override
public void run() {
FragmentTransition.callSharedElementStartEnd(
lastIn.getFragment(), firstOut.getFragment(), isPop,
lastInViews, false);
}
});
sharedElementFirstOutViews.addAll(firstOutViews.values());
// Compute the epicenter of the firstOut transition
if (!exitingNames.isEmpty()) {
String epicenterViewName = exitingNames.get(0);
firstOutEpicenterView = firstOutViews.get(epicenterViewName);
transitionImpl.setEpicenter(sharedElementTransition,
firstOutEpicenterView);
}
sharedElementLastInViews.addAll(lastInViews.values());
// Compute the epicenter of the lastIn transition
if (!enteringNames.isEmpty()) {
String epicenterViewName = enteringNames.get(0);
final View lastInEpicenterView = lastInViews.get(epicenterViewName);
if (lastInEpicenterView != null) {
hasLastInEpicenter = true;
// We can't set the epicenter here directly since the View might
// not have been laid out as of yet, so instead we set a Rect as
// the epicenter and compute the bounds one frame later
final FragmentTransitionImpl impl = transitionImpl;
OneShotPreDrawListener.add(getContainer(), new Runnable() {
@Override
public void run() {
impl.getBoundsOnScreen(lastInEpicenterView,
lastInEpicenterRect);
}
});
}
}
// Now set the transition's targets to only the firstOut Fragment's views
// It'll be swapped to the lastIn Fragment's views after the
// transition is started
transitionImpl.setSharedElementTargets(sharedElementTransition,
nonExistentView, sharedElementFirstOutViews);
// After the swap to the lastIn Fragment's view (done below), we
// need to clean up those targets. We schedule this here so that it
// runs directly after the swap
transitionImpl.scheduleRemoveTargets(sharedElementTransition,
null, null, null, null,
sharedElementTransition, sharedElementLastInViews);
// Both the firstOut and lastIn Operations are now associated
// with a Transition
startedTransitions.put(firstOut, true);
startedTransitions.put(lastIn, true);
}
}
}
ArrayList<View> enteringViews = new ArrayList<>();
// These transitions run together, overlapping one another
Object mergedTransition = null;
// These transitions run only after all of the other transitions complete
Object mergedNonOverlappingTransition = null;
// Now iterate through the set of transitions and merge them together
for (final TransitionInfo transitionInfo : transitionInfos) {
if (transitionInfo.isVisibilityUnchanged()) {
// No change in visibility, so we can immediately complete the transition
startedTransitions.put(transitionInfo.getOperation(), false);
transitionInfo.completeSpecialEffect();
continue;
}
Object transition = transitionImpl.cloneTransition(transitionInfo.getTransition());
Operation operation = transitionInfo.getOperation();
boolean involvedInSharedElementTransition = sharedElementTransition != null
&& (operation == firstOut || operation == lastIn);
if (transition == null) {
// Nothing more to do if the transition is null
if (!involvedInSharedElementTransition) {
// Only complete the transition if this fragment isn't involved
// in the shared element transition (as otherwise we need to wait
// for that to finish)
startedTransitions.put(operation, false);
transitionInfo.completeSpecialEffect();
}
} else {
// Target the Transition to *only* the set of transitioning views
final ArrayList<View> transitioningViews = new ArrayList<>();
captureTransitioningViews(transitioningViews,
operation.getFragment().mView);
if (involvedInSharedElementTransition) {
// Remove all of the shared element views from the transition
if (operation == firstOut) {
transitioningViews.removeAll(sharedElementFirstOutViews);
} else {
transitioningViews.removeAll(sharedElementLastInViews);
}
}
if (transitioningViews.isEmpty()) {
transitionImpl.addTarget(transition, nonExistentView);
} else {
transitionImpl.addTargets(transition, transitioningViews);
transitionImpl.scheduleRemoveTargets(transition,
transition, transitioningViews,
null, null, null, null);
if (operation.getFinalState() == Operation.State.GONE) {
// We're hiding the Fragment. This requires a bit of extra work
// First, we need to avoid immediately applying the container change as
// that will stop the Transition from occurring.
awaitingContainerChanges.remove(operation);
// Then schedule the actual hide of the fragment's view,
// essentially doing what applyState() would do for us
ArrayList<View> transitioningViewsToHide =
new ArrayList<>(transitioningViews);
transitioningViewsToHide.remove(operation.getFragment().mView);
transitionImpl.scheduleHideFragmentView(transition,
operation.getFragment().mView, transitioningViewsToHide);
// This OneShotPreDrawListener gets fired before the delayed start of
// the Transition and changes the visibility of any exiting child views
// that *ARE NOT* shared element transitions. The TransitionManager then
// properly considers exiting views and marks them as disappearing,
// applying a transition and a listener to take proper actions once the
// transition is complete.
OneShotPreDrawListener.add(getContainer(), new Runnable() {
@Override
public void run() {
FragmentTransition.setViewVisibility(transitioningViews,
View.INVISIBLE);
}
});
}
}
if (operation.getFinalState() == Operation.State.VISIBLE) {
enteringViews.addAll(transitioningViews);
if (hasLastInEpicenter) {
transitionImpl.setEpicenter(transition, lastInEpicenterRect);
}
} else {
transitionImpl.setEpicenter(transition, firstOutEpicenterView);
}
startedTransitions.put(operation, true);
// Now determine how this transition should be merged together
if (transitionInfo.isOverlapAllowed()) {
// Overlap is allowed, so add them to the mergeTransition set
mergedTransition = transitionImpl.mergeTransitionsTogether(
mergedTransition, transition, null);
} else {
// Overlap is not allowed, add them to the mergedNonOverlappingTransition
mergedNonOverlappingTransition = transitionImpl.mergeTransitionsTogether(
mergedNonOverlappingTransition, transition, null);
}
}
}
// Make sure that the mergedNonOverlappingTransition set
// runs after the mergedTransition set is complete
mergedTransition = transitionImpl.mergeTransitionsInSequence(mergedTransition,
mergedNonOverlappingTransition, sharedElementTransition);
// Now set up our completion signal on the completely merged transition set
for (final TransitionInfo transitionInfo : transitionInfos) {
if (transitionInfo.isVisibilityUnchanged()) {
// No change in visibility, so we've already completed the transition
continue;
}
Object transition = transitionInfo.getTransition();
Operation operation = transitionInfo.getOperation();
boolean involvedInSharedElementTransition = sharedElementTransition != null
&& (operation == firstOut || operation == lastIn);
if (transition != null || involvedInSharedElementTransition) {
// If the container has never been laid out, transitions will not start so
// so lets instantly complete them.
if (!ViewCompat.isLaidOut(getContainer())) {
if (FragmentManager.isLoggingEnabled(Log.VERBOSE)) {
Log.v(FragmentManager.TAG,
"SpecialEffectsController: Container " + getContainer()
+ " has not been laid out. Completing operation "
+ operation);
}
transitionInfo.completeSpecialEffect();
} else {
transitionImpl.setListenerForTransitionEnd(
transitionInfo.getOperation().getFragment(),
mergedTransition,
transitionInfo.getSignal(),
new Runnable() {
@Override
public void run() {
transitionInfo.completeSpecialEffect();
}
});
}
}
}
// Transitions won't run if the container isn't laid out so
// we can return early here to avoid doing unnecessary work.
if (!ViewCompat.isLaidOut(getContainer())) {
return startedTransitions;
}
// First, hide all of the entering views so they're in
// the correct initial state
FragmentTransition.setViewVisibility(enteringViews, View.INVISIBLE);
ArrayList<String> inNames =
transitionImpl.prepareSetNameOverridesReordered(sharedElementLastInViews);
// Now actually start the transition
transitionImpl.beginDelayedTransition(getContainer(), mergedTransition);
transitionImpl.setNameOverridesReordered(getContainer(), sharedElementFirstOutViews,
sharedElementLastInViews, inNames, sharedElementNameMapping);
// Then, show all of the entering views, putting them into
// the correct final state
FragmentTransition.setViewVisibility(enteringViews, View.VISIBLE);
transitionImpl.swapSharedElementTargets(sharedElementTransition,
sharedElementFirstOutViews, sharedElementLastInViews);
return startedTransitions;
}
/**
* Retain only the shared element views that have a transition name that is in
* the set of transition names.
*
* @param sharedElementViews The map of shared element transitions that should be filtered.
* @param transitionNames The set of transition names to be retained.
*/
void retainMatchingViews(@NonNull ArrayMap<String, View> sharedElementViews,
@NonNull Collection<String> transitionNames) {
Iterator<Map.Entry<String, View>> iterator = sharedElementViews.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, View> entry = iterator.next();
if (!transitionNames.contains(ViewCompat.getTransitionName(entry.getValue()))) {
iterator.remove();
}
}
}
/**
* Gets the Views in the hierarchy affected by entering and exiting transitions.
*
* @param transitioningViews This View will be added to transitioningViews if it has a
* transition name, is VISIBLE and a normal View, or a ViewGroup with
* {@link android.view.ViewGroup#isTransitionGroup()} true.
* @param view The base of the view hierarchy to look in.
*/
void captureTransitioningViews(ArrayList<View> transitioningViews, View view) {
if (view instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) view;
if (ViewGroupCompat.isTransitionGroup(viewGroup)) {
if (!transitioningViews.contains(view)) {
transitioningViews.add(viewGroup);
}
} else {
int count = viewGroup.getChildCount();
for (int i = 0; i < count; i++) {
View child = viewGroup.getChildAt(i);
if (child.getVisibility() == View.VISIBLE) {
captureTransitioningViews(transitioningViews, child);
}
}
}
} else {
if (!transitioningViews.contains(view)) {
transitioningViews.add(view);
}
}
}
/**
* Finds all views that have transition names in the hierarchy under the given view and
* stores them in {@code namedViews} map with the name as the key.
*/
void findNamedViews(Map<String, View> namedViews, @NonNull View view) {
String transitionName = ViewCompat.getTransitionName(view);
if (transitionName != null) {
namedViews.put(transitionName, view);
}
if (view instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) view;
int count = viewGroup.getChildCount();
for (int i = 0; i < count; i++) {
View child = viewGroup.getChildAt(i);
if (child.getVisibility() == View.VISIBLE) {
findNamedViews(namedViews, child);
}
}
}
}
@SuppressWarnings("WeakerAccess") /* synthetic access */
void applyContainerChanges(@NonNull Operation operation) {
View view = operation.getFragment().mView;
operation.getFinalState().applyState(view);
}
private static class SpecialEffectsInfo {
@NonNull
private final Operation mOperation;
@NonNull
private final CancellationSignal mSignal;
SpecialEffectsInfo(@NonNull Operation operation, @NonNull CancellationSignal signal) {
mOperation = operation;
mSignal = signal;
}
@NonNull
Operation getOperation() {
return mOperation;
}
@NonNull
CancellationSignal getSignal() {
return mSignal;
}
boolean isVisibilityUnchanged() {
Operation.State currentState = Operation.State.from(
mOperation.getFragment().mView);
Operation.State finalState = mOperation.getFinalState();
return currentState == finalState || (currentState != Operation.State.VISIBLE
&& finalState != Operation.State.VISIBLE);
}
void completeSpecialEffect() {
mOperation.completeSpecialEffect(mSignal);
}
}
private static class AnimationInfo extends SpecialEffectsInfo {
private boolean mIsPop;
private boolean mLoadedAnim = false;
@Nullable
private FragmentAnim.AnimationOrAnimator mAnimation;
AnimationInfo(@NonNull Operation operation, @NonNull CancellationSignal signal,
boolean isPop) {
super(operation, signal);
mIsPop = isPop;
}
@Nullable
FragmentAnim.AnimationOrAnimator getAnimation(@NonNull Context context) {
if (mLoadedAnim) {
return mAnimation;
}
mAnimation = FragmentAnim.loadAnimation(context,
getOperation().getFragment(),
getOperation().getFinalState() == Operation.State.VISIBLE,
mIsPop);
mLoadedAnim = true;
return mAnimation;
}
}
private static class TransitionInfo extends SpecialEffectsInfo {
@Nullable
private final Object mTransition;
private final boolean mOverlapAllowed;
@Nullable
private final Object mSharedElementTransition;
TransitionInfo(@NonNull Operation operation,
@NonNull CancellationSignal signal, boolean isPop,
boolean providesSharedElementTransition) {
super(operation, signal);
if (operation.getFinalState() == Operation.State.VISIBLE) {
mTransition = isPop
? operation.getFragment().getReenterTransition()
: operation.getFragment().getEnterTransition();
// Entering transitions can choose to run after all exit
// transitions complete, rather than overlapping with them
mOverlapAllowed = isPop
? operation.getFragment().getAllowReturnTransitionOverlap()
: operation.getFragment().getAllowEnterTransitionOverlap();
} else {
mTransition = isPop
? operation.getFragment().getReturnTransition()
: operation.getFragment().getExitTransition();
// Removing Fragments always overlap other transitions
mOverlapAllowed = true;
}
if (providesSharedElementTransition) {
if (isPop) {
mSharedElementTransition =
operation.getFragment().getSharedElementReturnTransition();
} else {
mSharedElementTransition =
operation.getFragment().getSharedElementEnterTransition();
}
} else {
mSharedElementTransition = null;
}
}
@Nullable
Object getTransition() {
return mTransition;
}
boolean isOverlapAllowed() {
return mOverlapAllowed;
}
public boolean hasSharedElementTransition() {
return mSharedElementTransition != null;
}
@Nullable
public Object getSharedElementTransition() {
return mSharedElementTransition;
}
@Nullable
FragmentTransitionImpl getHandlingImpl() {
FragmentTransitionImpl transitionImpl = getHandlingImpl(mTransition);
FragmentTransitionImpl sharedElementTransitionImpl =
getHandlingImpl(mSharedElementTransition);
if (transitionImpl != null && sharedElementTransitionImpl != null
&& transitionImpl != sharedElementTransitionImpl) {
throw new IllegalArgumentException("Mixing framework transitions and "
+ "AndroidX transitions is not allowed. Fragment "
+ getOperation().getFragment() + " returned Transition "
+ mTransition + " which uses a different Transition "
+ " type than its shared element transition "
+ mSharedElementTransition);
}
return transitionImpl != null ? transitionImpl : sharedElementTransitionImpl;
}
@Nullable
private FragmentTransitionImpl getHandlingImpl(Object transition) {
if (transition == null) {
return null;
}
if (FragmentTransition.PLATFORM_IMPL != null
&& FragmentTransition.PLATFORM_IMPL.canHandle(transition)) {
return FragmentTransition.PLATFORM_IMPL;
}
if (FragmentTransition.SUPPORT_IMPL != null
&& FragmentTransition.SUPPORT_IMPL.canHandle(transition)) {
return FragmentTransition.SUPPORT_IMPL;
}
throw new IllegalArgumentException("Transition " + transition + " for fragment "
+ getOperation().getFragment() + " is not a valid framework Transition or "
+ "AndroidX Transition");
}
}
}
| fragment/fragment/src/main/java/androidx/fragment/app/DefaultSpecialEffectsController.java | /*
* Copyright 2019 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 androidx.fragment.app;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.graphics.Rect;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.collection.ArrayMap;
import androidx.core.app.SharedElementCallback;
import androidx.core.os.CancellationSignal;
import androidx.core.util.Preconditions;
import androidx.core.view.OneShotPreDrawListener;
import androidx.core.view.ViewCompat;
import androidx.core.view.ViewGroupCompat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* A SpecialEffectsController that hooks into the existing Fragment APIs to run
* animations and transitions.
*/
class DefaultSpecialEffectsController extends SpecialEffectsController {
DefaultSpecialEffectsController(@NonNull ViewGroup container) {
super(container);
}
@Override
void executeOperations(@NonNull List<Operation> operations, boolean isPop) {
// Shared element transitions are done between the first fragment leaving and
// the last fragment coming in. Finding these operations is the first priority
Operation firstOut = null;
Operation lastIn = null;
for (final Operation operation : operations) {
Operation.State currentState = Operation.State.from(operation.getFragment().mView);
switch (operation.getFinalState()) {
case GONE:
case INVISIBLE:
case REMOVED:
if (currentState == Operation.State.VISIBLE && firstOut == null) {
// The firstOut Operation is the first Operation moving from VISIBLE
firstOut = operation;
}
break;
case VISIBLE:
if (currentState != Operation.State.VISIBLE) {
// The last Operation that moves to VISIBLE is the lastIn Operation
lastIn = operation;
}
break;
}
}
// Now iterate through the operations, collecting the set of animations
// and transitions that need to be executed
List<AnimationInfo> animations = new ArrayList<>();
List<TransitionInfo> transitions = new ArrayList<>();
final List<Operation> awaitingContainerChanges = new ArrayList<>(operations);
for (final Operation operation : operations) {
// Create the animation CancellationSignal
CancellationSignal animCancellationSignal = new CancellationSignal();
operation.markStartedSpecialEffect(animCancellationSignal);
// Add the animation special effect
animations.add(new AnimationInfo(operation, animCancellationSignal, isPop));
// Create the transition CancellationSignal
CancellationSignal transitionCancellationSignal = new CancellationSignal();
operation.markStartedSpecialEffect(transitionCancellationSignal);
// Add the transition special effect
transitions.add(new TransitionInfo(operation, transitionCancellationSignal, isPop,
isPop ? operation == firstOut : operation == lastIn));
// Ensure that if the Operation is synchronously complete, we still
// apply the container changes before the Operation completes
operation.addCompletionListener(new Runnable() {
@Override
public void run() {
if (awaitingContainerChanges.contains(operation)) {
awaitingContainerChanges.remove(operation);
applyContainerChanges(operation);
}
}
});
}
// Start transition special effects
Map<Operation, Boolean> startedTransitions = startTransitions(transitions,
awaitingContainerChanges, isPop, firstOut, lastIn);
boolean startedAnyTransition = startedTransitions.containsValue(true);
// Start animation special effects
startAnimations(animations, awaitingContainerChanges,
startedAnyTransition, startedTransitions);
for (final Operation operation : awaitingContainerChanges) {
applyContainerChanges(operation);
}
awaitingContainerChanges.clear();
}
private void startAnimations(@NonNull List<AnimationInfo> animationInfos,
@NonNull List<Operation> awaitingContainerChanges,
boolean startedAnyTransition, @NonNull Map<Operation, Boolean> startedTransitions) {
final ViewGroup container = getContainer();
final Context context = container.getContext();
ArrayList<AnimationInfo> animationsToRun = new ArrayList<>();
// First run Animators
boolean startedAnyAnimator = false;
for (final AnimationInfo animationInfo : animationInfos) {
if (animationInfo.isVisibilityUnchanged()) {
// No change in visibility, so we can immediately complete the animation
animationInfo.completeSpecialEffect();
continue;
}
FragmentAnim.AnimationOrAnimator anim = animationInfo.getAnimation(context);
if (anim == null) {
// No Animator or Animation, so we can immediately complete the animation
animationInfo.completeSpecialEffect();
continue;
}
final Animator animator = anim.animator;
if (animator == null) {
// We must have an Animation to run. Save those for a second pass
animationsToRun.add(animationInfo);
continue;
}
// First make sure we haven't already started a Transition for this Operation
final Operation operation = animationInfo.getOperation();
final Fragment fragment = operation.getFragment();
boolean startedTransition = Boolean.TRUE.equals(startedTransitions.get(operation));
if (startedTransition) {
if (FragmentManager.isLoggingEnabled(Log.VERBOSE)) {
Log.v(FragmentManager.TAG, "Ignoring Animator set on "
+ fragment + " as this Fragment was involved in a Transition.");
}
animationInfo.completeSpecialEffect();
continue;
}
// Okay, let's run the Animator!
startedAnyAnimator = true;
final boolean isHideOperation = operation.getFinalState() == Operation.State.GONE;
if (isHideOperation) {
// We don't want to immediately applyState() to hide operations as that
// immediately stops the Animator. Instead we'll applyState() manually
// when the Animator ends.
awaitingContainerChanges.remove(operation);
}
final View viewToAnimate = fragment.mView;
container.startViewTransition(viewToAnimate);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator anim) {
container.endViewTransition(viewToAnimate);
if (isHideOperation) {
// Specifically for hide operations with Animator, we can't
// applyState until the Animator finishes
operation.getFinalState().applyState(viewToAnimate);
}
animationInfo.completeSpecialEffect();
}
});
animator.setTarget(viewToAnimate);
animator.start();
// Listen for cancellation and use that to cancel the Animator
CancellationSignal signal = animationInfo.getSignal();
signal.setOnCancelListener(new CancellationSignal.OnCancelListener() {
@Override
public void onCancel() {
animator.end();
}
});
}
// Now run Animations
for (final AnimationInfo animationInfo : animationsToRun) {
// First make sure we haven't already started any Transition
final Operation operation = animationInfo.getOperation();
final Fragment fragment = operation.getFragment();
if (startedAnyTransition) {
if (FragmentManager.isLoggingEnabled(Log.VERBOSE)) {
Log.v(FragmentManager.TAG, "Ignoring Animation set on "
+ fragment + " as Animations cannot run alongside Transitions.");
}
animationInfo.completeSpecialEffect();
continue;
}
// Then make sure we haven't already started any Animator
if (startedAnyAnimator) {
if (FragmentManager.isLoggingEnabled(Log.VERBOSE)) {
Log.v(FragmentManager.TAG, "Ignoring Animation set on "
+ fragment + " as Animations cannot run alongside Animators.");
}
animationInfo.completeSpecialEffect();
continue;
}
// Okay, let's run the Animation!
final View viewToAnimate = fragment.mView;
Animation anim = Preconditions.checkNotNull(
Preconditions.checkNotNull(animationInfo.getAnimation(context)).animation);
Operation.State finalState = operation.getFinalState();
if (finalState != Operation.State.REMOVED) {
// If the operation does not remove the view, we can't use a
// AnimationSet due that causing the introduction of visual artifacts (b/163084315).
viewToAnimate.startAnimation(anim);
// This means we can't use setAnimationListener() without overriding
// any listener that the Fragment has set themselves, so we
// just mark the special effect as complete immediately.
animationInfo.completeSpecialEffect();
} else {
container.startViewTransition(viewToAnimate);
final Animation animation = new FragmentAnim.EndViewTransitionAnimation(
anim, container, viewToAnimate);
animation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
// onAnimationEnd() comes during draw(), so there can still be some
// draw events happening after this call. We don't want to complete the
// animation until after the onAnimationEnd()
container.post(new Runnable() {
@Override
public void run() {
container.endViewTransition(viewToAnimate);
animationInfo.completeSpecialEffect();
}
});
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
viewToAnimate.startAnimation(animation);
}
// Listen for cancellation and use that to cancel the Animation
CancellationSignal signal = animationInfo.getSignal();
signal.setOnCancelListener(new CancellationSignal.OnCancelListener() {
@Override
public void onCancel() {
viewToAnimate.clearAnimation();
container.endViewTransition(viewToAnimate);
animationInfo.completeSpecialEffect();
}
});
}
}
@NonNull
private Map<Operation, Boolean> startTransitions(@NonNull List<TransitionInfo> transitionInfos,
@NonNull List<Operation> awaitingContainerChanges,
final boolean isPop, @Nullable final Operation firstOut,
@Nullable final Operation lastIn) {
Map<Operation, Boolean> startedTransitions = new HashMap<>();
// First verify that we can run all transitions together
FragmentTransitionImpl transitionImpl = null;
for (TransitionInfo transitionInfo : transitionInfos) {
if (transitionInfo.isVisibilityUnchanged()) {
// No change in visibility, so we can skip this TransitionInfo
continue;
}
FragmentTransitionImpl handlingImpl = transitionInfo.getHandlingImpl();
if (transitionImpl == null) {
transitionImpl = handlingImpl;
} else if (handlingImpl != null && transitionImpl != handlingImpl) {
throw new IllegalArgumentException("Mixing framework transitions and "
+ "AndroidX transitions is not allowed. Fragment "
+ transitionInfo.getOperation().getFragment() + " returned Transition "
+ transitionInfo.getTransition() + " which uses a different Transition "
+ " type than other Fragments.");
}
}
if (transitionImpl == null) {
// There were no transitions at all so we can just complete all of them
for (TransitionInfo transitionInfo : transitionInfos) {
startedTransitions.put(transitionInfo.getOperation(), false);
transitionInfo.completeSpecialEffect();
}
return startedTransitions;
}
// Every transition needs to target at least one View so that they
// don't interfere with one another. This is the view we use
// in cases where there are no real views to target
final View nonExistentView = new View(getContainer().getContext());
// Now find the shared element transition if it exists
Object sharedElementTransition = null;
View firstOutEpicenterView = null;
boolean hasLastInEpicenter = false;
final Rect lastInEpicenterRect = new Rect();
ArrayList<View> sharedElementFirstOutViews = new ArrayList<>();
ArrayList<View> sharedElementLastInViews = new ArrayList<>();
ArrayMap<String, String> sharedElementNameMapping = new ArrayMap<>();
for (final TransitionInfo transitionInfo : transitionInfos) {
boolean hasSharedElementTransition = transitionInfo.hasSharedElementTransition();
// Compute the shared element transition between the firstOut and lastIn Fragments
if (hasSharedElementTransition && firstOut != null && lastIn != null) {
// swapSharedElementTargets requires wrapping this in a TransitionSet
sharedElementTransition = transitionImpl.wrapTransitionInSet(
transitionImpl.cloneTransition(
transitionInfo.getSharedElementTransition()));
// The exiting shared elements default to the source names from the
// last in fragment
ArrayList<String> exitingNames = lastIn.getFragment()
.getSharedElementSourceNames();
// But if we're doing multiple transactions, we may need to re-map
// the names from the first out fragment
ArrayList<String> firstOutSourceNames = firstOut.getFragment()
.getSharedElementSourceNames();
ArrayList<String> firstOutTargetNames = firstOut.getFragment()
.getSharedElementTargetNames();
// We do this by iterating through each first out target,
// seeing if there is a match from the last in sources
for (int index = 0; index < firstOutTargetNames.size(); index++) {
int nameIndex = exitingNames.indexOf(firstOutTargetNames.get(index));
if (nameIndex != -1) {
// If we found a match, replace the last in source name
// with the first out source name
exitingNames.set(nameIndex, firstOutSourceNames.get(index));
}
}
ArrayList<String> enteringNames = lastIn.getFragment()
.getSharedElementTargetNames();
SharedElementCallback exitingCallback;
SharedElementCallback enteringCallback;
if (!isPop) {
// Forward transitions have firstOut fragment exiting and the
// lastIn fragment entering
exitingCallback = firstOut.getFragment().getExitTransitionCallback();
enteringCallback = lastIn.getFragment().getEnterTransitionCallback();
} else {
// A pop is the reverse: the firstOut fragment is entering and the
// lastIn fragment is exiting
exitingCallback = firstOut.getFragment().getEnterTransitionCallback();
enteringCallback = lastIn.getFragment().getExitTransitionCallback();
}
int numSharedElements = exitingNames.size();
for (int i = 0; i < numSharedElements; i++) {
String exitingName = exitingNames.get(i);
String enteringName = enteringNames.get(i);
sharedElementNameMapping.put(exitingName, enteringName);
}
// Find all of the Views from the firstOut fragment that are
// part of the shared element transition
final ArrayMap<String, View> firstOutViews = new ArrayMap<>();
findNamedViews(firstOutViews, firstOut.getFragment().mView);
firstOutViews.retainAll(exitingNames);
if (exitingCallback != null) {
// Give the SharedElementCallback a chance to override the default mapping
exitingCallback.onMapSharedElements(exitingNames, firstOutViews);
for (int i = exitingNames.size() - 1; i >= 0; i--) {
String name = exitingNames.get(i);
View view = firstOutViews.get(name);
if (view == null) {
sharedElementNameMapping.remove(name);
} else if (!name.equals(ViewCompat.getTransitionName(view))) {
String targetValue = sharedElementNameMapping.remove(name);
sharedElementNameMapping.put(ViewCompat.getTransitionName(view),
targetValue);
}
}
} else {
// Only keep the mapping of elements that were found in the firstOut Fragment
sharedElementNameMapping.retainAll(firstOutViews.keySet());
}
// Find all of the Views from the lastIn fragment that are
// part of the shared element transition
final ArrayMap<String, View> lastInViews = new ArrayMap<>();
findNamedViews(lastInViews, lastIn.getFragment().mView);
lastInViews.retainAll(enteringNames);
lastInViews.retainAll(sharedElementNameMapping.values());
if (enteringCallback != null) {
// Give the SharedElementCallback a chance to override the default mapping
enteringCallback.onMapSharedElements(enteringNames, lastInViews);
for (int i = enteringNames.size() - 1; i >= 0; i--) {
String name = enteringNames.get(i);
View view = lastInViews.get(name);
if (view == null) {
String key = FragmentTransition.findKeyForValue(
sharedElementNameMapping, name);
if (key != null) {
sharedElementNameMapping.remove(key);
}
} else if (!name.equals(ViewCompat.getTransitionName(view))) {
String key = FragmentTransition.findKeyForValue(
sharedElementNameMapping, name);
if (key != null) {
sharedElementNameMapping.put(key,
ViewCompat.getTransitionName(view));
}
}
}
} else {
// Only keep the mapping of elements that were found in the lastIn Fragment
FragmentTransition.retainValues(sharedElementNameMapping, lastInViews);
}
// Now make a final pass through the Views list to ensure they
// don't still have elements that were removed from the mapping
retainMatchingViews(firstOutViews, sharedElementNameMapping.keySet());
retainMatchingViews(lastInViews, sharedElementNameMapping.values());
if (sharedElementNameMapping.isEmpty()) {
// We couldn't find any valid shared element mappings, so clear out
// the shared element transition information entirely
sharedElementTransition = null;
sharedElementFirstOutViews.clear();
sharedElementLastInViews.clear();
} else {
// Call through to onSharedElementStart() before capturing the
// starting values for the shared element transition
FragmentTransition.callSharedElementStartEnd(
lastIn.getFragment(), firstOut.getFragment(), isPop,
firstOutViews, true);
// Trigger the onSharedElementEnd callback in the next frame after
// the starting values are captured and before capturing the end states
OneShotPreDrawListener.add(getContainer(), new Runnable() {
@Override
public void run() {
FragmentTransition.callSharedElementStartEnd(
lastIn.getFragment(), firstOut.getFragment(), isPop,
lastInViews, false);
}
});
sharedElementFirstOutViews.addAll(firstOutViews.values());
// Compute the epicenter of the firstOut transition
if (!exitingNames.isEmpty()) {
String epicenterViewName = exitingNames.get(0);
firstOutEpicenterView = firstOutViews.get(epicenterViewName);
transitionImpl.setEpicenter(sharedElementTransition,
firstOutEpicenterView);
}
sharedElementLastInViews.addAll(lastInViews.values());
// Compute the epicenter of the lastIn transition
if (!enteringNames.isEmpty()) {
String epicenterViewName = enteringNames.get(0);
final View lastInEpicenterView = lastInViews.get(epicenterViewName);
if (lastInEpicenterView != null) {
hasLastInEpicenter = true;
// We can't set the epicenter here directly since the View might
// not have been laid out as of yet, so instead we set a Rect as
// the epicenter and compute the bounds one frame later
final FragmentTransitionImpl impl = transitionImpl;
OneShotPreDrawListener.add(getContainer(), new Runnable() {
@Override
public void run() {
impl.getBoundsOnScreen(lastInEpicenterView,
lastInEpicenterRect);
}
});
}
}
// Now set the transition's targets to only the firstOut Fragment's views
// It'll be swapped to the lastIn Fragment's views after the
// transition is started
transitionImpl.setSharedElementTargets(sharedElementTransition,
nonExistentView, sharedElementFirstOutViews);
// After the swap to the lastIn Fragment's view (done below), we
// need to clean up those targets. We schedule this here so that it
// runs directly after the swap
transitionImpl.scheduleRemoveTargets(sharedElementTransition,
null, null, null, null,
sharedElementTransition, sharedElementLastInViews);
// Both the firstOut and lastIn Operations are now associated
// with a Transition
startedTransitions.put(firstOut, true);
startedTransitions.put(lastIn, true);
}
}
}
ArrayList<View> enteringViews = new ArrayList<>();
// These transitions run together, overlapping one another
Object mergedTransition = null;
// These transitions run only after all of the other transitions complete
Object mergedNonOverlappingTransition = null;
// Now iterate through the set of transitions and merge them together
for (final TransitionInfo transitionInfo : transitionInfos) {
if (transitionInfo.isVisibilityUnchanged()) {
// No change in visibility, so we can immediately complete the transition
startedTransitions.put(transitionInfo.getOperation(), false);
transitionInfo.completeSpecialEffect();
continue;
}
Object transition = transitionImpl.cloneTransition(transitionInfo.getTransition());
Operation operation = transitionInfo.getOperation();
boolean involvedInSharedElementTransition = sharedElementTransition != null
&& (operation == firstOut || operation == lastIn);
if (transition == null) {
// Nothing more to do if the transition is null
if (!involvedInSharedElementTransition) {
// Only complete the transition if this fragment isn't involved
// in the shared element transition (as otherwise we need to wait
// for that to finish)
startedTransitions.put(operation, false);
transitionInfo.completeSpecialEffect();
}
} else {
// Target the Transition to *only* the set of transitioning views
final ArrayList<View> transitioningViews = new ArrayList<>();
captureTransitioningViews(transitioningViews,
operation.getFragment().mView);
if (involvedInSharedElementTransition) {
// Remove all of the shared element views from the transition
if (operation == firstOut) {
transitioningViews.removeAll(sharedElementFirstOutViews);
} else {
transitioningViews.removeAll(sharedElementLastInViews);
}
}
if (transitioningViews.isEmpty()) {
transitionImpl.addTarget(transition, nonExistentView);
} else {
transitionImpl.addTargets(transition, transitioningViews);
transitionImpl.scheduleRemoveTargets(transition,
transition, transitioningViews,
null, null, null, null);
if (operation.getFinalState() == Operation.State.GONE) {
// We're hiding the Fragment. This requires a bit of extra work
// First, we need to avoid immediately applying the container change as
// that will stop the Transition from occurring.
awaitingContainerChanges.remove(operation);
// Then schedule the actual hide of the fragment's view,
// essentially doing what applyState() would do for us
transitionImpl.scheduleHideFragmentView(transition,
operation.getFragment().mView,
transitioningViews);
// This OneShotPreDrawListener gets fired before the delayed start of
// the Transition and changes the visibility of any exiting child views
// that *ARE NOT* shared element transitions. The TransitionManager then
// properly considers exiting views and marks them as disappearing,
// applying a transition and a listener to take proper actions once the
// transition is complete.
OneShotPreDrawListener.add(getContainer(), new Runnable() {
@Override
public void run() {
FragmentTransition.setViewVisibility(transitioningViews,
View.INVISIBLE);
}
});
}
}
if (operation.getFinalState() == Operation.State.VISIBLE) {
enteringViews.addAll(transitioningViews);
if (hasLastInEpicenter) {
transitionImpl.setEpicenter(transition, lastInEpicenterRect);
}
} else {
transitionImpl.setEpicenter(transition, firstOutEpicenterView);
}
startedTransitions.put(operation, true);
// Now determine how this transition should be merged together
if (transitionInfo.isOverlapAllowed()) {
// Overlap is allowed, so add them to the mergeTransition set
mergedTransition = transitionImpl.mergeTransitionsTogether(
mergedTransition, transition, null);
} else {
// Overlap is not allowed, add them to the mergedNonOverlappingTransition
mergedNonOverlappingTransition = transitionImpl.mergeTransitionsTogether(
mergedNonOverlappingTransition, transition, null);
}
}
}
// Make sure that the mergedNonOverlappingTransition set
// runs after the mergedTransition set is complete
mergedTransition = transitionImpl.mergeTransitionsInSequence(mergedTransition,
mergedNonOverlappingTransition, sharedElementTransition);
// Now set up our completion signal on the completely merged transition set
for (final TransitionInfo transitionInfo : transitionInfos) {
if (transitionInfo.isVisibilityUnchanged()) {
// No change in visibility, so we've already completed the transition
continue;
}
Object transition = transitionInfo.getTransition();
Operation operation = transitionInfo.getOperation();
boolean involvedInSharedElementTransition = sharedElementTransition != null
&& (operation == firstOut || operation == lastIn);
if (transition != null || involvedInSharedElementTransition) {
// If the container has never been laid out, transitions will not start so
// so lets instantly complete them.
if (!ViewCompat.isLaidOut(getContainer())) {
if (FragmentManager.isLoggingEnabled(Log.VERBOSE)) {
Log.v(FragmentManager.TAG,
"SpecialEffectsController: Container " + getContainer()
+ " has not been laid out. Completing operation "
+ operation);
}
transitionInfo.completeSpecialEffect();
} else {
transitionImpl.setListenerForTransitionEnd(
transitionInfo.getOperation().getFragment(),
mergedTransition,
transitionInfo.getSignal(),
new Runnable() {
@Override
public void run() {
transitionInfo.completeSpecialEffect();
}
});
}
}
}
// Transitions won't run if the container isn't laid out so
// we can return early here to avoid doing unnecessary work.
if (!ViewCompat.isLaidOut(getContainer())) {
return startedTransitions;
}
// First, hide all of the entering views so they're in
// the correct initial state
FragmentTransition.setViewVisibility(enteringViews, View.INVISIBLE);
ArrayList<String> inNames =
transitionImpl.prepareSetNameOverridesReordered(sharedElementLastInViews);
// Now actually start the transition
transitionImpl.beginDelayedTransition(getContainer(), mergedTransition);
transitionImpl.setNameOverridesReordered(getContainer(), sharedElementFirstOutViews,
sharedElementLastInViews, inNames, sharedElementNameMapping);
// Then, show all of the entering views, putting them into
// the correct final state
FragmentTransition.setViewVisibility(enteringViews, View.VISIBLE);
transitionImpl.swapSharedElementTargets(sharedElementTransition,
sharedElementFirstOutViews, sharedElementLastInViews);
return startedTransitions;
}
/**
* Retain only the shared element views that have a transition name that is in
* the set of transition names.
*
* @param sharedElementViews The map of shared element transitions that should be filtered.
* @param transitionNames The set of transition names to be retained.
*/
void retainMatchingViews(@NonNull ArrayMap<String, View> sharedElementViews,
@NonNull Collection<String> transitionNames) {
Iterator<Map.Entry<String, View>> iterator = sharedElementViews.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, View> entry = iterator.next();
if (!transitionNames.contains(ViewCompat.getTransitionName(entry.getValue()))) {
iterator.remove();
}
}
}
/**
* Gets the Views in the hierarchy affected by entering and exiting transitions.
*
* @param transitioningViews This View will be added to transitioningViews if it has a
* transition name, is VISIBLE and a normal View, or a ViewGroup with
* {@link android.view.ViewGroup#isTransitionGroup()} true.
* @param view The base of the view hierarchy to look in.
*/
void captureTransitioningViews(ArrayList<View> transitioningViews, View view) {
if (view instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) view;
if (ViewGroupCompat.isTransitionGroup(viewGroup)) {
if (!transitioningViews.contains(view)) {
transitioningViews.add(viewGroup);
}
} else {
int count = viewGroup.getChildCount();
for (int i = 0; i < count; i++) {
View child = viewGroup.getChildAt(i);
if (child.getVisibility() == View.VISIBLE) {
captureTransitioningViews(transitioningViews, child);
}
}
}
} else {
if (!transitioningViews.contains(view)) {
transitioningViews.add(view);
}
}
}
/**
* Finds all views that have transition names in the hierarchy under the given view and
* stores them in {@code namedViews} map with the name as the key.
*/
void findNamedViews(Map<String, View> namedViews, @NonNull View view) {
String transitionName = ViewCompat.getTransitionName(view);
if (transitionName != null) {
namedViews.put(transitionName, view);
}
if (view instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) view;
int count = viewGroup.getChildCount();
for (int i = 0; i < count; i++) {
View child = viewGroup.getChildAt(i);
if (child.getVisibility() == View.VISIBLE) {
findNamedViews(namedViews, child);
}
}
}
}
@SuppressWarnings("WeakerAccess") /* synthetic access */
void applyContainerChanges(@NonNull Operation operation) {
View view = operation.getFragment().mView;
operation.getFinalState().applyState(view);
}
private static class SpecialEffectsInfo {
@NonNull
private final Operation mOperation;
@NonNull
private final CancellationSignal mSignal;
SpecialEffectsInfo(@NonNull Operation operation, @NonNull CancellationSignal signal) {
mOperation = operation;
mSignal = signal;
}
@NonNull
Operation getOperation() {
return mOperation;
}
@NonNull
CancellationSignal getSignal() {
return mSignal;
}
boolean isVisibilityUnchanged() {
Operation.State currentState = Operation.State.from(
mOperation.getFragment().mView);
Operation.State finalState = mOperation.getFinalState();
return currentState == finalState || (currentState != Operation.State.VISIBLE
&& finalState != Operation.State.VISIBLE);
}
void completeSpecialEffect() {
mOperation.completeSpecialEffect(mSignal);
}
}
private static class AnimationInfo extends SpecialEffectsInfo {
private boolean mIsPop;
private boolean mLoadedAnim = false;
@Nullable
private FragmentAnim.AnimationOrAnimator mAnimation;
AnimationInfo(@NonNull Operation operation, @NonNull CancellationSignal signal,
boolean isPop) {
super(operation, signal);
mIsPop = isPop;
}
@Nullable
FragmentAnim.AnimationOrAnimator getAnimation(@NonNull Context context) {
if (mLoadedAnim) {
return mAnimation;
}
mAnimation = FragmentAnim.loadAnimation(context,
getOperation().getFragment(),
getOperation().getFinalState() == Operation.State.VISIBLE,
mIsPop);
mLoadedAnim = true;
return mAnimation;
}
}
private static class TransitionInfo extends SpecialEffectsInfo {
@Nullable
private final Object mTransition;
private final boolean mOverlapAllowed;
@Nullable
private final Object mSharedElementTransition;
TransitionInfo(@NonNull Operation operation,
@NonNull CancellationSignal signal, boolean isPop,
boolean providesSharedElementTransition) {
super(operation, signal);
if (operation.getFinalState() == Operation.State.VISIBLE) {
mTransition = isPop
? operation.getFragment().getReenterTransition()
: operation.getFragment().getEnterTransition();
// Entering transitions can choose to run after all exit
// transitions complete, rather than overlapping with them
mOverlapAllowed = isPop
? operation.getFragment().getAllowReturnTransitionOverlap()
: operation.getFragment().getAllowEnterTransitionOverlap();
} else {
mTransition = isPop
? operation.getFragment().getReturnTransition()
: operation.getFragment().getExitTransition();
// Removing Fragments always overlap other transitions
mOverlapAllowed = true;
}
if (providesSharedElementTransition) {
if (isPop) {
mSharedElementTransition =
operation.getFragment().getSharedElementReturnTransition();
} else {
mSharedElementTransition =
operation.getFragment().getSharedElementEnterTransition();
}
} else {
mSharedElementTransition = null;
}
}
@Nullable
Object getTransition() {
return mTransition;
}
boolean isOverlapAllowed() {
return mOverlapAllowed;
}
public boolean hasSharedElementTransition() {
return mSharedElementTransition != null;
}
@Nullable
public Object getSharedElementTransition() {
return mSharedElementTransition;
}
@Nullable
FragmentTransitionImpl getHandlingImpl() {
FragmentTransitionImpl transitionImpl = getHandlingImpl(mTransition);
FragmentTransitionImpl sharedElementTransitionImpl =
getHandlingImpl(mSharedElementTransition);
if (transitionImpl != null && sharedElementTransitionImpl != null
&& transitionImpl != sharedElementTransitionImpl) {
throw new IllegalArgumentException("Mixing framework transitions and "
+ "AndroidX transitions is not allowed. Fragment "
+ getOperation().getFragment() + " returned Transition "
+ mTransition + " which uses a different Transition "
+ " type than its shared element transition "
+ mSharedElementTransition);
}
return transitionImpl != null ? transitionImpl : sharedElementTransitionImpl;
}
@Nullable
private FragmentTransitionImpl getHandlingImpl(Object transition) {
if (transition == null) {
return null;
}
if (FragmentTransition.PLATFORM_IMPL != null
&& FragmentTransition.PLATFORM_IMPL.canHandle(transition)) {
return FragmentTransition.PLATFORM_IMPL;
}
if (FragmentTransition.SUPPORT_IMPL != null
&& FragmentTransition.SUPPORT_IMPL.canHandle(transition)) {
return FragmentTransition.SUPPORT_IMPL;
}
throw new IllegalArgumentException("Transition " + transition + " for fragment "
+ getOperation().getFragment() + " is not a valid framework Transition or "
+ "AndroidX Transition");
}
}
}
| Fix exitTransition with hide and transition group true
Currently hide does not actually hide the fragment if you use transition
group true.
We should exclude the fragment root view from the list of transitioning
views so that it is not made VISIBLE when the transition completes.
RelNote: N/A
Test: tested in sample app
Bug: 193603427
Change-Id: Ifcf195587a211559bfdc2471cffd066c237cba97
| fragment/fragment/src/main/java/androidx/fragment/app/DefaultSpecialEffectsController.java | Fix exitTransition with hide and transition group true | <ide><path>ragment/fragment/src/main/java/androidx/fragment/app/DefaultSpecialEffectsController.java
<ide> awaitingContainerChanges.remove(operation);
<ide> // Then schedule the actual hide of the fragment's view,
<ide> // essentially doing what applyState() would do for us
<add> ArrayList<View> transitioningViewsToHide =
<add> new ArrayList<>(transitioningViews);
<add> transitioningViewsToHide.remove(operation.getFragment().mView);
<ide> transitionImpl.scheduleHideFragmentView(transition,
<del> operation.getFragment().mView,
<del> transitioningViews);
<add> operation.getFragment().mView, transitioningViewsToHide);
<ide> // This OneShotPreDrawListener gets fired before the delayed start of
<ide> // the Transition and changes the visibility of any exiting child views
<ide> // that *ARE NOT* shared element transitions. The TransitionManager then |
|
Java | apache-2.0 | a025680ab0db681e0ee83f43c054ff5903451564 | 0 | ryano144/intellij-community,kool79/intellij-community,allotria/intellij-community,fnouama/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,joewalnes/idea-community,Lekanich/intellij-community,caot/intellij-community,ahb0327/intellij-community,jexp/idea2,hurricup/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,holmes/intellij-community,youdonghai/intellij-community,semonte/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,asedunov/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,slisson/intellij-community,petteyg/intellij-community,dslomov/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,allotria/intellij-community,hurricup/intellij-community,semonte/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,amith01994/intellij-community,izonder/intellij-community,blademainer/intellij-community,retomerz/intellij-community,signed/intellij-community,supersven/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,samthor/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,vladmm/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,wreckJ/intellij-community,slisson/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,fitermay/intellij-community,holmes/intellij-community,kool79/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,robovm/robovm-studio,supersven/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,hurricup/intellij-community,asedunov/intellij-community,kdwink/intellij-community,caot/intellij-community,fnouama/intellij-community,petteyg/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,asedunov/intellij-community,jexp/idea2,youdonghai/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,vladmm/intellij-community,semonte/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,petteyg/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,apixandru/intellij-community,da1z/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,blademainer/intellij-community,joewalnes/idea-community,allotria/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,ernestp/consulo,robovm/robovm-studio,holmes/intellij-community,jexp/idea2,tmpgit/intellij-community,hurricup/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,caot/intellij-community,robovm/robovm-studio,petteyg/intellij-community,signed/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,supersven/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,ernestp/consulo,dslomov/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,consulo/consulo,wreckJ/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,izonder/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,jexp/idea2,clumsy/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,dslomov/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,amith01994/intellij-community,consulo/consulo,salguarnieri/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,signed/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,ernestp/consulo,vladmm/intellij-community,clumsy/intellij-community,slisson/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,izonder/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,samthor/intellij-community,clumsy/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,jexp/idea2,alphafoobar/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,kdwink/intellij-community,caot/intellij-community,retomerz/intellij-community,fitermay/intellij-community,ibinti/intellij-community,izonder/intellij-community,hurricup/intellij-community,fitermay/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,slisson/intellij-community,semonte/intellij-community,izonder/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,ernestp/consulo,diorcety/intellij-community,fitermay/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,allotria/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,samthor/intellij-community,asedunov/intellij-community,xfournet/intellij-community,diorcety/intellij-community,jexp/idea2,nicolargo/intellij-community,ahb0327/intellij-community,da1z/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,joewalnes/idea-community,vvv1559/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,semonte/intellij-community,ibinti/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,amith01994/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,vladmm/intellij-community,holmes/intellij-community,slisson/intellij-community,hurricup/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,gnuhub/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,FHannes/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,consulo/consulo,fitermay/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,signed/intellij-community,clumsy/intellij-community,allotria/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,kool79/intellij-community,dslomov/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,xfournet/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,holmes/intellij-community,ryano144/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,signed/intellij-community,xfournet/intellij-community,da1z/intellij-community,ryano144/intellij-community,signed/intellij-community,kdwink/intellij-community,ibinti/intellij-community,kool79/intellij-community,holmes/intellij-community,caot/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,adedayo/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,joewalnes/idea-community,ernestp/consulo,slisson/intellij-community,joewalnes/idea-community,lucafavatella/intellij-community,apixandru/intellij-community,retomerz/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,joewalnes/idea-community,supersven/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,blademainer/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,consulo/consulo,nicolargo/intellij-community,fnouama/intellij-community,vladmm/intellij-community,diorcety/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,xfournet/intellij-community,adedayo/intellij-community,blademainer/intellij-community,samthor/intellij-community,ibinti/intellij-community,signed/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,hurricup/intellij-community,caot/intellij-community,da1z/intellij-community,samthor/intellij-community,gnuhub/intellij-community,samthor/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,dslomov/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,ernestp/consulo,wreckJ/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,petteyg/intellij-community,consulo/consulo,kdwink/intellij-community,joewalnes/idea-community,blademainer/intellij-community,retomerz/intellij-community,da1z/intellij-community,signed/intellij-community,fitermay/intellij-community,caot/intellij-community,clumsy/intellij-community,izonder/intellij-community,supersven/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,da1z/intellij-community,jagguli/intellij-community,slisson/intellij-community,ryano144/intellij-community,izonder/intellij-community,diorcety/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,consulo/consulo,samthor/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,dslomov/intellij-community,kdwink/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,allotria/intellij-community,asedunov/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,joewalnes/idea-community,nicolargo/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,caot/intellij-community,slisson/intellij-community,youdonghai/intellij-community,signed/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,vladmm/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,semonte/intellij-community,jexp/idea2,apixandru/intellij-community,kool79/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,supersven/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,amith01994/intellij-community,jexp/idea2,holmes/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,semonte/intellij-community,jagguli/intellij-community,holmes/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,amith01994/intellij-community,FHannes/intellij-community,petteyg/intellij-community,xfournet/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,holmes/intellij-community,ryano144/intellij-community,petteyg/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,kool79/intellij-community,kool79/intellij-community,caot/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,signed/intellij-community,jagguli/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community | package com.intellij.ide.fileTemplates;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.ex.FileTypeManagerEx;
import com.intellij.util.IncorrectOperationException;
import java.util.Properties;
/**
* @author yole
*/
public class JavaCreateFromTemplateHandler implements CreateFromTemplateHandler {
public static PsiClass createClassOrInterface(Project project,
PsiDirectory directory,
String content,
boolean reformat,
String extension) throws IncorrectOperationException {
if (extension == null) extension = StdFileTypes.JAVA.getDefaultExtension();
final PsiFile psiFile = PsiFileFactory.getInstance(project).createFileFromText("myclass" + "." + extension, content);
if (!(psiFile instanceof PsiJavaFile)){
throw new IncorrectOperationException("This template did not produce a Java class or an interface\n"+psiFile.getText());
}
PsiJavaFile psiJavaFile = (PsiJavaFile)psiFile;
final PsiClass[] classes = psiJavaFile.getClasses();
if (classes.length == 0) {
throw new IncorrectOperationException("This template did not produce a Java class or an interface\n"+psiFile.getText());
}
PsiClass createdClass = classes[0];
if(reformat){
CodeStyleManager.getInstance(project).reformat(psiJavaFile);
}
String className = createdClass.getName();
String fileName = className + "." + extension;
if(createdClass.isInterface()){
JavaDirectoryService.getInstance().checkCreateInterface(directory, className);
}
else{
JavaDirectoryService.getInstance().checkCreateClass(directory, className);
}
psiJavaFile = (PsiJavaFile)psiJavaFile.setName(fileName);
psiJavaFile = (PsiJavaFile)directory.add(psiJavaFile);
return psiJavaFile.getClasses()[0];
}
static void hackAwayEmptyPackage(PsiJavaFile file, FileTemplate template, Properties props) throws IncorrectOperationException {
if (!template.isJavaClassTemplate()) return;
String packageName = props.getProperty(FileTemplate.ATTRIBUTE_PACKAGE_NAME);
if(packageName == null || packageName.length() == 0 || packageName.equals(FileTemplate.ATTRIBUTE_PACKAGE_NAME)){
PsiPackageStatement packageStatement = file.getPackageStatement();
if (packageStatement != null) {
packageStatement.delete();
}
}
}
public boolean handlesTemplate(final FileTemplate template) {
FileType fileType = FileTypeManagerEx.getInstanceEx().getFileTypeByExtension(template.getExtension());
return fileType.equals(StdFileTypes.JAVA);
}
public PsiElement createFromTemplate(final Project project, final PsiDirectory directory, final String fileName, FileTemplate template,
String templateText, Properties props) throws IncorrectOperationException {
String extension = template.getExtension();
PsiElement result = createClassOrInterface(project, directory, templateText, template.isAdjust(), extension);
hackAwayEmptyPackage((PsiJavaFile)result.getContainingFile(), template, props);
return result;
}
public boolean canCreate(final PsiDirectory[] dirs) {
for (PsiDirectory dir : dirs) {
if (JavaDirectoryService.getInstance().getPackage(dir) != null) return true;
}
return false;
}
}
| source/com/intellij/ide/fileTemplates/JavaCreateFromTemplateHandler.java | package com.intellij.ide.fileTemplates;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.ex.FileTypeManagerEx;
import com.intellij.util.IncorrectOperationException;
import java.util.Properties;
/**
* @author yole
*/
public class JavaCreateFromTemplateHandler implements CreateFromTemplateHandler {
public static PsiClass createClassOrInterface(Project project,
PsiDirectory directory,
String content,
boolean reformat,
String extension) throws IncorrectOperationException {
if (extension == null) extension = StdFileTypes.JAVA.getDefaultExtension();
final PsiFile psiFile = PsiFileFactory.getInstance(project).createFileFromText("myclass" + "." + extension, content);
if (!(psiFile instanceof PsiJavaFile)){
throw new IncorrectOperationException("This template did not produce Java class nor interface!\n"+psiFile.getText());
}
PsiJavaFile psiJavaFile = (PsiJavaFile)psiFile;
final PsiClass[] classes = psiJavaFile.getClasses();
if (classes.length == 0) {
throw new IncorrectOperationException("This template did not produce Java class nor interface!\n"+psiFile.getText());
}
PsiClass createdClass = classes[0];
if(reformat){
CodeStyleManager.getInstance(project).reformat(psiJavaFile);
}
String className = createdClass.getName();
String fileName = className + "." + extension;
if(createdClass.isInterface()){
JavaDirectoryService.getInstance().checkCreateInterface(directory, className);
}
else{
JavaDirectoryService.getInstance().checkCreateClass(directory, className);
}
psiJavaFile = (PsiJavaFile)psiJavaFile.setName(fileName);
psiJavaFile = (PsiJavaFile)directory.add(psiJavaFile);
return psiJavaFile.getClasses()[0];
}
static void hackAwayEmptyPackage(PsiJavaFile file, FileTemplate template, Properties props) throws IncorrectOperationException {
if (!template.isJavaClassTemplate()) return;
String packageName = props.getProperty(FileTemplate.ATTRIBUTE_PACKAGE_NAME);
if(packageName == null || packageName.length() == 0 || packageName.equals(FileTemplate.ATTRIBUTE_PACKAGE_NAME)){
PsiPackageStatement packageStatement = file.getPackageStatement();
if (packageStatement != null) {
packageStatement.delete();
}
}
}
public boolean handlesTemplate(final FileTemplate template) {
FileType fileType = FileTypeManagerEx.getInstanceEx().getFileTypeByExtension(template.getExtension());
return fileType.equals(StdFileTypes.JAVA);
}
public PsiElement createFromTemplate(final Project project, final PsiDirectory directory, final String fileName, FileTemplate template,
String templateText, Properties props) throws IncorrectOperationException {
String extension = template.getExtension();
PsiElement result = createClassOrInterface(project, directory, templateText, template.isAdjust(), extension);
hackAwayEmptyPackage((PsiJavaFile)result.getContainingFile(), template, props);
return result;
}
public boolean canCreate(final PsiDirectory[] dirs) {
for (PsiDirectory dir : dirs) {
if (JavaDirectoryService.getInstance().getPackage(dir) != null) return true;
}
return false;
}
}
| fix wording
| source/com/intellij/ide/fileTemplates/JavaCreateFromTemplateHandler.java | fix wording | <ide><path>ource/com/intellij/ide/fileTemplates/JavaCreateFromTemplateHandler.java
<ide> if (extension == null) extension = StdFileTypes.JAVA.getDefaultExtension();
<ide> final PsiFile psiFile = PsiFileFactory.getInstance(project).createFileFromText("myclass" + "." + extension, content);
<ide> if (!(psiFile instanceof PsiJavaFile)){
<del> throw new IncorrectOperationException("This template did not produce Java class nor interface!\n"+psiFile.getText());
<add> throw new IncorrectOperationException("This template did not produce a Java class or an interface\n"+psiFile.getText());
<ide> }
<ide> PsiJavaFile psiJavaFile = (PsiJavaFile)psiFile;
<ide> final PsiClass[] classes = psiJavaFile.getClasses();
<ide> if (classes.length == 0) {
<del> throw new IncorrectOperationException("This template did not produce Java class nor interface!\n"+psiFile.getText());
<add> throw new IncorrectOperationException("This template did not produce a Java class or an interface\n"+psiFile.getText());
<ide> }
<ide> PsiClass createdClass = classes[0];
<ide> if(reformat){ |
|
Java | mit | 9339bff20ae85e1e6558818944377851b13c3939 | 0 | Ordinastie/MalisisCore | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 Ordinastie
*
* 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 net.malisis.core.renderer;
import java.lang.reflect.Field;
import javax.vecmath.Matrix4f;
import net.malisis.core.MalisisCore;
import net.malisis.core.MalisisRegistry;
import net.malisis.core.asm.AsmUtils;
import net.malisis.core.renderer.element.Face;
import net.malisis.core.renderer.element.Shape;
import net.malisis.core.renderer.element.Vertex;
import net.malisis.core.renderer.element.shape.Cube;
import net.malisis.core.renderer.font.FontRenderOptions;
import net.malisis.core.renderer.font.MalisisFont;
import net.malisis.core.renderer.icon.MalisisIcon;
import net.malisis.core.renderer.icon.metaprovider.IBlockMetaIconProvider;
import net.malisis.core.renderer.icon.metaprovider.IItemMetaIconProvider;
import net.malisis.core.renderer.icon.provider.IBlockIconProvider;
import net.malisis.core.renderer.icon.provider.IIconProvider;
import net.malisis.core.renderer.icon.provider.IItemIconProvider;
import net.malisis.core.renderer.model.MalisisModel;
import net.malisis.core.util.BlockPosUtils;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.renderer.DestroyBlockProgress;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderGlobal;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.WorldRenderer;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms.TransformType;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.client.renderer.vertex.VertexFormatElement;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Timer;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import org.lwjgl.opengl.GL11;
/**
* Base class for rendering. Handles the rendering. Provides easy registration of the renderer, and automatically sets up the context for
* the rendering.
*
* @author Ordinastie
*
*/
@SuppressWarnings("deprecation")
public class MalisisRenderer extends TileEntitySpecialRenderer implements IBlockRenderer, IRenderWorldLast
{
/** Reference to Tessellator.isDrawing field **/
private static Field isDrawingField;
public static VertexFormat vertexFormat = new VertexFormat()
{
{
setElement(new VertexFormatElement(0, VertexFormatElement.EnumType.FLOAT, VertexFormatElement.EnumUsage.POSITION, 3));
setElement(new VertexFormatElement(0, VertexFormatElement.EnumType.UBYTE, VertexFormatElement.EnumUsage.COLOR, 4));
setElement(new VertexFormatElement(0, VertexFormatElement.EnumType.FLOAT, VertexFormatElement.EnumUsage.UV, 2));
setElement(new VertexFormatElement(1, VertexFormatElement.EnumType.SHORT, VertexFormatElement.EnumUsage.UV, 2));
setElement(new VertexFormatElement(0, VertexFormatElement.EnumType.BYTE, VertexFormatElement.EnumUsage.NORMAL, 3));
setElement(new VertexFormatElement(0, VertexFormatElement.EnumType.BYTE, VertexFormatElement.EnumUsage.PADDING, 1));
}
};
/** Whether this {@link MalisisRenderer} initialized. (initialize() already called) */
private boolean initialized = false;
/** Tessellator reference. */
protected WorldRenderer wr = Tessellator.getInstance().getWorldRenderer();
/** Current world reference (BLOCK/TESR/IRWL). */
protected IBlockAccess world;
/** Position of the block (BLOCK/TESR). */
protected BlockPos pos;
/** Block to render (BLOCK/TESR). */
protected Block block;
/** Metadata of the block to render (BLOCK/TESR). */
protected IBlockState blockState;
/** TileEntity currently drawing (TESR). */
protected TileEntity tileEntity;
/** Partial tick time (TESR/IRWL). */
protected float partialTick = 0;
/** ItemStack to render (ITEM). */
protected ItemStack itemStack;
/** Item to render (ITEM) */
protected Item item;
/** Type of render for item (ITEM) **/
protected TransformType tranformType;
/** RenderGlobal reference (IRWL) */
protected RenderGlobal renderGlobal;
/** Type of rendering. */
protected RenderType renderType;
/** Mode of rendering (GL constant). */
protected int drawMode;
/** Base brightness of the block. */
protected int baseBrightness;
/** An override texture set by the renderer. */
protected MalisisIcon overrideTexture;
/** Whether the damage for the blocks should be handled by this {@link MalisisRenderer} (for TESR). */
protected boolean getBlockDamage = false;
/** Current block destroy progression (for TESR). */
protected DestroyBlockProgress destroyBlockProgress = null;
/** Whether at least one vertex has been drawn. */
protected boolean vertexDrawn = false;
/**
* Instantiates a new {@link MalisisRenderer}.
*/
public MalisisRenderer()
{
//this.renderId = RenderingRegistry.getNextAvailableRenderId();
}
// #region set()
/**
* Resets data so this {@link MalisisRenderer} can be reused.
*/
public void reset()
{
this.wr = null;
this.renderType = RenderType.UNSET;
this.drawMode = 0;
this.world = null;
this.pos = null;
this.block = null;
this.blockState = null;
this.item = null;
this.itemStack = null;
this.overrideTexture = null;
this.destroyBlockProgress = null;
}
/**
* Sets informations for this {@link MalisisRenderer}.
*
* @param world the world
* @param block the block
* @param x the x
* @param y the y
* @param z the z
* @param metadata the metadata
*/
public void set(IBlockAccess world, Block block, BlockPos pos, IBlockState blockState)
{
this.world = world;
this.pos = pos;
this.block = block;
this.blockState = blockState;
}
/**
* Sets informations for this {@link MalisisRenderer}.
*
* @param world the world
*/
public void set(IBlockAccess world)
{
this.world = world;
}
/**
* Sets informations for this {@link MalisisRenderer}.
*
* @param block the block
*/
public void set(Block block)
{
this.block = block;
this.blockState = block.getDefaultState();
}
/**
* Sets informations for this {@link MalisisRenderer}.
*
* @param blockMetadata the block metadata
*/
public void set(IBlockState blockState)
{
this.blockState = blockState;
}
/**
* Sets informations for this {@link MalisisRenderer}.
*
* @param x the x
* @param y the y
* @param z the z
*/
public void set(BlockPos pos)
{
this.pos = pos;
}
/**
* Sets informations for this {@link MalisisRenderer}.
*
* @param te the te
* @param partialTick the partial tick
*/
public void set(TileEntity te, float partialTick)
{
set(te.getWorld(), te.getBlockType(), te.getPos(), te.getWorld().getBlockState(te.getPos()));
this.partialTick = partialTick;
this.tileEntity = te;
}
/**
* Sets informations for this {@link MalisisRenderer}.
*
* @param type the type
* @param itemStack the item stack
*/
public void set(ItemStack itemStack)
{
this.itemStack = itemStack;
this.item = itemStack.getItem();
if (item instanceof ItemBlock)
set(Block.getBlockFromItem(itemStack.getItem()));
}
// #end
//#region IBlockRenderer
@Override
public boolean renderBlock(WorldRenderer wr, IBlockAccess world, BlockPos pos, IBlockState state)
{
this.wr = wr;
set(world, state.getBlock(), pos, state);
prepare(RenderType.BLOCK);
render();
clean();
return vertexDrawn;
}
//#end IBlockRenderer
//#region IItemRenderer
@Override
public boolean renderItem(ItemStack itemStack, float partialTick)
{
this.wr = Tessellator.getInstance().getWorldRenderer();
set(itemStack);
prepare(RenderType.ITEM);
render();
clean();
return true;
}
@Override
public boolean isGui3d()
{
return true;
}
@Override
public Matrix4f getTransform(TransformType tranformType)
{
this.tranformType = tranformType;
return null;
}
//#end IItemRenderer
// #region TESR
/**
* Renders a {@link TileEntitySpecialRenderer}.
*
* @param te the TileEntity
* @param x the x
* @param y the y
* @param z the z
* @param partialTick the partial tick
*/
@Override
public void renderTileEntityAt(TileEntity te, double x, double y, double z, float partialTick, int destroyStage)
{
this.wr = Tessellator.getInstance().getWorldRenderer();
set(te, partialTick);
prepare(RenderType.TILE_ENTITY, x, y, z);
render();
//TODO
// if (getBlockDamage)
// {
// destroyBlockProgress = getBlockDestroyProgress();
// if (destroyBlockProgress != null)
// {
// next();
//
// GL11.glEnable(GL11.GL_BLEND);
// OpenGlHelper.glBlendFunc(GL11.GL_DST_COLOR, GL11.GL_SRC_COLOR, GL11.GL_ONE, GL11.GL_ZERO);
// GL11.glAlphaFunc(GL11.GL_GREATER, 0);
// GL11.glColor4f(1.0F, 1.0F, 1.0F, 0.5F);
//
// t.disableColor();
// renderDestroyProgress();
// next();
// GL11.glDisable(GL11.GL_BLEND);
// }
// }
clean();
}
// #end TESR
// #region IRenderWorldLast
@Override
public boolean shouldSetViewportPosition()
{
return true;
}
@Override
public boolean shouldRender(RenderWorldLastEvent event, IBlockAccess world)
{
return true;
}
@Override
public void renderWorldLastEvent(RenderWorldLastEvent event, IBlockAccess world)
{
set(world);
wr = Tessellator.getInstance().getWorldRenderer();
partialTick = event.partialTicks;
renderGlobal = event.context;
double x = 0, y = 0, z = 0;
if (shouldSetViewportPosition())
{
EntityPlayerSP p = Minecraft.getMinecraft().thePlayer;
x = -(p.lastTickPosX + (p.posX - p.lastTickPosX) * partialTick);
y = -(p.lastTickPosY + (p.posY - p.lastTickPosY) * partialTick);
z = -(p.lastTickPosZ + (p.posZ - p.lastTickPosZ) * partialTick);
}
prepare(RenderType.WORLD_LAST, x, y, z);
render();
clean();
}
// #end IRenderWorldLast
// #region prepare()
/**
* Prepares the {@link Tessellator} and the GL states for the <b>renderType</b>. <b>data</b> is only used for TESR and IRWL.<br>
* TESR and IRWL rendering are surrounded by glPushAttrib(GL_LIGHTING_BIT) and block texture sheet is bound.
*
* @param renderType the render type
* @param data the data
*/
public void prepare(RenderType renderType, double... data)
{
_initialize();
this.renderType = renderType;
if (renderType == RenderType.BLOCK)
{
wr.setVertexFormat(DefaultVertexFormats.BLOCK);
}
else if (renderType == RenderType.ITEM)
{
startDrawing();
}
else if (renderType == RenderType.TILE_ENTITY)
{
GlStateManager.pushAttrib();
GlStateManager.pushMatrix();
GlStateManager.disableLighting();
GlStateManager.translate(data[0], data[1], data[2]);
bindTexture(TextureMap.locationBlocksTexture);
startDrawing();
}
else if (renderType == RenderType.WORLD_LAST)
{
GlStateManager.pushAttrib();
GlStateManager.pushMatrix();
GlStateManager.translate(data[0], data[1], data[2]);
bindTexture(TextureMap.locationBlocksTexture);
startDrawing();
}
}
/**
* Cleans the current renderer state.
*/
public void clean()
{
if (renderType == RenderType.ITEM)
{
draw();
// GlStateManager.enableLighting();
// GlStateManager.popMatrix();
// GlStateManager.popAttrib();
}
else if (renderType == RenderType.TILE_ENTITY)
{
draw();
GlStateManager.enableLighting();
GlStateManager.popMatrix();
GlStateManager.popAttrib();
}
else if (renderType == RenderType.WORLD_LAST)
{
draw();
GlStateManager.popMatrix();
GlStateManager.popAttrib();
}
reset();
}
/**
* Tells the {@link Tessellator} to start drawing GL_QUADS.
*/
public void startDrawing()
{
startDrawing(GL11.GL_QUADS);
}
/**
* Tells the {@link Tessellator} to start drawing <b>drawMode</b>.
*
* @param drawMode the draw mode
*/
public void startDrawing(int drawMode)
{
if (isDrawing())
draw();
wr.startDrawing(drawMode);
wr.setVertexFormat(vertexFormat);
this.drawMode = drawMode;
}
/**
* Checks if the {@link Tessellator} is currently drawing.
*
* @return true, if is drawing
*/
public boolean isDrawing()
{
if (isDrawingField == null)
isDrawingField = AsmUtils.changeFieldAccess(WorldRenderer.class, "isDrawing", "field_179010_r");
try
{
if (wr == null)
throw new NullPointerException("[MalisisRenderer] WorldRenderer not set for " + renderType);
return isDrawingField.getBoolean(wr);
}
catch (IllegalArgumentException | IllegalAccessException e)
{
MalisisCore.log.error("[MalisisRenderer] Failed to get Tessellator.isDrawing value", e);
return false;
}
}
/**
* Triggers a draw and restart drawing with current {@link MalisisRenderer#drawMode}.
*/
public void next()
{
next(drawMode);
}
/**
* Triggers a draw and restart drawing with <b>drawMode</b>.
*
* @param drawMode the draw mode
*/
public void next(int drawMode)
{
draw();
startDrawing(drawMode);
}
/**
* Triggers a draw.
*/
public void draw()
{
if (isDrawing())
Tessellator.getInstance().draw();
}
/**
* Enables the blending for the rendering. Ineffective for BLOCK renderType.
*/
public void enableBlending()
{
if (renderType == RenderType.BLOCK)
return;
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
GlStateManager.alphaFunc(GL11.GL_GREATER, 0.0F);
GlStateManager.shadeModel(GL11.GL_SMOOTH);
GlStateManager.enableColorMaterial();
}
/**
* Disables blending for the rendering. Ineffective for BLOCK renderType.
*/
public void disableBlending()
{
if (renderType == RenderType.BLOCK)
return;
GlStateManager.disableBlend();
GlStateManager.disableColorMaterial();
}
/**
* Enables textures
*/
public void enableTextures()
{
GL11.glEnable(GL11.GL_TEXTURE_2D);
}
/**
* Disables textures.
*/
public void disableTextures()
{
GL11.glDisable(GL11.GL_TEXTURE_2D);
}
@Override
protected void bindTexture(ResourceLocation resourceLocaltion)
{
Minecraft.getMinecraft().getTextureManager().bindTexture(resourceLocaltion);
}
/**
* Sets billboard mode.<br>
* Contents drawn will always be facing the player.
*
* @param x the x
* @param y the y
* @param z the z
*/
public void setBillboard(float x, float y, float z)
{
EntityPlayerSP player = Minecraft.getMinecraft().thePlayer;
GlStateManager.pushMatrix();
GlStateManager.translate(x, y, z);
GlStateManager.rotate(180 - player.rotationYaw, 0, 1, 0);
}
/**
* End billboard mode.
*/
public void endBillboard()
{
GlStateManager.popMatrix();
}
// #end prepare()
/**
* _initialize.
*/
protected final void _initialize()
{
if (initialized)
return;
initialize();
initialized = true;
}
/**
* Initializes this {@link MalisisRenderer}. Does nothing by default.<br>
* Called the first time a rendering is done and should be overridden if some setup is needed for the rendering (building shape and
* parameters).
*/
protected void initialize()
{}
/**
* Renders the blocks using the default Minecraft rendering system.
*
* @param renderer the renderer
*/
public void renderStandard()
{
Minecraft.getMinecraft().getBlockRendererDispatcher().renderBlock(blockState, pos, world, wr);
}
/**
* Main rendering method. Draws simple cube by default.<br>
* Should be overridden to handle the rendering.
*/
public void render()
{
drawShape(new Cube());
}
protected void drawModel(MalisisModel model, RenderParameters params)
{
for (Shape s : model)
drawShape(s, params);
}
/**
* Draws a {@link Shape} without {@link RenderParameters} (default will be used).
*
* @param shape the shape
*/
public void drawShape(Shape shape)
{
drawShape(shape, null);
}
/**
* Draws a {@link Shape} with specified {@link RenderParameters}.
*
* @param s the s
* @param params the params
*/
public void drawShape(Shape s, RenderParameters params)
{
if (s == null)
return;
s.applyMatrix();
for (Face f : s.getFaces())
drawFace(f, params);
}
/**
* Draws a {@link Face} with its own {@link RenderParameters}.
*
* @param face the face
*/
protected void drawFace(Face face)
{
drawFace(face, null);
}
/**
* Draws a {@link Face} with specified {@link RenderParameters}.
*
* @param face the f
* @param params the face params
*/
protected void drawFace(Face face, RenderParameters params)
{
if (face == null)
return;
int vertexCount = face.getVertexes().length;
if (vertexCount != 4 && renderType == RenderType.BLOCK)
{
MalisisCore.log.error("[MalisisRenderer] Attempting to render a face containing {} vertexes in BLOCK for {}. Ignored",
vertexCount, block);
return;
}
params = RenderParameters.merge(params, face.getParameters());
if (!shouldRenderFace(face, params))
return;
if (params.applyTexture.get())
applyTexture(face, params);
//use normals if available
if ((renderType == RenderType.ITEM || params.useNormals.get()) && params.direction.get() != null)
wr.setNormal(params.direction.get().getFrontOffsetX(), params.direction.get().getFrontOffsetY(), params.direction.get()
.getFrontOffsetZ());
baseBrightness = getBaseBrightness(params);
for (int i = 0; i < face.getVertexes().length; i++)
drawVertex(face.getVertexes()[i], i, params);
//we need to separate each face
if (drawMode == GL11.GL_POLYGON || drawMode == GL11.GL_LINE || drawMode == GL11.GL_LINE_STRIP || drawMode == GL11.GL_LINE_LOOP)
next();
}
/**
* Draws a single {@link Vertex}.
*
* @param vertex the vertex
* @param number the offset inside the face. (Used for AO)
*/
protected void drawVertex(Vertex vertex, int number, RenderParameters params)
{
if (vertex == null)
vertex = new Vertex(0, 0, 0);
// brightness
int brightness = calcVertexBrightness(vertex, number, params);
vertex.setBrightness(brightness);
// color
int color = calcVertexColor(vertex, number, params);
vertex.setColor(color);
// alpha
if (params != null && !params.usePerVertexAlpha.get())
vertex.setAlpha(params.alpha.get());
if (renderType == RenderType.ITEM && params != null)
vertex.setNormal(params.direction.get());
wr.addVertexData(getVertexData(vertex));
vertexDrawn = true;
}
/**
* Gets the vertex data.
*
* @param vertex the vertex
* @return the vertex data
*/
private int[] getVertexData(Vertex vertex)
{
float x = (float) vertex.getX();
float y = (float) vertex.getY();
float z = (float) vertex.getZ();
int size = vertexFormat.getNextOffset();
if (renderType == RenderType.BLOCK)
{
size = DefaultVertexFormats.BLOCK.getNextOffset();
//when drawing a block, the position to draw is relative to current chunk
BlockPos chunkPos = BlockPosUtils.chunkPosition(pos);
x += chunkPos.getX();
y += chunkPos.getY();
z += chunkPos.getZ();
}
int[] data = new int[size / 4];
data[0] = Float.floatToRawIntBits(x);
data[1] = Float.floatToRawIntBits(y);
data[2] = Float.floatToRawIntBits(z);
data[3] = vertex.getRGBA();
data[4] = Float.floatToRawIntBits((float) vertex.getU());
data[5] = Float.floatToRawIntBits((float) vertex.getV());
data[6] = vertex.getBrightness();
if (renderType != RenderType.BLOCK)
data[7] = vertex.getNormal();
return data;
}
/**
* Draws a string at the specified coordinates, with color and shadow. The string gets translated. Uses FontRenderer.drawString().
*
* @param font the font
* @param text the text
* @param x the x
* @param y the y
* @param z the z
* @param fro the fro
*/
public void drawText(MalisisFont font, String text, float x, float y, float z, FontRenderOptions fro)
{
if (font == null)
font = MalisisFont.minecraftFont;
if (fro == null)
fro = new FontRenderOptions();
font.render(this, text, x, y, z, fro);
}
/**
* Checks if a {@link Face} should be rendered. {@link RenderParameters#direction} needs to be defined for the <b>face</b>.
*
* @param face the face
* @return true, if successful
*/
protected boolean shouldRenderFace(Face face, RenderParameters params)
{
if (renderType != RenderType.BLOCK || world == null || block == null)
return true;
if (params != null && params.renderAllFaces.get())
return true;
RenderParameters p = face.getParameters();
if (p.direction.get() == null || p.renderAllFaces.get())
return true;
boolean b = block.shouldSideBeRendered(world, pos.offset(p.direction.get()), p.direction.get());
return b;
}
/**
* Applies the texture to the {@link Shape}.<br>
* Usually necessary before some shape transformations in conjunction with {@link RenderParameters#applyTexture} set to
* <code>false</code> to prevent reapplying texture when rendering.
*
* @param shape the shape
*/
public void applyTexture(Shape shape)
{
applyTexture(shape, null);
}
/**
* Applies the texture to the {@link Shape} with specified {@link RenderParameters}.<br>
* Usually necessary before some shape transformations in conjunction with {@link RenderParameters#applyTexture} set to
* <code>false</code> to prevent reapplying texture when rendering.
*
* @param shape the shape
* @param params the parameters
*/
public void applyTexture(Shape shape, RenderParameters params)
{
//shape.applyMatrix();
for (Face f : shape.getFaces())
{
RenderParameters rp = RenderParameters.merge(params, f.getParameters());
applyTexture(f, rp);
}
}
/**
* Applies the texture to the {@link Face} with specified {@link RenderParameters}.<br>
*
* @param shape the shape
* @param params the parameters
*/
public void applyTexture(Face face, RenderParameters params)
{
MalisisIcon icon = getIcon(face, params);
boolean flipU = params.flipU.get();
if (params.direction.get() == EnumFacing.NORTH || params.direction.get() == EnumFacing.EAST)
flipU = !flipU;
face.setTexture(icon, flipU, params.flipV.get(), params.interpolateUV.get());
}
/**
* Gets the {@link MalisisIcon} corresponding to the specified {@link RenderParameters}.<br>
* If {@link #block} or {@link #item} is an {@link IIconProvider} and give the right provider for the current context, gets the icon
* from that provider.
*
* @param face the face
* @param params the params
* @return the icon
*/
protected MalisisIcon getIcon(Face face, RenderParameters params)
{
IIconProvider ip = getIconProvider(params);
if (ip instanceof IItemIconProvider && itemStack != null)
return ((IItemIconProvider) ip).getIcon(itemStack);
if (ip instanceof IBlockIconProvider && block != null)
{
IBlockIconProvider iblockp = (IBlockIconProvider) ip;
if (renderType == RenderType.BLOCK || renderType == RenderType.TILE_ENTITY)
return iblockp.getIcon(world, pos, blockState, params.direction.get());
else if (renderType == RenderType.ITEM)
return iblockp.getIcon(itemStack, params.direction.get());
}
IIconProvider iconProvider = params.iconProvider.get();
return iconProvider != null ? iconProvider.getIcon() : null;
}
/**
* Gets the {@link IIconProvider} either from parameters, the block or the item.
*
* @return the icon provider
*/
private IIconProvider getIconProvider(RenderParameters params)
{
if (params.iconProvider.get() != null)
return params.iconProvider.get();
if (item instanceof IItemMetaIconProvider && ((IItemMetaIconProvider) item).getItemIconProvider() != null)
return ((IItemMetaIconProvider) item).getItemIconProvider();
if (block instanceof IBlockMetaIconProvider && ((IBlockMetaIconProvider) block).getBlockIconProvider() != null)
return ((IBlockMetaIconProvider) block).getBlockIconProvider();
return null;
}
/**
* Calculates the ambient occlusion for a {@link Vertex} and also applies the side dependent shade.<br>
* <b>aoMatrix</b> is the list of block coordinates necessary to compute AO. If it's empty, only the global face shade is applied.<br>
* Also, <i>params.colorMultiplier</i> is applied as well.
*
* @param vertex the vertex
* @param aoMatrix the ao matrix
* @return the int
*/
protected int calcVertexColor(Vertex vertex, int number, RenderParameters params)
{
int color = 0xFFFFFF;
if (params == null)
return color;
if (params.usePerVertexColor.get()) //vertex should use their own colors
color = vertex.getColor();
if (params.colorMultiplier.get() != null) //global color multiplier is set
color = params.colorMultiplier.get();
else if (block != null) //use block color multiplier
color = world != null ? block.colorMultiplier(world, pos, 0) : block.getRenderColor(blockState);
if (drawMode == GL11.GL_LINE) //no AO for lines
return color;
if (renderType != RenderType.BLOCK && renderType != RenderType.TILE_ENTITY) //no AO for item/inventories
return color;
int[][] aoMatrix = (int[][]) params.aoMatrix.get(number);
float factor = 1;
//calculate AO
if (params.calculateAOColor.get() && aoMatrix != null && Minecraft.isAmbientOcclusionEnabled()
&& block.getLightValue(world, pos) == 0)
{
factor = getBlockAmbientOcclusion(world, pos.offset(params.direction.get()));
for (int i = 0; i < aoMatrix.length; i++)
factor += getBlockAmbientOcclusion(world, pos.add(aoMatrix[i][0], aoMatrix[i][1], aoMatrix[i][2]));
factor /= (aoMatrix.length + 1);
}
//apply face dependent shading
factor *= params.colorFactor.get();
int r = (int) ((color >> 16 & 255) * factor);
int g = (int) ((color >> 8 & 255) * factor);
int b = (int) ((color & 255) * factor);
color = r << 16 | g << 8 | b;
return color;
}
/**
* Gets the base brightness for the current {@link Face}.<br>
* If <i>params.useBlockBrightness</i> = false, <i>params.brightness</i>. Else, the brightness is determined based on
* <i>params.offset</i> and <i>getBlockBounds()</i>
*
* @return the base brightness
*/
protected int getBaseBrightness(RenderParameters params)
{
if (!params.useEnvironmentBrightness.get())
return params.brightness.get();
if (block != null)
{
if (world != null && block.getLightValue(world, pos) != 0)
return block.getLightValue(world, pos) << 4;
else if (block.getLightValue() != 0)
return block.getLightValue() << 4;
}
if (renderType == RenderType.ITEM)
return Minecraft.getMinecraft().thePlayer.getBrightnessForRender(getPartialTick());
//not in world
if (world == null || block == null)
return params.brightness.get();
//no direction, we can only use current block brightness
if (params.direction.get() == null && block != null)
return block.getMixedBrightnessForBlock(world, pos);
AxisAlignedBB bounds = getRenderBounds(params);
EnumFacing dir = params.direction.get();
BlockPos p = pos;
if (dir != null)
p = p.offset(dir);
//use the brightness of the block next to it
if (bounds != null)
{
if (dir == EnumFacing.WEST && bounds.minX > 0)
p = p.east();
else if (dir == EnumFacing.EAST && bounds.maxX < 1)
p = p.west();
else if (dir == EnumFacing.NORTH && bounds.minZ > 0)
p = p.south();
else if (dir == EnumFacing.SOUTH && bounds.maxZ < 1)
p = p.north();
else if (dir == EnumFacing.DOWN && bounds.minY > 0)
p = p.up();
else if (dir == EnumFacing.UP && bounds.maxY < 1)
p = p.down();
}
return getMixedBrightnessForBlock(world, p);
}
/**
* Calculates the ambient occlusion brightness for a {@link Vertex}. <b>aoMatrix</b> is the list of block coordinates necessary to
* compute AO. Only first 3 blocks are used.<br>
*
* @param vertex the vertex
* @param aoMatrix the ao matrix
* @return the int
*/
protected int calcVertexBrightness(Vertex vertex, int number, RenderParameters params)
{
if (params == null)
return baseBrightness;
if (params.usePerVertexBrightness.get())
return vertex.getBrightness();
if (drawMode == GL11.GL_LINE) //no AO for lines
return baseBrightness;
if (renderType != RenderType.BLOCK && renderType != RenderType.TILE_ENTITY) //not in world
return baseBrightness;
int[][] aoMatrix = (int[][]) params.aoMatrix.get(number);
if (!params.calculateBrightness.get() || aoMatrix == null) //no data
return baseBrightness;
if (!Minecraft.isAmbientOcclusionEnabled() || block.getLightValue(world, pos) != 0) // emit light
return baseBrightness;
int[] b = new int[Math.max(3, aoMatrix.length)];
for (int i = 0; i < b.length; i++)
b[i] += getMixedBrightnessForBlock(world, pos.add(aoMatrix[i][0], aoMatrix[i][1], aoMatrix[i][2]));
int brightness = getAoBrightness(b[0], b[1], b[2], baseBrightness);
return brightness;
}
/**
* Does the actual brightness calculation (copied from net.minecraft.client.renderer.BlocksRenderer.java)
*
* @param b1 the b1
* @param b2 the b2
* @param b3 the b3
* @param base the base
* @return the ao brightness
*/
protected int getAoBrightness(int b1, int b2, int b3, int base)
{
if (b1 == 0)
b1 = base;
if (b2 == 0)
b2 = base;
if (b3 == 0)
b3 = base;
return b1 + b2 + b3 + base >> 2 & 16711935;
}
/**
* Gets the block ambient occlusion value. Contrary to base Minecraft code, it's the actual block at the <b>x</b>, <b>y</b> and <b>z</b>
* coordinates which is used to get the value, and not value of the block drawn. This allows to have different logic behaviors for AO
* values for a block.
*
* @param world the world
* @param x the x
* @param y the y
* @param z the z
* @return the block ambient occlusion
*/
protected float getBlockAmbientOcclusion(IBlockAccess world, BlockPos pos)
{
Block block = world.getBlockState(pos).getBlock();
if (block == null)
return 1.0F;
return block.getAmbientOcclusionLightValue();
}
/**
* Gets the mix brightness for a block (sky + block source).
*
* @param world the world
* @param x the x
* @param y the y
* @param z the z
* @return the mixed brightness for block
*/
protected int getMixedBrightnessForBlock(IBlockAccess world, BlockPos pos)
{
// return world.getLightBrightnessForSkyBlocks(x, y, z, 0);
return world.getBlockState(pos).getBlock().getMixedBrightnessForBlock(world, pos);
}
/**
* Gets the rendering bounds. If <i>params.useBlockBounds</i> = false, <i>params.renderBounds</i> is used instead of the actual block
* bounds.
*
* @return the render bounds
*/
protected AxisAlignedBB getRenderBounds(RenderParameters params)
{
if (block == null || !params.useBlockBounds.get())
return params.renderBounds.get();
if (world != null)
block.setBlockBoundsBasedOnState(world, pos);
return new AxisAlignedBB(block.getBlockBoundsMinX(), block.getBlockBoundsMinY(), block.getBlockBoundsMinZ(),
block.getBlockBoundsMaxX(), block.getBlockBoundsMaxY(), block.getBlockBoundsMaxZ());
}
private static Timer timer = null;
public static float getPartialTick()
{
if (timer == null)
{
Field f = AsmUtils.changeFieldAccess(Minecraft.class, "timer", "field_71428_T");
try
{
timer = (Timer) f.get(Minecraft.getMinecraft());
}
catch (IllegalArgumentException | IllegalAccessException e)
{
MalisisCore.log.info("[MalisisRenderer] Failed to acces Minecraft timer.");
timer = new Timer(20F);
}
}
return timer.elapsedPartialTicks;
}
/**
* Registers this {@link MalisisRenderer} to be used for rendering the specified <b>block</b>.
*
* @param block the block
*/
public void registerFor(Block block)
{
registerFor(block, getDefaultRenderInfos());
}
public void registerFor(Block block, IItemRenderInfo renderInfos)
{
MalisisRegistry.registerBlockRenderer(block, this, renderInfos);
}
/**
* Registers this {@link MalisisRenderer} to be used for rendering the specified <b>item</b>.
*
* @param item the item
*/
public void registerFor(Item item)
{
registerFor(item, getDefaultRenderInfos());
}
public void registerFor(Item item, IItemRenderInfo renderInfos)
{
MalisisRegistry.registerItemRenderer(item, this, renderInfos);
}
/**
* Registers this {@link MalisisRenderer} to be used for rendering for a specified class.<br>
* Class has to extend TileEntity.<br>
*
* @param clazz the clazz
*/
public void registerFor(Class<? extends TileEntity> clazz)
{
ClientRegistry.bindTileEntitySpecialRenderer(clazz, this);
}
/**
* Registers this {@link MalisisRenderer} to be used for {@link RenderWorldLastEvent}.
*/
public void registerForRenderWorldLast()
{
MalisisRegistry.registerRenderWorldLast(this);
}
private IItemRenderInfo getDefaultRenderInfos()
{
return new IItemRenderInfo()
{
@Override
public boolean isGui3d()
{
return MalisisRenderer.this.isGui3d();
}
@Override
public Matrix4f getTransform(TransformType tranformType)
{
return MalisisRenderer.this.getTransform(tranformType);
}
};
}
}
| src/main/java/net/malisis/core/renderer/MalisisRenderer.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 Ordinastie
*
* 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 net.malisis.core.renderer;
import java.lang.reflect.Field;
import javax.vecmath.Matrix4f;
import net.malisis.core.MalisisCore;
import net.malisis.core.MalisisRegistry;
import net.malisis.core.asm.AsmUtils;
import net.malisis.core.renderer.element.Face;
import net.malisis.core.renderer.element.Shape;
import net.malisis.core.renderer.element.Vertex;
import net.malisis.core.renderer.element.shape.Cube;
import net.malisis.core.renderer.font.FontRenderOptions;
import net.malisis.core.renderer.font.MalisisFont;
import net.malisis.core.renderer.icon.MalisisIcon;
import net.malisis.core.renderer.icon.metaprovider.IBlockMetaIconProvider;
import net.malisis.core.renderer.icon.metaprovider.IItemMetaIconProvider;
import net.malisis.core.renderer.icon.provider.IBlockIconProvider;
import net.malisis.core.renderer.icon.provider.IIconProvider;
import net.malisis.core.renderer.icon.provider.IItemIconProvider;
import net.malisis.core.renderer.model.MalisisModel;
import net.malisis.core.util.BlockPosUtils;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.renderer.DestroyBlockProgress;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderGlobal;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.WorldRenderer;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms.TransformType;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.client.renderer.vertex.VertexFormatElement;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Timer;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import org.lwjgl.opengl.GL11;
/**
* Base class for rendering. Handles the rendering. Provides easy registration of the renderer, and automatically sets up the context for
* the rendering.
*
* @author Ordinastie
*
*/
@SuppressWarnings("deprecation")
public class MalisisRenderer extends TileEntitySpecialRenderer implements IBlockRenderer, IRenderWorldLast
{
/** Reference to Tessellator.isDrawing field **/
private static Field isDrawingField;
public static VertexFormat vertexFormat = new VertexFormat()
{
{
setElement(new VertexFormatElement(0, VertexFormatElement.EnumType.FLOAT, VertexFormatElement.EnumUsage.POSITION, 3));
setElement(new VertexFormatElement(0, VertexFormatElement.EnumType.UBYTE, VertexFormatElement.EnumUsage.COLOR, 4));
setElement(new VertexFormatElement(0, VertexFormatElement.EnumType.FLOAT, VertexFormatElement.EnumUsage.UV, 2));
setElement(new VertexFormatElement(1, VertexFormatElement.EnumType.SHORT, VertexFormatElement.EnumUsage.UV, 2));
setElement(new VertexFormatElement(0, VertexFormatElement.EnumType.BYTE, VertexFormatElement.EnumUsage.NORMAL, 3));
setElement(new VertexFormatElement(0, VertexFormatElement.EnumType.BYTE, VertexFormatElement.EnumUsage.PADDING, 1));
}
};
/** Whether this {@link MalisisRenderer} initialized. (initialize() already called) */
private boolean initialized = false;
/** Tessellator reference. */
protected WorldRenderer wr = Tessellator.getInstance().getWorldRenderer();
/** Current world reference (BLOCK/TESR/IRWL). */
protected IBlockAccess world;
/** Position of the block (BLOCK/TESR). */
protected BlockPos pos;
/** Block to render (BLOCK/TESR). */
protected Block block;
/** Metadata of the block to render (BLOCK/TESR). */
protected IBlockState blockState;
/** TileEntity currently drawing (TESR). */
protected TileEntity tileEntity;
/** Partial tick time (TESR/IRWL). */
protected float partialTick = 0;
/** ItemStack to render (ITEM). */
protected ItemStack itemStack;
/** Item to render (ITEM) */
protected Item item;
/** Type of render for item (ITEM) **/
protected TransformType tranformType;
/** RenderGlobal reference (IRWL) */
protected RenderGlobal renderGlobal;
/** Type of rendering. */
protected RenderType renderType;
/** Mode of rendering (GL constant). */
protected int drawMode;
/** Base brightness of the block. */
protected int baseBrightness;
/** An override texture set by the renderer. */
protected MalisisIcon overrideTexture;
/** Whether the damage for the blocks should be handled by this {@link MalisisRenderer} (for TESR). */
protected boolean getBlockDamage = false;
/** Current block destroy progression (for TESR). */
protected DestroyBlockProgress destroyBlockProgress = null;
/** Whether at least one vertex has been drawn. */
protected boolean vertexDrawn = false;
/**
* Instantiates a new {@link MalisisRenderer}.
*/
public MalisisRenderer()
{
//this.renderId = RenderingRegistry.getNextAvailableRenderId();
}
// #region set()
/**
* Resets data so this {@link MalisisRenderer} can be reused.
*/
public void reset()
{
this.wr = null;
this.renderType = RenderType.UNSET;
this.drawMode = 0;
this.world = null;
this.pos = null;
this.block = null;
this.blockState = null;
this.item = null;
this.itemStack = null;
this.overrideTexture = null;
this.destroyBlockProgress = null;
}
/**
* Sets informations for this {@link MalisisRenderer}.
*
* @param world the world
* @param block the block
* @param x the x
* @param y the y
* @param z the z
* @param metadata the metadata
*/
public void set(IBlockAccess world, Block block, BlockPos pos, IBlockState blockState)
{
this.world = world;
this.pos = pos;
this.block = block;
this.blockState = blockState;
}
/**
* Sets informations for this {@link MalisisRenderer}.
*
* @param world the world
*/
public void set(IBlockAccess world)
{
this.world = world;
}
/**
* Sets informations for this {@link MalisisRenderer}.
*
* @param block the block
*/
public void set(Block block)
{
this.block = block;
this.blockState = block.getDefaultState();
}
/**
* Sets informations for this {@link MalisisRenderer}.
*
* @param blockMetadata the block metadata
*/
public void set(IBlockState blockState)
{
this.blockState = blockState;
}
/**
* Sets informations for this {@link MalisisRenderer}.
*
* @param x the x
* @param y the y
* @param z the z
*/
public void set(BlockPos pos)
{
this.pos = pos;
}
/**
* Sets informations for this {@link MalisisRenderer}.
*
* @param te the te
* @param partialTick the partial tick
*/
public void set(TileEntity te, float partialTick)
{
set(te.getWorld(), te.getBlockType(), te.getPos(), te.getWorld().getBlockState(te.getPos()));
this.partialTick = partialTick;
this.tileEntity = te;
}
/**
* Sets informations for this {@link MalisisRenderer}.
*
* @param type the type
* @param itemStack the item stack
*/
public void set(ItemStack itemStack)
{
this.itemStack = itemStack;
this.item = itemStack.getItem();
if (item instanceof ItemBlock)
set(Block.getBlockFromItem(itemStack.getItem()));
}
// #end
//#region IBlockRenderer
@Override
public boolean renderBlock(WorldRenderer wr, IBlockAccess world, BlockPos pos, IBlockState state)
{
this.wr = wr;
set(world, state.getBlock(), pos, state);
prepare(RenderType.BLOCK);
render();
clean();
return vertexDrawn;
}
//#end IBlockRenderer
//#region IItemRenderer
@Override
public boolean renderItem(ItemStack itemStack, float partialTick)
{
this.wr = Tessellator.getInstance().getWorldRenderer();
set(itemStack);
prepare(RenderType.ITEM);
render();
clean();
return true;
}
@Override
public boolean isGui3d()
{
return true;
}
@Override
public Matrix4f getTransform(TransformType tranformType)
{
this.tranformType = tranformType;
return null;
}
//#end IItemRenderer
// #region TESR
/**
* Renders a {@link TileEntitySpecialRenderer}.
*
* @param te the TileEntity
* @param x the x
* @param y the y
* @param z the z
* @param partialTick the partial tick
*/
@Override
public void renderTileEntityAt(TileEntity te, double x, double y, double z, float partialTick, int destroyStage)
{
this.wr = Tessellator.getInstance().getWorldRenderer();
set(te, partialTick);
prepare(RenderType.TILE_ENTITY, x, y, z);
render();
//TODO
// if (getBlockDamage)
// {
// destroyBlockProgress = getBlockDestroyProgress();
// if (destroyBlockProgress != null)
// {
// next();
//
// GL11.glEnable(GL11.GL_BLEND);
// OpenGlHelper.glBlendFunc(GL11.GL_DST_COLOR, GL11.GL_SRC_COLOR, GL11.GL_ONE, GL11.GL_ZERO);
// GL11.glAlphaFunc(GL11.GL_GREATER, 0);
// GL11.glColor4f(1.0F, 1.0F, 1.0F, 0.5F);
//
// t.disableColor();
// renderDestroyProgress();
// next();
// GL11.glDisable(GL11.GL_BLEND);
// }
// }
clean();
}
// #end TESR
// #region IRenderWorldLast
@Override
public boolean shouldSetViewportPosition()
{
return true;
}
@Override
public boolean shouldRender(RenderWorldLastEvent event, IBlockAccess world)
{
return true;
}
@Override
public void renderWorldLastEvent(RenderWorldLastEvent event, IBlockAccess world)
{
set(world);
wr = Tessellator.getInstance().getWorldRenderer();
partialTick = event.partialTicks;
renderGlobal = event.context;
double x = 0, y = 0, z = 0;
if (shouldSetViewportPosition())
{
EntityPlayerSP p = Minecraft.getMinecraft().thePlayer;
x = -(p.lastTickPosX + (p.posX - p.lastTickPosX) * partialTick);
y = -(p.lastTickPosY + (p.posY - p.lastTickPosY) * partialTick);
z = -(p.lastTickPosZ + (p.posZ - p.lastTickPosZ) * partialTick);
}
prepare(RenderType.WORLD_LAST, x, y, z);
render();
clean();
}
// #end IRenderWorldLast
// #region prepare()
/**
* Prepares the {@link Tessellator} and the GL states for the <b>renderType</b>. <b>data</b> is only used for TESR and IRWL.<br>
* TESR and IRWL rendering are surrounded by glPushAttrib(GL_LIGHTING_BIT) and block texture sheet is bound.
*
* @param renderType the render type
* @param data the data
*/
public void prepare(RenderType renderType, double... data)
{
_initialize();
this.renderType = renderType;
if (renderType == RenderType.BLOCK)
{
wr.setVertexFormat(DefaultVertexFormats.BLOCK);
}
else if (renderType == RenderType.ITEM)
{
startDrawing();
}
else if (renderType == RenderType.TILE_ENTITY)
{
GlStateManager.pushAttrib();
GlStateManager.pushMatrix();
GlStateManager.disableLighting();
GlStateManager.translate(data[0], data[1], data[2]);
bindTexture(TextureMap.locationBlocksTexture);
startDrawing();
}
else if (renderType == RenderType.WORLD_LAST)
{
GlStateManager.pushAttrib();
GlStateManager.pushMatrix();
GlStateManager.translate(data[0], data[1], data[2]);
bindTexture(TextureMap.locationBlocksTexture);
startDrawing();
}
}
/**
* Cleans the current renderer state.
*/
public void clean()
{
if (renderType == RenderType.ITEM)
{
draw();
// GlStateManager.enableLighting();
// GlStateManager.popMatrix();
// GlStateManager.popAttrib();
}
else if (renderType == RenderType.TILE_ENTITY)
{
draw();
GlStateManager.enableLighting();
GlStateManager.popMatrix();
GlStateManager.popAttrib();
}
else if (renderType == RenderType.WORLD_LAST)
{
draw();
GlStateManager.popMatrix();
GlStateManager.popAttrib();
}
reset();
}
/**
* Tells the {@link Tessellator} to start drawing GL_QUADS.
*/
public void startDrawing()
{
startDrawing(GL11.GL_QUADS);
}
/**
* Tells the {@link Tessellator} to start drawing <b>drawMode</b>.
*
* @param drawMode the draw mode
*/
public void startDrawing(int drawMode)
{
if (isDrawing())
draw();
wr.startDrawing(drawMode);
wr.setVertexFormat(vertexFormat);
this.drawMode = drawMode;
}
/**
* Checks if the {@link Tessellator} is currently drawing.
*
* @return true, if is drawing
*/
public boolean isDrawing()
{
if (isDrawingField == null)
isDrawingField = AsmUtils.changeFieldAccess(WorldRenderer.class, "isDrawing", "field_179010_r");
try
{
if (wr == null)
throw new NullPointerException("[MalisisRenderer] WorldRenderer not set for " + renderType);
return isDrawingField.getBoolean(wr);
}
catch (IllegalArgumentException | IllegalAccessException e)
{
MalisisCore.log.error("[MalisisRenderer] Failed to get Tessellator.isDrawing value", e);
return false;
}
}
/**
* Triggers a draw and restart drawing with current {@link MalisisRenderer#drawMode}.
*/
public void next()
{
next(drawMode);
}
/**
* Triggers a draw and restart drawing with <b>drawMode</b>.
*
* @param drawMode the draw mode
*/
public void next(int drawMode)
{
draw();
startDrawing(drawMode);
}
/**
* Triggers a draw.
*/
public void draw()
{
if (isDrawing())
Tessellator.getInstance().draw();
}
/**
* Enables the blending for the rendering. Ineffective for BLOCK renderType.
*/
public void enableBlending()
{
if (renderType == RenderType.BLOCK)
return;
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
GlStateManager.alphaFunc(GL11.GL_GREATER, 0.0F);
GlStateManager.shadeModel(GL11.GL_SMOOTH);
GlStateManager.enableColorMaterial();
}
/**
* Disables blending for the rendering. Ineffective for BLOCK renderType.
*/
public void disableBlending()
{
if (renderType == RenderType.BLOCK)
return;
GlStateManager.disableBlend();
GlStateManager.disableColorMaterial();
}
/**
* Enables textures
*/
public void enableTextures()
{
GL11.glEnable(GL11.GL_TEXTURE_2D);
}
/**
* Disables textures.
*/
public void disableTextures()
{
GL11.glDisable(GL11.GL_TEXTURE_2D);
}
@Override
protected void bindTexture(ResourceLocation resourceLocaltion)
{
Minecraft.getMinecraft().getTextureManager().bindTexture(resourceLocaltion);
}
// #end prepare()
/**
* _initialize.
*/
protected final void _initialize()
{
if (initialized)
return;
initialize();
initialized = true;
}
/**
* Initializes this {@link MalisisRenderer}. Does nothing by default.<br>
* Called the first time a rendering is done and should be overridden if some setup is needed for the rendering (building shape and
* parameters).
*/
protected void initialize()
{}
/**
* Renders the blocks using the default Minecraft rendering system.
*
* @param renderer the renderer
*/
public void renderStandard()
{
Minecraft.getMinecraft().getBlockRendererDispatcher().renderBlock(blockState, pos, world, wr);
}
/**
* Main rendering method. Draws simple cube by default.<br>
* Should be overridden to handle the rendering.
*/
public void render()
{
drawShape(new Cube());
}
protected void drawModel(MalisisModel model, RenderParameters params)
{
for (Shape s : model)
drawShape(s, params);
}
/**
* Draws a {@link Shape} without {@link RenderParameters} (default will be used).
*
* @param shape the shape
*/
public void drawShape(Shape shape)
{
drawShape(shape, null);
}
/**
* Draws a {@link Shape} with specified {@link RenderParameters}.
*
* @param s the s
* @param params the params
*/
public void drawShape(Shape s, RenderParameters params)
{
if (s == null)
return;
s.applyMatrix();
for (Face f : s.getFaces())
drawFace(f, params);
}
/**
* Draws a {@link Face} with its own {@link RenderParameters}.
*
* @param face the face
*/
protected void drawFace(Face face)
{
drawFace(face, null);
}
/**
* Draws a {@link Face} with specified {@link RenderParameters}.
*
* @param face the f
* @param params the face params
*/
protected void drawFace(Face face, RenderParameters params)
{
if (face == null)
return;
int vertexCount = face.getVertexes().length;
if (vertexCount != 4 && renderType == RenderType.BLOCK)
{
MalisisCore.log.error("[MalisisRenderer] Attempting to render a face containing {} vertexes in BLOCK for {}. Ignored",
vertexCount, block);
return;
}
params = RenderParameters.merge(params, face.getParameters());
if (!shouldRenderFace(face, params))
return;
if (params.applyTexture.get())
applyTexture(face, params);
//use normals if available
if ((renderType == RenderType.ITEM || params.useNormals.get()) && params.direction.get() != null)
wr.setNormal(params.direction.get().getFrontOffsetX(), params.direction.get().getFrontOffsetY(), params.direction.get()
.getFrontOffsetZ());
baseBrightness = getBaseBrightness(params);
for (int i = 0; i < face.getVertexes().length; i++)
drawVertex(face.getVertexes()[i], i, params);
//we need to separate each face
if (drawMode == GL11.GL_POLYGON || drawMode == GL11.GL_LINE || drawMode == GL11.GL_LINE_STRIP || drawMode == GL11.GL_LINE_LOOP)
next();
}
/**
* Draws a single {@link Vertex}.
*
* @param vertex the vertex
* @param number the offset inside the face. (Used for AO)
*/
protected void drawVertex(Vertex vertex, int number, RenderParameters params)
{
if (vertex == null)
vertex = new Vertex(0, 0, 0);
// brightness
int brightness = calcVertexBrightness(vertex, number, params);
vertex.setBrightness(brightness);
// color
int color = calcVertexColor(vertex, number, params);
vertex.setColor(color);
// alpha
if (params != null && !params.usePerVertexAlpha.get())
vertex.setAlpha(params.alpha.get());
if (renderType == RenderType.ITEM && params != null)
vertex.setNormal(params.direction.get());
wr.addVertexData(getVertexData(vertex));
vertexDrawn = true;
}
/**
* Gets the vertex data.
*
* @param vertex the vertex
* @return the vertex data
*/
private int[] getVertexData(Vertex vertex)
{
float x = (float) vertex.getX();
float y = (float) vertex.getY();
float z = (float) vertex.getZ();
int size = vertexFormat.getNextOffset();
if (renderType == RenderType.BLOCK)
{
size = DefaultVertexFormats.BLOCK.getNextOffset();
//when drawing a block, the position to draw is relative to current chunk
BlockPos chunkPos = BlockPosUtils.chunkPosition(pos);
x += chunkPos.getX();
y += chunkPos.getY();
z += chunkPos.getZ();
}
int[] data = new int[size / 4];
data[0] = Float.floatToRawIntBits(x);
data[1] = Float.floatToRawIntBits(y);
data[2] = Float.floatToRawIntBits(z);
data[3] = vertex.getRGBA();
data[4] = Float.floatToRawIntBits((float) vertex.getU());
data[5] = Float.floatToRawIntBits((float) vertex.getV());
data[6] = vertex.getBrightness();
if (renderType != RenderType.BLOCK)
data[7] = vertex.getNormal();
return data;
}
/**
* Draws a string at the specified coordinates, with color and shadow. The string gets translated. Uses FontRenderer.drawString().
*
* @param font the font
* @param text the text
* @param x the x
* @param y the y
* @param z the z
* @param fro the fro
*/
public void drawText(MalisisFont font, String text, float x, float y, float z, FontRenderOptions fro)
{
if (font == null)
font = MalisisFont.minecraftFont;
if (fro == null)
fro = new FontRenderOptions();
font.render(this, text, x, y, z, fro);
}
/**
* Checks if a {@link Face} should be rendered. {@link RenderParameters#direction} needs to be defined for the <b>face</b>.
*
* @param face the face
* @return true, if successful
*/
protected boolean shouldRenderFace(Face face, RenderParameters params)
{
if (renderType != RenderType.BLOCK || world == null || block == null)
return true;
if (params != null && params.renderAllFaces.get())
return true;
RenderParameters p = face.getParameters();
if (p.direction.get() == null || p.renderAllFaces.get())
return true;
boolean b = block.shouldSideBeRendered(world, pos.offset(p.direction.get()), p.direction.get());
return b;
}
/**
* Applies the texture to the {@link Shape}.<br>
* Usually necessary before some shape transformations in conjunction with {@link RenderParameters#applyTexture} set to
* <code>false</code> to prevent reapplying texture when rendering.
*
* @param shape the shape
*/
public void applyTexture(Shape shape)
{
applyTexture(shape, null);
}
/**
* Applies the texture to the {@link Shape} with specified {@link RenderParameters}.<br>
* Usually necessary before some shape transformations in conjunction with {@link RenderParameters#applyTexture} set to
* <code>false</code> to prevent reapplying texture when rendering.
*
* @param shape the shape
* @param params the parameters
*/
public void applyTexture(Shape shape, RenderParameters params)
{
//shape.applyMatrix();
for (Face f : shape.getFaces())
{
RenderParameters rp = RenderParameters.merge(params, f.getParameters());
applyTexture(f, rp);
}
}
/**
* Applies the texture to the {@link Face} with specified {@link RenderParameters}.<br>
*
* @param shape the shape
* @param params the parameters
*/
public void applyTexture(Face face, RenderParameters params)
{
MalisisIcon icon = getIcon(face, params);
boolean flipU = params.flipU.get();
if (params.direction.get() == EnumFacing.NORTH || params.direction.get() == EnumFacing.EAST)
flipU = !flipU;
face.setTexture(icon, flipU, params.flipV.get(), params.interpolateUV.get());
}
/**
* Gets the {@link MalisisIcon} corresponding to the specified {@link RenderParameters}.<br>
* If {@link #block} or {@link #item} is an {@link IIconProvider} and give the right provider for the current context, gets the icon
* from that provider.
*
* @param face the face
* @param params the params
* @return the icon
*/
protected MalisisIcon getIcon(Face face, RenderParameters params)
{
IIconProvider ip = getIconProvider(params);
if (ip instanceof IItemIconProvider && itemStack != null)
return ((IItemIconProvider) ip).getIcon(itemStack);
if (ip instanceof IBlockIconProvider && block != null)
{
IBlockIconProvider iblockp = (IBlockIconProvider) ip;
if (renderType == RenderType.BLOCK)
return iblockp.getIcon(world, pos, blockState, params.direction.get());
else if (renderType == RenderType.ITEM)
return iblockp.getIcon(itemStack, params.direction.get());
}
IIconProvider iconProvider = params.iconProvider.get();
return iconProvider != null ? iconProvider.getIcon() : null;
}
/**
* Gets the {@link IIconProvider} either from parameters, the block or the item.
*
* @return the icon provider
*/
private IIconProvider getIconProvider(RenderParameters params)
{
if (params.iconProvider.get() != null)
return params.iconProvider.get();
if (item instanceof IItemMetaIconProvider && ((IItemMetaIconProvider) item).getItemIconProvider() != null)
return ((IItemMetaIconProvider) item).getItemIconProvider();
if (block instanceof IBlockMetaIconProvider && ((IBlockMetaIconProvider) block).getBlockIconProvider() != null)
return ((IBlockMetaIconProvider) block).getBlockIconProvider();
return null;
}
/**
* Calculates the ambient occlusion for a {@link Vertex} and also applies the side dependent shade.<br>
* <b>aoMatrix</b> is the list of block coordinates necessary to compute AO. If it's empty, only the global face shade is applied.<br>
* Also, <i>params.colorMultiplier</i> is applied as well.
*
* @param vertex the vertex
* @param aoMatrix the ao matrix
* @return the int
*/
protected int calcVertexColor(Vertex vertex, int number, RenderParameters params)
{
int color = 0xFFFFFF;
if (params == null)
return color;
if (params.usePerVertexColor.get()) //vertex should use their own colors
color = vertex.getColor();
if (params.colorMultiplier.get() != null) //global color multiplier is set
color = params.colorMultiplier.get();
else if (block != null) //use block color multiplier
color = world != null ? block.colorMultiplier(world, pos, 0) : block.getRenderColor(blockState);
if (drawMode == GL11.GL_LINE) //no AO for lines
return color;
if (renderType != RenderType.BLOCK && renderType != RenderType.TILE_ENTITY) //no AO for item/inventories
return color;
int[][] aoMatrix = (int[][]) params.aoMatrix.get(number);
float factor = 1;
//calculate AO
if (params.calculateAOColor.get() && aoMatrix != null && Minecraft.isAmbientOcclusionEnabled()
&& block.getLightValue(world, pos) == 0)
{
factor = getBlockAmbientOcclusion(world, pos.offset(params.direction.get()));
for (int i = 0; i < aoMatrix.length; i++)
factor += getBlockAmbientOcclusion(world, pos.add(aoMatrix[i][0], aoMatrix[i][1], aoMatrix[i][2]));
factor /= (aoMatrix.length + 1);
}
//apply face dependent shading
factor *= params.colorFactor.get();
int r = (int) ((color >> 16 & 255) * factor);
int g = (int) ((color >> 8 & 255) * factor);
int b = (int) ((color & 255) * factor);
color = r << 16 | g << 8 | b;
return color;
}
/**
* Gets the base brightness for the current {@link Face}.<br>
* If <i>params.useBlockBrightness</i> = false, <i>params.brightness</i>. Else, the brightness is determined based on
* <i>params.offset</i> and <i>getBlockBounds()</i>
*
* @return the base brightness
*/
protected int getBaseBrightness(RenderParameters params)
{
if (!params.useEnvironmentBrightness.get())
return params.brightness.get();
if (block != null)
{
if (world != null && block.getLightValue(world, pos) != 0)
return block.getLightValue(world, pos) << 4;
else if (block.getLightValue() != 0)
return block.getLightValue() << 4;
}
if (renderType == RenderType.ITEM)
return Minecraft.getMinecraft().thePlayer.getBrightnessForRender(getPartialTick());
//not in world
if (world == null || block == null)
return params.brightness.get();
//no direction, we can only use current block brightness
if (params.direction.get() == null && block != null)
return block.getMixedBrightnessForBlock(world, pos);
AxisAlignedBB bounds = getRenderBounds(params);
EnumFacing dir = params.direction.get();
BlockPos p = pos;
if (dir != null)
p = p.offset(dir);
//use the brightness of the block next to it
if (bounds != null)
{
if (dir == EnumFacing.WEST && bounds.minX > 0)
p = p.east();
else if (dir == EnumFacing.EAST && bounds.maxX < 1)
p = p.west();
else if (dir == EnumFacing.NORTH && bounds.minZ > 0)
p = p.south();
else if (dir == EnumFacing.SOUTH && bounds.maxZ < 1)
p = p.north();
else if (dir == EnumFacing.DOWN && bounds.minY > 0)
p = p.up();
else if (dir == EnumFacing.UP && bounds.maxY < 1)
p = p.down();
}
return getMixedBrightnessForBlock(world, p);
}
/**
* Calculates the ambient occlusion brightness for a {@link Vertex}. <b>aoMatrix</b> is the list of block coordinates necessary to
* compute AO. Only first 3 blocks are used.<br>
*
* @param vertex the vertex
* @param aoMatrix the ao matrix
* @return the int
*/
protected int calcVertexBrightness(Vertex vertex, int number, RenderParameters params)
{
if (params == null)
return baseBrightness;
if (params.usePerVertexBrightness.get())
return vertex.getBrightness();
if (drawMode == GL11.GL_LINE) //no AO for lines
return baseBrightness;
if (renderType != RenderType.BLOCK && renderType != RenderType.TILE_ENTITY) //not in world
return baseBrightness;
int[][] aoMatrix = (int[][]) params.aoMatrix.get(number);
if (!params.calculateBrightness.get() || aoMatrix == null) //no data
return baseBrightness;
if (!Minecraft.isAmbientOcclusionEnabled() || block.getLightValue(world, pos) != 0) // emit light
return baseBrightness;
int[] b = new int[Math.max(3, aoMatrix.length)];
for (int i = 0; i < b.length; i++)
b[i] += getMixedBrightnessForBlock(world, pos.add(aoMatrix[i][0], aoMatrix[i][1], aoMatrix[i][2]));
int brightness = getAoBrightness(b[0], b[1], b[2], baseBrightness);
return brightness;
}
/**
* Does the actual brightness calculation (copied from net.minecraft.client.renderer.BlocksRenderer.java)
*
* @param b1 the b1
* @param b2 the b2
* @param b3 the b3
* @param base the base
* @return the ao brightness
*/
protected int getAoBrightness(int b1, int b2, int b3, int base)
{
if (b1 == 0)
b1 = base;
if (b2 == 0)
b2 = base;
if (b3 == 0)
b3 = base;
return b1 + b2 + b3 + base >> 2 & 16711935;
}
/**
* Gets the block ambient occlusion value. Contrary to base Minecraft code, it's the actual block at the <b>x</b>, <b>y</b> and <b>z</b>
* coordinates which is used to get the value, and not value of the block drawn. This allows to have different logic behaviors for AO
* values for a block.
*
* @param world the world
* @param x the x
* @param y the y
* @param z the z
* @return the block ambient occlusion
*/
protected float getBlockAmbientOcclusion(IBlockAccess world, BlockPos pos)
{
Block block = world.getBlockState(pos).getBlock();
if (block == null)
return 1.0F;
return block.getAmbientOcclusionLightValue();
}
/**
* Gets the mix brightness for a block (sky + block source).
*
* @param world the world
* @param x the x
* @param y the y
* @param z the z
* @return the mixed brightness for block
*/
protected int getMixedBrightnessForBlock(IBlockAccess world, BlockPos pos)
{
// return world.getLightBrightnessForSkyBlocks(x, y, z, 0);
return world.getBlockState(pos).getBlock().getMixedBrightnessForBlock(world, pos);
}
/**
* Gets the rendering bounds. If <i>params.useBlockBounds</i> = false, <i>params.renderBounds</i> is used instead of the actual block
* bounds.
*
* @return the render bounds
*/
protected AxisAlignedBB getRenderBounds(RenderParameters params)
{
if (block == null || !params.useBlockBounds.get())
return params.renderBounds.get();
if (world != null)
block.setBlockBoundsBasedOnState(world, pos);
return new AxisAlignedBB(block.getBlockBoundsMinX(), block.getBlockBoundsMinY(), block.getBlockBoundsMinZ(),
block.getBlockBoundsMaxX(), block.getBlockBoundsMaxY(), block.getBlockBoundsMaxZ());
}
private static Timer timer = null;
public static float getPartialTick()
{
if (timer == null)
{
Field f = AsmUtils.changeFieldAccess(Minecraft.class, "timer", "field_71428_T");
try
{
timer = (Timer) f.get(Minecraft.getMinecraft());
}
catch (IllegalArgumentException | IllegalAccessException e)
{
MalisisCore.log.info("[MalisisRenderer] Failed to acces Minecraft timer.");
timer = new Timer(20F);
}
}
return timer.elapsedPartialTicks;
}
/**
* Registers this {@link MalisisRenderer} to be used for rendering the specified <b>block</b>.
*
* @param block the block
*/
public void registerFor(Block block)
{
registerFor(block, getDefaultRenderInfos());
}
public void registerFor(Block block, IItemRenderInfo renderInfos)
{
MalisisRegistry.registerBlockRenderer(block, this, renderInfos);
}
/**
* Registers this {@link MalisisRenderer} to be used for rendering the specified <b>item</b>.
*
* @param item the item
*/
public void registerFor(Item item)
{
registerFor(item, getDefaultRenderInfos());
}
public void registerFor(Item item, IItemRenderInfo renderInfos)
{
MalisisRegistry.registerItemRenderer(item, this, renderInfos);
}
/**
* Registers this {@link MalisisRenderer} to be used for rendering for a specified class.<br>
* Class has to extend TileEntity.<br>
*
* @param clazz the clazz
*/
public void registerFor(Class<? extends TileEntity> clazz)
{
ClientRegistry.bindTileEntitySpecialRenderer(clazz, this);
}
/**
* Registers this {@link MalisisRenderer} to be used for {@link RenderWorldLastEvent}.
*/
public void registerForRenderWorldLast()
{
MalisisRegistry.registerRenderWorldLast(this);
}
private IItemRenderInfo getDefaultRenderInfos()
{
return new IItemRenderInfo()
{
@Override
public boolean isGui3d()
{
return MalisisRenderer.this.isGui3d();
}
@Override
public Matrix4f getTransform(TransformType tranformType)
{
return MalisisRenderer.this.getTransform(tranformType);
}
};
}
}
| Fixed getting icon for TILE_ENTITY
Added setBillboard() endBillboard() | src/main/java/net/malisis/core/renderer/MalisisRenderer.java | Fixed getting icon for TILE_ENTITY Added setBillboard() endBillboard() | <ide><path>rc/main/java/net/malisis/core/renderer/MalisisRenderer.java
<ide> Minecraft.getMinecraft().getTextureManager().bindTexture(resourceLocaltion);
<ide> }
<ide>
<add> /**
<add> * Sets billboard mode.<br>
<add> * Contents drawn will always be facing the player.
<add> *
<add> * @param x the x
<add> * @param y the y
<add> * @param z the z
<add> */
<add> public void setBillboard(float x, float y, float z)
<add> {
<add> EntityPlayerSP player = Minecraft.getMinecraft().thePlayer;
<add> GlStateManager.pushMatrix();
<add> GlStateManager.translate(x, y, z);
<add> GlStateManager.rotate(180 - player.rotationYaw, 0, 1, 0);
<add> }
<add>
<add> /**
<add> * End billboard mode.
<add> */
<add> public void endBillboard()
<add> {
<add> GlStateManager.popMatrix();
<add> }
<add>
<ide> // #end prepare()
<ide>
<ide> /**
<ide> if (ip instanceof IBlockIconProvider && block != null)
<ide> {
<ide> IBlockIconProvider iblockp = (IBlockIconProvider) ip;
<del> if (renderType == RenderType.BLOCK)
<add> if (renderType == RenderType.BLOCK || renderType == RenderType.TILE_ENTITY)
<ide> return iblockp.getIcon(world, pos, blockState, params.direction.get());
<ide> else if (renderType == RenderType.ITEM)
<ide> return iblockp.getIcon(itemStack, params.direction.get()); |
|
Java | agpl-3.0 | 94349a9ad6f8408c3c340bfe6d7c225f85102c58 | 0 | Stanwar/agreementmaker,sabarish14/agreementmaker,Stanwar/agreementmaker,sabarish14/agreementmaker,Stanwar/agreementmaker,Stanwar/agreementmaker,sabarish14/agreementmaker,sabarish14/agreementmaker | package am.utility.referenceAlignment;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.dom4j.DocumentException;
import am.app.mappingEngine.Alignment;
import am.app.mappingEngine.Mapping;
import am.app.mappingEngine.ReferenceEvaluationData;
import am.app.mappingEngine.referenceAlignment.ReferenceAlignmentMatcher;
import am.app.mappingEngine.referenceAlignment.ReferenceAlignmentParameters;
import am.app.mappingEngine.referenceAlignment.ReferenceEvaluator;
import am.app.mappingEngine.utility.MatchingPair;
import am.app.ontology.Ontology;
import am.app.ontology.instance.Instance;
/**
* Utilities for alignments. (they need to be unit tested)
*
* See {@link ReferenceEvaluator#compare(Alignment, Alignment)} for evaluating a
* computed alignment against a reference alignment.
*
* @author <a href="http://cstroe.com">Cosmin Stroe</a>
*
*/
public class AlignmentUtilities {
public static AlignmentsComparison diff(List<MatchingPair> sourceList, List<MatchingPair> targetList){
return diff(sourceList, targetList, null, null);
}
/**
* Performs a comparison between two reference alignments. The results are stored in the AlignmentsComparison
* data structure
*/
public static AlignmentsComparison diff(List<MatchingPair> sourceList, List<MatchingPair> targetList, List<String> inSource, List<String> inTarget){
MatchingPair source;
MatchingPair target;
AlignmentsComparison comparison = new AlignmentsComparison();
boolean found = false;
HashSet<MatchingPair> foundTargets = new HashSet<MatchingPair>();
for (int i = 0; i < sourceList.size(); i++) {
source = sourceList.get(i);
found = false;
for (int j = 0; j < targetList.size(); j++) {
target = targetList.get(j);
if(source.sameSource(target) && source.sameTarget(target)){
foundTargets.add(target);
if(source.relation.equals(target.relation)){
//Right mapping
found = true;
comparison.getEqualMappingsInSource().add(source);
comparison.getEqualMappingsInTarget().add(target);
break;
}
else{
//right source and target, wrong relation
comparison.getDifferentRelationInSource().add(source);
comparison.getDifferentRelationInTarget().add(target);
}
}
}
if(found == false){
//wrong mapping
comparison.getNotInTarget().add(source);
}
if((inSource != null && !inSource.contains(source.sourceURI)) ||
inTarget != null && !inTarget.contains(source.targetURI))
comparison.getNonSolvableSource().add(source);
}
for (int i = 0; i < targetList.size(); i++) {
target = targetList.get(i);
if(!foundTargets.contains(target)){
//This mapping was not found in the source
comparison.getNotInSource().add(target);
//Checking if the lists of classes/properties contains the source and target
if((inSource != null && !inSource.contains(target.sourceURI)) ||
inTarget != null && !inTarget.contains(target.targetURI))
comparison.getNonSolvableSource().add(target);
}
}
return comparison;
}
/**
* Used in instance matching. Given a reference alignment, a source URI, and a list of candidates, it returns
* the solution to the problem of matching the source, if it is present in the candidates. This is based on
* the notion of solvability, if the solution is not present in the candidates, there's nothing you can do in
* the disambiguation phase
*
*/
public static String candidatesContainSolution(List<MatchingPair> pairs, String uri, List<Instance> candidates) {
MatchingPair pair;
for (int i = 0; i < pairs.size(); i++) {
pair = pairs.get(i);
if(pair.sourceURI.equals(uri)){
for (int j = 0; j < candidates.size(); j++) {
if(candidates.get(j).getUri().equals(pair.targetURI))
return pair.targetURI;
}
}
}
return null;
}
public static MatchingPair candidatesContainSolution(List<MatchingPair> pairs, String source, String target) {
MatchingPair pair;
for (int i = 0; i < pairs.size(); i++) {
pair = pairs.get(i);
if(pair.sourceURI.equals(source) && pair.targetURI.equals(target)){
return pair;
}
}
return null;
}
/**
* Helper function to read an alignment from a file.
* You must pass in the ontologies. If you do not have the ontologies, consider using {@link #getMatchingPairsOAEI(String)} instead.
*/
public static Alignment<Mapping> getOAEIAlignment(String fileName, Ontology sourceOntology, Ontology targetOntology) {
ReferenceAlignmentMatcher m = new ReferenceAlignmentMatcher();
ReferenceAlignmentParameters p = new ReferenceAlignmentParameters();
p.fileName = fileName;
p.format = ReferenceAlignmentMatcher.OAEI;
m.setParameters(p);
m.setSourceOntology(sourceOntology);
m.setTargetOntology(targetOntology);
try {
m.match();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return m.getAlignment();
}
/**
* Given a filename, opens the file and parses it expecting an alignment in the OAEI format
* It returns the alignments in the form of List of MatchingPairs.
*/
public static List<MatchingPair> getMatchingPairsOAEI(String filename){
ReferenceAlignmentMatcher refMatcher = new ReferenceAlignmentMatcher();
ReferenceAlignmentParameters parameters = new ReferenceAlignmentParameters();
parameters.fileName = filename;
refMatcher.setParam(parameters);
ArrayList<MatchingPair> refPairs;
try {
refPairs = refMatcher.parseStandardOAEI();
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (DocumentException e) {
e.printStackTrace();
return null;
}
return refPairs;
}
public static List<MatchingPair> getMatchingPairsTAB(String filename){
ReferenceAlignmentMatcher refMatcher = new ReferenceAlignmentMatcher();
ReferenceAlignmentParameters parameters = new ReferenceAlignmentParameters();
parameters.fileName = filename;
refMatcher.setParam(parameters);
ArrayList<MatchingPair> refPairs = null;
BufferedReader refBR = null;
try {
refBR = new BufferedReader(new FileReader(filename));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return refPairs;
}
try {
refPairs = refMatcher.parseRefFormat2(refBR);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return refPairs;
}
public static Alignment<Mapping> getAlignmentTAB(String filename) {
ReferenceAlignmentMatcher refMatcher = new ReferenceAlignmentMatcher();
ReferenceAlignmentParameters parameters = new ReferenceAlignmentParameters();
parameters.fileName = filename;
parameters.threshold = 0.01;
refMatcher.setParam(parameters);
ArrayList<MatchingPair> refPairs = null;
BufferedReader refBR = null;
try {
refBR = new BufferedReader(new FileReader(filename));
refPairs = refMatcher.parseRefFormat2(refBR);
refMatcher.match();
} catch (Exception e1) {
e1.printStackTrace();
return null;
}
return refMatcher.getAlignment();
}
public static List<MatchingPair> alignmentToMatchingPairs(
Alignment<Mapping> alignment) {
//System.out.println("Creating matching pairs from an alignment " + alignment.size());
List<MatchingPair> pairs = new ArrayList<MatchingPair>();
for (Mapping mapping : alignment) {
//System.out.println(mapping);
pairs.add(new MatchingPair(mapping.getEntity1().getLocalName(), mapping.getEntity2().getLocalName(),
mapping.getSimilarity(), mapping.getRelation()));
}
return pairs;
}
public static ReferenceEvaluationData compare(List<MatchingPair> toEvaluate, List<MatchingPair> reference){
ReferenceEvaluationData rd = new ReferenceEvaluationData();
int count = 0;
MatchingPair p1;
MatchingPair p2;
MatchingPair right = null;
boolean found;
Ontology sOnt = null;
Ontology tOnt = null;
HashSet<MatchingPair> foundTargets = new HashSet<MatchingPair>();
for (int i = 0; i < toEvaluate.size(); i++) {
found = false;
p1 = toEvaluate.get(i);
for (int j = 0; j < reference.size(); j++) {
p2 = reference.get(j);
if(p1.sourceURI.equals(p2.sourceURI)){
right = p2;
}
if(p1.sourceURI.equals(p2.sourceURI) && p1.targetURI.equals(p2.targetURI)
&& p1.relation.equals(p2.relation)){
count++;
found = true;
foundTargets.add(p2);
break;
}
}
}
//System.out.println("right mappings: "+count);
//System.out.println("prec:"+ (float)count/toEvaluate.size() + " rec: " + (float)count/reference.size());
double prec;
if(count == 0.0d) {
prec = 0.0d;
}
else prec = (double) count / (double) toEvaluate.size();
double rec;
if(reference.size() == 0.0d) {
rec = 0.0d;
}
else rec = (double) count / (double) reference.size();
//System.out.println("Precision: " + prec + ", Recall: " + rec);
// F-measure
double fm;
if(prec + rec == 0.0d) {
fm = 0.0d;
}
//else fm = (1 + ALPHA) * (prec * rec) / (ALPHA * prec + rec);
else fm = 2 * (prec * rec) / (prec + rec); // from Ontology Matching book
//System.out.print(prec + "\t" + rec + "\t");
rd.setPrecision(prec);
rd.setRecall(rec);
rd.setFmeasure(fm);
return rd;
}
public static void removeDuplicates(List<MatchingPair> pairs){
MatchingPair p1;
MatchingPair p2;
for (int i = 0; i < pairs.size(); i++) {
for (int j = i+1; j < pairs.size(); j++) {
p1 = pairs.get(i);
p2 = pairs.get(j);
if(p1.sourceURI.equals(p2.sourceURI) && p1.targetURI.equals(p2.targetURI)
&& p1.relation.equals(p2.relation)){
pairs.remove(j);
//System.out.println(p2.getTabString());
j--;
}
}
}
}
}
| AgreementMaker-OSGi/AgreementMaker-Core/src/am/utility/referenceAlignment/AlignmentUtilities.java | package am.utility.referenceAlignment;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.dom4j.DocumentException;
import am.app.mappingEngine.Alignment;
import am.app.mappingEngine.Mapping;
import am.app.mappingEngine.ReferenceEvaluationData;
import am.app.mappingEngine.referenceAlignment.ReferenceAlignmentMatcher;
import am.app.mappingEngine.referenceAlignment.ReferenceAlignmentParameters;
import am.app.mappingEngine.utility.MatchingPair;
import am.app.ontology.Ontology;
import am.app.ontology.instance.Instance;
public class AlignmentUtilities {
public static AlignmentsComparison diff(List<MatchingPair> sourceList, List<MatchingPair> targetList){
return diff(sourceList, targetList, null, null);
}
/**
* Performs a comparison between two reference alignments. The results are stored in the AlignmentsComparison
* data structure
*/
public static AlignmentsComparison diff(List<MatchingPair> sourceList, List<MatchingPair> targetList, List<String> inSource, List<String> inTarget){
MatchingPair source;
MatchingPair target;
AlignmentsComparison comparison = new AlignmentsComparison();
boolean found = false;
HashSet<MatchingPair> foundTargets = new HashSet<MatchingPair>();
for (int i = 0; i < sourceList.size(); i++) {
source = sourceList.get(i);
found = false;
for (int j = 0; j < targetList.size(); j++) {
target = targetList.get(j);
if(source.sameSource(target) && source.sameTarget(target)){
foundTargets.add(target);
if(source.relation.equals(target.relation)){
//Right mapping
found = true;
comparison.getEqualMappingsInSource().add(source);
comparison.getEqualMappingsInTarget().add(target);
break;
}
else{
//right source and target, wrong relation
comparison.getDifferentRelationInSource().add(source);
comparison.getDifferentRelationInTarget().add(target);
}
}
}
if(found == false){
//wrong mapping
comparison.getNotInTarget().add(source);
}
if((inSource != null && !inSource.contains(source.sourceURI)) ||
inTarget != null && !inTarget.contains(source.targetURI))
comparison.getNonSolvableSource().add(source);
}
for (int i = 0; i < targetList.size(); i++) {
target = targetList.get(i);
if(!foundTargets.contains(target)){
//This mapping was not found in the source
comparison.getNotInSource().add(target);
//Checking if the lists of classes/properties contains the source and target
if((inSource != null && !inSource.contains(target.sourceURI)) ||
inTarget != null && !inTarget.contains(target.targetURI))
comparison.getNonSolvableSource().add(target);
}
}
return comparison;
}
/**
* Used in instance matching. Given a reference alignment, a source URI, and a list of candidates, it returns
* the solution to the problem of matching the source, if it is present in the candidates. This is based on
* the notion of solvability, if the solution is not present in the candidates, there's nothing you can do in
* the disambiguation phase
*
*/
public static String candidatesContainSolution(List<MatchingPair> pairs, String uri, List<Instance> candidates) {
MatchingPair pair;
for (int i = 0; i < pairs.size(); i++) {
pair = pairs.get(i);
if(pair.sourceURI.equals(uri)){
for (int j = 0; j < candidates.size(); j++) {
if(candidates.get(j).getUri().equals(pair.targetURI))
return pair.targetURI;
}
}
}
return null;
}
public static MatchingPair candidatesContainSolution(List<MatchingPair> pairs, String source, String target) {
MatchingPair pair;
for (int i = 0; i < pairs.size(); i++) {
pair = pairs.get(i);
if(pair.sourceURI.equals(source) && pair.targetURI.equals(target)){
return pair;
}
}
return null;
}
/**
* Helper function to read an alignment from a file.
* You must pass in the ontologies. If you do not have the ontologies, consider using {@link #getMatchingPairsOAEI(String)} instead.
*/
public static Alignment<Mapping> getOAEIAlignment(String fileName, Ontology sourceOntology, Ontology targetOntology) {
ReferenceAlignmentMatcher m = new ReferenceAlignmentMatcher();
ReferenceAlignmentParameters p = new ReferenceAlignmentParameters();
p.fileName = fileName;
p.format = ReferenceAlignmentMatcher.OAEI;
m.setParameters(p);
m.setSourceOntology(sourceOntology);
m.setTargetOntology(targetOntology);
try {
m.match();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return m.getAlignment();
}
/**
* Given a filename, opens the file and parses it expecting an alignment in the OAEI format
* It returns the alignments in the form of List of MatchingPairs.
*/
public static List<MatchingPair> getMatchingPairsOAEI(String filename){
ReferenceAlignmentMatcher refMatcher = new ReferenceAlignmentMatcher();
ReferenceAlignmentParameters parameters = new ReferenceAlignmentParameters();
parameters.fileName = filename;
refMatcher.setParam(parameters);
ArrayList<MatchingPair> refPairs;
try {
refPairs = refMatcher.parseStandardOAEI();
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (DocumentException e) {
e.printStackTrace();
return null;
}
return refPairs;
}
public static List<MatchingPair> getMatchingPairsTAB(String filename){
ReferenceAlignmentMatcher refMatcher = new ReferenceAlignmentMatcher();
ReferenceAlignmentParameters parameters = new ReferenceAlignmentParameters();
parameters.fileName = filename;
refMatcher.setParam(parameters);
ArrayList<MatchingPair> refPairs = null;
BufferedReader refBR = null;
try {
refBR = new BufferedReader(new FileReader(filename));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return refPairs;
}
try {
refPairs = refMatcher.parseRefFormat2(refBR);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return refPairs;
}
public static Alignment<Mapping> getAlignmentTAB(String filename) {
ReferenceAlignmentMatcher refMatcher = new ReferenceAlignmentMatcher();
ReferenceAlignmentParameters parameters = new ReferenceAlignmentParameters();
parameters.fileName = filename;
parameters.threshold = 0.01;
refMatcher.setParam(parameters);
ArrayList<MatchingPair> refPairs = null;
BufferedReader refBR = null;
try {
refBR = new BufferedReader(new FileReader(filename));
refPairs = refMatcher.parseRefFormat2(refBR);
refMatcher.match();
} catch (Exception e1) {
e1.printStackTrace();
return null;
}
return refMatcher.getAlignment();
}
public static List<MatchingPair> alignmentToMatchingPairs(
Alignment<Mapping> alignment) {
//System.out.println("Creating matching pairs from an alignment " + alignment.size());
List<MatchingPair> pairs = new ArrayList<MatchingPair>();
for (Mapping mapping : alignment) {
//System.out.println(mapping);
pairs.add(new MatchingPair(mapping.getEntity1().getLocalName(), mapping.getEntity2().getLocalName(),
mapping.getSimilarity(), mapping.getRelation()));
}
return pairs;
}
public static ReferenceEvaluationData compare(List<MatchingPair> toEvaluate, List<MatchingPair> reference){
ReferenceEvaluationData rd = new ReferenceEvaluationData();
int count = 0;
MatchingPair p1;
MatchingPair p2;
MatchingPair right = null;
boolean found;
Ontology sOnt = null;
Ontology tOnt = null;
HashSet<MatchingPair> foundTargets = new HashSet<MatchingPair>();
for (int i = 0; i < toEvaluate.size(); i++) {
found = false;
p1 = toEvaluate.get(i);
for (int j = 0; j < reference.size(); j++) {
p2 = reference.get(j);
if(p1.sourceURI.equals(p2.sourceURI)){
right = p2;
}
if(p1.sourceURI.equals(p2.sourceURI) && p1.targetURI.equals(p2.targetURI)
&& p1.relation.equals(p2.relation)){
count++;
found = true;
foundTargets.add(p2);
break;
}
}
}
//System.out.println("right mappings: "+count);
//System.out.println("prec:"+ (float)count/toEvaluate.size() + " rec: " + (float)count/reference.size());
double prec;
if(count == 0.0d) {
prec = 0.0d;
}
else prec = (double) count / (double) toEvaluate.size();
double rec;
if(reference.size() == 0.0d) {
rec = 0.0d;
}
else rec = (double) count / (double) reference.size();
//System.out.println("Precision: " + prec + ", Recall: " + rec);
// F-measure
double fm;
if(prec + rec == 0.0d) {
fm = 0.0d;
}
//else fm = (1 + ALPHA) * (prec * rec) / (ALPHA * prec + rec);
else fm = 2 * (prec * rec) / (prec + rec); // from Ontology Matching book
//System.out.print(prec + "\t" + rec + "\t");
rd.setPrecision(prec);
rd.setRecall(rec);
rd.setFmeasure(fm);
return rd;
}
public static void removeDuplicates(List<MatchingPair> pairs){
MatchingPair p1;
MatchingPair p2;
for (int i = 0; i < pairs.size(); i++) {
for (int j = i+1; j < pairs.size(); j++) {
p1 = pairs.get(i);
p2 = pairs.get(j);
if(p1.sourceURI.equals(p2.sourceURI) && p1.targetURI.equals(p2.targetURI)
&& p1.relation.equals(p2.relation)){
pairs.remove(j);
//System.out.println(p2.getTabString());
j--;
}
}
}
}
}
| Added comment.
| AgreementMaker-OSGi/AgreementMaker-Core/src/am/utility/referenceAlignment/AlignmentUtilities.java | Added comment. | <ide><path>greementMaker-OSGi/AgreementMaker-Core/src/am/utility/referenceAlignment/AlignmentUtilities.java
<ide> import am.app.mappingEngine.ReferenceEvaluationData;
<ide> import am.app.mappingEngine.referenceAlignment.ReferenceAlignmentMatcher;
<ide> import am.app.mappingEngine.referenceAlignment.ReferenceAlignmentParameters;
<add>import am.app.mappingEngine.referenceAlignment.ReferenceEvaluator;
<ide> import am.app.mappingEngine.utility.MatchingPair;
<ide> import am.app.ontology.Ontology;
<ide> import am.app.ontology.instance.Instance;
<ide>
<add>/**
<add> * Utilities for alignments. (they need to be unit tested)
<add> *
<add> * See {@link ReferenceEvaluator#compare(Alignment, Alignment)} for evaluating a
<add> * computed alignment against a reference alignment.
<add> *
<add> * @author <a href="http://cstroe.com">Cosmin Stroe</a>
<add> *
<add> */
<ide> public class AlignmentUtilities {
<ide>
<ide> public static AlignmentsComparison diff(List<MatchingPair> sourceList, List<MatchingPair> targetList){ |
|
Java | bsd-2-clause | fda1204fb799c5726214d9a7a7dc7716d64af927 | 0 | bastienleonard/android-workout-stopwatch,bastienleonard/workout-stopwatch | // Copyright 2012 Bastien Léonard. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// THIS SOFTWARE IS PROVIDED BY BASTIEN LÉONARD ``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 BASTIEN LÉONARD OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
package net.alwaysdata.bastien_leonard.workout_stopwatch;
import java.lang.Runnable;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.widget.TextView;
import android.widget.Button;
public class MainActivity extends Activity {
// Delay until the next timer refresh, in milliseconds
private static final long REFRESH_DELAY = 100L;
private TextView mTime;
private Button mStart;
private Button mReset;
private TextView mSetsCounter;
private Button mResetSetsCountButton;
private boolean mRunning = false;
private long mTotalTime;
private long mLastTick;
private int mSetsCount;
private Handler mHandler;
private final Runnable mUpdater = new Runnable() {
public void run() {
if (mRunning) {
long newTick = SystemClock.elapsedRealtime();
long elapsed = newTick - mLastTick;
mTotalTime += elapsed;
refreshTimer();
mLastTick = newTick;
mHandler.postDelayed(this, REFRESH_DELAY);
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mHandler = new Handler();
mTime = (TextView) findViewById(R.id.time);
mStart = (Button) findViewById(R.id.start);
mReset = (Button) findViewById(R.id.reset);
mSetsCounter = (TextView) findViewById(R.id.sets_counter);
mResetSetsCountButton = (Button) findViewById(
R.id.reset_sets_count_button);
if (savedInstanceState != null) {
mRunning = savedInstanceState.getBoolean("mRunning");
mTotalTime = savedInstanceState.getLong("mTotalTime");
mLastTick = savedInstanceState.getLong("mLastTick");
mSetsCount = savedInstanceState.getInt("mSetsCount");
}
refreshTimer();
refreshSetsCount();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("mRunning", mRunning);
outState.putLong("mTotalTime", mTotalTime);
outState.putInt("mSetsCount", mSetsCount);
outState.putLong("mLastTick", mLastTick);
}
@Override
public void onStart() {
super.onStart();
if (mRunning) {
mHandler.post(mUpdater);
}
}
@Override
public void onStop() {
super.onStop();
mHandler.removeCallbacks(mUpdater);
}
public void start(View view) {
if (!mRunning) {
mRunning = true;
++mSetsCount;
refreshSetsCount();
mReset.setEnabled(false);
mLastTick = SystemClock.elapsedRealtime();
mStart.setText(getString(R.string.pause));
mHandler.post(mUpdater);
} else {
mRunning = false;
mReset.setEnabled(true);
mStart.setText(getString(R.string.start));
}
}
public void reset(View view) {
if (!mRunning) {
mResetSetsCountButton.setEnabled(true);
mTotalTime = 0;
refreshTimer();
mReset.setEnabled(false);
}
}
public void resetSetsCount(View view) {
mSetsCount = 0;
mResetSetsCountButton.setEnabled(false);
refreshSetsCount();
}
private void refreshTimer() {
long ticks = mTotalTime / 1000;
long minutes = ticks / 60;
long seconds = ticks % 60;
long fraction = (mTotalTime % 1000) / 100;
mTime.setText(String.format(getString(R.string.time_format),
minutes, seconds, fraction));
}
private void refreshSetsCount() {
mSetsCounter.setText(
String.format(getString(R.string.sets_count_format),
mSetsCount));
}
}
| app/src/main/java/net/alwaysdata/bastien_leonard/workout_stopwatch/MainActivity.java | // Copyright 2012 Bastien Léonard. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// THIS SOFTWARE IS PROVIDED BY BASTIEN LÉONARD ``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 BASTIEN LÉONARD OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
package net.alwaysdata.bastien_leonard.workout_stopwatch;
import java.lang.Runnable;
import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.TextView;
import android.widget.Button;
public class MainActivity extends Activity {
// Delay until the next timer refresh, in milliseconds
private static final long REFRESH_DELAY = 100L;
private TextView mTime;
private Button mStart;
private Button mReset;
private TextView mSetsCounter;
private Button mResetSetsCountButton;
private boolean mRunning = false;
private long mTotalTime;
private long mLastTick;
private int mSetsCount;
private final Runnable updater = new Runnable() {
public void run() {
if (mRunning) {
long newTick = SystemClock.elapsedRealtime();
long elapsed = newTick - mLastTick;
mTotalTime += elapsed;
refreshTimer();
mLastTick = newTick;
mTime.postDelayed(this, REFRESH_DELAY);
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTime = (TextView) findViewById(R.id.time);
mStart = (Button) findViewById(R.id.start);
mReset = (Button) findViewById(R.id.reset);
mSetsCounter = (TextView) findViewById(R.id.sets_counter);
mResetSetsCountButton = (Button) findViewById(
R.id.reset_sets_count_button);
if (savedInstanceState != null) {
mRunning = savedInstanceState.getBoolean("mRunning");
mTotalTime = savedInstanceState.getLong("mTotalTime");
mLastTick = savedInstanceState.getLong("mLastTick");
mSetsCount = savedInstanceState.getInt("mSetsCount");
if (mRunning) {
mTime.post(updater);
}
}
refreshTimer();
refreshSetsCount();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("mRunning", mRunning);
outState.putLong("mTotalTime", mTotalTime);
outState.putInt("mSetsCount", mSetsCount);
outState.putLong("mLastTick", mLastTick);
}
public void start(View view) {
if (!mRunning) {
mRunning = true;
++mSetsCount;
refreshSetsCount();
mReset.setEnabled(false);
mLastTick = SystemClock.elapsedRealtime();
mStart.setText(getString(R.string.pause));
mTime.post(updater);
} else {
mRunning = false;
mReset.setEnabled(true);
mStart.setText(getString(R.string.start));
}
}
public void reset(View view) {
if (!mRunning) {
mResetSetsCountButton.setEnabled(true);
mTotalTime = 0;
refreshTimer();
mReset.setEnabled(false);
}
}
public void resetSetsCount(View view) {
mSetsCount = 0;
mResetSetsCountButton.setEnabled(false);
refreshSetsCount();
}
private void refreshTimer() {
long ticks = mTotalTime / 1000;
long minutes = ticks / 60;
long seconds = ticks % 60;
long fraction = (mTotalTime % 1000) / 100;
mTime.setText(String.format(getString(R.string.time_format),
minutes, seconds, fraction));
}
private void refreshSetsCount() {
mSetsCounter.setText(
String.format(getString(R.string.sets_count_format),
mSetsCount));
}
}
| Don't refresh the current time when the app isn't on screen
| app/src/main/java/net/alwaysdata/bastien_leonard/workout_stopwatch/MainActivity.java | Don't refresh the current time when the app isn't on screen | <ide><path>pp/src/main/java/net/alwaysdata/bastien_leonard/workout_stopwatch/MainActivity.java
<ide>
<ide> import android.app.Activity;
<ide> import android.os.Bundle;
<add>import android.os.Handler;
<ide> import android.os.SystemClock;
<ide> import android.view.View;
<ide> import android.widget.TextView;
<ide> private long mTotalTime;
<ide> private long mLastTick;
<ide> private int mSetsCount;
<add> private Handler mHandler;
<ide>
<del> private final Runnable updater = new Runnable() {
<add> private final Runnable mUpdater = new Runnable() {
<ide> public void run() {
<ide> if (mRunning) {
<ide> long newTick = SystemClock.elapsedRealtime();
<ide> mTotalTime += elapsed;
<ide> refreshTimer();
<ide> mLastTick = newTick;
<del> mTime.postDelayed(this, REFRESH_DELAY);
<add> mHandler.postDelayed(this, REFRESH_DELAY);
<ide> }
<ide> }
<ide> };
<ide> public void onCreate(Bundle savedInstanceState) {
<ide> super.onCreate(savedInstanceState);
<ide> setContentView(R.layout.main);
<add> mHandler = new Handler();
<ide> mTime = (TextView) findViewById(R.id.time);
<ide> mStart = (Button) findViewById(R.id.start);
<ide> mReset = (Button) findViewById(R.id.reset);
<ide> mTotalTime = savedInstanceState.getLong("mTotalTime");
<ide> mLastTick = savedInstanceState.getLong("mLastTick");
<ide> mSetsCount = savedInstanceState.getInt("mSetsCount");
<del>
<del> if (mRunning) {
<del> mTime.post(updater);
<del> }
<ide> }
<ide>
<ide> refreshTimer();
<ide> outState.putLong("mLastTick", mLastTick);
<ide> }
<ide>
<add> @Override
<add> public void onStart() {
<add> super.onStart();
<add>
<add> if (mRunning) {
<add> mHandler.post(mUpdater);
<add> }
<add> }
<add>
<add> @Override
<add> public void onStop() {
<add> super.onStop();
<add> mHandler.removeCallbacks(mUpdater);
<add> }
<add>
<ide> public void start(View view) {
<ide> if (!mRunning) {
<ide> mRunning = true;
<ide> mReset.setEnabled(false);
<ide> mLastTick = SystemClock.elapsedRealtime();
<ide> mStart.setText(getString(R.string.pause));
<del> mTime.post(updater);
<add> mHandler.post(mUpdater);
<ide> } else {
<ide> mRunning = false;
<ide> mReset.setEnabled(true); |
|
Java | mit | d5ea8c4451cb9f768ae91622c43e02cdf75af5b8 | 0 | dbisUnibas/cineast,vitrivr/cineast,silvanheller/cineast,vitrivr/cineast | package org.vitrivr.cineast.core.features.exporter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.vitrivr.cineast.core.config.Config;
import org.vitrivr.cineast.core.data.Pair;
import org.vitrivr.cineast.core.data.segments.SegmentContainer;
import org.vitrivr.cineast.core.db.PersistencyWriterSupplier;
import org.vitrivr.cineast.core.features.extractor.Extractor;
import org.vitrivr.cineast.core.setup.EntityCreator;
import org.vitrivr.cineast.core.util.LogHelper;
import org.vitrivr.cineast.core.util.audio.HPCP;
import org.vitrivr.cineast.core.util.dsp.fft.FFTUtil;
import org.vitrivr.cineast.core.util.dsp.visualization.AudioSignalVisualizer;
import org.vitrivr.cineast.core.util.dsp.fft.STFT;
import org.vitrivr.cineast.core.util.dsp.fft.windows.HanningWindow;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.function.Supplier;
/**
* @author rgasser
* @version 1.0
* @created 21.02.17
*/
public class ChromagramExporter implements Extractor {
private static final Logger LOGGER = LogManager.getLogger();
/** Property names that can be used in the configuration hash map. */
private static final String PROPERTY_NAME_DESTINATION = "destination";
private static final String PROPERTY_NAME_WIDTH = "width";
private static final String PROPERTY_NAME_HEIGHT = "height";
/** Destination path; can be set in the ChromagramExporter properties. */
private Path destination = Paths.get(Config.sharedConfig().getExtractor().getOutputLocation().toString());
/** Width of the resulting chromagram image in pixels. */
private int width = 800;
/** Height of the resulting chromagram image in pixels. */
private int height = 600;
/**
* Default constructor. The ChromagramExporter can be configured via named properties
* in the provided HashMap. Supported parameters:
*
* <ol>
* <li>destination: Path where images should be stored.</li>
* <li>width: Width of the image in pixels.</li>
* <li>height: Height of the image in pixels.</li>
* </ol>
*
* @param properties HashMap containing named properties
*/
public ChromagramExporter(HashMap<String, String> properties) {
if (properties.containsKey(PROPERTY_NAME_DESTINATION)) {
this.destination = Paths.get(properties.get(PROPERTY_NAME_DESTINATION));
}
if (properties.containsKey(PROPERTY_NAME_WIDTH)) {
this.width = Integer.parseInt(properties.get(PROPERTY_NAME_WIDTH));
}
if (properties.containsKey(PROPERTY_NAME_HEIGHT)) {
this.height = Integer.parseInt(properties.get(PROPERTY_NAME_HEIGHT));
}
}
@Override
public void processShot(SegmentContainer shot) {
/* IF shot has no samples, this step is skipped. */
if (shot.getNumberOfSamples() == 0) return;
/* Prepare STFT and HPCP for the segment. */
final Path directory = this.destination.resolve(shot.getSuperId());
final Pair<Integer, Integer> parameters = FFTUtil.parametersForDuration(shot.getSamplingrate(), 0.1f);
final STFT stft = shot.getSTFT(parameters.first, (parameters.first-2*parameters.second)/2, parameters.second, new HanningWindow());
final HPCP hpcp = new HPCP();
hpcp.addContribution(stft);
/* Visualize chromagram and write it to disc. */
try {
BufferedImage image = AudioSignalVisualizer.visualizeChromagram(hpcp, this.width, this.height);
if (image != null) {
Files.createDirectories(directory);
ImageIO.write(image, "JPEG", directory.resolve(shot.getId() + ".jpg").toFile());
} else {
LOGGER.warn("Chromagram could not be visualized!");
}
} catch (IOException exception) {
LOGGER.error("A serious error occurred while writing the chromagram image! ({})", LogHelper.getStackTrace(exception));
}
}
@Override
public void init(PersistencyWriterSupplier phandlerSupply) { /* Noting to init. */}
@Override
public void finish() { /* Nothing to finish. */}
@Override
public void initalizePersistentLayer(Supplier<EntityCreator> supply) {/* Nothing to initialize. */}
@Override
public void dropPersistentLayer(Supplier<EntityCreator> supply) {/* Nothing to drop. */}
}
| src/org/vitrivr/cineast/core/features/exporter/ChromagramExporter.java | package org.vitrivr.cineast.core.features.exporter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.vitrivr.cineast.core.config.Config;
import org.vitrivr.cineast.core.data.segments.SegmentContainer;
import org.vitrivr.cineast.core.db.PersistencyWriterSupplier;
import org.vitrivr.cineast.core.features.extractor.Extractor;
import org.vitrivr.cineast.core.setup.EntityCreator;
import org.vitrivr.cineast.core.util.LogHelper;
import org.vitrivr.cineast.core.util.audio.HPCP;
import org.vitrivr.cineast.core.util.dsp.visualization.AudioSignalVisualizer;
import org.vitrivr.cineast.core.util.dsp.fft.STFT;
import org.vitrivr.cineast.core.util.dsp.fft.windows.HanningWindow;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.function.Supplier;
/**
* @author rgasser
* @version 1.0
* @created 21.02.17
*/
public class ChromagramExporter implements Extractor {
private static final Logger LOGGER = LogManager.getLogger();
/** Property names that can be used in the configuration hash map. */
private static final String PROPERTY_NAME_DESTINATION = "destination";
private static final String PROPERTY_NAME_WIDTH = "width";
private static final String PROPERTY_NAME_HEIGHT = "height";
/** Destination path; can be set in the ChromagramExporter properties. */
private Path destination = Paths.get(Config.sharedConfig().getExtractor().getOutputLocation().toString());
/** Width of the resulting chromagram image in pixels. */
private int width = 800;
/** Height of the resulting chromagram image in pixels. */
private int height = 600;
/**
* Default constructor. The ChromagramExporter can be configured via named properties
* in the provided HashMap. Supported parameters:
*
* <ol>
* <li>destination: Path where images should be stored.</li>
* <li>width: Width of the image in pixels.</li>
* <li>height: Height of the image in pixels.</li>
* </ol>
*
* @param properties HashMap containing named properties
*/
public ChromagramExporter(HashMap<String, String> properties) {
if (properties.containsKey(PROPERTY_NAME_DESTINATION)) {
this.destination = Paths.get(properties.get(PROPERTY_NAME_DESTINATION));
}
if (properties.containsKey(PROPERTY_NAME_WIDTH)) {
this.width = Integer.parseInt(properties.get(PROPERTY_NAME_WIDTH));
}
if (properties.containsKey(PROPERTY_NAME_HEIGHT)) {
this.height = Integer.parseInt(properties.get(PROPERTY_NAME_HEIGHT));
}
}
@Override
public void processShot(SegmentContainer shot) {
/* IF shot has no samples, this step is skipped. */
if (shot.getNumberOfSamples() == 0) return;
/* Prepare STFT and HPCP for the segment. */
final Path directory = this.destination.resolve(shot.getSuperId());
final STFT stft = shot.getSTFT(2048, 512, new HanningWindow());
final HPCP hpcp = new HPCP();
hpcp.addContribution(stft);
/* Visualize chromagram and write it to disc. */
try {
BufferedImage image = AudioSignalVisualizer.visualizeChromagram(hpcp, this.width, this.height);
if (image != null) {
Files.createDirectories(directory);
ImageIO.write(image, "JPEG", directory.resolve(shot.getId() + ".jpg").toFile());
} else {
LOGGER.warn("Chromagram could not be visualized!");
}
} catch (IOException exception) {
LOGGER.error("A serious error occurred while writing the chromagram image! ({})", LogHelper.getStackTrace(exception));
}
}
@Override
public void init(PersistencyWriterSupplier phandlerSupply) { /* Noting to init. */}
@Override
public void finish() { /* Nothing to finish. */}
@Override
public void initalizePersistentLayer(Supplier<EntityCreator> supply) {/* Nothing to initialize. */}
@Override
public void dropPersistentLayer(Supplier<EntityCreator> supply) {/* Nothing to drop. */}
}
| CHANGED: The ChromagramExporter now also uses the FFTUtil.parametersForDuration() method.
| src/org/vitrivr/cineast/core/features/exporter/ChromagramExporter.java | CHANGED: The ChromagramExporter now also uses the FFTUtil.parametersForDuration() method. | <ide><path>rc/org/vitrivr/cineast/core/features/exporter/ChromagramExporter.java
<ide> import org.apache.logging.log4j.LogManager;
<ide> import org.apache.logging.log4j.Logger;
<ide> import org.vitrivr.cineast.core.config.Config;
<add>import org.vitrivr.cineast.core.data.Pair;
<ide> import org.vitrivr.cineast.core.data.segments.SegmentContainer;
<ide> import org.vitrivr.cineast.core.db.PersistencyWriterSupplier;
<ide> import org.vitrivr.cineast.core.features.extractor.Extractor;
<ide> import org.vitrivr.cineast.core.setup.EntityCreator;
<ide> import org.vitrivr.cineast.core.util.LogHelper;
<ide> import org.vitrivr.cineast.core.util.audio.HPCP;
<add>import org.vitrivr.cineast.core.util.dsp.fft.FFTUtil;
<ide> import org.vitrivr.cineast.core.util.dsp.visualization.AudioSignalVisualizer;
<ide> import org.vitrivr.cineast.core.util.dsp.fft.STFT;
<ide> import org.vitrivr.cineast.core.util.dsp.fft.windows.HanningWindow;
<ide>
<ide> /* Prepare STFT and HPCP for the segment. */
<ide> final Path directory = this.destination.resolve(shot.getSuperId());
<del> final STFT stft = shot.getSTFT(2048, 512, new HanningWindow());
<add> final Pair<Integer, Integer> parameters = FFTUtil.parametersForDuration(shot.getSamplingrate(), 0.1f);
<add> final STFT stft = shot.getSTFT(parameters.first, (parameters.first-2*parameters.second)/2, parameters.second, new HanningWindow());
<ide> final HPCP hpcp = new HPCP();
<ide> hpcp.addContribution(stft);
<ide> |
|
Java | mit | d049a22fe848924576034b0500e9c4b5b5265e42 | 0 | berryma4/diirt,diirt/diirt,richardfearn/diirt,diirt/diirt,richardfearn/diirt,berryma4/diirt,richardfearn/diirt,ControlSystemStudio/diirt,diirt/diirt,diirt/diirt,ControlSystemStudio/diirt,berryma4/diirt,berryma4/diirt,ControlSystemStudio/diirt,ControlSystemStudio/diirt | /**
* Copyright (C) 2010-12 Brookhaven National Laboratory
* All rights reserved. Use is subject to license terms.
*/
package org.epics.pvmanager.graphene;
import org.epics.graphene.BubbleGraph2DRendererUpdate;
import org.epics.pvmanager.ReadFunction;
import org.epics.pvmanager.expression.DesiredRateExpression;
import org.epics.pvmanager.expression.DesiredRateExpressionImpl;
import org.epics.pvmanager.expression.DesiredRateExpressionList;
import static org.epics.pvmanager.graphene.ExpressionLanguage.*;
/**
* @author shroffk
*
*/
public class BubbleGraph2DExpression extends DesiredRateExpressionImpl<Graph2DResult> implements Graph2DExpression<BubbleGraph2DRendererUpdate> {
BubbleGraph2DExpression(DesiredRateExpressionList<?> childExpressions,
ReadFunction<Graph2DResult> function, String defaultName) {
super(childExpressions, function, defaultName);
}
BubbleGraph2DExpression(DesiredRateExpression<?> tableData,
DesiredRateExpression<?> xColumnName,
DesiredRateExpression<?> yColumnName,
DesiredRateExpression<?> sizeColumnName,
DesiredRateExpression<?> tooltipColumnName) {
super(ExpressionLanguage.<Object>createList(tableData, xColumnName, yColumnName, sizeColumnName, tooltipColumnName),
new BubbleGraph2DFunction(functionOf(tableData),
functionOf(xColumnName), functionOf(yColumnName), functionOf(sizeColumnName), functionOf(tooltipColumnName)),
"Bubble Graph");
}
@Override
public void update(BubbleGraph2DRendererUpdate update) {
((BubbleGraph2DFunction) getFunction()).getRendererUpdateQueue().writeValue(update);
}
@Override
public BubbleGraph2DRendererUpdate newUpdate() {
return new BubbleGraph2DRendererUpdate();
}
}
| pvmanager-graphene/src/main/java/org/epics/pvmanager/graphene/BubbleGraph2DExpression.java | /**
* Copyright (C) 2010-12 Brookhaven National Laboratory
* All rights reserved. Use is subject to license terms.
*/
package org.epics.pvmanager.graphene;
import org.epics.graphene.BubbleGraph2DRendererUpdate;
import org.epics.pvmanager.ReadFunction;
import org.epics.pvmanager.expression.DesiredRateExpression;
import org.epics.pvmanager.expression.DesiredRateExpressionImpl;
import org.epics.pvmanager.expression.DesiredRateExpressionList;
import static org.epics.pvmanager.graphene.ExpressionLanguage.*;
/**
* @author shroffk
*
*/
public class BubbleGraph2DExpression extends DesiredRateExpressionImpl<Graph2DResult> implements Graph2DExpression<BubbleGraph2DRendererUpdate> {
BubbleGraph2DExpression(DesiredRateExpressionList<?> childExpressions,
ReadFunction<Graph2DResult> function, String defaultName) {
super(childExpressions, function, defaultName);
}
BubbleGraph2DExpression(DesiredRateExpression<?> tableData,
DesiredRateExpression<?> xColumnName,
DesiredRateExpression<?> yColumnName,
DesiredRateExpression<?> sizeColumnName,
DesiredRateExpression<?> tooltipColumnName) {
super(ExpressionLanguage.<Object>createList(tableData, xColumnName, yColumnName, sizeColumnName, tooltipColumnName),
new BubbleGraph2DFunction(functionOf(tableData),
functionOf(xColumnName), functionOf(yColumnName), functionOf(sizeColumnName), functionOf(tooltipColumnName)),
"Bubble Graph");
}
@Override
public void update(BubbleGraph2DRendererUpdate update) {
if (getFunction() instanceof BubbleGraph2DRendererUpdate) {
((BubbleGraph2DFunction) getFunction()).getRendererUpdateQueue().writeValue(update);
}
}
@Override
public BubbleGraph2DRendererUpdate newUpdate() {
return new BubbleGraph2DRendererUpdate();
}
}
| graphene: fixing event forwarding
| pvmanager-graphene/src/main/java/org/epics/pvmanager/graphene/BubbleGraph2DExpression.java | graphene: fixing event forwarding | <ide><path>vmanager-graphene/src/main/java/org/epics/pvmanager/graphene/BubbleGraph2DExpression.java
<ide>
<ide> @Override
<ide> public void update(BubbleGraph2DRendererUpdate update) {
<del> if (getFunction() instanceof BubbleGraph2DRendererUpdate) {
<del> ((BubbleGraph2DFunction) getFunction()).getRendererUpdateQueue().writeValue(update);
<del> }
<add> ((BubbleGraph2DFunction) getFunction()).getRendererUpdateQueue().writeValue(update);
<ide> }
<ide>
<ide> @Override |
|
Java | mit | 418ee173861e1a2d1c71d8fb546cf8a40aef4e58 | 0 | mopsalarm/Pr0,mopsalarm/Pr0,mopsalarm/Pr0 | package com.pr0gramm.app.ui.fragments;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.ScrollView;
import com.google.common.base.CharMatcher;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Throwables;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.gson.JsonSyntaxException;
import com.pr0gramm.app.ActivityComponent;
import com.pr0gramm.app.R;
import com.pr0gramm.app.Settings;
import com.pr0gramm.app.api.pr0gramm.Api;
import com.pr0gramm.app.feed.ContentType;
import com.pr0gramm.app.feed.Feed;
import com.pr0gramm.app.feed.FeedFilter;
import com.pr0gramm.app.feed.FeedItem;
import com.pr0gramm.app.feed.FeedLoader;
import com.pr0gramm.app.feed.FeedService;
import com.pr0gramm.app.feed.FeedType;
import com.pr0gramm.app.feed.ImmutableFeedQuery;
import com.pr0gramm.app.services.BookmarkService;
import com.pr0gramm.app.services.EnhancedUserInfo;
import com.pr0gramm.app.services.FollowingService;
import com.pr0gramm.app.services.ImmutableEnhancedUserInfo;
import com.pr0gramm.app.services.InMemoryCacheService;
import com.pr0gramm.app.services.InboxService;
import com.pr0gramm.app.services.RecentSearchesServices;
import com.pr0gramm.app.services.SeenService;
import com.pr0gramm.app.services.SingleShotService;
import com.pr0gramm.app.services.Track;
import com.pr0gramm.app.services.UriHelper;
import com.pr0gramm.app.services.UserService;
import com.pr0gramm.app.services.config.Config;
import com.pr0gramm.app.services.preloading.PreloadManager;
import com.pr0gramm.app.services.preloading.PreloadService;
import com.pr0gramm.app.ui.AdService;
import com.pr0gramm.app.ui.ContentTypeDrawable;
import com.pr0gramm.app.ui.DetectTapTouchListener;
import com.pr0gramm.app.ui.DialogBuilder;
import com.pr0gramm.app.ui.FeedFilterFormatter;
import com.pr0gramm.app.ui.FeedItemViewHolder;
import com.pr0gramm.app.ui.FilterFragment;
import com.pr0gramm.app.ui.LoginActivity;
import com.pr0gramm.app.ui.LoginActivity.DoIfAuthorizedHelper;
import com.pr0gramm.app.ui.MainActionHandler;
import com.pr0gramm.app.ui.MergeRecyclerAdapter;
import com.pr0gramm.app.ui.OnOptionsItemSelected;
import com.pr0gramm.app.ui.OptionMenuHelper;
import com.pr0gramm.app.ui.PreviewInfo;
import com.pr0gramm.app.ui.RecyclerItemClickListener;
import com.pr0gramm.app.ui.SingleViewAdapter;
import com.pr0gramm.app.ui.WriteMessageActivity;
import com.pr0gramm.app.ui.back.BackAwareFragment;
import com.pr0gramm.app.ui.base.BaseFragment;
import com.pr0gramm.app.ui.dialogs.ErrorDialogFragment;
import com.pr0gramm.app.ui.dialogs.PopupPlayer;
import com.pr0gramm.app.ui.views.BusyIndicator;
import com.pr0gramm.app.ui.views.CustomSwipeRefreshLayout;
import com.pr0gramm.app.ui.views.SearchOptionsView;
import com.pr0gramm.app.ui.views.UserInfoCell;
import com.pr0gramm.app.ui.views.UserInfoFoundView;
import com.pr0gramm.app.util.AndroidUtility;
import com.pr0gramm.app.util.BackgroundScheduler;
import com.squareup.picasso.Picasso;
import com.trello.rxlifecycle.android.FragmentEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.ref.WeakReference;
import java.net.ConnectException;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import butterknife.BindView;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Actions;
import static com.google.common.base.Objects.equal;
import static com.google.common.base.Optional.absent;
import static com.google.common.base.Optional.fromNullable;
import static com.google.common.base.Optional.of;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.pr0gramm.app.R.id.empty;
import static com.pr0gramm.app.feed.ContentType.SFW;
import static com.pr0gramm.app.services.ThemeHelper.accentColor;
import static com.pr0gramm.app.ui.FeedFilterFormatter.feedTypeToString;
import static com.pr0gramm.app.ui.ScrollHideToolbarListener.ToolbarActivity;
import static com.pr0gramm.app.ui.ScrollHideToolbarListener.estimateRecyclerViewScrollY;
import static com.pr0gramm.app.util.AndroidUtility.checkMainThread;
import static com.pr0gramm.app.util.AndroidUtility.endAction;
import static com.pr0gramm.app.util.AndroidUtility.getStatusBarHeight;
import static com.pr0gramm.app.util.AndroidUtility.hideViewOnAnimationEnd;
import static com.pr0gramm.app.util.AndroidUtility.ifPresent;
import static com.pr0gramm.app.util.AndroidUtility.isNotNull;
import static java.util.Collections.emptyList;
import static rx.android.schedulers.AndroidSchedulers.mainThread;
/**
*/
public class FeedFragment extends BaseFragment implements FilterFragment, BackAwareFragment {
static final Logger logger = LoggerFactory.getLogger("FeedFragment");
private static final String ARG_FEED_FILTER = "FeedFragment.filter";
private static final String ARG_FEED_START = "FeedFragment.start.id";
private static final String ARG_SEARCH_QUERY_STATE = "FeedFragment.searchQueryState";
private static final String ARG_SIMPLE_MODE = "FeedFragment.simpleMode";
@Inject
FeedService feedService;
@Inject
Picasso picasso;
@Inject
SeenService seenService;
@Inject
Settings settings;
@Inject
BookmarkService bookmarkService;
@Inject
UserService userService;
@Inject
SingleShotService singleShotService;
@Inject
InMemoryCacheService inMemoryCacheService;
@Inject
PreloadManager preloadManager;
@Inject
InboxService inboxService;
@Inject
RecentSearchesServices recentSearchesServices;
@Inject
FollowingService followService;
@Inject
AdService adService;
@BindView(R.id.list)
RecyclerView recyclerView;
@BindView(R.id.progress)
BusyIndicator busyIndicator;
@BindView(R.id.refresh)
CustomSwipeRefreshLayout swipeRefreshLayout;
@BindView(empty)
View noResultsView;
@BindView(R.id.search_container)
ScrollView searchContainer;
@BindView(R.id.search_options)
SearchOptionsView searchView;
private final AdViewAdapter adViewAdapter = new AdViewAdapter();
private final DoIfAuthorizedHelper doIfAuthorizedHelper = LoginActivity.helper(this);
boolean userInfoCommentsOpen;
private boolean bookmarkable;
IndicatorStyle seenIndicatorStyle;
private Long autoScrollOnLoad = null;
private ItemWithComment autoOpenOnLoad = null;
FeedAdapter feedAdapter;
FeedLoader loader;
boolean scrollToolbar;
private WeakReference<Dialog> quickPeekDialog = new WeakReference<>(null);
private String activeUsername;
/**
* Initialize a new feed fragment.
*/
public FeedFragment() {
setHasOptionsMenu(true);
setRetainInstance(true);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// initialize auto opening
ItemWithComment start = getArguments().getParcelable(ARG_FEED_START);
if (start != null) {
autoScrollOnLoad = start.getItemId();
autoOpenOnLoad = start;
}
this.scrollToolbar = useToolbarTopMargin();
adService.enabledForType(Config.AdType.FEED)
.observeOn(mainThread())
.compose(bindToLifecycle())
.subscribe((show) -> {
adViewAdapter.setShowAds(show);
updateSpanSizeLookup();
});
}
@Override
protected void injectComponent(ActivityComponent activityComponent) {
activityComponent.inject(this);
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_feed, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (feedAdapter == null) {
if (busyIndicator != null)
busyIndicator.setVisibility(View.VISIBLE);
// create a new adapter if necessary
feedAdapter = newFeedAdapter();
} else {
updateNoResultsTextView();
removeBusyIndicator();
}
seenIndicatorStyle = settings.seenIndicatorStyle();
// prepare the list of items
int columnCount = getThumbnailColumns();
GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), columnCount);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(null);
setFeedAdapter(feedAdapter);
// we can still swipe up if we are not at the start of the feed.
swipeRefreshLayout.setCanSwipeUpPredicate(() -> !feedAdapter.getFeed().isAtStart());
swipeRefreshLayout.setOnRefreshListener(() -> {
Feed feed = feedAdapter.getFeed();
if (feed.isAtStart() && !loader.isLoading()) {
loader.restart(Optional.absent());
} else {
// do not refresh
swipeRefreshLayout.setRefreshing(false);
}
});
if (useToolbarTopMargin()) {
// use height of the toolbar to configure swipe refresh layout.
int abHeight = AndroidUtility.getActionBarContentOffset(getActivity());
int offset = getStatusBarHeight(getActivity());
swipeRefreshLayout.setProgressViewOffset(false, offset, (int) (offset + 1.5 * (abHeight - offset)));
}
swipeRefreshLayout.setColorSchemeResources(accentColor());
resetToolbar();
createRecyclerViewClickListener();
recyclerView.addOnScrollListener(onScrollListener);
// observe changes so we can update the mehu
followService.changes()
.compose(bindToLifecycle())
.observeOn(mainThread())
.filter(name -> name.equalsIgnoreCase(activeUsername))
.subscribe(name -> getActivity().supportInvalidateOptionsMenu());
// execute a search when we get a search term
searchView.searchQuery().compose(bindToLifecycle()).subscribe(this::performSearch);
searchView.searchCanceled().compose(bindToLifecycle()).subscribe(e -> hideSearchContainer());
searchView.setupAutoComplete(recentSearchesServices);
// restore open search
if (savedInstanceState != null && savedInstanceState.getBoolean("searchContainerVisible")) {
showSearchContainer(false);
}
// close search on click into the darkened area.
searchContainer.setOnTouchListener(
DetectTapTouchListener.withConsumer(this::hideSearchContainer));
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("searchContainerVisible", searchContainerIsVisible());
}
private Bundle initialSearchViewState() {
Bundle state = getArguments().getBundle(ARG_SEARCH_QUERY_STATE);
if (state == null) {
Optional<String> tags = getCurrentFilter().getTags();
if (tags.isPresent()) {
state = SearchOptionsView.ofQueryTerm(tags.get());
}
}
return state;
}
private void setFeedAdapter(FeedAdapter adapter) {
feedAdapter = adapter;
MergeRecyclerAdapter merged = new MergeRecyclerAdapter();
if (useToolbarTopMargin()) {
merged.addAdapter(SingleViewAdapter.of(FeedFragment::newFeedStartPaddingView));
}
merged.addAdapter(adViewAdapter);
merged.addAdapter(adapter);
recyclerView.setAdapter(merged);
updateSpanSizeLookup();
if (!isSimpleMode()) {
queryUserInfo()
.take(1)
.compose(bindToLifecycleAsync())
.subscribe(this::presentUserInfo, Actions.empty());
}
}
private boolean useToolbarTopMargin() {
return !isSimpleMode();
}
private boolean isSimpleMode() {
Bundle arguments = getArguments();
return arguments != null && !arguments.getBoolean(ARG_SIMPLE_MODE, true);
}
private void presentUserInfo(EnhancedUserInfo value) {
if (getCurrentFilter().getTags().isPresent()) {
presentUserUploadsHint(value.getInfo());
} else {
presentUserInfoCell(value);
}
}
private void presentUserInfoCell(EnhancedUserInfo info) {
UserCommentsAdapter messages = new UserCommentsAdapter(getActivity());
List<Api.UserComments.UserComment> comments = info.getComments();
if (userInfoCommentsOpen) {
messages.setComments(info.getInfo().getUser(), comments);
}
UserInfoCell view = new UserInfoCell(getActivity(), info.getInfo(), doIfAuthorizedHelper);
view.setUserActionListener(new UserInfoCell.UserActionListener() {
@Override
public void onWriteMessageClicked(int userId, String name) {
startActivity(WriteMessageActivity.intent(getActivity(), userId, name));
}
@Override
public void onUserFavoritesClicked(String name) {
FeedFilter filter = getCurrentFilter().basic().withLikes(name);
if (!filter.equals(getCurrentFilter())) {
((MainActionHandler) getActivity()).onFeedFilterSelected(filter);
}
showUserInfoComments(emptyList());
}
@Override
public void onShowUploadsClicked(int id, String name) {
FeedFilter filter = getCurrentFilter().basic().withFeedType(FeedType.NEW).withUser(name);
if (!filter.equals(getCurrentFilter())) {
((MainActionHandler) getActivity()).onFeedFilterSelected(filter);
}
showUserInfoComments(emptyList());
}
@Override
public void onShowCommentsClicked() {
showUserInfoComments(messages.getItemCount() == 0 ? comments : emptyList());
}
private void showUserInfoComments(List<Api.UserComments.UserComment> comments) {
userInfoCommentsOpen = comments.size() > 0;
messages.setComments(info.getInfo().getUser(), comments);
updateSpanSizeLookup();
}
});
view.setWriteMessageEnabled(!isSelfInfo(info.getInfo()));
view.setShowCommentsEnabled(!comments.isEmpty());
appendUserInfoAdapters(
SingleViewAdapter.ofView(view),
messages,
SingleViewAdapter.ofLayout(R.layout.user_info_footer));
// we are showing a user.
activeUsername = info.getInfo().getUser().getName();
getActivity().supportInvalidateOptionsMenu();
}
private void presentUserUploadsHint(Api.Info info) {
if (isSelfInfo(info))
return;
UserInfoFoundView view = new UserInfoFoundView(getActivity(), info);
view.setUploadsClickedListener((userId, name) -> {
FeedFilter newFilter = getCurrentFilter().basic()
.withFeedType(FeedType.NEW).withUser(name);
((MainActionHandler) getActivity()).onFeedFilterSelected(newFilter);
});
appendUserInfoAdapters(SingleViewAdapter.ofView(view));
}
private void appendUserInfoAdapters(RecyclerView.Adapter... adapters) {
if (adapters.length == 0) {
return;
}
MergeRecyclerAdapter mainAdapter = getMainAdapter().orNull();
if (mainAdapter != null) {
int offset = 0;
ImmutableList<? extends RecyclerView.Adapter<?>> subAdapters = mainAdapter.getAdapters();
for (int idx = 0; idx < subAdapters.size(); idx++) {
offset = idx;
RecyclerView.Adapter<?> subAdapter = subAdapters.get(idx);
if (subAdapter instanceof FeedAdapter || subAdapter instanceof AdViewAdapter) {
break;
}
}
for (int idx = 0; idx < adapters.length; idx++) {
mainAdapter.addAdapter(offset + idx, adapters[idx]);
}
updateSpanSizeLookup();
}
}
private Observable<EnhancedUserInfo> queryUserInfo() {
FeedFilter filter = getFilterArgument();
String queryString = filter.getUsername().or(filter.getTags()).or(filter.getLikes()).orNull();
if (queryString != null && queryString.matches("[A-Za-z0-9]+")) {
EnumSet<ContentType> contentTypes = getSelectedContentType();
Optional<EnhancedUserInfo> cached = inMemoryCacheService.getUserInfo(contentTypes, queryString);
if (cached.isPresent()) {
return Observable.just(cached.get());
}
Observable<Api.Info> first = userService
.info(queryString, getSelectedContentType())
.doOnNext(info -> followService.markAsFollowing(info.getUser().getName(), info.following()))
.onErrorResumeNext(Observable.empty());
Observable<List<Api.UserComments.UserComment>> third = inboxService
.getUserComments(queryString, contentTypes)
.map(Api.UserComments::getComments)
.onErrorResumeNext(Observable.just(emptyList()));
return Observable.zip(first, third, ImmutableEnhancedUserInfo::of)
.ofType(EnhancedUserInfo.class)
.doOnNext(info -> inMemoryCacheService.cacheUserInfo(contentTypes, info));
} else {
return Observable.empty();
}
}
void updateSpanSizeLookup() {
MergeRecyclerAdapter mainAdapter = getMainAdapter().orNull();
GridLayoutManager layoutManager = getRecyclerViewLayoutManager().orNull();
if (mainAdapter != null && layoutManager != null) {
int itemCount = 0;
ImmutableList<? extends RecyclerView.Adapter<?>> adapters = mainAdapter.getAdapters();
for (RecyclerView.Adapter<?> adapter : adapters) {
if (adapter instanceof FeedAdapter)
break;
itemCount += adapter.getItemCount();
}
// skip items!
int columnCount = layoutManager.getSpanCount();
layoutManager.setSpanSizeLookup(new NMatchParentSpanSizeLookup(itemCount, columnCount));
}
}
private static View newFeedStartPaddingView(Context context) {
int height = AndroidUtility.getActionBarContentOffset(context);
View view = new View(context);
view.setLayoutParams(new ViewGroup.LayoutParams(1, height));
return view;
}
private Optional<MergeRecyclerAdapter> getMainAdapter() {
if (recyclerView != null) {
RecyclerView.Adapter adapter = recyclerView.getAdapter();
return Optional.fromNullable((MergeRecyclerAdapter) adapter);
}
return Optional.absent();
}
@Override
public void onDestroyView() {
if (recyclerView != null) {
recyclerView.removeOnScrollListener(onScrollListener);
}
super.onDestroyView();
}
private void removeBusyIndicator() {
if (busyIndicator != null) {
ViewParent parent = busyIndicator.getParent();
((ViewGroup) parent).removeView(busyIndicator);
busyIndicator = null;
}
}
private void resetToolbar() {
if (getActivity() instanceof ToolbarActivity) {
ToolbarActivity activity = (ToolbarActivity) getActivity();
activity.getScrollHideToolbarListener().reset();
}
}
private void hideToolbar() {
if (getActivity() instanceof ToolbarActivity) {
ToolbarActivity activity = (ToolbarActivity) getActivity();
activity.getScrollHideToolbarListener().hide();
}
}
private void onBookmarkableStateChanged(boolean bookmarkable) {
this.bookmarkable = bookmarkable;
getActivity().supportInvalidateOptionsMenu();
}
private FeedAdapter newFeedAdapter() {
logger.info("Restore adapter now");
FeedFilter feedFilter = getFilterArgument();
Long around = null;
if (autoOpenOnLoad != null) {
around = autoOpenOnLoad.getItemId();
}
return newFeedAdapter(feedFilter, around);
}
private FeedAdapter newFeedAdapter(FeedFilter feedFilter, @Nullable Long around) {
Feed feed = new Feed(feedFilter, getSelectedContentType());
loader = new FeedLoader(new FeedLoader.Binder() {
@Override
public <T> Observable.Transformer<T, T> bind() {
return observable -> observable
.compose(bindUntilEventAsync(FragmentEvent.DESTROY_VIEW))
.doAfterTerminate(FeedFragment.this::onFeedLoadFinished);
}
@Override
public void onError(Throwable error) {
checkMainThread();
onFeedError(error);
}
}, feedService, feed);
// start loading now
loader.restart(fromNullable(around));
boolean usersFavorites = feed.getFeedFilter().getLikes()
.transform(name -> name.equalsIgnoreCase(userService.getName().orNull()))
.or(false);
return new FeedAdapter(this, feed, usersFavorites);
}
private FeedFilter getFilterArgument() {
return getArguments().getParcelable(ARG_FEED_FILTER);
}
private EnumSet<ContentType> getSelectedContentType() {
if (userService == null || !userService.isAuthorized())
return EnumSet.of(SFW);
return settings.getContentType();
}
@Override
public void onResume() {
super.onResume();
Track.screen("Feed");
// check if we should show the pin button or not.
if (settings.showPinButton()) {
bookmarkService.isBookmarkable(getCurrentFilter())
.toObservable()
.compose(bindToLifecycleAsync())
.subscribe(this::onBookmarkableStateChanged, Actions.empty());
}
recheckContentTypes();
// set new indicator style
if (seenIndicatorStyle != settings.seenIndicatorStyle()) {
seenIndicatorStyle = settings.seenIndicatorStyle();
feedAdapter.notifyDataSetChanged();
}
preloadManager.all()
.compose(bindToLifecycleAsync())
.subscribe(ignored -> feedAdapter.notifyDataSetChanged());
}
private void recheckContentTypes() {
// check if content type has changed, and reload if necessary
FeedFilter feedFilter = feedAdapter.getFilter();
EnumSet<ContentType> newContentType = getSelectedContentType();
boolean changed = !equal(feedAdapter.getContentType(), newContentType);
if (changed) {
Optional<Long> around = autoOpenOnLoad != null
? Optional.of(autoOpenOnLoad.getItemId())
: findLastVisibleFeedItem(newContentType).transform(FeedItem::id);
autoScrollOnLoad = around.orNull();
// set a new adapter if we have a new content type
setFeedAdapter(newFeedAdapter(feedFilter, autoScrollOnLoad));
getActivity().supportInvalidateOptionsMenu();
}
}
/**
* Finds the first item in the proxy, that is visible and of one of the given content type.
*
* @param contentType The target-content type.
*/
private Optional<FeedItem> findLastVisibleFeedItem(Set<ContentType> contentType) {
List<FeedItem> items = feedAdapter.getFeed().getItems();
return getRecyclerViewLayoutManager().<Optional<FeedItem>>transform(layoutManager -> {
MergeRecyclerAdapter adapter = (MergeRecyclerAdapter) recyclerView.getAdapter();
int offset = adapter.getOffset(feedAdapter).or(0);
// if the first row is visible, skip this stuff.
if (layoutManager.findFirstCompletelyVisibleItemPosition() == 0)
return absent();
int idx = layoutManager.findLastCompletelyVisibleItemPosition() - offset;
if (idx != RecyclerView.NO_POSITION && idx > 0 && idx < items.size()) {
for (FeedItem item : Lists.reverse(items.subList(0, idx))) {
if (contentType.contains(item.contentType())) {
return Optional.of(item);
}
}
}
return absent();
}).or(Optional::absent);
}
/**
* Depending on whether the screen is landscape or portrait, and how large
* the screen is, we show a different number of items per row.
*/
private int getThumbnailColumns() {
checkNotNull(getActivity(), "must be attached to call this method");
Configuration config = getResources().getConfiguration();
boolean portrait = config.screenWidthDp < config.screenHeightDp;
int screenWidth = config.screenWidthDp;
return Math.min((int) (screenWidth / 120.0 + 0.5), portrait ? 5 : 7);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_feed, menu);
// hide search item, if we are not searchable
MenuItem item = menu.findItem(R.id.action_search);
if (item != null && getActivity() != null) {
boolean searchable = getCurrentFilter().getFeedType().searchable();
if (!searchable) {
item.setVisible(false);
}
}
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
if (getActivity() == null)
return;
FeedFilter filter = getCurrentFilter();
FeedType feedType = filter.getFeedType();
MenuItem item;
if ((item = menu.findItem(R.id.action_refresh)) != null)
item.setVisible(settings.showRefreshButton());
if ((item = menu.findItem(R.id.action_pin)) != null)
item.setVisible(bookmarkable);
if ((item = menu.findItem(R.id.action_preload)) != null)
item.setVisible(feedType.preloadable() && !AndroidUtility.isOnMobile(getActivity()));
if ((item = menu.findItem(R.id.action_feedtype)) != null) {
item.setVisible(!filter.isBasic() &&
EnumSet.of(FeedType.PROMOTED, FeedType.NEW, FeedType.PREMIUM).contains(feedType));
item.setTitle(switchFeedTypeTarget(filter) == FeedType.PROMOTED
? R.string.action_switch_to_top
: R.string.action_switch_to_new);
}
if ((item = menu.findItem(R.id.action_change_content_type)) != null) {
if (userService.isAuthorized()) {
ContentTypeDrawable icon = new ContentTypeDrawable(getActivity(), getSelectedContentType());
icon.setTextSize(getResources().getDimensionPixelSize(
R.dimen.feed_content_type_action_icon_text_size));
item.setIcon(icon);
item.setVisible(true);
updateContentTypeItems(menu);
} else {
item.setVisible(false);
}
}
MenuItem follow = menu.findItem(R.id.action_follow);
MenuItem unfollow = menu.findItem(R.id.action_unfollow);
MenuItem bookmark = menu.findItem(R.id.action_pin);
if (follow != null && unfollow != null && bookmark != null) {
// go to default state.
follow.setVisible(false);
unfollow.setVisible(false);
if (activeUsername != null) {
if (userService.isPremiumUser()) {
boolean following = followService.isFollowing(activeUsername);
follow.setVisible(!following);
unfollow.setVisible(following);
}
// never bookmark a user
bookmark.setVisible(false);
}
}
}
private FeedType switchFeedTypeTarget(FeedFilter filter) {
return filter.getFeedType() != FeedType.PROMOTED ? FeedType.PROMOTED : FeedType.NEW;
}
private void updateContentTypeItems(Menu menu) {
// only one content type selected?
boolean single = ContentType.withoutImplicit(settings.getContentType()).size() == 1;
Map<Integer, Boolean> types = ImmutableMap.<Integer, Boolean>builder()
.put(R.id.action_content_type_sfw, settings.getContentTypeSfw())
.put(R.id.action_content_type_nsfw, settings.getContentTypeNsfw())
.put(R.id.action_content_type_nsfl, settings.getContentTypeNsfl())
.build();
for (Map.Entry<Integer, Boolean> entry : types.entrySet()) {
MenuItem item = menu.findItem(entry.getKey());
if (item != null) {
item.setChecked(entry.getValue());
item.setEnabled(!single || !entry.getValue());
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Map<Integer, String> contentTypes = ImmutableMap.<Integer, String>builder()
.put(R.id.action_content_type_sfw, "pref_feed_type_sfw")
.put(R.id.action_content_type_nsfw, "pref_feed_type_nsfw")
.put(R.id.action_content_type_nsfl, "pref_feed_type_nsfl")
.build();
if (contentTypes.containsKey(item.getItemId())) {
boolean newState = !item.isChecked();
settings.edit()
.putBoolean(contentTypes.get(item.getItemId()), newState)
.apply();
// this applies the new content types and refreshes the menu.
recheckContentTypes();
return true;
}
return OptionMenuHelper.dispatch(this, item) || super.onOptionsItemSelected(item);
}
@OnOptionsItemSelected(R.id.action_feedtype)
public void switchFeedType() {
FeedFilter filter = getCurrentFilter();
filter = filter.withFeedType(switchFeedTypeTarget(filter));
((MainActionHandler) getActivity()).onFeedFilterSelected(filter, initialSearchViewState());
}
@OnOptionsItemSelected(R.id.action_refresh)
public void refreshWithIndicator() {
if (swipeRefreshLayout.isRefreshing())
return;
swipeRefreshLayout.setRefreshing(true);
swipeRefreshLayout.postDelayed(() -> {
resetToolbar();
loader.restart(Optional.absent());
}, 500);
}
@OnOptionsItemSelected(R.id.action_pin)
public void pinCurrentFeedFilter() {
// not bookmarkable anymore.
onBookmarkableStateChanged(false);
FeedFilter filter = getCurrentFilter();
String title = FeedFilterFormatter.format(getActivity(), filter).singleline();
((MainActionHandler) getActivity()).pinFeedFilter(filter, title);
}
@OnOptionsItemSelected(R.id.action_preload)
public void preloadCurrentFeed() {
if (AndroidUtility.isOnMobile(getActivity())) {
DialogBuilder.start(getActivity())
.content(R.string.preload_not_on_mobile)
.positive()
.show();
return;
}
Intent intent = PreloadService.newIntent(getActivity(), feedAdapter.getFeed().getItems());
getActivity().startService(intent);
Track.preloadCurrentFeed(feedAdapter.getFeed().getItems().size());
if (singleShotService.isFirstTime("preload_info_hint")) {
DialogBuilder.start(getActivity())
.content(R.string.preload_info_hint)
.positive()
.show();
}
}
@OnOptionsItemSelected(R.id.action_follow)
public void onFollowClicked() {
followService.follow(activeUsername)
.subscribeOn(BackgroundScheduler.instance())
.subscribe(Actions.empty(), Actions.empty());
}
@OnOptionsItemSelected(R.id.action_unfollow)
public void onUnfollowClicked() {
followService.unfollow(activeUsername)
.subscribeOn(BackgroundScheduler.instance())
.subscribe(Actions.empty(), Actions.empty());
}
public void performSearch(SearchOptionsView.SearchQuery query) {
hideSearchContainer();
FeedFilter current = getCurrentFilter();
FeedFilter filter = current.withTagsNoReset(query.combined());
// do nothing, if the filter did not change
if (equal(current, filter))
return;
ItemWithComment startAt = null;
if (query.combined().trim().matches("[1-9][0-9]{5,}|id:[0-9]+")) {
filter = filter.withTags("");
startAt = new ItemWithComment(Long.parseLong(
CharMatcher.digit().retainFrom(query.combined())), null);
}
Bundle searchQueryState = searchView.currentState();
((MainActionHandler) getActivity()).onFeedFilterSelected(filter, searchQueryState, startAt);
// store the term for later
if (query.queryTerm().trim().length() > 0) {
recentSearchesServices.storeTerm(query.queryTerm());
}
Track.search(query.combined());
}
private void onItemClicked(int idx, Optional<Long> commentId, Optional<ImageView> preview) {
// reset auto open.
autoOpenOnLoad = null;
Feed feed = feedAdapter.getFeed();
if (idx < 0 || idx >= feed.size())
return;
try {
PostPagerFragment fragment = PostPagerFragment.newInstance(feed, idx, commentId);
if (preview.isPresent()) {
// pass pixels info to target fragment.
Drawable image = preview.get().getDrawable();
FeedItem item = feed.at(idx);
fragment.setPreviewInfo(PreviewInfo.of(getContext(), item, image));
}
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.content, fragment)
.addToBackStack("Post" + idx)
.commit();
} catch (Exception error) {
logger.warn("Error while showing post", error);
}
}
/**
* Creates a new {@link FeedFragment} for the given feed type.
*
* @param feedFilter A query to use for getting data
* @return The type new fragment that can be shown now.
*/
public static FeedFragment newInstance(FeedFilter feedFilter,
@Nullable ItemWithComment start,
@Nullable Bundle searchQueryState) {
Bundle arguments = newArguments(feedFilter, true, start, searchQueryState);
FeedFragment fragment = new FeedFragment();
fragment.setArguments(arguments);
return fragment;
}
public static Bundle newArguments(FeedFilter feedFilter, boolean simpleMode,
@Nullable ItemWithComment start,
@Nullable Bundle searchQueryState) {
Bundle arguments = new Bundle();
arguments.putParcelable(ARG_FEED_FILTER, feedFilter);
arguments.putParcelable(ARG_FEED_START, start);
arguments.putBoolean(ARG_SIMPLE_MODE, simpleMode);
arguments.putBundle(ARG_SEARCH_QUERY_STATE, searchQueryState);
return arguments;
}
/**
* Gets the current filter from this feed.
*
* @return The filter this feed uses.
*/
@Override
public FeedFilter getCurrentFilter() {
if (feedAdapter == null)
return new FeedFilter();
return feedAdapter.getFilter();
}
boolean isSeen(FeedItem item) {
return seenService.isSeen(item);
}
private void createRecyclerViewClickListener() {
RecyclerItemClickListener listener = new RecyclerItemClickListener(getActivity(), recyclerView);
listener.itemClicked()
.map(FeedFragment::extractFeedItemHolder)
.filter(isNotNull())
.subscribe(holder -> onItemClicked(holder.index, absent(), of(holder.image)));
listener.itemLongClicked()
.map(FeedFragment::extractFeedItemHolder)
.filter(isNotNull())
.subscribe(holder -> openQuickPeek(holder.item));
listener.itemLongClickEnded().subscribe(event -> dismissPopupPlayer());
settings.change()
.compose(bindToLifecycle())
.startWith("")
.subscribe(key -> listener.enableLongClick(settings.enableQuickPeek()));
}
private void openQuickPeek(FeedItem item) {
// check that the activity is not zero. Might happen, as this method might
// get called shortly after detaching the activity - which sucks. thanks android.
Activity activity = getActivity();
if (activity != null) {
this.quickPeekDialog = new WeakReference<>(
PopupPlayer.newInstance(activity, item));
swipeRefreshLayout.setEnabled(false);
Track.quickPeek();
}
}
@Nullable
private static FeedItemViewHolder extractFeedItemHolder(View view) {
Object tag = view.getTag();
return tag instanceof FeedItemViewHolder ? (FeedItemViewHolder) tag : null;
}
private void dismissPopupPlayer() {
swipeRefreshLayout.setEnabled(true);
Dialog quickPeek = quickPeekDialog.get();
if (quickPeek != null)
quickPeek.dismiss();
}
private static class FeedAdapter extends RecyclerView.Adapter<FeedItemViewHolder> implements Feed.FeedListener {
private final boolean usersFavorites;
private final WeakReference<FeedFragment> parent;
private final Feed feed;
FeedAdapter(FeedFragment fragment, Feed feed, boolean usersFavorites) {
this.usersFavorites = usersFavorites;
this.parent = new WeakReference<>(fragment);
this.feed = feed;
this.feed.setFeedListener(this);
setHasStableIds(true);
}
private void with(Action1<FeedFragment> action) {
FeedFragment fragment = parent.get();
if (fragment != null) {
action.call(fragment);
}
}
public FeedFilter getFilter() {
return feed.getFeedFilter();
}
public Feed getFeed() {
return feed;
}
@SuppressLint("InflateParams")
@Override
public FeedItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(this.parent.get().getActivity());
View view = inflater.inflate(R.layout.feed_item_view, null);
return new FeedItemViewHolder(view);
}
@Override
public void onBindViewHolder(FeedItemViewHolder holder,
@SuppressLint("RecyclerView") int position) {
FeedItem item = feed.at(position);
with(fragment -> {
Uri imageUri = UriHelper.of(fragment.getContext()).thumbnail(item);
fragment.picasso.load(imageUri)
.config(Bitmap.Config.RGB_565)
.placeholder(new ColorDrawable(0xff333333))
.into(holder.image);
holder.itemView.setTag(holder);
holder.index = position;
holder.item = item;
// show preload-badge
holder.setIsPreloaded(fragment.preloadManager.exists(item.id()));
// check if this item was already seen.
if (fragment.inMemoryCacheService.isRepost(item.id())) {
holder.setIsRepost();
} else if (fragment.seenIndicatorStyle == IndicatorStyle.ICON
&& !usersFavorites && fragment.isSeen(item)) {
holder.setIsSeen();
} else {
holder.clear();
}
});
}
@Override
public int getItemCount() {
return feed.size();
}
@Override
public long getItemId(int position) {
return feed.at(position).id();
}
Set<ContentType> getContentType() {
return feed.getContentType();
}
@Override
public void onNewItems(List<FeedItem> newItems) {
// check if we prepended items to the list.
int prependCount = 0;
for (int idx = 0; idx < newItems.size(); idx++) {
if (newItems.get(idx).id() == getItemId(idx)) {
prependCount++;
}
}
if (prependCount == 0) {
notifyDataSetChanged();
} else {
notifyItemRangeInserted(0, prependCount);
}
// load meta data for the items.
with(fragment -> {
if (newItems.size() > 0) {
FeedItem mostRecentItem = Ordering.natural()
.onResultOf((Function<FeedItem, Long>) FeedItem::id)
.min(newItems);
fragment.refreshRepostInfos(mostRecentItem.id(), feed.getFeedFilter());
}
fragment.performAutoOpen();
});
}
@Override
public void onRemoveItems() {
notifyDataSetChanged();
}
@Override
public void onWrongContentType() {
with(FeedFragment::showWrongContentTypeInfo);
}
}
void showWrongContentTypeInfo() {
Context context = getActivity();
if (context != null) {
DialogBuilder.start(context)
.content(R.string.hint_wrong_content_type)
.positive()
.show();
}
}
void refreshRepostInfos(long id, FeedFilter filter) {
if (filter.getFeedType() != FeedType.NEW && filter.getFeedType() != FeedType.PROMOTED)
return;
// check if it is possible to get repost info.
boolean queryTooLong = filter.getTags().or("").split("\\s+").length >= 5;
if (queryTooLong)
return;
FeedService.FeedQuery query = ImmutableFeedQuery.builder()
.contentTypes(getSelectedContentType())
.older(id)
.feedFilter(filter.withTags(filter.getTags().transform(tags -> tags + " repost").or("repost")))
.build();
InMemoryCacheService cacheService = this.inMemoryCacheService;
WeakReference<FeedFragment> fragment = new WeakReference<>(this);
feedService.getFeedItems(query)
.subscribeOn(BackgroundScheduler.instance())
.observeOn(mainThread())
.subscribe(items -> {
if (items.getItems().size() > 0) {
List<Long> ids = Lists.transform(items.getItems(), Api.Feed.Item::getId);
cacheService.cacheReposts(ids);
// update feed adapter to show new 'repost' badges.
FeedFragment frm = fragment.get();
if (frm != null) {
frm.feedAdapter.notifyDataSetChanged();
}
}
}, Actions.empty());
}
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
void onFeedError(Throwable error) {
logger.error("Error loading the feed", error);
if (autoOpenOnLoad != null) {
ErrorDialogFragment.showErrorString(getFragmentManager(),
getString(R.string.could_not_load_feed_nsfw));
} else if (error instanceof JsonSyntaxException) {
// show a special error
ErrorDialogFragment.showErrorString(getFragmentManager(),
getString(R.string.could_not_load_feed_json));
} else if (Throwables.getRootCause(error) instanceof ConnectException && settings.useHttps()) {
ErrorDialogFragment.showErrorString(getFragmentManager(),
getString(R.string.could_not_load_feed_https));
} else {
ErrorDialogFragment.defaultOnError().call(error);
}
}
/**
* Called when loading of feed data finished.
*/
void onFeedLoadFinished() {
removeBusyIndicator();
swipeRefreshLayout.setRefreshing(false);
updateNoResultsTextView();
}
private void updateNoResultsTextView() {
boolean empty = feedAdapter.getItemCount() == 0;
noResultsView.setVisibility(empty ? View.VISIBLE : View.GONE);
}
@OnOptionsItemSelected(R.id.action_search)
public void resetAndShowSearchContainer() {
searchView.applyState(initialSearchViewState());
showSearchContainer(true);
}
private void showSearchContainer(boolean animated) {
if (searchContainerIsVisible())
return;
View view = getView();
if (view == null)
return;
view.post(this::hideToolbar);
// prepare search view
String typeName = feedTypeToString(getContext(), getCurrentFilter().withTagsNoReset("dummy"));
searchView.setQueryHint(getString(R.string.action_search, typeName));
searchView.setPadding(0, AndroidUtility.getStatusBarHeight(getContext()), 0, 0);
searchContainer.setVisibility(View.VISIBLE);
if (animated) {
searchContainer.setAlpha(0.f);
searchContainer.animate()
.setListener(endAction(searchView::requestSearchFocus))
.alpha(1);
searchView.setTranslationY(-(int) (0.1 * view.getHeight()));
searchView.animate()
.setInterpolator(new DecelerateInterpolator())
.translationY(0);
} else {
searchContainer.animate().cancel();
searchContainer.setAlpha(1.f);
searchView.animate().cancel();
searchView.setTranslationY(0);
}
}
@Override
public boolean onBackButton() {
if (searchContainerIsVisible()) {
hideSearchContainer();
return true;
}
return false;
}
public boolean searchContainerIsVisible() {
return searchContainer != null && searchContainer.getVisibility() != View.GONE;
}
void hideSearchContainer() {
if (!searchContainerIsVisible())
return;
searchContainer.animate()
.setListener(hideViewOnAnimationEnd(searchContainer))
.alpha(0);
searchView.animate().translationY(-(int) (0.1 * getView().getHeight()));
resetToolbar();
AndroidUtility.hideSoftKeyboard(searchView);
}
@SuppressWarnings("CodeBlock2Expr")
void performAutoOpen() {
Feed feed = feedAdapter.getFeed();
if (autoScrollOnLoad != null) {
ifPresent(findItemIndexById(autoScrollOnLoad), idx -> {
// over scroll a bit
int scrollTo = Math.max(idx + getThumbnailColumns(), 0);
recyclerView.scrollToPosition(scrollTo);
});
}
if (autoOpenOnLoad != null) {
ifPresent(feed.indexOf(autoOpenOnLoad.getItemId()), idx -> {
onItemClicked(idx, autoOpenOnLoad.getCommentId(), absent());
});
}
autoScrollOnLoad = null;
}
/**
* Returns the item id of the index in the recycler views adapter.
*/
private Optional<Integer> findItemIndexById(long id) {
int offset = ((MergeRecyclerAdapter) recyclerView.getAdapter()).getOffset(feedAdapter).or(0);
// look for the index of the item with the given id
return FluentIterable
.from(feedAdapter.getFeed().getItems())
.firstMatch(item -> item.id() == id)
.transform(item -> feedAdapter.getFeed().indexOf(item).or(-1))
.transform(idx -> idx + offset);
}
Optional<GridLayoutManager> getRecyclerViewLayoutManager() {
if (recyclerView == null)
return absent();
return Optional.fromNullable((GridLayoutManager) recyclerView.getLayoutManager());
}
private boolean isSelfInfo(Api.Info info) {
return info.getUser().getName().equalsIgnoreCase(userService.getName().orNull());
}
private final RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (scrollToolbar && getActivity() instanceof ToolbarActivity) {
ToolbarActivity activity = (ToolbarActivity) getActivity();
activity.getScrollHideToolbarListener().onScrolled(dy);
}
ifPresent(getRecyclerViewLayoutManager(), layoutManager -> {
if (loader.isLoading())
return;
Feed feed = feedAdapter.getFeed();
int totalItemCount = layoutManager.getItemCount();
if (dy > 0 && !feed.isAtEnd()) {
int lastVisibleItem = layoutManager.findLastVisibleItemPosition();
if (totalItemCount > 12 && lastVisibleItem >= totalItemCount - 12) {
logger.info("Request next page now");
loader.next();
}
}
if (dy < 0 && !feed.isAtStart()) {
int firstVisibleItem = layoutManager.findFirstVisibleItemPosition();
if (totalItemCount > 12 && firstVisibleItem < 12) {
logger.info("Request previous page now");
loader.previous();
}
}
});
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
if (getActivity() instanceof ToolbarActivity) {
int y = estimateRecyclerViewScrollY(recyclerView).or(Integer.MAX_VALUE);
ToolbarActivity activity = (ToolbarActivity) getActivity();
activity.getScrollHideToolbarListener().onScrollFinished(y);
}
}
}
};
}
| app/src/main/java/com/pr0gramm/app/ui/fragments/FeedFragment.java | package com.pr0gramm.app.ui.fragments;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.ScrollView;
import com.google.common.base.CharMatcher;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Throwables;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.gson.JsonSyntaxException;
import com.pr0gramm.app.ActivityComponent;
import com.pr0gramm.app.R;
import com.pr0gramm.app.Settings;
import com.pr0gramm.app.api.pr0gramm.Api;
import com.pr0gramm.app.feed.ContentType;
import com.pr0gramm.app.feed.Feed;
import com.pr0gramm.app.feed.FeedFilter;
import com.pr0gramm.app.feed.FeedItem;
import com.pr0gramm.app.feed.FeedLoader;
import com.pr0gramm.app.feed.FeedService;
import com.pr0gramm.app.feed.FeedType;
import com.pr0gramm.app.feed.ImmutableFeedQuery;
import com.pr0gramm.app.services.BookmarkService;
import com.pr0gramm.app.services.EnhancedUserInfo;
import com.pr0gramm.app.services.FollowingService;
import com.pr0gramm.app.services.ImmutableEnhancedUserInfo;
import com.pr0gramm.app.services.InMemoryCacheService;
import com.pr0gramm.app.services.InboxService;
import com.pr0gramm.app.services.RecentSearchesServices;
import com.pr0gramm.app.services.SeenService;
import com.pr0gramm.app.services.SingleShotService;
import com.pr0gramm.app.services.Track;
import com.pr0gramm.app.services.UriHelper;
import com.pr0gramm.app.services.UserService;
import com.pr0gramm.app.services.config.Config;
import com.pr0gramm.app.services.preloading.PreloadManager;
import com.pr0gramm.app.services.preloading.PreloadService;
import com.pr0gramm.app.ui.AdService;
import com.pr0gramm.app.ui.ContentTypeDrawable;
import com.pr0gramm.app.ui.DetectTapTouchListener;
import com.pr0gramm.app.ui.DialogBuilder;
import com.pr0gramm.app.ui.FeedFilterFormatter;
import com.pr0gramm.app.ui.FeedItemViewHolder;
import com.pr0gramm.app.ui.FilterFragment;
import com.pr0gramm.app.ui.LoginActivity;
import com.pr0gramm.app.ui.LoginActivity.DoIfAuthorizedHelper;
import com.pr0gramm.app.ui.MainActionHandler;
import com.pr0gramm.app.ui.MergeRecyclerAdapter;
import com.pr0gramm.app.ui.OnOptionsItemSelected;
import com.pr0gramm.app.ui.OptionMenuHelper;
import com.pr0gramm.app.ui.PreviewInfo;
import com.pr0gramm.app.ui.RecyclerItemClickListener;
import com.pr0gramm.app.ui.SingleViewAdapter;
import com.pr0gramm.app.ui.WriteMessageActivity;
import com.pr0gramm.app.ui.back.BackAwareFragment;
import com.pr0gramm.app.ui.base.BaseFragment;
import com.pr0gramm.app.ui.dialogs.ErrorDialogFragment;
import com.pr0gramm.app.ui.dialogs.PopupPlayer;
import com.pr0gramm.app.ui.views.BusyIndicator;
import com.pr0gramm.app.ui.views.CustomSwipeRefreshLayout;
import com.pr0gramm.app.ui.views.SearchOptionsView;
import com.pr0gramm.app.ui.views.UserInfoCell;
import com.pr0gramm.app.ui.views.UserInfoFoundView;
import com.pr0gramm.app.util.AndroidUtility;
import com.pr0gramm.app.util.BackgroundScheduler;
import com.squareup.picasso.Picasso;
import com.trello.rxlifecycle.android.FragmentEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.ref.WeakReference;
import java.net.ConnectException;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import butterknife.BindView;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Actions;
import static com.google.common.base.Objects.equal;
import static com.google.common.base.Optional.absent;
import static com.google.common.base.Optional.fromNullable;
import static com.google.common.base.Optional.of;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.pr0gramm.app.R.id.empty;
import static com.pr0gramm.app.feed.ContentType.SFW;
import static com.pr0gramm.app.services.ThemeHelper.accentColor;
import static com.pr0gramm.app.ui.FeedFilterFormatter.feedTypeToString;
import static com.pr0gramm.app.ui.ScrollHideToolbarListener.ToolbarActivity;
import static com.pr0gramm.app.ui.ScrollHideToolbarListener.estimateRecyclerViewScrollY;
import static com.pr0gramm.app.util.AndroidUtility.checkMainThread;
import static com.pr0gramm.app.util.AndroidUtility.endAction;
import static com.pr0gramm.app.util.AndroidUtility.getStatusBarHeight;
import static com.pr0gramm.app.util.AndroidUtility.hideViewOnAnimationEnd;
import static com.pr0gramm.app.util.AndroidUtility.ifPresent;
import static com.pr0gramm.app.util.AndroidUtility.isNotNull;
import static java.util.Collections.emptyList;
import static rx.android.schedulers.AndroidSchedulers.mainThread;
/**
*/
public class FeedFragment extends BaseFragment implements FilterFragment, BackAwareFragment {
static final Logger logger = LoggerFactory.getLogger("FeedFragment");
private static final String ARG_FEED_FILTER = "FeedFragment.filter";
private static final String ARG_FEED_START = "FeedFragment.start.id";
private static final String ARG_SEARCH_QUERY_STATE = "FeedFragment.searchQueryState";
private static final String ARG_SIMPLE_MODE = "FeedFragment.simpleMode";
@Inject
FeedService feedService;
@Inject
Picasso picasso;
@Inject
SeenService seenService;
@Inject
Settings settings;
@Inject
BookmarkService bookmarkService;
@Inject
UserService userService;
@Inject
SingleShotService singleShotService;
@Inject
InMemoryCacheService inMemoryCacheService;
@Inject
PreloadManager preloadManager;
@Inject
InboxService inboxService;
@Inject
RecentSearchesServices recentSearchesServices;
@Inject
FollowingService followService;
@Inject
AdService adService;
@BindView(R.id.list)
RecyclerView recyclerView;
@BindView(R.id.progress)
BusyIndicator busyIndicator;
@BindView(R.id.refresh)
CustomSwipeRefreshLayout swipeRefreshLayout;
@BindView(empty)
View noResultsView;
@BindView(R.id.search_container)
ScrollView searchContainer;
@BindView(R.id.search_options)
SearchOptionsView searchView;
private final AdViewAdapter adViewAdapter = new AdViewAdapter();
private final DoIfAuthorizedHelper doIfAuthorizedHelper = LoginActivity.helper(this);
boolean userInfoCommentsOpen;
private boolean bookmarkable;
IndicatorStyle seenIndicatorStyle;
private Long autoScrollOnLoad = null;
private ItemWithComment autoOpenOnLoad = null;
FeedAdapter feedAdapter;
FeedLoader loader;
boolean scrollToolbar;
private WeakReference<Dialog> quickPeekDialog = new WeakReference<>(null);
private String activeUsername;
/**
* Initialize a new feed fragment.
*/
public FeedFragment() {
setHasOptionsMenu(true);
setRetainInstance(true);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// initialize auto opening
ItemWithComment start = getArguments().getParcelable(ARG_FEED_START);
if (start != null) {
autoScrollOnLoad = start.getItemId();
autoOpenOnLoad = start;
}
this.scrollToolbar = useToolbarTopMargin();
adService.enabledForType(Config.AdType.FEED)
.observeOn(mainThread())
.compose(bindToLifecycle())
.subscribe((show) -> {
adViewAdapter.setShowAds(show);
updateSpanSizeLookup();
});
}
@Override
protected void injectComponent(ActivityComponent activityComponent) {
activityComponent.inject(this);
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_feed, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (feedAdapter == null) {
if (busyIndicator != null)
busyIndicator.setVisibility(View.VISIBLE);
// create a new adapter if necessary
feedAdapter = newFeedAdapter();
} else {
updateNoResultsTextView();
removeBusyIndicator();
}
seenIndicatorStyle = settings.seenIndicatorStyle();
// prepare the list of items
int columnCount = getThumbnailColumns();
GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), columnCount);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(null);
setFeedAdapter(feedAdapter);
// we can still swipe up if we are not at the start of the feed.
swipeRefreshLayout.setCanSwipeUpPredicate(() -> !feedAdapter.getFeed().isAtStart());
swipeRefreshLayout.setOnRefreshListener(() -> {
Feed feed = feedAdapter.getFeed();
if (feed.isAtStart() && !loader.isLoading()) {
loader.restart(Optional.absent());
} else {
// do not refresh
swipeRefreshLayout.setRefreshing(false);
}
});
if (useToolbarTopMargin()) {
// use height of the toolbar to configure swipe refresh layout.
int abHeight = AndroidUtility.getActionBarContentOffset(getActivity());
int offset = getStatusBarHeight(getActivity());
swipeRefreshLayout.setProgressViewOffset(false, offset, (int) (offset + 1.5 * (abHeight - offset)));
}
swipeRefreshLayout.setColorSchemeResources(accentColor());
resetToolbar();
createRecyclerViewClickListener();
recyclerView.addOnScrollListener(onScrollListener);
// observe changes so we can update the mehu
followService.changes()
.compose(bindToLifecycle())
.observeOn(mainThread())
.filter(name -> name.equalsIgnoreCase(activeUsername))
.subscribe(name -> getActivity().supportInvalidateOptionsMenu());
// execute a search when we get a search term
searchView.searchQuery().compose(bindToLifecycle()).subscribe(this::performSearch);
searchView.searchCanceled().compose(bindToLifecycle()).subscribe(e -> hideSearchContainer());
searchView.setupAutoComplete(recentSearchesServices);
// restore open search
if (savedInstanceState != null && savedInstanceState.getBoolean("searchContainerVisible")) {
showSearchContainer(false);
}
// close search on click into the darkened area.
searchContainer.setOnTouchListener(
DetectTapTouchListener.withConsumer(this::hideSearchContainer));
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("searchContainerVisible", searchContainerIsVisible());
}
private Bundle initialSearchViewState() {
Bundle state = getArguments().getBundle(ARG_SEARCH_QUERY_STATE);
if (state == null) {
Optional<String> tags = getCurrentFilter().getTags();
if (tags.isPresent()) {
state = SearchOptionsView.ofQueryTerm(tags.get());
}
}
return state;
}
private void setFeedAdapter(FeedAdapter adapter) {
feedAdapter = adapter;
MergeRecyclerAdapter merged = new MergeRecyclerAdapter();
if (useToolbarTopMargin()) {
merged.addAdapter(SingleViewAdapter.of(FeedFragment::newFeedStartPaddingView));
}
merged.addAdapter(adViewAdapter);
merged.addAdapter(adapter);
recyclerView.setAdapter(merged);
updateSpanSizeLookup();
if (!isSimpleMode()) {
queryUserInfo()
.take(1)
.compose(bindToLifecycleAsync())
.subscribe(this::presentUserInfo, Actions.empty());
}
}
private boolean useToolbarTopMargin() {
return !isSimpleMode();
}
private boolean isSimpleMode() {
Bundle arguments = getArguments();
return arguments != null && !arguments.getBoolean(ARG_SIMPLE_MODE, true);
}
private void presentUserInfo(EnhancedUserInfo value) {
if (getCurrentFilter().getTags().isPresent()) {
presentUserUploadsHint(value.getInfo());
} else {
presentUserInfoCell(value);
}
}
private void presentUserInfoCell(EnhancedUserInfo info) {
UserCommentsAdapter messages = new UserCommentsAdapter(getActivity());
List<Api.UserComments.UserComment> comments = info.getComments();
if (userInfoCommentsOpen) {
messages.setComments(info.getInfo().getUser(), comments);
}
UserInfoCell view = new UserInfoCell(getActivity(), info.getInfo(), doIfAuthorizedHelper);
view.setUserActionListener(new UserInfoCell.UserActionListener() {
@Override
public void onWriteMessageClicked(int userId, String name) {
startActivity(WriteMessageActivity.intent(getActivity(), userId, name));
}
@Override
public void onUserFavoritesClicked(String name) {
FeedFilter filter = getCurrentFilter().basic().withLikes(name);
if (!filter.equals(getCurrentFilter())) {
((MainActionHandler) getActivity()).onFeedFilterSelected(filter);
}
showUserInfoComments(emptyList());
}
@Override
public void onShowUploadsClicked(int id, String name) {
FeedFilter filter = getCurrentFilter().basic().withFeedType(FeedType.NEW).withUser(name);
if (!filter.equals(getCurrentFilter())) {
((MainActionHandler) getActivity()).onFeedFilterSelected(filter);
}
showUserInfoComments(emptyList());
}
@Override
public void onShowCommentsClicked() {
showUserInfoComments(messages.getItemCount() == 0 ? comments : emptyList());
}
private void showUserInfoComments(List<Api.UserComments.UserComment> comments) {
userInfoCommentsOpen = comments.size() > 0;
messages.setComments(info.getInfo().getUser(), comments);
updateSpanSizeLookup();
}
});
view.setWriteMessageEnabled(!isSelfInfo(info.getInfo()));
view.setShowCommentsEnabled(!comments.isEmpty());
appendUserInfoAdapters(
SingleViewAdapter.ofView(view),
messages,
SingleViewAdapter.ofLayout(R.layout.user_info_footer));
// we are showing a user.
activeUsername = info.getInfo().getUser().getName();
getActivity().supportInvalidateOptionsMenu();
}
private void presentUserUploadsHint(Api.Info info) {
if (isSelfInfo(info))
return;
UserInfoFoundView view = new UserInfoFoundView(getActivity(), info);
view.setUploadsClickedListener((userId, name) -> {
FeedFilter newFilter = getCurrentFilter().basic()
.withFeedType(FeedType.NEW).withUser(name);
((MainActionHandler) getActivity()).onFeedFilterSelected(newFilter);
});
appendUserInfoAdapters(SingleViewAdapter.ofView(view));
}
private void appendUserInfoAdapters(RecyclerView.Adapter... adapters) {
if (adapters.length == 0) {
return;
}
MergeRecyclerAdapter mainAdapter = getMainAdapter().orNull();
if (mainAdapter != null) {
int offset = 0;
ImmutableList<? extends RecyclerView.Adapter<?>> subAdapters = mainAdapter.getAdapters();
for (int idx = 0; idx < subAdapters.size(); idx++) {
offset = idx;
RecyclerView.Adapter<?> subAdapter = subAdapters.get(idx);
if (subAdapter instanceof FeedAdapter || subAdapter instanceof AdViewAdapter) {
break;
}
}
for (int idx = 0; idx < adapters.length; idx++) {
mainAdapter.addAdapter(offset + idx, adapters[idx]);
}
updateSpanSizeLookup();
}
}
private Observable<EnhancedUserInfo> queryUserInfo() {
FeedFilter filter = getFilterArgument();
String queryString = filter.getUsername().or(filter.getTags()).or(filter.getLikes()).orNull();
if (queryString != null && queryString.matches("[A-Za-z0-9]+")) {
EnumSet<ContentType> contentTypes = getSelectedContentType();
Optional<EnhancedUserInfo> cached = inMemoryCacheService.getUserInfo(contentTypes, queryString);
if (cached.isPresent()) {
return Observable.just(cached.get());
}
Observable<Api.Info> first = userService
.info(queryString, getSelectedContentType())
.doOnNext(info -> followService.markAsFollowing(info.getUser().getName(), info.following()))
.onErrorResumeNext(Observable.empty());
Observable<List<Api.UserComments.UserComment>> third = inboxService
.getUserComments(queryString, contentTypes)
.map(Api.UserComments::getComments)
.onErrorResumeNext(Observable.just(emptyList()));
return Observable.zip(first, third, ImmutableEnhancedUserInfo::of)
.ofType(EnhancedUserInfo.class)
.doOnNext(info -> inMemoryCacheService.cacheUserInfo(contentTypes, info));
} else {
return Observable.empty();
}
}
void updateSpanSizeLookup() {
MergeRecyclerAdapter mainAdapter = getMainAdapter().orNull();
GridLayoutManager layoutManager = getRecyclerViewLayoutManager().orNull();
if (mainAdapter != null && layoutManager != null) {
int itemCount = 0;
ImmutableList<? extends RecyclerView.Adapter<?>> adapters = mainAdapter.getAdapters();
for (RecyclerView.Adapter<?> adapter : adapters) {
if (adapter instanceof FeedAdapter)
break;
itemCount += adapter.getItemCount();
}
// skip items!
int columnCount = layoutManager.getSpanCount();
layoutManager.setSpanSizeLookup(new NMatchParentSpanSizeLookup(itemCount, columnCount));
}
}
private static View newFeedStartPaddingView(Context context) {
int height = AndroidUtility.getActionBarContentOffset(context);
View view = new View(context);
view.setLayoutParams(new ViewGroup.LayoutParams(1, height));
return view;
}
private Optional<MergeRecyclerAdapter> getMainAdapter() {
if (recyclerView != null) {
RecyclerView.Adapter adapter = recyclerView.getAdapter();
return Optional.fromNullable((MergeRecyclerAdapter) adapter);
}
return Optional.absent();
}
@Override
public void onDestroyView() {
if (recyclerView != null) {
recyclerView.removeOnScrollListener(onScrollListener);
}
super.onDestroyView();
}
private void removeBusyIndicator() {
if (busyIndicator != null) {
ViewParent parent = busyIndicator.getParent();
((ViewGroup) parent).removeView(busyIndicator);
busyIndicator = null;
}
}
private void resetToolbar() {
if (getActivity() instanceof ToolbarActivity) {
ToolbarActivity activity = (ToolbarActivity) getActivity();
activity.getScrollHideToolbarListener().reset();
}
}
private void hideToolbar() {
if (getActivity() instanceof ToolbarActivity) {
ToolbarActivity activity = (ToolbarActivity) getActivity();
activity.getScrollHideToolbarListener().hide();
}
}
private void onBookmarkableStateChanged(boolean bookmarkable) {
this.bookmarkable = bookmarkable;
getActivity().supportInvalidateOptionsMenu();
}
private FeedAdapter newFeedAdapter() {
logger.info("Restore adapter now");
FeedFilter feedFilter = getFilterArgument();
Long around = null;
if (autoOpenOnLoad != null) {
around = autoOpenOnLoad.getItemId();
}
return newFeedAdapter(feedFilter, around);
}
private FeedAdapter newFeedAdapter(FeedFilter feedFilter, @Nullable Long around) {
Feed feed = new Feed(feedFilter, getSelectedContentType());
loader = new FeedLoader(new FeedLoader.Binder() {
@Override
public <T> Observable.Transformer<T, T> bind() {
return observable -> observable
.compose(bindUntilEventAsync(FragmentEvent.DESTROY_VIEW))
.doAfterTerminate(FeedFragment.this::onFeedLoadFinished);
}
@Override
public void onError(Throwable error) {
checkMainThread();
onFeedError(error);
}
}, feedService, feed);
// start loading now
loader.restart(fromNullable(around));
boolean usersFavorites = feed.getFeedFilter().getLikes()
.transform(name -> name.equalsIgnoreCase(userService.getName().orNull()))
.or(false);
return new FeedAdapter(this, feed, usersFavorites);
}
private FeedFilter getFilterArgument() {
return getArguments().getParcelable(ARG_FEED_FILTER);
}
private EnumSet<ContentType> getSelectedContentType() {
if (userService == null || !userService.isAuthorized())
return EnumSet.of(SFW);
return settings.getContentType();
}
@Override
public void onResume() {
super.onResume();
Track.screen("Item");
// check if we should show the pin button or not.
if (settings.showPinButton()) {
bookmarkService.isBookmarkable(getCurrentFilter())
.toObservable()
.compose(bindToLifecycleAsync())
.subscribe(this::onBookmarkableStateChanged, Actions.empty());
}
recheckContentTypes();
// set new indicator style
if (seenIndicatorStyle != settings.seenIndicatorStyle()) {
seenIndicatorStyle = settings.seenIndicatorStyle();
feedAdapter.notifyDataSetChanged();
}
preloadManager.all()
.compose(bindToLifecycleAsync())
.subscribe(ignored -> feedAdapter.notifyDataSetChanged());
}
private void recheckContentTypes() {
// check if content type has changed, and reload if necessary
FeedFilter feedFilter = feedAdapter.getFilter();
EnumSet<ContentType> newContentType = getSelectedContentType();
boolean changed = !equal(feedAdapter.getContentType(), newContentType);
if (changed) {
Optional<Long> around = autoOpenOnLoad != null
? Optional.of(autoOpenOnLoad.getItemId())
: findLastVisibleFeedItem(newContentType).transform(FeedItem::id);
autoScrollOnLoad = around.orNull();
// set a new adapter if we have a new content type
setFeedAdapter(newFeedAdapter(feedFilter, autoScrollOnLoad));
getActivity().supportInvalidateOptionsMenu();
}
}
/**
* Finds the first item in the proxy, that is visible and of one of the given content type.
*
* @param contentType The target-content type.
*/
private Optional<FeedItem> findLastVisibleFeedItem(Set<ContentType> contentType) {
List<FeedItem> items = feedAdapter.getFeed().getItems();
return getRecyclerViewLayoutManager().<Optional<FeedItem>>transform(layoutManager -> {
MergeRecyclerAdapter adapter = (MergeRecyclerAdapter) recyclerView.getAdapter();
int offset = adapter.getOffset(feedAdapter).or(0);
// if the first row is visible, skip this stuff.
if (layoutManager.findFirstCompletelyVisibleItemPosition() == 0)
return absent();
int idx = layoutManager.findLastCompletelyVisibleItemPosition() - offset;
if (idx != RecyclerView.NO_POSITION && idx > 0 && idx < items.size()) {
for (FeedItem item : Lists.reverse(items.subList(0, idx))) {
if (contentType.contains(item.contentType())) {
return Optional.of(item);
}
}
}
return absent();
}).or(Optional::absent);
}
/**
* Depending on whether the screen is landscape or portrait, and how large
* the screen is, we show a different number of items per row.
*/
private int getThumbnailColumns() {
checkNotNull(getActivity(), "must be attached to call this method");
Configuration config = getResources().getConfiguration();
boolean portrait = config.screenWidthDp < config.screenHeightDp;
int screenWidth = config.screenWidthDp;
return Math.min((int) (screenWidth / 120.0 + 0.5), portrait ? 5 : 7);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_feed, menu);
// hide search item, if we are not searchable
MenuItem item = menu.findItem(R.id.action_search);
if (item != null && getActivity() != null) {
boolean searchable = getCurrentFilter().getFeedType().searchable();
if (!searchable) {
item.setVisible(false);
}
}
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
if (getActivity() == null)
return;
FeedFilter filter = getCurrentFilter();
FeedType feedType = filter.getFeedType();
MenuItem item;
if ((item = menu.findItem(R.id.action_refresh)) != null)
item.setVisible(settings.showRefreshButton());
if ((item = menu.findItem(R.id.action_pin)) != null)
item.setVisible(bookmarkable);
if ((item = menu.findItem(R.id.action_preload)) != null)
item.setVisible(feedType.preloadable() && !AndroidUtility.isOnMobile(getActivity()));
if ((item = menu.findItem(R.id.action_feedtype)) != null) {
item.setVisible(!filter.isBasic() &&
EnumSet.of(FeedType.PROMOTED, FeedType.NEW, FeedType.PREMIUM).contains(feedType));
item.setTitle(switchFeedTypeTarget(filter) == FeedType.PROMOTED
? R.string.action_switch_to_top
: R.string.action_switch_to_new);
}
if ((item = menu.findItem(R.id.action_change_content_type)) != null) {
if (userService.isAuthorized()) {
ContentTypeDrawable icon = new ContentTypeDrawable(getActivity(), getSelectedContentType());
icon.setTextSize(getResources().getDimensionPixelSize(
R.dimen.feed_content_type_action_icon_text_size));
item.setIcon(icon);
item.setVisible(true);
updateContentTypeItems(menu);
} else {
item.setVisible(false);
}
}
MenuItem follow = menu.findItem(R.id.action_follow);
MenuItem unfollow = menu.findItem(R.id.action_unfollow);
MenuItem bookmark = menu.findItem(R.id.action_pin);
if (follow != null && unfollow != null && bookmark != null) {
// go to default state.
follow.setVisible(false);
unfollow.setVisible(false);
if (activeUsername != null) {
if (userService.isPremiumUser()) {
boolean following = followService.isFollowing(activeUsername);
follow.setVisible(!following);
unfollow.setVisible(following);
}
// never bookmark a user
bookmark.setVisible(false);
}
}
}
private FeedType switchFeedTypeTarget(FeedFilter filter) {
return filter.getFeedType() != FeedType.PROMOTED ? FeedType.PROMOTED : FeedType.NEW;
}
private void updateContentTypeItems(Menu menu) {
// only one content type selected?
boolean single = ContentType.withoutImplicit(settings.getContentType()).size() == 1;
Map<Integer, Boolean> types = ImmutableMap.<Integer, Boolean>builder()
.put(R.id.action_content_type_sfw, settings.getContentTypeSfw())
.put(R.id.action_content_type_nsfw, settings.getContentTypeNsfw())
.put(R.id.action_content_type_nsfl, settings.getContentTypeNsfl())
.build();
for (Map.Entry<Integer, Boolean> entry : types.entrySet()) {
MenuItem item = menu.findItem(entry.getKey());
if (item != null) {
item.setChecked(entry.getValue());
item.setEnabled(!single || !entry.getValue());
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Map<Integer, String> contentTypes = ImmutableMap.<Integer, String>builder()
.put(R.id.action_content_type_sfw, "pref_feed_type_sfw")
.put(R.id.action_content_type_nsfw, "pref_feed_type_nsfw")
.put(R.id.action_content_type_nsfl, "pref_feed_type_nsfl")
.build();
if (contentTypes.containsKey(item.getItemId())) {
boolean newState = !item.isChecked();
settings.edit()
.putBoolean(contentTypes.get(item.getItemId()), newState)
.apply();
// this applies the new content types and refreshes the menu.
recheckContentTypes();
return true;
}
return OptionMenuHelper.dispatch(this, item) || super.onOptionsItemSelected(item);
}
@OnOptionsItemSelected(R.id.action_feedtype)
public void switchFeedType() {
FeedFilter filter = getCurrentFilter();
filter = filter.withFeedType(switchFeedTypeTarget(filter));
((MainActionHandler) getActivity()).onFeedFilterSelected(filter, initialSearchViewState());
}
@OnOptionsItemSelected(R.id.action_refresh)
public void refreshWithIndicator() {
if (swipeRefreshLayout.isRefreshing())
return;
swipeRefreshLayout.setRefreshing(true);
swipeRefreshLayout.postDelayed(() -> {
resetToolbar();
loader.restart(Optional.absent());
}, 500);
}
@OnOptionsItemSelected(R.id.action_pin)
public void pinCurrentFeedFilter() {
// not bookmarkable anymore.
onBookmarkableStateChanged(false);
FeedFilter filter = getCurrentFilter();
String title = FeedFilterFormatter.format(getActivity(), filter).singleline();
((MainActionHandler) getActivity()).pinFeedFilter(filter, title);
}
@OnOptionsItemSelected(R.id.action_preload)
public void preloadCurrentFeed() {
if (AndroidUtility.isOnMobile(getActivity())) {
DialogBuilder.start(getActivity())
.content(R.string.preload_not_on_mobile)
.positive()
.show();
return;
}
Intent intent = PreloadService.newIntent(getActivity(), feedAdapter.getFeed().getItems());
getActivity().startService(intent);
Track.preloadCurrentFeed(feedAdapter.getFeed().getItems().size());
if (singleShotService.isFirstTime("preload_info_hint")) {
DialogBuilder.start(getActivity())
.content(R.string.preload_info_hint)
.positive()
.show();
}
}
@OnOptionsItemSelected(R.id.action_follow)
public void onFollowClicked() {
followService.follow(activeUsername)
.subscribeOn(BackgroundScheduler.instance())
.subscribe(Actions.empty(), Actions.empty());
}
@OnOptionsItemSelected(R.id.action_unfollow)
public void onUnfollowClicked() {
followService.unfollow(activeUsername)
.subscribeOn(BackgroundScheduler.instance())
.subscribe(Actions.empty(), Actions.empty());
}
public void performSearch(SearchOptionsView.SearchQuery query) {
hideSearchContainer();
FeedFilter current = getCurrentFilter();
FeedFilter filter = current.withTagsNoReset(query.combined());
// do nothing, if the filter did not change
if (equal(current, filter))
return;
ItemWithComment startAt = null;
if (query.combined().trim().matches("[1-9][0-9]{5,}|id:[0-9]+")) {
filter = filter.withTags("");
startAt = new ItemWithComment(Long.parseLong(
CharMatcher.digit().retainFrom(query.combined())), null);
}
Bundle searchQueryState = searchView.currentState();
((MainActionHandler) getActivity()).onFeedFilterSelected(filter, searchQueryState, startAt);
// store the term for later
if (query.queryTerm().trim().length() > 0) {
recentSearchesServices.storeTerm(query.queryTerm());
}
Track.search(query.combined());
}
private void onItemClicked(int idx, Optional<Long> commentId, Optional<ImageView> preview) {
// reset auto open.
autoOpenOnLoad = null;
Feed feed = feedAdapter.getFeed();
if (idx < 0 || idx >= feed.size())
return;
try {
PostPagerFragment fragment = PostPagerFragment.newInstance(feed, idx, commentId);
if (preview.isPresent()) {
// pass pixels info to target fragment.
Drawable image = preview.get().getDrawable();
FeedItem item = feed.at(idx);
fragment.setPreviewInfo(PreviewInfo.of(getContext(), item, image));
}
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.content, fragment)
.addToBackStack("Post" + idx)
.commit();
} catch (Exception error) {
logger.warn("Error while showing post", error);
}
}
/**
* Creates a new {@link FeedFragment} for the given feed type.
*
* @param feedFilter A query to use for getting data
* @return The type new fragment that can be shown now.
*/
public static FeedFragment newInstance(FeedFilter feedFilter,
@Nullable ItemWithComment start,
@Nullable Bundle searchQueryState) {
Bundle arguments = newArguments(feedFilter, true, start, searchQueryState);
FeedFragment fragment = new FeedFragment();
fragment.setArguments(arguments);
return fragment;
}
public static Bundle newArguments(FeedFilter feedFilter, boolean simpleMode,
@Nullable ItemWithComment start,
@Nullable Bundle searchQueryState) {
Bundle arguments = new Bundle();
arguments.putParcelable(ARG_FEED_FILTER, feedFilter);
arguments.putParcelable(ARG_FEED_START, start);
arguments.putBoolean(ARG_SIMPLE_MODE, simpleMode);
arguments.putBundle(ARG_SEARCH_QUERY_STATE, searchQueryState);
return arguments;
}
/**
* Gets the current filter from this feed.
*
* @return The filter this feed uses.
*/
@Override
public FeedFilter getCurrentFilter() {
if (feedAdapter == null)
return new FeedFilter();
return feedAdapter.getFilter();
}
boolean isSeen(FeedItem item) {
return seenService.isSeen(item);
}
private void createRecyclerViewClickListener() {
RecyclerItemClickListener listener = new RecyclerItemClickListener(getActivity(), recyclerView);
listener.itemClicked()
.map(FeedFragment::extractFeedItemHolder)
.filter(isNotNull())
.subscribe(holder -> onItemClicked(holder.index, absent(), of(holder.image)));
listener.itemLongClicked()
.map(FeedFragment::extractFeedItemHolder)
.filter(isNotNull())
.subscribe(holder -> openQuickPeek(holder.item));
listener.itemLongClickEnded().subscribe(event -> dismissPopupPlayer());
settings.change()
.compose(bindToLifecycle())
.startWith("")
.subscribe(key -> listener.enableLongClick(settings.enableQuickPeek()));
}
private void openQuickPeek(FeedItem item) {
// check that the activity is not zero. Might happen, as this method might
// get called shortly after detaching the activity - which sucks. thanks android.
Activity activity = getActivity();
if (activity != null) {
this.quickPeekDialog = new WeakReference<>(
PopupPlayer.newInstance(activity, item));
swipeRefreshLayout.setEnabled(false);
Track.quickPeek();
}
}
@Nullable
private static FeedItemViewHolder extractFeedItemHolder(View view) {
Object tag = view.getTag();
return tag instanceof FeedItemViewHolder ? (FeedItemViewHolder) tag : null;
}
private void dismissPopupPlayer() {
swipeRefreshLayout.setEnabled(true);
Dialog quickPeek = quickPeekDialog.get();
if (quickPeek != null)
quickPeek.dismiss();
}
private static class FeedAdapter extends RecyclerView.Adapter<FeedItemViewHolder> implements Feed.FeedListener {
private final boolean usersFavorites;
private final WeakReference<FeedFragment> parent;
private final Feed feed;
FeedAdapter(FeedFragment fragment, Feed feed, boolean usersFavorites) {
this.usersFavorites = usersFavorites;
this.parent = new WeakReference<>(fragment);
this.feed = feed;
this.feed.setFeedListener(this);
setHasStableIds(true);
}
private void with(Action1<FeedFragment> action) {
FeedFragment fragment = parent.get();
if (fragment != null) {
action.call(fragment);
}
}
public FeedFilter getFilter() {
return feed.getFeedFilter();
}
public Feed getFeed() {
return feed;
}
@SuppressLint("InflateParams")
@Override
public FeedItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(this.parent.get().getActivity());
View view = inflater.inflate(R.layout.feed_item_view, null);
return new FeedItemViewHolder(view);
}
@Override
public void onBindViewHolder(FeedItemViewHolder holder,
@SuppressLint("RecyclerView") int position) {
FeedItem item = feed.at(position);
with(fragment -> {
Uri imageUri = UriHelper.of(fragment.getContext()).thumbnail(item);
fragment.picasso.load(imageUri)
.config(Bitmap.Config.RGB_565)
.placeholder(new ColorDrawable(0xff333333))
.into(holder.image);
holder.itemView.setTag(holder);
holder.index = position;
holder.item = item;
// show preload-badge
holder.setIsPreloaded(fragment.preloadManager.exists(item.id()));
// check if this item was already seen.
if (fragment.inMemoryCacheService.isRepost(item.id())) {
holder.setIsRepost();
} else if (fragment.seenIndicatorStyle == IndicatorStyle.ICON
&& !usersFavorites && fragment.isSeen(item)) {
holder.setIsSeen();
} else {
holder.clear();
}
});
}
@Override
public int getItemCount() {
return feed.size();
}
@Override
public long getItemId(int position) {
return feed.at(position).id();
}
Set<ContentType> getContentType() {
return feed.getContentType();
}
@Override
public void onNewItems(List<FeedItem> newItems) {
// check if we prepended items to the list.
int prependCount = 0;
for (int idx = 0; idx < newItems.size(); idx++) {
if (newItems.get(idx).id() == getItemId(idx)) {
prependCount++;
}
}
if (prependCount == 0) {
notifyDataSetChanged();
} else {
notifyItemRangeInserted(0, prependCount);
}
// load meta data for the items.
with(fragment -> {
if (newItems.size() > 0) {
FeedItem mostRecentItem = Ordering.natural()
.onResultOf((Function<FeedItem, Long>) FeedItem::id)
.min(newItems);
fragment.refreshRepostInfos(mostRecentItem.id(), feed.getFeedFilter());
}
fragment.performAutoOpen();
});
}
@Override
public void onRemoveItems() {
notifyDataSetChanged();
}
@Override
public void onWrongContentType() {
with(FeedFragment::showWrongContentTypeInfo);
}
}
void showWrongContentTypeInfo() {
Context context = getActivity();
if (context != null) {
DialogBuilder.start(context)
.content(R.string.hint_wrong_content_type)
.positive()
.show();
}
}
void refreshRepostInfos(long id, FeedFilter filter) {
if (filter.getFeedType() != FeedType.NEW && filter.getFeedType() != FeedType.PROMOTED)
return;
// check if it is possible to get repost info.
boolean queryTooLong = filter.getTags().or("").split("\\s+").length >= 5;
if (queryTooLong)
return;
FeedService.FeedQuery query = ImmutableFeedQuery.builder()
.contentTypes(getSelectedContentType())
.older(id)
.feedFilter(filter.withTags(filter.getTags().transform(tags -> tags + " repost").or("repost")))
.build();
InMemoryCacheService cacheService = this.inMemoryCacheService;
WeakReference<FeedFragment> fragment = new WeakReference<>(this);
feedService.getFeedItems(query)
.subscribeOn(BackgroundScheduler.instance())
.observeOn(mainThread())
.subscribe(items -> {
if (items.getItems().size() > 0) {
List<Long> ids = Lists.transform(items.getItems(), Api.Feed.Item::getId);
cacheService.cacheReposts(ids);
// update feed adapter to show new 'repost' badges.
FeedFragment frm = fragment.get();
if (frm != null) {
frm.feedAdapter.notifyDataSetChanged();
}
}
}, Actions.empty());
}
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
void onFeedError(Throwable error) {
logger.error("Error loading the feed", error);
if (autoOpenOnLoad != null) {
ErrorDialogFragment.showErrorString(getFragmentManager(),
getString(R.string.could_not_load_feed_nsfw));
} else if (error instanceof JsonSyntaxException) {
// show a special error
ErrorDialogFragment.showErrorString(getFragmentManager(),
getString(R.string.could_not_load_feed_json));
} else if (Throwables.getRootCause(error) instanceof ConnectException && settings.useHttps()) {
ErrorDialogFragment.showErrorString(getFragmentManager(),
getString(R.string.could_not_load_feed_https));
} else {
ErrorDialogFragment.defaultOnError().call(error);
}
}
/**
* Called when loading of feed data finished.
*/
void onFeedLoadFinished() {
removeBusyIndicator();
swipeRefreshLayout.setRefreshing(false);
updateNoResultsTextView();
}
private void updateNoResultsTextView() {
boolean empty = feedAdapter.getItemCount() == 0;
noResultsView.setVisibility(empty ? View.VISIBLE : View.GONE);
}
@OnOptionsItemSelected(R.id.action_search)
public void resetAndShowSearchContainer() {
searchView.applyState(initialSearchViewState());
showSearchContainer(true);
}
private void showSearchContainer(boolean animated) {
if (searchContainerIsVisible())
return;
View view = getView();
if (view == null)
return;
view.post(this::hideToolbar);
// prepare search view
String typeName = feedTypeToString(getContext(), getCurrentFilter().withTagsNoReset("dummy"));
searchView.setQueryHint(getString(R.string.action_search, typeName));
searchView.setPadding(0, AndroidUtility.getStatusBarHeight(getContext()), 0, 0);
searchContainer.setVisibility(View.VISIBLE);
if (animated) {
searchContainer.setAlpha(0.f);
searchContainer.animate()
.setListener(endAction(searchView::requestSearchFocus))
.alpha(1);
searchView.setTranslationY(-(int) (0.1 * view.getHeight()));
searchView.animate()
.setInterpolator(new DecelerateInterpolator())
.translationY(0);
} else {
searchContainer.animate().cancel();
searchContainer.setAlpha(1.f);
searchView.animate().cancel();
searchView.setTranslationY(0);
}
}
@Override
public boolean onBackButton() {
if (searchContainerIsVisible()) {
hideSearchContainer();
return true;
}
return false;
}
public boolean searchContainerIsVisible() {
return searchContainer != null && searchContainer.getVisibility() != View.GONE;
}
void hideSearchContainer() {
if (!searchContainerIsVisible())
return;
searchContainer.animate()
.setListener(hideViewOnAnimationEnd(searchContainer))
.alpha(0);
searchView.animate().translationY(-(int) (0.1 * getView().getHeight()));
resetToolbar();
AndroidUtility.hideSoftKeyboard(searchView);
}
@SuppressWarnings("CodeBlock2Expr")
void performAutoOpen() {
Feed feed = feedAdapter.getFeed();
if (autoScrollOnLoad != null) {
ifPresent(findItemIndexById(autoScrollOnLoad), idx -> {
// over scroll a bit
int scrollTo = Math.max(idx + getThumbnailColumns(), 0);
recyclerView.scrollToPosition(scrollTo);
});
}
if (autoOpenOnLoad != null) {
ifPresent(feed.indexOf(autoOpenOnLoad.getItemId()), idx -> {
onItemClicked(idx, autoOpenOnLoad.getCommentId(), absent());
});
}
autoScrollOnLoad = null;
}
/**
* Returns the item id of the index in the recycler views adapter.
*/
private Optional<Integer> findItemIndexById(long id) {
int offset = ((MergeRecyclerAdapter) recyclerView.getAdapter()).getOffset(feedAdapter).or(0);
// look for the index of the item with the given id
return FluentIterable
.from(feedAdapter.getFeed().getItems())
.firstMatch(item -> item.id() == id)
.transform(item -> feedAdapter.getFeed().indexOf(item).or(-1))
.transform(idx -> idx + offset);
}
Optional<GridLayoutManager> getRecyclerViewLayoutManager() {
if (recyclerView == null)
return absent();
return Optional.fromNullable((GridLayoutManager) recyclerView.getLayoutManager());
}
private boolean isSelfInfo(Api.Info info) {
return info.getUser().getName().equalsIgnoreCase(userService.getName().orNull());
}
private final RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (scrollToolbar && getActivity() instanceof ToolbarActivity) {
ToolbarActivity activity = (ToolbarActivity) getActivity();
activity.getScrollHideToolbarListener().onScrolled(dy);
}
ifPresent(getRecyclerViewLayoutManager(), layoutManager -> {
if (loader.isLoading())
return;
Feed feed = feedAdapter.getFeed();
int totalItemCount = layoutManager.getItemCount();
if (dy > 0 && !feed.isAtEnd()) {
int lastVisibleItem = layoutManager.findLastVisibleItemPosition();
if (totalItemCount > 12 && lastVisibleItem >= totalItemCount - 12) {
logger.info("Request next page now");
loader.next();
}
}
if (dy < 0 && !feed.isAtStart()) {
int firstVisibleItem = layoutManager.findFirstVisibleItemPosition();
if (totalItemCount > 12 && firstVisibleItem < 12) {
logger.info("Request previous page now");
loader.previous();
}
}
});
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
if (getActivity() instanceof ToolbarActivity) {
int y = estimateRecyclerViewScrollY(recyclerView).or(Integer.MAX_VALUE);
ToolbarActivity activity = (ToolbarActivity) getActivity();
activity.getScrollHideToolbarListener().onScrollFinished(y);
}
}
}
};
}
| Fix wrong screen being tracked for feed.
| app/src/main/java/com/pr0gramm/app/ui/fragments/FeedFragment.java | Fix wrong screen being tracked for feed. | <ide><path>pp/src/main/java/com/pr0gramm/app/ui/fragments/FeedFragment.java
<ide> public void onResume() {
<ide> super.onResume();
<ide>
<del> Track.screen("Item");
<add> Track.screen("Feed");
<ide>
<ide> // check if we should show the pin button or not.
<ide> if (settings.showPinButton()) { |
|
Java | mit | eec3c911c056e3870f4568b5de75261922bf6447 | 0 | latteacocoa/MyDemo,latteacocoa/MyDemo | Java解答例/ABC049C.java | /**
*
*/
package myAtCoder;
import java.util.Scanner;
/**
* @author
*
*/
public class ABC049C {
/**
* @param args
*/
public static void main(String[] args) {
// 標準入力取得用オブジェクト **********
Scanner wScan = new Scanner(System.in);
// 標準入力より値を取得 **********
String wInStringS = wScan.next();
wScan.close();
// 出力情報を生成し出力 **********
String wStringT = "";
// チェックキーワードを優先順に格納したコレクション(最終値 null はbreak条件)
String[] wCheckValues = {"eraser", "erase", "dreamer", "dream", null};
// 文字列Sの後方からキーワード終わりかを判定する
// キーワードがnull(=該当無し)の場合,即座にチェックを終了
boolean wIsCheackBreak = false;
while (wInStringS.length() > wStringT.length() && !wIsCheackBreak) {
for (String wCheckValue : wCheckValues) {
if (wCheckValue == null) {
wIsCheackBreak = true;
break;
}
if (wInStringS.endsWith(wCheckValue + wStringT)) {
wStringT = wCheckValue + wStringT;
break;
}
}
}
System.out.println(wInStringS.equals(wStringT) ? "YES" : "NO");
}
}
| Delete ABC049C.java | Java解答例/ABC049C.java | Delete ABC049C.java | <ide><path>ava解答例/ABC049C.java
<del>/**
<del> *
<del> */
<del>package myAtCoder;
<del>
<del>import java.util.Scanner;
<del>
<del>/**
<del> * @author
<del> *
<del> */
<del>public class ABC049C {
<del>
<del> /**
<del> * @param args
<del> */
<del> public static void main(String[] args) {
<del> // 標準入力取得用オブジェクト **********
<del> Scanner wScan = new Scanner(System.in);
<del>
<del> // 標準入力より値を取得 **********
<del> String wInStringS = wScan.next();
<del> wScan.close();
<del>
<del> // 出力情報を生成し出力 **********
<del> String wStringT = "";
<del> // チェックキーワードを優先順に格納したコレクション(最終値 null はbreak条件)
<del> String[] wCheckValues = {"eraser", "erase", "dreamer", "dream", null};
<del>
<del> // 文字列Sの後方からキーワード終わりかを判定する
<del> // キーワードがnull(=該当無し)の場合,即座にチェックを終了
<del> boolean wIsCheackBreak = false;
<del> while (wInStringS.length() > wStringT.length() && !wIsCheackBreak) {
<del>
<del> for (String wCheckValue : wCheckValues) {
<del>
<del> if (wCheckValue == null) {
<del> wIsCheackBreak = true;
<del> break;
<del> }
<del>
<del> if (wInStringS.endsWith(wCheckValue + wStringT)) {
<del> wStringT = wCheckValue + wStringT;
<del> break;
<del> }
<del> }
<del> }
<del>
<del> System.out.println(wInStringS.equals(wStringT) ? "YES" : "NO");
<del> }
<del>} |
||
Java | apache-2.0 | c316325526e8889d3f0e2e323d2de98dcde3fda0 | 0 | intentionet/batfish,batfish/batfish,dhalperi/batfish,intentionet/batfish,batfish/batfish,arifogel/batfish,dhalperi/batfish,intentionet/batfish,batfish/batfish,intentionet/batfish,arifogel/batfish,dhalperi/batfish,intentionet/batfish,arifogel/batfish | package org.batfish.main;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.batfish.common.BfConsts;
import org.batfish.common.CoordConsts;
public class Settings {
private static final String ARG_ACCEPT_NODE = "acceptnode";
private static final String ARG_ANONYMIZE = "anonymize";
private static final String ARG_AUTO_BASE_DIR = "autobasedir";
private static final String ARG_BLACK_HOLE = "blackhole";
private static final String ARG_BLACK_HOLE_PATH = "blackholepath";
private static final String ARG_BLACKLIST_DST_IP_PATH = "blacklistdstippath";
private static final String ARG_BLACKLIST_INTERFACE = "blint";
private static final String ARG_BLACKLIST_NODE = "blnode";
private static final String ARG_BUILD_PREDICATE_INFO = "bpi";
private static final String ARG_CB_HOST = "lbhost";
private static final String ARG_CB_PORT = "lbport";
private static final String ARG_COMPILE = "compile";
private static final String ARG_CONC_UNIQUE = "concunique";
private static final String ARG_COORDINATOR_HOST = "coordinatorhost";
private static final String ARG_COORDINATOR_POOL_PORT = "coordinatorpoolport";
private static final String ARG_COORDINATOR_WORK_PORT = "coordinatorworkport";
private static final String ARG_COUNT = "count";
private static final String ARG_DATA_PLANE = "dp";
private static final String ARG_DATA_PLANE_DIR = "dpdir";
private static final String ARG_DISABLE_Z3_SIMPLIFICATION = "nosimplify";
private static final String ARG_DISABLED_FACTS = "disablefacts";
private static final String ARG_DUMP_CONTROL_PLANE_FACTS = "dumpcp";
private static final String ARG_DUMP_FACTS_DIR = "dumpdir";
private static final String ARG_DUMP_IF = "dumpif";
private static final String ARG_DUMP_IF_DIR = "dumpifdir";
private static final String ARG_DUMP_INTERFACE_DESCRIPTIONS = "id";
private static final String ARG_DUMP_INTERFACE_DESCRIPTIONS_PATH = "idpath";
private static final String ARG_DUMP_TRAFFIC_FACTS = "dumptraffic";
private static final String ARG_DUPLICATE_ROLE_FLOWS = "drf";
private static final String ARG_ENVIRONMENT_NAME = "env";
private static final String ARG_EXIT_ON_PARSE_ERROR = "ee";
private static final String ARG_FACTS = "facts";
private static final String ARG_FLATTEN = "flatten";
private static final String ARG_FLATTEN_DESTINATION = "flattendst";
private static final String ARG_FLATTEN_ON_THE_FLY = "flattenonthefly";
private static final String ARG_FLATTEN_SOURCE = "flattensrc";
private static final String ARG_FLOW_PATH = "flowpath";
private static final String ARG_FLOW_SINK_PATH = "flowsink";
private static final String ARG_FLOWS = "flow";
private static final String ARG_GEN_OSPF = "genospf";
private static final String ARG_GENERATE_STUBS = "gs";
private static final String ARG_GENERATE_STUBS_INPUT_ROLE = "gsinputrole";
private static final String ARG_GENERATE_STUBS_INTERFACE_DESCRIPTION_REGEX = "gsidregex";
private static final String ARG_GENERATE_STUBS_REMOTE_AS = "gsremoteas";
private static final String ARG_GUI = "gui";
private static final String ARG_HELP = "help";
private static final String ARG_HISTOGRAM = "histogram";
private static final String ARG_IGNORE_UNSUPPORTED = "ignoreunsupported";
private static final String ARG_INTERFACE_MAP_PATH = "impath";
private static final String ARG_LB_WEB_ADMIN_PORT = "lbwebadminport";
private static final String ARG_LB_WEB_PORT = "lbwebport";
private static final String ARG_LOG_FILE = "logfile";
private static final String ARG_LOG_LEVEL = "loglevel";
private static final String ARG_LOGICDIR = "logicdir";
private static final String ARG_MPI = "mpi";
private static final String ARG_MPI_PATH = "mpipath";
private static final String ARG_NO_TRAFFIC = "notraffic";
private static final String ARG_NODE_ROLES_PATH = "nrpath";
private static final String ARG_NODE_SET_PATH = "nodes";
private static final String ARG_PARSE_PARALLEL = "parseparallel";
private static final String ARG_PEDANTIC_AS_ERROR = "pedanticerror";
private static final String ARG_PEDANTIC_SUPPRESS = "pedanticsuppress";
private static final String ARG_PREDHELP = "predhelp";
private static final String ARG_PREDICATES = "predicates";
private static final String ARG_PRINT_PARSE_TREES = "ppt";
private static final String ARG_QUERY = "query";
private static final String ARG_QUERY_ALL = "all";
private static final String ARG_REACH = "reach";
private static final String ARG_REACH_PATH = "reachpath";
private static final String ARG_RED_FLAG_AS_ERROR = "redflagerror";
private static final String ARG_RED_FLAG_SUPPRESS = "redflagsuppress";
private static final String ARG_REDIRECT_STDERR = "redirect";
private static final String ARG_REMOVE_FACTS = "remove";
private static final String ARG_REVERT = "revert";
private static final String ARG_ROLE_HEADERS = "rh";
private static final String ARG_ROLE_NODES_PATH = "rnpath";
private static final String ARG_ROLE_REACHABILITY_QUERY = "rr";
private static final String ARG_ROLE_REACHABILITY_QUERY_PATH = "rrpath";
private static final String ARG_ROLE_SET_PATH = "rspath";
private static final String ARG_ROLE_TRANSIT_QUERY = "rt";
private static final String ARG_ROLE_TRANSIT_QUERY_PATH = "rtpath";
private static final String ARG_SERIALIZE_INDEPENDENT = "si";
private static final String ARG_SERIALIZE_INDEPENDENT_PATH = "sipath";
private static final String ARG_SERIALIZE_TO_TEXT = "stext";
private static final String ARG_SERIALIZE_VENDOR = "sv";
private static final String ARG_SERIALIZE_VENDOR_PATH = "svpath";
private static final String ARG_SERVICE_HOST = "servicehost";
private static final String ARG_SERVICE_LOGICBLOX_HOSTNAME = "servicelbhostname";
private static final String ARG_SERVICE_MODE = "servicemode";
private static final String ARG_SERVICE_PORT = "serviceport";
private static final String ARG_SERVICE_URL = "serviceurl";
private static final String ARG_TEST_RIG_PATH = "testrig";
private static final String ARG_THROW_ON_LEXER_ERROR = "throwlexer";
private static final String ARG_THROW_ON_PARSER_ERROR = "throwparser";
private static final String ARG_TIMESTAMP = "timestamp";
private static final String ARG_UNIMPLEMENTED_AS_ERROR = "unimplementederror";
private static final String ARG_UNIMPLEMENTED_SUPPRESS = "unimplementedsuppress";
private static final String ARG_UPDATE = "update";
private static final String ARG_VAR_SIZE_MAP_PATH = "vsmpath";
private static final String ARG_WORKSPACE = "workspace";
private static final String ARG_Z3 = "z3";
private static final String ARG_Z3_CONCRETIZE = "conc";
private static final String ARG_Z3_CONCRETIZER_INPUT_FILES = "concin";
private static final String ARG_Z3_CONCRETIZER_NEGATED_INPUT_FILES = "concinneg";
private static final String ARG_Z3_CONCRETIZER_OUTPUT_FILE = "concout";
private static final String ARG_Z3_OUTPUT = "z3path";
private static final String ARGNAME_ACCEPT_NODE = "node";
private static final String ARGNAME_ANONYMIZE = "path";
private static final String ARGNAME_AUTO_BASE_DIR = "path";
private static final String ARGNAME_BLACK_HOLE_PATH = "path";
private static final String ARGNAME_BLACKLIST_DST_IP = "ip";
private static final String ARGNAME_BLACKLIST_INTERFACE = "node,interface";
private static final String ARGNAME_BLACKLIST_NODE = "node";
private static final String ARGNAME_BUILD_PREDICATE_INFO = "path";
private static final String ARGNAME_COORDINATOR_HOST = "hostname";
private static final String ARGNAME_DATA_PLANE_DIR = "path";
private static final String ARGNAME_DUMP_FACTS_DIR = "path";
private static final String ARGNAME_DUMP_IF_DIR = "path";
private static final String ARGNAME_DUMP_INTERFACE_DESCRIPTIONS_PATH = "path";
private static final String ARGNAME_ENVIRONMENT_NAME = "name";
private static final String ARGNAME_FLATTEN_DESTINATION = "path";
private static final String ARGNAME_FLATTEN_SOURCE = "path";
private static final String ARGNAME_FLOW_PATH = "path";
private static final String ARGNAME_FLOW_SINK_PATH = "path";
private static final String ARGNAME_GEN_OSPF = "path";
private static final String ARGNAME_GENERATE_STUBS_INPUT_ROLE = "role";
private static final String ARGNAME_GENERATE_STUBS_INTERFACE_DESCRIPTION_REGEX = "java-regex";
private static final String ARGNAME_GENERATE_STUBS_REMOTE_AS = "as";
private static final String ARGNAME_INTERFACE_MAP_PATH = "path";
private static final String ARGNAME_LB_WEB_ADMIN_PORT = "port";
private static final String ARGNAME_LB_WEB_PORT = "port";
private static final String ARGNAME_LOG_FILE = "path";
private static final String ARGNAME_LOG_LEVEL = "level";
private static final String ARGNAME_LOGICDIR = "path";
private static final String ARGNAME_MPI_PATH = "path";
private static final String ARGNAME_NODE_ROLES_PATH = "path";
private static final String ARGNAME_NODE_SET_PATH = "path";
private static final String ARGNAME_QUESTION_NAME = "name";
private static final String ARGNAME_REACH_PATH = "path";
private static final String ARGNAME_REVERT = "branch-name";
private static final String ARGNAME_ROLE_NODES_PATH = "path";
private static final String ARGNAME_ROLE_REACHABILITY_QUERY_PATH = "path";
private static final String ARGNAME_ROLE_SET_PATH = "path";
private static final String ARGNAME_ROLE_TRANSIT_QUERY_PATH = "path";
private static final String ARGNAME_SERIALIZE_INDEPENDENT_PATH = "path";
private static final String ARGNAME_SERIALIZE_VENDOR_PATH = "path";
private static final String ARGNAME_SERVICE_HOST = "hostname";
private static final String ARGNAME_SERVICE_LOGICBLOX_HOSTNAME = "hostname";
private static final String ARGNAME_VAR_SIZE_MAP_PATH = "path";
private static final String ARGNAME_Z3_CONCRETIZER_INPUT_FILES = "paths";
private static final String ARGNAME_Z3_CONCRETIZER_NEGATED_INPUT_FILES = "paths";
private static final String ARGNAME_Z3_CONCRETIZER_OUTPUT_FILE = "path";
private static final String ARGNAME_Z3_OUTPUT = "path";
public static final String DEFAULT_CONNECTBLOX_ADMIN_PORT = "55181";
public static final String DEFAULT_CONNECTBLOX_HOST = "localhost";
public static final String DEFAULT_CONNECTBLOX_REGULAR_PORT = "55179";
private static final String DEFAULT_DUMP_IF_DIR = "if";
private static final String DEFAULT_DUMP_INTERFACE_DESCRIPTIONS_PATH = "interface_descriptions";
private static final String DEFAULT_FLOW_PATH = "flows";
private static final String DEFAULT_LB_WEB_ADMIN_PORT = "55183";
private static final String DEFAULT_LB_WEB_PORT = "8080";
private static final String DEFAULT_LOG_LEVEL = "debug";
private static final List<String> DEFAULT_PREDICATES = Collections
.singletonList("InstalledRoute");
private static final String DEFAULT_SERIALIZE_INDEPENDENT_PATH = "serialized-independent-configs";
private static final String DEFAULT_SERIALIZE_VENDOR_PATH = "serialized-vendor-configs";
private static final String DEFAULT_SERVICE_PORT = BfConsts.SVC_PORT
.toString();
private static final String DEFAULT_SERVICE_URL = "http://0.0.0.0";
private static final String DEFAULT_TEST_RIG_PATH = "default_test_rig";
private static final boolean DEFAULT_Z3_SIMPLIFY = true;
private static final String EXECUTABLE_NAME = "batfish";
private String _acceptNode;
private boolean _anonymize;
private String _anonymizeDir;
private boolean _answer;
private String _autoBaseDir;
private boolean _blackHole;
private String _blackHolePath;
private String _blacklistDstIpPath;
private String _blacklistInterface;
private String _blacklistNode;
private boolean _buildPredicateInfo;
private boolean _canExecute;
private String _cbHost;
private int _cbPort;
private boolean _compile;
private boolean _concretize;
private String[] _concretizerInputFilePaths;
private String _concretizerOutputFilePath;
private boolean _concUnique;
private String _coordinatorHost;
private int _coordinatorPoolPort;
private int _coordinatorWorkPort;
private boolean _counts;
private boolean _dataPlane;
private String _dataPlaneDir;
private Set<String> _disabledFacts;
private boolean _dumpControlPlaneFacts;
private String _dumpFactsDir;
private boolean _dumpIF;
private String _dumpIFDir;
private boolean _dumpInterfaceDescriptions;
private String _dumpInterfaceDescriptionsPath;
private boolean _dumpTrafficFacts;
private boolean _duplicateRoleFlows;
private String _environmentName;
private boolean _exitOnParseError;
private boolean _facts;
private boolean _flatten;
private String _flattenDestination;
private boolean _flattenOnTheFly;
private String _flattenSource;
private String _flowPath;
private boolean _flows;
private String _flowSinkPath;
private boolean _generateStubs;
private String _generateStubsInputRole;
private String _generateStubsInterfaceDescriptionRegex;
private Integer _generateStubsRemoteAs;
private boolean _genMultipath;
private String _genOspfTopology;
private List<String> _helpPredicates;
private boolean _histogram;
private String _hsaInputDir;
private String _hsaOutputDir;
private boolean _ignoreUnsupported;
private String _interfaceMapPath;
private String _jobLogicBloxHostnamePath;
private int _lbWebAdminPort;
private int _lbWebPort;
private String _logFile;
private BatfishLogger _logger;
private String _logicDir;
private String _logicSrcDir;
private String _logLevel;
private String _mpiPath;
private String[] _negatedConcretizerInputFilePaths;
private String _nodeRolesPath;
private String _nodeSetPath;
private boolean _noTraffic;
private Options _options;
private boolean _parseParallel;
private boolean _pedanticAsError;
private boolean _pedanticRecord;
private boolean _postFlows;
private List<String> _predicates;
private boolean _printParseTree;
private boolean _printSemantics;
private boolean _query;
private boolean _queryAll;
private String _queryDumpDir;
private String _questionName;
private String _questionPath;
private boolean _reach;
private String _reachPath;
private boolean _redFlagAsError;
private boolean _redFlagRecord;
private boolean _redirectStdErr;
private boolean _removeFacts;
private boolean _revert;
private String _revertBranchName;
private boolean _roleHeaders;
private String _roleNodesPath;
private boolean _roleReachabilityQuery;
private String _roleReachabilityQueryPath;
private String _roleSetPath;
private boolean _roleTransitQuery;
private String _roleTransitQueryPath;
private boolean _runInServiceMode;
private boolean _serializeIndependent;
private String _serializeIndependentPath;
private boolean _serializeToText;
private boolean _serializeVendor;
private String _serializeVendorPath;
private String _serviceHost;
private String _serviceLogicBloxHostname;
private int _servicePort;
private String _serviceUrl;
private boolean _simplify;
private String _testRigPath;
private boolean _throwOnLexerError;
private boolean _throwOnParserError;
private boolean _timestamp;
private String _trafficFactDumpDir;
private boolean _unimplementedAsError;
private boolean _unimplementedRecord;
private boolean _update;
private String _varSizeMapPath;
private String _workspaceName;
private boolean _z3;
private String _z3File;
public Settings() throws ParseException {
this(new String[] {});
}
public Settings(String[] args) throws ParseException {
initOptions();
parseCommandLine(args);
}
public boolean canExecute() {
return _canExecute;
}
public boolean concretizeUnique() {
return _concUnique;
}
public boolean createWorkspace() {
return _compile;
}
public boolean dumpInterfaceDescriptions() {
return _dumpInterfaceDescriptions;
}
public boolean duplicateRoleFlows() {
return _duplicateRoleFlows;
}
public boolean exitOnParseError() {
return _exitOnParseError;
}
public boolean flattenOnTheFly() {
return _flattenOnTheFly;
}
public String getAcceptNode() {
return _acceptNode;
}
public boolean getAnonymize() {
return _anonymize;
}
public String getAnonymizeDir() {
return _anonymizeDir;
}
public boolean getAnswer() {
return _answer;
}
public String getAutoBaseDir() {
return _autoBaseDir;
}
public String getBlackHoleQueryPath() {
return _blackHolePath;
}
public String getBlacklistDstIpPath() {
return _blacklistDstIpPath;
}
public String getBlacklistInterfaceString() {
return _blacklistInterface;
}
public String getBlacklistNode() {
return _blacklistNode;
}
public String getBranchName() {
return _revertBranchName;
}
public boolean getBuildPredicateInfo() {
return _buildPredicateInfo;
}
public boolean getConcretize() {
return _concretize;
}
public String[] getConcretizerInputFilePaths() {
return _concretizerInputFilePaths;
}
public String getConcretizerOutputFilePath() {
return _concretizerOutputFilePath;
}
public String getConnectBloxHost() {
return _cbHost;
}
public int getConnectBloxPort() {
return _cbPort;
}
public String getCoordinatorHost() {
return _coordinatorHost;
}
public int getCoordinatorPoolPort() {
return _coordinatorPoolPort;
}
public int getCoordinatorWorkPort() {
return _coordinatorWorkPort;
}
public boolean getCountsOnly() {
return _counts;
}
public boolean getDataPlane() {
return _dataPlane;
}
public String getDataPlaneDir() {
return _dataPlaneDir;
}
public Set<String> getDisabledFacts() {
return _disabledFacts;
}
public boolean getDumpControlPlaneFacts() {
return _dumpControlPlaneFacts;
}
public String getDumpFactsDir() {
return _dumpFactsDir;
}
public String getDumpIFDir() {
return _dumpIFDir;
}
public String getDumpInterfaceDescriptionsPath() {
return _dumpInterfaceDescriptionsPath;
}
public boolean getDumpTrafficFacts() {
return _dumpTrafficFacts;
}
public String getEnvironmentName() {
return _environmentName;
}
public boolean getFacts() {
return _facts;
}
public boolean getFlatten() {
return _flatten;
}
public String getFlattenDestination() {
return _flattenDestination;
}
public String getFlattenSource() {
return _flattenSource;
}
public String getFlowPath() {
return _flowPath;
}
public boolean getFlows() {
return _flows;
}
public String getFlowSinkPath() {
return _flowSinkPath;
}
public boolean getGenerateMultipathInconsistencyQuery() {
return _genMultipath;
}
public String getGenerateOspfTopologyPath() {
return _genOspfTopology;
}
public boolean getGenerateStubs() {
return _generateStubs;
}
public String getGenerateStubsInputRole() {
return _generateStubsInputRole;
}
public String getGenerateStubsInterfaceDescriptionRegex() {
return _generateStubsInterfaceDescriptionRegex;
}
public int getGenerateStubsRemoteAs() {
return _generateStubsRemoteAs;
}
public List<String> getHelpPredicates() {
return _helpPredicates;
}
public boolean getHistogram() {
return _histogram;
}
public String getHSAInputPath() {
return _hsaInputDir;
}
public String getHSAOutputPath() {
return _hsaOutputDir;
}
public boolean getInterfaceFailureInconsistencyBlackHoleQuery() {
return _blackHole;
}
public boolean getInterfaceFailureInconsistencyReachableQuery() {
return _reach;
}
public String getInterfaceMapPath() {
return _interfaceMapPath;
}
public String getJobLogicBloxHostnamePath() {
return _jobLogicBloxHostnamePath;
}
public int getLbWebAdminPort() {
return _lbWebAdminPort;
}
public int getLbWebPort() {
return _lbWebPort;
}
public String getLogFile() {
return _logFile;
}
public BatfishLogger getLogger() {
return _logger;
}
public String getLogicDir() {
return _logicDir;
}
public String getLogicSrcDir() {
return _logicSrcDir;
}
public String getLogLevel() {
return _logLevel;
}
public String getMultipathInconsistencyQueryPath() {
return _mpiPath;
}
public String[] getNegatedConcretizerInputFilePaths() {
return _negatedConcretizerInputFilePaths;
}
public String getNodeRolesPath() {
return _nodeRolesPath;
}
public String getNodeSetPath() {
return _nodeSetPath;
}
public boolean getNoTraffic() {
return _noTraffic;
}
public boolean getParseParallel() {
return _parseParallel;
}
public boolean getPedanticAsError() {
return _pedanticAsError;
}
public boolean getPedanticRecord() {
return _pedanticRecord;
}
public boolean getPostFlows() {
return _postFlows;
}
public List<String> getPredicates() {
return _predicates;
}
public boolean getPrintSemantics() {
return _printSemantics;
}
public boolean getQuery() {
return _query;
}
public boolean getQueryAll() {
return _queryAll;
}
public String getQueryDumpDir() {
return _queryDumpDir;
}
public String getQuestionName() {
return _questionName;
}
public String getQuestionPath() {
return _questionPath;
}
public String getReachableQueryPath() {
return _reachPath;
}
public boolean getRedFlagAsError() {
return _redFlagAsError;
}
public boolean getRedFlagRecord() {
return _redFlagRecord;
}
public boolean getRemoveFacts() {
return _removeFacts;
}
public boolean getRoleHeaders() {
return _roleHeaders;
}
public String getRoleNodesPath() {
return _roleNodesPath;
}
public boolean getRoleReachabilityQuery() {
return _roleReachabilityQuery;
}
public String getRoleReachabilityQueryPath() {
return _roleReachabilityQueryPath;
}
public String getRoleSetPath() {
return _roleSetPath;
}
public boolean getRoleTransitQuery() {
return _roleTransitQuery;
}
public String getRoleTransitQueryPath() {
return _roleTransitQueryPath;
}
public boolean getSerializeIndependent() {
return _serializeIndependent;
}
public String getSerializeIndependentPath() {
return _serializeIndependentPath;
}
public boolean getSerializeToText() {
return _serializeToText;
}
public boolean getSerializeVendor() {
return _serializeVendor;
}
public String getSerializeVendorPath() {
return _serializeVendorPath;
}
public String getServiceHost() {
return _serviceHost;
}
public String getServiceLogicBloxHostname() {
return _serviceLogicBloxHostname;
}
public int getServicePort() {
return _servicePort;
}
public String getServiceUrl() {
return _serviceUrl;
}
public boolean getSimplify() {
return _simplify;
}
public String getTestRigPath() {
return _testRigPath;
}
public boolean getThrowOnLexerError() {
return _throwOnLexerError;
}
public boolean getThrowOnParserError() {
return _throwOnParserError;
}
public boolean getTimestamp() {
return _timestamp;
}
public String getTrafficFactDumpDir() {
return _trafficFactDumpDir;
}
public boolean getUnimplementedAsError() {
return _unimplementedAsError;
}
public boolean getUnimplementedRecord() {
return _unimplementedRecord;
}
public boolean getUpdate() {
return _update;
}
public String getVarSizeMapPath() {
return _varSizeMapPath;
}
public String getWorkspaceName() {
return _workspaceName;
}
public boolean getZ3() {
return _z3;
}
public String getZ3File() {
return _z3File;
}
public boolean ignoreUnsupported() {
return _ignoreUnsupported;
}
private void initOptions() {
_options = new Options();
_options.addOption(Option
.builder()
.argName("predicates")
.hasArgs()
.desc("list of LogicBlox predicates to query (defaults to '"
+ DEFAULT_PREDICATES.get(0) + "')").longOpt(ARG_PREDICATES)
.build());
_options.addOption(Option.builder().argName("predicates").hasArgs()
.desc("list of LogicBlox fact predicates to suppress")
.longOpt(ARG_DISABLED_FACTS).build());
_options.addOption(Option
.builder()
.argName("path")
.hasArg()
.desc("path to test rig directory (defaults to \""
+ DEFAULT_TEST_RIG_PATH + "\")").longOpt(ARG_TEST_RIG_PATH)
.build());
_options
.addOption(Option.builder().argName("name").hasArg()
.desc("name of LogicBlox workspace").longOpt(ARG_WORKSPACE)
.build());
_options.addOption(Option.builder().argName("hostname").hasArg()
.desc("hostname of ConnectBlox server for regular session")
.longOpt(ARG_CB_HOST).build());
_options.addOption(Option.builder().argName("port_number").hasArg()
.desc("port of ConnectBlox server for regular session")
.longOpt(ARG_CB_PORT).build());
_options.addOption(Option.builder().argName(ARGNAME_LB_WEB_PORT).hasArg()
.desc("port of lb-web server").longOpt(ARG_LB_WEB_PORT).build());
_options.addOption(Option.builder().argName(ARGNAME_LB_WEB_ADMIN_PORT)
.hasArg().desc("admin port lb-web server")
.longOpt(ARG_LB_WEB_ADMIN_PORT).build());
_options
.addOption(Option
.builder()
.argName("predicates")
.optionalArg(true)
.hasArgs()
.desc("print semantics for all predicates, or for predicates supplied as optional arguments")
.longOpt(ARG_PREDHELP).build());
_options.addOption(Option.builder().desc("print this message")
.longOpt(ARG_HELP).build());
_options.addOption(Option.builder().desc("query workspace")
.longOpt(ARG_QUERY).build());
_options.addOption(Option.builder()
.desc("return predicate cardinalities instead of contents")
.longOpt(ARG_COUNT).build());
_options.addOption(Option.builder().desc("query ALL predicates")
.longOpt(ARG_QUERY_ALL).build());
_options.addOption(Option.builder()
.desc("create workspace and add project logic")
.longOpt(ARG_COMPILE).build());
_options.addOption(Option.builder().desc("add facts to workspace")
.longOpt(ARG_FACTS).build());
_options.addOption(Option.builder()
.desc("remove facts instead of adding them")
.longOpt(ARG_REMOVE_FACTS).build());
_options.addOption(Option.builder().desc("display results in GUI")
.longOpt(ARG_GUI).build());
_options.addOption(Option.builder()
.desc("differentially update test rig workspace")
.longOpt(ARG_UPDATE).build());
_options.addOption(Option.builder()
.desc("do not add injected traffic facts").longOpt(ARG_NO_TRAFFIC)
.build());
_options
.addOption(Option
.builder()
.desc("exit on first parse error (otherwise will exit on last parse error)")
.longOpt(ARG_EXIT_ON_PARSE_ERROR).build());
_options.addOption(Option.builder().desc("generate z3 data plane logic")
.longOpt(ARG_Z3).build());
_options.addOption(Option.builder().argName(ARGNAME_Z3_OUTPUT).hasArg()
.desc("set z3 data plane logic output file").longOpt(ARG_Z3_OUTPUT)
.build());
_options.addOption(Option.builder()
.argName(ARGNAME_Z3_CONCRETIZER_INPUT_FILES).hasArgs()
.desc("set z3 concretizer input file(s)")
.longOpt(ARG_Z3_CONCRETIZER_INPUT_FILES).build());
_options.addOption(Option.builder()
.argName(ARGNAME_Z3_CONCRETIZER_NEGATED_INPUT_FILES).hasArgs()
.desc("set z3 negated concretizer input file(s)")
.longOpt(ARG_Z3_CONCRETIZER_NEGATED_INPUT_FILES).build());
_options.addOption(Option.builder()
.argName(ARGNAME_Z3_CONCRETIZER_OUTPUT_FILE).hasArg()
.desc("set z3 concretizer output file")
.longOpt(ARG_Z3_CONCRETIZER_OUTPUT_FILE).build());
_options.addOption(Option.builder()
.desc("create z3 logic to concretize data plane constraints")
.longOpt(ARG_Z3_CONCRETIZE).build());
_options.addOption(Option.builder()
.desc("push concrete flows into logicblox databse")
.longOpt(ARG_FLOWS).build());
_options.addOption(Option.builder().argName(ARGNAME_FLOW_PATH).hasArg()
.desc("path to concrete flows").longOpt(ARG_FLOW_PATH).build());
_options.addOption(Option.builder().argName(ARGNAME_FLOW_SINK_PATH)
.hasArg().desc("path to flow sinks").longOpt(ARG_FLOW_SINK_PATH)
.build());
_options.addOption(Option.builder()
.desc("dump intermediate format of configurations")
.longOpt(ARG_DUMP_IF).build());
_options.addOption(Option.builder().argName(ARGNAME_DUMP_IF_DIR).hasArg()
.desc("directory to dump intermediate format files")
.longOpt(ARG_DUMP_IF_DIR).build());
_options.addOption(Option.builder().desc("dump control plane facts")
.longOpt(ARG_DUMP_CONTROL_PLANE_FACTS).build());
_options.addOption(Option.builder().desc("dump traffic facts")
.longOpt(ARG_DUMP_TRAFFIC_FACTS).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_DUMP_FACTS_DIR)
.desc("directory to dump LogicBlox facts")
.longOpt(ARG_DUMP_FACTS_DIR).build());
_options.addOption(Option.builder().hasArg().argName(ARGNAME_REVERT)
.desc("revert test rig workspace to specified branch")
.longOpt(ARG_REVERT).build());
_options.addOption(Option.builder().desc("redirect stderr to stdout")
.longOpt(ARG_REDIRECT_STDERR).build());
_options.addOption(Option.builder().hasArg().argName(ARGNAME_ANONYMIZE)
.desc("created anonymized versions of configs in test rig")
.longOpt(ARG_ANONYMIZE).build());
_options
.addOption(Option
.builder()
.hasArg()
.argName(ARGNAME_LOGICDIR)
.desc("set logic dir with respect to filesystem of machine running LogicBlox")
.longOpt(ARG_LOGICDIR).build());
_options.addOption(Option.builder().desc("disable z3 simplification")
.longOpt(ARG_DISABLE_Z3_SIMPLIFICATION).build());
_options.addOption(Option.builder().desc("serialize vendor configs")
.longOpt(ARG_SERIALIZE_VENDOR).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_SERIALIZE_VENDOR_PATH)
.desc("path to read or write serialized vendor configs")
.longOpt(ARG_SERIALIZE_VENDOR_PATH).build());
_options.addOption(Option.builder()
.desc("serialize vendor-independent configs")
.longOpt(ARG_SERIALIZE_INDEPENDENT).build());
_options
.addOption(Option
.builder()
.hasArg()
.argName(ARGNAME_SERIALIZE_INDEPENDENT_PATH)
.desc("path to read or write serialized vendor-independent configs")
.longOpt(ARG_SERIALIZE_INDEPENDENT_PATH).build());
_options.addOption(Option.builder()
.desc("compute and serialize data plane (requires logicblox)")
.longOpt(ARG_DATA_PLANE).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_DATA_PLANE_DIR)
.desc("path to read or write serialized data plane")
.longOpt(ARG_DATA_PLANE_DIR).build());
_options.addOption(Option.builder().desc("print parse trees")
.longOpt(ARG_PRINT_PARSE_TREES).build());
_options.addOption(Option.builder().desc("dump interface descriptions")
.longOpt(ARG_DUMP_INTERFACE_DESCRIPTIONS).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_DUMP_INTERFACE_DESCRIPTIONS_PATH)
.desc("path to read or write interface descriptions")
.longOpt(ARG_DUMP_INTERFACE_DESCRIPTIONS_PATH).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_NODE_SET_PATH)
.desc("path to read or write node set").longOpt(ARG_NODE_SET_PATH)
.build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_INTERFACE_MAP_PATH)
.desc("path to read or write interface-number mappings")
.longOpt(ARG_INTERFACE_MAP_PATH).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_VAR_SIZE_MAP_PATH)
.desc("path to read or write var-size mappings")
.longOpt(ARG_VAR_SIZE_MAP_PATH).build());
_options.addOption(Option.builder()
.desc("generate multipath-inconsistency query").longOpt(ARG_MPI)
.build());
_options.addOption(Option.builder().hasArg().argName(ARGNAME_MPI_PATH)
.desc("path to read or write multipath-inconsistency query")
.longOpt(ARG_MPI_PATH).build());
_options.addOption(Option.builder().desc("serialize to text")
.longOpt(ARG_SERIALIZE_TO_TEXT).build());
_options.addOption(Option.builder().desc("run in service mode")
.longOpt(ARG_SERVICE_MODE).build());
_options
.addOption(Option.builder().argName("port_number").hasArg()
.desc("port for batfish service").longOpt(ARG_SERVICE_PORT)
.build());
_options.addOption(Option.builder().argName("base_url").hasArg()
.desc("base url for batfish service").longOpt(ARG_SERVICE_URL)
.build());
_options
.addOption(Option
.builder()
.hasArg()
.argName(ARGNAME_BUILD_PREDICATE_INFO)
.desc("build predicate info (should only be called by ant build script) with provided input logic dir")
.longOpt(ARG_BUILD_PREDICATE_INFO).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_BLACKLIST_INTERFACE)
.desc("interface to blacklist (force inactive) during analysis")
.longOpt(ARG_BLACKLIST_INTERFACE).build());
_options
.addOption(Option
.builder()
.hasArg()
.argName(ARGNAME_BLACKLIST_NODE)
.desc("node to blacklist (remove from configuration structures) during analysis")
.longOpt(ARG_BLACKLIST_NODE).build());
_options.addOption(Option.builder().hasArg().argName(ARGNAME_ACCEPT_NODE)
.desc("accept node for reachability query")
.longOpt(ARG_ACCEPT_NODE).build());
_options
.addOption(Option
.builder()
.desc("generate interface-failure-inconsistency reachable packet query")
.longOpt(ARG_REACH).build());
_options
.addOption(Option
.builder()
.hasArg()
.argName(ARGNAME_REACH_PATH)
.desc("path to read or write interface-failure-inconsistency reachable packet query")
.longOpt(ARG_REACH_PATH).build());
_options
.addOption(Option
.builder()
.desc("generate interface-failure-inconsistency black-hole packet query")
.longOpt(ARG_BLACK_HOLE).build());
_options
.addOption(Option
.builder()
.desc("only concretize single packet (do not break up disjunctions)")
.longOpt(ARG_CONC_UNIQUE).build());
_options
.addOption(Option
.builder()
.hasArg()
.argName(ARGNAME_BLACK_HOLE_PATH)
.desc("path to read or write interface-failure-inconsistency black-hole packet query")
.longOpt(ARG_BLACK_HOLE_PATH).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_BLACKLIST_DST_IP)
.desc("destination ip to blacklist for concretizer queries")
.longOpt(ARG_BLACKLIST_DST_IP_PATH).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_NODE_ROLES_PATH)
.desc("path to read or write node-role mappings")
.longOpt(ARG_NODE_ROLES_PATH).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_ROLE_NODES_PATH)
.desc("path to read or write role-node mappings")
.longOpt(ARG_ROLE_NODES_PATH).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_ROLE_REACHABILITY_QUERY_PATH)
.desc("path to read or write role-reachability queries")
.longOpt(ARG_ROLE_REACHABILITY_QUERY_PATH).build());
_options.addOption(Option.builder()
.desc("generate role-reachability queries")
.longOpt(ARG_ROLE_REACHABILITY_QUERY).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_ROLE_TRANSIT_QUERY_PATH)
.desc("path to read or write role-transit queries")
.longOpt(ARG_ROLE_TRANSIT_QUERY_PATH).build());
_options.addOption(Option.builder().desc("generate role-transit queries")
.longOpt(ARG_ROLE_TRANSIT_QUERY).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_ROLE_SET_PATH)
.desc("path to read or write role set").longOpt(ARG_ROLE_SET_PATH)
.build());
_options.addOption(Option.builder()
.desc("duplicate flows across all nodes in same role")
.longOpt(ARG_DUPLICATE_ROLE_FLOWS).build());
_options.addOption(Option.builder().hasArg().argName(ARGNAME_LOG_LEVEL)
.desc("log level").longOpt(ARG_LOG_LEVEL).build());
_options.addOption(Option.builder()
.desc("header of concretized z3 output refers to role, not node")
.longOpt(ARG_ROLE_HEADERS).build());
_options.addOption(Option.builder()
.desc("throw exception immediately on parser error")
.longOpt(ARG_THROW_ON_PARSER_ERROR).build());
_options.addOption(Option.builder()
.desc("throw exception immediately on lexer error")
.longOpt(ARG_THROW_ON_LEXER_ERROR).build());
_options.addOption(Option.builder()
.desc("flatten hierarchical juniper configuration files")
.longOpt(ARG_FLATTEN).build());
_options
.addOption(Option
.builder()
.hasArg()
.argName(ARGNAME_FLATTEN_SOURCE)
.desc("path to test rig containing hierarchical juniper configurations to be flattened")
.longOpt(ARG_FLATTEN_SOURCE).build());
_options
.addOption(Option
.builder()
.hasArg()
.argName(ARGNAME_FLATTEN_DESTINATION)
.desc("output path to test rig in which flat juniper (and all other) configurations will be placed")
.longOpt(ARG_FLATTEN_DESTINATION).build());
_options
.addOption(Option
.builder()
.desc("flatten hierarchical juniper configuration files on-the-fly (line number references will be spurious)")
.longOpt(ARG_FLATTEN_ON_THE_FLY).build());
_options
.addOption(Option
.builder()
.desc("throws "
+ PedanticBatfishException.class.getSimpleName()
+ " for likely harmless warnings (e.g. deviation from good configuration style), instead of emitting warning and continuing")
.longOpt(ARG_PEDANTIC_AS_ERROR).build());
_options.addOption(Option.builder().desc("suppresses pedantic warnings")
.longOpt(ARG_PEDANTIC_SUPPRESS).build());
_options
.addOption(Option
.builder()
.desc("throws "
+ RedFlagBatfishException.class.getSimpleName()
+ " on some recoverable errors (e.g. bad config lines), instead of emitting warning and attempting to recover")
.longOpt(ARG_RED_FLAG_AS_ERROR).build());
_options.addOption(Option.builder().desc("suppresses red-flag warnings")
.longOpt(ARG_RED_FLAG_SUPPRESS).build());
_options
.addOption(Option
.builder()
.desc("throws "
+ UnimplementedBatfishException.class.getSimpleName()
+ " when encountering unimplemented configuration directives, instead of emitting warning and ignoring")
.longOpt(ARG_UNIMPLEMENTED_AS_ERROR).build());
_options.addOption(Option.builder()
.desc("suppresses unimplemented-configuration-directive warnings")
.longOpt(ARG_UNIMPLEMENTED_SUPPRESS).build());
_options.addOption(Option.builder()
.desc("build histogram of unimplemented features")
.longOpt(ARG_HISTOGRAM).build());
_options.addOption(Option.builder().desc("generate stubs")
.longOpt(ARG_GENERATE_STUBS).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_GENERATE_STUBS_INPUT_ROLE)
.desc("input role for which to generate stubs")
.longOpt(ARG_GENERATE_STUBS_INPUT_ROLE).build());
_options
.addOption(Option
.builder()
.hasArg()
.argName(ARGNAME_GENERATE_STUBS_INTERFACE_DESCRIPTION_REGEX)
.desc("java regex to extract hostname of generated stub from description of adjacent interface")
.longOpt(ARG_GENERATE_STUBS_INTERFACE_DESCRIPTION_REGEX)
.build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_GENERATE_STUBS_REMOTE_AS)
.desc("autonomous system number of stubs to be generated")
.longOpt(ARG_GENERATE_STUBS_REMOTE_AS).build());
_options.addOption(Option.builder().hasArg().argName(ARGNAME_LOG_FILE)
.desc("path to main log file").longOpt(ARG_LOG_FILE).build());
_options.addOption(Option.builder().hasArg().argName(ARGNAME_GEN_OSPF)
.desc("generate ospf configs from specified topology")
.longOpt(ARG_GEN_OSPF).build());
_options.addOption(Option.builder()
.desc("print timestamps in log messages").longOpt(ARG_TIMESTAMP)
.build());
_options
.addOption(Option
.builder()
.desc("ignore configuration files with unsupported format instead of crashing")
.longOpt(ARG_IGNORE_UNSUPPORTED).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_AUTO_BASE_DIR)
.desc("path to base dir for automatic i/o path selection")
.longOpt(ARG_AUTO_BASE_DIR).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_ENVIRONMENT_NAME)
.desc("name of environment to use").longOpt(ARG_ENVIRONMENT_NAME)
.build());
_options
.addOption(Option
.builder()
.hasArg()
.argName(ARGNAME_SERVICE_LOGICBLOX_HOSTNAME)
.desc("hostname of LogicBlox server to be used by batfish service when creating workspaces")
.longOpt(ARG_SERVICE_LOGICBLOX_HOSTNAME).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_QUESTION_NAME).desc("name of question")
.longOpt(BfConsts.ARG_QUESTION_NAME).build());
_options.addOption(Option.builder().desc("answer provided question")
.longOpt(BfConsts.COMMAND_ANSWER).build());
_options.addOption(Option.builder()
.desc("post dumped flows to logicblox")
.longOpt(BfConsts.COMMAND_POST_FLOWS).build());
_options.addOption(Option.builder().desc("parse configs in parallel")
.longOpt(ARG_PARSE_PARALLEL).build());
_options.addOption(Option.builder().argName("port_number").hasArg()
.desc("coordinator work manager listening port")
.longOpt(ARG_COORDINATOR_WORK_PORT).build());
_options.addOption(Option.builder().argName("port_number").hasArg()
.desc("coordinator pool manager listening port")
.longOpt(ARG_COORDINATOR_POOL_PORT).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_SERVICE_HOST)
.desc("local hostname to report to coordinator")
.longOpt(ARG_SERVICE_HOST).build());
_options.addOption(Option
.builder()
.hasArg()
.argName(ARGNAME_COORDINATOR_HOST)
.desc("hostname of coordinator for registration with -"
+ ARG_SERVICE_MODE).longOpt(ARG_COORDINATOR_HOST).build());
}
private void parseCommandLine(String[] args) throws ParseException {
_canExecute = true;
_runInServiceMode = false;
_printSemantics = false;
CommandLine line = null;
CommandLineParser parser = new DefaultParser();
// parse the command line arguments
line = parser.parse(_options, args);
_logLevel = line.getOptionValue(ARG_LOG_LEVEL, DEFAULT_LOG_LEVEL);
_logFile = line.getOptionValue(ARG_LOG_FILE);
if (line.hasOption(ARG_HELP)) {
_canExecute = false;
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.setLongOptPrefix("-");
formatter.printHelp(EXECUTABLE_NAME, _options);
return;
}
_runInServiceMode = line.hasOption(ARG_SERVICE_MODE);
_servicePort = Integer.parseInt(line.getOptionValue(ARG_SERVICE_PORT,
DEFAULT_SERVICE_PORT));
_serviceUrl = line.getOptionValue(ARG_SERVICE_URL, DEFAULT_SERVICE_URL);
_counts = line.hasOption(ARG_COUNT);
_queryAll = line.hasOption(ARG_QUERY_ALL);
_query = line.hasOption(ARG_QUERY);
if (line.hasOption(ARG_PREDHELP)) {
_printSemantics = true;
String[] optionValues = line.getOptionValues(ARG_PREDHELP);
if (optionValues != null) {
_helpPredicates = Arrays.asList(optionValues);
}
}
_cbHost = line.getOptionValue(ARG_CB_HOST, DEFAULT_CONNECTBLOX_HOST);
_cbPort = Integer.parseInt(line.getOptionValue(ARG_CB_PORT,
DEFAULT_CONNECTBLOX_REGULAR_PORT));
_testRigPath = line.getOptionValue(ARG_TEST_RIG_PATH,
DEFAULT_TEST_RIG_PATH);
_workspaceName = line.getOptionValue(ARG_WORKSPACE, null);
_disabledFacts = new HashSet<String>();
if (line.hasOption(ARG_DISABLED_FACTS)) {
_disabledFacts.addAll(Arrays.asList(line
.getOptionValues(ARG_DISABLED_FACTS)));
}
if (line.hasOption(ARG_PREDICATES)) {
_predicates = Arrays.asList(line.getOptionValues(ARG_PREDICATES));
}
else {
_predicates = DEFAULT_PREDICATES;
}
_removeFacts = line.hasOption(ARG_REMOVE_FACTS);
_compile = line.hasOption(ARG_COMPILE);
_facts = line.hasOption(ARG_FACTS);
_update = line.hasOption(ARG_UPDATE);
_noTraffic = line.hasOption(ARG_NO_TRAFFIC);
_exitOnParseError = line.hasOption(ARG_EXIT_ON_PARSE_ERROR);
_z3 = line.hasOption(ARG_Z3);
if (_z3) {
_z3File = line.getOptionValue(ARG_Z3_OUTPUT);
}
_concretize = line.hasOption(ARG_Z3_CONCRETIZE);
if (_concretize) {
_concretizerInputFilePaths = line
.getOptionValues(ARG_Z3_CONCRETIZER_INPUT_FILES);
_negatedConcretizerInputFilePaths = line
.getOptionValues(ARG_Z3_CONCRETIZER_NEGATED_INPUT_FILES);
_concretizerOutputFilePath = line
.getOptionValue(ARG_Z3_CONCRETIZER_OUTPUT_FILE);
}
_flows = line.hasOption(ARG_FLOWS);
if (_flows) {
_flowPath = line.getOptionValue(ARG_FLOW_PATH, DEFAULT_FLOW_PATH);
}
_flowSinkPath = line.getOptionValue(ARG_FLOW_SINK_PATH);
_dumpIF = line.hasOption(ARG_DUMP_IF);
if (_dumpIF) {
_dumpIFDir = line.getOptionValue(ARG_DUMP_IF_DIR, DEFAULT_DUMP_IF_DIR);
}
_dumpControlPlaneFacts = line.hasOption(ARG_DUMP_CONTROL_PLANE_FACTS);
_dumpTrafficFacts = line.hasOption(ARG_DUMP_TRAFFIC_FACTS);
_dumpFactsDir = line.getOptionValue(ARG_DUMP_FACTS_DIR);
_revertBranchName = line.getOptionValue(ARG_REVERT);
_revert = (_revertBranchName != null);
_redirectStdErr = line.hasOption(ARG_REDIRECT_STDERR);
_anonymize = line.hasOption(ARG_ANONYMIZE);
if (_anonymize) {
_anonymizeDir = line.getOptionValue(ARG_ANONYMIZE);
}
_logicDir = line.getOptionValue(ARG_LOGICDIR, null);
_simplify = DEFAULT_Z3_SIMPLIFY;
if (line.hasOption(ARG_DISABLE_Z3_SIMPLIFICATION)) {
_simplify = false;
}
_serializeVendor = line.hasOption(ARG_SERIALIZE_VENDOR);
_serializeVendorPath = line.getOptionValue(ARG_SERIALIZE_VENDOR_PATH,
DEFAULT_SERIALIZE_VENDOR_PATH);
_serializeIndependent = line.hasOption(ARG_SERIALIZE_INDEPENDENT);
_serializeIndependentPath = line.getOptionValue(
ARG_SERIALIZE_INDEPENDENT_PATH, DEFAULT_SERIALIZE_INDEPENDENT_PATH);
_dataPlane = line.hasOption(ARG_DATA_PLANE);
_dataPlaneDir = line.getOptionValue(ARG_DATA_PLANE_DIR);
_printParseTree = line.hasOption(ARG_PRINT_PARSE_TREES);
_dumpInterfaceDescriptions = line
.hasOption(ARG_DUMP_INTERFACE_DESCRIPTIONS);
_dumpInterfaceDescriptionsPath = line.getOptionValue(
ARG_DUMP_INTERFACE_DESCRIPTIONS_PATH,
DEFAULT_DUMP_INTERFACE_DESCRIPTIONS_PATH);
_nodeSetPath = line.getOptionValue(ARG_NODE_SET_PATH);
_interfaceMapPath = line.getOptionValue(ARG_INTERFACE_MAP_PATH);
_varSizeMapPath = line.getOptionValue(ARG_VAR_SIZE_MAP_PATH);
_genMultipath = line.hasOption(ARG_MPI);
_mpiPath = line.getOptionValue(ARG_MPI_PATH);
_serializeToText = line.hasOption(ARG_SERIALIZE_TO_TEXT);
_lbWebPort = Integer.parseInt(line.getOptionValue(ARG_LB_WEB_PORT,
DEFAULT_LB_WEB_PORT));
_lbWebAdminPort = Integer.parseInt(line.getOptionValue(
ARG_LB_WEB_ADMIN_PORT, DEFAULT_LB_WEB_ADMIN_PORT));
_buildPredicateInfo = line.hasOption(ARG_BUILD_PREDICATE_INFO);
if (_buildPredicateInfo) {
_logicSrcDir = line.getOptionValue(ARG_BUILD_PREDICATE_INFO);
}
_blacklistInterface = line.getOptionValue(ARG_BLACKLIST_INTERFACE);
_blacklistNode = line.getOptionValue(ARG_BLACKLIST_NODE);
_reach = line.hasOption(ARG_REACH);
_reachPath = line.getOptionValue(ARG_REACH_PATH);
_blackHole = line.hasOption(ARG_BLACK_HOLE);
_blackHolePath = line.getOptionValue(ARG_BLACK_HOLE_PATH);
_blacklistDstIpPath = line.getOptionValue(ARG_BLACKLIST_DST_IP_PATH);
_concUnique = line.hasOption(ARG_CONC_UNIQUE);
_acceptNode = line.getOptionValue(ARG_ACCEPT_NODE);
_nodeRolesPath = line.getOptionValue(ARG_NODE_ROLES_PATH);
_roleNodesPath = line.getOptionValue(ARG_ROLE_NODES_PATH);
_roleReachabilityQueryPath = line
.getOptionValue(ARG_ROLE_REACHABILITY_QUERY_PATH);
_roleReachabilityQuery = line.hasOption(ARG_ROLE_REACHABILITY_QUERY);
_roleTransitQueryPath = line.getOptionValue(ARG_ROLE_TRANSIT_QUERY_PATH);
_roleTransitQuery = line.hasOption(ARG_ROLE_TRANSIT_QUERY);
_roleSetPath = line.getOptionValue(ARG_ROLE_SET_PATH);
_duplicateRoleFlows = line.hasOption(ARG_DUPLICATE_ROLE_FLOWS);
_roleHeaders = line.hasOption(ARG_ROLE_HEADERS);
_throwOnParserError = line.hasOption(ARG_THROW_ON_PARSER_ERROR);
_throwOnLexerError = line.hasOption(ARG_THROW_ON_LEXER_ERROR);
_flatten = line.hasOption(ARG_FLATTEN);
_flattenSource = line.getOptionValue(ARG_FLATTEN_SOURCE);
_flattenDestination = line.getOptionValue(ARG_FLATTEN_DESTINATION);
_flattenOnTheFly = line.hasOption(ARG_FLATTEN_ON_THE_FLY);
_pedanticAsError = line.hasOption(ARG_PEDANTIC_AS_ERROR);
_pedanticRecord = !line.hasOption(ARG_PEDANTIC_SUPPRESS);
_redFlagAsError = line.hasOption(ARG_RED_FLAG_AS_ERROR);
_redFlagRecord = !line.hasOption(ARG_RED_FLAG_SUPPRESS);
_unimplementedAsError = line.hasOption(ARG_UNIMPLEMENTED_AS_ERROR);
_unimplementedRecord = !line.hasOption(ARG_UNIMPLEMENTED_SUPPRESS);
_histogram = line.hasOption(ARG_HISTOGRAM);
_generateStubs = line.hasOption(ARG_GENERATE_STUBS);
_generateStubsInputRole = line
.getOptionValue(ARG_GENERATE_STUBS_INPUT_ROLE);
_generateStubsInterfaceDescriptionRegex = line
.getOptionValue(ARG_GENERATE_STUBS_INTERFACE_DESCRIPTION_REGEX);
if (line.hasOption(ARG_GENERATE_STUBS_REMOTE_AS)) {
_generateStubsRemoteAs = Integer.parseInt(line
.getOptionValue(ARG_GENERATE_STUBS_REMOTE_AS));
}
_genOspfTopology = line.getOptionValue(ARG_GEN_OSPF);
_timestamp = line.hasOption(ARG_TIMESTAMP);
_ignoreUnsupported = line.hasOption(ARG_IGNORE_UNSUPPORTED);
_autoBaseDir = line.getOptionValue(ARG_AUTO_BASE_DIR);
_environmentName = line.getOptionValue(ARG_ENVIRONMENT_NAME);
_questionName = line.getOptionValue(BfConsts.ARG_QUESTION_NAME);
_answer = line.hasOption(BfConsts.COMMAND_ANSWER);
_postFlows = line.hasOption(BfConsts.COMMAND_POST_FLOWS);
_parseParallel = line.hasOption(ARG_PARSE_PARALLEL);
_coordinatorHost = line.getOptionValue(ARG_COORDINATOR_HOST);
_coordinatorPoolPort = Integer.parseInt(line.getOptionValue(
ARG_COORDINATOR_POOL_PORT, CoordConsts.SVC_POOL_PORT.toString()));
_coordinatorWorkPort = Integer.parseInt(line.getOptionValue(
ARG_COORDINATOR_WORK_PORT, CoordConsts.SVC_WORK_PORT.toString()));
_serviceHost = line.getOptionValue(ARG_SERVICE_HOST);
// set service logicblox hostname to service hostname unless set
// explicitly
_serviceLogicBloxHostname = line.getOptionValue(
ARG_SERVICE_LOGICBLOX_HOSTNAME, _serviceHost);
}
public boolean printParseTree() {
return _printParseTree;
}
public boolean redirectStdErr() {
return _redirectStdErr;
}
public boolean revert() {
return _revert;
}
public boolean runInServiceMode() {
return _runInServiceMode;
}
public void setConnectBloxHost(String hostname) {
_cbHost = hostname;
}
public void setDataPlaneDir(String path) {
_dataPlaneDir = path;
}
public void setDumpFactsDir(String path) {
_dumpFactsDir = path;
}
public void setJobLogicBloxHostnamePath(String path) {
_jobLogicBloxHostnamePath = path;
}
public void setLogger(BatfishLogger logger) {
_logger = logger;
}
public void setLogicDir(String logicDir) {
_logicDir = logicDir;
}
public void setMultipathInconsistencyQueryPath(String path) {
_mpiPath = path;
}
public void setNodeSetPath(String nodeSetPath) {
_nodeSetPath = nodeSetPath;
}
public void setQueryDumpDir(String path) {
_queryDumpDir = path;
}
public void setQuestionPath(String questionPath) {
_questionPath = questionPath;
}
public void setSerializeIndependentPath(String path) {
_serializeIndependentPath = path;
}
public void setSerializeVendorPath(String path) {
_serializeVendorPath = path;
}
public void setServiceLogicBloxHostname(String hostname) {
_serviceLogicBloxHostname = hostname;
}
public void setTestRigPath(String path) {
_testRigPath = path;
}
public void setTrafficFactDumpDir(String path) {
_trafficFactDumpDir = path;
}
public void setWorkspaceName(String name) {
_workspaceName = name;
}
public void setZ3DataPlaneFile(String path) {
_z3File = path;
}
}
| projects/batfish/src/org/batfish/main/Settings.java | package org.batfish.main;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.batfish.common.BfConsts;
import org.batfish.common.CoordConsts;
public class Settings {
private static final String ARG_ACCEPT_NODE = "acceptnode";
private static final String ARG_ANONYMIZE = "anonymize";
private static final String ARG_AUTO_BASE_DIR = "autobasedir";
private static final String ARG_BLACK_HOLE = "blackhole";
private static final String ARG_BLACK_HOLE_PATH = "blackholepath";
private static final String ARG_BLACKLIST_DST_IP_PATH = "blacklistdstippath";
private static final String ARG_BLACKLIST_INTERFACE = "blint";
private static final String ARG_BLACKLIST_NODE = "blnode";
private static final String ARG_BUILD_PREDICATE_INFO = "bpi";
private static final String ARG_CB_HOST = "lbhost";
private static final String ARG_CB_PORT = "lbport";
private static final String ARG_COMPILE = "compile";
private static final String ARG_CONC_UNIQUE = "concunique";
private static final String ARG_COORDINATOR_HOST = "coordinatorhost";
private static final String ARG_COORDINATOR_POOL_PORT = "coordinatorpoolport";
private static final String ARG_COORDINATOR_WORK_PORT = "coordinatorworkport";
private static final String ARG_COUNT = "count";
private static final String ARG_DATA_PLANE = "dp";
private static final String ARG_DATA_PLANE_DIR = "dpdir";
private static final String ARG_DISABLE_Z3_SIMPLIFICATION = "nosimplify";
private static final String ARG_DISABLED_FACTS = "disablefacts";
private static final String ARG_DUMP_CONTROL_PLANE_FACTS = "dumpcp";
private static final String ARG_DUMP_FACTS_DIR = "dumpdir";
private static final String ARG_DUMP_IF = "dumpif";
private static final String ARG_DUMP_IF_DIR = "dumpifdir";
private static final String ARG_DUMP_INTERFACE_DESCRIPTIONS = "id";
private static final String ARG_DUMP_INTERFACE_DESCRIPTIONS_PATH = "idpath";
private static final String ARG_DUMP_TRAFFIC_FACTS = "dumptraffic";
private static final String ARG_DUPLICATE_ROLE_FLOWS = "drf";
private static final String ARG_ENVIRONMENT_NAME = "env";
private static final String ARG_EXIT_ON_PARSE_ERROR = "ee";
private static final String ARG_FACTS = "facts";
private static final String ARG_FLATTEN = "flatten";
private static final String ARG_FLATTEN_DESTINATION = "flattendst";
private static final String ARG_FLATTEN_ON_THE_FLY = "flattenonthefly";
private static final String ARG_FLATTEN_SOURCE = "flattensrc";
private static final String ARG_FLOW_PATH = "flowpath";
private static final String ARG_FLOW_SINK_PATH = "flowsink";
private static final String ARG_FLOWS = "flow";
private static final String ARG_GEN_OSPF = "genospf";
private static final String ARG_GENERATE_STUBS = "gs";
private static final String ARG_GENERATE_STUBS_INPUT_ROLE = "gsinputrole";
private static final String ARG_GENERATE_STUBS_INTERFACE_DESCRIPTION_REGEX = "gsidregex";
private static final String ARG_GENERATE_STUBS_REMOTE_AS = "gsremoteas";
private static final String ARG_GUI = "gui";
private static final String ARG_HELP = "help";
private static final String ARG_HISTOGRAM = "histogram";
private static final String ARG_IGNORE_UNSUPPORTED = "ignoreunsupported";
private static final String ARG_INTERFACE_MAP_PATH = "impath";
private static final String ARG_LB_WEB_ADMIN_PORT = "lbwebadminport";
private static final String ARG_LB_WEB_PORT = "lbwebport";
private static final String ARG_LOG_FILE = "logfile";
private static final String ARG_LOG_LEVEL = "loglevel";
private static final String ARG_LOGICDIR = "logicdir";
private static final String ARG_MPI = "mpi";
private static final String ARG_MPI_PATH = "mpipath";
private static final String ARG_NO_TRAFFIC = "notraffic";
private static final String ARG_NODE_ROLES_PATH = "nrpath";
private static final String ARG_NODE_SET_PATH = "nodes";
private static final String ARG_PARSE_PARALLEL = "parseparallel";
private static final String ARG_PEDANTIC_AS_ERROR = "pedanticerror";
private static final String ARG_PEDANTIC_SUPPRESS = "pedanticsuppress";
private static final String ARG_PREDHELP = "predhelp";
private static final String ARG_PREDICATES = "predicates";
private static final String ARG_PRINT_PARSE_TREES = "ppt";
private static final String ARG_QUERY = "query";
private static final String ARG_QUERY_ALL = "all";
private static final String ARG_REACH = "reach";
private static final String ARG_REACH_PATH = "reachpath";
private static final String ARG_RED_FLAG_AS_ERROR = "redflagerror";
private static final String ARG_RED_FLAG_SUPPRESS = "redflagsuppress";
private static final String ARG_REDIRECT_STDERR = "redirect";
private static final String ARG_REMOVE_FACTS = "remove";
private static final String ARG_REVERT = "revert";
private static final String ARG_ROLE_HEADERS = "rh";
private static final String ARG_ROLE_NODES_PATH = "rnpath";
private static final String ARG_ROLE_REACHABILITY_QUERY = "rr";
private static final String ARG_ROLE_REACHABILITY_QUERY_PATH = "rrpath";
private static final String ARG_ROLE_SET_PATH = "rspath";
private static final String ARG_ROLE_TRANSIT_QUERY = "rt";
private static final String ARG_ROLE_TRANSIT_QUERY_PATH = "rtpath";
private static final String ARG_SERIALIZE_INDEPENDENT = "si";
private static final String ARG_SERIALIZE_INDEPENDENT_PATH = "sipath";
private static final String ARG_SERIALIZE_TO_TEXT = "stext";
private static final String ARG_SERIALIZE_VENDOR = "sv";
private static final String ARG_SERIALIZE_VENDOR_PATH = "svpath";
private static final String ARG_SERVICE_HOST = "servicehost";
private static final String ARG_SERVICE_LOGICBLOX_HOSTNAME = "servicelbhostname";
private static final String ARG_SERVICE_MODE = "servicemode";
private static final String ARG_SERVICE_PORT = "serviceport";
private static final String ARG_SERVICE_URL = "serviceurl";
private static final String ARG_TEST_RIG_PATH = "testrig";
private static final String ARG_THROW_ON_LEXER_ERROR = "throwlexer";
private static final String ARG_THROW_ON_PARSER_ERROR = "throwparser";
private static final String ARG_TIMESTAMP = "timestamp";
private static final String ARG_UNIMPLEMENTED_AS_ERROR = "unimplementederror";
private static final String ARG_UNIMPLEMENTED_SUPPRESS = "unimplementedsuppress";
private static final String ARG_UPDATE = "update";
private static final String ARG_VAR_SIZE_MAP_PATH = "vsmpath";
private static final String ARG_WORKSPACE = "workspace";
private static final String ARG_Z3 = "z3";
private static final String ARG_Z3_CONCRETIZE = "conc";
private static final String ARG_Z3_CONCRETIZER_INPUT_FILES = "concin";
private static final String ARG_Z3_CONCRETIZER_NEGATED_INPUT_FILES = "concinneg";
private static final String ARG_Z3_CONCRETIZER_OUTPUT_FILE = "concout";
private static final String ARG_Z3_OUTPUT = "z3path";
private static final String ARGNAME_ACCEPT_NODE = "node";
private static final String ARGNAME_ANONYMIZE = "path";
private static final String ARGNAME_AUTO_BASE_DIR = "path";
private static final String ARGNAME_BLACK_HOLE_PATH = "path";
private static final String ARGNAME_BLACKLIST_DST_IP = "ip";
private static final String ARGNAME_BLACKLIST_INTERFACE = "node,interface";
private static final String ARGNAME_BLACKLIST_NODE = "node";
private static final String ARGNAME_BUILD_PREDICATE_INFO = "path";
private static final String ARGNAME_COORDINATOR_HOST = "hostname";
private static final String ARGNAME_DATA_PLANE_DIR = "path";
private static final String ARGNAME_DUMP_FACTS_DIR = "path";
private static final String ARGNAME_DUMP_IF_DIR = "path";
private static final String ARGNAME_DUMP_INTERFACE_DESCRIPTIONS_PATH = "path";
private static final String ARGNAME_ENVIRONMENT_NAME = "name";
private static final String ARGNAME_FLATTEN_DESTINATION = "path";
private static final String ARGNAME_FLATTEN_SOURCE = "path";
private static final String ARGNAME_FLOW_PATH = "path";
private static final String ARGNAME_FLOW_SINK_PATH = "path";
private static final String ARGNAME_GEN_OSPF = "path";
private static final String ARGNAME_GENERATE_STUBS_INPUT_ROLE = "role";
private static final String ARGNAME_GENERATE_STUBS_INTERFACE_DESCRIPTION_REGEX = "java-regex";
private static final String ARGNAME_GENERATE_STUBS_REMOTE_AS = "as";
private static final String ARGNAME_INTERFACE_MAP_PATH = "path";
private static final String ARGNAME_LB_WEB_ADMIN_PORT = "port";
private static final String ARGNAME_LB_WEB_PORT = "port";
private static final String ARGNAME_LOG_FILE = "path";
private static final String ARGNAME_LOG_LEVEL = "level";
private static final String ARGNAME_LOGICDIR = "path";
private static final String ARGNAME_MPI_PATH = "path";
private static final String ARGNAME_NODE_ROLES_PATH = "path";
private static final String ARGNAME_NODE_SET_PATH = "path";
private static final String ARGNAME_QUESTION_NAME = "name";
private static final String ARGNAME_REACH_PATH = "path";
private static final String ARGNAME_REVERT = "branch-name";
private static final String ARGNAME_ROLE_NODES_PATH = "path";
private static final String ARGNAME_ROLE_REACHABILITY_QUERY_PATH = "path";
private static final String ARGNAME_ROLE_SET_PATH = "path";
private static final String ARGNAME_ROLE_TRANSIT_QUERY_PATH = "path";
private static final String ARGNAME_SERIALIZE_INDEPENDENT_PATH = "path";
private static final String ARGNAME_SERIALIZE_VENDOR_PATH = "path";
private static final String ARGNAME_SERVICE_HOST = "hostname";
private static final String ARGNAME_SERVICE_LOGICBLOX_HOSTNAME = "hostname";
private static final String ARGNAME_VAR_SIZE_MAP_PATH = "path";
private static final String ARGNAME_Z3_CONCRETIZER_INPUT_FILES = "paths";
private static final String ARGNAME_Z3_CONCRETIZER_NEGATED_INPUT_FILES = "paths";
private static final String ARGNAME_Z3_CONCRETIZER_OUTPUT_FILE = "path";
private static final String ARGNAME_Z3_OUTPUT = "path";
public static final String DEFAULT_CONNECTBLOX_ADMIN_PORT = "55181";
public static final String DEFAULT_CONNECTBLOX_HOST = "localhost";
public static final String DEFAULT_CONNECTBLOX_REGULAR_PORT = "55179";
private static final String DEFAULT_DUMP_IF_DIR = "if";
private static final String DEFAULT_DUMP_INTERFACE_DESCRIPTIONS_PATH = "interface_descriptions";
private static final String DEFAULT_FLOW_PATH = "flows";
private static final String DEFAULT_LB_WEB_ADMIN_PORT = "55183";
private static final String DEFAULT_LB_WEB_PORT = "8080";
private static final String DEFAULT_LOG_LEVEL = "debug";
private static final List<String> DEFAULT_PREDICATES = Collections
.singletonList("InstalledRoute");
private static final String DEFAULT_SERIALIZE_INDEPENDENT_PATH = "serialized-independent-configs";
private static final String DEFAULT_SERIALIZE_VENDOR_PATH = "serialized-vendor-configs";
private static final String DEFAULT_SERVICE_PORT = BfConsts.SVC_PORT
.toString();
private static final String DEFAULT_SERVICE_URL = "http://0.0.0.0";
private static final String DEFAULT_TEST_RIG_PATH = "default_test_rig";
private static final boolean DEFAULT_Z3_SIMPLIFY = true;
private static final String EXECUTABLE_NAME = "batfish";
private String _acceptNode;
private boolean _anonymize;
private String _anonymizeDir;
private boolean _answer;
private String _autoBaseDir;
private boolean _blackHole;
private String _blackHolePath;
private String _blacklistDstIpPath;
private String _blacklistInterface;
private String _blacklistNode;
private boolean _buildPredicateInfo;
private boolean _canExecute;
private String _cbHost;
private int _cbPort;
private boolean _compile;
private boolean _concretize;
private String[] _concretizerInputFilePaths;
private String _concretizerOutputFilePath;
private boolean _concUnique;
private String _coordinatorHost;
private int _coordinatorPoolPort;
private int _coordinatorWorkPort;
private boolean _counts;
private boolean _dataPlane;
private String _dataPlaneDir;
private Set<String> _disabledFacts;
private boolean _dumpControlPlaneFacts;
private String _dumpFactsDir;
private boolean _dumpIF;
private String _dumpIFDir;
private boolean _dumpInterfaceDescriptions;
private String _dumpInterfaceDescriptionsPath;
private boolean _dumpTrafficFacts;
private boolean _duplicateRoleFlows;
private String _environmentName;
private boolean _exitOnParseError;
private boolean _facts;
private boolean _flatten;
private String _flattenDestination;
private boolean _flattenOnTheFly;
private String _flattenSource;
private String _flowPath;
private boolean _flows;
private String _flowSinkPath;
private boolean _generateStubs;
private String _generateStubsInputRole;
private String _generateStubsInterfaceDescriptionRegex;
private Integer _generateStubsRemoteAs;
private boolean _genMultipath;
private String _genOspfTopology;
private List<String> _helpPredicates;
private boolean _histogram;
private String _hsaInputDir;
private String _hsaOutputDir;
private boolean _ignoreUnsupported;
private String _interfaceMapPath;
private String _jobLogicBloxHostnamePath;
private int _lbWebAdminPort;
private int _lbWebPort;
private String _logFile;
private BatfishLogger _logger;
private String _logicDir;
private String _logicSrcDir;
private String _logLevel;
private String _mpiPath;
private String[] _negatedConcretizerInputFilePaths;
private String _nodeRolesPath;
private String _nodeSetPath;
private boolean _noTraffic;
private Options _options;
private boolean _parseParallel;
private boolean _pedanticAsError;
private boolean _pedanticRecord;
private boolean _postFlows;
private List<String> _predicates;
private boolean _printParseTree;
private boolean _printSemantics;
private boolean _query;
private boolean _queryAll;
private String _queryDumpDir;
private String _questionName;
private String _questionPath;
private boolean _reach;
private String _reachPath;
private boolean _redFlagAsError;
private boolean _redFlagRecord;
private boolean _redirectStdErr;
private boolean _removeFacts;
private boolean _revert;
private String _revertBranchName;
private boolean _roleHeaders;
private String _roleNodesPath;
private boolean _roleReachabilityQuery;
private String _roleReachabilityQueryPath;
private String _roleSetPath;
private boolean _roleTransitQuery;
private String _roleTransitQueryPath;
private boolean _runInServiceMode;
private boolean _serializeIndependent;
private String _serializeIndependentPath;
private boolean _serializeToText;
private boolean _serializeVendor;
private String _serializeVendorPath;
private String _serviceHost;
private String _serviceLogicBloxHostname;
private int _servicePort;
private String _serviceUrl;
private boolean _simplify;
private String _testRigPath;
private boolean _throwOnLexerError;
private boolean _throwOnParserError;
private boolean _timestamp;
private String _trafficFactDumpDir;
private boolean _unimplementedAsError;
private boolean _unimplementedRecord;
private boolean _update;
private String _varSizeMapPath;
private String _workspaceName;
private boolean _z3;
private String _z3File;
public Settings() throws ParseException {
this(new String[] {});
}
public Settings(String[] args) throws ParseException {
initOptions();
parseCommandLine(args);
}
public boolean canExecute() {
return _canExecute;
}
public boolean concretizeUnique() {
return _concUnique;
}
public boolean createWorkspace() {
return _compile;
}
public boolean dumpInterfaceDescriptions() {
return _dumpInterfaceDescriptions;
}
public boolean duplicateRoleFlows() {
return _duplicateRoleFlows;
}
public boolean exitOnParseError() {
return _exitOnParseError;
}
public boolean flattenOnTheFly() {
return _flattenOnTheFly;
}
public String getAcceptNode() {
return _acceptNode;
}
public boolean getAnonymize() {
return _anonymize;
}
public String getAnonymizeDir() {
return _anonymizeDir;
}
public boolean getAnswer() {
return _answer;
}
public String getAutoBaseDir() {
return _autoBaseDir;
}
public String getBlackHoleQueryPath() {
return _blackHolePath;
}
public String getBlacklistDstIpPath() {
return _blacklistDstIpPath;
}
public String getBlacklistInterfaceString() {
return _blacklistInterface;
}
public String getBlacklistNode() {
return _blacklistNode;
}
public String getBranchName() {
return _revertBranchName;
}
public boolean getBuildPredicateInfo() {
return _buildPredicateInfo;
}
public boolean getConcretize() {
return _concretize;
}
public String[] getConcretizerInputFilePaths() {
return _concretizerInputFilePaths;
}
public String getConcretizerOutputFilePath() {
return _concretizerOutputFilePath;
}
public String getConnectBloxHost() {
return _cbHost;
}
public int getConnectBloxPort() {
return _cbPort;
}
public String getCoordinatorHost() {
return _coordinatorHost;
}
public int getCoordinatorPoolPort() {
return _coordinatorPoolPort;
}
public int getCoordinatorWorkPort() {
return _coordinatorWorkPort;
}
public boolean getCountsOnly() {
return _counts;
}
public boolean getDataPlane() {
return _dataPlane;
}
public String getDataPlaneDir() {
return _dataPlaneDir;
}
public Set<String> getDisabledFacts() {
return _disabledFacts;
}
public boolean getDumpControlPlaneFacts() {
return _dumpControlPlaneFacts;
}
public String getDumpFactsDir() {
return _dumpFactsDir;
}
public String getDumpIFDir() {
return _dumpIFDir;
}
public String getDumpInterfaceDescriptionsPath() {
return _dumpInterfaceDescriptionsPath;
}
public boolean getDumpTrafficFacts() {
return _dumpTrafficFacts;
}
public String getEnvironmentName() {
return _environmentName;
}
public boolean getFacts() {
return _facts;
}
public boolean getFlatten() {
return _flatten;
}
public String getFlattenDestination() {
return _flattenDestination;
}
public String getFlattenSource() {
return _flattenSource;
}
public String getFlowPath() {
return _flowPath;
}
public boolean getFlows() {
return _flows;
}
public String getFlowSinkPath() {
return _flowSinkPath;
}
public boolean getGenerateMultipathInconsistencyQuery() {
return _genMultipath;
}
public String getGenerateOspfTopologyPath() {
return _genOspfTopology;
}
public boolean getGenerateStubs() {
return _generateStubs;
}
public String getGenerateStubsInputRole() {
return _generateStubsInputRole;
}
public String getGenerateStubsInterfaceDescriptionRegex() {
return _generateStubsInterfaceDescriptionRegex;
}
public int getGenerateStubsRemoteAs() {
return _generateStubsRemoteAs;
}
public List<String> getHelpPredicates() {
return _helpPredicates;
}
public boolean getHistogram() {
return _histogram;
}
public String getHSAInputPath() {
return _hsaInputDir;
}
public String getHSAOutputPath() {
return _hsaOutputDir;
}
public boolean getInterfaceFailureInconsistencyBlackHoleQuery() {
return _blackHole;
}
public boolean getInterfaceFailureInconsistencyReachableQuery() {
return _reach;
}
public String getInterfaceMapPath() {
return _interfaceMapPath;
}
public String getJobLogicBloxHostnamePath() {
return _jobLogicBloxHostnamePath;
}
public int getLbWebAdminPort() {
return _lbWebAdminPort;
}
public int getLbWebPort() {
return _lbWebPort;
}
public String getLogFile() {
return _logFile;
}
public BatfishLogger getLogger() {
return _logger;
}
public String getLogicDir() {
return _logicDir;
}
public String getLogicSrcDir() {
return _logicSrcDir;
}
public String getLogLevel() {
return _logLevel;
}
public String getMultipathInconsistencyQueryPath() {
return _mpiPath;
}
public String[] getNegatedConcretizerInputFilePaths() {
return _negatedConcretizerInputFilePaths;
}
public String getNodeRolesPath() {
return _nodeRolesPath;
}
public String getNodeSetPath() {
return _nodeSetPath;
}
public boolean getNoTraffic() {
return _noTraffic;
}
public boolean getParseParallel() {
return _parseParallel;
}
public boolean getPedanticAsError() {
return _pedanticAsError;
}
public boolean getPedanticRecord() {
return _pedanticRecord;
}
public boolean getPostFlows() {
return _postFlows;
}
public List<String> getPredicates() {
return _predicates;
}
public boolean getPrintSemantics() {
return _printSemantics;
}
public boolean getQuery() {
return _query;
}
public boolean getQueryAll() {
return _queryAll;
}
public String getQueryDumpDir() {
return _queryDumpDir;
}
public String getQuestionName() {
return _questionName;
}
public String getQuestionPath() {
return _questionPath;
}
public String getReachableQueryPath() {
return _reachPath;
}
public boolean getRedFlagAsError() {
return _redFlagAsError;
}
public boolean getRedFlagRecord() {
return _redFlagRecord;
}
public boolean getRemoveFacts() {
return _removeFacts;
}
public boolean getRoleHeaders() {
return _roleHeaders;
}
public String getRoleNodesPath() {
return _roleNodesPath;
}
public boolean getRoleReachabilityQuery() {
return _roleReachabilityQuery;
}
public String getRoleReachabilityQueryPath() {
return _roleReachabilityQueryPath;
}
public String getRoleSetPath() {
return _roleSetPath;
}
public boolean getRoleTransitQuery() {
return _roleTransitQuery;
}
public String getRoleTransitQueryPath() {
return _roleTransitQueryPath;
}
public boolean getSerializeIndependent() {
return _serializeIndependent;
}
public String getSerializeIndependentPath() {
return _serializeIndependentPath;
}
public boolean getSerializeToText() {
return _serializeToText;
}
public boolean getSerializeVendor() {
return _serializeVendor;
}
public String getSerializeVendorPath() {
return _serializeVendorPath;
}
public String getServiceHost() {
return _serviceHost;
}
public String getServiceLogicBloxHostname() {
return _serviceLogicBloxHostname;
}
public int getServicePort() {
return _servicePort;
}
public String getServiceUrl() {
return _serviceUrl;
}
public boolean getSimplify() {
return _simplify;
}
public String getTestRigPath() {
return _testRigPath;
}
public boolean getThrowOnLexerError() {
return _throwOnLexerError;
}
public boolean getThrowOnParserError() {
return _throwOnParserError;
}
public boolean getTimestamp() {
return _timestamp;
}
public String getTrafficFactDumpDir() {
return _trafficFactDumpDir;
}
public boolean getUnimplementedAsError() {
return _unimplementedAsError;
}
public boolean getUnimplementedRecord() {
return _unimplementedRecord;
}
public boolean getUpdate() {
return _update;
}
public String getVarSizeMapPath() {
return _varSizeMapPath;
}
public String getWorkspaceName() {
return _workspaceName;
}
public boolean getZ3() {
return _z3;
}
public String getZ3File() {
return _z3File;
}
public boolean ignoreUnsupported() {
return _ignoreUnsupported;
}
private void initOptions() {
_options = new Options();
_options.addOption(Option
.builder()
.argName("predicates")
.hasArgs()
.desc("list of LogicBlox predicates to query (defaults to '"
+ DEFAULT_PREDICATES.get(0) + "')").longOpt(ARG_PREDICATES)
.build());
_options.addOption(Option.builder().argName("predicates").hasArgs()
.desc("list of LogicBlox fact predicates to suppress")
.longOpt(ARG_DISABLED_FACTS).build());
_options.addOption(Option
.builder()
.argName("path")
.hasArg()
.desc("path to test rig directory (defaults to \""
+ DEFAULT_TEST_RIG_PATH + "\")").longOpt(ARG_TEST_RIG_PATH)
.build());
_options
.addOption(Option.builder().argName("name").hasArg()
.desc("name of LogicBlox workspace").longOpt(ARG_WORKSPACE)
.build());
_options.addOption(Option.builder().argName("hostname").hasArg()
.desc("hostname of ConnectBlox server for regular session")
.longOpt(ARG_CB_HOST).build());
_options.addOption(Option.builder().argName("port_number").hasArg()
.desc("port of ConnectBlox server for regular session")
.longOpt(ARG_CB_PORT).build());
_options.addOption(Option.builder().argName(ARGNAME_LB_WEB_PORT).hasArg()
.desc("port of lb-web server").longOpt(ARG_LB_WEB_PORT).build());
_options.addOption(Option.builder().argName(ARGNAME_LB_WEB_ADMIN_PORT)
.hasArg().desc("admin port lb-web server")
.longOpt(ARG_LB_WEB_ADMIN_PORT).build());
_options
.addOption(Option
.builder()
.argName("predicates")
.optionalArg(true)
.hasArgs()
.desc("print semantics for all predicates, or for predicates supplied as optional arguments")
.longOpt(ARG_PREDHELP).build());
_options.addOption(Option.builder().desc("print this message")
.longOpt(ARG_HELP).build());
_options.addOption(Option.builder().desc("query workspace")
.longOpt(ARG_QUERY).build());
_options.addOption(Option.builder()
.desc("return predicate cardinalities instead of contents")
.longOpt(ARG_COUNT).build());
_options.addOption(Option.builder().desc("query ALL predicates")
.longOpt(ARG_QUERY_ALL).build());
_options.addOption(Option.builder()
.desc("create workspace and add project logic")
.longOpt(ARG_COMPILE).build());
_options.addOption(Option.builder().desc("add facts to workspace")
.longOpt(ARG_FACTS).build());
_options.addOption(Option.builder()
.desc("remove facts instead of adding them")
.longOpt(ARG_REMOVE_FACTS).build());
_options.addOption(Option.builder().desc("display results in GUI")
.longOpt(ARG_GUI).build());
_options.addOption(Option.builder()
.desc("differentially update test rig workspace")
.longOpt(ARG_UPDATE).build());
_options.addOption(Option.builder()
.desc("do not add injected traffic facts").longOpt(ARG_NO_TRAFFIC)
.build());
_options
.addOption(Option
.builder()
.desc("exit on first parse error (otherwise will exit on last parse error)")
.longOpt(ARG_EXIT_ON_PARSE_ERROR).build());
_options.addOption(Option.builder().desc("generate z3 data plane logic")
.longOpt(ARG_Z3).build());
_options.addOption(Option.builder().argName(ARGNAME_Z3_OUTPUT).hasArg()
.desc("set z3 data plane logic output file").longOpt(ARG_Z3_OUTPUT)
.build());
_options.addOption(Option.builder()
.argName(ARGNAME_Z3_CONCRETIZER_INPUT_FILES).hasArgs()
.desc("set z3 concretizer input file(s)")
.longOpt(ARG_Z3_CONCRETIZER_INPUT_FILES).build());
_options.addOption(Option.builder()
.argName(ARGNAME_Z3_CONCRETIZER_NEGATED_INPUT_FILES).hasArgs()
.desc("set z3 negated concretizer input file(s)")
.longOpt(ARG_Z3_CONCRETIZER_NEGATED_INPUT_FILES).build());
_options.addOption(Option.builder()
.argName(ARGNAME_Z3_CONCRETIZER_OUTPUT_FILE).hasArg()
.desc("set z3 concretizer output file")
.longOpt(ARG_Z3_CONCRETIZER_OUTPUT_FILE).build());
_options.addOption(Option.builder()
.desc("create z3 logic to concretize data plane constraints")
.longOpt(ARG_Z3_CONCRETIZE).build());
_options.addOption(Option.builder()
.desc("push concrete flows into logicblox databse")
.longOpt(ARG_FLOWS).build());
_options.addOption(Option.builder().argName(ARGNAME_FLOW_PATH).hasArg()
.desc("path to concrete flows").longOpt(ARG_FLOW_PATH).build());
_options.addOption(Option.builder().argName(ARGNAME_FLOW_SINK_PATH)
.hasArg().desc("path to flow sinks").longOpt(ARG_FLOW_SINK_PATH)
.build());
_options.addOption(Option.builder()
.desc("dump intermediate format of configurations")
.longOpt(ARG_DUMP_IF).build());
_options.addOption(Option.builder().argName(ARGNAME_DUMP_IF_DIR).hasArg()
.desc("directory to dump intermediate format files")
.longOpt(ARG_DUMP_IF_DIR).build());
_options.addOption(Option.builder().desc("dump control plane facts")
.longOpt(ARG_DUMP_CONTROL_PLANE_FACTS).build());
_options.addOption(Option.builder().desc("dump traffic facts")
.longOpt(ARG_DUMP_TRAFFIC_FACTS).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_DUMP_FACTS_DIR)
.desc("directory to dump LogicBlox facts")
.longOpt(ARG_DUMP_FACTS_DIR).build());
_options.addOption(Option.builder().hasArg().argName(ARGNAME_REVERT)
.desc("revert test rig workspace to specified branch")
.longOpt(ARG_REVERT).build());
_options.addOption(Option.builder().desc("redirect stderr to stdout")
.longOpt(ARG_REDIRECT_STDERR).build());
_options.addOption(Option.builder().hasArg().argName(ARGNAME_ANONYMIZE)
.desc("created anonymized versions of configs in test rig")
.longOpt(ARG_ANONYMIZE).build());
_options
.addOption(Option
.builder()
.hasArg()
.argName(ARGNAME_LOGICDIR)
.desc("set logic dir with respect to filesystem of machine running LogicBlox")
.longOpt(ARG_LOGICDIR).build());
_options.addOption(Option.builder().desc("disable z3 simplification")
.longOpt(ARG_DISABLE_Z3_SIMPLIFICATION).build());
_options.addOption(Option.builder().desc("serialize vendor configs")
.longOpt(ARG_SERIALIZE_VENDOR).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_SERIALIZE_VENDOR_PATH)
.desc("path to read or write serialized vendor configs")
.longOpt(ARG_SERIALIZE_VENDOR_PATH).build());
_options.addOption(Option.builder()
.desc("serialize vendor-independent configs")
.longOpt(ARG_SERIALIZE_INDEPENDENT).build());
_options
.addOption(Option
.builder()
.hasArg()
.argName(ARGNAME_SERIALIZE_INDEPENDENT_PATH)
.desc("path to read or write serialized vendor-independent configs")
.longOpt(ARG_SERIALIZE_INDEPENDENT_PATH).build());
_options.addOption(Option.builder()
.desc("compute and serialize data plane (requires logicblox)")
.longOpt(ARG_DATA_PLANE).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_DATA_PLANE_DIR)
.desc("path to read or write serialized data plane")
.longOpt(ARG_DATA_PLANE_DIR).build());
_options.addOption(Option.builder().desc("print parse trees")
.longOpt(ARG_PRINT_PARSE_TREES).build());
_options.addOption(Option.builder().desc("dump interface descriptions")
.longOpt(ARG_DUMP_INTERFACE_DESCRIPTIONS).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_DUMP_INTERFACE_DESCRIPTIONS_PATH)
.desc("path to read or write interface descriptions")
.longOpt(ARG_DUMP_INTERFACE_DESCRIPTIONS_PATH).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_NODE_SET_PATH)
.desc("path to read or write node set").longOpt(ARG_NODE_SET_PATH)
.build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_INTERFACE_MAP_PATH)
.desc("path to read or write interface-number mappings")
.longOpt(ARG_INTERFACE_MAP_PATH).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_VAR_SIZE_MAP_PATH)
.desc("path to read or write var-size mappings")
.longOpt(ARG_VAR_SIZE_MAP_PATH).build());
_options.addOption(Option.builder()
.desc("generate multipath-inconsistency query").longOpt(ARG_MPI)
.build());
_options.addOption(Option.builder().hasArg().argName(ARGNAME_MPI_PATH)
.desc("path to read or write multipath-inconsistency query")
.longOpt(ARG_MPI_PATH).build());
_options.addOption(Option.builder().desc("serialize to text")
.longOpt(ARG_SERIALIZE_TO_TEXT).build());
_options.addOption(Option.builder().desc("run in service mode")
.longOpt(ARG_SERVICE_MODE).build());
_options
.addOption(Option.builder().argName("port_number").hasArg()
.desc("port for batfish service").longOpt(ARG_SERVICE_PORT)
.build());
_options.addOption(Option.builder().argName("base_url").hasArg()
.desc("base url for batfish service").longOpt(ARG_SERVICE_URL)
.build());
_options
.addOption(Option
.builder()
.hasArg()
.argName(ARGNAME_BUILD_PREDICATE_INFO)
.desc("build predicate info (should only be called by ant build script) with provided input logic dir")
.longOpt(ARG_BUILD_PREDICATE_INFO).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_BLACKLIST_INTERFACE)
.desc("interface to blacklist (force inactive) during analysis")
.longOpt(ARG_BLACKLIST_INTERFACE).build());
_options
.addOption(Option
.builder()
.hasArg()
.argName(ARGNAME_BLACKLIST_NODE)
.desc("node to blacklist (remove from configuration structures) during analysis")
.longOpt(ARG_BLACKLIST_NODE).build());
_options.addOption(Option.builder().hasArg().argName(ARGNAME_ACCEPT_NODE)
.desc("accept node for reachability query")
.longOpt(ARG_ACCEPT_NODE).build());
_options
.addOption(Option
.builder()
.desc("generate interface-failure-inconsistency reachable packet query")
.longOpt(ARG_REACH).build());
_options
.addOption(Option
.builder()
.hasArg()
.argName(ARGNAME_REACH_PATH)
.desc("path to read or write interface-failure-inconsistency reachable packet query")
.longOpt(ARG_REACH_PATH).build());
_options
.addOption(Option
.builder()
.desc("generate interface-failure-inconsistency black-hole packet query")
.longOpt(ARG_BLACK_HOLE).build());
_options
.addOption(Option
.builder()
.desc("only concretize single packet (do not break up disjunctions)")
.longOpt(ARG_CONC_UNIQUE).build());
_options
.addOption(Option
.builder()
.hasArg()
.argName(ARGNAME_BLACK_HOLE_PATH)
.desc("path to read or write interface-failure-inconsistency black-hole packet query")
.longOpt(ARG_BLACK_HOLE_PATH).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_BLACKLIST_DST_IP)
.desc("destination ip to blacklist for concretizer queries")
.longOpt(ARG_BLACKLIST_DST_IP_PATH).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_NODE_ROLES_PATH)
.desc("path to read or write node-role mappings")
.longOpt(ARG_NODE_ROLES_PATH).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_ROLE_NODES_PATH)
.desc("path to read or write role-node mappings")
.longOpt(ARG_ROLE_NODES_PATH).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_ROLE_REACHABILITY_QUERY_PATH)
.desc("path to read or write role-reachability queries")
.longOpt(ARG_ROLE_REACHABILITY_QUERY_PATH).build());
_options.addOption(Option.builder()
.desc("generate role-reachability queries")
.longOpt(ARG_ROLE_REACHABILITY_QUERY).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_ROLE_TRANSIT_QUERY_PATH)
.desc("path to read or write role-transit queries")
.longOpt(ARG_ROLE_TRANSIT_QUERY_PATH).build());
_options.addOption(Option.builder().desc("generate role-transit queries")
.longOpt(ARG_ROLE_TRANSIT_QUERY).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_ROLE_SET_PATH)
.desc("path to read or write role set").longOpt(ARG_ROLE_SET_PATH)
.build());
_options.addOption(Option.builder()
.desc("duplicate flows across all nodes in same role")
.longOpt(ARG_DUPLICATE_ROLE_FLOWS).build());
_options.addOption(Option.builder().hasArg().argName(ARGNAME_LOG_LEVEL)
.desc("log level").longOpt(ARG_LOG_LEVEL).build());
_options.addOption(Option.builder()
.desc("header of concretized z3 output refers to role, not node")
.longOpt(ARG_ROLE_HEADERS).build());
_options.addOption(Option.builder()
.desc("throw exception immediately on parser error")
.longOpt(ARG_THROW_ON_PARSER_ERROR).build());
_options.addOption(Option.builder()
.desc("throw exception immediately on lexer error")
.longOpt(ARG_THROW_ON_LEXER_ERROR).build());
_options.addOption(Option.builder()
.desc("flatten hierarchical juniper configuration files")
.longOpt(ARG_FLATTEN).build());
_options
.addOption(Option
.builder()
.hasArg()
.argName(ARGNAME_FLATTEN_SOURCE)
.desc("path to test rig containing hierarchical juniper configurations to be flattened")
.longOpt(ARG_FLATTEN_SOURCE).build());
_options
.addOption(Option
.builder()
.hasArg()
.argName(ARGNAME_FLATTEN_DESTINATION)
.desc("output path to test rig in which flat juniper (and all other) configurations will be placed")
.longOpt(ARG_FLATTEN_DESTINATION).build());
_options
.addOption(Option
.builder()
.desc("flatten hierarchical juniper configuration files on-the-fly (line number references will be spurious)")
.longOpt(ARG_FLATTEN_ON_THE_FLY).build());
_options
.addOption(Option
.builder()
.desc("throws "
+ PedanticBatfishException.class.getSimpleName()
+ " for likely harmless warnings (e.g. deviation from good configuration style), instead of emitting warning and continuing")
.longOpt(ARG_PEDANTIC_AS_ERROR).build());
_options.addOption(Option.builder().desc("suppresses pedantic warnings")
.longOpt(ARG_PEDANTIC_SUPPRESS).build());
_options
.addOption(Option
.builder()
.desc("throws "
+ RedFlagBatfishException.class.getSimpleName()
+ " on some recoverable errors (e.g. bad config lines), instead of emitting warning and attempting to recover")
.longOpt(ARG_RED_FLAG_AS_ERROR).build());
_options.addOption(Option.builder().desc("suppresses red-flag warnings")
.longOpt(ARG_RED_FLAG_SUPPRESS).build());
_options
.addOption(Option
.builder()
.desc("throws "
+ UnimplementedBatfishException.class.getSimpleName()
+ " when encountering unimplemented configuration directives, instead of emitting warning and ignoring")
.longOpt(ARG_UNIMPLEMENTED_AS_ERROR).build());
_options.addOption(Option.builder()
.desc("suppresses unimplemented-configuration-directive warnings")
.longOpt(ARG_UNIMPLEMENTED_SUPPRESS).build());
_options.addOption(Option.builder()
.desc("build histogram of unimplemented features")
.longOpt(ARG_HISTOGRAM).build());
_options.addOption(Option.builder().desc("generate stubs")
.longOpt(ARG_GENERATE_STUBS).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_GENERATE_STUBS_INPUT_ROLE)
.desc("input role for which to generate stubs")
.longOpt(ARG_GENERATE_STUBS_INPUT_ROLE).build());
_options
.addOption(Option
.builder()
.hasArg()
.argName(ARGNAME_GENERATE_STUBS_INTERFACE_DESCRIPTION_REGEX)
.desc("java regex to extract hostname of generated stub from description of adjacent interface")
.longOpt(ARG_GENERATE_STUBS_INTERFACE_DESCRIPTION_REGEX)
.build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_GENERATE_STUBS_REMOTE_AS)
.desc("autonomous system number of stubs to be generated")
.longOpt(ARG_GENERATE_STUBS_REMOTE_AS).build());
_options.addOption(Option.builder().hasArg().argName(ARGNAME_LOG_FILE)
.desc("path to main log file").longOpt(ARG_LOG_FILE).build());
_options.addOption(Option.builder().hasArg().argName(ARGNAME_GEN_OSPF)
.desc("generate ospf configs from specified topology")
.longOpt(ARG_GEN_OSPF).build());
_options.addOption(Option.builder()
.desc("print timestamps in log messages").longOpt(ARG_TIMESTAMP)
.build());
_options
.addOption(Option
.builder()
.desc("ignore configuration files with unsupported format instead of crashing")
.longOpt(ARG_IGNORE_UNSUPPORTED).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_AUTO_BASE_DIR)
.desc("path to base dir for automatic i/o path selection")
.longOpt(ARG_AUTO_BASE_DIR).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_ENVIRONMENT_NAME)
.desc("name of environment to use").longOpt(ARG_ENVIRONMENT_NAME)
.build());
_options
.addOption(Option
.builder()
.hasArg()
.argName(ARGNAME_SERVICE_LOGICBLOX_HOSTNAME)
.desc("hostname of LogicBlox server to be used by batfish service when creating workspaces")
.longOpt(ARG_SERVICE_LOGICBLOX_HOSTNAME).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_QUESTION_NAME).desc("name of question")
.longOpt(BfConsts.ARG_QUESTION_NAME).build());
_options.addOption(Option.builder().desc("answer provided question")
.longOpt(BfConsts.COMMAND_ANSWER).build());
_options.addOption(Option.builder()
.desc("post dumped flows to logicblox")
.longOpt(BfConsts.COMMAND_POST_FLOWS).build());
_options.addOption(Option.builder().desc("parse configs in parallel")
.longOpt(ARG_PARSE_PARALLEL).build());
_options.addOption(Option.builder().argName("port_number").hasArg()
.desc("coordinator work manager listening port")
.longOpt(ARG_COORDINATOR_WORK_PORT).build());
_options.addOption(Option.builder().argName("port_number").hasArg()
.desc("coordinator pool manager listening port")
.longOpt(ARG_COORDINATOR_POOL_PORT).build());
_options.addOption(Option.builder().hasArg()
.argName(ARGNAME_SERVICE_HOST)
.desc("local hostname to report to coordinator")
.longOpt(ARG_SERVICE_HOST).build());
_options.addOption(Option
.builder()
.hasArg()
.argName(ARGNAME_COORDINATOR_HOST)
.desc("hostname of coordinator for registration with -"
+ ARG_SERVICE_MODE).longOpt(ARG_COORDINATOR_HOST).build());
}
private void parseCommandLine(String[] args) throws ParseException {
_canExecute = true;
_runInServiceMode = false;
_printSemantics = false;
CommandLine line = null;
CommandLineParser parser = new DefaultParser();
// parse the command line arguments
line = parser.parse(_options, args);
_logLevel = line.getOptionValue(ARG_LOG_LEVEL, DEFAULT_LOG_LEVEL);
_logFile = line.getOptionValue(ARG_LOG_FILE);
if (line.hasOption(ARG_HELP)) {
_canExecute = false;
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.setLongOptPrefix("-");
formatter.printHelp(EXECUTABLE_NAME, _options);
return;
}
_runInServiceMode = line.hasOption(ARG_SERVICE_MODE);
_servicePort = Integer.parseInt(line.getOptionValue(ARG_SERVICE_PORT,
DEFAULT_SERVICE_PORT));
_serviceUrl = line.getOptionValue(ARG_SERVICE_URL, DEFAULT_SERVICE_URL);
_counts = line.hasOption(ARG_COUNT);
_queryAll = line.hasOption(ARG_QUERY_ALL);
_query = line.hasOption(ARG_QUERY);
if (line.hasOption(ARG_PREDHELP)) {
_printSemantics = true;
String[] optionValues = line.getOptionValues(ARG_PREDHELP);
if (optionValues != null) {
_helpPredicates = Arrays.asList(optionValues);
}
}
_cbHost = line.getOptionValue(ARG_CB_HOST, DEFAULT_CONNECTBLOX_HOST);
_cbPort = Integer.parseInt(line.getOptionValue(ARG_CB_PORT,
DEFAULT_CONNECTBLOX_REGULAR_PORT));
_testRigPath = line.getOptionValue(ARG_TEST_RIG_PATH,
DEFAULT_TEST_RIG_PATH);
_workspaceName = line.getOptionValue(ARG_WORKSPACE, null);
_disabledFacts = new HashSet<String>();
if (line.hasOption(ARG_DISABLED_FACTS)) {
_disabledFacts.addAll(Arrays.asList(line
.getOptionValues(ARG_DISABLED_FACTS)));
}
if (line.hasOption(ARG_PREDICATES)) {
_predicates = Arrays.asList(line.getOptionValues(ARG_PREDICATES));
}
else {
_predicates = DEFAULT_PREDICATES;
}
_removeFacts = line.hasOption(ARG_REMOVE_FACTS);
_compile = line.hasOption(ARG_COMPILE);
_facts = line.hasOption(ARG_FACTS);
_update = line.hasOption(ARG_UPDATE);
_noTraffic = line.hasOption(ARG_NO_TRAFFIC);
_exitOnParseError = line.hasOption(ARG_EXIT_ON_PARSE_ERROR);
_z3 = line.hasOption(ARG_Z3);
if (_z3) {
_z3File = line.getOptionValue(ARG_Z3_OUTPUT);
}
_concretize = line.hasOption(ARG_Z3_CONCRETIZE);
if (_concretize) {
_concretizerInputFilePaths = line
.getOptionValues(ARG_Z3_CONCRETIZER_INPUT_FILES);
_negatedConcretizerInputFilePaths = line
.getOptionValues(ARG_Z3_CONCRETIZER_NEGATED_INPUT_FILES);
_concretizerOutputFilePath = line
.getOptionValue(ARG_Z3_CONCRETIZER_OUTPUT_FILE);
}
_flows = line.hasOption(ARG_FLOWS);
if (_flows) {
_flowPath = line.getOptionValue(ARG_FLOW_PATH, DEFAULT_FLOW_PATH);
}
_flowSinkPath = line.getOptionValue(ARG_FLOW_SINK_PATH);
_dumpIF = line.hasOption(ARG_DUMP_IF);
if (_dumpIF) {
_dumpIFDir = line.getOptionValue(ARG_DUMP_IF_DIR, DEFAULT_DUMP_IF_DIR);
}
_dumpControlPlaneFacts = line.hasOption(ARG_DUMP_CONTROL_PLANE_FACTS);
_dumpTrafficFacts = line.hasOption(ARG_DUMP_TRAFFIC_FACTS);
_dumpFactsDir = line.getOptionValue(ARG_DUMP_FACTS_DIR);
_revertBranchName = line.getOptionValue(ARG_REVERT);
_revert = (_revertBranchName != null);
_redirectStdErr = line.hasOption(ARG_REDIRECT_STDERR);
_anonymize = line.hasOption(ARG_ANONYMIZE);
if (_anonymize) {
_anonymizeDir = line.getOptionValue(ARG_ANONYMIZE);
}
_logicDir = line.getOptionValue(ARG_LOGICDIR, null);
_simplify = DEFAULT_Z3_SIMPLIFY;
if (line.hasOption(ARG_DISABLE_Z3_SIMPLIFICATION)) {
_simplify = false;
}
_serializeVendor = line.hasOption(ARG_SERIALIZE_VENDOR);
_serializeVendorPath = line.getOptionValue(ARG_SERIALIZE_VENDOR_PATH,
DEFAULT_SERIALIZE_VENDOR_PATH);
_serializeIndependent = line.hasOption(ARG_SERIALIZE_INDEPENDENT);
_serializeIndependentPath = line.getOptionValue(
ARG_SERIALIZE_INDEPENDENT_PATH, DEFAULT_SERIALIZE_INDEPENDENT_PATH);
_dataPlane = line.hasOption(ARG_DATA_PLANE);
_dataPlaneDir = line.getOptionValue(ARG_DATA_PLANE_DIR);
_printParseTree = line.hasOption(ARG_PRINT_PARSE_TREES);
_dumpInterfaceDescriptions = line
.hasOption(ARG_DUMP_INTERFACE_DESCRIPTIONS);
_dumpInterfaceDescriptionsPath = line.getOptionValue(
ARG_DUMP_INTERFACE_DESCRIPTIONS_PATH,
DEFAULT_DUMP_INTERFACE_DESCRIPTIONS_PATH);
_nodeSetPath = line.getOptionValue(ARG_NODE_SET_PATH);
_interfaceMapPath = line.getOptionValue(ARG_INTERFACE_MAP_PATH);
_varSizeMapPath = line.getOptionValue(ARG_VAR_SIZE_MAP_PATH);
_genMultipath = line.hasOption(ARG_MPI);
_mpiPath = line.getOptionValue(ARG_MPI_PATH);
_serializeToText = line.hasOption(ARG_SERIALIZE_TO_TEXT);
_lbWebPort = Integer.parseInt(line.getOptionValue(ARG_LB_WEB_PORT,
DEFAULT_LB_WEB_PORT));
_lbWebAdminPort = Integer.parseInt(line.getOptionValue(
ARG_LB_WEB_ADMIN_PORT, DEFAULT_LB_WEB_ADMIN_PORT));
_buildPredicateInfo = line.hasOption(ARG_BUILD_PREDICATE_INFO);
if (_buildPredicateInfo) {
_logicSrcDir = line.getOptionValue(ARG_BUILD_PREDICATE_INFO);
}
_blacklistInterface = line.getOptionValue(ARG_BLACKLIST_INTERFACE);
_blacklistNode = line.getOptionValue(ARG_BLACKLIST_NODE);
_reach = line.hasOption(ARG_REACH);
_reachPath = line.getOptionValue(ARG_REACH_PATH);
_blackHole = line.hasOption(ARG_BLACK_HOLE);
_blackHolePath = line.getOptionValue(ARG_BLACK_HOLE_PATH);
_blacklistDstIpPath = line.getOptionValue(ARG_BLACKLIST_DST_IP_PATH);
_concUnique = line.hasOption(ARG_CONC_UNIQUE);
_acceptNode = line.getOptionValue(ARG_ACCEPT_NODE);
_nodeRolesPath = line.getOptionValue(ARG_NODE_ROLES_PATH);
_roleNodesPath = line.getOptionValue(ARG_ROLE_NODES_PATH);
_roleReachabilityQueryPath = line
.getOptionValue(ARG_ROLE_REACHABILITY_QUERY_PATH);
_roleReachabilityQuery = line.hasOption(ARG_ROLE_REACHABILITY_QUERY);
_roleTransitQueryPath = line.getOptionValue(ARG_ROLE_TRANSIT_QUERY_PATH);
_roleTransitQuery = line.hasOption(ARG_ROLE_TRANSIT_QUERY);
_roleSetPath = line.getOptionValue(ARG_ROLE_SET_PATH);
_duplicateRoleFlows = line.hasOption(ARG_DUPLICATE_ROLE_FLOWS);
_roleHeaders = line.hasOption(ARG_ROLE_HEADERS);
_throwOnParserError = line.hasOption(ARG_THROW_ON_PARSER_ERROR);
_throwOnLexerError = line.hasOption(ARG_THROW_ON_LEXER_ERROR);
_flatten = line.hasOption(ARG_FLATTEN);
_flattenSource = line.getOptionValue(ARG_FLATTEN_SOURCE);
_flattenDestination = line.getOptionValue(ARG_FLATTEN_DESTINATION);
_flattenOnTheFly = line.hasOption(ARG_FLATTEN_ON_THE_FLY);
_pedanticAsError = line.hasOption(ARG_PEDANTIC_AS_ERROR);
_pedanticRecord = !line.hasOption(ARG_PEDANTIC_SUPPRESS);
_redFlagAsError = line.hasOption(ARG_RED_FLAG_AS_ERROR);
_redFlagRecord = !line.hasOption(ARG_RED_FLAG_SUPPRESS);
_unimplementedAsError = line.hasOption(ARG_UNIMPLEMENTED_AS_ERROR);
_unimplementedRecord = !line.hasOption(ARG_UNIMPLEMENTED_SUPPRESS);
_histogram = line.hasOption(ARG_HISTOGRAM);
_generateStubs = line.hasOption(ARG_GENERATE_STUBS);
_generateStubsInputRole = line
.getOptionValue(ARG_GENERATE_STUBS_INPUT_ROLE);
_generateStubsInterfaceDescriptionRegex = line
.getOptionValue(ARG_GENERATE_STUBS_INTERFACE_DESCRIPTION_REGEX);
if (line.hasOption(ARG_GENERATE_STUBS_REMOTE_AS)) {
_generateStubsRemoteAs = Integer.parseInt(line
.getOptionValue(ARG_GENERATE_STUBS_REMOTE_AS));
}
_genOspfTopology = line.getOptionValue(ARG_GEN_OSPF);
_timestamp = line.hasOption(ARG_TIMESTAMP);
_ignoreUnsupported = line.hasOption(ARG_IGNORE_UNSUPPORTED);
_autoBaseDir = line.getOptionValue(ARG_AUTO_BASE_DIR);
_environmentName = line.getOptionValue(ARG_ENVIRONMENT_NAME);
_serviceLogicBloxHostname = line
.getOptionValue(ARG_SERVICE_LOGICBLOX_HOSTNAME);
_questionName = line.getOptionValue(BfConsts.ARG_QUESTION_NAME);
_answer = line.hasOption(BfConsts.COMMAND_ANSWER);
_postFlows = line.hasOption(BfConsts.COMMAND_POST_FLOWS);
_parseParallel = line.hasOption(ARG_PARSE_PARALLEL);
_coordinatorHost = line.getOptionValue(ARG_COORDINATOR_HOST);
_coordinatorPoolPort = Integer.parseInt(line.getOptionValue(
ARG_COORDINATOR_POOL_PORT, CoordConsts.SVC_POOL_PORT.toString()));
_coordinatorWorkPort = Integer.parseInt(line.getOptionValue(
ARG_COORDINATOR_WORK_PORT, CoordConsts.SVC_WORK_PORT.toString()));
_serviceHost = line.getOptionValue(ARG_SERVICE_HOST);
}
public boolean printParseTree() {
return _printParseTree;
}
public boolean redirectStdErr() {
return _redirectStdErr;
}
public boolean revert() {
return _revert;
}
public boolean runInServiceMode() {
return _runInServiceMode;
}
public void setConnectBloxHost(String hostname) {
_cbHost = hostname;
}
public void setDataPlaneDir(String path) {
_dataPlaneDir = path;
}
public void setDumpFactsDir(String path) {
_dumpFactsDir = path;
}
public void setJobLogicBloxHostnamePath(String path) {
_jobLogicBloxHostnamePath = path;
}
public void setLogger(BatfishLogger logger) {
_logger = logger;
}
public void setLogicDir(String logicDir) {
_logicDir = logicDir;
}
public void setMultipathInconsistencyQueryPath(String path) {
_mpiPath = path;
}
public void setNodeSetPath(String nodeSetPath) {
_nodeSetPath = nodeSetPath;
}
public void setQueryDumpDir(String path) {
_queryDumpDir = path;
}
public void setQuestionPath(String questionPath) {
_questionPath = questionPath;
}
public void setSerializeIndependentPath(String path) {
_serializeIndependentPath = path;
}
public void setSerializeVendorPath(String path) {
_serializeVendorPath = path;
}
public void setServiceLogicBloxHostname(String hostname) {
_serviceLogicBloxHostname = hostname;
}
public void setTestRigPath(String path) {
_testRigPath = path;
}
public void setTrafficFactDumpDir(String path) {
_trafficFactDumpDir = path;
}
public void setWorkspaceName(String name) {
_workspaceName = name;
}
public void setZ3DataPlaneFile(String path) {
_z3File = path;
}
}
| set servicelbhostname to servicehostname by default
| projects/batfish/src/org/batfish/main/Settings.java | set servicelbhostname to servicehostname by default | <ide><path>rojects/batfish/src/org/batfish/main/Settings.java
<ide> _ignoreUnsupported = line.hasOption(ARG_IGNORE_UNSUPPORTED);
<ide> _autoBaseDir = line.getOptionValue(ARG_AUTO_BASE_DIR);
<ide> _environmentName = line.getOptionValue(ARG_ENVIRONMENT_NAME);
<del> _serviceLogicBloxHostname = line
<del> .getOptionValue(ARG_SERVICE_LOGICBLOX_HOSTNAME);
<ide> _questionName = line.getOptionValue(BfConsts.ARG_QUESTION_NAME);
<ide> _answer = line.hasOption(BfConsts.COMMAND_ANSWER);
<ide> _postFlows = line.hasOption(BfConsts.COMMAND_POST_FLOWS);
<ide> _coordinatorWorkPort = Integer.parseInt(line.getOptionValue(
<ide> ARG_COORDINATOR_WORK_PORT, CoordConsts.SVC_WORK_PORT.toString()));
<ide> _serviceHost = line.getOptionValue(ARG_SERVICE_HOST);
<add> // set service logicblox hostname to service hostname unless set
<add> // explicitly
<add> _serviceLogicBloxHostname = line.getOptionValue(
<add> ARG_SERVICE_LOGICBLOX_HOSTNAME, _serviceHost);
<ide> }
<ide>
<ide> public boolean printParseTree() { |
|
Java | apache-2.0 | 7479a5aa940cd8feea98b22a64ffbcba84775090 | 0 | tabish121/proton4j | /*
* 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.messaginghub.amqperative.impl;
import java.io.IOException;
import org.apache.qpid.proton4j.amqp.Binary;
import org.apache.qpid.proton4j.amqp.messaging.AmqpSequence;
import org.apache.qpid.proton4j.amqp.messaging.AmqpValue;
import org.apache.qpid.proton4j.amqp.messaging.ApplicationProperties;
import org.apache.qpid.proton4j.amqp.messaging.Data;
import org.apache.qpid.proton4j.amqp.messaging.DeliveryAnnotations;
import org.apache.qpid.proton4j.amqp.messaging.Footer;
import org.apache.qpid.proton4j.amqp.messaging.Header;
import org.apache.qpid.proton4j.amqp.messaging.MessageAnnotations;
import org.apache.qpid.proton4j.amqp.messaging.Properties;
import org.apache.qpid.proton4j.amqp.messaging.Section;
import org.apache.qpid.proton4j.buffer.ProtonBuffer;
import org.apache.qpid.proton4j.buffer.ProtonBufferAllocator;
import org.apache.qpid.proton4j.buffer.ProtonByteBufferAllocator;
import org.apache.qpid.proton4j.codec.CodecFactory;
import org.apache.qpid.proton4j.codec.Decoder;
import org.apache.qpid.proton4j.codec.DecoderState;
import org.apache.qpid.proton4j.codec.Encoder;
import org.apache.qpid.proton4j.codec.EncoderState;
import org.messaginghub.amqperative.Message;
import org.messaginghub.amqperative.impl.exceptions.ClientExceptionSupport;
/**
* Support methods dealing with Message types and encode or decode operations.
*/
abstract class ClientMessageSupport {
private static final Encoder DEFAULT_ENCODER = CodecFactory.getDefaultEncoder();
private static final Decoder DEFAULT_DECODER = CodecFactory.getDefaultDecoder();
//----- Message Encoding
public static ProtonBuffer encodeMessage(ClientMessage<?> message) {
return encodeMessage(DEFAULT_ENCODER, DEFAULT_ENCODER.newEncoderState(), ProtonByteBufferAllocator.DEFAULT, message);
}
public static ProtonBuffer encodeMessage(Encoder encoder, ProtonBufferAllocator allocator, ClientMessage<?> message) {
return encodeMessage(encoder, encoder.newEncoderState(), ProtonByteBufferAllocator.DEFAULT, message);
}
public static ProtonBuffer encodeMessage(Encoder encoder, EncoderState encoderState, ProtonBufferAllocator allocator, ClientMessage<?> message) {
ProtonBuffer buffer = allocator.allocate();
Header header = message.getHeader();
DeliveryAnnotations deliveryAnnotations = message.getDeliveryAnnotations();
MessageAnnotations messageAnnotations = message.getMessageAnnotations();
Properties properties = message.getProperties();
ApplicationProperties applicationProperties = message.getApplicationProperties();
Section body = message.getBodySection();
Footer footer = message.getFooter();
if (header != null) {
encoder.writeObject(buffer, encoderState, header);
}
if (deliveryAnnotations != null) {
encoder.writeObject(buffer, encoderState, deliveryAnnotations);
}
if (messageAnnotations != null) {
encoder.writeObject(buffer, encoderState, messageAnnotations);
}
if (properties != null) {
encoder.writeObject(buffer, encoderState, properties);
}
if (applicationProperties != null) {
encoder.writeObject(buffer, encoderState, applicationProperties);
}
if (body != null) {
encoder.writeObject(buffer, encoderState, body);
}
if (footer != null) {
encoder.writeObject(buffer, encoderState, footer);
}
return buffer;
}
//----- Message Decoding
public static Message<?> decodeMessage(ProtonBuffer buffer) throws ClientException {
return decodeMessage(DEFAULT_DECODER, DEFAULT_DECODER.newDecoderState(), buffer);
}
public static Message<?> decodeMessage(Decoder decoder, ProtonBuffer buffer) throws ClientException {
return decodeMessage(decoder, decoder.newDecoderState(), buffer);
}
public static Message<?> decodeMessage(Decoder decoder, DecoderState decoderState, ProtonBuffer buffer) throws ClientException {
Header header = null;
DeliveryAnnotations deliveryAnnotations = null;
MessageAnnotations messageAnnotations = null;
Properties properties = null;
ApplicationProperties applicationProperties = null;
Section body = null;
Footer footer = null;
Section section = null;
while (buffer.isReadable()) {
try {
section = (Section) decoder.readObject(buffer, decoderState);
} catch (IOException e) {
throw ClientExceptionSupport.createNonFatalOrPassthrough(e);
}
switch (section.getType()) {
case Header:
header = (Header) section;
break;
case DeliveryAnnotations:
deliveryAnnotations = (DeliveryAnnotations) section;
break;
case MessageAnnotations:
messageAnnotations = (MessageAnnotations) section;
break;
case Properties:
properties = (Properties) section;
break;
case ApplicationProperties:
applicationProperties = (ApplicationProperties) section;
break;
case Data:
case AmqpSequence:
case AmqpValue:
body = section;
break;
case Footer:
footer = (Footer) section;
break;
default:
throw new ClientException("Unknown Message Section forced decode abort.");
}
}
ClientMessage<?> result = createMessageFromBodySection(body);
if (result != null) {
result.setHeader(header);
result.setDeliveryAnnotations(deliveryAnnotations);
result.setMessageAnnotations(messageAnnotations);
result.setProperties(properties);
result.setApplicationProperties(applicationProperties);
result.setFooter(footer);
return result;
}
throw new ClientException("Failed to create Message from encoded payload");
}
private static ClientMessage<?> createMessageFromBodySection(Section body) {
Message<?> result = null;
if (body == null) {
result = Message.create();
} else if (body instanceof Data) {
Binary payload = ((Data) body).getValue();
if (payload != null) {
// TODO - Offset ?
result = Message.create(payload.getArray());
}
} else if (body instanceof AmqpSequence) {
result = Message.create(((AmqpSequence) body).getValue());
} else if (body instanceof AmqpValue) {
Object value = ((AmqpValue) body).getValue();
if (value instanceof String) {
result = Message.create((String) value);
} else {
result = Message.create(value);
}
}
return (ClientMessage<?>) result;
}
}
| protonj2-clients/amqperative-client/src/main/java/org/messaginghub/amqperative/impl/ClientMessageSupport.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.messaginghub.amqperative.impl;
import java.io.IOException;
import org.apache.qpid.proton4j.amqp.Binary;
import org.apache.qpid.proton4j.amqp.messaging.AmqpSequence;
import org.apache.qpid.proton4j.amqp.messaging.AmqpValue;
import org.apache.qpid.proton4j.amqp.messaging.ApplicationProperties;
import org.apache.qpid.proton4j.amqp.messaging.Data;
import org.apache.qpid.proton4j.amqp.messaging.DeliveryAnnotations;
import org.apache.qpid.proton4j.amqp.messaging.Footer;
import org.apache.qpid.proton4j.amqp.messaging.Header;
import org.apache.qpid.proton4j.amqp.messaging.MessageAnnotations;
import org.apache.qpid.proton4j.amqp.messaging.Properties;
import org.apache.qpid.proton4j.amqp.messaging.Section;
import org.apache.qpid.proton4j.buffer.ProtonBuffer;
import org.apache.qpid.proton4j.buffer.ProtonBufferAllocator;
import org.apache.qpid.proton4j.buffer.ProtonByteBufferAllocator;
import org.apache.qpid.proton4j.codec.CodecFactory;
import org.apache.qpid.proton4j.codec.Decoder;
import org.apache.qpid.proton4j.codec.DecoderState;
import org.apache.qpid.proton4j.codec.Encoder;
import org.apache.qpid.proton4j.codec.EncoderState;
import org.messaginghub.amqperative.Message;
import org.messaginghub.amqperative.impl.exceptions.ClientExceptionSupport;
/**
* Support methods dealing with Message types and encode or decode operations.
*/
abstract class ClientMessageSupport {
//----- Message Encoding
public static ProtonBuffer encodeMessage(ClientMessage<?> message) {
return encodeMessage(CodecFactory.getDefaultEncoder(), ProtonByteBufferAllocator.DEFAULT, message);
}
public static ProtonBuffer encodeMessage(Encoder encoder, ProtonBufferAllocator allocator, ClientMessage<?> message) {
// TODO - Hand in the Engine and use configured allocator and or cached encoder
EncoderState encoderState = encoder.newEncoderState();
ProtonBuffer buffer = allocator.allocate();
Header header = message.getHeader();
DeliveryAnnotations deliveryAnnotations = message.getDeliveryAnnotations();
MessageAnnotations messageAnnotations = message.getMessageAnnotations();
Properties properties = message.getProperties();
ApplicationProperties applicationProperties = message.getApplicationProperties();
Section body = message.getBodySection();
Footer footer = message.getFooter();
if (header != null) {
encoder.writeObject(buffer, encoderState, header);
}
if (deliveryAnnotations != null) {
encoder.writeObject(buffer, encoderState, deliveryAnnotations);
}
if (messageAnnotations != null) {
encoder.writeObject(buffer, encoderState, messageAnnotations);
}
if (properties != null) {
encoder.writeObject(buffer, encoderState, properties);
}
if (applicationProperties != null) {
encoder.writeObject(buffer, encoderState, applicationProperties);
}
if (body != null) {
encoder.writeObject(buffer, encoderState, body);
}
if (footer != null) {
encoder.writeObject(buffer, encoderState, footer);
}
return buffer;
}
//----- Message Decoding
public static Message<?> decodeMessage(ProtonBuffer buffer) throws ClientException {
Decoder decoder = CodecFactory.getDefaultDecoder();
DecoderState state = decoder.newDecoderState();
Header header = null;
DeliveryAnnotations deliveryAnnotations = null;
MessageAnnotations messageAnnotations = null;
Properties properties = null;
ApplicationProperties applicationProperties = null;
Section body = null;
Footer footer = null;
Section section = null;
while (buffer.isReadable()) {
try {
section = (Section) decoder.readObject(buffer, state);
} catch (IOException e) {
throw ClientExceptionSupport.createNonFatalOrPassthrough(e);
}
switch (section.getType()) {
case Header:
header = (Header) section;
break;
case DeliveryAnnotations:
deliveryAnnotations = (DeliveryAnnotations) section;
break;
case MessageAnnotations:
messageAnnotations = (MessageAnnotations) section;
break;
case Properties:
properties = (Properties) section;
break;
case ApplicationProperties:
applicationProperties = (ApplicationProperties) section;
break;
case Data:
case AmqpSequence:
case AmqpValue:
body = section;
break;
case Footer:
footer = (Footer) section;
break;
default:
throw new ClientException("Unknown Message Section forced decode abort.");
}
}
ClientMessage<?> result = createMessageFromBodySection(body);
if (result != null) {
result.setHeader(header);
result.setDeliveryAnnotations(deliveryAnnotations);
result.setMessageAnnotations(messageAnnotations);
result.setProperties(properties);
result.setApplicationProperties(applicationProperties);
result.setFooter(footer);
return result;
}
throw new ClientException("Failed to create Message from encoded payload");
}
private static ClientMessage<?> createMessageFromBodySection(Section body) {
Message<?> result = null;
if (body == null) {
result = Message.create();
} else if (body instanceof Data) {
Binary payload = ((Data) body).getValue();
if (payload != null) {
// TODO - Offset ?
result = Message.create(payload.getArray());
}
} else if (body instanceof AmqpSequence) {
result = Message.create(((AmqpSequence) body).getValue());
} else if (body instanceof AmqpValue) {
Object value = ((AmqpValue) body).getValue();
if (value instanceof String) {
result = Message.create((String) value);
} else {
result = Message.create(value);
}
}
return (ClientMessage<?>) result;
}
}
| Optimize the ClientMessageSupport to use a single codec instance
The class was creating a new encoder and decoder on each call which is
expensive and not necessary as the codec itself is thread safe, only the
state objects require thread synchronization or unique copies | protonj2-clients/amqperative-client/src/main/java/org/messaginghub/amqperative/impl/ClientMessageSupport.java | Optimize the ClientMessageSupport to use a single codec instance | <ide><path>rotonj2-clients/amqperative-client/src/main/java/org/messaginghub/amqperative/impl/ClientMessageSupport.java
<ide> */
<ide> abstract class ClientMessageSupport {
<ide>
<add> private static final Encoder DEFAULT_ENCODER = CodecFactory.getDefaultEncoder();
<add> private static final Decoder DEFAULT_DECODER = CodecFactory.getDefaultDecoder();
<add>
<ide> //----- Message Encoding
<ide>
<ide> public static ProtonBuffer encodeMessage(ClientMessage<?> message) {
<del> return encodeMessage(CodecFactory.getDefaultEncoder(), ProtonByteBufferAllocator.DEFAULT, message);
<add> return encodeMessage(DEFAULT_ENCODER, DEFAULT_ENCODER.newEncoderState(), ProtonByteBufferAllocator.DEFAULT, message);
<ide> }
<ide>
<ide> public static ProtonBuffer encodeMessage(Encoder encoder, ProtonBufferAllocator allocator, ClientMessage<?> message) {
<del> // TODO - Hand in the Engine and use configured allocator and or cached encoder
<del> EncoderState encoderState = encoder.newEncoderState();
<add> return encodeMessage(encoder, encoder.newEncoderState(), ProtonByteBufferAllocator.DEFAULT, message);
<add> }
<add>
<add> public static ProtonBuffer encodeMessage(Encoder encoder, EncoderState encoderState, ProtonBufferAllocator allocator, ClientMessage<?> message) {
<ide> ProtonBuffer buffer = allocator.allocate();
<ide>
<ide> Header header = message.getHeader();
<ide> //----- Message Decoding
<ide>
<ide> public static Message<?> decodeMessage(ProtonBuffer buffer) throws ClientException {
<del> Decoder decoder = CodecFactory.getDefaultDecoder();
<del> DecoderState state = decoder.newDecoderState();
<add> return decodeMessage(DEFAULT_DECODER, DEFAULT_DECODER.newDecoderState(), buffer);
<add> }
<ide>
<add> public static Message<?> decodeMessage(Decoder decoder, ProtonBuffer buffer) throws ClientException {
<add> return decodeMessage(decoder, decoder.newDecoderState(), buffer);
<add> }
<add>
<add> public static Message<?> decodeMessage(Decoder decoder, DecoderState decoderState, ProtonBuffer buffer) throws ClientException {
<ide> Header header = null;
<ide> DeliveryAnnotations deliveryAnnotations = null;
<ide> MessageAnnotations messageAnnotations = null;
<ide>
<ide> while (buffer.isReadable()) {
<ide> try {
<del> section = (Section) decoder.readObject(buffer, state);
<add> section = (Section) decoder.readObject(buffer, decoderState);
<ide> } catch (IOException e) {
<ide> throw ClientExceptionSupport.createNonFatalOrPassthrough(e);
<ide> } |
|
Java | bsd-2-clause | 374e48c9671d21c8932192777d0187ac9c0ecde6 | 0 | scifio/scifio | //
// FileStitcher.java
//
/*
LOCI Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan
and Eric Kjellman.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
/**
* Logic to stitch together files with similar names. Stitches based on the
* first series for each file, and assumes that all files have the same
* dimensions.
*/
public class FileStitcher implements IFormatReader {
// -- Fields --
/** FormatReader to use as a template for constituent readers. */
private IFormatReader reader;
/**
* Whether string ids given should be treated
* as file patterns rather than single file paths.
*/
private boolean patternIds = false;
/** Current file pattern string. */
private String currentId;
/** File pattern object used to build the list of files. */
private FilePattern fp;
/** Axis guesser object used to guess which dimensional axes are which. */
private AxisGuesser[] ag;
/** The matching files. */
private String[] files;
/** Reader used for each file. */
private IFormatReader[] readers;
/** Blank buffered image, for use when image counts vary between files. */
private BufferedImage[] blankImage;
/** Blank image bytes, for use when image counts vary between files. */
private byte[][] blankBytes;
/** Image dimensions. */
private int[] width, height;
/** Number of images per file. */
private int[] imagesPerFile;
/** Total number of image planes. */
private int[] totalImages;
/** Dimension order. */
private String[] order;
/** Dimensional axis lengths per file. */
private int[] sizeZ, sizeC, sizeT;
/** Total dimensional axis lengths. */
private int[] totalSizeZ, totalSizeC, totalSizeT;
/** Component lengths for each axis type. */
private int[][] lenZ, lenC, lenT;
/** Whether or not we're doing channel stat calculation (no by default). */
protected boolean enableChannelStatCalculation = false;
/** Whether or not to ignore color tables, if present. */
protected boolean ignoreColorTable = false;
/** Whether or not to normalize float data. */
protected boolean normalizeData = false;
// -- Constructors --
/** Constructs a FileStitcher around a new image reader. */
public FileStitcher() { this(new ImageReader()); }
/**
* Constructs a FileStitcher with the given reader.
* @param r The reader to use for reading stitched files.
*/
public FileStitcher(IFormatReader r) { this(r, false); }
/**
* Constructs a FileStitcher with the given reader.
* @param r The reader to use for reading stitched files.
* @param patternIds Whether string ids given should be treated as file
* patterns rather than single file paths.
*/
public FileStitcher(IFormatReader r, boolean patternIds) {
reader = r;
this.patternIds = patternIds;
}
// -- FileStitcher API methods --
/**
* Gets the axis type for each dimensional block.
* @return An array containing values from the enumeration:
* <ul>
* <li>AxisGuesser.Z_AXIS: focal planes</li>
* <li>AxisGuesser.T_AXIS: time points</li>
* <li>AxisGuesser.C_AXIS: channels</li>
* </ul>
*/
public int[] getAxisTypes(String id)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
return ag[getSeries(id)].getAxisTypes();
}
/**
* Sets the axis type for each dimensional block.
* @param axes An array containing values from the enumeration:
* <ul>
* <li>AxisGuesser.Z_AXIS: focal planes</li>
* <li>AxisGuesser.T_AXIS: time points</li>
* <li>AxisGuesser.C_AXIS: channels</li>
* </ul>
*/
public void setAxisTypes(String id, int[] axes)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
ag[getSeries(id)].setAxisTypes(axes);
computeAxisLengths();
}
/** Gets the file pattern object used to build the list of files. */
public FilePattern getFilePattern(String id)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
return fp;
}
/**
* Gets the axis guesser object used to guess
* which dimensional axes are which.
*/
public AxisGuesser getAxisGuesser(String id)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
return ag[getSeries(id)];
}
/**
* Finds the file pattern for the given ID, based on the state of the file
* stitcher. Takes both ID map entries and the patternIds flag into account.
*/
public FilePattern findPattern(String id) {
if (!patternIds) {
// find the containing pattern
Hashtable map = Location.getIdMap();
String pattern = null;
if (map.containsKey(id)) {
// search ID map for pattern, rather than files on disk
String[] idList = new String[map.size()];
Enumeration en = map.keys();
for (int i=0; i<idList.length; i++) {
idList[i] = (String) en.nextElement();
}
pattern = FilePattern.findPattern(id, null, idList);
}
else {
// id is an unmapped file path; look to similar files on disk
pattern = FilePattern.findPattern(new Location(id));
}
if (pattern != null) id = pattern;
}
return new FilePattern(id);
}
// -- IFormatReader API methods --
/* @see IFormatReader#isThisType(byte[]) */
public boolean isThisType(byte[] block) {
return reader.isThisType(block);
}
/* @see IFormatReader#getImageCount(String) */
public int getImageCount(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return totalImages[getSeries(id)];
}
/* @see IFormatReader#isRGB(String) */
public boolean isRGB(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.isRGB(files[0]);
}
/* @see IFormatReader#getSizeX(String) */
public int getSizeX(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return width[getSeries(id)];
}
/* @see IFormatReader#getSizeY(String) */
public int getSizeY(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return height[getSeries(id)];
}
/* @see IFormatReader#getSizeZ(String) */
public int getSizeZ(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return totalSizeZ[getSeries(id)];
}
/* @see IFormatReader#getSizeC(String) */
public int getSizeC(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return totalSizeC[getSeries(id)];
}
/* @see IFormatReader#getSizeT(String) */
public int getSizeT(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return totalSizeT[getSeries(id)];
}
/* @see IFormatReader#getPixelType(String) */
public int getPixelType(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.getPixelType(files[0]);
}
/* @see IFormatReader#getEffectiveSizeC(String) */
public int getEffectiveSizeC(String id) throws FormatException, IOException {
return FormatReader.getEffectiveSizeC(isRGB(id), getSizeC(id));
}
/* @see IFormatReader#getChannelGlobalMinimum(String, int) */
public Double getChannelGlobalMinimum(String id, int theC)
throws FormatException, IOException
{
int[] include = getIncludeList(id, theC);
Double min = new Double(Double.POSITIVE_INFINITY);
for (int i=0; i<readers.length; i++) {
if (include[i] >= 0) {
Double d = readers[i].getChannelGlobalMinimum(files[i], include[i]);
if (d.compareTo(min) < 0) min = d;
}
}
return min;
}
/* @see IFormatReader#getChannelGlobalMaximum(String, int) */
public Double getChannelGlobalMaximum(String id, int theC)
throws FormatException, IOException
{
int[] include = getIncludeList(id, theC);
Double max = new Double(Double.NEGATIVE_INFINITY);
for (int i=0; i<readers.length; i++) {
if (include[i] >= 0) {
Double d = readers[i].getChannelGlobalMaximum(files[i], include[i]);
if (d.compareTo(max) > 0) max = d;
}
}
return max;
}
/* @see IFormatReader#getThumbSizeX(String) */
public int getThumbSizeX(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.getThumbSizeX(files[0]);
}
/* @see IFormatReader#getThumbSizeY(String) */
public int getThumbSizeY(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.getThumbSizeY(files[0]);
}
/* @see IFormatReader#isLittleEndian(String) */
public boolean isLittleEndian(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.isLittleEndian(files[0]);
}
/**
* Gets a five-character string representing the
* dimension order across the file series.
*/
public String getDimensionOrder(String id)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
return order[getSeries(id)];
}
/* @see IFormatReader#isOrderCertain(String) */
public boolean isOrderCertain(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return ag[getSeries(id)].isCertain();
}
/* @see IFormatReader#setChannelStatCalculationStatus(boolean) */
public void setChannelStatCalculationStatus(boolean on) {
enableChannelStatCalculation = on;
}
/* @see IFormatReader#getChannelStatCalculationStatus */
public boolean getChannelStatCalculationStatus() {
return enableChannelStatCalculation;
}
/* @see IFormatReader#isInterleaved(String) */
public boolean isInterleaved(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.isInterleaved(files[0]);
}
/** Obtains the specified image from the given file series. */
public BufferedImage openImage(String id, int no)
throws FormatException, IOException
{
int[] q = computeIndices(id, no);
int fno = q[0], ino = q[1];
if (ino < readers[fno].getImageCount(files[fno])) {
return readers[fno].openImage(files[fno], ino);
}
// return a blank image to cover for the fact that
// this file does not contain enough image planes
int sno = getSeries(id);
if (blankImage[sno] == null) {
blankImage[sno] = ImageTools.blankImage(width[sno], height[sno],
sizeC[sno], getPixelType(currentId));
}
return blankImage[sno];
}
/** Obtains the specified image from the given file series as a byte array. */
public byte[] openBytes(String id, int no)
throws FormatException, IOException
{
int[] q = computeIndices(id, no);
int fno = q[0], ino = q[1];
if (ino < readers[fno].getImageCount(files[fno])) {
return readers[fno].openBytes(files[fno], ino);
}
// return a blank image to cover for the fact that
// this file does not contain enough image planes
int sno = getSeries(id);
if (blankBytes[sno] == null) {
int bytes = FormatReader.getBytesPerPixel(getPixelType(currentId));
blankBytes[sno] = new byte[width[sno] * height[sno] *
bytes * (isRGB(id) ? sizeC[sno] : 1)];
}
return blankBytes[sno];
}
/* @see IFormatReader#openBytes(String, int, byte[]) */
public byte[] openBytes(String id, int no, byte[] buf)
throws FormatException, IOException
{
int[] q = computeIndices(id, no);
int fno = q[0], ino = q[1];
return readers[fno].openBytes(files[fno], ino, buf);
}
/* @see IFormatReader#openThumbImage(String, int) */
public BufferedImage openThumbImage(String id, int no)
throws FormatException, IOException
{
int[] q = computeIndices(id, no);
int fno = q[0], ino = q[1];
return readers[fno].openThumbImage(files[fno], ino);
}
/* @see IFormatReader#openThumbImage(String, int) */
public byte[] openThumbBytes(String id, int no)
throws FormatException, IOException
{
int[] q = computeIndices(id, no);
int fno = q[0], ino = q[1];
return readers[fno].openThumbBytes(files[fno], ino);
}
/* @see IFormatReader#close() */
public void close() throws FormatException, IOException {
if (readers != null) {
for (int i=0; i<readers.length; i++) readers[i].close();
}
readers = null;
blankImage = null;
blankBytes = null;
currentId = null;
}
/* @see IFormatReader#getSeriesCount(String) */
public int getSeriesCount(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.getSeriesCount(files[0]);
}
/* @see IFormatReader#setSeries(String, int) */
public void setSeries(String id, int no) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
reader.setSeries(files[0], no);
}
/* @see IFormatReader#getSeries(String) */
public int getSeries(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.getSeries(files[0]);
}
/* @see IFormatReader#setColorTableIgnored(boolean) */
public void setColorTableIgnored(boolean ignore) {
ignoreColorTable = ignore;
reader.setColorTableIgnored(ignore);
if (readers != null) {
for (int i=0; i<readers.length; i++) {
readers[i].setColorTableIgnored(ignore);
}
}
}
/* @see IFormatReader#isColorTableIgnored() */
public boolean isColorTableIgnored() { return ignoreColorTable; }
/* @see IFormatReader#setNormalized(boolean) */
public void setNormalized(boolean normalize) {
normalizeData = normalize;
}
/* @see IFormatReader#isNormalized() */
public boolean isNormalized() { return normalizeData; }
/* @see IFormatReader#getUsedFiles() */
public String[] getUsedFiles(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return files;
}
/* @see IFormatReader#getCurrentFile() */
public String getCurrentFile() { return currentId; }
/* @see IFormatReader#swapDimensions(String, String) */
public void swapDimensions(String id, String dimOrder)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
order[getSeries(id)] = dimOrder;
String f0 = files[0];
reader.swapDimensions(f0, dimOrder);
sizeZ[getSeries(id)] = reader.getSizeZ(f0);
sizeC[getSeries(id)] = reader.getSizeC(f0);
sizeT[getSeries(id)] = reader.getSizeT(f0);
computeAxisLengths();
}
/* @see IFormatReader#getIndex(String, int, int, int) */
public int getIndex(String id, int z, int c, int t)
throws FormatException, IOException
{
return FormatReader.getIndex(this, id, z, c, t);
}
/* @see IFormatReader#getZCTCoords(String, int) */
public int[] getZCTCoords(String id, int index)
throws FormatException, IOException
{
return FormatReader.getZCTCoords(this, id, index);
}
/* @see IFormatReader#getMetadataValue(String, String) */
public Object getMetadataValue(String id, String field)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
return reader.getMetadataValue(files[0], field);
}
/* @see IFormatReader#getMetadata(String) */
public Hashtable getMetadata(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.getMetadata(files[0]);
}
/* @see IFormatReader#setMetadataStore(MetadataStore) */
public void setMetadataStore(MetadataStore store) {
reader.setMetadataStore(store);
}
/* @see IFormatReader#getMetadataStore(String) */
public MetadataStore getMetadataStore(String id)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
return reader.getMetadataStore(files[0]);
}
/* @see IFormatReader#getMetadataStoreRoot(String) */
public Object getMetadataStoreRoot(String id)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
return reader.getMetadataStoreRoot(files[0]);
}
/* @see IFormatReader#testRead(String[]) */
public boolean testRead(String[] args) throws FormatException, IOException {
return FormatReader.testRead(this, args);
}
// -- IFormatHandler API methods --
/* @see IFormatHandler#isThisType(String) */
public boolean isThisType(String name) {
return reader.isThisType(name);
}
/* @see IFormatHandler#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
return reader.isThisType(name, open);
}
/* @see IFormatHandler#getFormat() */
public String getFormat() {
return reader.getFormat();
}
/* @see IFormatHandler#getSuffixes() */
public String[] getSuffixes() {
return reader.getSuffixes();
}
/* @see IFormatHandler#getFileFilters() */
public FileFilter[] getFileFilters() {
return reader.getFileFilters();
}
/* @see IFormatHandler#getFileChooser() */
public JFileChooser getFileChooser() {
return reader.getFileChooser();
}
// -- Helper methods --
/** Initializes the given file. */
protected void initFile(String id) throws FormatException, IOException {
if (FormatReader.debug) {
System.out.println("calling FileStitcher.initFile(" + id + ")");
}
currentId = id;
fp = findPattern(id);
// verify that file pattern is valid and matches existing files
String msg = " Please rename your files or disable file stitching.";
if (!fp.isValid()) {
throw new FormatException("Invalid " +
(patternIds ? "file pattern" : "filename") +
" (" + currentId + "): " + fp.getErrorMessage() + msg);
}
files = fp.getFiles();
if (files == null) {
throw new FormatException("No files matching pattern (" +
fp.getPattern() + "). " + msg);
}
for (int i=0; i<files.length; i++) {
if (!new Location(files[i]).exists()) {
throw new FormatException("File #" + i +
" (" + files[i] + ") does not exist.");
}
}
// determine reader type for these files; assume all are the same type
Vector classes = new Vector();
IFormatReader r = reader;
while (r instanceof ReaderWrapper) {
classes.add(r.getClass());
r = ((ReaderWrapper) r).getReader();
}
if (r instanceof ImageReader) r = ((ImageReader) r).getReader(files[0]);
classes.add(r.getClass());
// construct list of readers for all files
readers = new IFormatReader[files.length];
readers[0] = reader;
for (int i=1; i<readers.length; i++) {
// use crazy reflection to instantiate a reader of the proper type
try {
r = null;
for (int j=classes.size()-1; j>=0; j--) {
Class c = (Class) classes.elementAt(j);
if (r == null) r = (IFormatReader) c.newInstance();
else {
r = (IFormatReader) c.getConstructor(
new Class[] {IFormatReader.class}).newInstance(new Object[] {r});
}
}
readers[i] = (IFormatReader) r;
}
catch (InstantiationException exc) { exc.printStackTrace(); }
catch (IllegalAccessException exc) { exc.printStackTrace(); }
catch (NoSuchMethodException exc) { exc.printStackTrace(); }
catch (InvocationTargetException exc) { exc.printStackTrace(); }
}
String f0 = files[0];
int seriesCount = reader.getSeriesCount(f0);
ag = new AxisGuesser[seriesCount];
blankImage = new BufferedImage[seriesCount];
blankBytes = new byte[seriesCount][];
width = new int[seriesCount];
height = new int[seriesCount];
imagesPerFile = new int[seriesCount];
totalImages = new int[seriesCount];
order = new String[seriesCount];
sizeZ = new int[seriesCount];
sizeC = new int[seriesCount];
sizeT = new int[seriesCount];
boolean[] certain = new boolean[seriesCount];
totalSizeZ = new int[seriesCount];
totalSizeC = new int[seriesCount];
totalSizeT = new int[seriesCount];
lenZ = new int[seriesCount][];
lenC = new int[seriesCount][];
lenT = new int[seriesCount][];
// analyze first file; assume each file has the same parameters
int oldSeries = reader.getSeries(f0);
for (int i=0; i<seriesCount; i++) {
reader.setSeries(f0, i);
width[i] = reader.getSizeX(f0);
height[i] = reader.getSizeY(f0);
imagesPerFile[i] = reader.getImageCount(f0);
totalImages[i] = files.length * imagesPerFile[i];
order[i] = reader.getDimensionOrder(f0);
sizeZ[i] = reader.getSizeZ(f0);
sizeC[i] = reader.getSizeC(f0);
sizeT[i] = reader.getSizeT(f0);
certain[i] = reader.isOrderCertain(f0);
}
reader.setSeries(f0, oldSeries);
// guess at dimensions corresponding to file numbering
for (int i=0; i<seriesCount; i++) {
ag[i] = new AxisGuesser(fp, order[i],
sizeZ[i], sizeT[i], sizeC[i], certain[i]);
}
// order may need to be adjusted
for (int i=0; i<seriesCount; i++) {
setSeries(currentId, i);
order[i] = ag[i].getAdjustedOrder();
swapDimensions(currentId, order[i]);
}
setSeries(currentId, oldSeries);
}
/** Computes axis length arrays, and total axis lengths. */
protected void computeAxisLengths() throws FormatException, IOException {
int sno = getSeries(currentId);
int[] count = fp.getCount();
int[] axes = ag[sno].getAxisTypes();
int numZ = ag[sno].getAxisCountZ();
int numC = ag[sno].getAxisCountC();
int numT = ag[sno].getAxisCountT();
totalSizeZ[sno] = sizeZ[sno];
totalSizeC[sno] = sizeC[sno];
totalSizeT[sno] = sizeT[sno];
lenZ[sno] = new int[numZ + 1];
lenC[sno] = new int[numC + 1];
lenT[sno] = new int[numT + 1];
lenZ[sno][0] = sizeZ[sno];
lenC[sno][0] = sizeC[sno];
lenT[sno][0] = sizeT[sno];
int z = 1, c = 1, t = 1;
for (int i=0; i<axes.length; i++) {
switch (axes[i]) {
case AxisGuesser.Z_AXIS:
totalSizeZ[sno] *= count[i];
lenZ[sno][z++] = count[i];
break;
case AxisGuesser.C_AXIS:
totalSizeC[sno] *= count[i];
lenC[sno][c++] = count[i];
break;
case AxisGuesser.T_AXIS:
totalSizeT[sno] *= count[i];
lenT[sno][t++] = count[i];
break;
default:
throw new FormatException("Unknown axis type for axis #" +
i + ": " + axes[i]);
}
}
// populate metadata store
String f0 = files[0];
int pixelType = getPixelType(currentId);
boolean little = reader.isLittleEndian(f0);
MetadataStore s = reader.getMetadataStore(f0);
s.setPixels(new Integer(width[sno]), new Integer(height[sno]),
new Integer(totalSizeZ[sno]), new Integer(totalSizeC[sno]),
new Integer(totalSizeT[sno]), new Integer(pixelType),
new Boolean(!little), order[sno], new Integer(sno));
}
/**
* Gets the file index, and image index into that file,
* corresponding to the given global image index.
*
* @return An array of size 2, dimensioned {file index, image index}.
*/
protected int[] computeIndices(String id, int no)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
int sno = getSeries(id);
int[] axes = ag[sno].getAxisTypes();
int[] count = fp.getCount();
// get Z, C and T positions
int[] zct = getZCTCoords(id, no);
int[] posZ = rasterToPosition(lenZ[sno], zct[0]);
int[] posC = rasterToPosition(lenC[sno], zct[1]);
int[] posT = rasterToPosition(lenT[sno], zct[2]);
// convert Z, C and T position lists into file index and image index
int[] pos = new int[axes.length];
int z = 1, c = 1, t = 1;
for (int i=0; i<axes.length; i++) {
if (axes[i] == AxisGuesser.Z_AXIS) pos[i] = posZ[z++];
else if (axes[i] == AxisGuesser.C_AXIS) pos[i] = posC[c++];
else if (axes[i] == AxisGuesser.T_AXIS) pos[i] = posT[t++];
else {
throw new FormatException("Unknown axis type for axis #" +
i + ": " + axes[i]);
}
}
int fno = positionToRaster(count, pos);
int ino = FormatReader.getIndex(order[sno], sizeZ[sno],
reader.getEffectiveSizeC(files[0]), sizeT[sno], imagesPerFile[sno],
posZ[0], posC[0], posT[0]);
// configure the reader, in case we haven't done this one yet
readers[fno].setChannelStatCalculationStatus(enableChannelStatCalculation);
readers[fno].setSeries(files[fno], reader.getSeries(files[0]));
readers[fno].setColorTableIgnored(ignoreColorTable);
readers[fno].swapDimensions(files[fno], order[sno]);
return new int[] {fno, ino};
}
/**
* Gets a list of readers to include in relation to the given C position.
* @return Array with indices corresponding to the list of readers, and
* values indicating the internal channel index to use for that reader.
*/
protected int[] getIncludeList(String id, int theC)
throws FormatException, IOException
{
int[] include = new int[readers.length];
Arrays.fill(include, -1);
for (int t=0; t<sizeT[getSeries(id)]; t++) {
for (int z=0; z<sizeZ[getSeries(id)]; z++) {
int no = getIndex(id, z, theC, t);
int[] q = computeIndices(id, no);
int fno = q[0], ino = q[1];
include[fno] = ino;
}
}
return include;
}
// -- Utility methods --
/**
* Computes a unique 1-D index corresponding to the multidimensional
* position given in the pos array, using the specified lengths array
* as the maximum value at each positional dimension.
*/
public static int positionToRaster(int[] lengths, int[] pos) {
int[] offsets = new int[lengths.length];
if (offsets.length > 0) offsets[0] = 1;
for (int i=1; i<offsets.length; i++) {
offsets[i] = offsets[i - 1] * lengths[i - 1];
}
int raster = 0;
for (int i=0; i<pos.length; i++) raster += offsets[i] * pos[i];
return raster;
}
/**
* Computes a unique 3-D position corresponding to the given raster
* value, using the specified lengths array as the maximum value at
* each positional dimension.
*/
public static int[] rasterToPosition(int[] lengths, int raster) {
int[] offsets = new int[lengths.length];
if (offsets.length > 0) offsets[0] = 1;
for (int i=1; i<offsets.length; i++) {
offsets[i] = offsets[i - 1] * lengths[i - 1];
}
int[] pos = new int[lengths.length];
for (int i=0; i<pos.length; i++) {
int q = i < pos.length - 1 ? raster % offsets[i + 1] : raster;
pos[i] = q / offsets[i];
raster -= q;
}
return pos;
}
/**
* Computes the maximum raster value of a positional array with
* the given maximum values.
*/
public static int getRasterLength(int[] lengths) {
int len = 1;
for (int i=0; i<lengths.length; i++) len *= lengths[i];
return len;
}
// -- Main method --
public static void main(String[] args) throws FormatException, IOException {
if (!new FileStitcher().testRead(args)) System.exit(1);
}
}
| loci/formats/FileStitcher.java | //
// FileStitcher.java
//
/*
LOCI Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan
and Eric Kjellman.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
/**
* Logic to stitch together files with similar names. Stitches based on the
* first series for each file, and assumes that all files have the same
* dimensions.
*/
public class FileStitcher implements IFormatReader {
// -- Fields --
/** FormatReader to use as a template for constituent readers. */
private IFormatReader reader;
/**
* Whether string ids given should be treated
* as file patterns rather than single file paths.
*/
private boolean patternIds = false;
/** Current file pattern string. */
private String currentId;
/** File pattern object used to build the list of files. */
private FilePattern fp;
/** Axis guesser object used to guess which dimensional axes are which. */
private AxisGuesser[] ag;
/** The matching files. */
private String[] files;
/** Reader used for each file. */
private IFormatReader[] readers;
/** Blank buffered image, for use when image counts vary between files. */
private BufferedImage[] blankImage;
/** Blank image bytes, for use when image counts vary between files. */
private byte[][] blankBytes;
/** Image dimensions. */
private int[] width, height;
/** Number of images per file. */
private int[] imagesPerFile;
/** Total number of image planes. */
private int[] totalImages;
/** Dimension order. */
private String[] order;
/** Dimensional axis lengths per file. */
private int[] sizeZ, sizeC, sizeT;
/** Total dimensional axis lengths. */
private int[] totalSizeZ, totalSizeC, totalSizeT;
/** Component lengths for each axis type. */
private int[][] lenZ, lenC, lenT;
/** Whether or not we're doing channel stat calculation (no by default). */
protected boolean enableChannelStatCalculation = false;
/** Whether or not to ignore color tables, if present. */
protected boolean ignoreColorTable = false;
/** Whether or not to normalize float data. */
protected boolean normalizeData = false;
// -- Constructors --
/** Constructs a FileStitcher around a new image reader. */
public FileStitcher() { this(new ImageReader()); }
/**
* Constructs a FileStitcher with the given reader.
* @param r The reader to use for reading stitched files.
*/
public FileStitcher(IFormatReader r) { this(r, false); }
/**
* Constructs a FileStitcher with the given reader.
* @param r The reader to use for reading stitched files.
* @param patternIds Whether string ids given should be treated as file
* patterns rather than single file paths.
*/
public FileStitcher(IFormatReader r, boolean patternIds) {
reader = r;
this.patternIds = patternIds;
}
// -- FileStitcher API methods --
/**
* Gets the axis type for each dimensional block.
* @return An array containing values from the enumeration:
* <ul>
* <li>AxisGuesser.Z_AXIS: focal planes</li>
* <li>AxisGuesser.T_AXIS: time points</li>
* <li>AxisGuesser.C_AXIS: channels</li>
* </ul>
*/
public int[] getAxisTypes(String id)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
return ag[getSeries(id)].getAxisTypes();
}
/**
* Sets the axis type for each dimensional block.
* @param axes An array containing values from the enumeration:
* <ul>
* <li>AxisGuesser.Z_AXIS: focal planes</li>
* <li>AxisGuesser.T_AXIS: time points</li>
* <li>AxisGuesser.C_AXIS: channels</li>
* </ul>
*/
public void setAxisTypes(String id, int[] axes)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
ag[getSeries(id)].setAxisTypes(axes);
computeAxisLengths();
}
/** Gets the file pattern object used to build the list of files. */
public FilePattern getFilePattern(String id)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
return fp;
}
/**
* Gets the axis guesser object used to guess
* which dimensional axes are which.
*/
public AxisGuesser getAxisGuesser(String id)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
return ag[getSeries(id)];
}
/**
* Finds the file pattern for the given ID, based on the state of the file
* stitcher. Takes both ID map entries and the patternIds flag into account.
*/
public FilePattern findPattern(String id) {
if (!patternIds) {
// find the containing pattern
Hashtable map = Location.getIdMap();
String pattern = null;
if (map.containsKey(id)) {
// search ID map for pattern, rather than files on disk
String[] idList = new String[map.size()];
Enumeration en = map.keys();
for (int i=0; i<idList.length; i++) {
idList[i] = (String) en.nextElement();
}
pattern = FilePattern.findPattern(id, null, idList);
}
else {
// id is an unmapped file path; look to similar files on disk
pattern = FilePattern.findPattern(new Location(id));
}
if (pattern != null) id = pattern;
}
return new FilePattern(id);
}
// -- IFormatReader API methods --
/* @see IFormatReader#isThisType(byte[]) */
public boolean isThisType(byte[] block) {
return reader.isThisType(block);
}
/* @see IFormatReader#getImageCount(String) */
public int getImageCount(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return totalImages[getSeries(id)];
}
/* @see IFormatReader#isRGB(String) */
public boolean isRGB(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.isRGB(files[0]);
}
/* @see IFormatReader#getSizeX(String) */
public int getSizeX(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return width[getSeries(id)];
}
/* @see IFormatReader#getSizeY(String) */
public int getSizeY(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return height[getSeries(id)];
}
/* @see IFormatReader#getSizeZ(String) */
public int getSizeZ(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return totalSizeZ[getSeries(id)];
}
/* @see IFormatReader#getSizeC(String) */
public int getSizeC(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return totalSizeC[getSeries(id)];
}
/* @see IFormatReader#getSizeT(String) */
public int getSizeT(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return totalSizeT[getSeries(id)];
}
/* @see IFormatReader#getPixelType(String) */
public int getPixelType(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.getPixelType(files[0]);
}
/* @see IFormatReader#getEffectiveSizeC(String) */
public int getEffectiveSizeC(String id) throws FormatException, IOException {
return FormatReader.getEffectiveSizeC(isRGB(id), getSizeC(id));
}
/* @see IFormatReader#getChannelGlobalMinimum(String, int) */
public Double getChannelGlobalMinimum(String id, int theC)
throws FormatException, IOException
{
int[] include = getIncludeList(id, theC);
Double min = new Double(Double.POSITIVE_INFINITY);
for (int i=0; i<readers.length; i++) {
if (include[i] >= 0) {
Double d = readers[i].getChannelGlobalMinimum(files[i], include[i]);
if (d.compareTo(min) < 0) min = d;
}
}
return min;
}
/* @see IFormatReader#getChannelGlobalMaximum(String, int) */
public Double getChannelGlobalMaximum(String id, int theC)
throws FormatException, IOException
{
int[] include = getIncludeList(id, theC);
Double max = new Double(Double.NEGATIVE_INFINITY);
for (int i=0; i<readers.length; i++) {
if (include[i] >= 0) {
Double d = readers[i].getChannelGlobalMaximum(files[i], include[i]);
if (d.compareTo(max) > 0) max = d;
}
}
return max;
}
/* @see IFormatReader#getThumbSizeX(String) */
public int getThumbSizeX(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.getThumbSizeX(files[0]);
}
/* @see IFormatReader#getThumbSizeY(String) */
public int getThumbSizeY(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.getThumbSizeY(files[0]);
}
/* @see IFormatReader#isLittleEndian(String) */
public boolean isLittleEndian(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.isLittleEndian(files[0]);
}
/**
* Gets a five-character string representing the
* dimension order across the file series.
*/
public String getDimensionOrder(String id)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
return order[getSeries(id)];
}
/* @see IFormatReader#isOrderCertain(String) */
public boolean isOrderCertain(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return ag[getSeries(id)].isCertain();
}
/* @see IFormatReader#setChannelStatCalculationStatus(boolean) */
public void setChannelStatCalculationStatus(boolean on) {
enableChannelStatCalculation = on;
}
/* @see IFormatReader#getChannelStatCalculationStatus */
public boolean getChannelStatCalculationStatus() {
return enableChannelStatCalculation;
}
/* @see IFormatReader#isInterleaved(String) */
public boolean isInterleaved(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.isInterleaved(files[0]);
}
/** Obtains the specified image from the given file series. */
public BufferedImage openImage(String id, int no)
throws FormatException, IOException
{
int[] q = computeIndices(id, no);
int fno = q[0], ino = q[1];
if (ino < readers[fno].getImageCount(files[fno])) {
return readers[fno].openImage(files[fno], ino);
}
// return a blank image to cover for the fact that
// this file does not contain enough image planes
int sno = getSeries(id);
if (blankImage[sno] == null) {
blankImage[sno] = ImageTools.blankImage(width[sno], height[sno],
sizeC[sno], getPixelType(currentId));
}
return blankImage[sno];
}
/** Obtains the specified image from the given file series as a byte array. */
public byte[] openBytes(String id, int no)
throws FormatException, IOException
{
int[] q = computeIndices(id, no);
int fno = q[0], ino = q[1];
if (ino < readers[fno].getImageCount(files[fno])) {
return readers[fno].openBytes(files[fno], ino);
}
// return a blank image to cover for the fact that
// this file does not contain enough image planes
int sno = getSeries(id);
if (blankBytes[sno] == null) {
int bytes = FormatReader.getBytesPerPixel(getPixelType(currentId));
blankBytes[sno] = new byte[width[sno] * height[sno] *
bytes * (isRGB(id) ? sizeC[sno] : 1)];
}
return blankBytes[sno];
}
/* @see IFormatReader#openBytes(String, int, byte[]) */
public byte[] openBytes(String id, int no, byte[] buf)
throws FormatException, IOException
{
int[] q = computeIndices(id, no);
int fno = q[0], ino = q[1];
return readers[fno].openBytes(files[fno], ino, buf);
}
/* @see IFormatReader#openThumbImage(String, int) */
public BufferedImage openThumbImage(String id, int no)
throws FormatException, IOException
{
int[] q = computeIndices(id, no);
int fno = q[0], ino = q[1];
return readers[fno].openThumbImage(files[fno], ino);
}
/* @see IFormatReader#openThumbImage(String, int) */
public byte[] openThumbBytes(String id, int no)
throws FormatException, IOException
{
int[] q = computeIndices(id, no);
int fno = q[0], ino = q[1];
return readers[fno].openThumbBytes(files[fno], ino);
}
/* @see IFormatReader#close() */
public void close() throws FormatException, IOException {
if (readers != null) {
for (int i=0; i<readers.length; i++) readers[i].close();
}
readers = null;
blankImage = null;
blankBytes = null;
currentId = null;
}
/* @see IFormatReader#getSeriesCount(String) */
public int getSeriesCount(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.getSeriesCount(files[0]);
}
/* @see IFormatReader#setSeries(String, int) */
public void setSeries(String id, int no) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
reader.setSeries(files[0], no);
}
/* @see IFormatReader#getSeries(String) */
public int getSeries(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.getSeries(files[0]);
}
/* @see IFormatReader#setColorTableIgnored(boolean) */
public void setColorTableIgnored(boolean ignore) {
ignoreColorTable = ignore;
reader.setColorTableIgnored(ignore);
if (readers != null) {
for (int i=0; i<readers.length; i++) {
readers[i].setColorTableIgnored(ignore);
}
}
}
/* @see IFormatReader#isColorTableIgnored() */
public boolean isColorTableIgnored() { return ignoreColorTable; }
/* @see IFormatReader#setNormalized(boolean) */
public void setNormalized(boolean normalize) {
normalizeData = normalize;
}
/* @see IFormatReader#isNormalized() */
public boolean isNormalized() { return normalizeData; }
/* @see IFormatReader#getUsedFiles() */
public String[] getUsedFiles(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return files;
}
/* @see IFormatReader#getCurrentFile() */
public String getCurrentFile() { return currentId; }
/* @see IFormatReader#swapDimensions(String, String) */
public void swapDimensions(String id, String dimOrder)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
order[getSeries(id)] = dimOrder;
String f0 = files[0];
reader.swapDimensions(f0, dimOrder);
sizeZ[getSeries(id)] = reader.getSizeZ(f0);
sizeC[getSeries(id)] = reader.getSizeC(f0);
sizeT[getSeries(id)] = reader.getSizeT(f0);
computeAxisLengths();
}
/* @see IFormatReader#getIndex(String, int, int, int) */
public int getIndex(String id, int z, int c, int t)
throws FormatException, IOException
{
return FormatReader.getIndex(this, id, z, c, t);
}
/* @see IFormatReader#getZCTCoords(String, int) */
public int[] getZCTCoords(String id, int index)
throws FormatException, IOException
{
return FormatReader.getZCTCoords(this, id, index);
}
/* @see IFormatReader#getMetadataValue(String, String) */
public Object getMetadataValue(String id, String field)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
return reader.getMetadataValue(files[0], field);
}
/* @see IFormatReader#getMetadata(String) */
public Hashtable getMetadata(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.getMetadata(files[0]);
}
/* @see IFormatReader#setMetadataStore(MetadataStore) */
public void setMetadataStore(MetadataStore store) {
reader.setMetadataStore(store);
}
/* @see IFormatReader#getMetadataStore(String) */
public MetadataStore getMetadataStore(String id)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
return reader.getMetadataStore(files[0]);
}
/* @see IFormatReader#getMetadataStoreRoot(String) */
public Object getMetadataStoreRoot(String id)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
return reader.getMetadataStoreRoot(files[0]);
}
/* @see IFormatReader#testRead(String[]) */
public boolean testRead(String[] args) throws FormatException, IOException {
return FormatReader.testRead(this, args);
}
// -- IFormatHandler API methods --
/* @see IFormatHandler#isThisType(String) */
public boolean isThisType(String name) {
return reader.isThisType(name);
}
/* @see IFormatHandler#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
return reader.isThisType(name, open);
}
/* @see IFormatHandler#getFormat() */
public String getFormat() {
return reader.getFormat();
}
/* @see IFormatHandler#getSuffixes() */
public String[] getSuffixes() {
return reader.getSuffixes();
}
/* @see IFormatHandler#getFileFilters() */
public FileFilter[] getFileFilters() {
return reader.getFileFilters();
}
/* @see IFormatHandler#getFileChooser() */
public JFileChooser getFileChooser() {
return reader.getFileChooser();
}
// -- Helper methods --
/** Initializes the given file. */
protected void initFile(String id) throws FormatException, IOException {
if (FormatReader.debug) {
System.out.println("calling FileStitcher.initFile(" + id + ")");
}
currentId = id;
fp = findPattern(id);
// verify that file pattern is valid and matches existing files
String msg = " Please rename your files or disable file stitching.";
if (!fp.isValid()) {
throw new FormatException("Invalid " +
(patternIds ? "file pattern" : "filename") +
" (" + currentId + "): " + fp.getErrorMessage() + msg);
}
files = fp.getFiles();
if (files == null) {
throw new FormatException("No files matching pattern (" +
fp.getPattern() + "). " + msg);
}
for (int i=0; i<files.length; i++) {
if (!new Location(files[i]).exists()) {
throw new FormatException("File #" + i +
" (" + files[i] + ") does not exist.");
}
}
// determine reader type for these files; assume all are the same type
Vector classes = new Vector();
IFormatReader r = reader;
while (r instanceof ReaderWrapper) {
classes.add(r.getClass());
r = ((ReaderWrapper) r).getReader();
}
if (r instanceof ImageReader) r = ((ImageReader) r).getReader(files[0]);
classes.add(r.getClass());
// construct list of readers for all files
readers = new IFormatReader[files.length];
readers[0] = reader;
for (int i=1; i<readers.length; i++) {
// use crazy reflection to instantiate a reader of the proper type
try {
r = null;
for (int j=classes.size()-1; j>=0; j--) {
Class c = (Class) classes.elementAt(j);
if (r == null) r = (IFormatReader) c.newInstance();
else {
r = (IFormatReader) c.getConstructor(
new Class[] {IFormatReader.class}).newInstance(new Object[] {r});
}
}
readers[i] = (IFormatReader) r;
}
catch (InstantiationException exc) { exc.printStackTrace(); }
catch (IllegalAccessException exc) { exc.printStackTrace(); }
catch (NoSuchMethodException exc) { exc.printStackTrace(); }
catch (InvocationTargetException exc) { exc.printStackTrace(); }
}
String f0 = files[0];
int seriesCount = reader.getSeriesCount(f0);
ag = new AxisGuesser[seriesCount];
blankImage = new BufferedImage[seriesCount];
blankBytes = new byte[seriesCount][];
width = new int[seriesCount];
height = new int[seriesCount];
imagesPerFile = new int[seriesCount];
totalImages = new int[seriesCount];
order = new String[seriesCount];
sizeZ = new int[seriesCount];
sizeC = new int[seriesCount];
sizeT = new int[seriesCount];
boolean[] certain = new boolean[seriesCount];
totalSizeZ = new int[seriesCount];
totalSizeC = new int[seriesCount];
totalSizeT = new int[seriesCount];
lenZ = new int[seriesCount][];
lenC = new int[seriesCount][];
lenT = new int[seriesCount][];
// analyze first file; assume each file has the same parameters
int oldSeries = reader.getSeries(f0);
for (int i=0; i<seriesCount; i++) {
reader.setSeries(f0, i);
width[i] = reader.getSizeX(f0);
height[i] = reader.getSizeY(f0);
imagesPerFile[i] = reader.getImageCount(f0);
totalImages[i] = files.length * imagesPerFile[i];
order[i] = reader.getDimensionOrder(f0);
sizeZ[i] = reader.getSizeZ(f0);
sizeC[i] = reader.getSizeC(f0);
sizeT[i] = reader.getSizeT(f0);
certain[i] = reader.isOrderCertain(f0);
}
reader.setSeries(f0, oldSeries);
// guess at dimensions corresponding to file numbering
for (int i=0; i<seriesCount; i++) {
ag[i] = new AxisGuesser(fp, order[i],
sizeZ[i], sizeT[i], sizeC[i], certain[i]);
}
// order may need to be adjusted
for (int i=0; i<seriesCount; i++) {
setSeries(currentId, i);
order[i] = ag[i].getAdjustedOrder();
swapDimensions(currentId, order[i]);
}
setSeries(currentId, oldSeries);
}
/** Computes axis length arrays, and total axis lengths. */
protected void computeAxisLengths() throws FormatException, IOException {
int sno = getSeries(currentId);
int[] count = fp.getCount();
int[] axes = ag[sno].getAxisTypes();
int numZ = ag[sno].getAxisCountZ();
int numC = ag[sno].getAxisCountC();
int numT = ag[sno].getAxisCountT();
totalSizeZ[sno] = sizeZ[sno];
totalSizeC[sno] = sizeC[sno];
totalSizeT[sno] = sizeT[sno];
lenZ[sno] = new int[numZ + 1];
lenC[sno] = new int[numC + 1];
lenT[sno] = new int[numT + 1];
lenZ[sno][0] = sizeZ[sno];
lenC[sno][0] = sizeC[sno];
lenT[sno][0] = sizeT[sno];
int z = 1, c = 1, t = 1;
for (int i=0; i<axes.length; i++) {
switch (axes[i]) {
case AxisGuesser.Z_AXIS:
totalSizeZ[sno] *= count[i];
lenZ[sno][z++] = count[i];
break;
case AxisGuesser.C_AXIS:
totalSizeC[sno] *= count[i];
lenC[sno][c++] = count[i];
break;
case AxisGuesser.T_AXIS:
totalSizeT[sno] *= count[i];
lenT[sno][t++] = count[i];
break;
default:
throw new FormatException("Unknown axis type for axis #" +
i + ": " + axes[i]);
}
}
// populate metadata store
String f0 = files[0];
int pixelType = getPixelType(currentId);
boolean little = reader.isLittleEndian(f0);
MetadataStore s = reader.getMetadataStore(f0);
s.setPixels(new Integer(width[sno]), new Integer(height[sno]),
new Integer(totalSizeZ[sno]), new Integer(totalSizeC[sno]),
new Integer(totalSizeT[sno]), new Integer(pixelType),
new Boolean(!little), order[sno], new Integer(sno));
}
/**
* Gets the file index, and image index into that file,
* corresponding to the given global image index.
*
* @return An array of size 2, dimensioned {file index, image index}.
*/
protected int[] computeIndices(String id, int no)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
int sno = getSeries(id);
int[] axes = ag[sno].getAxisTypes();
int[] count = fp.getCount();
// get Z, C and T positions
int[] zct = getZCTCoords(id, no);
int[] posZ = rasterToPosition(lenZ[sno], zct[0]);
int[] posC = rasterToPosition(lenC[sno], zct[1]);
int[] posT = rasterToPosition(lenT[sno], zct[2]);
// convert Z, C and T position lists into file index and image index
int[] pos = new int[axes.length];
int z = 1, c = 1, t = 1;
for (int i=0; i<axes.length; i++) {
if (axes[i] == AxisGuesser.Z_AXIS) pos[i] = posZ[z++];
else if (axes[i] == AxisGuesser.C_AXIS) pos[i] = posC[c++];
else if (axes[i] == AxisGuesser.T_AXIS) pos[i] = posT[t++];
else {
throw new FormatException("Unknown axis type for axis #" +
i + ": " + axes[i]);
}
}
int fno = positionToRaster(count, pos);
int ino = FormatReader.getIndex(order[sno], sizeZ[sno],
sizeC[sno], sizeT[sno], imagesPerFile[sno],
posZ[0], posC[0], posT[0]);
// configure the reader, in case we haven't done this one yet
readers[fno].setChannelStatCalculationStatus(enableChannelStatCalculation);
readers[fno].setSeries(files[fno], reader.getSeries(files[0]));
readers[fno].setColorTableIgnored(ignoreColorTable);
readers[fno].swapDimensions(files[fno], order[sno]);
return new int[] {fno, ino};
}
/**
* Gets a list of readers to include in relation to the given C position.
* @return Array with indices corresponding to the list of readers, and
* values indicating the internal channel index to use for that reader.
*/
protected int[] getIncludeList(String id, int theC)
throws FormatException, IOException
{
int[] include = new int[readers.length];
Arrays.fill(include, -1);
for (int t=0; t<sizeT[getSeries(id)]; t++) {
for (int z=0; z<sizeZ[getSeries(id)]; z++) {
int no = getIndex(id, z, theC, t);
int[] q = computeIndices(id, no);
int fno = q[0], ino = q[1];
include[fno] = ino;
}
}
return include;
}
// -- Utility methods --
/**
* Computes a unique 1-D index corresponding to the multidimensional
* position given in the pos array, using the specified lengths array
* as the maximum value at each positional dimension.
*/
public static int positionToRaster(int[] lengths, int[] pos) {
int[] offsets = new int[lengths.length];
if (offsets.length > 0) offsets[0] = 1;
for (int i=1; i<offsets.length; i++) {
offsets[i] = offsets[i - 1] * lengths[i - 1];
}
int raster = 0;
for (int i=0; i<pos.length; i++) raster += offsets[i] * pos[i];
return raster;
}
/**
* Computes a unique 3-D position corresponding to the given raster
* value, using the specified lengths array as the maximum value at
* each positional dimension.
*/
public static int[] rasterToPosition(int[] lengths, int raster) {
int[] offsets = new int[lengths.length];
if (offsets.length > 0) offsets[0] = 1;
for (int i=1; i<offsets.length; i++) {
offsets[i] = offsets[i - 1] * lengths[i - 1];
}
int[] pos = new int[lengths.length];
for (int i=0; i<pos.length; i++) {
int q = i < pos.length - 1 ? raster % offsets[i + 1] : raster;
pos[i] = q / offsets[i];
raster -= q;
}
return pos;
}
/**
* Computes the maximum raster value of a positional array with
* the given maximum values.
*/
public static int getRasterLength(int[] lengths) {
int len = 1;
for (int i=0; i<lengths.length; i++) len *= lengths[i];
return len;
}
// -- Main method --
public static void main(String[] args) throws FormatException, IOException {
if (!new FileStitcher().testRead(args)) System.exit(1);
}
}
| I'm an idiot, we really do want to use the effective sizeC...but it should be reader.getEffectiveSizeC, not this.getEffectiveSizeC.
| loci/formats/FileStitcher.java | I'm an idiot, we really do want to use the effective sizeC...but it should be reader.getEffectiveSizeC, not this.getEffectiveSizeC. | <ide><path>oci/formats/FileStitcher.java
<ide> }
<ide> int fno = positionToRaster(count, pos);
<ide> int ino = FormatReader.getIndex(order[sno], sizeZ[sno],
<del> sizeC[sno], sizeT[sno], imagesPerFile[sno],
<add> reader.getEffectiveSizeC(files[0]), sizeT[sno], imagesPerFile[sno],
<ide> posZ[0], posC[0], posT[0]);
<ide>
<ide> // configure the reader, in case we haven't done this one yet |
|
Java | mit | c5b3149b6ba17a0c9718eebbd241bc7e374843ec | 0 | microsoftgraph/msgraph-sdk-java-core | package com.microsoft.graph.authentication;
import com.azure.core.credential.AccessToken;
import com.azure.core.credential.TokenCredential;
import com.azure.core.credential.TokenRequestContext;
import com.microsoft.graph.exceptions.AuthenticationException;
import com.microsoft.graph.exceptions.Error;
import com.microsoft.graph.httpcore.IHttpRequest;
import okhttp3.Request;
import com.microsoft.graph.exceptions.ErrorConstants.*;
import java.util.List;
public class TokenCredentialAuthProvider implements ICoreAuthenticationProvider , IAuthenticationProvider {
//TokenCredential expected form user
private TokenCredential tokenCredential;
//Context options which can be optionally set by the user
private TokenRequestContext context;
//Access token to be retrieved
private AccessToken accessToken;
/**
* Creates an Authentication provider using a passed in TokenCredential
*
* @param tokenCredential Credential object inheriting the TokenCredential interface used to instantiate the Auth Provider
* @throws AuthenticationException exception occurs if the TokenCredential parameter is null
*/
public TokenCredentialAuthProvider(TokenCredential tokenCredential) throws AuthenticationException {
if(tokenCredential == null) {
throw new AuthenticationException(new Error(Codes.InvalidArgument,
String.format(Messages.NullParameter, "TokenCredential"))
,new IllegalArgumentException());
}
this.tokenCredential = tokenCredential;
this.context = new TokenRequestContext();
}
/**
* Creates an Authentication provider using a TokenCredential and list of scopes
*
* @param tokenCredential Credential object inheriting the TokenCredential interface used to instantiate the Auth Provider
* @param scopes Specified desired scopes of the Auth Provider
* @throws AuthenticationException exception occurs if the TokenCredential parameter is null
*/
public TokenCredentialAuthProvider(TokenCredential tokenCredential, List<String> scopes) throws AuthenticationException {
this(tokenCredential);
this.context.setScopes(scopes);
}
/**
* Authenticates the request
*
* @param request the request to authenticate
*/
@Override
public void authenticateRequest(IHttpRequest request) {
request.addHeader(AuthConstants.AUTHORIZATION_HEADER, AuthConstants.BEARER + getAccessToken());
}
/**
* Authenticates the request
*
* @param request the request to authenticate
* @return Request with Authorization header added to it
*/
@Override
public Request authenticateRequest(Request request) {
return request.newBuilder()
.addHeader(AuthConstants.AUTHORIZATION_HEADER, AuthConstants.BEARER + getAccessToken())
.build();
}
/**
* Returns an AccessToken as a string
*
* @return String representing the retrieved AccessToken
*/
String getAccessToken() {
this.tokenCredential.getToken(this.context).doOnError(exception -> exception.printStackTrace())
.subscribe(token -> {
this.accessToken = token;
});
return this.accessToken.getToken();
}
}
| src/main/java/com/microsoft/graph/authentication/TokenCredentialAuthProvider.java | package com.microsoft.graph.authentication;
import com.azure.core.credential.AccessToken;
import com.azure.core.credential.TokenCredential;
import com.azure.core.credential.TokenRequestContext;
import com.microsoft.graph.exceptions.AuthenticationException;
import com.microsoft.graph.exceptions.Error;
import com.microsoft.graph.httpcore.IHttpRequest;
import okhttp3.Request;
import com.microsoft.graph.exceptions.ErrorConstants.*;
import java.util.List;
public class TokenCredentialAuthProvider implements ICoreAuthenticationProvider , IAuthenticationProvider {
//TokenCredential expected form user
private TokenCredential tokenCredential;
//Context options which can be optionally set by the user
private TokenRequestContext context;
//Access token to be retrieved
private AccessToken accessToken;
/**
* Creates an Authentication provider using a passed in TokenCredential
*
* @param tokenCredential Credential object inheriting the TokenCredential interface used to instantiate the Auth Provider
* @throws AuthenticationException exception occurs if the TokenCredential parameter is null
*/
public TokenCredentialAuthProvider(TokenCredential tokenCredential) throws AuthenticationException {
if(tokenCredential == null) {
throw new AuthenticationException(new Error(Codes.InvalidArgument,
String.format(Messages.NullParameter, "TokenCredential"))
,new IllegalArgumentException());
}
this.tokenCredential = tokenCredential;
this.context = new TokenRequestContext();
}
/**
*Created an Authentication provider using a TokenCredential and list of scopes
*
* @param tokenCredential Credential object inheriting the TokenCredential interface used to instantiate the Auth Provider
* @param scopes Specified desired scopes of the Auth Provider
* @throws AuthenticationException exception occurs if the TokenCredential parameter is null
*/
public TokenCredentialAuthProvider(TokenCredential tokenCredential, List<String> scopes) throws AuthenticationException {
this(tokenCredential);
this.context.setScopes(scopes);
}
/**
* Authenticates the request
*
* @param request the request to authenticate
*/
@Override
public void authenticateRequest(IHttpRequest request) {
request.addHeader(AuthConstants.AUTHORIZATION_HEADER, AuthConstants.BEARER + getAccessToken());
}
/**
* Authenticates the request
*
* @param request the request to authenticate
* @return Request with Authorization header added to it
*/
@Override
public Request authenticateRequest(Request request) {
return request.newBuilder()
.addHeader(AuthConstants.AUTHORIZATION_HEADER, AuthConstants.BEARER + getAccessToken())
.build();
}
/**
* Returns an AccessToken as a string
*
* @return String representing the retrieved AccessToken
*/
String getAccessToken() {
this.tokenCredential.getToken(this.context).doOnError(exception -> exception.printStackTrace())
.subscribe(token -> {
this.accessToken = token;
});
return this.accessToken.getToken();
}
}
| Update src/main/java/com/microsoft/graph/authentication/TokenCredentialAuthProvider.java
Co-authored-by: DeVere Dyett <[email protected]> | src/main/java/com/microsoft/graph/authentication/TokenCredentialAuthProvider.java | Update src/main/java/com/microsoft/graph/authentication/TokenCredentialAuthProvider.java | <ide><path>rc/main/java/com/microsoft/graph/authentication/TokenCredentialAuthProvider.java
<ide> }
<ide>
<ide> /**
<del> *Created an Authentication provider using a TokenCredential and list of scopes
<add> * Creates an Authentication provider using a TokenCredential and list of scopes
<ide> *
<ide> * @param tokenCredential Credential object inheriting the TokenCredential interface used to instantiate the Auth Provider
<ide> * @param scopes Specified desired scopes of the Auth Provider |
|
Java | mit | ceb3af4e0278456819dc4bb602dd623d977de28b | 0 | FAU-Inf2/yasme-android | package net.yasme.android.storage;
import android.content.Context;
import android.util.Log;
import net.yasme.android.entities.Chat;
import net.yasme.android.entities.Message;
import net.yasme.android.entities.MessageKey;
import net.yasme.android.entities.User;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by robert on 13.06.14.
*/
public class DatabaseManager {
static private DatabaseManager instance;
private static Boolean initialized = false;
static public void init(Context context, long userId, String accessToken) {
if (null == instance) {
instance = new DatabaseManager(context, userId);
}
initialized = true;
}
public static Boolean isInitialized() {
return initialized;
}
static public DatabaseManager getInstance() {
return instance;
}
private DatabaseHelper helper;
private DatabaseManager(Context context, long userId) {
helper = new DatabaseHelper(context, userId);
}
private DatabaseHelper getHelper() {
return helper;
}
/******* CRUD functions ******/
/**
* Chat methods
*/
/**
* Adds one chat to database
* @param chat Chat
*/
public void createChat(Chat chat) {
try {
for(User user : chat.getParticipants()) {
getHelper().getUserDao().createIfNotExists(user);
getHelper().getChatUserDao().create(new ChatUser(chat, user));
}
getHelper().getChatDao().create(chat);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* This function will return all chats from database
* @return list of chats or an empty list on error
*/
public ArrayList<Chat> getAllChats() {
List<Chat> chats = null;
try {
chats = getHelper().getChatDao().queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}
if(chats == null) {
return new ArrayList<Chat>();
}
for(Chat chat : chats) {
chat.setParticipants(getParticipantsForChat(chat.getId()));
}
ArrayList<Chat> chatsArray = new ArrayList(chats);
return chatsArray;
}
/**
* This function will return one chat from database with chatId
*
* @param chatId ID (primary key) of chat
* @return chat with chatID or null if chat not exists
*/
public Chat getChat(long chatId) {
Chat chat = null;
try {
chat = getHelper().getChatDao().queryForId(chatId);
if(chat == null) {
return null;
}
chat.setParticipants(getParticipantsForChat(chat.getId()));
chat.setMessages(new ArrayList<Message>(getMessagesForChat(chat.getId())));
} catch (SQLException e) {
e.printStackTrace();
}
return chat;
}
/**
* Retrieves the chat which all given users (and no one else) participate in
* @param users list of users who have joined the chat
* @return list of chats if existent, null or an empty list otherwise
*/
public List<Chat> getChats(List<User> users) {
List<Chat> matchingChats = null;
Chat search = new Chat(0, users, null, null, null); //TODO: not working
try {
matchingChats = getHelper().getChatDao().queryForMatchingArgs(search);
} catch (SQLException e) {
e.printStackTrace();
}
for(Chat chat : matchingChats) {
chat.setParticipants(getParticipantsForChat(chat.getId()));
}
return matchingChats;
}
/**
* This function will update a chat
* in table
*
* @param chat Chat
*/
public void updateChat(Chat chat) {
try {
List<User> dbParticipants = getParticipantsForChat(chat.getId());
if(dbParticipants == null) {
Log.e(this.getClass().getSimpleName(), "Error: Kein Teilnehmer in DB vorhanden");
return;
}
for(User u : dbParticipants) {
if(!chat.getParticipants().contains(u)) {
Chat queryChat = new Chat();
queryChat.setId(chat.getId());
ChatUser queryChatUser = new ChatUser(queryChat, u);
deleteChatUser(queryChatUser);
}
}
for(User u: chat.getParticipants()) {
if(!dbParticipants.contains(u)) {
Chat queryChat = new Chat();
queryChat.setId(chat.getId());
ChatUser queryChatUser = new ChatUser(queryChat, u);
createChatUser(queryChatUser);
}
}
getHelper().getChatDao().update(chat);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Updates the given chat or creates a new chat, if no such chat exists
* @param chat Chat
*/
public void createOrUpdateChat(Chat chat) {
try {
if(getHelper().getChatDao().idExists(chat.getId())) {
//if(getChat(chat.getId()) != null) {
updateChat(chat);
Log.d(this.getClass().getSimpleName(), "updated chat");
} else {
createChat(chat);
Log.d(this.getClass().getSimpleName(), "created chat");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* ChatUser methods
*/
/**
* creates a new ChatUser object
* @param cu
*/
public void createChatUser(ChatUser cu) {
try {
Chat queryChat = new Chat();
queryChat.setId(cu.chat.getId());
ChatUser queryChatUser = new ChatUser(queryChat, cu.user);
getHelper().getChatUserDao().create(queryChatUser);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Removes a ChatUser object from the Database
* @param cu ChatUser
*/
public void deleteChatUser(ChatUser cu) {
List<ChatUser> matching = new ArrayList<ChatUser>();
try {
Chat queryChat = new Chat();
queryChat.setId(cu.chat.getId());
ChatUser queryChatUser = new ChatUser(queryChat, cu.user);
matching = getHelper().getChatUserDao().queryForMatchingArgs(queryChatUser);
} catch (SQLException e) {
e.printStackTrace();
}
if(matching.isEmpty()) {
Log.e(this.getClass().getSimpleName(),
"Error: Kein ChatUser zum Loeschen in DB vorhanden");
return;
}
try {
getHelper().getChatUserDao().deleteById(matching.get(0).id);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* User methods
*/
/**
* Adds one user to database (using createIfNotExists)
*/
public void createUserIfNotExists(User u) {
try {
getHelper().getUserDao().createIfNotExists(u);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Updates the given user or creates a new user, if no such user exists
* @param u User
*/
public void createOrUpdateUser(User u) {
try {
User tmp = getHelper().getUserDao().queryForId(u.getId());
if(tmp == null) {
getHelper().getUserDao().create(u);
} else {
if(tmp.isContact() == 1) {
u.addToContacts();
getHelper().getUserDao().update(u);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* This function if a user is already stored in the Database
* @param userId long
* @return true if user with userId exists, otherwise false
*/
public boolean existsUser(long userId) {
try {
return getHelper().getUserDao().idExists(userId);
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
/**
* This function returns all participants from the chat with the given chatId
* @param chatId long
* @return a list of users
*/
public List<User> getParticipantsForChat(long chatId) {
List<User> insert = null;
try {
Chat c = new Chat();
c.setId(chatId);
List<ChatUser> temp = null;
temp = getHelper().getChatUserDao().queryForMatchingArgs(new ChatUser(c, null));
insert = new ArrayList<User>();
if(temp == null) {
Log.d(this.getClass().getSimpleName(), "[Debug] keine participants in DB gefunden");
}
if(temp.isEmpty()) {
Log.d(this.getClass().getSimpleName(), "[Debug] keine participants in DB gefunden");
}
for(ChatUser cu : temp) {
User tmp = getHelper().getUserDao().queryForId(cu.user.getId());
if(tmp == null) {
continue;
}
insert.add(getHelper().getUserDao().queryForId(cu.user.getId()));
Log.d(this.getClass().getSimpleName(), "[Debug] name from DB: " + tmp.getName());
}
if(insert.isEmpty()) {
Log.d(this.getClass().getSimpleName(), "[Debug] keine participants in DB gefunden");
}
} catch (SQLException e) {
e.printStackTrace();
}
return insert;
}
/**
* This function returns the user with userId
* @param userId long
* @return User with userId or null if no such User exists
*/
public User getUser(long userId) {
try {
return getHelper().getUserDao().queryForId(userId);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* This function will get all participants with contactFlag = 1
* @return contacts or null on error
*/
public List<User> getContactsFromDB() {
List<User> contacts;
try {
contacts = getHelper().getUserDao().queryForEq(DatabaseConstants.CONTACT, 1);
} catch (SQLException e) {
contacts = null;
}
return contacts;
}
/**
* This function will reset the contactFlag so that the user is removed from the contact list
* @param u User
*/
public void removeContactFromDB(User u) {
try {
getHelper().getUserDao().queryForId(u.getId());
u.removeFromContacts();
getHelper().getUserDao().update(u);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Message methods
*/
public void storeMessages(List<Message> messages) {
for(Message msg : messages) {
try {
getHelper().getMessageDao().create(msg);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public List<Message> getMessagesForChat(long chatId) {
Chat chat = new Chat();
chat.setId(chatId);
Message matchingObj = new Message(null, null, null, chat, 0);
List<Message> matching = null;
try {
matching = getHelper().getMessageDao().queryForEq(DatabaseConstants.CHAT, chat);
//matching = getHelper().getMessageDao().queryForMatchingArgs(matchingObj);
} catch (SQLException e) {
e.printStackTrace();
}
return matching;
}
/**
* MessageKey and CurrentKey methods
*/
public long getCurrentKey(long chatId) {
List<CurrentKey> currentKeys = null;
Chat chat = new Chat();
chat.setId(chatId);
try {
currentKeys = getHelper().getCurrentKeyDao().queryForEq(DatabaseConstants.CURRENT_KEY_CHAT, chat);
} catch (SQLException e) {
e.printStackTrace();
}
if(currentKeys.size() != 1) {
Log.e(this.getClass().getSimpleName(), "Mehrere currentKeys pro Chat");
return -1;
}
return currentKeys.get(0).getMessageKey().getId();
}
public void updateCurrentKey(long keyId, long chatId) {
Chat chat = new Chat();
chat.setId(chatId);
MessageKey messageKey = new MessageKey();
messageKey.setId(keyId);
CurrentKey newCurrentKey = new CurrentKey(chat, messageKey);
try {
getHelper().getCurrentKeyDao().update(newCurrentKey);
} catch (SQLException e) {
e.printStackTrace();
}
}
public boolean existsCurrentKeyForChat(long chatId) {
//TODO: effektiver machen, evtl. SELECT
List<CurrentKey> currentKeys = null;
Chat chat = new Chat();
chat.setId(chatId);
try {
currentKeys = getHelper().getCurrentKeyDao().queryForEq(DatabaseConstants.CURRENT_KEY_CHAT, chat);
} catch (SQLException e) {
e.printStackTrace();
}
if(currentKeys.size() != 1) {
Log.e(this.getClass().getSimpleName(), "Mehrere currentKeys pro Chat");
}
return (currentKeys.size() != 0);
}
public MessageKey getMessageKey(long keyId) {
MessageKey messageKey = null;
try {
messageKey = getHelper().getMessageKeyDao().queryForId(keyId);
} catch (SQLException e) {
e.printStackTrace();
}
return messageKey;
}
} | yasme/src/main/java/net/yasme/android/storage/DatabaseManager.java | package net.yasme.android.storage;
import android.content.Context;
import android.util.Log;
import net.yasme.android.entities.Chat;
import net.yasme.android.entities.Message;
import net.yasme.android.entities.MessageKey;
import net.yasme.android.entities.User;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by robert on 13.06.14.
*/
public class DatabaseManager {
static private DatabaseManager instance;
private static Boolean initialized = false;
static public void init(Context context, long userId, String accessToken) {
if (null == instance) {
instance = new DatabaseManager(context, userId);
}
initialized = true;
}
public static Boolean isInitialized() {
return initialized;
}
static public DatabaseManager getInstance() {
return instance;
}
private DatabaseHelper helper;
private DatabaseManager(Context context, long userId) {
helper = new DatabaseHelper(context, userId);
}
private DatabaseHelper getHelper() {
return helper;
}
/******* CRUD functions ******/
/**
* Chat methods
*/
/**
* Adds one chat to database
* @param chat Chat
*/
public void createChat(Chat chat) {
try {
for(User user : chat.getParticipants()) {
getHelper().getUserDao().createIfNotExists(user);
getHelper().getChatUserDao().create(new ChatUser(chat, user));
}
getHelper().getChatDao().create(chat);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* This function will return all chats from database
* @return list of chats or an empty list on error
*/
public ArrayList<Chat> getAllChats() {
List<Chat> chats = null;
try {
chats = getHelper().getChatDao().queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}
if(chats == null) {
return new ArrayList<Chat>();
}
for(Chat chat : chats) {
chat.setParticipants(getParticipantsForChat(chat.getId()));
}
ArrayList<Chat> chatsArray = new ArrayList(chats);
return chatsArray;
}
/**
* This function will return one chat from database with chatId
*
* @param chatId ID (primary key) of chat
* @return chat with chatID or null if chat not exists
*/
public Chat getChat(long chatId) {
Chat chat = null;
try {
chat = getHelper().getChatDao().queryForId(chatId);
if(chat == null) {
return null;
}
chat.setParticipants(getParticipantsForChat(chat.getId()));
chat.setMessages(new ArrayList<Message>(getMessagesForChat(chat.getId())));
} catch (SQLException e) {
e.printStackTrace();
}
return chat;
}
/**
* Retrieves the chat which all given users (and no one else) participate in
* @param users list of users who have joined the chat
* @return list of chats if existent, null or an empty list otherwise
*/
public List<Chat> getChats(List<User> users) {
List<Chat> matchingChats = null;
Chat search = new Chat(0, users, null, null, null); //TODO: not working
try {
matchingChats = getHelper().getChatDao().queryForMatchingArgs(search);
} catch (SQLException e) {
e.printStackTrace();
}
for(Chat chat : matchingChats) {
chat.setParticipants(getParticipantsForChat(chat.getId()));
}
return matchingChats;
}
/**
* This function will update a chat
* in table
*
* @param chat Chat
*/
public void updateChat(Chat chat) {
try {
List<User> dbParticipants = getParticipantsForChat(chat.getId());
if(dbParticipants == null) {
Log.e(this.getClass().getSimpleName(), "Error: Kein Teilnehmer in DB vorhanden");
return;
}
for(User u : dbParticipants) {
if(!chat.getParticipants().contains(u)) {
Chat queryChat = new Chat();
queryChat.setId(chat.getId());
ChatUser queryChatUser = new ChatUser(queryChat, u);
deleteChatUser(queryChatUser);
}
}
for(User u: chat.getParticipants()) {
if(!dbParticipants.contains(u)) {
Chat queryChat = new Chat();
queryChat.setId(chat.getId());
ChatUser queryChatUser = new ChatUser(queryChat, u);
createChatUser(queryChatUser);
}
}
getHelper().getChatDao().update(chat);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Updates the given chat or creates a new chat, if no such chat exists
* @param chat Chat
*/
public void createOrUpdateChat(Chat chat) {
try {
if(getHelper().getChatDao().idExists(chat.getId())) {
//if(getChat(chat.getId()) != null) {
updateChat(chat);
Log.d(this.getClass().getSimpleName(), "updated chat");
} else {
createChat(chat);
Log.d(this.getClass().getSimpleName(), "created chat");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* ChatUser methods
*/
/**
* creates a new ChatUser object
* @param cu
*/
public void createChatUser(ChatUser cu) {
try {
Chat queryChat = new Chat();
queryChat.setId(cu.chat.getId());
ChatUser queryChatUser = new ChatUser(queryChat, cu.user);
getHelper().getChatUserDao().create(queryChatUser);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Removes a ChatUser object from the Database
* @param cu ChatUser
*/
public void deleteChatUser(ChatUser cu) {
List<ChatUser> matching = new ArrayList<ChatUser>();
try {
Chat queryChat = new Chat();
queryChat.setId(cu.chat.getId());
ChatUser queryChatUser = new ChatUser(queryChat, cu.user);
matching = getHelper().getChatUserDao().queryForMatchingArgs(queryChatUser);
} catch (SQLException e) {
e.printStackTrace();
}
if(matching.isEmpty()) {
Log.e(this.getClass().getSimpleName(),
"Error: Kein ChatUser zum Loeschen in DB vorhanden");
return;
}
try {
getHelper().getChatUserDao().deleteById(matching.get(0).id);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* User methods
*/
/**
* Adds one user to database (using createIfNotExists)
*/
public void createUserIfNotExists(User u) {
try {
getHelper().getUserDao().createIfNotExists(u);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Updates the given user or creates a new user, if no such user exists
* @param u User
*/
public void createOrUpdateUser(User u) {
try {
User tmp = getHelper().getUserDao().queryForId(u.getId());
if(tmp == null) {
getHelper().getUserDao().create(u);
} else {
if(tmp.isContact() == 1) {
u.addToContacts();
getHelper().getUserDao().update(u);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* This function if a user is already stored in the Database
* @param userId long
* @return true if user with userId exists, otherwise false
*/
public boolean existsUser(long userId) {
try {
return getHelper().getUserDao().idExists(userId);
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
/**
* This function returns all participants from the chat with the given chatId
* @param chatId long
* @return a list of users
*/
public List<User> getParticipantsForChat(long chatId) {
List<User> insert = null;
try {
Chat c = new Chat();
c.setId(chatId);
List<ChatUser> temp = null;
temp = getHelper().getChatUserDao().queryForMatchingArgs(new ChatUser(c, null));
insert = new ArrayList<User>();
if(temp == null) {
Log.d(this.getClass().getSimpleName(), "[Debug] keine participants in DB gefunden");
}
if(temp.isEmpty()) {
Log.d(this.getClass().getSimpleName(), "[Debug] keine participants in DB gefunden");
}
for(ChatUser cu : temp) {
User tmp = getHelper().getUserDao().queryForId(cu.user.getId());
if(tmp == null) {
continue;
}
insert.add(getHelper().getUserDao().queryForId(cu.user.getId()));
Log.d(this.getClass().getSimpleName(), "[Debug] name from DB: " + tmp.getName());
}
if(insert.isEmpty()) {
Log.d(this.getClass().getSimpleName(), "[Debug] keine participants in DB gefunden");
}
} catch (SQLException e) {
e.printStackTrace();
}
return insert;
}
/**
* This function returns the user with userId
* @param userId long
* @return User with userId or null if no such User exists
*/
public User getUser(long userId) {
try {
return getHelper().getUserDao().queryForId(userId);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* This function will get all participants with contactFlag = 1
* @return contacts or null on error
*/
public List<User> getContactsFromDB() {
List<User> contacts;
try {
contacts = getHelper().getUserDao().queryForEq(DatabaseConstants.CONTACT, 1);
} catch (SQLException e) {
contacts = null;
}
return contacts;
}
/**
* This function will reset the contactFlag so that the user is removed from the contact list
* @param u User
*/
public void removeContactFromDB(User u) {
try {
getHelper().getUserDao().queryForId(u.getId());
u.removeFromContacts();
getHelper().getUserDao().update(u);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Message methods
*/
public void storeMessages(List<Message> messages) {
for(Message msg : messages) {
try {
getHelper().getMessageDao().create(msg);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public List<Message> getMessagesForChat(long chatId) {
Chat chat = new Chat();
chat.setId(chatId);
Message matchingObj = new Message(null, null, null, chat, 0);
List<Message> matching = null;
try {
matching = getHelper().getMessageDao().queryForEq(DatabaseConstants.CHAT, chat);
//matching = getHelper().getMessageDao().queryForMatchingArgs(matchingObj);
} catch (SQLException e) {
e.printStackTrace();
}
return matching;
}
/**
* MessageKey and CurrentKey methods
*/
public long getCurrentKey(long chatId) {
List<CurrentKey> currentKeys = null;
Chat chat = new Chat();
chat.setId(chatId);
try {
currentKeys = getHelper().getCurrentKeyDao().queryForEq(DatabaseConstants.CURRENT_KEY_CHAT, chat);
} catch (SQLException e) {
e.printStackTrace();
}
if(currentKeys.size() != 1) {
Log.e(this.getClass().getSimpleName(), "Mehrere currentKeys pro Chat");
return -1;
}
return currentKeys.get(0).getMessageKey().getId();
}
public void updateCurrentKey(long keyId, long chatId) {
Chat chat = new Chat();
chat.setId(chatId);
MessageKey messageKey = new MessageKey();
messageKey.setId(keyId);
CurrentKey newCurrentKey = new CurrentKey(chat, messageKey);
try {
getHelper().getCurrentKeyDao().update(newCurrentKey);
} catch (SQLException e) {
e.printStackTrace();
}
}
public MessageKey getMessageKey(long keyId) {
MessageKey messageKey = null;
try {
messageKey = getHelper().getMessageKeyDao().queryForId(keyId);
} catch (SQLException e) {
e.printStackTrace();
}
return messageKey;
}
} | implemented exists method
| yasme/src/main/java/net/yasme/android/storage/DatabaseManager.java | implemented exists method | <ide><path>asme/src/main/java/net/yasme/android/storage/DatabaseManager.java
<ide> }
<ide> }
<ide>
<add> public boolean existsCurrentKeyForChat(long chatId) {
<add> //TODO: effektiver machen, evtl. SELECT
<add> List<CurrentKey> currentKeys = null;
<add> Chat chat = new Chat();
<add> chat.setId(chatId);
<add> try {
<add> currentKeys = getHelper().getCurrentKeyDao().queryForEq(DatabaseConstants.CURRENT_KEY_CHAT, chat);
<add> } catch (SQLException e) {
<add> e.printStackTrace();
<add> }
<add> if(currentKeys.size() != 1) {
<add> Log.e(this.getClass().getSimpleName(), "Mehrere currentKeys pro Chat");
<add> }
<add> return (currentKeys.size() != 0);
<add> }
<add>
<ide> public MessageKey getMessageKey(long keyId) {
<ide> MessageKey messageKey = null;
<ide> try {
<ide> return messageKey;
<ide> }
<ide>
<add>
<ide> } |
|
Java | mit | cf770330a65618e685fcc47ed1758f33c2dff743 | 0 | astdb/Misc,astdb/Misc,astdb/TB_ShortProbs,astdb/Misc,astdb/TB_ShortProbs,astdb/Misc,astdb/TB_ShortProbs,astdb/Misc,astdb/Misc |
// This program takes in a list of credit card transactions and outputs a list of credit card numbers
// associated with suspected fraudulent transactions according to given guidelines.
import java.util.*;
import java.io.*;
import java.text.*;
import java.util.regex.*;
public class FraudDetector {
public static void main(String[] args) {
if( args.length <= 0 || args[0].trim().length() <= 0 ){
System.out.println("Usage: $> java FraudDetector inputfile");
return;
}
String inputFile = args[0]; // read transactions input file from command line
Long priceThreshold = 11000L; // in cents
String date = "2017-09-14"; // in "yyyy-MM-dd" format
// ------------------------- Test 01 -------------------------
// a single card, with one exceeding transaction
ArrayList<String> expected_test01 = new ArrayList<String>();
expected_test01.add("10d7ce2f43e35fa57d1bbf8b1e2");
if(equalLists(expected_test01, filterTransactions("test01.file", date, priceThreshold))) {
System.out.println("Test01: Pass");
} else {
System.out.println("Test01: Fail");
}
// ------------------------- Test 02 -------------------------
// a single card, with one non-exceeding transaction
ArrayList<String> expected_test02 = new ArrayList<String>();
if(equalLists(expected_test02, filterTransactions("test02.file", date, priceThreshold))) {
System.out.println("Test02: Pass");
} else {
System.out.println("Test02: Fail");
}
// ------------------------- Test 03 -------------------------
// an empty input
ArrayList<String> expected_test03 = new ArrayList<String>();
if(equalLists(expected_test03, filterTransactions("test03.file", date, priceThreshold))) {
System.out.println("Test03: Pass");
} else {
System.out.println("Test03: Fail");
}
// ------------------------- Test 04 -------------------------
// a garbage input
ArrayList<String> expected_test04 = new ArrayList<String>();
if(equalLists(expected_test04, filterTransactions("test04.file", date, priceThreshold))) {
System.out.println("Test04: Pass");
} else {
System.out.println("Test04: Fail");
}
// ------------------------- Test 05 -------------------------
// Two cards, both exceeding limit for the same day
ArrayList<String> expected_test05 = new ArrayList<String>();
expected_test05.add("10d7ce2f43e35fa57d1bbf8b1e2");
expected_test05.add("10d7ce2f43e35fa57d1bbf8b1e3");
if(equalLists(expected_test05, filterTransactions("test05.file", date, priceThreshold))) {
System.out.println("Test05: Pass");
} else {
System.out.println("Test05: Fail");
}
// ------------------------- Test 06 -------------------------
// Two cards, both exceeding limit for different days
ArrayList<String> expected_test06 = new ArrayList<String>();
expected_test06.add("10d7ce2f43e35fa57d1bbf8b1e2");
if(equalLists(expected_test06, filterTransactions("test06.file", date, priceThreshold))) {
System.out.println("Test06: Pass");
} else {
System.out.println("Test06: Fail");
}
// print out suspected card hashes
ArrayList<String> suspect_cards_list = filterTransactions("test06.file", date, priceThreshold);
if(suspect_cards_list.size() == 0) {
System.out.println("No cards with fraudulent transactions found.");
return;
} else {
for (String cardHash: suspect_cards_list) {
System.out.println(cardHash);
return;
}
}
// ------------------------- Test 07 -------------------------
// Non-existent input file
ArrayList<String> expected_test07 = null;
if(equalLists(expected_test07, filterTransactions("test07.file", date, priceThreshold))) {
System.out.println("Test07: Pass");
} else {
System.out.println("Test07: Fail");
}
// ------------------------- Test 08 -------------------------
// Two cards, multiple transcations, single day, both exceeding
ArrayList<String> expected_test08 = new ArrayList<String>();
expected_test08.add("10d7ce2f43e35fa57d1bbf8b1e2");
expected_test08.add("10d7ce2f43e35fa57d1bbf8b1e3");
if(equalLists(expected_test08, filterTransactions("test08.file", date, priceThreshold))) {
System.out.println("Test08: Pass");
} else {
System.out.println("Test08: Fail");
}
// ------------------------- Test 09 -------------------------
// Two cards, multiple transcations, single day, both non-exceeding
ArrayList<String> expected_test09 = new ArrayList<String>();
if(equalLists(expected_test09, filterTransactions("test09.file", date, priceThreshold))) {
System.out.println("Test09: Pass");
} else {
System.out.println("Test09: Fail");
}
// ------------------------- Test 10 -------------------------
// Two cards, multiple transcations, single day, both non-exceeding
ArrayList<String> expected_test10 = new ArrayList<String>();
expected_test08.add("10d7ce2f43e35fa57d1bbf8b1e4");
if(equalLists(expected_test10, filterTransactions("test10.file", date, priceThreshold))) {
System.out.println("Test10: Pass");
} else {
System.out.println("Test10: Fail");
}
// print out suspected card hashes
// ArrayList<String> suspect_cards_list = filterTransactions("test05.file", date, priceThreshold);
// if(suspect_cards_list.size() == 0) {
// System.out.println("No cards with fraudulent transactions found.");
// return;
// } else {
// for (String cardHash: suspect_cards_list) {
// System.out.println(cardHash);
// return;
// }
// }
}
// filterTransactions function takes in a list of transactions, a date, and a threshold spend amount and returns
// a list of credit card number hashes associated with a total of transactions exceeding the threshold for that day.
public static ArrayList<String> filterTransactions(String inputFile, String dateThreshold, long amountThreshold) {
// read input file
Scanner input = null;
try {
input = new Scanner(new File(inputFile));
} catch( FileNotFoundException e ) {
// System.out.println("No such file: " + inputFile);
return null;
}
if(inputFile == null || dateThreshold == null) {
return null;
}
// ensure that the date provided is of "yyyy-MM-dd" format
dateThreshold = dateThreshold.trim();
Pattern properDate = Pattern.compile("^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$");
Matcher m = properDate.matcher(dateThreshold);
if (!m.find()) {
System.out.println("Invalid date threshold parameter.");
return null;
}
// declare map structure to collect creditcards and expense totals
// this collection will be a set of creditcard numbers mapping to a set of maps, which in turn map dates to totals
// e.g
// card1 -> {date1 -> total1, date2 -> total2}
// card2 -> {date3 -> total3}
// HashMap<String, HashMap<Long, Long>> creditCardTotals = new HashMap<String, HashMap<Long, Long>>();
HashMap<String, Long> creditCardTotals = new HashMap<String, Long>();
// list of suspicious cards - this will be populated whenever a card's total for a given day is detected to be over threshold
ArrayList<String> suspectCards = new ArrayList<String>();
// get timestamp for the threshold date (the date the fraudulent transaction cards are required for)
// Long dateThreshold = null;
// try {
// DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
// Date dte = dateFormat.parse(date);
// dateThreshold = new Long(dte.getTime());
// } catch(ParseException e) {
// // malformed input, move to next transaction
// // System.out.println("Error parsing date: " + dayComp);
// return null;
// }
// iterate through each of the transaction input file
while(input.hasNextLine()) {
String transaction = input.nextLine(); // e.g. "10d7ce2f43e35fa57d1bbf8b1e2, 2014-04-29T13:15:54, 10.00"
// ignore if line starts with # (comment)
Pattern commentLine = Pattern.compile("^#");
Matcher clm = commentLine.matcher(transaction.trim());
if (clm.find()) {
continue;
}
// split transaction string into components (card hash, date, amount)
String[] transactionComponents = transaction.split(",");
// confirm transaction is complete
if(transactionComponents.length < 3) {
// malformed input, move to next transaction
// System.out.println("Error parsing transaction: " + transaction);
continue;
}
// components of this transaction
String transactionCardHash = transactionComponents[0].trim();
String transactionDate = transactionComponents[1].trim();
String transactionAmount = transactionComponents[2].trim();
// extract day component from input e.g. "2014-04-29" from "2014-04-29T13:15:54"
String[] dateSplit = transactionDate.split("T");
String transactionDate_day = dateSplit[0];
// ensure that the date provided is of "yyyy-MM-dd" format
transactionDate_day = transactionDate_day.trim();
Matcher pdm = properDate.matcher(transactionDate_day);
if (!pdm.find()) {
// System.out.println("Invalid date threshold parameter.");
// return null;
// possibly malformed transaction reord - move onto next
continue;
}
// get timestamp for the transaction date (day component)
// Long day = null;
// try {
// DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
// Date dte = dateFormat.parse(dayComp);
// day = new Long(dte.getTime());
// } catch(ParseException e) {
// // malformed input, move to next transaction
// // System.out.println("Error parsing date: " + dayComp);
// continue;
// }
// check if this transaction is one we'd be interested in - i.e. one for the date given
// TODO - begs the question, can't you just string compare the day components?
// Also, if the processor only sees transactions only for a given day, can't it be a simple hashmap of card hash-> total?
if(transactionDate_day != dateThreshold) {
continue;
}
Long amt = null;
try {
amt = new Long((long)(Float.parseFloat(transactionAmount)*100));
} catch(NumberFormatException e) {
// malformed input - continue to next
continue;
}
// check if a record exists for this credit card
// HashMap<Long, Long> cardExists = creditCardTotals.get(transactionCardHash);
Long cardTotal = creditCardTotals.get(transactionCardHash);
if(cardTotal != null) {
// card known in this dataset before - update total
Long newTotal = cardTotal + amt;
if(newTotal > amountThreshold) {
if(!suspectCards.contains(transactionCardHash)) {
suspectCards.add(transactionCardHash);
}
}
// // check if a total exists for this card for this date
// Long totalExists = cardExists.get(day);
// if(totalExists != null) {
// // a count is known for this card for this date - update
// Long newTot = cardExists.get(day) + amt;
// if(newTot > amountThreshold) {
// if(!suspectCards.contains(transactionCardHash)) {
// suspectCards.add(transactionCardHash);
// }
// }
// cardExists.put(day, newTot);
// } else {
// // no count for this card for this date, add
// cardExists.put(day, amt);
// }
} else {
// new card to this dataset - create record
creditCardTotals.put(transactionCardHash, amt);
if(amt > amountThreshold) {
if(!suspectCards.contains(transactionCardHash)) {
suspectCards.add(transactionCardHash);
}
}
// HashMap<Long, Long> thisAmount = new HashMap<Long, Long>();
// thisAmount.put(day, amt);
// creditCardTotals.put(transactionCardHash, thisAmount);
}
}
return suspectCards;
}
// utility test function to check if two given lists of card number hashes contain the same elements
public static boolean equalLists(ArrayList<String> expected, ArrayList<String> result) {
// DEBUG - print out the two lists
System.out.println("\tExpected: " + expected);
System.out.println("\tResults: " + result);
if (expected == null && result == null) {
return true;
}
if ((expected == null && result!= null) || (expected != null && result== null) || (expected.size() != result.size())) {
return false;
}
// Sort and compare the two lists
Collections.sort(expected);
Collections.sort(result);
return expected.equals(result);
}
}
| FraudDetector.java |
// This program takes in a list of credit card transactions and outputs a list of credit card numbers
// associated with suspected fraudulent transactions according to given guidelines.
import java.util.*;
import java.io.*;
import java.text.*;
import java.util.regex.*;
public class FraudDetector {
public static void main(String[] args) {
if( args.length <= 0 || args[0].trim().length() <= 0 ){
System.out.println("Usage: $> java FraudDetector inputfile");
return;
}
String inputFile = args[0]; // read transactions input file from command line
Long priceThreshold = 11000L; // in cents
String date = "2017-09-14"; // in "yyyy-MM-dd" format
// ------------------------- Test 01 -------------------------
// a single card, with one exceeding transaction
ArrayList<String> expected_test01 = new ArrayList<String>();
expected_test01.add("10d7ce2f43e35fa57d1bbf8b1e2");
if(equalLists(expected_test01, filterTransactions("test01.file", date, priceThreshold))) {
System.out.println("Test01: Pass");
} else {
System.out.println("Test01: Fail");
}
// ------------------------- Test 02 -------------------------
// a single card, with one non-exceeding transaction
ArrayList<String> expected_test02 = new ArrayList<String>();
if(equalLists(expected_test02, filterTransactions("test02.file", date, priceThreshold))) {
System.out.println("Test02: Pass");
} else {
System.out.println("Test02: Fail");
}
// ------------------------- Test 03 -------------------------
// an empty input
ArrayList<String> expected_test03 = new ArrayList<String>();
if(equalLists(expected_test03, filterTransactions("test03.file", date, priceThreshold))) {
System.out.println("Test03: Pass");
} else {
System.out.println("Test03: Fail");
}
// ------------------------- Test 04 -------------------------
// a garbage input
ArrayList<String> expected_test04 = new ArrayList<String>();
if(equalLists(expected_test04, filterTransactions("test04.file", date, priceThreshold))) {
System.out.println("Test04: Pass");
} else {
System.out.println("Test04: Fail");
}
// ------------------------- Test 05 -------------------------
// Two cards, both exceeding limit for the same day
ArrayList<String> expected_test05 = new ArrayList<String>();
expected_test05.add("10d7ce2f43e35fa57d1bbf8b1e2");
expected_test05.add("10d7ce2f43e35fa57d1bbf8b1e3");
if(equalLists(expected_test05, filterTransactions("test05.file", date, priceThreshold))) {
System.out.println("Test05: Pass");
} else {
System.out.println("Test05: Fail");
}
// ------------------------- Test 06 -------------------------
// Two cards, both exceeding limit for different days
ArrayList<String> expected_test06 = new ArrayList<String>();
expected_test06.add("10d7ce2f43e35fa57d1bbf8b1e3");
if(equalLists(expected_test06, filterTransactions("test06.file", date, priceThreshold))) {
System.out.println("Test06: Pass");
} else {
System.out.println("Test06: Fail");
}
// ------------------------- Test 07 -------------------------
// Non-existent input file
ArrayList<String> expected_test07 = null;
if(equalLists(expected_test07, filterTransactions("test07.file", date, priceThreshold))) {
System.out.println("Test07: Pass");
} else {
System.out.println("Test07: Fail");
}
// ------------------------- Test 08 -------------------------
// Two cards, multiple transcations, single day, both exceeding
ArrayList<String> expected_test08 = new ArrayList<String>();
expected_test08.add("10d7ce2f43e35fa57d1bbf8b1e2");
expected_test08.add("10d7ce2f43e35fa57d1bbf8b1e3");
if(equalLists(expected_test08, filterTransactions("test08.file", date, priceThreshold))) {
System.out.println("Test08: Pass");
} else {
System.out.println("Test08: Fail");
}
// ------------------------- Test 09 -------------------------
// Two cards, multiple transcations, single day, both non-exceeding
ArrayList<String> expected_test09 = new ArrayList<String>();
if(equalLists(expected_test09, filterTransactions("test09.file", date, priceThreshold))) {
System.out.println("Test09: Pass");
} else {
System.out.println("Test09: Fail");
}
// ------------------------- Test 10 -------------------------
// Two cards, multiple transcations, single day, both non-exceeding
ArrayList<String> expected_test10 = new ArrayList<String>();
expected_test08.add("10d7ce2f43e35fa57d1bbf8b1e4");
if(equalLists(expected_test10, filterTransactions("test10.file", date, priceThreshold))) {
System.out.println("Test10: Pass");
} else {
System.out.println("Test10: Fail");
}
// // call filterTransactions() with transactions, price threchold and date to get a list of cards w/ suspicious transactions
// ArrayList<String> suspect_cards_list = filterTransactions("test06.file", date, priceThreshold);
// // print out suspected card hashes
// if(suspect_cards_list.size() == 0) {
// System.out.println("No cards with fraudulent transactions found.");
// } else {
// for (String cardHash: suspect_cards_list) {
// System.out.println(cardHash);
// }
// }
}
// filterTransactions function takes in a list of transactions, a date, and a threshold spend amount and returns
// a list of credit card number hashes associated with a total of transactions exceeding the threshold for that day.
public static ArrayList<String> filterTransactions(String inputFile, String date, long amountThreshold) {
// read input file
Scanner input = null;
try {
input = new Scanner(new File(inputFile));
} catch( FileNotFoundException e ) {
System.out.println("No such file: " + inputFile);
return null;
}
// declare map structure to collect creditcards and expense totals
// this collection will be a set of creditcard numbers mapping to a set of maps, which in turn map dates to totals
// e.g
// card1 -> {date1 -> total1, date2 -> total2}
// card2 -> {date3 -> total3}
HashMap<String, HashMap<Long, Long>> creditCardTotals = new HashMap<String, HashMap<Long, Long>>();
// list of suspicious cards - this will be populated whenever a card's total for a given day is detected to be over threshold
ArrayList<String> suspectCards = new ArrayList<String>();
// iterate through each of the transaction input file
while( input.hasNextLine() ) {
String transaction = input.nextLine(); // e.g. "10d7ce2f43e35fa57d1bbf8b1e2, 2014-04-29T13:15:54, 10.00"
// ignore if line starts with # (comment)
Pattern commentLine = Pattern.compile("^#");
Matcher m = commentLine.matcher(transaction.trim());
if (m.find()) {
continue;
}
// split transaction string into components (card hash, date, amount)
String[] transactionComponents = transaction.split(",");
// confirm transaction is complete
if(transactionComponents.length < 3) {
// malformed input, move to next transaction
// System.out.println("Error parsing transaction: " + transaction);
continue;
}
// components of this transaction
String transactionCardHash = transactionComponents[0].trim();
String transactionDate = transactionComponents[1].trim();
String transactionAmount = transactionComponents[2].trim();
// extract day component from input e.g. "2014-04-29" from "2014-04-29T13:15:54"
String[] dateSplit = transactionDate.split("T");
String dayComp = dateSplit[0];
// get timestamp for the date (day component)
Long day = null;
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date dte = dateFormat.parse(dayComp);
day = new Long(dte.getTime());
} catch(ParseException e) {
// malformed input, move to next transaction
// System.out.println("Error parsing date: " + dayComp);
continue;
}
Long amt = new Long((long)(Float.parseFloat(transactionAmount)*100));
// check if a record exists for this credit card
HashMap<Long, Long> cardExists = creditCardTotals.get(transactionCardHash);
if( cardExists != null ) {
// card known in this dataset before - check if a total eists for this date
// check if a total exists for this card for this date
Long totalExists = cardExists.get(day);
if(totalExists != null) {
// a count is known for this card for this date - update
Long newTot = cardExists.get(day) + amt;
if(newTot > amountThreshold) {
if(!suspectCards.contains(transactionCardHash)){
suspectCards.add(transactionCardHash);
}
}
cardExists.put(day, newTot);
} else {
// no count for this card for this date, add
cardExists.put(day, amt);
}
} else {
// new card to this dataset - create record
if(amt > amountThreshold) {
if(!suspectCards.contains(transactionCardHash)){
suspectCards.add(transactionCardHash);
}
}
HashMap<Long, Long> thisAmount = new HashMap<Long, Long>();
thisAmount.put(day, amt);
creditCardTotals.put(transactionCardHash, thisAmount);
}
}
return suspectCards;
}
// utility test function to check if two given lists of card number hashes contain the same elements
public static boolean equalLists(ArrayList<String> expected, ArrayList<String> result) {
if (expected == null && result == null) {
return true;
}
if ((expected == null && result!= null) || (expected != null && result== null) || (expected.size() != result.size())) {
return false;
}
// Sort and compare the two lists
Collections.sort(expected);
Collections.sort(result);
return expected.equals(result);
}
}
| Change date comparisons and skip over irrelevant date tx.s | FraudDetector.java | Change date comparisons and skip over irrelevant date tx.s | <ide><path>raudDetector.java
<ide> // ------------------------- Test 06 -------------------------
<ide> // Two cards, both exceeding limit for different days
<ide> ArrayList<String> expected_test06 = new ArrayList<String>();
<del> expected_test06.add("10d7ce2f43e35fa57d1bbf8b1e3");
<add> expected_test06.add("10d7ce2f43e35fa57d1bbf8b1e2");
<ide>
<ide> if(equalLists(expected_test06, filterTransactions("test06.file", date, priceThreshold))) {
<ide> System.out.println("Test06: Pass");
<ide> } else {
<ide> System.out.println("Test06: Fail");
<add> }
<add>
<add> // print out suspected card hashes
<add> ArrayList<String> suspect_cards_list = filterTransactions("test06.file", date, priceThreshold);
<add> if(suspect_cards_list.size() == 0) {
<add> System.out.println("No cards with fraudulent transactions found.");
<add> return;
<add> } else {
<add> for (String cardHash: suspect_cards_list) {
<add> System.out.println(cardHash);
<add> return;
<add> }
<ide> }
<ide>
<ide> // ------------------------- Test 07 -------------------------
<ide> System.out.println("Test10: Fail");
<ide> }
<ide>
<del> // // call filterTransactions() with transactions, price threchold and date to get a list of cards w/ suspicious transactions
<del> // ArrayList<String> suspect_cards_list = filterTransactions("test06.file", date, priceThreshold);
<del>
<del> // // print out suspected card hashes
<add> // print out suspected card hashes
<add> // ArrayList<String> suspect_cards_list = filterTransactions("test05.file", date, priceThreshold);
<ide> // if(suspect_cards_list.size() == 0) {
<ide> // System.out.println("No cards with fraudulent transactions found.");
<add> // return;
<ide> // } else {
<ide> // for (String cardHash: suspect_cards_list) {
<ide> // System.out.println(cardHash);
<add> // return;
<ide> // }
<del> // }
<add> // }
<ide> }
<ide>
<ide> // filterTransactions function takes in a list of transactions, a date, and a threshold spend amount and returns
<ide> // a list of credit card number hashes associated with a total of transactions exceeding the threshold for that day.
<del> public static ArrayList<String> filterTransactions(String inputFile, String date, long amountThreshold) {
<add> public static ArrayList<String> filterTransactions(String inputFile, String dateThreshold, long amountThreshold) {
<ide> // read input file
<ide> Scanner input = null;
<ide>
<ide> try {
<ide> input = new Scanner(new File(inputFile));
<ide> } catch( FileNotFoundException e ) {
<del> System.out.println("No such file: " + inputFile);
<add> // System.out.println("No such file: " + inputFile);
<add> return null;
<add> }
<add>
<add> if(inputFile == null || dateThreshold == null) {
<add> return null;
<add> }
<add>
<add> // ensure that the date provided is of "yyyy-MM-dd" format
<add> dateThreshold = dateThreshold.trim();
<add> Pattern properDate = Pattern.compile("^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$");
<add> Matcher m = properDate.matcher(dateThreshold);
<add> if (!m.find()) {
<add> System.out.println("Invalid date threshold parameter.");
<ide> return null;
<ide> }
<ide>
<ide> // e.g
<ide> // card1 -> {date1 -> total1, date2 -> total2}
<ide> // card2 -> {date3 -> total3}
<del> HashMap<String, HashMap<Long, Long>> creditCardTotals = new HashMap<String, HashMap<Long, Long>>();
<add> // HashMap<String, HashMap<Long, Long>> creditCardTotals = new HashMap<String, HashMap<Long, Long>>();
<add> HashMap<String, Long> creditCardTotals = new HashMap<String, Long>();
<ide>
<ide> // list of suspicious cards - this will be populated whenever a card's total for a given day is detected to be over threshold
<ide> ArrayList<String> suspectCards = new ArrayList<String>();
<add>
<add> // get timestamp for the threshold date (the date the fraudulent transaction cards are required for)
<add> // Long dateThreshold = null;
<add> // try {
<add> // DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
<add> // Date dte = dateFormat.parse(date);
<add> // dateThreshold = new Long(dte.getTime());
<add>
<add> // } catch(ParseException e) {
<add> // // malformed input, move to next transaction
<add> // // System.out.println("Error parsing date: " + dayComp);
<add> // return null;
<add> // }
<ide>
<ide> // iterate through each of the transaction input file
<del> while( input.hasNextLine() ) {
<add> while(input.hasNextLine()) {
<ide> String transaction = input.nextLine(); // e.g. "10d7ce2f43e35fa57d1bbf8b1e2, 2014-04-29T13:15:54, 10.00"
<ide>
<ide> // ignore if line starts with # (comment)
<ide> Pattern commentLine = Pattern.compile("^#");
<del> Matcher m = commentLine.matcher(transaction.trim());
<del> if (m.find()) {
<add> Matcher clm = commentLine.matcher(transaction.trim());
<add> if (clm.find()) {
<ide> continue;
<ide> }
<ide>
<ide>
<ide> // extract day component from input e.g. "2014-04-29" from "2014-04-29T13:15:54"
<ide> String[] dateSplit = transactionDate.split("T");
<del> String dayComp = dateSplit[0];
<del>
<del> // get timestamp for the date (day component)
<del> Long day = null;
<add> String transactionDate_day = dateSplit[0];
<add>
<add> // ensure that the date provided is of "yyyy-MM-dd" format
<add> transactionDate_day = transactionDate_day.trim();
<add> Matcher pdm = properDate.matcher(transactionDate_day);
<add> if (!pdm.find()) {
<add> // System.out.println("Invalid date threshold parameter.");
<add> // return null;
<add>
<add> // possibly malformed transaction reord - move onto next
<add> continue;
<add> }
<add>
<add> // get timestamp for the transaction date (day component)
<add> // Long day = null;
<add> // try {
<add> // DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
<add> // Date dte = dateFormat.parse(dayComp);
<add> // day = new Long(dte.getTime());
<add>
<add> // } catch(ParseException e) {
<add> // // malformed input, move to next transaction
<add> // // System.out.println("Error parsing date: " + dayComp);
<add> // continue;
<add> // }
<add>
<add> // check if this transaction is one we'd be interested in - i.e. one for the date given
<add> // TODO - begs the question, can't you just string compare the day components?
<add> // Also, if the processor only sees transactions only for a given day, can't it be a simple hashmap of card hash-> total?
<add> if(transactionDate_day != dateThreshold) {
<add> continue;
<add> }
<add>
<add> Long amt = null;
<ide> try {
<del> DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
<del> Date dte = dateFormat.parse(dayComp);
<del> day = new Long(dte.getTime());
<del>
<del> } catch(ParseException e) {
<del> // malformed input, move to next transaction
<del> // System.out.println("Error parsing date: " + dayComp);
<del> continue;
<del> }
<del>
<del> Long amt = new Long((long)(Float.parseFloat(transactionAmount)*100));
<add> amt = new Long((long)(Float.parseFloat(transactionAmount)*100));
<add> } catch(NumberFormatException e) {
<add> // malformed input - continue to next
<add> continue;
<add> }
<ide>
<ide> // check if a record exists for this credit card
<del> HashMap<Long, Long> cardExists = creditCardTotals.get(transactionCardHash);
<del>
<del> if( cardExists != null ) {
<del> // card known in this dataset before - check if a total eists for this date
<del>
<del> // check if a total exists for this card for this date
<del> Long totalExists = cardExists.get(day);
<del>
<del> if(totalExists != null) {
<del> // a count is known for this card for this date - update
<del> Long newTot = cardExists.get(day) + amt;
<del>
<del> if(newTot > amountThreshold) {
<del> if(!suspectCards.contains(transactionCardHash)){
<del> suspectCards.add(transactionCardHash);
<del> }
<add> // HashMap<Long, Long> cardExists = creditCardTotals.get(transactionCardHash);
<add> Long cardTotal = creditCardTotals.get(transactionCardHash);
<add>
<add> if(cardTotal != null) {
<add> // card known in this dataset before - update total
<add> Long newTotal = cardTotal + amt;
<add>
<add> if(newTotal > amountThreshold) {
<add> if(!suspectCards.contains(transactionCardHash)) {
<add> suspectCards.add(transactionCardHash);
<ide> }
<del> cardExists.put(day, newTot);
<del> } else {
<del> // no count for this card for this date, add
<del> cardExists.put(day, amt);
<add>
<ide> }
<add>
<add> // // check if a total exists for this card for this date
<add> // Long totalExists = cardExists.get(day);
<add>
<add> // if(totalExists != null) {
<add> // // a count is known for this card for this date - update
<add> // Long newTot = cardExists.get(day) + amt;
<add>
<add> // if(newTot > amountThreshold) {
<add> // if(!suspectCards.contains(transactionCardHash)) {
<add> // suspectCards.add(transactionCardHash);
<add> // }
<add> // }
<add> // cardExists.put(day, newTot);
<add> // } else {
<add> // // no count for this card for this date, add
<add> // cardExists.put(day, amt);
<add> // }
<ide>
<ide> } else {
<ide> // new card to this dataset - create record
<add> creditCardTotals.put(transactionCardHash, amt);
<add>
<ide> if(amt > amountThreshold) {
<del> if(!suspectCards.contains(transactionCardHash)){
<add> if(!suspectCards.contains(transactionCardHash)) {
<ide> suspectCards.add(transactionCardHash);
<ide> }
<ide> }
<ide>
<del> HashMap<Long, Long> thisAmount = new HashMap<Long, Long>();
<del> thisAmount.put(day, amt);
<del>
<del> creditCardTotals.put(transactionCardHash, thisAmount);
<add> // HashMap<Long, Long> thisAmount = new HashMap<Long, Long>();
<add> // thisAmount.put(day, amt);
<add>
<add> // creditCardTotals.put(transactionCardHash, thisAmount);
<ide> }
<ide> }
<ide>
<ide>
<ide> // utility test function to check if two given lists of card number hashes contain the same elements
<ide> public static boolean equalLists(ArrayList<String> expected, ArrayList<String> result) {
<add> // DEBUG - print out the two lists
<add> System.out.println("\tExpected: " + expected);
<add> System.out.println("\tResults: " + result);
<add>
<ide> if (expected == null && result == null) {
<ide> return true;
<ide> }
<ide>
<ide> // Sort and compare the two lists
<ide> Collections.sort(expected);
<del> Collections.sort(result);
<add> Collections.sort(result);
<add>
<ide> return expected.equals(result);
<ide> }
<ide> } |
|
JavaScript | mit | 5baad565ec04c08e5fff6b9bf58cbe097cf3ba45 | 0 | CookPete/react-player,CookPete/react-player | import React, { Component } from 'react'
import { propTypes, defaultProps } from './props'
import { isEqual } from './utils'
const SEEK_ON_PLAY_EXPIRY = 5000
export default class Player extends Component {
static displayName = 'Player'
static propTypes = propTypes
static defaultProps = defaultProps
mounted = false
isReady = false
isPlaying = false // Track playing state internally to prevent bugs
isLoading = true // Use isLoading to prevent onPause when switching URL
loadOnReady = null
startOnPlay = true
seekOnPlay = null
onDurationCalled = false
componentDidMount () {
this.mounted = true
this.player.load(this.props.url)
this.progress()
}
componentWillUnmount () {
clearTimeout(this.progressTimeout)
clearTimeout(this.durationCheckTimeout)
if (this.isReady) {
this.player.stop()
}
if (this.player.disablePIP) {
this.player.disablePIP()
}
this.mounted = false
}
componentWillReceiveProps (nextProps) {
// Invoke player methods based on incoming props
const { url, playing, volume, muted, playbackRate, pip, loop } = this.props
if (!isEqual(url, nextProps.url)) {
if (this.isLoading) {
console.warn(`ReactPlayer: the attempt to load ${nextProps.url} is being deferred until the player has loaded`)
this.loadOnReady = nextProps.url
return
}
this.isLoading = true
this.startOnPlay = true
this.onDurationCalled = false
this.player.load(nextProps.url, this.isReady)
}
if (!playing && nextProps.playing && !this.isPlaying) {
this.player.play()
}
if (playing && !nextProps.playing && this.isPlaying) {
this.player.pause()
}
if (!pip && nextProps.pip && this.player.enablePIP) {
this.player.enablePIP()
} else if (pip && !nextProps.pip && this.player.disablePIP) {
this.player.disablePIP()
}
if (volume !== nextProps.volume && nextProps.volume !== null) {
this.player.setVolume(nextProps.volume)
}
if (muted !== nextProps.muted) {
if (nextProps.muted) {
this.player.mute()
} else {
this.player.unmute()
if (nextProps.volume !== null) {
// Set volume next tick to fix a bug with DailyMotion
setTimeout(() => this.player.setVolume(nextProps.volume))
}
}
}
if (playbackRate !== nextProps.playbackRate && this.player.setPlaybackRate) {
this.player.setPlaybackRate(nextProps.playbackRate)
}
if (loop !== nextProps.loop && this.player.setLoop) {
this.player.setLoop(nextProps.loop)
}
}
getDuration () {
if (!this.isReady) return null
return this.player.getDuration()
}
getCurrentTime () {
if (!this.isReady) return null
return this.player.getCurrentTime()
}
getSecondsLoaded () {
if (!this.isReady) return null
return this.player.getSecondsLoaded()
}
getInternalPlayer = (key) => {
if (!this.player) return null
return this.player[key]
}
progress = () => {
if (this.props.url && this.player && this.isReady) {
const playedSeconds = this.getCurrentTime() || 0
const loadedSeconds = this.getSecondsLoaded()
const duration = this.getDuration()
if (duration) {
const progress = {
playedSeconds,
played: playedSeconds / duration
}
if (loadedSeconds !== null) {
progress.loadedSeconds = loadedSeconds
progress.loaded = loadedSeconds / duration
}
// Only call onProgress if values have changed
if (progress.playedSeconds !== this.prevPlayed || progress.loadedSeconds !== this.prevLoaded) {
this.props.onProgress(progress)
}
this.prevPlayed = progress.playedSeconds
this.prevLoaded = progress.loadedSeconds
}
}
this.progressTimeout = setTimeout(this.progress, this.props.progressFrequency || this.props.progressInterval)
}
seekTo (amount, type) {
// When seeking before player is ready, store value and seek later
if (!this.isReady && amount !== 0) {
this.seekOnPlay = amount
setTimeout(() => { this.seekOnPlay = null }, SEEK_ON_PLAY_EXPIRY)
return
}
const isFraction = !type ? (amount > 0 && amount < 1) : type === 'fraction'
if (isFraction) {
// Convert fraction to seconds based on duration
const duration = this.player.getDuration()
if (!duration) {
console.warn('ReactPlayer: could not seek using fraction – duration not yet available')
return
}
this.player.seekTo(duration * amount)
return
}
this.player.seekTo(amount)
}
onReady = () => {
if (!this.mounted) return
this.isReady = true
this.isLoading = false
const { onReady, playing, volume, muted } = this.props
onReady()
if (!muted && volume !== null) {
this.player.setVolume(volume)
}
if (this.loadOnReady) {
this.player.load(this.loadOnReady, true)
this.loadOnReady = null
} else if (playing) {
this.player.play()
}
this.onDurationCheck()
}
onPlay = () => {
this.isPlaying = true
this.isLoading = false
const { onStart, onPlay, playbackRate } = this.props
if (this.startOnPlay) {
if (this.player.setPlaybackRate) {
this.player.setPlaybackRate(playbackRate)
}
onStart()
this.startOnPlay = false
}
onPlay()
if (this.seekOnPlay) {
this.seekTo(this.seekOnPlay)
this.seekOnPlay = null
}
this.onDurationCheck()
}
onPause = (e) => {
this.isPlaying = false
if (!this.isLoading) {
this.props.onPause(e)
}
}
onEnded = () => {
const { activePlayer, loop, onEnded } = this.props
if (activePlayer.loopOnEnded && loop) {
this.seekTo(0)
}
if (!loop) {
this.isPlaying = false
onEnded()
}
}
onError = (...args) => {
this.isLoading = false
this.props.onError(...args)
}
onDurationCheck = () => {
clearTimeout(this.durationCheckTimeout)
const duration = this.getDuration()
if (duration) {
if (!this.onDurationCalled) {
this.props.onDuration(duration)
this.onDurationCalled = true
}
} else {
this.durationCheckTimeout = setTimeout(this.onDurationCheck, 100)
}
}
onLoaded = () => {
// Sometimes we know loading has stopped but onReady/onPlay are never called
// so this provides a way for players to avoid getting stuck
this.isLoading = false
}
ref = player => {
if (player) {
this.player = player
}
}
render () {
const Player = this.props.activePlayer
if (!Player) {
return null
}
return (
<Player
{...this.props}
ref={this.ref}
onReady={this.onReady}
onPlay={this.onPlay}
onPause={this.onPause}
onEnded={this.onEnded}
onLoaded={this.onLoaded}
onError={this.onError}
/>
)
}
}
| src/Player.js | import React, { Component } from 'react'
import { propTypes, defaultProps } from './props'
import { isEqual } from './utils'
const SEEK_ON_PLAY_EXPIRY = 5000
export default class Player extends Component {
static displayName = 'Player'
static propTypes = propTypes
static defaultProps = defaultProps
mounted = false
isReady = false
isPlaying = false // Track playing state internally to prevent bugs
isLoading = true // Use isLoading to prevent onPause when switching URL
loadOnReady = null
startOnPlay = true
seekOnPlay = null
onDurationCalled = false
componentDidMount () {
this.mounted = true
this.player.load(this.props.url)
this.progress()
}
componentWillUnmount () {
clearTimeout(this.progressTimeout)
clearTimeout(this.durationCheckTimeout)
if (this.isReady) {
this.player.stop()
}
if (this.player.disablePIP) {
this.player.disablePIP()
}
this.mounted = false
}
componentWillReceiveProps (nextProps) {
// Invoke player methods based on incoming props
const { url, playing, volume, muted, playbackRate, pip, loop } = this.props
if (!isEqual(url, nextProps.url)) {
if (this.isLoading) {
console.warn(`ReactPlayer: the attempt to load ${nextProps.url} is being deferred until the player has loaded`)
this.loadOnReady = nextProps.url
return
}
this.isLoading = true
this.startOnPlay = true
this.onDurationCalled = false
this.player.load(nextProps.url, this.isReady)
}
if (!playing && nextProps.playing && !this.isPlaying) {
this.player.play()
}
if (playing && !nextProps.playing && this.isPlaying) {
this.player.pause()
}
if (!pip && nextProps.pip && this.player.enablePIP) {
this.player.enablePIP()
} else if (pip && !nextProps.pip && this.player.disablePIP) {
this.player.disablePIP()
}
if (volume !== nextProps.volume && nextProps.volume !== null) {
this.player.setVolume(nextProps.volume)
}
if (muted !== nextProps.muted) {
if (nextProps.muted) {
this.player.mute()
} else {
this.player.unmute()
if (nextProps.volume !== null) {
// Set volume next tick to fix a bug with DailyMotion
setTimeout(() => this.player.setVolume(nextProps.volume))
}
}
}
if (playbackRate !== nextProps.playbackRate && this.player.setPlaybackRate) {
this.player.setPlaybackRate(nextProps.playbackRate)
}
if (loop !== nextProps.loop && this.player.setLoop) {
this.player.setLoop(nextProps.loop)
}
}
getDuration () {
if (!this.isReady) return null
return this.player.getDuration()
}
getCurrentTime () {
if (!this.isReady) return null
return this.player.getCurrentTime()
}
getSecondsLoaded () {
if (!this.isReady) return null
return this.player.getSecondsLoaded()
}
getInternalPlayer = (key) => {
if (!this.player) return null
return this.player[key]
}
progress = () => {
if (this.props.url && this.player && this.isReady) {
const playedSeconds = this.getCurrentTime() || 0
const loadedSeconds = this.getSecondsLoaded()
const duration = this.getDuration()
if (duration) {
const progress = {
playedSeconds,
played: playedSeconds / duration
}
if (loadedSeconds !== null) {
progress.loadedSeconds = loadedSeconds
progress.loaded = loadedSeconds / duration
}
// Only call onProgress if values have changed
if (progress.played !== this.prevPlayed || progress.loaded !== this.prevLoaded) {
this.props.onProgress(progress)
}
this.prevPlayed = progress.played
this.prevLoaded = progress.loaded
}
}
this.progressTimeout = setTimeout(this.progress, this.props.progressFrequency || this.props.progressInterval)
}
seekTo (amount, type) {
// When seeking before player is ready, store value and seek later
if (!this.isReady && amount !== 0) {
this.seekOnPlay = amount
setTimeout(() => { this.seekOnPlay = null }, SEEK_ON_PLAY_EXPIRY)
return
}
const isFraction = !type ? (amount > 0 && amount < 1) : type === 'fraction'
if (isFraction) {
// Convert fraction to seconds based on duration
const duration = this.player.getDuration()
if (!duration) {
console.warn('ReactPlayer: could not seek using fraction – duration not yet available')
return
}
this.player.seekTo(duration * amount)
return
}
this.player.seekTo(amount)
}
onReady = () => {
if (!this.mounted) return
this.isReady = true
this.isLoading = false
const { onReady, playing, volume, muted } = this.props
onReady()
if (!muted && volume !== null) {
this.player.setVolume(volume)
}
if (this.loadOnReady) {
this.player.load(this.loadOnReady, true)
this.loadOnReady = null
} else if (playing) {
this.player.play()
}
this.onDurationCheck()
}
onPlay = () => {
this.isPlaying = true
this.isLoading = false
const { onStart, onPlay, playbackRate } = this.props
if (this.startOnPlay) {
if (this.player.setPlaybackRate) {
this.player.setPlaybackRate(playbackRate)
}
onStart()
this.startOnPlay = false
}
onPlay()
if (this.seekOnPlay) {
this.seekTo(this.seekOnPlay)
this.seekOnPlay = null
}
this.onDurationCheck()
}
onPause = (e) => {
this.isPlaying = false
if (!this.isLoading) {
this.props.onPause(e)
}
}
onEnded = () => {
const { activePlayer, loop, onEnded } = this.props
if (activePlayer.loopOnEnded && loop) {
this.seekTo(0)
}
if (!loop) {
this.isPlaying = false
onEnded()
}
}
onError = (...args) => {
this.isLoading = false
this.props.onError(...args)
}
onDurationCheck = () => {
clearTimeout(this.durationCheckTimeout)
const duration = this.getDuration()
if (duration) {
if (!this.onDurationCalled) {
this.props.onDuration(duration)
this.onDurationCalled = true
}
} else {
this.durationCheckTimeout = setTimeout(this.onDurationCheck, 100)
}
}
onLoaded = () => {
// Sometimes we know loading has stopped but onReady/onPlay are never called
// so this provides a way for players to avoid getting stuck
this.isLoading = false
}
ref = player => {
if (player) {
this.player = player
}
}
render () {
const Player = this.props.activePlayer
if (!Player) {
return null
}
return (
<Player
{...this.props}
ref={this.ref}
onReady={this.onReady}
onPlay={this.onPlay}
onPause={this.onPause}
onEnded={this.onEnded}
onLoaded={this.onLoaded}
onError={this.onError}
/>
)
}
}
| Fix onProgress for infinite duration streams
Fixes https://github.com/CookPete/react-player/issues/503 based on the suggestion here: https://github.com/CookPete/react-player/issues/503#issuecomment-482031553
| src/Player.js | Fix onProgress for infinite duration streams | <ide><path>rc/Player.js
<ide> progress.loaded = loadedSeconds / duration
<ide> }
<ide> // Only call onProgress if values have changed
<del> if (progress.played !== this.prevPlayed || progress.loaded !== this.prevLoaded) {
<add> if (progress.playedSeconds !== this.prevPlayed || progress.loadedSeconds !== this.prevLoaded) {
<ide> this.props.onProgress(progress)
<ide> }
<del> this.prevPlayed = progress.played
<del> this.prevLoaded = progress.loaded
<add> this.prevPlayed = progress.playedSeconds
<add> this.prevLoaded = progress.loadedSeconds
<ide> }
<ide> }
<ide> this.progressTimeout = setTimeout(this.progress, this.props.progressFrequency || this.props.progressInterval) |
|
Java | apache-2.0 | ae41fe0ca58cf26cb89d42d417cb9d8bbd56b764 | 0 | yangfuhai/jboot,yangfuhai/jboot | /**
* Copyright (c) 2015-2020, Michael Yang 杨福海 ([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>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.jboot.service;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import io.jboot.db.model.Columns;
import io.jboot.db.model.JbootModel;
import io.jboot.exception.JbootException;
import io.jboot.utils.ClassUtil;
import io.jboot.utils.ObjectFunc;
import io.jboot.utils.ObjectUtil;
import java.util.ArrayList;
import java.util.List;
/**
* JbootServiceBase 类
* Jboot 1.x 的 Service 需要 Join 功能的话,需要实现 JbootServiceJoiner 接口
*/
public class JbootServiceBase<M extends JbootModel<M>>
extends JbootServiceJoinerImpl
implements JbootServiceJoiner {
protected static final int ACTION_ADD = 1;
protected static final int ACTION_DEL = 2;
protected static final int ACTION_UPDATE = 3;
protected JbootModel<M> DAO = null;
public JbootServiceBase() {
DAO = initDao();
}
/**
* 初始化 DAO
* 子类可以复写 自定义自己的DAO
*
* @return
*/
protected M initDao() {
Class<M> modelClass = ClassUtil.getGenericClass(getClass());
if (modelClass == null) {
throw new JbootException("can not get model class name in " + ClassUtil.getUsefulClass(getClass()));
}
//默认不通过AOP构建DAO,提升性能,若特殊需要重写initDao()方法即可
return ClassUtil.newInstance(modelClass, false);
}
public JbootModel getDao() {
return DAO;
}
/**
* 根据ID查找model
*
* @param id
* @return
*/
public M findById(Object id) {
return DAO.findById(id);
}
/**
* 根据 Columns 查找单条数据
*
* @param columns
* @return
*/
public M findFirstByColumns(Columns columns) {
return findFirstByColumns(columns, null);
}
/**
* 根据 Columns 查找单条数据
*
* @param columns
* @param orderBy
* @return
*/
public M findFirstByColumns(Columns columns, String orderBy) {
return DAO.findFirstByColumns(columns, orderBy);
}
/**
* 查找全部数据
*
* @return
*/
public List<M> findAll() {
return DAO.findAll();
}
/**
* 根据 Columns 查找数据
*
* @param columns
* @return
*/
public List<M> findListByColumns(Columns columns) {
return DAO.findListByColumns(columns);
}
/**
* 根据 Columns 查找数据
*
* @param columns
* @param orderBy
* @return
*/
public List<M> findListByColumns(Columns columns, String orderBy) {
return DAO.findListByColumns(columns, orderBy);
}
/**
* 根据 Columns 查找数据
*
* @param columns
* @param count
* @return
*/
public List<M> findListByColumns(Columns columns, Integer count) {
return DAO.findListByColumns(columns, count);
}
/**
* 根据 Columns 查找数据
*
* @param columns
* @param orderBy
* @param count
* @return
*/
public List<M> findListByColumns(Columns columns, String orderBy, Integer count) {
return DAO.findListByColumns(columns, orderBy, count);
}
public List<M> findListByIds(Object... ids) {
if (ids == null || ids.length == 0) {
return null;
}
List<M> list = new ArrayList<>();
for (Object id : ids) {
if (id.getClass() == int[].class) {
findListByIds(list, (int[]) id);
} else if (id.getClass() == long[].class) {
findListByIds(list, (long[]) id);
} else if (id.getClass() == short[].class) {
findListByIds(list, (short[]) id);
} else {
M model = findById(id);
if (model != null) {
list.add(model);
}
}
}
return list;
}
private void findListByIds(List<M> list, int[] ids) {
for (int id : ids) {
M model = findById(id);
if (model != null) {
list.add(model);
}
}
}
private void findListByIds(List<M> list, long[] ids) {
for (long id : ids) {
M model = findById(id);
if (model != null) {
list.add(model);
}
}
}
private void findListByIds(List<M> list, short[] ids) {
for (short id : ids) {
M model = findById(id);
if (model != null) {
list.add(model);
}
}
}
/**
* 根据提交查询数据量
*
* @param columns
* @return
*/
public long findCountByColumns(Columns columns) {
return DAO.findCountByColumns(columns);
}
/**
* 根据ID 删除model
*
* @param id
* @return
*/
public boolean deleteById(Object id) {
boolean result = DAO.deleteById(id);
if (result) {
shouldUpdateCache(ACTION_DEL, null, id);
}
return result;
}
/**
* 删除
*
* @param model
* @return
*/
public boolean delete(M model) {
boolean result = model.delete();
if (result) {
shouldUpdateCache(ACTION_DEL, model, model._getIdValue());
}
return result;
}
/**
* 根据 多个 id 批量删除
*
* @param ids
* @return
*/
public boolean batchDeleteByIds(Object... ids) {
boolean result = DAO.batchDeleteByIds(ids);
if (result) {
for (Object id : ids) {
shouldUpdateCache(ACTION_DEL, null, id);
}
}
return result;
}
/**
* 保存到数据库
*
* @param model
* @return id if success
*/
public Object save(M model) {
boolean result = model.save();
if (result) {
shouldUpdateCache(ACTION_ADD, model, model._getIdValue());
return model._getIdValue();
}
return null;
}
/**
* 保存或更新
*
* @param model
* @return id if success
*/
public Object saveOrUpdate(M model) {
if (model._getIdValue() == null) {
return save(model);
} else if (update(model)) {
return model._getIdValue();
}
return null;
}
/**
* 更新
*
* @param model
* @return
*/
public boolean update(M model) {
boolean result = model.update();
if (result) {
shouldUpdateCache(ACTION_UPDATE, model, model._getIdValue());
}
return result;
}
/**
* 分页
*
* @param page
* @param pageSize
* @return
*/
public Page<M> paginate(int page, int pageSize) {
return DAO.paginate(page, pageSize);
}
/**
* 分页
*
* @param page
* @param pageSize
* @return
*/
public Page<M> paginateByColumns(int page, int pageSize, Columns columns) {
return DAO.paginateByColumns(page, pageSize, columns);
}
/**
* 分页
*
* @param page
* @param pageSize
* @param columns
* @param orderBy
* @return
*/
public Page<M> paginateByColumns(int page, int pageSize, Columns columns, String orderBy) {
return DAO.paginateByColumns(page, pageSize, columns, orderBy);
}
/**
* 同步 model 数据到数据库
*
* @param columns
* @param syncModels
* @param compareAttrGetters
*/
public void syncModels(Columns columns, List<M> syncModels, ObjectFunc<M>... compareAttrGetters) {
if (columns == null) {
throw new NullPointerException("columns must not be null");
}
if (syncModels == null || syncModels.isEmpty()) {
DAO.deleteByColumns(columns);
return;
}
List<M> existModels = findListByColumns(columns);
if (existModels == null || existModels.isEmpty()) {
Db.batchSave(syncModels, syncModels.size());
return;
}
for (M existModel : existModels) {
if (!ObjectUtil.isContainsObject(syncModels, existModel, compareAttrGetters)) {
existModel.delete();
}
}
for (M syncModel : syncModels) {
M existModel = ObjectUtil.getContainsObject(existModels, syncModel, compareAttrGetters);
if (existModel == null) {
syncModel.save();
} else {
existModel._setAttrs(syncModel).update();
}
}
}
/**
* 复写 JbootServiceJoinerImpl 的方法
*
* @param columnValue
* @return
*/
@Override
protected JbootModel joinByValue(Object columnValue, JbootModel sourceModel) {
return findById(columnValue);
}
/**
* 用于给子类复写,用于刷新缓存
*
* @param action
* @param model
* @param id
*/
public void shouldUpdateCache(int action, Model model, Object id) {
}
@Override
protected <M extends JbootModel> List<M> joinManyByValue(String columnName, Object value, M sourceModel) {
return (List<M>) findListByColumns(Columns.create(columnName, value));
}
}
| src/main/java/io/jboot/service/JbootServiceBase.java | /**
* Copyright (c) 2015-2020, Michael Yang 杨福海 ([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>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.jboot.service;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import io.jboot.db.model.Columns;
import io.jboot.db.model.JbootModel;
import io.jboot.exception.JbootException;
import io.jboot.utils.ClassUtil;
import io.jboot.utils.ObjectFunc;
import io.jboot.utils.ObjectUtil;
import java.util.List;
/**
* JbootServiceBase 类
* Jboot 1.x 的 Service 需要 Join 功能的话,需要实现 JbootServiceJoiner 接口
*/
public class JbootServiceBase<M extends JbootModel<M>>
extends JbootServiceJoinerImpl
implements JbootServiceJoiner {
protected static final int ACTION_ADD = 1;
protected static final int ACTION_DEL = 2;
protected static final int ACTION_UPDATE = 3;
protected JbootModel<M> DAO = null;
public JbootServiceBase() {
DAO = initDao();
}
/**
* 初始化 DAO
* 子类可以复写 自定义自己的DAO
*
* @return
*/
protected M initDao() {
Class<M> modelClass = ClassUtil.getGenericClass(getClass());
if (modelClass == null) {
throw new JbootException("can not get model class name in " + ClassUtil.getUsefulClass(getClass()));
}
//默认不通过AOP构建DAO,提升性能,若特殊需要重写initDao()方法即可
return ClassUtil.newInstance(modelClass, false);
}
public JbootModel getDao() {
return DAO;
}
/**
* 根据ID查找model
*
* @param id
* @return
*/
public M findById(Object id) {
return DAO.findById(id);
}
/**
* 根据 Columns 查找单条数据
*
* @param columns
* @return
*/
public M findFirstByColumns(Columns columns) {
return findFirstByColumns(columns, null);
}
/**
* 根据 Columns 查找单条数据
*
* @param columns
* @param orderBy
* @return
*/
public M findFirstByColumns(Columns columns, String orderBy) {
return DAO.findFirstByColumns(columns, orderBy);
}
/**
* 查找全部数据
*
* @return
*/
public List<M> findAll() {
return DAO.findAll();
}
/**
* 根据 Columns 查找数据
*
* @param columns
* @return
*/
public List<M> findListByColumns(Columns columns) {
return DAO.findListByColumns(columns);
}
/**
* 根据 Columns 查找数据
*
* @param columns
* @param orderBy
* @return
*/
public List<M> findListByColumns(Columns columns, String orderBy) {
return DAO.findListByColumns(columns, orderBy);
}
/**
* 根据 Columns 查找数据
*
* @param columns
* @param count
* @return
*/
public List<M> findListByColumns(Columns columns, Integer count) {
return DAO.findListByColumns(columns, count);
}
/**
* 根据 Columns 查找数据
*
* @param columns
* @param orderBy
* @param count
* @return
*/
public List<M> findListByColumns(Columns columns, String orderBy, Integer count) {
return DAO.findListByColumns(columns, orderBy, count);
}
/**
* 根据提交查询数据量
*
* @param columns
* @return
*/
public long findCountByColumns(Columns columns) {
return DAO.findCountByColumns(columns);
}
/**
* 根据ID 删除model
*
* @param id
* @return
*/
public boolean deleteById(Object id) {
boolean result = DAO.deleteById(id);
if (result) {
shouldUpdateCache(ACTION_DEL, null, id);
}
return result;
}
/**
* 删除
*
* @param model
* @return
*/
public boolean delete(M model) {
boolean result = model.delete();
if (result) {
shouldUpdateCache(ACTION_DEL, model, model._getIdValue());
}
return result;
}
/**
* 根据 多个 id 批量删除
*
* @param ids
* @return
*/
public boolean batchDeleteByIds(Object... ids) {
boolean result = DAO.batchDeleteByIds(ids);
if (result) {
for (Object id : ids) {
shouldUpdateCache(ACTION_DEL, null, id);
}
}
return result;
}
/**
* 保存到数据库
*
* @param model
* @return id if success
*/
public Object save(M model) {
boolean result = model.save();
if (result) {
shouldUpdateCache(ACTION_ADD, model, model._getIdValue());
return model._getIdValue();
}
return null;
}
/**
* 保存或更新
*
* @param model
* @return id if success
*/
public Object saveOrUpdate(M model) {
if (model._getIdValue() == null) {
return save(model);
} else if (update(model)) {
return model._getIdValue();
}
return null;
}
/**
* 更新
*
* @param model
* @return
*/
public boolean update(M model) {
boolean result = model.update();
if (result) {
shouldUpdateCache(ACTION_UPDATE, model, model._getIdValue());
}
return result;
}
/**
* 分页
*
* @param page
* @param pageSize
* @return
*/
public Page<M> paginate(int page, int pageSize) {
return DAO.paginate(page, pageSize);
}
/**
* 分页
*
* @param page
* @param pageSize
* @return
*/
public Page<M> paginateByColumns(int page, int pageSize, Columns columns) {
return DAO.paginateByColumns(page, pageSize, columns);
}
/**
* 分页
*
* @param page
* @param pageSize
* @param columns
* @param orderBy
* @return
*/
public Page<M> paginateByColumns(int page, int pageSize, Columns columns, String orderBy) {
return DAO.paginateByColumns(page, pageSize, columns, orderBy);
}
/**
* 同步 model 数据到数据库
*
* @param columns
* @param syncModels
* @param compareAttrGetters
*/
public void syncModels(Columns columns, List<M> syncModels, ObjectFunc<M>... compareAttrGetters) {
if (columns == null) {
throw new NullPointerException("columns must not be null");
}
if (syncModels == null || syncModels.isEmpty()) {
DAO.deleteByColumns(columns);
return;
}
List<M> existModels = findListByColumns(columns);
if (existModels == null || existModels.isEmpty()) {
Db.batchSave(syncModels, syncModels.size());
return;
}
for (M existModel : existModels) {
if (!ObjectUtil.isContainsObject(syncModels, existModel, compareAttrGetters)) {
existModel.delete();
}
}
for (M syncModel : syncModels) {
M existModel = ObjectUtil.getContainsObject(existModels, syncModel, compareAttrGetters);
if (existModel == null) {
syncModel.save();
} else {
existModel._setAttrs(syncModel).update();
}
}
}
/**
* 复写 JbootServiceJoinerImpl 的方法
*
* @param columnValue
* @return
*/
@Override
protected JbootModel joinByValue(Object columnValue, JbootModel sourceModel) {
return findById(columnValue);
}
/**
* 用于给子类复写,用于刷新缓存
*
* @param action
* @param model
* @param id
*/
public void shouldUpdateCache(int action, Model model, Object id) {
}
@Override
protected <M extends JbootModel> List<M> joinManyByValue(String columnName, Object value, M sourceModel) {
return (List<M>) findListByColumns(Columns.create(columnName, value));
}
}
| add JbootServiceBase.findListByIds() methods
| src/main/java/io/jboot/service/JbootServiceBase.java | add JbootServiceBase.findListByIds() methods | <ide><path>rc/main/java/io/jboot/service/JbootServiceBase.java
<ide> import io.jboot.utils.ObjectFunc;
<ide> import io.jboot.utils.ObjectUtil;
<ide>
<add>import java.util.ArrayList;
<ide> import java.util.List;
<ide>
<ide> /**
<ide> }
<ide>
<ide>
<add> public List<M> findListByIds(Object... ids) {
<add> if (ids == null || ids.length == 0) {
<add> return null;
<add> }
<add>
<add> List<M> list = new ArrayList<>();
<add> for (Object id : ids) {
<add> if (id.getClass() == int[].class) {
<add> findListByIds(list, (int[]) id);
<add> } else if (id.getClass() == long[].class) {
<add> findListByIds(list, (long[]) id);
<add> } else if (id.getClass() == short[].class) {
<add> findListByIds(list, (short[]) id);
<add> } else {
<add> M model = findById(id);
<add> if (model != null) {
<add> list.add(model);
<add> }
<add> }
<add> }
<add> return list;
<add> }
<add>
<add> private void findListByIds(List<M> list, int[] ids) {
<add> for (int id : ids) {
<add> M model = findById(id);
<add> if (model != null) {
<add> list.add(model);
<add> }
<add> }
<add> }
<add>
<add> private void findListByIds(List<M> list, long[] ids) {
<add> for (long id : ids) {
<add> M model = findById(id);
<add> if (model != null) {
<add> list.add(model);
<add> }
<add> }
<add> }
<add>
<add>
<add> private void findListByIds(List<M> list, short[] ids) {
<add> for (short id : ids) {
<add> M model = findById(id);
<add> if (model != null) {
<add> list.add(model);
<add> }
<add> }
<add> }
<add>
<add>
<ide> /**
<ide> * 根据提交查询数据量
<ide> * |
|
Java | apache-2.0 | fc2d1e74307719f28d4360efcd059f92c5945c70 | 0 | Magic2Brain/M2B,Magic2Brain/M2B | package m2b.magic2brain.com;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.picasso.Picasso;
import org.w3c.dom.Text;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import m2b.magic2brain.com.magic2brain.R;
//TODO: Add alternative query-mode (All vs. Sets of eg. 7)
public class QueryActivity extends AppCompatActivity {
private ImageView imgv; // The image of the card gets stored here
private ImageView imgCorr; // Is over the image. It's to indicate if the answer was correct or not
private Toolbar hiding; // This is a bar that hides a certain area
private ArrayList<Card> set; //This Arraylist holds all Cards that need to query. It won't be edited (after loading it)
private ArrayList<Card> wrongGuessed;
private int indexCard; // Actually not needed (because we remove cards from WrongGuessed) but may be useful in later edits
private boolean firstGuess; //This is to check if he guessed it at first try. If so we remove the card from the Arraylist. Else it stays there.
private String deckName; //Name of the deck. Only for saving/loading purpose
private TextView score; //this will show the user the current progress
private boolean queryLand = true; // should we really query lands?
private boolean skipped = false; // this is to store if the user has skipped or not
private ArrayList<String> recentlyLearned; // this is to save the deckname if a new set is learned
protected void onCreate(Bundle savedInstanceState) {
// Build UI
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_query);
hiding = (Toolbar) findViewById(R.id.toolbar_query);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
buildMenu();
// Hide the status bar.
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
// Prepare Query
Intent i = getIntent();
Deck qur = (Deck) i.getSerializableExtra("Set");
deckName = qur.getName();
String code = qur.getCode();
if(deckName == null){deckName="DEFAULT";}
setTitle(deckName);
if(!loadRecent()){recentlyLearned = new ArrayList<>();}
if(!recentlyLearned.contains(code)){recentlyLearned.add(code);} //TODO: CODE DOESNT WORK. DECKNAME DOES. WHY THE FUCK?
if(recentlyLearned.size() == 2){recentlyLearned.remove(0);}
saveRecent();
set = qur.getSet();
if(!loadProgress()) { //First we try to load the progress. If this fails, we simply start over
wrongGuessed = (ArrayList) set.clone(); //Lets assume he guessed everything wrong and remove the card of this Array when he guesses it right
shuffleWrongs(); //Shuffle it a bit (better learn-effect)
indexCard = 0;
}
showFirstPic(); //Start the query
if(deckName.contains("DEFAULT")){restartAll();}
}
protected void onPause(){
super.onPause();
saveProgress();
}
public boolean loadRecent(){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Gson gson = new Gson();
String json = sharedPrefs.getString("query_recent",null);
Type type = new TypeToken<ArrayList<String>>(){}.getType();
ArrayList<String> aL = gson.fromJson(json, type);
if(aL == null){return false;}
recentlyLearned = aL;
return true;
}
public void saveRecent(){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(recentlyLearned);
editor.putString("query_recent", json);
editor.commit();
}
public boolean loadProgress(){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Gson gson = new Gson();
String json = sharedPrefs.getString("query_list_"+deckName,null);
Type type = new TypeToken<ArrayList<Card>>(){}.getType();
ArrayList<Card> aL = gson.fromJson(json, type);
int loadedIndex = sharedPrefs.getInt("query_index_"+deckName,-1);
if(aL == null){return false;}
wrongGuessed = aL;
indexCard = loadedIndex;
return true;
}
public void saveProgress(){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(wrongGuessed);
editor.putString("query_list_"+deckName, json);
editor.putInt("query_index_"+deckName,indexCard);
editor.commit();
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.query, menu);
return true;
}
public void shuffleWrongs(){
Collections.shuffle(wrongGuessed, new Random(System.nanoTime()));
}
public void showPic(int MultiID){
Picasso.with(this)
.load("http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=" + MultiID + "&type=card")
.placeholder(R.drawable.loading_image)
.error(R.drawable.image_not_found)
.into(imgv);
}
public void showFirstPic(){
updateScore();
showHiderInstant();
firstGuess = true;
showPic(wrongGuessed.get(indexCard).getMultiverseid());
hiding.bringToFront();
}
public void showNextPic(){
updateScore();
skipped = false;
showHider();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
firstGuess = true;
showPic(wrongGuessed.get(indexCard).getMultiverseid());
hiding.bringToFront();
}
}, 800);
}
public void checkAnswer(String txt){ //TODO: Optional: Ask other things (like Mana-Cost etc.)
if(txt.replaceAll("\\s+","").equalsIgnoreCase(wrongGuessed.get(indexCard).getName().replaceAll("\\s+",""))) {
if(firstGuess){wrongGuessed.remove(indexCard);} //if he guessed it, we remove it.
else {indexCard++;} // else we continue with the next card
if(indexCard == wrongGuessed.size()){ //If this true he's through the set
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
setDone();
}
}, 1000);
} else {
if(!skipped){
imgCorr.setImageResource(R.drawable.correct_answer);
showImgCorr();
}
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if(!skipped){hideImgCorr();}
showNextPic();
}
}, 1000);
}
} else {
wrongAnswer();
}
}
public void skip(){
skipped = true;
wrongAnswer();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
checkAnswer(wrongGuessed.get(indexCard).getName());
}
}, 1000);
}
public void wrongAnswer(){
firstGuess = false;
imgCorr.setImageResource(R.drawable.wrong_answer);
showImgCorr();
hideHider();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
hideImgCorr();
}
}, 1000);
}
public void setDone(){
buildEndScreen();
shuffleWrongs();
}
public void hideHider(){ // Shows the name of the card fadingly
hiding.animate().alpha(0).setDuration(1000).setInterpolator(new DecelerateInterpolator()).withEndAction(new Runnable() {
public void run() {hiding.animate().alpha(0).setDuration(1000).setInterpolator(new AccelerateInterpolator()).start();}}).start();
}
public void showHider(){ // Hides the name of the card fadingly
hiding.animate().alpha(1).setDuration(1000).setInterpolator(new DecelerateInterpolator()).withEndAction(new Runnable() {
public void run() {hiding.animate().alpha(1).setDuration(100).setInterpolator(new AccelerateInterpolator()).start();}}).start();
}
public void showHiderInstant(){ // Hides the name of the card instantly
hiding.animate().alpha(1).setDuration(10).setInterpolator(new DecelerateInterpolator()).withEndAction(new Runnable() {
public void run() {hiding.animate().alpha(1).setDuration(100).setInterpolator(new AccelerateInterpolator()).start();}}).start();
}
public void hideImgCorr(){
Animation myFadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fadeout);
imgCorr.startAnimation(myFadeInAnimation); //Set animation to your ImageView
}
public void showImgCorr(){
Animation myFadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fadein);
imgCorr.startAnimation(myFadeInAnimation); //Set animation to your ImageView
}
public void buildMenu(){
int scrWidth = getWindowManager().getDefaultDisplay().getWidth();
int scrHeight = getWindowManager().getDefaultDisplay().getHeight();
RelativeLayout lyt = (RelativeLayout) findViewById(R.id.query_absolute); // Get the View of the XML
lyt.removeAllViews(); //Clear the Board
RelativeLayout.LayoutParams params;
params = new RelativeLayout.LayoutParams((int)(0.55*scrWidth),(int)(0.03*scrHeight));
params.leftMargin = (scrWidth/2 - (int)(0.55*scrWidth)/2); // X-Position
params.topMargin = (int)(0.07*scrHeight); // Y-Position
lyt.addView(hiding,params);
imgv = new ImageView(this); // Create new Imageview
params = new RelativeLayout.LayoutParams(scrWidth /*Width*/, (int)(0.5*scrHeight))/*Height*/;
params.leftMargin = 0; // X-Position
params.topMargin = (int)(0.05*scrHeight); // Y-Position
lyt.addView(imgv, params); // add it to the View
imgCorr = new ImageView(this); // Create new Imageview
hideImgCorr();
params = new RelativeLayout.LayoutParams(scrWidth /*Width*/, (int)(0.5*scrHeight))/*Height*/;
params.leftMargin = 0; // X-Position
params.topMargin = (int)(0.05*scrHeight); // Y-Position
lyt.addView(imgCorr, params); // add it to the View
// Add EditText like Imageview
final EditText inputtxt = new EditText(this);
inputtxt.setGravity(Gravity.CENTER);
inputtxt.setHint("What is the name of this card?");
params = new RelativeLayout.LayoutParams((int)(0.75*scrWidth), (int)(0.1*scrHeight));
params.leftMargin = (int)(0.125*scrWidth);
params.topMargin = (int)(0.55*scrHeight);
lyt.addView(inputtxt, params);
// Add a Listener to it (so the User can simply press ENTER on the keyboard)
inputtxt.setOnKeyListener(new View.OnKeyListener(){
public boolean onKey(View v, int keyCode, KeyEvent event){
if (event.getAction() == KeyEvent.ACTION_DOWN){
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
checkAnswer(inputtxt.getText().toString());
inputtxt.setText("");
return true;
default:
break;
}
}
return false;
}
});
Button answer = new Button(this);
answer.setText("Answer");
answer.setTextColor(Color.WHITE);
answer.getBackground().setColorFilter(getResources().getColor(R.color.colorAccent), PorterDuff.Mode.MULTIPLY);
params = new RelativeLayout.LayoutParams((int)(0.25*scrWidth), (int)(0.1*scrHeight));
params.leftMargin = (scrWidth/2)-(int)(0.25*scrWidth);
params.topMargin = (int)(0.50*scrHeight)+(int)(0.15*scrHeight);
lyt.addView(answer, params);
answer.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
checkAnswer(inputtxt.getText().toString());
inputtxt.setText("");
}
});
Button skip = new Button(this);
skip.setText("Skip");
skip.setTextColor(Color.WHITE);
skip.getBackground().setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.MULTIPLY);
params = new RelativeLayout.LayoutParams((int)(0.25*scrWidth), (int)(0.1*scrHeight));
params.leftMargin = (scrWidth/2);
params.topMargin = (int)(0.50*scrHeight)+(int)(0.15*scrHeight);
lyt.addView(skip, params);
skip.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {skip();}
});
score = new TextView(this); // Create new Textview
score.setGravity(Gravity.CENTER);
score.setTextSize(36);
params = new RelativeLayout.LayoutParams(scrWidth /*Width*/, (int)(0.1*scrHeight))/*Height*/;
params.leftMargin = 0; // X-Position
params.topMargin = (int)(0.78*scrHeight); // Y-Position
lyt.addView(score, params); // add it to the View
}
public void updateScore(){
score.setText( (set.size()-wrongGuessed.size()) + " / " + indexCard +" / " + (wrongGuessed.size()-indexCard));
}
public void buildEndScreen(){
int scrWidth = getWindowManager().getDefaultDisplay().getWidth();
int scrHeight = getWindowManager().getDefaultDisplay().getHeight();
RelativeLayout lyt = (RelativeLayout) findViewById(R.id.query_absolute); // Get the View of the XML
lyt.removeAllViews(); //Clear the board
RelativeLayout.LayoutParams params;
TextView rights = new TextView(this);
rights.setText("Right: ");
rights.setTextSize(36);
rights.setTextColor(getResources().getColor(R.color.colorPrimary));
params = new RelativeLayout.LayoutParams(scrWidth /*Width*/, (int)(0.1*scrHeight))/*Height*/;
params.leftMargin = (int)(0.1*scrHeight); // X-Position
params.topMargin = (int)(0.05*scrHeight); // Y-Position
lyt.addView(rights, params); // add it to the View
TextView rights2 = new TextView(this);
rights2.setText(""+(set.size() - wrongGuessed.size()));
rights2.setTextSize(36);
rights2.setTextColor(getResources().getColor(R.color.colorPrimary));
params = new RelativeLayout.LayoutParams(scrWidth /*Width*/, (int)(0.1*scrHeight))/*Height*/;
params.leftMargin = (int)(0.4*scrHeight); // X-Position
params.topMargin = (int)(0.05*scrHeight); // Y-Position
lyt.addView(rights2, params); // add it to the View
TextView wrongs = new TextView(this);
wrongs.setText("Wrong: ");
wrongs.setTextSize(36);
wrongs.setTextColor(getResources().getColor(R.color.colorAccent));
params = new RelativeLayout.LayoutParams(scrWidth /*Width*/, (int)(0.1*scrHeight))/*Height*/;
params.leftMargin = (int)(0.1*scrHeight); // X-Position
params.topMargin = (int)(0.05*scrHeight) + (int)(0.1*scrHeight); // Y-Position
lyt.addView(wrongs, params); // add it to the View
TextView wrongs2 = new TextView(this);
wrongs2.setText("" + (wrongGuessed.size()));
wrongs2.setTextSize(36);
wrongs2.setTextColor(getResources().getColor(R.color.colorAccent));
params = new RelativeLayout.LayoutParams(scrWidth /*Width*/, (int)(0.1*scrHeight))/*Height*/;
params.leftMargin = (int)(0.4*scrHeight); // X-Position
params.topMargin = (int)(0.05*scrHeight) + (int)(0.1*scrHeight); // Y-Position
lyt.addView(wrongs2, params); // add it to the View
TextView total = new TextView(this);
total.setText("Total: ");
total.setTextSize(36);
total.setTextColor(Color.BLACK);
params = new RelativeLayout.LayoutParams(scrWidth /*Width*/, (int)(0.09*scrHeight))/*Height*/;
params.leftMargin = (int)(0.1*scrHeight); // X-Position
params.topMargin = (int)(0.05*scrHeight) + (int)(0.1*scrHeight) + (int)(0.1*scrHeight); // Y-Position
lyt.addView(total, params); // add it to the View
TextView total2 = new TextView(this);
total2.setText("" + (set.size()));
total2.setTextSize(36);
total2.setTextColor(Color.BLACK);
params = new RelativeLayout.LayoutParams(scrWidth /*Width*/, (int)(0.09*scrHeight))/*Height*/;
params.leftMargin = (int)(0.4*scrHeight); // X-Position
params.topMargin = (int)(0.05*scrHeight) + (int)(0.1*scrHeight) + (int)(0.1*scrHeight); // Y-Position
lyt.addView(total2, params); // add it to the View
if(wrongGuessed.size() > 0) {
Button repWrong = new Button(this);
repWrong.setText("Repeat wrong guessed");
repWrong.setTextColor(Color.WHITE);
repWrong.getBackground().setColorFilter(getResources().getColor(R.color.colorAccent), PorterDuff.Mode.MULTIPLY);
params = new RelativeLayout.LayoutParams((int) (0.90 * scrWidth), (int) (0.1 * scrHeight));
params.leftMargin = (int) (0.05 * scrWidth);
params.topMargin = (int) (0.4 * scrHeight) + (int) (0.1 * scrHeight) + (int) (0.1 * scrHeight) + (int) (0.1 * scrHeight);
lyt.addView(repWrong, params);
repWrong.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
buildMenu();
indexCard = 0;
showFirstPic();
}
});
}
Button repAll = new Button(this);
repAll.setText("Repeat all");
repAll.setTextColor(Color.WHITE);
repAll.getBackground().setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.MULTIPLY);
params = new RelativeLayout.LayoutParams((int)(0.90*scrWidth), (int)(0.1*scrHeight));
params.leftMargin = (int)(0.05*scrWidth);
params.topMargin = (int)(0.5*scrHeight) + (int)(0.1*scrHeight) + (int)(0.1*scrHeight) + (int)(0.1*scrHeight);
lyt.addView(repAll, params);
repAll.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
restartAll();
}
});
}
public void restartAll(){
wrongGuessed.clear();
if(queryLand){
wrongGuessed = (ArrayList)set.clone();
} else {
for(Card c : set){
if(!c.getType().contains("Land")){
wrongGuessed.add(c);
}
}
}
shuffleWrongs();
buildMenu();
indexCard = 0;
showFirstPic();
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id){
case android.R.id.home:
onBackPressed();
break;
case R.id.restart_all:
restartAll();
break;
case R.id.query_lands:
queryLand = !queryLand;
item.setChecked(queryLand);
restartAll();
break;
}
return true;
}
public void onBackPressed(){
finish();
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);
}
}
| Magic2Brain/app/src/main/java/m2b/magic2brain/com/QueryActivity.java | package m2b.magic2brain.com;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.picasso.Picasso;
import org.w3c.dom.Text;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import m2b.magic2brain.com.magic2brain.R;
//TODO: Add alternative query-mode (All vs. Sets of eg. 7)
public class QueryActivity extends AppCompatActivity {
private ImageView imgv; // The image of the card gets stored here
private ImageView imgCorr; // Is over the image. It's to indicate if the answer was correct or not
private Toolbar hiding; // This is a bar that hides a certain area
private ArrayList<Card> set; //This Arraylist holds all Cards that need to query. It won't be edited (after loading it)
private ArrayList<Card> wrongGuessed;
private int indexCard; // Actually not needed (because we remove cards from WrongGuessed) but may be useful in later edits
private boolean firstGuess; //This is to check if he guessed it at first try. If so we remove the card from the Arraylist. Else it stays there.
private String deckName; //Name of the deck. Only for saving/loading purpose
private TextView score; //this will show the user the current progress
private boolean queryLand = true; // should we really query lands?
private boolean skipped = false; // this is to store if the user has skipped or not
private ArrayList<String> recentlyLearned; // this is to save the deckname if a new set is learned
protected void onCreate(Bundle savedInstanceState) {
// Build UI
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_query);
hiding = (Toolbar) findViewById(R.id.toolbar_query);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
buildMenu();
// Hide the status bar.
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
// Prepare Query
Intent i = getIntent();
Deck qur = (Deck) i.getSerializableExtra("Set");
deckName = qur.getName();
String code = qur.getCode();
if(deckName == null){deckName="DEFAULT";}
setTitle(deckName);
if(!loadRecent()){recentlyLearned = new ArrayList<>();}
if(recentlyLearned.size() == 2){recentlyLearned.remove(0);}
saveRecent();
set = qur.getSet();
if(!loadProgress()) { //First we try to load the progress. If this fails, we simply start over
wrongGuessed = (ArrayList) set.clone(); //Lets assume he guessed everything wrong and remove the card of this Array when he guesses it right
shuffleWrongs(); //Shuffle it a bit (better learn-effect)
indexCard = 0;
}
showFirstPic(); //Start the query
if(deckName.contains("DEFAULT")){restartAll();}
}
protected void onPause(){
super.onPause();
saveProgress();
}
public boolean loadRecent(){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Gson gson = new Gson();
String json = sharedPrefs.getString("query_recent",null);
Type type = new TypeToken<ArrayList<String>>(){}.getType();
ArrayList<String> aL = gson.fromJson(json, type);
if(aL == null){return false;}
recentlyLearned = aL;
return true;
}
public void saveRecent(){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(recentlyLearned);
editor.putString("query_recent", json);
editor.commit();
}
public boolean loadProgress(){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Gson gson = new Gson();
String json = sharedPrefs.getString("query_list_"+deckName,null);
Type type = new TypeToken<ArrayList<Card>>(){}.getType();
ArrayList<Card> aL = gson.fromJson(json, type);
int loadedIndex = sharedPrefs.getInt("query_index_"+deckName,-1);
if(aL == null){return false;}
wrongGuessed = aL;
indexCard = loadedIndex;
return true;
}
public void saveProgress(){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(wrongGuessed);
editor.putString("query_list_"+deckName, json);
editor.putInt("query_index_"+deckName,indexCard);
editor.commit();
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.query, menu);
return true;
}
public void shuffleWrongs(){
Collections.shuffle(wrongGuessed, new Random(System.nanoTime()));
}
public void showPic(int MultiID){
Picasso.with(this)
.load("http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=" + MultiID + "&type=card")
.placeholder(R.drawable.loading_image)
.error(R.drawable.image_not_found)
.into(imgv);
}
public void showFirstPic(){
updateScore();
showHiderInstant();
firstGuess = true;
showPic(wrongGuessed.get(indexCard).getMultiverseid());
hiding.bringToFront();
}
public void showNextPic(){
updateScore();
skipped = false;
showHider();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
firstGuess = true;
showPic(wrongGuessed.get(indexCard).getMultiverseid());
hiding.bringToFront();
}
}, 800);
}
public void checkAnswer(String txt){ //TODO: Optional: Ask other things (like Mana-Cost etc.)
if(txt.replaceAll("\\s+","").equalsIgnoreCase(wrongGuessed.get(indexCard).getName().replaceAll("\\s+",""))) {
if(firstGuess){wrongGuessed.remove(indexCard);} //if he guessed it, we remove it.
else {indexCard++;} // else we continue with the next card
if(indexCard == wrongGuessed.size()){ //If this true he's through the set
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
setDone();
}
}, 1000);
} else {
if(!skipped){
imgCorr.setImageResource(R.drawable.correct_answer);
showImgCorr();
}
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if(!skipped){hideImgCorr();}
showNextPic();
}
}, 1000);
}
} else {
wrongAnswer();
}
}
public void skip(){
skipped = true;
wrongAnswer();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
checkAnswer(wrongGuessed.get(indexCard).getName());
}
}, 1000);
}
public void wrongAnswer(){
firstGuess = false;
imgCorr.setImageResource(R.drawable.wrong_answer);
showImgCorr();
hideHider();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
hideImgCorr();
}
}, 1000);
}
public void setDone(){
buildEndScreen();
shuffleWrongs();
}
public void hideHider(){ // Shows the name of the card fadingly
hiding.animate().alpha(0).setDuration(1000).setInterpolator(new DecelerateInterpolator()).withEndAction(new Runnable() {
public void run() {hiding.animate().alpha(0).setDuration(1000).setInterpolator(new AccelerateInterpolator()).start();}}).start();
}
public void showHider(){ // Hides the name of the card fadingly
hiding.animate().alpha(1).setDuration(1000).setInterpolator(new DecelerateInterpolator()).withEndAction(new Runnable() {
public void run() {hiding.animate().alpha(1).setDuration(100).setInterpolator(new AccelerateInterpolator()).start();}}).start();
}
public void showHiderInstant(){ // Hides the name of the card instantly
hiding.animate().alpha(1).setDuration(10).setInterpolator(new DecelerateInterpolator()).withEndAction(new Runnable() {
public void run() {hiding.animate().alpha(1).setDuration(100).setInterpolator(new AccelerateInterpolator()).start();}}).start();
}
public void hideImgCorr(){
Animation myFadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fadeout);
imgCorr.startAnimation(myFadeInAnimation); //Set animation to your ImageView
}
public void showImgCorr(){
Animation myFadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fadein);
imgCorr.startAnimation(myFadeInAnimation); //Set animation to your ImageView
}
public void buildMenu(){
int scrWidth = getWindowManager().getDefaultDisplay().getWidth();
int scrHeight = getWindowManager().getDefaultDisplay().getHeight();
RelativeLayout lyt = (RelativeLayout) findViewById(R.id.query_absolute); // Get the View of the XML
lyt.removeAllViews(); //Clear the Board
RelativeLayout.LayoutParams params;
params = new RelativeLayout.LayoutParams((int)(0.55*scrWidth),(int)(0.03*scrHeight));
params.leftMargin = (scrWidth/2 - (int)(0.55*scrWidth)/2); // X-Position
params.topMargin = (int)(0.07*scrHeight); // Y-Position
lyt.addView(hiding,params);
imgv = new ImageView(this); // Create new Imageview
params = new RelativeLayout.LayoutParams(scrWidth /*Width*/, (int)(0.5*scrHeight))/*Height*/;
params.leftMargin = 0; // X-Position
params.topMargin = (int)(0.05*scrHeight); // Y-Position
lyt.addView(imgv, params); // add it to the View
imgCorr = new ImageView(this); // Create new Imageview
hideImgCorr();
params = new RelativeLayout.LayoutParams(scrWidth /*Width*/, (int)(0.5*scrHeight))/*Height*/;
params.leftMargin = 0; // X-Position
params.topMargin = (int)(0.05*scrHeight); // Y-Position
lyt.addView(imgCorr, params); // add it to the View
// Add EditText like Imageview
final EditText inputtxt = new EditText(this);
inputtxt.setGravity(Gravity.CENTER);
inputtxt.setHint("What is the name of this card?");
params = new RelativeLayout.LayoutParams((int)(0.75*scrWidth), (int)(0.1*scrHeight));
params.leftMargin = (int)(0.125*scrWidth);
params.topMargin = (int)(0.55*scrHeight);
lyt.addView(inputtxt, params);
// Add a Listener to it (so the User can simply press ENTER on the keyboard)
inputtxt.setOnKeyListener(new View.OnKeyListener(){
public boolean onKey(View v, int keyCode, KeyEvent event){
if (event.getAction() == KeyEvent.ACTION_DOWN){
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
checkAnswer(inputtxt.getText().toString());
inputtxt.setText("");
return true;
default:
break;
}
}
return false;
}
});
Button answer = new Button(this);
answer.setText("Answer");
answer.setTextColor(Color.WHITE);
answer.getBackground().setColorFilter(getResources().getColor(R.color.colorAccent), PorterDuff.Mode.MULTIPLY);
params = new RelativeLayout.LayoutParams((int)(0.25*scrWidth), (int)(0.1*scrHeight));
params.leftMargin = (scrWidth/2)-(int)(0.25*scrWidth);
params.topMargin = (int)(0.50*scrHeight)+(int)(0.15*scrHeight);
lyt.addView(answer, params);
answer.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
checkAnswer(inputtxt.getText().toString());
inputtxt.setText("");
}
});
Button skip = new Button(this);
skip.setText("Skip");
skip.setTextColor(Color.WHITE);
skip.getBackground().setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.MULTIPLY);
params = new RelativeLayout.LayoutParams((int)(0.25*scrWidth), (int)(0.1*scrHeight));
params.leftMargin = (scrWidth/2);
params.topMargin = (int)(0.50*scrHeight)+(int)(0.15*scrHeight);
lyt.addView(skip, params);
skip.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {skip();}
});
score = new TextView(this); // Create new Textview
score.setGravity(Gravity.CENTER);
score.setTextSize(36);
params = new RelativeLayout.LayoutParams(scrWidth /*Width*/, (int)(0.1*scrHeight))/*Height*/;
params.leftMargin = 0; // X-Position
params.topMargin = (int)(0.78*scrHeight); // Y-Position
lyt.addView(score, params); // add it to the View
}
public void updateScore(){
score.setText( (set.size()-wrongGuessed.size()) + " / " + indexCard +" / " + (wrongGuessed.size()-indexCard));
}
public void buildEndScreen(){
int scrWidth = getWindowManager().getDefaultDisplay().getWidth();
int scrHeight = getWindowManager().getDefaultDisplay().getHeight();
RelativeLayout lyt = (RelativeLayout) findViewById(R.id.query_absolute); // Get the View of the XML
lyt.removeAllViews(); //Clear the board
RelativeLayout.LayoutParams params;
TextView rights = new TextView(this);
rights.setText("Right: ");
rights.setTextSize(36);
rights.setTextColor(getResources().getColor(R.color.colorPrimary));
params = new RelativeLayout.LayoutParams(scrWidth /*Width*/, (int)(0.1*scrHeight))/*Height*/;
params.leftMargin = (int)(0.1*scrHeight); // X-Position
params.topMargin = (int)(0.05*scrHeight); // Y-Position
lyt.addView(rights, params); // add it to the View
TextView rights2 = new TextView(this);
rights2.setText(""+(set.size() - wrongGuessed.size()));
rights2.setTextSize(36);
rights2.setTextColor(getResources().getColor(R.color.colorPrimary));
params = new RelativeLayout.LayoutParams(scrWidth /*Width*/, (int)(0.1*scrHeight))/*Height*/;
params.leftMargin = (int)(0.4*scrHeight); // X-Position
params.topMargin = (int)(0.05*scrHeight); // Y-Position
lyt.addView(rights2, params); // add it to the View
TextView wrongs = new TextView(this);
wrongs.setText("Wrong: ");
wrongs.setTextSize(36);
wrongs.setTextColor(getResources().getColor(R.color.colorAccent));
params = new RelativeLayout.LayoutParams(scrWidth /*Width*/, (int)(0.1*scrHeight))/*Height*/;
params.leftMargin = (int)(0.1*scrHeight); // X-Position
params.topMargin = (int)(0.05*scrHeight) + (int)(0.1*scrHeight); // Y-Position
lyt.addView(wrongs, params); // add it to the View
TextView wrongs2 = new TextView(this);
wrongs2.setText("" + (wrongGuessed.size()));
wrongs2.setTextSize(36);
wrongs2.setTextColor(getResources().getColor(R.color.colorAccent));
params = new RelativeLayout.LayoutParams(scrWidth /*Width*/, (int)(0.1*scrHeight))/*Height*/;
params.leftMargin = (int)(0.4*scrHeight); // X-Position
params.topMargin = (int)(0.05*scrHeight) + (int)(0.1*scrHeight); // Y-Position
lyt.addView(wrongs2, params); // add it to the View
TextView total = new TextView(this);
total.setText("Total: ");
total.setTextSize(36);
total.setTextColor(Color.BLACK);
params = new RelativeLayout.LayoutParams(scrWidth /*Width*/, (int)(0.09*scrHeight))/*Height*/;
params.leftMargin = (int)(0.1*scrHeight); // X-Position
params.topMargin = (int)(0.05*scrHeight) + (int)(0.1*scrHeight) + (int)(0.1*scrHeight); // Y-Position
lyt.addView(total, params); // add it to the View
TextView total2 = new TextView(this);
total2.setText("" + (set.size()));
total2.setTextSize(36);
total2.setTextColor(Color.BLACK);
params = new RelativeLayout.LayoutParams(scrWidth /*Width*/, (int)(0.09*scrHeight))/*Height*/;
params.leftMargin = (int)(0.4*scrHeight); // X-Position
params.topMargin = (int)(0.05*scrHeight) + (int)(0.1*scrHeight) + (int)(0.1*scrHeight); // Y-Position
lyt.addView(total2, params); // add it to the View
if(wrongGuessed.size() > 0) {
Button repWrong = new Button(this);
repWrong.setText("Repeat wrong guessed");
repWrong.setTextColor(Color.WHITE);
repWrong.getBackground().setColorFilter(getResources().getColor(R.color.colorAccent), PorterDuff.Mode.MULTIPLY);
params = new RelativeLayout.LayoutParams((int) (0.90 * scrWidth), (int) (0.1 * scrHeight));
params.leftMargin = (int) (0.05 * scrWidth);
params.topMargin = (int) (0.4 * scrHeight) + (int) (0.1 * scrHeight) + (int) (0.1 * scrHeight) + (int) (0.1 * scrHeight);
lyt.addView(repWrong, params);
repWrong.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
buildMenu();
indexCard = 0;
showFirstPic();
}
});
}
Button repAll = new Button(this);
repAll.setText("Repeat all");
repAll.setTextColor(Color.WHITE);
repAll.getBackground().setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.MULTIPLY);
params = new RelativeLayout.LayoutParams((int)(0.90*scrWidth), (int)(0.1*scrHeight));
params.leftMargin = (int)(0.05*scrWidth);
params.topMargin = (int)(0.5*scrHeight) + (int)(0.1*scrHeight) + (int)(0.1*scrHeight) + (int)(0.1*scrHeight);
lyt.addView(repAll, params);
repAll.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
restartAll();
}
});
}
public void restartAll(){
wrongGuessed.clear();
if(queryLand){
wrongGuessed = (ArrayList)set.clone();
} else {
for(Card c : set){
if(!c.getType().contains("Land")){
wrongGuessed.add(c);
}
}
}
shuffleWrongs();
buildMenu();
indexCard = 0;
showFirstPic();
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id){
case android.R.id.home:
onBackPressed();
break;
case R.id.restart_all:
restartAll();
break;
case R.id.query_lands:
queryLand = !queryLand;
item.setChecked(queryLand);
restartAll();
break;
}
return true;
}
public void onBackPressed(){
finish();
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);
}
}
| small change
| Magic2Brain/app/src/main/java/m2b/magic2brain/com/QueryActivity.java | small change | <ide><path>agic2Brain/app/src/main/java/m2b/magic2brain/com/QueryActivity.java
<ide> if(deckName == null){deckName="DEFAULT";}
<ide> setTitle(deckName);
<ide> if(!loadRecent()){recentlyLearned = new ArrayList<>();}
<add> if(!recentlyLearned.contains(code)){recentlyLearned.add(code);} //TODO: CODE DOESNT WORK. DECKNAME DOES. WHY THE FUCK?
<ide> if(recentlyLearned.size() == 2){recentlyLearned.remove(0);}
<ide> saveRecent();
<ide> set = qur.getSet(); |
|
Java | apache-2.0 | 3fe2fac6f5153af91a732e1a19b665b2a95a0b13 | 0 | fengshao0907/wasp,fengshao0907/wasp,fengshao0907/wasp,alibaba/wasp,alibaba/wasp,fengshao0907/wasp,alibaba/wasp,fengshao0907/wasp,alibaba/wasp | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.wasp.meta;
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.expr.SQLBinaryOperator;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Pair;
import com.alibaba.wasp.DataType;
import com.alibaba.wasp.FConstants;
import com.alibaba.wasp.MetaException;
import com.alibaba.wasp.plan.action.ColumnStruct;
import com.alibaba.wasp.plan.action.InsertAction;
import com.alibaba.wasp.plan.action.UpdateAction;
import com.alibaba.wasp.plan.parser.Condition;
import com.alibaba.wasp.plan.parser.QueryInfo;
import com.alibaba.wasp.plan.parser.UnsupportedException;
import com.alibaba.wasp.plan.parser.druid.DruidParser;
import com.alibaba.wasp.util.ParserUtils;
import com.alibaba.wasp.util.Utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.NavigableMap;
import java.util.Set;
public class RowBuilder {
private final static RowBuilder instance = new RowBuilder();
private RowBuilder() {
}
/** single **/
public static RowBuilder build() {
return instance;
}
/**
* Build start key and end key by queryInfo.
*
* @param index
* @param queryInfo
* @return
* @throws UnsupportedException
*/
public Pair<byte[], byte[]> buildStartkeyAndEndkey(Index index,
QueryInfo queryInfo) throws UnsupportedException {
List<IndexField> indexFields = new ArrayList<IndexField>();
Condition range = queryInfo.getRangeCondition();
for (Field field : index.getIndexKeys().values()) {
if (range == null || !field.getName().equals(range.getFieldName())) {
LinkedHashMap<String, Condition> eqConditions = queryInfo
.getEqConditions();
Condition entry = ParserUtils.getCondition(field.getName(),
eqConditions);
addToIndexFields(DruidParser.convert(field, entry.getValue()),
indexFields, field);
}
}
byte[] prefixKey = genRowkey(index, indexFields).getFirst();
if (range == null) {// no range condition
return buildStartEndKeyWithoutRange(prefixKey);
} else {// has range condition
return buildStartEndKeyWithRange(prefixKey, range, index);
}
}
private Pair<byte[], byte[]> buildStartEndKeyWithRange(byte[] prefixKey,
Condition rangeCondition, Index index) throws UnsupportedException {
Pair<byte[], byte[]> pair = new Pair<byte[], byte[]>();
boolean isDesc = index.isDesc(rangeCondition.getFieldName());
SQLExpr left = rangeCondition.getLeft();
SQLExpr right = rangeCondition.getRight();
byte[] prefixKeyWithRowSep = prefixKey.length == 0 ? prefixKey : Bytes.add(
prefixKey, FConstants.DATA_ROW_SEP_STORE);
try {
if (left != null) {
pair.setFirst(Bytes.add(prefixKeyWithRowSep,
parseByte(index, isDesc, left, rangeCondition.getFieldName(), rangeCondition.getLeftOperator())));
} else {
pair.setFirst(Bytes.add(prefixKey, FConstants.DATA_ROW_SEP_STORE));
}
if (right != null) {
pair.setSecond(Bytes.add(prefixKeyWithRowSep,
parseByte(index, isDesc, right, rangeCondition.getFieldName(), rangeCondition.getRightOperator())));
} else {
pair.setSecond(prefixKey.length == 0 ? HConstants.EMPTY_END_ROW : Bytes.add(prefixKey, FConstants.DATA_ROW_SEP_QUERY));
}
} catch (ParseException e) {
throw new UnsupportedException(e.getMessage(), e);
}
// if desc the startkey and stop key will be swap
if (isDesc) {
return Pair.newPair(pair.getSecond(), pair.getFirst());
}
return pair;
}
private byte[] parseByte(Index index, boolean isDesc, SQLExpr range,
String fieldName, SQLBinaryOperator operator) throws UnsupportedException, ParseException {
LinkedHashMap<String, Field> indexs = index.getIndexKeys();
Field field = indexs.get(fieldName);
byte[] value = null;
if (field.getType() == DataType.DATETIME) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long time = formatter.parse(DruidParser.parseString(range)).getTime();
if (isDesc) {
time = descLong(time);
}
value = Bytes.toBytes(time);
} else {
value = DruidParser.convert(field, range);
}
value = parseValueIfNegative(value, field);
if(operator == SQLBinaryOperator.LessThanOrEqual || operator == SQLBinaryOperator.GreaterThan) {
return Bytes.add(value, FConstants.DATA_ROW_SEP_QUERY);
} else {
return value;
}
}
private byte[] parseValueIfNegative(byte[] value, Field field) {
DataType type = field.getType();
if (type == DataType.INT32) {
int val = Bytes.toInt(value);
return addBytesPrefix(value, val < 0);
} else if (type == DataType.INT64) {
long val = Bytes.toLong(value);
return addBytesPrefix(value, val < 0);
} else if (type == DataType.DOUBLE ) {
double val = Bytes.toDouble(value);
return addBytesPrefix(value, val < 0);
} else if (type == DataType.FLOAT) {
float val = Bytes.toFloat(value);
return addBytesPrefix(value, val < 0);
}
return value;
}
private byte[] addBytesPrefix(byte[] value, boolean isNegative) {
return Bytes.add(isNegative ? FConstants.NUM_VALUE_NEGATIVE : FConstants.NUM_VALUE_POSITIVE, value);
}
private Pair<byte[], byte[]> buildStartEndKeyWithoutRange(byte[] prefixKey) {
return new Pair<byte[], byte[]>(Bytes.add(prefixKey,
FConstants.DATA_ROW_SEP_STORE), Bytes.add(prefixKey,
FConstants.DATA_ROW_SEP_QUERY));
}
/**
*
* Build a entity row key by sorted primary key conditions.
*
* @param primaryKeyPairs
* @return
* @throws UnsupportedException
*/
public byte[] genRowkey(List<Pair<String, byte[]>> primaryKeyPairs)
throws UnsupportedException {
byte[] rowKey = new byte[0];
Iterator<Pair<String, byte[]>> iter = primaryKeyPairs.iterator();
boolean first = true;
while (iter.hasNext()) {
Pair<String, byte[]> pair = iter.next();
if (first) {
rowKey = Bytes.add(rowKey, pair.getSecond());
first = false;
} else {
rowKey = Bytes.add(rowKey, FConstants.DATA_ROW_SEP_STORE,
pair.getSecond());
}
}
return rowKey;
}
/**
* Build a row key by using one index schema.
*
* @param index
* @param indexFields
* @return
*/
private Pair<byte[], String> genRowkey(Index index,
List<IndexField> indexFields) {
byte[] rowKey = new byte[0];
boolean first = true;
for (IndexField indexField : indexFields) {
if (indexField.getValue() == null) {
return null;
}
if (index.isDesc(indexField.getName())) {// is desc?
indexField.setValue(descLong(indexField.getValue()));
}
Field field = index.getIndexKeys().get(indexField.getName());
if (first) {
rowKey = Bytes.add(rowKey, parseValueIfNegative(indexField.getValue(), field));
first = false;
} else {
rowKey = Bytes.add(rowKey, FConstants.DATA_ROW_SEP_STORE,
parseValueIfNegative(indexField.getValue(), field));
}
}
return new Pair<byte[], String>(rowKey,
StorageTableNameBuilder.buildIndexTableName(index));
}
public byte[] descLong(byte[] value) {
return Bytes.toBytes(descLong(Bytes.toLong(value)));
}
public long descLong(long value) {
return Long.MAX_VALUE - value;
}
/**
* Convert values to index key/value.
*
* @param index
* @param result
* @return
*/
public Pair<byte[], String> buildIndexKey(Index index,
NavigableMap<byte[], NavigableMap<byte[], byte[]>> result,
byte[] primaryKey) {
List<IndexField> indexFieldLists = getIndexFields(index, result);
Pair<byte[], String> pair = genRowkey(index, indexFieldLists);
if (pair == null) {
return null;
}
pair.setFirst(Bytes.add(pair.getFirst(), FConstants.DATA_ROW_SEP_STORE,
primaryKey));
return pair;
}
/**
* Build a variety of indexes.
*
* @param index
* @param values
* @return
*/
public static List<IndexField> getIndexFields(Index index,
NavigableMap<byte[], NavigableMap<byte[], byte[]>> values) {
List<IndexField> indexFields = new ArrayList<IndexField>();
for (Field field : index.getIndexKeys().values()) {
addToIndexFields(values, indexFields, field);
}
return indexFields;
}
/**
* @param values
* @param indexFields
* @param field
*/
private static void addToIndexFields(
NavigableMap<byte[], NavigableMap<byte[], byte[]>> values,
List<IndexField> indexFields, Field field) {
String name = field.getName();
byte[] value = getValue(values, field.getFamily(), name);
IndexField indexField = new IndexField(field.getFamily(), name, value,
isNumericDataType(field));
indexFields.add(indexField);
}
/**
* Tool method.
*
* @param value
* @param indexFields
* @param field
*/
private void addToIndexFields(byte[] value, List<IndexField> indexFields,
Field field) {
IndexField indexField = new IndexField(field.getFamily(), field.getName(),
value, isNumericDataType(field));
indexFields.add(indexField);
}
/**
* Return current family:column value.
*
* @param results
* @param family
* @param name
* @return current family:column value
*/
private static byte[] getValue(
NavigableMap<byte[], NavigableMap<byte[], byte[]>> results,
String family, String name) {
if (results == null) {
return null;
}
NavigableMap<byte[], byte[]> values = results.get(Bytes.toBytes(family));
if (values == null) {
return null;
}
return values.get(Bytes.toBytes(name));
}
/**
* Return true which is INT32 or INT64 or FLOAT or DOUBLE.
*
* @param indexField
* @return
*/
static boolean isNumericDataType(Field indexField) {
return indexField.getType() == DataType.INT32
|| indexField.getType() == DataType.INT64
|| indexField.getType() == DataType.FLOAT
|| indexField.getType() == DataType.DOUBLE;
}
/**
* Convert update action to put.
*
* @param action
* UpdateAction
* @return
* @throws MetaException
*/
public Put buildPut(UpdateAction action) throws MetaException {
return buildPut(
this.buildEntityRowKey(action.getConf(), action.getFTableName(),
action.getCombinedPrimaryKey()), action.getColumns());
}
/**
* Convert insert action to put.
*
* @param action
* InsertAction
* @return
* @throws MetaException
*/
public Put buildPut(InsertAction action) throws MetaException {
return buildPut(
this.buildEntityRowKey(action.getConf(), action.getFTableName(),
action.getCombinedPrimaryKey()), action.getColumns());
}
private Put buildPut(byte[] primayKey, List<ColumnStruct> cols) {
Put put = new Put(primayKey);
for (ColumnStruct actionColumn : cols) {
put.add(Bytes.toBytes(actionColumn.getFamilyName()),
Bytes.toBytes(actionColumn.getColumnName()), actionColumn.getValue());
}
return put;
}
public static Set<String> buildFamilyName(FTable ftable) {
HashSet<String> hs = new HashSet<String>();
for (Field field : ftable.getColumns().values()) {
hs.add(field.getFamily());
}
hs.add(FConstants.COLUMNFAMILYNAME_STR);
return hs;
}
/**
* Return entity row key.
*
* @param tableName
* @param primaryKey
* @return
*/
public byte[] buildEntityRowKey(Configuration conf, String tableName,
byte[] primaryKey) throws MetaException {
TableSchemaCacheReader reader = TableSchemaCacheReader.getInstance(conf);
FTable tableDescriptor = reader.getSchema(tableName);
if (tableDescriptor.isChildTable()) {
String parentName = tableDescriptor.getParentName();
return Bytes.add(
Bytes.toBytes(parentName + FConstants.TABLE_ROW_SEP + tableName
+ FConstants.TABLE_ROW_SEP), primaryKey);
} else {
return Bytes.add(Bytes.toBytes(tableName + FConstants.TABLE_ROW_SEP),
primaryKey);
}
}
/**
* Convert index key to entity row key.
*
* @param result
* @return
*/
public byte[] buildEntityRowKey(Result result) {
return result.getValue(FConstants.INDEX_STORING_FAMILY_BYTES,
FConstants.INDEX_STORE_ROW_QUALIFIER);
}
} | src/main/java/com/alibaba/wasp/meta/RowBuilder.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.wasp.meta;
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.expr.SQLBinaryOperator;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Pair;
import com.alibaba.wasp.DataType;
import com.alibaba.wasp.FConstants;
import com.alibaba.wasp.MetaException;
import com.alibaba.wasp.plan.action.ColumnStruct;
import com.alibaba.wasp.plan.action.InsertAction;
import com.alibaba.wasp.plan.action.UpdateAction;
import com.alibaba.wasp.plan.parser.Condition;
import com.alibaba.wasp.plan.parser.QueryInfo;
import com.alibaba.wasp.plan.parser.UnsupportedException;
import com.alibaba.wasp.plan.parser.druid.DruidParser;
import com.alibaba.wasp.util.ParserUtils;
import com.alibaba.wasp.util.Utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.NavigableMap;
import java.util.Set;
public class RowBuilder {
private final static RowBuilder instance = new RowBuilder();
private RowBuilder() {
}
/** single **/
public static RowBuilder build() {
return instance;
}
/**
* Build start key and end key by queryInfo.
*
* @param index
* @param queryInfo
* @return
* @throws UnsupportedException
*/
public Pair<byte[], byte[]> buildStartkeyAndEndkey(Index index,
QueryInfo queryInfo) throws UnsupportedException {
List<IndexField> indexFields = new ArrayList<IndexField>();
Condition range = queryInfo.getRangeCondition();
for (Field field : index.getIndexKeys().values()) {
if (range == null || !field.getName().equals(range.getFieldName())) {
LinkedHashMap<String, Condition> eqConditions = queryInfo
.getEqConditions();
Condition entry = ParserUtils.getCondition(field.getName(),
eqConditions);
addToIndexFields(DruidParser.convert(field, entry.getValue()),
indexFields, field);
}
}
byte[] prefixKey = genRowkey(index, indexFields).getFirst();
if (range == null) {// no range condition
return buildStartEndKeyWithoutRange(prefixKey);
} else {// has range condition
return buildStartEndKeyWithRange(prefixKey, range, index);
}
}
private Pair<byte[], byte[]> buildStartEndKeyWithRange(byte[] prefixKey,
Condition rangeCondition, Index index) throws UnsupportedException {
Pair<byte[], byte[]> pair = new Pair<byte[], byte[]>();
boolean isDesc = index.isDesc(rangeCondition.getFieldName());
SQLExpr left = rangeCondition.getLeft();
SQLExpr right = rangeCondition.getRight();
byte[] prefixKeyWithRowSep = prefixKey.length == 0 ? prefixKey : Bytes.add(
prefixKey, FConstants.DATA_ROW_SEP_STORE);
try {
if (left != null) {
pair.setFirst(Bytes.add(prefixKeyWithRowSep,
parseByte(index, isDesc, left, rangeCondition.getFieldName(), rangeCondition.getLeftOperator())));
} else {
pair.setFirst(Bytes.add(prefixKey, FConstants.DATA_ROW_SEP_STORE));
}
if (right != null) {
pair.setSecond(Bytes.add(prefixKeyWithRowSep,
parseByte(index, isDesc, right, rangeCondition.getFieldName(), rangeCondition.getRightOperator())));
} else {
pair.setSecond(Bytes.add(prefixKey, FConstants.DATA_ROW_SEP_QUERY));
}
} catch (ParseException e) {
throw new UnsupportedException(e.getMessage(), e);
}
// if desc the startkey and stop key will be swap
if (isDesc) {
return Pair.newPair(pair.getSecond(), pair.getFirst());
}
return pair;
}
private byte[] parseByte(Index index, boolean isDesc, SQLExpr range,
String fieldName, SQLBinaryOperator operator) throws UnsupportedException, ParseException {
LinkedHashMap<String, Field> indexs = index.getIndexKeys();
Field field = indexs.get(fieldName);
byte[] value = null;
if (field.getType() == DataType.DATETIME) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long time = formatter.parse(DruidParser.parseString(range)).getTime();
if (isDesc) {
time = descLong(time);
}
value = Bytes.toBytes(time);
} else {
value = DruidParser.convert(field, range);
}
value = parseValueIfNegative(value, field);
if(operator == SQLBinaryOperator.LessThanOrEqual || operator == SQLBinaryOperator.GreaterThan) {
return Bytes.add(value, FConstants.DATA_ROW_SEP_QUERY);
} else {
return value;
}
}
private byte[] parseValueIfNegative(byte[] value, Field field) {
DataType type = field.getType();
if (type == DataType.INT32) {
int val = Bytes.toInt(value);
return addBytesPrefix(value, val < 0);
} else if (type == DataType.INT64) {
long val = Bytes.toLong(value);
return addBytesPrefix(value, val < 0);
} else if (type == DataType.DOUBLE ) {
double val = Bytes.toDouble(value);
return addBytesPrefix(value, val < 0);
} else if (type == DataType.FLOAT) {
float val = Bytes.toFloat(value);
return addBytesPrefix(value, val < 0);
}
return value;
}
private byte[] addBytesPrefix(byte[] value, boolean isNegative) {
return Bytes.add(isNegative ? FConstants.NUM_VALUE_NEGATIVE : FConstants.NUM_VALUE_POSITIVE, value);
}
private Pair<byte[], byte[]> buildStartEndKeyWithoutRange(byte[] prefixKey) {
return new Pair<byte[], byte[]>(Bytes.add(prefixKey,
FConstants.DATA_ROW_SEP_STORE), Bytes.add(prefixKey,
FConstants.DATA_ROW_SEP_QUERY));
}
/**
*
* Build a entity row key by sorted primary key conditions.
*
* @param primaryKeyPairs
* @return
* @throws UnsupportedException
*/
public byte[] genRowkey(List<Pair<String, byte[]>> primaryKeyPairs)
throws UnsupportedException {
byte[] rowKey = new byte[0];
Iterator<Pair<String, byte[]>> iter = primaryKeyPairs.iterator();
boolean first = true;
while (iter.hasNext()) {
Pair<String, byte[]> pair = iter.next();
if (first) {
rowKey = Bytes.add(rowKey, pair.getSecond());
first = false;
} else {
rowKey = Bytes.add(rowKey, FConstants.DATA_ROW_SEP_STORE,
pair.getSecond());
}
}
return rowKey;
}
/**
* Build a row key by using one index schema.
*
* @param index
* @param indexFields
* @return
*/
private Pair<byte[], String> genRowkey(Index index,
List<IndexField> indexFields) {
byte[] rowKey = new byte[0];
boolean first = true;
for (IndexField indexField : indexFields) {
if (indexField.getValue() == null) {
return null;
}
if (index.isDesc(indexField.getName())) {// is desc?
indexField.setValue(descLong(indexField.getValue()));
}
Field field = index.getIndexKeys().get(indexField.getName());
if (first) {
rowKey = Bytes.add(rowKey, parseValueIfNegative(indexField.getValue(), field));
first = false;
} else {
rowKey = Bytes.add(rowKey, FConstants.DATA_ROW_SEP_STORE,
parseValueIfNegative(indexField.getValue(), field));
}
}
return new Pair<byte[], String>(rowKey,
StorageTableNameBuilder.buildIndexTableName(index));
}
public byte[] descLong(byte[] value) {
return Bytes.toBytes(descLong(Bytes.toLong(value)));
}
public long descLong(long value) {
return Long.MAX_VALUE - value;
}
/**
* Convert values to index key/value.
*
* @param index
* @param result
* @return
*/
public Pair<byte[], String> buildIndexKey(Index index,
NavigableMap<byte[], NavigableMap<byte[], byte[]>> result,
byte[] primaryKey) {
List<IndexField> indexFieldLists = getIndexFields(index, result);
Pair<byte[], String> pair = genRowkey(index, indexFieldLists);
if (pair == null) {
return null;
}
pair.setFirst(Bytes.add(pair.getFirst(), FConstants.DATA_ROW_SEP_STORE,
primaryKey));
return pair;
}
/**
* Build a variety of indexes.
*
* @param index
* @param values
* @return
*/
public static List<IndexField> getIndexFields(Index index,
NavigableMap<byte[], NavigableMap<byte[], byte[]>> values) {
List<IndexField> indexFields = new ArrayList<IndexField>();
for (Field field : index.getIndexKeys().values()) {
addToIndexFields(values, indexFields, field);
}
return indexFields;
}
/**
* @param values
* @param indexFields
* @param field
*/
private static void addToIndexFields(
NavigableMap<byte[], NavigableMap<byte[], byte[]>> values,
List<IndexField> indexFields, Field field) {
String name = field.getName();
byte[] value = getValue(values, field.getFamily(), name);
IndexField indexField = new IndexField(field.getFamily(), name, value,
isNumericDataType(field));
indexFields.add(indexField);
}
/**
* Tool method.
*
* @param value
* @param indexFields
* @param field
*/
private void addToIndexFields(byte[] value, List<IndexField> indexFields,
Field field) {
IndexField indexField = new IndexField(field.getFamily(), field.getName(),
value, isNumericDataType(field));
indexFields.add(indexField);
}
/**
* Return current family:column value.
*
* @param results
* @param family
* @param name
* @return current family:column value
*/
private static byte[] getValue(
NavigableMap<byte[], NavigableMap<byte[], byte[]>> results,
String family, String name) {
if (results == null) {
return null;
}
NavigableMap<byte[], byte[]> values = results.get(Bytes.toBytes(family));
if (values == null) {
return null;
}
return values.get(Bytes.toBytes(name));
}
/**
* Return true which is INT32 or INT64 or FLOAT or DOUBLE.
*
* @param indexField
* @return
*/
static boolean isNumericDataType(Field indexField) {
return indexField.getType() == DataType.INT32
|| indexField.getType() == DataType.INT64
|| indexField.getType() == DataType.FLOAT
|| indexField.getType() == DataType.DOUBLE;
}
/**
* Convert update action to put.
*
* @param action
* UpdateAction
* @return
* @throws MetaException
*/
public Put buildPut(UpdateAction action) throws MetaException {
return buildPut(
this.buildEntityRowKey(action.getConf(), action.getFTableName(),
action.getCombinedPrimaryKey()), action.getColumns());
}
/**
* Convert insert action to put.
*
* @param action
* InsertAction
* @return
* @throws MetaException
*/
public Put buildPut(InsertAction action) throws MetaException {
return buildPut(
this.buildEntityRowKey(action.getConf(), action.getFTableName(),
action.getCombinedPrimaryKey()), action.getColumns());
}
private Put buildPut(byte[] primayKey, List<ColumnStruct> cols) {
Put put = new Put(primayKey);
for (ColumnStruct actionColumn : cols) {
put.add(Bytes.toBytes(actionColumn.getFamilyName()),
Bytes.toBytes(actionColumn.getColumnName()), actionColumn.getValue());
}
return put;
}
public static Set<String> buildFamilyName(FTable ftable) {
HashSet<String> hs = new HashSet<String>();
for (Field field : ftable.getColumns().values()) {
hs.add(field.getFamily());
}
hs.add(FConstants.COLUMNFAMILYNAME_STR);
return hs;
}
/**
* Return entity row key.
*
* @param tableName
* @param primaryKey
* @return
*/
public byte[] buildEntityRowKey(Configuration conf, String tableName,
byte[] primaryKey) throws MetaException {
TableSchemaCacheReader reader = TableSchemaCacheReader.getInstance(conf);
FTable tableDescriptor = reader.getSchema(tableName);
if (tableDescriptor.isChildTable()) {
String parentName = tableDescriptor.getParentName();
return Bytes.add(
Bytes.toBytes(parentName + FConstants.TABLE_ROW_SEP + tableName
+ FConstants.TABLE_ROW_SEP), primaryKey);
} else {
return Bytes.add(Bytes.toBytes(tableName + FConstants.TABLE_ROW_SEP),
primaryKey);
}
}
/**
* Convert index key to entity row key.
*
* @param result
* @return
*/
public byte[] buildEntityRowKey(Result result) {
return result.getValue(FConstants.INDEX_STORING_FAMILY_BYTES,
FConstants.INDEX_STORE_ROW_QUALIFIER);
}
} | Fix [Issue-18]: condition with only one field, than greater than can't query any results
| src/main/java/com/alibaba/wasp/meta/RowBuilder.java | Fix [Issue-18]: condition with only one field, than greater than can't query any results | <ide><path>rc/main/java/com/alibaba/wasp/meta/RowBuilder.java
<ide> import com.alibaba.druid.sql.ast.SQLExpr;
<ide> import com.alibaba.druid.sql.ast.expr.SQLBinaryOperator;
<ide> import org.apache.hadoop.conf.Configuration;
<add>import org.apache.hadoop.hbase.HConstants;
<ide> import org.apache.hadoop.hbase.client.Put;
<ide> import org.apache.hadoop.hbase.client.Result;
<ide> import org.apache.hadoop.hbase.util.Bytes;
<ide> pair.setSecond(Bytes.add(prefixKeyWithRowSep,
<ide> parseByte(index, isDesc, right, rangeCondition.getFieldName(), rangeCondition.getRightOperator())));
<ide> } else {
<del> pair.setSecond(Bytes.add(prefixKey, FConstants.DATA_ROW_SEP_QUERY));
<add> pair.setSecond(prefixKey.length == 0 ? HConstants.EMPTY_END_ROW : Bytes.add(prefixKey, FConstants.DATA_ROW_SEP_QUERY));
<ide> }
<ide> } catch (ParseException e) {
<ide> throw new UnsupportedException(e.getMessage(), e); |
|
Java | mit | 09f009f576bf06a46fa1514c24b3f04ff0f5290d | 0 | jaredlll08/MCBot | package com.tterrag.k9.commands;
import java.io.StringWriter;
import java.security.AccessControlException;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.io.IOUtils;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.tterrag.k9.K9;
import com.tterrag.k9.commands.CommandQuote.Quote;
import com.tterrag.k9.commands.api.Command;
import com.tterrag.k9.commands.api.CommandBase;
import com.tterrag.k9.commands.api.CommandContext;
import com.tterrag.k9.commands.api.CommandException;
import com.tterrag.k9.commands.api.CommandRegistrar;
import com.tterrag.k9.trick.Trick;
import com.tterrag.k9.util.BakedMessage;
import com.tterrag.k9.util.NonNull;
import com.tterrag.k9.util.NullHelper;
import clojure.core.Vec;
import clojure.java.api.Clojure;
import clojure.lang.AFn;
import clojure.lang.IFn;
import clojure.lang.IPersistentMap;
import clojure.lang.PersistentArrayMap;
import clojure.lang.PersistentHashMap;
import clojure.lang.PersistentVector;
import clojure.lang.Var;
import lombok.SneakyThrows;
import lombok.val;
import lombok.extern.slf4j.Slf4j;
import sx.blah.discord.api.internal.json.objects.EmbedObject;
import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IGuild;
import sx.blah.discord.handle.obj.IMessage;
import sx.blah.discord.handle.obj.IRole;
import sx.blah.discord.handle.obj.IUser;
import sx.blah.discord.handle.obj.Permissions;
import sx.blah.discord.util.EmbedBuilder;
import sx.blah.discord.util.RequestBuffer;
@Command
@Slf4j
public class CommandClojure extends CommandBase {
private static class BindingBuilder {
private final Map<Object, Object> bindings = new HashMap<>();
public BindingBuilder bind(String name, Object val) {
this.bindings.put(Clojure.read(":" + name), val);
return this;
}
public IPersistentMap build() {
return PersistentHashMap.create(Maps.newHashMap(this.bindings));
}
}
private static final SentenceArgument ARG_EXPR = new SentenceArgument("expression", "The clojure expression to evaluate.", true);
private static final Class<?>[] BLACKLIST_CLASSES = {
Thread.class
};
// Blacklist accessing discord functions
private static final String[] BLACKLIST_PACKAGES = {
K9.class.getPackage().getName(),
"sx.blah.discord"
};
private final IFn sandbox;
@SneakyThrows
public CommandClojure() {
super("clj", false);
// Make sure to load in clojail
Clojure.var("clojure.core", "require").invoke(Clojure.read("[clojail core jvm testers]"));
// Convenience declarations of used functions
IFn read_string = Clojure.var("clojure.core", "read-string");
IFn sandboxfn = Clojure.var("clojail.core", "sandbox");
Var secure_tester = (Var) Clojure.var("clojail.testers", "secure-tester");
// Load these to add new blacklisted resources
IFn blacklist_objects = Clojure.var("clojail.testers", "blacklist-objects");
IFn blacklist_packages = Clojure.var("clojail.testers", "blacklist-packages");
// Create our tester with custom blacklist
Object tester = Clojure.var("clojure.core/conj").invoke(secure_tester.getRawRoot(),
blacklist_objects.invoke(PersistentVector.create((Object[]) BLACKLIST_CLASSES)),
blacklist_packages.invoke(PersistentVector.create((Object[]) BLACKLIST_PACKAGES)));
/* == Setting up Context == */
// Defining all the context vars and the functions to bind them for a given CommandContext
// A simple function that returns a map representing a user, given an IUser
BiFunction<IGuild, IUser, IPersistentMap> getBinding = (g, u) -> new BindingBuilder()
.bind("name", u.getName())
.bind("nick", u.getDisplayName(g))
.bind("id", u.getLongID())
.bind("presence", new BindingBuilder()
.bind("text", u.getPresence().getText().orElse(null))
.bind("activity", u.getPresence().getActivity().map(Object::toString).orElse(null))
.bind("status", u.getPresence().getStatus().toString())
.bind("streamurl", u.getPresence().getStreamingUrl().orElse(null))
.build())
.bind("bot", u.isBot())
.bind("roles",
PersistentVector.create(u.getRolesForGuild(g).stream()
.sorted(Comparator.comparing(IRole::getPosition).reversed())
.map(IRole::getLongID)
.toArray(Object[]::new)))
.bind("avatar", u.getAvatarURL())
.bind("joined", g.getJoinTimeForUser(u))
.build();
// Set up global context vars
// Create an easily accessible map for the sending user
addContextVar("author", ctx -> getBinding.apply(ctx.getGuild(), ctx.getAuthor()));
// Add a lookup function for looking up an arbitrary user in the guild
addContextVar("users", ctx -> new AFn() {
@Override
public Object invoke(Object id) {
IGuild guild = ctx.getGuild();
IUser ret = null;
if (guild != null) {
ret = guild.getUserByID(((Number)id).longValue());
}
if (ret == null) {
throw new IllegalArgumentException("Could not find user for ID");
}
return getBinding.apply(ctx.getGuild(), ret);
}
});
addContextVar("roles", ctx -> new AFn() {
@Override
public Object invoke(Object id) {
IGuild guild = ctx.getGuild();
IRole ret = null;
if (guild != null) {
ret = guild.getRoleByID(((Number)id).longValue());
}
if (ret == null) {
throw new IllegalArgumentException("Could not find role for ID");
}
return new BindingBuilder()
.bind("name", ret.getName())
.bind("color", PersistentVector.create(ret.getColor().getRed(), ret.getColor().getGreen(), ret.getColor().getBlue()))
.bind("id", ret.getLongID())
.build();
}
});
// Simple data bean representing the current channel
addContextVar("channel", ctx ->
new BindingBuilder()
.bind("name", ctx.getChannel().getName())
.bind("id", ctx.getChannel().getLongID())
.bind("topic", ctx.getChannel().isPrivate() ? null : ctx.getChannel().getTopic())
.build());
// Simple data bean representing the current guild
addContextVar("guild", ctx -> {
IGuild guild = ctx.getGuild();
return guild == null ? null :
new BindingBuilder()
.bind("name", guild.getName())
.bind("id", guild.getLongID())
.bind("owner", guild.getOwner().getLongID())
.bind("region", guild.getRegion().getName())
.bind("created", guild.getCreationDate())
.build();
});
// Add the current message ID
addContextVar("message", ctx -> ctx.getMessage().getLongID());
// Provide a lookup function for ID->message
addContextVar("messages", ctx -> new AFn() {
@Override
public Object invoke(Object arg1) {
IGuild guild = ctx.getGuild();
List<IChannel> channels;
if (guild == null) {
channels = Collections.singletonList(ctx.getChannel());
} else {
channels = guild.getChannels();
}
IMessage msg = channels.stream()
.filter(c -> c.getModifiedPermissions(K9.instance.getOurUser()).contains(Permissions.READ_MESSAGES))
.map(c -> c.getMessageByID(((Number)arg1).longValue()))
.filter(Objects::nonNull)
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("No message found"));
return new BindingBuilder()
.bind("content", msg.getContent())
.bind("fcontent", msg.getFormattedContent())
.bind("id", arg1)
.bind("author", msg.getAuthor().getLongID())
.bind("channel", msg.getChannel().getLongID())
.bind("timestamp", msg.getTimestamp())
.build();
}
});
// A function for looking up quotes, given an ID, or pass no arguments to return a vector of valid quote IDs
addContextVar("quotes", ctx -> {
CommandQuote cmd = (CommandQuote) CommandRegistrar.INSTANCE.findCommand(ctx.getGuild(), "quote");
return new AFn() {
@Override
public Object invoke() {
if (cmd == null) {
return null;
}
return PersistentVector.create(cmd.getData(ctx).keySet());
}
@Override
public Object invoke(Object arg1) {
if (cmd == null) {
return null;
}
Quote q = cmd.getData(ctx).get(((Number)arg1).intValue());
if (q == null) {
throw new IllegalArgumentException("No quote for ID " + arg1);
}
return new BindingBuilder()
.bind("quote", q.getQuote())
.bind("quotee", q.getQuotee())
.bind("owner", q.getOwner())
.bind("weight", q.getWeight())
.bind("id", arg1)
.build();
}
};
});
// A function for looking up tricks, given a name. Optionally pass "true" as second param to force global lookup
addContextVar("tricks", ctx -> new AFn() {
@Override
public Object invoke(Object name) {
return invoke(name, false);
}
@Override
public Object invoke(Object name, Object global) {
CommandTrick cmd = (CommandTrick) CommandRegistrar.INSTANCE.findCommand(ctx.getGuild(), "trick");
if (cmd == null) {
return null;
}
Trick t = cmd.getTrick(ctx, (String) name, (Boolean) global);
// Return a function which allows invoking the trick
return new AFn() {
@Override
public Object invoke() {
return invoke(PersistentVector.create());
}
@Override
public Object invoke(Object args) {
return t.process(ctx, (Object[]) Clojure.var("clojure.core", "to-array").invoke(args));
}
};
}
});
// Used only by us, to delete the invoking message after sandbox is finished
addContextVar("delete-self", ctx -> false);
// Create a sandbox, 2000ms timeout, under domain k9.sandbox, and running the sandbox-init.clj script before execution
this.sandbox = (IFn) sandboxfn.invoke(tester,
Clojure.read(":timeout"), 2000L,
Clojure.read(":namespace"), Clojure.read("k9.sandbox"),
Clojure.read(":refer-clojure"), false,
Clojure.read(":init"), read_string.invoke(Joiner.on('\n').join(
IOUtils.readLines(K9.class.getResourceAsStream("/sandbox-init.clj"), Charsets.UTF_8))));
}
private final Map<String, Function<@NonNull CommandContext, Object>> contextVars = new LinkedHashMap<>();
private void addContextVar(String name, Function<@NonNull CommandContext, Object> factory) {
String var = "*" + name + "*";
((Var) Clojure.var("k9.sandbox", var)).setDynamic().bindRoot(new PersistentArrayMap(new Object[0]));
contextVars.put(var, factory);
}
@Override
public void process(CommandContext ctx) throws CommandException {
BakedMessage ret = exec(ctx, ctx.getArg(ARG_EXPR));
ret = ret.withContent("=> " + Strings.nullToEmpty(ret.getContent()));
ret.sendBuffered(ctx.getChannel());
}
public BakedMessage exec(CommandContext ctx, String code) throws CommandException {
try {
StringWriter sw = new StringWriter();
Map<Object, Object> bindings = new HashMap<>();
bindings.put(Clojure.var("clojure.core", "*out*"), sw);
for (val e : contextVars.entrySet()) {
bindings.put(Clojure.var("k9.sandbox", e.getKey()), e.getValue().apply(ctx));
}
Object res;
boolean delete;
// Make sure we only modify *delete-self* on one thread at a time
synchronized (sandbox) {
res = sandbox.invoke(Clojure.read(code), PersistentArrayMap.create(bindings));
Var binding = (Var) Clojure.var("k9.sandbox/*delete-self*");
delete = binding.get() == Boolean.TRUE;
if (delete) {
RequestBuffer.request(ctx.getMessage()::delete);
binding.bindRoot(null);
}
}
if (res instanceof EmbedBuilder) {
res = ((EmbedBuilder) res).build();
}
BakedMessage msg = new BakedMessage();
if (res instanceof EmbedObject) {
msg = msg.withEmbed((EmbedObject) res);
} else {
if (res == null) {
res = sw.getBuffer();
}
msg = msg.withContent(res.toString());
}
if (delete) {
msg = msg.withContent("Sent by: " + ctx.getAuthor().getDisplayName(ctx.getGuild()) + (msg.getContent() == null ? "" : "\n" + msg.getContent()));
}
return msg;
} catch (Exception e) {
log.error("Clojure error trace: ", e);
final Throwable cause;
if (e instanceof ExecutionException) {
cause = e.getCause();
} else {
cause = e;
}
// Can't catch TimeoutException because invoke() does not declare it as a possible checked exception
if (cause instanceof TimeoutException) {
throw new CommandException("That took too long to execute!");
} else if (cause instanceof AccessControlException || cause instanceof SecurityException) {
throw new CommandException("Sorry, you're not allowed to do that!");
} else if (cause != null) {
throw new CommandException(cause);
}
throw new CommandException("Unknown");
}
}
@Override
public String getDescription() {
return "Evaluate some clojure code in a sandboxed REPL.\n\n"
+ "Available context vars: " + Joiner.on(", ").join(contextVars.keySet().stream().map(s -> "`" + s + "`").iterator()) + "."
+ " Run `!clj [var]` to preview their contents.";
}
}
| src/main/java/com/tterrag/k9/commands/CommandClojure.java | package com.tterrag.k9.commands;
import java.io.StringWriter;
import java.security.AccessControlException;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.io.IOUtils;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.tterrag.k9.K9;
import com.tterrag.k9.commands.CommandQuote.Quote;
import com.tterrag.k9.commands.api.Command;
import com.tterrag.k9.commands.api.CommandBase;
import com.tterrag.k9.commands.api.CommandContext;
import com.tterrag.k9.commands.api.CommandException;
import com.tterrag.k9.commands.api.CommandRegistrar;
import com.tterrag.k9.trick.Trick;
import com.tterrag.k9.util.BakedMessage;
import com.tterrag.k9.util.NonNull;
import com.tterrag.k9.util.NullHelper;
import clojure.core.Vec;
import clojure.java.api.Clojure;
import clojure.lang.AFn;
import clojure.lang.IFn;
import clojure.lang.IPersistentMap;
import clojure.lang.PersistentArrayMap;
import clojure.lang.PersistentHashMap;
import clojure.lang.PersistentVector;
import clojure.lang.Var;
import lombok.SneakyThrows;
import lombok.val;
import lombok.extern.slf4j.Slf4j;
import sx.blah.discord.api.internal.json.objects.EmbedObject;
import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IGuild;
import sx.blah.discord.handle.obj.IMessage;
import sx.blah.discord.handle.obj.IRole;
import sx.blah.discord.handle.obj.IUser;
import sx.blah.discord.handle.obj.Permissions;
import sx.blah.discord.util.EmbedBuilder;
import sx.blah.discord.util.RequestBuffer;
@Command
@Slf4j
public class CommandClojure extends CommandBase {
private static class BindingBuilder {
private final Map<Object, Object> bindings = new HashMap<>();
public BindingBuilder bind(String name, Object val) {
this.bindings.put(Clojure.read(":" + name), val);
return this;
}
public IPersistentMap build() {
return PersistentHashMap.create(Maps.newHashMap(this.bindings));
}
}
private static final SentenceArgument ARG_EXPR = new SentenceArgument("expression", "The clojure expression to evaluate.", true);
private static final Class<?>[] BLACKLIST_CLASSES = {
Thread.class
};
// Blacklist accessing discord functions
private static final String[] BLACKLIST_PACKAGES = {
K9.class.getPackage().getName(),
"sx.blah.discord"
};
private final IFn sandbox;
@SneakyThrows
public CommandClojure() {
super("clj", false);
// Make sure to load in clojail
Clojure.var("clojure.core", "require").invoke(Clojure.read("[clojail core jvm testers]"));
// Convenience declarations of used functions
IFn read_string = Clojure.var("clojure.core", "read-string");
IFn sandboxfn = Clojure.var("clojail.core", "sandbox");
Var secure_tester = (Var) Clojure.var("clojail.testers", "secure-tester");
// Load these to add new blacklisted resources
IFn blacklist_objects = Clojure.var("clojail.testers", "blacklist-objects");
IFn blacklist_packages = Clojure.var("clojail.testers", "blacklist-packages");
// Create our tester with custom blacklist
Object tester = Clojure.var("clojure.core/conj").invoke(secure_tester.getRawRoot(),
blacklist_objects.invoke(PersistentVector.create((Object[]) BLACKLIST_CLASSES)),
blacklist_packages.invoke(PersistentVector.create((Object[]) BLACKLIST_PACKAGES)));
/* == Setting up Context == */
// Defining all the context vars and the functions to bind them for a given CommandContext
// A simple function that returns a map representing a user, given an IUser
BiFunction<IGuild, IUser, IPersistentMap> getBinding = (g, u) -> new BindingBuilder()
.bind("name", u.getName())
.bind("nick", u.getDisplayName(g))
.bind("id", u.getLongID())
.bind("presence", new BindingBuilder()
.bind("text", u.getPresence().getText().orElse(null))
.bind("activity", u.getPresence().getActivity().map(Object::toString).orElse(null))
.bind("status", u.getPresence().getStatus().toString())
.bind("streamurl", u.getPresence().getStreamingUrl().orElse(null))
.build())
.bind("bot", u.isBot())
.bind("roles",
PersistentVector.create(u.getRolesForGuild(g).stream()
.sorted(Comparator.comparing(IRole::getPosition).reversed())
.map(IRole::getLongID)
.toArray(Object[]::new)))
.bind("avatar", u.getAvatarURL())
.build();
// Set up global context vars
// Create an easily accessible map for the sending user
addContextVar("author", ctx -> getBinding.apply(ctx.getGuild(), ctx.getAuthor()));
// Add a lookup function for looking up an arbitrary user in the guild
addContextVar("users", ctx -> new AFn() {
@Override
public Object invoke(Object id) {
IGuild guild = ctx.getGuild();
IUser ret = null;
if (guild != null) {
ret = guild.getUserByID(((Number)id).longValue());
}
if (ret == null) {
throw new IllegalArgumentException("Could not find user for ID");
}
return getBinding.apply(ctx.getGuild(), ret);
}
});
addContextVar("roles", ctx -> new AFn() {
@Override
public Object invoke(Object id) {
IGuild guild = ctx.getGuild();
IRole ret = null;
if (guild != null) {
ret = guild.getRoleByID(((Number)id).longValue());
}
if (ret == null) {
throw new IllegalArgumentException("Could not find role for ID");
}
return new BindingBuilder()
.bind("name", ret.getName())
.bind("color", PersistentVector.create(ret.getColor().getRed(), ret.getColor().getGreen(), ret.getColor().getBlue()))
.bind("id", ret.getLongID())
.build();
}
});
// Simple data bean representing the current channel
addContextVar("channel", ctx ->
new BindingBuilder()
.bind("name", ctx.getChannel().getName())
.bind("id", ctx.getChannel().getLongID())
.bind("topic", ctx.getChannel().isPrivate() ? null : ctx.getChannel().getTopic())
.build());
// Simple data bean representing the current guild
addContextVar("guild", ctx -> {
IGuild guild = ctx.getGuild();
return guild == null ? null :
new BindingBuilder()
.bind("name", guild.getName())
.bind("id", guild.getLongID())
.bind("owner", guild.getOwner().getLongID())
.bind("region", guild.getRegion().getName())
.build();
});
// Add the current message ID
addContextVar("message", ctx -> ctx.getMessage().getLongID());
// Provide a lookup function for ID->message
addContextVar("messages", ctx -> new AFn() {
@Override
public Object invoke(Object arg1) {
IGuild guild = ctx.getGuild();
List<IChannel> channels;
if (guild == null) {
channels = Collections.singletonList(ctx.getChannel());
} else {
channels = guild.getChannels();
}
IMessage msg = channels.stream()
.filter(c -> c.getModifiedPermissions(K9.instance.getOurUser()).contains(Permissions.READ_MESSAGES))
.map(c -> c.getMessageByID(((Number)arg1).longValue()))
.filter(Objects::nonNull)
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("No message found"));
return new BindingBuilder()
.bind("content", msg.getContent())
.bind("fcontent", msg.getFormattedContent())
.bind("id", arg1)
.bind("author", msg.getAuthor().getLongID())
.bind("channel", msg.getChannel().getLongID())
.bind("timestamp", msg.getTimestamp())
.build();
}
});
// A function for looking up quotes, given an ID, or pass no arguments to return a vector of valid quote IDs
addContextVar("quotes", ctx -> {
CommandQuote cmd = (CommandQuote) CommandRegistrar.INSTANCE.findCommand(ctx.getGuild(), "quote");
return new AFn() {
@Override
public Object invoke() {
if (cmd == null) {
return null;
}
return PersistentVector.create(cmd.getData(ctx).keySet());
}
@Override
public Object invoke(Object arg1) {
if (cmd == null) {
return null;
}
Quote q = cmd.getData(ctx).get(((Number)arg1).intValue());
if (q == null) {
throw new IllegalArgumentException("No quote for ID " + arg1);
}
return new BindingBuilder()
.bind("quote", q.getQuote())
.bind("quotee", q.getQuotee())
.bind("owner", q.getOwner())
.bind("weight", q.getWeight())
.bind("id", arg1)
.build();
}
};
});
// A function for looking up tricks, given a name. Optionally pass "true" as second param to force global lookup
addContextVar("tricks", ctx -> new AFn() {
@Override
public Object invoke(Object name) {
return invoke(name, false);
}
@Override
public Object invoke(Object name, Object global) {
CommandTrick cmd = (CommandTrick) CommandRegistrar.INSTANCE.findCommand(ctx.getGuild(), "trick");
if (cmd == null) {
return null;
}
Trick t = cmd.getTrick(ctx, (String) name, (Boolean) global);
// Return a function which allows invoking the trick
return new AFn() {
@Override
public Object invoke() {
return invoke(PersistentVector.create());
}
@Override
public Object invoke(Object args) {
return t.process(ctx, (Object[]) Clojure.var("clojure.core", "to-array").invoke(args));
}
};
}
});
// Used only by us, to delete the invoking message after sandbox is finished
addContextVar("delete-self", ctx -> false);
// Create a sandbox, 2000ms timeout, under domain k9.sandbox, and running the sandbox-init.clj script before execution
this.sandbox = (IFn) sandboxfn.invoke(tester,
Clojure.read(":timeout"), 2000L,
Clojure.read(":namespace"), Clojure.read("k9.sandbox"),
Clojure.read(":refer-clojure"), false,
Clojure.read(":init"), read_string.invoke(Joiner.on('\n').join(
IOUtils.readLines(K9.class.getResourceAsStream("/sandbox-init.clj"), Charsets.UTF_8))));
}
private final Map<String, Function<@NonNull CommandContext, Object>> contextVars = new LinkedHashMap<>();
private void addContextVar(String name, Function<@NonNull CommandContext, Object> factory) {
String var = "*" + name + "*";
((Var) Clojure.var("k9.sandbox", var)).setDynamic().bindRoot(new PersistentArrayMap(new Object[0]));
contextVars.put(var, factory);
}
@Override
public void process(CommandContext ctx) throws CommandException {
BakedMessage ret = exec(ctx, ctx.getArg(ARG_EXPR));
ret = ret.withContent("=> " + Strings.nullToEmpty(ret.getContent()));
ret.sendBuffered(ctx.getChannel());
}
public BakedMessage exec(CommandContext ctx, String code) throws CommandException {
try {
StringWriter sw = new StringWriter();
Map<Object, Object> bindings = new HashMap<>();
bindings.put(Clojure.var("clojure.core", "*out*"), sw);
for (val e : contextVars.entrySet()) {
bindings.put(Clojure.var("k9.sandbox", e.getKey()), e.getValue().apply(ctx));
}
Object res;
boolean delete;
// Make sure we only modify *delete-self* on one thread at a time
synchronized (sandbox) {
res = sandbox.invoke(Clojure.read(code), PersistentArrayMap.create(bindings));
Var binding = (Var) Clojure.var("k9.sandbox/*delete-self*");
delete = binding.get() == Boolean.TRUE;
if (delete) {
RequestBuffer.request(ctx.getMessage()::delete);
binding.bindRoot(null);
}
}
if (res instanceof EmbedBuilder) {
res = ((EmbedBuilder) res).build();
}
BakedMessage msg = new BakedMessage();
if (res instanceof EmbedObject) {
msg = msg.withEmbed((EmbedObject) res);
} else {
if (res == null) {
res = sw.getBuffer();
}
msg = msg.withContent(res.toString());
}
if (delete) {
msg = msg.withContent("Sent by: " + ctx.getAuthor().getDisplayName(ctx.getGuild()) + (msg.getContent() == null ? "" : "\n" + msg.getContent()));
}
return msg;
} catch (Exception e) {
log.error("Clojure error trace: ", e);
final Throwable cause;
if (e instanceof ExecutionException) {
cause = e.getCause();
} else {
cause = e;
}
// Can't catch TimeoutException because invoke() does not declare it as a possible checked exception
if (cause instanceof TimeoutException) {
throw new CommandException("That took too long to execute!");
} else if (cause instanceof AccessControlException || cause instanceof SecurityException) {
throw new CommandException("Sorry, you're not allowed to do that!");
} else if (cause != null) {
throw new CommandException(cause);
}
throw new CommandException("Unknown");
}
}
@Override
public String getDescription() {
return "Evaluate some clojure code in a sandboxed REPL.\n\n"
+ "Available context vars: " + Joiner.on(", ").join(contextVars.keySet().stream().map(s -> "`" + s + "`").iterator()) + "."
+ " Run `!clj [var]` to preview their contents.";
}
}
| Add server join time to user binding and creation time to guild | src/main/java/com/tterrag/k9/commands/CommandClojure.java | Add server join time to user binding and creation time to guild | <ide><path>rc/main/java/com/tterrag/k9/commands/CommandClojure.java
<ide> .map(IRole::getLongID)
<ide> .toArray(Object[]::new)))
<ide> .bind("avatar", u.getAvatarURL())
<add> .bind("joined", g.getJoinTimeForUser(u))
<ide> .build();
<ide>
<ide> // Set up global context vars
<ide> .bind("id", guild.getLongID())
<ide> .bind("owner", guild.getOwner().getLongID())
<ide> .bind("region", guild.getRegion().getName())
<add> .bind("created", guild.getCreationDate())
<ide> .build();
<ide> });
<ide> |
|
Java | apache-2.0 | ac91fe51ff443ad505b68c2a182ff52d38649982 | 0 | heriram/incubator-asterixdb,apache/incubator-asterixdb,waans11/incubator-asterixdb-hyracks,sjaco002/incubator-asterixdb-hyracks,kisskys/incubator-asterixdb-hyracks,ty1er/incubator-asterixdb,ecarm002/incubator-asterixdb,ecarm002/incubator-asterixdb,lwhay/hyracks,ty1er/incubator-asterixdb,tectronics/hyracks,waans11/incubator-asterixdb,parshimers/incubator-asterixdb-hyracks,waans11/incubator-asterixdb,tectronics/hyracks,ty1er/incubator-asterixdb-hyracks,apache/incubator-asterixdb,ty1er/incubator-asterixdb-hyracks,heriram/incubator-asterixdb,ilovesoup/hyracks,waans11/incubator-asterixdb,kisskys/incubator-asterixdb-hyracks,waans11/incubator-asterixdb-hyracks,sjaco002/incubator-asterixdb-hyracks,ecarm002/incubator-asterixdb,kisskys/incubator-asterixdb,kisskys/incubator-asterixdb,amoudi87/hyracks,ecarm002/incubator-asterixdb,sjaco002/incubator-asterixdb-hyracks,apache/incubator-asterixdb,waans11/incubator-asterixdb-hyracks,parshimers/incubator-asterixdb-hyracks,kisskys/incubator-asterixdb,ty1er/incubator-asterixdb,apache/incubator-asterixdb,ecarm002/incubator-asterixdb,ilovesoup/hyracks,ecarm002/incubator-asterixdb,amoudi87/hyracks,ty1er/incubator-asterixdb,kisskys/incubator-asterixdb-hyracks,ilovesoup/hyracks,ecarm002/incubator-asterixdb,lwhay/hyracks,heriram/incubator-asterixdb,ilovesoup/hyracks,apache/incubator-asterixdb,kisskys/incubator-asterixdb,waans11/incubator-asterixdb-hyracks,kisskys/incubator-asterixdb,waans11/incubator-asterixdb,parshimers/incubator-asterixdb-hyracks,waans11/incubator-asterixdb,ty1er/incubator-asterixdb,tectronics/hyracks,lwhay/hyracks,kisskys/incubator-asterixdb,sjaco002/incubator-asterixdb-hyracks,tectronics/hyracks,ty1er/incubator-asterixdb-hyracks,amoudi87/hyracks,apache/incubator-asterixdb,waans11/incubator-asterixdb,kisskys/incubator-asterixdb-hyracks,heriram/incubator-asterixdb,kisskys/incubator-asterixdb,heriram/incubator-asterixdb,lwhay/hyracks,heriram/incubator-asterixdb,amoudi87/hyracks,heriram/incubator-asterixdb,waans11/incubator-asterixdb,parshimers/incubator-asterixdb-hyracks,apache/incubator-asterixdb,ty1er/incubator-asterixdb-hyracks,ty1er/incubator-asterixdb | /*
* Copyright 2009-2010 by The Regents of the University of California
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* you may obtain a copy of the License from
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.hyracks.server.drivers;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import edu.uci.ics.hyracks.control.common.controllers.CCConfig;
import edu.uci.ics.hyracks.control.common.controllers.NCConfig;
import edu.uci.ics.hyracks.server.process.HyracksCCProcess;
import edu.uci.ics.hyracks.server.process.HyracksNCProcess;
public class VirtualClusterDriver {
private static class Options {
@Option(name = "-n", required = false, usage = "Number of node controllers (default: 2)")
public int n = 2;
@Option(name = "-cc-client-net-port", required = false, usage = "CC Port (default: 1098)")
public int ccClientNetPort = 1098;
@Option(name = "-cc-cluster-net-port", required = false, usage = "CC Port (default: 1099)")
public int ccClusterNetPort = 1099;
@Option(name = "-cc-http-port", required = false, usage = "CC Port (default: 16001)")
public int ccHttpPort = 16001;
}
public static void main(String[] args) throws Exception {
Options options = new Options();
CmdLineParser cp = new CmdLineParser(options);
try {
cp.parseArgument(args);
} catch (Exception e) {
System.err.println(e.getMessage());
cp.printUsage(System.err);
return;
}
CCConfig ccConfig = new CCConfig();
ccConfig.clusterNetIpAddress = "127.0.0.1";
ccConfig.clusterNetPort = options.ccClusterNetPort;
ccConfig.clientNetIpAddress = "127.0.0.1";
ccConfig.clientNetPort = options.ccClientNetPort;
ccConfig.httpPort = options.ccHttpPort;
HyracksCCProcess ccp = new HyracksCCProcess(ccConfig);
ccp.start();
Thread.sleep(5000);
HyracksNCProcess ncps[] = new HyracksNCProcess[options.n];
for (int i = 0; i < options.n; ++i) {
NCConfig ncConfig = new NCConfig();
ncConfig.ccHost = "127.0.0.1";
ncConfig.ccPort = options.ccClusterNetPort;
ncConfig.clusterNetIPAddress = "127.0.0.1";
ncConfig.nodeId = "nc" + i;
ncConfig.dataIPAddress = "127.0.0.1";
ncps[i] = new HyracksNCProcess(ncConfig);
ncps[i].start();
}
while (true) {
Thread.sleep(10000);
}
}
} | hyracks-server/src/main/java/edu/uci/ics/hyracks/server/drivers/VirtualClusterDriver.java | /*
* Copyright 2009-2010 by The Regents of the University of California
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* you may obtain a copy of the License from
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.hyracks.server.drivers;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import edu.uci.ics.hyracks.control.common.controllers.CCConfig;
import edu.uci.ics.hyracks.control.common.controllers.NCConfig;
import edu.uci.ics.hyracks.server.process.HyracksCCProcess;
import edu.uci.ics.hyracks.server.process.HyracksNCProcess;
public class VirtualClusterDriver {
private static class Options {
@Option(name = "-n", required = false, usage = "Number of node controllers (default: 2)")
public int n = 2;
@Option(name = "-cc-client-net-port", required = false, usage = "CC Port (default: 1098)")
public int ccClientNetPort = 1098;
@Option(name = "-cc-cluster-net-port", required = false, usage = "CC Port (default: 1099)")
public int ccClusterNetPort = 1099;
@Option(name = "-cc-http-port", required = false, usage = "CC Port (default: 19001)")
public int ccHttpPort = 19001;
}
public static void main(String[] args) throws Exception {
Options options = new Options();
CmdLineParser cp = new CmdLineParser(options);
try {
cp.parseArgument(args);
} catch (Exception e) {
System.err.println(e.getMessage());
cp.printUsage(System.err);
return;
}
CCConfig ccConfig = new CCConfig();
ccConfig.clusterNetIpAddress = "127.0.0.1";
ccConfig.clusterNetPort = options.ccClusterNetPort;
ccConfig.clientNetIpAddress = "127.0.0.1";
ccConfig.clientNetPort = options.ccClientNetPort;
ccConfig.httpPort = options.ccHttpPort;
HyracksCCProcess ccp = new HyracksCCProcess(ccConfig);
ccp.start();
Thread.sleep(5000);
HyracksNCProcess ncps[] = new HyracksNCProcess[options.n];
for (int i = 0; i < options.n; ++i) {
NCConfig ncConfig = new NCConfig();
ncConfig.ccHost = "127.0.0.1";
ncConfig.ccPort = options.ccClusterNetPort;
ncConfig.clusterNetIPAddress = "127.0.0.1";
ncConfig.nodeId = "nc" + i;
ncConfig.dataIPAddress = "127.0.0.1";
ncps[i] = new HyracksNCProcess(ncConfig);
ncps[i].start();
}
while (true) {
Thread.sleep(10000);
}
}
} | Changed default web port to 16001
git-svn-id: a078fbb96e5d5886a75e65008c06a47c9bdeda97@1219 123451ca-8445-de46-9d55-352943316053
| hyracks-server/src/main/java/edu/uci/ics/hyracks/server/drivers/VirtualClusterDriver.java | Changed default web port to 16001 | <ide><path>yracks-server/src/main/java/edu/uci/ics/hyracks/server/drivers/VirtualClusterDriver.java
<ide> @Option(name = "-cc-cluster-net-port", required = false, usage = "CC Port (default: 1099)")
<ide> public int ccClusterNetPort = 1099;
<ide>
<del> @Option(name = "-cc-http-port", required = false, usage = "CC Port (default: 19001)")
<del> public int ccHttpPort = 19001;
<add> @Option(name = "-cc-http-port", required = false, usage = "CC Port (default: 16001)")
<add> public int ccHttpPort = 16001;
<ide> }
<ide>
<ide> public static void main(String[] args) throws Exception { |
|
JavaScript | mpl-2.0 | f461a39170d17ed953295e4e8788e387601bad71 | 0 | mozilla/openbadges-badges,andrewhayward/openbadges-badges | if (process.env.NEW_RELIC_HOME) {
require('newrelic');
}
const config = require('./lib/config');
const express = require('express');
const nunjucks = require('nunjucks');
const path = require('path');
const views = require('./views');
const app = express();
const env = new nunjucks.Environment(new nunjucks.FileSystemLoader(path.join(__dirname, 'templates')), {autoescape: true});
env.express(app);
// Bootstrap the app for reversible routing, and other niceties
require('../lib/router.js')(app);
var staticDir = path.join(__dirname, '/static');
var staticRoot = '/static';
app.use(express.compress());
app.use(express.bodyParser());
app.use(staticRoot, express.static(staticDir));
app.use(function (req, res, next) {
res.locals.static = function static (staticPath) {
return path.join(app.mountPoint, staticRoot, staticPath);
}
next();
});
app.get('/', 'home', views.home);
app.get('/dml', 'dml.home', views.dml.home);
app.get('/summit', 'summit.home', views.summit.home);
app.get('*', views.errors.notFound);
app.use(views.errors.error);
if (!module.parent) {
var port = config('PORT', 3000);
app.listen(port, function(err) {
if (err) throw err;
console.log("Listening on port " + port + ".");
});
} else {
module.exports = http.createServer(app);
} | app/index.js | if (process.env.NEW_RELIC_HOME) {
require( 'newrelic' );
}
const config = require('./lib/config');
const express = require('express');
const nunjucks = require('nunjucks');
const path = require('path');
const views = require('./views');
const app = express();
const env = new nunjucks.Environment(new nunjucks.FileSystemLoader(path.join(__dirname, 'templates')), {autoescape: true});
env.express(app);
// Bootstrap the app for reversible routing, and other niceties
require('../lib/router.js')(app);
var staticDir = path.join(__dirname, '/static');
var staticRoot = '/static';
app.use(express.compress());
app.use(express.bodyParser());
app.use(staticRoot, express.static(staticDir));
app.use(function (req, res, next) {
res.locals.static = function static (staticPath) {
return path.join(app.mountPoint, staticRoot, staticPath);
}
next();
});
app.get('/', 'home', views.home);
app.get('/dml', 'dml.home', views.dml.home);
app.get('/summit', 'summit.home', views.summit.home);
app.get('*', views.errors.notFound);
app.use(views.errors.error);
if (!module.parent) {
var port = config('PORT', 3000);
app.listen(port, function(err) {
if (err) throw err;
console.log("Listening on port " + port + ".");
});
} else {
module.exports = http.createServer(app);
} | White space fixing | app/index.js | White space fixing | <ide><path>pp/index.js
<ide> if (process.env.NEW_RELIC_HOME) {
<del> require( 'newrelic' );
<add> require('newrelic');
<ide> }
<ide>
<ide> const config = require('./lib/config'); |
|
Java | agpl-3.0 | d77349292617b2e0d1804951b002ffb47a583dd2 | 0 | PeterWithers/temp-to-delete1,PeterWithers/temp-to-delete1,KinshipSoftware/KinOathKinshipArchiver,KinshipSoftware/KinOathKinshipArchiver | package nl.mpi.kinnate.svg;
import java.awt.Point;
import java.util.ArrayList;
import nl.mpi.arbil.util.MessageDialogHandler;
import nl.mpi.kinnate.kindata.DataTypes;
import nl.mpi.kinnate.kindata.EntityData;
import nl.mpi.kinnate.kindata.EntityRelation;
import nl.mpi.kinnate.uniqueidentifiers.IdentifierException;
import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.w3c.dom.svg.SVGDocument;
/**
* Document : RelationSvg
* Created on : Mar 9, 2011, 3:21:16 PM
* Author : Peter Withers
*/
public class RelationSvg {
private MessageDialogHandler dialogHandler;
public RelationSvg(MessageDialogHandler dialogHandler) {
this.dialogHandler = dialogHandler;
}
private void addUseNode(SVGDocument doc, String svgNameSpace, Element targetGroup, String targetDefId) {
String useNodeId = targetDefId + "use";
Node useNodeOld = doc.getElementById(useNodeId);
if (useNodeOld != null) {
useNodeOld.getParentNode().removeChild(useNodeOld);
}
Element useNode = doc.createElementNS(svgNameSpace, "use");
useNode.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + targetDefId); // the xlink: of "xlink:href" is required for some svg viewers to render correctly
// useNode.setAttribute("href", "#" + lineIdString);
useNode.setAttribute("id", useNodeId);
targetGroup.appendChild(useNode);
}
private void updateLabelNode(SVGDocument doc, String svgNameSpace, String lineIdString, String targetRelationId) {
// remove and readd the text on path label so that it updates with the new path
String labelNodeId = targetRelationId + "label";
Node useNodeOld = doc.getElementById(labelNodeId);
if (useNodeOld != null) {
Node textParentNode = useNodeOld.getParentNode();
String labelText = useNodeOld.getTextContent();
useNodeOld.getParentNode().removeChild(useNodeOld);
Element textPath = doc.createElementNS(svgNameSpace, "textPath");
textPath.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + lineIdString); // the xlink: of "xlink:href" is required for some svg viewers to render correctly
textPath.setAttribute("startOffset", "50%");
textPath.setAttribute("id", labelNodeId);
Text textNode = doc.createTextNode(labelText);
textPath.appendChild(textNode);
textParentNode.appendChild(textPath);
}
}
private boolean oldFormatWarningShown = false;
protected void setPolylinePointsAttribute(LineLookUpTable lineLookUpTable, String lineIdString, Element targetNode, DataTypes.RelationType relationType, float vSpacing, float egoX, float egoY, float alterX, float alterY, float[] averageParentPassed) {
//float midY = (egoY + alterY) / 2;
// todo: Ticket #1064 when an entity is above one that it should be below the line should make a zigzag to indicate it
ArrayList<Point> initialPointsList = new ArrayList<Point>();
float[] averageParent = null;
float midSpacing = vSpacing / 2;
// float parentSpacing = 10;
float egoYmid;
float alterYmid;
float centerX = (egoX + alterX) / 2;
switch (relationType) {
case ancestor:
if (averageParentPassed == null) {
// if no parent location has been provided then just use the current parent
averageParent = new float[]{alterX, alterY};
} else {
// todo: this is filtering out the parent location for non ancestor relations, but it would be more efficient to no get the parent location unless required
averageParent = averageParentPassed;
}
egoYmid = egoY - midSpacing;
alterYmid = averageParent[1] + 30;
// alterYmid = alterY + midSpacing;
// egoYmid = alterYmid + 30;
centerX = (egoYmid < alterYmid) ? centerX : egoX;
centerX = (egoY < alterY && egoX == alterX) ? centerX - midSpacing : centerX;
break;
// float tempX = egoX;
// float tempY = egoY;
// egoX = alterX;
// egoY = alterY;
// alterX = tempX;
// alterY = tempY;
case descendant:
if (!oldFormatWarningShown) {
dialogHandler.addMessageDialogToQueue("This diagram needs to be updated, select recalculate diagram from the edit menu before continuing.", "Old or erroneous format detected");
oldFormatWarningShown = true;
}
// targetNode.getParentNode().getParentNode().getParentNode().getParentNode().removeChild(targetNode.getParentNode().getParentNode().getParentNode());
// throw new UnsupportedOperationException("in order to simplify section, the ancestor relations should be swapped so that ego is the parent");
return;
// throw new UnsupportedOperationException("in order to simplify section, the ancestor relations should be swapped so that ego is the parent");
// egoYmid = egoY + midSpacing;
// alterYmid = alterY - midSpacing;
// centerX = (egoYmid < alterYmid) ? alterX : centerX;
// centerX = (egoY > alterY && egoX == alterX) ? centerX - midSpacing : centerX;
// break;
case sibling:
egoYmid = egoY - midSpacing;
alterYmid = alterY - midSpacing;
centerX = (egoY < alterY) ? alterX : egoX;
centerX = (egoX == alterX) ? centerX - midSpacing : centerX;
break;
case union:
// float unionMid = (egoY > alterY) ? egoY : alterY;
egoYmid = egoY + 30;
alterYmid = alterY + 30;
centerX = (egoY < alterY) ? egoX : alterX;
centerX = (egoX == alterX) ? centerX - midSpacing : centerX;
break;
// case affiliation:
// case none:
default:
egoYmid = egoY;
alterYmid = alterY;
break;
}
// if (alterY == egoY) {
// // make sure that union lines go below the entities and sibling lines go above
// if (relationType == DataTypes.RelationType.sibling) {
// midY = alterY - vSpacing / 2;
// } else if (relationType == DataTypes.RelationType.union) {
// midY = alterY + vSpacing / 2;
// }
// }
initialPointsList.add(new Point((int) egoX, (int) egoY));
initialPointsList.add(new Point((int) egoX, (int) egoYmid));
if (averageParent != null) {
float averageParentX = averageParent[0];
// float minParentY = averageParent[1];
initialPointsList.add(new Point((int) averageParentX, (int) egoYmid));
initialPointsList.add(new Point((int) averageParentX, (int) alterYmid));
} else {
initialPointsList.add(new Point((int) centerX, (int) egoYmid));
initialPointsList.add(new Point((int) centerX, (int) alterYmid));
}
initialPointsList.add(new Point((int) alterX, (int) alterYmid));
initialPointsList.add(new Point((int) alterX, (int) alterY));
Point[] adjustedPointsList;
if (lineLookUpTable != null) {
// this version is used when the relations are drawn on the diagram
// or when an entity is dragged before the diagram is redrawn in the case of a reloaded from disk diagram (this case is sub optimal in that on first load the loops will not be drawn)
adjustedPointsList = lineLookUpTable.adjustLineToObstructions(lineIdString, initialPointsList);
} else {
// this version is used when the relation drag handles are used
adjustedPointsList = initialPointsList.toArray(new Point[]{});
}
StringBuilder stringBuilder = new StringBuilder();
for (Point currentPoint : adjustedPointsList) {
stringBuilder.append(currentPoint.x);
stringBuilder.append(",");
stringBuilder.append(currentPoint.y);
stringBuilder.append(" ");
}
targetNode.setAttribute("points", stringBuilder.toString());
}
protected void setPathPointsAttribute(Element targetNode, DataTypes.RelationType relationType, float hSpacing, float vSpacing, float egoX, float egoY, float alterX, float alterY) {
float fromBezX;
float fromBezY;
float toBezX;
float toBezY;
if ((egoX > alterX && egoY < alterY) || (egoX > alterX && egoY > alterY)) {
// prevent the label on the line from rendering upside down
float tempX = alterX;
float tempY = alterY;
alterX = egoX;
alterY = egoY;
egoX = tempX;
egoY = tempY;
}
if (relationType == DataTypes.RelationType.verticalCurve) {
fromBezX = egoX;
fromBezY = alterY;
toBezX = alterX;
toBezY = egoY;
// todo: update the bezier positions similar to in the follwing else statement
if (1 / (egoY - alterY) < vSpacing) {
fromBezX = egoX;
fromBezY = alterY - vSpacing / 2;
toBezX = alterX;
toBezY = egoY - vSpacing / 2;
}
} else {
fromBezX = alterX;
fromBezY = egoY;
toBezX = egoX;
toBezY = alterY;
// todo: if the nodes are almost in align then this test fails and it should insted check for proximity not equality
// System.out.println(1 / (egoX - alterX));
// if (1 / (egoX - alterX) < vSpacing) {
if (egoX > alterX) {
if (egoX - alterX < hSpacing / 4) {
fromBezX = egoX - hSpacing / 4;
toBezX = alterX - hSpacing / 4;
} else {
fromBezX = (egoX - alterX) / 2 + alterX;
toBezX = (egoX - alterX) / 2 + alterX;
}
} else {
if (alterX - egoX < hSpacing / 4) {
fromBezX = egoX + hSpacing / 4;
toBezX = alterX + hSpacing / 4;
} else {
fromBezX = (alterX - egoX) / 2 + egoX;
toBezX = (alterX - egoX) / 2 + egoX;
}
}
}
targetNode.setAttribute("d", "M " + egoX + "," + egoY + " C " + fromBezX + "," + fromBezY + " " + toBezX + "," + toBezY + " " + alterX + "," + alterY);
}
public boolean hasCommonParent(EntityData currentNode, EntityRelation graphLinkNode) {
if (graphLinkNode.relationType == DataTypes.RelationType.sibling) {
for (EntityRelation altersRelation : graphLinkNode.getAlterNode().getDistinctRelateNodes()) {
if (altersRelation.relationType == DataTypes.RelationType.ancestor) {
for (EntityRelation egosRelation : currentNode.getDistinctRelateNodes()) {
if (egosRelation.relationType == DataTypes.RelationType.ancestor) {
if (altersRelation.alterUniqueIdentifier.equals(egosRelation.alterUniqueIdentifier)) {
if (altersRelation.getAlterNode().isVisible) {
return true;
}
}
}
}
}
}
}
return false;
}
// private Float getCommonParentMaxY(EntitySvg entitySvg, EntityData currentNode, EntityRelation graphLinkNode) {
// if (graphLinkNode.relationType == DataTypes.RelationType.sibling) {
// Float maxY = null;
// ArrayList<Float> commonParentY = new ArrayList<Float>();
// for (EntityRelation altersRelation : graphLinkNode.getAlterNode().getDistinctRelateNodes()) {
// if (altersRelation.relationType == DataTypes.RelationType.ancestor) {
// for (EntityRelation egosRelation : currentNode.getDistinctRelateNodes()) {
// if (egosRelation.relationType == DataTypes.RelationType.ancestor) {
// if (altersRelation.alterUniqueIdentifier.equals(egosRelation.alterUniqueIdentifier)) {
// float parentY = entitySvg.getEntityLocation(egosRelation.alterUniqueIdentifier)[1];
// maxY = parentY > maxY ? parentY : maxY;
// }
// }
// }
// }
// }
// return maxY;
// } else {
// return null;
// }
//
// }
protected void insertRelation(GraphPanel graphPanel, Element relationGroupNode, EntityData leftEntity, EntityData rightEntity, DataTypes.RelationType directedRelation, String lineColour, String lineLabel, int hSpacing, int vSpacing) {
float[] egoSymbolPoint;
float[] alterSymbolPoint;
float[] parentPoint;
// the ancestral relations should already be unidirectional and duplicates should have been removed
egoSymbolPoint = graphPanel.entitySvg.getEntityLocation(leftEntity.getUniqueIdentifier());
alterSymbolPoint = graphPanel.entitySvg.getEntityLocation(rightEntity.getUniqueIdentifier());
parentPoint = graphPanel.entitySvg.getAverageParentLocation(leftEntity);
int relationLineIndex = relationGroupNode.getChildNodes().getLength();
Element groupNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "g");
groupNode.setAttribute("id", "relation" + relationLineIndex);
Element defsNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "defs");
String lineIdString = "relation" + relationLineIndex + "Line";
new DataStoreSvg().storeRelationParameters(graphPanel.doc, groupNode, directedRelation, leftEntity.getUniqueIdentifier(), rightEntity.getUniqueIdentifier());
// set the line end points
// int[] egoSymbolPoint = graphPanel.dataStoreSvg.graphData.getEntityLocation(currentNode.getUniqueIdentifier());
// int[] alterSymbolPoint = graphPanel.dataStoreSvg.graphData.getEntityLocation(graphLinkNode.getAlterNode().getUniqueIdentifier());
// float fromX = (currentNode.getxPos()); // * hSpacing + hSpacing
// float fromY = (currentNode.getyPos()); // * vSpacing + vSpacing
// float toX = (graphLinkNode.getAlterNode().getxPos()); // * hSpacing + hSpacing
// float toY = (graphLinkNode.getAlterNode().getyPos()); // * vSpacing + vSpacing
float fromX = (egoSymbolPoint[0]); // * hSpacing + hSpacing
float fromY = (egoSymbolPoint[1]); // * vSpacing + vSpacing
float toX = (alterSymbolPoint[0]); // * hSpacing + hSpacing
float toY = (alterSymbolPoint[1]); // * vSpacing + vSpacing
boolean addedRelationLine = false;
if (!DataTypes.isSanguinLine(directedRelation)) {
// case kinTermLine:
// this case uses the following case
// case verticalCurve:
// todo: groupNode.setAttribute("id", );
// System.out.println("link: " + graphLinkNode.linkedNode.xPos + ":" + graphLinkNode.linkedNode.yPos);
//
//// <line id="_15" transform="translate(146.0,112.0)" x1="0" y1="0" x2="100" y2="100" ="black" stroke-width="1"/>
// Element linkLine = doc.createElementNS(svgNS, "line");
// linkLine.setAttribute("x1", Integer.toString(currentNode.xPos * hSpacing + hSpacing));
// linkLine.setAttribute("y1", Integer.toString(currentNode.yPos * vSpacing + vSpacing));
//
// linkLine.setAttribute("x2", Integer.toString(graphLinkNode.linkedNode.xPos * hSpacing + hSpacing));
// linkLine.setAttribute("y2", Integer.toString(graphLinkNode.linkedNode.yPos * vSpacing + vSpacing));
// linkLine.setAttribute("stroke", "black");
// linkLine.setAttribute("stroke-width", "1");
// // Attach the rectangle to the root 'svg' element.
// svgRoot.appendChild(linkLine);
//System.out.println("link: " + graphLinkNode.getAlterNode().xPos + ":" + graphLinkNode.getAlterNode().yPos);
// <line id="_15" transform="translate(146.0,112.0)" x1="0" y1="0" x2="100" y2="100" ="black" stroke-width="1"/>
Element linkLine = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "path");
setPathPointsAttribute(linkLine, directedRelation, hSpacing, vSpacing, fromX, fromY, toX, toY);
// linkLine.setAttribute("x1", );
// linkLine.setAttribute("y1", );
//
// linkLine.setAttribute("x2", );
linkLine.setAttribute("fill", "none");
if (lineColour != null) {
linkLine.setAttribute("stroke", lineColour);
} else {
linkLine.setAttribute("stroke", "blue");
}
linkLine.setAttribute("stroke-width", Integer.toString(EntitySvg.strokeWidth));
linkLine.setAttribute("id", lineIdString);
defsNode.appendChild(linkLine);
addedRelationLine = true;
// break;
} else {
// case sanguineLine:
// Element squareLinkLine = doc.createElement("line");
// squareLinkLine.setAttribute("x1", Integer.toString(currentNode.xPos * hSpacing + hSpacing));
// squareLinkLine.setAttribute("y1", Integer.toString(currentNode.yPos * vSpacing + vSpacing));
//
// squareLinkLine.setAttribute("x2", Integer.toString(graphLinkNode.linkedNode.xPos * hSpacing + hSpacing));
// squareLinkLine.setAttribute("y2", Integer.toString(graphLinkNode.linkedNode.yPos * vSpacing + vSpacing));
// squareLinkLine.setAttribute("stroke", "grey");
// squareLinkLine.setAttribute("stroke-width", Integer.toString(strokeWidth));
Element squareLinkLine = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "polyline");
setPolylinePointsAttribute(graphPanel.lineLookUpTable, lineIdString, squareLinkLine, directedRelation, vSpacing, fromX, fromY, toX, toY, parentPoint);
squareLinkLine.setAttribute("fill", "none");
squareLinkLine.setAttribute("stroke", "grey");
squareLinkLine.setAttribute("stroke-width", Integer.toString(EntitySvg.strokeWidth));
squareLinkLine.setAttribute("id", lineIdString);
defsNode.appendChild(squareLinkLine);
addedRelationLine = true;
// break;
}
groupNode.appendChild(defsNode);
if (addedRelationLine) {
// insert the node that uses the above definition
addUseNode(graphPanel.doc, graphPanel.svgNameSpace, groupNode, lineIdString);
// add the relation label
if (lineLabel != null) {
Element labelText = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "text");
labelText.setAttribute("text-anchor", "middle");
// labelText.setAttribute("x", Integer.toString(labelX));
// labelText.setAttribute("y", Integer.toString(labelY));
if (lineColour != null) {
labelText.setAttribute("fill", lineColour);
} else {
labelText.setAttribute("fill", "blue");
}
labelText.setAttribute("stroke-width", "0");
labelText.setAttribute("font-size", "14");
// labelText.setAttribute("transform", "rotate(45)");
// // todo: resolve issues with the USE node for the text
// Element textPath = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "textPath");
// textPath.setAttributeNS("http://www.w3.rg/1999/xlink", "xlink:href", "#" + lineIdString); // the xlink: of "xlink:href" is required for some svg viewers to render correctly
// textPath.setAttribute("startOffset", "50%");
// textPath.setAttribute("id", "relation" + relationLineIndex + "label");
// Text textNode = graphPanel.doc.createTextNode(lineLabel);
// textPath.appendChild(textNode);
// labelText.appendChild(textPath);
groupNode.appendChild(labelText);
}
}
relationGroupNode.appendChild(groupNode);
}
public void updateRelationLines(GraphPanel graphPanel, ArrayList<UniqueIdentifier> draggedNodeIds, int hSpacing, int vSpacing) {
// todo: if an entity is above its ancestor then this must be corrected, if the ancestor data is stored in the relationLine attributes then this would be a good place to correct this
Element relationGroup = graphPanel.doc.getElementById("RelationGroup");
for (Node currentChild = relationGroup.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) {
if ("g".equals(currentChild.getLocalName())) {
Node idAttrubite = currentChild.getAttributes().getNamedItem("id");
//System.out.println("idAttrubite: " + idAttrubite.getNodeValue());
try {
DataStoreSvg.GraphRelationData graphRelationData = new DataStoreSvg().getEntitiesForRelations(currentChild);
if (graphRelationData != null) {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// we update all the relation lines here, rather than cacluating which co parent (parentPoint) lines need updating when the current parent is moved //
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// if (draggedNodeIds.contains(graphRelationData.egoNodeId) || draggedNodeIds.contains(graphRelationData.alterNodeId)) {
// todo: update the relation lines
//System.out.println("needs update on: " + idAttrubite.getNodeValue());
String lineElementId = idAttrubite.getNodeValue() + "Line";
Element relationLineElement = graphPanel.doc.getElementById(lineElementId);
if (relationLineElement != null) {
//System.out.println("type: " + relationLineElement.getLocalName());
float[] egoSymbolPoint;
float[] alterSymbolPoint;
float[] parentPoint;
// int[] egoSymbolPoint = graphPanel.dataStoreSvg.graphData.getEntityLocation(graphRelationData.egoNodeId);
// int[] alterSymbolPoint = graphPanel.dataStoreSvg.graphData.getEntityLocation(graphRelationData.alterNodeId);
DataTypes.RelationType directedRelation = graphRelationData.relationType;
// the relation lines are already directed so there is no need to make then unidirectional here
egoSymbolPoint = graphPanel.entitySvg.getEntityLocation(graphRelationData.egoNodeId);
alterSymbolPoint = graphPanel.entitySvg.getEntityLocation(graphRelationData.alterNodeId);
parentPoint = graphPanel.entitySvg.getAverageParentLocation(graphRelationData.egoNodeId);
float egoX = egoSymbolPoint[0];
float egoY = egoSymbolPoint[1];
float alterX = alterSymbolPoint[0];
float alterY = alterSymbolPoint[1];
// SVGRect egoSymbolRect = new EntitySvg().getEntityLocation(doc, graphRelationData.egoNodeId);
// SVGRect alterSymbolRect = new EntitySvg().getEntityLocation(doc, graphRelationData.alterNodeId);
//
// float egoX = egoSymbolRect.getX() + egoSymbolRect.getWidth() / 2;
// float egoY = egoSymbolRect.getY() + egoSymbolRect.getHeight() / 2;
// float alterX = alterSymbolRect.getX() + alterSymbolRect.getWidth() / 2;
// float alterY = alterSymbolRect.getY() + alterSymbolRect.getHeight() / 2;
if ("polyline".equals(relationLineElement.getLocalName())) {
//System.out.println("polyline to update: " + lineElementId);
setPolylinePointsAttribute(graphPanel.lineLookUpTable, lineElementId, relationLineElement, directedRelation, vSpacing, egoX, egoY, alterX, alterY, parentPoint);
}
if ("path".equals(relationLineElement.getLocalName())) {
//System.out.println("path to update: " + relationLineElement.getLocalName());
setPathPointsAttribute(relationLineElement, directedRelation, hSpacing, vSpacing, egoX, egoY, alterX, alterY);
}
addUseNode(graphPanel.doc, graphPanel.svgNameSpace, (Element) currentChild, lineElementId);
updateLabelNode(graphPanel.doc, graphPanel.svgNameSpace, lineElementId, idAttrubite.getNodeValue());
}
}
} catch (IdentifierException exception) {
// GuiHelper.linorgBugCatcher.logError(exception);
dialogHandler.addMessageDialogToQueue("Failed to read related entities, sanguine lines might be incorrect", "Update Sanguine Lines");
}
}
}
}
// new RelationSvg().addTestNode(doc, (Element) relationLineElement.getParentNode().getParentNode(), svgNameSpace);
// public void addTestNode(SVGDocument doc, Element addTarget, String svgNameSpace) {
// Element squareNode = doc.createElementNS(svgNameSpace, "rect");
// squareNode.setAttribute("x", "100");
// squareNode.setAttribute("y", "100");
// squareNode.setAttribute("width", "20");
// squareNode.setAttribute("height", "20");
// squareNode.setAttribute("fill", "green");
// squareNode.setAttribute("stroke", "black");
// squareNode.setAttribute("stroke-width", "2");
// addTarget.appendChild(squareNode);
// }
}
| desktop/src/main/java/nl/mpi/kinnate/svg/RelationSvg.java | package nl.mpi.kinnate.svg;
import java.awt.Point;
import nl.mpi.kinnate.kindata.EntityData;
import java.util.ArrayList;
import nl.mpi.arbil.util.MessageDialogHandler;
import nl.mpi.kinnate.kindata.DataTypes;
import nl.mpi.kinnate.kindata.EntityRelation;
import nl.mpi.kinnate.uniqueidentifiers.IdentifierException;
import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.w3c.dom.svg.SVGDocument;
/**
* Document : RelationSvg
* Created on : Mar 9, 2011, 3:21:16 PM
* Author : Peter Withers
*/
public class RelationSvg {
private MessageDialogHandler dialogHandler;
public RelationSvg(MessageDialogHandler dialogHandler) {
this.dialogHandler = dialogHandler;
}
private void addUseNode(SVGDocument doc, String svgNameSpace, Element targetGroup, String targetDefId) {
String useNodeId = targetDefId + "use";
Node useNodeOld = doc.getElementById(useNodeId);
if (useNodeOld != null) {
useNodeOld.getParentNode().removeChild(useNodeOld);
}
Element useNode = doc.createElementNS(svgNameSpace, "use");
useNode.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + targetDefId); // the xlink: of "xlink:href" is required for some svg viewers to render correctly
// useNode.setAttribute("href", "#" + lineIdString);
useNode.setAttribute("id", useNodeId);
targetGroup.appendChild(useNode);
}
private void updateLabelNode(SVGDocument doc, String svgNameSpace, String lineIdString, String targetRelationId) {
// remove and readd the text on path label so that it updates with the new path
String labelNodeId = targetRelationId + "label";
Node useNodeOld = doc.getElementById(labelNodeId);
if (useNodeOld != null) {
Node textParentNode = useNodeOld.getParentNode();
String labelText = useNodeOld.getTextContent();
useNodeOld.getParentNode().removeChild(useNodeOld);
Element textPath = doc.createElementNS(svgNameSpace, "textPath");
textPath.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + lineIdString); // the xlink: of "xlink:href" is required for some svg viewers to render correctly
textPath.setAttribute("startOffset", "50%");
textPath.setAttribute("id", labelNodeId);
Text textNode = doc.createTextNode(labelText);
textPath.appendChild(textNode);
textParentNode.appendChild(textPath);
}
}
private boolean oldFormatWarningShown = false;
protected void setPolylinePointsAttribute(LineLookUpTable lineLookUpTable, String lineIdString, Element targetNode, DataTypes.RelationType relationType, float vSpacing, float egoX, float egoY, float alterX, float alterY, float[] averageParentPassed) {
//float midY = (egoY + alterY) / 2;
// todo: Ticket #1064 when an entity is above one that it should be below the line should make a zigzag to indicate it
ArrayList<Point> initialPointsList = new ArrayList<Point>();
float[] averageParent = null;
float midSpacing = vSpacing / 2;
// float parentSpacing = 10;
float egoYmid;
float alterYmid;
float centerX = (egoX + alterX) / 2;
switch (relationType) {
case ancestor:
if (averageParentPassed == null) {
// if no parent location has been provided then just use the current parent
averageParent = new float[]{alterX, alterY};
} else {
// todo: this is filtering out the parent location for non ancestor relations, but it would be more efficient to no get the parent location unless required
averageParent = averageParentPassed;
}
egoYmid = egoY - midSpacing;
alterYmid = averageParent[1] + 30;
// alterYmid = alterY + midSpacing;
// egoYmid = alterYmid + 30;
centerX = (egoYmid < alterYmid) ? centerX : egoX;
centerX = (egoY < alterY && egoX == alterX) ? centerX - midSpacing : centerX;
break;
// float tempX = egoX;
// float tempY = egoY;
// egoX = alterX;
// egoY = alterY;
// alterX = tempX;
// alterY = tempY;
case descendant:
if (!oldFormatWarningShown) {
dialogHandler.addMessageDialogToQueue("This diagram needs to be updated, select recalculate diagram from the edit menu before continuing.", "Old or erroneous format detected");
oldFormatWarningShown = true;
}
// targetNode.getParentNode().getParentNode().getParentNode().getParentNode().removeChild(targetNode.getParentNode().getParentNode().getParentNode());
// throw new UnsupportedOperationException("in order to simplify section, the ancestor relations should be swapped so that ego is the parent");
return;
// throw new UnsupportedOperationException("in order to simplify section, the ancestor relations should be swapped so that ego is the parent");
// egoYmid = egoY + midSpacing;
// alterYmid = alterY - midSpacing;
// centerX = (egoYmid < alterYmid) ? alterX : centerX;
// centerX = (egoY > alterY && egoX == alterX) ? centerX - midSpacing : centerX;
// break;
case sibling:
egoYmid = egoY - midSpacing;
alterYmid = alterY - midSpacing;
centerX = (egoY < alterY) ? alterX : egoX;
centerX = (egoX == alterX) ? centerX - midSpacing : centerX;
break;
case union:
// float unionMid = (egoY > alterY) ? egoY : alterY;
egoYmid = egoY + 30;
alterYmid = alterY + 30;
centerX = (egoY < alterY) ? egoX : alterX;
centerX = (egoX == alterX) ? centerX - midSpacing : centerX;
break;
case affiliation:
case none:
default:
egoYmid = egoY;
alterYmid = alterY;
break;
}
// if (alterY == egoY) {
// // make sure that union lines go below the entities and sibling lines go above
// if (relationType == DataTypes.RelationType.sibling) {
// midY = alterY - vSpacing / 2;
// } else if (relationType == DataTypes.RelationType.union) {
// midY = alterY + vSpacing / 2;
// }
// }
initialPointsList.add(new Point((int) egoX, (int) egoY));
initialPointsList.add(new Point((int) egoX, (int) egoYmid));
if (averageParent != null) {
float averageParentX = averageParent[0];
// float minParentY = averageParent[1];
initialPointsList.add(new Point((int) averageParentX, (int) egoYmid));
initialPointsList.add(new Point((int) averageParentX, (int) alterYmid));
} else {
initialPointsList.add(new Point((int) centerX, (int) egoYmid));
initialPointsList.add(new Point((int) centerX, (int) alterYmid));
}
initialPointsList.add(new Point((int) alterX, (int) alterYmid));
initialPointsList.add(new Point((int) alterX, (int) alterY));
Point[] adjustedPointsList;
if (lineLookUpTable != null) {
// this version is used when the relations are drawn on the diagram
// or when an entity is dragged before the diagram is redrawn in the case of a reloaded from disk diagram (this case is sub optimal in that on first load the loops will not be drawn)
adjustedPointsList = lineLookUpTable.adjustLineToObstructions(lineIdString, initialPointsList);
} else {
// this version is used when the relation drag handles are used
adjustedPointsList = initialPointsList.toArray(new Point[]{});
}
StringBuilder stringBuilder = new StringBuilder();
for (Point currentPoint : adjustedPointsList) {
stringBuilder.append(currentPoint.x);
stringBuilder.append(",");
stringBuilder.append(currentPoint.y);
stringBuilder.append(" ");
}
targetNode.setAttribute("points", stringBuilder.toString());
}
protected void setPathPointsAttribute(Element targetNode, DataTypes.RelationType relationType, DataTypes.RelationLineType relationLineType, float hSpacing, float vSpacing, float egoX, float egoY, float alterX, float alterY) {
float fromBezX;
float fromBezY;
float toBezX;
float toBezY;
if ((egoX > alterX && egoY < alterY) || (egoX > alterX && egoY > alterY)) {
// prevent the label on the line from rendering upside down
float tempX = alterX;
float tempY = alterY;
alterX = egoX;
alterY = egoY;
egoX = tempX;
egoY = tempY;
}
if (relationLineType == DataTypes.RelationLineType.verticalCurve) {
fromBezX = egoX;
fromBezY = alterY;
toBezX = alterX;
toBezY = egoY;
// todo: update the bezier positions similar to in the follwing else statement
if (1 / (egoY - alterY) < vSpacing) {
fromBezX = egoX;
fromBezY = alterY - vSpacing / 2;
toBezX = alterX;
toBezY = egoY - vSpacing / 2;
}
} else {
fromBezX = alterX;
fromBezY = egoY;
toBezX = egoX;
toBezY = alterY;
// todo: if the nodes are almost in align then this test fails and it should insted check for proximity not equality
// System.out.println(1 / (egoX - alterX));
// if (1 / (egoX - alterX) < vSpacing) {
if (egoX > alterX) {
if (egoX - alterX < hSpacing / 4) {
fromBezX = egoX - hSpacing / 4;
toBezX = alterX - hSpacing / 4;
} else {
fromBezX = (egoX - alterX) / 2 + alterX;
toBezX = (egoX - alterX) / 2 + alterX;
}
} else {
if (alterX - egoX < hSpacing / 4) {
fromBezX = egoX + hSpacing / 4;
toBezX = alterX + hSpacing / 4;
} else {
fromBezX = (alterX - egoX) / 2 + egoX;
toBezX = (alterX - egoX) / 2 + egoX;
}
}
}
targetNode.setAttribute("d", "M " + egoX + "," + egoY + " C " + fromBezX + "," + fromBezY + " " + toBezX + "," + toBezY + " " + alterX + "," + alterY);
}
public boolean hasCommonParent(EntityData currentNode, EntityRelation graphLinkNode) {
if (graphLinkNode.relationType == DataTypes.RelationType.sibling) {
for (EntityRelation altersRelation : graphLinkNode.getAlterNode().getDistinctRelateNodes()) {
if (altersRelation.relationType == DataTypes.RelationType.ancestor) {
for (EntityRelation egosRelation : currentNode.getDistinctRelateNodes()) {
if (egosRelation.relationType == DataTypes.RelationType.ancestor) {
if (altersRelation.alterUniqueIdentifier.equals(egosRelation.alterUniqueIdentifier)) {
if (altersRelation.getAlterNode().isVisible) {
return true;
}
}
}
}
}
}
}
return false;
}
// private Float getCommonParentMaxY(EntitySvg entitySvg, EntityData currentNode, EntityRelation graphLinkNode) {
// if (graphLinkNode.relationType == DataTypes.RelationType.sibling) {
// Float maxY = null;
// ArrayList<Float> commonParentY = new ArrayList<Float>();
// for (EntityRelation altersRelation : graphLinkNode.getAlterNode().getDistinctRelateNodes()) {
// if (altersRelation.relationType == DataTypes.RelationType.ancestor) {
// for (EntityRelation egosRelation : currentNode.getDistinctRelateNodes()) {
// if (egosRelation.relationType == DataTypes.RelationType.ancestor) {
// if (altersRelation.alterUniqueIdentifier.equals(egosRelation.alterUniqueIdentifier)) {
// float parentY = entitySvg.getEntityLocation(egosRelation.alterUniqueIdentifier)[1];
// maxY = parentY > maxY ? parentY : maxY;
// }
// }
// }
// }
// }
// return maxY;
// } else {
// return null;
// }
//
// }
protected void insertRelation(GraphPanel graphPanel, Element relationGroupNode, EntityData leftEntity, EntityData rightEntity, DataTypes.RelationType directedRelation, DataTypes.RelationLineType relationLineType, String lineColour, String lineLabel, int hSpacing, int vSpacing) {
float[] egoSymbolPoint;
float[] alterSymbolPoint;
float[] parentPoint;
// the ancestral relations should already be unidirectional and duplicates should have been removed
egoSymbolPoint = graphPanel.entitySvg.getEntityLocation(leftEntity.getUniqueIdentifier());
alterSymbolPoint = graphPanel.entitySvg.getEntityLocation(rightEntity.getUniqueIdentifier());
parentPoint = graphPanel.entitySvg.getAverageParentLocation(leftEntity);
int relationLineIndex = relationGroupNode.getChildNodes().getLength();
Element groupNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "g");
groupNode.setAttribute("id", "relation" + relationLineIndex);
Element defsNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "defs");
String lineIdString = "relation" + relationLineIndex + "Line";
new DataStoreSvg().storeRelationParameters(graphPanel.doc, groupNode, directedRelation, relationLineType, leftEntity.getUniqueIdentifier(), rightEntity.getUniqueIdentifier());
// set the line end points
// int[] egoSymbolPoint = graphPanel.dataStoreSvg.graphData.getEntityLocation(currentNode.getUniqueIdentifier());
// int[] alterSymbolPoint = graphPanel.dataStoreSvg.graphData.getEntityLocation(graphLinkNode.getAlterNode().getUniqueIdentifier());
// float fromX = (currentNode.getxPos()); // * hSpacing + hSpacing
// float fromY = (currentNode.getyPos()); // * vSpacing + vSpacing
// float toX = (graphLinkNode.getAlterNode().getxPos()); // * hSpacing + hSpacing
// float toY = (graphLinkNode.getAlterNode().getyPos()); // * vSpacing + vSpacing
float fromX = (egoSymbolPoint[0]); // * hSpacing + hSpacing
float fromY = (egoSymbolPoint[1]); // * vSpacing + vSpacing
float toX = (alterSymbolPoint[0]); // * hSpacing + hSpacing
float toY = (alterSymbolPoint[1]); // * vSpacing + vSpacing
boolean addedRelationLine = false;
switch (relationLineType) {
case kinTermLine:
// this case uses the following case
case verticalCurve:
// todo: groupNode.setAttribute("id", );
// System.out.println("link: " + graphLinkNode.linkedNode.xPos + ":" + graphLinkNode.linkedNode.yPos);
//
//// <line id="_15" transform="translate(146.0,112.0)" x1="0" y1="0" x2="100" y2="100" ="black" stroke-width="1"/>
// Element linkLine = doc.createElementNS(svgNS, "line");
// linkLine.setAttribute("x1", Integer.toString(currentNode.xPos * hSpacing + hSpacing));
// linkLine.setAttribute("y1", Integer.toString(currentNode.yPos * vSpacing + vSpacing));
//
// linkLine.setAttribute("x2", Integer.toString(graphLinkNode.linkedNode.xPos * hSpacing + hSpacing));
// linkLine.setAttribute("y2", Integer.toString(graphLinkNode.linkedNode.yPos * vSpacing + vSpacing));
// linkLine.setAttribute("stroke", "black");
// linkLine.setAttribute("stroke-width", "1");
// // Attach the rectangle to the root 'svg' element.
// svgRoot.appendChild(linkLine);
//System.out.println("link: " + graphLinkNode.getAlterNode().xPos + ":" + graphLinkNode.getAlterNode().yPos);
// <line id="_15" transform="translate(146.0,112.0)" x1="0" y1="0" x2="100" y2="100" ="black" stroke-width="1"/>
Element linkLine = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "path");
setPathPointsAttribute(linkLine, directedRelation, relationLineType, hSpacing, vSpacing, fromX, fromY, toX, toY);
// linkLine.setAttribute("x1", );
// linkLine.setAttribute("y1", );
//
// linkLine.setAttribute("x2", );
linkLine.setAttribute("fill", "none");
if (lineColour != null) {
linkLine.setAttribute("stroke", lineColour);
} else {
linkLine.setAttribute("stroke", "blue");
}
linkLine.setAttribute("stroke-width", Integer.toString(EntitySvg.strokeWidth));
linkLine.setAttribute("id", lineIdString);
defsNode.appendChild(linkLine);
addedRelationLine = true;
break;
case sanguineLine:
// Element squareLinkLine = doc.createElement("line");
// squareLinkLine.setAttribute("x1", Integer.toString(currentNode.xPos * hSpacing + hSpacing));
// squareLinkLine.setAttribute("y1", Integer.toString(currentNode.yPos * vSpacing + vSpacing));
//
// squareLinkLine.setAttribute("x2", Integer.toString(graphLinkNode.linkedNode.xPos * hSpacing + hSpacing));
// squareLinkLine.setAttribute("y2", Integer.toString(graphLinkNode.linkedNode.yPos * vSpacing + vSpacing));
// squareLinkLine.setAttribute("stroke", "grey");
// squareLinkLine.setAttribute("stroke-width", Integer.toString(strokeWidth));
Element squareLinkLine = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "polyline");
setPolylinePointsAttribute(graphPanel.lineLookUpTable, lineIdString, squareLinkLine, directedRelation, vSpacing, fromX, fromY, toX, toY, parentPoint);
squareLinkLine.setAttribute("fill", "none");
squareLinkLine.setAttribute("stroke", "grey");
squareLinkLine.setAttribute("stroke-width", Integer.toString(EntitySvg.strokeWidth));
squareLinkLine.setAttribute("id", lineIdString);
defsNode.appendChild(squareLinkLine);
addedRelationLine = true;
break;
}
groupNode.appendChild(defsNode);
if (addedRelationLine) {
// insert the node that uses the above definition
addUseNode(graphPanel.doc, graphPanel.svgNameSpace, groupNode, lineIdString);
// add the relation label
if (lineLabel != null) {
Element labelText = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "text");
labelText.setAttribute("text-anchor", "middle");
// labelText.setAttribute("x", Integer.toString(labelX));
// labelText.setAttribute("y", Integer.toString(labelY));
if (lineColour != null) {
labelText.setAttribute("fill", lineColour);
} else {
labelText.setAttribute("fill", "blue");
}
labelText.setAttribute("stroke-width", "0");
labelText.setAttribute("font-size", "14");
// labelText.setAttribute("transform", "rotate(45)");
// // todo: resolve issues with the USE node for the text
// Element textPath = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "textPath");
// textPath.setAttributeNS("http://www.w3.rg/1999/xlink", "xlink:href", "#" + lineIdString); // the xlink: of "xlink:href" is required for some svg viewers to render correctly
// textPath.setAttribute("startOffset", "50%");
// textPath.setAttribute("id", "relation" + relationLineIndex + "label");
// Text textNode = graphPanel.doc.createTextNode(lineLabel);
// textPath.appendChild(textNode);
// labelText.appendChild(textPath);
groupNode.appendChild(labelText);
}
}
relationGroupNode.appendChild(groupNode);
}
public void updateRelationLines(GraphPanel graphPanel, ArrayList<UniqueIdentifier> draggedNodeIds, int hSpacing, int vSpacing) {
// todo: if an entity is above its ancestor then this must be corrected, if the ancestor data is stored in the relationLine attributes then this would be a good place to correct this
Element relationGroup = graphPanel.doc.getElementById("RelationGroup");
for (Node currentChild = relationGroup.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) {
if ("g".equals(currentChild.getLocalName())) {
Node idAttrubite = currentChild.getAttributes().getNamedItem("id");
//System.out.println("idAttrubite: " + idAttrubite.getNodeValue());
try {
DataStoreSvg.GraphRelationData graphRelationData = new DataStoreSvg().getEntitiesForRelations(currentChild);
if (graphRelationData != null) {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// we update all the relation lines here, rather than cacluating which co parent (parentPoint) lines need updating when the current parent is moved //
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// if (draggedNodeIds.contains(graphRelationData.egoNodeId) || draggedNodeIds.contains(graphRelationData.alterNodeId)) {
// todo: update the relation lines
//System.out.println("needs update on: " + idAttrubite.getNodeValue());
String lineElementId = idAttrubite.getNodeValue() + "Line";
Element relationLineElement = graphPanel.doc.getElementById(lineElementId);
//System.out.println("type: " + relationLineElement.getLocalName());
float[] egoSymbolPoint;
float[] alterSymbolPoint;
float[] parentPoint;
// int[] egoSymbolPoint = graphPanel.dataStoreSvg.graphData.getEntityLocation(graphRelationData.egoNodeId);
// int[] alterSymbolPoint = graphPanel.dataStoreSvg.graphData.getEntityLocation(graphRelationData.alterNodeId);
DataTypes.RelationType directedRelation = graphRelationData.relationType;
// the relation lines are already directed so there is no need to make then unidirectional here
egoSymbolPoint = graphPanel.entitySvg.getEntityLocation(graphRelationData.egoNodeId);
alterSymbolPoint = graphPanel.entitySvg.getEntityLocation(graphRelationData.alterNodeId);
parentPoint = graphPanel.entitySvg.getAverageParentLocation(graphRelationData.egoNodeId);
float egoX = egoSymbolPoint[0];
float egoY = egoSymbolPoint[1];
float alterX = alterSymbolPoint[0];
float alterY = alterSymbolPoint[1];
// SVGRect egoSymbolRect = new EntitySvg().getEntityLocation(doc, graphRelationData.egoNodeId);
// SVGRect alterSymbolRect = new EntitySvg().getEntityLocation(doc, graphRelationData.alterNodeId);
//
// float egoX = egoSymbolRect.getX() + egoSymbolRect.getWidth() / 2;
// float egoY = egoSymbolRect.getY() + egoSymbolRect.getHeight() / 2;
// float alterX = alterSymbolRect.getX() + alterSymbolRect.getWidth() / 2;
// float alterY = alterSymbolRect.getY() + alterSymbolRect.getHeight() / 2;
if ("polyline".equals(relationLineElement.getLocalName())) {
//System.out.println("polyline to update: " + lineElementId);
setPolylinePointsAttribute(graphPanel.lineLookUpTable, lineElementId, relationLineElement, directedRelation, vSpacing, egoX, egoY, alterX, alterY, parentPoint);
}
if ("path".equals(relationLineElement.getLocalName())) {
//System.out.println("path to update: " + relationLineElement.getLocalName());
setPathPointsAttribute(relationLineElement, directedRelation, graphRelationData.relationLineType, hSpacing, vSpacing, egoX, egoY, alterX, alterY);
}
addUseNode(graphPanel.doc, graphPanel.svgNameSpace, (Element) currentChild, lineElementId);
updateLabelNode(graphPanel.doc, graphPanel.svgNameSpace, lineElementId, idAttrubite.getNodeValue());
// }
}
} catch (IdentifierException exception) {
// GuiHelper.linorgBugCatcher.logError(exception);
dialogHandler.addMessageDialogToQueue("Failed to read related entities, sanguine lines might be incorrect", "Update Sanguine Lines");
}
}
}
}
// new RelationSvg().addTestNode(doc, (Element) relationLineElement.getParentNode().getParentNode(), svgNameSpace);
// public void addTestNode(SVGDocument doc, Element addTarget, String svgNameSpace) {
// Element squareNode = doc.createElementNS(svgNameSpace, "rect");
// squareNode.setAttribute("x", "100");
// squareNode.setAttribute("y", "100");
// squareNode.setAttribute("width", "20");
// squareNode.setAttribute("height", "20");
// squareNode.setAttribute("fill", "green");
// squareNode.setAttribute("stroke", "black");
// squareNode.setAttribute("stroke-width", "2");
// addTarget.appendChild(squareNode);
// }
}
| Added a settings panel for the relation type definitions.
Added the relation type definitions to the data stored in the svg.
Added the DCR to the relation types and its settings UI.
Restructured the relation type data structure to suit the recent changes.
| desktop/src/main/java/nl/mpi/kinnate/svg/RelationSvg.java | Added a settings panel for the relation type definitions. Added the relation type definitions to the data stored in the svg. Added the DCR to the relation types and its settings UI. Restructured the relation type data structure to suit the recent changes. | <ide><path>esktop/src/main/java/nl/mpi/kinnate/svg/RelationSvg.java
<ide> package nl.mpi.kinnate.svg;
<ide>
<ide> import java.awt.Point;
<del>import nl.mpi.kinnate.kindata.EntityData;
<ide> import java.util.ArrayList;
<ide> import nl.mpi.arbil.util.MessageDialogHandler;
<ide> import nl.mpi.kinnate.kindata.DataTypes;
<add>import nl.mpi.kinnate.kindata.EntityData;
<ide> import nl.mpi.kinnate.kindata.EntityRelation;
<ide> import nl.mpi.kinnate.uniqueidentifiers.IdentifierException;
<ide> import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier;
<ide> centerX = (egoY < alterY) ? egoX : alterX;
<ide> centerX = (egoX == alterX) ? centerX - midSpacing : centerX;
<ide> break;
<del> case affiliation:
<del> case none:
<add>// case affiliation:
<add>// case none:
<ide> default:
<ide> egoYmid = egoY;
<ide> alterYmid = alterY;
<ide> targetNode.setAttribute("points", stringBuilder.toString());
<ide> }
<ide>
<del> protected void setPathPointsAttribute(Element targetNode, DataTypes.RelationType relationType, DataTypes.RelationLineType relationLineType, float hSpacing, float vSpacing, float egoX, float egoY, float alterX, float alterY) {
<add> protected void setPathPointsAttribute(Element targetNode, DataTypes.RelationType relationType, float hSpacing, float vSpacing, float egoX, float egoY, float alterX, float alterY) {
<ide> float fromBezX;
<ide> float fromBezY;
<ide> float toBezX;
<ide> egoX = tempX;
<ide> egoY = tempY;
<ide> }
<del> if (relationLineType == DataTypes.RelationLineType.verticalCurve) {
<add> if (relationType == DataTypes.RelationType.verticalCurve) {
<ide> fromBezX = egoX;
<ide> fromBezY = alterY;
<ide> toBezX = alterX;
<ide> // }
<ide> //
<ide> // }
<del> protected void insertRelation(GraphPanel graphPanel, Element relationGroupNode, EntityData leftEntity, EntityData rightEntity, DataTypes.RelationType directedRelation, DataTypes.RelationLineType relationLineType, String lineColour, String lineLabel, int hSpacing, int vSpacing) {
<add> protected void insertRelation(GraphPanel graphPanel, Element relationGroupNode, EntityData leftEntity, EntityData rightEntity, DataTypes.RelationType directedRelation, String lineColour, String lineLabel, int hSpacing, int vSpacing) {
<ide> float[] egoSymbolPoint;
<ide> float[] alterSymbolPoint;
<ide> float[] parentPoint;
<ide> groupNode.setAttribute("id", "relation" + relationLineIndex);
<ide> Element defsNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "defs");
<ide> String lineIdString = "relation" + relationLineIndex + "Line";
<del> new DataStoreSvg().storeRelationParameters(graphPanel.doc, groupNode, directedRelation, relationLineType, leftEntity.getUniqueIdentifier(), rightEntity.getUniqueIdentifier());
<add> new DataStoreSvg().storeRelationParameters(graphPanel.doc, groupNode, directedRelation, leftEntity.getUniqueIdentifier(), rightEntity.getUniqueIdentifier());
<ide> // set the line end points
<ide> // int[] egoSymbolPoint = graphPanel.dataStoreSvg.graphData.getEntityLocation(currentNode.getUniqueIdentifier());
<ide> // int[] alterSymbolPoint = graphPanel.dataStoreSvg.graphData.getEntityLocation(graphLinkNode.getAlterNode().getUniqueIdentifier());
<ide> float toY = (alterSymbolPoint[1]); // * vSpacing + vSpacing
<ide>
<ide> boolean addedRelationLine = false;
<del> switch (relationLineType) {
<del> case kinTermLine:
<add> if (!DataTypes.isSanguinLine(directedRelation)) {
<add>// case kinTermLine:
<ide> // this case uses the following case
<del> case verticalCurve:
<del> // todo: groupNode.setAttribute("id", );
<del> // System.out.println("link: " + graphLinkNode.linkedNode.xPos + ":" + graphLinkNode.linkedNode.yPos);
<del> //
<del> //// <line id="_15" transform="translate(146.0,112.0)" x1="0" y1="0" x2="100" y2="100" ="black" stroke-width="1"/>
<del> // Element linkLine = doc.createElementNS(svgNS, "line");
<del> // linkLine.setAttribute("x1", Integer.toString(currentNode.xPos * hSpacing + hSpacing));
<del> // linkLine.setAttribute("y1", Integer.toString(currentNode.yPos * vSpacing + vSpacing));
<del> //
<del> // linkLine.setAttribute("x2", Integer.toString(graphLinkNode.linkedNode.xPos * hSpacing + hSpacing));
<del> // linkLine.setAttribute("y2", Integer.toString(graphLinkNode.linkedNode.yPos * vSpacing + vSpacing));
<del> // linkLine.setAttribute("stroke", "black");
<del> // linkLine.setAttribute("stroke-width", "1");
<del> // // Attach the rectangle to the root 'svg' element.
<del> // svgRoot.appendChild(linkLine);
<del> //System.out.println("link: " + graphLinkNode.getAlterNode().xPos + ":" + graphLinkNode.getAlterNode().yPos);
<del>
<del> // <line id="_15" transform="translate(146.0,112.0)" x1="0" y1="0" x2="100" y2="100" ="black" stroke-width="1"/>
<del> Element linkLine = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "path");
<del>
<del> setPathPointsAttribute(linkLine, directedRelation, relationLineType, hSpacing, vSpacing, fromX, fromY, toX, toY);
<del> // linkLine.setAttribute("x1", );
<del> // linkLine.setAttribute("y1", );
<del> //
<del> // linkLine.setAttribute("x2", );
<del> linkLine.setAttribute("fill", "none");
<del> if (lineColour != null) {
<del> linkLine.setAttribute("stroke", lineColour);
<del> } else {
<del> linkLine.setAttribute("stroke", "blue");
<del> }
<del> linkLine.setAttribute("stroke-width", Integer.toString(EntitySvg.strokeWidth));
<del> linkLine.setAttribute("id", lineIdString);
<del> defsNode.appendChild(linkLine);
<del> addedRelationLine = true;
<del> break;
<del> case sanguineLine:
<del> // Element squareLinkLine = doc.createElement("line");
<del> // squareLinkLine.setAttribute("x1", Integer.toString(currentNode.xPos * hSpacing + hSpacing));
<del> // squareLinkLine.setAttribute("y1", Integer.toString(currentNode.yPos * vSpacing + vSpacing));
<del> //
<del> // squareLinkLine.setAttribute("x2", Integer.toString(graphLinkNode.linkedNode.xPos * hSpacing + hSpacing));
<del> // squareLinkLine.setAttribute("y2", Integer.toString(graphLinkNode.linkedNode.yPos * vSpacing + vSpacing));
<del> // squareLinkLine.setAttribute("stroke", "grey");
<del> // squareLinkLine.setAttribute("stroke-width", Integer.toString(strokeWidth));
<del> Element squareLinkLine = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "polyline");
<del>
<del> setPolylinePointsAttribute(graphPanel.lineLookUpTable, lineIdString, squareLinkLine, directedRelation, vSpacing, fromX, fromY, toX, toY, parentPoint);
<del>
<del> squareLinkLine.setAttribute("fill", "none");
<del> squareLinkLine.setAttribute("stroke", "grey");
<del> squareLinkLine.setAttribute("stroke-width", Integer.toString(EntitySvg.strokeWidth));
<del> squareLinkLine.setAttribute("id", lineIdString);
<del> defsNode.appendChild(squareLinkLine);
<del> addedRelationLine = true;
<del> break;
<add>// case verticalCurve:
<add> // todo: groupNode.setAttribute("id", );
<add> // System.out.println("link: " + graphLinkNode.linkedNode.xPos + ":" + graphLinkNode.linkedNode.yPos);
<add> //
<add> //// <line id="_15" transform="translate(146.0,112.0)" x1="0" y1="0" x2="100" y2="100" ="black" stroke-width="1"/>
<add> // Element linkLine = doc.createElementNS(svgNS, "line");
<add> // linkLine.setAttribute("x1", Integer.toString(currentNode.xPos * hSpacing + hSpacing));
<add> // linkLine.setAttribute("y1", Integer.toString(currentNode.yPos * vSpacing + vSpacing));
<add> //
<add> // linkLine.setAttribute("x2", Integer.toString(graphLinkNode.linkedNode.xPos * hSpacing + hSpacing));
<add> // linkLine.setAttribute("y2", Integer.toString(graphLinkNode.linkedNode.yPos * vSpacing + vSpacing));
<add> // linkLine.setAttribute("stroke", "black");
<add> // linkLine.setAttribute("stroke-width", "1");
<add> // // Attach the rectangle to the root 'svg' element.
<add> // svgRoot.appendChild(linkLine);
<add> //System.out.println("link: " + graphLinkNode.getAlterNode().xPos + ":" + graphLinkNode.getAlterNode().yPos);
<add>
<add> // <line id="_15" transform="translate(146.0,112.0)" x1="0" y1="0" x2="100" y2="100" ="black" stroke-width="1"/>
<add> Element linkLine = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "path");
<add>
<add> setPathPointsAttribute(linkLine, directedRelation, hSpacing, vSpacing, fromX, fromY, toX, toY);
<add> // linkLine.setAttribute("x1", );
<add> // linkLine.setAttribute("y1", );
<add> //
<add> // linkLine.setAttribute("x2", );
<add> linkLine.setAttribute("fill", "none");
<add> if (lineColour != null) {
<add> linkLine.setAttribute("stroke", lineColour);
<add> } else {
<add> linkLine.setAttribute("stroke", "blue");
<add> }
<add> linkLine.setAttribute("stroke-width", Integer.toString(EntitySvg.strokeWidth));
<add> linkLine.setAttribute("id", lineIdString);
<add> defsNode.appendChild(linkLine);
<add> addedRelationLine = true;
<add>// break;
<add> } else {
<add>// case sanguineLine:
<add> // Element squareLinkLine = doc.createElement("line");
<add> // squareLinkLine.setAttribute("x1", Integer.toString(currentNode.xPos * hSpacing + hSpacing));
<add> // squareLinkLine.setAttribute("y1", Integer.toString(currentNode.yPos * vSpacing + vSpacing));
<add> //
<add> // squareLinkLine.setAttribute("x2", Integer.toString(graphLinkNode.linkedNode.xPos * hSpacing + hSpacing));
<add> // squareLinkLine.setAttribute("y2", Integer.toString(graphLinkNode.linkedNode.yPos * vSpacing + vSpacing));
<add> // squareLinkLine.setAttribute("stroke", "grey");
<add> // squareLinkLine.setAttribute("stroke-width", Integer.toString(strokeWidth));
<add> Element squareLinkLine = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "polyline");
<add>
<add> setPolylinePointsAttribute(graphPanel.lineLookUpTable, lineIdString, squareLinkLine, directedRelation, vSpacing, fromX, fromY, toX, toY, parentPoint);
<add>
<add> squareLinkLine.setAttribute("fill", "none");
<add> squareLinkLine.setAttribute("stroke", "grey");
<add> squareLinkLine.setAttribute("stroke-width", Integer.toString(EntitySvg.strokeWidth));
<add> squareLinkLine.setAttribute("id", lineIdString);
<add> defsNode.appendChild(squareLinkLine);
<add> addedRelationLine = true;
<add>// break;
<ide> }
<ide> groupNode.appendChild(defsNode);
<ide>
<ide> //System.out.println("needs update on: " + idAttrubite.getNodeValue());
<ide> String lineElementId = idAttrubite.getNodeValue() + "Line";
<ide> Element relationLineElement = graphPanel.doc.getElementById(lineElementId);
<del> //System.out.println("type: " + relationLineElement.getLocalName());
<del> float[] egoSymbolPoint;
<del> float[] alterSymbolPoint;
<del> float[] parentPoint;
<add> if (relationLineElement != null) {
<add> //System.out.println("type: " + relationLineElement.getLocalName());
<add> float[] egoSymbolPoint;
<add> float[] alterSymbolPoint;
<add> float[] parentPoint;
<ide> // int[] egoSymbolPoint = graphPanel.dataStoreSvg.graphData.getEntityLocation(graphRelationData.egoNodeId);
<ide> // int[] alterSymbolPoint = graphPanel.dataStoreSvg.graphData.getEntityLocation(graphRelationData.alterNodeId);
<del> DataTypes.RelationType directedRelation = graphRelationData.relationType;
<del> // the relation lines are already directed so there is no need to make then unidirectional here
<del> egoSymbolPoint = graphPanel.entitySvg.getEntityLocation(graphRelationData.egoNodeId);
<del> alterSymbolPoint = graphPanel.entitySvg.getEntityLocation(graphRelationData.alterNodeId);
<del> parentPoint = graphPanel.entitySvg.getAverageParentLocation(graphRelationData.egoNodeId);
<del>
<del> float egoX = egoSymbolPoint[0];
<del> float egoY = egoSymbolPoint[1];
<del> float alterX = alterSymbolPoint[0];
<del> float alterY = alterSymbolPoint[1];
<add> DataTypes.RelationType directedRelation = graphRelationData.relationType;
<add> // the relation lines are already directed so there is no need to make then unidirectional here
<add> egoSymbolPoint = graphPanel.entitySvg.getEntityLocation(graphRelationData.egoNodeId);
<add> alterSymbolPoint = graphPanel.entitySvg.getEntityLocation(graphRelationData.alterNodeId);
<add> parentPoint = graphPanel.entitySvg.getAverageParentLocation(graphRelationData.egoNodeId);
<add>
<add> float egoX = egoSymbolPoint[0];
<add> float egoY = egoSymbolPoint[1];
<add> float alterX = alterSymbolPoint[0];
<add> float alterY = alterSymbolPoint[1];
<ide>
<ide> // SVGRect egoSymbolRect = new EntitySvg().getEntityLocation(doc, graphRelationData.egoNodeId);
<ide> // SVGRect alterSymbolRect = new EntitySvg().getEntityLocation(doc, graphRelationData.alterNodeId);
<ide> // float alterX = alterSymbolRect.getX() + alterSymbolRect.getWidth() / 2;
<ide> // float alterY = alterSymbolRect.getY() + alterSymbolRect.getHeight() / 2;
<ide>
<del> if ("polyline".equals(relationLineElement.getLocalName())) {
<del> //System.out.println("polyline to update: " + lineElementId);
<del> setPolylinePointsAttribute(graphPanel.lineLookUpTable, lineElementId, relationLineElement, directedRelation, vSpacing, egoX, egoY, alterX, alterY, parentPoint);
<add> if ("polyline".equals(relationLineElement.getLocalName())) {
<add> //System.out.println("polyline to update: " + lineElementId);
<add> setPolylinePointsAttribute(graphPanel.lineLookUpTable, lineElementId, relationLineElement, directedRelation, vSpacing, egoX, egoY, alterX, alterY, parentPoint);
<add> }
<add> if ("path".equals(relationLineElement.getLocalName())) {
<add> //System.out.println("path to update: " + relationLineElement.getLocalName());
<add> setPathPointsAttribute(relationLineElement, directedRelation, hSpacing, vSpacing, egoX, egoY, alterX, alterY);
<add> }
<add> addUseNode(graphPanel.doc, graphPanel.svgNameSpace, (Element) currentChild, lineElementId);
<add> updateLabelNode(graphPanel.doc, graphPanel.svgNameSpace, lineElementId, idAttrubite.getNodeValue());
<ide> }
<del> if ("path".equals(relationLineElement.getLocalName())) {
<del> //System.out.println("path to update: " + relationLineElement.getLocalName());
<del> setPathPointsAttribute(relationLineElement, directedRelation, graphRelationData.relationLineType, hSpacing, vSpacing, egoX, egoY, alterX, alterY);
<del> }
<del> addUseNode(graphPanel.doc, graphPanel.svgNameSpace, (Element) currentChild, lineElementId);
<del> updateLabelNode(graphPanel.doc, graphPanel.svgNameSpace, lineElementId, idAttrubite.getNodeValue());
<del>// }
<ide> }
<ide> } catch (IdentifierException exception) {
<ide> // GuiHelper.linorgBugCatcher.logError(exception); |
|
Java | apache-2.0 | b7772ab53766863e36c93713beae8048dd69a456 | 0 | pfcoperez/crossdata,jjlopezm/crossdata,pfcoperez/crossdata,hdominguez1989/Crossdata,miguel0afd/crossdata,ccaballe/crossdata,gserranojc/Crossdata,hdominguez1989/Crossdata,luismcl/crossdata,Stratio/crossdata,miguel0afd/crossdata,pmadrigal/Crossdata,ccaballe/crossdata,darroyocazorla/crossdata,Stratio/crossdata,gserranojc/Crossdata,compae/Crossdata,pmadrigal/Crossdata,jjlopezm/crossdata,darroyocazorla/crossdata,luismcl/crossdata,compae/Crossdata | /*
* Stratio Meta
*
* Copyright (c) 2014, Stratio, All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under the terms of the
* GNU Lesser General Public License as published by the Free Software Foundation; either version
* 3.0 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library.
*/
package com.stratio.meta.core.statements;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import com.datastax.driver.core.ColumnMetadata;
import com.datastax.driver.core.Statement;
import com.datastax.driver.core.TableMetadata;
import com.datastax.driver.core.querybuilder.Clause;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
import com.datastax.driver.core.querybuilder.Select.Where;
import com.stratio.meta.common.result.CommandResult;
import com.stratio.meta.common.result.QueryResult;
import com.stratio.meta.common.result.Result;
import com.stratio.meta.core.engine.EngineConfig;
import com.stratio.meta.core.metadata.CustomIndexMetadata;
import com.stratio.meta.core.metadata.MetadataManager;
import com.stratio.meta.core.structures.GroupBy;
import com.stratio.meta.core.structures.GroupByFunction;
import com.stratio.meta.core.structures.IndexType;
import com.stratio.meta.core.structures.InnerJoin;
import com.stratio.meta.core.structures.OrderDirection;
import com.stratio.meta.core.structures.Ordering;
import com.stratio.meta.core.structures.Relation;
import com.stratio.meta.core.structures.RelationCompare;
import com.stratio.meta.core.structures.RelationIn;
import com.stratio.meta.core.structures.RelationToken;
import com.stratio.meta.core.structures.Selection;
import com.stratio.meta.core.structures.SelectionAsterisk;
import com.stratio.meta.core.structures.SelectionClause;
import com.stratio.meta.core.structures.SelectionList;
import com.stratio.meta.core.structures.SelectionSelector;
import com.stratio.meta.core.structures.SelectionSelectors;
import com.stratio.meta.core.structures.SelectorFunction;
import com.stratio.meta.core.structures.SelectorGroupBy;
import com.stratio.meta.core.structures.SelectorIdentifier;
import com.stratio.meta.core.structures.SelectorMeta;
import com.stratio.meta.core.structures.Term;
import com.stratio.meta.core.structures.WindowSelect;
import com.stratio.meta.core.structures.WindowTime;
import com.stratio.meta.core.utils.MetaPath;
import com.stratio.meta.core.utils.MetaStep;
import com.stratio.meta.core.utils.ParserUtils;
import com.stratio.meta.core.utils.Tree;
import com.stratio.streaming.api.IStratioStreamingAPI;
import com.stratio.streaming.commons.messages.ColumnNameTypeValue;
/**
* Class that models a {@code SELECT} statement from the META language.
*/
public class SelectStatement extends MetaStatement {
/**
* Maximum limit of rows to be retreived in a query.
*/
private static final int MAX_LIMIT = 10000;
/**
* The {@link com.stratio.meta.core.structures.SelectionClause} of the Select statement.
*/
private SelectionClause selectionClause = null;
/**
* The name of the target table.
*/
private final String tableName;
/**
* Whether a time window has been specified in the Select statement.
*/
private boolean windowInc = false;
/**
* The {@link com.stratio.meta.core.structures.WindowSelect} specified in the Select statement for
* streaming queries.
*/
private WindowSelect window = null;
/**
* Whether a JOIN clause has been specified.
*/
private boolean joinInc = false;
/**
* The {@link com.stratio.meta.core.structures.InnerJoin} clause.
*/
private InnerJoin join = null;
/**
* Whether the Select contains a WHERE clause.
*/
private boolean whereInc = false;
/**
* The list of {@link com.stratio.meta.core.structures.Relation} found in the WHERE clause.
*/
private List<Relation> where = null;
/**
* Whether an ORDER BY clause has been specified.
*/
private boolean orderInc = false;
/**
* The list of {@link com.stratio.meta.core.structures.Ordering} clauses.
*/
private List<Ordering> order = null;
/**
* Whether a GROUP BY clause has been specified.
*/
private boolean groupInc = false;
/**
* The {@link com.stratio.meta.core.structures.GroupBy} clause.
*/
private List<GroupBy> group = null;
/**
* Whether a LIMIT clause has been specified.
*/
private boolean limitInc = false;
/**
* The LIMIT in terms of the number of rows to be retrieved in the result of the SELECT statement.
*/
private int limit = 0;
/**
* Flag to disable complex analytic functions such as INNER JOIN.
*/
private boolean disableAnalytics = false;
// TODO: We should probably remove this an pass it as parameters.
/**
* The {@link com.stratio.meta.core.metadata.MetadataManager} used to retrieve table metadata
* during the validation process and the statement execution phase.
*/
private MetadataManager metadata = null;
/**
* The {@link com.datastax.driver.core.TableMetadata} associated with the table specified in the
* FROM of the Select statement.
*/
private TableMetadata tableMetadataFrom = null;
/**
* Map with the collection of {@link com.datastax.driver.core.ColumnMetadata} associated with the
* tables specified in the FROM and the INNER JOIN parts of the Select statement. A virtual table
* named {@code any} is used to match unqualified column names.
*/
private Map<String, Collection<ColumnMetadata>> columns = new HashMap<>();
private boolean streamMode = false;
/**
* Class logger.
*/
private static final Logger LOG = Logger.getLogger(SelectStatement.class);
private Map<String, String> fieldsAliasesMap;
/**
* Class constructor.
*
* @param tableName The name of the target table.
*/
public SelectStatement(String tableName) {
this.command = false;
if (tableName.contains(".")) {
String[] ksAndTablename = tableName.split("\\.");
this.setKeyspace(ksAndTablename[0]);
this.tableName = ksAndTablename[1];
} else {
this.tableName = tableName;
}
}
/**
* Class constructor.
*
* @param selectionClause The {@link com.stratio.meta.core.structures.SelectionClause} of the
* Select statement.
* @param tableName The name of the target table.
*/
public SelectStatement(SelectionClause selectionClause, String tableName) {
this(tableName);
this.selectionClause = selectionClause;
this.selectionClause.addTablename(this.tableName);
}
/**
* Get the name of the target table.
*
* @return The table name.
*/
public String getTableName() {
return tableName;
}
/**
* Get the {@link com.stratio.meta.core.structures.SelectionClause}.
*
* @return The selection clause.
*/
public SelectionClause getSelectionClause() {
return selectionClause;
}
/**
* Set the {@link com.stratio.meta.core.structures.SelectionClause} for selecting columns.
*
* @param selectionClause selection clause.
*/
public void setSelectionClause(SelectionClause selectionClause) {
this.selectionClause = selectionClause;
}
/**
* Set the {@link com.stratio.meta.core.structures.WindowSelect} for streaming queries.
*
* @param window The window.
*/
public void setWindow(WindowSelect window) {
this.windowInc = true;
this.window = window;
}
/**
* Get the Join clause.
*
* @return The Join or null if not set.
*/
public InnerJoin getJoin() {
return join;
}
/**
* Set the {@link com.stratio.meta.core.structures.InnerJoin} clause.
*
* @param join The join clause.
*/
public void setJoin(InnerJoin join) {
this.joinInc = true;
this.join = join;
}
/**
* Get the list of {@link Relation} in the where clause.
*
* @return The list of relations.
*/
public List<Relation> getWhere() {
return where;
}
/**
* Set the list of {@link Relation} in the where clause.
*
* @param where The list of relations.
*/
public void setWhere(List<Relation> where) {
this.whereInc = true;
this.where = where;
}
/**
* Set the {@link Ordering} in the ORDER BY clause.
*
* @param order The order.
*/
public void setOrder(List<Ordering> order) {
this.orderInc = true;
this.order = order;
}
/**
* Return ORDER BY clause.
*
* @return list of {@link com.stratio.meta.core.structures.Ordering}.
*/
public List<Ordering> getOrder() {
return order;
}
/**
* Check if ORDER BY clause is included.
*
* @return {@code true} if is included.
*/
public boolean isOrderInc() {
return orderInc;
}
/**
* Set the {@link com.stratio.meta.core.structures.GroupBy} clause.
*
* @param group The group by.
*/
public void setGroup(List<GroupBy> group) {
this.groupInc = true;
this.group = group;
}
public void setGroup(GroupBy groupBy) {
this.groupInc = true;
group = new ArrayList<>();
group.add(groupBy);
}
/**
* Return GROUP BY clause.
*
* @return list of {@link com.stratio.meta.core.structures.GroupBy}.
*/
public List<GroupBy> getGroup() {
return group;
}
/**
* Check if GROUP BY clause is included.
*
* @return {@code true} if is included.
*/
public boolean isGroupInc() {
return groupInc;
}
/**
* Check if a WHERE clause is included.
*
* @return Whether it is included.
*/
public boolean isWhereInc() {
return whereInc;
}
/**
* Set the LIMIT of the query.
*
* @param limit The maximum number of rows to be returned.
*/
public void setLimit(int limit) {
this.limitInc = true;
if (limit <= MAX_LIMIT) {
this.limit = limit;
} else {
this.limit = MAX_LIMIT;
}
}
public int getLimit() {
return limit;
}
public WindowSelect getWindow() {
return window;
}
public MetadataManager getMetadata() {
return metadata;
}
/**
* Disable the analytics mode.
*
* @param disableAnalytics Whether analytics are enable (default) or not.
*/
public void setDisableAnalytics(boolean disableAnalytics) {
this.disableAnalytics = disableAnalytics;
}
/**
* Add a {@link com.stratio.meta.core.structures.SelectionSelector} to the
* {@link com.stratio.meta.core.structures.SelectionClause}.
*
* @param selSelector The new selector.
*/
public void addSelection(SelectionSelector selSelector) {
if (selectionClause == null) {
SelectionSelectors selSelectors = new SelectionSelectors();
selectionClause = new SelectionList(selSelectors);
}
SelectionList selList = (SelectionList) selectionClause;
SelectionSelectors selSelectors = (SelectionSelectors) selList.getSelection();
selSelectors.addSelectionSelector(selSelector);
}
public Map<String, String> getFieldsAliasesMap() {
/*
if(selectionClause instanceof SelectionCount){
fieldsAliasesMap.clear();
fieldsAliasesMap.put("COUNT", "COUNT");
}
*/
return fieldsAliasesMap;
}
public void setFieldsAliasesMap(Map<String, String> fieldsAliasesMap) {
this.fieldsAliasesMap = fieldsAliasesMap;
}
/**
* Creates a String representing the Statement with META syntax.
*
* @return String
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder("SELECT ");
if (selectionClause != null) {
sb.append(selectionClause.toString());
}
sb.append(" FROM ");
if (this.isKeyspaceIncluded()) {
sb.append(this.getEffectiveKeyspace()).append(".");
}
sb.append(tableName);
if (windowInc) {
sb.append(" WITH WINDOW ").append(window.toString());
}
if (joinInc) {
sb.append(" INNER JOIN ").append(join.toString());
}
if (whereInc) {
sb.append(" WHERE ");
sb.append(ParserUtils.stringList(where, " AND "));
}
if (orderInc) {
sb.append(" ORDER BY ").append(ParserUtils.stringList(order, ", "));
}
if (groupInc) {
sb.append(" GROUP BY ").append(ParserUtils.stringList(group, ", "));
}
if (limitInc) {
sb.append(" LIMIT ").append(limit);
}
if (disableAnalytics) {
sb.append(" DISABLE ANALYTICS");
}
return sb.toString().replace(" ", " ");
}
/** {@inheritDoc} */
@Override
public Result validate(MetadataManager metadata, EngineConfig config) {
// Validate FROM keyspace
Result result = validateKeyspaceAndTable(metadata, this.getEffectiveKeyspace(), tableName);
if ((!result.hasError()) && (result instanceof CommandResult)
&& ("streaming".equalsIgnoreCase(((CommandResult) result).getResult().toString()))) {
streamMode = true;
}
if (!streamMode && windowInc) {
result =
Result
.createValidationErrorResult("Window option can only be applied to ephemeral tables.");
}
if (streamMode && !windowInc) {
result = Result.createValidationErrorResult("Window is mandatory for ephemeral tables.");
}
if (!result.hasError() && joinInc) {
result =
validateKeyspaceAndTable(metadata,
join.findEffectiveKeyspace(this.getEffectiveKeyspace()), join.getTablename());
}
String effectiveKs1 = getEffectiveKeyspace();
String effectiveKs2 = null;
if (joinInc) {
SelectStatement secondSelect = new SelectStatement("");
if (join.getKeyspace() != null) {
secondSelect.setKeyspace(join.getKeyspace());
}
secondSelect.setSessionKeyspace(this.getEffectiveKeyspace());
effectiveKs2 = secondSelect.getEffectiveKeyspace();
}
TableMetadata tableMetadataJoin = null;
com.stratio.meta.common.metadata.structures.TableMetadata streamingMetadata = null;
if (!result.hasError()) {
// Cache Metadata manager and table metadata for the getDriverStatement.
this.metadata = metadata;
if (streamMode) {
streamingMetadata = metadata.convertStreamingToMeta(getEffectiveKeyspace(), tableName);
} else {
tableMetadataFrom = metadata.getTableMetadata(effectiveKs1, tableName);
}
if (joinInc) {
tableMetadataJoin = metadata.getTableMetadata(effectiveKs2, join.getTablename());
}
if (streamMode) {
result = validateSelectionColumns(streamingMetadata, tableMetadataJoin);
} else {
result = validateSelectionColumns(tableMetadataFrom, tableMetadataJoin);
}
if (!result.hasError()) {
result = validateOptions();
}
}
if (!result.hasError() && joinInc) {
if (streamMode) {
result = validateJoinClause(streamingMetadata, tableMetadataJoin);
} else {
result = validateJoinClause(tableMetadataFrom, tableMetadataJoin);
}
}
if (!result.hasError() && whereInc) {
if (streamMode) {
result =
Result
.createValidationErrorResult(
"Where clauses in ephemeral tables are not supported yet.");
} else {
result = validateWhereClauses(tableMetadataFrom, tableMetadataJoin);
}
}
/*
* if(!result.hasError() && windowInc){ result = validateWindow(config); }
*/
return result;
}
private Result validateWindow(EngineConfig config) {
Result result = QueryResult.createSuccessQueryResult();
if (window instanceof WindowTime) {
WindowTime windowTime = (WindowTime) window;
long windowMillis = windowTime.getDurationInMilliseconds();
if (windowMillis % config.getStreamingDuration() != 0) {
result =
Result.createValidationErrorResult("Window time must be multiple of "
+ config.getStreamingDuration() + " milliseconds.");
}
} else {
result = Result.createValidationErrorResult("This type of window is not supported yet.");
}
return result;
}
/**
* Validate the supported select options.
*
* @return A {@link com.stratio.meta.common.result.Result} with the validation result.
*/
private Result validateOptions() {
Result result = QueryResult.createSuccessQueryResult();
if (groupInc) {
result = validateGroupByClause();
}
if (orderInc) {
result = validateOrderByClause();
}
return result;
}
private boolean checkSelectorExists(SelectorIdentifier selector) {
return !findColumn(selector.getTable(), selector.getField()).hasError();
}
/**
* Validate the JOIN clause.
*
* @param tableFrom The table in the FROM clause.
* @param tableJoin The table in the JOIN clause.
* @return Whether the specified table names and fields are valid.
*/
private Result validateJoinClause(TableMetadata tableFrom, TableMetadata tableJoin) {
Result result = QueryResult.createSuccessQueryResult();
if (joinInc) {
if (!checkSelectorExists(join.getLeftField())) {
result =
Result.createValidationErrorResult("Join selector " + join.getLeftField().toString()
+ " table or column name not found");
}
if (!checkSelectorExists(join.getRightField())) {
result =
Result.createValidationErrorResult("Join selector " + join.getRightField().toString()
+ " table or column name not found");
}
}
return result;
}
private Result validateJoinClause(
com.stratio.meta.common.metadata.structures.TableMetadata streamingMetadata,
TableMetadata tableMetadataJoin) {
Result result = QueryResult.createSuccessQueryResult();
if (joinInc) {
SelectorIdentifier leftField = join.getLeftField();
SelectorIdentifier rightField = join.getRightField();
boolean streamingLeft = false;
boolean batchLeft = false;
if (leftField.getTable().equalsIgnoreCase(streamingMetadata.getTableName())) {
if (streamingMetadata.getColumn(leftField.getField()) == null) {
result =
Result.createValidationErrorResult("Ephemeral table '"
+ streamingMetadata.getTableName() + "' doesn't contain the field '"
+ leftField.getField() + "'.");
} else {
streamingLeft = true;
}
} else if (leftField.getTable().equalsIgnoreCase(tableMetadataJoin.getName())) {
if (tableMetadataJoin.getColumn(leftField.getField()) == null) {
result =
Result.createValidationErrorResult("Table '" + tableMetadataJoin.getName()
+ "' doesn't contain the field '" + leftField.getField() + "'.");
} else {
batchLeft = true;
}
} else {
result =
Result.createValidationErrorResult("Table '" + leftField.getTable()
+ "' doesn't match any of the incoming tables.");
}
if (!result.hasError()) {
if (streamingLeft) {
if (tableMetadataJoin.getColumn(rightField.getField()) == null) {
result =
Result.createValidationErrorResult("Table '" + tableMetadataJoin.getName()
+ "' doesn't contain the field '" + rightField.getField() + "'.");
}
} else if (batchLeft) {
if (streamingMetadata.getColumn(rightField.getField()) == null) {
result =
Result.createValidationErrorResult("Ephemeral table '"
+ streamingMetadata.getTableName() + "' doesn't contain the field '"
+ rightField.getField() + "'.");
}
}
}
}
return result;
}
/**
* Validate a relation found in a where clause.
*
* @param targetTable The target table.
* @param column The name of the column.
* @param terms The terms.
* @param rc Relation of Comparator type.
* @return Whether the relation is valid.
*/
private Result validateWhereSingleColumnRelation(String targetTable, String column,
List<Term<?>> terms, Relation rc) {
Result result = QueryResult.createSuccessQueryResult();
String operator = rc.getOperator();
ColumnMetadata cm = findColumnMetadata(targetTable, column);
if (cm != null) {
Iterator<Term<?>> termsIt = terms.iterator();
Class<?> columnType = cm.getType().asJavaClass();
while (!result.hasError() && termsIt.hasNext()) {
Term<?> term = termsIt.next();
if (!columnType.equals(term.getTermClass())) {
result =
Result.createValidationErrorResult("Column [" + column + "] of type [" + columnType
+ "] does not accept " + term.getTermClass() + " values (" + term.toString()
+ ")");
}
}
if (Boolean.class.equals(columnType)) {
boolean supported = true;
switch (operator) {
case ">":
case "<":
case ">=":
case "<=":
case "in":
case "between":
supported = false;
break;
default:
break;
}
if (!supported) {
result =
Result.createValidationErrorResult("Operand " + operator + " not supported for"
+ " column " + column + ".");
}
}
} else {
result =
Result.createValidationErrorResult("Column " + column + " not found in " + targetTable
+ " table.");
}
return result;
}
/**
* Validate that the where clause is valid by checking that columns exists on the target table and
* that the comparisons are semantically valid.
*
* @return A {@link com.stratio.meta.common.result.Result} with the validation result.
*/
private Result validateWhereClauses(TableMetadata tableMetadata, TableMetadata tableMetadataJoin) {
// TODO: Check that the MATCH operator is only used in Lucene mapped columns.
Result result = QueryResult.createSuccessQueryResult();
Iterator<Relation> relations = where.iterator();
while (!result.hasError() && relations.hasNext()) {
Relation relation = relations.next();
if (tableMetadata.getName().equalsIgnoreCase(relation.getIdentifiers().get(0).getTable())
|| (relation.getIdentifiers().get(0).getTable() == null)) {
relation.updateTermClass(tableMetadata);
} else {
relation.updateTermClass(tableMetadataJoin);
}
if (Relation.TYPE_COMPARE == relation.getType() || Relation.TYPE_IN == relation.getType()
|| Relation.TYPE_BETWEEN == relation.getType()) {
// Check comparison, =, >, <, etc.
// RelationCompare rc = RelationCompare.class.cast(relation);
String column = relation.getIdentifiers().get(0).toString();
// Determine the target table the column belongs to.
String targetTable = "any";
if (column.contains(".")) {
String[] tableAndColumn = column.split("\\.");
targetTable = tableAndColumn[0];
column = tableAndColumn[1];
}
// Check terms types
result =
validateWhereSingleColumnRelation(targetTable, column, relation.getTerms(), relation);
if ("match".equalsIgnoreCase(relation.getOperator()) && joinInc) {
result =
Result
.createValidationErrorResult("Select statements with 'Inner Join' don't support MATCH operator.");
}
} else if (Relation.TYPE_TOKEN == relation.getType()) {
// TODO: Check TOKEN relation
result = Result.createValidationErrorResult("TOKEN function not supported.");
}
}
return result;
}
/**
* Validate whether the group by clause is valid or not by checking columns exist on the target
* table and comparisons are semantically correct.
*
* @return A {@link com.stratio.meta.common.result.Result} with the validation result.
*/
private Result validateGroupByClause() {
Result result = QueryResult.createSuccessQueryResult();
List<String> selectionCols = this.getSelectionClause().getIds(false);
for (GroupBy groupByCol : this.group) {
String col = groupByCol.toString();
if (!selectionCols.contains(col)) {
this.getSelectionClause().getIds(false).add(col);
}
}
return result;
}
/**
* Validate whether the group by clause is valid or not by checking columns exist on the target
* table and comparisons are semantically correct.
*
* @return A {@link com.stratio.meta.common.result.Result} with the validation result.
*/
private Result validateOrderByClause() {
Result result = QueryResult.createSuccessQueryResult();
for (Ordering orderField : order) {
String field = orderField.getSelectorIdentifier().toString();
String targetTable = "any";
String columnName = field;
if (field.contains(".")) {
targetTable = field.substring(0, field.indexOf("."));
columnName = field.substring(field.indexOf(".") + 1);
}
Result columnResult = findColumn(targetTable, columnName);
if (columnResult.hasError()) {
result = columnResult;
}
}
return result;
}
/**
* Find a column in the selected tables.
*
* @param table The target table of the column.
* @param column The name of the column.
* @return A {@link com.stratio.meta.common.result.Result}.
*/
private Result findColumn(String table, String column) {
Result result = QueryResult.createSuccessQueryResult();
boolean found = false;
if (columns.get(table) != null) {
Iterator<ColumnMetadata> it = columns.get(table).iterator();
while (!found && it.hasNext()) {
ColumnMetadata cm = it.next();
if (cm.getName().equals(column)) {
found = true;
}
}
if (!found) {
result =
Result.createValidationErrorResult("Column " + column + " does not " + "exist in "
+ table + " table.");
}
} else {
result =
Result.createValidationErrorResult("Column " + column + " refers to table " + table
+ " that has not been specified on query.");
}
return result;
}
/**
* Find a column in the selected tables.
*
* @param table The target table of the column.
* @param column The name of the column.
* @return A {@link com.datastax.driver.core.ColumnMetadata} or null if not found.
*/
private ColumnMetadata findColumnMetadata(String table, String column) {
ColumnMetadata result = null;
boolean found = false;
if (columns.get(table) != null) {
Iterator<ColumnMetadata> it = columns.get(table).iterator();
while (!found && it.hasNext()) {
ColumnMetadata cm = it.next();
if (cm.getName().equals(column)) {
found = true;
result = cm;
}
}
}
return result;
}
/**
* Validate that the columns specified in the select are valid by checking that the selection
* columns exists in the table.
*
* @param tableFrom The {@link com.datastax.driver.core.TableMetadata} associated with the FROM
* table.
* @param tableJoin The {@link com.datastax.driver.core.TableMetadata} associated with the JOIN
* table.
* @return A {@link com.stratio.meta.common.result.Result} with the validation result.
*/
private Result validateSelectionColumns(TableMetadata tableFrom, TableMetadata tableJoin) {
Result result = QueryResult.createSuccessQueryResult();
if (streamMode && (selectionClause instanceof SelectionList)
&& (((SelectionList) selectionClause).getTypeSelection() == Selection.TYPE_SELECTOR)) {
List<String> colNames =
metadata.getStreamingColumnNames(getEffectiveKeyspace() + "_" + tableName);
SelectionList selectionList = (SelectionList) selectionClause;
SelectionSelectors selectionSelectors = (SelectionSelectors) selectionList.getSelection();
selectionSelectors.getSelectors();
for (SelectionSelector selectionSelector : selectionSelectors.getSelectors()) {
SelectorIdentifier selectorIdentifier =
(SelectorIdentifier) selectionSelector.getSelector();
String colName = selectorIdentifier.getField();
if (!colNames.contains(colName.toLowerCase())) {
return Result.createValidationErrorResult("Column '" + colName
+ "' not found in ephemeral table '" + getEffectiveKeyspace() + "." + tableName
+ "'.");
}
}
}
if (streamMode) {
return result;
}
// Create a HashMap with the columns
Collection<ColumnMetadata> allColumns = new ArrayList<>();
columns.put(tableFrom.getName(), tableFrom.getColumns());
allColumns.addAll(tableFrom.getColumns());
if (joinInc) {
// TODO: Check that what happens if two columns from t1 and t2 have the same name.
columns.put(tableJoin.getName(), tableJoin.getColumns());
allColumns.addAll(tableJoin.getColumns());
}
columns.put("any", allColumns);
Result columnResult = null;
boolean check = false;
SelectionList sl = null;
if (selectionClause.getType() == SelectionClause.TYPE_SELECTION) {
sl = SelectionList.class.cast(selectionClause);
// Check columns only if an asterisk is not selected.
if (sl.getSelection().getType() == Selection.TYPE_SELECTOR) {
check = true;
}
}
if (!check) {
return result;
}
SelectionSelectors ss = SelectionSelectors.class.cast(sl.getSelection());
for (SelectionSelector selector : ss.getSelectors()) {
if (selector.getSelector() instanceof SelectorIdentifier) {
SelectorIdentifier si = SelectorIdentifier.class.cast(selector.getSelector());
columnResult = findColumn(si.getTable(), si.getField());
if (columnResult.hasError()) {
result = columnResult;
}
} else if (selector.getSelector() instanceof SelectorGroupBy) {
if (groupInc) {
SelectorGroupBy selectorMeta = (SelectorGroupBy) selector.getSelector();
if (!selectorMeta.getGbFunction().equals(GroupByFunction.COUNT)) {
// Checking column in the group by aggregation function
if (selectorMeta.getParam().getType() == SelectorMeta.TYPE_IDENT) {
SelectorIdentifier subselectorIdentifier =
(SelectorIdentifier) selectorMeta.getParam();
columnResult =
findColumn(subselectorIdentifier.getTable(), subselectorIdentifier.getField());
if (columnResult.hasError()) {
result = columnResult;
}
} else {
result =
Result
.createValidationErrorResult("Nested functions on selected fields not supported.");
}
}
}
} else {
result =
Result.createValidationErrorResult("Functions type on selected fields not supported.");
}
}
return result;
}
private Result validateSelectionColumns(
com.stratio.meta.common.metadata.structures.TableMetadata streamingMetadata,
TableMetadata tableJoin) {
Result result = QueryResult.createSuccessQueryResult();
if ((selectionClause instanceof SelectionList)
&& (((SelectionList) selectionClause).getTypeSelection() == Selection.TYPE_SELECTOR)) {
SelectionList selectionList = (SelectionList) selectionClause;
SelectionSelectors selectionSelectors = (SelectionSelectors) selectionList.getSelection();
selectionSelectors.getSelectors();
for (SelectionSelector selectionSelector : selectionSelectors.getSelectors()) {
SelectorIdentifier selectorIdentifier =
(SelectorIdentifier) selectionSelector.getSelector();
String tableName = selectorIdentifier.getTable();
String colName = selectorIdentifier.getField();
result = findColumn(streamingMetadata, tableJoin, colName);
}
}
return result;
}
private Result findColumn(
com.stratio.meta.common.metadata.structures.TableMetadata streamingMetadata,
TableMetadata tableJoin, String colName) {
Result result = QueryResult.createSuccessQueryResult();
if (tableName.equalsIgnoreCase(streamingMetadata.getTableName())) {
if (streamingMetadata.getColumn(colName) == null) {
result =
Result.createValidationErrorResult("Field '" + colName
+ "' not found in ephemeral table '" + tableName + "'.");
}
} else if (tableName.equalsIgnoreCase(tableJoin.getName())) {
if (tableJoin.getColumn(colName) == null) {
result =
Result.createValidationErrorResult("Field '" + colName + "' not found in table '"
+ tableName + "'.");
}
} else {
result =
Result.createValidationErrorResult("Table '" + tableName
+ "' doesn't match to any incoming tables.");
}
return result;
}
/**
* Get the processed where clause to be sent to Cassandra related with lucene indexes.
*
* @param metadata The {@link com.stratio.meta.core.metadata.MetadataManager} that provides the
* required information.
* @param tableMetadata The associated {@link com.datastax.driver.core.TableMetadata}.
* @return A String array with the column name and the lucene query, or null if no index is found.
*/
public String[] getLuceneWhereClause(MetadataManager metadata, TableMetadata tableMetadata) {
String[] result = null;
CustomIndexMetadata luceneIndex = metadata.getLuceneIndex(tableMetadata);
int addedClauses = 0;
if (luceneIndex != null) {
// TODO: Check in the validator that the query uses AND with the lucene mapped columns.
StringBuilder sb = new StringBuilder("{filter:{type:\"boolean\",must:[");
// Iterate throughout the relations of the where clause looking for MATCH.
for (Relation relation : where) {
if (Relation.TYPE_COMPARE == relation.getType()
&& "MATCH".equalsIgnoreCase(relation.getOperator())) {
RelationCompare rc = RelationCompare.class.cast(relation);
// String column = rc.getIdentifiers().get(0).toString();
String column = rc.getIdentifiers().get(0).getField();
String value = rc.getTerms().get(0).toString();
// Generate query for column
String[] processedQuery = processLuceneQueryType(value);
sb.append("{type:\"");
sb.append(processedQuery[0]);
sb.append("\",field:\"");
sb.append(column);
sb.append("\",value:\"");
sb.append(processedQuery[1]);
sb.append("\"},");
addedClauses++;
}
}
sb.replace(sb.length() - 1, sb.length(), "");
sb.append("]}}");
if (addedClauses > 0) {
result = new String[] {luceneIndex.getIndexName(), sb.toString()};
}
}
return result;
}
/**
* Process a query pattern to determine the type of Lucene query. The supported types of queries
* are: <li>
* <ul>
* Wildcard: The query contains * or ?.
* </ul>
* <ul>
* Fuzzy: The query ends with ~ and a number.
* </ul>
* <ul>
* Regex: The query contains [ or ].
* </ul>
* <ul>
* Match: Default query, supporting escaped symbols: *, ?, [, ], etc.
* </ul>
* </li>
*
* @param query The user query.
* @return An array with the type of query and the processed query.
*/
protected String[] processLuceneQueryType(String query) {
String[] result = {"", ""};
Pattern escaped = Pattern.compile(".*\\\\\\*.*|.*\\\\\\?.*|.*\\\\\\[.*|.*\\\\\\].*");
Pattern wildcard = Pattern.compile(".*\\*.*|.*\\?.*");
Pattern regex = Pattern.compile(".*\\].*|.*\\[.*");
Pattern fuzzy = Pattern.compile(".*~\\d+");
if (escaped.matcher(query).matches()) {
result[0] = "match";
result[1] =
query.replace("\\*", "*").replace("\\?", "?").replace("\\]", "]").replace("\\[", "[");
} else if (regex.matcher(query).matches()) {
result[0] = "regex";
result[1] = query;
} else if (fuzzy.matcher(query).matches()) {
result[0] = "fuzzy";
result[1] = query;
} else if (wildcard.matcher(query).matches()) {
result[0] = "wildcard";
result[1] = query;
} else {
result[0] = "match";
result[1] = query;
}
// C* Query builder doubles the ' character.
result[1] = result[1].replaceAll("^'", "").replaceAll("'$", "");
return result;
}
/**
* Creates a String representing the Statement with CQL syntax.
*
* @return
*/
@Override
public String translateToCQL(MetadataManager metadataManager) {
StringBuilder sb = new StringBuilder(this.toString());
if (sb.toString().contains("TOKEN(")) {
int currentLength = 0;
int newLength = sb.toString().length();
while (newLength != currentLength) {
currentLength = newLength;
sb = new StringBuilder(sb.toString().replaceAll("(.*)" // $1
+ "(=|<|>|<=|>=|<>|LIKE)" // $2
+ "(\\s?)" // $3
+ "(TOKEN\\()" // $4
+ "([^'][^\\)]+)" // $5
+ "(\\).*)", // $6
"$1$2$3$4'$5'$6"));
sb = new StringBuilder(sb.toString().replaceAll("(.*TOKEN\\(')" // $1
+ "([^,]+)" // $2
+ "(,)" // $3
+ "(\\s*)" // $4
+ "([^']+)" // $5
+ "(')" // $6
+ "(\\).*)", // $7
"$1$2'$3$4'$5$6$7"));
sb = new StringBuilder(sb.toString().replaceAll("(.*TOKEN\\(')" // $1
+ "(.+)" // $2
+ "([^'])" // $3
+ "(,)" // $4
+ "(\\s*)" // $5
+ "([^']+)" // $6
+ "(')" // $7
+ "(\\).*)", // $8
"$1$2$3'$4$5'$6$7$8"));
sb = new StringBuilder(sb.toString().replaceAll("(.*TOKEN\\(')" // $1
+ "(.+)" // $2
+ "([^'])" // $3
+ "(,)" // $4
+ "(\\s*)" // $5
+ "([^']+)" // $6
+ "(')" // $7
+ "([^TOKEN]+)" // $8
+ "('\\).*)", // $9
"$1$2$3'$4$5'$6$7$8$9"));
newLength = sb.toString().length();
}
}
return sb.toString();
}
@Override
public String translateToSiddhi(IStratioStreamingAPI stratioStreamingAPI, String streamName,
String outgoing) {
StringBuilder querySb = new StringBuilder("from ");
querySb.append(streamName);
if (windowInc) {
querySb.append("#window.timeBatch( ").append(getWindow().toString().toLowerCase())
.append(" )");
}
List<String> ids = new ArrayList<>();
boolean asterisk = false;
SelectionClause selectionClause = getSelectionClause();
if (selectionClause.getType() == SelectionClause.TYPE_SELECTION) {
SelectionList selectionList = (SelectionList) selectionClause;
Selection selection = selectionList.getSelection();
if (selection.getType() == Selection.TYPE_ASTERISK) {
asterisk = true;
}
}
if (asterisk) {
List<ColumnNameTypeValue> cols = null;
try {
cols = stratioStreamingAPI.columnsFromStream(streamName);
} catch (Exception e) {
LOG.error(e);
}
for (ColumnNameTypeValue ctv : cols) {
ids.add(ctv.getColumn());
}
} else {
ids = getSelectionClause().getFields();
}
String idsStr = Arrays.toString(ids.toArray()).replace("[", "").replace("]", "");
querySb.append(" select ").append(idsStr).append(" insert into ");
querySb.append(outgoing);
return querySb.toString();
}
/**
* Get the driver representation of the fields found in the selection clause.
*
* @param selSelectors The selectors.
* @param selection The current Select.Selection.
* @return A {@link com.datastax.driver.core.querybuilder.Select.Selection}.
*/
private Select.Selection getDriverBuilderSelection(SelectionSelectors selSelectors,
Select.Selection selection) {
Select.Selection result = selection;
for (SelectionSelector selSelector : selSelectors.getSelectors()) {
SelectorMeta selectorMeta = selSelector.getSelector();
if (selectorMeta.getType() == SelectorMeta.TYPE_IDENT) {
SelectorIdentifier selIdent = (SelectorIdentifier) selectorMeta;
if (selSelector.isAliasInc()) {
result = result.column(selIdent.getField()).as(selSelector.getAlias());
} else {
result = result.column(selIdent.getField());
}
} else if (selectorMeta.getType() == SelectorMeta.TYPE_FUNCTION) {
SelectorFunction selFunction = (SelectorFunction) selectorMeta;
List<SelectorMeta> params = selFunction.getParams();
Object[] innerFunction = new Object[params.size()];
int pos = 0;
for (SelectorMeta selMeta : params) {
innerFunction[pos] = QueryBuilder.raw(selMeta.toString());
pos++;
}
result = result.fcall(selFunction.getName(), innerFunction);
}
}
return result;
}
/**
* Get the driver builder object with the selection clause.
*
* @return A {@link com.datastax.driver.core.querybuilder.Select.Builder}.
*/
private Select.Builder getDriverBuilder() {
Select.Builder builder;
if (selectionClause.getType() == SelectionClause.TYPE_COUNT) {
builder = QueryBuilder.select().countAll();
} else {
// Selection type
SelectionList selList = (SelectionList) selectionClause;
if (selList.getSelection().getType() != Selection.TYPE_ASTERISK) {
Select.Selection selection = QueryBuilder.select();
if (selList.isDistinct()) {
selection = selection.distinct();
}
// Select the required columns.
SelectionSelectors selSelectors = (SelectionSelectors) selList.getSelection();
builder = getDriverBuilderSelection(selSelectors, selection);
} else {
builder = QueryBuilder.select().all();
}
}
return builder;
}
/**
* Cast an input value to the class associated with the comparison column.
*
* @param columnName The name of the column.
* @param value The initial value.
* @return A casted object.
*/
private Object getWhereCastValue(String columnName, Object value) {
Object result = null;
Class<?> clazz = tableMetadataFrom.getColumn(columnName).getType().asJavaClass();
if (String.class.equals(clazz)) {
result = String.class.cast(value);
} else if (UUID.class.equals(clazz)) {
result = UUID.fromString(String.class.cast(value));
} else if (Date.class.equals(clazz)) {
// TODO getWhereCastValue with date
result = null;
} else {
try {
if (value.getClass().equals(clazz)) {
result = clazz.getConstructor(String.class).newInstance(value.toString());
} else {
Method m = clazz.getMethod("valueOf", value.getClass());
result = m.invoke(value);
}
} catch (InstantiationException | IllegalAccessException | InvocationTargetException
| NoSuchMethodException e) {
LOG.error("Cannot parse input value", e);
}
}
return result;
}
/**
* Get the driver clause associated with a compare relation.
*
* @param metaRelation The {@link com.stratio.meta.core.structures.RelationCompare} clause.
* @return A {@link com.datastax.driver.core.querybuilder.Clause}.
*/
private Clause getRelationCompareClause(Relation metaRelation) {
Clause clause = null;
RelationCompare relCompare = (RelationCompare) metaRelation;
String field = relCompare.getIdentifiers().get(0).getField();
Object value = relCompare.getTerms().get(0).getTermValue();
value = getWhereCastValue(field, value);
switch (relCompare.getOperator().toUpperCase()) {
case "=":
clause = QueryBuilder.eq(field, value);
break;
case ">":
clause = QueryBuilder.gt(field, value);
break;
case ">=":
clause = QueryBuilder.gte(field, value);
break;
case "<":
clause = QueryBuilder.lt(field, value);
break;
case "<=":
clause = QueryBuilder.lte(field, value);
break;
case "MATCH":
// Processed as LuceneIndex
break;
default:
LOG.error("Unsupported operator: " + relCompare.getOperator());
break;
}
return clause;
}
/**
* Get the driver clause associated with an in relation.
*
* @param metaRelation The {@link com.stratio.meta.core.structures.RelationIn} clause.
* @return A {@link com.datastax.driver.core.querybuilder.Clause}.
*/
private Clause getRelationInClause(Relation metaRelation) {
Clause clause = null;
RelationIn relIn = (RelationIn) metaRelation;
List<Term<?>> terms = relIn.getTerms();
String field = relIn.getIdentifiers().get(0).getField();
Object[] values = new Object[relIn.numberOfTerms()];
int nTerm = 0;
for (Term<?> term : terms) {
values[nTerm] = getWhereCastValue(field, term.getTermValue());
nTerm++;
}
clause = QueryBuilder.in(relIn.getIdentifiers().get(0).toString(), values);
return clause;
}
/**
* Get the driver clause associated with an token relation.
*
* @param metaRelation The {@link com.stratio.meta.core.structures.RelationToken} clause.
* @return A {@link com.datastax.driver.core.querybuilder.Clause}.
*/
private Clause getRelationTokenClause(Relation metaRelation) {
Clause clause = null;
RelationToken relToken = (RelationToken) metaRelation;
List<String> names = new ArrayList<>();
for (SelectorIdentifier identifier : relToken.getIdentifiers()) {
names.add(identifier.toString());
}
if (!relToken.isRightSideTokenType()) {
Object value = relToken.getTerms().get(0).getTermValue();
switch (relToken.getOperator()) {
case "=":
clause =
QueryBuilder.eq(QueryBuilder.token(names.toArray(new String[names.size()])), value);
break;
case ">":
clause =
QueryBuilder.gt(QueryBuilder.token(names.toArray(new String[names.size()])), value);
break;
case ">=":
clause =
QueryBuilder.gte(QueryBuilder.token(names.toArray(new String[names.size()])), value);
break;
case "<":
clause =
QueryBuilder.lt(QueryBuilder.token(names.toArray(new String[names.size()])), value);
break;
case "<=":
clause =
QueryBuilder.lte(QueryBuilder.token(names.toArray(new String[names.size()])), value);
break;
default:
LOG.error("Unsupported operator " + relToken.getOperator());
break;
}
} else {
return null;
}
return clause;
}
/**
* Get the driver where clause.
*
* @param sel The current Select.
* @return A {@link com.datastax.driver.core.querybuilder.Select.Where}.
*/
private Where getDriverWhere(Select sel) {
Where whereStmt = null;
String[] luceneWhere = getLuceneWhereClause(metadata, tableMetadataFrom);
if (luceneWhere != null) {
Clause lc = QueryBuilder.eq(luceneWhere[0], luceneWhere[1]);
whereStmt = sel.where(lc);
}
for (Relation metaRelation : this.where) {
Clause clause = null;
switch (metaRelation.getType()) {
case Relation.TYPE_COMPARE:
clause = getRelationCompareClause(metaRelation);
break;
case Relation.TYPE_IN:
clause = getRelationInClause(metaRelation);
break;
case Relation.TYPE_TOKEN:
clause = getRelationTokenClause(metaRelation);
break;
default:
LOG.error("Unsupported relation type: " + metaRelation.getType());
break;
}
if (clause != null) {
if (whereStmt == null) {
whereStmt = sel.where(clause);
} else {
whereStmt = whereStmt.and(clause);
}
}
}
return whereStmt;
}
@Override
public Statement getDriverStatement() {
Select.Builder builder = getDriverBuilder();
Select sel = builder.from(this.getEffectiveKeyspace(), this.tableName);
if (this.limitInc) {
sel.limit(this.limit);
}
if (this.orderInc) {
com.datastax.driver.core.querybuilder.Ordering[] orderings =
new com.datastax.driver.core.querybuilder.Ordering[order.size()];
int nOrdering = 0;
for (Ordering metaOrdering : this.order) {
if (metaOrdering.isDirInc() && (metaOrdering.getOrderDir() == OrderDirection.DESC)) {
orderings[nOrdering] = QueryBuilder.desc(metaOrdering.getSelectorIdentifier().toString());
} else {
orderings[nOrdering] = QueryBuilder.asc(metaOrdering.getSelectorIdentifier().toString());
}
nOrdering++;
}
sel.orderBy(orderings);
}
Where whereStmt = null;
if (this.whereInc) {
whereStmt = getDriverWhere(sel);
} else {
whereStmt = sel.where();
}
LOG.trace("Executing: " + whereStmt.toString());
return whereStmt;
}
/**
* Find the table that contains the selected column.
*
* @param columnName The name of the column.
* @return The name of the table.
*/
private String findAssociatedTable(String columnName) {
String result = null;
boolean found = false;
String[] tableNames = columns.keySet().toArray(new String[columns.size()]);
for (int tableIndex = 0; tableIndex < tableNames.length && !found; tableIndex++) {
Iterator<ColumnMetadata> columnIterator = columns.get(tableNames[tableIndex]).iterator();
while (columnIterator.hasNext() && !found) {
ColumnMetadata cm = columnIterator.next();
if (cm.getName().equals(columnName)) {
result = cm.getTable().getName();
found = true;
}
}
}
return result;
}
/**
* Check whether a selection clause should be added to the new Select statement that will be
* generated as part of the planning process of a JOIN.
*
* @param select The {@link com.stratio.meta.core.statements.SelectStatement}.
* @param whereColumnName The name of the column.
* @return Whether it should be added or not.
*/
private boolean checkAddSelectionJoinWhere(SelectStatement select, String whereColumnName) {
Selection selList = ((SelectionList) this.selectionClause).getSelection();
boolean addCol = true;
if (selList instanceof SelectionSelectors) {
// Otherwise, it's an asterisk selection
// Add column to Select clauses if applied
SelectionList sClause = (SelectionList) select.getSelectionClause();
SelectionSelectors sSelectors = (SelectionSelectors) sClause.getSelection();
for (SelectionSelector ss : sSelectors.getSelectors()) {
SelectorIdentifier si = (SelectorIdentifier) ss.getSelector();
String colName = si.getField();
if (colName.equalsIgnoreCase(whereColumnName)) {
addCol = false;
break;
}
}
} else {
addCol = false;
}
return addCol;
}
/**
* Get a map of relations to be added to where clauses of the sub-select queries that will be
* executed for a JOIN select.
*
* @param firstSelect The first select statement.
* @param secondSelect The second select statement.
* @return A map with keys {@code 1} or {@code 2} for each select.
*/
private Map<Integer, List<Relation>> getWhereJoinPlan(SelectStatement firstSelect,
SelectStatement secondSelect) {
Map<Integer, List<Relation>> result = new HashMap<>();
List<Relation> firstWhere = new ArrayList<>();
List<Relation> secondWhere = new ArrayList<>();
result.put(1, firstWhere);
result.put(2, secondWhere);
List<Relation> targetWhere = null;
SelectStatement targetSelect = null;
for (Relation relation : where) {
String id = relation.getIdentifiers().iterator().next().toString();
String whereTableName = null;
String whereColumnName = null;
if (id.contains(".")) {
String[] tablenameAndColumnname = id.split("\\.");
whereTableName = tablenameAndColumnname[0];
whereColumnName = tablenameAndColumnname[1];
} else {
whereTableName = findAssociatedTable(id);
whereColumnName = id;
}
// Where clause corresponding to first table
if (tableName.equalsIgnoreCase(whereTableName)) {
targetWhere = firstWhere;
targetSelect = firstSelect;
} else {
targetWhere = secondWhere;
targetSelect = secondSelect;
}
targetWhere.add(new RelationCompare(whereColumnName, relation.getOperator(), relation
.getTerms().get(0)));
if (checkAddSelectionJoinWhere(targetSelect, whereColumnName)) {
targetSelect.addSelection(new SelectionSelector(new SelectorIdentifier(whereColumnName)));
}
}
return result;
}
/**
* Get the execution plan of a Join.
*
* @return The execution plan.
*/
private Tree getJoinPlan() {
Tree steps = new Tree();
SelectStatement firstSelect = new SelectStatement(tableName);
firstSelect.setSessionKeyspace(this.getEffectiveKeyspace());
firstSelect.setKeyspace(getEffectiveKeyspace());
SelectStatement secondSelect = new SelectStatement(this.join.getTablename());
if (this.join.getKeyspace() != null) {
secondSelect.setKeyspace(join.getKeyspace());
}
secondSelect.setSessionKeyspace(this.getEffectiveKeyspace());
SelectStatement joinSelect = new SelectStatement("");
System.out.println("TRACE 1: firstSelect = "+firstSelect.toString());
System.out.println("TRACE 1: secondSelect = "+secondSelect.toString());
System.out.println("TRACE 1: joinSelect = "+joinSelect.toString());
System.out.println("TRACE 1: ---------------------------------------");
// ADD FIELDS OF THE JOIN
if (this.join.getLeftField().getTable().trim().equalsIgnoreCase(tableName)) {
firstSelect.addSelection(new SelectionSelector(this.join.getLeftField()));
secondSelect.addSelection(new SelectionSelector(this.join.getRightField()));
} else {
firstSelect.addSelection(new SelectionSelector(this.join.getRightField()));
secondSelect.addSelection(new SelectionSelector(this.join.getLeftField()));
}
System.out.println("TRACE 2: firstSelect = "+firstSelect.toString());
System.out.println("TRACE 2: secondSelect = "+secondSelect.toString());
System.out.println("TRACE 2: joinSelect = "+joinSelect.toString());
System.out.println("TRACE 2: ---------------------------------------");
// ADD FIELDS OF THE SELECT
SelectionList selectionList = (SelectionList) this.selectionClause;
Selection selection = selectionList.getSelection();
System.out.println("TRACE 3: firstSelect = "+firstSelect.toString());
System.out.println("TRACE 3: secondSelect = "+secondSelect.toString());
System.out.println("TRACE 3: joinSelect = "+joinSelect.toString());
System.out.println("TRACE 3: ---------------------------------------");
if (selection instanceof SelectionSelectors) {
SelectionSelectors selectionSelectors = (SelectionSelectors) selectionList.getSelection();
for (SelectionSelector ss : selectionSelectors.getSelectors()) {
if(ss.getSelector() instanceof SelectorIdentifier){ // Example: users.name
SelectorIdentifier si = (SelectorIdentifier) ss.getSelector();
if (tableMetadataFrom.getColumn(si.getField()) != null) {
firstSelect.addSelection(new SelectionSelector(new SelectorIdentifier(si.getTable(), si.getField())));
} else {
secondSelect.addSelection(new SelectionSelector(new SelectorIdentifier(si.getTable(), si.getField())));
}
} else if (ss.getSelector() instanceof SelectorFunction) { // Example: myfunction(users.age, users_info.dateOfRegistration)
SelectorFunction sf = (SelectorFunction) ss.getSelector();
List<SelectorMeta> paramsFirst = new ArrayList<>();
List<SelectorMeta> paramsSecond = new ArrayList<>();
for(SelectorMeta sm: sf.getParams()){
SelectorIdentifier si = (SelectorIdentifier) sm;
if (tableMetadataFrom.getColumn(si.getField()) != null) {
paramsFirst.add(new SelectorIdentifier(si.getTable(), si.getField()));
} else {
paramsSecond.add(new SelectorIdentifier(si.getTable(), si.getField()));
}
}
if (!paramsFirst.isEmpty()) {
firstSelect.addSelection(new SelectionSelector(new SelectorFunction(sf.getName(), paramsFirst)));
}
if(!paramsFirst.isEmpty()) {
secondSelect.addSelection(new SelectionSelector(new SelectorFunction(sf.getName(), paramsSecond)));
}
} else if (ss.getSelector() instanceof SelectorGroupBy) { // Example: sum(users.age) ... GroupBy users.gender
SelectorGroupBy sg = (SelectorGroupBy) ss.getSelector();
SelectorIdentifier si = (SelectorIdentifier) sg.getParam();
SelectorIdentifier newSi = new SelectorIdentifier(si.getTable(), si.getField());
if (tableMetadataFrom.getColumn(si.getField()) != null) {
firstSelect.addSelection(new SelectionSelector(newSi));
} else {
secondSelect.addSelection(new SelectionSelector(newSi));
}
}
}
} else {
// instanceof SelectionAsterisk
firstSelect.setSelectionClause(new SelectionList(new SelectionAsterisk()));
secondSelect.setSelectionClause(new SelectionList(new SelectionAsterisk()));
}
System.out.println("TRACE 4: firstSelect = "+firstSelect.toString());
System.out.println("TRACE 4: secondSelect = "+secondSelect.toString());
System.out.println("TRACE 4: joinSelect = "+joinSelect.toString());
System.out.println("TRACE 4: ---------------------------------------");
// ADD WHERE CLAUSES IF ANY
if (whereInc) {
Map<Integer, List<Relation>> whereRelations = getWhereJoinPlan(firstSelect, secondSelect);
if (!whereRelations.get(1).isEmpty()) {
firstSelect.setWhere(whereRelations.get(1));
}
if (!whereRelations.get(2).isEmpty()) {
secondSelect.setWhere(whereRelations.get(2));
}
}
// ADD GROUP BY CLAUSE IF ANY
if(groupInc){
GroupBy param = group.get(0);
String groupTable = param.getSelectorIdentifier().getTable();
GroupBy newGroupBy = new GroupBy(groupTable+"."+param.getSelectorIdentifier().getField());
joinSelect.setGroup(newGroupBy);
}
// ADD GROUP BY CLAUSE IF ANY
if(groupInc){
List newGroup = new ArrayList<GroupBy>();
GroupBy param = group.get(0);
GroupBy newGroupBy = new GroupBy(param.getSelectorIdentifier().getField());
String groupTable = param.getSelectorIdentifier().getTable();
}
// ADD SELECTED COLUMNS TO THE JOIN STATEMENT
joinSelect.setSelectionClause(selectionClause);
// ADD MAP OF THE JOIN
if (this.join.getLeftField().getTable().equalsIgnoreCase(tableName)) {
joinSelect.setJoin(new InnerJoin("", this.join.getLeftField(), this.join.getRightField()));
} else {
joinSelect.setJoin(new InnerJoin("", this.join.getRightField(), this.join.getLeftField()));
}
firstSelect.validate(metadata, null);
secondSelect.validate(metadata, null);
// ADD STEPS
steps.setNode(new MetaStep(MetaPath.DEEP, joinSelect));
steps.addChild(new Tree(new MetaStep(MetaPath.DEEP, firstSelect)));
steps.addChild(new Tree(new MetaStep(MetaPath.DEEP, secondSelect)));
return steps;
}
private Map<String, String> getColumnsFromWhere() {
Map<String, String> whereCols = new HashMap<>();
for (Relation relation : where) {
for (SelectorIdentifier id : relation.getIdentifiers()) {
whereCols.put(id.getField(), relation.getOperator());
}
}
return whereCols;
}
private boolean matchWhereColsWithPartitionKeys(TableMetadata tableMetadata,
Map<String, String> whereCols) {
boolean partialMatched = false;
for (ColumnMetadata colMD : tableMetadata.getPartitionKey()) {
String operator = "";
for (Relation relation : where) {
if (relation.getIdentifiers().contains(colMD.getName())) {
operator = relation.getOperator();
}
}
if (whereCols.keySet().contains(colMD.getName()) && "=".equals(operator)) {
partialMatched = true;
whereCols.remove(colMD.getName());
}
}
if (whereCols.size() == 0) {
partialMatched = false;
}
return partialMatched;
}
private void matchWhereColsWithClusteringKeys(TableMetadata tableMetadata,
Map<String, String> whereCols) {
for (ColumnMetadata colMD : tableMetadata.getClusteringColumns()) {
String operator = "";
for (Relation relation : where) {
if (relation.getIdentifiers().contains(colMD.getName())) {
operator = relation.getOperator();
}
}
if (whereCols.keySet().contains(colMD.getName()) && "=".equals(operator)) {
whereCols.remove(colMD.getName());
}
}
}
private boolean checkWhereColsWithLucene(Set<String> luceneCols, Map<String, String> whereCols,
MetadataManager metadataManager, boolean cassandraPath) {
if (luceneCols.containsAll(whereCols.keySet())) {
boolean onlyMatchOperators = true;
for (String operator : whereCols.values()) {
if (!"match".equalsIgnoreCase(operator)) {
onlyMatchOperators = false;
break;
}
}
cassandraPath = (onlyMatchOperators) ? onlyMatchOperators : cassandraPath;
/*
* //TODO Retreive original table create metadata and check for text columns. if(cassandraPath
* && !whereCols.isEmpty()){ // When querying a text type column with a Lucene index, content
* must be lowercased TableMetadata metaData =
* metadataManager.getTableMetadata(getEffectiveKeyspace(), tableName);
* metadataManager.loadMetadata(); String lucenCol = whereCols.keySet().iterator().next();
* if(metaData.getColumn(lucenCol).getType() == DataType.text() &&
* where.get(0).getTerms().get(0) instanceof StringTerm){ StringTerm stringTerm = (StringTerm)
* where.get(0).getTerms().get(0); ((StringTerm)
* where.get(0).getTerms().get(0)).setTerm(stringTerm.getStringValue().toLowerCase(),
* stringTerm.isQuotedLiteral()); } }
*/
}
return cassandraPath;
}
/**
* Get the execution plan of a non JOIN select with a where clause.
*
* @param metadataManager The medata manager.
* @return The execution plan.
*/
private Tree getWherePlan(MetadataManager metadataManager) {
Tree steps = new Tree();
// Get columns of the where clauses (Map<identifier, operator>)
Map<String, String> whereCols = getColumnsFromWhere();
// By default go through deep.
boolean cassandraPath = false;
if (whereCols.isEmpty()) {
// All where clauses are included in the primary key with equals comparator.
cassandraPath = true;
} else if (areOperatorsCassandraCompatible(whereCols)) {
String effectiveKeyspace = getEffectiveKeyspace();
TableMetadata tableMetadata = metadataManager.getTableMetadata(effectiveKeyspace, tableName);
// Check if all partition columns have an equals operator
boolean partialMatched = matchWhereColsWithPartitionKeys(tableMetadata, whereCols);
if (!partialMatched) {
// Check if all clustering columns have an equals operator
matchWhereColsWithClusteringKeys(tableMetadata, whereCols);
// Get columns of the custom and lucene indexes
Set<String> indexedCols = new HashSet<>();
Set<String> luceneCols = new HashSet<>();
for (CustomIndexMetadata cim : metadataManager.getTableIndex(tableMetadata)) {
if (cim.getIndexType() == IndexType.DEFAULT) {
indexedCols.addAll(cim.getIndexedColumns());
} else {
luceneCols.addAll(cim.getIndexedColumns());
}
}
if (indexedCols.containsAll(whereCols.keySet())
&& !containsRelationalOperators(whereCols.values())) {
cassandraPath = true;
}
if (!whereCols.isEmpty()) {
cassandraPath =
checkWhereColsWithLucene(luceneCols, whereCols, metadataManager, cassandraPath);
}
}
}
if (cassandraPath) {
steps.setNode(new MetaStep(MetaPath.CASSANDRA, this));
} else {
steps.setNode(new MetaStep(MetaPath.DEEP, this));
}
return steps;
}
private boolean areOperatorsCassandraCompatible(Map<String, String> whereCols) {
boolean compatible = true;
Iterator<Entry<String, String>> whereColsIt = whereCols.entrySet().iterator();
while (compatible && whereColsIt.hasNext()) {
Entry<String, String> whereCol = whereColsIt.next();
switch (whereCol.getValue().toLowerCase()) {
case "in":
case "between":
compatible = false;
break;
}
}
return compatible;
}
@Override
public Tree getPlan(MetadataManager metadataManager, String targetKeyspace) {
Tree steps = new Tree();
if (metadataManager.checkStream(getEffectiveKeyspace() + "_" + tableName) && joinInc) {
steps = getStreamJoinPlan();
} else if (metadataManager.checkStream(getEffectiveKeyspace() + "_" + tableName)) {
steps.setNode(new MetaStep(MetaPath.STREAMING, this));
steps.setInvolvesStreaming(true);
} else if (joinInc) {
steps = getJoinPlan();
} else if (groupInc || orderInc || selectionClause.containsFunctions()) {
steps.setNode(new MetaStep(MetaPath.DEEP, this));
} else if (whereInc) {
steps = getWherePlan(metadataManager);
} else {
steps.setNode(new MetaStep(MetaPath.CASSANDRA, this));
}
LOG.info("PLAN: " + System.lineSeparator() + steps.toStringDownTop());
return steps;
}
private Tree getStreamJoinPlan() {
Tree steps = new Tree();
SelectStatement firstSelect = new SelectStatement(tableName);
firstSelect.setSessionKeyspace(this.getEffectiveKeyspace());
firstSelect.setKeyspace(getEffectiveKeyspace());
SelectStatement secondSelect = new SelectStatement(this.join.getTablename());
if (this.join.getKeyspace() != null) {
secondSelect.setKeyspace(join.getKeyspace());
}
secondSelect.setSessionKeyspace(this.getEffectiveKeyspace());
SelectStatement joinSelect = new SelectStatement("");
// ADD FIELDS OF THE JOIN
String streamingField = null;
if (this.join.getLeftField().getTable().trim().equalsIgnoreCase(tableName)) {
// streamingField = this.join.getLeftField().getField();
// if(streamingField.contains(".")) {
// this.join.getLeftField().setField(streamingField.split(".")[1]);
// }
this.join.getLeftField().setTable(null);
firstSelect.addSelection(new SelectionSelector(this.join.getLeftField()));
secondSelect.addSelection(new SelectionSelector(this.join.getRightField()));
} else {
// streamingField = this.join.getRightField().getField();
// if(streamingField.contains(".")) {
// this.join.getRightField().setField(streamingField.split(".")[1]);
// }
this.join.getRightField().setTable(null);
firstSelect.addSelection(new SelectionSelector(this.join.getRightField()));
secondSelect.addSelection(new SelectionSelector(this.join.getLeftField()));
}
com.stratio.meta.common.metadata.structures.TableMetadata streamingTable =
metadata.convertStreamingToMeta(this.getEffectiveKeyspace(), tableName);
// ADD FIELDS OF THE SELECT
SelectionList selectionList = (SelectionList) this.selectionClause;
Selection selection = selectionList.getSelection();
if (selection instanceof SelectionSelectors) {
SelectionSelectors selectionSelectors = (SelectionSelectors) selectionList.getSelection();
for (SelectionSelector ss : selectionSelectors.getSelectors()) {
SelectorIdentifier si = (SelectorIdentifier) ss.getSelector();
if (streamingTable.getColumn(si.getField()) != null) {
firstSelect.addSelection(new SelectionSelector(new SelectorIdentifier(si.getField())));
} else {
secondSelect.addSelection(new SelectionSelector(new SelectorIdentifier(si.getField())));
}
}
} else {
// instanceof SelectionAsterisk
firstSelect.setSelectionClause(new SelectionList(new SelectionAsterisk()));
secondSelect.setSelectionClause(new SelectionList(new SelectionAsterisk()));
}
// ADD WHERE CLAUSES IF ANY
if (whereInc) {
Map<Integer, List<Relation>> whereRelations = getWhereJoinPlan(firstSelect, secondSelect);
if (!whereRelations.get(1).isEmpty()) {
firstSelect.setWhere(whereRelations.get(1));
}
if (!whereRelations.get(2).isEmpty()) {
secondSelect.setWhere(whereRelations.get(2));
}
}
// ADD WINDOW
if (windowInc) {
firstSelect.setWindow(window);
}
// ADD SELECTED COLUMNS TO THE JOIN STATEMENT
joinSelect.setSelectionClause(selectionClause);
// ADD MAP OF THE JOIN
if (this.join.getLeftField().getTable().equalsIgnoreCase(tableName)) {
joinSelect.setJoin(new InnerJoin("", this.join.getLeftField(), this.join.getRightField()));
} else {
joinSelect.setJoin(new InnerJoin("", this.join.getRightField(), this.join.getLeftField()));
}
firstSelect.validate(metadata, null);
secondSelect.validate(metadata, null);
// ADD STEPS
// steps.setNode(new MetaStep(MetaPath.DEEP, joinSelect));
// steps.addChild(new Tree(new MetaStep(MetaPath.STREAMING, firstSelect)));
// steps.addChild(new Tree(new MetaStep(MetaPath.DEEP, secondSelect)));
steps.setNode(new MetaStep(MetaPath.STREAMING, firstSelect));
Tree join = new Tree(new MetaStep(MetaPath.DEEP, joinSelect));
steps.addChild(join);
Tree selectB = new Tree(new MetaStep(MetaPath.DEEP, secondSelect));
join.addChild(selectB);
steps.setInvolvesStreaming(true);
return steps;
}
/**
* Check if operators collection contains any relational operator.
*
* @param collection {@link java.util.Collection} of relational operators.
* @return {@code true} if contains any relational operator.
*/
private boolean containsRelationalOperators(Collection<String> collection) {
boolean result = false;
if (collection.contains("<=") || collection.contains("<") || collection.contains(">")
|| collection.contains(">=")) {
result = true;
}
return result;
}
public void addTablenameToIds() {
selectionClause.addTablename(tableName);
}
private void replaceAliasesInSelect(Map<String, String> tablesAliasesMap) {
if (this.selectionClause instanceof SelectionList
&& ((SelectionList) this.selectionClause).getSelection() instanceof SelectionSelectors) {
List<SelectionSelector> selectors =
((SelectionSelectors) ((SelectionList) this.selectionClause).getSelection())
.getSelectors();
for (SelectionSelector selector : selectors) {
SelectorIdentifier identifier = null;
if (selector.getSelector() instanceof SelectorIdentifier) {
identifier = (SelectorIdentifier) selector.getSelector();
} else if (selector.getSelector() instanceof SelectorGroupBy) {
identifier = (SelectorIdentifier) ((SelectorGroupBy) selector.getSelector()).getParam();
}
if (identifier != null) {
String table = tablesAliasesMap.get(identifier.getTable());
if (table != null) {
identifier.setTable(table);
}
}
}
}
}
private void replaceAliasesInWhere(Map<String, String> fieldsAliasesMap,
Map<String, String> tablesAliasesMap) {
if (this.where != null) {
for (Relation whereCol : this.where) {
for (SelectorIdentifier id : whereCol.getIdentifiers()) {
String table = tablesAliasesMap.get(id.getTable());
if (table != null) {
id.setTable(table);
}
String identifier = fieldsAliasesMap.get(id.toString());
if (identifier != null) {
id.setIdentifier(identifier);
}
}
}
}
}
private void replaceAliasesInGroupBy(Map<String, String> fieldsAliasesMap,
Map<String, String> tablesAliasesMap) {
if (this.group != null) {
for (GroupBy groupByCol : this.group) {
SelectorIdentifier selectorIdentifier = groupByCol.getSelectorIdentifier();
String table = tablesAliasesMap.get(selectorIdentifier.getTable());
if (table != null) {
selectorIdentifier.setTable(table);
}
String identifier = fieldsAliasesMap.get(selectorIdentifier.toString());
if (identifier != null) {
selectorIdentifier.setIdentifier(identifier);
}
}
}
}
private void replaceAliasesInOrderBy(Map<String, String> fieldsAliasesMap,
Map<String, String> tablesAliasesMap) {
if (this.order != null) {
for (Ordering orderBycol : this.order) {
SelectorIdentifier selectorIdentifier = orderBycol.getSelectorIdentifier();
String table = tablesAliasesMap.get(selectorIdentifier.getTable());
if (table != null) {
selectorIdentifier.setTable(table);
}
String identifier = fieldsAliasesMap.get(selectorIdentifier.toString());
if (identifier != null) {
selectorIdentifier.setIdentifier(identifier);
}
}
}
}
private void replaceAliasesInJoin(Map<String, String> tablesAliasesMap) {
if (this.join != null) {
String leftTable = this.join.getLeftField().getTable();
String tableName = tablesAliasesMap.get(leftTable);
if (tableName != null) {
this.join.getLeftField().setTable(tableName);
}
String rightTable = this.join.getRightField().getTable();
tableName = tablesAliasesMap.get(rightTable);
if (tableName != null) {
this.join.getRightField().setTable(tableName);
}
}
}
public void replaceAliasesWithName(Map<String, String> fieldsAliasesMap,
Map<String, String> tablesAliasesMap) {
Iterator<Entry<String, String>> entriesIt = tablesAliasesMap.entrySet().iterator();
while (entriesIt.hasNext()) {
Entry<String, String> entry = entriesIt.next();
if (entry.getValue().contains(".")) {
tablesAliasesMap.put(entry.getKey(), entry.getValue().split("\\.")[1]);
}
}
this.setFieldsAliasesMap(fieldsAliasesMap);
// Replacing alias in SELECT clause
replaceAliasesInSelect(tablesAliasesMap);
// Replacing alias in WHERE clause
replaceAliasesInWhere(fieldsAliasesMap, tablesAliasesMap);
// Replacing alias in GROUP BY clause
replaceAliasesInGroupBy(fieldsAliasesMap, tablesAliasesMap);
// Replacing alias in ORDER BY clause
replaceAliasesInOrderBy(fieldsAliasesMap, tablesAliasesMap);
// Replacing alias in JOIN clause
replaceAliasesInJoin(tablesAliasesMap);
}
public void updateTableNames() {
// Adding table name to the identifiers in WHERE clause
if (this.where != null) {
for (Relation whereCol : this.where) {
for (SelectorIdentifier identifier : whereCol.getIdentifiers()) {
identifier.addTablename(this.tableName);
}
}
}
// Adding table name to the identifiers in GROUP BY clause
if (this.group != null) {
for (GroupBy groupByCol : this.group) {
groupByCol.getSelectorIdentifier().addTablename(this.tableName);
}
}
// Adding table name to the identifiers in ORDER BY clause
if (this.order != null) {
for (Ordering orderByCol : this.order) {
orderByCol.getSelectorIdentifier().addTablename(this.tableName);
}
}
}
}
| meta-core/src/main/java/com/stratio/meta/core/statements/SelectStatement.java | /*
* Stratio Meta
*
* Copyright (c) 2014, Stratio, All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under the terms of the
* GNU Lesser General Public License as published by the Free Software Foundation; either version
* 3.0 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library.
*/
package com.stratio.meta.core.statements;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import com.datastax.driver.core.ColumnMetadata;
import com.datastax.driver.core.Statement;
import com.datastax.driver.core.TableMetadata;
import com.datastax.driver.core.querybuilder.Clause;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
import com.datastax.driver.core.querybuilder.Select.Where;
import com.stratio.meta.common.result.CommandResult;
import com.stratio.meta.common.result.QueryResult;
import com.stratio.meta.common.result.Result;
import com.stratio.meta.core.engine.EngineConfig;
import com.stratio.meta.core.metadata.CustomIndexMetadata;
import com.stratio.meta.core.metadata.MetadataManager;
import com.stratio.meta.core.structures.GroupBy;
import com.stratio.meta.core.structures.GroupByFunction;
import com.stratio.meta.core.structures.IndexType;
import com.stratio.meta.core.structures.InnerJoin;
import com.stratio.meta.core.structures.OrderDirection;
import com.stratio.meta.core.structures.Ordering;
import com.stratio.meta.core.structures.Relation;
import com.stratio.meta.core.structures.RelationCompare;
import com.stratio.meta.core.structures.RelationIn;
import com.stratio.meta.core.structures.RelationToken;
import com.stratio.meta.core.structures.Selection;
import com.stratio.meta.core.structures.SelectionAsterisk;
import com.stratio.meta.core.structures.SelectionClause;
import com.stratio.meta.core.structures.SelectionList;
import com.stratio.meta.core.structures.SelectionSelector;
import com.stratio.meta.core.structures.SelectionSelectors;
import com.stratio.meta.core.structures.SelectorFunction;
import com.stratio.meta.core.structures.SelectorGroupBy;
import com.stratio.meta.core.structures.SelectorIdentifier;
import com.stratio.meta.core.structures.SelectorMeta;
import com.stratio.meta.core.structures.Term;
import com.stratio.meta.core.structures.WindowSelect;
import com.stratio.meta.core.structures.WindowTime;
import com.stratio.meta.core.utils.MetaPath;
import com.stratio.meta.core.utils.MetaStep;
import com.stratio.meta.core.utils.ParserUtils;
import com.stratio.meta.core.utils.Tree;
import com.stratio.streaming.api.IStratioStreamingAPI;
import com.stratio.streaming.commons.messages.ColumnNameTypeValue;
/**
* Class that models a {@code SELECT} statement from the META language.
*/
public class SelectStatement extends MetaStatement {
/**
* Maximum limit of rows to be retreived in a query.
*/
private static final int MAX_LIMIT = 10000;
/**
* The {@link com.stratio.meta.core.structures.SelectionClause} of the Select statement.
*/
private SelectionClause selectionClause = null;
/**
* The name of the target table.
*/
private final String tableName;
/**
* Whether a time window has been specified in the Select statement.
*/
private boolean windowInc = false;
/**
* The {@link com.stratio.meta.core.structures.WindowSelect} specified in the Select statement for
* streaming queries.
*/
private WindowSelect window = null;
/**
* Whether a JOIN clause has been specified.
*/
private boolean joinInc = false;
/**
* The {@link com.stratio.meta.core.structures.InnerJoin} clause.
*/
private InnerJoin join = null;
/**
* Whether the Select contains a WHERE clause.
*/
private boolean whereInc = false;
/**
* The list of {@link com.stratio.meta.core.structures.Relation} found in the WHERE clause.
*/
private List<Relation> where = null;
/**
* Whether an ORDER BY clause has been specified.
*/
private boolean orderInc = false;
/**
* The list of {@link com.stratio.meta.core.structures.Ordering} clauses.
*/
private List<Ordering> order = null;
/**
* Whether a GROUP BY clause has been specified.
*/
private boolean groupInc = false;
/**
* The {@link com.stratio.meta.core.structures.GroupBy} clause.
*/
private List<GroupBy> group = null;
/**
* Whether a LIMIT clause has been specified.
*/
private boolean limitInc = false;
/**
* The LIMIT in terms of the number of rows to be retrieved in the result of the SELECT statement.
*/
private int limit = 0;
/**
* Flag to disable complex analytic functions such as INNER JOIN.
*/
private boolean disableAnalytics = false;
// TODO: We should probably remove this an pass it as parameters.
/**
* The {@link com.stratio.meta.core.metadata.MetadataManager} used to retrieve table metadata
* during the validation process and the statement execution phase.
*/
private MetadataManager metadata = null;
/**
* The {@link com.datastax.driver.core.TableMetadata} associated with the table specified in the
* FROM of the Select statement.
*/
private TableMetadata tableMetadataFrom = null;
/**
* Map with the collection of {@link com.datastax.driver.core.ColumnMetadata} associated with the
* tables specified in the FROM and the INNER JOIN parts of the Select statement. A virtual table
* named {@code any} is used to match unqualified column names.
*/
private Map<String, Collection<ColumnMetadata>> columns = new HashMap<>();
private boolean streamMode = false;
/**
* Class logger.
*/
private static final Logger LOG = Logger.getLogger(SelectStatement.class);
private Map<String, String> fieldsAliasesMap;
/**
* Class constructor.
*
* @param tableName The name of the target table.
*/
public SelectStatement(String tableName) {
this.command = false;
if (tableName.contains(".")) {
String[] ksAndTablename = tableName.split("\\.");
this.setKeyspace(ksAndTablename[0]);
this.tableName = ksAndTablename[1];
} else {
this.tableName = tableName;
}
}
/**
* Class constructor.
*
* @param selectionClause The {@link com.stratio.meta.core.structures.SelectionClause} of the
* Select statement.
* @param tableName The name of the target table.
*/
public SelectStatement(SelectionClause selectionClause, String tableName) {
this(tableName);
this.selectionClause = selectionClause;
this.selectionClause.addTablename(this.tableName);
}
/**
* Get the name of the target table.
*
* @return The table name.
*/
public String getTableName() {
return tableName;
}
/**
* Get the {@link com.stratio.meta.core.structures.SelectionClause}.
*
* @return The selection clause.
*/
public SelectionClause getSelectionClause() {
return selectionClause;
}
/**
* Set the {@link com.stratio.meta.core.structures.SelectionClause} for selecting columns.
*
* @param selectionClause selection clause.
*/
public void setSelectionClause(SelectionClause selectionClause) {
this.selectionClause = selectionClause;
}
/**
* Set the {@link com.stratio.meta.core.structures.WindowSelect} for streaming queries.
*
* @param window The window.
*/
public void setWindow(WindowSelect window) {
this.windowInc = true;
this.window = window;
}
/**
* Get the Join clause.
*
* @return The Join or null if not set.
*/
public InnerJoin getJoin() {
return join;
}
/**
* Set the {@link com.stratio.meta.core.structures.InnerJoin} clause.
*
* @param join The join clause.
*/
public void setJoin(InnerJoin join) {
this.joinInc = true;
this.join = join;
}
/**
* Get the list of {@link Relation} in the where clause.
*
* @return The list of relations.
*/
public List<Relation> getWhere() {
return where;
}
/**
* Set the list of {@link Relation} in the where clause.
*
* @param where The list of relations.
*/
public void setWhere(List<Relation> where) {
this.whereInc = true;
this.where = where;
}
/**
* Set the {@link Ordering} in the ORDER BY clause.
*
* @param order The order.
*/
public void setOrder(List<Ordering> order) {
this.orderInc = true;
this.order = order;
}
/**
* Return ORDER BY clause.
*
* @return list of {@link com.stratio.meta.core.structures.Ordering}.
*/
public List<Ordering> getOrder() {
return order;
}
/**
* Check if ORDER BY clause is included.
*
* @return {@code true} if is included.
*/
public boolean isOrderInc() {
return orderInc;
}
/**
* Set the {@link com.stratio.meta.core.structures.GroupBy} clause.
*
* @param group The group by.
*/
public void setGroup(List<GroupBy> group) {
this.groupInc = true;
this.group = group;
}
public void setGroup(GroupBy groupBy) {
this.groupInc = true;
group = new ArrayList<>();
group.add(groupBy);
}
/**
* Return GROUP BY clause.
*
* @return list of {@link com.stratio.meta.core.structures.GroupBy}.
*/
public List<GroupBy> getGroup() {
return group;
}
/**
* Check if GROUP BY clause is included.
*
* @return {@code true} if is included.
*/
public boolean isGroupInc() {
return groupInc;
}
/**
* Check if a WHERE clause is included.
*
* @return Whether it is included.
*/
public boolean isWhereInc() {
return whereInc;
}
/**
* Set the LIMIT of the query.
*
* @param limit The maximum number of rows to be returned.
*/
public void setLimit(int limit) {
this.limitInc = true;
if (limit <= MAX_LIMIT) {
this.limit = limit;
} else {
this.limit = MAX_LIMIT;
}
}
public int getLimit() {
return limit;
}
public WindowSelect getWindow() {
return window;
}
public MetadataManager getMetadata() {
return metadata;
}
/**
* Disable the analytics mode.
*
* @param disableAnalytics Whether analytics are enable (default) or not.
*/
public void setDisableAnalytics(boolean disableAnalytics) {
this.disableAnalytics = disableAnalytics;
}
/**
* Add a {@link com.stratio.meta.core.structures.SelectionSelector} to the
* {@link com.stratio.meta.core.structures.SelectionClause}.
*
* @param selSelector The new selector.
*/
public void addSelection(SelectionSelector selSelector) {
if (selectionClause == null) {
SelectionSelectors selSelectors = new SelectionSelectors();
selectionClause = new SelectionList(selSelectors);
}
SelectionList selList = (SelectionList) selectionClause;
SelectionSelectors selSelectors = (SelectionSelectors) selList.getSelection();
selSelectors.addSelectionSelector(selSelector);
}
public Map<String, String> getFieldsAliasesMap() {
/*
if(selectionClause instanceof SelectionCount){
fieldsAliasesMap.clear();
fieldsAliasesMap.put("COUNT", "COUNT");
}
*/
return fieldsAliasesMap;
}
public void setFieldsAliasesMap(Map<String, String> fieldsAliasesMap) {
this.fieldsAliasesMap = fieldsAliasesMap;
}
/**
* Creates a String representing the Statement with META syntax.
*
* @return String
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder("SELECT ");
if (selectionClause != null) {
sb.append(selectionClause.toString());
}
sb.append(" FROM ");
if (this.isKeyspaceIncluded()) {
sb.append(this.getEffectiveKeyspace()).append(".");
}
sb.append(tableName);
if (windowInc) {
sb.append(" WITH WINDOW ").append(window.toString());
}
if (joinInc) {
sb.append(" INNER JOIN ").append(join.toString());
}
if (whereInc) {
sb.append(" WHERE ");
sb.append(ParserUtils.stringList(where, " AND "));
}
if (orderInc) {
sb.append(" ORDER BY ").append(ParserUtils.stringList(order, ", "));
}
if (groupInc) {
sb.append(" GROUP BY ").append(ParserUtils.stringList(group, ", "));
}
if (limitInc) {
sb.append(" LIMIT ").append(limit);
}
if (disableAnalytics) {
sb.append(" DISABLE ANALYTICS");
}
return sb.toString().replace(" ", " ");
}
/** {@inheritDoc} */
@Override
public Result validate(MetadataManager metadata, EngineConfig config) {
// Validate FROM keyspace
Result result = validateKeyspaceAndTable(metadata, this.getEffectiveKeyspace(), tableName);
if ((!result.hasError()) && (result instanceof CommandResult)
&& ("streaming".equalsIgnoreCase(((CommandResult) result).getResult().toString()))) {
streamMode = true;
}
if (!streamMode && windowInc) {
result =
Result
.createValidationErrorResult("Window option can only be applied to ephemeral tables.");
}
if (streamMode && !windowInc) {
result = Result.createValidationErrorResult("Window is mandatory for ephemeral tables.");
}
if (!result.hasError() && joinInc) {
result =
validateKeyspaceAndTable(metadata,
join.findEffectiveKeyspace(this.getEffectiveKeyspace()), join.getTablename());
}
String effectiveKs1 = getEffectiveKeyspace();
String effectiveKs2 = null;
if (joinInc) {
SelectStatement secondSelect = new SelectStatement("");
if (join.getKeyspace() != null) {
secondSelect.setKeyspace(join.getKeyspace());
}
secondSelect.setSessionKeyspace(this.getEffectiveKeyspace());
effectiveKs2 = secondSelect.getEffectiveKeyspace();
}
TableMetadata tableMetadataJoin = null;
com.stratio.meta.common.metadata.structures.TableMetadata streamingMetadata = null;
if (!result.hasError()) {
// Cache Metadata manager and table metadata for the getDriverStatement.
this.metadata = metadata;
if (streamMode) {
streamingMetadata = metadata.convertStreamingToMeta(getEffectiveKeyspace(), tableName);
} else {
tableMetadataFrom = metadata.getTableMetadata(effectiveKs1, tableName);
}
if (joinInc) {
tableMetadataJoin = metadata.getTableMetadata(effectiveKs2, join.getTablename());
}
if (streamMode) {
result = validateSelectionColumns(streamingMetadata, tableMetadataJoin);
} else {
result = validateSelectionColumns(tableMetadataFrom, tableMetadataJoin);
}
if (!result.hasError()) {
result = validateOptions();
}
}
if (!result.hasError() && joinInc) {
if (streamMode) {
result = validateJoinClause(streamingMetadata, tableMetadataJoin);
} else {
result = validateJoinClause(tableMetadataFrom, tableMetadataJoin);
}
}
if (!result.hasError() && whereInc) {
if (streamMode) {
result =
Result
.createValidationErrorResult(
"Where clauses in ephemeral tables are not supported yet.");
} else {
result = validateWhereClauses(tableMetadataFrom, tableMetadataJoin);
}
}
/*
* if(!result.hasError() && windowInc){ result = validateWindow(config); }
*/
return result;
}
private Result validateWindow(EngineConfig config) {
Result result = QueryResult.createSuccessQueryResult();
if (window instanceof WindowTime) {
WindowTime windowTime = (WindowTime) window;
long windowMillis = windowTime.getDurationInMilliseconds();
if (windowMillis % config.getStreamingDuration() != 0) {
result =
Result.createValidationErrorResult("Window time must be multiple of "
+ config.getStreamingDuration() + " milliseconds.");
}
} else {
result = Result.createValidationErrorResult("This type of window is not supported yet.");
}
return result;
}
/**
* Validate the supported select options.
*
* @return A {@link com.stratio.meta.common.result.Result} with the validation result.
*/
private Result validateOptions() {
Result result = QueryResult.createSuccessQueryResult();
if (groupInc) {
result = validateGroupByClause();
}
if (orderInc) {
result = validateOrderByClause();
}
return result;
}
private boolean checkSelectorExists(SelectorIdentifier selector) {
return !findColumn(selector.getTable(), selector.getField()).hasError();
}
/**
* Validate the JOIN clause.
*
* @param tableFrom The table in the FROM clause.
* @param tableJoin The table in the JOIN clause.
* @return Whether the specified table names and fields are valid.
*/
private Result validateJoinClause(TableMetadata tableFrom, TableMetadata tableJoin) {
Result result = QueryResult.createSuccessQueryResult();
if (joinInc) {
if (!checkSelectorExists(join.getLeftField())) {
result =
Result.createValidationErrorResult("Join selector " + join.getLeftField().toString()
+ " table or column name not found");
}
if (!checkSelectorExists(join.getRightField())) {
result =
Result.createValidationErrorResult("Join selector " + join.getRightField().toString()
+ " table or column name not found");
}
}
return result;
}
private Result validateJoinClause(
com.stratio.meta.common.metadata.structures.TableMetadata streamingMetadata,
TableMetadata tableMetadataJoin) {
Result result = QueryResult.createSuccessQueryResult();
if (joinInc) {
SelectorIdentifier leftField = join.getLeftField();
SelectorIdentifier rightField = join.getRightField();
boolean streamingLeft = false;
boolean batchLeft = false;
if (leftField.getTable().equalsIgnoreCase(streamingMetadata.getTableName())) {
if (streamingMetadata.getColumn(leftField.getField()) == null) {
result =
Result.createValidationErrorResult("Ephemeral table '"
+ streamingMetadata.getTableName() + "' doesn't contain the field '"
+ leftField.getField() + "'.");
} else {
streamingLeft = true;
}
} else if (leftField.getTable().equalsIgnoreCase(tableMetadataJoin.getName())) {
if (tableMetadataJoin.getColumn(leftField.getField()) == null) {
result =
Result.createValidationErrorResult("Table '" + tableMetadataJoin.getName()
+ "' doesn't contain the field '" + leftField.getField() + "'.");
} else {
batchLeft = true;
}
} else {
result =
Result.createValidationErrorResult("Table '" + leftField.getTable()
+ "' doesn't match any of the incoming tables.");
}
if (!result.hasError()) {
if (streamingLeft) {
if (tableMetadataJoin.getColumn(rightField.getField()) == null) {
result =
Result.createValidationErrorResult("Table '" + tableMetadataJoin.getName()
+ "' doesn't contain the field '" + rightField.getField() + "'.");
}
} else if (batchLeft) {
if (streamingMetadata.getColumn(rightField.getField()) == null) {
result =
Result.createValidationErrorResult("Ephemeral table '"
+ streamingMetadata.getTableName() + "' doesn't contain the field '"
+ rightField.getField() + "'.");
}
}
}
}
return result;
}
/**
* Validate a relation found in a where clause.
*
* @param targetTable The target table.
* @param column The name of the column.
* @param terms The terms.
* @param rc Relation of Comparator type.
* @return Whether the relation is valid.
*/
private Result validateWhereSingleColumnRelation(String targetTable, String column,
List<Term<?>> terms, Relation rc) {
Result result = QueryResult.createSuccessQueryResult();
String operator = rc.getOperator();
ColumnMetadata cm = findColumnMetadata(targetTable, column);
if (cm != null) {
Iterator<Term<?>> termsIt = terms.iterator();
Class<?> columnType = cm.getType().asJavaClass();
while (!result.hasError() && termsIt.hasNext()) {
Term<?> term = termsIt.next();
if (!columnType.equals(term.getTermClass())) {
result =
Result.createValidationErrorResult("Column [" + column + "] of type [" + columnType
+ "] does not accept " + term.getTermClass() + " values (" + term.toString()
+ ")");
}
}
if (Boolean.class.equals(columnType)) {
boolean supported = true;
switch (operator) {
case ">":
case "<":
case ">=":
case "<=":
case "in":
case "between":
supported = false;
break;
default:
break;
}
if (!supported) {
result =
Result.createValidationErrorResult("Operand " + operator + " not supported for"
+ " column " + column + ".");
}
}
} else {
result =
Result.createValidationErrorResult("Column " + column + " not found in " + targetTable
+ " table.");
}
return result;
}
/**
* Validate that the where clause is valid by checking that columns exists on the target table and
* that the comparisons are semantically valid.
*
* @return A {@link com.stratio.meta.common.result.Result} with the validation result.
*/
private Result validateWhereClauses(TableMetadata tableMetadata, TableMetadata tableMetadataJoin) {
// TODO: Check that the MATCH operator is only used in Lucene mapped columns.
Result result = QueryResult.createSuccessQueryResult();
Iterator<Relation> relations = where.iterator();
while (!result.hasError() && relations.hasNext()) {
Relation relation = relations.next();
if (tableMetadata.getName().equalsIgnoreCase(relation.getIdentifiers().get(0).getTable())
|| (relation.getIdentifiers().get(0).getTable() == null)) {
relation.updateTermClass(tableMetadata);
} else {
relation.updateTermClass(tableMetadataJoin);
}
if (Relation.TYPE_COMPARE == relation.getType() || Relation.TYPE_IN == relation.getType()
|| Relation.TYPE_BETWEEN == relation.getType()) {
// Check comparison, =, >, <, etc.
// RelationCompare rc = RelationCompare.class.cast(relation);
String column = relation.getIdentifiers().get(0).toString();
// Determine the target table the column belongs to.
String targetTable = "any";
if (column.contains(".")) {
String[] tableAndColumn = column.split("\\.");
targetTable = tableAndColumn[0];
column = tableAndColumn[1];
}
// Check terms types
result =
validateWhereSingleColumnRelation(targetTable, column, relation.getTerms(), relation);
if ("match".equalsIgnoreCase(relation.getOperator()) && joinInc) {
result =
Result
.createValidationErrorResult("Select statements with 'Inner Join' don't support MATCH operator.");
}
} else if (Relation.TYPE_TOKEN == relation.getType()) {
// TODO: Check TOKEN relation
result = Result.createValidationErrorResult("TOKEN function not supported.");
}
}
return result;
}
/**
* Validate whether the group by clause is valid or not by checking columns exist on the target
* table and comparisons are semantically correct.
*
* @return A {@link com.stratio.meta.common.result.Result} with the validation result.
*/
private Result validateGroupByClause() {
Result result = QueryResult.createSuccessQueryResult();
List<String> selectionCols = this.getSelectionClause().getIds(false);
for (GroupBy groupByCol : this.group) {
String col = groupByCol.toString();
if (!selectionCols.contains(col)) {
this.getSelectionClause().getIds(false).add(col);
}
}
return result;
}
/**
* Validate whether the group by clause is valid or not by checking columns exist on the target
* table and comparisons are semantically correct.
*
* @return A {@link com.stratio.meta.common.result.Result} with the validation result.
*/
private Result validateOrderByClause() {
Result result = QueryResult.createSuccessQueryResult();
for (Ordering orderField : order) {
String field = orderField.getSelectorIdentifier().toString();
String targetTable = "any";
String columnName = field;
if (field.contains(".")) {
targetTable = field.substring(0, field.indexOf("."));
columnName = field.substring(field.indexOf(".") + 1);
}
Result columnResult = findColumn(targetTable, columnName);
if (columnResult.hasError()) {
result = columnResult;
}
}
return result;
}
/**
* Find a column in the selected tables.
*
* @param table The target table of the column.
* @param column The name of the column.
* @return A {@link com.stratio.meta.common.result.Result}.
*/
private Result findColumn(String table, String column) {
Result result = QueryResult.createSuccessQueryResult();
boolean found = false;
if (columns.get(table) != null) {
Iterator<ColumnMetadata> it = columns.get(table).iterator();
while (!found && it.hasNext()) {
ColumnMetadata cm = it.next();
if (cm.getName().equals(column)) {
found = true;
}
}
if (!found) {
result =
Result.createValidationErrorResult("Column " + column + " does not " + "exist in "
+ table + " table.");
}
} else {
result =
Result.createValidationErrorResult("Column " + column + " refers to table " + table
+ " that has not been specified on query.");
}
return result;
}
/**
* Find a column in the selected tables.
*
* @param table The target table of the column.
* @param column The name of the column.
* @return A {@link com.datastax.driver.core.ColumnMetadata} or null if not found.
*/
private ColumnMetadata findColumnMetadata(String table, String column) {
ColumnMetadata result = null;
boolean found = false;
if (columns.get(table) != null) {
Iterator<ColumnMetadata> it = columns.get(table).iterator();
while (!found && it.hasNext()) {
ColumnMetadata cm = it.next();
if (cm.getName().equals(column)) {
found = true;
result = cm;
}
}
}
return result;
}
/**
* Validate that the columns specified in the select are valid by checking that the selection
* columns exists in the table.
*
* @param tableFrom The {@link com.datastax.driver.core.TableMetadata} associated with the FROM
* table.
* @param tableJoin The {@link com.datastax.driver.core.TableMetadata} associated with the JOIN
* table.
* @return A {@link com.stratio.meta.common.result.Result} with the validation result.
*/
private Result validateSelectionColumns(TableMetadata tableFrom, TableMetadata tableJoin) {
Result result = QueryResult.createSuccessQueryResult();
if (streamMode && (selectionClause instanceof SelectionList)
&& (((SelectionList) selectionClause).getTypeSelection() == Selection.TYPE_SELECTOR)) {
List<String> colNames =
metadata.getStreamingColumnNames(getEffectiveKeyspace() + "_" + tableName);
SelectionList selectionList = (SelectionList) selectionClause;
SelectionSelectors selectionSelectors = (SelectionSelectors) selectionList.getSelection();
selectionSelectors.getSelectors();
for (SelectionSelector selectionSelector : selectionSelectors.getSelectors()) {
SelectorIdentifier selectorIdentifier =
(SelectorIdentifier) selectionSelector.getSelector();
String colName = selectorIdentifier.getField();
if (!colNames.contains(colName.toLowerCase())) {
return Result.createValidationErrorResult("Column '" + colName
+ "' not found in ephemeral table '" + getEffectiveKeyspace() + "." + tableName
+ "'.");
}
}
}
if (streamMode) {
return result;
}
// Create a HashMap with the columns
Collection<ColumnMetadata> allColumns = new ArrayList<>();
columns.put(tableFrom.getName(), tableFrom.getColumns());
allColumns.addAll(tableFrom.getColumns());
if (joinInc) {
// TODO: Check that what happens if two columns from t1 and t2 have the same name.
columns.put(tableJoin.getName(), tableJoin.getColumns());
allColumns.addAll(tableJoin.getColumns());
}
columns.put("any", allColumns);
Result columnResult = null;
boolean check = false;
SelectionList sl = null;
if (selectionClause.getType() == SelectionClause.TYPE_SELECTION) {
sl = SelectionList.class.cast(selectionClause);
// Check columns only if an asterisk is not selected.
if (sl.getSelection().getType() == Selection.TYPE_SELECTOR) {
check = true;
}
}
if (!check) {
return result;
}
SelectionSelectors ss = SelectionSelectors.class.cast(sl.getSelection());
for (SelectionSelector selector : ss.getSelectors()) {
if (selector.getSelector() instanceof SelectorIdentifier) {
SelectorIdentifier si = SelectorIdentifier.class.cast(selector.getSelector());
columnResult = findColumn(si.getTable(), si.getField());
if (columnResult.hasError()) {
result = columnResult;
}
} else if (selector.getSelector() instanceof SelectorGroupBy) {
if (groupInc) {
SelectorGroupBy selectorMeta = (SelectorGroupBy) selector.getSelector();
if (!selectorMeta.getGbFunction().equals(GroupByFunction.COUNT)) {
// Checking column in the group by aggregation function
if (selectorMeta.getParam().getType() == SelectorMeta.TYPE_IDENT) {
SelectorIdentifier subselectorIdentifier =
(SelectorIdentifier) selectorMeta.getParam();
columnResult =
findColumn(subselectorIdentifier.getTable(), subselectorIdentifier.getField());
if (columnResult.hasError()) {
result = columnResult;
}
} else {
result =
Result
.createValidationErrorResult("Nested functions on selected fields not supported.");
}
}
}
} else {
result =
Result.createValidationErrorResult("Functions type on selected fields not supported.");
}
}
return result;
}
private Result validateSelectionColumns(
com.stratio.meta.common.metadata.structures.TableMetadata streamingMetadata,
TableMetadata tableJoin) {
Result result = QueryResult.createSuccessQueryResult();
if ((selectionClause instanceof SelectionList)
&& (((SelectionList) selectionClause).getTypeSelection() == Selection.TYPE_SELECTOR)) {
SelectionList selectionList = (SelectionList) selectionClause;
SelectionSelectors selectionSelectors = (SelectionSelectors) selectionList.getSelection();
selectionSelectors.getSelectors();
for (SelectionSelector selectionSelector : selectionSelectors.getSelectors()) {
SelectorIdentifier selectorIdentifier =
(SelectorIdentifier) selectionSelector.getSelector();
String tableName = selectorIdentifier.getTable();
String colName = selectorIdentifier.getField();
result = findColumn(streamingMetadata, tableJoin, colName);
}
}
return result;
}
private Result findColumn(
com.stratio.meta.common.metadata.structures.TableMetadata streamingMetadata,
TableMetadata tableJoin, String colName) {
Result result = QueryResult.createSuccessQueryResult();
if (tableName.equalsIgnoreCase(streamingMetadata.getTableName())) {
if (streamingMetadata.getColumn(colName) == null) {
result =
Result.createValidationErrorResult("Field '" + colName
+ "' not found in ephemeral table '" + tableName + "'.");
}
} else if (tableName.equalsIgnoreCase(tableJoin.getName())) {
if (tableJoin.getColumn(colName) == null) {
result =
Result.createValidationErrorResult("Field '" + colName + "' not found in table '"
+ tableName + "'.");
}
} else {
result =
Result.createValidationErrorResult("Table '" + tableName
+ "' doesn't match to any incoming tables.");
}
return result;
}
/**
* Get the processed where clause to be sent to Cassandra related with lucene indexes.
*
* @param metadata The {@link com.stratio.meta.core.metadata.MetadataManager} that provides the
* required information.
* @param tableMetadata The associated {@link com.datastax.driver.core.TableMetadata}.
* @return A String array with the column name and the lucene query, or null if no index is found.
*/
public String[] getLuceneWhereClause(MetadataManager metadata, TableMetadata tableMetadata) {
String[] result = null;
CustomIndexMetadata luceneIndex = metadata.getLuceneIndex(tableMetadata);
int addedClauses = 0;
if (luceneIndex != null) {
// TODO: Check in the validator that the query uses AND with the lucene mapped columns.
StringBuilder sb = new StringBuilder("{filter:{type:\"boolean\",must:[");
// Iterate throughout the relations of the where clause looking for MATCH.
for (Relation relation : where) {
if (Relation.TYPE_COMPARE == relation.getType()
&& "MATCH".equalsIgnoreCase(relation.getOperator())) {
RelationCompare rc = RelationCompare.class.cast(relation);
// String column = rc.getIdentifiers().get(0).toString();
String column = rc.getIdentifiers().get(0).getField();
String value = rc.getTerms().get(0).toString();
// Generate query for column
String[] processedQuery = processLuceneQueryType(value);
sb.append("{type:\"");
sb.append(processedQuery[0]);
sb.append("\",field:\"");
sb.append(column);
sb.append("\",value:\"");
sb.append(processedQuery[1]);
sb.append("\"},");
addedClauses++;
}
}
sb.replace(sb.length() - 1, sb.length(), "");
sb.append("]}}");
if (addedClauses > 0) {
result = new String[] {luceneIndex.getIndexName(), sb.toString()};
}
}
return result;
}
/**
* Process a query pattern to determine the type of Lucene query. The supported types of queries
* are: <li>
* <ul>
* Wildcard: The query contains * or ?.
* </ul>
* <ul>
* Fuzzy: The query ends with ~ and a number.
* </ul>
* <ul>
* Regex: The query contains [ or ].
* </ul>
* <ul>
* Match: Default query, supporting escaped symbols: *, ?, [, ], etc.
* </ul>
* </li>
*
* @param query The user query.
* @return An array with the type of query and the processed query.
*/
protected String[] processLuceneQueryType(String query) {
String[] result = {"", ""};
Pattern escaped = Pattern.compile(".*\\\\\\*.*|.*\\\\\\?.*|.*\\\\\\[.*|.*\\\\\\].*");
Pattern wildcard = Pattern.compile(".*\\*.*|.*\\?.*");
Pattern regex = Pattern.compile(".*\\].*|.*\\[.*");
Pattern fuzzy = Pattern.compile(".*~\\d+");
if (escaped.matcher(query).matches()) {
result[0] = "match";
result[1] =
query.replace("\\*", "*").replace("\\?", "?").replace("\\]", "]").replace("\\[", "[");
} else if (regex.matcher(query).matches()) {
result[0] = "regex";
result[1] = query;
} else if (fuzzy.matcher(query).matches()) {
result[0] = "fuzzy";
result[1] = query;
} else if (wildcard.matcher(query).matches()) {
result[0] = "wildcard";
result[1] = query;
} else {
result[0] = "match";
result[1] = query;
}
// C* Query builder doubles the ' character.
result[1] = result[1].replaceAll("^'", "").replaceAll("'$", "");
return result;
}
/**
* Creates a String representing the Statement with CQL syntax.
*
* @return
*/
@Override
public String translateToCQL(MetadataManager metadataManager) {
StringBuilder sb = new StringBuilder(this.toString());
if (sb.toString().contains("TOKEN(")) {
int currentLength = 0;
int newLength = sb.toString().length();
while (newLength != currentLength) {
currentLength = newLength;
sb = new StringBuilder(sb.toString().replaceAll("(.*)" // $1
+ "(=|<|>|<=|>=|<>|LIKE)" // $2
+ "(\\s?)" // $3
+ "(TOKEN\\()" // $4
+ "([^'][^\\)]+)" // $5
+ "(\\).*)", // $6
"$1$2$3$4'$5'$6"));
sb = new StringBuilder(sb.toString().replaceAll("(.*TOKEN\\(')" // $1
+ "([^,]+)" // $2
+ "(,)" // $3
+ "(\\s*)" // $4
+ "([^']+)" // $5
+ "(')" // $6
+ "(\\).*)", // $7
"$1$2'$3$4'$5$6$7"));
sb = new StringBuilder(sb.toString().replaceAll("(.*TOKEN\\(')" // $1
+ "(.+)" // $2
+ "([^'])" // $3
+ "(,)" // $4
+ "(\\s*)" // $5
+ "([^']+)" // $6
+ "(')" // $7
+ "(\\).*)", // $8
"$1$2$3'$4$5'$6$7$8"));
sb = new StringBuilder(sb.toString().replaceAll("(.*TOKEN\\(')" // $1
+ "(.+)" // $2
+ "([^'])" // $3
+ "(,)" // $4
+ "(\\s*)" // $5
+ "([^']+)" // $6
+ "(')" // $7
+ "([^TOKEN]+)" // $8
+ "('\\).*)", // $9
"$1$2$3'$4$5'$6$7$8$9"));
newLength = sb.toString().length();
}
}
return sb.toString();
}
@Override
public String translateToSiddhi(IStratioStreamingAPI stratioStreamingAPI, String streamName,
String outgoing) {
StringBuilder querySb = new StringBuilder("from ");
querySb.append(streamName);
if (windowInc) {
querySb.append("#window.timeBatch( ").append(getWindow().toString().toLowerCase())
.append(" )");
}
List<String> ids = new ArrayList<>();
boolean asterisk = false;
SelectionClause selectionClause = getSelectionClause();
if (selectionClause.getType() == SelectionClause.TYPE_SELECTION) {
SelectionList selectionList = (SelectionList) selectionClause;
Selection selection = selectionList.getSelection();
if (selection.getType() == Selection.TYPE_ASTERISK) {
asterisk = true;
}
}
if (asterisk) {
List<ColumnNameTypeValue> cols = null;
try {
cols = stratioStreamingAPI.columnsFromStream(streamName);
} catch (Exception e) {
LOG.error(e);
}
for (ColumnNameTypeValue ctv : cols) {
ids.add(ctv.getColumn());
}
} else {
ids = getSelectionClause().getFields();
}
String idsStr = Arrays.toString(ids.toArray()).replace("[", "").replace("]", "");
querySb.append(" select ").append(idsStr).append(" insert into ");
querySb.append(outgoing);
return querySb.toString();
}
/**
* Get the driver representation of the fields found in the selection clause.
*
* @param selSelectors The selectors.
* @param selection The current Select.Selection.
* @return A {@link com.datastax.driver.core.querybuilder.Select.Selection}.
*/
private Select.Selection getDriverBuilderSelection(SelectionSelectors selSelectors,
Select.Selection selection) {
Select.Selection result = selection;
for (SelectionSelector selSelector : selSelectors.getSelectors()) {
SelectorMeta selectorMeta = selSelector.getSelector();
if (selectorMeta.getType() == SelectorMeta.TYPE_IDENT) {
SelectorIdentifier selIdent = (SelectorIdentifier) selectorMeta;
if (selSelector.isAliasInc()) {
result = result.column(selIdent.getField()).as(selSelector.getAlias());
} else {
result = result.column(selIdent.getField());
}
} else if (selectorMeta.getType() == SelectorMeta.TYPE_FUNCTION) {
SelectorFunction selFunction = (SelectorFunction) selectorMeta;
List<SelectorMeta> params = selFunction.getParams();
Object[] innerFunction = new Object[params.size()];
int pos = 0;
for (SelectorMeta selMeta : params) {
innerFunction[pos] = QueryBuilder.raw(selMeta.toString());
pos++;
}
result = result.fcall(selFunction.getName(), innerFunction);
}
}
return result;
}
/**
* Get the driver builder object with the selection clause.
*
* @return A {@link com.datastax.driver.core.querybuilder.Select.Builder}.
*/
private Select.Builder getDriverBuilder() {
Select.Builder builder;
if (selectionClause.getType() == SelectionClause.TYPE_COUNT) {
builder = QueryBuilder.select().countAll();
} else {
// Selection type
SelectionList selList = (SelectionList) selectionClause;
if (selList.getSelection().getType() != Selection.TYPE_ASTERISK) {
Select.Selection selection = QueryBuilder.select();
if (selList.isDistinct()) {
selection = selection.distinct();
}
// Select the required columns.
SelectionSelectors selSelectors = (SelectionSelectors) selList.getSelection();
builder = getDriverBuilderSelection(selSelectors, selection);
} else {
builder = QueryBuilder.select().all();
}
}
return builder;
}
/**
* Cast an input value to the class associated with the comparison column.
*
* @param columnName The name of the column.
* @param value The initial value.
* @return A casted object.
*/
private Object getWhereCastValue(String columnName, Object value) {
Object result = null;
Class<?> clazz = tableMetadataFrom.getColumn(columnName).getType().asJavaClass();
if (String.class.equals(clazz)) {
result = String.class.cast(value);
} else if (UUID.class.equals(clazz)) {
result = UUID.fromString(String.class.cast(value));
} else if (Date.class.equals(clazz)) {
// TODO getWhereCastValue with date
result = null;
} else {
try {
if (value.getClass().equals(clazz)) {
result = clazz.getConstructor(String.class).newInstance(value.toString());
} else {
Method m = clazz.getMethod("valueOf", value.getClass());
result = m.invoke(value);
}
} catch (InstantiationException | IllegalAccessException | InvocationTargetException
| NoSuchMethodException e) {
LOG.error("Cannot parse input value", e);
}
}
return result;
}
/**
* Get the driver clause associated with a compare relation.
*
* @param metaRelation The {@link com.stratio.meta.core.structures.RelationCompare} clause.
* @return A {@link com.datastax.driver.core.querybuilder.Clause}.
*/
private Clause getRelationCompareClause(Relation metaRelation) {
Clause clause = null;
RelationCompare relCompare = (RelationCompare) metaRelation;
String field = relCompare.getIdentifiers().get(0).getField();
Object value = relCompare.getTerms().get(0).getTermValue();
value = getWhereCastValue(field, value);
switch (relCompare.getOperator().toUpperCase()) {
case "=":
clause = QueryBuilder.eq(field, value);
break;
case ">":
clause = QueryBuilder.gt(field, value);
break;
case ">=":
clause = QueryBuilder.gte(field, value);
break;
case "<":
clause = QueryBuilder.lt(field, value);
break;
case "<=":
clause = QueryBuilder.lte(field, value);
break;
case "MATCH":
// Processed as LuceneIndex
break;
default:
LOG.error("Unsupported operator: " + relCompare.getOperator());
break;
}
return clause;
}
/**
* Get the driver clause associated with an in relation.
*
* @param metaRelation The {@link com.stratio.meta.core.structures.RelationIn} clause.
* @return A {@link com.datastax.driver.core.querybuilder.Clause}.
*/
private Clause getRelationInClause(Relation metaRelation) {
Clause clause = null;
RelationIn relIn = (RelationIn) metaRelation;
List<Term<?>> terms = relIn.getTerms();
String field = relIn.getIdentifiers().get(0).getField();
Object[] values = new Object[relIn.numberOfTerms()];
int nTerm = 0;
for (Term<?> term : terms) {
values[nTerm] = getWhereCastValue(field, term.getTermValue());
nTerm++;
}
clause = QueryBuilder.in(relIn.getIdentifiers().get(0).toString(), values);
return clause;
}
/**
* Get the driver clause associated with an token relation.
*
* @param metaRelation The {@link com.stratio.meta.core.structures.RelationToken} clause.
* @return A {@link com.datastax.driver.core.querybuilder.Clause}.
*/
private Clause getRelationTokenClause(Relation metaRelation) {
Clause clause = null;
RelationToken relToken = (RelationToken) metaRelation;
List<String> names = new ArrayList<>();
for (SelectorIdentifier identifier : relToken.getIdentifiers()) {
names.add(identifier.toString());
}
if (!relToken.isRightSideTokenType()) {
Object value = relToken.getTerms().get(0).getTermValue();
switch (relToken.getOperator()) {
case "=":
clause =
QueryBuilder.eq(QueryBuilder.token(names.toArray(new String[names.size()])), value);
break;
case ">":
clause =
QueryBuilder.gt(QueryBuilder.token(names.toArray(new String[names.size()])), value);
break;
case ">=":
clause =
QueryBuilder.gte(QueryBuilder.token(names.toArray(new String[names.size()])), value);
break;
case "<":
clause =
QueryBuilder.lt(QueryBuilder.token(names.toArray(new String[names.size()])), value);
break;
case "<=":
clause =
QueryBuilder.lte(QueryBuilder.token(names.toArray(new String[names.size()])), value);
break;
default:
LOG.error("Unsupported operator " + relToken.getOperator());
break;
}
} else {
return null;
}
return clause;
}
/**
* Get the driver where clause.
*
* @param sel The current Select.
* @return A {@link com.datastax.driver.core.querybuilder.Select.Where}.
*/
private Where getDriverWhere(Select sel) {
Where whereStmt = null;
String[] luceneWhere = getLuceneWhereClause(metadata, tableMetadataFrom);
if (luceneWhere != null) {
Clause lc = QueryBuilder.eq(luceneWhere[0], luceneWhere[1]);
whereStmt = sel.where(lc);
}
for (Relation metaRelation : this.where) {
Clause clause = null;
switch (metaRelation.getType()) {
case Relation.TYPE_COMPARE:
clause = getRelationCompareClause(metaRelation);
break;
case Relation.TYPE_IN:
clause = getRelationInClause(metaRelation);
break;
case Relation.TYPE_TOKEN:
clause = getRelationTokenClause(metaRelation);
break;
default:
LOG.error("Unsupported relation type: " + metaRelation.getType());
break;
}
if (clause != null) {
if (whereStmt == null) {
whereStmt = sel.where(clause);
} else {
whereStmt = whereStmt.and(clause);
}
}
}
return whereStmt;
}
@Override
public Statement getDriverStatement() {
Select.Builder builder = getDriverBuilder();
Select sel = builder.from(this.getEffectiveKeyspace(), this.tableName);
if (this.limitInc) {
sel.limit(this.limit);
}
if (this.orderInc) {
com.datastax.driver.core.querybuilder.Ordering[] orderings =
new com.datastax.driver.core.querybuilder.Ordering[order.size()];
int nOrdering = 0;
for (Ordering metaOrdering : this.order) {
if (metaOrdering.isDirInc() && (metaOrdering.getOrderDir() == OrderDirection.DESC)) {
orderings[nOrdering] = QueryBuilder.desc(metaOrdering.getSelectorIdentifier().toString());
} else {
orderings[nOrdering] = QueryBuilder.asc(metaOrdering.getSelectorIdentifier().toString());
}
nOrdering++;
}
sel.orderBy(orderings);
}
Where whereStmt = null;
if (this.whereInc) {
whereStmt = getDriverWhere(sel);
} else {
whereStmt = sel.where();
}
LOG.trace("Executing: " + whereStmt.toString());
return whereStmt;
}
/**
* Find the table that contains the selected column.
*
* @param columnName The name of the column.
* @return The name of the table.
*/
private String findAssociatedTable(String columnName) {
String result = null;
boolean found = false;
String[] tableNames = columns.keySet().toArray(new String[columns.size()]);
for (int tableIndex = 0; tableIndex < tableNames.length && !found; tableIndex++) {
Iterator<ColumnMetadata> columnIterator = columns.get(tableNames[tableIndex]).iterator();
while (columnIterator.hasNext() && !found) {
ColumnMetadata cm = columnIterator.next();
if (cm.getName().equals(columnName)) {
result = cm.getTable().getName();
found = true;
}
}
}
return result;
}
/**
* Check whether a selection clause should be added to the new Select statement that will be
* generated as part of the planning process of a JOIN.
*
* @param select The {@link com.stratio.meta.core.statements.SelectStatement}.
* @param whereColumnName The name of the column.
* @return Whether it should be added or not.
*/
private boolean checkAddSelectionJoinWhere(SelectStatement select, String whereColumnName) {
Selection selList = ((SelectionList) this.selectionClause).getSelection();
boolean addCol = true;
if (selList instanceof SelectionSelectors) {
// Otherwise, it's an asterisk selection
// Add column to Select clauses if applied
SelectionList sClause = (SelectionList) select.getSelectionClause();
SelectionSelectors sSelectors = (SelectionSelectors) sClause.getSelection();
for (SelectionSelector ss : sSelectors.getSelectors()) {
SelectorIdentifier si = (SelectorIdentifier) ss.getSelector();
String colName = si.getField();
if (colName.equalsIgnoreCase(whereColumnName)) {
addCol = false;
break;
}
}
} else {
addCol = false;
}
return addCol;
}
/**
* Get a map of relations to be added to where clauses of the sub-select queries that will be
* executed for a JOIN select.
*
* @param firstSelect The first select statement.
* @param secondSelect The second select statement.
* @return A map with keys {@code 1} or {@code 2} for each select.
*/
private Map<Integer, List<Relation>> getWhereJoinPlan(SelectStatement firstSelect,
SelectStatement secondSelect) {
Map<Integer, List<Relation>> result = new HashMap<>();
List<Relation> firstWhere = new ArrayList<>();
List<Relation> secondWhere = new ArrayList<>();
result.put(1, firstWhere);
result.put(2, secondWhere);
List<Relation> targetWhere = null;
SelectStatement targetSelect = null;
for (Relation relation : where) {
String id = relation.getIdentifiers().iterator().next().toString();
String whereTableName = null;
String whereColumnName = null;
if (id.contains(".")) {
String[] tablenameAndColumnname = id.split("\\.");
whereTableName = tablenameAndColumnname[0];
whereColumnName = tablenameAndColumnname[1];
} else {
whereTableName = findAssociatedTable(id);
whereColumnName = id;
}
// Where clause corresponding to first table
if (tableName.equalsIgnoreCase(whereTableName)) {
targetWhere = firstWhere;
targetSelect = firstSelect;
} else {
targetWhere = secondWhere;
targetSelect = secondSelect;
}
targetWhere.add(new RelationCompare(whereColumnName, relation.getOperator(), relation
.getTerms().get(0)));
if (checkAddSelectionJoinWhere(targetSelect, whereColumnName)) {
targetSelect.addSelection(new SelectionSelector(new SelectorIdentifier(whereColumnName)));
}
}
return result;
}
/**
* Get the execution plan of a Join.
*
* @return The execution plan.
*/
private Tree getJoinPlan() {
Tree steps = new Tree();
SelectStatement firstSelect = new SelectStatement(tableName);
firstSelect.setSessionKeyspace(this.getEffectiveKeyspace());
firstSelect.setKeyspace(getEffectiveKeyspace());
SelectStatement secondSelect = new SelectStatement(this.join.getTablename());
if (this.join.getKeyspace() != null) {
secondSelect.setKeyspace(join.getKeyspace());
}
secondSelect.setSessionKeyspace(this.getEffectiveKeyspace());
SelectStatement joinSelect = new SelectStatement("");
// ADD FIELDS OF THE JOIN
if (this.join.getLeftField().getTable().trim().equalsIgnoreCase(tableName)) {
firstSelect.addSelection(new SelectionSelector(this.join.getLeftField()));
secondSelect.addSelection(new SelectionSelector(this.join.getRightField()));
} else {
firstSelect.addSelection(new SelectionSelector(this.join.getRightField()));
secondSelect.addSelection(new SelectionSelector(this.join.getLeftField()));
}
// ADD FIELDS OF THE SELECT
SelectionList selectionList = (SelectionList) this.selectionClause;
Selection selection = selectionList.getSelection();
if (selection instanceof SelectionSelectors) {
SelectionSelectors selectionSelectors = (SelectionSelectors) selectionList.getSelection();
for (SelectionSelector ss : selectionSelectors.getSelectors()) {
if(ss.getSelector() instanceof SelectorIdentifier){ // Example: users.name
SelectorIdentifier si = (SelectorIdentifier) ss.getSelector();
if (tableMetadataFrom.getColumn(si.getField()) != null) {
firstSelect.addSelection(new SelectionSelector(new SelectorIdentifier(si.getTable(), si.getField())));
} else {
secondSelect.addSelection(new SelectionSelector(new SelectorIdentifier(si.getTable(), si.getField())));
}
} else if (ss.getSelector() instanceof SelectorFunction) { // Example: myfunction(users.age, users_info.dateOfRegistration)
SelectorFunction sf = (SelectorFunction) ss.getSelector();
List<SelectorMeta> paramsFirst = new ArrayList<>();
List<SelectorMeta> paramsSecond = new ArrayList<>();
for(SelectorMeta sm: sf.getParams()){
SelectorIdentifier si = (SelectorIdentifier) sm;
if (tableMetadataFrom.getColumn(si.getField()) != null) {
paramsFirst.add(new SelectorIdentifier(si.getTable(), si.getField()));
} else {
paramsSecond.add(new SelectorIdentifier(si.getTable(), si.getField()));
}
}
if (!paramsFirst.isEmpty()) {
firstSelect.addSelection(new SelectionSelector(new SelectorFunction(sf.getName(), paramsFirst)));
}
if(!paramsFirst.isEmpty()) {
secondSelect.addSelection(new SelectionSelector(new SelectorFunction(sf.getName(), paramsSecond)));
}
} else if (ss.getSelector() instanceof SelectorGroupBy) { // Example: sum(users.age) ... GroupBy users.gender
/*
SelectorGroupBy sg = (SelectorGroupBy) ss.getSelector();
SelectorIdentifier si = (SelectorIdentifier) sg.getParam();
SelectorIdentifier newSi = new SelectorIdentifier(si.getField());
if (tableMetadataFrom.getColumn(si.getField()) != null) {
firstSelect.addSelection(new SelectionSelector(new SelectorGroupBy(sg.getGbFunction(), newSi)));
} else {
secondSelect.addSelection(new SelectionSelector(new SelectorGroupBy(sg.getGbFunction(), newSi)));
}
*/
SelectorGroupBy sg = (SelectorGroupBy) ss.getSelector();
SelectorIdentifier si = (SelectorIdentifier) sg.getParam();
SelectorIdentifier newSi = new SelectorIdentifier(si.getTable(), si.getField());
if (tableMetadataFrom.getColumn(si.getField()) != null) {
firstSelect.addSelection(new SelectionSelector(newSi));
} else {
secondSelect.addSelection(new SelectionSelector(newSi));
}
}
}
} else {
// instanceof SelectionAsterisk
firstSelect.setSelectionClause(new SelectionList(new SelectionAsterisk()));
secondSelect.setSelectionClause(new SelectionList(new SelectionAsterisk()));
}
// ADD WHERE CLAUSES IF ANY
if (whereInc) {
Map<Integer, List<Relation>> whereRelations = getWhereJoinPlan(firstSelect, secondSelect);
if (!whereRelations.get(1).isEmpty()) {
firstSelect.setWhere(whereRelations.get(1));
}
if (!whereRelations.get(2).isEmpty()) {
secondSelect.setWhere(whereRelations.get(2));
}
}
// ADD GROUP BY CLAUSE IF ANY
if(groupInc){
GroupBy param = group.get(0);
String groupTable = param.getSelectorIdentifier().getTable();
GroupBy newGroupBy = new GroupBy(groupTable+"."+param.getSelectorIdentifier().getField());
/*
if(groupTable.equalsIgnoreCase(firstSelect.getTableName())){
firstSelect.setGroup(newGroupBy);
} else {
secondSelect.setGroup(newGroupBy);
}
*/
joinSelect.setGroup(newGroupBy);
}
// ADD SELECTED COLUMNS TO THE JOIN STATEMENT
joinSelect.setSelectionClause(selectionClause);
// ADD MAP OF THE JOIN
if (this.join.getLeftField().getTable().equalsIgnoreCase(tableName)) {
joinSelect.setJoin(new InnerJoin("", this.join.getLeftField(), this.join.getRightField()));
} else {
joinSelect.setJoin(new InnerJoin("", this.join.getRightField(), this.join.getLeftField()));
}
firstSelect.validate(metadata, null);
secondSelect.validate(metadata, null);
// ADD STEPS
steps.setNode(new MetaStep(MetaPath.DEEP, joinSelect));
steps.addChild(new Tree(new MetaStep(MetaPath.DEEP, firstSelect)));
steps.addChild(new Tree(new MetaStep(MetaPath.DEEP, secondSelect)));
return steps;
}
private Map<String, String> getColumnsFromWhere() {
Map<String, String> whereCols = new HashMap<>();
for (Relation relation : where) {
for (SelectorIdentifier id : relation.getIdentifiers()) {
whereCols.put(id.getField(), relation.getOperator());
}
}
return whereCols;
}
private boolean matchWhereColsWithPartitionKeys(TableMetadata tableMetadata,
Map<String, String> whereCols) {
boolean partialMatched = false;
for (ColumnMetadata colMD : tableMetadata.getPartitionKey()) {
String operator = "";
for (Relation relation : where) {
if (relation.getIdentifiers().contains(colMD.getName())) {
operator = relation.getOperator();
}
}
if (whereCols.keySet().contains(colMD.getName()) && "=".equals(operator)) {
partialMatched = true;
whereCols.remove(colMD.getName());
}
}
if (whereCols.size() == 0) {
partialMatched = false;
}
return partialMatched;
}
private void matchWhereColsWithClusteringKeys(TableMetadata tableMetadata,
Map<String, String> whereCols) {
for (ColumnMetadata colMD : tableMetadata.getClusteringColumns()) {
String operator = "";
for (Relation relation : where) {
if (relation.getIdentifiers().contains(colMD.getName())) {
operator = relation.getOperator();
}
}
if (whereCols.keySet().contains(colMD.getName()) && "=".equals(operator)) {
whereCols.remove(colMD.getName());
}
}
}
private boolean checkWhereColsWithLucene(Set<String> luceneCols, Map<String, String> whereCols,
MetadataManager metadataManager, boolean cassandraPath) {
if (luceneCols.containsAll(whereCols.keySet())) {
boolean onlyMatchOperators = true;
for (String operator : whereCols.values()) {
if (!"match".equalsIgnoreCase(operator)) {
onlyMatchOperators = false;
break;
}
}
cassandraPath = (onlyMatchOperators) ? onlyMatchOperators : cassandraPath;
/*
* //TODO Retreive original table create metadata and check for text columns. if(cassandraPath
* && !whereCols.isEmpty()){ // When querying a text type column with a Lucene index, content
* must be lowercased TableMetadata metaData =
* metadataManager.getTableMetadata(getEffectiveKeyspace(), tableName);
* metadataManager.loadMetadata(); String lucenCol = whereCols.keySet().iterator().next();
* if(metaData.getColumn(lucenCol).getType() == DataType.text() &&
* where.get(0).getTerms().get(0) instanceof StringTerm){ StringTerm stringTerm = (StringTerm)
* where.get(0).getTerms().get(0); ((StringTerm)
* where.get(0).getTerms().get(0)).setTerm(stringTerm.getStringValue().toLowerCase(),
* stringTerm.isQuotedLiteral()); } }
*/
}
return cassandraPath;
}
/**
* Get the execution plan of a non JOIN select with a where clause.
*
* @param metadataManager The medata manager.
* @return The execution plan.
*/
private Tree getWherePlan(MetadataManager metadataManager) {
Tree steps = new Tree();
// Get columns of the where clauses (Map<identifier, operator>)
Map<String, String> whereCols = getColumnsFromWhere();
// By default go through deep.
boolean cassandraPath = false;
if (whereCols.isEmpty()) {
// All where clauses are included in the primary key with equals comparator.
cassandraPath = true;
} else if (areOperatorsCassandraCompatible(whereCols)) {
String effectiveKeyspace = getEffectiveKeyspace();
TableMetadata tableMetadata = metadataManager.getTableMetadata(effectiveKeyspace, tableName);
// Check if all partition columns have an equals operator
boolean partialMatched = matchWhereColsWithPartitionKeys(tableMetadata, whereCols);
if (!partialMatched) {
// Check if all clustering columns have an equals operator
matchWhereColsWithClusteringKeys(tableMetadata, whereCols);
// Get columns of the custom and lucene indexes
Set<String> indexedCols = new HashSet<>();
Set<String> luceneCols = new HashSet<>();
for (CustomIndexMetadata cim : metadataManager.getTableIndex(tableMetadata)) {
if (cim.getIndexType() == IndexType.DEFAULT) {
indexedCols.addAll(cim.getIndexedColumns());
} else {
luceneCols.addAll(cim.getIndexedColumns());
}
}
if (indexedCols.containsAll(whereCols.keySet())
&& !containsRelationalOperators(whereCols.values())) {
cassandraPath = true;
}
if (!whereCols.isEmpty()) {
cassandraPath =
checkWhereColsWithLucene(luceneCols, whereCols, metadataManager, cassandraPath);
}
}
}
if (cassandraPath) {
steps.setNode(new MetaStep(MetaPath.CASSANDRA, this));
} else {
steps.setNode(new MetaStep(MetaPath.DEEP, this));
}
return steps;
}
private boolean areOperatorsCassandraCompatible(Map<String, String> whereCols) {
boolean compatible = true;
Iterator<Entry<String, String>> whereColsIt = whereCols.entrySet().iterator();
while (compatible && whereColsIt.hasNext()) {
Entry<String, String> whereCol = whereColsIt.next();
switch (whereCol.getValue().toLowerCase()) {
case "in":
case "between":
compatible = false;
break;
}
}
return compatible;
}
@Override
public Tree getPlan(MetadataManager metadataManager, String targetKeyspace) {
Tree steps = new Tree();
if (metadataManager.checkStream(getEffectiveKeyspace() + "_" + tableName) && joinInc) {
steps = getStreamJoinPlan();
} else if (metadataManager.checkStream(getEffectiveKeyspace() + "_" + tableName)) {
steps.setNode(new MetaStep(MetaPath.STREAMING, this));
steps.setInvolvesStreaming(true);
} else if (joinInc) {
steps = getJoinPlan();
} else if (groupInc || orderInc || selectionClause.containsFunctions()) {
steps.setNode(new MetaStep(MetaPath.DEEP, this));
} else if (whereInc) {
steps = getWherePlan(metadataManager);
} else {
steps.setNode(new MetaStep(MetaPath.CASSANDRA, this));
}
LOG.info("PLAN: " + System.lineSeparator() + steps.toStringDownTop());
return steps;
}
private Tree getStreamJoinPlan() {
Tree steps = new Tree();
SelectStatement firstSelect = new SelectStatement(tableName);
firstSelect.setSessionKeyspace(this.getEffectiveKeyspace());
firstSelect.setKeyspace(getEffectiveKeyspace());
SelectStatement secondSelect = new SelectStatement(this.join.getTablename());
if (this.join.getKeyspace() != null) {
secondSelect.setKeyspace(join.getKeyspace());
}
secondSelect.setSessionKeyspace(this.getEffectiveKeyspace());
SelectStatement joinSelect = new SelectStatement("");
// ADD FIELDS OF THE JOIN
String streamingField = null;
if (this.join.getLeftField().getTable().trim().equalsIgnoreCase(tableName)) {
// streamingField = this.join.getLeftField().getField();
// if(streamingField.contains(".")) {
// this.join.getLeftField().setField(streamingField.split(".")[1]);
// }
this.join.getLeftField().setTable(null);
firstSelect.addSelection(new SelectionSelector(this.join.getLeftField()));
secondSelect.addSelection(new SelectionSelector(this.join.getRightField()));
} else {
// streamingField = this.join.getRightField().getField();
// if(streamingField.contains(".")) {
// this.join.getRightField().setField(streamingField.split(".")[1]);
// }
this.join.getRightField().setTable(null);
firstSelect.addSelection(new SelectionSelector(this.join.getRightField()));
secondSelect.addSelection(new SelectionSelector(this.join.getLeftField()));
}
com.stratio.meta.common.metadata.structures.TableMetadata streamingTable =
metadata.convertStreamingToMeta(this.getEffectiveKeyspace(), tableName);
// ADD FIELDS OF THE SELECT
SelectionList selectionList = (SelectionList) this.selectionClause;
Selection selection = selectionList.getSelection();
if (selection instanceof SelectionSelectors) {
SelectionSelectors selectionSelectors = (SelectionSelectors) selectionList.getSelection();
for (SelectionSelector ss : selectionSelectors.getSelectors()) {
SelectorIdentifier si = (SelectorIdentifier) ss.getSelector();
if (streamingTable.getColumn(si.getField()) != null) {
firstSelect.addSelection(new SelectionSelector(new SelectorIdentifier(si.getField())));
} else {
secondSelect.addSelection(new SelectionSelector(new SelectorIdentifier(si.getField())));
}
}
} else {
// instanceof SelectionAsterisk
firstSelect.setSelectionClause(new SelectionList(new SelectionAsterisk()));
secondSelect.setSelectionClause(new SelectionList(new SelectionAsterisk()));
}
// ADD WHERE CLAUSES IF ANY
if (whereInc) {
Map<Integer, List<Relation>> whereRelations = getWhereJoinPlan(firstSelect, secondSelect);
if (!whereRelations.get(1).isEmpty()) {
firstSelect.setWhere(whereRelations.get(1));
}
if (!whereRelations.get(2).isEmpty()) {
secondSelect.setWhere(whereRelations.get(2));
}
}
// ADD WINDOW
if (windowInc) {
firstSelect.setWindow(window);
}
// ADD SELECTED COLUMNS TO THE JOIN STATEMENT
joinSelect.setSelectionClause(selectionClause);
// ADD MAP OF THE JOIN
if (this.join.getLeftField().getTable().equalsIgnoreCase(tableName)) {
joinSelect.setJoin(new InnerJoin("", this.join.getLeftField(), this.join.getRightField()));
} else {
joinSelect.setJoin(new InnerJoin("", this.join.getRightField(), this.join.getLeftField()));
}
firstSelect.validate(metadata, null);
secondSelect.validate(metadata, null);
// ADD STEPS
// steps.setNode(new MetaStep(MetaPath.DEEP, joinSelect));
// steps.addChild(new Tree(new MetaStep(MetaPath.STREAMING, firstSelect)));
// steps.addChild(new Tree(new MetaStep(MetaPath.DEEP, secondSelect)));
steps.setNode(new MetaStep(MetaPath.STREAMING, firstSelect));
Tree join = new Tree(new MetaStep(MetaPath.DEEP, joinSelect));
steps.addChild(join);
Tree selectB = new Tree(new MetaStep(MetaPath.DEEP, secondSelect));
join.addChild(selectB);
steps.setInvolvesStreaming(true);
return steps;
}
/**
* Check if operators collection contains any relational operator.
*
* @param collection {@link java.util.Collection} of relational operators.
* @return {@code true} if contains any relational operator.
*/
private boolean containsRelationalOperators(Collection<String> collection) {
boolean result = false;
if (collection.contains("<=") || collection.contains("<") || collection.contains(">")
|| collection.contains(">=")) {
result = true;
}
return result;
}
public void addTablenameToIds() {
selectionClause.addTablename(tableName);
}
private void replaceAliasesInSelect(Map<String, String> tablesAliasesMap) {
if (this.selectionClause instanceof SelectionList
&& ((SelectionList) this.selectionClause).getSelection() instanceof SelectionSelectors) {
List<SelectionSelector> selectors =
((SelectionSelectors) ((SelectionList) this.selectionClause).getSelection())
.getSelectors();
for (SelectionSelector selector : selectors) {
SelectorIdentifier identifier = null;
if (selector.getSelector() instanceof SelectorIdentifier) {
identifier = (SelectorIdentifier) selector.getSelector();
} else if (selector.getSelector() instanceof SelectorGroupBy) {
identifier = (SelectorIdentifier) ((SelectorGroupBy) selector.getSelector()).getParam();
}
if (identifier != null) {
String table = tablesAliasesMap.get(identifier.getTable());
if (table != null) {
identifier.setTable(table);
}
}
}
}
}
private void replaceAliasesInWhere(Map<String, String> fieldsAliasesMap,
Map<String, String> tablesAliasesMap) {
if (this.where != null) {
for (Relation whereCol : this.where) {
for (SelectorIdentifier id : whereCol.getIdentifiers()) {
String table = tablesAliasesMap.get(id.getTable());
if (table != null) {
id.setTable(table);
}
String identifier = fieldsAliasesMap.get(id.toString());
if (identifier != null) {
id.setIdentifier(identifier);
}
}
}
}
}
private void replaceAliasesInGroupBy(Map<String, String> fieldsAliasesMap,
Map<String, String> tablesAliasesMap) {
if (this.group != null) {
for (GroupBy groupByCol : this.group) {
SelectorIdentifier selectorIdentifier = groupByCol.getSelectorIdentifier();
String table = tablesAliasesMap.get(selectorIdentifier.getTable());
if (table != null) {
selectorIdentifier.setTable(table);
}
String identifier = fieldsAliasesMap.get(selectorIdentifier.toString());
if (identifier != null) {
selectorIdentifier.setIdentifier(identifier);
}
}
}
}
private void replaceAliasesInOrderBy(Map<String, String> fieldsAliasesMap,
Map<String, String> tablesAliasesMap) {
if (this.order != null) {
for (Ordering orderBycol : this.order) {
SelectorIdentifier selectorIdentifier = orderBycol.getSelectorIdentifier();
String table = tablesAliasesMap.get(selectorIdentifier.getTable());
if (table != null) {
selectorIdentifier.setTable(table);
}
String identifier = fieldsAliasesMap.get(selectorIdentifier.toString());
if (identifier != null) {
selectorIdentifier.setIdentifier(identifier);
}
}
}
}
private void replaceAliasesInJoin(Map<String, String> tablesAliasesMap) {
if (this.join != null) {
String leftTable = this.join.getLeftField().getTable();
String tableName = tablesAliasesMap.get(leftTable);
if (tableName != null) {
this.join.getLeftField().setTable(tableName);
}
String rightTable = this.join.getRightField().getTable();
tableName = tablesAliasesMap.get(rightTable);
if (tableName != null) {
this.join.getRightField().setTable(tableName);
}
}
}
public void replaceAliasesWithName(Map<String, String> fieldsAliasesMap,
Map<String, String> tablesAliasesMap) {
Iterator<Entry<String, String>> entriesIt = tablesAliasesMap.entrySet().iterator();
while (entriesIt.hasNext()) {
Entry<String, String> entry = entriesIt.next();
if (entry.getValue().contains(".")) {
tablesAliasesMap.put(entry.getKey(), entry.getValue().split("\\.")[1]);
}
}
this.setFieldsAliasesMap(fieldsAliasesMap);
// Replacing alias in SELECT clause
replaceAliasesInSelect(tablesAliasesMap);
// Replacing alias in WHERE clause
replaceAliasesInWhere(fieldsAliasesMap, tablesAliasesMap);
// Replacing alias in GROUP BY clause
replaceAliasesInGroupBy(fieldsAliasesMap, tablesAliasesMap);
// Replacing alias in ORDER BY clause
replaceAliasesInOrderBy(fieldsAliasesMap, tablesAliasesMap);
// Replacing alias in JOIN clause
replaceAliasesInJoin(tablesAliasesMap);
}
public void updateTableNames() {
// Adding table name to the identifiers in WHERE clause
if (this.where != null) {
for (Relation whereCol : this.where) {
for (SelectorIdentifier identifier : whereCol.getIdentifiers()) {
identifier.addTablename(this.tableName);
}
}
}
// Adding table name to the identifiers in GROUP BY clause
if (this.group != null) {
for (GroupBy groupByCol : this.group) {
groupByCol.getSelectorIdentifier().addTablename(this.tableName);
}
}
// Adding table name to the identifiers in ORDER BY clause
if (this.order != null) {
for (Ordering orderByCol : this.order) {
orderByCol.getSelectorIdentifier().addTablename(this.tableName);
}
}
}
}
| Implementing solution for issue #32
| meta-core/src/main/java/com/stratio/meta/core/statements/SelectStatement.java | Implementing solution for issue #32 | <ide><path>eta-core/src/main/java/com/stratio/meta/core/statements/SelectStatement.java
<ide>
<ide> SelectStatement joinSelect = new SelectStatement("");
<ide>
<add> System.out.println("TRACE 1: firstSelect = "+firstSelect.toString());
<add> System.out.println("TRACE 1: secondSelect = "+secondSelect.toString());
<add> System.out.println("TRACE 1: joinSelect = "+joinSelect.toString());
<add> System.out.println("TRACE 1: ---------------------------------------");
<add>
<ide> // ADD FIELDS OF THE JOIN
<ide> if (this.join.getLeftField().getTable().trim().equalsIgnoreCase(tableName)) {
<ide> firstSelect.addSelection(new SelectionSelector(this.join.getLeftField()));
<ide> secondSelect.addSelection(new SelectionSelector(this.join.getLeftField()));
<ide> }
<ide>
<add> System.out.println("TRACE 2: firstSelect = "+firstSelect.toString());
<add> System.out.println("TRACE 2: secondSelect = "+secondSelect.toString());
<add> System.out.println("TRACE 2: joinSelect = "+joinSelect.toString());
<add> System.out.println("TRACE 2: ---------------------------------------");
<add>
<ide> // ADD FIELDS OF THE SELECT
<ide> SelectionList selectionList = (SelectionList) this.selectionClause;
<ide> Selection selection = selectionList.getSelection();
<add>
<add> System.out.println("TRACE 3: firstSelect = "+firstSelect.toString());
<add> System.out.println("TRACE 3: secondSelect = "+secondSelect.toString());
<add> System.out.println("TRACE 3: joinSelect = "+joinSelect.toString());
<add> System.out.println("TRACE 3: ---------------------------------------");
<ide>
<ide> if (selection instanceof SelectionSelectors) {
<ide> SelectionSelectors selectionSelectors = (SelectionSelectors) selectionList.getSelection();
<ide> secondSelect.addSelection(new SelectionSelector(new SelectorFunction(sf.getName(), paramsSecond)));
<ide> }
<ide> } else if (ss.getSelector() instanceof SelectorGroupBy) { // Example: sum(users.age) ... GroupBy users.gender
<del> /*
<del> SelectorGroupBy sg = (SelectorGroupBy) ss.getSelector();
<del> SelectorIdentifier si = (SelectorIdentifier) sg.getParam();
<del> SelectorIdentifier newSi = new SelectorIdentifier(si.getField());
<del> if (tableMetadataFrom.getColumn(si.getField()) != null) {
<del> firstSelect.addSelection(new SelectionSelector(new SelectorGroupBy(sg.getGbFunction(), newSi)));
<del> } else {
<del> secondSelect.addSelection(new SelectionSelector(new SelectorGroupBy(sg.getGbFunction(), newSi)));
<del> }
<del> */
<ide> SelectorGroupBy sg = (SelectorGroupBy) ss.getSelector();
<ide> SelectorIdentifier si = (SelectorIdentifier) sg.getParam();
<ide> SelectorIdentifier newSi = new SelectorIdentifier(si.getTable(), si.getField());
<ide> secondSelect.setSelectionClause(new SelectionList(new SelectionAsterisk()));
<ide> }
<ide>
<add> System.out.println("TRACE 4: firstSelect = "+firstSelect.toString());
<add> System.out.println("TRACE 4: secondSelect = "+secondSelect.toString());
<add> System.out.println("TRACE 4: joinSelect = "+joinSelect.toString());
<add> System.out.println("TRACE 4: ---------------------------------------");
<add>
<ide> // ADD WHERE CLAUSES IF ANY
<ide> if (whereInc) {
<ide> Map<Integer, List<Relation>> whereRelations = getWhereJoinPlan(firstSelect, secondSelect);
<ide> GroupBy param = group.get(0);
<ide> String groupTable = param.getSelectorIdentifier().getTable();
<ide> GroupBy newGroupBy = new GroupBy(groupTable+"."+param.getSelectorIdentifier().getField());
<del> /*
<del> if(groupTable.equalsIgnoreCase(firstSelect.getTableName())){
<del> firstSelect.setGroup(newGroupBy);
<del> } else {
<del> secondSelect.setGroup(newGroupBy);
<del> }
<del> */
<ide> joinSelect.setGroup(newGroupBy);
<add> }
<add>
<add> // ADD GROUP BY CLAUSE IF ANY
<add> if(groupInc){
<add>
<add> List newGroup = new ArrayList<GroupBy>();
<add>
<add> GroupBy param = group.get(0);
<add> GroupBy newGroupBy = new GroupBy(param.getSelectorIdentifier().getField());
<add> String groupTable = param.getSelectorIdentifier().getTable();
<add>
<ide> }
<ide>
<ide> // ADD SELECTED COLUMNS TO THE JOIN STATEMENT |
|
Java | agpl-3.0 | 11141a69df28a68487b149ee12ad4a3cbffdcba5 | 0 | Audiveris/audiveris,Audiveris/audiveris | //----------------------------------------------------------------------------//
// //
// R u n s B u i l d e r //
// //
// Copyright (C) Herve Bitteur 2000-2007. All rights reserved. //
// This software is released under the GNU General Public License. //
// Contact author at [email protected] to report bugs & suggestions. //
//----------------------------------------------------------------------------//
//
package omr.lag;
import omr.util.Logger;
import omr.util.OmrExecutors;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
/**
* Class <code>RunsBuilder</code> is in charge of building a collection of runs,
* that can be used by a lag for example.
*
* @author Hervé Bitteur
* @version $Id$
*/
public class RunsBuilder
{
//~ Static fields/initializers ---------------------------------------------
/** Usual logger utility */
private static final Logger logger = Logger.getLogger(RunsBuilder.class);
//~ Instance fields --------------------------------------------------------
/** The adapter that takes care of pixel access */
private final Reader reader;
//~ Constructors -----------------------------------------------------------
//-------------//
// RunsBuilder //
//-------------//
/**
* Creates a new RunsBuilder object.
*
* @param reader an adapter to provide pixel access as well as specific
* call-back actions when a run (either foreground or
* background) has just been read.
*/
public RunsBuilder (Reader reader)
{
this.reader = reader;
}
//~ Methods ----------------------------------------------------------------
//------------//
// createRuns //
//------------//
/**
* The <code>createRuns</code> method can be used to build the runs on the
* fly, by providing a given rectangle. Note that the w and h parameters can
* be swapped, which allows both vertical and horizontal uses, if the
* Reader.getPixel() method is defined accordingly.
*
* @param rect the rectangular area (coord x pos) to explore
*/
public void createRuns (Rectangle rect)
{
final int cMin = rect.x;
final int cMax = (rect.x + rect.width) - 1;
final int pMin = rect.y;
final int pMax = (rect.y + rect.height) - 1;
createParallelRuns(pMin, pMax, cMin, cMax);
reader.terminate();
}
//--------------------//
// createParallelRuns //
//--------------------//
/**
* This method handles the pixels run either in a parallel or a serial way,
* according to the possibilities of the high OMR executor.
*/
private void createParallelRuns (int pMin,
int pMax,
final int cMin,
final int cMax)
{
try {
// Browse one dimension
List<Callable<Void>> tasks = new ArrayList<Callable<Void>>(
pMax - pMin + 1);
for (int p = pMin; p <= pMax; p++) {
final int pp = p;
tasks.add(
new Callable<Void>() {
public Void call ()
throws Exception
{
processPosition(pp, cMin, cMax);
return null;
}
});
}
OmrExecutors.getHighExecutor()
.invokeAll(tasks);
} catch (InterruptedException ex) {
logger.warning("ParallelRuns got interrupted", ex);
}
}
//-----------------//
// processPosition //
//-----------------//
/**
* Process the pixels in position 'p' between coordinates 'cMin' & 'cMax'
* @param p the position in the pixels array (x for vertical)
* @param cMin the starting coordinate (y for vertical)
* @param cMax the ending coordinate
*/
private void processPosition (int p,
int cMin,
int cMax)
{
// Current run is FOREGROUND or BACKGROUND
boolean isFore = false;
// Current length of the run in progress
int length = 0;
// Current cumulated grey level for the run in progress
int cumul = 0;
// Browse other dimension
for (int c = cMin; c <= cMax; c++) {
final int level = reader.getLevel(c, p);
if (reader.isFore(level)) {
// We are on a foreground pixel
if (isFore) {
// Append to the foreground run in progress
length++;
cumul += level;
} else {
// End the previous background run if any
if (length > 0) {
reader.backRun(c, p, length);
}
// Initialize values for the starting foreground run
isFore = true;
length = 1;
cumul = level;
}
} else {
// We are on a background pixel
if (isFore) {
// End the previous foreground run
reader.foreRun(c, p, length, cumul);
// Initialize values for the starting background run
isFore = false;
length = 1;
} else {
// Append to the background run in progress
length++;
}
}
}
// Process end of last run in this position
if (isFore) {
reader.foreRun(cMax + 1, p, length, cumul);
} else {
reader.backRun(cMax + 1, p, length);
}
}
//~ Inner Interfaces -------------------------------------------------------
/**
* Interface <code<Reader</code> is used to plug call-backs to a run
* retrieval process.
*/
public static interface Reader
{
//~ Methods ------------------------------------------------------------
//--------//
// isFore //
//--------//
/**
* This method is used to check if the grey level corresponds to a
* foreground pixel.
*
* @param level pixel level of grey
*
* @return true if pixel is foreground, false otherwise
*/
boolean isFore (int level);
//----------//
// getLevel //
//----------//
/**
* This method is used to report the grey level of the pixel read at
* location (coord, pos).
*
* @param coord x for horizontal runs, y for vertical runs
* @param pos y for horizontal runs, x for vertical runs
*
* @return the pixel grey value (from 0 for black up to 255 for white)
*/
int getLevel (int coord,
int pos);
//---------//
// backRun //
//---------//
/**
* Called at end of a background run, with the related coordinates
*
* @param coord location of the point past the end of the run
* @param pos constant position of the run
* @param length length of the run just found
*/
void backRun (int coord,
int pos,
int length);
//---------//
// foreRun //
//---------//
/**
* Same as background, but for a foreground run. We also provide the
* measure of accumulated grey level in that case.
*
* @param coord location of the point past the end of the run
* @param pos constant position of the run
* @param length length of the run just found
* @param cumul cumulated grey levels along the run
*/
void foreRun (int coord,
int pos,
int length,
int cumul);
//-----------//
// terminate //
//-----------//
/**
* Called at the very end of run retrieval
*/
void terminate ();
}
}
| src/main/omr/lag/RunsBuilder.java | //----------------------------------------------------------------------------//
// //
// R u n s B u i l d e r //
// //
// Copyright (C) Herve Bitteur 2000-2007. All rights reserved. //
// This software is released under the GNU General Public License. //
// Contact author at [email protected] to report bugs & suggestions. //
//----------------------------------------------------------------------------//
//
package omr.lag;
import omr.util.Logger;
import omr.util.OmrExecutors;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
/**
* Class <code>RunsBuilder</code> is in charge of building a collection of runs,
* that can be used by a lag for example.
*
* @author Hervé Bitteur
* @version $Id$
*/
public class RunsBuilder
{
//~ Static fields/initializers ---------------------------------------------
/** Usual logger utility */
private static final Logger logger = Logger.getLogger(RunsBuilder.class);
//~ Instance fields --------------------------------------------------------
/** The adapter that takes care of pixel access */
private final Reader reader;
//~ Constructors -----------------------------------------------------------
//-------------//
// RunsBuilder //
//-------------//
/**
* Creates a new RunsBuilder object.
*
* @param reader an adapter to provide pixel access as well as specific
* call-back actions when a run (either foreground or
* background) has just been read.
*/
public RunsBuilder (Reader reader)
{
this.reader = reader;
}
//~ Methods ----------------------------------------------------------------
//------------//
// createRuns //
//------------//
/**
* The <code>createRuns</code> method can be used to build the runs on the
* fly, by providing a given rectangle. Note that the w and h parameters can
* be swapped, which allows both vertical and horizontal uses, if the
* Reader.getPixel() method is defined accordingly.
*
* @param rect the rectangular area (coord x pos) to explore
*/
public void createRuns (Rectangle rect)
{
final int cMin = rect.x;
final int cMax = (rect.x + rect.width) - 1;
final int pMin = rect.y;
final int pMax = (rect.y + rect.height) - 1;
createParallelRuns(pMin, pMax, cMin, cMax);
reader.terminate();
}
//--------------------//
// createParallelRuns //
//--------------------//
/**
* Parallel version
*/
private void createParallelRuns (int pMin,
int pMax,
final int cMin,
final int cMax)
{
try {
// Browse one dimension
List<Callable<Void>> tasks = new ArrayList<Callable<Void>>(
pMax - pMin + 1);
for (int p = pMin; p <= pMax; p++) {
final int pp = p;
tasks.add(
new Callable<Void>() {
public Void call ()
throws Exception
{
processPosition(pp, cMin, cMax);
return null;
}
});
}
OmrExecutors.getHighExecutor()
.invokeAll(tasks);
} catch (InterruptedException ex) {
logger.warning("ParallelRuns got interrupted", ex);
}
}
//-----------------//
// processPosition //
//-----------------//
private void processPosition (int p,
int cMin,
int cMax)
{
// Current run is FOREGROUND or BACKGROUND
boolean isFore = false;
// Current length of the run in progress
int length = 0;
// Current cumulated grey level for the run in progress
int cumul = 0;
// Browse other dimension
for (int c = cMin; c <= cMax; c++) {
final int level = reader.getLevel(c, p);
if (reader.isFore(level)) {
// We are on a foreground pixel
if (isFore) {
// Append to the foreground run in progress
length++;
cumul += level;
} else {
// End the previous background run if any
if (length > 0) {
reader.backRun(c, p, length);
}
// Initialize values for the starting foreground run
isFore = true;
length = 1;
cumul = level;
}
} else {
// We are on a background pixel
if (isFore) {
// End the previous foreground run
reader.foreRun(c, p, length, cumul);
// Initialize values for the starting background run
isFore = false;
length = 1;
} else {
// Append to the background run in progress
length++;
}
}
}
// Process end of last run in this position
if (isFore) {
reader.foreRun(cMax + 1, p, length, cumul);
} else {
reader.backRun(cMax + 1, p, length);
}
}
//~ Inner Interfaces -------------------------------------------------------
/**
* Interface <code<Reader</code> is used to plug call-backs to a run
* retrieval process.
*/
public static interface Reader
{
//~ Methods ------------------------------------------------------------
//--------//
// isFore //
//--------//
/**
* This method is used to check if the grey level corresponds to a
* foreground pixel.
*
* @param level pixel level of grey
*
* @return true if pixel is foreground, false otherwise
*/
boolean isFore (int level);
//----------//
// getLevel //
//----------//
/**
* This method is used to report the grey level of the pixel read at
* location (coord, pos).
*
* @param coord x for horizontal runs, y for vertical runs
* @param pos y for horizontal runs, x for vertical runs
*
* @return the pixel grey value (from 0 for black up to 255 for white)
*/
int getLevel (int coord,
int pos);
//---------//
// backRun //
//---------//
/**
* Called at end of a background run, with the related coordinates
*
* @param coord location of the point past the end of the run
* @param pos constant position of the run
* @param length length of the run just found
*/
void backRun (int coord,
int pos,
int length);
//---------//
// foreRun //
//---------//
/**
* Same as background, but for a foreground run. We also provide the
* measure of accumulated grey level in that case.
*
* @param coord location of the point past the end of the run
* @param pos constant position of the run
* @param length length of the run just found
* @param cumul cumulated grey levels along the run
*/
void foreRun (int coord,
int pos,
int length,
int cumul);
//-----------//
// terminate //
//-----------//
/**
* Called at the very end of run retrieval
*/
void terminate ();
}
}
| Better comments
| src/main/omr/lag/RunsBuilder.java | Better comments | <ide><path>rc/main/omr/lag/RunsBuilder.java
<ide> // createParallelRuns //
<ide> //--------------------//
<ide> /**
<del> * Parallel version
<add> * This method handles the pixels run either in a parallel or a serial way,
<add> * according to the possibilities of the high OMR executor.
<ide> */
<ide> private void createParallelRuns (int pMin,
<ide> int pMax,
<ide> //-----------------//
<ide> // processPosition //
<ide> //-----------------//
<add> /**
<add> * Process the pixels in position 'p' between coordinates 'cMin' & 'cMax'
<add> * @param p the position in the pixels array (x for vertical)
<add> * @param cMin the starting coordinate (y for vertical)
<add> * @param cMax the ending coordinate
<add> */
<ide> private void processPosition (int p,
<ide> int cMin,
<ide> int cMax) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.