answer
stringlengths 17
10.2M
|
|---|
package uk.org.adamretter.maven;
import io.xspec.maven.xspecMavenPlugin.resolver.Resolver;
import io.xspec.maven.xspecMavenPlugin.utils.ProcessedFile;
import io.xspec.maven.xspecMavenPlugin.utils.XmlStuff;
import net.sf.saxon.s9api.*;
import com.jenitennison.xslt.tests.XSLTCoverageTraceListener;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.*;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javanet.staxutils.IndentingXMLStreamWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import net.sf.saxon.Configuration;
import net.sf.saxon.trans.XPathException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.input.ReaderInputStream;
import org.apache.commons.io.output.NullOutputStream;
import org.apache.maven.artifact.DependencyResolutionRequiredException;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.interpolation.util.StringUtils;
import org.xml.sax.EntityResolver;
import org.xmlresolver.helpers.URIUtils;
import top.marchand.maven.saxon.utils.SaxonOptions;
import top.marchand.maven.saxon.utils.SaxonUtils;
@Mojo(name = "run-xspec", defaultPhase = LifecyclePhase.TEST, requiresDependencyResolution = ResolutionScope.TEST)
public class XSpecMojo extends AbstractMojo implements LogProvider {
public static final transient String XSPEC_PREFIX = "dependency://io.xspec+xspec/";
public static final transient String XML_UTILITIES_PREFIX = "dependency://org.mricaud+xml-utilities/";
public static final transient String CATALOG_NS = "urn:oasis:names:tc:entity:xmlns:xml:catalog";
public static final transient String XSPEC_NS = "http:
public static final transient String LOCAL_PREFIX = "dependency://io.xspec.maven+xspec-maven-plugin/";
@Component
private MavenSession session;
@Parameter( defaultValue = "${project}", readonly = true, required = true )
public MavenProject project;
/**
* Defines if XSpec unit tests should be run or skipped.
* It's a bad practise to set this option, and this NEVER be done.
*/
@Parameter(property = "skipTests", defaultValue = "false")
public boolean skipTests;
/**
* Path to compiler/generate-xspec-tests.xsl XSpec implementation file.
* This parameter is only available for developement purposes, and should never be overriden.
*/
// @Parameter(defaultValue = XSPEC_PREFIX+"compiler/generate-xspec-tests.xsl", required = true)
@Parameter(defaultValue = LOCAL_PREFIX+"io/xspec/maven/xspec-maven-plugin/compiler/generate-xspec-tests.xsl", required = true)
public String xspecXslCompiler;
// issue
/**
* Path to compiler/generate-query-tests.xsl.
* This parameter is only available for developement purposes, and should never be overriden.
*/
// @Parameter(defaultValue = XSPEC_PREFIX+"compiler/generate-query-tests.xsl", required = true)
@Parameter(defaultValue = LOCAL_PREFIX+"io/xspec/maven/xspec-maven-plugin/compiler/generate-query-tests.xsl", required = true)
public String xspecXQueryCompiler;
/**
* Path to schematron/iso-schematron/iso_dsdl_include.xsl.
* This parameter is only available for developement purposes, and should never be overriden.
*/
@Parameter(defaultValue = XSPEC_PREFIX+"schematron/iso-schematron/iso_dsdl_include.xsl", required = true)
public String schIsoDsdlInclude;
/**
* Path to schematron/iso-schematron/iso_abstract_expand.xsl.
* This parameter is only available for developement purposes, and should never be overriden.
*/
@Parameter(defaultValue = XSPEC_PREFIX+"schematron/iso-schematron/iso_abstract_expand.xsl", required = true)
public String schIsoAbstractExpand;
/**
* Path to schematron/iso-schematron/iso_svrl_for_xslt2.xsl.
* This parameter is only available for developement purposes, and should never be overriden.
*/
@Parameter(defaultValue = XSPEC_PREFIX+"schematron/iso-schematron/iso_svrl_for_xslt2.xsl", required = true)
public String schIsoSvrlForXslt2;
/**
* Path to schematron/schut-to-xspec.xsl.
* This parameter is only available for developement purposes, and should never be overriden.
*/
@Parameter(defaultValue = LOCAL_PREFIX+"schematron/schut-to-xspec.xsl", required = true)
public String schSchut;
/**
* Path to reporter/format-xspec-report.xsl.
* This parameter is only available for developement purposes, and should never be overriden.
*/
@Parameter(defaultValue = XSPEC_PREFIX+"reporter/format-xspec-report.xsl", required = true)
public String xspecReporter;
/**
* Path to reporter/junit-report.xsl.
* This parameter is only available for developement purposes, and should never be overriden.
*/
@Parameter(defaultValue = XSPEC_PREFIX+"reporter/junit-report.xsl", required = true)
public String junitReporter;
/**
* Path to reporter/coverage-report.xsl.
* This parameter is only available for developement purposes, and should never be overriden.
*/
@Parameter(defaultValue = XSPEC_PREFIX+"reporter/coverage-report.xsl", required = true)
public String coverageReporter;
/**
* Path to io/xspec/maven/xspec-maven-plugin/junit-aggregator.xsl.
* This parameter is only available for developement purposes, and should never be overriden.
*/
@Parameter(defaultValue = LOCAL_PREFIX+"io/xspec/maven/xspec-maven-plugin/junit-aggregator.xsl")
public String junitAggregator;
/**
* Path to org/mricaud/xml-utilities/get-xml-file-static-dependency-tree.xsl.
* This parameter is only available for developement purposes, and should never be overriden.
*/
@Parameter(defaultValue = XML_UTILITIES_PREFIX+"org/mricaud/xml-utilities/get-xml-file-static-dependency-tree.xsl")
public String dependencyScanner;
/**
* Directory where XSpec files are search
*/
@Parameter(defaultValue = "${project.basedir}/src/test/xspec", required = true)
public File testDir;
@Parameter(name = "saxonOptions")
public SaxonOptions saxonOptions;
/**
* Patterns fo files to exclude
* Each found file that ends with an excluded value will be skipped.
* <pre>
* <configuration>
* <excludes>
* <exclude>-TI.xspec</exclude>
* </excludes>
* </configuration>
* </pre>
* Each file that ends with -TI.xspec will be skipped.
*/
@Parameter(alias = "excludes")
public List<String> excludes;
/**
* Defines if a test failure should fail the build, or not.
* This option should NEVER be used.
*/
@Parameter(defaultValue = "${maven.test.failure.ignore}")
public boolean testFailureIgnore;
/**
* The directory where report files will be created
*/
@Parameter(defaultValue = "${project.build.directory}/xspec-reports", required = true)
public File reportDir;
/**
* The directory where JUnit final report will be created.
* xspec-maven-plugin produces on junit report file per XSpec file, in
* <tt>reportDir</tt> directory, and creates a merged report, in <tt>junitReportDir</tt>,
* named <tt>TEST-xspec<suffix>.xml</tt>.
* suffix depends on execution id
*/
@Parameter(defaultValue = "${project.build.directory}/surefire-reports", required = true)
public File junitReportDir;
@Parameter(defaultValue = "${catalog.filename}")
public String catalogFile;
/**
* The directory where surefire report will be created
*/
@Parameter(defaultValue = "${project.build.directory}/surefire-reports", required = true)
public File surefireReportDir;
/**
* Defines if a surefire report must be generated
*/
@Parameter(defaultValue = "false")
public Boolean generateSurefireReport;
/**
* Defines if generated catalog should be kept or not.
* xspec-maven-plugin generates its own catalog to access its own resources,
* and if <tt>catalogFile</tt> is defined, adds a <tt><next-catalog /></tt>
* entry in this generated catalog.
* Only usefull to debug plugin.
*/
@Parameter(defaultValue = "false")
public Boolean keepGeneratedCatalog;
/**
* Defines if code coverage reporting should be generated or not.
*/
@Parameter(defaultValue = "false")
public Boolean generateCoverage;
@Parameter(defaultValue = "${mojoExecution}", readonly = true)
public MojoExecution execution;
private String generateXspecUtilsUri = null;
public static final SAXParserFactory PARSER_FACTORY = SAXParserFactory.newInstance();
public static final Configuration SAXON_CONFIGURATION = getSaxonConfiguration();
// package private for tests
XmlStuff xmlStuff;
// package private for test purpose
boolean uriResolverSet = false;
private List<ProcessedFile> processedFiles;
private static final List<ProcessedFile> PROCESS_FILES = new ArrayList<>();
public static final QName INITIAL_TEMPLATE_NAME=QName.fromClarkName("{http:
private static URIResolver initialUriResolver;
public static final QName QN_NAME = new QName("name");
public static final QName QN_SELECT = new QName("select");
public static final QName QN_STYLESHEET = new QName("stylesheet");
public static final QName QN_TEST_DIR = new QName("test_dir");
public static final QName QN_URI = new QName("uri");
private static final QName QN_REPORT_CSS_URI = new QName("report-css-uri");
private List<File> filesToDelete, junitFiles;
private static final String COVERAGE_ERROR_MESSAGE = "Coverage report is only available with Saxon-PE or Saxon-EE";
private String schLocationCompareUri;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
if (isSkipTests()) {
getLog().info("'skipTests' is set... skipping XSpec tests!");
return;
}
filesToDelete = new ArrayList<>();
junitFiles = new ArrayList<>();
try {
prepareXmlUtilities();
getLog().debug("Looking for XSpecs in: " + getTestDir());
final List<File> xspecs = findAllXSpecs(getTestDir());
getLog().info("Found " + xspecs.size() + " XSpecs...");
boolean failed = false;
processedFiles= new ArrayList<>(xspecs.size());
for (final File xspec : xspecs) {
if (shouldExclude(xspec)) {
getLog().warn("Skipping excluded XSpec: " + xspec.getAbsolutePath());
} else {
if (!processXSpec(xspec)) {
failed = true;
}
}
}
// extract css
File cssFile = new File(getReportDir(),XmlStuff.RESOURCES_TEST_REPORT_CSS);
cssFile.getParentFile().mkdirs();
try {
Source cssSource = xmlStuff.getUriResolver().resolve(XSPEC_PREFIX+"reporter/test-report.css", project.getBasedir().toURI().toURL().toExternalForm());
BufferedInputStream is = new BufferedInputStream(new URL(cssSource.getSystemId()).openStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(cssFile));
byte[] buffer = new byte[1024];
int read = is.read(buffer);
while(read>0) {
bos.write(buffer, 0, read);
read = is.read(buffer);
}
} catch(TransformerException ex) {
getLog().error("while extracting CSS: ",ex);
}
createJunitReport();
// issue
if (failed) {
if(!testFailureIgnore) {
throw new MojoFailureException("Some XSpec tests failed or were missed!");
} else {
getLog().warn("Some XSpec tests failed or were missed, but build will not fail!");
}
}
} catch (final SaxonApiException | TransformerException | IOException sae) {
throw new MojoExecutionException(sae.getMessage(), sae);
} finally {
if(processedFiles==null) {
processedFiles = new ArrayList<>();
}
PROCESS_FILES.addAll(processedFiles);
// if there are many executions, index file is generated each time, but results are appended...
generateIndex();
}
}
/**
* Prepares all XML stuff : XPathCompiler, XsltCompiler, compiled stylesheets,
* Saxon configuration, and so on...
* @throws MojoExecutionException
* @throws MojoFailureException
* @throws SaxonApiException
* @throws MalformedURLException
* @throws TransformerException
*/
protected void prepareXmlUtilities() throws MojoExecutionException, MojoFailureException, SaxonApiException, MalformedURLException, TransformerException {
xmlStuff = new XmlStuff(new Processor(SAXON_CONFIGURATION), getLog());
if(saxonOptions!=null) {
try {
SaxonUtils.prepareSaxonConfiguration(xmlStuff.getProcessor(), saxonOptions);
} catch(XPathException ex) {
getLog().error(ex);
throw new MojoExecutionException("Illegal value in Saxon configuration property", ex);
}
}
if(initialUriResolver==null) {
initialUriResolver = xmlStuff.getUriResolver();
}
try {
xmlStuff.doAdditionalConfiguration(saxonOptions);
} catch(XPathException ex) {
getLog().error(ex);
throw new MojoExecutionException("Illegal value in Saxon configuration property", ex);
}
if (!uriResolverSet) {
try {
xmlStuff.setUriResolver(buildUriResolver(initialUriResolver));
uriResolverSet = true;
} catch(DependencyResolutionRequiredException | IOException | XMLStreamException ex) {
throw new MojoExecutionException("while creating URI resolver", ex);
}
}
// trace activation
xmlStuff.getXsltCompiler().setCompileWithTracing(true);
xmlStuff.getXqueryCompiler().setCompileWithTracing(true);
xmlStuff.setXpExecGetXSpecType(xmlStuff.getXPathCompiler().compile("/*/@*"));
xmlStuff.setXpSchGetXSpecFile(xmlStuff.getXPathCompiler().compile(
"iri-to-uri("
+ "concat("
+ "replace(document-uri(/), '(.*)/.*$', '$1'), "
+ "'/', "
/**
* Utility method to resolve a URI, using URIResolver. If resource can not be
* located, uses <tt>desc</tt> to construct an error message, thrown in
* <tt>MojoExecutionExcecution</tt>
* @param source
* @param baseUri
* @param desc
* @return
* @throws MojoExecutionException
* @throws TransformerException
*/
private Source resolveSrc(String source, String baseUri, String desc) throws MojoExecutionException, TransformerException {
Source ret = xmlStuff.getUriResolver().resolve(source, baseUri);
if(ret == null) {
throw new MojoExecutionException("Could not find "+desc+" stylesheet in: "+source);
}
return ret;
}
/**
* Generates the index.html file that point all XSpec reports.
* All required infos are in {@link #PROCESS_FILES}
*/
protected void generateIndex() {
File index = new File(reportDir, "index.html");
if(!reportDir.exists()) reportDir.mkdirs();
try (BufferedWriter fos = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(index), Charset.forName("UTF-8")))) {
fos.write("<!DOCTYPE HTML PUBLIC \"-
fos.write("<html>");
fos.write("<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n");
fos.write("<style>\n\ttable {border: solid black 1px; border-collapse: collapse; }\n");
fos.write("\ttr.error {background-color: red; color: white; }\n");
fos.write("\ttr.error td a { color: white;}\n");
fos.write("\ttr.title {background-color: lightgrey; }\n");
fos.write("\ttd,th {border: solid black 1px; }\n");
fos.write("\ttd:not(:first-child) {text-align: right; }\n");
fos.write("</style>\n");
fos.write("<title>XSpec results</title><meta name=\"date\" content=\"");
fos.write(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
fos.write("\"></head>\n");
fos.write("<body><h1>XSpec results</h1>");
fos.write("<table>\n");
fos.write("<colgroup><col/><col class=\"successful\"/><col class=\"pending\"/><col class=\"failed\"/><col class=\"missed\"/><col/></colgroup>\n");
fos.write("<thead><tr><th>XSpec file</th><th>Passed</th><th>Pending</th><th>Failed</th><th>Missed</th><th>Total</th></tr></thead>\n");
fos.write("<tbody>");
String lastRootDir="";
for(ProcessedFile pf:PROCESS_FILES) {
String rootDir = pf.getRootSourceDir().toString();
if(!lastRootDir.equals(rootDir)) {
fos.write("<tr class=\"title\"><td colspan=\"6\">");
fos.write(rootDir);
fos.write("</td></tr>\n");
lastRootDir = rootDir;
}
int errorCount = pf.getFailed()+pf.getMissed();
if(errorCount==0) {
fos.write("<tr>");
} else {
fos.write("<tr class=\"error\">");
}
fos.write("<td><a href=\"");
fos.write(pf.getReportFile().toUri().toString());
fos.write("\">"+pf.getRelativeSourcePath()+"</a></td>");
fos.write("<td");
if(pf.getPassed()==0) fos.write(" class=\"zero\"");
fos.write(">"+pf.getPassed()+"</td>");
fos.write("<td");
if(pf.getPending()==0) fos.write(" class=\"zero\"");
fos.write(">"+pf.getPending()+"</td>");
fos.write("<td");
if(pf.getFailed()==0) fos.write(" class=\"zero\"");
fos.write(">"+pf.getFailed()+"</td>");
fos.write("<td");
if(pf.getMissed()==0) fos.write(" class=\"zero\"");
fos.write(">"+pf.getMissed()+"</td>");
fos.write("<td>"+pf.getTotal()+"</td>");
fos.write("</tr>\n");
}
fos.write("</tbody></table>");
fos.write("</body></html>");
fos.flush();
} catch (IOException ex) {
getLog().warn("while writing XSpec index file", ex);
}
}
/**
* Checks whether an XSpec should be excluded from processing
* The comparison is performed on the filename of the xspec
* @param xspec The filepath of the XSpec
* @return true if the XSpec should be excluded, false otherwise
*/
private boolean shouldExclude(final File xspec) {
final List<String> excludePatterns = getExcludes();
if (excludePatterns != null) {
for (final String excludePattern : excludePatterns) {
if (xspec.getAbsolutePath().replaceAll("\\\\","/").endsWith(excludePattern)) {
return true;
}
}
}
return false;
}
/**
* Process a XSpec file
* @param xspec
* @return <tt>true</tt> if XSpec succeed, <tt>false</tt> otherwise.
* @throws SaxonApiException
* @throws TransformerException
* @throws IOException
*/
final boolean processXSpec(final File xspec) throws SaxonApiException, TransformerException, IOException {
getLog().info("Processing XSpec: " + xspec.getAbsolutePath());
XdmNode xspecDocument = xmlStuff.getDocumentBuilder().build(xspec);
XSpecType type = getXSpecType(xspecDocument);
switch(type) {
case XQ: return processXQueryXSpec(xspecDocument);
case SCH: {
XdmNode compiledSchXSpec = prepareSchematronDocument(xspecDocument);
// it will have a problem in report with filename.
return processXsltXSpec(compiledSchXSpec);
}
default: return processXsltXSpec(xspecDocument);
}
}
/**
* Process an XSpec on XSLT Test
* @param xspec The path to the XSpec test file
* @return true if all tests in XSpec pass, false otherwise
*/
final boolean processXsltXSpec(XdmNode xspec) throws SaxonApiException, FileNotFoundException {
File actualSourceFile = new File(xspec.getBaseURI());
// Try to determine where was the original XSpec file, in case of XSpec on schematron
File sourceFile = actualSourceFile;
XPathSelector xps = xmlStuff.getXPathCompiler().compile("/x:description/@xspec-original-location").load();
xps.setContextItem(xspec);
XdmItem item = xps.evaluateSingle();
if(item!=null) {
String value = item.getStringValue();
if(!value.isEmpty()) {
try {
sourceFile = new File(new URI(value));
} catch (URISyntaxException ex) {
getLog().error("This should never be possible ! Check /x:description/@xspec-original-location", ex);
}
}
}
getLog().debug("sourceFile is "+sourceFile.getAbsolutePath());
/* compile the test stylesheet */
final CompiledXSpec compiledXSpec = compileXSpecForXslt(actualSourceFile);
if (compiledXSpec == null) {
return false;
}
/* execute the test stylesheet */
final XSpecResultsHandler resultsHandler = new XSpecResultsHandler(this);
try {
final XsltExecutable xeXSpec = xmlStuff.compileXsl(
new StreamSource(compiledXSpec.getCompiledStylesheet()));
final XsltTransformer xtXSpec = xeXSpec.load();
File tempCoverageFile=null;
if(isCoverageRequired()) {
tempCoverageFile = getCoverageTempPath(getReportDir(), sourceFile);
if(!keepGeneratedCatalog) {
tempCoverageFile.deleteOnExit();
}
final String xspecStylesheetUri = compiledXSpec.getCompiledStylesheet().toURI().toString();
XSLTCoverageTraceListener listener = new XSLTCoverageTraceListener(new PrintStream(tempCoverageFile)) {
@Override
public boolean isUtilsStylesheet(String systemId) {
return generateXspecUtilsUri.equals(systemId) || schLocationCompareUri.equals(systemId);
}
@Override
public boolean isXSpecStylesheet(String systemId) {
return xspecStylesheetUri.equals(systemId);
}
};
listener.setGenerateTestsUtilsName(generateXspecUtilsUri);
getLog().info("Trace listener is active");
xtXSpec.setTraceListener(listener);
}
xtXSpec.setInitialTemplate(INITIAL_TEMPLATE_NAME);
getLog().info("Executing XSpec: " + compiledXSpec.getCompiledStylesheet().getName());
//setup xml report output
final File xspecXmlResult = getXSpecXmlResultPath(getReportDir(), sourceFile);
final Serializer xmlSerializer = xmlStuff.getProcessor().newSerializer();
xmlSerializer.setOutputProperty(Serializer.Property.METHOD, "xml");
xmlSerializer.setOutputProperty(Serializer.Property.INDENT, "yes");
xmlSerializer.setOutputFile(xspecXmlResult);
//setup html report output
final File xspecHtmlResult = getXSpecHtmlResultPath(getReportDir(), sourceFile);
final Serializer htmlSerializer = xmlStuff.getProcessor().newSerializer();
htmlSerializer.setOutputProperty(Serializer.Property.METHOD, "html");
htmlSerializer.setOutputProperty(Serializer.Property.INDENT, "yes");
htmlSerializer.setOutputFile(xspecHtmlResult);
XsltTransformer reporter = xmlStuff.getReporter().load();
reporter.setBaseOutputURI(xspecHtmlResult.toURI().toString());
reporter.setDestination(htmlSerializer);
// setup surefire report output
Destination xtSurefire = null;
if(xmlStuff.getXeSurefire()!=null) {
XsltTransformer xt = xmlStuff.getXeSurefire().load();
try {
xt.setParameter(new QName("baseDir"), new XdmAtomicValue(project.getBasedir().toURI().toURL().toExternalForm()));
xt.setParameter(new QName("outputDir"), new XdmAtomicValue(surefireReportDir.toURI().toURL().toExternalForm()));
xt.setParameter(new QName("reportFileName"), new XdmAtomicValue(xspecXmlResult.getName()));
xt.setDestination(xmlStuff.newSerializer(new NullOutputStream()));
// setBaseOutputURI not required, surefire-reporter.xsl
// does xsl:result-document with absolute @href
xtSurefire = xt;
} catch(MalformedURLException ex) {
getLog().warn("Unable to generate surefire report", ex);
}
} else {
xtSurefire = xmlStuff.newSerializer(new NullOutputStream());
}
// JUnit report
XsltTransformer juReporter = xmlStuff.getJUnitReporter().load();
File junitFile = getJUnitReportPath(getReportDir(), sourceFile);
Serializer junitDest = xmlStuff.newSerializer(new FileOutputStream(junitFile));
junitDest.setOutputProperty(Serializer.Property.INDENT, "yes");
juReporter.setDestination(junitDest);
junitFiles.add(junitFile);
ProcessedFile pf = new ProcessedFile(testDir, sourceFile, reportDir, xspecHtmlResult);
processedFiles.add(pf);
String relativeCssPath =
(pf.getRelativeCssPath().length()>0 ? pf.getRelativeCssPath()+"/" : "") + XmlStuff.RESOURCES_TEST_REPORT_CSS;
reporter.setParameter(QN_REPORT_CSS_URI, new XdmAtomicValue(relativeCssPath));
//execute
final Destination destination =
new TeeDestination(
new TeeDestination(
new SAXDestination(resultsHandler),
new TeeDestination(
xmlSerializer,
xtSurefire)
),
new TeeDestination(reporter, juReporter));
xtXSpec.setDestination(destination);
xtXSpec.setBaseOutputURI(xspecXmlResult.toURI().toString());
// Source xspecSource = new StreamSource(sourceFile);
// utilisation du resolver dans le document source
XMLReader reader = PARSER_FACTORY.newSAXParser().getXMLReader();
reader.setEntityResolver((EntityResolver)xmlStuff.getUriResolver());
Source xspecSource = new SAXSource(reader, new InputSource(new FileInputStream(sourceFile)));
xspecSource.setSystemId(sourceFile.toURI().toString());
xtXSpec.setSource(xspecSource);
xtXSpec.setURIResolver(xmlStuff.getUriResolver());
xtXSpec.transform();
// limit to pure XSLT, exclude schematron
if(isCoverageRequired() && (sourceFile.equals(actualSourceFile))) {
if(xmlStuff.getCoverageReporter()!=null) {
XsltTransformer coverage = xmlStuff.getCoverageReporter().load();
File coverageReportFile = getCoverageFinalPath(reportDir, sourceFile);
coverage.setDestination(xmlStuff.getProcessor().newSerializer(coverageReportFile));
coverage.setSource(new StreamSource(tempCoverageFile));
getLog().info("coverage pwd: "+testDir.toURI().toString());
coverage.setParameter(new QName("pwd"),XdmAtomicValue.makeAtomicValue(testDir.toURI().toString()));
Path relative = testDir.toPath().relativize(sourceFile.toPath());
// Path relative = testDir.toPath().relativize(actualSourceFile.toPath());
getLog().info("coverage tests: "+relative.toString());
coverage.setParameter(new QName("tests"), XdmAtomicValue.makeAtomicValue(relative.toString()));
coverage.setParameter(QN_REPORT_CSS_URI, new XdmAtomicValue(relativeCssPath));
coverage.transform();
} else {
getLog().warn(COVERAGE_ERROR_MESSAGE);
}
}
} catch (final Exception te) {
getLog().error(te.getMessage());
getLog().debug(te);
}
//missed tests come about when the XSLT processor aborts processing the XSpec due to an XSLT error
final int missed = compiledXSpec.getTests() - resultsHandler.getTests();
//report results
final String msg = String.format("%s results [Passed/Pending/Failed/Missed/Total] = [%d/%d/%d/%d/%d]",
sourceFile.getName(),
resultsHandler.getPassed(),
resultsHandler.getPending(),
resultsHandler.getFailed(),
missed,
compiledXSpec.getTests());
if(processedFiles.size()>0) {
processedFiles.get(processedFiles.size()-1).setResults(
resultsHandler.getPassed(),
resultsHandler.getPending(),
resultsHandler.getFailed(),
missed,
compiledXSpec.getTests());
}
if (resultsHandler.getFailed() + missed > 0) {
getLog().error(msg);
return false;
} else {
getLog().info(msg);
return true;
}
}
private boolean isSaxonPEorEE() {
String configurationClassName = SAXON_CONFIGURATION.getClass().getName();
return "com.saxonica.config.ProfessionalConfiguration".equals(configurationClassName) ||
"com.saxonica.config.EnterpriseConfiguration".equals(configurationClassName);
}
/**
* Process an XSpec on XQuery Test
* @param xspec The path to the XSpec test file
* @return true if all tests in XSpec pass, false otherwise
*/
final boolean processXQueryXSpec(XdmNode xspec) throws SaxonApiException, FileNotFoundException, IOException {
File sourceFile = new File(xspec.getBaseURI());
/* compile the test stylesheet */
final CompiledXSpec compiledXSpec = compileXSpecForXQuery(sourceFile);
if (compiledXSpec == null) {
getLog().error("unable to compile "+sourceFile.getAbsolutePath());
return false;
} else {
getLog().debug("XQuery compiled XSpec is at "+compiledXSpec.getCompiledStylesheet().getAbsolutePath());
/* execute the test stylesheet */
final XSpecResultsHandler resultsHandler = new XSpecResultsHandler(this);
boolean processedFileAdded = false;
try {
final XQueryExecutable xeXSpec = xmlStuff.getXqueryCompiler().compile(new FileInputStream(compiledXSpec.getCompiledStylesheet()));
final XQueryEvaluator xtXSpec = xeXSpec.load();
getLog().info("Executing XQuery XSpec: " + compiledXSpec.getCompiledStylesheet().getName());
//setup xml report output
final File xspecXmlResult = getXSpecXmlResultPath(getReportDir(), sourceFile);
final Serializer xmlSerializer = xmlStuff.getProcessor().newSerializer();
xmlSerializer.setOutputProperty(Serializer.Property.METHOD, "xml");
xmlSerializer.setOutputProperty(Serializer.Property.INDENT, "yes");
xmlSerializer.setOutputFile(xspecXmlResult);
//setup html report output
final File xspecHtmlResult = getXSpecHtmlResultPath(getReportDir(), sourceFile);
final Serializer htmlSerializer = xmlStuff.getProcessor().newSerializer();
htmlSerializer.setOutputProperty(Serializer.Property.METHOD, "html");
htmlSerializer.setOutputProperty(Serializer.Property.INDENT, "yes");
htmlSerializer.setOutputFile(xspecHtmlResult);
XsltTransformer reporter = xmlStuff.getReporter().load();
reporter.setBaseOutputURI(xspecHtmlResult.toURI().toString());
reporter.setDestination(htmlSerializer);
// setup surefire report output
Destination xtSurefire = null;
if(xmlStuff.getXeSurefire()!=null) {
XsltTransformer xt = xmlStuff.getXeSurefire().load();
try {
xt.setParameter(new QName("baseDir"), new XdmAtomicValue(project.getBasedir().toURI().toURL().toExternalForm()));
xt.setParameter(new QName("outputDir"), new XdmAtomicValue(surefireReportDir.toURI().toURL().toExternalForm()));
xt.setParameter(new QName("reportFileName"), new XdmAtomicValue(xspecXmlResult.getName()));
xt.setDestination(xmlStuff.newSerializer(new NullOutputStream()));
// setBaseOutputURI not required, surefire-reporter.xsl
// does xsl:result-document with absolute @href
xtSurefire = xt;
} catch(MalformedURLException ex) {
getLog().warn("Unable to generate surefire report", ex);
}
} else {
xtSurefire = xmlStuff.newSerializer(new NullOutputStream());
}
ProcessedFile pf = new ProcessedFile(testDir, sourceFile, reportDir, xspecHtmlResult);
processedFiles.add(pf);
processedFileAdded = true;
String relativeCssPath =
(pf.getRelativeCssPath().length()>0 ? pf.getRelativeCssPath()+"/" : "") + XmlStuff.RESOURCES_TEST_REPORT_CSS;
reporter.setParameter(new QName("report-css-uri"), new XdmAtomicValue(relativeCssPath));
//execute
// JUnit report
XsltTransformer juReporter = xmlStuff.getJUnitReporter().load();
File junitFile = getJUnitReportPath(getReportDir(), sourceFile);
Serializer junitDest = xmlStuff.newSerializer(new FileOutputStream(junitFile));
junitDest.setOutputProperty(Serializer.Property.INDENT, "yes");
juReporter.setDestination(junitDest);
junitFiles.add(junitFile);
// Serializer nullOutput1 = xmlStuff.newSerializer(new NullOutputStream());
final Destination destination =
new TeeDestination(
new TeeDestination(
new SAXDestination(resultsHandler),
new TeeDestination(
xmlSerializer,
xtSurefire)
),
new TeeDestination(reporter, juReporter));
// xtXSpec.setDestination(destination);
// ??? par quoi remplacer cela ???
// xtXSpec.setBaseOutputURI(xspecXmlResult.toURI().toString());
Source xspecSource = new StreamSource(sourceFile);
xtXSpec.setSource(xspecSource);
xtXSpec.setURIResolver(xmlStuff.getUriResolver());
XdmValue result = xtXSpec.evaluate();
if(result==null) {
getLog().debug("processXQueryXSpec result is null");
} else {
getLog().debug("processXQueryXSpec result : "+result.toString());
xmlStuff.getProcessor().writeXdmValue(result, destination);
}
} catch (final SaxonApiException te) {
getLog().error(te.getMessage());
getLog().debug(te);
if(!processedFileAdded) {
ProcessedFile pf = new ProcessedFile(testDir, sourceFile, reportDir, getXSpecHtmlResultPath(getReportDir(), sourceFile));
processedFiles.add(pf);
processedFileAdded = true;
}
}
//missed tests come about when the XSLT processor aborts processing the XSpec due to an XSLT error
final int missed = compiledXSpec.getTests() - resultsHandler.getTests();
//report results
final String msg = String.format("%s results [Passed/Pending/Failed/Missed/Total] = [%d/%d/%d/%d/%d]",
sourceFile.getName(),
resultsHandler.getPassed(),
resultsHandler.getPending(),
resultsHandler.getFailed(),
missed,
compiledXSpec.getTests());
if(processedFiles.size()>0) {
processedFiles.get(processedFiles.size()-1).setResults(
resultsHandler.getPassed(),
resultsHandler.getPending(),
resultsHandler.getFailed(),
missed,
compiledXSpec.getTests());
}
if (resultsHandler.getFailed() + missed > 0) {
getLog().error(msg);
return false;
} else {
getLog().info(msg);
return true;
}
}
}
/**
* Compiles a XSpec file that test a XQuery
* @param sourceFile The XSpec file to compile
* @return The compiled XSpec informations
*/
final CompiledXSpec compileXSpecForXQuery(final File sourceFile) {
return compileXSpec(sourceFile, xmlStuff.getXspec4xqueryCompiler());
}
/**
* Compiles a XSpec file that test a XSLT
* @param sourceFile The XSpec file to compile
* @return The compiled XSpec informations
*/
final CompiledXSpec compileXSpecForXslt(final File sourceFile) {
return compileXSpec(sourceFile, xmlStuff.getXspec4xsltCompiler());
}
/**
* Compiles an XSpec using the provided XSLT XSpec compiler
* @param compiler The XSpec XSLT compiler
* @param xspec The XSpec test to compile
* @return Details of the Compiled XSpec or null if the XSpec could not be
* compiled
*/
final CompiledXSpec compileXSpec(final File sourceFile, XsltExecutable compilerExec) {
XsltTransformer compiler = compilerExec.load();
InputStream isXSpec = null;
try {
final File compiledXSpec = getCompiledXSpecPath(getReportDir(), sourceFile);
getLog().info("Compiling XSpec to XSLT: " + compiledXSpec);
isXSpec = new FileInputStream(sourceFile);
final SAXParser parser = PARSER_FACTORY.newSAXParser();
final XMLReader reader = parser.getXMLReader();
final XSpecTestFilter xspecTestFilter = new XSpecTestFilter(
reader,
// Bug under Windows
sourceFile.toURI().toString(),
xmlStuff.getUriResolver(),
this,
false);
final InputSource inXSpec = new InputSource(isXSpec);
inXSpec.setSystemId(sourceFile.getAbsolutePath());
compiler.setSource(new SAXSource(xspecTestFilter, inXSpec));
final Serializer serializer = xmlStuff.getProcessor().newSerializer();
serializer.setOutputFile(compiledXSpec);
compiler.setDestination(serializer);
compiler.transform();
return new CompiledXSpec(xspecTestFilter.getTests(), xspecTestFilter.getPendingTests(), compiledXSpec);
} catch (final SaxonApiException sae) {
getLog().error(sae.getMessage());
getLog().debug(sae);
} catch (final ParserConfigurationException | FileNotFoundException pce) {
getLog().error(pce);
} catch (SAXException saxe) {
getLog().error(saxe.getMessage());
getLog().debug(saxe);
} finally {
if (isXSpec != null) {
try {
isXSpec.close();
} catch (final IOException ioe) {
getLog().warn(ioe);
}
}
}
return null;
}
/**
* Prepare a Schematron XSpec test.
* There two phases :
* <ul>
* <li>compile schematron to a XSLT</li>
* <li>compile the XSpec (that points to the schematron) into a XSpec that
* points to the XSLT (the compiled at phase 1)</li>
* </ul>
*
* @param xspecDocument
* @return
* @throws SaxonApiException
* @throws TransformerException
* @throws IOException
*/
protected XdmNode prepareSchematronDocument(XdmNode xspecDocument) throws SaxonApiException, TransformerException, IOException {
XsltTransformer step1 = xmlStuff.getSchematronDsdl().load();
XsltTransformer step2 = xmlStuff.getSchematronExpand().load();
XsltTransformer step3 = xmlStuff.getSchematronSvrl().load();
XPathSelector xp = xmlStuff.getXPathCompiler().compile("/x:description/x:param[@name='phase'][1]/text()").load();
xp.setContextItem(xspecDocument);
XdmItem phaseItem = xp.evaluateSingle();
if(phaseItem!=null) {
String phase = phaseItem.getStringValue();
getLog().debug("Evaluating phase: "+phase);
if(phase!=null && !phase.isEmpty()) {
step3.setParameter(new QName("phase"), new XdmAtomicValue(phase));
}
}
step3.setParameter(new QName("allow-foreign"), new XdmAtomicValue("true"));
File sourceFile = new File(xspecDocument.getBaseURI());
// compiling schematron
step1.setDestination(step2);
step2.setDestination(step3);
File compiledSchematronDest = getCompiledSchematronPath(getReportDir(), sourceFile);
Serializer serializer = xmlStuff.newSerializer(new FileOutputStream(compiledSchematronDest));
step3.setDestination(serializer);
// getting from XSpec the schematron location
XPathSelector xpSchemaPath = xmlStuff.getXPathCompiler().compile("/*/@schematron").load();
xpSchemaPath.setContextItem(xspecDocument);
String schematronPath = xpSchemaPath.evaluateSingle().getStringValue();
Source source = xmlStuff.getUriResolver().resolve(schematronPath, xspecDocument.getBaseURI().toString());
step1.setInitialContextNode(xmlStuff.getDocumentBuilder().build(source));
step1.transform();
getLog().debug("Schematron compiled ! "+compiledSchematronDest.getAbsolutePath());
// modifying xspec to point to compiled schematron
XsltTransformer schut = xmlStuff.getSchematronSchut().load();
schut.setParameter(QN_STYLESHEET, new XdmAtomicValue(compiledSchematronDest.toURI().toString()));
schut.setParameter(QN_TEST_DIR, new XdmAtomicValue(testDir.toURI().toString()));
schut.setInitialContextNode(xspecDocument);
File resultFile = getCompiledXspecSchematronPath(getReportDir(), sourceFile);
// WARNING : we can't use a XdmDestination, the XdmNode generated does not have
// an absolute systemId, which is used in processXsltXSpec(XdmNode xspec)
schut.setDestination(xmlStuff.newSerializer(new FileOutputStream(resultFile)));
schut.transform();
getLog().debug("XSpec for schematron compiled: "+resultFile.getAbsolutePath());
XdmNode result = xmlStuff.getDocumentBuilder().build(resultFile);
if(!resultFile.exists()) {
getLog().error(resultFile.getAbsolutePath()+" has not be written");
}
// copy resources referenced from XSpec
getLog().info("Copying resource files referenced from XSpec for Schematron");
XsltTransformer xslDependencyScanner = xmlStuff.getXmlDependencyScanner().load();
XdmDestination xdmDest = new XdmDestination();
xslDependencyScanner.setDestination(xdmDest);
xslDependencyScanner.setInitialContextNode(xspecDocument);
xslDependencyScanner.transform();
XPathSelector xpFile = xmlStuff.getXpFileSearcher().load();
xpFile.setContextItem(xdmDest.getXdmNode());
XdmValue ret = xpFile.evaluate();
for(int i=0;i<ret.size();i++) {
XdmNode node = (XdmNode)(ret.itemAt(i));
String uri = node.getAttributeValue(QN_URI);
try {
copyFile(xspecDocument.getUnderlyingNode().getSystemId(), uri, resultFile);
} catch(URISyntaxException ex) {
// it can not happens, it is always correct as provided by saxon
throw new SaxonApiException("Saxon has generated an invalid URI : ",ex);
}
}
return result;
}
/**
* Copies <tt>referencedFile</tt> located relative to <tt>baseUri</tt> to
* <tt>resutBase</tt>/<tt>referencedFile</tt>.
* @param baseUri
* @param referencedFile
* @param resultBase
* @throws IOException
* @throws URISyntaxException
*/
protected void copyFile(String baseUri, String referencedFile, File resultBase) throws IOException, URISyntaxException {
getLog().debug("copyFile("+baseUri+", "+referencedFile+", "+resultBase.getAbsolutePath()+")");
Path basePath = new File(new URI(baseUri)).getParentFile().toPath();
File source = basePath.resolve(referencedFile).toFile();
File dest = resultBase.getParentFile().toPath().resolve(referencedFile).toFile();
getLog().debug("Copying "+source.getAbsolutePath()+" to "+dest.getAbsolutePath());
FileUtils.copyFile(source, dest);
}
/**
* Get location for Compiled XSpecs
* @param xspecReportDir The directory to place XSpec reports in
* @param xspec The XSpec that will be compiled eventually
* @return A filepath to place the compiled XSpec in
*/
final File getCompiledXSpecPath(final File xspecReportDir, final File xspec) {
return getCompiledPath(xspecReportDir, xspec, "xslt", ".xslt");
}
/**
* Get location for Compiled XSpecs
* @param xspecReportDir The directory to place XSpec reports in
* @param schematron The Schematron that will be compiled eventually
*
* @return A filepath to place the compiled Schematron (a XSLT) in
*/
final File getCompiledSchematronPath(final File xspecReportDir, final File schematron) {
File ret = getCompiledPath(xspecReportDir, schematron, "schematron", ".xslt");
return ret;
}
final File getCompiledXspecSchematronPath(final File xspecReportDir, final File xspec) {
File ret = getCompiledPath(xspecReportDir, xspec, FilenameUtils.getBaseName(xspec.getName()),"-compiled.xspec");
filesToDelete.add(ret);
return ret;
}
/**
* Computes the compiled XSpec location
* @param xspecReportDir
* @param xspec
* @param name
* @param extension
* @return
*/
private File getCompiledPath(final File xspecReportDir, final File xspec, final String name, final String extension) {
if (!xspecReportDir.exists()) {
xspecReportDir.mkdirs();
}
Path relativeSource = testDir.toPath().relativize(xspec.toPath());
File executionReportDir = (
execution!=null && execution.getExecutionId()!=null && !"default".equals(execution.getExecutionId()) ?
new File(xspecReportDir,execution.getExecutionId()) :
xspecReportDir);
executionReportDir.mkdirs();
File outputDir = executionReportDir.toPath().resolve(relativeSource).toFile();
final File fCompiledDir = new File(outputDir, name);
if (!fCompiledDir.exists()) {
fCompiledDir.mkdirs();
}
return new File(fCompiledDir, xspec.getName() + extension);
}
/**
* Get location for XSpec test report (XML Format)
*
* @param xspecReportDir The directory to place XSpec reports in
* @param xspec The XSpec that will be compiled eventually
*
* @return A filepath for the report
*/
final File getXSpecXmlResultPath(final File xspecReportDir, final File xspec) {
return getXSpecResultPath(xspecReportDir, xspec, "xml");
}
/**
* Get location for XSpec test report (HTML Format)
*
* @param xspecReportDir The directory to place XSpec reports in
* @param xspec The XSpec that will be compiled eventually
*
* @return A filepath for the report
*/
final File getXSpecHtmlResultPath(final File xspecReportDir, final File xspec) {
return getXSpecResultPath(xspecReportDir, xspec, "html");
}
/**
* Get location for XSpec test report
*
* @param xspecReportDir The directory to place XSpec reports in
* @param xspec The XSpec that will be compiled eventually
* @param extension Filename extension for the report (excluding the '.'
*
* @return A filepath for the report
*/
final File getXSpecResultPath(final File xspecReportDir, final File xspec, final String extension) {
if (!xspecReportDir.exists()) {
xspecReportDir.mkdirs();
}
Path relativeSource = testDir.toPath().relativize(xspec.toPath());
getLog().debug("executionId="+execution.getExecutionId());
getLog().debug("relativeSource="+relativeSource.toString());
File executionReportDir = (
execution!=null && execution.getExecutionId()!=null && !"default".equals(execution.getExecutionId()) ?
new File(xspecReportDir,execution.getExecutionId()) :
xspecReportDir);
executionReportDir.mkdirs();
getLog().debug("executionReportDir="+executionReportDir.getAbsolutePath());
File outputDir = executionReportDir.toPath().resolve(relativeSource).toFile();
getLog().debug("outputDir="+outputDir.getAbsolutePath());
return new File(outputDir, xspec.getName().replace(".xspec", "") + "." + extension);
}
/**
* Computes Junit report location
* @param xspecReportDir
* @param xspec
* @return
*/
final File getJUnitReportPath(final File xspecReportDir, final File xspec) {
if (!xspecReportDir.exists()) {
xspecReportDir.mkdirs();
}
Path relativeSource = testDir.toPath().relativize(xspec.toPath());
File executionReportDir = (
execution!=null && execution.getExecutionId()!=null && !"default".equals(execution.getExecutionId()) ?
new File(xspecReportDir,execution.getExecutionId()) :
xspecReportDir);
executionReportDir.mkdirs();
File outputDir = executionReportDir.toPath().resolve(relativeSource).toFile();
return new File(outputDir, "junit-"+xspec.getName().replace(".xspec", "") + ".xml");
}
final File getCoverageTempPath(final File xspecReportDir, final File xspec) {
if (!xspecReportDir.exists()) {
xspecReportDir.mkdirs();
}
Path relativeSource = testDir.toPath().relativize(xspec.toPath());
File executionReportDir = (
execution!=null && execution.getExecutionId()!=null && !"default".equals(execution.getExecutionId()) ?
new File(xspecReportDir,execution.getExecutionId()) :
xspecReportDir);
executionReportDir.mkdirs();
File outputDir = executionReportDir.toPath().resolve(relativeSource).toFile();
return new File(outputDir, "coverage-"+xspec.getName().replace(".xspec","") + ".xml");
}
final File getCoverageFinalPath(final File xspecReportDir, final File xspec) {
if (!xspecReportDir.exists()) {
xspecReportDir.mkdirs();
}
Path relativeSource = testDir.toPath().relativize(xspec.toPath());
File executionReportDir = (
execution!=null && execution.getExecutionId()!=null && !"default".equals(execution.getExecutionId()) ?
new File(xspecReportDir,execution.getExecutionId()) :
xspecReportDir);
executionReportDir.mkdirs();
File outputDir = executionReportDir.toPath().resolve(relativeSource).toFile();
return new File(outputDir, xspec.getName().replace(".xspec","-coverage") + ".html");
}
/**
* Recursively find any files whoose name ends '.xspec' under the directory
* xspecTestDir
*
* @param xspecTestDir The directory to search for XSpec files
*
* @return List of XSpec files
*/
private List<File> findAllXSpecs(final File xspecTestDir) {
final List<File> specs = new ArrayList<>();
if (xspecTestDir.exists()) {
final File[] specFiles = xspecTestDir.listFiles(new FileFilter() {
@Override
public boolean accept(final File file) {
return file.isFile() && file.getName().endsWith(".xspec");
}
});
specs.addAll(Arrays.asList(specFiles));
for (final File subDir : xspecTestDir.listFiles(new FileFilter() {
@Override
public boolean accept(final File file) {
return file.isDirectory();
}
})) {
specs.addAll(findAllXSpecs(subDir));
}
}
return specs;
}
protected boolean isSkipTests() {
return skipTests;
}
protected String getXspecXslCompiler() {
return xspecXslCompiler;
}
protected String getXspecXQueryCompiler() {
return xspecXQueryCompiler;
}
protected String getXspecReporter() {
return xspecReporter;
}
protected String getJUnitReporter() {
return junitReporter;
}
protected String getCoverageReporter() {
return coverageReporter;
}
protected String getSchematronIsoDsdl() {
return schIsoDsdlInclude;
}
protected String getSchematronExpand() {
return schIsoAbstractExpand;
}
protected String getSchematronSvrForXslt() {
return schIsoSvrlForXslt2;
}
protected String getSchematronSchut() {
return schSchut;
}
protected String getXmlDependencyScanner() {
return dependencyScanner;
}
protected File getReportDir() {
return reportDir;
}
protected File getTestDir() {
return testDir;
}
protected List<String> getExcludes() {
return excludes;
}
protected Boolean isCoverageRequired() {
return generateCoverage;
}
/**
* Computes the location of the jar identified by <tt>(groupId, artifactId)</tt>.
* A dependency on this artifact must have been decalred in plugin.
* @param groupId
* @param artifactId
* @return The jar URI
* @throws IOException
* @throws MojoFailureException
*/
private String getJarUri(final String groupId, final String artifactId) throws IOException, MojoFailureException {
String thisJar = null;
String marker = createMarker(groupId, artifactId);
getLog().debug("marker="+marker);
for(String s:getClassPathElements()) {
if(s.contains(marker)) {
thisJar = s;
break;
}
}
if(thisJar==null) {
throw new MojoFailureException("Unable to locate xspec jar file from classpath-");
}
String jarUri = makeJarUri(thisJar);
return jarUri;
}
/**
* Creates the URI Resolver. It also generates the catalog with all
* dependencies
* @param saxonUriResolver
* @return
* @throws DependencyResolutionRequiredException
* @throws IOException
* @throws XMLStreamException
* @throws MojoFailureException
*/
private URIResolver buildUriResolver(final URIResolver saxonUriResolver) throws DependencyResolutionRequiredException, IOException, XMLStreamException, MojoFailureException {
File tmpCatalog = File.createTempFile("tmp", "-catalog.xml");
try (OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(tmpCatalog), Charset.forName("UTF-8"))) {
XMLStreamWriter xmlWriter = XMLOutputFactory.newFactory().createXMLStreamWriter(osw);
xmlWriter = new IndentingXMLStreamWriter(xmlWriter);
xmlWriter.writeStartDocument("UTF-8", "1.0");
xmlWriter.writeStartElement("catalog");
xmlWriter.setDefaultNamespace(CATALOG_NS);
xmlWriter.writeNamespace("", CATALOG_NS);
// io.spec / xspec
String jarUri = getJarUri("io.xspec", "xspec");
writeCatalogEntry(xmlWriter, jarUri, XSPEC_PREFIX);
// io.xspec / xspec-maven-plugin
jarUri = getJarUri("io.xspec.maven", "xspec-maven-plugin");
writeCatalogEntry(xmlWriter, jarUri, XML_UTILITIES_PREFIX);
// io.xspec.maven / xspec-maven-plugin
jarUri = getJarUri("io.xspec.maven", "xspec-maven-plugin");
writeCatalogEntry(xmlWriter, jarUri, LOCAL_PREFIX);
if(catalogFile!=null) {
xmlWriter.writeEmptyElement("nextCatalog");
Properties props = new Properties();
props.putAll(session.getUserProperties());
props.putAll(session.getSystemProperties());
String catalogFilename = org.codehaus.plexus.util.StringUtils.interpolate(catalogFile, props);
try {
URI uri = new URI(catalogFilename);
if(uri.isAbsolute()) {
xmlWriter.writeAttribute("catalog", uri.toString());
} else {
xmlWriter.writeAttribute("catalog", new File(catalogFilename).toURI().toURL().toExternalForm());
}
} catch(Exception ex) {
xmlWriter.writeAttribute("catalog", new File(catalogFilename).toURI().toURL().toExternalForm());
}
}
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
osw.flush();
}
if(!keepGeneratedCatalog) tmpCatalog.deleteOnExit();
else getLog().info("keeping generated catalog: "+tmpCatalog.toURI().toURL().toExternalForm());
return new Resolver(saxonUriResolver, tmpCatalog, getLog());
}
/**
* Writes a catalog entries for a jar and a URI prefix
* @param xmlWriter
* @param jarUri
* @param prefix
* @throws XMLStreamException
*/
private void writeCatalogEntry(final XMLStreamWriter xmlWriter, final String jarUri, String prefix) throws XMLStreamException {
xmlWriter.writeEmptyElement("rewriteURI");
xmlWriter.writeAttribute("uriStartString", prefix);
xmlWriter.writeAttribute("rewritePrefix", jarUri);
xmlWriter.writeEmptyElement("rewriteSystem");
xmlWriter.writeAttribute("uriStartString", prefix);
xmlWriter.writeAttribute("rewritePrefix", jarUri);
}
/**
* Transform a jar file to a URI, as to must be declared in catalog entries
* @param jarFile
* @return
* @throws MalformedURLException
*/
private String makeJarUri(String jarFile) throws MalformedURLException {
getLog().debug(String.format("makeJarUri(%s)", jarFile));
return "jar:" + jarFile +"!/";
}
/**
* Returns classpath entries
* @return
* @throws MojoFailureException
*/
private List<String> getClassPathElements() throws MojoFailureException {
ClassLoader cl = getClass().getClassLoader();
if(cl instanceof URLClassLoader) {
URLClassLoader ucl = (URLClassLoader)cl;
List<String> ret = new ArrayList(ucl.getURLs().length);
for(URL u:ucl.getURLs()) {
ret.add(u.toExternalForm());
}
return ret;
} else {
throw new MojoFailureException("classloader is not a URL classloader : "+cl.getClass().getName());
}
}
/**
* Creates a marker of a jar file. This marker is used to identify the jar
* associated to a <tt>(groupId, artifactId)</tt>
* @param groupId
* @param artifactId
* @return
* @throws IOException
*/
private String createMarker(String groupId, String artifactId) throws IOException {
Properties props = new Properties();
props.load(getClass().getResourceAsStream("/META-INF/maven/"+groupId+"/"+artifactId+"/pom.properties"));
return String.format("%s-%s", props.getProperty("artifactId"), props.getProperty("version"));
}
static final String XSPEC_MOJO_PFX = "[xspec-mojo] ";
/**
* Creates the unified JUnit report, which groups all JUnit reports from
* each XSpec file into a common one
* @throws MalformedURLException
* @throws TransformerException
* @throws SaxonApiException
*/
private void createJunitReport() throws MalformedURLException, TransformerException, SaxonApiException {
String baseUri = project!=null ? project.getBasedir().toURI().toURL().toExternalForm() : null;
XsltTransformer xsl = xmlStuff.compileXsl(xmlStuff.getUriResolver().resolve(junitAggregator, baseUri)).load();
xsl.setParameter(new QName("baseDir"), new XdmAtomicValue(testDir.toURI().toString()));
StringBuilder sb = new StringBuilder("<files>");
for(File f: junitFiles) {
sb.append("<file>").append(f.toURI().toString()).append("</file>");
}
sb.append("</files>");
xsl.setSource(new StreamSource(new ReaderInputStream(new StringReader(sb.toString()))));
String fileName = execution!=null && execution.getExecutionId()!=null ? "TEST-xspec-"+execution.getExecutionId()+".xml" : "TEST-xspec.xml";
Serializer ser = xmlStuff.getProcessor().newSerializer(new File(junitReportDir, fileName));
ser.setOutputProperty(Serializer.Property.INDENT, "yes");
xsl.setDestination(ser);
xsl.setMessageListener(new MessageListener() {
@Override
public void message(XdmNode xn, boolean bln, SourceLocator sl) {
getLog().debug(xn.getStringValue());
}
});
xsl.transform();
}
private static Configuration getSaxonConfiguration() {
Configuration ret = Configuration.newConfiguration();
ret.setConfigurationProperty("http://saxon.sf.net/feature/allow-external-functions", Boolean.TRUE);
return ret;
}
/**
* Returns the nature of the XSpec tested file
* @param doc
* @return
* @throws SaxonApiException
*/
XSpecType getXSpecType(XdmNode doc) throws SaxonApiException {
XPathSelector xps = xmlStuff.getXpExecGetXSpecType().load();
xps.setContextItem(doc);
XdmValue values = xps.evaluate();
for(XdmSequenceIterator it=values.iterator();it.hasNext();) {
XdmNode item=(XdmNode)(it.next());
if(item.getNodeKind().equals(XdmNodeKind.ATTRIBUTE)) {
String nodeName = item.getNodeName().getLocalName();
switch(nodeName) {
case "query":
case "query-at": {
return XSpecType.XQ;
}
case "schematron": {
return XSpecType.SCH;
}
case "stylesheet": {
return XSpecType.XSL;
}
}
}
}
throw new SaxonApiException("This file does not seem to be a valid XSpec file: "+doc.getBaseURI().toString());
}
public enum XSpecType {
XSL, SCH, XQ;
}
}
|
package vg.civcraft.mc.civmodcore;
import java.io.ObjectInputFilter.Config;
import java.util.List;
import java.util.logging.Level;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.ConfigurationSerialization;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import vg.civcraft.mc.civmodcore.chatDialog.ChatListener;
import vg.civcraft.mc.civmodcore.chatDialog.DialogManager;
import vg.civcraft.mc.civmodcore.command.CommandHandler;
import vg.civcraft.mc.civmodcore.command.StandaloneCommandHandler;
import vg.civcraft.mc.civmodcore.dao.ManagedDatasource;
import vg.civcraft.mc.civmodcore.inventorygui.ClickableInventoryListener;
import vg.civcraft.mc.civmodcore.itemHandling.NiceNames;
import vg.civcraft.mc.civmodcore.playersettings.PlayerSettingAPI;
import vg.civcraft.mc.civmodcore.scoreboard.ScoreBoardListener;
public abstract class ACivMod extends JavaPlugin {
@Deprecated
protected CommandHandler handle;
protected StandaloneCommandHandler newCommandHandler;
private static boolean initializedAPIs = false;
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (handle == null) {
return newCommandHandler.executeCommand(sender, command, args);
} else {
return handle.execute(sender, command, args);
}
}
@Override
public void onEnable() {
initApis(this);
this.newCommandHandler = new StandaloneCommandHandler(this);
}
@Override
public void onDisable() {
PlayerSettingAPI.saveAll();
}
private static synchronized void initApis(ACivMod instance) {
if (!initializedAPIs) {
initializedAPIs = true;
instance.registerListener(new ClickableInventoryListener());
instance.registerListener(new ChatListener());
instance.registerListener(new ScoreBoardListener());
new NiceNames().loadNames();
new DialogManager();
ConfigurationSerialization.registerClass(ManagedDatasource.class);
}
}
protected void registerListener(Listener listener) {
if (listener == null) {
throw new IllegalArgumentException("Cannot register a listener if it's null, you dummy");
}
getServer().getPluginManager().registerEvents(listener, this);
}
@Deprecated
public boolean toBool(String value) {
if (value.equals("1") || value.equalsIgnoreCase("true")) {
return true;
}
return false;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String alias, String[] args) {
if (handle == null) {
return newCommandHandler.tabCompleteCommand(sender, cmd, args);
} else {
return handle.complete(sender, cmd, args);
}
}
public CommandHandler getCommandHandler() {
return handle;
}
protected void setCommandHandler(CommandHandler handle) {
this.handle = handle;
}
protected abstract String getPluginName();
/**
* Simple SEVERE level logging.
*/
public void severe(String message) {
getLogger().log(Level.SEVERE, message);
}
/**
* Simple SEVERE level logging with Throwable record.
*/
public void severe(String message, Throwable error) {
getLogger().log(Level.SEVERE, message, error);
}
/**
* Simple WARNING level logging.
*/
public void warning(String message) {
getLogger().log(Level.WARNING, message);
}
/**
* Simple WARNING level logging with Throwable record.
*/
public void warning(String message, Throwable error) {
getLogger().log(Level.WARNING, message, error);
}
/**
* Simple WARNING level logging with ellipsis notation shortcut for defered
* injection argument array.
*/
public void warning(String message, Object... vars) {
getLogger().log(Level.WARNING, message, vars);
}
/**
* Simple INFO level logging
*/
public void info(String message) {
getLogger().log(Level.INFO, message);
}
/**
* Simple INFO level logging with ellipsis notation shortcut for defered
* injection argument array.
*/
public void info(String message, Object... vars) {
getLogger().log(Level.INFO, message, vars);
}
/**
* Live activatable debug message (using {@link Config#DebugLog} to decide) at
* INFO level.
*
* Skipped if DebugLog is false.
*/
public void debug(String message) {
if (getConfig() != null && getConfig().getBoolean("debug", false)) {
getLogger().log(Level.INFO, message);
}
}
/**
* Live activatable debug message (using {@link Config#DebugLog} to decide) at
* INFO level with ellipsis notation shorcut for defered injection argument
* array.
*
* Skipped if DebugLog is false.
*/
public void debug(String message, Object... vars) {
if (getConfig() != null && getConfig().getBoolean("debug", false)) {
getLogger().log(Level.INFO, message, vars);
}
}
}
|
package se.hiflyer.fettle;
/**
* A view of a state machine from a users perspective, i.e it is immutable and already set up.
*
* @param <S> the type of the states
* @param <E> the type of the events that can trigger state changes
*/
public interface StateMachine<S, E> {
/**
* Gets the current state of the machine
*
* @return the state the machine is currently in
*/
S getCurrentState();
/**
* Fires an event at the state machine, possibly triggering a state change
*
* @param event the event that is fired
* @return true if the event resulted in a state change, false otherwise
*/
boolean fireEvent(E event);
/**
* Fires an event at the state machine, possibly triggering a state change
*
* @param event the event that is fired
* @param args the arguments to be sent to any actions that are run on a state change
* @return true if the event resulted in a state change, false otherwise
*/
boolean fireEvent(E event, Arguments args);
/**
* Forces the state machine to enter the forcedState even if there are no transitions leading to it
* No transition actions are run but exit actions on the current state and entry actions on the new state are run
*
* @param forcedState the state the machine will be in after this method is called
*/
void forceSetState(S forcedState);
}
|
package objektwerks;
import org.junit.jupiter.api.Test;
import java.util.List;
class LoopTest {
@Test void forTest() {
int[] xs = {1, 2, 3};
int sum = 0;
for(int i = 0; i < xs.length; i++) {
sum += xs[i];
}
assert(sum == 6);
}
@Test void enhancedForTest() {
int[] xs = {1, 2, 3};
int sum = 0;
for (int x : xs) {
sum += x;
}
assert(sum == 6);
}
@Test void iteratorTest() {
var xs = List.of(1, 2, 3);
var iterator = xs.iterator();
while (iterator.hasNext()) {
assert(iterator.next() > 0);
}
}
@Test void whileTest() {
int i = 0;
while (i < 10) {
i++;
assert(i > 0);
}
}
}
|
package thinwire.ui.layout;
import java.util.List;
import java.util.logging.Logger;
import thinwire.ui.Component;
import thinwire.ui.layout.TableLayout.Limit.Justify;
/**
* @author Joshua J. Gertzen
* @author Ted C. Howard
*/
public final class TableLayout extends AbstractLayout {
private static final Logger log = Logger.getLogger(TableLayout.class.getName());
public static class Limit {
public enum Justify {
CENTER,
CENTER_BOTTOM,
CENTER_FULL,
CENTER_TOP,
FULL,
FULL_CENTER,
LEFT_BOTTOM,
LEFT_CENTER,
LEFT_FULL,
LEFT_TOP,
RIGHT_BOTTOM,
RIGHT_CENTER,
RIGHT_FULL,
RIGHT_TOP
};
private int column;
private int row;
private int width;
private int height;
private String value;
private Justify justification;
public Limit() {
this(0, 0, 1, 1, Justify.FULL);
}
public Limit(String range) {
String[] values = ((String)range).split("\\s*,\\s*");
Justify just = Justify.FULL;
int width = 1;
int height = 1;
if (values.length >= 3) {
if (values[2].equals("l")) {
values[2] = "left";
} else if (values[2].equals("r")) {
values[2] = "right";
} else if (values[2].equals("c")) {
values[2] = "center";
} else if (values[2].equals("f")) {
values[2] = "full";
}
if (values[3].equals("t")) {
values[3] = "top";
} else if (values[3].equals("b")) {
values[3] = "bottom";
} else if (values[3].equals("c")) {
values[3] = "center";
} else if (values[3].equals("f")) {
values[3] = "full";
}
try {
String justStr = values[2].equals(values[3]) ? values[2] : values[2] + "_" + values[3];
just = Justify.valueOf(justStr.toUpperCase());
} catch (IllegalArgumentException e) {
width = Integer.parseInt(values[2]);
height = Integer.parseInt(values[3]);
}
}
init(values.length >= 1 ? Integer.parseInt(values[0]) : 0,
values.length >= 2 ? Integer.parseInt(values[1]) : 0,
width, height, just);
}
public Limit(int column, int row, int width, int height, Justify justification) {
init(column, row, width, height, justification);
}
private void init(int column, int row, int width, int height, Justify justification) {
rangeCheck("column", column);
rangeCheck("row", row);
rangeCheck("width", width);
rangeCheck("height", height);
this.column = column;
this.row = row;
this.width = width;
this.height = height;
this.value = getClass().getName() + "(" + column + ", " + row + ", " + width + ", " + height + ")";
this.justification = justification;
}
private void rangeCheck(String name, int value) {
if (value < 0 || value > Short.MAX_VALUE) throw new IllegalArgumentException(Limit.class.getName() + "." + name + " < 0 || " + Limit.class.getName() + "." + name + " > " + Short.MAX_VALUE);
}
public int getColumn() {
return column;
}
public int getRow() {
return row;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public Justify getJustification() {
return justification;
}
public boolean equals(Object o) {
return o instanceof Limit && toString().equals(o.toString());
}
public int hashCode() {
return toString().hashCode();
}
public String toString() {
return value;
}
}
private static final Limit DEFAULT_LIMIT = new Limit();
private double[] widths;
private double[] heights;
private int margin;
private int spacing;
public TableLayout(double sizes[][]) {
this(sizes, 0, 0);
}
public TableLayout(double sizes[][], int margin) {
this(sizes, margin, 0);
}
public TableLayout(double sizes[][], int margin, int spacing) {
super(Component.PROPERTY_LIMIT);
if (sizes == null || sizes.length != 2) throw new IllegalArgumentException("sizes == null || sizes.length != 2");
if (sizes[0] == null || sizes[0].length == 0) throw new IllegalArgumentException("sizes[0] == null || sizes[0].length == 0");
if (sizes[1] == null || sizes[1].length == 0) throw new IllegalArgumentException("sizes[1] == null || sizes[1].length == 0");
widths = sizes[0];
heights = sizes[1];
setSpacing(spacing);
setMargin(margin);
setAutoLayout(true);
}
protected Object getFormalLimit(Component comp) {
Object oLimit = comp.getLimit();
if (oLimit instanceof String) {
return new Limit((String)oLimit);
} else if (oLimit instanceof Limit) {
return (Limit)oLimit;
} else {
return null;
}
}
private int[] getAbsoluteSizes(int availableSize, double[] sizes) {
int[] absoluteSizes = new int[sizes.length];
availableSize -= (sizes.length - 1) * spacing + margin * 2;
int fillCnt = 0;
for (double f : sizes) {
if (f >= 1) availableSize -= f;
}
int pctSize = availableSize;
for (int i = 0, cnt = sizes.length; i < cnt; i++) {
double size = sizes[i];
if (size == 0) {
fillCnt++;
} else if (size < 1) {
absoluteSizes[i] = (int)(pctSize * size);
availableSize -= absoluteSizes[i];
} else {
absoluteSizes[i] = (int)size;
}
}
if (fillCnt > 0) {
int fillSize = availableSize / fillCnt;
int lastIndex = -1;
for (int i = 0, cnt = sizes.length; i < cnt; i++) {
if (sizes[i] == 0) {
absoluteSizes[i] = fillSize;
lastIndex = i;
}
}
if (lastIndex != -1) absoluteSizes[lastIndex] += availableSize % fillCnt;
}
return absoluteSizes;
}
public int getMargin() {
return margin;
}
public void setMargin(int margin) {
if (margin < 0 || margin >= Short.MAX_VALUE) throw new IllegalArgumentException("margin < 0 || margin >= " + Short.MAX_VALUE);
this.margin = margin;
if (autoLayout) apply();
}
public int getSpacing() {
return spacing;
}
public void setSpacing(int spacing) {
if (spacing < 0 || spacing >= Short.MAX_VALUE) throw new IllegalArgumentException("spacing < 0 || spacing >= " + Short.MAX_VALUE);
this.spacing = spacing;
if (autoLayout) apply();
}
public void apply() {
if (container == null) return;
int[] absoluteWidths = getAbsoluteSizes(container.getInnerWidth(), widths);
int[] absoluteHeights = getAbsoluteSizes(container.getInnerHeight(), heights);
for (Component c : (List<Component>) container.getChildren()) {
Limit limit = (Limit)c.getLimit();
if (limit == null) limit = DEFAULT_LIMIT;
Justify just = limit.getJustification();
int x = margin, y = margin, width = 0, height = 0;
for (int i = 0, cnt = limit.width, column = limit.column; i < cnt; i++) {
width += absoluteWidths[i + column] + spacing;
}
width -= spacing;
if (just != Justify.FULL && c.getWidth() < width) width = c.getWidth();
for (int i = 0, cnt = limit.height, row = limit.row; i < cnt; i++) {
height += absoluteHeights[i + row] + spacing;
}
height -= spacing;
if (just != Justify.FULL && c.getHeight() < height) height = c.getHeight();
for (int i = 0, cnt = limit.column; i < cnt; i++) {
x += absoluteWidths[i] + spacing;
}
if (width == c.getWidth()) {
if (just.name().indexOf("RIGHT") > -1) {
x += absoluteWidths[limit.column] - width;
} else if (just == Justify.CENTER || just == Justify.CENTER_BOTTOM || just == Justify.CENTER_FULL
|| just == Justify.CENTER_TOP) {
x += (absoluteWidths[limit.column] / 2) - (width / 2);
}
}
for (int i = 0, cnt = limit.row; i < cnt; i++) {
y += absoluteHeights[i] + spacing;
}
if (height == c.getHeight()) {
if (just.name().indexOf("BOTTOM") > -1) {
y += absoluteHeights[limit.row] - height;
} else if (just == Justify.CENTER || just == Justify.FULL_CENTER || just == Justify.LEFT_CENTER
|| just == Justify.RIGHT_CENTER) {
y += (absoluteHeights[limit.row] / 2) - (height / 2);
}
}
if (width >= 0 && height >= 0) c.setBounds(x, y, width, height);
}
}
}
|
package org.akvo.rsr.up.util;
/**
* Class to hold all public constants used in the application
*
* @author Stellan Lagerstroem
*
*/
public class ConstantUtil {
/**
* server and API constants
*/
public static final String TEST_HOST = "http://rsr.uat.akvo.org";
public static final String LIVE_HOST = "http://rsr.akvo.org";
public static final String PWD_URL = "/accounts/password/reset/";
public static final String AUTH_URL = "/auth/token/";
public static final String API_KEY_PATTERN = "&api_key=%s&username=%s";
// public static final String POST_UPDATE_URL = "/api/v1/project_update/?format=xml";
public static final String POST_UPDATE_URL = "/rest/v1/project_update/?format=xml";
public static final String FETCH_UPDATE_URL_PATTERN = "/rest/v1/project_update/?format=xml&limit=1000&project=%s"; // /api/v1/project_update/?format=xml&limit=0&project=
// public static final String VERIFY_UPDATE_PATTERN = "/api/v1/project_update/?format=xml&uuid=%s&limit=2";
public static final String VERIFY_UPDATE_PATTERN = "/rest/v1/project_update/?format=xml&uuid=%s&limit=2";
public static final String FETCH_PROJ_URL_PATTERN = "/api/v1/project/?format=xml&limit=0&partnerships__organisation=%s";
public static final String FETCH_COUNTRIES_URL = "/api/v1/country/?format=xml&limit=0";
public static final String FETCH_PROJ_COUNT_URL = "/api/v1/project/?format=xml&limit=0&partnerships__organisation=%s";
public static final String PROJECT_PATH_PATTERN = "/api/v1/project/%s/";
public static final String USER_PATH_PATTERN= "/api/v1/user/%s/";
public static final String FETCH_USER_URL_PATTERN = "/api/v1/user/%s/?format=xml&depth=1";
public static final String FETCH_ORG_URL_PATTERN = "/api/v1/organisation/%s/?format=xml&depth=0";
public static final int MAX_IMAGE_UPLOAD_SIZE = 2000000; //Nginx POST limit is 3MB, B64 encoding expands 33% and there may be long text
public static final String SERVER_VERSION_HEADER = "x-akvo-server-version"; //TODO
/**
* file system constants
*/
public static final String XML_SUFFIX = ".xml";
public static final String JPG_SUFFIX = ".jpg";
// public static final String TOP_DIR = "/akvorsr/";
public static final String PHOTO_DIR = "/akvorsr/photos/";
public static final String IMAGECACHE_DIR = "/akvorsr/imagecache/";
/**
* status related constants
*/
public static final String COMPLETE_STATUS = "Complete";
public static final String SENT_STATUS = "Sent";
public static final String RUNNING_STATUS = "Running";
public static final String IN_PROGRESS_STATUS = "In Progress";
public static final String QUEUED_STATUS = "Queued";
public static final String FAILED_STATUS = "Failed";
/**
* notification types
*/
public static final String PROGRESS = "PROGRESS";
public static final String FILE_COMPLETE = "FILE_COMPLETE";
public static final String ERROR = "ERROR";
/**
* keys for saved state and bundle extras
*/
public static final String PROJECT_ID_KEY = "org.akvo.rsr.up.PROJECT";
public static final String UPDATE_ID_KEY = "org.akvo.rsr.up.UPDATE";
/**
* settings keys
*/
public static final String HOST_SETTING_KEY = "data_host";
public static final String DEBUG_SETTING_KEY = "setting_debug";
public static final String SEND_IMG_SETTING_KEY = "setting_send_images";
public static final String DELAY_IMG_SETTING_KEY = "setting_delay_image_fetch";
public static final String AUTH_USERNAME_KEY = "authorized_username";
public static final String AUTH_APIKEY_KEY = "authorized_apikey";
public static final String AUTH_USERID_KEY = "authorized_userid";
public static final String AUTH_ORGID_KEY = "authorized_orgid";
public static final String LOCAL_ID_KEY = "next_local_id";
/**
* intents
*/
public static final String PROJECTS_FETCHED_ACTION = "org.akvo.rsr.up.PROJECTS_FETCHED";
public static final String PROJECTS_PROGRESS_ACTION = "org.akvo.rsr.up.PROJECTS_PROGRESS";
public static final String UPDATES_SENT_ACTION = "org.akvo.rsr.up.UPDATES_SENT";
public static final String UPDATES_SENDPROGRESS_ACTION = "org.akvo.rsr.up.UPDATES_PROGRESS";
public static final String UPDATES_VERIFIED_ACTION = "org.akvo.rsr.up.UPDATES_VERIFIED";
public static final String AUTHORIZATION_RESULT_ACTION = "org.akvo.rsr.up.AUTHORIZATION_RESULT";
public static final String GPS_STATUS_INTENT = "com.eclipsim.gpsstatus.VIEW";
public static final String BARCODE_SCAN_INTENT = "com.google.zxing.client.android.SCAN";
/**
* intent extra keys
*/
public static final String PHASE_KEY = "PHASE_KEY";
public static final String SOFAR_KEY = "SOFAR_KEY";
public static final String TOTAL_KEY = "TOTAL_KEY";
public static final String SERVICE_ERRMSG_KEY = "org.akvo.rsr.up.ERRMSG";
public static final String SERVICE_UNRESOLVED_KEY = "org.akvo.rsr.up.UNRESOLVED";
public static final String USERNAME_KEY = "org.akvo.rsr.up.USERNAME";
public static final String PASSWORD_KEY = "org.akvo.rsr.up.PASSWORD";
/**
* posting outcomes
*/
public static final int POST_SUCCESS = 0;
public static final int POST_FAILURE = 1;
public static final int POST_UNKNOWN = 2;
/**
* language codes
*/
public static final String ENGLISH_CODE = "en";
/**
* "code" to prevent unauthorized use of administrative settings/preferences
*/
public static final String ADMIN_AUTH_CODE = "12345";
/**
* prevent instantiation
*/
private ConstantUtil() {
}
}
|
package com.horcrux.svg;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.PointF;
import android.graphics.RectF;
import android.graphics.Typeface;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.uimanager.ReactShadowNode;
import com.facebook.react.uimanager.annotations.ReactProp;
import javax.annotation.Nullable;
import static android.graphics.PathMeasure.POSITION_MATRIX_FLAG;
import static android.graphics.PathMeasure.TANGENT_MATRIX_FLAG;
/**
* Shadow node for virtual TSpan view
*/
public class TSpanShadowNode extends TextShadowNode {
private Path mCache;
private @Nullable String mContent;
private TextPathShadowNode textPath;
private static final String PROP_FONT_FAMILY = "fontFamily";
private static final String PROP_FONT_SIZE = "fontSize";
private static final String PROP_FONT_STYLE = "fontStyle";
private static final String PROP_FONT_WEIGHT = "fontWeight";
private static final String PROP_KERNING = "kerning";
private static final String PROP_IS_KERNING_VALUE_SET = "isKerningValueSet";
private static final String PROP_LETTER_SPACING = "letterSpacing";
@ReactProp(name = "content")
public void setContent(@Nullable String content) {
mContent = content;
markUpdated();
}
@Override
public void draw(Canvas canvas, Paint paint, float opacity) {
if (mContent != null) {
drawPath(canvas, paint, opacity);
} else {
clip(canvas, paint);
drawGroup(canvas, paint, opacity);
}
}
@Override
protected void releaseCachedPath() {
mCache = null;
}
@Override
protected Path getPath(Canvas canvas, Paint paint) {
if (mCache != null) {
return mCache;
}
if (mContent == null) {
return getGroupPath(canvas, paint);
}
setupTextPath();
pushGlyphContext();
Path path = mCache = getLinePath(canvas, mContent, paint);
popGlyphContext();
path.computeBounds(new RectF(), true);
return path;
}
private float getTextAnchorShift(float width) {
float x = 0;
switch (getComputedTextAnchor()) {
case TEXT_ANCHOR_MIDDLE:
x = -width / 2;
break;
case TEXT_ANCHOR_END:
x = -width;
break;
}
return x;
}
private Path getLinePath(Canvas canvas, String line, Paint paint) {
ReadableMap font = applyTextPropertiesToPaint(paint);
int length = line.length();
Path path = new Path();
if (length == 0) {
return path;
}
float distance = 0;
float startOffset = 0;
float renderMethodScaling = 1;
float textMeasure = paint.measureText(line);
float textAnchorShift = getTextAnchorShift(textMeasure);
PathMeasure pm = null;
if (textPath != null) {
pm = new PathMeasure(textPath.getPath(), false);
distance = pm.getLength();
startOffset = PropHelper.fromPercentageToFloat(textPath.getStartOffset(), distance, 0, mScale);
// String spacing = textPath.getSpacing(); // spacing = "auto | exact"
String method = textPath.getMethod(); // method = "align | stretch"
if ("stretch".equals(method)) {
renderMethodScaling = distance / textMeasure;
}
}
Path glyph;
float width;
Matrix matrix;
String current;
PointF glyphPoint;
PointF glyphDelta;
String previous = "";
char[] chars = line.toCharArray();
float[] widths = new float[length];
float glyphPosition = startOffset + textAnchorShift;
double kerningValue = font.getDouble(PROP_KERNING) * mScale;
boolean isKerningValueSet = font.getBoolean(PROP_IS_KERNING_VALUE_SET);
paint.getTextWidths(line, widths);
for (int index = 0; index < length; index++) {
width = widths[index] * renderMethodScaling;
current = String.valueOf(chars[index]);
glyph = new Path();
if (isKerningValueSet) {
glyphPosition += kerningValue;
} else {
float bothWidth = paint.measureText(previous + current);
float previousWidth = paint.measureText(previous);
float currentWidth = paint.measureText(current);
float kernedWidth = bothWidth - previousWidth;
float kerning = kernedWidth - currentWidth;
glyphPosition += kerning;
previous = current;
}
glyphPoint = getGlyphPointFromContext(glyphPosition, width);
glyphDelta = getGlyphDeltaFromContext();
glyphPosition += width;
matrix = new Matrix();
if (textPath != null) {
float halfway = width / 2;
float start = glyphPoint.x + glyphDelta.x;
float midpoint = start + halfway;
if (midpoint > distance ) {
if (start <= distance) {
// Seems to cut off too early, see e.g. toap3, this shows the last "p"
// Tangent will be from start position instead of midpoint
midpoint = start;
halfway = 0;
} else {
break;
}
} else if (midpoint < 0) {
continue;
}
pm.getMatrix(midpoint, matrix, POSITION_MATRIX_FLAG | TANGENT_MATRIX_FLAG);
matrix.preTranslate(-halfway, glyphDelta.y);
matrix.preScale(renderMethodScaling, 1);
matrix.postTranslate(0, glyphPoint.y);
} else {
matrix.setTranslate(
glyphPoint.x + glyphDelta.x + textAnchorShift,
glyphPoint.y + glyphDelta.y
);
}
paint.getTextPath(current, 0, 1, 0, 0, glyph);
glyph.transform(matrix);
path.addPath(glyph);
}
return path;
}
private ReadableMap applyTextPropertiesToPaint(Paint paint) {
ReadableMap font = getFontFromContext();
paint.setTextAlign(Paint.Align.LEFT);
float fontSize = (float)font.getDouble(PROP_FONT_SIZE) * mScale;
float letterSpacing = (float)font.getDouble(PROP_LETTER_SPACING) * mScale;
paint.setTextSize(fontSize);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
paint.setLetterSpacing(letterSpacing / fontSize); // setLetterSpacing is only available from LOLLIPOP and on
}
boolean isBold = font.hasKey(PROP_FONT_WEIGHT) && "bold".equals(font.getString(PROP_FONT_WEIGHT));
boolean isItalic = font.hasKey(PROP_FONT_STYLE) && "italic".equals(font.getString(PROP_FONT_STYLE));
int fontStyle;
if (isBold && isItalic) {
fontStyle = Typeface.BOLD_ITALIC;
} else if (isBold) {
fontStyle = Typeface.BOLD;
} else if (isItalic) {
fontStyle = Typeface.ITALIC;
} else {
fontStyle = Typeface.NORMAL;
}
// NB: if the font family is null / unsupported, the default one will be used
paint.setTypeface(Typeface.create(font.getString(PROP_FONT_FAMILY), fontStyle));
return font;
}
private void setupTextPath() {
ReactShadowNode parent = getParent();
while (parent != null) {
if (parent.getClass() == TextPathShadowNode.class) {
textPath = (TextPathShadowNode)parent;
break;
} else if (!(parent instanceof TextShadowNode)) {
break;
}
parent = parent.getParent();
}
}
}
|
package gov.nih.nci.security.dao;
import gov.nih.nci.security.authorization.domainobjects.*;
import gov.nih.nci.security.util.*;
import java.util.Collection;
import java.util.Iterator;
import gov.nih.nci.security.authorization.jaas.*;
import gov.nih.nci.security.dao.hibernate.HibernateSessionFactory;
import gov.nih.nci.security.exceptions.CSObjectNotFoundException;
import gov.nih.nci.security.exceptions.CSTransactionException;
import java.security.Principal;
import java.util.Set;
import javax.security.auth.Subject;
import org.apache.log4j.Logger;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.SessionFactory;
import java.util.List;
import net.sf.hibernate.expression.*;
import gov.nih.nci.security.dao.hibernate.*;
import java.util.*;
/**
* @version 1.0
* @created 03-Dec-2004 1:17:47 AM
*/
public class AuthorizationDAOImpl implements AuthorizationDAO {
static final Logger log = Logger.getLogger(AuthorizationDAOImpl.class
.getName());
private SessionFactory sf = null;
private Application application = null;
public AuthorizationDAOImpl(SessionFactory sf, String applicationContextName) {
this.sf = sf;
try {
this.application = this
.getApplicationByName(applicationContextName);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void finalize() throws Throwable {
super.finalize();
}
public void setHibernateSessionFactory(SessionFactory sf) {
this.sf = sf;
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#addUserToGroup(java.lang.String,
* java.lang.String)
*/
public void addUserToGroup(String groupId, String user)
throws CSTransactionException {
// TODO Auto-generated method stub
/**
* insert into usergroup table (groupid,userid);
*/
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#assignGroupRoleToProtectionGroup(java.lang.String,
* java.lang.String, java.lang.String)
*/
public void assignGroupRoleToProtectionGroup(String protectionGroupId,
String groupId, String[] rolesId) throws CSTransactionException {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#assignPrivilegesToRole(java.lang.String[],
* java.lang.String)
*/
public void assignPrivilegesToRole(String roleId, String[] privilegeIds)
throws CSTransactionException {
Session s = null;
Transaction t = null;
//log.debug("Running create test...");
try {
ArrayList newList = new ArrayList();
for (int k = 0; k < privilegeIds.length; k++) {
log.debug("The new list:" + privilegeIds[k]);
newList.add(privilegeIds[k]);
}
s = sf.openSession();
t = s.beginTransaction();
Role r = this.getRole(new Long(roleId));
/**
* First check if there are some privileges for this role If there
* are any then delete them.
*/
RolePrivilege search = new RolePrivilege();
search.setRole(r);
List list = s.createCriteria(RolePrivilege.class).add(
Example.create(search)).list();
ArrayList oldList = new ArrayList();
Iterator it = list.iterator();
while (it.hasNext()) {
RolePrivilege rp1 = (RolePrivilege) it.next();
Privilege priv = rp1.getPrivilege();
oldList.add(priv.getId().toString());
log.debug("The old List" + priv.getId().toString());
}
Collection toBeInserted = ObjectSetUtil.minus(newList, oldList);
Collection toBeRemoved = ObjectSetUtil.minus(oldList, newList);
Iterator toBeInsertedIt = toBeInserted.iterator();
Iterator toBeRemovedIt = toBeRemoved.iterator();
while (toBeInsertedIt.hasNext()) {
String rp_id = (String) toBeInsertedIt.next();
log.debug("To Be Inserted: " + rp_id);
Privilege p = this.getPrivilege(rp_id);
RolePrivilege rp = new RolePrivilege();
rp.setPrivilege(p);
rp.setRole(r);
rp.setUpdateDate(new java.util.Date());
s.save(rp);
}
while (toBeRemovedIt.hasNext()) {
String p_id = (String) toBeRemovedIt.next();
log.debug("To Be Removed: " + p_id);
Privilege p = new Privilege();
p.setId(new Long(p_id));
search.setPrivilege(p);
List list_del = s.createCriteria(RolePrivilege.class).add(
Example.create(search)).list();
RolePrivilege rp_del = (RolePrivilege) list_del.get(0);
s.delete(rp_del);
}
t.commit();
//log.debug( "Privilege ID is: " +
// privilege.getId().doubleValue() );
} catch (Exception ex) {
log.error(ex);
try {
t.rollback();
} catch (Exception ex3) {
}
throw new CSTransactionException("Bad", ex);
} finally {
try {
s.close();
} catch (Exception ex2) {
}
}
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#assignProtectionElements(java.lang.String,
* java.lang.String[], java.lang.String[])
*/
public void assignProtectionElements(String protectionGroupName,
String[] protectionElementObjectName,
String[] protectionElementAttributeName)
throws CSTransactionException {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#assignProtectionElements(java.lang.String,
* java.lang.String[])
*/
public void assignProtectionElements(String protectionGroupName,
String[] protectionElementObjectNames)
throws CSTransactionException {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#assignUserRoleToProtectionGroup(java.lang.String,
* java.lang.String[], java.lang.String)
*/
public void assignUserRoleToProtectionGroup(String userId,
String[] rolesId, String protectionGroupId)
throws CSTransactionException {
// TODO Auto-generated method stub
}
public boolean checkPermission(AccessPermission permission, String userName) {
// TODO Auto-generated method stub
return false;
}
public boolean checkPermission(AccessPermission permission, Subject subject) {
// TODO Auto-generated method stub
return false;
}
public boolean checkPermission(AccessPermission permission, User user) {
// TODO Auto-generated method stub
return false;
}
public boolean checkPermission(String userName, String objectId,
String attributeId, String privilegeName) {
// TODO Auto-generated method stub
return false;
}
public boolean checkPermission(String userName, String objectId,
String privilegeName) {
// TODO Auto-generated method stub
return false;
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#createGroup(gov.nih.nci.security.authorization.domainobjects.Group)
*/
public void createGroup(Group group) throws CSTransactionException {
// TODO Auto-generated method stub
Session s = null;
Transaction t = null;
try {
s = sf.openSession();
t = s.beginTransaction();
group.setApplication(application);
s.save(group);
t.commit();
log.debug("Group ID is: " + group.getGroupId());
} catch (Exception ex) {
log.error(ex);
try {
t.rollback();
} catch (Exception ex3) {
}
throw new CSTransactionException("Bad", ex);
} finally {
try {
s.close();
} catch (Exception ex2) {
}
}
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#createPrivilege(gov.nih.nci.security.authorization.domainobjects.Privilege)
*/
public void createPrivilegeXXX(Privilege privilege)
throws CSTransactionException {
// TODO Auto-generated method stub
Session s = null;
Transaction t = null;
log.debug("Running create test...");
try {
s = HibernateSessionFactory.currentSession();
t = s.beginTransaction();
//Privilege p = new Privilege();
//p.setDesc("TestDesc");
//p.setName("TestName");
s.save(privilege);
t.commit();
log.debug("Privilege ID is: "
+ privilege.getId().doubleValue());
} catch (Exception ex) {
log.error(ex);
try {
t.rollback();
} catch (Exception ex3) {
}
throw new CSTransactionException("Bad", ex);
} finally {
try {
s.close();
} catch (Exception ex2) {
}
}
}
public void createPrivilege(Privilege privilege)
throws CSTransactionException {
// TODO Auto-generated method stub
Session s = null;
Transaction t = null;
try {
s = sf.openSession();
t = s.beginTransaction();
s.save(privilege);
t.commit();
log.debug("Privilege ID is: "
+ privilege.getId().doubleValue());
} catch (Exception ex) {
log.error(ex);
try {
t.rollback();
} catch (Exception ex3) {
}
throw new CSTransactionException("Bad", ex);
} finally {
try {
s.close();
} catch (Exception ex2) {
}
}
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#createProtectionElement(gov.nih.nci.security.authorization.domainobjects.ProtectionElement)
*/
public void createProtectionElement(ProtectionElement protectionElement)
throws CSTransactionException {
Session s = null;
Transaction t = null;
try {
s = sf.openSession();
t = s.beginTransaction();
protectionElement.setApplication(application);
protectionElement.setUpdateDate(new Date());
s.save(protectionElement);
t.commit();
log.debug("Protection element ID is: " + protectionElement.getProtectionElementId());
} catch (Exception ex) {
log.error(ex);
try {
t.rollback();
} catch (Exception ex3) {
}
throw new CSTransactionException("Protection Element could not be created:", ex);
} finally {
try {
s.close();
} catch (Exception ex2) {
}
}
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#createProtectionGroup(gov.nih.nci.security.authorization.domainobjects.ProtectionGroup)
*/
public void createProtectionGroup(ProtectionGroup protectionGroup)
throws CSTransactionException {
Session s = null;
Transaction t = null;
try {
s = sf.openSession();
t = s.beginTransaction();
protectionGroup.setApplication(application);
protectionGroup.setUpdateDate(new Date());
s.save(protectionGroup);
t.commit();
log.debug("Protection group ID is: " + protectionGroup.getProtectionGroupId());
} catch (Exception ex) {
log.error(ex);
try {
t.rollback();
} catch (Exception ex3) {
}
throw new CSTransactionException("Protection group could not be created:", ex);
} finally {
try {
s.close();
} catch (Exception ex2) {
}
}
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#createRole(gov.nih.nci.security.authorization.domainobjects.Role)
*/
public void createRole(Role role) throws CSTransactionException {
// TODO Auto-generated method stub
Session s = null;
Transaction t = null;
try {
s = sf.openSession();
t = s.beginTransaction();
role.setApplication(application);
role.setUpdateDate(new Date());
s.save(role);
t.commit();
log.debug("Role ID is: " + role.getId().doubleValue());
} catch (Exception ex) {
log.error(ex);
try {
t.rollback();
} catch (Exception ex3) {
}
throw new CSTransactionException("Bad", ex);
} finally {
try {
s.close();
} catch (Exception ex2) {
}
}
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#deAssignProtectionElements(java.lang.String,
* java.lang.String[], java.lang.String[])
*/
public void deAssignProtectionElements(String protectionGroupName,
String[] protectionElementObjectNames,
String[] protectionElementAttributeNames)
throws CSTransactionException {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#deAssignProtectionElements(java.lang.String[],
* java.lang.String)
*/
public void deAssignProtectionElements(
String[] protectionElementObjectNames, String protectionGroupName)
throws CSTransactionException {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#getApplicationContext()
*/
public ApplicationContext getApplicationContext() {
// TODO Auto-generated method stub
return null;
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#getGroup(java.lang.Long)
*/
public Group getGroup(Long groupId) throws CSObjectNotFoundException {
// TODO Auto-generated method stub
return (Group)this.getObjectByPrimaryKey(Group.class,groupId);
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#getGroup(java.lang.String)
*/
public Group getGroup(String groupName) throws CSObjectNotFoundException {
// TODO Auto-generated method stub
Session s = null;
Group grp = null;
try {
Group search = new Group();
search.setGroupName(groupName);
search.setApplication(application);
//String query = "FROM
// gov.nih.nci.security.authorization.domianobjects.Application";
s = sf.openSession();
List list = s.createCriteria(Group.class).add(
Example.create(search)).list();
//p = (Privilege)s.load(Privilege.class,new Long(privilegeId));
if (list.size() == 0) {
throw new CSObjectNotFoundException("Group not found");
}
grp = (Group) list.get(0);
} catch (Exception ex) {
log.fatal("Unable to find Group", ex);
} finally {
try {
s.close();
} catch (Exception ex2) {
}
}
return grp;
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#getObjects(gov.nih.nci.security.dao.SearchCriteria)
*/
public Set getObjects(SearchCriteria searchCriteria) {
// TODO Auto-generated method stub
return null;
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#getPrincipals(java.lang.String)
*/
public Principal[] getPrincipals(String userName) {
// TODO Auto-generated method stub
return null;
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#getPrivilege(java.lang.String)
*/
public Privilege getPrivilege(String privilegeId)
throws CSObjectNotFoundException {
// TODO Auto-generated method stub
/**
* Session s = null; Privilege p = null; try { //String query = "SELECT
* privilege FROM privilege IN CLASS
* gov.nih.nci.security.authorization.domianobjects.Privilege where
* privilege.privilege_id=:id"; s = sf.openSession(); //List list =
* s.find(query,new Long(privilegeId),Hibernate.LONG); p =
* (Privilege)s.load(Privilege.class,new Long(privilegeId));
* log.debug("Somwthing"); if(p==null){ throw new
* CSObjectNotFoundException("Not found"); }
* } catch (Exception ex) { ex.printStackTrace(); try { s.close(); }
* catch (Exception ex2) { }
* } return p;
*/
return (Privilege) this.getObjectByPrimaryKey(Privilege.class,
new Long(privilegeId));
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#getProtectionElement(java.lang.Long)
*/
public ProtectionElement getProtectionElement(Long protectionElementId)
throws CSObjectNotFoundException {
// TODO Auto-generated method stub
return (ProtectionElement)this.getObjectByPrimaryKey(ProtectionElement.class,protectionElementId);
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#getProtectionElement(java.lang.String)
*/
public ProtectionElement getProtectionElement(String objectId)
throws CSObjectNotFoundException {
Session s = null;
ProtectionElement pe = null;
try {
ProtectionElement search = new ProtectionElement();
search.setObjectId(objectId);
search.setApplication(application);
//String query = "FROM
// gov.nih.nci.security.authorization.domianobjects.Application";
s = sf.openSession();
List list = s.createCriteria(ProtectionElement.class).add(
Example.create(search)).list();
if (list.size() == 0) {
throw new CSObjectNotFoundException("Protection Element not found");
}
pe = (ProtectionElement)list.get(0);
} catch (Exception ex) {
log.fatal("Unable to find Protection Element", ex);
} finally {
try {
s.close();
} catch (Exception ex2) {
}
}
return pe;
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#getProtectionGroup(java.lang.Long)
*/
public ProtectionGroup getProtectionGroup(Long protectionGroupId)
throws CSObjectNotFoundException {
// TODO Auto-generated method stub
return (ProtectionGroup)this.getObjectByPrimaryKey(ProtectionGroup.class,protectionGroupId);
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#getProtectionGroup(java.lang.String)
*/
public ProtectionGroup getProtectionGroup(String protectionGroupName)
throws CSObjectNotFoundException {
// TODO Auto-generated method stub
Session s = null;
ProtectionGroup pgrp = null;
try {
ProtectionGroup search = new ProtectionGroup();
search.setProtectionGroupName(protectionGroupName);
search.setApplication(application);
//String query = "FROM
// gov.nih.nci.security.authorization.domianobjects.Application";
s = sf.openSession();
List list = s.createCriteria(ProtectionGroup.class).add(
Example.create(search)).list();
if (list.size() == 0) {
throw new CSObjectNotFoundException("Protection Group not found");
}
pgrp = (ProtectionGroup) list.get(0);
} catch (Exception ex) {
log.fatal("Unable to find Protection group", ex);
} finally {
try {
s.close();
} catch (Exception ex2) {
}
}
return pgrp;
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#getRole(java.lang.Long)
*/
public Role getRole(Long roleId) throws CSObjectNotFoundException {
// TODO Auto-generated method stub
Role r = (Role) this.getObjectByPrimaryKey(Role.class, roleId);
r.setPrivileges(this.getPrivileges(roleId.toString()));
return r;
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#getRole(java.lang.String)
*/
public Role getRole(String roleName) throws CSObjectNotFoundException {
// TODO Auto-generated method stub
return null;
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#getUser(java.lang.String)
*/
public User getUser(String loginName) {
// TODO Auto-generated method stub
return null;
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#modifyGroup(gov.nih.nci.security.authorization.domainobjects.Group)
*/
public void modifyGroup(Group group) throws CSTransactionException {
// TODO Auto-generated method stub
Session s = null;
Transaction t = null;
try {
log.debug("About to be Modified");
s = sf.openSession();
t = s.beginTransaction();
group.setUpdateDate(new Date());
s.update(group);
log.debug("Modified");
t.commit();
//log.debug( "Privilege ID is: " +
// privilege.getId().doubleValue() );
} catch (Exception ex) {
log.error(ex);
try {
t.rollback();
} catch (Exception ex3) {
}
throw new CSTransactionException("Group Object could not be modified:", ex);
} finally {
try {
s.close();
} catch (Exception ex2) {
}
}
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#modifyPrivilege(gov.nih.nci.security.authorization.domainobjects.Privilege)
*/
public void modifyPrivilege(Privilege privilege)
throws CSTransactionException {
// TODO Auto-generated method stub
Session s = null;
Transaction t = null;
try {
log.debug("About to be Modified");
s = sf.openSession();
t = s.beginTransaction();
s.saveOrUpdate(privilege);
log.debug("Modified");
t.commit();
//log.debug( "Privilege ID is: " +
// privilege.getId().doubleValue() );
} catch (Exception ex) {
log.error(ex);
try {
t.rollback();
} catch (Exception ex3) {
}
throw new CSTransactionException("Bad", ex);
} finally {
try {
s.close();
} catch (Exception ex2) {
}
}
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#modifyProtectionGroup(gov.nih.nci.security.authorization.domainobjects.ProtectionGroup)
*/
public void modifyProtectionGroup(ProtectionGroup protectionGroup)
throws CSTransactionException {
Session s = null;
Transaction t = null;
try {
s = sf.openSession();
t = s.beginTransaction();
protectionGroup.setUpdateDate(new Date());
s.update(protectionGroup);
log.debug("Modified");
t.commit();
} catch (Exception ex) {
log.error(ex);
try {
t.rollback();
} catch (Exception ex3) {
}
throw new CSTransactionException("Protection group could not be modified", ex);
} finally {
try {
s.close();
} catch (Exception ex2) {
}
}
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#modifyRole(gov.nih.nci.security.authorization.domainobjects.Role)
*/
public void modifyRole(Role role) throws CSTransactionException {
// TODO Auto-generated method stub
Session s = null;
Transaction t = null;
try {
s = sf.openSession();
t = s.beginTransaction();
s.update(role);
log.debug("Modified");
t.commit();
} catch (Exception ex) {
log.error(ex);
try {
t.rollback();
} catch (Exception ex3) {
}
throw new CSTransactionException("Bad", ex);
} finally {
try {
s.close();
} catch (Exception ex2) {
}
}
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#removeGroup(java.lang.String)
*/
public void removeGroup(String groupId) throws CSTransactionException {
// TODO Auto-generated method stub
/**
* This method should remove all the children
* Namely all the reocrds form user_group table where this
* group is refernced
* Also
* All the records from the user_group_role_protection_group
*/
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#removeGroupFromProtectionGroup(java.lang.String,
* java.lang.String)
*/
public void removeGroupFromProtectionGroup(String protectionGroupId,
String groupId) throws CSTransactionException {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#removeGroupRoleFromProtectionGroup(java.lang.String,
* java.lang.String, java.lang.String[])
*/
public void removeGroupRoleFromProtectionGroup(String protectionGroupId,
String groupId, String[] roleId) throws CSTransactionException {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#removePrivilege(java.lang.String)
*/
public void removePrivilege(String privilegeId)
throws CSTransactionException {
Privilege p = new Privilege();
p.setId(new Long(privilegeId));
this.removeObject(p);
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#removeProtectionElement(gov.nih.nci.security.authorization.domainobjects.ProtectionElement)
*/
public void removeProtectionElement(ProtectionElement element)
throws CSTransactionException {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#removeProtectionGroup(java.lang.String)
*/
public void removeProtectionGroup(String protectionGroupName)
throws CSTransactionException {
// TODO Auto-generated method stub
/**
* All the children should be removed
* Namely - all the records from protection_elements
* all the records from user_group_role_protectiongroup
*/
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#removeRole(java.lang.String)
*/
public void removeRole(String roleId) throws CSTransactionException {
// TODO Auto-generated method stub
Role r = new Role();
r.setId(new Long(roleId));
this.removeObject(r);
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#removeUserFromGroup(java.lang.String,
* java.lang.String)
*/
public void removeUserFromGroup(String groupId, String userId)
throws CSTransactionException {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#removeUserFromProtectionGroup(java.lang.String,
* java.lang.String)
*/
public void removeUserFromProtectionGroup(String protectionGroupId,
String userId) throws CSTransactionException {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#removeUserRoleFromProtectionGroup(java.lang.String,
* java.lang.String, java.lang.String[])
*/
public void removeUserRoleFromProtectionGroup(String protectionGroupName,
String userName, String[] roles) throws CSTransactionException {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#setOwnerForProtectionElement(java.lang.String,
* java.lang.String, java.lang.String)
*/
public void setOwnerForProtectionElement(String userName,
String protectionElementObjectName,
String protectionElementAttributeName)
throws CSTransactionException {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.security.dao.AuthorizationDAO#setOwnerForProtectionElement(java.lang.String,
* java.lang.String)
*/
public void setOwnerForProtectionElement(
String protectionElementObjectName, String userName)
throws CSTransactionException {
// TODO Auto-generated method stub
}
public Set getPrivileges(String roleId) throws CSObjectNotFoundException {
Session s = null;
//ArrayList result = new ArrayList();
Set result = new HashSet();
try {
s = sf.openSession();
RolePrivilege search = new RolePrivilege();
Role r = new Role();
r.setId(new Long(roleId));
List list = s.createCriteria(RolePrivilege.class).add(
Example.create(search)).list();
Iterator it = list.iterator();
while (it.hasNext()) {
RolePrivilege rp = (RolePrivilege) it.next();
Privilege p = rp.getPrivilege();
result.add(p);
}
} catch (Exception ex) {
log.error(ex);
throw new CSObjectNotFoundException("No Set found", ex);
} finally {
try {
s.close();
} catch (Exception ex2) {
}
}
return result;
}
private Object getObjectByPrimaryKey(Class objectType, Long primaryKey)
throws CSObjectNotFoundException {
Object oj = null;
Session s = null;
try {
s = sf.openSession();
oj = s.load(objectType, primaryKey);
if (oj == null) {
throw new CSObjectNotFoundException(objectType.getName()
+ " not found");
}
} catch (Exception ex) {
log.error(ex);
throw new CSObjectNotFoundException(objectType.getName()
+ " not found", ex);
} finally {
try {
s.close();
} catch (Exception ex2) {
}
}
return oj;
}
private void removeObject(Object oj) throws CSTransactionException {
Session s = null;
Transaction t = null;
try {
s = sf.openSession();
t = s.beginTransaction();
s.delete(oj);
t.commit();
} catch (Exception ex) {
log.error(ex);
try {
t.rollback();
} catch (Exception ex3) {
}
throw new CSTransactionException("Bad", ex);
} finally {
try {
s.close();
} catch (Exception ex2) {
}
}
}
private Application getApplicationByName(String contextName)
throws CSObjectNotFoundException {
Session s = null;
Application app = null;
try {
Application search = new Application();
search.setApplicationName(contextName);
//String query = "FROM
// gov.nih.nci.security.authorization.domianobjects.Application";
s = sf.openSession();
List list = s.createCriteria(Application.class).add(
Example.create(search)).list();
//p = (Privilege)s.load(Privilege.class,new Long(privilegeId));
log.debug("Somwthing");
if (list.size() == 0) {
throw new CSObjectNotFoundException("Not found");
}
app = (Application) list.get(0);
} catch (Exception ex) {
log.fatal("Unable to find application context", ex);
} finally {
try {
s.close();
} catch (Exception ex2) {
}
}
return app;
}
}
|
package controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import model.*;
import view.*;
/**
* Handles listeners.
*
* @author Lazar Klincov, Robin Duda.
*/
public class Controller implements ActionListener {
private WBView wbview;
private Model model;
private Album album = null;
private Movie movie = null;
private Book book = null;
private Review review = null;
private int rating;
private String media;
private QueryInterpreter qx = null;
public Controller(Model m, WBView wbv, QueryInterpreter queryExecuter) {
this.model = m;
this.wbview = wbv;
this.qx = queryExecuter;
executeQuery(QueryType.ALBUMSEARCH, "%");
}
/** executes a query in a thread, when the query is done an event is
added to gui thread, which will load all available data from the data
bank in model.
@param queryType type of query to be executed.
@param queryText text parameters to query. */
public void executeQuery(final QueryType queryType, final String queryText) {
new Thread() {
String errormsg = "";
public void run() {
qx.open();
try {
wbview.setColumnFilter(new String[] { "review" });
switch (queryType) {
case MEDIAADD:
switch (addType()) {
case ALBUMSEARCH:
qx.addMedia(album.getName(), album.getYear(), album
.getGenre(), album.getArtist().toArray(),
0, 1);
break;
case MOVIESEARCH:
qx.addMedia(movie.getTitle(), movie.getYear(),
movie.getGenre(), movie.getDirector()
.toArray(), movie.getDuration(), 2);
break;
case BOOKSEARCH:
qx.addMedia(book.getTitle(), book.getYear(),
book.getGenre(),
book.getAuthor().toArray(), 0, 3);
break;
default:
break;
}
break;
case MOVIESEARCH:
qx.getMoviesByAny(queryText);
break;
case ALBUMSEARCH:
qx.getAlbumsByAny(queryText);
break;
case REVIEWSEARCH:
qx.getReviewsByAny(queryText);
break;
case RATE:
qx.rateAlbum(rating, media);
break;
case REVIEW:
qx.reviewMedia(review, queryText);
break;
case LOGIN:
qx.verifyAccount(model.getUser(), model.getPass());
break;
default:
break;
}
} catch (SQLException e) {
e.printStackTrace();
errormsg = e.getMessage();
} finally {
qx.disconnect();
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (!errormsg.equals(""))
wbview.showError(errormsg);
if (queryType != QueryType.LOGIN)
wbview.feedTable(model.getBank());
if (queryType == QueryType.LOGIN) {
if (model.getValidAccount()) {
wbview.setVisible(true);
wbview.getLoginDialog().setVisible(false);
} else {
wbview.getLoginDialog().loginFailed();
wbview.showError("Invalid Login!\r\nPlease contact database admin\r\nto create a new account.");
}
}
}
});
}
}.start();
}
/*** @return type of media seleted in AddDialog ***/
private QueryType addType() {
QueryType qt = null;
switch (wbview.getMediaDialog().getMediaIndex()) {
case 0:
qt = QueryType.ALBUMSEARCH;
break;
case 1:
qt = QueryType.MOVIESEARCH;
break;
case 2:
qt = QueryType.BOOKSEARCH;
break;
}
return qt;
}
/*** @return type of media selected in main search-form. ***/
private QueryType queryType() {
QueryType qt = null;
switch (wbview.getMediaIndex()) {
case 0:
qt = QueryType.ALBUMSEARCH;
break;
case 1:
qt = QueryType.MOVIESEARCH;
break;
//case 2:
// qt = QueryType.BOOKSEARCH;
// break;
case 2:
qt = QueryType.REVIEWSEARCH;
break;
}
return qt;
}
/*** listen to changes in the search-box, updates search. ***/
public void setQuerySource(JTextField textField) {
textField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
}
@Override
public void insertUpdate(DocumentEvent arg0) {
executeQuery(queryType(), "%" + wbview.getMediaQuery() + "%");
}
@Override
public void removeUpdate(DocumentEvent arg0) {
executeQuery(queryType(), "%" + wbview.getMediaQuery() + "%");
}
});
}
/*** the search button, using this will return only exact matches. ***/
public void setButtonSearch(JButton button) {
button.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
executeQuery(queryType(), wbview.getMediaQuery());
}
});
}
/*** Event triggered when a revied is added from AddReviewDialog ***/
public void setButtonAddReview(JButton button) {
button.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
ReviewMediaDialog reviewDialog = wbview.getReviewDialog();
review = new Review(reviewDialog.getReviewTitle(), reviewDialog.getReviewBody(), "", "", "");
executeQuery(QueryType.REVIEW, "" + reviewDialog.getPK());
wbview.getReviewDialog().setVisible(false);
}
});
}
/*** Triggered before showind the AddReviewDialog, ensures that not more or less than a single
* row is selected.
* @param button triggers the event.
*/
public void setButtonReview(JButton button) {
button.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
try {
if (wbview.getSelectedRowCount() == 1) {
wbview.getReviewDialog().setPK(wbview.getSelectedId());
wbview.invokeReviewMediaDialog();
} else {
throw new Exception("multiselect");
}
} catch (Exception e) {
e.printStackTrace();
if (e.getMessage().equals("multiselect")) {
wbview.showError("You have to select ONE media item!");
} else {
wbview.showError("You have to select a media item!");
}
}
}
});
}
/*** Button used to show the rating dialog, ensures that valid amount of rows are selected ***/
public void setButtonRate(JButton button) {
button.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
try {
System.out.println("Rate Button for Media_Id: "
+ wbview.getSelectedId());
if (wbview.getSelectedRowCount() == 1) {
wbview.invokeRateMediaDialog();
} else {
throw new Exception("multiselect");
}
} catch (Exception e) {
if (e.getMessage().equals("multiselect")) {
wbview.showError("You have to select ONE media item!");
} else {
wbview.showError("You have to select a media item!");
}
}
}
});
}
/*** Convert a list of values into an object.
*
* @param key determines the name of the class attribute.
* @param value determines the value of the class attribute.
*/
private void dataToAlbum(String key, String value) {
if (key.toString().equals("name"))
album.setName(value);
if (key.toString().equals("genre"))
album.setGenre(value);
if (key.toString().equals("year"))
album.setYear(value);
if (key.toString().equals("artist")) {
String[] artists = value.split(", ");
for (int i = 0; i < artists.length; i++)
album.AddArtist(artists[i]);
}
}
/*** Convert a list of values into an object.
*
* @param key determines the name of the class attribute.
* @param value determines the value of the class attribute.
*/
private void dataToMovie(String key, String value) {
if (key.toString().equals("title"))
movie.setTitle(value);
if (key.toString().equals("genre"))
movie.setGenre(value);
if (key.toString().equals("year"))
movie.setYear(value);
if (key.toString().equals("director")) {
String[] director = value.split(", ");
for (int i = 0; i < director.length; i++)
movie.addDirector(director[i]);
}
}
/*** Convert a list of values into an object.
*
* @param key determines the name of the class attribute.
* @param value determines the value of the class attribute.
*/
private void dataToBook(String key, String value) {
if (key.toString().equals("title"))
book.setTitle(value);
if (key.toString().equals("genre"))
book.setGenre(value);
if (key.toString().equals("year"))
book.setYear(value);
if (key.toString().equals("author")) {
String[] author = value.split(", ");
for (int i = 0; i < author.length; i++)
book.addAuthor(author[i]);
}
}
public void setSubmit(JButton button, final AddMediaDialog dialog) {
button.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
@SuppressWarnings("rawtypes")
Hashtable table = dialog.getValues();
dialog.setVisible(false);
album = new Album("", "", "", "");
movie = new Movie("", "", "", "", 0, "");
book = new Book("", "", 0);
@SuppressWarnings("rawtypes")
Enumeration e = table.keys();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
System.out.println(key + " : " + table.get(key));
switch (addType()) {
case ALBUMSEARCH:
dataToAlbum(key, table.get(key).toString());
break;
case MOVIESEARCH:
dataToMovie(key, table.get(key).toString());
break;
case BOOKSEARCH:
dataToBook(key, table.get(key).toString());
break;
default:
break;
}
}
executeQuery(QueryType.MEDIAADD, "");
}
});
}
/*** Submits a media rating ***/
public void setSubmitRate(JButton button, final RateMediaDialog dialog) {
button.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
rating = dialog.getValues();
media = wbview.getSelectedId();
dialog.setVisible(false);
executeQuery(QueryType.RATE, "");
}
});
}
/*** Show add media dialog ***/
public void setButtonAdd(JButton button) {
button.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
if (queryType() != QueryType.REVIEWSEARCH)
wbview.invokeAddMediaDialog(wbview.getMediaIndex());
else
wbview.invokeAddMediaDialog(0);
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
}
public enum QueryType {
BOOKSEARCH, ALBUMSEARCH, MOVIESEARCH, REVIEWSEARCH, MEDIAADD, RATE, LOGIN, REVIEW
}
/*** check a users password and set model password ***/
public void setLogin(JButton login, final LoginDialog loginDialog) {
login.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
model.setPass(loginDialog.getPass());
model.setUser(loginDialog.getUser());
executeQuery(QueryType.LOGIN, "");
}
});
}
/*** called from wbview on ComboChanged. ***/
public void comboMediaChanged() {
executeQuery(queryType(), "%" + wbview.getMediaQuery() + "%");
}
}
|
package ch.unizh.ini.caviar.eventprocessing.tracking;
//import ch.unizh.ini.caviar.aemonitor.AEConstants;
import ch.unizh.ini.caviar.chip.*;
import ch.unizh.ini.caviar.eventprocessing.EventFilter2D;
import ch.unizh.ini.caviar.event.*;
import ch.unizh.ini.caviar.event.EventPacket;
import ch.unizh.ini.caviar.graphics.*;
import java.awt.*;
//import ch.unizh.ini.caviar.util.PreferencesEditor;
import java.awt.geom.*;
import java.io.*;
import java.util.*;
import java.util.prefs.*;
import javax.media.opengl.GL;
import javax.media.opengl.GLAutoDrawable;
/**
*
* @author Philipp <hafliger@ifi.uio.no>
*/
public class ParticleTracker extends EventFilter2D implements FrameAnnotater, Observer{
private static Preferences prefs=Preferences.userNodeForPackage(ParticleTracker.class);
private java.util.List<Cluster> clusters=new LinkedList<Cluster>();
protected AEChip chip;
private AEChipRenderer renderer;
private int[][] lastCluster= new int[128][128];
private int[][] lastEvent= new int[128][128];
private int next_cluster_id=1;
protected Random random=new Random();
private PrintStream logStream=null;
//Variables that will be set by the tracker parameter pop-up window:
//private final int CLUSTER_UNSUPPORTED_LIFETIME=50000;
int surround=2;//neighbourhood that is searched for recent events that are considered to belong to the same cluster
int clusterUnsupportedLifetime= prefs.getInt("ParticleTracker.clusterUnsupportedLifetime",50000);
//private final int CLUSTER_MINLIFEFORCE_4_DISPLAY=10;
float clusterMinMass4Display= prefs.getFloat("ParticleTracker.clusterMinMass4Display",10);
boolean OnPolarityOnly=prefs.getBoolean("ParticleTracker.OnPolarityOnly",false);
float displayVelocityScaling=prefs.getFloat("ParticleTracker.DisplayVelocityScaling",1000.0f);
int logFrameLength=prefs.getInt("Particletracker.LogFrameLength",0);
int logFrameNumber=0;
/** Creates a new instance of ParticleTracker */
public ParticleTracker(AEChip chip) {
super(chip);
this.chip=chip;
renderer=(AEChipRenderer)chip.getRenderer();
chip.getRenderer().addAnnotator(this); // to draw the clusters
chip.getCanvas().addAnnotator(this);
chip.addObserver(this);
// prefs.addPreferenceChangeListener(this);
// Cluster newCluster=new Cluster(40,60,-1,-1);
// clusters.add(newCluster);
initFilter();
}
// All callback functions for the tracker parameter pop-up:
public void setDisplayVelocityScaling(float x){
this.displayVelocityScaling=x;
prefs.putFloat("ParticleTracker.displayVelocityScaling", displayVelocityScaling);
}
public final float getDisplayVelocityScaling(){
return(displayVelocityScaling);
}
public void setLogFrameLength(int x){
if(x>0){
openLog();
}else{
closeLog();
}
this.logFrameLength=x;
prefs.putInt("ParticleTracker.logFrameLength", logFrameLength);
}
public final int getLogFrameLength(){
return(logFrameLength);
}
public void setClusterUnsupportedLifetime(int x){
this.clusterUnsupportedLifetime=x;
prefs.putInt("ParticleTracker.clusterUnsupportedLifetime", clusterUnsupportedLifetime);
}
public final int getClusterUnsupportedLifetime(){
return(clusterUnsupportedLifetime);
}
public void setOnPolarityOnly(boolean b){
this.OnPolarityOnly=b;
prefs.putBoolean("ParticleTracker.OnPolarityOnly", OnPolarityOnly);
}
public final boolean getOnPolarityOnly(){
return(OnPolarityOnly);
}
public void setClusterMinMass4Display(float x){
this.clusterMinMass4Display=x;
prefs.putFloat("ParticleTracker.clusterMinMass4Display", clusterMinMass4Display);
}
public final float getClusterMinMass4Display(){
return(clusterMinMass4Display);
}
synchronized public void setFilterEnabled(boolean enabled) {
super.setFilterEnabled(enabled);
initFilter();
if (!enabled){
closeLog();
}
}
// all default values for the tracker parameter pop-up
private void initDefaults(){
initDefault("ParticleTracker.clusterUnsupportedLifetime","50000");
initDefault("ParticleTracker.ParticleTracker.clusterMinMass4Display","10");
initDefault("ParticleTracker.displayVelocityScaling","1000.0f");
initDefault("ParticleTracker.OnPolarityOnly","false");
initDefault("ParticleTracker.LogFrameRate","0");
// initDefault("ClassTracker.","");
}
private void initDefault(String key, String value){
if(prefs.get(key,null)==null) prefs.put(key,value);
}
private void closeLog(){
if(logStream!=null){
logStream.println("otherwise");
logStream.println("particles=[];");
//logStream.println("cla;");
//logStream.println("set(gca,'xlim',xlim,'ylim',ylim)");
logStream.println("end; %switch");
logStream.flush();
logStream.close();
logStream=null;
}
}
private void openLog(){
if(logStream==null){
try{
logStream=new PrintStream(new BufferedOutputStream(new FileOutputStream(new File("ParticleTrackerLog.m"))));
//logStream.println("function [particles]=ParticleTrackerLog(frameN,time_shift,xshift,yshift,xscaling,yscaling,xlim,ylim)");
logStream.println("function [particles]=ParticleTrackerLog(frameN)");
logStream.println("% lasttimestamp x y u v");
//logStream.println("switch (frameN+time_shift)");
logStream.println("switch (frameN)");
}catch(Exception e){
e.printStackTrace();
}
}
}
private void printClusterLog(PrintStream log, LinkedList<Cluster> cl, int frameNumber, int now){
ListIterator listScanner=cl.listIterator();
Cluster c=null;
int time_limit;
if(logStream==null) openLog();
time_limit=now-clusterUnsupportedLifetime;
logStream.println(String.format("case %d", frameNumber));
logStream.println(String.format("particles=["));
while (listScanner.hasNext()){
c=(Cluster)listScanner.next();
if ((c.last < time_limit)||(c.last > now)){ //check if cluster is dead or if time has moved backwards
listScanner.remove();
}else{
if ((c.mass*weighEvent((float)c.last,(float)now))>clusterMinMass4Display){
logStream.println(String.format("%d %e %e %e %e", c.last,c.location.x,c.location.y,c.velocity.x,c.velocity.y));
}
}
}
logStream.println("];");
//logStream.println("if (~isempty(particles))");
//logStream.println("plot(xscaling*particles(:,2)-xshift,yscaling*particles(:,3)-yshift,'o')");
//logStream.println("set(gca,'xlim',xlim,'ylim',ylim)");
//logStream.println("end; %if");
}
public float weighEvent(float t_ev, float now){
float result;
result=(float)Math.exp(-(now-t_ev)/(float)clusterUnsupportedLifetime);
//result=1f-(now-t_ev)/(float)clusterUnsupportedLifetime;
return(result);
}
// the method that actually does the tracking
synchronized private void track(EventPacket<BasicEvent> ae){
int n=ae.getSize();
//int surround=2;
if(n==0) return;
int l,k,i,ir,il,j,jr,jl;
//int most_recent;
//LinkedList<Cluster> pruneList=new LinkedList<Cluster>();
int[] cluster_ids=new int[9];
Cluster thisCluster=null;
int[] merged_ids=null;
float thisClusterWeight;
float thatClusterWeight;
ListIterator listScanner;
Cluster c=null;
//int maxNumClusters=getMaxNumClusters();
// for each event, see which cluster it is closest to and add it to this cluster.
// if its too far from any cluster, make a new cluster if we can
// for(int i=0;i<n;i++){
for(BasicEvent ev:ae){
// check for if off-polarity is to be ignored
if( !( OnPolarityOnly && (ev instanceof TypedEvent)&&(((TypedEvent)ev).type==0) ) ){
if(logFrameLength>0){
if ((ev.timestamp/logFrameLength)>logFrameNumber){
logFrameNumber=ev.timestamp/logFrameLength;
printClusterLog(logStream, (LinkedList<Cluster>)clusters, logFrameNumber, ev.timestamp);
}
}
// check if any neigbours are assigned to a cluster already
il=-surround;
if ((ev.x+il)<0) il=il-(ev.x+il);
ir=surround;
if ((ev.x+ir)>127) ir=ir-(ev.x+ir-127);
jl=-surround;
if ((ev.y+jl)<0) jl=jl-(ev.y+jl);
jr=surround;
if ((ev.y+jr)>127) jr=jr-(ev.y+jr-127);
//if (ev.x==0){il=0;}else{il=-1;}
//if (ev.x==127){ir=0;}else{ir=1;}
//if (ev.y==0){jl=0;}else{jl=-1;}
//if (ev.y==127){jr=0;}else{jr=1;}
//most_recent=-1;
k=0;
for (i=il;i<=ir;i++){
for(j=jl;j<=jr;j++){
if (lastEvent[ev.x+i][ev.y+j] != -1){
//if (lastEvent[ev.x+i][ev.y+j]>most_recent){
//most_recent=lastEvent[ev.x+i][ev.y+j];
//lastCluster[ev.x][ev.y]=lastCluster[ev.x+i][ev.y+j];
if (lastEvent[ev.x+i][ev.y+j] >= ev.timestamp-clusterUnsupportedLifetime){
lastCluster[ev.x][ev.y]=lastCluster[ev.x+i][ev.y+j];
cluster_ids[k]=lastCluster[ev.x+i][ev.y+j]; // an existing cluster id at or around the event
k++;
for (l=0;l<(k-1);l++){ // checking if its a doublicate
if (cluster_ids[k-1]==cluster_ids[l]){
k
break;
}
}
}
}
}
}
lastEvent[ev.x][ev.y]=ev.timestamp;
if (k==0){// new cluster
//if (next_cluster_id<200){
lastCluster[ev.x][ev.y]=next_cluster_id;
thisCluster=new Cluster(ev.x,ev.y,ev.timestamp);
clusters.add(thisCluster);
}else{// existing cluster: new event of one or several existing cluster
listScanner=clusters.listIterator();
while (listScanner.hasNext()){ // add new event to cluster
c=(Cluster)listScanner.next();
if ((c.last < ev.timestamp- clusterUnsupportedLifetime)||(c.last > ev.timestamp)){ //check if cluster is dead or if time has moved backwards
listScanner.remove();
}else{ //if cluster is still alive
for (l=0;l<c.id.length;l++){
if (c.id[l]==lastCluster[ev.x][ev.y]){// check if this event belongs to this cluster
c.addEvent(ev);
thisCluster=c;
//break;
}
}
}
}
if (k>1){ //merge clusters if there has been more alive clusters in neighbourhood
mergeClusters(thisCluster, cluster_ids, k, ev.timestamp);
}
//clusters.removeAll(pruneList);
//pruneList.clear();
}
}
}
}
public int mergeClusters(Cluster thisCluster, int[] cluster_ids, int n_ids, int now){
ListIterator listScanner;
Cluster c=null;
int i,j,l;
int c_count=1;
int[] merged_ids;
float thisClusterWeight,thatClusterWeight;
if (thisCluster!=null){
listScanner=clusters.listIterator();
while (listScanner.hasNext()){ // look for the clusters to be merged
c=(Cluster)listScanner.next();
if (c!=thisCluster){
for (i=0;i<c.id.length;i++){
for (j=0;j<n_ids;j++){
if (c.id[i]== cluster_ids[j]){
c_count++;
merged_ids=new int[c.id.length + thisCluster.id.length];
for (l=0;l<thisCluster.id.length;l++){
merged_ids[l]=thisCluster.id[l];
}
for (l=0;l<(c.id.length);l++){
merged_ids[l+thisCluster.id.length]= c.id[l];
}
//for (l=0;l<(c.id.length+ thisCluster.id.length);l++){
//System.out.print(" "+merged_ids[l]);
//System.out.println();
thisCluster.id=merged_ids;
c.mass= c.mass*weighEvent((float)c.last,(float)now);
c.lifeForce= c.lifeForce*(float)Math.exp(-(float)(now- c.last)/clusterUnsupportedLifetime);
thisClusterWeight=thisCluster.mass/ (thisCluster.mass + c.mass);
thatClusterWeight=1-thisClusterWeight;
thisCluster.location.x=thisClusterWeight*thisCluster.location.x+thatClusterWeight*c.location.x;
thisCluster.location.y=thisClusterWeight*thisCluster.location.y+thatClusterWeight*c.location.y;
thisCluster.velocity.x=thisClusterWeight*thisCluster.velocity.x+thatClusterWeight*c.velocity.x;
thisCluster.velocity.y=thisClusterWeight*thisCluster.velocity.y+thatClusterWeight*c.velocity.y;
if (thisCluster.mass<c.mass){
thisCluster.color=c.color;
}
thisCluster.mass=thisCluster.mass + c.mass;
thisCluster.lifeForce=thisCluster.lifeForce + c.lifeForce;
j=n_ids;
i=c.id.length;
listScanner.remove();
}
}
}
}
}
}else{
log.warning("null thisCluster in ParticleTracker.mergeClusters");
}
return(c_count);
}
public class DiffusedCluster{
int t;
Point2D.Float location = new Point2D.Float();
int n=0;
float mass=0;
public DiffusedCluster(){
}
public DiffusedCluster(int x, int y, int ti){
t=ti;
location.x=x;
location.y=y;
n=0;
mass=0;
}
}
public DiffusedCluster diffuseCluster(int x, int y, int id, int time_limit,int lowest_id, DiffusedCluster c){
int i,j,t,most_recent;
float new_event_weight;
//int surround=2;
if ((x>=0)&&(x<128)&&(y>=0)&&(y<128)&&(lastCluster[x][y]<lowest_id)&&(lastEvent[x][y]>=time_limit)){
if (c == null){
c = new DiffusedCluster(0,0,lastEvent[x][y]);
}
lastCluster[x][y]=id;
c.n++;
//new_event_weight = (float)Math.exp( ((float)(lastEvent[x][y]-time_limit)) / (float)clusterUnsupportedLifetime - 1f);
new_event_weight = weighEvent((float)lastEvent[x][y],(float)(time_limit+clusterUnsupportedLifetime));
c.location.x= (c.location.x*c.mass + x*new_event_weight)/(c.mass + new_event_weight);
c.location.y= (c.location.y*c.mass + y*new_event_weight)/(c.mass + new_event_weight);
c.mass= c.mass + new_event_weight;
if (c.t < lastEvent[x][y]) c.t= lastEvent[x][y];
for (i=-surround;i<=surround;i++){
for(j=-surround;j<=surround;j++){
c=diffuseCluster(x+i,y+j,id,time_limit,lowest_id,c);
}
}
}
return(c);
}
public int splitClusters(){
int split_count=0;
float max_new_mass=0f;
int local_split_count=0;
ListIterator clusterScanner,old_new_id_scanner;
Cluster c,new_c;
int now=-1;
int new_clusters_from;
DiffusedCluster dc=null;
int x,y,time_limit,i/*,new_id*/,old_id;
float first_x=0;
float first_y=0;
//int[] old_cluster_id = new int[1];
int[] old_ids;
//int[] new_ids;
class OldNewId{
int o;
int n;
DiffusedCluster c; //last event timestamp in this cluster, estimated location and mass
}
java.util.List<OldNewId> old_new_id_list= new java.util.LinkedList<OldNewId>();
OldNewId old_new_id;
int this_pixel_old_id;
boolean position_correction_necessary=false;
float old_mass;
clusterScanner=clusters.listIterator();
while (clusterScanner.hasNext()){ // check for the most recent event timestamp
c=(Cluster)clusterScanner.next();
if (c.last> now) now=c.last;
}
time_limit=now-clusterUnsupportedLifetime;
if (time_limit<0) time_limit=0;
new_clusters_from=next_cluster_id;
// the next foor loop builds up a list of clusters based on all connected alive events in the pixels
// and assignes new cluster ids in the lastCluster array. This new id, the old id and the cluster are stored ina temporary list
for (x=0;x<128;x++){
for (y=0;y<128;y++){
this_pixel_old_id=lastCluster[x][y];
try{
dc=diffuseCluster(x,y,next_cluster_id,time_limit,new_clusters_from,null);
}catch(java.lang.StackOverflowError e){
log.warning(e.getMessage());
log.warning("Probably a stack overflow: resetting ParticleTracker");
dc=null;
initFilter();
}
if (dc != null){
//dc.mass = dc.mass * (float)Math.exp((float)(now-dc.t)/clusterUnsupportedLifetime);
// the above is not necessary since already right from the difuseCluster function
old_new_id= new OldNewId();
old_new_id.o = this_pixel_old_id;
old_new_id.n = next_cluster_id;
old_new_id.c = dc;
old_new_id_list.add(old_new_id);
next_cluster_id++;
}else{
//lastCluster[x][y]=-1;
}
}
}
clusterScanner=clusters.listIterator();
while (clusterScanner.hasNext()){ // get all old clusters, assign new ids and split if necessary
c=(Cluster)clusterScanner.next();
if ((c.last < time_limit)||(c.last > now)){ //check if cluster is dead or if time has moved backwards
clusterScanner.remove();
}else{
old_mass=c.mass;
old_ids=c.id;
max_new_mass=0;
local_split_count=0;
//new_id=new_clusters_from;
first_x=-1; // dummy initialization : this variable should always be initialized in if (local_split_count >0){}else{...}
first_y=-1;
old_new_id_scanner=old_new_id_list.listIterator();
while (old_new_id_scanner.hasNext()){ // checking for all new clusters if they have been part of this old cluster
old_new_id= (OldNewId)old_new_id_scanner.next();
for (i=0;i<old_ids.length;i++){
if (old_ids[i]==old_new_id.o){
//position_correction_necessary=
//(old_mass > 1000*old_new_id.c.mass);
// //((Math.abs(old_new_id.c.location.x-c.location.x) > 10)||
// //(Math.abs(old_new_id.c.location.y-c.location.y)>10 ));
if(local_split_count>0){// cluster has been split
new_c = new Cluster(old_new_id.n, c.location.x, c.location.y, c.velocity.x, c.velocity.y, old_new_id.c.t);
if (old_new_id.c.mass>max_new_mass){
max_new_mass=old_new_id.c.mass;
c.mass=0f;
new_c.mass=old_mass;
}else{
new_c.mass = 0f;
}
//new_c.mass = old_new_id.c.mass; // not so good this, since various events in the same pixel can have contributed
new_c.color=c.color;
clusterScanner.add(new_c);
}else{ // found first old cluster and assigning the new id
max_new_mass=old_new_id.c.mass;
c.id=new int[1];
c.id[0]= old_new_id.n;
c.last = old_new_id.c.t;
new_c = c;
}
//if (position_correction_necessary){
// //System.out.println("correcting position"
// // +" "+(old_new_id.c.location.x-new_c.location.x)
// // +" "+(old_new_id.c.location.y-new_c.location.y)
// // +" "+(old_mass)
// // +" "+(old_new_id.c.mass)
//new_c.location.x= old_new_id.c.location.x;
//new_c.location.y= old_new_id.c.location.y;
//new_c.mass=0;
local_split_count++;
}
}
}
if (local_split_count<1){
log.warning("could not associate an existing cluster with one of the still valid diffused clusters");
clusterScanner.remove();
}
split_count+=(local_split_count-1);
}
}
return(split_count);
}
public class Cluster{
public Point2D.Float location=new Point2D.Float(); // location in chip pixels
public Point2D.Float lastPixel=new Point2D.Float(); // location of last active pixel belonging to cluster
/** velocity of cluster in pixels/tick, where tick is timestamp tick (usually microseconds) */
public Point2D.Float velocity=new Point2D.Float(); // velocity in chip pixels/sec
//protected float distanceToLastEvent=Float.POSITIVE_INFINITY;
public int[] id=null;
int last=-1;
public float mass=(float)0;
public float lifeForce=0f;
public Color color=null;
public boolean em=false; //emphazise when drawing;
// public Cluster(){
// location.x=(float)20.5;
// location.y=(float)10.9;
// id=-1;
public Cluster(float x, float y, int first_event_time){
location.x=x;
location.y=y;
lastPixel.x=x;
lastPixel.y=y;
id=new int[1];
id[0]=next_cluster_id++;
last=first_event_time;
velocity.x=(float)0.0;
velocity.y=(float)0.0;
lifeForce=1;
mass=1;
//float hue=random.nextFloat();
color=Color.getHSBColor(random.nextFloat(),1f,1f);
}
public Cluster(int identity, float x, float y, float vx, float vy, int first_event_time){
location.x=x;
location.y=y;
id=new int[1];
id[0]=identity;
last=first_event_time;
velocity.x=vx;
velocity.y=vy;
lifeForce=1;
mass=1;
//float hue=random.nextFloat();
color=Color.getHSBColor(random.nextFloat(),1f,1f);
}
public void addEvent(BasicEvent ev){
int interval;
interval=ev.timestamp - this.last;
if (interval==0) interval=1;
this.last= ev.timestamp;
this.lastPixel.x= ev.x;
this.lastPixel.y= ev.y;
this.lifeForce= this.lifeForce * (float)Math.exp(-(float)interval/clusterUnsupportedLifetime) +1;
//this.mass= this.mass * (float)Math.exp(-(float)interval/clusterUnsupportedLifetime) +1;
this.mass= this.mass * weighEvent(this.last-interval,this.last)+1;
//float event_weight=(float)interval/clusterUnsupportedLifetime;
//if (event_weight>1) event_weight=1;
//float event_weight=(float)1/(this.mass);
float predicted_x=this.location.x + this.velocity.x * (interval);
float predicted_y=this.location.y + this.velocity.y * (interval);
//float new_x=(1-event_weight)*predicted_x + event_weight*ev.x ;
//float new_x=(1-1/(this.mass))*predicted_x + 1/(this.mass)*ev.x ;
float new_x=(1-1/(this.mass))*this.location.x + 1/(this.mass)*ev.x ;
//float new_y=(1-event_weight)*predicted_y + event_weight*ev.y ;
//float new_y=(1-1/(this.mass))*predicted_y + 1/(this.mass)*ev.y ;
float new_y=(1-1/(this.mass))*this.location.y + 1/(this.mass)*ev.y ;
//this.velocity.x= (1-event_weight)*this.velocity.x + event_weight*(new_x - this.location.x)/interval;
this.velocity.x= (1-1/(this.mass))*this.velocity.x + 1/(this.mass)*(new_x - this.location.x)/(float)interval;
//this.velocity.x= (new_x - this.location.x)/interval;
//this.velocity.y= (1-event_weight)*this.velocity.y + event_weight*(new_y - this.location.y)/interval;
this.velocity.y= (1-1/(this.mass))*this.velocity.y + 1/(this.mass)*(new_y - this.location.y)/(float)interval;
//this.velocity.y= (new_y - this.location.y)/interval;
this.location.x= new_x;
this.location.y= new_y;
}
public Point2D.Float getLocation() {
return location;
}
public void setLocation(Point2D.Float l){
this.location = l;
}
}
public java.util.List<ParticleTracker.Cluster> getClusters() {
return this.clusters;
}
// private LinkedList<ParticleTracker.Cluster> getPruneList(){
// return this.pruneList;
private final void drawCluster(final Cluster c, float[][][] fr){
int x=(int)c.getLocation().x;
int y=(int)c.getLocation().y;
int i;
if(y<0 || y>fr.length-1 || x<0 || x>fr[0].length-1) return;
// for (x=20;x<(fr[0].length-20);x++){
// for(y=20;y<(fr[1].length-20);y++){
fr[x][y][0]=(float)0.2;
fr[x][y][1]=(float)1.0;
fr[x][y][2]=(float)1.0;
}
public void initFilter() {
initDefaults();
resetFilter();
// defaultClusterRadius=(int)Math.max(chip.getSizeX(),chip.getSizeY())*getClusterSize();
if ((logFrameLength>0)&&(logStream==null)){
openLog();
}
}
synchronized public void resetFilter() {
int i,j;
clusters.clear();
next_cluster_id=1;
for (i=0;i<128;i++){
for (j=0;j<128;j++){
lastCluster[i][j]=-1;
lastEvent[i][j]=-1;
}
}
}
public Object getFilterState() {
return null;
}
private boolean isGeneratingFilter() {
return false;
}
public EventPacket filterPacket(EventPacket in) {
if(in==null) return null;
if(!filterEnabled) return in;
if(enclosedFilter!=null) in=enclosedFilter.filterPacket(in);
track(in);
return in;
}
public void update(Observable o, Object arg) {
initFilter();
}
public void annotate(Graphics2D g) {
}
protected void drawBox(GL gl, int x, int y, int sx, int sy){
gl.glBegin(GL.GL_LINE_LOOP);
{
gl.glVertex2i(x-sx,y-sy);
gl.glVertex2i(x+sx,y-sy);
gl.glVertex2i(x+sx,y+sy);
gl.glVertex2i(x-sx,y+sy);
}
gl.glEnd();
}
synchronized public void annotate(GLAutoDrawable drawable) {
final float BOX_LINE_WIDTH=5f; // in pixels
final float PATH_LINE_WIDTH=3f;
float[] rgb;
int sx,sy;
if(!isFilterEnabled()) return;
GL gl=drawable.getGL(); // when we get this we are already set up with scale 1=1 pixel, at LL corner
if(gl==null){
log.warning("null GL in ClassTracker.annotate");
return;
}
gl.glPushMatrix();
splitClusters();
for(Cluster c:clusters){
rgb=c.color.getRGBComponents(null);
if (c.mass>clusterMinMass4Display){
sx=4;
sy=4;
if (c.em){
gl.glLineWidth((float)2);
}else{
gl.glLineWidth((float)1);
}
gl.glColor3fv(rgb,0);
//gl.glColor3f(.5f,.7f,.1f);
}else{
sx=(int)(4.0*c.mass/clusterMinMass4Display);
sy=(int)(4.0*c.mass/clusterMinMass4Display);
gl.glLineWidth((float).2);
//gl.glColor3fv(rgb,0);
gl.glColor3f(.1f,.2f,.1f);
}
drawBox(gl,(int)c.location.x,(int)c.location.y,sx,sy);
gl.glBegin(GL.GL_LINES);
{
gl.glVertex2i((int)c.location.x,(int)c.location.y);
gl.glVertex2f((int)(c.location.x+c.velocity.x*displayVelocityScaling),(int)(c.location.y+c.velocity.y*displayVelocityScaling));
}
gl.glEnd();
}
gl.glPopMatrix();
}
/** annotate the rendered retina frame to show locations of clusters */
synchronized public void annotate(float[][][] frame) {
if(!isFilterEnabled()) return;
// disable for now TODO
if(chip.getCanvas().isOpenGLEnabled()) return; // done by open gl annotator
for(Cluster c:clusters){
// if(c.isVisible()){
drawCluster(c, frame);
}
}
}
|
// checkstyle: Checks Java source code for adherence to a set of rules.
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.puppycrawl.tools.checkstyle.api;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.converters.AbstractArrayConverter;
import org.apache.commons.beanutils.converters.BooleanArrayConverter;
import org.apache.commons.beanutils.converters.BooleanConverter;
import org.apache.commons.beanutils.converters.ByteArrayConverter;
import org.apache.commons.beanutils.converters.ByteConverter;
import org.apache.commons.beanutils.converters.CharacterArrayConverter;
import org.apache.commons.beanutils.converters.CharacterConverter;
import org.apache.commons.beanutils.converters.DoubleArrayConverter;
import org.apache.commons.beanutils.converters.DoubleConverter;
import org.apache.commons.beanutils.converters.FloatArrayConverter;
import org.apache.commons.beanutils.converters.FloatConverter;
import org.apache.commons.beanutils.converters.IntegerArrayConverter;
import org.apache.commons.beanutils.converters.IntegerConverter;
import org.apache.commons.beanutils.converters.LongArrayConverter;
import org.apache.commons.beanutils.converters.LongConverter;
import org.apache.commons.beanutils.converters.ShortArrayConverter;
import org.apache.commons.beanutils.converters.ShortConverter;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.beans.PropertyDescriptor;
/**
* A Java Bean that implements the component lifecycle interfaces by
* calling the bean's setters for all configration attributes.
* @author lkuehne
*/
public class AutomaticBean implements Configurable, Contextualizable
{
static {
initConverters();
}
/**
* Setup the jakarta-commons-beanutils type converters so they throw
* a ConversionException instead of using the default value.
*/
private static void initConverters()
{
// TODO: is there a smarter way to tell beanutils not to use defaults?
// If any runtime environment like ANT or an IDE would use beanutils
// with different converters we would really be stuck here.
// Having to configure a static utility class in this way is really
// strange, it seems like a design problem in BeanUtils
boolean[] booleanArray = new boolean[0];
byte[] byteArray = new byte[0];
char[] charArray = new char[0];
double[] doubleArray = new double[0];
float[] floatArray = new float[0];
int[] intArray = new int[0];
long[] longArray = new long[0];
short[] shortArray = new short[0];
ConvertUtils.register(new BooleanConverter(), Boolean.TYPE);
ConvertUtils.register(new BooleanConverter(), Boolean.class);
ConvertUtils.register(
new BooleanArrayConverter(), booleanArray.getClass());
ConvertUtils.register(new ByteConverter(), Byte.TYPE);
ConvertUtils.register(new ByteConverter(), Byte.class);
ConvertUtils.register(
new ByteArrayConverter(byteArray), byteArray.getClass());
ConvertUtils.register(new CharacterConverter(), Character.TYPE);
ConvertUtils.register(new CharacterConverter(), Character.class);
ConvertUtils.register(
new CharacterArrayConverter(), charArray.getClass());
ConvertUtils.register(new DoubleConverter(), Double.TYPE);
ConvertUtils.register(new DoubleConverter(), Double.class);
ConvertUtils.register(
new DoubleArrayConverter(doubleArray), doubleArray.getClass());
ConvertUtils.register(new FloatConverter(), Float.TYPE);
ConvertUtils.register(new FloatConverter(), Float.class);
ConvertUtils.register(new FloatArrayConverter(), floatArray.getClass());
ConvertUtils.register(new IntegerConverter(), Integer.TYPE);
ConvertUtils.register(new IntegerConverter(), Integer.class);
ConvertUtils.register(new IntegerArrayConverter(), intArray.getClass());
ConvertUtils.register(new LongConverter(), Long.TYPE);
ConvertUtils.register(new LongConverter(), Long.class);
ConvertUtils.register(new LongArrayConverter(), longArray.getClass());
ConvertUtils.register(new ShortConverter(), Short.TYPE);
ConvertUtils.register(new ShortConverter(), Short.class);
ConvertUtils.register(new ShortArrayConverter(), shortArray.getClass());
// TODO: investigate:
// StringArrayConverter doesn't properly convert an array of tokens with
// elements containing an underscore, "_".
// Hacked a replacement class :(
// ConvertUtils.register(new StringArrayConverter(),
// String[].class);
ConvertUtils.register(new StrArrayConverter(), String[].class);
ConvertUtils.register(new IntegerArrayConverter(), Integer[].class);
// BigDecimal, BigInteger, Class, Date, String, Time, TimeStamp
// do not use defaults in the default configuration of ConvertUtils
}
/** the configuration of this bean */
private Configuration mConfiguration;
/**
* Implements the Configurable interface using bean introspection.
*
* Subclasses are allowed to add behaviour. After the bean
* based setup has completed first the method
* {@link #finishLocalSetup finishLocalSetup}
* is called to allow completion of the bean's local setup,
* after that the method {@link #setupChild setupChild}
* is called for each {@link Configuration#getChildren child Configuration}
* of <code>aConfiguration</code>.
*
* @see Configurable
*/
public final void configure(Configuration aConfiguration)
throws CheckstyleException
{
mConfiguration = aConfiguration;
// TODO: debug log messages
final String[] attributes = aConfiguration.getAttributeNames();
for (int i = 0; i < attributes.length; i++) {
final String key = attributes[i];
final String value = aConfiguration.getAttribute(key);
try {
// BeanUtils.copyProperties silently ignores missing setters
// for key, so we have to go through great lengths here to
// figure out if the bean property really exists.
PropertyDescriptor pd =
PropertyUtils.getPropertyDescriptor(this, key);
if (pd == null || pd.getWriteMethod() == null) {
throw new CheckstyleException(
"Property '" + key + "' in module "
+ aConfiguration.getName()
+ " does not exist, please check the documentation");
}
// finally we can set the bean property
BeanUtils.copyProperty(this, key, value);
}
catch (InvocationTargetException e) {
throw new CheckstyleException(
"Cannot set property '" + key + "' in module "
+ aConfiguration.getName() + " to '" + value
+ "': " + e.getTargetException().getMessage());
}
catch (IllegalAccessException e) {
throw new CheckstyleException(
"cannot access " + key + " in "
+ this.getClass().getName());
}
catch (NoSuchMethodException e) {
throw new CheckstyleException(
"cannot access " + key + " in "
+ this.getClass().getName());
}
catch (IllegalArgumentException e) {
throw new CheckstyleException(
"illegal value '" + value + "' for property '" + key
+ "' of module " + aConfiguration.getName());
}
catch (ConversionException e) {
throw new CheckstyleException(
"illegal value '" + value + "' for property '" + key
+ "' of module " + aConfiguration.getName());
}
}
finishLocalSetup();
Configuration[] childConfigs = aConfiguration.getChildren();
for (int i = 0; i < childConfigs.length; i++) {
final Configuration childConfig = childConfigs[i];
setupChild(childConfig);
}
}
/**
* Implements the Contextualizable interface using bean introspection.
* @see Contextualizable
*/
public final void contextualize(Context aContext)
throws CheckstyleException
{
// TODO: debug log messages
final String[] attributes = aContext.getAttributeNames();
for (int i = 0; i < attributes.length; i++) {
final String key = attributes[i];
final Object value = aContext.get(key);
try {
BeanUtils.copyProperty(this, key, value);
}
catch (InvocationTargetException e) {
// TODO: log.debug("The bean " + this.getClass()
// + " is not interested in " + value)
throw new CheckstyleException("cannot set property "
+ key + " to value " + value + " in bean "
+ this.getClass().getName());
}
catch (IllegalAccessException e) {
throw new CheckstyleException(
"cannot access " + key + " in "
+ this.getClass().getName());
}
catch (IllegalArgumentException e) {
throw new CheckstyleException(
"illegal value '" + value + "' for property '" + key
+ "' of bean " + this.getClass().getName());
}
catch (ConversionException e) {
throw new CheckstyleException(
"illegal value '" + value + "' for property '" + key
+ "' of bean " + this.getClass().getName());
}
}
}
/**
* Returns the configuration that was used to configure this component.
* @return the configuration that was used to configure this component.
*/
protected final Configuration getConfiguration()
{
return mConfiguration;
}
/**
* Provides a hook to finish the part of this compoent's setup that
* was not handled by the bean introspection.
* <p>
* The default implementation does nothing.
* </p>
* @throws CheckstyleException if there is a configuration error.
*/
protected void finishLocalSetup() throws CheckstyleException
{
}
/**
* Called by configure() for every child of this component's Configuration.
* <p>
* The default implementation does nothing.
* </p>
* @param aChildConf a child of this component's Configuration
* @throws CheckstyleException if there is a configuration error.
* @see Configuration#getChildren
*/
protected void setupChild(Configuration aChildConf)
throws CheckstyleException
{
}
}
class StrArrayConverter extends AbstractArrayConverter
{
/**
* <p>Model object for type comparisons.</p>
*/
private static String[] sModel = new String[0];
/**
* Creates a new StrArrayConverter object.
*/
public StrArrayConverter()
{
this.defaultValue = null;
this.useDefault = false;
}
/**
* Create a onverter that will return the specified default value
* if a conversion error occurs.
*
* @param aDefaultValue The default value to be returned
*/
public StrArrayConverter(Object aDefaultValue)
{
this.defaultValue = aDefaultValue;
this.useDefault = true;
}
/**
* Convert the specified input object into an output object of the
* specified type.
*
* @param aType Data type to which this value should be converted
* @param aValue The input value to be converted
*
* @return the converted object
*
* @throws ConversionException if conversion cannot be performed
* successfully
*/
public Object convert(Class aType, Object aValue)
throws ConversionException
{
// Deal with a null value
if (aValue == null) {
if (useDefault) {
return (defaultValue);
}
else {
throw new ConversionException("No value specified");
}
}
// Deal with the no-conversion-needed case
if (sModel.getClass() == aValue.getClass()) {
return (aValue);
}
// Parse the input value as a String into elements
// and convert to the appropriate type
try {
final List list = parseElements(aValue.toString());
final String[] results = new String[list.size()];
for (int i = 0; i < results.length; i++) {
results[i] = (String) list.get(i);
}
return (results);
}
catch (Exception e) {
if (useDefault) {
return (defaultValue);
}
else {
throw new ConversionException(aValue.toString(), e);
}
}
}
/**
* <p>Parse an incoming String of the form similar to an array initializer
* in the Java language into a <code>List</code> individual Strings
* for each element, according to the following rules.</p>
* <ul>
* <li>The string must have matching '{' and '}' delimiters around
* a comma-delimited list of values.</li>
* <li>Whitespace before and after each element is stripped.
* <li>If an element is itself delimited by matching single or double
* quotes, the usual rules for interpreting a quoted String apply.</li>
* </ul>
*
* @param aValue String value to be parsed
* @return the list of Strings parsed from the array
* @throws NullPointerException if <code>svalue</code>
* is <code>null</code>
*/
protected List parseElements(String aValue)
throws NullPointerException
{
// Validate the passed argument
if (aValue == null) {
throw new NullPointerException();
}
// Trim any matching '{' and '}' delimiters
aValue = aValue.trim();
if (aValue.startsWith("{") && aValue.endsWith("}")) {
aValue = aValue.substring(1, aValue.length() - 1);
}
final StringTokenizer st = new StringTokenizer(aValue, ",");
final List retVal = new ArrayList();
while (st.hasMoreTokens()) {
final String token = st.nextToken();
retVal.add(token.trim());
}
return retVal;
}
}
|
package edu.psu.rcy5017.publicspeakingassistant;
import edu.psu.rcy501.publicspeakingassistant.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Window;
public class SplashScreenActivity extends Activity {
private static final String TAG = "SplashScreenActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Remove title bar.
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splash);
Log.d(TAG, "Splash acticity started");
final int SPLASH_TIME_OUT = 3000;
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
@Override
public void run() {
// This method will be executed once the timer is over
// Start app main activity
Intent i = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(i);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
}
}
|
package eu.bryants.anthony.plinth.compiler.passes.llvm;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import nativelib.c.C;
import nativelib.llvm.LLVM;
import nativelib.llvm.LLVM.LLVMBasicBlockRef;
import nativelib.llvm.LLVM.LLVMBuilderRef;
import nativelib.llvm.LLVM.LLVMContextRef;
import nativelib.llvm.LLVM.LLVMModuleRef;
import nativelib.llvm.LLVM.LLVMTypeRef;
import nativelib.llvm.LLVM.LLVMValueRef;
import eu.bryants.anthony.plinth.ast.ClassDefinition;
import eu.bryants.anthony.plinth.ast.CompoundDefinition;
import eu.bryants.anthony.plinth.ast.InterfaceDefinition;
import eu.bryants.anthony.plinth.ast.TypeDefinition;
import eu.bryants.anthony.plinth.ast.expression.ArithmeticExpression;
import eu.bryants.anthony.plinth.ast.expression.ArithmeticExpression.ArithmeticOperator;
import eu.bryants.anthony.plinth.ast.expression.ArrayAccessExpression;
import eu.bryants.anthony.plinth.ast.expression.ArrayCreationExpression;
import eu.bryants.anthony.plinth.ast.expression.BitwiseNotExpression;
import eu.bryants.anthony.plinth.ast.expression.BooleanLiteralExpression;
import eu.bryants.anthony.plinth.ast.expression.BooleanNotExpression;
import eu.bryants.anthony.plinth.ast.expression.BracketedExpression;
import eu.bryants.anthony.plinth.ast.expression.CastExpression;
import eu.bryants.anthony.plinth.ast.expression.ClassCreationExpression;
import eu.bryants.anthony.plinth.ast.expression.EqualityExpression;
import eu.bryants.anthony.plinth.ast.expression.EqualityExpression.EqualityOperator;
import eu.bryants.anthony.plinth.ast.expression.Expression;
import eu.bryants.anthony.plinth.ast.expression.FieldAccessExpression;
import eu.bryants.anthony.plinth.ast.expression.FloatingLiteralExpression;
import eu.bryants.anthony.plinth.ast.expression.FunctionCallExpression;
import eu.bryants.anthony.plinth.ast.expression.InlineIfExpression;
import eu.bryants.anthony.plinth.ast.expression.IntegerLiteralExpression;
import eu.bryants.anthony.plinth.ast.expression.LogicalExpression;
import eu.bryants.anthony.plinth.ast.expression.LogicalExpression.LogicalOperator;
import eu.bryants.anthony.plinth.ast.expression.MinusExpression;
import eu.bryants.anthony.plinth.ast.expression.NullCoalescingExpression;
import eu.bryants.anthony.plinth.ast.expression.NullLiteralExpression;
import eu.bryants.anthony.plinth.ast.expression.ObjectCreationExpression;
import eu.bryants.anthony.plinth.ast.expression.RelationalExpression;
import eu.bryants.anthony.plinth.ast.expression.RelationalExpression.RelationalOperator;
import eu.bryants.anthony.plinth.ast.expression.ShiftExpression;
import eu.bryants.anthony.plinth.ast.expression.StringLiteralExpression;
import eu.bryants.anthony.plinth.ast.expression.ThisExpression;
import eu.bryants.anthony.plinth.ast.expression.TupleExpression;
import eu.bryants.anthony.plinth.ast.expression.TupleIndexExpression;
import eu.bryants.anthony.plinth.ast.expression.VariableExpression;
import eu.bryants.anthony.plinth.ast.member.ArrayLengthMember;
import eu.bryants.anthony.plinth.ast.member.BuiltinMethod;
import eu.bryants.anthony.plinth.ast.member.Constructor;
import eu.bryants.anthony.plinth.ast.member.Field;
import eu.bryants.anthony.plinth.ast.member.Initialiser;
import eu.bryants.anthony.plinth.ast.member.Member;
import eu.bryants.anthony.plinth.ast.member.Method;
import eu.bryants.anthony.plinth.ast.metadata.FieldInitialiser;
import eu.bryants.anthony.plinth.ast.metadata.GlobalVariable;
import eu.bryants.anthony.plinth.ast.metadata.MemberVariable;
import eu.bryants.anthony.plinth.ast.metadata.Variable;
import eu.bryants.anthony.plinth.ast.misc.ArrayElementAssignee;
import eu.bryants.anthony.plinth.ast.misc.Assignee;
import eu.bryants.anthony.plinth.ast.misc.BlankAssignee;
import eu.bryants.anthony.plinth.ast.misc.FieldAssignee;
import eu.bryants.anthony.plinth.ast.misc.Parameter;
import eu.bryants.anthony.plinth.ast.misc.VariableAssignee;
import eu.bryants.anthony.plinth.ast.statement.AssignStatement;
import eu.bryants.anthony.plinth.ast.statement.Block;
import eu.bryants.anthony.plinth.ast.statement.BreakStatement;
import eu.bryants.anthony.plinth.ast.statement.BreakableStatement;
import eu.bryants.anthony.plinth.ast.statement.ContinueStatement;
import eu.bryants.anthony.plinth.ast.statement.DelegateConstructorStatement;
import eu.bryants.anthony.plinth.ast.statement.ExpressionStatement;
import eu.bryants.anthony.plinth.ast.statement.ForStatement;
import eu.bryants.anthony.plinth.ast.statement.IfStatement;
import eu.bryants.anthony.plinth.ast.statement.PrefixIncDecStatement;
import eu.bryants.anthony.plinth.ast.statement.ReturnStatement;
import eu.bryants.anthony.plinth.ast.statement.ShorthandAssignStatement;
import eu.bryants.anthony.plinth.ast.statement.ShorthandAssignStatement.ShorthandAssignmentOperator;
import eu.bryants.anthony.plinth.ast.statement.Statement;
import eu.bryants.anthony.plinth.ast.statement.WhileStatement;
import eu.bryants.anthony.plinth.ast.type.ArrayType;
import eu.bryants.anthony.plinth.ast.type.FunctionType;
import eu.bryants.anthony.plinth.ast.type.NamedType;
import eu.bryants.anthony.plinth.ast.type.NullType;
import eu.bryants.anthony.plinth.ast.type.ObjectType;
import eu.bryants.anthony.plinth.ast.type.PrimitiveType;
import eu.bryants.anthony.plinth.ast.type.PrimitiveType.PrimitiveTypeType;
import eu.bryants.anthony.plinth.ast.type.TupleType;
import eu.bryants.anthony.plinth.ast.type.Type;
import eu.bryants.anthony.plinth.ast.type.VoidType;
import eu.bryants.anthony.plinth.compiler.passes.Resolver;
import eu.bryants.anthony.plinth.compiler.passes.SpecialTypeHandler;
import eu.bryants.anthony.plinth.compiler.passes.TypeChecker;
/**
* @author Anthony Bryant
*/
public class CodeGenerator
{
private TypeDefinition typeDefinition;
private LLVMContextRef context;
private LLVMModuleRef module;
private LLVMValueRef callocFunction;
private Map<GlobalVariable, LLVMValueRef> globalVariables = new HashMap<GlobalVariable, LLVMValueRef>();
private TypeHelper typeHelper;
private VirtualFunctionHandler virtualFunctionHandler;
private BuiltinCodeGenerator builtinGenerator;
public CodeGenerator(TypeDefinition typeDefinition)
{
this.typeDefinition = typeDefinition;
}
public void generateModule()
{
if (module != null)
{
throw new IllegalStateException("Cannot generate the module again, it has already been generated by this CodeGenerator");
}
context = LLVM.LLVMContextCreate();
module = LLVM.LLVMModuleCreateWithName(typeDefinition.getQualifiedName().toString());
virtualFunctionHandler = new VirtualFunctionHandler(this, typeDefinition, module);
typeHelper = new TypeHelper(this, virtualFunctionHandler, module);
virtualFunctionHandler.setTypeHelper(typeHelper);
builtinGenerator = new BuiltinCodeGenerator(module, this, typeHelper);
// add all of the global (static) variables
addGlobalVariables();
// add all of the LLVM functions, including initialisers, constructors, and methods
addFunctions();
if (typeDefinition instanceof ClassDefinition || typeDefinition instanceof InterfaceDefinition)
{
virtualFunctionHandler.addVirtualFunctionTable();
virtualFunctionHandler.addVirtualFunctionTableDescriptor();
}
if (typeDefinition instanceof ClassDefinition && !typeDefinition.isAbstract())
{
virtualFunctionHandler.addClassVFTInitialisationFunction();
addAllocatorFunction();
}
addInitialiserBody(true); // add the static initialisers
if (!(typeDefinition instanceof InterfaceDefinition))
{
addInitialiserBody(false); // add the non-static initialisers (but not for interfaces)
}
addConstructorBodies();
addMethodBodies();
// set the llvm.global_ctors variable, to contain things which need to run before main()
LLVMValueRef[] globalConstructorFunctions;
int[] priorities;
if (typeDefinition instanceof ClassDefinition && !typeDefinition.isAbstract())
{
globalConstructorFunctions = new LLVMValueRef[] {virtualFunctionHandler.getClassVFTInitialisationFunction(),
getInitialiserFunction(true)};
priorities = new int[] {0, 10};
}
else
{
globalConstructorFunctions = new LLVMValueRef[] {getInitialiserFunction(true)};
priorities = new int[] {10};
}
setGlobalConstructors(globalConstructorFunctions, priorities);
MetadataGenerator.generateMetadata(typeDefinition, module);
}
public LLVMContextRef getContext()
{
if (context == null)
{
throw new IllegalStateException("The context has not yet been created; please call generateModule() before getContext()");
}
return context;
}
public LLVMModuleRef getModule()
{
if (module == null)
{
throw new IllegalStateException("The module has not yet been created; please call generateModule() before getModule()");
}
return module;
}
private void addGlobalVariables()
{
for (Field field : typeDefinition.getFields())
{
if (field.isStatic())
{
getGlobal(field.getGlobalVariable());
}
}
if (typeDefinition instanceof ClassDefinition)
{
virtualFunctionHandler.getVFTGlobal(typeDefinition);
virtualFunctionHandler.getVFTDescriptorPointer(typeDefinition);
}
}
private LLVMValueRef getGlobal(GlobalVariable globalVariable)
{
LLVMValueRef value = globalVariables.get(globalVariable);
if (value != null)
{
return value;
}
// lazily initialise globals which do not yet exist
Type type = globalVariable.getType();
LLVMValueRef newValue = LLVM.LLVMAddGlobal(module, typeHelper.findStandardType(type), globalVariable.getMangledName());
if (globalVariable.getEnclosingTypeDefinition() == typeDefinition)
{
LLVM.LLVMSetInitializer(newValue, LLVM.LLVMConstNull(typeHelper.findStandardType(type)));
}
globalVariables.put(globalVariable, newValue);
return newValue;
}
private void addFunctions()
{
// add calloc() as an external function
LLVMTypeRef callocReturnType = LLVM.LLVMPointerType(LLVM.LLVMInt8Type(), 0);
LLVMTypeRef[] callocParamTypes = new LLVMTypeRef[] {LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount())};
callocFunction = LLVM.LLVMAddFunction(module, "calloc", LLVM.LLVMFunctionType(callocReturnType, C.toNativePointerArray(callocParamTypes, false, true), callocParamTypes.length, false));
// create the static and non-static initialiser functions
if (typeDefinition instanceof ClassDefinition && !typeDefinition.isAbstract())
{
virtualFunctionHandler.getClassVFTInitialisationFunction();
getAllocatorFunction((ClassDefinition) typeDefinition);
}
getInitialiserFunction(true);
if (!(typeDefinition instanceof InterfaceDefinition))
{
getInitialiserFunction(false);
}
// create the constructor and method functions
for (Constructor constructor : typeDefinition.getAllConstructors())
{
getConstructorFunction(constructor);
}
for (Method method : typeDefinition.getAllMethods())
{
if (method.isAbstract())
{
continue;
}
getMethodFunction(method);
}
}
/**
* @return the declaration of the i8* calloc(i32, i32) function
*/
public LLVMValueRef getCallocFunction()
{
return callocFunction;
}
/**
* Gets the allocator function for the specified ClassDefinition.
* @param classDefinition - the class definition to get the allocator for
* @return the function declaration for the allocator of the specified ClassDefinition
*/
private LLVMValueRef getAllocatorFunction(ClassDefinition classDefinition)
{
if (classDefinition.isAbstract())
{
throw new IllegalArgumentException("Abstract classes do not have allocator functions");
}
String mangledName = classDefinition.getAllocatorMangledName();
LLVMValueRef existingFunc = LLVM.LLVMGetNamedFunction(module, mangledName);
if (existingFunc != null)
{
return existingFunc;
}
LLVMTypeRef[] types = new LLVMTypeRef[0];
LLVMTypeRef returnType = typeHelper.findTemporaryType(new NamedType(false, false, classDefinition));
LLVMTypeRef functionType = LLVM.LLVMFunctionType(returnType, C.toNativePointerArray(types, false, true), types.length, false);
LLVMValueRef llvmFunc = LLVM.LLVMAddFunction(module, mangledName, functionType);
LLVM.LLVMSetFunctionCallConv(llvmFunc, LLVM.LLVMCallConv.LLVMCCallConv);
return llvmFunc;
}
/**
* Gets the (static or non-static) initialiser function for the TypeDefinition we are building.
* @param isStatic - true for the static initialiser, false for the non-static initialiser
* @return the function declaration for the specified Initialiser
*/
private LLVMValueRef getInitialiserFunction(boolean isStatic)
{
if (typeDefinition instanceof InterfaceDefinition && !isStatic)
{
throw new IllegalArgumentException("Interfaces do not have non-static initialisers");
}
String mangledName = Initialiser.getMangledName(typeDefinition, isStatic);
LLVMValueRef existingFunc = LLVM.LLVMGetNamedFunction(module, mangledName);
if (existingFunc != null)
{
return existingFunc;
}
LLVMTypeRef[] types = null;
if (isStatic)
{
types = new LLVMTypeRef[0];
}
else
{
types = new LLVMTypeRef[1];
types[0] = typeHelper.findTemporaryType(new NamedType(false, false, typeDefinition));
}
LLVMTypeRef returnType = LLVM.LLVMVoidType();
LLVMTypeRef functionType = LLVM.LLVMFunctionType(returnType, C.toNativePointerArray(types, false, true), types.length, false);
LLVMValueRef llvmFunc = LLVM.LLVMAddFunction(module, mangledName, functionType);
LLVM.LLVMSetFunctionCallConv(llvmFunc, LLVM.LLVMCallConv.LLVMCCallConv);
if (!isStatic)
{
LLVM.LLVMSetValueName(LLVM.LLVMGetParam(llvmFunc, 0), "this");
}
return llvmFunc;
}
/**
* Gets the function definition for the specified Constructor. If necessary, it is added first.
* @param constructor - the Constructor to find the declaration of (or to declare)
* @return the function declaration for the specified Constructor
*/
LLVMValueRef getConstructorFunction(Constructor constructor)
{
String mangledName = constructor.getMangledName();
LLVMValueRef existingFunc = LLVM.LLVMGetNamedFunction(module, mangledName);
if (existingFunc != null)
{
return existingFunc;
}
TypeDefinition typeDefinition = constructor.getContainingTypeDefinition();
Parameter[] parameters = constructor.getParameters();
LLVMTypeRef[] types = null;
// constructors need an extra 'uninitialised this' parameter at the start, which is the newly allocated data to initialise
// the 'this' parameter always has a temporary type representation
types = new LLVMTypeRef[1 + parameters.length];
types[0] = typeHelper.findTemporaryType(new NamedType(false, false, typeDefinition));
for (int i = 0; i < parameters.length; i++)
{
types[1 + i] = typeHelper.findStandardType(parameters[i].getType());
}
LLVMTypeRef resultType = LLVM.LLVMVoidType();
LLVMTypeRef functionType = LLVM.LLVMFunctionType(resultType, C.toNativePointerArray(types, false, true), types.length, false);
LLVMValueRef llvmFunc = LLVM.LLVMAddFunction(module, mangledName, functionType);
LLVM.LLVMSetFunctionCallConv(llvmFunc, LLVM.LLVMCallConv.LLVMCCallConv);
LLVM.LLVMSetValueName(LLVM.LLVMGetParam(llvmFunc, 0), "this");
for (int i = 0; i < parameters.length; i++)
{
LLVMValueRef parameter = LLVM.LLVMGetParam(llvmFunc, 1 + i);
LLVM.LLVMSetValueName(parameter, parameters[i].getName());
}
return llvmFunc;
}
/**
* Looks up the function definition for the specified Method. If necessary, its declaration is added first.
* For non-static methods, this function may generate a lookup into a virtual function table on the callee rather than looking up the method directly.
* @param builder - the LLVMBuilderRef to build instructions with
* @param callee - the callee of the method, to look up the virtual method on if the Method is part of a virtual function table
* @param calleeType - the Type of the callee of the method, to determine how to extract the function from the callee value
* @param method - the Method to find
* @return the function to call for the specified Method
*/
LLVMValueRef lookupMethodFunction(LLVMBuilderRef builder, LLVMValueRef callee, Type calleeType, Method method)
{
if (!method.isStatic() &&
(calleeType instanceof ObjectType ||
(calleeType instanceof NamedType && ((NamedType) calleeType).getResolvedTypeDefinition() instanceof ClassDefinition) ||
(calleeType instanceof NamedType && ((NamedType) calleeType).getResolvedTypeDefinition() instanceof InterfaceDefinition)))
{
// generate a virtual function table lookup
return virtualFunctionHandler.getMethodPointer(builder, callee, calleeType, method);
}
return getMethodFunction(method);
}
/**
* Gets the LLVM function for the specified Method. If necessary, its declaration is added first.
* @param method - the Method to find the declaration of (or to declare)
* @return the function declaration for the specified Method
*/
LLVMValueRef getMethodFunction(Method method)
{
if (method.isAbstract())
{
throw new IllegalArgumentException("Abstract methods do not have LLVM functions: " + method);
}
String mangledName = method.getMangledName();
LLVMValueRef existingFunc = LLVM.LLVMGetNamedFunction(module, mangledName);
if (existingFunc != null)
{
return existingFunc;
}
// if it is a built-in method, generate it (unless it is part of a type definition, in which case just define it to be linked in)
if (method instanceof BuiltinMethod && method.getContainingTypeDefinition() == null)
{
return builtinGenerator.generateMethod((BuiltinMethod) method);
}
LLVMTypeRef functionType = typeHelper.findMethodType(method);
LLVMValueRef llvmFunc = LLVM.LLVMAddFunction(module, mangledName, functionType);
LLVM.LLVMSetFunctionCallConv(llvmFunc, LLVM.LLVMCallConv.LLVMCCallConv);
LLVM.LLVMSetValueName(LLVM.LLVMGetParam(llvmFunc, 0), method.isStatic() ? "unused" : "this");
Parameter[] parameters = method.getParameters();
for (int i = 0; i < parameters.length; ++i)
{
LLVMValueRef parameter = LLVM.LLVMGetParam(llvmFunc, i + 1);
LLVM.LLVMSetValueName(parameter, parameters[i].getName());
}
return llvmFunc;
}
/**
* Adds a native function which calls the specified non-native function.
* This consists simply of a new function with the method's native name, which calls the non-native function and returns its result.
* @param method - the method that this native upcall function is for
* @param nonNativeFunction - the non-native function to call
*/
private void addNativeUpcallFunction(Method method, LLVMValueRef nonNativeFunction)
{
LLVMTypeRef resultType = typeHelper.findStandardType(method.getReturnType());
Parameter[] parameters = method.getParameters();
// if the method is non-static, add the pointer argument
int offset = method.isStatic() ? 0 : 1;
LLVMTypeRef[] parameterTypes = new LLVMTypeRef[offset + parameters.length];
if (!method.isStatic())
{
if (typeDefinition instanceof ClassDefinition || typeDefinition instanceof CompoundDefinition)
{
parameterTypes[0] = typeHelper.findTemporaryType(new NamedType(false, method.isImmutable(), method.getContainingTypeDefinition()));
}
else if (typeDefinition instanceof InterfaceDefinition)
{
// interfaces are just represented by objects in native code, without a VFT tuple
parameterTypes[0] = typeHelper.findTemporaryType(new ObjectType(false, method.isImmutable(), null));
}
}
for (int i = 0; i < parameters.length; ++i)
{
Type type = parameters[i].getType();
if (type instanceof NamedType && ((NamedType) type).getResolvedTypeDefinition() instanceof InterfaceDefinition)
{
// interfaces are represented by objects in native code
parameterTypes[offset + i] = typeHelper.findStandardType(new ObjectType(type.isNullable(), ((NamedType) type).isContextuallyImmutable(), null));
}
else
{
parameterTypes[offset + i] = typeHelper.findStandardType(parameters[i].getType());
}
}
LLVMTypeRef functionType = LLVM.LLVMFunctionType(resultType, C.toNativePointerArray(parameterTypes, false, true), parameterTypes.length, false);
LLVMValueRef nativeFunction = LLVM.LLVMAddFunction(module, method.getNativeName(), functionType);
LLVM.LLVMSetFunctionCallConv(nativeFunction, LLVM.LLVMCallConv.LLVMCCallConv);
LLVMBuilderRef builder = LLVM.LLVMCreateFunctionBuilder(nativeFunction);
// if the method is static, add a null first argument to the list of arguments to pass to the non-native function
LLVMValueRef[] arguments = new LLVMValueRef[1 + parameters.length];
if (method.isStatic())
{
arguments[0] = LLVM.LLVMConstNull(typeHelper.getOpaquePointer());
}
else
{
LLVMValueRef callee = LLVM.LLVMGetParam(nativeFunction, 0);
if (typeDefinition instanceof InterfaceDefinition)
{
arguments[0] = typeHelper.convertTemporary(builder, callee, new ObjectType(false, method.isImmutable(), null), new NamedType(false, method.isImmutable(), method.getContainingTypeDefinition()));
}
else
{
arguments[0] = callee;
}
}
for (int i = 0; i < parameters.length; ++i)
{
Type type = parameters[i].getType();
if (type instanceof NamedType && ((NamedType) type).getResolvedTypeDefinition() instanceof InterfaceDefinition)
{
// interfaces are represented by objects in native code, so convert them back to interfaces
ObjectType objectType = new ObjectType(type.isNullable(), ((NamedType) type).isContextuallyImmutable(), null);
LLVMValueRef tempValue = typeHelper.convertStandardToTemporary(builder, LLVM.LLVMGetParam(nativeFunction, offset + i), objectType);
arguments[1 + i] = typeHelper.convertTemporaryToStandard(builder, tempValue, objectType, type);
}
else
{
arguments[1 + i] = LLVM.LLVMGetParam(nativeFunction, offset + i);
}
}
LLVMValueRef result = LLVM.LLVMBuildCall(builder, nonNativeFunction, C.toNativePointerArray(arguments, false, true), arguments.length, "");
if (method.getReturnType() instanceof VoidType)
{
LLVM.LLVMBuildRetVoid(builder);
}
else
{
LLVM.LLVMBuildRet(builder, result);
}
LLVM.LLVMDisposeBuilder(builder);
}
/**
* Adds a native function, and calls it from the specified non-native function.
* This consists simply of a new function declaration with the method's native name,
* and a call to it from the specified non-native function which returns its result.
* @param method - the method that this native downcall function is for
* @param nonNativeFunction - the non-native function to make the downcall
*/
private void addNativeDowncallFunction(Method method, LLVMValueRef nonNativeFunction)
{
LLVMTypeRef resultType = typeHelper.findStandardType(method.getReturnType());
Parameter[] parameters = method.getParameters();
// if the method is non-static, add the pointer argument
int offset = method.isStatic() ? 0 : 1;
LLVMTypeRef[] parameterTypes = new LLVMTypeRef[offset + parameters.length];
if (!method.isStatic())
{
if (typeDefinition instanceof ClassDefinition || typeDefinition instanceof CompoundDefinition)
{
parameterTypes[0] = typeHelper.findTemporaryType(new NamedType(false, method.isImmutable(), method.getContainingTypeDefinition()));
}
else if (typeDefinition instanceof InterfaceDefinition)
{
parameterTypes[0] = typeHelper.findTemporaryType(new ObjectType(false, method.isImmutable(), null));
}
}
for (int i = 0; i < parameters.length; ++i)
{
Type type = parameters[i].getType();
if (type instanceof NamedType && ((NamedType) type).getResolvedTypeDefinition() instanceof InterfaceDefinition)
{
// interfaces are represented by objects in native code
parameterTypes[offset + i] = typeHelper.findStandardType(new ObjectType(type.isNullable(), ((NamedType) type).isContextuallyImmutable(), null));
}
else
{
parameterTypes[offset + i] = typeHelper.findStandardType(parameters[i].getType());
}
}
LLVMTypeRef functionType = LLVM.LLVMFunctionType(resultType, C.toNativePointerArray(parameterTypes, false, true), parameterTypes.length, false);
LLVMValueRef nativeFunction = LLVM.LLVMAddFunction(module, method.getNativeName(), functionType);
LLVM.LLVMSetFunctionCallConv(nativeFunction, LLVM.LLVMCallConv.LLVMCCallConv);
LLVMBuilderRef builder = LLVM.LLVMCreateFunctionBuilder(nonNativeFunction);
LLVMValueRef[] arguments = new LLVMValueRef[parameterTypes.length];
if (!method.isStatic())
{
LLVMValueRef callee = LLVM.LLVMGetParam(nonNativeFunction, 0);
if (typeDefinition instanceof InterfaceDefinition)
{
arguments[0] = typeHelper.convertTemporary(builder, callee, new ObjectType(false, method.isImmutable(), null), new NamedType(false, method.isImmutable(), method.getContainingTypeDefinition()));
}
else
{
arguments[0] = callee;
}
}
for (int i = 0; i < parameters.length; ++i)
{
Type type = parameters[i].getType();
if (type instanceof NamedType && ((NamedType) type).getResolvedTypeDefinition() instanceof InterfaceDefinition)
{
// convert the interface to an object
LLVMValueRef tempValue = typeHelper.convertStandardToTemporary(builder, LLVM.LLVMGetParam(nonNativeFunction, 1 + i), type);
arguments[offset + i] = typeHelper.convertTemporaryToStandard(builder, tempValue, type, new ObjectType(false, ((NamedType) type).isContextuallyImmutable(), null));
}
else
{
arguments[offset + i] = LLVM.LLVMGetParam(nonNativeFunction, 1 + i);
}
}
LLVMValueRef result = LLVM.LLVMBuildCall(builder, nativeFunction, C.toNativePointerArray(arguments, false, true), arguments.length, "");
if (method.getReturnType() instanceof VoidType)
{
LLVM.LLVMBuildRetVoid(builder);
}
else
{
LLVM.LLVMBuildRet(builder, result);
}
LLVM.LLVMDisposeBuilder(builder);
}
private void addAllocatorFunction()
{
if (!(typeDefinition instanceof ClassDefinition))
{
throw new UnsupportedOperationException("Allocators cannot be created for anything but class definitions");
}
LLVMValueRef llvmFunction = getAllocatorFunction((ClassDefinition) typeDefinition);
LLVMBuilderRef builder = LLVM.LLVMCreateFunctionBuilder(llvmFunction);
// allocate memory for the object
LLVMTypeRef nativeType = typeHelper.findTemporaryType(new NamedType(false, false, typeDefinition));
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false)};
LLVMValueRef llvmStructSize = LLVM.LLVMBuildGEP(builder, LLVM.LLVMConstNull(nativeType), C.toNativePointerArray(indices, false, true), indices.length, "");
LLVMValueRef llvmSize = LLVM.LLVMBuildPtrToInt(builder, llvmStructSize, LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), "");
LLVMValueRef[] callocArguments = new LLVMValueRef[] {llvmSize, LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false)};
LLVMValueRef memory = LLVM.LLVMBuildCall(builder, callocFunction, C.toNativePointerArray(callocArguments, false, true), callocArguments.length, "");
LLVMValueRef pointer = LLVM.LLVMBuildBitCast(builder, memory, nativeType, "");
// store the interface search list
LLVMValueRef interfaceSearchList = virtualFunctionHandler.getInterfaceSearchList();
interfaceSearchList = LLVM.LLVMBuildBitCast(builder, interfaceSearchList, LLVM.LLVMPointerType(virtualFunctionHandler.getInterfaceSearchListType(), 0), "");
LLVMValueRef interfaceSearchListPointer = virtualFunctionHandler.getInterfaceSearchListPointer(builder, pointer);
LLVM.LLVMBuildStore(builder, interfaceSearchList, interfaceSearchListPointer);
// set up the virtual function tables
for (TypeDefinition current : typeDefinition.getInheritanceLinearisation())
{
LLVMValueRef currentVFT;
if (current == typeDefinition)
{
currentVFT = virtualFunctionHandler.getVFTGlobal(current);
}
else
{
LLVMValueRef globalValue = virtualFunctionHandler.getSuperTypeVFTGlobal(current);
currentVFT = LLVM.LLVMBuildLoad(builder, globalValue, "");
}
LLVMValueRef vftPointer = virtualFunctionHandler.getVirtualFunctionTablePointer(builder, pointer, (ClassDefinition) typeDefinition, current);
LLVM.LLVMBuildStore(builder, currentVFT, vftPointer);
}
LLVMValueRef objectVFTGlobal = virtualFunctionHandler.getObjectSuperTypeVFTGlobal();
LLVMValueRef objectVFT = LLVM.LLVMBuildLoad(builder, objectVFTGlobal, "");
LLVMValueRef objectVFTPointer = virtualFunctionHandler.getFirstVirtualFunctionTablePointer(builder, pointer);
LLVM.LLVMBuildStore(builder, objectVFT, objectVFTPointer);
LLVM.LLVMBuildRet(builder, pointer);
LLVM.LLVMDisposeBuilder(builder);
}
private void addInitialiserBody(boolean isStatic)
{
LLVMValueRef initialiserFunc = getInitialiserFunction(isStatic);
LLVMValueRef thisValue = isStatic ? null : LLVM.LLVMGetParam(initialiserFunc, 0);
LLVMBuilderRef builder = LLVM.LLVMCreateFunctionBuilder(initialiserFunc);
// build all of the static/non-static initialisers in one LLVM function
for (Initialiser initialiser : typeDefinition.getInitialisers())
{
if (initialiser.isStatic() != isStatic)
{
continue;
}
if (initialiser instanceof FieldInitialiser)
{
Field field = ((FieldInitialiser) initialiser).getField();
LLVMValueRef result = buildExpression(field.getInitialiserExpression(), builder, thisValue, new HashMap<Variable, LLVM.LLVMValueRef>());
LLVMValueRef assigneePointer = null;
if (field.isStatic())
{
assigneePointer = getGlobal(field.getGlobalVariable());
}
else
{
assigneePointer = typeHelper.getFieldPointer(builder, thisValue, field);
}
LLVMValueRef convertedValue = typeHelper.convertTemporaryToStandard(builder, result, field.getInitialiserExpression().getType(), field.getType());
LLVM.LLVMBuildStore(builder, convertedValue, assigneePointer);
}
else
{
// build allocas for all of the variables, at the start of the entry block
Set<Variable> allVariables = Resolver.getAllNestedVariables(initialiser.getBlock());
Map<Variable, LLVMValueRef> variables = new HashMap<Variable, LLVM.LLVMValueRef>();
for (Variable v : allVariables)
{
LLVMValueRef allocaInst = LLVM.LLVMBuildAllocaInEntryBlock(builder, typeHelper.findTemporaryType(v.getType()), v.getName());
variables.put(v, allocaInst);
}
buildStatement(initialiser.getBlock(), VoidType.VOID_TYPE, builder, thisValue, variables, new HashMap<BreakableStatement, LLVM.LLVMBasicBlockRef>(), new HashMap<BreakableStatement, LLVM.LLVMBasicBlockRef>(), new Runnable()
{
@Override
public void run()
{
throw new IllegalStateException("Cannot return from an initialiser");
}
});
}
}
LLVM.LLVMBuildRetVoid(builder);
LLVM.LLVMDisposeBuilder(builder);
}
/**
* Sets the global constructors for this module. This should only be done once per module.
* The functions provided are put into the llvm.global_ctors variable, along with their associated priorities.
* At run time, these functions will be run before main(), in ascending order of priority (so priority 0 is run first, then priority 1, etc.)
* @param functions - the functions to run before main()
* @param priorities - the priorities of the functions
*/
private void setGlobalConstructors(LLVMValueRef[] functions, int[] priorities)
{
if (functions.length != priorities.length)
{
throw new IllegalArgumentException("To set the global constructors, you must provide an equal number of functions and priorities");
}
// build up the type of the global variable
LLVMTypeRef[] paramTypes = new LLVMTypeRef[0];
LLVMTypeRef functionType = LLVM.LLVMFunctionType(LLVM.LLVMVoidType(), C.toNativePointerArray(paramTypes, false, true), paramTypes.length, false);
LLVMTypeRef functionPointerType = LLVM.LLVMPointerType(functionType, 0);
LLVMTypeRef[] structSubTypes = new LLVMTypeRef[] {LLVM.LLVMInt32Type(), functionPointerType};
LLVMTypeRef structType = LLVM.LLVMStructType(C.toNativePointerArray(structSubTypes, false, true), structSubTypes.length, false);
LLVMTypeRef arrayType = LLVM.LLVMArrayType(structType, functions.length);
// build the constant expression for global variable's initialiser
LLVMValueRef[] arrayElements = new LLVMValueRef[functions.length];
for (int i = 0; i < functions.length; ++i)
{
LLVMValueRef[] constantValues = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMInt32Type(), priorities[i], false), functions[i]};
arrayElements[i] = LLVM.LLVMConstStruct(C.toNativePointerArray(constantValues, false, true), constantValues.length, false);
}
LLVMValueRef array = LLVM.LLVMConstArray(structType, C.toNativePointerArray(arrayElements, false, true), arrayElements.length);
// create the 'llvm.global_ctors' global variable, which lists which functions are run before main()
LLVMValueRef global = LLVM.LLVMAddGlobal(module, arrayType, "llvm.global_ctors");
LLVM.LLVMSetLinkage(global, LLVM.LLVMLinkage.LLVMAppendingLinkage);
LLVM.LLVMSetInitializer(global, array);
}
private void addConstructorBodies()
{
for (Constructor constructor : typeDefinition.getAllConstructors())
{
final LLVMValueRef llvmFunction = getConstructorFunction(constructor);
final LLVMBuilderRef builder = LLVM.LLVMCreateFunctionBuilder(llvmFunction);
// create LLVMValueRefs for all of the variables, including paramters
Set<Variable> allVariables = Resolver.getAllNestedVariables(constructor.getBlock());
Map<Variable, LLVMValueRef> variables = new HashMap<Variable, LLVM.LLVMValueRef>();
for (Variable v : allVariables)
{
LLVMValueRef allocaInst = LLVM.LLVMBuildAlloca(builder, typeHelper.findTemporaryType(v.getType()), v.getName());
variables.put(v, allocaInst);
}
// the first constructor parameter is always the newly allocated 'this' pointer
final LLVMValueRef thisValue = LLVM.LLVMGetParam(llvmFunction, 0);
// store the parameter values to the LLVMValueRefs
for (Parameter p : constructor.getParameters())
{
LLVMValueRef llvmParameter = LLVM.LLVMGetParam(llvmFunction, 1 + p.getIndex());
LLVMValueRef convertedParameter = typeHelper.convertStandardToTemporary(builder, llvmParameter, p.getType());
LLVM.LLVMBuildStore(builder, convertedParameter, variables.get(p.getVariable()));
}
if (!constructor.getCallsDelegateConstructor())
{
// for classes which have superclasses, we must call the implicit no-args super() constructor here
if (typeDefinition instanceof ClassDefinition)
{
ClassDefinition superClassDefinition = ((ClassDefinition) typeDefinition).getSuperClassDefinition();
if (superClassDefinition != null)
{
Constructor noArgsSuper = null;
for (Constructor test : superClassDefinition.getUniqueConstructors())
{
if (test.getParameters().length == 0)
{
noArgsSuper = test;
}
}
if (noArgsSuper == null)
{
throw new IllegalArgumentException("Missing no-args super() constructor");
}
LLVMValueRef convertedThis = typeHelper.convertTemporary(builder, thisValue, new NamedType(false, false, typeDefinition), new NamedType(false, false, superClassDefinition));
LLVMValueRef[] superConstructorArgs = new LLVMValueRef[] {convertedThis};
LLVM.LLVMBuildCall(builder, getConstructorFunction(noArgsSuper), C.toNativePointerArray(superConstructorArgs, false, true), superConstructorArgs.length, "");
}
}
// call the non-static initialiser function, which runs all non-static initialisers and sets the initial values for all of the fields
// if this constructor calls a delegate constructor then it will be called later on in the block
LLVMValueRef initialiserFunction = getInitialiserFunction(false);
LLVMValueRef[] initialiserArgs = new LLVMValueRef[] {thisValue};
LLVM.LLVMBuildCall(builder, initialiserFunction, C.toNativePointerArray(initialiserArgs, false, true), initialiserArgs.length, "");
}
buildStatement(constructor.getBlock(), VoidType.VOID_TYPE, builder, thisValue, variables, new HashMap<BreakableStatement, LLVM.LLVMBasicBlockRef>(), new HashMap<BreakableStatement, LLVM.LLVMBasicBlockRef>(), new Runnable()
{
@Override
public void run()
{
// this will be run whenever a return void is found
// so return the result of the constructor, which is always void
LLVM.LLVMBuildRetVoid(builder);
}
});
// return if control reaches the end of the function
if (!constructor.getBlock().stopsExecution())
{
LLVM.LLVMBuildRetVoid(builder);
}
LLVM.LLVMDisposeBuilder(builder);
}
}
private void addMethodBodies()
{
for (Method method : typeDefinition.getAllMethods())
{
if (method.isAbstract())
{
continue;
}
if (method instanceof BuiltinMethod)
{
builtinGenerator.generateMethod((BuiltinMethod) method);
continue;
}
LLVMValueRef llvmFunction = getMethodFunction(method);
// add the native function if the programmer specified one
if (method.getNativeName() != null)
{
if (method.getBlock() == null)
{
addNativeDowncallFunction(method, llvmFunction);
}
else
{
addNativeUpcallFunction(method, llvmFunction);
}
}
if (method.getBlock() == null)
{
continue;
}
final LLVMBuilderRef builder = LLVM.LLVMCreateFunctionBuilder(llvmFunction);
// create LLVMValueRefs for all of the variables, including parameters
Map<Variable, LLVMValueRef> variables = new HashMap<Variable, LLVM.LLVMValueRef>();
for (Variable v : Resolver.getAllNestedVariables(method.getBlock()))
{
LLVMValueRef allocaInst = LLVM.LLVMBuildAlloca(builder, typeHelper.findTemporaryType(v.getType()), v.getName());
variables.put(v, allocaInst);
}
// store the parameter values to the LLVMValueRefs
for (Parameter p : method.getParameters())
{
// find the LLVM parameter, the +1 on the index is to account for the 'this' pointer (or the unused opaque* for static methods)
LLVMValueRef llvmParameter = LLVM.LLVMGetParam(llvmFunction, p.getIndex() + 1);
LLVMValueRef convertedParameter = typeHelper.convertStandardToTemporary(builder, llvmParameter, p.getType());
LLVM.LLVMBuildStore(builder, convertedParameter, variables.get(p.getVariable()));
}
LLVMValueRef thisValue = method.isStatic() ? null : LLVM.LLVMGetParam(llvmFunction, 0);
// convert interface callees from object to their temporary representation
if (!method.isStatic() && method.getContainingTypeDefinition() instanceof InterfaceDefinition)
{
thisValue = typeHelper.convertTemporary(builder, thisValue, new ObjectType(false, method.isImmutable(), null),
new NamedType(false, method.isImmutable(), method.getContainingTypeDefinition()));
}
buildStatement(method.getBlock(), method.getReturnType(), builder, thisValue, variables, new HashMap<BreakableStatement, LLVM.LLVMBasicBlockRef>(), new HashMap<BreakableStatement, LLVM.LLVMBasicBlockRef>(), new Runnable()
{
@Override
public void run()
{
// this will be run whenever a return void is found
// so return void
LLVM.LLVMBuildRetVoid(builder);
}
});
// add a "ret void" if control reaches the end of the function
if (!method.getBlock().stopsExecution())
{
LLVM.LLVMBuildRetVoid(builder);
}
LLVM.LLVMDisposeBuilder(builder);
}
}
/**
* Adds a string constant with the specified value, with the LLVM type: {i32, [n x i8]}
* @param value - the value to store in the constant
* @return the global variable created (a pointer to the constant value)
*/
public LLVMValueRef addStringConstant(String value)
{
byte[] bytes;
try
{
bytes = value.getBytes("UTF-8");
}
catch (UnsupportedEncodingException e)
{
throw new IllegalStateException("UTF-8 encoding not supported!", e);
}
StringBuffer nameBuffer = new StringBuffer("_STR_");
byte[] hexChars = "0123456789ABCDEF".getBytes();
for (byte b : bytes)
{
if (('a' <= b & b <= 'z') | ('A' <= b & b <= 'Z') | ('0' <= b & b <= '9'))
{
nameBuffer.append((char) b);
}
else
{
nameBuffer.append('_');
nameBuffer.append((char) hexChars[(b >> 4) & 0xf]);
nameBuffer.append((char) hexChars[b & 0xf]);
}
}
String mangledName = nameBuffer.toString();
LLVMValueRef existingGlobal = LLVM.LLVMGetNamedGlobal(module, mangledName);
if (existingGlobal != null)
{
return existingGlobal;
}
// build the []ubyte up from the string value, and store it as a global variable
ArrayType arrayType = new ArrayType(false, false, new PrimitiveType(false, PrimitiveTypeType.UBYTE, null), null);
LLVMValueRef lengthValue = LLVM.LLVMConstInt(typeHelper.findStandardType(ArrayLengthMember.ARRAY_LENGTH_TYPE), bytes.length, false);
LLVMValueRef constString = LLVM.LLVMConstString(bytes, bytes.length, true);
LLVMValueRef[] arrayValues = new LLVMValueRef[] {virtualFunctionHandler.getEmptyInterfaceSearchList(), virtualFunctionHandler.getBaseChangeObjectVFT(arrayType), lengthValue, constString};
LLVMValueRef byteArrayStruct = LLVM.LLVMConstStruct(C.toNativePointerArray(arrayValues, false, true), arrayValues.length, false);
LLVMTypeRef interfaceSearchListType = LLVM.LLVMPointerType(virtualFunctionHandler.getInterfaceSearchListType(), 0);
LLVMTypeRef vftPointerType = LLVM.LLVMPointerType(virtualFunctionHandler.getObjectVFTType(), 0);
LLVMTypeRef stringType = LLVM.LLVMArrayType(LLVM.LLVMInt8Type(), bytes.length);
LLVMTypeRef[] structSubTypes = new LLVMTypeRef[] {interfaceSearchListType, vftPointerType, typeHelper.findStandardType(ArrayLengthMember.ARRAY_LENGTH_TYPE), stringType};
LLVMTypeRef structType = LLVM.LLVMStructType(C.toNativePointerArray(structSubTypes, false, true), structSubTypes.length, false);
LLVMValueRef globalVariable = LLVM.LLVMAddGlobal(module, structType, mangledName);
LLVM.LLVMSetInitializer(globalVariable, byteArrayStruct);
LLVM.LLVMSetLinkage(globalVariable, LLVM.LLVMLinkage.LLVMLinkOnceODRLinkage);
LLVM.LLVMSetVisibility(globalVariable, LLVM.LLVMVisibility.LLVMHiddenVisibility);
LLVM.LLVMSetGlobalConstant(globalVariable, true);
return globalVariable;
}
/**
* Builds a string creation for the specified string value.
* @param builder - the LLVMBuilderRef to build instructions with
* @param value - the value of the string to create
* @return the result of creating the string, in a temporary type representation
*/
public LLVMValueRef buildStringCreation(LLVMBuilderRef builder, String value)
{
LLVMValueRef globalVariable = addStringConstant(value);
// extract the string([]ubyte) constructor from the type of this expression
LLVMValueRef constructorFunction = getConstructorFunction(SpecialTypeHandler.stringArrayConstructor);
LLVMValueRef bitcastedArray = LLVM.LLVMBuildBitCast(builder, globalVariable, typeHelper.findRawStringType(), "");
// find the type to alloca, which is the standard representation of a non-nullable version of this type
// when we alloca this type, it becomes equivalent to the temporary type representation of this compound type (with any nullability)
LLVMTypeRef allocaBaseType = typeHelper.findStandardType(new NamedType(false, false, SpecialTypeHandler.stringArrayConstructor.getContainingTypeDefinition()));
LLVMValueRef alloca = LLVM.LLVMBuildAllocaInEntryBlock(builder, allocaBaseType, "");
typeHelper.initialiseCompoundType(builder, (CompoundDefinition) SpecialTypeHandler.stringArrayConstructor.getContainingTypeDefinition(), alloca);
LLVMValueRef[] arguments = new LLVMValueRef[] {alloca, bitcastedArray};
LLVM.LLVMBuildCall(builder, constructorFunction, C.toNativePointerArray(arguments, false, true), arguments.length, "");
return alloca;
}
/**
* Builds a string concatenation for the specified strings.
* @param builder - the LLVMBuilderRef to build instructions with
* @param strings - the array of strings to concatenate, each in a standard type representation
* @return the result of concatenating the two strings, in a temporary type representation
*/
public LLVMValueRef buildStringConcatenation(LLVMBuilderRef builder, LLVMValueRef... strings)
{
if (strings.length < 2)
{
throw new IllegalArgumentException("Cannot concatenate less than two strings");
}
// concatenate the strings
// find the type to alloca, which is the standard representation of a non-nullable version of this type
// when we alloca this type, it becomes equivalent to the temporary type representation of this compound type (with any nullability)
LLVMTypeRef allocaBaseType = typeHelper.findStandardType(new NamedType(false, false, SpecialTypeHandler.stringConcatenationConstructor.getContainingTypeDefinition()));
LLVMValueRef alloca = LLVM.LLVMBuildAllocaInEntryBlock(builder, allocaBaseType, "");
typeHelper.initialiseCompoundType(builder, (CompoundDefinition) SpecialTypeHandler.stringConcatenationConstructor.getContainingTypeDefinition(), alloca);
if (strings.length == 2)
{
// call the string(string, string) constructor
LLVMValueRef[] arguments = new LLVMValueRef[] {alloca, strings[0], strings[1]};
LLVMValueRef concatenationConstructor = getConstructorFunction(SpecialTypeHandler.stringConcatenationConstructor);
LLVM.LLVMBuildCall(builder, concatenationConstructor, C.toNativePointerArray(arguments, false, true), arguments.length, "");
return alloca;
}
LLVMValueRef arrayLength = LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), strings.length, false);
ArrayType arrayType = new ArrayType(false, false, SpecialTypeHandler.STRING_TYPE, null);
LLVMValueRef array = buildArrayCreation(builder, new LLVMValueRef[] {arrayLength}, arrayType);
for (int i = 0; i < strings.length; ++i)
{
LLVMValueRef elementPointer = typeHelper.getArrayElementPointer(builder, array, LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), i, false));
LLVM.LLVMBuildStore(builder, strings[i], elementPointer);
}
LLVMValueRef[] arguments = new LLVMValueRef[] {alloca, typeHelper.convertTemporaryToStandard(builder, array, arrayType)};
LLVMValueRef concatenationConstructor = getConstructorFunction(SpecialTypeHandler.stringArrayConcatenationConstructor);
LLVM.LLVMBuildCall(builder, concatenationConstructor, C.toNativePointerArray(arguments, false, true), arguments.length, "");
return alloca;
}
/**
* Generates a main method for the "static uint main([]string)" method in the TypeDefinition we are generating.
*/
public void generateMainMethod()
{
Type argsType = new ArrayType(false, false, SpecialTypeHandler.STRING_TYPE, null);
Method mainMethod = null;
for (Method method : typeDefinition.getAllMethods())
{
if (method.isStatic() && method.getName().equals(SpecialTypeHandler.MAIN_METHOD_NAME) && method.getReturnType().isEquivalent(new PrimitiveType(false, PrimitiveTypeType.UINT, null)))
{
Parameter[] parameters = method.getParameters();
if (parameters.length == 1 && parameters[0].getType().isEquivalent(argsType))
{
mainMethod = method;
break;
}
}
}
if (mainMethod == null)
{
throw new IllegalArgumentException("Could not find main method in " + typeDefinition.getQualifiedName());
}
LLVMValueRef languageMainFunction = getMethodFunction(mainMethod);
// define strlen (which we will need for finding the length of each of the arguments)
LLVMTypeRef[] strlenParameters = new LLVMTypeRef[] {LLVM.LLVMPointerType(LLVM.LLVMInt8Type(), 0)};
LLVMTypeRef strlenFunctionType = LLVM.LLVMFunctionType(LLVM.LLVMInt32Type(), C.toNativePointerArray(strlenParameters, false, true), strlenParameters.length, false);
LLVMValueRef strlenFunction = LLVM.LLVMAddFunction(module, "strlen", strlenFunctionType);
// define main
LLVMTypeRef argvType = LLVM.LLVMPointerType(LLVM.LLVMPointerType(LLVM.LLVMInt8Type(), 0), 0);
LLVMTypeRef[] paramTypes = new LLVMTypeRef[] {LLVM.LLVMInt32Type(), argvType};
LLVMTypeRef returnType = LLVM.LLVMInt32Type();
LLVMTypeRef functionType = LLVM.LLVMFunctionType(returnType, C.toNativePointerArray(paramTypes, false, true), paramTypes.length, false);
LLVMValueRef mainFunction = LLVM.LLVMAddFunction(module, "main", functionType);
LLVMBuilderRef builder = LLVM.LLVMCreateFunctionBuilder(mainFunction);
LLVMBasicBlockRef finalBlock = LLVM.LLVMAddBasicBlock(builder, "startProgram");
LLVMBasicBlockRef argvLoopEndBlock = LLVM.LLVMAddBasicBlock(builder, "argvCopyLoopEnd");
LLVMBasicBlockRef stringLoopBlock = LLVM.LLVMAddBasicBlock(builder, "stringCopyLoop");
LLVMBasicBlockRef argvLoopBlock = LLVM.LLVMAddBasicBlock(builder, "argvCopyLoop");
LLVMValueRef argc = LLVM.LLVMGetParam(mainFunction, 0);
LLVM.LLVMSetValueName(argc, "argc");
LLVMValueRef argv = LLVM.LLVMGetParam(mainFunction, 1);
LLVM.LLVMSetValueName(argv, "argv");
// create the final args array
ArrayType stringArrayType = new ArrayType(false, false, SpecialTypeHandler.STRING_TYPE, null);
LLVMTypeRef llvmArrayType = typeHelper.findTemporaryType(stringArrayType);
// find the element of our array at index argc (i.e. one past the end of the array), which gives us our size
LLVMValueRef llvmArraySize = typeHelper.getArrayElementPointer(builder, LLVM.LLVMConstNull(llvmArrayType), argc);
LLVMValueRef llvmSize = LLVM.LLVMBuildPtrToInt(builder, llvmArraySize, LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), "");
LLVMValueRef[] callocArgs = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMInt32Type(), 1, false), llvmSize};
LLVMValueRef stringArray = LLVM.LLVMBuildCall(builder, callocFunction, C.toNativePointerArray(callocArgs, false, true), callocArgs.length, "");
stringArray = LLVM.LLVMBuildBitCast(builder, stringArray, llvmArrayType, "");
LLVMValueRef stringsInterfaceSearchList = virtualFunctionHandler.getEmptyInterfaceSearchList();
LLVMValueRef stringsInterfaceSearchListPointer = virtualFunctionHandler.getInterfaceSearchListPointer(builder, stringArray);
LLVM.LLVMBuildStore(builder, stringsInterfaceSearchList, stringsInterfaceSearchListPointer);
LLVMValueRef stringsVFT = virtualFunctionHandler.getBaseChangeObjectVFT(stringArrayType);
LLVMValueRef stringsVFTPointer = virtualFunctionHandler.getFirstVirtualFunctionTablePointer(builder, stringArray);
LLVM.LLVMBuildStore(builder, stringsVFT, stringsVFTPointer);
LLVMValueRef sizePointer = typeHelper.getArrayLengthPointer(builder, stringArray);
LLVM.LLVMBuildStore(builder, argc, sizePointer);
// branch to the argv-copying loop
LLVMValueRef initialArgvLoopCheck = LLVM.LLVMBuildICmp(builder, LLVM.LLVMIntPredicate.LLVMIntNE, argc, LLVM.LLVMConstInt(LLVM.LLVMInt32Type(), 0, false), "");
LLVMBasicBlockRef startBlock = LLVM.LLVMGetInsertBlock(builder);
LLVM.LLVMBuildCondBr(builder, initialArgvLoopCheck, argvLoopBlock, finalBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, argvLoopBlock);
LLVMValueRef argvIndex = LLVM.LLVMBuildPhi(builder, LLVM.LLVMInt32Type(), "");
LLVMValueRef[] charArrayIndices = new LLVMValueRef[] {argvIndex};
LLVMValueRef charArrayPointer = LLVM.LLVMBuildGEP(builder, argv, C.toNativePointerArray(charArrayIndices, false, true), charArrayIndices.length, "");
LLVMValueRef charArray = LLVM.LLVMBuildLoad(builder, charArrayPointer, "");
// call strlen(argv[argvIndex])
LLVMValueRef[] strlenArgs = new LLVMValueRef[] {charArray};
LLVMValueRef argLength = LLVM.LLVMBuildCall(builder, strlenFunction, C.toNativePointerArray(strlenArgs, false, true), strlenArgs.length, "");
// allocate the []ubyte to contain this argument
ArrayType ubyteArrayType = new ArrayType(false, true, new PrimitiveType(false, PrimitiveTypeType.UBYTE, null), null);
LLVMTypeRef llvmUbyteArrayType = typeHelper.findTemporaryType(ubyteArrayType);
// find the element of our array at index argLength (i.e. one past the end of the array), which gives us our size
LLVMValueRef llvmUbyteArraySize = typeHelper.getArrayElementPointer(builder, LLVM.LLVMConstNull(llvmUbyteArrayType), argLength);
LLVMValueRef llvmUbyteSize = LLVM.LLVMBuildPtrToInt(builder, llvmUbyteArraySize, LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), "");
LLVMValueRef[] ubyteCallocArgs = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMInt32Type(), 1, false), llvmUbyteSize};
LLVMValueRef bytes = LLVM.LLVMBuildCall(builder, callocFunction, C.toNativePointerArray(ubyteCallocArgs, false, true), ubyteCallocArgs.length, "");
bytes = LLVM.LLVMBuildBitCast(builder, bytes, llvmUbyteArrayType, "");
LLVMValueRef bytesInterfaceSearchList = virtualFunctionHandler.getEmptyInterfaceSearchList();
LLVMValueRef bytesInterfaceSearchListPointer = virtualFunctionHandler.getInterfaceSearchListPointer(builder, bytes);
LLVM.LLVMBuildStore(builder, bytesInterfaceSearchList, bytesInterfaceSearchListPointer);
LLVMValueRef bytesVFT = virtualFunctionHandler.getBaseChangeObjectVFT(ubyteArrayType);
LLVMValueRef bytesVFTPointer = virtualFunctionHandler.getFirstVirtualFunctionTablePointer(builder, bytes);
LLVM.LLVMBuildStore(builder, bytesVFT, bytesVFTPointer);
LLVMValueRef bytesLengthPointer = typeHelper.getArrayLengthPointer(builder, bytes);
LLVM.LLVMBuildStore(builder, argLength, bytesLengthPointer);
// branch to the character copying loop
LLVMValueRef initialBytesLoopCheck = LLVM.LLVMBuildICmp(builder, LLVM.LLVMIntPredicate.LLVMIntNE, argLength, LLVM.LLVMConstInt(LLVM.LLVMInt32Type(), 0, false), "");
LLVM.LLVMBuildCondBr(builder, initialBytesLoopCheck, stringLoopBlock, argvLoopEndBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, stringLoopBlock);
// copy the character
LLVMValueRef characterIndex = LLVM.LLVMBuildPhi(builder, LLVM.LLVMInt32Type(), "");
LLVMValueRef[] inPointerIndices = new LLVMValueRef[] {characterIndex};
LLVMValueRef inPointer = LLVM.LLVMBuildGEP(builder, charArray, C.toNativePointerArray(inPointerIndices, false, true), inPointerIndices.length, "");
LLVMValueRef character = LLVM.LLVMBuildLoad(builder, inPointer, "");
LLVMValueRef outPointer = typeHelper.getArrayElementPointer(builder, bytes, characterIndex);
LLVM.LLVMBuildStore(builder, character, outPointer);
// update the character index, and branch
LLVMValueRef incCharacterIndex = LLVM.LLVMBuildAdd(builder, characterIndex, LLVM.LLVMConstInt(LLVM.LLVMInt32Type(), 1, false), "");
LLVMValueRef bytesLoopCheck = LLVM.LLVMBuildICmp(builder, LLVM.LLVMIntPredicate.LLVMIntNE, incCharacterIndex, argLength, "");
LLVM.LLVMBuildCondBr(builder, bytesLoopCheck, stringLoopBlock, argvLoopEndBlock);
// add the incomings for the character index
LLVMValueRef[] bytesLoopPhiValues = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMInt32Type(), 0, false), incCharacterIndex};
LLVMBasicBlockRef[] bytesLoopPhiBlocks = new LLVMBasicBlockRef[] {argvLoopBlock, stringLoopBlock};
LLVM.LLVMAddIncoming(characterIndex, C.toNativePointerArray(bytesLoopPhiValues, false, true), C.toNativePointerArray(bytesLoopPhiBlocks, false, true), bytesLoopPhiValues.length);
// build the end of the string creation loop
LLVM.LLVMPositionBuilderAtEnd(builder, argvLoopEndBlock);
LLVMValueRef stringArrayElementPointer = typeHelper.getArrayElementPointer(builder, stringArray, argvIndex);
typeHelper.initialiseCompoundType(builder, (CompoundDefinition) SpecialTypeHandler.STRING_TYPE.getResolvedTypeDefinition(), stringArrayElementPointer);
LLVMValueRef[] stringCreationArgs = new LLVMValueRef[] {stringArrayElementPointer, bytes};
LLVM.LLVMBuildCall(builder, getConstructorFunction(SpecialTypeHandler.stringArrayConstructor), C.toNativePointerArray(stringCreationArgs, false, true), stringCreationArgs.length, "");
// update the argv index, and branch
LLVMValueRef incArgvIndex = LLVM.LLVMBuildAdd(builder, argvIndex, LLVM.LLVMConstInt(LLVM.LLVMInt32Type(), 1, false), "");
LLVMValueRef argvLoopCheck = LLVM.LLVMBuildICmp(builder, LLVM.LLVMIntPredicate.LLVMIntNE, incArgvIndex, argc, "");
LLVM.LLVMBuildCondBr(builder, argvLoopCheck, argvLoopBlock, finalBlock);
// add the incomings for the argv index
LLVMValueRef[] argvLoopPhiValues = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMInt32Type(), 0, false), incArgvIndex};
LLVMBasicBlockRef[] argvLoopPhiBlocks = new LLVMBasicBlockRef[] {startBlock, argvLoopEndBlock};
LLVM.LLVMAddIncoming(argvIndex, C.toNativePointerArray(argvLoopPhiValues, false, true), C.toNativePointerArray(argvLoopPhiBlocks, false, true), argvLoopPhiValues.length);
// build the actual function call
LLVM.LLVMPositionBuilderAtEnd(builder, finalBlock);
LLVMValueRef[] arguments = new LLVMValueRef[] {LLVM.LLVMConstNull(typeHelper.getOpaquePointer()), stringArray};
LLVMValueRef returnCode = LLVM.LLVMBuildCall(builder, languageMainFunction, C.toNativePointerArray(arguments, false, true), arguments.length, "");
LLVM.LLVMBuildRet(builder, returnCode);
LLVM.LLVMDisposeBuilder(builder);
}
private void buildStatement(Statement statement, Type returnType, LLVMBuilderRef builder, LLVMValueRef thisValue, Map<Variable, LLVMValueRef> variables,
Map<BreakableStatement, LLVMBasicBlockRef> breakBlocks, Map<BreakableStatement, LLVMBasicBlockRef> continueBlocks, Runnable returnVoidCallback)
{
if (statement instanceof AssignStatement)
{
AssignStatement assignStatement = (AssignStatement) statement;
Assignee[] assignees = assignStatement.getAssignees();
LLVMValueRef[] llvmAssigneePointers = new LLVMValueRef[assignees.length];
boolean[] standardTypeRepresentations = new boolean[assignees.length];
for (int i = 0; i < assignees.length; i++)
{
if (assignees[i] instanceof VariableAssignee)
{
Variable resolvedVariable = ((VariableAssignee) assignees[i]).getResolvedVariable();
if (resolvedVariable instanceof MemberVariable)
{
Field field = ((MemberVariable) resolvedVariable).getField();
llvmAssigneePointers[i] = typeHelper.getFieldPointer(builder, thisValue, field);
standardTypeRepresentations[i] = true;
}
else if (resolvedVariable instanceof GlobalVariable)
{
llvmAssigneePointers[i] = getGlobal((GlobalVariable) resolvedVariable);
standardTypeRepresentations[i] = true;
}
else
{
llvmAssigneePointers[i] = variables.get(resolvedVariable);
standardTypeRepresentations[i] = false;
}
}
else if (assignees[i] instanceof ArrayElementAssignee)
{
ArrayElementAssignee arrayElementAssignee = (ArrayElementAssignee) assignees[i];
LLVMValueRef array = buildExpression(arrayElementAssignee.getArrayExpression(), builder, thisValue, variables);
LLVMValueRef dimension = buildExpression(arrayElementAssignee.getDimensionExpression(), builder, thisValue, variables);
LLVMValueRef convertedDimension = typeHelper.convertTemporaryToStandard(builder, dimension, arrayElementAssignee.getDimensionExpression().getType(), ArrayLengthMember.ARRAY_LENGTH_TYPE);
llvmAssigneePointers[i] = typeHelper.getArrayElementPointer(builder, array, convertedDimension);
standardTypeRepresentations[i] = true;
}
else if (assignees[i] instanceof FieldAssignee)
{
FieldAssignee fieldAssignee = (FieldAssignee) assignees[i];
FieldAccessExpression fieldAccessExpression = fieldAssignee.getFieldAccessExpression();
if (fieldAccessExpression.getResolvedMember() instanceof Field)
{
Field field = (Field) fieldAccessExpression.getResolvedMember();
if (field.isStatic())
{
llvmAssigneePointers[i] = getGlobal(field.getGlobalVariable());
standardTypeRepresentations[i] = true;
}
else
{
LLVMValueRef expressionValue = buildExpression(fieldAccessExpression.getBaseExpression(), builder, thisValue, variables);
llvmAssigneePointers[i] = typeHelper.getFieldPointer(builder, expressionValue, field);
standardTypeRepresentations[i] = true;
}
}
else
{
throw new IllegalArgumentException("Unknown member assigned to in a FieldAssignee: " + fieldAccessExpression.getResolvedMember());
}
}
else if (assignees[i] instanceof BlankAssignee)
{
// this assignee doesn't actually get assigned to
llvmAssigneePointers[i] = null;
standardTypeRepresentations[i] = false;
}
else
{
throw new IllegalStateException("Unknown Assignee type: " + assignees[i]);
}
}
if (assignStatement.getExpression() != null)
{
LLVMValueRef value = buildExpression(assignStatement.getExpression(), builder, thisValue, variables);
if (llvmAssigneePointers.length == 1)
{
if (llvmAssigneePointers[0] != null)
{
LLVMValueRef convertedValue;
if (standardTypeRepresentations[0])
{
convertedValue = typeHelper.convertTemporaryToStandard(builder, value, assignStatement.getExpression().getType(), assignees[0].getResolvedType());
}
else
{
convertedValue = typeHelper.convertTemporary(builder, value, assignStatement.getExpression().getType(), assignees[0].getResolvedType());
}
// TODO: compound types should be copied here, rather than having their pointer copied
LLVM.LLVMBuildStore(builder, convertedValue, llvmAssigneePointers[0]);
}
}
else
{
if (assignStatement.getResolvedType().isNullable())
{
throw new IllegalStateException("An assign statement's type cannot be nullable if it is about to be split into multiple assignees");
}
Type[] expressionSubTypes = ((TupleType) assignStatement.getExpression().getType()).getSubTypes();
for (int i = 0; i < llvmAssigneePointers.length; i++)
{
if (llvmAssigneePointers[i] != null)
{
LLVMValueRef extracted = LLVM.LLVMBuildExtractValue(builder, value, i, "");
LLVMValueRef convertedValue;
if (standardTypeRepresentations[i])
{
convertedValue = typeHelper.convertTemporaryToStandard(builder, extracted, expressionSubTypes[i], assignees[i].getResolvedType());
}
else
{
convertedValue = typeHelper.convertTemporary(builder, extracted, expressionSubTypes[i], assignees[i].getResolvedType());
}
LLVM.LLVMBuildStore(builder, convertedValue, llvmAssigneePointers[i]);
}
}
}
}
}
else if (statement instanceof Block)
{
for (Statement s : ((Block) statement).getStatements())
{
buildStatement(s, returnType, builder, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback);
}
}
else if (statement instanceof BreakStatement)
{
LLVMBasicBlockRef block = breakBlocks.get(((BreakStatement) statement).getResolvedBreakable());
if (block == null)
{
throw new IllegalStateException("Break statement leads to a null block during code generation: " + statement);
}
LLVM.LLVMBuildBr(builder, block);
}
else if (statement instanceof ContinueStatement)
{
LLVMBasicBlockRef block = continueBlocks.get(((ContinueStatement) statement).getResolvedBreakable());
if (block == null)
{
throw new IllegalStateException("Continue statement leads to a null block during code generation: " + statement);
}
LLVM.LLVMBuildBr(builder, block);
}
else if (statement instanceof DelegateConstructorStatement)
{
DelegateConstructorStatement delegateConstructorStatement = (DelegateConstructorStatement) statement;
Constructor delegatedConstructor = delegateConstructorStatement.getResolvedConstructor();
Parameter[] parameters = delegatedConstructor.getParameters();
Expression[] arguments = delegateConstructorStatement.getArguments();
LLVMValueRef llvmConstructor = getConstructorFunction(delegatedConstructor);
LLVMValueRef[] llvmArguments = new LLVMValueRef[1 + parameters.length];
// convert the thisValue to the delegated constructor's type, since if this is a super(...) constructor, the native type representation will be different
llvmArguments[0] = typeHelper.convertTemporary(builder, thisValue, new NamedType(false, false, typeDefinition), new NamedType(false, false, delegatedConstructor.getContainingTypeDefinition()));
for (int i = 0; i < parameters.length; ++i)
{
LLVMValueRef argument = buildExpression(arguments[i], builder, thisValue, variables);
llvmArguments[1 + i] = typeHelper.convertTemporaryToStandard(builder, argument, arguments[i].getType(), parameters[i].getType());
}
LLVM.LLVMBuildCall(builder, llvmConstructor, C.toNativePointerArray(llvmArguments, false, true), llvmArguments.length, "");
if (delegateConstructorStatement.isSuperConstructor())
{
// call the non-static initialiser function, which runs all non-static initialisers and sets the initial values for all of the fields
// since, unlike a this(...) constructor, the super(...) constructor will not call this implicitly for us
LLVMValueRef initialiserFunction = getInitialiserFunction(false);
LLVMValueRef[] initialiserArgs = new LLVMValueRef[] {thisValue};
LLVM.LLVMBuildCall(builder, initialiserFunction, C.toNativePointerArray(initialiserArgs, false, true), initialiserArgs.length, "");
}
}
else if (statement instanceof ExpressionStatement)
{
buildExpression(((ExpressionStatement) statement).getExpression(), builder, thisValue, variables);
}
else if (statement instanceof ForStatement)
{
ForStatement forStatement = (ForStatement) statement;
Statement init = forStatement.getInitStatement();
if (init != null)
{
buildStatement(init, returnType, builder, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback);
}
Expression conditional = forStatement.getConditional();
Statement update = forStatement.getUpdateStatement();
// only generate a continuation block if there is a way to get out of the loop
LLVMBasicBlockRef continuationBlock = forStatement.stopsExecution() ? null : LLVM.LLVMAddBasicBlock(builder, "afterForLoop");
LLVMBasicBlockRef loopUpdate = update == null ? null : LLVM.LLVMAddBasicBlock(builder, "forLoopUpdate");
LLVMBasicBlockRef loopBody = LLVM.LLVMAddBasicBlock(builder, "forLoopBody");
LLVMBasicBlockRef loopCheck = conditional == null ? null : LLVM.LLVMAddBasicBlock(builder, "forLoopCheck");
if (conditional == null)
{
LLVM.LLVMBuildBr(builder, loopBody);
}
else
{
LLVM.LLVMBuildBr(builder, loopCheck);
LLVM.LLVMPositionBuilderAtEnd(builder, loopCheck);
LLVMValueRef conditionResult = buildExpression(conditional, builder, thisValue, variables);
conditionResult = typeHelper.convertTemporaryToStandard(builder, conditionResult, conditional.getType(), new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null));
LLVM.LLVMBuildCondBr(builder, conditionResult, loopBody, continuationBlock);
}
LLVM.LLVMPositionBuilderAtEnd(builder, loopBody);
if (continuationBlock != null)
{
breakBlocks.put(forStatement, continuationBlock);
}
continueBlocks.put(forStatement, loopUpdate == null ? (loopCheck == null ? loopBody : loopCheck) : loopUpdate);
buildStatement(forStatement.getBlock(), returnType, builder, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback);
if (!forStatement.getBlock().stopsExecution())
{
LLVM.LLVMBuildBr(builder, loopUpdate == null ? (loopCheck == null ? loopBody : loopCheck) : loopUpdate);
}
if (update != null)
{
LLVM.LLVMPositionBuilderAtEnd(builder, loopUpdate);
buildStatement(update, returnType, builder, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback);
if (update.stopsExecution())
{
throw new IllegalStateException("For loop update stops execution before the branch to the loop check: " + update);
}
LLVM.LLVMBuildBr(builder, loopCheck == null ? loopBody : loopCheck);
}
if (continuationBlock != null)
{
LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock);
}
}
else if (statement instanceof IfStatement)
{
IfStatement ifStatement = (IfStatement) statement;
LLVMValueRef conditional = buildExpression(ifStatement.getExpression(), builder, thisValue, variables);
conditional = typeHelper.convertTemporaryToStandard(builder, conditional, ifStatement.getExpression().getType(), new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null));
LLVMBasicBlockRef continuation = null;
if (!ifStatement.stopsExecution())
{
continuation = LLVM.LLVMAddBasicBlock(builder, "continuation");
}
LLVMBasicBlockRef elseClause = null;
if (ifStatement.getElseClause() != null)
{
elseClause = LLVM.LLVMAddBasicBlock(builder, "else");
}
LLVMBasicBlockRef thenClause = LLVM.LLVMAddBasicBlock(builder, "then");
// build the branch instruction
if (elseClause == null)
{
// if we have no else clause, then a continuation must have been created, since the if statement cannot stop execution
LLVM.LLVMBuildCondBr(builder, conditional, thenClause, continuation);
}
else
{
LLVM.LLVMBuildCondBr(builder, conditional, thenClause, elseClause);
// build the else clause
LLVM.LLVMPositionBuilderAtEnd(builder, elseClause);
buildStatement(ifStatement.getElseClause(), returnType, builder, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback);
if (!ifStatement.getElseClause().stopsExecution())
{
LLVM.LLVMBuildBr(builder, continuation);
}
}
// build the then clause
LLVM.LLVMPositionBuilderAtEnd(builder, thenClause);
buildStatement(ifStatement.getThenClause(), returnType, builder, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback);
if (!ifStatement.getThenClause().stopsExecution())
{
LLVM.LLVMBuildBr(builder, continuation);
}
if (continuation != null)
{
LLVM.LLVMPositionBuilderAtEnd(builder, continuation);
}
}
else if (statement instanceof PrefixIncDecStatement)
{
PrefixIncDecStatement prefixIncDecStatement = (PrefixIncDecStatement) statement;
Assignee assignee = prefixIncDecStatement.getAssignee();
LLVMValueRef pointer;
boolean standardTypeRepresentation = false;
if (assignee instanceof VariableAssignee)
{
Variable resolvedVariable = ((VariableAssignee) assignee).getResolvedVariable();
if (resolvedVariable instanceof MemberVariable)
{
Field field = ((MemberVariable) resolvedVariable).getField();
pointer = typeHelper.getFieldPointer(builder, thisValue, field);
standardTypeRepresentation = true;
}
else if (resolvedVariable instanceof GlobalVariable)
{
pointer = getGlobal((GlobalVariable) resolvedVariable);
standardTypeRepresentation = true;
}
else
{
pointer = variables.get(resolvedVariable);
standardTypeRepresentation = false;
}
}
else if (assignee instanceof ArrayElementAssignee)
{
ArrayElementAssignee arrayElementAssignee = (ArrayElementAssignee) assignee;
LLVMValueRef array = buildExpression(arrayElementAssignee.getArrayExpression(), builder, thisValue, variables);
LLVMValueRef dimension = buildExpression(arrayElementAssignee.getDimensionExpression(), builder, thisValue, variables);
LLVMValueRef convertedDimension = typeHelper.convertTemporaryToStandard(builder, dimension, arrayElementAssignee.getDimensionExpression().getType(), ArrayLengthMember.ARRAY_LENGTH_TYPE);
pointer = typeHelper.getArrayElementPointer(builder, array, convertedDimension);
standardTypeRepresentation = true;
}
else if (assignee instanceof FieldAssignee)
{
FieldAssignee fieldAssignee = (FieldAssignee) assignee;
FieldAccessExpression fieldAccessExpression = fieldAssignee.getFieldAccessExpression();
if (fieldAccessExpression.getResolvedMember() instanceof Field)
{
Field field = (Field) fieldAccessExpression.getResolvedMember();
if (field.isStatic())
{
pointer = getGlobal(field.getGlobalVariable());
standardTypeRepresentation = true;
}
else
{
LLVMValueRef expressionValue = buildExpression(fieldAccessExpression.getBaseExpression(), builder, thisValue, variables);
pointer = typeHelper.getFieldPointer(builder, expressionValue, field);
standardTypeRepresentation = true;
}
}
else
{
throw new IllegalArgumentException("Unknown member assigned to in a FieldAssignee: " + fieldAccessExpression.getResolvedMember());
}
}
else
{
// ignore blank assignees, they shouldn't be able to get through variable resolution
throw new IllegalStateException("Unknown Assignee type: " + assignee);
}
LLVMValueRef loaded = LLVM.LLVMBuildLoad(builder, pointer, "");
PrimitiveType type = (PrimitiveType) assignee.getResolvedType();
LLVMValueRef result;
if (type.getPrimitiveTypeType().isFloating())
{
LLVMValueRef one = LLVM.LLVMConstReal(typeHelper.findTemporaryType(type), 1);
if (prefixIncDecStatement.isIncrement())
{
result = LLVM.LLVMBuildFAdd(builder, loaded, one, "");
}
else
{
result = LLVM.LLVMBuildFSub(builder, loaded, one, "");
}
}
else
{
LLVMValueRef one = LLVM.LLVMConstInt(typeHelper.findTemporaryType(type), 1, false);
if (prefixIncDecStatement.isIncrement())
{
result = LLVM.LLVMBuildAdd(builder, loaded, one, "");
}
else
{
result = LLVM.LLVMBuildSub(builder, loaded, one, "");
}
}
if (standardTypeRepresentation)
{
result = typeHelper.convertTemporaryToStandard(builder, result, type);
}
LLVM.LLVMBuildStore(builder, result, pointer);
}
else if (statement instanceof ReturnStatement)
{
Expression returnedExpression = ((ReturnStatement) statement).getExpression();
if (returnedExpression == null)
{
returnVoidCallback.run();
}
else
{
LLVMValueRef value = buildExpression(returnedExpression, builder, thisValue, variables);
LLVMValueRef convertedValue = typeHelper.convertTemporaryToStandard(builder, value, returnedExpression.getType(), returnType);
LLVM.LLVMBuildRet(builder, convertedValue);
}
}
else if (statement instanceof ShorthandAssignStatement)
{
ShorthandAssignStatement shorthandAssignStatement = (ShorthandAssignStatement) statement;
Assignee[] assignees = shorthandAssignStatement.getAssignees();
LLVMValueRef[] llvmAssigneePointers = new LLVMValueRef[assignees.length];
boolean[] standardTypeRepresentations = new boolean[assignees.length];
for (int i = 0; i < assignees.length; ++i)
{
if (assignees[i] instanceof VariableAssignee)
{
Variable resolvedVariable = ((VariableAssignee) assignees[i]).getResolvedVariable();
if (resolvedVariable instanceof MemberVariable)
{
Field field = ((MemberVariable) resolvedVariable).getField();
llvmAssigneePointers[i] = typeHelper.getFieldPointer(builder, thisValue, field);
standardTypeRepresentations[i] = true;
}
else if (resolvedVariable instanceof GlobalVariable)
{
llvmAssigneePointers[i] = getGlobal((GlobalVariable) resolvedVariable);
standardTypeRepresentations[i] = true;
}
else
{
llvmAssigneePointers[i] = variables.get(resolvedVariable);
standardTypeRepresentations[i] = false;
}
}
else if (assignees[i] instanceof ArrayElementAssignee)
{
ArrayElementAssignee arrayElementAssignee = (ArrayElementAssignee) assignees[i];
LLVMValueRef array = buildExpression(arrayElementAssignee.getArrayExpression(), builder, thisValue, variables);
LLVMValueRef dimension = buildExpression(arrayElementAssignee.getDimensionExpression(), builder, thisValue, variables);
LLVMValueRef convertedDimension = typeHelper.convertTemporaryToStandard(builder, dimension, arrayElementAssignee.getDimensionExpression().getType(), ArrayLengthMember.ARRAY_LENGTH_TYPE);
llvmAssigneePointers[i] = typeHelper.getArrayElementPointer(builder, array, convertedDimension);
standardTypeRepresentations[i] = true;
}
else if (assignees[i] instanceof FieldAssignee)
{
FieldAssignee fieldAssignee = (FieldAssignee) assignees[i];
FieldAccessExpression fieldAccessExpression = fieldAssignee.getFieldAccessExpression();
if (fieldAccessExpression.getResolvedMember() instanceof Field)
{
Field field = (Field) fieldAccessExpression.getResolvedMember();
if (field.isStatic())
{
llvmAssigneePointers[i] = getGlobal(field.getGlobalVariable());
standardTypeRepresentations[i] = true;
}
else
{
LLVMValueRef expressionValue = buildExpression(fieldAccessExpression.getBaseExpression(), builder, thisValue, variables);
llvmAssigneePointers[i] = typeHelper.getFieldPointer(builder, expressionValue, field);
standardTypeRepresentations[i] = true;
}
}
else
{
throw new IllegalArgumentException("Unknown member assigned to in a FieldAssignee: " + fieldAccessExpression.getResolvedMember());
}
}
else if (assignees[i] instanceof BlankAssignee)
{
// this assignee doesn't actually get assigned to
llvmAssigneePointers[i] = null;
standardTypeRepresentations[i] = false;
}
else
{
throw new IllegalStateException("Unknown Assignee type: " + assignees[i]);
}
}
LLVMValueRef result = buildExpression(shorthandAssignStatement.getExpression(), builder, thisValue, variables);
Type resultType = shorthandAssignStatement.getExpression().getType();
LLVMValueRef[] resultValues = new LLVMValueRef[assignees.length];
Type[] resultValueTypes = new Type[assignees.length];
if (resultType instanceof TupleType && !resultType.isNullable() && ((TupleType) resultType).getSubTypes().length == assignees.length)
{
Type[] subTypes = ((TupleType) resultType).getSubTypes();
for (int i = 0; i < assignees.length; ++i)
{
if (assignees[i] instanceof BlankAssignee)
{
continue;
}
resultValues[i] = LLVM.LLVMBuildExtractValue(builder, result, i, "");
resultValueTypes[i] = subTypes[i];
}
}
else
{
for (int i = 0; i < assignees.length; ++i)
{
resultValues[i] = result;
resultValueTypes[i] = resultType;
}
}
for (int i = 0; i < assignees.length; ++i)
{
if (llvmAssigneePointers[i] == null)
{
// this is a blank assignee, so don't try to do anything for it
continue;
}
Type type = assignees[i].getResolvedType();
LLVMValueRef leftValue = LLVM.LLVMBuildLoad(builder, llvmAssigneePointers[i], "");
LLVMValueRef rightValue = typeHelper.convertTemporary(builder, resultValues[i], resultValueTypes[i], type);
LLVMValueRef assigneeResult;
if (shorthandAssignStatement.getOperator() == ShorthandAssignmentOperator.ADD && type.isEquivalent(SpecialTypeHandler.STRING_TYPE))
{
if (!standardTypeRepresentations[i])
{
leftValue = typeHelper.convertTemporaryToStandard(builder, leftValue, type);
}
rightValue = typeHelper.convertTemporaryToStandard(builder, rightValue, type);
assigneeResult = buildStringConcatenation(builder, leftValue, rightValue);
}
else if (type instanceof PrimitiveType)
{
if (standardTypeRepresentations[i])
{
leftValue = typeHelper.convertStandardToTemporary(builder, leftValue, type);
}
PrimitiveTypeType primitiveType = ((PrimitiveType) type).getPrimitiveTypeType();
boolean floating = primitiveType.isFloating();
boolean signed = primitiveType.isSigned();
switch (shorthandAssignStatement.getOperator())
{
case AND:
assigneeResult = LLVM.LLVMBuildAnd(builder, leftValue, rightValue, "");
break;
case OR:
assigneeResult = LLVM.LLVMBuildOr(builder, leftValue, rightValue, "");
break;
case XOR:
assigneeResult = LLVM.LLVMBuildXor(builder, leftValue, rightValue, "");
break;
case ADD:
assigneeResult = floating ? LLVM.LLVMBuildFAdd(builder, leftValue, rightValue, "") : LLVM.LLVMBuildAdd(builder, leftValue, rightValue, "");
break;
case SUBTRACT:
assigneeResult = floating ? LLVM.LLVMBuildFSub(builder, leftValue, rightValue, "") : LLVM.LLVMBuildSub(builder, leftValue, rightValue, "");
break;
case MULTIPLY:
assigneeResult = floating ? LLVM.LLVMBuildFMul(builder, leftValue, rightValue, "") : LLVM.LLVMBuildMul(builder, leftValue, rightValue, "");
break;
case DIVIDE:
assigneeResult = floating ? LLVM.LLVMBuildFDiv(builder, leftValue, rightValue, "") : signed ? LLVM.LLVMBuildSDiv(builder, leftValue, rightValue, "") : LLVM.LLVMBuildUDiv(builder, leftValue, rightValue, "");
break;
case REMAINDER:
assigneeResult = floating ? LLVM.LLVMBuildFRem(builder, leftValue, rightValue, "") : signed ? LLVM.LLVMBuildSRem(builder, leftValue, rightValue, "") : LLVM.LLVMBuildURem(builder, leftValue, rightValue, "");
break;
case MODULO:
if (floating)
{
LLVMValueRef rem = LLVM.LLVMBuildFRem(builder, leftValue, rightValue, "");
LLVMValueRef add = LLVM.LLVMBuildFAdd(builder, rem, rightValue, "");
assigneeResult = LLVM.LLVMBuildFRem(builder, add, rightValue, "");
}
else if (signed)
{
LLVMValueRef rem = LLVM.LLVMBuildSRem(builder, leftValue, rightValue, "");
LLVMValueRef add = LLVM.LLVMBuildAdd(builder, rem, rightValue, "");
assigneeResult = LLVM.LLVMBuildSRem(builder, add, rightValue, "");
}
else
{
// unsigned modulo is the same as unsigned remainder
assigneeResult = LLVM.LLVMBuildURem(builder, leftValue, rightValue, "");
}
break;
case LEFT_SHIFT:
assigneeResult = LLVM.LLVMBuildShl(builder, leftValue, rightValue, "");
break;
case RIGHT_SHIFT:
assigneeResult = signed ? LLVM.LLVMBuildAShr(builder, leftValue, rightValue, "") : LLVM.LLVMBuildLShr(builder, leftValue, rightValue, "");
break;
default:
throw new IllegalStateException("Unknown shorthand assignment operator: " + shorthandAssignStatement.getOperator());
}
}
else
{
throw new IllegalStateException("Unknown shorthand assignment operation: " + shorthandAssignStatement);
}
if (standardTypeRepresentations[i])
{
assigneeResult = typeHelper.convertTemporaryToStandard(builder, assigneeResult, type);
}
LLVM.LLVMBuildStore(builder, assigneeResult, llvmAssigneePointers[i]);
}
}
else if (statement instanceof WhileStatement)
{
WhileStatement whileStatement = (WhileStatement) statement;
LLVMBasicBlockRef afterLoopBlock = LLVM.LLVMAddBasicBlock(builder, "afterWhileLoop");
LLVMBasicBlockRef loopBodyBlock = LLVM.LLVMAddBasicBlock(builder, "whileLoopBody");
LLVMBasicBlockRef loopCheck = LLVM.LLVMAddBasicBlock(builder, "whileLoopCheck");
LLVM.LLVMBuildBr(builder, loopCheck);
LLVM.LLVMPositionBuilderAtEnd(builder, loopCheck);
LLVMValueRef conditional = buildExpression(whileStatement.getExpression(), builder, thisValue, variables);
conditional = typeHelper.convertTemporaryToStandard(builder, conditional, whileStatement.getExpression().getType(), new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null));
LLVM.LLVMBuildCondBr(builder, conditional, loopBodyBlock, afterLoopBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, loopBodyBlock);
// add the while statement's afterLoop block to the breakBlocks map before it's statement is built
breakBlocks.put(whileStatement, afterLoopBlock);
continueBlocks.put(whileStatement, loopCheck);
buildStatement(whileStatement.getStatement(), returnType, builder, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback);
if (!whileStatement.getStatement().stopsExecution())
{
LLVM.LLVMBuildBr(builder, loopCheck);
}
LLVM.LLVMPositionBuilderAtEnd(builder, afterLoopBlock);
}
}
private int getPredicate(EqualityOperator operator, boolean floating)
{
if (floating)
{
switch (operator)
{
case EQUAL:
return LLVM.LLVMRealPredicate.LLVMRealOEQ;
case NOT_EQUAL:
return LLVM.LLVMRealPredicate.LLVMRealONE;
}
}
else
{
switch (operator)
{
case EQUAL:
return LLVM.LLVMIntPredicate.LLVMIntEQ;
case NOT_EQUAL:
return LLVM.LLVMIntPredicate.LLVMIntNE;
}
}
throw new IllegalArgumentException("Unknown predicate '" + operator + "'");
}
private int getPredicate(RelationalOperator operator, boolean floating, boolean signed)
{
if (floating)
{
switch (operator)
{
case LESS_THAN:
return LLVM.LLVMRealPredicate.LLVMRealOLT;
case LESS_THAN_EQUAL:
return LLVM.LLVMRealPredicate.LLVMRealOLE;
case MORE_THAN:
return LLVM.LLVMRealPredicate.LLVMRealOGT;
case MORE_THAN_EQUAL:
return LLVM.LLVMRealPredicate.LLVMRealOGE;
}
}
else
{
switch (operator)
{
case LESS_THAN:
return signed ? LLVM.LLVMIntPredicate.LLVMIntSLT : LLVM.LLVMIntPredicate.LLVMIntULT;
case LESS_THAN_EQUAL:
return signed ? LLVM.LLVMIntPredicate.LLVMIntSLE : LLVM.LLVMIntPredicate.LLVMIntULE;
case MORE_THAN:
return signed ? LLVM.LLVMIntPredicate.LLVMIntSGT : LLVM.LLVMIntPredicate.LLVMIntUGT;
case MORE_THAN_EQUAL:
return signed ? LLVM.LLVMIntPredicate.LLVMIntSGE : LLVM.LLVMIntPredicate.LLVMIntUGE;
}
}
throw new IllegalArgumentException("Unknown predicate '" + operator + "'");
}
/**
* Builds code to create an array in the specified function, with the specified length(s) and type
* @param builder - the LLVMBuilderRef to build instructions with
* @param llvmLengths - the list of lengths of the array(s), each being a native uint.
* if the array is multidimensional, this should contain an element per dimension to be created
* @param type - the type of the array to create
* @return the pointer to the array to create, in a temporary type representation
*/
public LLVMValueRef buildArrayCreation(LLVMBuilderRef builder, LLVMValueRef[] llvmLengths, ArrayType type)
{
LLVMTypeRef llvmArrayType = typeHelper.findTemporaryType(type);
// find the element of our array at index length (i.e. one past the end of the array), which gives us our size
LLVMValueRef llvmArraySize = typeHelper.getArrayElementPointer(builder, LLVM.LLVMConstNull(llvmArrayType), llvmLengths[0]);
LLVMValueRef llvmSize = LLVM.LLVMBuildPtrToInt(builder, llvmArraySize, LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), "");
// call calloc to allocate the memory and initialise it to a string of zeros
LLVMValueRef[] arguments = new LLVMValueRef[] {llvmSize, LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false)};
LLVMValueRef memoryPointer = LLVM.LLVMBuildCall(builder, callocFunction, C.toNativePointerArray(arguments, false, true), arguments.length, "");
LLVMValueRef allocatedPointer = LLVM.LLVMBuildBitCast(builder, memoryPointer, llvmArrayType, "");
LLVMValueRef interfaceSearchList = virtualFunctionHandler.getEmptyInterfaceSearchList();
LLVMValueRef interfaceSearchListPointer = virtualFunctionHandler.getInterfaceSearchListPointer(builder, allocatedPointer);
LLVM.LLVMBuildStore(builder, interfaceSearchList, interfaceSearchListPointer);
LLVMValueRef vftPointer = virtualFunctionHandler.getFirstVirtualFunctionTablePointer(builder, allocatedPointer);
LLVMValueRef vft = virtualFunctionHandler.getBaseChangeObjectVFT(type);
LLVM.LLVMBuildStore(builder, vft, vftPointer);
LLVMValueRef sizeElementPointer = typeHelper.getArrayLengthPointer(builder, allocatedPointer);
LLVM.LLVMBuildStore(builder, llvmLengths[0], sizeElementPointer);
if (llvmLengths.length > 1)
{
// build a loop to create all of the elements of this array by recursively calling buildArrayCreation()
ArrayType subType = (ArrayType) type.getBaseType();
LLVMBasicBlockRef startBlock = LLVM.LLVMGetInsertBlock(builder);
LLVMBasicBlockRef exitBlock = LLVM.LLVMAddBasicBlock(builder, "arrayCreationEnd");
LLVMBasicBlockRef loopBlock = LLVM.LLVMAddBasicBlock(builder, "arrayCreation");
LLVMBasicBlockRef loopCheckBlock = LLVM.LLVMAddBasicBlock(builder, "arrayCreationCheck");
LLVM.LLVMBuildBr(builder, loopCheckBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, loopCheckBlock);
LLVMValueRef phiNode = LLVM.LLVMBuildPhi(builder, LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), "arrayCounter");
LLVMValueRef breakBoolean = LLVM.LLVMBuildICmp(builder, LLVM.LLVMIntPredicate.LLVMIntULT, phiNode, llvmLengths[0], "");
LLVM.LLVMBuildCondBr(builder, breakBoolean, loopBlock, exitBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, loopBlock);
// recurse to create this element of the array
LLVMValueRef[] subLengths = new LLVMValueRef[llvmLengths.length - 1];
System.arraycopy(llvmLengths, 1, subLengths, 0, subLengths.length);
LLVMValueRef subArray = buildArrayCreation(builder, subLengths, subType);
// store this array element
LLVMValueRef elementPointer = typeHelper.getArrayElementPointer(builder, allocatedPointer, phiNode);
LLVM.LLVMBuildStore(builder, subArray, elementPointer);
// add the incoming values to the phi node
LLVMValueRef nextCounterValue = LLVM.LLVMBuildAdd(builder, phiNode, LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false), "");
LLVMValueRef[] incomingValues = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), nextCounterValue};
LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {startBlock, LLVM.LLVMGetInsertBlock(builder)};
LLVM.LLVMAddIncoming(phiNode, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), 2);
LLVM.LLVMBuildBr(builder, loopCheckBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, exitBlock);
}
return allocatedPointer;
}
/**
* Builds the LLVM statements for a null check on the specified value.
* @param builder - the LLVMBuilderRef to build instructions with
* @param value - the LLVMValueRef to compare to null, in a temporary native representation
* @param type - the type of the specified LLVMValueRef
* @return an LLVMValueRef for an i1, which will be 1 if the value is non-null, and 0 if the value is null
*/
public LLVMValueRef buildNullCheck(LLVMBuilderRef builder, LLVMValueRef value, Type type)
{
if (!type.isNullable())
{
throw new IllegalArgumentException("A null check can only work on a nullable type");
}
if (type instanceof ArrayType)
{
return LLVM.LLVMBuildICmp(builder, LLVM.LLVMIntPredicate.LLVMIntNE, value, LLVM.LLVMConstNull(typeHelper.findTemporaryType(type)), "");
}
if (type instanceof FunctionType)
{
LLVMValueRef functionPointer = LLVM.LLVMBuildExtractValue(builder, value, 1, "");
LLVMTypeRef llvmFunctionPointerType = typeHelper.findRawFunctionPointerType((FunctionType) type);
return LLVM.LLVMBuildICmp(builder, LLVM.LLVMIntPredicate.LLVMIntNE, functionPointer, LLVM.LLVMConstNull(llvmFunctionPointerType), "");
}
if (type instanceof NamedType)
{
TypeDefinition typeDefinition = ((NamedType) type).getResolvedTypeDefinition();
if (typeDefinition instanceof ClassDefinition)
{
return LLVM.LLVMBuildIsNotNull(builder, value, "");
}
else if (typeDefinition instanceof CompoundDefinition)
{
// a compound type with a temporary native representation is a pointer which may or may not be null
return LLVM.LLVMBuildIsNotNull(builder, value, "");
}
else if (typeDefinition instanceof InterfaceDefinition)
{
// extract the object pointer from the interface representation, and check whether it is null
LLVMValueRef objectValue = LLVM.LLVMBuildExtractValue(builder, value, 1, "");
return LLVM.LLVMBuildIsNotNull(builder, objectValue, "");
}
}
if (type instanceof NullType)
{
return LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 0, false);
}
if (type instanceof PrimitiveType)
{
return LLVM.LLVMBuildExtractValue(builder, value, 0, "");
}
if (type instanceof TupleType)
{
return LLVM.LLVMBuildExtractValue(builder, value, 0, "");
}
throw new IllegalArgumentException("Cannot build a null check for the unrecognised type: " + type);
}
/**
* Builds the LLVM statements for an equality check between the specified two values, which are both of the specified type.
* The equality check either checks whether the values are equal, or not equal, depending on the EqualityOperator provided.
* @param left - the left LLVMValueRef in the comparison, in a temporary native representation
* @param right - the right LLVMValueRef in the comparison, in a temporary native representation
* @param type - the Type of both of the values - both of the values should be converted to this type before this function is called
* @param operator - the EqualityOperator which determines which way to compare the values (e.g. EQUAL results in a 1 iff the values are equal)
* @return an LLVMValueRef for an i1, which will be 1 if the check returns true, or 0 if the check returns false
*/
private LLVMValueRef buildEqualityCheck(LLVMBuilderRef builder, LLVMValueRef left, LLVMValueRef right, Type type, EqualityOperator operator)
{
if (type instanceof ArrayType)
{
return LLVM.LLVMBuildICmp(builder, getPredicate(operator, false), left, right, "");
}
if (type instanceof FunctionType)
{
LLVMValueRef leftOpaque = LLVM.LLVMBuildExtractValue(builder, left, 0, "");
LLVMValueRef rightOpaque = LLVM.LLVMBuildExtractValue(builder, right, 0, "");
LLVMValueRef opaqueComparison = LLVM.LLVMBuildICmp(builder, getPredicate(operator, false), leftOpaque, rightOpaque, "");
LLVMValueRef leftFunction = LLVM.LLVMBuildExtractValue(builder, left, 1, "");
LLVMValueRef rightFunction = LLVM.LLVMBuildExtractValue(builder, right, 1, "");
LLVMValueRef functionComparison = LLVM.LLVMBuildICmp(builder, getPredicate(operator, false), leftFunction, rightFunction, "");
if (operator == EqualityOperator.EQUAL)
{
return LLVM.LLVMBuildAnd(builder, opaqueComparison, functionComparison, "");
}
if (operator == EqualityOperator.NOT_EQUAL)
{
return LLVM.LLVMBuildOr(builder, opaqueComparison, functionComparison, "");
}
throw new IllegalArgumentException("Cannot build an equality check without a valid EqualityOperator");
}
if (type instanceof NamedType)
{
TypeDefinition typeDefinition = ((NamedType) type).getResolvedTypeDefinition();
if (typeDefinition instanceof ClassDefinition)
{
return LLVM.LLVMBuildICmp(builder, getPredicate(operator, false), left, right, "");
}
if (typeDefinition instanceof CompoundDefinition)
{
// we don't want to compare anything if one of the compound definitions is null, so we need to branch and only compare them if they are both not-null
LLVMValueRef nullityComparison = null;
LLVMBasicBlockRef startBlock = null;
LLVMBasicBlockRef finalBlock = null;
if (type.isNullable())
{
LLVMValueRef leftNullity = LLVM.LLVMBuildIsNotNull(builder, left, "");
LLVMValueRef rightNullity = LLVM.LLVMBuildIsNotNull(builder, right, "");
nullityComparison = LLVM.LLVMBuildICmp(builder, getPredicate(operator, false), leftNullity, rightNullity, "");
LLVMValueRef bothNotNull = LLVM.LLVMBuildAnd(builder, leftNullity, rightNullity, "");
startBlock = LLVM.LLVMGetInsertBlock(builder);
finalBlock = LLVM.LLVMAddBasicBlock(builder, "equality_final");
LLVMBasicBlockRef comparisonBlock = LLVM.LLVMAddBasicBlock(builder, "equality_comparevalues");
LLVM.LLVMBuildCondBr(builder, bothNotNull, comparisonBlock, finalBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, comparisonBlock);
}
// compare each of the fields from the left and right values
Field[] nonStaticFields = typeDefinition.getNonStaticFields();
LLVMValueRef[] compareResults = new LLVMValueRef[nonStaticFields.length];
for (int i = 0; i < nonStaticFields.length; ++i)
{
Type fieldType = nonStaticFields[i].getType();
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), i, false)};
LLVMValueRef leftField = LLVM.LLVMBuildGEP(builder, left, C.toNativePointerArray(indices, false, true), indices.length, "");
LLVMValueRef rightField = LLVM.LLVMBuildGEP(builder, right, C.toNativePointerArray(indices, false, true), indices.length, "");
LLVMValueRef leftValue = LLVM.LLVMBuildLoad(builder, leftField, "");
LLVMValueRef rightValue = LLVM.LLVMBuildLoad(builder, rightField, "");
leftValue = typeHelper.convertStandardToTemporary(builder, leftValue, fieldType);
rightValue = typeHelper.convertStandardToTemporary(builder, rightValue, fieldType);
compareResults[i] = buildEqualityCheck(builder, leftValue, rightValue, fieldType, operator);
}
// AND or OR the list together, using a binary tree
int multiple = 1;
while (multiple < nonStaticFields.length)
{
for (int i = 0; i < nonStaticFields.length; i += 2 * multiple)
{
LLVMValueRef first = compareResults[i];
if (i + multiple >= nonStaticFields.length)
{
continue;
}
LLVMValueRef second = compareResults[i + multiple];
LLVMValueRef result = null;
if (operator == EqualityOperator.EQUAL)
{
result = LLVM.LLVMBuildAnd(builder, first, second, "");
}
else if (operator == EqualityOperator.NOT_EQUAL)
{
result = LLVM.LLVMBuildOr(builder, first, second, "");
}
compareResults[i] = result;
}
multiple *= 2;
}
LLVMValueRef normalComparison = compareResults[0];
if (type.isNullable())
{
LLVMBasicBlockRef endComparisonBlock = LLVM.LLVMGetInsertBlock(builder);
LLVM.LLVMBuildBr(builder, finalBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, finalBlock);
LLVMValueRef phiNode = LLVM.LLVMBuildPhi(builder, LLVM.LLVMInt1Type(), "");
LLVMValueRef[] incomingValues = new LLVMValueRef[] {nullityComparison, normalComparison};
LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {startBlock, endComparisonBlock};
LLVM.LLVMAddIncoming(phiNode, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), incomingValues.length);
return phiNode;
}
return normalComparison;
}
if (typeDefinition instanceof InterfaceDefinition)
{
// extract the object pointer from each of the interface representations, and check whether they are equal
LLVMValueRef leftObject = LLVM.LLVMBuildExtractValue(builder, left, 1, "");
LLVMValueRef rightObject = LLVM.LLVMBuildExtractValue(builder, right, 1, "");
return LLVM.LLVMBuildICmp(builder, getPredicate(operator, false), leftObject, rightObject, "");
}
}
if (type instanceof PrimitiveType)
{
PrimitiveTypeType primitiveTypeType = ((PrimitiveType) type).getPrimitiveTypeType();
LLVMValueRef leftValue = left;
LLVMValueRef rightValue = right;
if (type.isNullable())
{
leftValue = LLVM.LLVMBuildExtractValue(builder, left, 1, "");
rightValue = LLVM.LLVMBuildExtractValue(builder, right, 1, "");
}
LLVMValueRef valueEqualityResult;
if (primitiveTypeType.isFloating())
{
valueEqualityResult = LLVM.LLVMBuildFCmp(builder, getPredicate(operator, true), leftValue, rightValue, "");
}
else
{
valueEqualityResult = LLVM.LLVMBuildICmp(builder, getPredicate(operator, false), leftValue, rightValue, "");
}
if (type.isNullable())
{
LLVMValueRef leftNullity = LLVM.LLVMBuildExtractValue(builder, left, 0, "");
LLVMValueRef rightNullity = LLVM.LLVMBuildExtractValue(builder, right, 0, "");
LLVMValueRef bothNotNull = LLVM.LLVMBuildAnd(builder, leftNullity, rightNullity, "");
LLVMValueRef notNullAndValueResult = LLVM.LLVMBuildAnd(builder, bothNotNull, valueEqualityResult, "");
LLVMValueRef nullityComparison;
if (operator == EqualityOperator.EQUAL)
{
nullityComparison = LLVM.LLVMBuildNot(builder, LLVM.LLVMBuildOr(builder, leftNullity, rightNullity, ""), "");
}
else
{
nullityComparison = LLVM.LLVMBuildXor(builder, leftNullity, rightNullity, "");
}
return LLVM.LLVMBuildOr(builder, notNullAndValueResult, nullityComparison, "");
}
return valueEqualityResult;
}
if (type instanceof TupleType)
{
// we don't want to compare anything if one of the tuples is null, so we need to branch and only compare them if they are both not-null
LLVMValueRef nullityComparison = null;
LLVMBasicBlockRef startBlock = null;
LLVMBasicBlockRef finalBlock = null;
LLVMValueRef leftNotNull = left;
LLVMValueRef rightNotNull = right;
if (type.isNullable())
{
LLVMValueRef leftNullity = LLVM.LLVMBuildExtractValue(builder, left, 0, "");
LLVMValueRef rightNullity = LLVM.LLVMBuildExtractValue(builder, right, 0, "");
nullityComparison = LLVM.LLVMBuildICmp(builder, getPredicate(operator, false), leftNullity, rightNullity, "");
LLVMValueRef bothNotNull = LLVM.LLVMBuildAnd(builder, leftNullity, rightNullity, "");
startBlock = LLVM.LLVMGetInsertBlock(builder);
finalBlock = LLVM.LLVMAddBasicBlock(builder, "equality_final");
LLVMBasicBlockRef comparisonBlock = LLVM.LLVMAddBasicBlock(builder, "equality_comparevalues");
LLVM.LLVMBuildCondBr(builder, bothNotNull, comparisonBlock, finalBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, comparisonBlock);
leftNotNull = LLVM.LLVMBuildExtractValue(builder, left, 1, "");
rightNotNull = LLVM.LLVMBuildExtractValue(builder, right, 1, "");
}
// compare each of the fields from the left and right values
Type[] subTypes = ((TupleType) type).getSubTypes();
LLVMValueRef[] compareResults = new LLVMValueRef[subTypes.length];
for (int i = 0; i < subTypes.length; ++i)
{
Type subType = subTypes[i];
LLVMValueRef leftValue = LLVM.LLVMBuildExtractValue(builder, leftNotNull, i, "");
LLVMValueRef rightValue = LLVM.LLVMBuildExtractValue(builder, rightNotNull, i, "");
compareResults[i] = buildEqualityCheck(builder, leftValue, rightValue, subType, operator);
}
// AND or OR the list together, using a binary tree
int multiple = 1;
while (multiple < subTypes.length)
{
for (int i = 0; i < subTypes.length; i += 2 * multiple)
{
LLVMValueRef first = compareResults[i];
if (i + multiple >= subTypes.length)
{
continue;
}
LLVMValueRef second = compareResults[i + multiple];
LLVMValueRef result = null;
if (operator == EqualityOperator.EQUAL)
{
result = LLVM.LLVMBuildAnd(builder, first, second, "");
}
else if (operator == EqualityOperator.NOT_EQUAL)
{
result = LLVM.LLVMBuildOr(builder, first, second, "");
}
compareResults[i] = result;
}
multiple *= 2;
}
LLVMValueRef normalComparison = compareResults[0];
if (type.isNullable())
{
LLVMBasicBlockRef endComparisonBlock = LLVM.LLVMGetInsertBlock(builder);
LLVM.LLVMBuildBr(builder, finalBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, finalBlock);
LLVMValueRef phiNode = LLVM.LLVMBuildPhi(builder, LLVM.LLVMInt1Type(), "");
LLVMValueRef[] incomingValues = new LLVMValueRef[] {nullityComparison, normalComparison};
LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {startBlock, endComparisonBlock};
LLVM.LLVMAddIncoming(phiNode, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), incomingValues.length);
return phiNode;
}
return normalComparison;
}
throw new IllegalArgumentException("Cannot compare two values of type '" + type + "' for equality");
}
private LLVMValueRef buildExpression(Expression expression, LLVMBuilderRef builder, LLVMValueRef thisValue, Map<Variable, LLVMValueRef> variables)
{
if (expression instanceof ArithmeticExpression)
{
ArithmeticExpression arithmeticExpression = (ArithmeticExpression) expression;
LLVMValueRef left = buildExpression(arithmeticExpression.getLeftSubExpression(), builder, thisValue, variables);
LLVMValueRef right = buildExpression(arithmeticExpression.getRightSubExpression(), builder, thisValue, variables);
Type leftType = arithmeticExpression.getLeftSubExpression().getType();
Type rightType = arithmeticExpression.getRightSubExpression().getType();
Type resultType = arithmeticExpression.getType();
// cast if necessary
left = typeHelper.convertTemporary(builder, left, leftType, resultType);
right = typeHelper.convertTemporary(builder, right, rightType, resultType);
if (arithmeticExpression.getOperator() == ArithmeticOperator.ADD && resultType.isEquivalent(SpecialTypeHandler.STRING_TYPE))
{
LLVMValueRef leftString = typeHelper.convertTemporaryToStandard(builder, left, resultType);
LLVMValueRef rightString = typeHelper.convertTemporaryToStandard(builder, right, resultType);
LLVMValueRef result = buildStringConcatenation(builder, leftString, rightString);
return typeHelper.convertTemporary(builder, result, SpecialTypeHandler.STRING_TYPE, resultType);
}
boolean floating = ((PrimitiveType) resultType).getPrimitiveTypeType().isFloating();
boolean signed = ((PrimitiveType) resultType).getPrimitiveTypeType().isSigned();
switch (arithmeticExpression.getOperator())
{
case ADD:
return floating ? LLVM.LLVMBuildFAdd(builder, left, right, "") : LLVM.LLVMBuildAdd(builder, left, right, "");
case SUBTRACT:
return floating ? LLVM.LLVMBuildFSub(builder, left, right, "") : LLVM.LLVMBuildSub(builder, left, right, "");
case MULTIPLY:
return floating ? LLVM.LLVMBuildFMul(builder, left, right, "") : LLVM.LLVMBuildMul(builder, left, right, "");
case DIVIDE:
return floating ? LLVM.LLVMBuildFDiv(builder, left, right, "") : signed ? LLVM.LLVMBuildSDiv(builder, left, right, "") : LLVM.LLVMBuildUDiv(builder, left, right, "");
case REMAINDER:
return floating ? LLVM.LLVMBuildFRem(builder, left, right, "") : signed ? LLVM.LLVMBuildSRem(builder, left, right, "") : LLVM.LLVMBuildURem(builder, left, right, "");
case MODULO:
if (floating)
{
LLVMValueRef rem = LLVM.LLVMBuildFRem(builder, left, right, "");
LLVMValueRef add = LLVM.LLVMBuildFAdd(builder, rem, right, "");
return LLVM.LLVMBuildFRem(builder, add, right, "");
}
if (signed)
{
LLVMValueRef rem = LLVM.LLVMBuildSRem(builder, left, right, "");
LLVMValueRef add = LLVM.LLVMBuildAdd(builder, rem, right, "");
return LLVM.LLVMBuildSRem(builder, add, right, "");
}
// unsigned modulo is the same as unsigned remainder
return LLVM.LLVMBuildURem(builder, left, right, "");
}
throw new IllegalArgumentException("Unknown arithmetic operator: " + arithmeticExpression.getOperator());
}
if (expression instanceof ArrayAccessExpression)
{
ArrayAccessExpression arrayAccessExpression = (ArrayAccessExpression) expression;
LLVMValueRef arrayValue = buildExpression(arrayAccessExpression.getArrayExpression(), builder, thisValue, variables);
LLVMValueRef dimensionValue = buildExpression(arrayAccessExpression.getDimensionExpression(), builder, thisValue, variables);
LLVMValueRef convertedDimensionValue = typeHelper.convertTemporaryToStandard(builder, dimensionValue, arrayAccessExpression.getDimensionExpression().getType(), ArrayLengthMember.ARRAY_LENGTH_TYPE);
LLVMValueRef elementPointer = typeHelper.getArrayElementPointer(builder, arrayValue, convertedDimensionValue);
ArrayType arrayType = (ArrayType) arrayAccessExpression.getArrayExpression().getType();
return typeHelper.convertStandardPointerToTemporary(builder, elementPointer, arrayType.getBaseType(), arrayAccessExpression.getType());
}
if (expression instanceof ArrayCreationExpression)
{
ArrayCreationExpression arrayCreationExpression = (ArrayCreationExpression) expression;
ArrayType type = arrayCreationExpression.getDeclaredType();
Expression[] dimensionExpressions = arrayCreationExpression.getDimensionExpressions();
if (dimensionExpressions == null)
{
Expression[] valueExpressions = arrayCreationExpression.getValueExpressions();
LLVMValueRef llvmLength = LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), valueExpressions.length, false);
LLVMValueRef array = buildArrayCreation(builder, new LLVMValueRef[] {llvmLength}, type);
for (int i = 0; i < valueExpressions.length; i++)
{
LLVMValueRef expressionValue = buildExpression(valueExpressions[i], builder, thisValue, variables);
LLVMValueRef convertedValue = typeHelper.convertTemporaryToStandard(builder, expressionValue, valueExpressions[i].getType(), type.getBaseType());
LLVMValueRef elementPointer = typeHelper.getArrayElementPointer(builder, array, LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), i, false));
LLVM.LLVMBuildStore(builder, convertedValue, elementPointer);
}
return typeHelper.convertTemporary(builder, array, type, arrayCreationExpression.getType());
}
LLVMValueRef[] llvmLengths = new LLVMValueRef[dimensionExpressions.length];
for (int i = 0; i < llvmLengths.length; i++)
{
LLVMValueRef expressionValue = buildExpression(dimensionExpressions[i], builder, thisValue, variables);
llvmLengths[i] = typeHelper.convertTemporaryToStandard(builder, expressionValue, dimensionExpressions[i].getType(), ArrayLengthMember.ARRAY_LENGTH_TYPE);
}
LLVMValueRef array = buildArrayCreation(builder, llvmLengths, type);
return typeHelper.convertTemporary(builder, array, type, arrayCreationExpression.getType());
}
if (expression instanceof BitwiseNotExpression)
{
LLVMValueRef value = buildExpression(((BitwiseNotExpression) expression).getExpression(), builder, thisValue, variables);
value = typeHelper.convertTemporary(builder, value, ((BitwiseNotExpression) expression).getExpression().getType(), expression.getType());
return LLVM.LLVMBuildNot(builder, value, "");
}
if (expression instanceof BooleanLiteralExpression)
{
LLVMValueRef value = LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), ((BooleanLiteralExpression) expression).getValue() ? 1 : 0, false);
return typeHelper.convertStandardToTemporary(builder, value, new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null), expression.getType());
}
if (expression instanceof BooleanNotExpression)
{
LLVMValueRef value = buildExpression(((BooleanNotExpression) expression).getExpression(), builder, thisValue, variables);
LLVMValueRef result = LLVM.LLVMBuildNot(builder, value, "");
return typeHelper.convertTemporary(builder, result, ((BooleanNotExpression) expression).getExpression().getType(), expression.getType());
}
if (expression instanceof BracketedExpression)
{
BracketedExpression bracketedExpression = (BracketedExpression) expression;
LLVMValueRef value = buildExpression(bracketedExpression.getExpression(), builder, thisValue, variables);
return typeHelper.convertTemporary(builder, value, bracketedExpression.getExpression().getType(), expression.getType());
}
if (expression instanceof CastExpression)
{
CastExpression castExpression = (CastExpression) expression;
LLVMValueRef value = buildExpression(castExpression.getExpression(), builder, thisValue, variables);
return typeHelper.convertTemporary(builder, value, castExpression.getExpression().getType(), castExpression.getType());
}
if (expression instanceof ClassCreationExpression)
{
ClassCreationExpression classCreationExpression = (ClassCreationExpression) expression;
Expression[] arguments = classCreationExpression.getArguments();
Constructor constructor = classCreationExpression.getResolvedConstructor();
Parameter[] parameters = constructor.getParameters();
LLVMValueRef[] llvmArguments = new LLVMValueRef[1 + arguments.length];
for (int i = 0; i < arguments.length; ++i)
{
LLVMValueRef argument = buildExpression(arguments[i], builder, thisValue, variables);
llvmArguments[i + 1] = typeHelper.convertTemporaryToStandard(builder, argument, arguments[i].getType(), parameters[i].getType());
}
Type type = classCreationExpression.getType();
if (!(type instanceof NamedType) || !(((NamedType) type).getResolvedTypeDefinition() instanceof ClassDefinition))
{
throw new IllegalStateException("A class creation expression must be for a class type");
}
ClassDefinition classDefinition = (ClassDefinition) ((NamedType) type).getResolvedTypeDefinition();
LLVMValueRef[] allocatorArgs = new LLVMValueRef[0];
LLVMValueRef pointer = LLVM.LLVMBuildCall(builder, getAllocatorFunction(classDefinition), C.toNativePointerArray(allocatorArgs, false, true), allocatorArgs.length, "");
llvmArguments[0] = pointer;
// get the constructor and call it
LLVMValueRef llvmFunc = getConstructorFunction(constructor);
LLVM.LLVMBuildCall(builder, llvmFunc, C.toNativePointerArray(llvmArguments, false, true), llvmArguments.length, "");
return pointer;
}
if (expression instanceof EqualityExpression)
{
EqualityExpression equalityExpression = (EqualityExpression) expression;
EqualityOperator operator = equalityExpression.getOperator();
// if the type checker has annotated this as a null check, just perform it without building both sub-expressions
Expression nullCheckExpression = equalityExpression.getNullCheckExpression();
if (nullCheckExpression != null)
{
LLVMValueRef value = buildExpression(nullCheckExpression, builder, thisValue, variables);
LLVMValueRef convertedValue = typeHelper.convertTemporary(builder, value, nullCheckExpression.getType(), equalityExpression.getComparisonType());
LLVMValueRef nullity = buildNullCheck(builder, convertedValue, equalityExpression.getComparisonType());
switch (operator)
{
case EQUAL:
return LLVM.LLVMBuildNot(builder, nullity, "");
case NOT_EQUAL:
return nullity;
default:
throw new IllegalArgumentException("Cannot build an EqualityExpression with no EqualityOperator");
}
}
LLVMValueRef left = buildExpression(equalityExpression.getLeftSubExpression(), builder, thisValue, variables);
LLVMValueRef right = buildExpression(equalityExpression.getRightSubExpression(), builder, thisValue, variables);
Type leftType = equalityExpression.getLeftSubExpression().getType();
Type rightType = equalityExpression.getRightSubExpression().getType();
Type comparisonType = equalityExpression.getComparisonType();
// if comparisonType is null, then the types are integers which cannot be assigned to each other either way around, because one is signed and the other is unsigned
// so we must extend each of them to a larger bitCount which they can both fit into, and compare them there
if (comparisonType == null)
{
if (!(leftType instanceof PrimitiveType) || !(rightType instanceof PrimitiveType))
{
throw new IllegalStateException("A comparison type must be provided if either the left or right type is not a PrimitiveType: " + equalityExpression);
}
LLVMValueRef leftIsNotNull = LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false);
LLVMValueRef rightIsNotNull = LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false);
LLVMValueRef leftValue = left;
LLVMValueRef rightValue = right;
if (leftType.isNullable())
{
leftIsNotNull = LLVM.LLVMBuildExtractValue(builder, left, 0, "");
leftValue = LLVM.LLVMBuildExtractValue(builder, left, 1, "");
}
if (rightType.isNullable())
{
rightIsNotNull = LLVM.LLVMBuildExtractValue(builder, right, 0, "");
rightValue = LLVM.LLVMBuildExtractValue(builder, right, 1, "");
}
PrimitiveTypeType leftTypeType = ((PrimitiveType) leftType).getPrimitiveTypeType();
PrimitiveTypeType rightTypeType = ((PrimitiveType) rightType).getPrimitiveTypeType();
if (!leftTypeType.isFloating() && !rightTypeType.isFloating() &&
leftTypeType.isSigned() != rightTypeType.isSigned())
{
// compare the signed and non-signed integers as (bitCount + 1) bit numbers, since they will not fit in bitCount bits
int bitCount = Math.max(leftTypeType.getBitCount(), rightTypeType.getBitCount()) + 1;
LLVMTypeRef llvmComparisonType = LLVM.LLVMIntType(bitCount);
if (leftTypeType.isSigned())
{
leftValue = LLVM.LLVMBuildSExt(builder, leftValue, llvmComparisonType, "");
rightValue = LLVM.LLVMBuildZExt(builder, rightValue, llvmComparisonType, "");
}
else
{
leftValue = LLVM.LLVMBuildZExt(builder, leftValue, llvmComparisonType, "");
rightValue = LLVM.LLVMBuildSExt(builder, rightValue, llvmComparisonType, "");
}
LLVMValueRef comparisonResult = LLVM.LLVMBuildICmp(builder, getPredicate(equalityExpression.getOperator(), false), leftValue, rightValue, "");
if (leftType.isNullable() || rightType.isNullable())
{
LLVMValueRef nullityComparison = LLVM.LLVMBuildICmp(builder, getPredicate(equalityExpression.getOperator(), false), leftIsNotNull, rightIsNotNull, "");
if (equalityExpression.getOperator() == EqualityOperator.EQUAL)
{
comparisonResult = LLVM.LLVMBuildAnd(builder, nullityComparison, comparisonResult, "");
}
else
{
comparisonResult = LLVM.LLVMBuildOr(builder, nullityComparison, comparisonResult, "");
}
}
return typeHelper.convertTemporary(builder, comparisonResult, new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null), equalityExpression.getType());
}
throw new IllegalArgumentException("Unknown result type, unable to generate comparison expression: " + equalityExpression);
}
// perform a standard equality check, using buildEqualityCheck()
left = typeHelper.convertTemporary(builder, left, leftType, comparisonType);
right = typeHelper.convertTemporary(builder, right, rightType, comparisonType);
return buildEqualityCheck(builder, left, right, comparisonType, operator);
}
if (expression instanceof FieldAccessExpression)
{
FieldAccessExpression fieldAccessExpression = (FieldAccessExpression) expression;
Member member = fieldAccessExpression.getResolvedMember();
Expression baseExpression = fieldAccessExpression.getBaseExpression();
if (baseExpression != null)
{
LLVMValueRef baseValue = buildExpression(baseExpression, builder, thisValue, variables);
Type notNullType = baseExpression.getType();
LLVMValueRef notNullValue = baseValue;
LLVMBasicBlockRef startBlock = null;
LLVMBasicBlockRef continuationBlock = null;
if (fieldAccessExpression.isNullTraversing())
{
LLVMValueRef nullCheckResult = buildNullCheck(builder, baseValue, baseExpression.getType());
continuationBlock = LLVM.LLVMAddBasicBlock(builder, "nullTraversalContinuation");
LLVMBasicBlockRef accessBlock = LLVM.LLVMAddBasicBlock(builder, "nullTraversalAccess");
startBlock = LLVM.LLVMGetInsertBlock(builder);
LLVM.LLVMBuildCondBr(builder, nullCheckResult, accessBlock, continuationBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, accessBlock);
notNullType = TypeChecker.findTypeWithNullability(baseExpression.getType(), false);
notNullValue = typeHelper.convertTemporary(builder, baseValue, baseExpression.getType(), notNullType);
}
LLVMValueRef result;
if (member instanceof ArrayLengthMember)
{
LLVMValueRef elementPointer = typeHelper.getArrayLengthPointer(builder, notNullValue);
result = LLVM.LLVMBuildLoad(builder, elementPointer, "");
result = typeHelper.convertStandardToTemporary(builder, result, ArrayLengthMember.ARRAY_LENGTH_TYPE, fieldAccessExpression.getType());
}
else if (member instanceof Field)
{
Field field = (Field) member;
if (field.isStatic())
{
throw new IllegalStateException("A FieldAccessExpression for a static field should not have a base expression");
}
LLVMValueRef fieldPointer = typeHelper.getFieldPointer(builder, notNullValue, field);
result = typeHelper.convertStandardPointerToTemporary(builder, fieldPointer, field.getType(), fieldAccessExpression.getType());
}
else if (member instanceof Method)
{
Method method = (Method) member;
Parameter[] parameters = method.getParameters();
Type[] parameterTypes = new Type[parameters.length];
for (int i = 0; i < parameters.length; ++i)
{
parameterTypes[i] = parameters[i].getType();
}
FunctionType functionType = new FunctionType(false, method.isImmutable(), method.getReturnType(), parameterTypes, null);
if (method.isStatic())
{
throw new IllegalStateException("A FieldAccessExpression for a static method should not have a base expression");
}
LLVMValueRef function;
if (notNullType instanceof ObjectType ||
(notNullType instanceof NamedType && ((NamedType) notNullType).getResolvedTypeDefinition() instanceof ClassDefinition) ||
(notNullType instanceof NamedType && ((NamedType) notNullType).getResolvedTypeDefinition() instanceof InterfaceDefinition) ||
notNullType instanceof ArrayType)
{
function = lookupMethodFunction(builder, notNullValue, notNullType, method);
}
else
{
function = typeHelper.getBaseChangeFunction(method);
}
function = LLVM.LLVMBuildBitCast(builder, function, typeHelper.findRawFunctionPointerType(functionType), "");
Type objectType = new ObjectType(false, false, null);
LLVMValueRef firstArgument = typeHelper.convertTemporary(builder, notNullValue, notNullType, objectType);
firstArgument = LLVM.LLVMBuildBitCast(builder, firstArgument, typeHelper.getOpaquePointer(), "");
result = LLVM.LLVMGetUndef(typeHelper.findStandardType(functionType));
result = LLVM.LLVMBuildInsertValue(builder, result, firstArgument, 0, "");
result = LLVM.LLVMBuildInsertValue(builder, result, function, 1, "");
result = typeHelper.convertStandardToTemporary(builder, result, functionType, fieldAccessExpression.getType());
}
else
{
throw new IllegalArgumentException("Unknown member type for a FieldAccessExpression: " + member);
}
if (fieldAccessExpression.isNullTraversing())
{
LLVMBasicBlockRef accessBlock = LLVM.LLVMGetInsertBlock(builder);
LLVM.LLVMBuildBr(builder, continuationBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock);
LLVMValueRef phiNode = LLVM.LLVMBuildPhi(builder, typeHelper.findTemporaryType(fieldAccessExpression.getType()), "");
LLVMValueRef nullAlternative = LLVM.LLVMConstNull(typeHelper.findTemporaryType(fieldAccessExpression.getType()));
LLVMValueRef[] phiValues = new LLVMValueRef[] {result, nullAlternative};
LLVMBasicBlockRef[] phiBlocks = new LLVMBasicBlockRef[] {accessBlock, startBlock};
LLVM.LLVMAddIncoming(phiNode, C.toNativePointerArray(phiValues, false, true), C.toNativePointerArray(phiBlocks, false, true), phiValues.length);
return phiNode;
}
return result;
}
// we don't have a base expression, so handle the static field accesses
if (member instanceof Field)
{
Field field = (Field) member;
if (!field.isStatic())
{
throw new IllegalStateException("A FieldAccessExpression for a non-static field should have a base expression");
}
LLVMValueRef global = getGlobal(field.getGlobalVariable());
return typeHelper.convertStandardPointerToTemporary(builder, global, field.getType(), fieldAccessExpression.getType());
}
if (member instanceof Method)
{
Method method = (Method) member;
if (!method.isStatic())
{
throw new IllegalStateException("A FieldAccessExpression for a non-static method should have a base expression");
}
Parameter[] parameters = method.getParameters();
Type[] parameterTypes = new Type[parameters.length];
for (int i = 0; i < parameters.length; ++i)
{
parameterTypes[i] = parameters[i].getType();
}
FunctionType functionType = new FunctionType(false, method.isImmutable(), method.getReturnType(), parameterTypes, null);
LLVMValueRef function = getMethodFunction(method);
function = LLVM.LLVMBuildBitCast(builder, function, typeHelper.findRawFunctionPointerType(functionType), "");
LLVMValueRef firstArgument = LLVM.LLVMConstNull(typeHelper.getOpaquePointer());
LLVMValueRef result = LLVM.LLVMGetUndef(typeHelper.findStandardType(functionType));
result = LLVM.LLVMBuildInsertValue(builder, result, firstArgument, 0, "");
result = LLVM.LLVMBuildInsertValue(builder, result, function, 1, "");
return typeHelper.convertStandardToTemporary(builder, result, functionType, fieldAccessExpression.getType());
}
throw new IllegalArgumentException("Unknown member type for a FieldAccessExpression: " + member);
}
if (expression instanceof FloatingLiteralExpression)
{
double value = Double.parseDouble(((FloatingLiteralExpression) expression).getLiteral().toString());
LLVMValueRef llvmValue = LLVM.LLVMConstReal(typeHelper.findStandardType(TypeChecker.findTypeWithNullability(expression.getType(), false)), value);
return typeHelper.convertStandardToTemporary(builder, llvmValue, TypeChecker.findTypeWithNullability(expression.getType(), false), expression.getType());
}
if (expression instanceof FunctionCallExpression)
{
FunctionCallExpression functionExpression = (FunctionCallExpression) expression;
Constructor resolvedConstructor = functionExpression.getResolvedConstructor();
Method resolvedMethod = functionExpression.getResolvedMethod();
Expression resolvedBaseExpression = functionExpression.getResolvedBaseExpression();
Type[] parameterTypes;
Type returnType;
if (resolvedConstructor != null)
{
Parameter[] params = resolvedConstructor.getParameters();
parameterTypes = new Type[params.length];
for (int i = 0; i < params.length; ++i)
{
parameterTypes[i] = params[i].getType();
}
returnType = new NamedType(false, false, resolvedConstructor.getContainingTypeDefinition());
}
else if (resolvedMethod != null)
{
Parameter[] params = resolvedMethod.getParameters();
parameterTypes = new Type[params.length];
for (int i = 0; i < params.length; ++i)
{
parameterTypes[i] = params[i].getType();
}
returnType = resolvedMethod.getReturnType();
}
else if (resolvedBaseExpression != null)
{
FunctionType baseType = (FunctionType) resolvedBaseExpression.getType();
parameterTypes = baseType.getParameterTypes();
returnType = baseType.getReturnType();
}
else
{
throw new IllegalArgumentException("Unresolved function call expression: " + functionExpression);
}
LLVMValueRef callee = null;
Type calleeType = null;
if (resolvedBaseExpression != null)
{
callee = buildExpression(resolvedBaseExpression, builder, thisValue, variables);
calleeType = resolvedBaseExpression.getType();
}
// if this is a null traversing function call, apply it properly
boolean nullTraversal = resolvedBaseExpression != null && resolvedMethod != null && functionExpression.getResolvedNullTraversal();
LLVMValueRef notNullCallee = callee;
LLVMBasicBlockRef startBlock = null;
LLVMBasicBlockRef continuationBlock = null;
if (nullTraversal)
{
LLVMValueRef nullCheckResult = buildNullCheck(builder, callee, resolvedBaseExpression.getType());
continuationBlock = LLVM.LLVMAddBasicBlock(builder, "nullTraversalCallContinuation");
LLVMBasicBlockRef callBlock = LLVM.LLVMAddBasicBlock(builder, "nullTraversalCall");
startBlock = LLVM.LLVMGetInsertBlock(builder);
LLVM.LLVMBuildCondBr(builder, nullCheckResult, callBlock, continuationBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, callBlock);
calleeType = TypeChecker.findTypeWithNullability(resolvedBaseExpression.getType(), false);
notNullCallee = typeHelper.convertTemporary(builder, callee, resolvedBaseExpression.getType(), calleeType);
}
Expression[] arguments = functionExpression.getArguments();
LLVMValueRef[] values = new LLVMValueRef[arguments.length];
for (int i = 0; i < arguments.length; i++)
{
LLVMValueRef arg = buildExpression(arguments[i], builder, thisValue, variables);
values[i] = typeHelper.convertTemporaryToStandard(builder, arg, arguments[i].getType(), parameterTypes[i]);
}
LLVMValueRef result;
boolean resultIsTemporary = false; // true iff result has a temporary type representation
if (resolvedConstructor != null)
{
// find the type to alloca, which is the standard representation of a non-nullable type
// when we alloca this type, it becomes equivalent to the temporary type representation of this compound type (with any nullability)
LLVMTypeRef allocaBaseType = typeHelper.findStandardType(returnType);
LLVMValueRef alloca = LLVM.LLVMBuildAllocaInEntryBlock(builder, allocaBaseType, "");
typeHelper.initialiseCompoundType(builder, (CompoundDefinition) ((NamedType) returnType).getResolvedTypeDefinition(), alloca);
LLVMValueRef[] realArguments = new LLVMValueRef[1 + values.length];
realArguments[0] = alloca;
System.arraycopy(values, 0, realArguments, 1, values.length);
LLVMValueRef llvmResolvedFunction = getConstructorFunction(resolvedConstructor);
LLVM.LLVMBuildCall(builder, llvmResolvedFunction, C.toNativePointerArray(realArguments, false, true), realArguments.length, "");
result = alloca;
resultIsTemporary = true;
}
else if (resolvedMethod != null)
{
LLVMValueRef[] realArguments = new LLVMValueRef[values.length + 1];
System.arraycopy(values, 0, realArguments, 1, values.length);
if (resolvedMethod.isStatic())
{
realArguments[0] = LLVM.LLVMConstNull(typeHelper.getOpaquePointer());
}
else
{
calleeType = calleeType != null ? calleeType : new NamedType(false, false, typeDefinition);
realArguments[0] = notNullCallee != null ? notNullCallee : thisValue;
}
// converting the callee can change the type of the callee, so look up the method's function first (while we know the type)
LLVMValueRef llvmResolvedFunction = lookupMethodFunction(builder, realArguments[0], calleeType, resolvedMethod);
realArguments[0] = typeHelper.convertMethodCallee(builder, realArguments[0], calleeType, resolvedMethod);
result = LLVM.LLVMBuildCall(builder, llvmResolvedFunction, C.toNativePointerArray(realArguments, false, true), realArguments.length, "");
}
else if (resolvedBaseExpression != null)
{
// callee here is actually a tuple of an opaque pointer and a function type, where the first argument to the function is the opaque pointer
LLVMValueRef firstArgument = LLVM.LLVMBuildExtractValue(builder, callee, 0, "");
LLVMValueRef calleeFunction = LLVM.LLVMBuildExtractValue(builder, callee, 1, "");
LLVMValueRef[] realArguments = new LLVMValueRef[values.length + 1];
realArguments[0] = firstArgument;
System.arraycopy(values, 0, realArguments, 1, values.length);
result = LLVM.LLVMBuildCall(builder, calleeFunction, C.toNativePointerArray(realArguments, false, true), realArguments.length, "");
}
else
{
throw new IllegalArgumentException("Unresolved function call expression: " + functionExpression);
}
if (nullTraversal)
{
if (returnType instanceof VoidType)
{
LLVM.LLVMBuildBr(builder, continuationBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock);
return null;
}
if (resultIsTemporary)
{
result = typeHelper.convertTemporary(builder, result, returnType, functionExpression.getType());
}
else
{
result = typeHelper.convertStandardToTemporary(builder, result, returnType, functionExpression.getType());
}
LLVMBasicBlockRef callBlock = LLVM.LLVMGetInsertBlock(builder);
LLVM.LLVMBuildBr(builder, continuationBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock);
LLVMValueRef phiNode = LLVM.LLVMBuildPhi(builder, typeHelper.findTemporaryType(functionExpression.getType()), "");
LLVMValueRef nullAlternative = LLVM.LLVMConstNull(typeHelper.findTemporaryType(functionExpression.getType()));
LLVMValueRef[] phiValues = new LLVMValueRef[] {result, nullAlternative};
LLVMBasicBlockRef[] phiBlocks = new LLVMBasicBlockRef[] {callBlock, startBlock};
LLVM.LLVMAddIncoming(phiNode, C.toNativePointerArray(phiValues, false, true), C.toNativePointerArray(phiBlocks, false, true), phiValues.length);
return phiNode;
}
if (returnType instanceof VoidType)
{
return result;
}
if (resultIsTemporary)
{
return typeHelper.convertTemporary(builder, result, returnType, functionExpression.getType());
}
return typeHelper.convertStandardToTemporary(builder, result, returnType, functionExpression.getType());
}
if (expression instanceof InlineIfExpression)
{
InlineIfExpression inlineIf = (InlineIfExpression) expression;
LLVMValueRef conditionValue = buildExpression(inlineIf.getCondition(), builder, thisValue, variables);
conditionValue = typeHelper.convertTemporaryToStandard(builder, conditionValue, inlineIf.getCondition().getType(), new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null));
LLVMBasicBlockRef continuationBlock = LLVM.LLVMAddBasicBlock(builder, "afterInlineIf");
LLVMBasicBlockRef elseBlock = LLVM.LLVMAddBasicBlock(builder, "inlineIfElse");
LLVMBasicBlockRef thenBlock = LLVM.LLVMAddBasicBlock(builder, "inlineIfThen");
LLVM.LLVMBuildCondBr(builder, conditionValue, thenBlock, elseBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, thenBlock);
LLVMValueRef thenValue = buildExpression(inlineIf.getThenExpression(), builder, thisValue, variables);
LLVMValueRef convertedThenValue = typeHelper.convertTemporary(builder, thenValue, inlineIf.getThenExpression().getType(), inlineIf.getType());
LLVMBasicBlockRef thenBranchBlock = LLVM.LLVMGetInsertBlock(builder);
LLVM.LLVMBuildBr(builder, continuationBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, elseBlock);
LLVMValueRef elseValue = buildExpression(inlineIf.getElseExpression(), builder, thisValue, variables);
LLVMValueRef convertedElseValue = typeHelper.convertTemporary(builder, elseValue, inlineIf.getElseExpression().getType(), inlineIf.getType());
LLVMBasicBlockRef elseBranchBlock = LLVM.LLVMGetInsertBlock(builder);
LLVM.LLVMBuildBr(builder, continuationBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock);
LLVMValueRef result = LLVM.LLVMBuildPhi(builder, typeHelper.findTemporaryType(inlineIf.getType()), "");
LLVMValueRef[] incomingValues = new LLVMValueRef[] {convertedThenValue, convertedElseValue};
LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {thenBranchBlock, elseBranchBlock};
LLVM.LLVMAddIncoming(result, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), 2);
return result;
}
if (expression instanceof IntegerLiteralExpression)
{
BigInteger bigintValue = ((IntegerLiteralExpression) expression).getLiteral().getValue();
byte[] bytes = bigintValue.toByteArray();
// convert the big-endian byte[] from the BigInteger into a little-endian long[] for LLVM
long[] longs = new long[(bytes.length + 7) / 8];
for (int i = 0; i < bytes.length; ++i)
{
int longIndex = (bytes.length - 1 - i) / 8;
int longBitPos = ((bytes.length - 1 - i) % 8) * 8;
longs[longIndex] |= (((long) bytes[i]) & 0xff) << longBitPos;
}
LLVMValueRef value = LLVM.LLVMConstIntOfArbitraryPrecision(typeHelper.findStandardType(TypeChecker.findTypeWithNullability(expression.getType(), false)), longs.length, longs);
return typeHelper.convertStandardToTemporary(builder, value, TypeChecker.findTypeWithNullability(expression.getType(), false), expression.getType());
}
if (expression instanceof LogicalExpression)
{
LogicalExpression logicalExpression = (LogicalExpression) expression;
LLVMValueRef left = buildExpression(logicalExpression.getLeftSubExpression(), builder, thisValue, variables);
PrimitiveType leftType = (PrimitiveType) logicalExpression.getLeftSubExpression().getType();
PrimitiveType rightType = (PrimitiveType) logicalExpression.getRightSubExpression().getType();
// cast if necessary
PrimitiveType resultType = (PrimitiveType) logicalExpression.getType();
left = typeHelper.convertTemporary(builder, left, leftType, resultType);
LogicalOperator operator = logicalExpression.getOperator();
if (operator != LogicalOperator.SHORT_CIRCUIT_AND && operator != LogicalOperator.SHORT_CIRCUIT_OR)
{
LLVMValueRef right = buildExpression(logicalExpression.getRightSubExpression(), builder, thisValue, variables);
right = typeHelper.convertTemporary(builder, right, rightType, resultType);
switch (operator)
{
case AND:
return LLVM.LLVMBuildAnd(builder, left, right, "");
case OR:
return LLVM.LLVMBuildOr(builder, left, right, "");
case XOR:
return LLVM.LLVMBuildXor(builder, left, right, "");
default:
throw new IllegalStateException("Unexpected non-short-circuit operator: " + logicalExpression.getOperator());
}
}
LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder);
LLVMBasicBlockRef continuationBlock = LLVM.LLVMAddBasicBlock(builder, "shortCircuitContinue");
LLVMBasicBlockRef rightCheckBlock = LLVM.LLVMAddBasicBlock(builder, "shortCircuitCheck");
// the only difference between short circuit AND and OR is whether they jump to the check block when the left hand side is true or false
LLVMBasicBlockRef trueDest = operator == LogicalOperator.SHORT_CIRCUIT_AND ? rightCheckBlock : continuationBlock;
LLVMBasicBlockRef falseDest = operator == LogicalOperator.SHORT_CIRCUIT_AND ? continuationBlock : rightCheckBlock;
LLVM.LLVMBuildCondBr(builder, left, trueDest, falseDest);
LLVM.LLVMPositionBuilderAtEnd(builder, rightCheckBlock);
LLVMValueRef right = buildExpression(logicalExpression.getRightSubExpression(), builder, thisValue, variables);
right = typeHelper.convertTemporary(builder, right, rightType, resultType);
LLVM.LLVMBuildBr(builder, continuationBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock);
// create a phi node for the result, and return it
LLVMValueRef phi = LLVM.LLVMBuildPhi(builder, typeHelper.findTemporaryType(resultType), "");
LLVMValueRef[] incomingValues = new LLVMValueRef[] {left, right};
LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {currentBlock, rightCheckBlock};
LLVM.LLVMAddIncoming(phi, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), 2);
return phi;
}
if (expression instanceof MinusExpression)
{
MinusExpression minusExpression = (MinusExpression) expression;
LLVMValueRef value = buildExpression(minusExpression.getExpression(), builder, thisValue, variables);
value = typeHelper.convertTemporary(builder, value, minusExpression.getExpression().getType(), TypeChecker.findTypeWithNullability(minusExpression.getType(), false));
PrimitiveTypeType primitiveTypeType = ((PrimitiveType) minusExpression.getType()).getPrimitiveTypeType();
LLVMValueRef result;
if (primitiveTypeType.isFloating())
{
result = LLVM.LLVMBuildFNeg(builder, value, "");
}
else
{
result = LLVM.LLVMBuildNeg(builder, value, "");
}
return typeHelper.convertTemporary(builder, result, TypeChecker.findTypeWithNullability(minusExpression.getType(), false), minusExpression.getType());
}
if (expression instanceof NullCoalescingExpression)
{
NullCoalescingExpression nullCoalescingExpression = (NullCoalescingExpression) expression;
LLVMValueRef nullableValue = buildExpression(nullCoalescingExpression.getNullableExpression(), builder, thisValue, variables);
nullableValue = typeHelper.convertTemporary(builder, nullableValue, nullCoalescingExpression.getNullableExpression().getType(), TypeChecker.findTypeWithNullability(nullCoalescingExpression.getType(), true));
LLVMValueRef checkResult = buildNullCheck(builder, nullableValue, TypeChecker.findTypeWithNullability(nullCoalescingExpression.getType(), true));
LLVMBasicBlockRef continuationBlock = LLVM.LLVMAddBasicBlock(builder, "nullCoalescingContinuation");
LLVMBasicBlockRef alternativeBlock = LLVM.LLVMAddBasicBlock(builder, "nullCoalescingAlternative");
LLVMBasicBlockRef conversionBlock = LLVM.LLVMAddBasicBlock(builder, "nullCoalescingConversion");
LLVM.LLVMBuildCondBr(builder, checkResult, conversionBlock, alternativeBlock);
// create a block to convert the nullable value into a non-nullable value
LLVM.LLVMPositionBuilderAtEnd(builder, conversionBlock);
LLVMValueRef convertedNullableValue = typeHelper.convertTemporary(builder, nullableValue, TypeChecker.findTypeWithNullability(nullCoalescingExpression.getType(), true), nullCoalescingExpression.getType());
LLVMBasicBlockRef endConversionBlock = LLVM.LLVMGetInsertBlock(builder);
LLVM.LLVMBuildBr(builder, continuationBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, alternativeBlock);
LLVMValueRef alternativeValue = buildExpression(nullCoalescingExpression.getAlternativeExpression(), builder, thisValue, variables);
alternativeValue = typeHelper.convertTemporary(builder, alternativeValue, nullCoalescingExpression.getAlternativeExpression().getType(), nullCoalescingExpression.getType());
LLVMBasicBlockRef endAlternativeBlock = LLVM.LLVMGetInsertBlock(builder);
LLVM.LLVMBuildBr(builder, continuationBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock);
// create a phi node for the result, and return it
LLVMTypeRef resultType = typeHelper.findTemporaryType(nullCoalescingExpression.getType());
LLVMValueRef result = LLVM.LLVMBuildPhi(builder, resultType, "");
LLVMValueRef[] incomingValues = new LLVMValueRef[] {convertedNullableValue, alternativeValue};
LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {endConversionBlock, endAlternativeBlock};
LLVM.LLVMAddIncoming(result, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), incomingValues.length);
return result;
}
if (expression instanceof NullLiteralExpression)
{
Type type = expression.getType();
return LLVM.LLVMConstNull(typeHelper.findTemporaryType(type));
}
if (expression instanceof ObjectCreationExpression)
{
ObjectType objectType = new ObjectType(false, false, null);
LLVMTypeRef nativeType = typeHelper.findStandardType(objectType);
// allocate memory for the object
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false)};
LLVMValueRef llvmStructSize = LLVM.LLVMBuildGEP(builder, LLVM.LLVMConstNull(nativeType), C.toNativePointerArray(indices, false, true), indices.length, "");
LLVMValueRef llvmSize = LLVM.LLVMBuildPtrToInt(builder, llvmStructSize, LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), "");
LLVMValueRef[] callocArguments = new LLVMValueRef[] {llvmSize, LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false)};
LLVMValueRef memory = LLVM.LLVMBuildCall(builder, callocFunction, C.toNativePointerArray(callocArguments, false, true), callocArguments.length, "");
LLVMValueRef pointer = LLVM.LLVMBuildBitCast(builder, memory, nativeType, "");
// store the VFT
LLVMValueRef interfaceSearchList = virtualFunctionHandler.getEmptyInterfaceSearchList();
LLVMValueRef interfaceSearchListPointer = virtualFunctionHandler.getInterfaceSearchListPointer(builder, pointer);
LLVM.LLVMBuildStore(builder, interfaceSearchList, interfaceSearchListPointer);
LLVMValueRef objectVFT = virtualFunctionHandler.getObjectVFTGlobal();
LLVMValueRef vftElementPointer = virtualFunctionHandler.getFirstVirtualFunctionTablePointer(builder, pointer);
LLVM.LLVMBuildStore(builder, objectVFT, vftElementPointer);
return typeHelper.convertStandardToTemporary(builder, pointer, objectType);
}
if (expression instanceof RelationalExpression)
{
RelationalExpression relationalExpression = (RelationalExpression) expression;
LLVMValueRef left = buildExpression(relationalExpression.getLeftSubExpression(), builder, thisValue, variables);
LLVMValueRef right = buildExpression(relationalExpression.getRightSubExpression(), builder, thisValue, variables);
PrimitiveType leftType = (PrimitiveType) relationalExpression.getLeftSubExpression().getType();
PrimitiveType rightType = (PrimitiveType) relationalExpression.getRightSubExpression().getType();
// cast if necessary
PrimitiveType resultType = relationalExpression.getComparisonType();
if (resultType == null)
{
PrimitiveTypeType leftTypeType = leftType.getPrimitiveTypeType();
PrimitiveTypeType rightTypeType = rightType.getPrimitiveTypeType();
if (!leftTypeType.isFloating() && !rightTypeType.isFloating() &&
leftTypeType.isSigned() != rightTypeType.isSigned() &&
!leftType.isNullable() && !rightType.isNullable())
{
// compare the signed and non-signed integers as (bitCount + 1) bit numbers, since they will not fit in bitCount bits
int bitCount = Math.max(leftTypeType.getBitCount(), rightTypeType.getBitCount()) + 1;
LLVMTypeRef comparisonType = LLVM.LLVMIntType(bitCount);
if (leftTypeType.isSigned())
{
left = LLVM.LLVMBuildSExt(builder, left, comparisonType, "");
right = LLVM.LLVMBuildZExt(builder, right, comparisonType, "");
}
else
{
left = LLVM.LLVMBuildZExt(builder, left, comparisonType, "");
right = LLVM.LLVMBuildSExt(builder, right, comparisonType, "");
}
return LLVM.LLVMBuildICmp(builder, getPredicate(relationalExpression.getOperator(), false, true), left, right, "");
}
throw new IllegalArgumentException("Unknown result type, unable to generate comparison expression: " + expression);
}
left = typeHelper.convertTemporary(builder, left, leftType, resultType);
right = typeHelper.convertTemporary(builder, right, rightType, resultType);
LLVMValueRef result;
if (resultType.getPrimitiveTypeType().isFloating())
{
result = LLVM.LLVMBuildFCmp(builder, getPredicate(relationalExpression.getOperator(), true, true), left, right, "");
}
else
{
result = LLVM.LLVMBuildICmp(builder, getPredicate(relationalExpression.getOperator(), false, resultType.getPrimitiveTypeType().isSigned()), left, right, "");
}
return typeHelper.convertTemporary(builder, result, new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null), relationalExpression.getType());
}
if (expression instanceof ShiftExpression)
{
ShiftExpression shiftExpression = (ShiftExpression) expression;
LLVMValueRef leftValue = buildExpression(shiftExpression.getLeftExpression(), builder, thisValue, variables);
LLVMValueRef rightValue = buildExpression(shiftExpression.getRightExpression(), builder, thisValue, variables);
LLVMValueRef convertedLeft = typeHelper.convertTemporary(builder, leftValue, shiftExpression.getLeftExpression().getType(), shiftExpression.getType());
LLVMValueRef convertedRight = typeHelper.convertTemporary(builder, rightValue, shiftExpression.getRightExpression().getType(), shiftExpression.getType());
switch (shiftExpression.getOperator())
{
case RIGHT_SHIFT:
if (((PrimitiveType) shiftExpression.getType()).getPrimitiveTypeType().isSigned())
{
return LLVM.LLVMBuildAShr(builder, convertedLeft, convertedRight, "");
}
return LLVM.LLVMBuildLShr(builder, convertedLeft, convertedRight, "");
case LEFT_SHIFT:
return LLVM.LLVMBuildShl(builder, convertedLeft, convertedRight, "");
}
throw new IllegalArgumentException("Unknown shift operator: " + shiftExpression.getOperator());
}
if (expression instanceof StringLiteralExpression)
{
StringLiteralExpression stringLiteralExpression = (StringLiteralExpression) expression;
String value = stringLiteralExpression.getLiteral().getLiteralValue();
LLVMValueRef llvmString = buildStringCreation(builder, value);
return typeHelper.convertTemporary(builder, llvmString, new NamedType(false, false, SpecialTypeHandler.stringArrayConstructor.getContainingTypeDefinition()), expression.getType());
}
if (expression instanceof ThisExpression)
{
// the 'this' value always has a temporary representation
return thisValue;
}
if (expression instanceof TupleExpression)
{
TupleExpression tupleExpression = (TupleExpression) expression;
Type[] tupleTypes = ((TupleType) tupleExpression.getType()).getSubTypes();
Expression[] subExpressions = tupleExpression.getSubExpressions();
Type nonNullableTupleType = TypeChecker.findTypeWithNullability(tupleExpression.getType(), false);
LLVMValueRef currentValue = LLVM.LLVMGetUndef(typeHelper.findTemporaryType(nonNullableTupleType));
for (int i = 0; i < subExpressions.length; i++)
{
LLVMValueRef value = buildExpression(subExpressions[i], builder, thisValue, variables);
Type type = tupleTypes[i];
value = typeHelper.convertTemporary(builder, value, subExpressions[i].getType(), type);
currentValue = LLVM.LLVMBuildInsertValue(builder, currentValue, value, i, "");
}
return typeHelper.convertTemporary(builder, currentValue, nonNullableTupleType, tupleExpression.getType());
}
if (expression instanceof TupleIndexExpression)
{
TupleIndexExpression tupleIndexExpression = (TupleIndexExpression) expression;
TupleType tupleType = (TupleType) tupleIndexExpression.getExpression().getType();
LLVMValueRef result = buildExpression(tupleIndexExpression.getExpression(), builder, thisValue, variables);
// convert the 1-based indexing to 0-based before extracting the value
int index = tupleIndexExpression.getIndexLiteral().getValue().intValue() - 1;
LLVMValueRef value = LLVM.LLVMBuildExtractValue(builder, result, index, "");
return typeHelper.convertTemporary(builder, value, tupleType.getSubTypes()[index], tupleIndexExpression.getType());
}
if (expression instanceof VariableExpression)
{
VariableExpression variableExpression = (VariableExpression) expression;
Variable variable = variableExpression.getResolvedVariable();
if (variable != null)
{
if (variable instanceof MemberVariable)
{
Field field = ((MemberVariable) variable).getField();
LLVMValueRef fieldPointer = typeHelper.getFieldPointer(builder, thisValue, field);
return typeHelper.convertStandardPointerToTemporary(builder, fieldPointer, variable.getType(), variableExpression.getType());
}
if (variable instanceof GlobalVariable)
{
LLVMValueRef global = getGlobal((GlobalVariable) variable);
return typeHelper.convertStandardPointerToTemporary(builder, global, variable.getType(), variableExpression.getType());
}
LLVMValueRef value = variables.get(variable);
if (value == null)
{
throw new IllegalStateException("Missing LLVMValueRef in variable Map: " + variableExpression.getName());
}
return LLVM.LLVMBuildLoad(builder, value, "");
}
Method method = variableExpression.getResolvedMethod();
if (method != null)
{
Parameter[] parameters = method.getParameters();
Type[] parameterTypes = new Type[parameters.length];
for (int i = 0; i < parameters.length; ++i)
{
parameterTypes[i] = parameters[i].getType();
}
FunctionType functionType = new FunctionType(false, method.isImmutable(), method.getReturnType(), parameterTypes, null);
LLVMValueRef callee = method.isStatic() ? LLVM.LLVMConstNull(typeHelper.getOpaquePointer()) : thisValue;
Type calleeType = method.isStatic() ? null : new NamedType(false, false, typeDefinition);
LLVMValueRef function = lookupMethodFunction(builder, callee, calleeType, method);
function = LLVM.LLVMBuildBitCast(builder, function, typeHelper.findRawFunctionPointerType(functionType), "");
LLVMValueRef firstArgument = typeHelper.convertMethodCallee(builder, callee, calleeType, method);
firstArgument = LLVM.LLVMBuildBitCast(builder, firstArgument, typeHelper.getOpaquePointer(), "");
LLVMValueRef result = LLVM.LLVMGetUndef(typeHelper.findStandardType(functionType));
result = LLVM.LLVMBuildInsertValue(builder, result, firstArgument, 0, "");
result = LLVM.LLVMBuildInsertValue(builder, result, function, 1, "");
return typeHelper.convertStandardToTemporary(builder, result, functionType, variableExpression.getType());
}
}
throw new IllegalArgumentException("Unknown Expression type: " + expression);
}
}
|
package gov.nih.nci.caintegrator.application.analysis;
import gov.nih.nci.caintegrator.analysis.messaging.DataPoint;
import gov.nih.nci.caintegrator.analysis.messaging.DataPointVector;
import gov.nih.nci.caintegrator.analysis.messaging.ExpressionLookupRequest;
import gov.nih.nci.caintegrator.analysis.messaging.ReporterGroup;
import gov.nih.nci.caintegrator.analysis.messaging.SampleGroup;
import gov.nih.nci.caintegrator.application.cache.BusinessTierCache;
import gov.nih.nci.caintegrator.application.cache.CacheFactory;
import gov.nih.nci.caintegrator.enumeration.FindingStatus;
import gov.nih.nci.caintegrator.service.findings.ExpressionLookupFinding;
import gov.nih.nci.caintegrator.service.findings.Finding;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import javax.jms.JMSException;
import javax.naming.NamingException;
import org.apache.log4j.Logger;
/**
* This class provides some helper methods for making synchronous calls to the analysis server
* functions. The analysis server is asynchronous so the methods in this class are requrired to transform
* them into synchronous calls.
* @author harrismic
*
*/
public class AnalysisHelper {
private static Logger logger = Logger.getLogger(AnalysisHelper.class);
private static void loadTestVec(DataPointVector vec, SampleGroup samples, boolean log) {
DataPoint dp;
for (String sample : samples) {
dp = new DataPoint(sample);
if (log) {
dp.setX(Math.random()+15.0);
}
else {
dp.setX(Math.random()*6000.0);
}
vec.addDataPoint(dp);
}
}
// public static void main(String[] args) {
// System.out.println("Hi");
// SampleGroup sg = new SampleGroup("Grp1");
// sg.add("001");
// sg.add("002");
// sg.add("003");
// sg.add("004");
// ExpressionLookupFinding f = getExpressionValuesForGeneSymbol("EGFR", "rbinsample.txt", sg, false);
// public static ExpressionLookupFinding getExpressionValuesForGeneSymbol(String geneSymbol,String rbinaryFileName,SampleGroup samples, boolean computeLogValue) {
// String sessionId = new Long(System.currentTimeMillis()).toString();
// String taskId = sessionId + "_1";
// //Dummy Result for now.
// ExpressionLookupFinding luf = new ExpressionLookupFinding("1","1", FindingStatus.Completed);
// DataPointVector v1 = new DataPointVector("15678_at");
// loadTestVec(v1, samples, computeLogValue);
// luf.addDataPointVector(v1);
// DataPointVector v2 = new DataPointVector("15679_at");
// loadTestVec(v2, samples, computeLogValue);
// luf.addDataPointVector(v2);
// DataPointVector v3 = new DataPointVector("15680_at");
// loadTestVec(v3, samples, computeLogValue);
// luf.addDataPointVector(v3);
// DataPointVector v4 = new DataPointVector("15690_at");
// loadTestVec(v4, samples, computeLogValue);
// luf.addDataPointVector(v4);
// DataPointVector v5 = new DataPointVector("15695_at");
// loadTestVec(v5, samples, computeLogValue);
// luf.addDataPointVector(v5);
// return luf;
// //RembrandtFindingsFactory factory = new RembrandtFindingsFactory();
// Finding finding = null;
// try {
// AnalysisServerClientManager mgr = AnalysisServerClientManager.getInstance();
// mgr.sendRequest(elr);
// while(finding.getStatus() == FindingStatus.Running){
// finding = businessTierCache.getSessionFinding(finding.getSessionId(),finding.getTaskId());
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// logger.error(e);
// return finding;
// ExpressionLookupResult result = new ExpressionLookupResult(sessionId, taskId);
// return result;
// } catch (Exception ex) {
// ExpressionLookupResult result = new ExpressionLookupResult("1", "1");
// DataPointVector vec = new DataPointVector("ExpressionValues");
// DataPoint p = new Data
// vec.addDataPoint()
// result.setDataPoints(dataPoints);
// return result;
public static List<ExpressionLookupFinding> getExpressionValuesForReporters(ReporterGroup reporters, String rbinaryFileName, List<SampleGroup> sampleGroups) {
List<ExpressionLookupFinding> findings = new ArrayList<ExpressionLookupFinding>();
ExpressionLookupFinding finding = null;
for (SampleGroup sampleGroup : sampleGroups) {
finding = getExpressionValuesForReporters(reporters, rbinaryFileName, sampleGroup);
findings.add(finding);
}
return findings;
}
public static ExpressionLookupFinding getExpressionValuesForReporters(ReporterGroup reporters,String rbinaryFileName,SampleGroup samples, String sessionId) {
Finding finding = null;
try {
AnalysisServerClientManager as = AnalysisServerClientManager.getInstance();
String taskId = new Long(System.currentTimeMillis()).toString();
ExpressionLookupRequest lookupReq = new ExpressionLookupRequest(sessionId, taskId);
ExpressionLookupFinding elf = new ExpressionLookupFinding(sessionId,taskId, FindingStatus.Running);
BusinessTierCache btcache = CacheFactory.getBusinessTierCache();
btcache.addToSessionCache(sessionId, taskId, elf);
as.setCache(btcache);
lookupReq.setReporters(reporters);
lookupReq.setSamples(samples);
lookupReq.setDataFileName(rbinaryFileName);
as.sendRequest(lookupReq);
finding = btcache.getSessionFinding(sessionId, taskId);
while(finding.getStatus() == FindingStatus.Running){
finding = btcache.getSessionFinding(sessionId,taskId);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
logger.error(e);
}
}
}
catch (NamingException e) {
// TODO Auto-generated catch block
logException(e);
} catch (JMSException e) {
// TODO Auto-generated catch block
logException(e);
}
catch (Exception e) {
logException(e);
}
return (ExpressionLookupFinding) finding;
}
public static ExpressionLookupFinding getExpressionValuesForReporters(ReporterGroup reporters,String rbinaryFileName,SampleGroup samples) {
Finding finding = null;
try {
AnalysisServerClientManager as = AnalysisServerClientManager.getInstance();
String sessionId = new Long(System.currentTimeMillis()).toString();
String taskId = new Long(System.currentTimeMillis()).toString();
ExpressionLookupRequest lookupReq = new ExpressionLookupRequest(sessionId, taskId);
ExpressionLookupFinding elf = new ExpressionLookupFinding(sessionId,taskId, FindingStatus.Running);
BusinessTierCache btcache = CacheFactory.getBusinessTierCache();
btcache.addToSessionCache(sessionId, taskId, elf);
as.setCache(btcache);
lookupReq.setReporters(reporters);
lookupReq.setSamples(samples);
lookupReq.setDataFileName(rbinaryFileName);
as.sendRequest(lookupReq);
finding = btcache.getSessionFinding(sessionId, taskId);
while(finding.getStatus() == FindingStatus.Running){
finding = btcache.getSessionFinding(sessionId,taskId);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
logger.error(e);
}
}
}
catch (NamingException e) {
// TODO Auto-generated catch block
logException(e);
} catch (JMSException e) {
// TODO Auto-generated catch block
logException(e);
}
catch (Exception e) {
logException(e);
}
return (ExpressionLookupFinding) finding;
}
private static void logException(Exception ex) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
logger.error(sw.toString());
}
}
|
package co.phoenixlab.discord.commands.dn;
import co.phoenixlab.common.lang.number.ParseInt;
import co.phoenixlab.common.localization.Localizer;
import co.phoenixlab.discord.Command;
import co.phoenixlab.discord.MessageContext;
import co.phoenixlab.discord.api.DiscordApiClient;
import co.phoenixlab.discord.api.entities.Embed;
import co.phoenixlab.discord.api.entities.EmbedField;
import co.phoenixlab.discord.api.entities.EmbedFooter;
public class DnCritDmgCommand implements Command {
public static final float CRITDMG_MAX_PERCENT = 1.0F;
public static final float[] critDmgCaps = {
2650.0F, 3074.0F, 3498.0F, 3922.0F, 4346.0F, 4770.0F, 5194.0F, 5618.0F,
6042.0F, 6466.0F, 6890.0F, 7314.0F, 7738.0F, 8162.0F, 10070.0F, 10600.0F,
11130.0F, 11660.0F, 12190.0F, 12720.0F, 13250.0F, 13780.0F, 14310.0F,
14840.0F, 15635.0F, 16430.0F, 17225.0F, 18020.0F, 18815.0F, 19610.0F,
20405.0F, 21200.0F, 22260.0F, 23320.0F, 24380.0F, 25440.0F, 26500.0F,
27560.0F, 28620.0F, 29680.0F, 31641.0F, 33575.0F, 35510.0F, 37206.0F,
39326.0F, 41419.0F, 43513.0F, 45553.0F, 47832.0F, 50350.0F, 55650.0F,
59757.0F, 64580.0F, 69589.0F, 74756.0F, 80109.0F, 86310.0F, 93121.0F,
99375.0F, 103350.0F, 107987.0F, 113950.0F, 121237.0F, 129850.0F, 139787.0F,
151050.0F, 163637.0F, 177894.0F, 193794.0F, 211337.0F, 228555.0F, 245520.0F,
262220.0F, 278587.0F, 296902.0F, 320100.0F, 343263.0F, 374976.0F, 407979.0F,
431970.0F, 453390.0F, 474810.0F, 496230.0F, 517650.0F, 542640.0F, 567630.0F,
592620.0F, 617610.0F, 642600.0F, 671160.0F, 769692.0F, 801108.0F, 832524.0F,
863940.0F, 899283.0F, 934626.0F, 969969.0F, 1005312.0F, 1040655.0F, 1075998.0F
};
private final Localizer loc;
public static final int[] CRITDMG_DEFAULT_LEVELS;
static {
CRITDMG_DEFAULT_LEVELS = new int[]{93, 90, 80};
}
public DnCritDmgCommand(Localizer loc) {
this.loc = loc;
}
@Override
public void handleCommand(MessageContext context, String args) {
DiscordApiClient apiClient = context.getApiClient();
// Strip commas
args = args.replace(",", "");
String[] split = args.split(" ", 2);
int level = -1;
if (split.length == 2) {
level = ParseInt.parseOrDefault(split[1], -1);
}
int critDmg = -1;
float critDmgPercent = 0;
String critDmgAmt = split[0];
try {
if (critDmgAmt.endsWith("%")) {
String noPercent = critDmgAmt.substring(0, critDmgAmt.length() - 1);
critDmgPercent = ((float) Double.parseDouble(noPercent) - 200F) / 100F;
critDmgPercent = Math.min(critDmgPercent, CRITDMG_MAX_PERCENT);
} else {
critDmg = (int) DnCommandUtils.parseStat(critDmgAmt, loc);
if (critDmg < 0) {
throw new IllegalArgumentException(loc.localize(
"commands.dn.critdmg.response.critdmg_out_of_range",
0, 200
));
}
}
if (level == -1) {
String title;
// Default level, use embed style for showing lvl 80, 90, and 93 critdmg
Embed embed = new Embed();
embed.setType(Embed.TYPE_RICH);
embed.setColor(5941733); // GLAZE Accent 2 (temporary, replace with rolecolor)
EmbedField[] fields = new EmbedField[CRITDMG_DEFAULT_LEVELS.length];
if (critDmg == -1) {
title = String.format("**__%.1f%% Critical Damage__**", critDmgPercent * 100F + 200F);
for (int i = 0; i < fields.length; i++) {
fields[i] = new EmbedField(
String.format("Level %d", CRITDMG_DEFAULT_LEVELS[i]),
String.format("%,d",
calculateCritDmgRequiredForPercent(critDmgPercent, CRITDMG_DEFAULT_LEVELS[i])),
true
);
}
} else {
title = String.format("**__%,d Critical Damage__**", critDmg);
for (int i = 0; i < fields.length; i++) {
fields[i] = new EmbedField(
String.format("Level %d", CRITDMG_DEFAULT_LEVELS[i]),
String.format("%.1f%%",
calculateCritDmgPercent(critDmg, CRITDMG_DEFAULT_LEVELS[i]) + 200F),
true
);
}
}
embed.setFields(fields);
EmbedFooter footer = new EmbedFooter();
footer.setText(DnCommandUtils.DIVINITOR_FOOTER_TEXT);
footer.setIconUrl(DnCommandUtils.DIVINITOR_FOOTER_ICON_URL);
embed.setFooter(footer);
apiClient.sendMessage(title, context.getChannel(), embed);
} else {
if (critDmg == -1) {
critDmg = calculateCritDmgRequiredForPercent(critDmgPercent, level);
String msg = loc.localize(
"commands.dn.critdmg.response.format.required",
level,
critDmg,
critDmgPercent * 100D + 200D
);
apiClient.sendMessage(msg, context.getChannel());
} else {
critDmgPercent = calculateCritDmgPercent(critDmg, level) + 200F;
String msg = loc.localize(
"commands.dn.critdmg.response.format",
level,
critDmgPercent,
(int) (critDmgCaps[level - 1] * CRITDMG_MAX_PERCENT),
(int) (CRITDMG_MAX_PERCENT * 100D + 200F)
);
apiClient.sendMessage(msg, context.getChannel());
}
}
return;
} catch (NumberFormatException nfe) {
apiClient.sendMessage(loc.localize("commands.dn.critdmg.response.invalid",
context.getBot().getMainCommandDispatcher().getCommandPrefix()),
context.getChannel());
return;
} catch (IllegalArgumentException ile) {
apiClient.sendMessage(ile.getMessage(), context.getChannel());
return;
}
}
public float calculateCritDmgPercent(int critDmg, int level) {
int levelIndex = level - 1;
if (levelIndex < 0 || levelIndex > critDmgCaps.length) {
throw new IllegalArgumentException(loc.localize(
"commands.dn.critdmg.response.level_out_of_range",
1,
critDmgCaps.length
));
}
if (critDmg < 0) {
throw new IllegalArgumentException(loc.localize(
"commands.dn.critdmg.response.critdmg_out_of_range",
0, 200
));
}
float critDmgCap = critDmgCaps[levelIndex];
float critDmgPercent = critDmg / critDmgCap;
return Math.max(0, Math.min(CRITDMG_MAX_PERCENT, critDmgPercent)) * 100F;
}
public int calculateCritDmgRequiredForPercent(float percent, int level) {
int levelIndex = level - 1;
if (levelIndex < 0 || levelIndex > critDmgCaps.length) {
throw new IllegalArgumentException(loc.localize(
"commands.dn.critdmg.response.level_out_of_range",
1,
critDmgCaps.length
));
}
if (percent < 0) {
throw new IllegalArgumentException(loc.localize(
"commands.dn.critdmg.response.critdmg_out_of_range",
0, 200
));
}
percent = Math.min(percent, CRITDMG_MAX_PERCENT);
float critDmgCap = critDmgCaps[levelIndex];
float critDmg = critDmgCap * percent;
return (int) critDmg;
}
}
|
package com.arckenver.mightyloot.listener;
import java.util.ArrayList;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.block.InteractBlockEvent;
import org.spongepowered.api.event.filter.cause.First;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.channel.MessageChannel;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;
import com.arckenver.mightyloot.DataHandler;
import com.arckenver.mightyloot.LanguageHandler;
import com.arckenver.mightyloot.object.Loot;
public class InteractListener
{
@Listener
public void onInteract(InteractBlockEvent event, @First Player player)
{
World world = player.getWorld();
if (!event.getTargetBlock().getLocation().isPresent())
{
return;
}
Location<World> blockLoc = event.getTargetBlock().getLocation().get();
ArrayList<Loot> loots = DataHandler.getLoots(world.getUniqueId());
if (loots != null)
{
for (Loot loot : loots)
{
if (loot.getLoc().getBlockPosition().equals(blockLoc.getBlockPosition()) || loot.getLoc().getBlockPosition().add(0, -1, 0).equals(blockLoc.getBlockPosition()))
{
DataHandler.removeLoot(loot);
String[] s1 = LanguageHandler.get("BA").split("\\{LOOT\\}");
String[] s2 = s1[0].split("\\{PLAYER\\}");
String[] s3 = s1[1].split("\\{PLAYER\\}");
MessageChannel.TO_ALL.send(Text.builder()
.append(Text.of(TextColors.GOLD, (s2.length > 0) ? s2[0] : ""))
.append(Text.of(TextColors.YELLOW, (s2.length > 1) ? player.getName() : ""))
.append(Text.of(TextColors.GOLD, (s2.length > 1) ? s2[1] : ""))
.append(loot.getType().getDisplay())
.append(Text.of(TextColors.GOLD, (s3.length > 0) ? s3[0] : ""))
.append(Text.of(TextColors.YELLOW, (s3.length > 1) ? player.getName() : ""))
.append(Text.of(TextColors.GOLD, (s3.length > 1) ? s3[1] : ""))
.build());
}
}
}
}
}
|
package com.brohoof.minelittlepony.model.part;
import com.brohoof.minelittlepony.PonyData;
import com.brohoof.minelittlepony.model.AbstractPonyModel;
import com.brohoof.minelittlepony.model.BodyPart;
import com.brohoof.minelittlepony.model.PonyModelConstants;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.util.math.MathHelper;
public class PegasusWings implements IPonyPart, PonyModelConstants {
private final AbstractPonyModel pony;
public ModelRenderer[] leftWing;
public ModelRenderer[] rightWing;
public ModelRenderer[] leftWingExt;
public ModelRenderer[] rightWingExt;
public PegasusWings(AbstractPonyModel pony) {
this.pony = pony;
}
@Override
public void init(float yOffset, float stretch) {
this.leftWing = new ModelRenderer[3];
this.rightWing = new ModelRenderer[3];
this.leftWingExt = new ModelRenderer[6];
this.rightWingExt = new ModelRenderer[6];
for (int i = 0; i < leftWing.length; i++) {
this.leftWing[i] = new ModelRenderer(pony, 56, 32);
this.pony.boxList.remove(this.leftWing[i]);
}
for (int i = 0; i < rightWing.length; i++) {
this.rightWing[i] = new ModelRenderer(pony, 56, 16);
this.pony.boxList.remove(this.rightWing[i]);
}
for (int i = 0; i < leftWingExt.length; i++) {
this.leftWingExt[i] = new ModelRenderer(pony, 56, 35);
this.pony.boxList.remove(this.leftWingExt[i]);
}
for (int i = 0; i < rightWingExt.length; i++) {
this.rightWingExt[i] = new ModelRenderer(pony, 56, 19);
// this seems to hide the wings being a different size when folded
this.rightWingExt[i].mirror = true;
this.pony.boxList.remove(this.rightWingExt[i]);
}
initPositions(yOffset, stretch);
}
private void initPositions(float yOffset, float stretch) {
this.leftWing[0].addBox(4.0F, 5.0F, 2.0F, 2, 6, 2, stretch);
this.leftWing[0].setRotationPoint(HEAD_RP_X, WING_FOLDED_RP_Y + yOffset, WING_FOLDED_RP_Z);
this.leftWing[0].rotateAngleX = ROTATE_90;
this.leftWing[1].addBox(4.0F, 5.0F, 4.0F, 2, 8, 2, stretch);
this.leftWing[1].setRotationPoint(HEAD_RP_X, WING_FOLDED_RP_Y + yOffset, WING_FOLDED_RP_Z);
this.leftWing[1].rotateAngleX = ROTATE_90;
this.leftWing[2].addBox(4.0F, 5.0F, 6.0F, 2, 6, 2, stretch);
this.leftWing[2].setRotationPoint(HEAD_RP_X, WING_FOLDED_RP_Y + yOffset, WING_FOLDED_RP_Z);
this.leftWing[2].rotateAngleX = ROTATE_90;
this.rightWing[0].addBox(-6.0F, 5.0F, 2.0F, 2, 6, 2, stretch);
this.rightWing[0].setRotationPoint(HEAD_RP_X, WING_FOLDED_RP_Y + yOffset, WING_FOLDED_RP_Z);
this.rightWing[0].rotateAngleX = ROTATE_90;
this.rightWing[1].addBox(-6.0F, 5.0F, 4.0F, 2, 8, 2, stretch);
this.rightWing[1].setRotationPoint(HEAD_RP_X, WING_FOLDED_RP_Y + yOffset, WING_FOLDED_RP_Z);
this.rightWing[1].rotateAngleX = ROTATE_90;
this.rightWing[2].addBox(-6.0F, 5.0F, 6.0F, 2, 6, 2, stretch);
this.rightWing[2].setRotationPoint(HEAD_RP_X, WING_FOLDED_RP_Y + yOffset, WING_FOLDED_RP_Z);
this.rightWing[2].rotateAngleX = ROTATE_90;
this.leftWingExt[0].addBox(0.0F, 6.0F, 0.0F, 1, 8, 2, stretch + 0.1F);
this.leftWingExt[0].setRotationPoint(LEFT_WING_EXT_RP_X, LEFT_WING_EXT_RP_Y + yOffset, LEFT_WING_EXT_RP_Z);
this.leftWingExt[1].addBox(0.0F, -1.2F, -0.2F, 1, 8, 2, stretch - 0.2F);
this.leftWingExt[1].setRotationPoint(LEFT_WING_EXT_RP_X, LEFT_WING_EXT_RP_Y + yOffset, LEFT_WING_EXT_RP_Z);
this.leftWingExt[2].addBox(0.0F, 1.8F, 1.3F, 1, 8, 2, stretch - 0.1F);
this.leftWingExt[2].setRotationPoint(LEFT_WING_EXT_RP_X, LEFT_WING_EXT_RP_Y + yOffset, LEFT_WING_EXT_RP_Z);
this.leftWingExt[3].addBox(0.0F, 5.0F, 2.0F, 1, 8, 2, stretch);
this.leftWingExt[3].setRotationPoint(LEFT_WING_EXT_RP_X, LEFT_WING_EXT_RP_Y + yOffset, LEFT_WING_EXT_RP_Z);
this.leftWingExt[4].addBox(0.0F, 0.0F, -0.2F, 1, 6, 2, stretch + 0.3F);
this.leftWingExt[4].setRotationPoint(LEFT_WING_EXT_RP_X, LEFT_WING_EXT_RP_Y + yOffset, LEFT_WING_EXT_RP_Z);
this.leftWingExt[5].addBox(0.0F, 0.0F, 0.2F, 1, 3, 2, stretch + 0.19F);
this.leftWingExt[5].setRotationPoint(LEFT_WING_EXT_RP_X, LEFT_WING_EXT_RP_Y + yOffset, LEFT_WING_EXT_RP_Z);
this.rightWingExt[0].addBox(0.0F, 6.0F, 0.0F, 1, 8, 2, stretch + 0.1F);
this.rightWingExt[0].setRotationPoint(RIGHT_WING_EXT_RP_X, RIGHT_WING_EXT_RP_Y + yOffset, RIGHT_WING_EXT_RP_Z);
this.rightWingExt[1].addBox(0.0F, -1.2F, -0.2F, 1, 8, 2, stretch - 0.2F);
this.rightWingExt[1].setRotationPoint(RIGHT_WING_EXT_RP_X, RIGHT_WING_EXT_RP_Y + yOffset, RIGHT_WING_EXT_RP_Z);
this.rightWingExt[2].addBox(0.0F, 1.8F, 1.3F, 1, 8, 2, stretch - 0.1F);
this.rightWingExt[2].setRotationPoint(RIGHT_WING_EXT_RP_X, RIGHT_WING_EXT_RP_Y + yOffset, RIGHT_WING_EXT_RP_Z);
this.rightWingExt[3].addBox(0.0F, 5.0F, 2.0F, 1, 8, 2, stretch);
this.rightWingExt[3].setRotationPoint(RIGHT_WING_EXT_RP_X, RIGHT_WING_EXT_RP_Y + yOffset, RIGHT_WING_EXT_RP_Z);
this.rightWingExt[4].addBox(0.0F, 0.0F, -0.2F, 1, 6, 2, stretch + 0.3F);
this.rightWingExt[4].setRotationPoint(RIGHT_WING_EXT_RP_X, RIGHT_WING_EXT_RP_Y + yOffset, RIGHT_WING_EXT_RP_Z);
this.rightWingExt[5].addBox(0.0F, 0.0F, 0.2F, 1, 3, 2, stretch + 0.19F);
this.rightWingExt[5].setRotationPoint(RIGHT_WING_EXT_RP_X, RIGHT_WING_EXT_RP_Y + yOffset, RIGHT_WING_EXT_RP_Z);
}
@Override
public void animate(PonyData metadata, float move, float swing, float tick, float horz, float vert) {
float bodySwingRotation = 0.0F;
if (pony.swingProgress > -9990.0F && !metadata.hasMagic()) {
bodySwingRotation = MathHelper.sin(MathHelper.sqrt_float(pony.swingProgress) * 3.1415927F * 2.0F) * 0.2F;
}
for (int i = 0; i < this.leftWing.length; ++i) {
this.leftWing[i].rotateAngleY = bodySwingRotation * 0.2F;
}
for (int i = 0; i < this.rightWing.length; ++i) {
this.rightWing[i].rotateAngleY = bodySwingRotation * 0.2F;
}
if (pony.isSneak && !pony.isFlying) {
this.sneak();
} else {
this.unsneak(tick);
}
float angle = ROTATE_90;
for (int i = 0; i < this.leftWing.length; i++) {
this.leftWing[i].rotateAngleX = angle;
}
for (int i = 0; i < this.rightWing.length; i++) {
this.rightWing[i].rotateAngleX = angle;
}
// Special
this.leftWingExt[1].rotateAngleX -= 0.85F;
this.leftWingExt[2].rotateAngleX -= 0.75F;
this.leftWingExt[3].rotateAngleX -= 0.5F;
this.leftWingExt[5].rotateAngleX -= 0.85F;
this.rightWingExt[1].rotateAngleX -= 0.85F;
this.rightWingExt[2].rotateAngleX -= 0.75F;
this.rightWingExt[3].rotateAngleX -= 0.5F;
this.rightWingExt[5].rotateAngleX -= 0.85F;
}
@Override
public void render(PonyData data, float scale) {
pony.transform(BodyPart.BODY);
pony.bipedBody.postRender(scale);
if (data.getRace() != null && data.getRace().hasWings()) {
if (!pony.isFlying && !pony.isSneak) {
for (int k1 = 0; k1 < this.leftWing.length; ++k1) {
this.leftWing[k1].render(scale);
}
for (int k1 = 0; k1 < this.rightWing.length; ++k1) {
this.rightWing[k1].render(scale);
}
} else {
for (int k1 = 0; k1 < this.leftWingExt.length; ++k1) {
this.leftWingExt[k1].render(scale);
}
for (int i = 0; i < this.rightWingExt.length; ++i) {
this.rightWingExt[i].render(scale);
}
}
}
}
private void sneak() {
for (int i = 0; i < this.leftWingExt.length; ++i) {
this.leftWingExt[i].rotateAngleX = EXT_WING_ROTATE_ANGLE_X;
this.leftWingExt[i].rotateAngleZ = LEFT_WING_ROTATE_ANGLE_Z_SNEAK;
}
for (int i = 0; i < this.leftWingExt.length; ++i) {
this.rightWingExt[i].rotateAngleX = EXT_WING_ROTATE_ANGLE_X;
this.rightWingExt[i].rotateAngleZ = RIGHT_WING_ROTATE_ANGLE_Z_SNEAK;
}
}
private void unsneak(float tick) {
if (pony.isFlying) {
float WingRotateAngleZ = MathHelper.sin(tick * 0.536F) * 1.0F;
for (int i = 0; i < this.leftWingExt.length; ++i) {
this.leftWingExt[i].rotateAngleX = EXT_WING_ROTATE_ANGLE_X;
this.leftWingExt[i].rotateAngleZ = -WingRotateAngleZ - ROTATE_270 - 0.4F;
}
for (int i = 0; i < this.rightWingExt.length; ++i) {
this.rightWingExt[i].rotateAngleX = EXT_WING_ROTATE_ANGLE_X;
this.rightWingExt[i].rotateAngleZ = WingRotateAngleZ + ROTATE_270 + 0.4F;
}
}
}
}
|
package com.cultofbits.elasticsearch.metrics;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.SharedMetricRegistries;
import org.elasticsearch.action.admin.cluster.node.stats.NodeStats;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.index.engine.SegmentsStats;
import org.elasticsearch.index.flush.FlushStats;
import org.elasticsearch.index.indexing.IndexingStats;
import org.elasticsearch.index.merge.MergeStats;
import org.elasticsearch.index.refresh.RefreshStats;
import org.elasticsearch.index.search.stats.SearchStats;
import org.elasticsearch.index.service.IndexService;
import org.elasticsearch.index.shard.DocsStats;
import org.elasticsearch.index.shard.service.IndexShard;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.indices.NodeIndicesStats;
import org.elasticsearch.node.service.NodeService;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class MetricsWorker implements Runnable {
private ESLogger logger;
private NodeService nodeService;
private IndicesService indicesService;
private long interval;
private ClusterService clusterService;
private String[] indexesToResolve;
private String[] indexesToInclude = new String[0];
private boolean alreadyRegistered = false;
private boolean indicesResolved = false;
public volatile boolean stopping;
private Map<String, Long> cachedGauges = new ConcurrentHashMap<>();
public MetricsWorker(ESLogger logger,
NodeService nodeService, IndicesService indicesService, long interval,
ClusterService clusterService, String[] indexesToResolve) {
this.logger = logger;
this.nodeService = nodeService;
this.indicesService = indicesService;
this.interval = interval;
this.clusterService = clusterService;
this.indexesToResolve = indexesToResolve;
}
@Override
public void run() {
while (!stopping) {
try {
Thread.sleep(interval);
if(!indicesResolved) resolveIndices();
updateTotalStats();
for (String indexName : indexesToInclude) {
IndexService service = indicesService.indexServiceSafe(indexName);
updateIndicesDocsStats(indexName, service);
updateIndicesIndexingStats(indexName, service);
updateIndicesMergeStats(indexName, service);
}
if (indicesResolved && !alreadyRegistered) registerMetrics();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void resolveIndices() {
if(indexesToResolve.length == 0) {
logger.info("Will not track indices stats");
indicesResolved = true;
}
String[] indexesToInclude = clusterService.state().metaData().concreteIndices(
IndicesOptions.lenientExpandOpen(),
indexesToResolve
);
if(indexesToInclude.length > 0) {
logger.info("Will track stats for the indices [{}], resolved from [{}]",
indexesToInclude,
indexesToResolve);
indicesResolved = true;
this.indexesToInclude = indexesToInclude;
}
}
void updateTotalStats() {
NodeStats stats = nodeService.stats();
NodeIndicesStats indices = stats.getIndices();
DocsStats docs = indices.getDocs();
cachedGauges.put("indices.docs._all.count", docs.getCount());
cachedGauges.put("indices.docs._all.deleted", docs.getDeleted());
SearchStats.Stats search = indices.getSearch().getTotal();
cachedGauges.put("indices.search._all.query-time", search.getQueryTimeInMillis());
cachedGauges.put("indices.search._all.query-count", search.getQueryCount());
cachedGauges.put("indices.search._all.query-time-per",
ratio(search.getQueryTimeInMillis(), search.getQueryCount()));
cachedGauges.put("indices.search._all.query-current", search.getQueryCurrent());
cachedGauges.put("indices.search._all.fetch-time", search.getFetchTimeInMillis());
cachedGauges.put("indices.search._all.fetch-count", search.getFetchCount());
cachedGauges.put("indices.search._all.fetch-time-per",
ratio(search.getFetchTimeInMillis(), search.getFetchCount()));
cachedGauges.put("indices.search._all.fetch-current", search.getFetchCurrent());
IndexingStats.Stats indexing = indices.getIndexing().getTotal();
cachedGauges.put("indices.indexing._all.index-time", indexing.getIndexTimeInMillis());
cachedGauges.put("indices.indexing._all.index-count", indexing.getIndexCount());
cachedGauges.put("indices.indexing._all.index-time-per",
ratio(indexing.getIndexTimeInMillis(), indexing.getIndexCount()));
cachedGauges.put("indices.indexing._all.index-current", indexing.getIndexCurrent());
cachedGauges.put("indices.indexing._all.delete-time", indexing.getDeleteTimeInMillis());
cachedGauges.put("indices.indexing._all.delete-count", indexing.getDeleteCount());
cachedGauges.put("indices.indexing._all.delete-time-per",
ratio(indexing.getDeleteTimeInMillis(), indexing.getDeleteCount()));
cachedGauges.put("indices.indexing._all.delete-current", indexing.getDeleteCurrent());
FlushStats flush = indices.getFlush();
cachedGauges.put("indices.flush._all.time", flush.getTotalTimeInMillis());
cachedGauges.put("indices.flush._all.count", flush.getTotal());
cachedGauges.put("indices.flush._all.time-per",
ratio(flush.getTotalTimeInMillis(), flush.getTotal()));
MergeStats merge = indices.getMerge();
cachedGauges.put("indices.merge._all.time", merge.getTotalTimeInMillis());
cachedGauges.put("indices.merge._all.count", merge.getTotal());
cachedGauges.put("indices.merge._all.time-per",
ratio(merge.getTotalTimeInMillis(), merge.getTotal()));
cachedGauges.put("indices.merge._all.docs", merge.getTotalNumDocs());
cachedGauges.put("indices.merge._all.size", merge.getTotalSizeInBytes());
cachedGauges.put("indices.merge._all.current", merge.getCurrent());
RefreshStats refresh = indices.getRefresh();
cachedGauges.put("indices.refresh._all.time", refresh.getTotalTimeInMillis());
cachedGauges.put("indices.refresh._all.count", refresh.getTotal());
cachedGauges.put("indices.refresh._all.time-per",
ratio(refresh.getTotalTimeInMillis(), refresh.getTotal()));
SegmentsStats segments = indices.getSegments();
cachedGauges.put("indices.segments._all.count", segments.getCount());
cachedGauges.put("indices.segments._all.memory", segments.getMemoryInBytes());
cachedGauges.put("indices.segments._all.index-writer-memory", segments.getIndexWriterMemoryInBytes());
}
private void updateIndicesDocsStats(String indexName, IndexService service) {
long count = 0;
long deleted = 0;
for (IndexShard shard : service) {
DocsStats stats = shard.docStats();
count += stats.getCount();
deleted += stats.getDeleted();
}
cachedGauges.put("indices.docs." + indexName + ".count", count);
cachedGauges.put("indices.docs." + indexName + ".deleted", deleted);
}
private void updateIndicesIndexingStats(String indexName, IndexService service) {
long count = 0;
long time = 0;
long current = 0;
long deleted = 0;
long deletedTime = 0;
long deleteCurrent = 0;
for (IndexShard shard : service) {
IndexingStats.Stats stats = shard.indexingStats("_all").getTotal();
count += stats.getIndexCount();
time += stats.getIndexTimeInMillis();
current += stats.getIndexCurrent();
deleted += stats.getDeleteCount();
deletedTime += stats.getDeleteTimeInMillis();
deleteCurrent += stats.getDeleteCurrent();
}
cachedGauges.put("indices.indexing." + indexName + ".index-count", count);
cachedGauges.put("indices.indexing." + indexName + ".index-time", time);
cachedGauges.put("indices.indexing." + indexName + ".index-current", current);
cachedGauges.put("indices.indexing." + indexName + ".delete-count", deleted);
cachedGauges.put("indices.indexing." + indexName + ".delete-time", deletedTime);
cachedGauges.put("indices.indexing." + indexName + ".delete-current", deleteCurrent);
}
private void updateIndicesMergeStats(String indexName, IndexService service) {
long time = 0;
long count = 0;
long docs = 0;
long size = 0;
long current = 0;
for (IndexShard shard : service) {
MergeStats stats = shard.mergeStats();
time += stats.getTotalTimeInMillis();
count += stats.getTotal();
docs += stats.getTotalNumDocs();
size += stats.getTotalSizeInBytes();
current += stats.getCurrent();
}
cachedGauges.put("indices.merge." + indexName + ".time", time);
cachedGauges.put("indices.merge." + indexName + ".count", count);
cachedGauges.put("indices.merge." + indexName + ".docs", docs);
cachedGauges.put("indices.merge." + indexName + ".size", size);
cachedGauges.put("indices.merge." + indexName + ".current", current);
}
private void registerMetrics() {
MetricRegistry metrics = SharedMetricRegistries.getOrCreate("elasticsearch");
for (final String name : cachedGauges.keySet()) {
metrics.register(name, new Gauge<Long>() {
@Override
public Long getValue() {
return cachedGauges.get(name);
}
});
}
alreadyRegistered = true;
}
private static long ratio(long time, long count){
if(count <= 0) return 0;
return time / count;
}
}
|
package com.dreaminsteam.rpbot.commands;
import com.dreaminsteam.rpbot.db.DatabaseUtil;
import com.dreaminsteam.rpbot.db.models.Player;
import de.btobastian.sdcf4j.Command;
import de.btobastian.sdcf4j.CommandExecutor;
import sx.blah.discord.api.IDiscordClient;
import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IPrivateChannel;
import sx.blah.discord.handle.obj.IUser;
public class ListPlayersCommand implements CommandExecutor{
@Command(aliases = {"!playerInfo"}, description = "List current player information. **Admin only!**", usage="!playerInfo", async=true)
public String getPlayerInfo(IChannel channel, IUser user, IDiscordClient apiClient, String command, String[] args) throws Exception{
boolean hasAdminRole = CommandUtils.hasAdminRole(user, channel);
if(!hasAdminRole){
return user.mention() + " You are likely to be eaten by a grue. If this predicament seems particularly cruel, consider whose fault it might be: not a torch nor a match in your inventory.";
}
IPrivateChannel pmChannel = user.getOrCreatePMChannel();
StringBuilder sb = new StringBuilder();
sb.append("Current players: \n");
int count = 0;
for (Player player : DatabaseUtil.getPlayerDao().queryForAll()) {
if(player != null){
String snowflakeId = player.getSnowflakeId();
String playerName = player.getName();
String currentYear = player.getCurrentYear() != null ? player.getCurrentYear().getPrettyName() : " - MISSING YEAR!!!!
sb.append("**" + snowflakeId + "**: " + playerName + ", " + currentYear + "\n");
count++;
if(count == 50){
count = 0;
pmChannel.sendMessage(sb.toString());
sb = new StringBuilder();
}
}
}
if(count > 0){
pmChannel.sendMessage(sb.toString());
}
return user.mention() + " Information DM'd to you.";
}
}
|
package com.goodformentertainment.canary.xis;
import net.canarymod.Canary;
import net.canarymod.api.world.DimensionType;
import net.canarymod.api.world.World;
import net.canarymod.api.world.WorldManager;
import net.canarymod.api.world.WorldType;
import net.canarymod.api.world.position.Location;
import net.canarymod.config.Configuration;
import net.canarymod.config.WorldConfiguration;
import net.visualillusionsent.utils.PropertiesFile;
import com.goodformentertainment.canary.playerstate.PlayerStatePlugin;
import com.goodformentertainment.canary.playerstate.api.IWorldStateManager;
import com.goodformentertainment.canary.playerstate.api.SaveState;
public class XWorldManager {
private static final DimensionType X_DIMENSION = DimensionType.NORMAL;
private static final WorldType X_TYPE = WorldType.SUPERFLAT;
private final XConfig config;
private final WorldManager worldManager;
private World world;
public XWorldManager(final XConfig config) {
this.config = config;
worldManager = Canary.getServer().getWorldManager();
}
public Location getDefaultSpawn() {
return Canary.getServer().getDefaultWorld().getSpawnLocation();
}
public boolean createWorld() {
boolean success = false;
if (!worldManager.worldExists(config.getWorldName())) {
XPlugin.LOG.info("Creating XtremeIsland world " + config.getWorldName());
final WorldConfiguration worldConfig = Configuration.getWorldConfig(config.getWorldName()
+ "_" + X_DIMENSION.getName());
final PropertiesFile file = worldConfig.getFile();
file.setInt("difficulty", World.Difficulty.HARD.getId());
file.setBoolean("generate-structures", false);
file.setBoolean("allow-nether", false);
file.setBoolean("allow-end", false);
file.setBoolean("spawn-villagers", true);
file.setBoolean("spawn-golems", true);
file.setBoolean("spawn-animals", true);
file.setBoolean("spawn-monsters", true);
file.setString("world-type", "FLAT");
file.setString("generator-settings", "2;0;0;");
// file.setString("generator-settings", "3;minecraft:air;0;");
file.save();
success = worldManager.createWorld(config.getWorldName(), 0, X_DIMENSION, X_TYPE);
} else {
success = true;
}
return success;
}
public boolean load() {
world = worldManager.getWorld(config.getWorldName(), true);
final IWorldStateManager worldStateManager = PlayerStatePlugin.getWorldManager();
worldStateManager.registerWorld(world, new SaveState[] {
SaveState.CONDITIONS, SaveState.INVENTORY, SaveState.LOCATIONS
});
return world != null;
}
public void unload() {
worldManager.unloadWorld(config.getWorldName(), X_DIMENSION, true);
final IWorldStateManager worldStateManager = PlayerStatePlugin.getWorldManager();
worldStateManager.unregisterWorld(world);
}
public World getWorld() {
return world;
}
}
|
package com.insightng.backup;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.RDFWriter;
import org.openrdf.rio.trig.TriGWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Creates a backup of the given repository on the Sesame server
*
* @author Hayden Smith
* @since 1.2
*/
public class SesameRepositoryBackupCreator implements Runnable {
private Logger logger = LoggerFactory.getLogger(getClass());
private String repositoryId;
private File backupFile;
private Repository repository;
public SesameRepositoryBackupCreator(final String repositoryId, final File backupFile,
final Repository repository) {
this.repositoryId = repositoryId;
this.backupFile = backupFile;
this.repository = repository;
}
@Override
public void run() {
if (backupToFile()) {
compressFile();
}
}
private boolean backupToFile() {
logger.info("backing up repository {} to file {}", repositoryId, backupFile.getAbsolutePath());
if (this.backupFile.exists()) {
logger.error("Unable to backup repository " + repositoryId + ": file "
+ this.backupFile.getAbsolutePath() + " already exists");
return false;
}
try {
if (!this.backupFile.createNewFile()) {
logger.error("Unable to backup repository " + repositoryId + ": unable to create file "
+ this.backupFile.getAbsolutePath());
return false;
}
} catch (IOException e) {
logger.error("Unable to backup repository " + repositoryId + ": unable to create file "
+ this.backupFile.getAbsolutePath(), e);
return false;
}
FileOutputStream outputStream = null;
boolean errorDuringBackup = false;
try {
outputStream = new FileOutputStream(backupFile);
final RDFWriter trigWriter = new TriGWriter(outputStream);
final RepositoryConnection conn = this.repository.getConnection();
try {
// Export the contents of the repository to a TriG-formatted
// file
conn.export(trigWriter);
} catch (RDFHandlerException e) {
logger.error("Unable to backup repository " + repositoryId, e);
if (!backupFile.delete()) {
logger.error("Unable to remove incomplete backup file " + backupFile.getAbsolutePath());
}
} finally {
conn.close();
}
} catch (FileNotFoundException e) {
logger.error("Unable to backup repository " + repositoryId + " due to missing backup file "
+ backupFile.getAbsolutePath(), e);
errorDuringBackup = true;
} catch (RepositoryException e) {
logger.error("Unable to open connection to repository " + repositoryId, e);
errorDuringBackup = true;
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
logger.error("Unable to close backup file " + backupFile.getAbsolutePath(), e);
errorDuringBackup = true;
}
}
}
return !errorDuringBackup;
}
private void compressFile() {
logger.info("compressing file {}", repositoryId, backupFile.getAbsolutePath());
File gzipBackupFile = new File(backupFile.getParent(), backupFile.getName() + ".gz");
if (gzipBackupFile.exists()) {
logger.error("Compressed backup file " + gzipBackupFile.getAbsolutePath() + " already exists");
return;
}
try {
if (!gzipBackupFile.createNewFile()) {
logger.error("Unable to create compressed backup file " + gzipBackupFile.getAbsolutePath());
return;
}
} catch (IOException e) {
logger.error("Unable to create compressed backup file " + gzipBackupFile.getAbsolutePath(), e);
return;
}
FileInputStream inputStream = null;
GZIPOutputStream gzipOutputStream = null;
try {
inputStream = new FileInputStream(backupFile);
} catch (FileNotFoundException e) {
logger.error("Could not find backup file " + backupFile.getAbsolutePath(), e);
return;
}
try {
gzipOutputStream = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(
gzipBackupFile)));
// TODO Use Channels?
int bufferSize = 4096;
byte[] buffer = new byte[bufferSize];
int bytesRead = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
gzipOutputStream.write(buffer, 0, bytesRead);
}
} catch (FileNotFoundException e) {
logger.error("Could not find backup file " + gzipBackupFile.getAbsolutePath(), e);
} catch (IOException e) {
logger.error("Could not compress backup file " + gzipBackupFile.getAbsolutePath(), e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
logger.error("Unable to close uncompressed backup file " + backupFile.getAbsolutePath(),
e);
}
}
if (gzipOutputStream != null) {
try {
gzipOutputStream.close();
} catch (IOException e) {
logger.error(
"Unable to close compressed backup file " + gzipBackupFile.getAbsolutePath(), e);
}
}
if (!backupFile.delete()) {
logger.warn("Unable to delete uncompressed backup file " + backupFile.getAbsolutePath());
}
}
}
}
|
package com.lothrazar.cyclicmagic.event;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntitySign;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import com.lothrazar.cyclicmagic.util.Const;
public class EventSignSkullName{
@SubscribeEvent
public void onPlayerInteract(PlayerInteractEvent event){
EntityPlayer entityPlayer = event.getEntityPlayer();
BlockPos pos = event.getPos();
World worldObj = event.getWorld();
if(pos == null){
return;
}
IBlockState bstate = worldObj.getBlockState(pos);
if(bstate == null){
return;
}
// event has no hand??
//and no item stack. and right click rarely works. known bug
ItemStack held = entityPlayer.getHeldItemMainhand();
if(held == null){
held = entityPlayer.getHeldItemOffhand();
}
TileEntity container = worldObj.getTileEntity(pos);
// event.getAction() == PlayerInteractEvent.Action.LEFT_CLICK_BLOCK &&
// entityPlayer.isSneaking() &&
if(held != null && held.getItem() == Items.skull && held.getItemDamage() == Const.skull_player && container != null && container instanceof TileEntitySign){
TileEntitySign sign = (TileEntitySign) container;
System.out.println("hit sign with skull");
String firstLine = sign.signText[0].getUnformattedText();
if(firstLine == null){
firstLine = "";
}
if(firstLine.isEmpty() || firstLine.split(" ").length == 0){
held.setTagCompound(null);
}
else{
firstLine = firstLine.split(" ")[0];
if(held.getTagCompound() == null)
held.setTagCompound(new NBTTagCompound());
held.getTagCompound().setString(Const.SkullOwner, firstLine);
}
} // end of skullSignNames
}
}
|
package com.royalrangers.configuration.bootstrap;
import com.esotericsoftware.yamlbeans.YamlReader;
import com.royalrangers.dto.user.UserRegistrationDto;
import com.royalrangers.enums.AuthorityName;
import com.royalrangers.enums.UserAgeGroup;
import com.royalrangers.model.Authority;
import com.royalrangers.model.Country;
import com.royalrangers.model.User;
import com.royalrangers.model.achievement.*;
import com.royalrangers.repository.AuthorityRepository;
import com.royalrangers.repository.CountryRepository;
import com.royalrangers.repository.UserRepository;
import com.royalrangers.repository.achievement.*;
import com.royalrangers.service.UserService;
import com.royalrangers.service.achievement.RewardService;
import com.royalrangers.service.achievement.TestService;
import com.royalrangers.service.achievement.TwelveYearAchievementService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;
@Slf4j
@Component
public class Bootstrap {
private final String DDL_AUTO_CREATE = "create";
private final String DDL_AUTO_CREATE_DROP = "create-drop";
private final String COUNTRY_FILE = "init/ukraine.yml";
private final String USERS_FILE = "init/initial_users.yml";
@Value("${spring.jpa.hibernate.ddl-auto}")
private String ddlAuto;
@Autowired
private UserRepository userRepository;
@Autowired
private UserService userService;
@Autowired
private CountryRepository countryRepository;
@Autowired
private AuthorityRepository authorityRepository;
@Autowired
private TwelveYearAchievementService twelveYearAchievementService;
@Autowired
private ThreeYearAchievementRepository threeYearAchievementRepository;
@Autowired
private YearAchievementRepository yearAchievementRepository;
@Autowired
private QuarterAchievementRepository quarterAchievementRepository;
public YearAchievementBootstrap yearAchievementBootstrap = new YearAchievementBootstrap();
public QuarterAchievementBootstrap quarterAchievementBootstrap = new QuarterAchievementBootstrap();
public AchievementBootstrap achievementBootstrap = new AchievementBootstrap();
TestBootstrap testBootstrap = new TestBootstrap();
@Autowired
private TestService testService;
@Autowired
private TestRepository testRepository;
TaskBootstrap taskBootstrap = new TaskBootstrap();
@Autowired
private RewardService rewardService;
RewardBootstrap rewardBootstrap = new RewardBootstrap();
@Autowired
private TaskRepository taskRepository;
@PostConstruct
public void init() {
if (DDL_AUTO_CREATE.equals(ddlAuto) || DDL_AUTO_CREATE_DROP.equals(ddlAuto)) {
initTwelveYear();
initReward();
initAuthorities();
initCountry();
initUsers();
}
}
private void initUsers() {
List<User> users = new ArrayList<>();
try {
YamlReader reader = getYamlReader(USERS_FILE);
while (true) {
UserRegistrationDto userDto = reader.read(UserRegistrationDto.class);
if (userDto == null) break;
User user = userService.createUser(userDto);
user.setEnabled(true);
user.setConfirmed(true);
user.setApproved(true);
user.setLastPasswordResetDate(new Date(new GregorianCalendar(
2017, Calendar.FEBRUARY, 9)
.getTimeInMillis()));
users.add(user);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
userRepository.save(users);
}
private void initCountry() {
try {
YamlReader reader = getYamlReader(COUNTRY_FILE);
Country country = reader.read(Country.class);
countryRepository.save(country);
} catch (IOException e) {
e.printStackTrace();
}
}
//Used for read file with correct encoding
private YamlReader getYamlReader(String file) throws IOException {
Resource resource = new ClassPathResource(file);
InputStreamReader isr = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8);
return new YamlReader(isr);
}
private void initAuthorities() {
Authority userAuthority = new Authority();
userAuthority.setName(AuthorityName.ROLE_USER);
authorityRepository.save(userAuthority);
Authority adminAuthority = new Authority();
adminAuthority.setName(AuthorityName.ROLE_ADMIN);
authorityRepository.save(adminAuthority);
Authority superAdminAuthority = new Authority();
superAdminAuthority.setName(AuthorityName.ROLE_SUPER_ADMIN);
authorityRepository.save(superAdminAuthority);
}
private void initReward() {
Stream.of(rewardBootstrap.createReward().toArray()).forEach(element -> {
rewardService.addReward((Reward) element);
});
}
private void initTwelveYear() {
twelveYearAchievementService.addTwelveYearAchievement(achievementBootstrap.createTwelveYear());
initThreeYear();
}
private void initThreeYear() {
Stream.of(twelveYearAchievementService.getAllTwelveYearAchievement().toArray()).forEach(twelveYearId -> {
TwelveYearAchievement twelveYearAchievement = (TwelveYearAchievement) twelveYearId;
Stream.of(achievementBootstrap.createThreeYear().toArray()).forEach(element -> {
ThreeYearAchievement threeYearAchievement = (ThreeYearAchievement) element;
threeYearAchievement.setTwelveYearAchievement(twelveYearAchievement);
threeYearAchievementRepository.saveAndFlush(threeYearAchievement);
});
});
initYear();
}
private void initYear() {
Stream.of(yearAchievementBootstrap.createYear().toArray()).forEach(yearAchievements -> {
yearAchievementRepository.saveAndFlush((YearAchievement) yearAchievements);
});
Stream.of(threeYearAchievementRepository.findAll().toArray()).forEach(threeYearAchievements -> {
ThreeYearAchievement threeYearAchievement = (ThreeYearAchievement) threeYearAchievements;
List<YearAchievement> yearAchievementList = yearAchievementRepository.findByUserAgeGroup(threeYearAchievement.getUserAgeGroup());
Stream.of(yearAchievementList.toArray()).forEach(year -> {
YearAchievement yearAchievement = (YearAchievement) year;
yearAchievement.setThreeYearAchievement(threeYearAchievement);
yearAchievementRepository.saveAndFlush(yearAchievement);
});
});
initQuarter();
}
private void initQuarter() {
Stream.of(quarterAchievementBootstrap.createQuarter().toArray()).forEach(quarter -> {
quarterAchievementRepository.saveAndFlush((QuarterAchievement) quarter);
});
Stream.of(UserAgeGroup.values()).forEach(ageGroup -> {
List<YearAchievement> yearAchievementList = yearAchievementRepository.findByUserAgeGroup(ageGroup);
IntStream.range(1, 4).forEach(index -> {
List<QuarterAchievement> quarterAchievementList = quarterAchievementRepository.findByUserAgeGroup(ageGroup);
if (yearAchievementList.size() != 0 && quarterAchievementList.size() != 0) {
YearAchievement yearAchievement = yearAchievementList.get(index - 1);
List<QuarterAchievement> subList = null;
switch (index) {
case 1: {
subList = quarterAchievementList.subList(0, 4);
break;
}
case 2: {
subList = quarterAchievementList.subList(4, 8);
break;
}
case 3: {
subList = quarterAchievementList.subList(8, 12);
break;
}
}
Stream.of(subList.toArray()).forEach(quarterAchievement -> {
QuarterAchievement savedQuarterAchievement = (QuarterAchievement) quarterAchievement;
savedQuarterAchievement.setYearAchievement(yearAchievement);
quarterAchievementRepository.saveAndFlush(savedQuarterAchievement);
});
}
});
});
initTest();
}
public void initTest() {
Stream.of(testBootstrap.createTest().toArray()).forEach(test -> {
testRepository.saveAndFlush((Test) test);
});
initTask();
}
public void initTask() {
IntStream.range(1, testService.getAllTest().size()).forEach(testId -> {
Test test = testService.getTestById((long) testId);
Map<Integer, Object> map = taskBootstrap.createTask();
List<Task> list = (List<Task>) map.get(testId);
while (testId <= map.size()) {
if (list.size() != 0) {
Stream.of(list.toArray()).forEach(item -> {
Task task = (Task) item;
task.setTest(test);
taskRepository.saveAndFlush(task);
});
return;
}
}
});
}
}
|
package com.tikal.jenkins.plugins.multijob;
import java.io.IOException;
import java.util.Map;
import hudson.Extension;
import hudson.model.DependencyGraph;
import hudson.model.ItemGroup;
import hudson.model.TopLevelItem;
import hudson.model.Hudson;
import hudson.model.Project;
import hudson.scm.SCM;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.AlternativeUiTextProvider;
import com.tikal.jenkins.plugins.multijob.views.MultiJobView;
public class MultiJobProject extends Project<MultiJobProject, MultiJobBuild>
implements TopLevelItem {
@SuppressWarnings("rawtypes")
private MultiJobProject(ItemGroup parent, String name) {
super(parent, name);
}
public MultiJobProject(Hudson parent, String name) {
super(parent, name);
}
@Override
protected Class<MultiJobBuild> getBuildClass() {
return MultiJobBuild.class;
}
@Override
public Hudson getParent() {
return Hudson.getInstance();
}
@Override
public String getPronoun() {
return AlternativeUiTextProvider.get(PRONOUN, this, getDescriptor().getDisplayName());
}
public DescriptorImpl getDescriptor() {
return DESCRIPTOR;
}
@Extension(ordinal = 1000)
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
public static final class DescriptorImpl extends AbstractProjectDescriptor {
public String getDisplayName() {
return "MultiJob Project";
}
@SuppressWarnings("rawtypes")
public MultiJobProject newInstance(ItemGroup itemGroup, String name) {
return new MultiJobProject(itemGroup, name);
}
}
@Override
protected void buildDependencyGraph(DependencyGraph graph) {
super.buildDependencyGraph(graph);
}
public boolean isTopMost() {
return getUpstreamProjects().size() == 0;
}
public MultiJobView getView() {
MultiJobView view = new MultiJobView("");
return view;
}
public String getRootUrl() {
return Hudson.getInstance().getRootUrl();
}
}
|
package crazypants.enderio.integration.tic;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import crazypants.enderio.material.PowderIngot;
import crazypants.util.Things;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.event.FMLInterModComms;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import static crazypants.enderio.ModObject.itemPowderIngot;
public class AdditionalFluid {
static void init(FMLPreInitializationEvent event) {
if (!Loader.isModLoaded("ThermalFoundation")) {
glowstone(event);
redstone(event);
ender(event);
}
}
static void init(FMLPostInitializationEvent event) {
glowstone(event);
redstone(event);
ender(event);
}
private static boolean registerVanillaRecipesForGlowstone = false;
private static boolean registerVanillaRecipesForRedstone = false;
private static boolean registerVanillaRecipesForEnder = false;
private static void glowstone(FMLPreInitializationEvent event) {
Fluid f = new Fluid("glowstone", TicProxy.TEX_FLOWING, TicProxy.TEX_STILL) {
@Override
public int getColor() {
return 0xFF000000 | 0xffbc5e;
}
};
f.setDensity(-500);
f.setGaseous(true);
f.setLuminosity(15);
f.setTemperature(1500 + 273);
f.setViscosity(100);
if (FluidRegistry.registerFluid(f)) {
// HL: Disabled because I don't have a nice texture for it
// MoltenGlowstone block = new crazypants.enderio.fluid.BlockFluidEio.MoltenGlowstone(f, Material.WATER, 0xffbc5e);
// block.init();
// f.setBlock(block);
// if (!EnderIO.proxy.isDedicatedServer()) {
// EnderIO.fluids.registerFluidBlockRendering(f, f.getName());
if (FluidRegistry.isUniversalBucketEnabled()) {
FluidRegistry.addBucketForFluid(f);
}
NBTTagCompound tag = new NBTTagCompound();
tag.setString("fluid", f.getName());
tag.setString("ore", StringUtils.capitalize("glowstone"));
tag.setBoolean("toolforge", true);
FMLInterModComms.sendMessage("tconstruct", "integrateSmeltery", tag);
registerVanillaRecipesForGlowstone = true;
}
}
private static void glowstone(FMLPostInitializationEvent event) {
Fluid f = FluidRegistry.getFluid("glowstone");
if (registerVanillaRecipesForGlowstone) {
// Note: We match the old TE amounts
TicProxy.registerSmelterySmelting(new ItemStack(Items.GLOWSTONE_DUST), f, 250);
TicProxy.registerSmelterySmelting(new ItemStack(Blocks.GLOWSTONE), f, 1000);
TicProxy.registerBasinCasting(new ItemStack(Blocks.GLOWSTONE), null, f, 1000);
}
}
private static void redstone(FMLPreInitializationEvent event) {
Fluid f = new Fluid("redstone", TicProxy.TEX_FLOWING, TicProxy.TEX_STILL) {
@Override
public int getColor() {
return 0xFF000000 | 0xff0000;
}
};
f.setDensity(1200);
f.setLuminosity(7);
f.setTemperature(1700 + 273);
f.setViscosity(1500);
if (FluidRegistry.registerFluid(f)) {
// HL: Disabled because I don't have a nice texture for it
// MoltenRedstone block = new crazypants.enderio.fluid.BlockFluidEio.MoltenRedstone(f, Material.WATER, 0xff0000);
// block.init();
// f.setBlock(block);
// if (!EnderIO.proxy.isDedicatedServer()) {
// EnderIO.fluids.registerFluidBlockRendering(f, f.getName());
if (FluidRegistry.isUniversalBucketEnabled()) {
FluidRegistry.addBucketForFluid(f);
}
NBTTagCompound tag = new NBTTagCompound();
tag.setString("fluid", f.getName());
tag.setString("ore", StringUtils.capitalize("redstone"));
tag.setBoolean("toolforge", true);
FMLInterModComms.sendMessage("tconstruct", "integrateSmeltery", tag);
registerVanillaRecipesForRedstone = true;
}
}
private static void redstone(FMLPostInitializationEvent event) {
Fluid f = FluidRegistry.getFluid("redstone");
if (registerVanillaRecipesForRedstone) {
// Note: We match the old TE amounts
TicProxy.registerSmelterySmelting(new ItemStack(Items.REDSTONE), f, 100);
TicProxy.registerSmelterySmelting(new ItemStack(Blocks.REDSTONE_BLOCK), f, 900);
TicProxy.registerBasinCasting(new ItemStack(Blocks.REDSTONE_BLOCK), null, f, 900);
}
}
private static void ender(FMLPreInitializationEvent event) {
Fluid f = new Fluid("ender", TicProxy.TEX_FLOWING, TicProxy.TEX_STILL) {
@Override
public int getColor() {
return 0xFF000000 | 0x1b7b6b;
}
};
f.setDensity(4000);
f.setLuminosity(3);
f.setTemperature(1000 + 273);
f.setViscosity(3500);
if (FluidRegistry.registerFluid(f)) {
// HL: Disabled because I don't have a nice texture for it
// MoltenEnder block = new crazypants.enderio.fluid.BlockFluidEio.MoltenEnder(f, Material.WATER, 0x1b7b6b);
// block.init();
// f.setBlock(block);
// if (!EnderIO.proxy.isDedicatedServer()) {
// EnderIO.fluids.registerFluidBlockRendering(f, f.getName());
if (FluidRegistry.isUniversalBucketEnabled()) {
FluidRegistry.addBucketForFluid(f);
}
NBTTagCompound tag = new NBTTagCompound();
tag.setString("fluid", f.getName());
tag.setString("ore", StringUtils.capitalize("ender"));
tag.setBoolean("toolforge", true);
FMLInterModComms.sendMessage("tconstruct", "integrateSmeltery", tag);
registerVanillaRecipesForEnder = true;
}
}
private static void ender(FMLPostInitializationEvent event) {
Fluid f = FluidRegistry.getFluid("ender");
if (registerVanillaRecipesForEnder) {
// Note: We match the old TE amounts
TicProxy.registerSmelterySmelting(new ItemStack(Items.ENDER_PEARL), f, 250);
// Need to do this later because of the cast
Things cast = new Things("tconstruct:cast_custom:2");
List<ItemStack> casts = cast.getItemStacks();
if (!casts.isEmpty()) {
TicProxy.registerTableCast(new ItemStack(Items.ENDER_PEARL), casts.get(0), f, 250);
}
}
TicProxy.registerSmelterySmelting(new ItemStack(itemPowderIngot.getItem(), 1, PowderIngot.POWDER_ENDER.ordinal()), f, 250 / 9);
}
}
|
package eu.over9000.skadi.notification;
import java.awt.AWTException;
import java.awt.Image;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.TrayIcon.MessageType;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import javax.imageio.ImageIO;
import eu.over9000.skadi.SkadiMain;
import eu.over9000.skadi.channel.Channel;
import eu.over9000.skadi.channel.ChannelEventListener;
import eu.over9000.skadi.channel.ChannelManager;
import eu.over9000.skadi.util.StringUtil;
public class NotificationManager implements ChannelEventListener {
private static NotificationManager instance;
public static NotificationManager getInstance() {
if (NotificationManager.instance == null) {
NotificationManager.instance = new NotificationManager();
}
return NotificationManager.instance;
}
private TrayIcon trayIcon;
public NotificationManager() {
try {
if (SystemTray.isSupported()) {
final Image image = ImageIO.read(this.getClass().getResource("/icon.png"));
this.trayIcon = new TrayIcon(image, "Skadi", null);
this.trayIcon.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
if ((e.getClickCount() == 1) || (e.getClickCount() == 2)) {
System.out.println("clicked on icon");
}
}
});
SystemTray.getSystemTray().add(this.trayIcon);
}
ChannelManager.getInstance().addListener(this);
} catch (final IOException | AWTException e1) {
e1.printStackTrace();
}
}
public void displayNotification(final String header, final String message) {
if (this.trayIcon == null) {
return;
}
this.trayIcon.displayMessage(header, message, MessageType.NONE);
}
@Override
public void added(final Channel channel, final int count) {
}
@Override
public void removed(final Channel channel, final int count) {
}
@Override
public void updatedMetadata(final Channel channel) {
if (SkadiMain.getInstance().display_notifications && channel.wentOnline()) {
this.displayNotification(StringUtil.extractChannelName(channel.getURL()) + " went live", channel
.getMetadata().getTitle());
}
}
@Override
public void updatedStreamdata(final Channel channel) {
}
@Override
public String getListenerName() {
return this.getClass().getName();
}
}
|
package hudson.plugins.analysis.core;
import java.io.IOException;
import hudson.Launcher;
import hudson.matrix.MatrixAggregator;
import hudson.matrix.MatrixRun;
import hudson.matrix.MatrixBuild;
import hudson.model.Action;
import hudson.model.BuildListener;
/**
* Aggregates {@link AbstractResultAction}s of {@link MatrixRun}s into
* {@link MatrixBuild}.
*
* @author Ulli Hafner
*/
public abstract class AnnotationsAggregator extends MatrixAggregator {
private final ParserResult totals = new ParserResult();
private final HealthDescriptor healthDescriptor;
private final String defaultEncoding;
/**
* Creates a new instance of {@link AnnotationsAggregator}.
*
* @param build
* the matrix build
* @param launcher
* the launcher
* @param listener
* the build listener
* @param healthDescriptor
* health descriptor
* @param defaultEncoding
* the default encoding to be used when reading and parsing files
*/
public AnnotationsAggregator(final MatrixBuild build, final Launcher launcher, final BuildListener listener,
final HealthDescriptor healthDescriptor, final String defaultEncoding) {
super(build, launcher, listener);
this.healthDescriptor = healthDescriptor;
this.defaultEncoding = defaultEncoding;
}
/** {@inheritDoc} */
@Override
public boolean endRun(final MatrixRun run) throws InterruptedException, IOException {
if (totals.hasNoAnnotations()) {
BuildResult result = getResult(run);
totals.addAnnotations(result.getAnnotations());
totals.addModules(result.getModules());
}
return true;
}
/** {@inheritDoc} */
@Override
public boolean endBuild() throws InterruptedException, IOException {
build.addAction(createAction(healthDescriptor, defaultEncoding, totals));
return true;
}
/**
* Returns the annotations of the specified run.
*
* @param run
* the run to obtain the annotations from
* @return the annotations of the specified run
*/
protected abstract BuildResult getResult(MatrixRun run);
/**
* Creates the action that will render the aggregated results.
*
* @param healthDescriptor
* health descriptor
* @param defaultEncoding
* the default encoding to be used when reading and parsing files
* @param aggregatedResult
* the aggregated annotations
* @return the created action
*/
protected abstract Action createAction(HealthDescriptor healthDescriptor, String defaultEncoding, ParserResult aggregatedResult);
}
|
package io.domisum.lib.auxiliumlib.util.file;
import io.domisum.lib.auxiliumlib.PHR;
import io.domisum.lib.auxiliumlib.annotations.API;
import io.domisum.lib.auxiliumlib.util.file.FileUtil.FileType;
import io.domisum.lib.auxiliumlib.util.file.filter.FileFilter;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Arrays;
import java.util.Collection;
@API
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public final class DirectoryCopy
{
// INPUT
private final File sourceRootDirectory;
private final File targetRootDirectory;
// SETTINGS
private final Collection<FileFilter> filters;
// INIT
@API
public static DirectoryCopy fromTo(File sourceRootDir, File targetRootDir, FileFilter... filters)
{
return new DirectoryCopy(sourceRootDir, targetRootDir, Arrays.asList(filters));
}
// COPY
@API
public void copy()
{
if(!sourceRootDirectory.exists())
return;
validateInputDirectories(sourceRootDirectory, targetRootDirectory);
copyDirectoryRecursively(sourceRootDirectory, targetRootDirectory);
}
private void copyDirectoryRecursively(File sourceRoot, File targetRoot)
{
FileUtil.mkdirs(targetRoot);
for(var file : FileUtil.listFilesFlat(sourceRoot, FileType.FILE))
if(shouldCopyFile(file))
FileUtil.copyFile(file, new File(targetRoot, file.getName()));
for(var file : FileUtil.listFilesFlat(sourceRoot, FileType.DIRECTORY))
if(shouldCopyFile(file))
copyDirectoryRecursively(file, new File(targetRoot, file.getName()));
}
// UTIL
private static void validateInputDirectories(File sourceRootDirectory, File targetRootDirectory)
{
if(sourceRootDirectory.isFile())
throw new UncheckedIOException(new IOException(PHR.r(
"Can't copy directory '{}', it is actually a file", sourceRootDirectory)));
if(targetRootDirectory.isFile())
throw new UncheckedIOException(new IOException(PHR.r(
"Can't copy into directory '{}', it is actually a file", targetRootDirectory)));
}
private boolean shouldCopyFile(File file)
{
for(var fileFilter : filters)
if(fileFilter.shouldFilterOut(file, sourceRootDirectory, targetRootDirectory))
return false;
return true;
}
}
|
package joshie.enchiridion.gui.book.features;
import com.google.gson.JsonObject;
import joshie.enchiridion.api.EnchiridionAPI;
import joshie.enchiridion.api.book.IButtonAction;
import joshie.enchiridion.api.book.IButtonActionProvider;
import joshie.enchiridion.gui.book.GuiSimpleEditor;
import joshie.enchiridion.gui.book.GuiSimpleEditorButton;
import joshie.enchiridion.helpers.JSONHelper;
import joshie.enchiridion.helpers.MCClientHelper;
import joshie.enchiridion.util.ELocation;
import net.minecraft.util.ResourceLocation;
import java.util.List;
public class FeatureButton extends FeatureJump implements IButtonActionProvider {
protected transient ResourceLocation hovered;
protected transient ResourceLocation unhovered;
protected transient boolean isInit = false;
private IButtonAction action; //Serialize these
private float size = 1F; //Serialize but hide
//Readables
public boolean leftClick = true;
public boolean rightClick = true;
public boolean otherClick = false;
public String tooltip = "";
public String hoverText = "";
public int hoverXOffset = 0;
public int hoverYOffset = 0;
public String unhoveredText = "";
public int unhoveredXOffset;
public int unhoveredYOffset;
public FeatureButton(){}
public FeatureButton(IButtonAction action) {
this.action = action;
setResourceLocation(true, new ELocation("arrow_left_on")); //Default
setResourceLocation(false, new ELocation("arrow_left_off")); //Default
}
@Override
public IButtonAction getAction() {
return action;
}
public void setAction(IButtonAction action) {
this.action = action;
}
public float getSize() {
return size;
}
public void setSize(float size) {
this.size = size;
}
@Override
public FeatureButton copy() {
FeatureButton button = new FeatureButton(action.copy());
button.hovered = hovered;
button.unhovered = unhovered;
button.size = size;
button.leftClick = leftClick;
button.rightClick = rightClick;
button.otherClick = otherClick;
button.tooltip = tooltip;
button.hoverText = hoverText;
button.hoverXOffset = hoverXOffset;
button.hoverYOffset = hoverYOffset;
button.unhoveredText = unhoveredText;
button.unhoveredXOffset = unhoveredXOffset;
button.unhoveredYOffset = unhoveredYOffset;
return button;
}
@Override
public void keyTyped(char character, int key) {
if (MCClientHelper.isShiftPressed()) {
if (key == 78) {
size = Math.min(15F, Math.max(0.5F, size + 0.1F));
} else if (key == 74) {
size = Math.min(15F, Math.max(0.5F, size - 0.1F));
}
}
}
@Override
public void draw(int mouseX, int mouseY) {
if (action == null || !action.isVisible()) return;
if (!isInit && action != null) { //Called here because action needs everything to be loaded, where as update doesn't
action.onFieldsSet("");
isInit = true;
}
boolean isHovered = position.isOverFeature(mouseX, mouseY);
ResourceLocation location = getResource(isHovered);
if (location != null) {
EnchiridionAPI.draw.drawImage(location, position.getLeft(), position.getTop(), position.getRight(), position.getBottom());
}
EnchiridionAPI.draw.drawSplitScaledString(getText(isHovered), position.getLeft() + getTextOffsetX(isHovered), position.getTop() + getTextOffsetY(isHovered), 200, 0x555555, size);
}
@Override
public boolean getAndSetEditMode() {
GuiSimpleEditor.INSTANCE.setEditor(GuiSimpleEditorButton.INSTANCE.setButton(this));
return true;
}
@Override
public void performClick(int mouseX, int mouseY, int button) {
if (action != null && action.isVisible() && processesClick(button)) action.performAction();
}
@Override
public void addTooltip(List<String> tooltip, int mouseX, int mouseY) {
if (action != null && action.isVisible()) {
String[] title = getTooltip().split("\n");
if (title != null) {
boolean first = false;
for (String t: title) {
if (first || !t.equals("")) {
tooltip.add(t);
} else first = true;
}
}
}
}
//Let's fix the broken json
public FeatureButton fix(JsonObject json) {
if (json.get("deflt") != null) {
String dflt = json.get("deflt").getAsJsonObject().get("path").getAsString();
setResourceLocation(false, new ResourceLocation(dflt));
}
if (json.get("hover") != null) {
String hover = json.get("hover").getAsJsonObject().get("path").getAsString();
setResourceLocation(true, new ResourceLocation(hover));
}
//Fix some more
if (json.get("action") != null && json.get("action").getAsJsonObject().get("properties") != null) {
JsonObject properties = json.get("action").getAsJsonObject().get("properties").getAsJsonObject();
if (properties.get("hoveredResource") != null) {
String hover = properties.get("hoveredResource").getAsString();
setResourceLocation(true, new ResourceLocation(hover));
}
if (properties.get("unhoveredResource") != null) {
String hover = properties.get("unhoveredResource").getAsString();
setResourceLocation(false, new ResourceLocation(hover));
}
if (properties.get("tooltip") != null) {
setTooltip(properties.get("tooltip").getAsString());
}
if (properties.get("hoverText") != null) {
setText(true, properties.get("hoverText").getAsString());
}
if (properties.get("unhoveredText") != null) {
setText(false, properties.get("unhoveredText").getAsString());
}
if (properties.get("hoverXOffset") != null) {
setTextOffsetX(true, properties.get("hoverXOffset").getAsInt());
}
if (properties.get("hoverYOffset") != null) {
setTextOffsetY(true, properties.get("hoverYOffset").getAsInt());
}
if (properties.get("unhoveredXOffset") != null) {
setTextOffsetX(false, properties.get("unhoveredXOffset").getAsInt());
}
if (properties.get("unhoveredYOffset") != null) {
setTextOffsetY(false, properties.get("unhoveredYOffset").getAsInt());
}
}
if (!leftClick && !rightClick && !otherClick) {
leftClick = true;
rightClick = true;
otherClick = true;
}
return this;
}
@Override
public String getText(boolean isHovered) {
return isHovered ? hoverText : unhoveredText;
}
@Override
public String getTooltip() {
return tooltip;
}
@Override
public boolean processesClick(int button) {
return button == 0 ? leftClick : button == 1 ? rightClick : otherClick;
}
@Override
public int getTextOffsetX(boolean isHovered) {
return isHovered ? hoverXOffset: unhoveredXOffset;
}
@Override
public int getTextOffsetY(boolean isHovered) {
return isHovered ? hoverYOffset : unhoveredYOffset;
}
@Override
public ResourceLocation getResource(boolean isHovered) {
return isHovered ? hovered : unhovered;
}
@Override
public IButtonActionProvider setResourceLocation(boolean isHovered, ResourceLocation resource) {
if (isHovered) hovered = resource;
else unhovered = resource;
return this;
}
@Override
public IButtonActionProvider setText(boolean isHovered, String text) {
if (isHovered) hoverText = text;
else unhoveredText = text;
return this;
}
@Override
public IButtonActionProvider setTooltip(String tooltip) {
this.tooltip = tooltip;
return this;
}
@Override
public IButtonActionProvider setTextOffsetX(boolean isHovered, int x) {
if (isHovered) hoverXOffset = x;
else unhoveredXOffset = x;
return this;
}
@Override
public IButtonActionProvider setTextOffsetY(boolean isHovered, int y) {
if (isHovered) hoverYOffset = y;
else unhoveredYOffset = y;
return this;
}
@Override
public IButtonActionProvider setProcessesClick(int button, boolean value) {
if (button == 0) leftClick = value;
else if (button == 1) rightClick = value;
else otherClick = value;
return this;
}
@Override
public void readFromJson(JsonObject object) {
hovered = new ResourceLocation(JSONHelper.getStringIfExists(object, "hoveredResource"));
unhovered = new ResourceLocation(JSONHelper.getStringIfExists(object, "unhoveredResource"));
}
@Override
public void writeToJson(JsonObject object) {
if (hovered != null) object.addProperty("hoveredResource", hovered.toString());
if (unhovered != null) object.addProperty("unhoveredResource", unhovered.toString());
}
}
|
package jp.crafterkina.pipes.common.item;
import net.minecraft.client.resources.I18n;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.IMerchant;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.annotation.Nonnull;
import java.util.List;
import java.util.UUID;
import static jp.crafterkina.pipes.api.PipesConstants.MOD_ID;
import static jp.crafterkina.pipes.common.RegistryEntries.ITEM.merchant_phone;
public class ItemMerchantPhone extends Item{
public ItemMerchantPhone(){
setUnlocalizedName(MOD_ID + ".merchant_phone");
setCreativeTab(CreativeTabs.MISC);
if(FMLCommonHandler.instance().getSide() == Side.CLIENT){
addPropertyOverride(new ResourceLocation("registered"), (stack, world, entity) -> stack.getTagCompound() != null && stack.getTagCompound().hasUniqueId("Merchant") ? 1 : 0);
}
MinecraftForge.EVENT_BUS.register(this);
}
@SubscribeEvent
protected void interactOnEntity(PlayerInteractEvent.EntityInteract event){
if(event.getWorld().isRemote) return;
EntityPlayer player = event.getEntityPlayer();
ItemStack stack = player.getHeldItem(event.getHand());
Entity target = event.getTarget();
if(!(target instanceof IMerchant)) return;
NBTTagCompound compound = stack.getTagCompound();
if(compound == null) stack.setTagCompound(compound = new NBTTagCompound());
if(compound.hasUniqueId("Merchant") && !player.isSneaking()) return;
compound.setUniqueId("Merchant", target.getUniqueID());
player.sendMessage(new TextComponentTranslation("mes." + merchant_phone.getUnlocalizedName() + ".register"));
event.setCanceled(true);
}
@Override
@Nonnull
public ActionResult<ItemStack> onItemRightClick(World worldIn, EntityPlayer playerIn, @Nonnull EnumHand handIn){
ItemStack stack = playerIn.getHeldItem(handIn);
if(!(worldIn instanceof WorldServer)) return new ActionResult<>(EnumActionResult.PASS, stack);
NBTTagCompound compound = stack.getTagCompound();
if(compound == null) stack.setTagCompound(compound = new NBTTagCompound());
if(!compound.hasUniqueId("Merchant")) return new ActionResult<>(EnumActionResult.PASS, stack);
UUID uuid = compound.getUniqueId("Merchant");
if(uuid == null) return new ActionResult<>(EnumActionResult.PASS, stack);
Entity entity = ((WorldServer) worldIn).getEntityFromUuid(uuid);
if(!(entity instanceof IMerchant)){
stack.getTagCompound().removeTag("MerchantMost");
stack.getTagCompound().removeTag("MerchantLeast");
return new ActionResult<>(EnumActionResult.PASS, stack);
}
((IMerchant) entity).setCustomer(playerIn);
playerIn.displayVillagerTradeGui((IMerchant) entity);
return new ActionResult<>(EnumActionResult.SUCCESS, stack);
}
@Override
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack stack, EntityPlayer playerIn, List<String> tooltip, boolean advanced){
for(int i = 0; ; i++){
if(!I18n.hasKey("tooltip." + merchant_phone.getUnlocalizedName() + "." + i)) break;
tooltip.add(I18n.format("tooltip." + merchant_phone.getUnlocalizedName() + "." + i));
}
if(advanced){
tooltip.add(String.format("Merchant UUID: %s", stack.getTagCompound() == null || !stack.getTagCompound().hasUniqueId("Merchant") ? "Not Registered" : stack.getTagCompound().getUniqueId("Merchant")));
}
}
}
|
package me.deftware.mixin.mixins.render;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.systems.RenderSystem;
import me.deftware.client.framework.FrameworkConstants;
import me.deftware.client.framework.chat.ChatMessage;
import me.deftware.client.framework.event.events.EventWeather;
import me.deftware.client.framework.render.camera.entity.CameraEntityMan;
import me.deftware.client.framework.render.shader.ShaderTarget;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.block.entity.EnderChestBlockEntity;
import net.minecraft.block.entity.LootableContainerBlockEntity;
import net.minecraft.client.gl.Framebuffer;
import net.minecraft.client.render.*;
import net.minecraft.client.render.block.entity.BlockEntityRenderDispatcher;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.entity.Entity;
import net.minecraft.entity.ItemEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.math.Matrix4f;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.ModifyArg;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.Arrays;
@Mixin(WorldRenderer.class)
public abstract class MixinWorldRenderer {
@Shadow
@Final
private BufferBuilderStorage bufferBuilders;
@Shadow
protected abstract void renderEntity(Entity entity, double cameraX, double cameraY, double cameraZ, float tickDelta, MatrixStack matrices, VertexConsumerProvider vertexConsumers);
@Shadow
protected abstract boolean canDrawEntityOutlines();
@Inject(method = "tickRainSplashing", at = @At("HEAD"), cancellable = true)
private void renderRain(Camera camera, CallbackInfo ci) {
EventWeather event = new EventWeather(EventWeather.WeatherType.Rain);
event.broadcast();
if (event.isCanceled()) {
ci.cancel();
}
}
@Inject(method = "renderWeather", at = @At("HEAD"), cancellable = true)
private void renderWeather(LightmapTextureManager manager, float tickDelta, double posX, double posY, double posZ, CallbackInfo ci) {
EventWeather event = new EventWeather(EventWeather.WeatherType.Rain);
event.broadcast();
if (event.isCanceled()) {
ci.cancel();
}
}
@ModifyArg(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/render/WorldRenderer;setupTerrain(Lnet/minecraft/client/render/Camera;Lnet/minecraft/client/render/Frustum;ZIZ)V"), index = 4)
public boolean isSpectator(boolean spectator) {
return spectator || CameraEntityMan.isActive();
}
/*
Shader
*/
@Unique
private ShaderTarget shaderTarget;
@Unique
private boolean canDrawCustomBuffers() {
if (!FrameworkConstants.OPTIFINE) {
return true;
}
return FrameworkConstants.CAN_RENDER_SHADER;
}
@Inject(method = "loadEntityOutlineShader", at = @At("HEAD"))
public void loadEntityOutlineShader(CallbackInfo ci) {
if (canDrawCustomBuffers())
Arrays.stream(ShaderTarget.values()).forEach(target -> target.init(bufferBuilders.getEntityVertexConsumers()));
}
@Inject(method = "onResized", at = @At("HEAD"))
public void onResized(int width, int height, CallbackInfo ci) {
if (canDrawCustomBuffers())
Arrays.stream(ShaderTarget.values()).forEach(target -> target.onResized(width, height));
}
@Redirect(method = "drawEntityOutlinesFramebuffer", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/render/WorldRenderer;canDrawEntityOutlines()Z", opcode = 180))
public boolean drawEntityOutlinesFramebuffer(WorldRenderer worldRenderer) {
boolean emc = Arrays.stream(ShaderTarget.values()).anyMatch(ShaderTarget::isEnabled);
if (emc && canDrawCustomBuffers()) {
RenderSystem.enableBlend();
RenderSystem.blendFuncSeparate(GlStateManager.SrcFactor.SRC_ALPHA, GlStateManager.DstFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SrcFactor.ZERO, GlStateManager.DstFactor.ONE);
Arrays.stream(ShaderTarget.values()).forEach(ShaderTarget::renderBuffer);
RenderSystem.disableBlend();
return false;
}
return canDrawEntityOutlines();
}
@Redirect(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/render/WorldRenderer;canDrawEntityOutlines()Z", opcode = 180, ordinal = 0))
private boolean onRenderHead(WorldRenderer worldRenderer) {
if (canDrawCustomBuffers()) Arrays.stream(ShaderTarget.values()).forEach(ShaderTarget::clear);
if (!FrameworkConstants.OPTIFINE) return true;
return canDrawEntityOutlines();
}
@Redirect(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/render/block/entity/BlockEntityRenderDispatcher;render(Lnet/minecraft/block/entity/BlockEntity;FLnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;)V", opcode = 180, ordinal = 0))
private void renderBlocKEntity(BlockEntityRenderDispatcher blockEntityRenderDispatcher, BlockEntity blockEntity, float tickDelta, MatrixStack matrix, VertexConsumerProvider original) {
boolean flag;
if (flag = canDrawCustomBuffers() && ShaderTarget.STORAGE.isEnabled() && (blockEntity instanceof LootableContainerBlockEntity || blockEntity instanceof EnderChestBlockEntity)) {
shaderTarget = ShaderTarget.STORAGE;
}
BlockEntityRenderDispatcher.INSTANCE.render(blockEntity, tickDelta, matrix,
flag ? shaderTarget.getOutlineVertexConsumerProvider() : original
);
}
@Inject(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/render/OutlineVertexConsumerProvider;draw()V", opcode = 180))
private void onRenderOutlineVertexConsumers(MatrixStack matrices, float tickDelta, long limitTime, boolean renderBlockOutline, Camera camera, GameRenderer gameRenderer, LightmapTextureManager lightmapTextureManager, Matrix4f matrix4f, CallbackInfo ci) {
// Draw custom outline vertex, only required for block entities
if (canDrawCustomBuffers() && shaderTarget != null && shaderTarget == ShaderTarget.STORAGE)
shaderTarget.getOutlineVertexConsumerProvider().draw();
}
@Inject(method = "getEntityOutlinesFramebuffer", at = @At("HEAD"), cancellable = true)
public void getEntityOutlinesFramebufferInject(CallbackInfoReturnable<Framebuffer> cir) {
if (canDrawCustomBuffers() && shaderTarget != null && shaderTarget.getFramebuffer() != null) {
// Return our custom frame buffer
cir.setReturnValue(shaderTarget.getFramebuffer());
}
}
@Redirect(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/render/WorldRenderer;renderEntity(Lnet/minecraft/entity/Entity;DDDFLnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;)V", opcode = 180))
private void doRenderEntity(WorldRenderer worldRenderer, Entity entity, double cameraX, double cameraY, double cameraZ, float tickDelta, MatrixStack matrices, VertexConsumerProvider vertexConsumers) {
boolean enabled;
// Player
if (entity instanceof PlayerEntity) {
if (enabled = ShaderTarget.PLAYER.isEnabled()) {
shaderTarget = ShaderTarget.PLAYER;
}
} else if (entity instanceof ItemEntity) {
if (enabled = ShaderTarget.DROPPED.isEnabled()) {
shaderTarget = ShaderTarget.DROPPED;
}
} else if (enabled = ShaderTarget.ENTITY.isEnabled()) {
shaderTarget = ShaderTarget.ENTITY;
}
if (enabled) enabled = canDrawCustomBuffers();
// Check target
if (enabled) {
enabled = shaderTarget.getPredicate().test(
new ChatMessage().fromText(entity.getType().getName()).toString(false)
);
}
renderEntity(entity, cameraX, cameraY, cameraZ, tickDelta, matrices,
enabled ? shaderTarget.getOutlineVertexConsumerProvider() : vertexConsumers
);
if (enabled) {
// Since the target could be different we have to render it now
shaderTarget.getOutlineVertexConsumerProvider().draw();
}
}
}
|
package net.geforcemods.securitycraft;
import com.mojang.blaze3d.platform.Window;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import net.geforcemods.securitycraft.api.IExplosive;
import net.geforcemods.securitycraft.blockentities.SecurityCameraBlockEntity;
import net.geforcemods.securitycraft.blocks.SecurityCameraBlock;
import net.geforcemods.securitycraft.entity.Sentry;
import net.geforcemods.securitycraft.entity.camera.SecurityCamera;
import net.geforcemods.securitycraft.misc.KeyBindings;
import net.geforcemods.securitycraft.misc.ModuleType;
import net.geforcemods.securitycraft.misc.SCSounds;
import net.geforcemods.securitycraft.util.ClientUtils;
import net.geforcemods.securitycraft.util.PlayerUtils;
import net.geforcemods.securitycraft.util.Utils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.Options;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiComponent;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.TitleScreen;
import net.minecraft.client.gui.screens.multiplayer.JoinMultiplayerScreen;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.ClipContext.Block;
import net.minecraft.world.level.ClipContext.Fluid;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.GuiOpenEvent;
import net.minecraftforge.client.event.InputEvent;
import net.minecraftforge.client.event.RenderHandEvent;
import net.minecraftforge.client.event.ScreenshotEvent;
import net.minecraftforge.client.gui.ForgeIngameGui;
import net.minecraftforge.client.gui.OverlayRegistry;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
@EventBusSubscriber(modid=SecurityCraft.MODID, value=Dist.CLIENT)
public class SCClientEventHandler
{
public static final ResourceLocation CAMERA_DASHBOARD = new ResourceLocation("securitycraft:textures/gui/camera/camera_dashboard.png");
public static final ResourceLocation BEACON_GUI = new ResourceLocation("textures/gui/container/beacon.png");
public static final ResourceLocation NIGHT_VISION = new ResourceLocation("textures/mob_effect/night_vision.png");
private static final ItemStack REDSTONE = new ItemStack(Items.REDSTONE);
@SubscribeEvent
public static void onScreenshot(ScreenshotEvent event)
{
Player player = Minecraft.getInstance().player;
if(PlayerUtils.isPlayerMountedOnCamera(player))
{
SecurityCamera camera = (SecurityCamera)Minecraft.getInstance().cameraEntity;
if(camera.screenshotSoundCooldown == 0)
{
camera.screenshotSoundCooldown = 7;
Minecraft.getInstance().level.playLocalSound(player.blockPosition(), SCSounds.CAMERASNAP.event, SoundSource.BLOCKS, 1.0F, 1.0F, true);
}
}
}
@SubscribeEvent
public static void renderHandEvent(RenderHandEvent event){
if(ClientHandler.isPlayerMountedOnCamera())
event.setCanceled(true);
}
@SubscribeEvent
public static void onClickInput(InputEvent.ClickInputEvent event) {
if(event.isAttack() && ClientHandler.isPlayerMountedOnCamera())
{
event.setCanceled(true);
event.setSwingHand(false);
}
}
@SubscribeEvent
public static void onGuiOpen(GuiOpenEvent event)
{
Screen screen = event.getGui();
//makes sure the overlays are properly reset when the player exits a world/server when viewing a camera
if(screen instanceof TitleScreen || screen instanceof JoinMultiplayerScreen)
{
OverlayRegistry.enableOverlay(ClientHandler.cameraOverlay, false);
OverlayRegistry.enableOverlay(ClientHandler.hotbarBindOverlay, true);
}
}
public static void cameraOverlay(ForgeIngameGui gui, PoseStack pose, float partialTicks, int width, int height) {
Minecraft mc = Minecraft.getInstance();
Level level = mc.level;
BlockPos pos = mc.cameraEntity.blockPosition();
Window window = mc.getWindow();
Font font = Minecraft.getInstance().font;
Options settings = Minecraft.getInstance().options;
SecurityCameraBlockEntity te = (SecurityCameraBlockEntity)level.getBlockEntity(pos);
boolean hasRedstoneModule = te.hasModule(ModuleType.REDSTONE);
Component lookAround = Utils.localize("gui.securitycraft:camera.lookAround", settings.keyUp.getTranslatedKeyMessage(), settings.keyLeft.getTranslatedKeyMessage(), settings.keyDown.getTranslatedKeyMessage(), settings.keyRight.getTranslatedKeyMessage());
Component exit = Utils.localize("gui.securitycraft:camera.exit", settings.keyShift.getTranslatedKeyMessage());
Component zoom = Utils.localize("gui.securitycraft:camera.zoom", KeyBindings.cameraZoomIn.getTranslatedKeyMessage(), KeyBindings.cameraZoomOut.getTranslatedKeyMessage());
Component nightVision = Utils.localize("gui.securitycraft:camera.activateNightVision", KeyBindings.cameraActivateNightVision.getTranslatedKeyMessage());
Component redstone = Utils.localize("gui.securitycraft:camera.toggleRedstone", KeyBindings.cameraEmitRedstone.getTranslatedKeyMessage());
Component redstoneNote = Utils.localize("gui.securitycraft:camera.toggleRedstoneNote");
String time = ClientUtils.getFormattedMinecraftTime();
int timeY = 25;
if(te.hasCustomSCName())
{
Component cameraName = te.getCustomSCName();
font.drawShadow(pose, cameraName, window.getGuiScaledWidth() - font.width(cameraName) - 8, 25, 16777215);
timeY += 10;
}
font.drawShadow(pose, time, window.getGuiScaledWidth() - font.width(time) - 4, timeY, 16777215);
font.drawShadow(pose, lookAround, window.getGuiScaledWidth() - font.width(lookAround) - 8, window.getGuiScaledHeight() - 80, 16777215);
font.drawShadow(pose, exit, window.getGuiScaledWidth() - font.width(exit) - 8, window.getGuiScaledHeight() - 70, 16777215);
font.drawShadow(pose, zoom, window.getGuiScaledWidth() - font.width(zoom) - 8, window.getGuiScaledHeight() - 60, 16777215);
font.drawShadow(pose, nightVision, window.getGuiScaledWidth() - font.width(nightVision) - 8, window.getGuiScaledHeight() - 50, 16777215);
font.drawShadow(pose, redstone, window.getGuiScaledWidth() - font.width(redstone) - 8, window.getGuiScaledHeight() - 40, hasRedstoneModule ? 16777215 : 16724855);
font.drawShadow(pose, redstoneNote, window.getGuiScaledWidth() - font.width(redstoneNote) -8, window.getGuiScaledHeight() - 30, hasRedstoneModule ? 16777215 : 16724855);
RenderSystem._setShaderTexture(0, CAMERA_DASHBOARD);
RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
gui.blit(pose, 5, 0, 0, 0, 90, 20);
gui.blit(pose, window.getGuiScaledWidth() - 70, 5, 190, 0, 65, 30);
if(!mc.player.hasEffect(MobEffects.NIGHT_VISION))
gui.blit(pose, 28, 4, 90, 12, 16, 11);
else{
RenderSystem._setShaderTexture(0, NIGHT_VISION);
GuiComponent.blit(pose, 27, -1, 0, 0, 18, 18, 18, 18);
RenderSystem._setShaderTexture(0, CAMERA_DASHBOARD);
}
BlockState state = level.getBlockState(pos);
if((state.getSignal(level, pos, state.getValue(SecurityCameraBlock.FACING)) == 0) && !te.hasModule(ModuleType.REDSTONE))
gui.blit(pose, 12, 2, 104, 0, 12, 12);
else if((state.getSignal(level, pos, state.getValue(SecurityCameraBlock.FACING)) == 0) && te.hasModule(ModuleType.REDSTONE))
gui.blit(pose, 12, 3, 90, 0, 12, 11);
else
Minecraft.getInstance().getItemRenderer().renderAndDecorateItem(REDSTONE, 10, 0);
}
public static void hotbarBindOverlay(ForgeIngameGui gui, PoseStack pose, float partialTicks, int width, int height) {
Minecraft mc = Minecraft.getInstance();
LocalPlayer player = mc.player;
Level world = player.getCommandSenderWorld();
for (InteractionHand hand : InteractionHand.values()) {
int uCoord = 0;
ItemStack stack = player.getItemInHand(hand);
if(stack.getItem() == SCContent.CAMERA_MONITOR.get())
{
double eyeHeight = player.getEyeHeight();
Vec3 lookVec = new Vec3((player.getX() + (player.getLookAngle().x * 5)), ((eyeHeight + player.getY()) + (player.getLookAngle().y * 5)), (player.getZ() + (player.getLookAngle().z * 5)));
HitResult mop = world.clip(new ClipContext(new Vec3(player.getX(), player.getY() + player.getEyeHeight(), player.getZ()), lookVec, Block.OUTLINE, Fluid.NONE, player));
if(mop instanceof BlockHitResult bhr && world.getBlockEntity(bhr.getBlockPos()) instanceof SecurityCameraBlockEntity)
{
CompoundTag cameras = stack.getTag();
uCoord = 110;
if(cameras != null) {
for(int i = 1; i < 31; i++)
{
if(!cameras.contains("Camera" + i))
continue;
String[] coords = cameras.getString("Camera" + i).split(" ");
if(Integer.parseInt(coords[0]) == bhr.getBlockPos().getX() && Integer.parseInt(coords[1]) == bhr.getBlockPos().getY() && Integer.parseInt(coords[2]) == bhr.getBlockPos().getZ())
{
uCoord = 88;
break;
}
}
}
}
}
else if(stack.getItem() == SCContent.REMOTE_ACCESS_MINE.get())
{
double eyeHeight = player.getEyeHeight();
Vec3 lookVec = new Vec3((player.getX() + (player.getLookAngle().x * 5)), ((eyeHeight + player.getY()) + (player.getLookAngle().y * 5)), (player.getZ() + (player.getLookAngle().z * 5)));
HitResult mop = world.clip(new ClipContext(new Vec3(player.getX(), player.getY() + player.getEyeHeight(), player.getZ()), lookVec, Block.OUTLINE, Fluid.NONE, player));
if(mop instanceof BlockHitResult bhr && world.getBlockState(bhr.getBlockPos()).getBlock() instanceof IExplosive)
{
uCoord = 110;
CompoundTag mines = stack.getTag();
if(mines != null) {
for(int i = 1; i <= 6; i++)
{
if(stack.getTag().getIntArray("mine" + i).length > 0)
{
int[] coords = mines.getIntArray("mine" + i);
if(coords[0] == bhr.getBlockPos().getX() && coords[1] == bhr.getBlockPos().getY() && coords[2] == bhr.getBlockPos().getZ())
{
uCoord = 88;
break;
}
}
}
}
}
}
else if(stack.getItem() == SCContent.REMOTE_ACCESS_SENTRY.get())
{
Entity hitEntity = Minecraft.getInstance().crosshairPickEntity;
if(hitEntity instanceof Sentry)
{
uCoord = 110;
CompoundTag sentries = stack.getTag();
if(sentries != null) {
for(int i = 1; i <= 12; i++)
{
if(stack.getTag().getIntArray("sentry" + i).length > 0)
{
int[] coords = sentries.getIntArray("sentry" + i);
if(coords[0] == hitEntity.blockPosition().getX() && coords[1] == hitEntity.blockPosition().getY() && coords[2] == hitEntity.blockPosition().getZ())
{
uCoord = 88;
break;
}
}
}
}
}
}
if (uCoord != 0) {
RenderSystem._setShaderTexture(0, BEACON_GUI);
GuiComponent.blit(pose, Minecraft.getInstance().getWindow().getGuiScaledWidth() / 2 - 90 + (hand == InteractionHand.MAIN_HAND ? player.getInventory().selected * 20 : -29), Minecraft.getInstance().getWindow().getGuiScaledHeight() - 22, uCoord, 219, 21, 22, 256, 256);
}
}
}
}
|
package net.openhft.chronicle.map.internal;
import net.openhft.chronicle.core.analytics.AnalyticsFacade;
import net.openhft.chronicle.core.pom.PomProperties;
public enum AnalyticsHolder {;
// Todo: VERSION is "unknown" for some reason
private static final String VERSION = PomProperties.version("net.openhft", "chronicle-map");
private static final AnalyticsFacade ANALYTICS = AnalyticsFacade.standardBuilder("G-TDTJG5CT6G", "J8qsWGHgQP6CLs43mQ10KQ", VERSION)
//.withReportDespiteJUnit()
.withDebugLogger(System.out::println)
.build();
public static AnalyticsFacade instance() {
return ANALYTICS;
}
}
|
package org.cboard.elasticsearch;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import org.apache.commons.collections.keyvalue.DefaultMapEntry;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.cboard.cache.CacheManager;
import org.cboard.cache.HeapCacheManager;
import org.cboard.dataprovider.DataProvider;
import org.cboard.dataprovider.Initializing;
import org.cboard.dataprovider.aggregator.Aggregatable;
import org.cboard.dataprovider.annotation.DatasourceParameter;
import org.cboard.dataprovider.annotation.ProviderName;
import org.cboard.dataprovider.annotation.QueryParameter;
import org.cboard.dataprovider.config.*;
import org.cboard.dataprovider.result.AggregateResult;
import org.cboard.dataprovider.result.ColumnIndex;
import org.cboard.elasticsearch.query.QueryBuilder;
import org.cboard.util.json.JSONBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static org.cboard.elasticsearch.aggregation.AggregationBuilder.dateHistAggregation;
import static org.cboard.elasticsearch.aggregation.AggregationBuilder.termsAggregation;
import static org.cboard.elasticsearch.query.QueryBuilder.*;
import static org.cboard.util.SqlMethod.coalesce;
@ProviderName(name = "Elasticsearch")
public class ElasticsearchDataProvider extends DataProvider implements Aggregatable, Initializing {
private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchDataProvider.class);
@DatasourceParameter(label = "Elasticsearch Server (domain:port)", type = DatasourceParameter.Type.Input, order = 1)
protected String SERVERIP = "serverIp";
@QueryParameter(label = "Index", type = QueryParameter.Type.Input, order = 2)
protected String INDEX = "index";
@QueryParameter(label = "Type", type = QueryParameter.Type.Input, order = 3)
protected String TYPE = "type";
@DatasourceParameter(label = "UserName", type = DatasourceParameter.Type.Input, order = 4)
private String USERNAME = "username";
@DatasourceParameter(label = "Password", type = DatasourceParameter.Type.Password, order = 5)
private String PASSWORD = "password";
@QueryParameter(label = "Override Aggregations", type = QueryParameter.Type.TextArea, order = 6)
private String OVERRIDE = "override";
@DatasourceParameter(label = "Charset", type = DatasourceParameter.Type.Input, order = 7)
private String CHARSET = "charset";
private JSONObject overrideAggregations = new JSONObject();
private static final CacheManager<Map<String, String>> typesCache = new HeapCacheManager<>();
private static final JSONPath jsonPath_value = JSONPath.compile("$..value");
private static final List<String> numericTypes = new ArrayList<>();
private static final Integer NULL_NUMBER = -999;
static {
numericTypes.add("long");
numericTypes.add("integer");
numericTypes.add("short");
numericTypes.add("byte");
numericTypes.add("double");
numericTypes.add("float");
}
@Override
public boolean doAggregationInDataSource() {
return true;
}
@Override
public String[] queryDimVals(String columnName, AggConfig config) throws Exception {
JSONObject request = new JSONObject();
request.put("size", 1000);
request.put("aggregations", getAggregation(columnName, config));
if (config != null) {
JSONArray filter = getFilter(config);
if (filter.size() > 0) {
request.put("query", buildFilterDSL(config));
}
}
JSONObject response = post(getSearchUrl(request), request);
String[] filtered = response.getJSONObject("aggregations").getJSONObject(columnName).getJSONArray("buckets").stream()
.map(e -> ((JSONObject) e).getString("key"))
.map(e -> e.replaceAll(NULL_NUMBER.toString(), NULL_STRING))
.toArray(String[]::new);
return filtered;
}
private JSONArray getFilter(AggConfig config) {
Stream<DimensionConfig> c = config.getColumns().stream();
Stream<DimensionConfig> r = config.getRows().stream();
Stream<ConfigComponent> f = config.getFilters().stream();
Stream<ConfigComponent> filters = Stream.concat(Stream.concat(c, r), f);
JSONArray result = new JSONArray();
filters.map(e -> separateNull(e)).map(e -> configComponentToFilter(e)).filter(e -> e != null).forEach(result::add);
return result;
}
private JSONObject configComponentToFilter(ConfigComponent cc) {
if (cc instanceof DimensionConfig) {
return getFilterPart((DimensionConfig) cc);
} else if (cc instanceof CompositeConfig) {
CompositeConfig compositeConfig = (CompositeConfig) cc;
BoolType boolType = BoolType.MUST;
if ("AND".equalsIgnoreCase(compositeConfig.getType())) {
boolType = BoolType.MUST;
} else if ("OR".equalsIgnoreCase(compositeConfig.getType())) {
boolType = BoolType.SHOULD;
}
JSONArray boolArr = new JSONArray();
compositeConfig.getConfigComponents().stream().map(e -> separateNull(e)).map(e -> configComponentToFilter(e)).forEach(boolArr::add);
return boolFilter(boolType, boolArr);
}
return null;
}
private JSONObject getFilterPart(DimensionConfig config) {
if (config.getValues().size() == 0) {
return null;
}
String fieldName = config.getColumnName();
String v0 = config.getValues().get(0);
String v1 = null;
if (config.getValues().size() == 2) {
v1 = config.getValues().get(1);
}
if (NULL_STRING.equals(v0)) {
switch (config.getFilterType()) {
case "=":
case "≠":
return nullQuery(fieldName, "=".equals(config.getFilterType()));
}
}
switch (config.getFilterType()) {
case "=":
case "eq":
return termsQuery(fieldName, config.getValues());
case "≠":
case "ne":
return getFilterPartEq(BoolType.MUST_NOT, fieldName, config.getValues());
case ">":
return rangeQuery(fieldName, v0, null);
case "<":
return rangeQuery(fieldName, null, v0);
case "≥":
return rangeQuery(fieldName, v0, null, true, true);
case "≤":
return rangeQuery(fieldName, null, v0, true, true);
case "(a,b]":
return rangeQuery(fieldName, v0, v1, false, true);
case "[a,b)":
return rangeQuery(fieldName, v0, v1, true, false);
case "(a,b)":
return rangeQuery(fieldName, v0, v1, false, false);
case "[a,b]":
return rangeQuery(fieldName, v0, v1, true, true);
}
return null;
}
private JSONObject getFilterPartEq(BoolType boolType, String fieldName, List<String> values) {
JSONArray boolArr = new JSONArray();
values.stream()
.map(e -> termQuery(fieldName, e))
.forEach(boolArr::add);
return QueryBuilder.boolFilter(boolType, boolArr);
}
protected JSONObject post(String url, JSONObject request) throws Exception {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
HttpPost httpPost = new HttpPost(url);
StringEntity reqEntity = new StringEntity(request.toString());
httpPost.setEntity(reqEntity);
HttpResponse httpResponse = httpClientBuilder.build().execute(httpPost, getHttpContext());
String response = EntityUtils.toString(httpResponse.getEntity(), dataSource.get(CHARSET));
if (httpResponse.getStatusLine().getStatusCode() == 200) {
return JSONObject.parseObject(response);
} else {
throw new Exception(response);
}
}
protected JSONObject get(String url) throws Exception {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpClientBuilder.build().execute(httpget, getHttpContext());
return JSONObject.parseObject(EntityUtils.toString(response.getEntity(), dataSource.get(CHARSET)));
}
private HttpClientContext getHttpContext() {
HttpClientContext context = HttpClientContext.create();
String userName = dataSource.get(USERNAME);
String password = dataSource.get(PASSWORD);
if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
return context;
}
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(
new AuthScope(AuthScope.ANY),
new UsernamePasswordCredentials(userName, password)
);
context.setCredentialsProvider(provider);
AuthCache authCache = new BasicAuthCache();
context.setAuthCache(authCache);
return context;
}
private JSONObject getOverrideTermsAggregation(String columnName) {
if (overrideAggregations.containsKey(columnName)) {
JSONObject override = new JSONObject();
override.put(columnName, overrideAggregations.getJSONObject(columnName));
return override;
}
return null;
}
private JSONObject getAggregation(String columnName, AggConfig config) {
DimensionConfig d = new DimensionConfig();
d.setColumnName(columnName);
return getAggregation(d, config);
}
private JSONObject getAggregation(DimensionConfig d, AggConfig config) {
JSONObject aggregation = null;
try {
Map<String, String> types = getTypes();
JSONObject overrideAgg = getOverrideTermsAggregation(d.getColumnName());
// Build default aggregation
switch (types.get(d.getColumnName())) {
case "date":
aggregation = buildDateHistAggregation(d.getColumnName(), config);
break;
default:
Object missing = numericTypes.contains(getTypes().get(d.getColumnName())) ? NULL_NUMBER : NULL_STRING;
aggregation = json(d.getColumnName(), termsAggregation(d.getColumnName(), 1000, missing));
}
// Query Override
if (overrideAgg != null) {
aggregation = overrideAgg;
}
// Schema Override
if (StringUtils.isNotEmpty(d.getCustom())) {
aggregation = json(d.getColumnName(), JSONObject.parseObject(d.getCustom()).get("esBucket"));
}
} catch (Exception e) {
e.printStackTrace();
}
return aggregation;
}
private JSONObject buildDateHistAggregation(String columnName, AggConfig config) throws Exception {
if (config == null) {
return queryBound(columnName, config);
}
String intervalStr = "10m";
JSONObject queryDsl = buildFilterDSL(config);
Object object = JSONPath.compile("$.." + columnName.replace(".", "\\.")).eval(queryDsl);
List<JSONObject> array = (List) object;
Long lower = array.stream()
.map(jo -> coalesce(jo.getLong("gt"), jo.getLong("gte")))
.filter(Objects::nonNull)
.max(Comparator.naturalOrder())
.orElse(null);
Long upper = array.stream()
.map(jo -> coalesce(jo.getLong("lt"), jo.getLong("lte")))
.filter(Objects::nonNull)
.min(Comparator.naturalOrder())
.orElse(new Date().getTime());
if (lower == null || lower >= upper) {
return queryBound(columnName, config);
}
intervalStr = dateInterval(lower, upper);
return json(columnName, dateHistAggregation(columnName, intervalStr, 0, lower, upper));
}
private JSONObject queryBound(String columnName, AggConfig config) {
String maxKey = "max_ts";
String minKey = "min_ts";
JSONBuilder request = json("size", 0).
put("aggregations", json().
put(minKey, json("min", json("field", columnName))).
put(maxKey, json("max", json("field", columnName)))
);
if (config != null) {
JSONArray filter = getFilter(config);
if (filter.size() > 0) {
request.put("query", buildFilterDSL(config));
}
}
String intervalStr = "10m";
try {
JSONObject response = post(getSearchUrl(request), request);
long maxTs = coalesce(response.getJSONObject("aggregations").getJSONObject(maxKey).getLong("value"), 0l);
long minTs = coalesce(response.getJSONObject("aggregations").getJSONObject(minKey).getLong("value"), 0l);
intervalStr = dateInterval(minTs, maxTs);
} catch (Exception e) {
e.printStackTrace();
}
return json(columnName, dateHistAggregation(columnName, intervalStr, 0));
}
protected String dateInterval(long minTs, long maxTs) {
String intervalStr = "1m";
int buckets = 100;
long stepTs = (maxTs - minTs) / buckets;
long minutesOfDuration = Duration.ofMillis(stepTs).toMinutes();
long secondsOfDuration = Duration.ofMillis(stepTs).toMillis() / 1000;
if (minutesOfDuration > 0) {
intervalStr = minutesOfDuration + "m";
} else if (secondsOfDuration > 0) {
intervalStr = secondsOfDuration + "s";
}
return intervalStr;
}
protected String getMappingUrl() {
return String.format("http://%s/%s/_mapping/%s", dataSource.get(SERVERIP), query.get(INDEX), query.get(TYPE));
}
protected String getSearchUrl(JSONObject request) {
return String.format("http://%s/%s/%s/_search", dataSource.get(SERVERIP), query.get(INDEX), query.get(TYPE));
}
@Override
public String[] getColumn() throws Exception {
typesCache.remove(getKey());
Map<String, String> types = getTypes();
return types.keySet().toArray(new String[0]);
}
private Map<String, String> getTypes() throws Exception {
String key = getKey();
Map<String, String> types = typesCache.get(key);
if (types == null) {
synchronized (key.intern()) {
types = typesCache.get(key);
if (types == null) {
JSONObject mapping = get(getMappingUrl());
mapping = mapping.getJSONObject(mapping.keySet().iterator().next()).getJSONObject("mappings").getJSONObject(query.get(TYPE));
types = new HashMap<>();
getField(types, new DefaultMapEntry(null, mapping), null);
typesCache.put(key, types, 1 * 60 * 60 * 1000);
}
}
}
return types;
}
@Override
public AggregateResult queryAggData(AggConfig config) throws Exception {
LOG.info("queryAggData");
JSONObject request = getQueryAggDataRequest(config);
JSONObject response = post(getSearchUrl(request), request);
Stream<DimensionConfig> dimStream = Stream.concat(config.getColumns().stream(), config.getRows().stream());
List<ColumnIndex> dimensionList = dimStream.map(ColumnIndex::fromDimensionConfig).collect(Collectors.toList());
List<ColumnIndex> valueList = config.getValues().stream().map(ColumnIndex::fromValueConfig).collect(Collectors.toList());
List<ColumnIndex> columnList = new ArrayList<>();
columnList.addAll(dimensionList);
columnList.addAll(valueList);
IntStream.range(0, columnList.size()).forEach(j -> columnList.get(j).setIndex(j));
List<String[]> result = new ArrayList<>();
JSONObject aggregations = response.getJSONObject("aggregations");
getAggregationResponse(aggregations, result, null, 0, dimensionList, valueList);
String[][] _result = result.toArray(new String[][]{});
Map<String, String> types = getTypes();
int[] numericIdx = dimensionList.stream().filter(e -> numericTypes.contains(types.get(e.getName())))
.map(e -> e.getIndex()).mapToInt(e -> e).toArray();
for (String[] strings : _result) {
for (int i : numericIdx) {
strings[i] = strings[i].replaceAll(NULL_NUMBER.toString(), NULL_STRING);
}
}
return new AggregateResult(columnList, _result);
}
private JSONObject getQueryAggDataRequest(AggConfig config) throws Exception {
Stream<DimensionConfig> c = config.getColumns().stream();
Stream<DimensionConfig> r = config.getRows().stream();
Stream<DimensionConfig> aggregationStream = Stream.concat(c, r);
List<JSONObject> termAggregations =
aggregationStream.map(e -> getAggregation(e, config))
.collect(Collectors.toList());
JSONObject metricAggregations = getMetricAggregation(config.getValues(), getTypes());
termAggregations.add(metricAggregations);
JSONObject request = new JSONObject();
for (int i = termAggregations.size() - 1; i > 0; i
JSONObject pre = termAggregations.get(i - 1);
String key = pre.keySet().iterator().next();
pre.getJSONObject(key).put("aggregations", termAggregations.get(i));
}
request.put("size", 0);
request.put("query", buildFilterDSL(config));
request.put("aggregations", termAggregations.get(0));
return request;
}
public JSONObject buildFilterDSL(AggConfig config) {
return boolFilter(BoolType.FILTER, getFilter(config));
}
private void getAggregationResponse(JSONObject object, List<String[]> result, List<String> parentKeys, int dimensionLevel, List<ColumnIndex> dimensionList, List<ColumnIndex> valueList) {
List<String> keys = new ArrayList<>();
if (parentKeys != null) {
keys.addAll(parentKeys);
}
if (dimensionLevel > 0) {
keys.add(object.getOrDefault("key_as_string", object.getString("key")).toString());
}
if (dimensionLevel >= dimensionList.size()) {
for (ColumnIndex value : valueList) {
String valueKey = getAggregationName(value.getAggType(), value.getName());
JSONObject valueObject = object.getJSONObject(valueKey);
List<Object> values = (List<Object>) jsonPath_value.eval(valueObject);
keys.add("" + values.get(0));
}
result.add(keys.toArray(new String[keys.size()]));
} else {
JSONArray buckets = object.getJSONObject(dimensionList.get(dimensionLevel).getName()).getJSONArray("buckets");
for (Object _bucket : buckets) {
int nextLevel = dimensionLevel + 1;
getAggregationResponse((JSONObject) _bucket, result, keys, nextLevel, dimensionList, valueList);
}
}
}
private String getAggregationName(String aggregationType, String columnName) {
return Hashing.crc32().newHasher().putString(aggregationType + columnName, Charsets.UTF_8).hash().toString();
}
private JSONObject getMetricAggregation(List<ValueConfig> configList, Map<String, String> typesCache) {
JSONObject aggregation = new JSONObject();
configList.stream().forEach(config -> {
String aggregationName = getAggregationName(config.getAggType(), config.getColumn());
String type;
switch (config.getAggType()) {
case "sum":
type = "sum";
break;
case "avg":
type = "avg";
break;
case "max":
type = "max";
break;
case "min":
type = "min";
break;
case "distinct":
type = "cardinality";
break;
default:
type = "value_count";
break;
}
aggregation.put(aggregationName, new JSONObject());
if (typesCache.containsKey(config.getColumn())) {
aggregation.getJSONObject(aggregationName).put(type, new JSONObject());
aggregation.getJSONObject(aggregationName).getJSONObject(type).put("field", config.getColumn());
} else {
JSONObject extend = JSONObject.parseObject(config.getColumn());
String column = extend.getString("column");
JSONObject filter = extend.getJSONObject("filter");
JSONObject script = extend.getJSONObject("script");
JSONObject _aggregations = aggregation.getJSONObject(aggregationName);
if (filter != null) {
_aggregations.put("filter", filter);
_aggregations.put("aggregations", new JSONObject());
_aggregations.getJSONObject("aggregations").put("agg_value", new JSONObject());
_aggregations = _aggregations.getJSONObject("aggregations").getJSONObject("agg_value");
}
_aggregations.put(type, new JSONObject());
_aggregations = _aggregations.getJSONObject(type);
if (script != null) {
_aggregations.put("script", script);
} else {
_aggregations.put("field", column);
}
}
});
return aggregation;
}
@Override
public String[][] getData() throws Exception {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
HttpGet httpget = new HttpGet(getMappingUrl());
HttpResponse httpResponse = httpClientBuilder.build().execute(httpget, getHttpContext());
String response = EntityUtils.toString(httpResponse.getEntity(), dataSource.get(CHARSET));
if (httpResponse.getStatusLine().getStatusCode() == 200) {
return new String[0][];
} else {
throw new Exception(response);
}
}
private String getKey() {
return Hashing.md5().newHasher().putString(JSONObject.toJSON(dataSource).toString() + JSONObject.toJSON(query).toString(), Charsets.UTF_8).hash().toString();
}
private void getField(Map<String, String> types, Map.Entry<String, Object> field, String parent) {
JSONObject property = (JSONObject) field.getValue();
if (property.keySet().contains("properties")) {
for (Map.Entry e : property.getJSONObject("properties").entrySet()) {
String key = field.getKey();
if (parent != null) {
key = parent + "." + field.getKey();
}
getField(types, e, key);
}
} else {
String key = null;
String type = property.getString("type");
if (parent == null) {
key = field.getKey();
} else {
key = parent + "." + field.getKey();
}
if (isTextWithoutKeywordField(property)) {
return;
}
if (isTextWithKeywordField(property)) {
key += ".keyword";
}
types.put(key, type);
}
}
private boolean isTextWithKeywordField(JSONObject property) {
String type = property.getString("type");
return "text".equals(type) && JSONPath.containsValue(property, "$.fields..type", "keyword");
}
private boolean isTextWithoutKeywordField(JSONObject property) {
String type = property.getString("type");
return "text".equals(type) && !JSONPath.containsValue(property, "$.fields..type", "keyword");
}
@Override
public String viewAggDataQuery(AggConfig ac) throws Exception {
String format = "curl -XPOST '%s?pretty' -d '\n%s'";
JSONObject request = getQueryAggDataRequest(ac);
String dsl = JSON.toJSONString(request, true);
return String.format(format, getSearchUrl(request), dsl);
}
@Override
public void afterPropertiesSet() throws Exception {
if (StringUtils.isNotBlank(query.get(OVERRIDE))) {
overrideAggregations = JSONObject.parseObject(query.get(OVERRIDE));
}
}
}
|
package org.fiteagle.north.sfa.am.allocate;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBException;
import javax.xml.stream.XMLStreamException;
import com.hp.hpl.jena.datatypes.xsd.XSDDateTime;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.vocabulary.OWL;
import org.fiteagle.api.core.Config;
import org.fiteagle.api.core.IConfig;
import org.fiteagle.api.core.IGeni;
import org.fiteagle.api.core.IMessageBus;
import org.fiteagle.api.core.MessageBusOntologyModel;
import org.fiteagle.api.core.MessageUtil;
import org.fiteagle.api.core.OntologyModelUtil;
import org.fiteagle.api.core.TimeHelperMethods;
import org.fiteagle.north.sfa.am.ISFA_AM;
import org.fiteagle.north.sfa.am.ReservationStateEnum;
import org.fiteagle.north.sfa.am.common.AbstractMethodProcessor;
import org.fiteagle.north.sfa.exceptions.BadArgumentsException;
import org.fiteagle.north.sfa.util.URN;
import com.hp.hpl.jena.vocabulary.RDF;
import info.openmultinet.ontology.exceptions.DeprecatedRspecVersionException;
import info.openmultinet.ontology.exceptions.InvalidModelException;
import info.openmultinet.ontology.exceptions.InvalidRspecValueException;
import info.openmultinet.ontology.exceptions.MissingRspecElementException;
import info.openmultinet.ontology.translators.dm.DeliveryMechanism;
import info.openmultinet.ontology.translators.geni.ManifestConverter;
import info.openmultinet.ontology.translators.tosca.Tosca2OMN.UnsupportedException;
import info.openmultinet.ontology.vocabulary.Omn;
import info.openmultinet.ontology.vocabulary.Omn_lifecycle;
public class ProcessAllocate extends AbstractMethodProcessor {
private final static Logger LOGGER = Logger.getLogger(ProcessAllocate.class
.getName());
private Map<String, Object> allocateOptions = new HashMap<>();
private URN urn;
private String request;
public ProcessAllocate(List<?> parameter) {
this.parameter = parameter;
}
public void parseAllocateParameter() throws JAXBException,
InvalidModelException {
ProcessAllocate.LOGGER.log(Level.INFO, "parsing allocate parameter");
LOGGER.log(Level.INFO, "allocate parameters " + this.parameter);
LOGGER.log(Level.INFO, "number of allocate parameters "
+ this.parameter.size());
if (parameter.get(0) == null || parameter.get(2) == null) {
throw new BadArgumentsException(
"sliceUrn and rspec fileds must not be null");
}
String slice_urn = (String) parameter.get(0);
this.urn = new URN(slice_urn);
LOGGER.log(Level.INFO, "urn " + this.urn);
this.request = (String) parameter.get(2);
LOGGER.log(Level.INFO, "request " + this.request);
@SuppressWarnings("unchecked")
final Map<String, ?> param2 = (Map<String, ?>) parameter.get(3);
if (!param2.isEmpty()) {
for (Map.Entry<String, ?> parameters : param2.entrySet()) {
if (parameters.getKey().toString().equals(IGeni.GENI_END_TIME)) {
allocateOptions.put(ISFA_AM.EndTime, parameters.getValue()
.toString());
ProcessAllocate.LOGGER.log(Level.INFO,
allocateOptions.get(ISFA_AM.EndTime).toString());
}
if (parameters.getKey().toString()
.equals(IGeni.GENI_START_TIME)) {
allocateOptions.put(ISFA_AM.StartTime, parameters
.getValue().toString());
}
}
}
}
public Model reserveInstances() throws JAXBException,
InvalidModelException, MissingRspecElementException,
InvalidRspecValueException {
Model incoming = parseRSpec(request);
Model requestModel = ModelFactory.createDefaultModel();
Resource topology = requestModel.createResource("http:
+ this.urn.getDomain() + "/topology/" + this.urn.getSubject());
topology.addProperty(RDF.type, Omn.Topology);
if (!this.urn.getProject().isEmpty()) {
topology.addProperty(Omn_lifecycle.project, this.urn.getProject());
}
Model leaseInfo = getLeaseInfo(topology, incoming);
requestModel.add(leaseInfo);
addDateInformation(topology);
Model requestedResources = getRequestedResources(topology, incoming);
requestModel.add(requestedResources);
String serializedModel = MessageUtil.serializeModel(requestModel,
IMessageBus.SERIALIZATION_TURTLE);
LOGGER.log(Level.INFO, "START: Reserving model: " + serializedModel);
Model resultModel = getSender().sendRDFRequest(serializedModel,
IMessageBus.TYPE_CREATE, IMessageBus.TARGET_RESERVATION);
LOGGER.log(
Level.INFO,
"END: Reserving model: "
+ OntologyModelUtil.toString(resultModel));
return resultModel;
}
private Model getLeaseInfo(Resource topologyResource, Model incoming) {
ResIterator topologies = incoming.listSubjectsWithProperty(RDF.type,
Omn.Topology);
if (!topologies.hasNext()) {
return null;
}
Resource incomingTopology = topologies.next();
LOGGER.log(Level.INFO, "getLeaseInfo");
String serializedModel = MessageUtil.serializeModel(incoming,
IMessageBus.SERIALIZATION_TURTLE);
LOGGER.log(Level.INFO, "getLeaseInfo: incoming model "
+ serializedModel);
Model leaseInfo = ModelFactory.createDefaultModel();
Resource topology = leaseInfo.createResource(topologyResource.getURI());
if (incomingTopology.hasProperty(Omn_lifecycle.hasLease)) {
LOGGER.log(Level.INFO,
"createReservationModel: hasLease property present");
Resource lease = incomingTopology
.getProperty(Omn_lifecycle.hasLease).getObject()
.asResource();
if (lease.hasProperty(Omn_lifecycle.startTime)) {
XSDDateTime time = null;
Object startTime = ((Object) lease
.getProperty(Omn_lifecycle.startTime).getObject()
.asLiteral().getValue());
if (startTime instanceof XSDDateTime) {
time = (XSDDateTime) startTime;
}
Date date = TimeHelperMethods.getDateFromXSD(time);
Property property = leaseInfo.createProperty(
MessageBusOntologyModel.startTime.getNameSpace(),
MessageBusOntologyModel.startTime.getLocalName());
property.addProperty(RDF.type, OWL.FunctionalProperty);
topology.addProperty(property, new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ssXXX").format(date));
}
if (lease.hasProperty(Omn_lifecycle.expirationTime)) {
XSDDateTime time = null;
Object startTime = ((Object) lease
.getProperty(Omn_lifecycle.expirationTime).getObject()
.asLiteral().getValue());
if (startTime instanceof XSDDateTime) {
time = (XSDDateTime) startTime;
}
Date date = TimeHelperMethods.getDateFromXSD(time);
Property property = leaseInfo.createProperty(
MessageBusOntologyModel.endTime.getNameSpace(),
MessageBusOntologyModel.endTime.getLocalName());
property.addProperty(RDF.type, OWL.FunctionalProperty);
topology.addProperty(property, new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ssXXX").format(date));
}
}
return leaseInfo;
}
private void addDateInformation(Resource topology) {
if (allocateOptions.get(ISFA_AM.EndTime) != null) {
String endTime = (String) allocateOptions.get(ISFA_AM.EndTime);
Property property = topology.getModel().createProperty(
MessageBusOntologyModel.endTime.getNameSpace(),
MessageBusOntologyModel.endTime.getLocalName());
property.addProperty(RDF.type, OWL.FunctionalProperty);
topology.addProperty(property, endTime);
}
if (allocateOptions.get(ISFA_AM.StartTime) != null) {
String startTime = (String) allocateOptions.get(ISFA_AM.StartTime);
Property property = topology.getModel().createProperty(
MessageBusOntologyModel.startTime.getNameSpace(),
MessageBusOntologyModel.startTime.getLocalName());
property.addProperty(RDF.type, OWL.FunctionalProperty);
topology.addProperty(property, startTime);
}
}
private Model getRequestedResources(Resource topology, Model requestedModel) {
ResIterator resIterator = requestedModel.listSubjects();
// ResIterator resIterator =
// requestedModel.listResourcesWithProperty(Omn.isResourceOf);
Model requestedResourcesModel = ModelFactory.createDefaultModel();
Map<String, Resource> originalResourceNames = new HashMap<String, Resource>();
while (resIterator.hasNext()) {
Resource oldResource = resIterator.nextResource();
if (oldResource.hasProperty(Omn.isResourceOf)) {
Resource newResource = null;
if (oldResource.hasProperty(Omn_lifecycle.implementedBy)) {
Resource oldBase = oldResource
.getProperty(Omn_lifecycle.implementedBy)
.getObject().asResource();
newResource = requestedResourcesModel
.createResource(oldBase.getURI() + "/"
+ oldResource.getLocalName());
} else {
newResource = requestedResourcesModel
.createResource(oldResource.getURI());
}
originalResourceNames.put(oldResource.getURI(), newResource);
StmtIterator stmtIterator = oldResource.listProperties();
while (stmtIterator.hasNext()) {
Statement statement = stmtIterator.nextStatement();
if (statement.getPredicate().equals(Omn.isResourceOf)) {
newResource.addProperty(statement.getPredicate(),
topology);
} else {
newResource.addProperty(statement.getPredicate(),
statement.getObject());
}
if (statement.getPredicate().equals(
Omn_lifecycle.usesService)) {
Resource service = requestedModel.getResource(statement
.getObject().asResource().getURI());
StmtIterator serviceProperties = service
.listProperties();
while (serviceProperties.hasNext()) {
requestedResourcesModel.add(serviceProperties
.nextStatement());
}
}
}
topology.addProperty(Omn.hasResource, newResource);
requestedResourcesModel.add(topology
.getProperty(Omn.hasResource));
} else if (oldResource.hasProperty(Omn.hasResource)) {
} else {
// if(!oldResource.hasProperty(Omn.isResourceOf) ||
// !oldResource.hasProperty(Omn.hasResource)){
StmtIterator stmtIterator = oldResource.listProperties();
while (stmtIterator.hasNext()) {
Statement statement = stmtIterator.nextStatement();
requestedResourcesModel.add(statement);
}
}
}
Model newRequestedResourcesModel = ModelFactory.createDefaultModel();
ResIterator resIter = requestedResourcesModel.listSubjects();
while (resIter.hasNext()) {
Resource res = resIter.nextResource();
StmtIterator stmtIter = res.listProperties();
while (stmtIter.hasNext()) {
Statement stmt = stmtIter.nextStatement();
// if("deployedOn".equals(stmt.getPredicate().getLocalName()) ||
// "requires".equals(stmt.getPredicate().getLocalName())){
// Statement newStatement = new StatementImpl(stmt.getSubject(),
// stmt.getPredicate(),
// originalResourceNames.get(stmt.getObject().toString()));
// newRequestedResourcesModel.add(newStatement);
// else{
newRequestedResourcesModel.add(stmt);
}
}
// check whether replaced resources were also used as objects, replace
// old uri with new
List<Statement> toAdd = new ArrayList<Statement>();
List<Statement> toDelete = new ArrayList<Statement>();
Model model = ModelFactory.createDefaultModel();
for (Map.Entry<String, Resource> entry : originalResourceNames
.entrySet()) {
String oldUri = entry.getKey();
Resource newResource = entry.getValue();
StmtIterator statements = newRequestedResourcesModel
.listStatements();
while (statements.hasNext()) {
Statement stmt = statements.nextStatement();
if (stmt.getObject().isURIResource()
&& stmt.getObject().asResource().getURI()
.equals(oldUri)) {
toDelete.add(stmt);
Statement statementToAdd = model
.createStatement(stmt.getSubject(),
stmt.getPredicate(), newResource);
toAdd.add(statementToAdd);
}
}
}
newRequestedResourcesModel.add(toAdd);
newRequestedResourcesModel.remove(toDelete);
return newRequestedResourcesModel;
}
private Model parseRSpec(String request) throws JAXBException,
InvalidModelException, MissingRspecElementException,
InvalidRspecValueException {
Model model = null;
InputStream is = new ByteArrayInputStream(request.getBytes(Charset
.defaultCharset()));
if (request.contains(RDF.getURI())) {
model = ModelFactory.createDefaultModel();
model.read(is, null, IMessageBus.SERIALIZATION_RDFXML);
} else {
// model = RequestConverter.getModel(is);
try {
model = DeliveryMechanism.getModelFromUnkownInput(request);
} catch (UnsupportedException | XMLStreamException
| DeprecatedRspecVersionException e) {
LOGGER.log(
Level.SEVERE,
" problem has been occured while converting received request to rdf model \n",
e);
}
}
return model;
}
public void createResponse(final HashMap<String, Object> result,
Model allocateResponse) throws UnsupportedEncodingException {
final Map<String, Object> value = new HashMap<>();
try {
Config config = new Config();
value.put(
IGeni.GENI_RSPEC,
ManifestConverter.getRSpec(allocateResponse,
config.getProperty(IConfig.KEY_HOSTNAME)));
} catch (JAXBException | InvalidModelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final List<Map<String, Object>> geniSlivers = new LinkedList<>();
ResIterator iterator = allocateResponse.listResourcesWithProperty(
RDF.type, Omn.Reservation);
while (iterator.hasNext()) {
final Map<String, Object> sliverMap = new HashMap<>();
Resource reservation = iterator.nextResource();
Config config = new Config();
sliverMap.put(IGeni.GENI_SLIVER_URN, ManifestConverter
.generateSliverID(config.getProperty(IConfig.KEY_HOSTNAME),
reservation.getProperty(Omn.isReservationOf)
.getResource().getURI()));
sliverMap.put(IGeni.GENI_EXPIRES,
reservation.getProperty(MessageBusOntologyModel.endTime)
.getLiteral().getString());
sliverMap.put(
IGeni.GENI_ALLOCATION_STATUS,
ReservationStateEnum.valueOf(
reservation
.getProperty(
Omn_lifecycle.hasReservationState)
.getResource().getLocalName())
.getGeniState());
geniSlivers.add(sliverMap);
}
value.put(IGeni.GENI_SLIVERS, geniSlivers);
result.put(ISFA_AM.VALUE, value);
this.addCode(result);
this.addOutput(result);
}
}
|
package io.rong;
import io.rong.models.ChatroomInfo;
import io.rong.models.FormatType;
import io.rong.models.GroupInfo;
import io.rong.models.Message;
import io.rong.models.SdkHttpResult;
import io.rong.util.HttpUtil;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.List;
public class ApiHttpClient {
private static final String RONGCLOUDURI = "http://api.cn.ronghub.com";
private static final String UTF8 = "UTF-8";
// token
public static SdkHttpResult getToken(String appKey, String appSecret,
String userId, String userName, String portraitUri,
FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil
.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI
+ "/user/getToken." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
sb.append("&name=").append(URLEncoder.encode(userName==null?"":userName, UTF8));
sb.append("&portraitUri=").append(URLEncoder.encode(portraitUri==null?"":portraitUri, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult checkOnline(String appKey, String appSecret,
String userId, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/user/checkOnline." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult refreshUser(String appKey, String appSecret,
String userId, String userName, String portraitUri,
FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret, RONGCLOUDURI + "/user/refresh." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
sb.append("&name=").append(URLEncoder.encode(userName==null?"":userName, UTF8));
sb.append("&portraitUri=").append(URLEncoder.encode(portraitUri==null?"":portraitUri, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult blockUser(String appKey, String appSecret,
String userId, int minute, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret, RONGCLOUDURI + "/user/block." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
sb.append("&minute=").append(
URLEncoder.encode(String.valueOf(minute), UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult unblockUser(String appKey, String appSecret,
String userId, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret, RONGCLOUDURI + "/user/unblock." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult queryBlockUsers(String appKey,
String appSecret, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/user/block/query." + format.toString());
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult blackUser(String appKey, String appSecret,
String userId, List<String> blackUserIds, FormatType format)
throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/user/blacklist/add." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
if (blackUserIds != null) {
for (String blackId : blackUserIds) {
sb.append("&blackUserId=").append(
URLEncoder.encode(blackId, UTF8));
}
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult unblackUser(String appKey, String appSecret,
String userId, List<String> blackUserIds, FormatType format)
throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/user/blacklist/remove." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
if (blackUserIds != null) {
for (String blackId : blackUserIds) {
sb.append("&blackUserId=").append(
URLEncoder.encode(blackId, UTF8));
}
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult QueryblackUser(String appKey, String appSecret,
String userId, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/user/blacklist/query." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult createGroup(String appKey, String appSecret,
List<String> userIds, String groupId, String groupName,
FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret, RONGCLOUDURI + "/group/create." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("groupId=").append(URLEncoder.encode(groupId, UTF8));
sb.append("&groupName=").append(URLEncoder.encode(groupName==null?"":groupName, UTF8));
if (userIds != null) {
for (String id : userIds) {
sb.append("&userId=").append(URLEncoder.encode(id, UTF8));
}
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult joinGroup(String appKey, String appSecret,
String userId, String groupId, String groupName, FormatType format)
throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret, RONGCLOUDURI + "/group/join." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
sb.append("&groupId=").append(URLEncoder.encode(groupId, UTF8));
sb.append("&groupName=").append(URLEncoder.encode(groupName==null?"":groupName, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult joinGroupBatch(String appKey, String appSecret,
List<String> userIds, String groupId, String groupName,
FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret, RONGCLOUDURI + "/group/join." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("groupId=").append(URLEncoder.encode(groupId, UTF8));
sb.append("&groupName=").append(URLEncoder.encode(groupName==null?"":groupName, UTF8));
if (userIds != null) {
for (String id : userIds) {
sb.append("&userId=").append(URLEncoder.encode(id, UTF8));
}
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult quitGroup(String appKey, String appSecret,
String userId, String groupId, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret, RONGCLOUDURI + "/group/quit." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
sb.append("&groupId=").append(URLEncoder.encode(groupId, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult quitGroupBatch(String appKey, String appSecret,
List<String> userIds, String groupId, FormatType format)
throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret, RONGCLOUDURI + "/group/quit." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("groupId=").append(URLEncoder.encode(groupId, UTF8));
if (userIds != null) {
for (String id : userIds) {
sb.append("&userId=").append(URLEncoder.encode(id, UTF8));
}
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult dismissGroup(String appKey, String appSecret,
String userId, String groupId, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil
.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI
+ "/group/dismiss." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
sb.append("&groupId=").append(URLEncoder.encode(groupId, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult syncGroup(String appKey, String appSecret,
String userId, List<GroupInfo> groups, FormatType format)
throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret, RONGCLOUDURI + "/group/sync." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
if (groups != null) {
for (GroupInfo info : groups) {
if (info != null) {
sb.append(
String.format("&group[%s]=",
URLEncoder.encode(info.getId(), UTF8)))
.append(URLEncoder.encode(info.getName(), UTF8));
}
}
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult refreshGroupInfo(String appKey,
String appSecret, String groupId, String groupName,
FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil
.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI
+ "/group/refresh." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("groupId=").append(URLEncoder.encode(groupId, UTF8));
sb.append("&groupName=").append(URLEncoder.encode(groupName==null?"":groupName, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult refreshGroupInfo(String appKey,
String appSecret, GroupInfo group, FormatType format)
throws Exception {
HttpURLConnection conn = HttpUtil
.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI
+ "/group/refresh." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("groupId=").append(URLEncoder.encode(group.getId(), UTF8));
sb.append("&groupName=").append(
URLEncoder.encode(group.getName(), UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult publishMessage(String appKey, String appSecret,
String fromUserId, List<String> toUserIds, Message msg,
FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/message/private/publish." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("fromUserId=").append(URLEncoder.encode(fromUserId, UTF8));
if (toUserIds != null) {
for (int i = 0; i < toUserIds.size(); i++) {
sb.append("&toUserId=").append(
URLEncoder.encode(toUserIds.get(i), UTF8));
}
}
sb.append("&objectName=")
.append(URLEncoder.encode(msg.getType(), UTF8));
sb.append("&content=").append(URLEncoder.encode(msg.toString(), UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult publishMessage(String appKey, String appSecret,
String fromUserId, List<String> toUserIds, Message msg,
String pushContent, String pushData, FormatType format)
throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/message/publish." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("fromUserId=").append(URLEncoder.encode(fromUserId, UTF8));
if (toUserIds != null) {
for (int i = 0; i < toUserIds.size(); i++) {
sb.append("&toUserId=").append(
URLEncoder.encode(toUserIds.get(i), UTF8));
}
}
sb.append("&objectName=")
.append(URLEncoder.encode(msg.getType(), UTF8));
sb.append("&content=").append(URLEncoder.encode(msg.toString(), UTF8));
if (pushContent != null) {
sb.append("&pushContent=").append(
URLEncoder.encode(pushContent==null?"":pushContent, UTF8));
}
if (pushData != null) {
sb.append("&pushData=").append(URLEncoder.encode(pushData==null?"":pushData, UTF8));
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult publishSystemMessage(String appKey,
String appSecret, String fromUserId, List<String> toUserIds,
Message msg, String pushContent, String pushData, FormatType format)
throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/message/system/publish." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("fromUserId=").append(URLEncoder.encode(fromUserId, UTF8));
if (toUserIds != null) {
for (int i = 0; i < toUserIds.size(); i++) {
sb.append("&toUserId=").append(
URLEncoder.encode(toUserIds.get(i), UTF8));
}
}
sb.append("&objectName=")
.append(URLEncoder.encode(msg.getType(), UTF8));
sb.append("&content=").append(URLEncoder.encode(msg.toString(), UTF8));
if (pushContent != null) {
sb.append("&pushContent=").append(
URLEncoder.encode(pushContent==null?"":pushContent, UTF8));
}
if (pushData != null) {
sb.append("&pushData=").append(URLEncoder.encode(pushData==null?"":pushData, UTF8));
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult publishGroupMessage(String appKey,
String appSecret, String fromUserId, List<String> toGroupIds,
Message msg, String pushContent, String pushData, FormatType format)
throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/message/group/publish." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("fromUserId=").append(URLEncoder.encode(fromUserId, UTF8));
if (toGroupIds != null) {
for (int i = 0; i < toGroupIds.size(); i++) {
sb.append("&toGroupId=").append(
URLEncoder.encode(toGroupIds.get(i), UTF8));
}
}
sb.append("&objectName=")
.append(URLEncoder.encode(msg.getType(), UTF8));
sb.append("&content=").append(URLEncoder.encode(msg.toString(), UTF8));
if (pushContent != null) {
sb.append("&pushContent=").append(
URLEncoder.encode(pushContent==null?"":pushContent, UTF8));
}
if (pushData != null) {
sb.append("&pushData=").append(URLEncoder.encode(pushData==null?"":pushData, UTF8));
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult publishChatroomMessage(String appKey,
String appSecret, String fromUserId, List<String> toChatroomIds,
Message msg, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil
.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI
+ "/message/chatroom/publish." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("fromUserId=").append(URLEncoder.encode(fromUserId, UTF8));
if (toChatroomIds != null) {
for (int i = 0; i < toChatroomIds.size(); i++) {
sb.append("&toChatroomId=").append(
URLEncoder.encode(toChatroomIds.get(i), UTF8));
}
}
sb.append("&objectName=")
.append(URLEncoder.encode(msg.getType(), UTF8));
sb.append("&content=").append(URLEncoder.encode(msg.toString(), UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult broadcastMessage(String appKey, String appSecret,
String fromUserId, Message msg,String pushContent, String pushData, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/message/broadcast." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("fromUserId=").append(URLEncoder.encode(fromUserId, UTF8));
sb.append("&objectName=")
.append(URLEncoder.encode(msg.getType(), UTF8));
sb.append("&content=").append(URLEncoder.encode(msg.toString(), UTF8));
if (pushContent != null) {
sb.append("&pushContent=").append(
URLEncoder.encode(pushContent==null?"":pushContent, UTF8));
}
if (pushData != null) {
sb.append("&pushData=").append(URLEncoder.encode(pushData==null?"":pushData, UTF8));
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult createChatroom(String appKey, String appSecret,
List<ChatroomInfo> chatrooms, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/chatroom/create." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("1=1");
if (chatrooms != null) {
for (ChatroomInfo info : chatrooms) {
if (info != null) {
sb.append(
String.format("&chatroom[%s]=",
URLEncoder.encode(info.getId(), UTF8)))
.append(URLEncoder.encode(info.getName(), UTF8));
}
}
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult destroyChatroom(String appKey,
String appSecret, List<String> chatroomIds, FormatType format)
throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/chatroom/destroy." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("1=1");
if (chatroomIds != null) {
for (String id : chatroomIds) {
sb.append("&chatroomId=").append(URLEncoder.encode(id, UTF8));
}
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult queryChatroom(String appKey, String appSecret,
List<String> chatroomIds, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/chatroom/query." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("1=1");
if (chatroomIds != null) {
for (String id : chatroomIds) {
sb.append("&chatroomId=").append(URLEncoder.encode(id, UTF8));
}
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult getMessageHistoryUrl(String appKey,
String appSecret, String date, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/message/history." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("date=").append(URLEncoder.encode(date, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult deleteMessageHistory(String appKey,
String appSecret, String date, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/message/history/delete." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("date=").append(URLEncoder.encode(date, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
}
|
package jade.lang.sl;
import java.io.StringReader;
import jade.lang.Codec;
import jade.onto.Frame;
import jade.onto.Ontology;
import jade.onto.basic.BasicOntologyVocabulary;
import java.util.List;
public class SL0Codec implements Codec {
/**
A symbolic constant, containing the name of this language.
*/
public static final String NAME = "FIPA-SL0";
/** Symbolic constant identifying a frame representing an action **/
public static String NAME_OF_ACTION_FRAME = BasicOntologyVocabulary.ACTION;
/** Symbolic constant identifying a slot representing an actor **/
public static String NAME_OF_ACTOR_SLOT = Frame.UNNAMEDPREFIX+".ACTION.actor";
/** Symbolic constant identifying a slot representing an action **/
public static String NAME_OF_ACTION_SLOT = Frame.UNNAMEDPREFIX+".ACTION.action";
private SL0Parser parser = new SL0Parser(new StringReader(""));
private SL0Encoder encoder = new SL0Encoder();
public String encode(List v, Ontology o) {
StringBuffer s = new StringBuffer("(");
for (int i=0; i<v.size(); i++)
s.append(encoder.encode((Frame)v.get(i))+" ");
return s.append(")").toString();
}
public List decode(String s, Ontology o) throws Codec.CodecException {
try {
return parser.parse(s);
}
catch(ParseException pe) {
throw new Codec.CodecException("Parse exception", pe);
}
catch(TokenMgrError tme) {
throw new Codec.CodecException("Token Manager error", tme);
}
}
}
|
package org.sagebionetworks.bridge.exporter;
import java.io.File;
import java.io.IOException;
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.TreeSet;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import com.amazonaws.AmazonClientException;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Index;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.s3.AmazonS3Client;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Stopwatch;
import com.google.common.base.Strings;
import com.google.common.collect.Multimap;
import com.google.common.collect.TreeMultimap;
import org.joda.time.LocalDate;
import org.sagebionetworks.client.exceptions.SynapseException;
import org.sagebionetworks.repo.model.table.ColumnType;
import org.sagebionetworks.bridge.s3.S3Helper;
import org.sagebionetworks.bridge.synapse.SynapseHelper;
public class BridgeExporter {
private static final Joiner JOINER_MESSAGE_LIST_SEPARATOR = Joiner.on(", ");
private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
public static final String S3_BUCKET_ATTACHMENTS = "org-sagebridge-attachment-prod";
// Number of records before the script stops processing records. This is used for testing. To make this unlimited,
// set it to -1.
private static final int RECORD_LIMIT = -1;
// Script should report progress after this many records, so users tailing the logs can see that it's still
// making progress
private static final int PROGRESS_REPORT_PERIOD = 100;
public static void main(String[] args) throws IOException {
try {
BridgeExporter bridgeExporter = new BridgeExporter();
bridgeExporter.setDate(args[0]);
bridgeExporter.run();
} catch (Throwable t) {
t.printStackTrace(System.out);
} finally {
System.exit(0);
}
}
private final Map<String, Integer> counterMap = new HashMap<>();
private final Map<String, Set<String>> setCounterMap = new HashMap<>();
private DynamoDB ddbClient;
private LocalDate date;
private String dateString;
private UploadSchemaHelper schemaHelper;
private S3Helper s3Helper;
private SynapseHelper synapseHelper;
public void run() throws IOException, SynapseException {
Stopwatch stopwatch = Stopwatch.createStarted();
try {
init();
Stopwatch downloadStopwatch = Stopwatch.createStarted();
downloadHealthDataRecords();
downloadStopwatch.stop();
System.out.println("Time to make TSVs: " + downloadStopwatch.elapsed(TimeUnit.SECONDS) + " seconds");
Stopwatch uploadStopwatch = Stopwatch.createStarted();
synapseHelper.uploadTsvsToSynapse();
uploadStopwatch.stop();
System.out.println("Time to upload TSVs to Synapse: " + uploadStopwatch.elapsed(TimeUnit.SECONDS)
+ " seconds");
} finally {
close();
stopwatch.stop();
System.out.println("Total time: " + stopwatch.elapsed(TimeUnit.SECONDS) + " seconds");
}
}
public void setDate(String dateString) {
this.dateString = dateString;
this.date = LocalDate.parse(dateString);
}
private void init() throws IOException, SynapseException {
File synapseConfigFile = new File(System.getProperty("user.home") + "/bridge-synapse-exporter-config.json");
JsonNode synapseConfigJson = JSON_MAPPER.readTree(synapseConfigFile);
String ddbPrefix = synapseConfigJson.get("ddbPrefix").textValue();
// Dynamo DB client - move to Spring
// This gets credentials from the default credential chain. For developer desktops, this is ~/.aws/credentials.
// For EC2 instances, this happens transparently.
// http://docs.aws.amazon.com/AWSSdkDocsJava/latest/DeveloperGuide/java-dg-setup.html#set-up-creds for more
// info.
ddbClient = new DynamoDB(new AmazonDynamoDBClient());
// S3 client - move to Spring
AmazonS3Client s3Client = new AmazonS3Client();
s3Helper = new S3Helper();
s3Helper.setS3Client(s3Client);
// synapse helper
synapseHelper = new SynapseHelper();
synapseHelper.setDdbClient(ddbClient);
synapseHelper.setS3Helper(s3Helper);
synapseHelper.init();
// DDB tables and Schema Helper
Table uploadSchemaTable = ddbClient.getTable("prod-heroku-UploadSchema");
Table synapseTablesTable = ddbClient.getTable(ddbPrefix + "SynapseTables");
schemaHelper = new UploadSchemaHelper();
schemaHelper.setSchemaTable(uploadSchemaTable);
schemaHelper.setSynapseHelper(synapseHelper);
schemaHelper.setSynapseTablesTable(synapseTablesTable);
schemaHelper.init();
System.out.println("Done initializing.");
}
private void close() {
if (synapseHelper != null) {
synapseHelper.close();
}
}
private void downloadHealthDataRecords() {
// get key objects by querying uploadDate index
Table recordTable = ddbClient.getTable("prod-heroku-HealthDataRecord3");
Index recordTableUploadDateIndex = recordTable.getIndex("uploadDate-index");
Iterable<Item> recordKeyIter = recordTableUploadDateIndex.query("uploadDate", dateString);
// re-query table to get values
Set<String> schemasNotFound = new TreeSet<>();
Multimap<String, String> appVersionsByStudy = TreeMultimap.create();
for (Item oneRecordKey : recordKeyIter) {
// running count of records
int numTotal = incrementCounter("numTotal");
if (numTotal % PROGRESS_REPORT_PERIOD == 0) {
System.out.println("Num records so far: " + numTotal);
}
if (RECORD_LIMIT > 0 && numTotal > RECORD_LIMIT) {
break;
}
// re-query health data records to get values
String recordId = oneRecordKey.getString("id");
Item oneRecord;
try {
oneRecord = recordTable.getItem("id", recordId);
} catch (AmazonClientException ex) {
System.out.println("Exception querying record for ID " + recordId + ": " + ex.getMessage());
continue;
}
if (oneRecord == null) {
System.out.println("No record for ID " + recordId);
continue;
}
// process/filter by user sharing scope
String userSharingScope = oneRecord.getString("userSharingScope");
if (Strings.isNullOrEmpty(userSharingScope) || userSharingScope.equalsIgnoreCase("no_sharing")) {
// must not be exported
incrementCounter("numNotShared");
continue;
} else if (userSharingScope.equalsIgnoreCase("sponsors_and_partners")) {
incrementCounter("numSharingBroadly");
} else if (userSharingScope.equalsIgnoreCase("all_qualified_researchers")) {
incrementCounter("numSharingSparsely");
} else {
System.out.println("Unknown sharing scope: " + userSharingScope);
continue;
}
// basic record data
String studyId = oneRecord.getString("studyId");
String schemaId = oneRecord.getString("schemaId");
int schemaRev = oneRecord.getInt("schemaRevision");
String externalId = getDdbStringRemoveTabsAndTrim(oneRecord, "userExternalId", 48);
String healthCode = oneRecord.getString("healthCode");
incrementSetCounter("uniqueHealthCodes[" + studyId + "]", healthCode);
// special handling for surveys
JsonNode dataJson;
if ("ios-survey".equals(schemaId)) {
incrementCounter("numSurveys");
// TODO: move survey translation layer to server-side
JsonNode oldDataJson;
try {
oldDataJson = JSON_MAPPER.readTree(oneRecord.getString("data"));
} catch (IOException ex) {
System.out.println("Error parsing JSON data for record " + recordId + ": " + ex.getMessage());
continue;
}
if (oldDataJson == null) {
System.out.println("No JSON data for record " + recordId);
continue;
}
JsonNode itemNode = oldDataJson.get("item");
if (itemNode == null) {
System.out.println("Survey with no item for record ID " + recordId);
continue;
}
String item = itemNode.textValue();
if (Strings.isNullOrEmpty(item)) {
System.out.println("Survey with null or empty item for record ID " + recordId);
continue;
}
schemaId = item;
// surveys default to rev 1 until this code is moved to server side
schemaRev = 1;
// download answers from S3 attachments
JsonNode answerLinkNode = oldDataJson.get("answers");
if (answerLinkNode == null) {
System.out.println("Survey with no answer link for record ID " + recordId);
continue;
}
String answerLink = answerLinkNode.textValue();
String answerText;
try {
answerText = s3Helper.readS3FileAsString(S3_BUCKET_ATTACHMENTS, answerLink);
} catch (AmazonClientException | IOException ex) {
System.out.println("Error getting survey answers from S3 for record ID " + recordId + ": "
+ ex.getMessage());
continue;
}
JsonNode answerArrayNode;
try {
answerArrayNode = JSON_MAPPER.readTree(answerText);
} catch (IOException ex) {
System.out.println("Error parsing JSON survey answers for record ID " + recordId + ": "
+ ex.getMessage());
continue;
}
if (answerArrayNode == null) {
System.out.println("Survey with no answers for record ID " + recordId);
continue;
}
// get schema and field type map, so we can process attachments
UploadSchemaKey surveySchemaKey = new UploadSchemaKey(studyId, item, 1);
UploadSchema surveySchema = schemaHelper.getSchema(surveySchemaKey);
if (surveySchema == null) {
System.out.println("Survey " + surveySchemaKey.toString() + " not found for record "
+ recordId);
schemasNotFound.add(surveySchemaKey.toString());
continue;
}
Map<String, String> surveyFieldTypeMap = surveySchema.getFieldTypeMap();
// copy fields to "non-survey" format
ObjectNode convertedSurveyNode = JSON_MAPPER.createObjectNode();
int numAnswers = answerArrayNode.size();
for (int i = 0; i < numAnswers; i++) {
JsonNode oneAnswerNode = answerArrayNode.get(i);
if (oneAnswerNode == null) {
System.out.println("Survey record ID " + recordId + " answer " + i + " has no value");
continue;
}
// question name ("item")
JsonNode answerItemNode = oneAnswerNode.get("item");
if (answerItemNode == null) {
System.out.println("Survey record ID " + recordId + " answer " + i
+ " has no question name (item)");
continue;
}
String answerItem = answerItemNode.textValue();
if (Strings.isNullOrEmpty(answerItem)) {
System.out.println("Survey record ID " + recordId + " answer " + i
+ " has null or empty question name (item)");
continue;
}
// question type
JsonNode questionTypeNameNode = oneAnswerNode.get("questionTypeName");
if (questionTypeNameNode == null || questionTypeNameNode.isNull()) {
// fall back to questionType
questionTypeNameNode = oneAnswerNode.get("questionType");
}
if (questionTypeNameNode == null || questionTypeNameNode.isNull()) {
System.out.println("Survey record ID " + recordId + " answer " + i + " has no question type");
continue;
}
String questionTypeName = questionTypeNameNode.textValue();
if (Strings.isNullOrEmpty(questionTypeName)) {
System.out.println("Survey record ID " + recordId + " answer " + i
+ " has null or empty question type");
continue;
}
// answer
// TODO: Hey, this should really be a Map<String, String>, not a big switch statement
JsonNode answerAnswerNode = null;
switch (questionTypeName) {
case "Boolean":
answerAnswerNode = oneAnswerNode.get("booleanAnswer");
break;
case "Date":
answerAnswerNode = oneAnswerNode.get("dateAnswer");
break;
case "Decimal":
case "Integer":
answerAnswerNode = oneAnswerNode.get("numericAnswer");
break;
case "MultipleChoice":
case "SingleChoice":
answerAnswerNode = oneAnswerNode.get("choiceAnswers");
break;
case "None":
case "Scale":
// yes, None really gets the answer from scaleAnswer
answerAnswerNode = oneAnswerNode.get("scaleAnswer");
break;
case "Text":
answerAnswerNode = oneAnswerNode.get("textAnswer");
break;
case "TimeInterval":
answerAnswerNode = oneAnswerNode.get("intervalAnswer");
break;
case "TimeOfDay":
answerAnswerNode = oneAnswerNode.get("dateComponentsAnswer");
break;
default:
System.out.println("Survey record ID " + recordId + " answer " + i
+ " has unknown question type " + questionTypeName);
break;
}
if (answerAnswerNode != null && !answerAnswerNode.isNull()) {
// handle attachment types (file handle types)
String bridgeType = surveyFieldTypeMap.get(answerItem);
ColumnType synapseType = SynapseHelper.BRIDGE_TYPE_TO_SYNAPSE_TYPE.get(bridgeType);
if (synapseType == ColumnType.FILEHANDLEID) {
String attachmentId = null;
String answer = answerAnswerNode.asText();
try {
attachmentId = uploadFreeformTextAsAttachment(recordId, answer);
} catch (AmazonClientException | IOException ex) {
System.out.println("Error uploading freeform text as attachment for record ID "
+ recordId + ", survey item " + answerItem + ": " + ex.getMessage());
}
convertedSurveyNode.put(answerItem, attachmentId);
} else {
convertedSurveyNode.set(answerItem, answerAnswerNode);
}
}
// if there's a unit, add it as well
JsonNode unitNode = oneAnswerNode.get("unit");
if (unitNode != null && !unitNode.isNull()) {
convertedSurveyNode.set(answerItem + "_unit", unitNode);
}
}
dataJson = convertedSurveyNode;
} else {
// non-surveys
incrementCounter("numNonSurveys");
try {
dataJson = JSON_MAPPER.readTree(oneRecord.getString("data"));
} catch (IOException ex) {
System.out.println("Error parsing JSON for record ID " + recordId + ": " + ex.getMessage());
continue;
}
if (dataJson == null) {
System.out.println("Null data JSON for record ID " + recordId);
continue;
}
}
// get phone and app info
String appVersion = null;
String phoneInfo = null;
String metadataString = oneRecord.getString("metadata");
if (!Strings.isNullOrEmpty(metadataString)) {
try {
JsonNode metadataJson = JSON_MAPPER.readTree(metadataString);
appVersion = getJsonStringRemoveTabsAndTrim(metadataJson, "appVersion", 48);
phoneInfo = getJsonStringRemoveTabsAndTrim(metadataJson, "phoneInfo", 48);
} catch (IOException ex) {
// we can recover from this
System.out.println("Error parsing metadata for record ID " + recordId + ": " + ex.getMessage());
}
}
// app version bookkeeping
if (!Strings.isNullOrEmpty(appVersion)) {
appVersionsByStudy.put(studyId, appVersion);
}
writeHealthDataToSynapse(recordId, healthCode, externalId, studyId, schemaId, schemaRev, appVersion,
phoneInfo, oneRecord, dataJson, schemasNotFound);
writeAppVersionToSynapse(recordId, healthCode, externalId, studyId, schemaId, schemaRev, appVersion,
phoneInfo);
}
for (Map.Entry<String, Integer> oneCounter : counterMap.entrySet()) {
System.out.println(oneCounter.getKey() + ": " + oneCounter.getValue());
}
for (Map.Entry<String, Set<String>> oneSetCounter : setCounterMap.entrySet()) {
System.out.println(oneSetCounter.getKey() + ": " + oneSetCounter.getValue().size());
}
if (!schemasNotFound.isEmpty()) {
System.out.println("The following schemas were referenced but not found: "
+ JOINER_MESSAGE_LIST_SEPARATOR.join(schemasNotFound));
}
for (Map.Entry<String, Collection<String>> appVersionEntry : appVersionsByStudy.asMap().entrySet()) {
System.out.println("App versions for " + appVersionEntry.getKey() + ": "
+ JOINER_MESSAGE_LIST_SEPARATOR.join(appVersionEntry.getValue()));
}
}
private void writeHealthDataToSynapse(String recordId, String healthCode, String externalId, String studyId,
String schemaId, int schemaRev, String appVersion, String phoneInfo, Item oneRecord, JsonNode dataJson,
Set<String> schemasNotFound) {
// get schema
UploadSchemaKey schemaKey = new UploadSchemaKey(studyId, schemaId, schemaRev);
UploadSchema schema = schemaHelper.getSchema(schemaKey);
if (schema == null) {
// No schema. Skip.
System.out.println("Schema " + schemaKey.toString() + " not found for record " + recordId);
schemasNotFound.add(schemaKey.toString());
return;
}
// write record
String synapseTableId;
try {
synapseTableId = schemaHelper.getSynapseTableId(schemaKey);
} catch (IOException | RuntimeException | SynapseException ex) {
System.out.println("Error getting/creating Synapse table for schemaKey " + schemaKey.toString()
+ ", record ID " + recordId + ": " + ex.getMessage());
return;
}
List<String> rowValueList = new ArrayList<>();
// common values
rowValueList.add(recordId);
rowValueList.add(healthCode);
rowValueList.add(externalId);
rowValueList.add(oneRecord.getString("uploadDate"));
// createdOn as a long epoch millis
rowValueList.add(String.valueOf(oneRecord.getLong("createdOn")));
rowValueList.add(appVersion);
rowValueList.add(phoneInfo);
// schema-specific columns
List<String> fieldNameList = schema.getFieldNameList();
Map<String, String> fieldTypeMap = schema.getFieldTypeMap();
for (String oneFieldName : fieldNameList) {
String bridgeType = fieldTypeMap.get(oneFieldName);
JsonNode valueNode = dataJson.get(oneFieldName);
if (shouldConvertFreeformTextToAttachment(schemaKey, oneFieldName)) {
// special hack, see comments on shouldConvertFreeformTextToAttachment()
bridgeType = "attachment_blob";
if (valueNode != null && !valueNode.isNull() && valueNode.isTextual()) {
try {
String attachmentId = uploadFreeformTextAsAttachment(recordId, valueNode.textValue());
valueNode = new TextNode(attachmentId);
} catch (AmazonClientException | IOException ex) {
System.out.println("Error uploading freeform text as attachment for record ID " + recordId
+ ", field " + oneFieldName + ": " + ex.getMessage());
valueNode = null;
}
} else {
valueNode = null;
}
}
String value = synapseHelper.serializeToSynapseType(studyId, recordId, oneFieldName, bridgeType,
valueNode);
rowValueList.add(value);
}
try {
synapseHelper.appendToTsv(synapseTableId, rowValueList);
} catch (IOException ex) {
System.out.println("Error writing TSV row for record " + recordId + ": " + ex.getMessage());
}
}
private void writeAppVersionToSynapse(String recordId, String healthCode, String externalId, String studyId,
String schemaId, int schemaRev, String appVersion, String phoneInfo) {
UploadSchemaKey schemaKey = new UploadSchemaKey(studyId, schemaId, schemaRev);
// table ID
String synapseTableId;
try {
synapseTableId = synapseHelper.getSynapseAppVersionTableForStudy(studyId);
} catch (IOException | RuntimeException | SynapseException ex) {
System.out.println("Error getting/creating appVersion table for study " + studyId + ": "
+ ex.getMessage());
return;
}
// column values
List<String> rowValueList = new ArrayList<>();
rowValueList.add(recordId);
rowValueList.add(healthCode);
rowValueList.add(externalId);
rowValueList.add(schemaKey.toString());
rowValueList.add(appVersion);
rowValueList.add(phoneInfo);
try {
synapseHelper.appendToTsv(synapseTableId, rowValueList);
} catch (IOException ex) {
System.out.println("Error writing appVersion TSV row for record " + recordId + ": " + ex.getMessage());
}
}
private String uploadFreeformTextAsAttachment(String recordId, String text)
throws AmazonClientException, IOException {
// write to health data attachments table to reserve guid
String attachmentId = UUID.randomUUID().toString();
Item attachment = new Item();
attachment.withString("id", attachmentId);
attachment.withString("recordId", recordId);
Table attachmentsTable = ddbClient.getTable("prod-heroku-HealthDataAttachment");
attachmentsTable.putItem(attachment);
// upload to S3
s3Helper.writeBytesToS3(S3_BUCKET_ATTACHMENTS, attachmentId, text.getBytes(Charsets.UTF_8));
return attachmentId;
}
private int incrementCounter(String name) {
Integer oldValue = counterMap.get(name);
int newValue;
if (oldValue == null) {
newValue = 1;
} else {
newValue = oldValue + 1;
}
counterMap.put(name, newValue);
return newValue;
}
// Only increments the counter if the value hasn't already been used. Used for things like counting unique health
// codes.
private void incrementSetCounter(String name, String value) {
Set<String> set = setCounterMap.get(name);
if (set == null) {
set = new HashSet<>();
setCounterMap.put(name, set);
}
set.add(value);
}
public static boolean shouldConvertFreeformTextToAttachment(UploadSchemaKey schemaKey, String fieldName) {
// When we initially designed these schemas, we didn't realize Synapse had a character limit on strings.
// These strings may exceed that character limit, so we need this special hack to convert these strings to
// attachments. This code applies only to legacy schemas. New schemas need to declare ATTACHMENT_BLOB,
// otherwise the strings get automatically truncated.
if ("breastcancer".equals(schemaKey.getStudyId())) {
if ("BreastCancer-DailyJournal".equals(schemaKey.getSchemaId())) {
if (schemaKey.getRev() == 1) {
return "content_data.APHMoodLogNoteText".equals(fieldName)
|| "DailyJournalStep103_data.content".equals(fieldName);
}
} else if ("BreastCancer-ExerciseSurvey".equals(schemaKey.getSchemaId())) {
if (schemaKey.getRev() == 1) {
return "exercisesurvey101_data.result".equals(fieldName)
|| "exercisesurvey102_data.result".equals(fieldName)
|| "exercisesurvey103_data.result".equals(fieldName)
|| "exercisesurvey104_data.result".equals(fieldName)
|| "exercisesurvey105_data.result".equals(fieldName)
|| "exercisesurvey106_data.result".equals(fieldName);
}
}
}
return false;
}
private static String getDdbStringRemoveTabsAndTrim(Item ddbItem, String key, int maxLength) {
return trimToLengthAndWarn(removeTabs(ddbItem.getString(key)), maxLength);
}
private static String getJsonStringRemoveTabsAndTrim(JsonNode node, String key, int maxLength) {
return trimToLengthAndWarn(removeTabs(getJsonString(node, key)), maxLength);
}
private static String getJsonString(JsonNode node, String key) {
if (node.hasNonNull(key)) {
return node.get(key).textValue();
} else {
return null;
}
}
private static String removeTabs(String in) {
if (in != null) {
return in.replaceAll("\t+", " ");
} else {
return null;
}
}
public static String trimToLengthAndWarn(String in, int maxLength) {
if (in != null && in.length() > maxLength) {
System.out.println("Trunacting string " + in + " to length " + maxLength);
return in.substring(0, maxLength);
} else {
return in;
}
}
}
|
package reborncore.client.multiblock;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.renderer.*;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.client.MinecraftForgeClient;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.event.world.WorldEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import org.lwjgl.opengl.GL11;
import reborncore.client.multiblock.component.MultiblockComponent;
public class MultiblockRenderEvent {
public static BlockPos anchor;
private static BlockRendererDispatcher blockRender = Minecraft.getMinecraft().getBlockRendererDispatcher();
public MultiblockSet currentMultiblock;
//public Location parent;
public BlockPos parent;
RebornFluidRenderer fluidRenderer;
public MultiblockRenderEvent() {
this.fluidRenderer = new RebornFluidRenderer();
}
public void setMultiblock(MultiblockSet set) {
currentMultiblock = set;
anchor = null;
parent = null;
}
@SubscribeEvent
public void onWorldRenderLast(RenderWorldLastEvent event) throws Throwable {
Minecraft mc = Minecraft.getMinecraft();
if (mc.player != null && mc.objectMouseOver != null && !mc.player.isSneaking()) {
if (currentMultiblock != null) {
BlockPos anchorPos = anchor != null ? anchor : mc.objectMouseOver.getBlockPos();
Multiblock mb = currentMultiblock.getForIndex(0);
//Render the liquids first, it looks better.
for (MultiblockComponent comp : mb.getComponents()) {
if(comp.state.getRenderType() == EnumBlockRenderType.LIQUID){
renderComponent(comp, anchorPos.up(), event.getPartialTicks(), mc.player);
}
}
for (MultiblockComponent comp : mb.getComponents()) {
if(comp.state.getRenderType() != EnumBlockRenderType.LIQUID){
renderComponent(comp, anchorPos.up(), event.getPartialTicks(), mc.player);
}
}
}
}
}
private void renderComponent(MultiblockComponent comp, BlockPos anchor, float partialTicks, EntityPlayerSP player) {
double dx = player.lastTickPosX + (player.posX - player.lastTickPosX) * partialTicks;
double dy = player.lastTickPosY + (player.posY - player.lastTickPosY) * partialTicks;
double dz = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * partialTicks;
BlockPos pos = anchor.add(comp.getRelativePosition());
Minecraft minecraft = Minecraft.getMinecraft();
World world = player.world;
minecraft.getTextureManager().bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE);
BlockRenderLayer originalLayer = MinecraftForgeClient.getRenderLayer();
ForgeHooksClient.setRenderLayer(BlockRenderLayer.CUTOUT);
GlStateManager.pushMatrix();
GlStateManager.translate(-dx, -dy, -dz);
GlStateManager.translate(pos.getX(), pos.getY(), pos.getZ());
GlStateManager.scale(0.8, 0.8, 0.8);
GlStateManager.translate(0.2, 0.2, 0.2);
RenderHelper.disableStandardItemLighting();
GlStateManager.enableBlend();
GlStateManager.enableTexture2D();
GlStateManager.color(1f, 1f, 1f, 1f);
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.CONSTANT_ALPHA);
GlStateManager.colorMask(true, true, true, true);
GlStateManager.depthFunc(GL11.GL_LEQUAL);
this.renderModel(world, pos, comp.state);
GlStateManager.disableBlend();
GlStateManager.popMatrix();
ForgeHooksClient.setRenderLayer(originalLayer);
}
private void renderModel(World world, BlockPos pos,IBlockState state) {
final BlockRendererDispatcher blockRendererDispatcher = Minecraft.getMinecraft().blockRenderDispatcher;
final Tessellator tessellator = Tessellator.getInstance();
final BufferBuilder buffer = tessellator.getBuffer();
GlStateManager.translate(-pos.getX(), -pos.getY(), -pos.getZ());
buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.BLOCK);
if(state.getRenderType() == EnumBlockRenderType.LIQUID){
fluidRenderer.renderFluid(world, state, pos, buffer);
} else {
blockRendererDispatcher.renderBlock(state, pos, world, buffer);
}
tessellator.draw();
}
@SubscribeEvent
public void breakBlock(BlockEvent.BreakEvent event) {
if (parent != null) {
if (event.getPos().getX() == parent.getX() && event.getPos().getY() == parent.getY() && event.getPos().getZ() == parent.getZ()) {
setMultiblock(null);
}
}
}
@SubscribeEvent
public void worldUnloaded(WorldEvent.Unload event) {
setMultiblock(null);
}
}
|
package reciter.database.oracle.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import reciter.database.oracle.OracleConnectionFactory;
import reciter.database.oracle.OracleIdentityDao;
@Repository("oracleIdentityDao")
public class OracleIdentityDaoImpl implements OracleIdentityDao {
private static final Logger slf4jLogger = LoggerFactory.getLogger(OracleIdentityDaoImpl.class);
@Autowired
private OracleConnectionFactory oracleConnectionFactory;
@Override
public int getBachelorDegreeYear(String cwid) {
int year = 0;
Connection connection = oracleConnectionFactory.createConnection();
if (connection == null) {
return year;
}
ResultSet rs = null;
PreparedStatement pst = null;
String sql = "select degree_year from OFA_DB.PERSON p1 "
+ "inner join "
+ "(select cwid, degree_year from ofa_db.degree d "
+ "join OFA_DB.FACORE fac on fac.facore_pk = d.facore_fk "
+ "join OFA_DB.PERSON p on p.PERSON_PK = fac.FACORE_PK "
+ "join OFA_DB.INSTITUTE i on i.institute_PK = d.institute_FK "
+ "left join OFA_DB.DEGREE_NAME n on n.DEGREE_NAME_PK = d.degree_name_fk "
+ "where p.cwid is not NULL and terminal_degree <> 'Yes' and doctoral_degree is null "
+ "and md = 'F' and mdphd ='F' and do_degree = 'F' and n.OTHER_PROFESSORIAL = 'F' "
+ "and degree not like 'M%' and degree not like 'Pharm%' and degree not like 'Sc%' "
+ "order by degree_year asc) p2 "
+ "on p2.cwid = p1.cwid and p1.cwid = ?";
try {
pst = connection.prepareStatement(sql);
pst.setString(1, cwid);
rs = pst.executeQuery();
while(rs.next()) {
year = rs.getInt(1);
}
} catch(SQLException e) {
slf4jLogger.error("Exception occured in query=" + sql, e);
}
finally {
try {
rs.close();
pst.close();
connection.close();;
} catch(SQLException e) {
slf4jLogger.error("Unabled to close connection to Oracle DB.", e);
}
}
return year;
}
@Override
public int getDoctoralYear(String cwid) {
int year = 0;
Connection connection = oracleConnectionFactory.createConnection();
if (connection == null) {
return year;
}
ResultSet rs = null;
PreparedStatement pst = null;
String sql = "select degree_year from ofa_db.degree d "
+ "join OFA_DB.FACORE fac on fac.facore_pk = d.facore_fk "
+ "join OFA_DB.PERSON p ON p.PERSON_PK = fac.FACORE_PK "
+ "join OFA_DB.INSTITUTE i on i.institute_PK = d.institute_FK "
+ "left join OFA_DB.DEGREE_NAME n on n.DEGREE_NAME_PK = d.degree_name_fk "
+ "where p.cwid is not NULL and cwid <> '0' and terminal_degree = 'Yes' and p.cwid = ?";
try {
pst = connection.prepareStatement(sql);
pst.setString(1, cwid);
rs = pst.executeQuery();
while(rs.next()) {
year = rs.getInt(1);
}
} catch(SQLException e) {
slf4jLogger.error("Exception occured in query=" + sql, e);
}
finally {
try {
rs.close();
pst.close();
connection.close();;
} catch(SQLException e) {
slf4jLogger.error("Unabled to close connection to Oracle DB.", e);
}
}
return year;
}
@Override
public List<String> getInstitutions(String cwid) {
Connection connection = oracleConnectionFactory.createConnection();
if (connection == null) {
return Collections.emptyList();
}
ResultSet rs = null;
PreparedStatement pst = null;
String sql = "SELECT cwid, ai.INSTITUTION, 'Academic-PrimaryAffiliation' from OFA_DB.FACORE fac "
+ "JOIN OFA_DB.AFFIL_INSTITUTE ai ON ai.affil_institute_pk = fac.affil_institute_FK "
+ "JOIN OFA_DB.PERSON p ON p.PERSON_PK = fac.FACORE_PK where cwid is not null and cwid <> '0' and cwid = ?"
+ "union "
+ "SELECT p.cwid, ai.INSTITUTION, 'Academic-AppointingInstitution' FROM OFA_DB.FACORE fac "
+ "JOIN OFA_DB.APPOINTMENT a ON fac.facore_PK = a.facore_fk "
+ "JOIN OFA_DB.AFFIL_INSTITUTE ai ON ai.affil_institute_pk = a.affil_institute_FK "
+ "JOIN OFA_DB.AFFIL_INSTITUTE ai ON ai.affil_institute_pk = fac.affil_institute_FK "
+ "JOIN OFA_DB.PERSON p ON p.PERSON_PK = fac.FACORE_PK "
+ "where cwid is not null and cwid <> '0' and cwid = ?"
+ "union "
+ "SELECT cwid, institution, 'Academic-Degree' from ofa_db.degree d "
+ "join OFA_DB.FACORE fac on fac.facore_pk = d.facore_fk "
+ "join OFA_DB.PERSON p ON p.PERSON_PK = fac.FACORE_PK "
+ "join OFA_DB.INSTITUTE i on i.institute_PK = d.institute_FK "
+ "left join OFA_DB.DEGREE_NAME n on n.DEGREE_NAME_PK = d.degree_name_fk "
+ "where cwid is not null and cwid <> '0' and cwid = ?";
Set<String> distinctInstitutions = new HashSet<String>();
try {
pst = connection.prepareStatement(sql);
pst.setString(1, cwid);
pst.setString(2, cwid);
pst.setString(3, cwid);
rs = pst.executeQuery();
while(rs.next()) {
distinctInstitutions.add(rs.getString(2));
}
} catch(SQLException e) {
slf4jLogger.error("Exception occured in query=" + sql, e);
}
finally {
try {
rs.close();
pst.close();
connection.close();;
} catch(SQLException e) {
slf4jLogger.error("Unabled to close connection to Oracle DB.", e);
}
}
return new ArrayList<>(distinctInstitutions);
}
@Override
public List<String> getPersonalEmailFromOfa(String cwid) {
List<String> emails = new ArrayList<String>();
Connection connection = oracleConnectionFactory.createConnection();
if (connection == null) {
return emails;
}
ResultSet rs = null;
PreparedStatement pst = null;
String sql = "select email from "
+ "(select distinct p.cwid, substr(private_email,1,INSTR(private_email,',')-1) as email "
+ "FROM OFA_DB.PERSON p where p.private_email like '%,%' "
+ "UNION "
+ "select distinct p.cwid, substr(email,1,INSTR(email,',')-1) AS email from OFA_DB.PERSON p "
+ "where p.email like '%,%' "
+ "UNION "
+ "select distinct p.cwid, "
+ "substr(replace(p.private_email,' ',''),1 + INSTR(replace(p.private_email,' ',''),',')) "
+ "as email from OFA_DB.PERSON p where p.private_email like '%,%' "
+ "UNION "
+ "select distinct p.cwid, "
+ "substr(replace(p.email,' ',''),1 + INSTR(replace(p.email,' ',''),',')) as email from OFA_DB.PERSON p "
+ "where p.email like '%,%') where email like '%@%' and email like '%.%' and CWID = ?";
try {
pst = connection.prepareStatement(sql);
pst.setString(1, cwid);
rs = pst.executeQuery();
while(rs.next()) {
emails.add(rs.getString(1));
}
} catch(SQLException e) {
slf4jLogger.error("Exception occured in query=" + sql, e);
}
finally {
try {
rs.close();
pst.close();
connection.close();;
} catch(SQLException e) {
slf4jLogger.error("Unabled to close connection to Oracle DB.", e);
}
}
return emails;
}
}
|
// JSFunction.java
package ed.js;
import ed.util.*;
import ed.js.engine.Scope;
public abstract class JSFunction extends JSFunctionBase {
static {
JS._debugSIStart( "JSFunction" );
}
public static final String TO_STRING_PREFIX = "JSFunction : ";
public JSFunction( int num ){
this( null , null , num );
}
public JSFunction( Scope scope , String name , int num ){
super( num );
_scope = scope;
_name = name;
_prototype = new JSObjectBase();
_init();
set( "prototype" , _prototype );
set( "isFunction" , true );
init();
}
public Object set( Object n , Object b ){
if ( n != null && "prototype".equals( n.toString() ) )
_prototype = (JSObject)b;
return super.set( n , b );
}
public JSObject newOne(){
return new JSObjectBase( this );
}
protected void init(){}
public Object get( Object n ){
Object foo = super.get( n );
if ( foo != null )
return foo;
return _prototype.get( n );
}
public void setName( String name ){
_name = name;
}
public String getName(){
return _name;
}
public Scope getScope(){
return getScope( false );
}
/**
* @package threadLocal if this is true, it returns a thread local scope that you can modify for your thread
*/
public Scope getScope( boolean threadLocal ){
Scope s = _tlScope.get();
if ( s != null ){
return s;
}
if ( threadLocal ){
if ( _scope == null )
s = new Scope( "func tl scope" , null );
else
s = _scope.child( "func tl scope" );
s.setGlobal( true );
_tlScope.set( s );
return s;
}
return _scope;
}
public void setTLScope( Scope tl ){
_tlScope.set( tl );
}
public Scope getTLScope(){
return _tlScope.get();
}
public void clearScope(){
Scope s = _tlScope.get();
if ( s != null )
s.reset();
}
public String toString(){
return TO_STRING_PREFIX + _name;
}
public JSArray argumentNames(){
if ( _arguments != null )
return _arguments;
JSArray temp = new JSArray();
for ( int i=0; i<_num; i++ ){
temp.add( "unknown" + i );
}
return temp;
}
public void setUsePassedInScope( boolean usePassedInScope ){
_forceUsePassedInScope = usePassedInScope;
}
synchronized Object _cache( Scope s , long cacheTime , Object args[] ){
if ( _callCache == null )
_callCache = new LRUCache<Long,Pair<Object,String>>( 1000 * 3600 );
final long hash = JSInternalFunctions.hash( args );
Pair<Object,String> p = _callCache.get( hash , cacheTime );
if ( p == null ){
PrintBuffer buf = new PrintBuffer();
getScope( true ).set( "print" , buf );
p = new Pair<Object,String>();
p.first = call( s , args );
p.second = buf.toString();
_callCache.put( hash , p , cacheTime );
clearScope();
}
JSFunction print = (JSFunction)(s.get( "print" ));
if ( print == null )
throw new JSException( "print is null" );
print.call( s , p.second );
return p.first;
}
public Object callAndSetThis( Scope s , Object obj , Object args[] ){
s.setThis( obj );
try {
return call( s , args );
}
finally {
s.clearThisNormal( null );
}
}
private final Scope _scope;
private final ThreadLocal<Scope> _tlScope = new ThreadLocal<Scope>();
protected JSObject _prototype;
protected boolean _forceUsePassedInScope = false;
protected JSArray _arguments;
protected String _name = "NO NAME SET";
private LRUCache<Long,Pair<Object,String>> _callCache;
public static JSFunction _call = new ed.js.func.JSFunctionCalls1(){
public Object call( Scope s , Object obj , Object[] args ){
JSFunction func = (JSFunction)s.getThis();
return func.callAndSetThis( s , obj , args );
}
};
static JSFunction _apply = new ed.js.func.JSFunctionCalls2(){
public Object call( Scope s , Object obj , Object args , Object [] foo ){
JSFunction func = (JSFunction)s.getThis();
if ( args == null )
args = new JSArray();
if( ! (args instanceof JSArray) )
throw new RuntimeException("second argument to Function.prototype.apply must be an array not a " + args.getClass() );
JSArray jary = (JSArray)args;
s.setThis( obj );
try {
return func.call( s , jary.toArray() );
}
finally {
s.clearThisNormal( null );
}
}
};
static JSFunction _cache = new ed.js.func.JSFunctionCalls1(){
public Object call( Scope s , Object cacheTimeObj , Object[] args ){
JSFunction func = (JSFunction)s.getThis();
long cacheTime = Long.MAX_VALUE;
if ( cacheTimeObj != null && cacheTimeObj instanceof Number )
cacheTime = ((Number)cacheTimeObj).longValue();
return func._cache( s , cacheTime , args );
}
};
private static void _init(){
if ( _staticInited )
return;
JSFunction fcons = JSInternalFunctions.FunctionCons;
if ( fcons == null )
return;
fcons._prototype.set( "wrap" , Prototype._functionWrap );
fcons._prototype.set( "bind", Prototype._functionBind );
fcons._prototype.set( "call" , _call );
fcons._prototype.set( "apply" , _apply );
fcons._prototype.set( "cache" , _cache );
_staticInited = true;
}
private static boolean _staticInited = false;
static {
JS._debugSIDone( "JSFunction" );
}
}
|
/**
* Each new term in the Fibonacci sequence is generated by adding the previous two terms.
* By starting with 1 and 2, the first 10 terms will be:1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
* <p>
* By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the
* even-valued terms.
*
* @author David Clutter
*/
public class Problem0002 {
public static void main(final String[] args) {
int previous = 1;
int current = 2;
long sum = current;
while(current <= 4_000_000) {
final int temp = previous + current;
previous = current;
current = temp;
if((current & 1) == 0) {
sum += current;
}
}
System.out.println(sum);
}
}
|
package app.gui;
import app.App;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI extends JFrame implements ActionListener {
private JButton equalsButton;
private JButton plusButton;
private JButton minusButton;
private JButton multiplyButton;
private JButton divideButton;
private JButton clearButton;
private JButton deleteButton;
private JButton offButton;
private JTextField outputField;
private JButton[] numberButtons;
private JPanel numPanel;
private JPanel mainPanel;
private JPanel outPanel;
private App appRef;
public GUI (App app) {
super("Crazy Calculator");
this.appRef = app;
numberButtons= new JButton[12];
setLayout(new BorderLayout());
//mainPanel.setLayout(new BorderLayout());
Font font = new Font("Verdana", Font.BOLD, 14);
for(int i=9; i>=0;i
numberButtons[i] = new JButton(Integer.toString(i));
numberButtons[i].setPreferredSize(new Dimension(40,40));
numberButtons[i].setHorizontalAlignment(SwingConstants.CENTER);
numberButtons[i].setForeground(Color.WHITE);
numberButtons[i].setBackground(Color.BLACK);
numberButtons[i].setOpaque(true);
numberButtons[i].addActionListener(this);
}
numberButtons[10] = new JButton("(");
numberButtons[10].setHorizontalAlignment(SwingConstants.CENTER);
numberButtons[10].setForeground(Color.WHITE);
numberButtons[10].setBackground(Color.BLACK);
numberButtons[10].setOpaque(true);
numberButtons[10].addActionListener(this);
numberButtons[11] = new JButton(")");
numberButtons[11].setHorizontalAlignment(SwingConstants.CENTER);
numberButtons[11].setForeground(Color.WHITE);
numberButtons[11].setBackground(Color.BLACK);
numberButtons[11].setOpaque(true);
numberButtons[11].addActionListener(this);
clearButton = new JButton("AC");
clearButton.setForeground(Color.WHITE);
clearButton.setBackground(Color.BLACK);
clearButton.setOpaque(true);
clearButton.setHorizontalAlignment(SwingConstants.CENTER);
clearButton.addActionListener(this);
deleteButton = new JButton("DEL");
deleteButton.setForeground(Color.WHITE);
deleteButton.setBackground(Color.BLACK);
deleteButton.setOpaque(true);
deleteButton.setHorizontalAlignment(SwingConstants.CENTER);
deleteButton.addActionListener(this);
offButton = new JButton("OFF");
offButton.setForeground(Color.WHITE);
offButton.setBackground(Color.BLACK);
offButton.setOpaque(true);
offButton.setHorizontalAlignment(SwingConstants.CENTER);
offButton.addActionListener(this);
plusButton = new JButton("+");
plusButton.setHorizontalAlignment(SwingConstants.CENTER);
plusButton.addActionListener(this);
plusButton.setForeground(Color.WHITE);
plusButton.setBackground(Color.BLACK);
minusButton = new JButton("-");
minusButton.setHorizontalAlignment(SwingConstants.CENTER);
minusButton.addActionListener(this);
minusButton.setForeground(Color.WHITE);
minusButton.setBackground(Color.BLACK);
multiplyButton = new JButton("*");
multiplyButton.setHorizontalAlignment(SwingConstants.CENTER);
multiplyButton.addActionListener(this);
multiplyButton.setForeground(Color.WHITE);
multiplyButton.setBackground(Color.BLACK);
divideButton = new JButton("/");
divideButton.setHorizontalAlignment(SwingConstants.CENTER);
divideButton.addActionListener(this);
divideButton.setForeground(Color.WHITE);
divideButton.setBackground(Color.BLACK);
equalsButton = new JButton("=");
equalsButton.setHorizontalAlignment(SwingConstants.CENTER);
equalsButton.addActionListener(this);
equalsButton.setForeground(Color.WHITE);
equalsButton.setBackground(Color.BLACK);
outputField = new JTextField();
outputField.setLayout(new FlowLayout());
outputField.setHorizontalAlignment(JTextField.RIGHT);
outputField.setPreferredSize(new Dimension(295,95));
outputField.setBorder(javax.swing.BorderFactory.createEmptyBorder());
outputField.setOpaque(false);
outputField.setBackground(new Color(0,0,0,0));
outputField.setEditable(false);
outputField.setFont(font);
outPanel = new JPanel();
outPanel.setPreferredSize(new Dimension(50,100));
//outPanel.setBackground(Color.BLACK);
outPanel.add(outputField);
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(outPanel, BorderLayout.NORTH);
numPanel = new JPanel();
numPanel.setLayout(new GridLayout(5,4));
numPanel.setBackground(Color.BLACK);
//numPanel.setBorder(BorderFactory.createLineBorder(Color.black));
numPanel.add(clearButton);
numPanel.add(deleteButton);
numPanel.add(offButton);
numPanel.add(divideButton);
numPanel.add(numberButtons[7]);
numPanel.add(numberButtons[8]);
numPanel.add(numberButtons[9]);
numPanel.add(multiplyButton);
numPanel.add(numberButtons[4]);
numPanel.add(numberButtons[5]);
numPanel.add(numberButtons[6]);
numPanel.add(minusButton);
numPanel.add(numberButtons[1]);
numPanel.add(numberButtons[2]);
numPanel.add(numberButtons[3]);
numPanel.add(plusButton);
numPanel.add(numberButtons[0]);
numPanel.add(numberButtons[10]);
numPanel.add(numberButtons[11]);
numPanel.add(equalsButton);
mainPanel.add(numPanel);
add(mainPanel, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e)
{
for (int i = 0; i < 12; i++)
{
if (e.getSource() == numberButtons[i]) {
outputField.setText(outputField.getText() + numberButtons[i].getText());
}
}
if (e.getSource() == plusButton) {
outputField.setText(outputField.getText() + plusButton.getText());
} else if (e.getSource() == minusButton) {
outputField.setText(outputField.getText() + minusButton.getText());
} else if (e.getSource() == multiplyButton) {
outputField.setText(outputField.getText() + multiplyButton.getText());
} else if (e.getSource() == divideButton) {
outputField.setText(outputField.getText() + divideButton.getText());
} else if (e.getSource() == equalsButton) {
if (!this.outputField.getText().equals("")) {
this.appRef.startComputing(this.outputField.getText());
}
} else if (e.getSource() == clearButton) {
outputField.setText("");
} else if (e.getSource() == deleteButton) {
if (outputField.getText().length() > 0) {
outputField.setText(outputField.getText().substring(0, outputField.getText().length() - 1));
}
} else if (e.getSource() == offButton) {
System.exit(0);
}
}
public void setOutputField(String text)
{
this.outputField.setText(text);
}
}
|
package com.ai;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.boot.SpringApplication;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
private static final Logger logger = Logger.getLogger(Main.class);
public static void main(String ... args) throws Exception {
SpringApplication.run(Main.class, args);
OptionSet options = getOptions(args);
run(options);
}
/**
* Sets up logging options for sample run or test run
*
* @param options Options to check
*/
private static void handleSampleRun(OptionSet options) {
if (options.hasArgument("sample-run")) {
logger.setLevel(Level.DEBUG);
logger.debug("Beginning Sample Run...");
} else {
logger.setLevel(Level.WARN);
logger.debug("Beginning Test Run...");
}
}
/**
* Creates policy tests for each of the given racetracks and collision models
*
* @param options to check for num tests of
* @param racetracks racetracks to setup policy testers for
* @param collisionModels collision model to test with
* @return the list of needed policy testers
*/
private static Map<Racetrack, List<PolicyTester>> getPolicyTesters(OptionSet options, List<Racetrack> racetracks, List<CollisionModel> collisionModels) {
Map<Racetrack, List<PolicyTester>> policyTesters = new HashMap<>();
for(Racetrack raceTrack : racetracks) {
if (!policyTesters.containsKey(raceTrack)) {
policyTesters.put(raceTrack, new ArrayList<>());
}
for (CollisionModel collisionModel: collisionModels) {
logger.debug("Adding policy tester for "+ raceTrack + " and "+ collisionModel);
List<PolicyTester> policyTesterList = policyTesters.get(raceTrack);
policyTesterList.add(new PolicyTester(raceTrack, collisionModel, (Integer) options.valueOf("num-tests")));
}
}
return policyTesters;
}
/**
* Gets the needed collision models from the options
*
* @param options options to check for a model in
* @return the needed collision models
*/
private static List<CollisionModel> getCollisionModels(OptionSet options) {
List<CollisionModel> collisionModels = new ArrayList<>();
if (options.hasArgument("model")) {
switch (options.valueOf("model").toString()) {
case "stop":
logger.debug("Setting stop collision model for policy testers...");
collisionModels.add(Collision.STOP);
break;
case "restart":
logger.debug("Setting restart collision model for policy testers");
collisionModels.add(Collision.RESTART);
default:
logger.error("Unrecognized value for model " + options.valueOf("model").toString() + "expected <restart> or <stop>");
logger.error("Throwing runtime exception...");
new RuntimeException("Unrecognized argument");
}
} else {
collisionModels = Arrays.asList(Collision.STOP, Collision.RESTART);
}
return collisionModels;
}
/**
* Gets the needed racetrack learners for a racetrack
*
* @param options options to check for learners in
* @param racetracks racetracks to build learners for
*
* @return the needed racetrack learners for testing
*/
private static Map<Racetrack, RacetrackLearner> getRaceTrackLearners(OptionSet options, List<Racetrack> racetracks) {
Map<Racetrack, RacetrackLearner> learners = new HashMap<>();
if (options.hasArgument("learner")) {
String learnerName = options.valueOf("learner").toString();
switch (learnerName) {
case "sarsa":
logger.debug("Adding Sarsa to tester...");
//TODO add Sarsa
break;
case "value-iteration":
logger.debug("Adding Value iteration to tester...");
//TODO add value iteration
break;
default:
logger.error("Value not recognized: " + learnerName + ". Expected <sarsa> or <value-iteration>...");
logger.error("Throwing runtime exception...");
new RuntimeException("Learner name not recognized");
}
} else {
//TODO add sarsa
//TODO add value iteration
}
return learners;
}
/**
* Executes the tests determined by the options
*
* @param options the options that configure the tests
* @throws IOException caused by racetrack file not existing
*/
private static void run(OptionSet options) throws Exception {
handleSampleRun(options);
List<Racetrack> racetracks = getRaceTracks(options);
Map<Racetrack, RacetrackLearner> learners = getRaceTrackLearners(options, racetracks);
List<CollisionModel> collisionModels = getCollisionModels(options);
Map<Racetrack, List<PolicyTester>> policyTesters = getPolicyTesters(options, racetracks, collisionModels);
if (options.hasArgument("no-thread")) {
nonThreadedRun(learners, policyTesters, (Integer) options.valueOf("max-iteration"));
} else {
multiThreadedRun(learners, policyTesters, (Integer) options.valueOf("max-iteration"));
}
}
/**
* Gets the racetracks specified by the options
*
* @param options the options to check for racetracks in
*
* @return the specified racetracks
* @throws IOException if the racetracks cannot be found
*/
private static List<Racetrack> getRaceTracks(OptionSet options) throws IOException {
List<Racetrack> racetracks = new ArrayList<>();
Map<String, Racetrack> racetrackRegistry = new HashMap<>();
logger.debug("Adding only the l_track to the registry...");
racetrackRegistry.put("l_track", Racetrack.fromFile("l_track.txt"));
logger.debug("Adding only the r_track to the registry...");
racetrackRegistry.put("r_track", Racetrack.fromFile("r_track.txt"));
logger.debug("Adding only the o_track to the registry...");
racetrackRegistry.put("o_track", Racetrack.fromFile("o_track.txt"));
logger.debug("Adding only the small_l_track to the registry...");
racetrackRegistry.put("small_l_track", Racetrack.fromFile("small_l_track.txt"));
if (options.hasArgument("racetrack")) {
if (options.valueOf("racetrack").toString().equals("all")) {
logger.debug("Adding every racetrack in the registry...");
racetracks.addAll(racetrackRegistry.values());
} else {
logger.debug("Adding the specified racetrack" + racetrackRegistry.get(options.valueOf("racetrack").toString())+" ...");
racetracks.add(racetrackRegistry.get(options.valueOf("racetrack").toString()));
}
} else {
racetracks.add(racetrackRegistry.get("small_l_track"));
logger.debug("Adding only the small_l_track...");
}
return racetracks;
}
private static void nonThreadedRun(Map<Racetrack, RacetrackLearner> learners, Map<Racetrack, List<PolicyTester>> policyTesters, Integer maxIteration) {
logger.debug("Starting a non threaded run...");
while (!learners.isEmpty()) {
for (Map.Entry<Racetrack, RacetrackLearner> entry : learners.entrySet()) {
entry.getValue().next();
Policy policy = entry.getValue().getPolicy();
Iterator<PolicyTester> policyTesterIterator = policyTesters.get(entry.getKey()).iterator();
while (policyTesterIterator.hasNext()) {
PolicyTester policyTester = policyTesterIterator.next();
Result result = policyTester.testPolicy(policy);
logger.debug(
"Result: "+result.getMean() +
" with confidence of: " + result.getConfidence()+
" variance: " + result.getVariance() +
" for Learner :" + entry.getValue() +
" on iteration: "+entry.getValue().getIterationCount() +
" using the policy: " + policyTester.collisionModel()
);
if (entry.getValue().getIterationCount() >= maxIteration) {
logger.error("Max iteration count exceeded for: " +entry.getValue() + "removing policy testers...");
policyTesterIterator.remove();
} else if (entry.getValue().finished()) {
logger.info(entry.getValue() + " finished! Removing policy testers...");
policyTesterIterator.remove();
}
}
}
}
}
private static List<Result> runLearner(RacetrackLearner learner, PolicyTester tester, Integer maxIterations) {
List<Result> results = new ArrayList<>();
while (!learner.finished() && learner.getIterationCount() <= maxIterations) {
learner.next();
Policy policy = learner.getPolicy();
results.add(tester.testPolicy(policy, maxIterations));
}
if (learner.finished()) {
logger.debug(learner + " finished!");
} else {
logger.debug(learner + "did not terminate");
}
return results;
}
/**
* Runs a multi-threaded run of the racetrack runner
*
* @param learners to test
* @param policyTesters to test with
* @param maxIteration finish if the max iteration count is run
*
* @throws Exception thrown by the thread pool
*/
private static void multiThreadedRun(Map<Racetrack, RacetrackLearner> learners, Map<Racetrack, List<PolicyTester>> policyTesters, Integer maxIteration) throws Exception{
ExecutorService executor = Executors.newWorkStealingPool();
List<Callable<List<Result>>> callables = new ArrayList<>();
for (Map.Entry<Racetrack, RacetrackLearner> entry : learners.entrySet()) {
for (PolicyTester tester : policyTesters.get(entry.getKey())) {
callables.add(() -> runLearner(entry.getValue(), tester, maxIteration));
}
}
logger.debug("About to create futures...");
executor.invokeAll(callables).stream()
.map(future -> {
try {
return future.get();
}
catch (Exception e) {
throw new IllegalStateException(e);
}
}).forEach(logger::debug);
}
/**
* Takes the options for the program to run
* @param args program arguments
* @return returns an option set
*/
private static OptionSet getOptions(String ... args) {
OptionParser parser = new OptionParser();
parser.accepts("racetrack").withOptionalArg().ofType(String.class);
parser.accepts("model").withOptionalArg().ofType(String.class);
parser.accepts("learner").withOptionalArg().ofType(String.class);
parser.accepts("max-iteration").withRequiredArg().ofType(Integer.class).defaultsTo(Integer.MAX_VALUE);
parser.accepts("no-thread");
parser.accepts("num-tests").withRequiredArg().ofType(Integer.class).defaultsTo(20);
parser.accepts("result-loc").withRequiredArg().ofType(String.class).defaultsTo("/results");
parser.accepts("sample-loc").withRequiredArg().ofType(String.class).defaultsTo("/sample_runs");
parser.accepts("sample-run");
return parser.parse(args);
}
}
|
package org.sagebionetworks.bridge.services;
import static com.amazonaws.services.s3.Headers.SERVER_SIDE_ENCRYPTION;
import static com.amazonaws.services.s3.model.ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.Resource;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import com.amazonaws.AmazonClientException;
import com.google.common.base.Strings;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.sagebionetworks.bridge.config.BridgeConfig;
import org.sagebionetworks.bridge.dao.UploadDao;
import org.sagebionetworks.bridge.dao.UploadDedupeDao;
import org.sagebionetworks.bridge.exceptions.BadRequestException;
import org.sagebionetworks.bridge.exceptions.ConcurrentModificationException;
import org.sagebionetworks.bridge.exceptions.NotFoundException;
import org.sagebionetworks.bridge.json.DateUtils;
import org.sagebionetworks.bridge.models.DateTimeRangeResourceList;
import org.sagebionetworks.bridge.models.accounts.StudyParticipant;
import org.sagebionetworks.bridge.models.healthdata.HealthDataRecord;
import org.sagebionetworks.bridge.models.studies.StudyIdentifier;
import org.sagebionetworks.bridge.models.upload.Upload;
import org.sagebionetworks.bridge.models.upload.UploadCompletionClient;
import org.sagebionetworks.bridge.models.upload.UploadRequest;
import org.sagebionetworks.bridge.models.upload.UploadSession;
import org.sagebionetworks.bridge.models.upload.UploadStatus;
import org.sagebionetworks.bridge.models.upload.UploadValidationStatus;
import org.sagebionetworks.bridge.models.upload.UploadView;
import org.sagebionetworks.bridge.validators.UploadValidator;
import org.sagebionetworks.bridge.validators.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Validator;
import com.amazonaws.HttpMethod;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
@Component
public class UploadService {
private static final Logger logger = LoggerFactory.getLogger(UploadService.class);
private static final long EXPIRATION = 24 * 60 * 60 * 1000; // 24 hours
private static final int QUERY_WINDOW_IN_DAYS = 2;
// package-scoped to be available in unit tests
static final String CONFIG_KEY_UPLOAD_BUCKET = "upload.bucket";
private HealthDataService healthDataService;
private AmazonS3 s3UploadClient;
private AmazonS3 s3Client;
private String uploadBucket;
private UploadDao uploadDao;
private UploadSessionCredentialsService uploadCredentailsService;
private UploadDedupeDao uploadDedupeDao;
private UploadValidationService uploadValidationService;
private Validator validator;
/** Sets parameters from the specified Bridge config. */
@Autowired
final void setConfig(BridgeConfig config) {
uploadBucket = config.getProperty(CONFIG_KEY_UPLOAD_BUCKET);
}
/**
* Health data record service. This is needed to fetch the health data record when constructing the upload
* validation status.
*/
@Autowired
public void setHealthDataService(HealthDataService healthDataService) {
this.healthDataService = healthDataService;
}
@Resource(name = "s3UploadClient")
public void setS3UploadClient(AmazonS3 s3UploadClient) {
this.s3UploadClient = s3UploadClient;
}
@Resource(name = "s3Client")
public void setS3Client(AmazonS3 s3Client) {
this.s3Client = s3Client;
}
@Autowired
public void setUploadDao(UploadDao uploadDao) {
this.uploadDao = uploadDao;
}
/** Upload dedupe DAO, for checking to see if an upload is a dupe. (And eventually dedupe if it is.) */
@Autowired
final void setUploadDedupeDao(UploadDedupeDao uploadDedupeDao) {
this.uploadDedupeDao = uploadDedupeDao;
}
@Autowired
public void setUploadSessionCredentialsService(UploadSessionCredentialsService uploadCredentialsService) {
this.uploadCredentailsService = uploadCredentialsService;
}
/** Service handler for upload validation. This is configured by Spring. */
@Autowired
final void setUploadValidationService(UploadValidationService uploadValidationService) {
this.uploadValidationService = uploadValidationService;
}
@Autowired
public void setValidator(UploadValidator validator) {
this.validator = validator;
}
public UploadSession createUpload(StudyIdentifier studyId, StudyParticipant participant, UploadRequest uploadRequest) {
Validate.entityThrowingException(validator, uploadRequest);
// Check to see if upload is a dupe, and if it is, get the upload status.
String uploadMd5 = uploadRequest.getContentMd5();
DateTime uploadRequestedOn = DateUtils.getCurrentDateTime();
String originalUploadId = null;
UploadStatus originalUploadStatus = null;
try {
originalUploadId = uploadDedupeDao.getDuplicate(participant.getHealthCode(), uploadMd5, uploadRequestedOn);
if (originalUploadId != null) {
Upload originalUpload = uploadDao.getUpload(originalUploadId);
originalUploadStatus = originalUpload.getStatus();
}
} catch (RuntimeException ex) {
// Don't want dedupe logic to fail the upload. Log an error and swallow the exception.
logger.error("Error deduping upload: " + ex.getMessage(), ex);
}
String uploadId;
if (originalUploadId != null && originalUploadStatus == UploadStatus.REQUESTED) {
// This is a dupe of a previous upload, and that previous upload is incomplete (REQUESTED). Instead of
// creating a new upload in the upload table, reactivate the old one.
uploadId = originalUploadId;
} else {
// This is a new upload.
Upload upload = uploadDao.createUpload(uploadRequest, studyId, participant.getHealthCode());
uploadId = upload.getUploadId();
if (originalUploadId != null) {
// We had a dupe of a previous completed upload. Log this for future analysis.
logger.info("Detected dupe: Study " + studyId.getIdentifier() + ", upload " + uploadId +
" is a dupe of " + originalUploadId);
} else {
try {
// Not a dupe. Register this dupe so we can detect dupes of this.
uploadDedupeDao.registerUpload(participant.getHealthCode(), uploadMd5, uploadRequestedOn, uploadId);
} catch (RuntimeException ex) {
// Don't want dedupe logic to fail the upload. Log an error and swallow the exception.
logger.error("Error registering upload " + uploadId + " in dedupe table: " + ex.getMessage(), ex);
}
}
}
// Upload ID in DynamoDB is the same as the S3 Object ID
GeneratePresignedUrlRequest presignedUrlRequest =
new GeneratePresignedUrlRequest(uploadBucket, uploadId, HttpMethod.PUT);
// Expiration
final Date expiration = DateTime.now(DateTimeZone.UTC).toDate();
expiration.setTime(expiration.getTime() + EXPIRATION);
presignedUrlRequest.setExpiration(expiration);
// Temporary session credentials
presignedUrlRequest.setRequestCredentials(uploadCredentailsService.getSessionCredentials());
// Ask for server-side encryption
presignedUrlRequest.addRequestParameter(SERVER_SIDE_ENCRYPTION, AES_256_SERVER_SIDE_ENCRYPTION);
// Additional headers for signing
presignedUrlRequest.setContentMd5(uploadMd5);
presignedUrlRequest.setContentType(uploadRequest.getContentType());
URL url = s3UploadClient.generatePresignedUrl(presignedUrlRequest);
return new UploadSession(uploadId, url, expiration.getTime());
}
/**
* <p>
* Get upload service handler. This isn't currently exposed directly to the users, but is currently used by the
* controller class to call both uploadComplete() and upload validation APIs.
* </p>
* <p>
* user comes from the controller, and is guaranteed to be present. However, uploadId is user input and must be
* validated.
* </p>
*
* @param uploadId
* ID of upload to fetch, must be non-null and non-empty
* @return upload metadata object
*/
public Upload getUpload(@Nonnull String uploadId) {
if (Strings.isNullOrEmpty(uploadId)) {
throw new BadRequestException(String.format(Validate.CANNOT_BE_BLANK, "uploadId"));
}
return uploadDao.getUpload(uploadId);
}
/**
* <p>Get uploads for a given user in a time window. Start and end time are optional. If neither are provided, they
* default to the last day of uploads. If end time is not provided, the query ends at the time of the request. If the
* start time is not provided, it defaults to a day before the end time. The time window is constrained to two days
* of uploads (though those days can be any period in time). </p>
*/
public DateTimeRangeResourceList<? extends UploadView> getUploads(@Nonnull String healthCode,
@Nullable DateTime startTime, @Nullable DateTime endTime) {
checkNotNull(healthCode);
return getUploads(startTime, endTime, (start, end)-> {
return uploadDao.getUploads(healthCode, start, end);
});
}
/**
* <p>Get uploads for an entire study in a time window. Start and end time are optional. If neither are provided, they
* default to the last day of uploads. If end time is not provided, the query ends at the time of the request. If the
* start time is not provided, it defaults to a day before the end time. The time window is constrained to two days
* of uploads (though those days can be any period in time). </p>
*/
public DateTimeRangeResourceList<? extends UploadView> getStudyUploads(@Nonnull StudyIdentifier studyId,
@Nullable DateTime startTime, @Nullable DateTime endTime) {
checkNotNull(studyId);
return getUploads(startTime, endTime, (start, end)-> {
return uploadDao.getStudyUploads(studyId, start, end);
});
}
private DateTimeRangeResourceList<? extends UploadView> getUploads(DateTime startTime, DateTime endTime, UploadSupplier supplier) {
checkNotNull(supplier);
if (startTime == null && endTime == null) {
endTime = DateTime.now();
startTime = endTime.minusDays(1);
} else if (endTime == null) {
endTime = startTime.plusDays(1);
} else if (startTime == null) {
startTime = endTime.minusDays(1);
}
if (endTime.isBefore(startTime)) {
throw new BadRequestException("Start time cannot be after end time: " + startTime + "-" + endTime);
}
if (startTime.plusDays(QUERY_WINDOW_IN_DAYS).isBefore(endTime)) {
throw new BadRequestException("Query window cannot be longer than two days: " + startTime + "-" + endTime);
}
List<UploadView> views = supplier.get(startTime, endTime).stream().map(upload -> {
UploadView.Builder builder = new UploadView.Builder();
builder.withUpload(upload);
if (upload.getRecordId() != null) {
HealthDataRecord record = healthDataService.getRecordById(upload.getRecordId());
if (record != null) {
builder.withSchemaId(record.getSchemaId());
builder.withSchemaRevision(record.getSchemaRevision());
}
}
return builder.build();
}).collect(Collectors.toList());
return new DateTimeRangeResourceList<UploadView>(views, startTime, endTime);
}
/**
* <p>
* Gets validation status and messages for the given upload ID. This includes the health data record, if one was
* created for the upload.
* </p>
* <p>
* user comes from the controller, and is guaranteed to be present. However, uploadId is user input and must be
* validated.
* </p>
*
* @param uploadId
* ID of upload to fetch, must be non-null and non-empty
* @return upload validation status, which includes the health data record if one was created
*/
public UploadValidationStatus getUploadValidationStatus(@Nonnull String uploadId) {
Upload upload = getUpload(uploadId);
// get record, if it exists
HealthDataRecord record = null;
String recordId = upload.getRecordId();
if (!Strings.isNullOrEmpty(recordId)) {
try {
record = healthDataService.getRecordById(recordId);
} catch (RuntimeException ex) {
// Underlying service failed to get the health data record. Log a warning, but move on.
logger.warn("Error getting record ID " + recordId + " for upload ID " + uploadId + ": "
+ ex.getMessage(), ex);
}
}
UploadValidationStatus validationStatus = UploadValidationStatus.from(upload, record);
return validationStatus;
}
public void uploadComplete(StudyIdentifier studyId, UploadCompletionClient completedBy, Upload upload) {
String uploadId = upload.getUploadId();
// We don't want to kick off upload validation on an upload that already has upload validation.
if (!upload.canBeValidated()) {
logger.info(String.format("uploadComplete called for upload %s, which is already complete", uploadId));
return;
}
final String objectId = upload.getObjectId();
ObjectMetadata obj;
try {
obj = s3Client.getObjectMetadata(uploadBucket, objectId);
} catch (AmazonClientException ex) {
throw new NotFoundException(ex);
}
String sse = obj.getSSEAlgorithm();
if (!AES_256_SERVER_SIDE_ENCRYPTION.equals(sse)) {
logger.error("Missing S3 server-side encryption (SSE) for presigned upload " + uploadId + ".");
}
try {
uploadDao.uploadComplete(completedBy, upload);
} catch (ConcurrentModificationException ex) {
// The old workflow is the app calls uploadComplete. The new workflow has an S3 trigger to call
// uploadComplete. During the transition, it's very likely that this will be called twice, sometimes
// concurrently. As such, we should log and squelch the ConcurrentModificationException.
logger.info("Concurrent modification of upload " + uploadId + " while marking upload complete");
// Also short-circuit the call early, so we don't end up validating the upload twice, as this causes errors
// and duplicate records.
return;
}
// kick off upload validation
uploadValidationService.validateUpload(studyId, upload);
}
@FunctionalInterface
private static interface UploadSupplier {
List<? extends Upload> get(DateTime startTime, DateTime endTime);
}
}
|
package net.java.sip.communicator.impl.contactlist;
import java.io.*;
import java.util.*;
import javax.xml.parsers.*;
import net.java.sip.communicator.service.contactlist.*;
import net.java.sip.communicator.service.contactlist.event.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.util.*;
import org.jitsi.service.configuration.*;
import org.jitsi.service.fileaccess.*;
import org.jitsi.util.xml.*;
import org.jitsi.util.xml.XMLUtils;
import org.osgi.framework.*;
import org.w3c.dom.*;
/**
* The class handles read / write operations over the file where a persistent
* copy of the meta contact list is stored.
* <p>
* The load / resolve strategy that we use when storing contact lists is roughly
* the following:
* <p>
* 1) The MetaContactListService is started. <br>
* 2) If no file exists for the meta contact list, create one. <br>
* 3) We receive an OSGI event telling us that a new ProtocolProviderService is
* registered or we simply retrieve one that was already in the bundle <br>
* 4) We look through the contact list file and load groups and contacts
* belonging to this new provider. Unresolved proto groups and contacts will be
* created for every one of them.
* <p>
*
* @author Emil Ivov
*/
public class MclStorageManager
implements MetaContactListListener
{
private static final Logger logger
= Logger.getLogger(MclStorageManager.class);
/**
* Indicates whether the storage manager has been properly started or in
* other words that it has successfully found and read the xml contact list
* file.
*/
private boolean started = false;
/**
* Indicates whether there has been a change since the last time we stored
* this contact list. Used by the storage methods.
*/
private boolean isModified = false;
/**
* A currently valid reference to the OSGI bundle context,
*/
private BundleContext bundleContext = null;
/**
* The file access service that we'll be using in order to obtain a
* reference to the contact list file.
*/
private FileAccessService faService = null;
/**
* The name of the system property that stores the name of the contact list
* file.
*/
private static final String FILE_NAME_PROPERTY =
"net.java.sip.communicator.CONTACTLIST_FILE_NAME";
/**
* The XML Document containing the contact list file.
*/
private Document contactListDocument = null;
/**
* A reference to the file containing the locally stored meta contact list.
*/
private File contactlistFile = null;
/**
* A reference to the failsafe transaction used with the contactlist file.
*/
private FailSafeTransaction contactlistTrans = null;
/**
* A reference to the MetaContactListServiceImpl that created and started
* us.
*/
private MetaContactListServiceImpl mclServiceImpl = null;
/**
* The name of the system property that stores the name of the contact list
* file.
*/
private static final String DEFAULT_FILE_NAME = "contactlist.xml";
/**
* The name of the node that represents the contact list root.
*/
private static String DOCUMENT_ROOT_NAME = "sip-communicator";
/**
* The name of the XML node corresponding to a meta contact group.
*/
private static final String GROUP_NODE_NAME = "group";
/**
* The name of the XML node corresponding to a collection of meta contact
* subgroups.
*/
private static final String SUBGROUPS_NODE_NAME = "subgroups";
/**
* The name of the XML attribute that contains group names.
*/
private static final String GROUP_NAME_ATTR_NAME = "name";
/**
* The name of the XML attribute that contains group UIDs.
*/
private static final String GROUP_UID_ATTR_NAME = "uid";
/**
* The name of the XML node that contains protocol specific group
* descriptorS.
*/
private static final String PROTO_GROUPS_NODE_NAME = "proto-groups";
/**
* The name of the XML node that contains A protocol specific group
* descriptor.
*/
private static final String PROTO_GROUP_NODE_NAME = "proto-group";
/**
* The name of the XML attribute that contains unique identifiers
*/
private static final String UID_ATTR_NAME = "uid";
/**
* The name of the XML attribute that contains unique identifiers for parent
* contact groups.
*/
private static final String PARENT_PROTO_GROUP_UID_ATTR_NAME =
"parent-proto-group-uid";
/**
* The name of the XML attribute that contains account identifiers
* indicating proto group's and proto contacts' owning providers.
*/
private static final String ACCOUNT_ID_ATTR_NAME = "account-id";
/**
* The name of the XML node that contains meta contact details.
*/
private static final String META_CONTACT_NODE_NAME = "meta-contact";
/**
* The name of the XML node that contains meta contact display names.
*/
private static final String META_CONTACT_DISPLAY_NAME_NODE_NAME =
"display-name";
/**
* The name of the XML attribute that contains true/false, whether
* this meta contact was renamed by user.
*/
private static final String USER_DEFINED_DISPLAY_NAME_ATTR_NAME =
"user-defined";
/**
* The name of the XML node that contains meta contact detail.
*/
private static final String META_CONTACT_DETAIL_NAME_NODE_NAME = "detail";
/**
* The name of the XML attribute that contains detail name.
*/
private static final String DETAIL_NAME_ATTR_NAME = "name";
/**
* The name of the XML attribute that contains detail value.
*/
private static final String DETAIL_VALUE_ATTR_NAME = "value";
/**
* The name of the XML node that contains information of a proto contact
*/
private static final String PROTO_CONTACT_NODE_NAME = "contact";
/**
* The name of the XML node that contains information of a proto contact
*/
private static final String PROTO_CONTACT_ADDRESS_ATTR_NAME = "address";
/**
* The name of the XML node that contains information that contacts or
* groups returned as persistent and that should be used when restoring a
* contact or a group.
*/
private static final String PERSISTENT_DATA_NODE_NAME = "persistent-data";
/**
* The name of the XML node that contains all meta contact nodes inside a
* group
*/
private static final String CHILD_CONTACTS_NODE_NAME = "child-contacts";
/**
* A lock that we use when storing the contact list to avoid being exited
* while in there.
*/
private static final Object contactListRWLock = new Object();
/**
* Determines whether the storage manager has been properly started or in
* other words that it has successfully found and read the xml contact list
* file.
*
* @return true if the storage manager has been successfully initialized and
* false otherwise.
*/
boolean isStarted()
{
return started;
}
/**
* Prepares the storage manager for shutdown.
*/
public void stop()
{
if (logger.isTraceEnabled())
logger.trace("Stopping the MCL XML storage manager.");
this.started = false;
synchronized (contactListRWLock)
{
contactListRWLock.notifyAll();
}
}
/**
* Initializes the storage manager and makes it do initial load and parsing
* of the contact list file.
*
* @param bc a reference to the currently valid OSGI <tt>BundleContext</tt>
* @param mclServImpl a reference to the currently valid instance of the
* <tt>MetaContactListServiceImpl</tt> that we could use to pass
* parsed contacts and contact groups.
* @throws IOException if the contact list file specified file does not
* exist and could not be created.
* @throws XMLException if there is a problem with the file syntax.
*/
void start(BundleContext bc, MetaContactListServiceImpl mclServImpl)
throws IOException,
XMLException
{
bundleContext = bc;
// retrieve a reference to the file access service.
ServiceReference faServiceReference =
bundleContext
.getServiceReference(FileAccessService.class.getName());
faService =
(FileAccessService) bundleContext.getService(faServiceReference);
// retrieve a reference to the file access service.
ServiceReference confServiceRefs =
bundleContext.getServiceReference(ConfigurationService.class
.getName());
ConfigurationService configurationService =
(ConfigurationService) bundleContext.getService(confServiceRefs);
String fileName = configurationService.getString(FILE_NAME_PROPERTY);
if (fileName == null)
{
fileName = System.getProperty(FILE_NAME_PROPERTY);
if (fileName == null)
fileName = DEFAULT_FILE_NAME;
}
// get a reference to the contact list file.
try
{
contactlistFile = faService.getPrivatePersistentFile(fileName,
FileCategory.PROFILE);
if (!contactlistFile.exists() && !contactlistFile.createNewFile())
throw new IOException("Failed to create file"
+ contactlistFile.getAbsolutePath());
}
catch (Exception ex)
{
logger.error("Failed to get a reference to the contact list file.",
ex);
throw new IOException("Failed to get a reference to the contact "
+ "list file=" + fileName + ". error was:" + ex.getMessage());
}
// create the failsafe transaction and restore the file if needed
try
{
contactlistTrans =
faService.createFailSafeTransaction(this.contactlistFile);
contactlistTrans.restoreFile();
}
catch (NullPointerException e)
{
logger.error("the contactlist file is null", e);
}
catch (IllegalStateException e)
{
logger.error("The contactlist file can't be found", e);
}
try
{
// load the contact list
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
if (contactlistFile.length() == 0)
{
// if the contact list does not exist - create it.
contactListDocument = builder.newDocument();
initVirginDocument(mclServImpl, contactListDocument);
// write the contact list so that it is there for the parser
storeContactList0();
}
else
{
try
{
contactListDocument = builder.parse(contactlistFile);
}
catch (Throwable ex)
{
logger.error("Error parsing configuration file", ex);
logger.error("Creating replacement file");
// re-create and re-init the new document
contactlistFile.delete();
contactlistFile.createNewFile();
contactListDocument = builder.newDocument();
initVirginDocument(mclServImpl, contactListDocument);
// write the contact list so that it is there for the parser
storeContactList0();
}
}
}
catch (ParserConfigurationException ex)
{
// it is not highly probable that this might happen - so lets just
// log it.
logger.error("Error finding configuration for default parsers", ex);
}
mclServImpl.addMetaContactListListener(this);
this.mclServiceImpl = mclServImpl;
started = true;
this.launchStorageThread();
}
/**
* Stores the contact list in its current state.
*
* @throws IOException if writing fails.
*/
private void scheduleContactListStorage() throws IOException
{
synchronized (contactListRWLock)
{
if (!isStarted())
return;
this.isModified = true;
contactListRWLock.notifyAll();
}
}
/**
* Writes the contact list on the hard disk.
*
* @throws IOException in case writing fails.
*/
private void storeContactList0() throws IOException
{
if (logger.isTraceEnabled())
logger.trace("storing contact list. because is started =="
+ isStarted());
if (logger.isTraceEnabled())
logger.trace("storing contact list. because is modified =="
+ isModified);
if (isStarted())
{
// begin a new transaction
try
{
contactlistTrans.beginTransaction();
}
catch (IllegalStateException e)
{
logger.error("the contactlist file is missing", e);
}
// really write the modification
OutputStream stream = new FileOutputStream(contactlistFile);
XMLUtils.indentedWriteXML(contactListDocument, stream);
stream.close();
// commit the changes
try
{
contactlistTrans.commit();
}
catch (IllegalStateException e)
{
logger.error("the contactlist file is missing", e);
}
}
}
/**
* Launches a separate thread that waits on the contact list rw lock and
* when notified stores the contact list in case there have been
* modifications since last time it saved.
*/
private void launchStorageThread()
{
new Thread()
{
@Override
public void run()
{
try
{
synchronized (contactListRWLock)
{
while (isStarted())
{
contactListRWLock.wait(5000);
if (isModified)
{
storeContactList0();
isModified = false;
}
}
}
}
catch (IOException ex)
{
logger.error("Storing contact list failed", ex);
started = false;
}
catch (InterruptedException ex)
{
logger.error("Storing contact list failed", ex);
started = false;
}
}
}.start();
}
/**
* Stops the storage manager and performs a final write
*/
public void storeContactListAndStopStorageManager()
{
synchronized (contactListRWLock)
{
if (!isStarted())
return;
started = false;
// make sure everyone gets released after we finish.
contactListRWLock.notifyAll();
// write the contact list ourselves before we go out..
try
{
storeContactList0();
}
catch (IOException ex)
{
logger
.debug("Failed to store contact list before stopping", ex);
}
}
}
/**
* update persistent data in the dom object model for the given metacontact
* and its contacts
*
* @param metaContact MetaContact target meta contact
*/
private void updatePersistentDataForMetaContact(MetaContact metaContact)
{
Element metaContactNode = findMetaContactNode(metaContact.getMetaUID());
Iterator<Contact> iter = metaContact.getContacts();
while (iter.hasNext())
{
Contact item = iter.next();
String persistentData = item.getPersistentData();
/*
* TODO If persistentData is null and persistentDataNode exists and
* contains non-null text, will persistentDataNode be left without
* updating?
*/
if (persistentData != null)
{
Element currentNode =
XMLUtils.locateElement(metaContactNode,
PROTO_CONTACT_NODE_NAME,
PROTO_CONTACT_ADDRESS_ATTR_NAME, item.getAddress());
Element persistentDataNode =
XMLUtils.findChild(currentNode, PERSISTENT_DATA_NODE_NAME);
// if node does not exist - create it
if (persistentDataNode == null)
{
persistentDataNode =
contactListDocument
.createElement(PERSISTENT_DATA_NODE_NAME);
currentNode.appendChild(persistentDataNode);
}
XMLUtils.setText(persistentDataNode, persistentData);
}
}
}
/**
* Fills the document with the tags necessary for it to be filled properly
* as the meta contact list evolves.
*
* @param mclServImpl the meta contact list service to use when
* initializing the document.
* @param contactListDoc the document to init.
*/
private void initVirginDocument(MetaContactListServiceImpl mclServImpl,
Document contactListDoc)
{
Element root = contactListDoc.createElement(DOCUMENT_ROOT_NAME);
contactListDoc.appendChild(root);
// create the rootGroup
Element rootGroup =
createMetaContactGroupNode(mclServImpl.getRoot());
root.appendChild(rootGroup);
}
/**
* Parses the contact list file and calls corresponding "add" methods
* belonging to <tt>mclServiceImpl</tt> for every meta contact and meta
* contact group stored in the (contactlist.xml) file that correspond to a
* provider caring the specified <tt>accountID</tt>.
*
* @param accountID the identifier of the account whose contacts we're
* interested in.
* @throws XMLException if a problem occurs while parsing contact list
* contents.
*/
void extractContactsForAccount(String accountID) throws XMLException
{
if (!isStarted())
return;
// we don't want to receive meta contact events triggered by ourselves
// so we stop listening. it is possible but very unlikely that other
// events, not triggered by us are received while we're off the channel
// but that would be a very bizzare case ..... I guess we got to live
// with the risk.
this.mclServiceImpl.removeMetaContactListListener(this);
try
{
Element root =
findMetaContactGroupNode(mclServiceImpl.getRoot().getMetaUID());
if (root == null)
{
// If there is no root, there is definitely something wrong
// really broken file will create it again
logger
.fatal("The contactlist file is recreated cause its broken");
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
contactListDocument = builder.newDocument();
initVirginDocument(mclServiceImpl, contactListDocument);
// write the contact list so that it is there for the parser
storeContactList0();
}
else
{
// if there is root lets parse it
// parse the group node and extract all its child groups and
// contacts
processGroupXmlNode(mclServiceImpl, accountID, root, null, null);
// now save the contact list in case it has changed
scheduleContactListStorage();
}
}
catch (Throwable exc)
{
// catch everything because we MUST NOT disturb the thread
// initializing the meta CL for a new provider with null point
// exceptions or others of the sort
throw new XMLException("Failed to extract contacts for account "
+ accountID, exc);
}
finally
{
// now that we're done updating the contact list we can start
// listening
// again
this.mclServiceImpl.addMetaContactListListener(this);
}
}
/**
* Parses <tt>groupNode</tt> and all of its subnodes, creating corresponding
* instances through <tt>mclServiceImpl</tt> as children of
* <tt>parentGroup</tt>
*
* @param mclServImpl the <tt>MetaContactListServiceImpl</tt> for
* creating new contacts and groups.
* @param accountID a String identifier of the account whose contacts we're
* interested in.
* @param groupNode the XML <tt>Element</tt> that points to the group we're
* currently parsing.
* @param parentGroup the <tt>MetaContactGroupImpl</tt> where we should be
* creating children.
* @param parentProtoGroups a Map containing all proto groups that could be
* parents of any groups parsed from the specified groupNode. The
* map binds UIDs to group references and may be null for top
* level groups.
*/
private void processGroupXmlNode(MetaContactListServiceImpl mclServImpl,
String accountID, Element groupNode, MetaContactGroupImpl parentGroup,
Map<String, ContactGroup> parentProtoGroups)
{
// first resolve the group itself.(unless this is the meta contact list
// root which is already resolved)
MetaContactGroupImpl currentMetaGroup;
// in this map we store all proto groups that we find in this meta group
// (unless this is the MCL root)in order to pass them as parent
// references to any subgroups.
Map<String, ContactGroup> protoGroupsMap =
new Hashtable<String, ContactGroup>();
if (parentGroup == null)
{
currentMetaGroup = mclServImpl.rootMetaGroup;
}
else
{
String groupMetaUID =
XMLUtils.getAttribute(groupNode, GROUP_UID_ATTR_NAME);
String groupDisplayName =
XMLUtils.getAttribute(groupNode, GROUP_NAME_ATTR_NAME);
// create the meta group
currentMetaGroup =
mclServImpl.loadStoredMetaContactGroup(parentGroup,
groupMetaUID, groupDisplayName);
// extract and load one by one all proto groups in this meta group.
Node protoGroupsNode =
XMLUtils.findChild(groupNode, PROTO_GROUPS_NODE_NAME);
NodeList protoGroups = protoGroupsNode.getChildNodes();
for (int i = 0; i < protoGroups.getLength(); i++)
{
Node currentProtoGroupNode = protoGroups.item(i);
if (currentProtoGroupNode.getNodeType() != Node.ELEMENT_NODE)
continue;
String groupAccountID =
XMLUtils.getAttribute(currentProtoGroupNode,
ACCOUNT_ID_ATTR_NAME);
if (!accountID.equals(groupAccountID))
continue;
String protoGroupUID =
XMLUtils.getAttribute(currentProtoGroupNode, UID_ATTR_NAME);
String parentProtoGroupUID =
XMLUtils.getAttribute(currentProtoGroupNode,
PARENT_PROTO_GROUP_UID_ATTR_NAME);
Element persistentDataNode =
XMLUtils.findChild((Element) currentProtoGroupNode,
PERSISTENT_DATA_NODE_NAME);
String persistentData = "";
if (persistentDataNode != null)
{
persistentData = XMLUtils.getText(persistentDataNode);
}
// try to find the parent proto group for the one we're
// currently
// parsing.
ContactGroup parentProtoGroup = null;
if (parentProtoGroups != null && parentProtoGroups.size() > 0)
parentProtoGroup =
parentProtoGroups.get(parentProtoGroupUID);
// create the proto group
ContactGroup newProtoGroup =
mclServImpl.loadStoredContactGroup(currentMetaGroup,
protoGroupUID, parentProtoGroup, persistentData,
accountID);
protoGroupsMap.put(protoGroupUID, newProtoGroup);
}
// if this is not the meta contact list root and if it doesn't
// contain proto groups of the account we're currently loading then
// we don't need to recurese it since it cound contain any child
// contacts of the same account.
if (protoGroupsMap.size() == 0)
return;
}
// we have parsed groups now go over the children
Node childContactsNode =
XMLUtils.findChild(groupNode, CHILD_CONTACTS_NODE_NAME);
NodeList childContacts =
(childContactsNode == null) ? null : childContactsNode
.getChildNodes();
// go over every meta contact, extract its details and its encapsulated
// proto contacts
for (int i = 0; childContacts != null && i < childContacts.getLength(); i++)
{
Node currentMetaContactNode = childContacts.item(i);
if (currentMetaContactNode.getNodeType() != Node.ELEMENT_NODE)
continue;
try
{
String uid =
XMLUtils
.getAttribute(currentMetaContactNode, UID_ATTR_NAME);
Element displayNameNode =
XMLUtils.findChild((Element) currentMetaContactNode,
META_CONTACT_DISPLAY_NAME_NODE_NAME);
String displayName = XMLUtils.getText(displayNameNode);
boolean isDisplayNameUserDefined =
Boolean.valueOf(displayNameNode
.getAttribute(USER_DEFINED_DISPLAY_NAME_ATTR_NAME));
// extract a map of all encapsulated proto contacts
List<MclStorageManager.StoredProtoContactDescriptor> protoContacts =
extractProtoContacts((Element) currentMetaContactNode,
accountID, protoGroupsMap);
// if the size of the map is 0 then the meta contact does not
// contain any contacts matching the currently parsed account
if (protoContacts.size() < 1)
continue;
// Extract contact details.
Map<String, List<String>> details = null;
try
{
List<Element> detailsNodes =
XMLUtils.findChildren((Element) currentMetaContactNode,
META_CONTACT_DETAIL_NAME_NODE_NAME);
if (detailsNodes.size() > 0)
{
details = new Hashtable<String, List<String>>();
for (Element e : detailsNodes)
{
String name = e.getAttribute(DETAIL_NAME_ATTR_NAME);
String value
= e.getAttribute(DETAIL_VALUE_ATTR_NAME);
List<String> detailsObj = details.get(name);
if (detailsObj == null)
{
List<String> ds = new ArrayList<String>();
ds.add(value);
details.put(name, ds);
}
else
detailsObj.add(value);
}
}
}
catch (Exception ex)
{
// catch any exception from loading contacts
// that will prevent loading the contact
logger.error("Cannot load details for contact node "
+ currentMetaContactNode, ex);
}
// pass the parsed proto contacts to the mcl service
MetaContactImpl mc = mclServImpl.loadStoredMetaContact(
currentMetaGroup, uid,
displayName, details, protoContacts, accountID);
if(isDisplayNameUserDefined)
mc.setDisplayNameUserDefined(true);
}
catch (Throwable thr)
{
// if we fail parsing a meta contact, we should remove it so
// that
// it stops causing trouble, and let other meta contacts load.
logger.warn("Failed to parse meta contact "
+ currentMetaContactNode
+ ". Will remove and continue with other contacts", thr);
// remove the node so that it doesn't cause us problems again
if (currentMetaContactNode.getParentNode() != null)
{
try
{
currentMetaContactNode.getParentNode().removeChild(
currentMetaContactNode);
}
catch (Throwable throwable)
{
// hmm, failed to remove the faulty node. we must be
// in some kind of serious troble (but i don't see
// what we can do about it)
logger.error("Failed to remove meta contact node "
+ currentMetaContactNode, throwable);
}
}
}
}
// now, last thing that's left to do - go over all subgroups if any
Node subgroupsNode = XMLUtils.findChild(groupNode, SUBGROUPS_NODE_NAME);
if (subgroupsNode == null)
return;
NodeList subgroups = subgroupsNode.getChildNodes();
// recurse for every sub meta group
for (int i = 0; i < subgroups.getLength(); i++)
{
Node currentGroupNode = subgroups.item(i);
if (currentGroupNode.getNodeType() != Node.ELEMENT_NODE
|| !currentGroupNode.getNodeName().equals(GROUP_NODE_NAME))
continue;
try
{
processGroupXmlNode(mclServImpl, accountID,
(Element) currentGroupNode, currentMetaGroup,
protoGroupsMap);
}
catch (Throwable throwable)
{
// catch everything and bravely continue with remaining groups
// and contacts
logger.error("Failed to process group node " + currentGroupNode
+ ". Removing.", throwable);
// remove the node so that it doesn't cause us problems again
if (currentGroupNode.getParentNode() != null)
{
try
{
currentGroupNode.getParentNode().removeChild(
currentGroupNode);
}
catch (Throwable thr)
{
// hmm, failed to remove the faulty node. we must be
// in some kind of serious troble (but i don't see
// what we can do about it)
logger.error("Failed to remove group node "
+ currentGroupNode, thr);
}
}
}
}
}
/**
* Returns all proto contacts that are encapsulated inside the meta contact
* represented by <tt>metaContactNode</tt> and that originate from the
* account with id - <tt>accountID</tt>. The returned list contains contact
* contact descriptors as elements. In case the meta contact does not
* contain proto contacts originating from the specified account, an empty
* list is returned.
* <p>
*
* @param metaContactNode the Element whose proto contacts we'd like to
* extract.
* @param accountID the id of the account whose contacts we're interested
* in.
* @param protoGroups a map binding proto group UIDs to protogroups, that
* the method could use i n order to fill in the corresponding
* field in the contact descriptors.
* @return a java.util.List containing contact descriptors.
*/
private List<MclStorageManager.StoredProtoContactDescriptor>
extractProtoContacts(Element metaContactNode,
String accountID,
Map<String, ContactGroup> protoGroups)
{
if(logger.isTraceEnabled())
logger.trace("Extracting proto contacts for "
+ XMLUtils.getAttribute( metaContactNode, "uid"));
List<StoredProtoContactDescriptor> protoContacts =
new LinkedList<StoredProtoContactDescriptor>();
NodeList children = metaContactNode.getChildNodes();
List<Node> duplicates = new LinkedList<Node>();
for (int i = 0; i < children.getLength(); i++)
{
Node currentNode = children.item(i);
//for some reason every now and then we would get a null nodename
//... go figure
if (currentNode.getNodeName() == null)
continue;
if (currentNode.getNodeType() != Node.ELEMENT_NODE
|| !currentNode.getNodeName().equals(PROTO_CONTACT_NODE_NAME))
continue;
String contactAccountID =
XMLUtils.getAttribute(currentNode, ACCOUNT_ID_ATTR_NAME);
if (!accountID.equals(contactAccountID))
continue;
String contactAddress =
XMLUtils.getAttribute(currentNode,
PROTO_CONTACT_ADDRESS_ATTR_NAME);
if (StoredProtoContactDescriptor.findContactInList(contactAddress,
protoContacts) != null)
{
// this is a duplicate. mark for removal and continue
duplicates.add(currentNode);
continue;
}
String protoGroupUID =
XMLUtils.getAttribute(currentNode,
PARENT_PROTO_GROUP_UID_ATTR_NAME);
Element persistentDataNode =
XMLUtils.findChild((Element) currentNode,
PERSISTENT_DATA_NODE_NAME);
String persistentData =
(persistentDataNode == null) ? "" : XMLUtils
.getText(persistentDataNode);
protoContacts.add(new StoredProtoContactDescriptor(contactAddress,
persistentData, protoGroups.get(protoGroupUID)));
}
// remove all duplicates
for (Node node : duplicates)
{
metaContactNode.removeChild(node);
}
return protoContacts;
}
/**
* Creates a node element corresponding to <tt>protoContact</tt>.
*
* @param protoContact the Contact whose element we'd like to create
* @return a XML Element corresponding to <tt>protoContact</tt>.
*/
private Element createProtoContactNode(Contact protoContact)
{
Element protoContactElement =
contactListDocument.createElement(PROTO_CONTACT_NODE_NAME);
// set attributes
protoContactElement.setAttribute(PROTO_CONTACT_ADDRESS_ATTR_NAME,
protoContact.getAddress());
protoContactElement.setAttribute(ACCOUNT_ID_ATTR_NAME, protoContact
.getProtocolProvider().getAccountID().getAccountUniqueID());
if(logger.isTraceEnabled()
&& protoContact.getParentContactGroup() == null)
{
if (logger.isTraceEnabled())
logger.trace("the following contact looks weird:" + protoContact);
if (logger.isTraceEnabled())
logger.trace("group:" + protoContact.getParentContactGroup());
}
protoContactElement.setAttribute(PARENT_PROTO_GROUP_UID_ATTR_NAME,
protoContact.getParentContactGroup().getUID());
// append persistent data child node
String persistentData = protoContact.getPersistentData();
if ((persistentData != null) && (persistentData.length() != 0))
{
Element persDataNode =
contactListDocument.createElement(PERSISTENT_DATA_NODE_NAME);
XMLUtils.setText(persDataNode, persistentData);
protoContactElement.appendChild(persDataNode);
}
return protoContactElement;
}
/**
* Creates a new XML <code>Element</code> corresponding to
* <tt>protoGroup</tt> or <tt>null</tt> if <tt>protoGroup</tt> is not
* eligible for serialization in its current state.
*
* @param protoGroup
* the <code>ContactGroup</code> which a corresponding XML
* <code>Element</code> is to be created for
* @return a new XML <code>Element</code> corresponding to
* <tt>protoGroup</tt> or <tt>null</tt> if <tt>protoGroup</tt> is
* not eligible for serialization in its current state
*/
private Element createProtoContactGroupNode(ContactGroup protoGroup)
{
Element protoGroupElement =
contactListDocument.createElement(PROTO_GROUP_NODE_NAME);
// set attributes
protoGroupElement.setAttribute(UID_ATTR_NAME, protoGroup.getUID());
protoGroupElement
.setAttribute(
ACCOUNT_ID_ATTR_NAME,
protoGroup
.getProtocolProvider().getAccountID().getAccountUniqueID());
/*
* The Javadoc on ContactGroup#getParentContactGroup() states null may
* be returned. Prevent a NullPointerException.
*/
ContactGroup parentContactGroup = protoGroup.getParentContactGroup();
if (parentContactGroup != null)
protoGroupElement.setAttribute(
PARENT_PROTO_GROUP_UID_ATTR_NAME,
parentContactGroup.getUID());
// append persistent data child node
String persistentData = protoGroup.getPersistentData();
if ((persistentData != null) && (persistentData.length() != 0))
{
Element persDataNode =
contactListDocument.createElement(PERSISTENT_DATA_NODE_NAME);
XMLUtils.setText(persDataNode, persistentData);
protoGroupElement.appendChild(persDataNode);
}
return protoGroupElement;
}
/**
* Creates a meta contact node element corresponding to <tt>metaContact</tt>
* .
*
*
* @param metaContact the MetaContact that the new node is about
* @return the XML Element containing the persistent version of
* <tt>metaContact</tt>
*/
private Element createMetaContactNode(MetaContact metaContact)
{
Element metaContactElement =
this.contactListDocument.createElement(META_CONTACT_NODE_NAME);
metaContactElement
.setAttribute(UID_ATTR_NAME, metaContact.getMetaUID());
// create the display name node
Element displayNameNode =
contactListDocument
.createElement(META_CONTACT_DISPLAY_NAME_NODE_NAME);
displayNameNode.appendChild(contactListDocument
.createTextNode(metaContact.getDisplayName()));
if(((MetaContactImpl)metaContact).isDisplayNameUserDefined())
displayNameNode.setAttribute(USER_DEFINED_DISPLAY_NAME_ATTR_NAME,
Boolean.TRUE.toString());
metaContactElement.appendChild(displayNameNode);
Iterator<Contact> contacts = metaContact.getContacts();
while (contacts.hasNext())
{
Contact contact = contacts.next();
Element contactElement = createProtoContactNode(contact);
metaContactElement.appendChild(contactElement);
}
return metaContactElement;
}
/**
* Creates a meta contact group node element corresponding to
* <tt>metaGroup</tt>.
*
* @param metaGroup the MetaContactGroup that the new node is about
* @return the XML Element containing the persistent version of
* <tt>metaGroup</tt>
*/
private Element createMetaContactGroupNode(MetaContactGroup metaGroup)
{
Element metaGroupElement =
this.contactListDocument.createElement(GROUP_NODE_NAME);
metaGroupElement.setAttribute(GROUP_NAME_ATTR_NAME, metaGroup
.getGroupName());
metaGroupElement.setAttribute(UID_ATTR_NAME, metaGroup.getMetaUID());
// create and fill the proto groups node
Element protoGroupsElement =
this.contactListDocument.createElement(PROTO_GROUPS_NODE_NAME);
metaGroupElement.appendChild(protoGroupsElement);
Iterator<ContactGroup> protoGroups = metaGroup.getContactGroups();
while (protoGroups.hasNext())
{
ContactGroup group = protoGroups.next();
// ignore if the proto group is not persistent:
if (!group.isPersistent())
continue;
Element protoGroupEl = createProtoContactGroupNode(group);
protoGroupsElement.appendChild(protoGroupEl);
}
// create and fill the sub groups node
Element subgroupsElement =
this.contactListDocument.createElement(SUBGROUPS_NODE_NAME);
metaGroupElement.appendChild(subgroupsElement);
Iterator<MetaContactGroup> subgroups = metaGroup.getSubgroups();
while (subgroups.hasNext())
{
MetaContactGroup subgroup = subgroups.next();
Element subgroupEl = createMetaContactGroupNode(subgroup);
subgroupsElement.appendChild(subgroupEl);
}
// create and fill child contacts node
Element childContactsElement =
this.contactListDocument.createElement(CHILD_CONTACTS_NODE_NAME);
metaGroupElement.appendChild(childContactsElement);
Iterator<MetaContact> childContacts = metaGroup.getChildContacts();
while (childContacts.hasNext())
{
MetaContact metaContact = childContacts.next();
Element metaContactEl = createMetaContactNode(metaContact);
childContactsElement.appendChild(metaContactEl);
}
return metaGroupElement;
}
/**
* Indicates that a MetaContact has been successfully added to the
* MetaContact list.
*
* @param evt the MetaContactListEvent containing the corresponding contact
*/
public void metaContactAdded(MetaContactEvent evt)
{
Element parentGroupNode =
findMetaContactGroupNode(evt.getParentGroup().getMetaUID());
// not sure what to do in case of null. we'll be logging an internal
// err for now and that's all.
if (parentGroupNode == null)
{
logger.error("Couldn't find parent of a newly added contact: "
+ evt.getSourceMetaContact());
if(logger.isTraceEnabled())
logger.trace("The above exception occurred with the "
+ "following stack trace: ",
new Exception());
return;
}
parentGroupNode =
XMLUtils.findChild(parentGroupNode, CHILD_CONTACTS_NODE_NAME);
Element metaContactElement =
createMetaContactNode(evt.getSourceMetaContact());
parentGroupNode.appendChild(metaContactElement);
try
{
scheduleContactListStorage();
}
catch (IOException ex)
{
/**
* given we're being invoked from an event dispatch thread that was
* probably triggered by a net operation - we could not do much. so
* ... log and @todo one day we'll have a global error dispatcher
*/
logger.error("Writing CL failed after adding contact "
+ evt.getSourceMetaContact(), ex);
}
}
/**
* Creates XML nodes for the source metacontact group, its child meta
* contacts and associated protogroups and adds them to the xml contact
* list.
*
* @param evt the MetaContactListEvent containing the corresponding contact
*/
public void metaContactGroupAdded(MetaContactGroupEvent evt)
{
// if the group was created as an encapsulator of a non persistent proto
// group then we'll ignore it.
if (evt.getSourceProtoGroup() != null
&& !evt.getSourceProtoGroup().isPersistent())
return;
MetaContactGroup parentGroup =
evt.getSourceMetaContactGroup().getParentMetaContactGroup();
Element parentGroupNode =
findMetaContactGroupNode(parentGroup.getMetaUID());
// not sure what to do in case of null. we'll be logging an internal
// err for now and that's all.
if (parentGroupNode == null)
{
logger.error("Couldn't find parent of a newly added group: "
+ parentGroup);
return;
}
Element newGroupElement =
createMetaContactGroupNode(evt.getSourceMetaContactGroup());
Element subgroupsNode =
XMLUtils.findChild(parentGroupNode, SUBGROUPS_NODE_NAME);
subgroupsNode.appendChild(newGroupElement);
try
{
scheduleContactListStorage();
}
catch (IOException ex)
{
/**
* given we're being invoked from an event dispatch thread that was
* probably triggered by a net operation - we could not do much. so
* ... log and @todo one day we'll have a global error dispatcher
*/
logger.error("Writing CL failed after adding contact "
+ evt.getSourceMetaContactGroup(), ex);
}
}
/**
* Removes the corresponding node from the xml document.
*
* @param evt the MetaContactGroupEvent containing the corresponding contact
*/
public void metaContactGroupRemoved(MetaContactGroupEvent evt)
{
Element metaContactGroupNode =
findMetaContactGroupNode(evt.getSourceMetaContactGroup()
.getMetaUID());
// not sure what to do in case of null. we'll be loggin an internal err
// for now and that's all.
if (metaContactGroupNode == null)
{
logger.error("Save after removing an MN group. Groupt not found: "
+ evt.getSourceMetaContactGroup());
return;
}
// remove the meta contact node.
metaContactGroupNode.getParentNode().removeChild(metaContactGroupNode);
try
{
scheduleContactListStorage();
}
catch (IOException ex)
{
/**
* given we're being invoked from an event dispatch thread that was
* probably triggered by a net operation - we could not do much. so
* ... log and @todo one day we'll have a global error dispatcher
*/
logger.error("Writing CL failed after removing group "
+ evt.getSourceMetaContactGroup(), ex);
}
}
/**
* Moves the corresponding node from its old parent to the node
* corresponding to the new parent meta group.
*
* @param evt the MetaContactListEvent containing the corresponding contact
*/
public void metaContactMoved(MetaContactMovedEvent evt)
{
Element metaContactNode =
findMetaContactNode(evt.getSourceMetaContact().getMetaUID());
Element newParentNode =
findMetaContactGroupNode(evt.getNewParent().getMetaUID());
if (newParentNode == null)
{
logger.error("Save after metacontact moved. new parent not found: "
+ evt.getNewParent());
if(logger.isTraceEnabled())
logger.error("The above exception has occurred with the "
+"following stack trace",
new Exception());
return;
}
// in case of null this is a case of moving from non persistent group
// to a persistent one.
if(metaContactNode == null)
{
// create new node
metaContactNode = createMetaContactNode(evt.getSourceMetaContact());
}
else
{
metaContactNode.getParentNode().removeChild(metaContactNode);
}
updateParentsForMetaContactNode(metaContactNode, evt.getNewParent());
Element childContacts =
XMLUtils.findChild(newParentNode, CHILD_CONTACTS_NODE_NAME);
childContacts.appendChild(metaContactNode);
try
{
scheduleContactListStorage();
}
catch (IOException ex)
{
/**
* given we're being invoked from an event dispatch thread that was
* probably triggered by a net operation - we could not do much. so
* ... log and @todo one day we'll have a global error dispatcher
*/
logger.error("Writing CL failed after moving "
+ evt.getSourceMetaContact(), ex);
}
}
/**
* Traverses all contact elements of the metaContactNode argument and
* updates theirs parent proto group uid-s to point to the first contact
* group that is encapsulated by the newParent meta group and that belongs
* to the same account as the contact itself.
*
* @param metaContactNode the meta contact node whose child contacts we're
* to update.
* @param newParent a reference to the <tt>MetaContactGroup</tt> where
* metaContactNode was moved.
*/
private void updateParentsForMetaContactNode(Element metaContactNode,
MetaContactGroup newParent)
{
NodeList children = metaContactNode.getChildNodes();
for (int i = 0; i < children.getLength(); i++)
{
Node currentNode = children.item(i);
if (currentNode.getNodeType() != Node.ELEMENT_NODE
|| !currentNode.getNodeName().equals(PROTO_CONTACT_NODE_NAME))
continue;
Element contactElement = (Element) currentNode;
String attribute =
contactElement.getAttribute(PARENT_PROTO_GROUP_UID_ATTR_NAME);
if (attribute == null || attribute.trim().length() == 0)
continue;
String contactAccountID =
contactElement.getAttribute(ACCOUNT_ID_ATTR_NAME);
// find the first protogroup originating from the same account as
// the one that the current contact belongs to.
Iterator<ContactGroup> possibleParents =
newParent.getContactGroupsForAccountID(contactAccountID);
String newParentUID = possibleParents.next().getUID();
contactElement.setAttribute(PARENT_PROTO_GROUP_UID_ATTR_NAME,
newParentUID);
}
}
/**
* Removes the corresponding node from the xml document.
*
* @param evt the MetaContactListEvent containing the corresponding contact
*/
public void metaContactRemoved(MetaContactEvent evt)
{
Element metaContactNode =
findMetaContactNode(evt.getSourceMetaContact().getMetaUID());
// not sure what to do in case of null. we'll be loggin an internal err
// for now and that's all.
if (metaContactNode == null)
{
logger.error("Save after metacontact removed. Contact not found: "
+ evt.getSourceMetaContact());
return;
}
// remove the meta contact node.
metaContactNode.getParentNode().removeChild(metaContactNode);
try
{
scheduleContactListStorage();
}
catch (IOException ex)
{
/**
* given we're being invoked from an event dispatch thread that was
* probably triggered by a net operation - we could not do much. so
* ... log and @todo one day we'll have a global error dispatcher
*/
logger.error("Writing CL failed after removing "
+ evt.getSourceMetaContact(), ex);
}
}
/**
* Changes the display name attribute of the specified meta contact node.
*
* @param evt the MetaContactListEvent containing the corresponding contact
*/
public void metaContactRenamed(MetaContactRenamedEvent evt)
{
Element metaContactNode =
findMetaContactNode(evt.getSourceMetaContact().getMetaUID());
// not sure what to do in case of null. we'll be loggin an internal err
// for now and that's all.
if (metaContactNode == null)
{
logger.error("Save after renam failed. Contact not found: "
+ evt.getSourceMetaContact());
return;
}
Element displayNameNode =
XMLUtils.findChild(metaContactNode,
META_CONTACT_DISPLAY_NAME_NODE_NAME);
if(((MetaContactImpl)evt.getSourceMetaContact())
.isDisplayNameUserDefined())
{
displayNameNode.setAttribute(USER_DEFINED_DISPLAY_NAME_ATTR_NAME,
Boolean.TRUE.toString());
}
else
{
displayNameNode.removeAttribute(
USER_DEFINED_DISPLAY_NAME_ATTR_NAME);
}
XMLUtils.setText(displayNameNode, evt.getNewDisplayName());
updatePersistentDataForMetaContact(evt.getSourceMetaContact());
try
{
scheduleContactListStorage();
}
catch (IOException ex)
{
/**
* given we're being invoked from an event dispatch thread that was
* probably triggered by a net operation - we could not do much. so
* ... log and @todo one day we'll have a global error dispatcher
*/
logger.error("Writing CL failed after rename of "
+ evt.getSourceMetaContact(), ex);
}
}
/**
* Updates the data stored for the contact that caused this event.
*
* @param evt the MetaContactListEvent containing the corresponding contact
*/
public void protoContactModified(ProtoContactEvent evt)
{
Element metaContactNode =
findMetaContactNode(evt.getParent().getMetaUID());
// not sure what to do in case of null. we'll be logging an internal err
// for now and that's all.
if (metaContactNode == null)
{
logger.error("Save after proto contact modification failed. "
+ "Contact not found: " + evt.getParent());
return;
}
updatePersistentDataForMetaContact(evt.getParent());
// i don't think we could do anything else in addition to updating the
// persistent data.
try
{
scheduleContactListStorage();
}
catch (IOException ex)
{
/**
* given we're being invoked from an event dispatch thread that was
* probably triggered by a net operation - we could not do much. so
* ... log and @todo one day we'll have a global error dispatcher
*/
logger.error(
"Writing CL failed after rename of " + evt.getParent(), ex);
}
}
/**
* Indicates that a MetaContact has been modified.
*
* @param evt the MetaContactModifiedEvent containing the corresponding
* contact
*/
public void metaContactModified(MetaContactModifiedEvent evt)
{
String name = evt.getModificationName();
Element metaContactNode =
findMetaContactNode(evt.getSourceMetaContact().getMetaUID());
// not sure what to do in case of null. we'll be logging an internal err
// for now and that's all.
if (metaContactNode == null)
{
logger.error("Save after rename failed. Contact not found: "
+ evt.getSourceMetaContact());
return;
}
Object oldValue = evt.getOldValue();
Object newValue = evt.getNewValue();
boolean isChanged = false;
if (oldValue == null && newValue != null)
{
// indicates add
if (!(newValue instanceof String))
return;
Element detailElement =
contactListDocument
.createElement(META_CONTACT_DETAIL_NAME_NODE_NAME);
detailElement.setAttribute(DETAIL_NAME_ATTR_NAME, name);
detailElement.setAttribute(DETAIL_VALUE_ATTR_NAME,
(String) newValue);
metaContactNode.appendChild(detailElement);
isChanged = true;
}
else if (oldValue != null && newValue == null)
{
// indicates remove
if (oldValue instanceof List<?>)
{
List<?> valuesToRemove = (List<?>) oldValue;
// indicates removing multiple values at one time
List<Element> nodes =
XMLUtils.locateElements(metaContactNode,
META_CONTACT_DETAIL_NAME_NODE_NAME,
DETAIL_NAME_ATTR_NAME, name);
List<Element> nodesToRemove = new ArrayList<Element>();
for (Element e : nodes)
{
if (valuesToRemove
.contains(e.getAttribute(DETAIL_VALUE_ATTR_NAME)))
{
nodesToRemove.add(e);
}
}
for (Element e : nodesToRemove)
{
metaContactNode.removeChild(e);
}
if (nodesToRemove.size() > 0)
isChanged = true;
}
else if (oldValue instanceof String)
{
// removing one value only
List<Element> nodes =
XMLUtils.locateElements(metaContactNode,
META_CONTACT_DETAIL_NAME_NODE_NAME,
DETAIL_NAME_ATTR_NAME, name);
Element elementToRemove = null;
for (Element e : nodes)
{
if (e.getAttribute(DETAIL_VALUE_ATTR_NAME).equals(oldValue))
{
elementToRemove = e;
break;
}
}
if (elementToRemove == null)
return;
metaContactNode.removeChild(elementToRemove);
isChanged = true;
}
}
else if (oldValue != null && newValue != null)
{
// indicates change
List<Element> nodes =
XMLUtils.locateElements(metaContactNode,
META_CONTACT_DETAIL_NAME_NODE_NAME, DETAIL_NAME_ATTR_NAME,
name);
Element changedElement = null;
for (Element e : nodes)
{
if (e.getAttribute(DETAIL_VALUE_ATTR_NAME).equals(oldValue))
{
changedElement = e;
break;
}
}
if (changedElement == null)
return;
changedElement.setAttribute(DETAIL_VALUE_ATTR_NAME,
(String) newValue);
isChanged = true;
}
if (!isChanged)
return;
try
{
scheduleContactListStorage();
}
catch (IOException ex)
{
/**
* given we're being invoked from an event dispatch thread that was
* probably triggered by a net operation - we could not do much. so
* ... log and @todo one day we'll have a global error dispatcher
*/
logger.error("Writing CL failed after rename of "
+ evt.getSourceMetaContact(), ex);
}
}
/**
* Removes the corresponding node from the xml contact list.
*
* @param evt a reference to the corresponding <tt>ProtoContactEvent</tt>
*/
public void protoContactRemoved(ProtoContactEvent evt)
{
Element oldMcNode =
findMetaContactNode(evt.getOldParent().getMetaUID());
// not sure what to do in case of null. we'll be logging an internal err
// for now and that's all.
if (oldMcNode == null)
{
logger.error("Failed to find meta contact (old parent): "
+ oldMcNode);
return;
}
Element protoNode =
XMLUtils.locateElement(oldMcNode, PROTO_CONTACT_NODE_NAME,
PROTO_CONTACT_ADDRESS_ATTR_NAME, evt.getProtoContact()
.getAddress());
protoNode.getParentNode().removeChild(protoNode);
try
{
scheduleContactListStorage();
}
catch (IOException ex)
{
/**
* given we're being invoked from an event dispatch thread that was
* probably triggered by a net operation - we could not do much. so
* ... log and @todo one day we'll have a global error dispatcher
*/
logger.error("Writing CL failed after removing proto contact "
+ evt.getProtoContact(), ex);
}
}
/**
* We simply ignore - we're not interested in this kind of events.
*
* @param evt the <tt>MetaContactGroupEvent</tt> containing details of this
* event.
*/
public void childContactsReordered(MetaContactGroupEvent evt)
{
// ignore - not interested in such kind of events
}
/**
* Determines the exact type of the change and acts accordingly by either
* updating group name or .
*
* @param evt the MetaContactListEvent containing the corresponding contact
*/
public void metaContactGroupModified(MetaContactGroupEvent evt)
{
MetaContactGroup mcGroup = evt.getSourceMetaContactGroup();
Element mcGroupNode = findMetaContactGroupNode(mcGroup.getMetaUID());
// not sure what to do in case of null. we'll be logging an internal err
// for now and that's all.
if (mcGroupNode == null)
{
logger.error("Failed to find meta contact group: " + mcGroup);
if (logger.isTraceEnabled())
logger.trace(
"The above error occurred with the following stack trace: ",
new Exception());
return;
}
switch (evt.getEventID())
{
case MetaContactGroupEvent.CONTACT_GROUP_RENAMED_IN_META_GROUP:
case MetaContactGroupEvent.CONTACT_GROUP_REMOVED_FROM_META_GROUP:
case MetaContactGroupEvent.CONTACT_GROUP_ADDED_TO_META_GROUP:
// the fact that a contact group was added or removed to a
// meta group may imply substantial changes in the child contacts
// and the layout of any possible subgroups, so
// to make things simple, we'll remove the existing meta contact
// group node and re-create it according to its current state.
Node parentNode = mcGroupNode.getParentNode();
parentNode.removeChild(mcGroupNode);
Element newGroupElement = createMetaContactGroupNode(mcGroup);
parentNode.appendChild(newGroupElement);
try
{
scheduleContactListStorage();
}
catch (IOException ex)
{
/**
* given we're being invoked from an event dispatch thread that
* was probably triggered by a net operation - we could not do
* much. so ... log and @todo one day we'll have a global error
* dispatcher
*/
logger.error(
"Writing CL failed after adding contact " + mcGroup,
ex);
}
break;
case MetaContactGroupEvent.META_CONTACT_GROUP_RENAMED:
mcGroupNode
.setAttribute(GROUP_NAME_ATTR_NAME, mcGroup.getGroupName());
break;
}
try
{
scheduleContactListStorage();
}
catch (IOException ex)
{
/**
* given we're being invoked from an event dispatch thread that was
* probably triggered by a net operation - we could not do much. so
* ... log and @todo one day we'll have a global error dispatcher
*/
logger.error(
"Writing CL failed after removing proto group "
+ mcGroup.getGroupName(),
ex);
}
}
/**
* Indicates that a protocol specific <tt>Contact</tt> instance has been
* added to the list of protocol specific buddies in this
* <tt>MetaContact</tt>
*
* @param evt a reference to the corresponding <tt>ProtoContactEvent</tt>
*/
public void protoContactAdded(ProtoContactEvent evt)
{
Element mcNode = findMetaContactNode(evt.getParent().getMetaUID());
// not sure what to do in case of null. we'll be logging an internal err
// for now and that's all.
if (mcNode == null)
{
logger.error("Failed to find meta contact: " + evt.getParent());
return;
}
Element protoNode = createProtoContactNode(evt.getProtoContact());
mcNode.appendChild(protoNode);
try
{
scheduleContactListStorage();
}
catch (IOException ex)
{
/**
* given we're being invoked from an event dispatch thread that was
* probably triggered by a net operation - we could not do much. so
* ... log and @todo one day we'll have a global error dispatcher
*/
logger.error("Writing CL failed after adding proto contact "
+ evt.getProtoContact(), ex);
}
}
/**
* Indicates that a protocol specific <tt>Contact</tt> instance has been
* moved from within one <tt>MetaContact</tt> to another.
*
* @param evt a reference to the <tt>ProtoContactMovedEvent</tt> instance.
*/
public void protoContactMoved(ProtoContactEvent evt)
{
Element newMcNode =
findMetaContactNode(evt.getNewParent().getMetaUID());
Element oldMcNode =
findMetaContactNode(evt.getOldParent().getMetaUID());
// not sure what to do in case of null. we'll be logging an internal err
// for now and that's all.
if (oldMcNode == null)
{
logger.error("Failed to find meta contact (old parent): "
+ oldMcNode);
return;
}
if (newMcNode == null)
{
logger.error("Failed to find meta contact (old parent): "
+ newMcNode);
return;
}
Element protoNode =
XMLUtils.locateElement(oldMcNode, PROTO_CONTACT_NODE_NAME,
PROTO_CONTACT_ADDRESS_ATTR_NAME, evt.getProtoContact()
.getAddress());
protoNode.getParentNode().removeChild(protoNode);
// update parent attr and append the contact to its new parent node.
protoNode.setAttribute(PARENT_PROTO_GROUP_UID_ATTR_NAME, evt
.getProtoContact().getParentContactGroup().getUID());
newMcNode.appendChild(protoNode);
try
{
scheduleContactListStorage();
}
catch (IOException ex)
{
/**
* given we're being invoked from an event dispatch thread that was
* probably triggered by a net operation - we could not do much. so
* ... log and @todo one day we'll have a global error dispatcher
*/
logger.error("Writing CL failed after moving proto contact "
+ evt.getProtoContact(), ex);
}
}
/**
* Returns the node corresponding to the meta contact with the specified uid
* or null if no such node was found.
*
* @param metaContactUID the UID String of the meta contact whose node we
* are looking for.
* @return the node corresponding to the meta contact with the specified UID
* or null if no such contact was found in the meta contact list
* file.
*/
private Element findMetaContactNode(String metaContactUID)
{
Element root = (Element) contactListDocument.getFirstChild();
return XMLUtils.locateElement(root, META_CONTACT_NODE_NAME,
UID_ATTR_NAME, metaContactUID);
}
/**
* Returns the node corresponding to the meta contact with the specified uid
* or null if no such node was found.
*
* @param metaContactGroupUID the UID String of the meta contact whose node
* we are looking for.
* @return the node corresponding to the meta contact group with the
* specified UID or null if no such group was found in the meta
* contact list file.
*/
private Element findMetaContactGroupNode(String metaContactGroupUID)
{
Element root = (Element) contactListDocument.getFirstChild();
return XMLUtils.locateElement(root, GROUP_NODE_NAME, UID_ATTR_NAME,
metaContactGroupUID);
}
/**
* Removes the file where we store contact lists.
*/
void removeContactListFile()
{
this.contactlistFile.delete();
}
/**
* Contains details parsed out of the contact list xml file, necessary for
* creating unresolved contacts.
*/
static class StoredProtoContactDescriptor
{
String contactAddress = null;
String persistentData = null;
ContactGroup parentProtoGroup = null;
StoredProtoContactDescriptor(String contactAddress,
String persistentData, ContactGroup parentProtoGroup)
{
this.contactAddress = contactAddress;
this.persistentData = persistentData;
this.parentProtoGroup = parentProtoGroup;
}
/**
* Returns a string representation of the descriptor.
*
* @return a string representation of the descriptor.
*/
@Override
public String toString()
{
return "StoredProtocoContactDescriptor[ "
+ " contactAddress="
+ contactAddress
+ " persistenData="
+ persistentData
+ " parentProtoGroup="
+ ((parentProtoGroup == null) ? "" : parentProtoGroup
.getGroupName()) + "]";
}
/**
* Utility method that allows us to verify whether a ContactDescriptor
* corresponding to a particular contact is already in a descriptor list
* and thus eliminate duplicates.
*
* @param contactAddress the address of the contact whose descriptor we
* are looking for.
* @param list the <tt>List</tt> of
* <tt>StoredProtoContactDescriptor</tt> that we are supposed
* to search for <tt>contactAddress</tt>
* @return a <tt>StoredProtoContactDescriptor</tt> corresponding to
* <tt>contactAddress</tt> or <tt>null</tt> if no such
* descriptor exists.
*/
private static StoredProtoContactDescriptor findContactInList(
String contactAddress, List<StoredProtoContactDescriptor> list)
{
if (list != null && list.size() > 0)
{
for (StoredProtoContactDescriptor desc : list)
{
if (desc.contactAddress.equals(contactAddress))
return desc;
}
}
return null;
}
}
/**
* Indicates that a new avatar is available for a <tt>MetaContact</tt>.
* @param evt the <tt>MetaContactAvatarUpdateEvent</tt> containing details
* of this event
*/
public void metaContactAvatarUpdated(MetaContactAvatarUpdateEvent evt)
{
// TODO Store MetaContact avatar.
}
}
|
package net.java.sip.communicator.service.gui;
import java.lang.ref.*;
import java.util.*;
/**
* The <tt>PluginComponentFactory</tt> is the factory that will be used by the
* <tt>PluginComponents</tt> to register in OSGI bundle context and will be
* used by containers of the plugins to create Plugin component instances.
*
* @author Damian Minkov
*/
public abstract class PluginComponentFactory
{
/**
* The container id for this plugin.
*/
private Container container;
/**
* Any special constraints if needed for placing the plugin instances.
*/
private String constraints;
/**
* The position of the plugin, where to be added.
*/
private int position;
/**
* Is it a native component.
*/
private boolean nativeComponent;
/**
* Weak hash map holding plugins if the parent (container) is garbage
* collected free and the plugin instance that corresponds it.
*/
private WeakHashMap<Object,WeakReference<PluginComponent>> pluginInstances =
new WeakHashMap<Object, WeakReference<PluginComponent>>();
/**
* Creates a default factory for a <tt>container</tt>.
* @param container the container id for the plugins to be created.
*/
public PluginComponentFactory(Container container)
{
this(container, null, -1, false);
}
/**
* Creates factory.
* @param container the container id
* @param constraints the constraints
* @param position a position for the plugin component.
* @param nativeComponent is it native one.
*/
public PluginComponentFactory(Container container,
String constraints,
int position,
boolean nativeComponent)
{
this.container = container;
this.constraints = constraints;
this.position = position;
this.nativeComponent = nativeComponent;
}
/**
* Returns the identifier of the container, where we would like to add
* our control. All possible container identifiers are defined in the
* <tt>Container</tt> class. If the <tt>Container</tt> returned by this
* method is not supported by the current UI implementation the plugin won't
* be added.
*
* @return the container, where we would like to add our control.
*/
public Container getContainer()
{
return container;
}
/**
* Returns the constraints, which will indicate to the container, where this
* component should be added. All constraints are defined in the Container
* class and are as follows: START, END, TOP, BOTTOM, LEFT, RIGHT.
*
* @return the constraints, which will indicate to the container, where this
* component should be added.
*/
public String getConstraints()
{
return constraints;
}
/**
* Returns the index position of this component in the container, where it
* will be added. An index of 0 would mean that this component should be
* added before all other components. An index of -1 would mean that the
* position of this component is not important.
* @return the index position of this component in the container, where it
* will be added.
*/
public int getPositionIndex()
{
return position;
}
/**
* Returns <code>true</code> to indicate that this component is a native
* component and <code>false</code> otherwise. This method is meant to be
* used by containers if a special treatment is needed for native components.
*
* @return <code>true</code> to indicate that this component is a native
* component and <code>false</code> otherwise.
*/
public boolean isNativeComponent()
{
return nativeComponent;
}
/**
* Returns the component that should be added. This method should return a
* valid AWT, SWT or Swing object in order to appear properly in the user
* interface.
* @param parent the parent that will contain this plugin
*
* @return the component that should be added.
*/
@SuppressWarnings("unchecked")
public PluginComponent getPluginComponentInstance(Object parent)
{
WeakReference<PluginComponent> p = pluginInstances.get(parent);
if(p == null)
{
p = new WeakReference(getPluginInstance());
pluginInstances.put(parent, p);
}
return p.get();
}
/**
* Implementers use it to create plugin component instances.
* @return the plugin component instance.
*/
abstract protected PluginComponent getPluginInstance();
}
|
package net.yeputons.ofeed.web.dmanager;
import android.support.annotation.NonNull;
import android.util.Log;
import net.yeputons.ofeed.web.DownloadCompleteListener;
import net.yeputons.ofeed.web.ResourceDownload;
import net.yeputons.ofeed.web.ResourceToFileDownloader;
import net.yeputons.ofeed.web.WebResource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolResourceDownloader extends ResourceToFileDownloader {
private static final String TAG = ThreadPoolResourceDownloader.class.getName();
private final ExecutorService executor = Executors.newCachedThreadPool();
@NonNull
@Override
public ResourceDownload createDownload(@NonNull WebResource resource) {
URI uri = resource.uri;
File destination = getFileForUri(uri);
return new AtResourceDownload(uri, destination);
}
public void shutdown() {
executor.shutdown();
}
private class AtResourceDownload implements ResourceDownload, Runnable {
private final URI uri;
private final File destination;
private State state;
private final List<DownloadCompleteListener> listeners = new ArrayList<>();
private boolean taskStarted = false;
@Override
public void run() {
HttpURLConnection urlConnection;
try {
Log.d(TAG, String.format("Download '%s' to '%s'", uri, destination));
setState(State.IN_PROGRESS);
urlConnection = (HttpURLConnection) uri.toURL().openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
int responseCode = urlConnection.getResponseCode();
if (!(200 <= responseCode && responseCode <= 299)) { // Not an HTTP success code
Log.w(TAG, "Strange response code during download: " + responseCode
+ " " + urlConnection.getResponseMessage());
}
InputStream input = urlConnection.getInputStream();
destination.getParentFile().mkdirs();
FileOutputStream output = new FileOutputStream(destination);
byte[] buffer = new byte[4 * 1024];
int bufferLength = 0;
while ((bufferLength = input.read(buffer)) > 0) {
output.write(buffer, 0, bufferLength);
}
output.close();
Log.d(TAG, "Download completed");
setState(State.COMPLETED);
input.close();
urlConnection.disconnect();
} catch (IOException e) {
Log.w(TAG, "Download failed", e);
setState(State.FAILED);
}
}
private AtResourceDownload(URI uri, File destination) {
this.uri = uri;
this.destination = destination;
}
@Override
public synchronized void addDownloadCompleteListener(DownloadCompleteListener listener) {
listeners.add(listener);
}
@NonNull
@Override
public synchronized State getState() {
return state;
}
@NonNull
@Override
public File getLocalFile() {
return destination;
}
private synchronized void setState(State state) {
this.state = state;
if (this.state == State.COMPLETED || this.state == State.FAILED) {
for (DownloadCompleteListener l : listeners) {
l.onDownloadComplete();
}
listeners.clear();
}
}
@Override
public synchronized void start() {
if (taskStarted) {
throw new IllegalStateException("Download was already started");
}
taskStarted = true;
executor.submit(this);
}
}
}
|
/*
* @author <a href="mailto:novotny@aei.mpg.de">Jason Novotny</a>
* @version $Id$
*/
package org.gridlab.gridsphere.portlets.core.file;
import org.gridlab.gridsphere.portlet.*;
import org.gridlab.gridsphere.portlet.service.PortletServiceException;
import org.gridlab.gridsphere.provider.event.FormEvent;
import org.gridlab.gridsphere.provider.portlet.ActionPortlet;
import org.gridlab.gridsphere.provider.portletui.beans.*;
import org.gridlab.gridsphere.services.core.file.FileManagerService;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.servlet.UnavailableException;
import java.io.*;
import java.util.Iterator;
import java.util.List;
public class FileManagerPortlet extends ActionPortlet {
private FileManagerService userStorage = null;
public void init(PortletConfig config) throws UnavailableException {
super.init(config);
try {
userStorage = (FileManagerService)config.getContext().getService(FileManagerService.class);
} catch (PortletServiceException e) {
log.error("Unable to initialize FileManagerService", e);
}
DEFAULT_VIEW_PAGE = "doViewUserFiles";
}
public void initConcrete(PortletSettings settings) throws UnavailableException {
super.initConcrete(settings);
}
public void doViewUserFiles(FormEvent event) throws PortletException {
log.debug("in FileManagerPortlet: doViewUser");
PortletRequest request = event.getPortletRequest();
User user = request.getUser();
ListBoxBean lb = event.getListBoxBean("filelist");
lb.clear();
String[] list = userStorage.getUserFileList(user);
// set the list box size to number of files plus padding
if (list == null) {
ListBoxItemBean item = new ListBoxItemBean();
item.setValue("empty directory");
item.setDisabled(true);
lb.setSize(4);
lb.addBean(item);
} else {
lb.setSize(list.length + 3);
for (int i = 0; i < list.length; i++) {
ListBoxItemBean item = new ListBoxItemBean();
item.setValue(list[i]);
lb.addBean(item);
}
}
setNextState(request, "filemanager/view.jsp");
}
public void uploadFile(FormEvent event) throws PortletException {
log.debug("in FileManagerPortlet: doUploadFile");
try {
FileInputBean fi = event.getFileInputBean("userfile");
User user = event.getPortletRequest().getUser();
File f = fi.getFile();
if (f == null) return;
String fileName = fi.getFileName();
if (fileName.equals("")) return;
userStorage.storeFile(user, f, fileName);
//String location = userStorage.getLocationPath(user, "myfile");
//log.debug("fileinputbean value=" + fi.getValue() + " location to store=" + location);
//fi.saveFile(location);
} catch (IOException e) {
log.error("Unable to store uploaded file " + e.getMessage());
}
setNextState(event.getPortletRequest(), DEFAULT_VIEW_PAGE);
}
public void deleteFile(FormEvent event) throws PortletException {
log.debug("in FileManagerPortlet: deleteFile");
// Files can be deleted from edit or view pages
// In view page the file is in a listbox
ListBoxBean lb = event.getListBoxBean("filelist");
List files = lb.getSelectedValues();
User user = event.getPortletRequest().getUser();
Iterator it = files.iterator();
String fname = null;
while (it.hasNext()) {
fname = (String)it.next();
userStorage.deleteFile(user, fname);
}
// In edit page the file is in a hidden field
HiddenFieldBean hf = event.getHiddenFieldBean("fileName");
fname = hf.getValue();
if (fname != null) userStorage.deleteFile(user, fname);
}
public void cancelEdit(FormEvent event) throws PortletException {
log.debug("in FileManagerPortlet: cancelEdit");
setNextState(event.getPortletRequest(), DEFAULT_VIEW_PAGE);
}
public void saveFile(FormEvent event) throws PortletException {
log.debug("in FileManagerPortlet: saveFile");
User user = event.getPortletRequest().getUser();
PortletRequest req = event.getPortletRequest();
//String fname = event.getPortletAction().getParameter("fileName");
HiddenFieldBean hf = event.getHiddenFieldBean("fileName");
String fileName = hf.getValue();
TextAreaBean ta = event.getTextAreaBean("fileTextArea");
String newText = ta.getValue();
try {
File tmpFile = userStorage.getFile(user, fileName);
FileWriter f = new FileWriter(tmpFile);
f.write(newText);
f.close();
//userStorage.storeFile(user, tmpFile, fname);
//tmpFile.delete();
} catch (IOException e) {
log.error("Error saving file:" + fileName, e);
FrameBean error = event.getFrameBean("editError");
error.setValue("Unable to save file: " + fileName);
}
}
public void downloadFile(FormEvent event) throws PortletException {
log.debug("in FileManagerPortlet: downloadFile");
ListBoxBean lb = event.getListBoxBean("filelist");
List files = lb.getSelectedValues();
PortletRequest req = event.getPortletRequest();
User user = req.getUser();
Iterator it = files.iterator();
String fileName = null;
while (it.hasNext()) {
fileName = (String)it.next();
}
String path = userStorage.getLocationPath(user, fileName);
setFileDownloadEvent(req, fileName, path);
}
public void editFile(FormEvent event) throws PortletException {
log.debug("in FileManagerPortlet: viewFile");
ListBoxBean lb = event.getListBoxBean("filelist");
PortletRequest req = event.getPortletRequest();
User user = req.getUser();
if (lb.hasSelectedValue()) {
String file = lb.getSelectedValue();
try {
req.setAttribute("fileName", file);
TextBean textBean = event.getTextBean("msg");
textBean.setValue("Displaying file: " + file);
TextAreaBean fileTextArea = event.getTextAreaBean("fileTextArea");
HiddenFieldBean hidden = event.getHiddenFieldBean("fileName");
hidden.setValue(file);
File editFile = userStorage.getFile(user, file);
BufferedReader reader = new BufferedReader(new FileReader(editFile));
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
fileTextArea.setValue(sb.toString());
setNextState(req, "filemanager/edit.jsp");
} catch (FileNotFoundException e) {
log.error("Error opening file:" + file, e);
FrameBean error = event.getFrameBean("errorFrame");
error.setValue("Unable to open file: " + file);
error.setStyle(FrameBean.ERROR_TYPE);
setNextState(req, DEFAULT_VIEW_PAGE);
} catch (IOException e) {
log.error("Error opening file:" + file, e);
FrameBean error = event.getFrameBean("errorFrame");
error.setStyle(FrameBean.ERROR_TYPE);
error.setValue("Unable to open file: " + file);
setNextState(req, DEFAULT_VIEW_PAGE);
}
}
}
}
|
package org.jitsi.impl.neomedia.transform.dtls;
import java.io.*;
import java.security.*;
import org.bouncycastle.crypto.tls.*;
import org.ice4j.ice.*;
import org.jitsi.impl.neomedia.*;
import org.jitsi.impl.neomedia.transform.*;
import org.jitsi.impl.neomedia.transform.srtp.*;
import org.jitsi.service.neomedia.*;
import org.jitsi.util.*;
/**
* Implements {@link PacketTransformer} for DTLS-SRTP. It's capable of working
* in pure DTLS mode if appropriate flag was set in <tt>DtlsControlImpl</tt>.
*
* @author Lyubomir Marinov
*/
public class DtlsPacketTransformer
extends SinglePacketTransformer
{
/**
* The maximum number of times that
* {@link #runInConnectThread(DTLSProtocol, TlsPeer, DatagramTransport)} is
* to retry the invocations of
* {@link DTLSClientProtocol#connect(TlsClient, DatagramTransport)} and
* {@link DTLSServerProtocol#accept(TlsServer, DatagramTransport)} in
* anticipation of a successful connection.
*/
private static final int CONNECT_TRIES = 3;
private static final long CONNECT_RETRY_INTERVAL = 500;
/**
* The length of the header of a DTLS record.
*/
static final int DTLS_RECORD_HEADER_LENGTH = 13;
/**
* The number of milliseconds a <tt>DtlsPacketTransform</tt> is to wait on
* its {@link #dtlsTransport} in order to receive a packet.
*/
private static final int DTLS_TRANSPORT_RECEIVE_WAITMILLIS = -1;
/**
* The <tt>Logger</tt> used by the <tt>DtlsPacketTransformer</tt> class and
* its instances to print debug information.
*/
private static final Logger logger
= Logger.getLogger(DtlsPacketTransformer.class);
/**
* Determines whether a specific array of <tt>byte</tt>s appears to contain
* a DTLS record.
*
* @param buf the array of <tt>byte</tt>s to be analyzed
* @param off the offset within <tt>buf</tt> at which the analysis is to
* start
* @param len the number of bytes within <tt>buf</tt> starting at
* <tt>off</tt> to be analyzed
* @return <tt>true</tt> if the specified <tt>buf</tt> appears to contain a
* DTLS record
*/
public static boolean isDtlsRecord(byte[] buf, int off, int len)
{
boolean b = false;
if (len >= DTLS_RECORD_HEADER_LENGTH)
{
short type = TlsUtils.readUint8(buf, off);
switch (type)
{
case ContentType.alert:
case ContentType.application_data:
case ContentType.change_cipher_spec:
case ContentType.handshake:
int major = buf[off + 1] & 0xff;
int minor = buf[off + 2] & 0xff;
ProtocolVersion version = null;
if ((major == ProtocolVersion.DTLSv10.getMajorVersion())
&& (minor == ProtocolVersion.DTLSv10.getMinorVersion()))
{
version = ProtocolVersion.DTLSv10;
}
if ((version == null)
&& (major == ProtocolVersion.DTLSv12.getMajorVersion())
&& (minor == ProtocolVersion.DTLSv12.getMinorVersion()))
{
version = ProtocolVersion.DTLSv12;
}
if (version != null)
{
int length = TlsUtils.readUint16(buf, off + 11);
if (DTLS_RECORD_HEADER_LENGTH + length <= len)
b = true;
}
break;
default:
/*
* Unless a new ContentType has been defined by the Bouncy
* Castle Crypto APIs, the specified buf does not represent a
* DTLS record.
*/
break;
}
}
return b;
}
/**
* The ID of the component which this instance works for/is associated with.
*/
private final int componentID;
/**
* The background <tt>Thread</tt> which initializes {@link #dtlsTransport}.
*/
private Thread connectThread;
/**
* The <tt>RTPConnector</tt> which uses this <tt>PacketTransformer</tt>.
*/
private AbstractRTPConnector connector;
/**
* The <tt>DatagramTransport</tt> implementation which adapts
* {@link #connector} and this <tt>PacketTransformer</tt> to the terms of
* the Bouncy Castle Crypto APIs.
*/
private DatagramTransportImpl datagramTransport;
/**
* The <tt>DTLSTransport</tt> through which the actual packet
* transformations are being performed by this instance.
*/
private DTLSTransport dtlsTransport;
/**
* The <tt>MediaType</tt> of the stream which this instance works for/is
* associated with.
*/
private MediaType mediaType;
/**
* The <tt>SRTPTransformer</tt> to be used by this instance.
*/
private SinglePacketTransformer srtpTransformer;
/**
* The value of the <tt>setup</tt> SDP attribute defined by RFC 4145
* "TCP-Based Media Transport in the Session Description Protocol
* (SDP)" which determines whether this instance acts as a DTLS client
* or a DTLS server.
*/
private DtlsControl.Setup setup;
/**
* The indicator which determines whether the <tt>TlsPeer</tt> employed by
* this <tt>PacketTransformer</tt> has raised an
* <tt>AlertDescription.close_notify</tt> <tt>AlertLevel.warning</tt> i.e.
* the remote DTLS peer has closed the write side of the connection.
*/
private boolean tlsPeerHasRaisedCloseNotifyWarning;
/**
* The <tt>TransformEngine</tt> which has initialized this instance.
*/
private final DtlsTransformEngine transformEngine;
/**
* Whether rtcp-mux is in use.
*
* If enabled, and this is the transformer for RTCP, it will not establish
* a DTLS session on its own, but rather wait for the RTP transformer to
* do so, and reuse it to initialize the SRTP transformer.
*/
private boolean rtcpmux = false;
/**
* Initializes a new <tt>DtlsPacketTransformer</tt> instance.
*
* @param transformEngine the <tt>TransformEngine</tt> which is initializing
* the new instance
* @param componentID the ID of the component for which the new instance is
* to work
*/
public DtlsPacketTransformer(
DtlsTransformEngine transformEngine,
int componentID)
{
this.transformEngine = transformEngine;
this.componentID = componentID;
}
/**
* {@inheritDoc}
*/
public synchronized void close()
{
/*
* SrtpControl.start(MediaType) starts its associated TransformEngine.
* We will use that mediaType to signal the normal stop then as well
* i.e. we will call setMediaType(null) first.
*/
setMediaType(null);
setConnector(null);
}
/**
* Closes {@link #datagramTransport} if it is non-<tt>null</tt> and logs and
* swallows any <tt>IOException</tt>.
*/
private void closeDatagramTransport()
{
if (datagramTransport != null)
{
try
{
datagramTransport.close();
}
catch (IOException ioe)
{
/*
* DatagramTransportImpl has no reason to fail because it is
* merely an adapter of #connector and this PacketTransformer to
* the terms of the Bouncy Castle Crypto API.
*/
logger.error(
"Failed to (properly) close "
+ datagramTransport.getClass(),
ioe);
}
datagramTransport = null;
}
}
/**
* Determines whether
* {@link #runInConnectThread(DTLSProtocol, TlsPeer, DatagramTransport)} is
* to try to establish a DTLS connection.
*
* @param i the number of tries remaining after the current one
* @param datagramTransport
* @return <tt>true</tt> to try to establish a DTLS connection; otherwise,
* <tt>false</tt>
*/
private boolean enterRunInConnectThreadLoop(
int i,
DatagramTransport datagramTransport)
{
if ((i < 0) || (i > CONNECT_TRIES))
{
return false;
}
else
{
Thread currentThread = Thread.currentThread();
synchronized (this)
{
if ((i > 0) && (i < CONNECT_TRIES - 1))
{
boolean interrupted = false;
try
{
wait(CONNECT_RETRY_INTERVAL);
}
catch (InterruptedException ie)
{
interrupted = true;
}
if (interrupted)
currentThread.interrupt();
}
return
currentThread.equals(this.connectThread)
&& datagramTransport.equals(this.datagramTransport);
}
}
}
/**
* Gets the <tt>DtlsControl</tt> implementation associated with this
* instance.
*
* @return the <tt>DtlsControl</tt> implementation associated with this
* instance
*/
DtlsControlImpl getDtlsControl()
{
return getTransformEngine().getDtlsControl();
}
/**
* Gets the <tt>TransformEngine</tt> which has initialized this instance.
*
* @return the <tt>TransformEngine</tt> which has initialized this instance
*/
DtlsTransformEngine getTransformEngine()
{
return transformEngine;
}
/**
* Handles a specific <tt>IOException</tt> which was thrown during the
* execution of
* {@link #runInConnectThread(DTLSProtocol, TlsPeer, DatagramTransport)}
* while trying to establish a DTLS connection
*
* @param ioe the <tt>IOException</tt> to handle
* @param msg the human-readable message to log about the specified
* <tt>ioe</tt>
* @param i the number of tries remaining after the current one
* @return <tt>true</tt> if the specified <tt>ioe</tt> was successfully
* handled; <tt>false</tt>, otherwise
*/
private boolean handleRunInConnectThreadException(
IOException ioe,
String msg,
int i)
{
/*
* SrtpControl.start(MediaType) starts its associated TransformEngine.
* We will use that mediaType to signal the normal stop then as well
* i.e. we will ignore exception after the procedure to stop this
* PacketTransformer has begun.
*/
if (mediaType == null)
return false;
if (ioe instanceof TlsFatalAlert)
{
TlsFatalAlert tfa = (TlsFatalAlert) ioe;
short alertDescription = tfa.getAlertDescription();
if (alertDescription == AlertDescription.unexpected_message)
{
msg += " Received fatal unexpected message.";
if ((i == 0)
|| !Thread.currentThread().equals(connectThread)
|| (connector == null)
|| (mediaType == null))
{
msg
+= " Giving up after " + (CONNECT_TRIES - i)
+ " retries.";
}
else
{
msg += " Will retry.";
logger.error(msg, ioe);
return true;
}
}
else
{
msg += " Received fatal alert " + alertDescription + ".";
}
}
logger.error(msg, ioe);
return false;
}
/**
* Initializes a new <tt>SRTPTransformer</tt> instance with a specific
* (negotiated) <tt>SRTPProtectionProfile</tt> and the keying material
* specified by a specific <tt>TlsContext</tt>.
*
* @param srtpProtectionProfile the (negotiated)
* <tt>SRTPProtectionProfile</tt> to initialize the new instance with
* @param tlsContext the <tt>TlsContext</tt> which represents the keying
* material
* @return a new <tt>SRTPTransformer</tt> instance initialized with
* <tt>srtpProtectionProfile</tt> and <tt>tlsContext</tt>
*/
private SinglePacketTransformer initializeSRTPTransformer(
int srtpProtectionProfile,
TlsContext tlsContext)
{
boolean rtcp;
switch (componentID)
{
case Component.RTCP:
rtcp = true;
break;
case Component.RTP:
rtcp = false;
break;
default:
throw new IllegalStateException("componentID");
}
int cipher_key_length;
int cipher_salt_length;
int cipher;
int auth_function;
int auth_key_length;
int RTCP_auth_tag_length, RTP_auth_tag_length;
switch (srtpProtectionProfile)
{
case SRTPProtectionProfile.SRTP_AES128_CM_HMAC_SHA1_32:
cipher_key_length = 128 / 8;
cipher_salt_length = 112 / 8;
cipher = SRTPPolicy.AESCM_ENCRYPTION;
auth_function = SRTPPolicy.HMACSHA1_AUTHENTICATION;
auth_key_length = 160 / 8;
RTCP_auth_tag_length = 80 / 8;
RTP_auth_tag_length = 32 / 8;
break;
case SRTPProtectionProfile.SRTP_AES128_CM_HMAC_SHA1_80:
cipher_key_length = 128 / 8;
cipher_salt_length = 112 / 8;
cipher = SRTPPolicy.AESCM_ENCRYPTION;
auth_function = SRTPPolicy.HMACSHA1_AUTHENTICATION;
auth_key_length = 160 / 8;
RTCP_auth_tag_length = RTP_auth_tag_length = 80 / 8;
break;
case SRTPProtectionProfile.SRTP_NULL_HMAC_SHA1_32:
cipher_key_length = 0;
cipher_salt_length = 0;
cipher = SRTPPolicy.NULL_ENCRYPTION;
auth_function = SRTPPolicy.HMACSHA1_AUTHENTICATION;
auth_key_length = 160 / 8;
RTCP_auth_tag_length = 80 / 8;
RTP_auth_tag_length = 32 / 8;
break;
case SRTPProtectionProfile.SRTP_NULL_HMAC_SHA1_80:
cipher_key_length = 0;
cipher_salt_length = 0;
cipher = SRTPPolicy.NULL_ENCRYPTION;
auth_function = SRTPPolicy.HMACSHA1_AUTHENTICATION;
auth_key_length = 160 / 8;
RTCP_auth_tag_length = RTP_auth_tag_length = 80 / 8;
break;
default:
throw new IllegalArgumentException("srtpProtectionProfile");
}
byte[] keyingMaterial
= tlsContext.exportKeyingMaterial(
ExporterLabel.dtls_srtp,
null,
2 * (cipher_key_length + cipher_salt_length));
byte[] client_write_SRTP_master_key = new byte[cipher_key_length];
byte[] server_write_SRTP_master_key = new byte[cipher_key_length];
byte[] client_write_SRTP_master_salt = new byte[cipher_salt_length];
byte[] server_write_SRTP_master_salt = new byte[cipher_salt_length];
byte[][] keyingMaterialValues
= {
client_write_SRTP_master_key,
server_write_SRTP_master_key,
client_write_SRTP_master_salt,
server_write_SRTP_master_salt
};
for (int i = 0, keyingMaterialOffset = 0;
i < keyingMaterialValues.length;
i++)
{
byte[] keyingMaterialValue = keyingMaterialValues[i];
System.arraycopy(
keyingMaterial, keyingMaterialOffset,
keyingMaterialValue, 0,
keyingMaterialValue.length);
keyingMaterialOffset += keyingMaterialValue.length;
}
SRTPPolicy srtcpPolicy
= new SRTPPolicy(
cipher,
cipher_key_length,
auth_function,
auth_key_length,
RTCP_auth_tag_length,
cipher_salt_length);
SRTPPolicy srtpPolicy
= new SRTPPolicy(
cipher,
cipher_key_length,
auth_function,
auth_key_length,
RTP_auth_tag_length,
cipher_salt_length);
SRTPContextFactory clientSRTPContextFactory
= new SRTPContextFactory(
/* sender */ tlsContext instanceof TlsClientContext,
client_write_SRTP_master_key,
client_write_SRTP_master_salt,
srtpPolicy,
srtcpPolicy);
SRTPContextFactory serverSRTPContextFactory
= new SRTPContextFactory(
/* sender */ tlsContext instanceof TlsServerContext,
server_write_SRTP_master_key,
server_write_SRTP_master_salt,
srtpPolicy,
srtcpPolicy);
SRTPContextFactory forwardSRTPContextFactory;
SRTPContextFactory reverseSRTPContextFactory;
if (tlsContext instanceof TlsClientContext)
{
forwardSRTPContextFactory = clientSRTPContextFactory;
reverseSRTPContextFactory = serverSRTPContextFactory;
}
else if (tlsContext instanceof TlsServerContext)
{
forwardSRTPContextFactory = serverSRTPContextFactory;
reverseSRTPContextFactory = clientSRTPContextFactory;
}
else
{
throw new IllegalArgumentException("tlsContext");
}
SinglePacketTransformer srtpTransformer;
if (rtcp)
{
srtpTransformer
= new SRTCPTransformer(
forwardSRTPContextFactory,
reverseSRTPContextFactory);
}
else
{
srtpTransformer
= new SRTPTransformer(
forwardSRTPContextFactory,
reverseSRTPContextFactory);
}
return srtpTransformer;
}
/**
* Notifies this instance that the DTLS record layer associated with a
* specific <tt>TlsPeer</tt> has raised an alert.
*
* @param tlsPeer the <tt>TlsPeer</tt> whose associated DTLS record layer
* has raised an alert
* @param alertLevel {@link AlertLevel}
* @param alertDescription {@link AlertDescription}
* @param message a human-readable message explaining what caused the alert.
* May be <tt>null</tt>.
* @param cause the exception that caused the alert to be raised. May be
* <tt>null</tt>.
*/
void notifyAlertRaised(
TlsPeer tlsPeer,
short alertLevel,
short alertDescription,
String message,
Exception cause)
{
if ((AlertLevel.warning == alertLevel)
&& (AlertDescription.close_notify == alertDescription))
{
tlsPeerHasRaisedCloseNotifyWarning = true;
}
}
/**
* {@inheritDoc}
*/
public RawPacket reverseTransform(RawPacket pkt)
{
byte[] buf = pkt.getBuffer();
int off = pkt.getOffset();
int len = pkt.getLength();
if (isDtlsRecord(buf, off, len))
{
if (rtcpmux && Component.RTCP == componentID)
{
// This should never happen.
logger.warn("Dropping a DTLS record, because it was received"
+ " on the RTCP channel while rtcpmux is in use.");
return null;
}
boolean receive;
synchronized (this)
{
if (datagramTransport == null)
{
receive = false;
}
else
{
datagramTransport.queueReceive(buf, off, len);
receive = true;
}
}
if (receive)
{
DTLSTransport dtlsTransport = this.dtlsTransport;
if (dtlsTransport == null)
{
/*
* The specified pkt looks like a DTLS record and it has
* been consumed for the purposes of the secure channel
* represented by this PacketTransformer.
*/
pkt = null;
}
else
{
try
{
int receiveLimit = dtlsTransport.getReceiveLimit();
int delta = receiveLimit - len;
if (delta > 0)
{
pkt.grow(delta);
buf = pkt.getBuffer();
off = pkt.getOffset();
len = pkt.getLength();
}
else if (delta < 0)
{
pkt.shrink(-delta);
buf = pkt.getBuffer();
off = pkt.getOffset();
len = pkt.getLength();
}
int received
= dtlsTransport.receive(
buf, off, len,
DTLS_TRANSPORT_RECEIVE_WAITMILLIS);
if (received <= 0)
{
// No application data was decoded.
pkt = null;
}
else
{
delta = len - received;
if (delta > 0)
pkt.shrink(delta);
/*
* In DTLS-SRTP no application data is transmitted
* over the DTLS channel.
*/
if (!transformEngine.isSrtpDisabled())
pkt = null;
}
}
catch (IOException ioe)
{
pkt = null;
/*
* SrtpControl.start(MediaType) starts its associated
* TransformEngine. We will use that mediaType to signal
* the normal stop then as well i.e. we will ignore
* exception after the procedure to stop this
* PacketTransformer has begun.
*/
if ((mediaType != null)
&& !tlsPeerHasRaisedCloseNotifyWarning)
{
logger.error(
"Failed to decode a DTLS record!",
ioe);
}
}
}
}
else
{
/*
* The specified pkt looks like a DTLS record but it is
* unexpected in the current state of the secure channel
* represented by this PacketTransformer.
*/
pkt = null;
}
}
else if (transformEngine.isSrtpDisabled())
{
/**
* In pure DTLS mode only DTLS records pass through.
*/
pkt = null;
}
else
{
/*
* XXX If DTLS-SRTP has not been initialized yet or has failed to
* initialize, it is our explicit policy to let the received packet
* pass through and rely on the SrtpListener to notify the user that
* the session is not secured.
*/
SinglePacketTransformer srtpTransformer = this.srtpTransformer;
if (srtpTransformer == null
&& rtcpmux
&& Component.RTCP == componentID)
{
srtpTransformer = initializeSRTCPTransformerFromRtp();
}
if (srtpTransformer != null)
pkt = srtpTransformer.reverseTransform(pkt);
}
return pkt;
}
/**
* Runs in {@link #connectThread} to initialize {@link #dtlsTransport}.
*
* @param dtlsProtocol
* @param tlsPeer
* @param datagramTransport
*/
private void runInConnectThread(
DTLSProtocol dtlsProtocol,
TlsPeer tlsPeer,
DatagramTransport datagramTransport)
{
DTLSTransport dtlsTransport = null;
int srtpProtectionProfile = 0;
TlsContext tlsContext = null;
if (dtlsProtocol instanceof DTLSClientProtocol)
{
DTLSClientProtocol dtlsClientProtocol
= (DTLSClientProtocol) dtlsProtocol;
TlsClientImpl tlsClient = (TlsClientImpl) tlsPeer;
for (int i = CONNECT_TRIES - 1; i >= 0; i
{
if (!enterRunInConnectThreadLoop(i, datagramTransport))
break;
try
{
dtlsTransport
= dtlsClientProtocol.connect(
tlsClient,
datagramTransport);
break;
}
catch (IOException ioe)
{
if (handleRunInConnectThreadException(
ioe,
"Failed to connect this DTLS client to a DTLS"
+ " server!",
i))
{
continue;
}
else
{
break;
}
}
}
if (dtlsTransport != null && !transformEngine.isSrtpDisabled())
{
srtpProtectionProfile = tlsClient.getChosenProtectionProfile();
tlsContext = tlsClient.getContext();
}
}
else if (dtlsProtocol instanceof DTLSServerProtocol)
{
DTLSServerProtocol dtlsServerProtocol
= (DTLSServerProtocol) dtlsProtocol;
TlsServerImpl tlsServer = (TlsServerImpl) tlsPeer;
for (int i = CONNECT_TRIES - 1; i >= 0; i
{
if (!enterRunInConnectThreadLoop(i, datagramTransport))
break;
try
{
dtlsTransport
= dtlsServerProtocol.accept(
tlsServer,
datagramTransport);
break;
}
catch (IOException ioe)
{
if (handleRunInConnectThreadException(
ioe,
"Failed to accept a connection from a DTLS client!",
i))
{
continue;
}
else
{
break;
}
}
}
if (dtlsTransport != null && !transformEngine.isSrtpDisabled())
{
srtpProtectionProfile = tlsServer.getChosenProtectionProfile();
tlsContext = tlsServer.getContext();
}
}
else
throw new IllegalStateException("dtlsProtocol");
SinglePacketTransformer srtpTransformer
= (dtlsTransport == null || transformEngine.isSrtpDisabled())
? null
: initializeSRTPTransformer(srtpProtectionProfile, tlsContext);
boolean closeSRTPTransformer;
synchronized (this)
{
if (Thread.currentThread().equals(this.connectThread)
&& datagramTransport.equals(this.datagramTransport))
{
this.dtlsTransport = dtlsTransport;
this.srtpTransformer = srtpTransformer;
notifyAll();
}
closeSRTPTransformer
= (this.srtpTransformer != srtpTransformer);
}
if (closeSRTPTransformer && (srtpTransformer != null))
srtpTransformer.close();
}
/**
* Sets the <tt>RTPConnector</tt> which is to use or uses this
* <tt>PacketTransformer</tt>.
*
* @param connector the <tt>RTPConnector</tt> which is to use or uses this
* <tt>PacketTransformer</tt>
*/
void setConnector(AbstractRTPConnector connector)
{
if (this.connector != connector)
{
this.connector = connector;
DatagramTransportImpl datagramTransport = this.datagramTransport;
if (datagramTransport != null)
datagramTransport.setConnector(connector);
}
}
/**
* Sets the <tt>MediaType</tt> of the stream which this instance is to work
* for/be associated with.
*
* @param mediaType the <tt>MediaType</tt> of the stream which this instance
* is to work for/be associated with
*/
synchronized void setMediaType(MediaType mediaType)
{
if (this.mediaType != mediaType)
{
MediaType oldValue = this.mediaType;
this.mediaType = mediaType;
if (oldValue != null)
stop();
if (this.mediaType != null)
start();
}
}
/**
* Sets the DTLS protocol according to which this
* <tt>DtlsPacketTransformer</tt> is to act either as a DTLS server or a
* DTLS client.
*
* @param setup the value of the <tt>setup</tt> SDP attribute to set on this
* instance in order to determine whether this instance is to act as a DTLS
* client or a DTLS server
*/
void setSetup(DtlsControl.Setup setup)
{
if (this.setup != setup)
this.setup = setup;
}
/**
* Starts this <tt>PacketTransformer</tt>.
*/
private synchronized void start()
{
if (this.datagramTransport != null)
{
if ((this.connectThread == null) && (dtlsTransport == null))
{
logger.warn(
getClass().getName()
+ " has been started but has failed to establish"
+ " the DTLS connection!");
}
return;
}
if (rtcpmux && Component.RTCP == componentID)
{
/*
* In the case of rtcp-mux, the RTCP transformer does not create
* a DTLS session. The SRTP context (srtpTransformer) will be
* initialized on demand using initializeSRTCPTransformerFromRtp()
*/
return;
}
AbstractRTPConnector connector = this.connector;
if (connector == null)
throw new NullPointerException("connector");
DtlsControl.Setup setup = this.setup;
SecureRandom secureRandom = DtlsControlImpl.createSecureRandom();
final DTLSProtocol dtlsProtocolObj;
final TlsPeer tlsPeer;
if (DtlsControl.Setup.ACTIVE.equals(setup))
{
dtlsProtocolObj = new DTLSClientProtocol(secureRandom);
tlsPeer = new TlsClientImpl(this);
}
else
{
dtlsProtocolObj = new DTLSServerProtocol(secureRandom);
tlsPeer = new TlsServerImpl(this);
}
tlsPeerHasRaisedCloseNotifyWarning = false;
final DatagramTransportImpl datagramTransport
= new DatagramTransportImpl(componentID);
datagramTransport.setConnector(connector);
Thread connectThread
= new Thread()
{
@Override
public void run()
{
try
{
runInConnectThread(
dtlsProtocolObj,
tlsPeer,
datagramTransport);
}
finally
{
if (Thread.currentThread().equals(
DtlsPacketTransformer.this.connectThread))
{
DtlsPacketTransformer.this.connectThread = null;
}
}
}
};
connectThread.setDaemon(true);
connectThread.setName(
DtlsPacketTransformer.class.getName() + ".connectThread");
this.connectThread = connectThread;
this.datagramTransport = datagramTransport;
boolean started = false;
try
{
connectThread.start();
started = true;
}
finally
{
if (!started)
{
if (connectThread.equals(this.connectThread))
this.connectThread = null;
if (datagramTransport.equals(this.datagramTransport))
this.datagramTransport = null;
}
}
notifyAll();
}
/**
* Stops this <tt>PacketTransformer</tt>.
*/
private synchronized void stop()
{
if (connectThread != null)
connectThread = null;
try
{
/*
* The dtlsTransport and srtpTransformer SHOULD be closed, of
* course. The datagramTransport MUST be closed.
*/
if (dtlsTransport != null)
{
try
{
dtlsTransport.close();
}
catch (IOException ioe)
{
logger.error(
"Failed to (properly) close "
+ dtlsTransport.getClass(),
ioe);
}
dtlsTransport = null;
}
if (srtpTransformer != null)
{
srtpTransformer.close();
srtpTransformer = null;
}
}
finally
{
try
{
closeDatagramTransport();
}
finally
{
notifyAll();
}
}
}
/**
* {@inheritDoc}
*/
public RawPacket transform(RawPacket pkt)
{
byte[] buf = pkt.getBuffer();
int off = pkt.getOffset();
int len = pkt.getLength();
/*
* If the specified pkt represents a DTLS record, then it should pass
* through this PacketTransformer (e.g. it has been sent through
* DatagramTransportImpl).
*/
if (isDtlsRecord(buf, off, len))
return pkt;
/* SRTP mode */
if (!transformEngine.isSrtpDisabled())
{
/*
* XXX If DTLS-SRTP has not been initialized yet or has failed to
* initialize, it is our explicit policy to let the received packet
* pass through and rely on the SrtpListener to notify the user that
* the session is not secured.
*/
SinglePacketTransformer srtpTransformer = this.srtpTransformer;
if (srtpTransformer == null
&& rtcpmux
&& Component.RTCP == componentID)
{
srtpTransformer = initializeSRTCPTransformerFromRtp();
}
if (srtpTransformer != null)
pkt = srtpTransformer.transform(pkt);
}
/* Pure DTLS mode */
else
{
/*
* The specified pkt will pass through this PacketTransformer only
* if it gets transformed into a DTLS record.
*/
pkt = null;
DTLSTransport dtlsTransport = this.dtlsTransport;
if (dtlsTransport != null)
{
try
{
dtlsTransport.send(buf, off, len);
}
catch (IOException ioe)
{
/*
* SrtpControl.start(MediaType) starts its associated
* TransformEngine. We will use that mediaType to signal the
* normal stop then as well i.e. we will ignore exception
* after the procedure to stop this PacketTransformer has
* begun.
*/
if ((mediaType != null)
&& !tlsPeerHasRaisedCloseNotifyWarning)
{
logger.error(
"Failed to send application data over DTLS"
+ " transport!",
ioe);
}
}
}
}
return pkt;
}
/**
* Enables/disables rtcp-mux.
* @param rtcpmux whether to enable or disable.
*/
void setRtcpmux(boolean rtcpmux)
{
this.rtcpmux = rtcpmux;
}
/**
* Tries to initialize {@link #srtpTransformer} by using the
* <tt>DtlsPacketTransformer</tt> for RTP.
*
* @return the (possibly updated) value of {@link #srtpTransformer}.
*/
private SinglePacketTransformer initializeSRTCPTransformerFromRtp()
{
if (srtpTransformer != null)
return srtpTransformer; //already initialized
DtlsPacketTransformer rtpDtlsPacketTransformer
= (DtlsPacketTransformer) getTransformEngine().getRTPTransformer();
PacketTransformer rtpSrtpTransformer
= rtpDtlsPacketTransformer.srtpTransformer;
if (rtpSrtpTransformer != null
&& rtpSrtpTransformer instanceof SRTPTransformer)
{
synchronized (this)
{
if (srtpTransformer == null) //previous check was not synchronized
{
DtlsPacketTransformer.this.srtpTransformer
= new SRTCPTransformer(
(SRTPTransformer) rtpSrtpTransformer);
}
return srtpTransformer;
}
}
return srtpTransformer;
}
}
|
package org.pentaho.di.job.entries.dtdvalidator;
import static org.pentaho.di.job.entry.validator.AbstractFileValidator.putVariableSpace;
import static org.pentaho.di.job.entry.validator.AndValidator.putValidators;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.andValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.fileExistsValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notBlankValidator;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.vfs.FileObject;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobEntryType;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entry.JobEntryBase;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.job.entry.validator.ValidatorContext;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.resource.ResourceEntry;
import org.pentaho.di.resource.ResourceReference;
import org.pentaho.di.resource.ResourceEntry.ResourceType;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/**
* This defines a 'dtdvalidator' job entry.
*
* @author Samatar Hassan
* @since 30-04-2007
*
*/
public class JobEntryDTDValidator extends JobEntryBase implements Cloneable, JobEntryInterface
{
private String xmlfilename;
private String dtdfilename;
private boolean dtdintern;
public JobEntryDTDValidator(String n)
{
super(n, "");
xmlfilename=null;
dtdfilename=null;
dtdintern=false;
setID(-1L);
setJobEntryType(JobEntryType.DTD_VALIDATOR);
}
public JobEntryDTDValidator()
{
this("");
}
public JobEntryDTDValidator(JobEntryBase jeb)
{
super(jeb);
}
public Object clone()
{
JobEntryDTDValidator je = (JobEntryDTDValidator)super.clone();
return je;
}
public String getXML()
{
StringBuffer retval = new StringBuffer(50);
retval.append(super.getXML());
retval.append(" ").append(XMLHandler.addTagValue("xmlfilename", xmlfilename));
retval.append(" ").append(XMLHandler.addTagValue("dtdfilename", dtdfilename));
retval.append(" ").append(XMLHandler.addTagValue("dtdintern", dtdintern));
return retval.toString();
}
public void loadXML(Node entrynode, List<DatabaseMeta> databases, Repository rep)
throws KettleXMLException
{
try
{
super.loadXML(entrynode, databases);
xmlfilename = XMLHandler.getTagValue(entrynode, "xmlfilename");
dtdfilename = XMLHandler.getTagValue(entrynode, "dtdfilename");
dtdintern = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "dtdintern"));
}
catch(KettleXMLException xe)
{
throw new KettleXMLException("Unable to load job entry of type 'DTDvalidator' from XML node", xe);
}
}
public void loadRep(Repository rep, long id_jobentry, List<DatabaseMeta> databases)
throws KettleException
{
try
{
super.loadRep(rep, id_jobentry, databases);
xmlfilename = rep.getJobEntryAttributeString(id_jobentry, "xmlfilename");
dtdfilename = rep.getJobEntryAttributeString(id_jobentry, "dtdfilename");
dtdintern=rep.getJobEntryAttributeBoolean(id_jobentry, "dtdintern");
}
catch(KettleException dbe)
{
throw new KettleException("Unable to load job entry of type 'DTDvalidator' from the repository for id_jobentry="+id_jobentry, dbe);
}
}
public void saveRep(Repository rep, long id_job)
throws KettleException
{
try
{
super.saveRep(rep, id_job);
rep.saveJobEntryAttribute(id_job, getID(), "xmlfilename", xmlfilename);
rep.saveJobEntryAttribute(id_job, getID(), "DTDfilename", dtdfilename);
rep.saveJobEntryAttribute(id_job, getID(), "dtdintern", dtdintern);
}
catch(KettleDatabaseException dbe)
{
throw new KettleException("Unable to save job entry of type 'DTDvalidator' to the repository for id_job="+id_job, dbe);
}
}
public String getRealxmlfilename()
{
return environmentSubstitute(xmlfilename);
}
public String getRealDTDfilename()
{
return environmentSubstitute(dtdfilename);
}
public Result execute(Result previousResult, int nr, Repository rep, Job parentJob)
{
LogWriter log = LogWriter.getInstance();
Result result = previousResult;
result.setResult( false );
String realxmlfilename = getRealxmlfilename();
String realDTDfilename = getRealDTDfilename();
FileObject xmlfile = null;
FileObject DTDfile = null;
try
{
if (xmlfilename!=null && ((dtdfilename!=null && !dtdintern) || (dtdintern)) )
{
xmlfile = KettleVFS.getFileObject(realxmlfilename);
if ( xmlfile.exists())
{
//URL xmlFile = new URL (KettleVFS.getFilename(xmlfile));
URL xmlFile = new File(KettleVFS.getFilename(xmlfile)).toURL();
// open XML File
BufferedReader xmlBufferedReader = new BufferedReader(new InputStreamReader(xmlFile.openStream()));
StringBuffer xmlStringbuffer = new StringBuffer("");
char[] buffertXML = new char[1024];
int LenXML = -1;
while ((LenXML = xmlBufferedReader.read(buffertXML)) != -1)
xmlStringbuffer.append(buffertXML, 0,LenXML);
// Prepare parsing ...
DocumentBuilderFactory DocBuilderFactory = DocumentBuilderFactory.newInstance();
Document xmlDocDTD=null;
DocumentBuilder DocBuilder = DocBuilderFactory.newDocumentBuilder();
// Let's try to get XML document encoding
DocBuilderFactory.setValidating(false);
xmlDocDTD = DocBuilder.parse(new ByteArrayInputStream(xmlStringbuffer.toString().getBytes("UTF-8")));
String encoding = null;
if (xmlDocDTD.getXmlEncoding() == null)
{
encoding = "UTF-8";
}
else
{
encoding = xmlDocDTD.getXmlEncoding();
}
int xmlStartDTD = xmlStringbuffer.indexOf("<!DOCTYPE");
if (dtdintern)
{
// DTD find in the XML document
if (xmlStartDTD != -1)
{
log.logBasic(toString(), Messages.getString("JobEntryDTDValidator.ERRORDTDFound.Label", realxmlfilename));
}
else
{
log.logBasic(toString(), Messages.getString("JobEntryDTDValidator.ERRORDTDNotFound.Label", realxmlfilename));
}
}
else
{
// DTD in external document
// If we find an intern declaration, we remove it
DTDfile = KettleVFS.getFileObject(realDTDfilename);
if (DTDfile.exists())
{
if (xmlStartDTD != -1)
{
int EndDTD = xmlStringbuffer.indexOf(">",xmlStartDTD);
//String DocTypeDTD = xmlStringbuffer.substring(xmlStartDTD, EndDTD + 1);
xmlStringbuffer.replace(xmlStartDTD,EndDTD + 1, "");
}
String xmlRootnodeDTD = xmlDocDTD.getDocumentElement().getNodeName();
String RefDTD = "<?xml version='"
+ xmlDocDTD.getXmlVersion() + "' encoding='"
+ encoding + "'?>\n<!DOCTYPE " + xmlRootnodeDTD
+ " SYSTEM '" + KettleVFS.getFilename(DTDfile) + "'>\n";
int xmloffsetDTD = xmlStringbuffer.indexOf("<"+ xmlRootnodeDTD);
xmlStringbuffer.replace(0, xmloffsetDTD,RefDTD);
}
else
{
log.logError(Messages.getString("JobEntryDTDValidator.ERRORDTDFileNotExists.Subject"), Messages.getString("JobEntryDTDValidator.ERRORDTDFileNotExists.Msg",realDTDfilename));
}
}
if ((dtdintern && xmlStartDTD == -1 || (!dtdintern && !DTDfile.exists())))
{
result.setResult( false );
result.setNrErrors(1);
}
else
{
DocBuilderFactory.setValidating(true);
// Let's parse now ...
xmlDocDTD = DocBuilder.parse(new ByteArrayInputStream(xmlStringbuffer.toString().getBytes(encoding)));
log.logBasic(Messages.getString("JobEntryDTDValidator.DTDValidatorOK.Subject"),
Messages.getString("JobEntryDTDValidator.DTDValidatorOK.Label",
realxmlfilename));
// Everything is OK
result.setResult( true );
}
}
else
{
if( !xmlfile.exists())
{
log.logError(toString(), Messages.getString("JobEntryDTDValidator.FileDoesNotExist.Label", realxmlfilename));
}
result.setResult( false );
result.setNrErrors(1);
}
}
else
{
log.logError(toString(), Messages.getString("JobEntryDTDValidator.AllFilesNotNull.Label"));
result.setResult( false );
result.setNrErrors(1);
}
}
catch ( Exception e )
{
log.logError(Messages.getString("JobEntryDTDValidator.ErrorDTDValidator.Subject"),
Messages.getString("JobEntryDTDValidator.ErrorDTDValidator.Label",
realxmlfilename,realDTDfilename,e.getMessage()));
result.setResult( false );
result.setNrErrors(1);
}
finally
{
try
{
if ( xmlfile != null )
xmlfile.close();
if ( DTDfile != null )
DTDfile.close();
}
catch ( IOException e ) { }
}
return result;
}
public boolean evaluates()
{
return true;
}
public void setxmlFilename(String filename)
{
this.xmlfilename = filename;
}
public String getxmlFilename()
{
return xmlfilename;
}
public void setdtdFilename(String filename)
{
this.dtdfilename = filename;
}
public String getdtdFilename()
{
return dtdfilename;
}
public boolean getDTDIntern()
{
return dtdintern;
}
public void setDTDIntern(boolean dtdinternin)
{
this.dtdintern=dtdinternin;
}
public List<ResourceReference> getResourceDependencies(JobMeta jobMeta) {
List<ResourceReference> references = super.getResourceDependencies(jobMeta);
if ( (!Const.isEmpty(dtdfilename)) && (!Const.isEmpty(xmlfilename)) ) {
String realXmlFileName = jobMeta.environmentSubstitute(xmlfilename);
String realXsdFileName = jobMeta.environmentSubstitute(dtdfilename);
ResourceReference reference = new ResourceReference(this);
reference.getEntries().add( new ResourceEntry(realXmlFileName, ResourceType.FILE));
reference.getEntries().add( new ResourceEntry(realXsdFileName, ResourceType.FILE));
references.add(reference);
}
return references;
}
@Override
public void check(List<CheckResultInterface> remarks, JobMeta jobMeta)
{
ValidatorContext ctx = new ValidatorContext();
putVariableSpace(ctx, getVariables());
putValidators(ctx, notBlankValidator(), fileExistsValidator());
andValidator().validate(this, "dtdfilename", remarks, ctx);//$NON-NLS-1$
andValidator().validate(this, "xmlFilename", remarks, ctx);//$NON-NLS-1$
}
}
|
package algorithms.statistics;
import algorithms.misc.Histogram;
import algorithms.misc.HistogramHolder;
import algorithms.misc.MiscMath0;
import algorithms.util.FormatArray;
import algorithms.util.PolygonAndPointPlotter;
import gnu.trove.list.TDoubleList;
import gnu.trove.list.array.TDoubleArrayList;
import junit.framework.TestCase;
import java.util.logging.Logger;
public class GeneralizedExtremeValue2Test extends TestCase {
protected Logger log = Logger.getLogger(this.getClass().getName());
public void testGenerateGumberCurve() throws Exception {
double[] xPoints;
double[] curve;
double sigma, k, mu;
int n = 100;
// TypeI
double xMin = -100;
double xMax = 100;
xPoints = new double[n];
double dx = (xMax - xMin)/n;
xPoints[0] = xMin;
for (int i = 1; i < n; i++) {
xPoints[i] = xPoints[i - 1] + dx;
}
mu = 3.0;
sigma = 7.0;
k = 0.0;
curve = GeneralizedExtremeValue.generateGumbelCurve(xPoints, mu, sigma);
PolygonAndPointPlotter plotter = new PolygonAndPointPlotter((float)xMin, (float)xMax, 0f, 0.5f);
plotter.addPlot(xPoints, curve, null, null, xPoints, curve, "gumbel: loc=" + mu + " scale=" + sigma);
// to generate the input for the estimators, we need to turn
// the pair (xPoints, curve) into an ordered statistic for x,
// that is, x points present in proportion to the curve (pdf).
// TODO: add methods to do this properly, after take a quick rough look.
//(Chap 19 of "Statistical Distributions").
// where right tail begins to flatten
double factor = 338.;
//z=(x-mu)/sigma
TDoubleList x = new TDoubleArrayList();
int yC;
for (int i = 0; i < curve.length; ++i) {
yC = (int) Math.ceil(factor*curve[i]);
for (int j = 0; j < yC; ++j) {
x.add(xPoints[i]);
}
}
double[] xOrd = x.toArray();
double[] params = GeneralizedExtremeValue.gumbelParamsViaMethodOfMoments(xOrd);
log.info(String.format("params=%s\n", FormatArray.toString(params, "%.3f")));
String filePath = plotter.writeFile("gumbel_mu1_sigma_1");
}
}
|
package co.leantechniques.maven.buildtime;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertSame;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.apache.maven.execution.ExecutionEvent;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Plugin;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.project.MavenProject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.slf4j.Logger;
import co.leantechniques.maven.buildtime.output.CsvReporter;
import co.leantechniques.maven.buildtime.output.LogReporter;
@RunWith(MockitoJUnitRunner.class)
public class SessionTimerTest {
private ConcurrentMap<String,ProjectTimer> existingProjects;
private SessionTimer sessionTimer;
private ProjectTimer oneProject;
private ConcurrentMap<String, MojoTimer> mojoTiming;
@Mock
private Logger logger;
@Mock
private ExecutionEvent sessionEndEvent;
@Mock
private MavenSession session;
private CsvReporter csvReporter;
private LogReporter logReporter;
private MojoExecution mojoExecution;
private MavenProject project;
private PrintWriter printWriter;
private ByteArrayOutputStream outputStream;
private Properties userProperties = new Properties();
private Properties systemProperties = new Properties();
@Before
public void setUp() throws Exception {
logReporter = new LogReporter();
csvReporter = new CsvReporter();
existingProjects = new ConcurrentHashMap<String, ProjectTimer>();
SystemClock mockClock = mock(SystemClock.class);
when(mockClock.currentTimeMillis())
.thenReturn(100L)
.thenReturn(200L);
sessionTimer = new SessionTimer(existingProjects, mockClock);
mojoTiming = new ConcurrentHashMap<String, MojoTimer>();
oneProject = new ProjectTimer("one", mojoTiming, mockClock);
mojoExecution = createMojoExecution();
project = createMavenProject();
outputStream = new ByteArrayOutputStream();
printWriter = new PrintWriter(outputStream);
userProperties.setProperty(Constants.BUILDTIME_OUTPUT_LOG_PROPERTY, "true");
when(sessionEndEvent.getSession()).thenReturn(session);
when(session.getSystemProperties()).thenReturn(systemProperties);
when(session.getUserProperties()).thenReturn(userProperties);
when(sessionEndEvent.getType()).thenReturn(ExecutionEvent.Type.SessionEnded);
}
@Test
public void getProjectReturnsNewWhenNotExists(){
ProjectTimer actual = sessionTimer.getProject("not existing");
assertNotNull(actual);
}
@Test
public void getProjectReturnsSameWhenExists() {
existingProjects.put("one", oneProject);
ProjectTimer actual = sessionTimer.getProject("one");
assertSame(oneProject, actual);
}
@Test
public void writeOneProjectWithOnePlugin() {
MojoTimer goal1Timer = new MojoTimer("one", "artifactId:goal1", 1, 2);
MojoTimer goal2Timer = new MojoTimer("one", "artifactId:goal2", 2, 4);
mojoTiming.put(goal1Timer.getName(), goal1Timer);
mojoTiming.put(goal2Timer.getName(), goal2Timer);
existingProjects.put("one", oneProject);
logReporter.performReport(logger, sessionEndEvent, sessionTimer);
String dividerLine = LogReporter.DIVIDER;
InOrder inOrder = inOrder(logger);
inOrder.verify(logger).info(dividerLine);
inOrder.verify(logger).info("Build Time Summary:");
inOrder.verify(logger).info(dividerLine);
inOrder.verify(logger).info("one [0.003s]");
inOrder.verify(logger).info(" artifactId:goal1 ......................................... [0.001s]");
inOrder.verify(logger).info(" artifactId:goal2 ......................................... [0.002s]");
}
@Test
public void testResultsOrderedByStartTime() {
MojoTimer goal1Timer = new MojoTimer("one", "artifactId:goal1", 2, 5);
MojoTimer goal2Timer = new MojoTimer("one", "artifactId:goal2", 1, 3);
mojoTiming.put(goal1Timer.getName(), goal1Timer);
mojoTiming.put(goal2Timer.getName(), goal2Timer);
existingProjects.put("one", oneProject);
logReporter.performReport(logger, sessionEndEvent, sessionTimer);
String dividerLine = LogReporter.DIVIDER;
InOrder inOrder = inOrder(logger);
inOrder.verify(logger).info(dividerLine);
inOrder.verify(logger).info("Build Time Summary:");
inOrder.verify(logger).info(dividerLine);
inOrder.verify(logger).info("one [0.004s]");
inOrder.verify(logger).info(" artifactId:goal2 ......................................... [0.002s]");
inOrder.verify(logger).info(" artifactId:goal1 ......................................... [0.003s]");
}
@Test
public void writeToOneProjectWithOnePlugin() {
MojoTimer goal1Timer = new MojoTimer("one", "artifactId:goal1", 1, 2);
MojoTimer goal2Timer = new MojoTimer("one", "artifactId:goal2", 2, 4);
mojoTiming.put(goal1Timer.getName(), goal1Timer);
mojoTiming.put(goal2Timer.getName(), goal2Timer);
existingProjects.put("one", oneProject);
csvReporter.writeTo(sessionTimer, printWriter);
printWriter.flush();
String output = outputStream.toString();
String[] split = output.split("\r?\n");
Assert.assertEquals(split[0], "\"Module\";\"Mojo\";\"Time\"");
Assert.assertEquals(split[1], "\"one\";\"artifactId:goal1\";\"0.001\"");
Assert.assertEquals(split[2], "\"one\";\"artifactId:goal2\";\"0.002\"");
}
@Test
public void successfulMojoShouldStopTimer(){
sessionTimer.mojoStarted(project, mojoExecution);
sessionTimer.mojoSucceeded(project, mojoExecution);
MojoTimer mojoTimer = sessionTimer.getMojoTimer(project, mojoExecution);
assertEquals(new Long(100), mojoTimer.getDuration());
}
@Test
public void failureMojoShouldStopTimer(){
sessionTimer.mojoStarted(project, mojoExecution);
sessionTimer.mojoFailed(project, mojoExecution);
MojoTimer mojoTimer = sessionTimer.getMojoTimer(project, mojoExecution);
assertEquals(new Long(100), mojoTimer.getDuration());
}
private MojoExecution createMojoExecution() {
Plugin plugin = new Plugin();
plugin.setArtifactId("plugin");
return new MojoExecution(plugin, "goal", "executionId");
}
private MavenProject createMavenProject() {
MavenProject project = new MavenProject();
project.setArtifactId("maven-project-artifact");
return project;
}
}
|
package com.jakewharton.trakt.services;
import com.jakewharton.trakt.BaseTestCase;
import com.jakewharton.trakt.entities.Activity;
import static org.fest.assertions.api.Assertions.assertThat;
public class ActivityServiceTest extends BaseTestCase {
public void test_community() {
Activity activity = getManager().activityService().community();
assertThat(activity).isNotNull();
//TODO
}
// public void test_episodes() {
// Activity activity = getManager().activityService().episodes("the-walking-dead", 2, 1).fire();
// assertNotNull("Result was null.", activity);
// //TODO
// public void test_friends() {
// Activity activity = getManager().activityService().friends().fire();
// assertNotNull("Result was null.", activity);
// //TODO
// public void test_movies() {
// Activity activity = getManager().activityService().movies("the-matrix-1999","cloud-atlas-2012").fire();
// assertNotNull("Result was null.", activity);
// //TODO
// public void test_seasons() {
// Activity activity = getManager().activityService().seasons("dexter", 6).fire();
// assertNotNull("Result was null.", activity);
// //TODO
// public void test_shows() {
// Activity activity = getManager().activityService().shows("battlestar-galactica-2003", "caprica").fire();
// assertNotNull("Result was null.", activity);
// //TODO
public void test_user() {
Activity activity = getManager().activityService().user("JakeWharton");
assertThat(activity).isNotNull();
activity = getManager().activityService()
.user("JakeWharton", "all", "checkin,seen", null, null);
assertThat(activity).isNotNull();
activity = getManager().activityService()
.user("JakeWharton", "all", "checkin,seen", 1, 1);
assertThat(activity).isNotNull();
}
}
|
package com.jos.dem.vetlog.service;
import com.jos.dem.vetlog.model.RegistrationCode;
import com.jos.dem.vetlog.repository.RegistrationCodeRepository;
import com.jos.dem.vetlog.service.impl.RegistrationServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@Slf4j
class RegistrationServiceTest {
private static final String TOKEN = "token";
private static final String EMAIL = "contact@josdem.io";
private RegistrationService service;
@Mock
private LocaleService localeService;
@Mock
private RegistrationCodeRepository repository;
@BeforeEach
void setup() {
MockitoAnnotations.openMocks(this);
service = new RegistrationServiceImpl(localeService, repository);
}
@Test
@DisplayName("getting user by token")
void shouldGetUserByToken(TestInfo testInfo) {
log.info("Running: {}", testInfo.getDisplayName());
RegistrationCode registrationCode = new RegistrationCode();
registrationCode.setEmail(EMAIL);
when(repository.findByToken(TOKEN)).thenReturn(registrationCode);
assertEquals(EMAIL, service.findEmailByToken(TOKEN));
}
@Test
@DisplayName("generating token")
void shouldGenerateToken(TestInfo testInfo) {
log.info("Running: {}", testInfo.getDisplayName());
String token = service.generateToken(EMAIL);
assertEquals(36, token.length());
verify(repository).save(isA(RegistrationCode.class));
}
}
|
package com.microsoft.rest;
import com.microsoft.rest.bat.AutoRestIntegerTestService;
import com.microsoft.rest.bat.AutoRestIntegerTestServiceImpl;
import junit.framework.Assert;
import org.junit.Test;
import retrofit.client.Response;
public class AutoRestIntegerTestServiceTests {
@Test
public void GetMaxInt() throws Exception {
AutoRestIntegerTestService client = new AutoRestIntegerTestServiceImpl();
try {
Response response = client.getIntOperations().putMax32(Integer.MAX_VALUE);
Assert.assertEquals(200, response.getStatus());
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
}
|
package de.fernunihagen.dna.jkn.scalephant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import junit.framework.Assert;
import org.junit.Test;
import de.fernunihagen.dna.jkn.scalephant.storage.entity.BoundingBox;
public class TestBoundingBox {
/**
* Create some invalid bounding boxes
*/
@Test
public void testBoundingBoxCreateInvalid() {
final BoundingBox bb1 = new BoundingBox(1f, 2f, 3f, 4f, 5f);
Assert.assertFalse(bb1.isValid());
// Dimension 1 error
final BoundingBox bb2 = new BoundingBox(2f, -2f, 3f, 4f);
Assert.assertFalse(bb2.isValid());
// Dimension 2 error
final BoundingBox bb3 = new BoundingBox(1f, 2f, 3f, -4f);
Assert.assertFalse(bb3.isValid());
}
/**
* Create some valid bounding boxes
*/
@Test
public void testBoundingBoxCreateValid() {
final BoundingBox bb1 = new BoundingBox(1f, 10f);
Assert.assertTrue(bb1.isValid());
final BoundingBox bb2 = new BoundingBox(-10f, 10f);
Assert.assertTrue(bb2.isValid());
final BoundingBox bb3 = new BoundingBox(1f, 20f, -50f, 50f);
Assert.assertTrue(bb3.isValid());
final BoundingBox bb4 = new BoundingBox(1f, 20f, -50f, 50f, -100f, 10f);
Assert.assertTrue(bb4.isValid());
}
/**
* Test the getter and the setter for the dimension data
*/
@Test
public void testGetValues() {
final BoundingBox bb1 = new BoundingBox(1f, 10f);
Assert.assertEquals(1f, bb1.getCoordinateLow(0));
Assert.assertEquals(10f, bb1.getExtent(0));
final BoundingBox bb2 = new BoundingBox(1f, 20f, -50f, 50f, -100f, 10f);
Assert.assertEquals(1f, bb2.getCoordinateLow(0));
Assert.assertEquals(20f, bb2.getExtent(0));
Assert.assertEquals(-50f, bb2.getCoordinateLow(1));
Assert.assertEquals(50f, bb2.getExtent(1));
Assert.assertEquals(-100f, bb2.getCoordinateLow(2));
Assert.assertEquals(10f, bb2.getExtent(2));
}
/**
* Test the calculation of low and high values
*/
@Test
public void testLowHigh() {
final BoundingBox bb1 = new BoundingBox(1f, 10f);
Assert.assertEquals(1f, bb1.getCoordinateLow(0));
Assert.assertEquals(11f, bb1.getCoordinateHigh(0));
final BoundingBox bb2 = new BoundingBox(1f, 10f, 10f, 50f);
Assert.assertEquals(1f, bb2.getCoordinateLow(0));
Assert.assertEquals(11f, bb2.getCoordinateHigh(0));
Assert.assertEquals(10f, bb2.getCoordinateLow(1));
Assert.assertEquals(60f, bb2.getCoordinateHigh(1));
}
/**
* Test the dimension of the bounding box
*/
@Test
public void testDimension() {
final BoundingBox bb1 = new BoundingBox();
Assert.assertEquals(0, bb1.getDimension());
final BoundingBox bb2 = new BoundingBox(1f, 10f);
Assert.assertEquals(1, bb2.getDimension());
final BoundingBox bb3 = new BoundingBox(1f, 10f, 10f, 50f);
Assert.assertEquals(2, bb3.getDimension());
final BoundingBox bb4 = new BoundingBox(1f, 10f, 10f, 50f, 10f, 10f);
Assert.assertEquals(3, bb4.getDimension());
final BoundingBox bb5 = new BoundingBox(1f, 10f, 10f);
Assert.assertEquals(BoundingBox.INVALID_DIMENSION, bb5.getDimension());
}
/**
* Test the overlapping in 1d
*/
@Test
public void testOverlapping1D() {
final BoundingBox bb1left = new BoundingBox(0f, 10f);
final BoundingBox bb1middle = new BoundingBox(5f, 10f);
final BoundingBox bb1right = new BoundingBox(10.1f, 10f);
Assert.assertTrue(bb1left.overlaps(bb1left));
Assert.assertTrue(bb1middle.overlaps(bb1middle));
Assert.assertTrue(bb1right.overlaps(bb1right));
Assert.assertFalse(bb1left.overlaps(null));
Assert.assertFalse(bb1middle.overlaps(null));
Assert.assertFalse(bb1right.overlaps(null));
Assert.assertFalse(bb1left.overlaps(bb1right));
Assert.assertFalse(bb1right.overlaps(bb1left));
Assert.assertTrue(bb1left.overlaps(bb1middle));
Assert.assertTrue(bb1middle.overlaps(bb1left));
Assert.assertTrue(bb1middle.overlaps(bb1right));
Assert.assertTrue(bb1right.overlaps(bb1middle));
}
/**
* Test the overlapping in 2d
*/
@Test
public void testOverlapping2D() {
final BoundingBox bb1left = new BoundingBox(0f, 1f, 0f, 1f);
final BoundingBox bb1leftinside = new BoundingBox(0.5f, 0.2f, 0.5f, 0.2f);
Assert.assertTrue(bb1left.overlaps(bb1leftinside));
Assert.assertTrue(bb1leftinside.overlaps(bb1left));
final BoundingBox bb1middle = new BoundingBox(0.5f, 1f, 0.5f, 1f);
Assert.assertTrue(bb1left.overlaps(bb1middle));
Assert.assertTrue(bb1middle.overlaps(bb1left));
final BoundingBox bb1right = new BoundingBox(1f, 1f, 10f, 1f);
Assert.assertFalse(bb1left.overlaps(bb1right));
Assert.assertFalse(bb1right.overlaps(bb1left));
}
/**
* Test the overlapping in 3d
*/
@Test
public void testOverlapping3D() {
final BoundingBox bb1left = new BoundingBox(0f, 1f, 0f, 1f, 0f, 1f);
final BoundingBox bb1leftinside = new BoundingBox(0.5f, 0.2f, 0.5f, 0.2f, 0.5f, 0.2f);
Assert.assertTrue(bb1left.overlaps(bb1leftinside));
Assert.assertTrue(bb1leftinside.overlaps(bb1left));
final BoundingBox bb1middle = new BoundingBox(0.5f, 1f, 0.5f, 1f, 0.5f, 1f);
Assert.assertTrue(bb1left.overlaps(bb1middle));
Assert.assertTrue(bb1middle.overlaps(bb1left));
final BoundingBox bb1right = new BoundingBox(10f, 1f, 10f, 1f, 10f, 1f);
Assert.assertFalse(bb1left.overlaps(bb1right));
Assert.assertFalse(bb1right.overlaps(bb1left));
}
/**
* Test empty bounding box overlapping
*/
@Test
public void testOverlapEmptyBoundingBox() {
final BoundingBox bb1left = new BoundingBox(0f, 1f, 0f, 1f, 0f, 1f);
Assert.assertTrue(bb1left.overlaps(BoundingBox.EMPTY_BOX));
Assert.assertTrue(BoundingBox.EMPTY_BOX.overlaps(BoundingBox.EMPTY_BOX));
}
/**
* Test the creation of the covering bounding box
*/
@Test
public void testCoverBoundingBox() {
final BoundingBox boundingBox1 = new BoundingBox(1f, 2f, 1f, 2f);
final BoundingBox boundingBox2 = new BoundingBox(1f, 3f, 1f, 3f);
final BoundingBox boundingBox3 = new BoundingBox(1f, 3f, 1f, 3f, 1f, 3f);
final BoundingBox boundingBox4 = new BoundingBox(-1f, 3f, -1f, 3f, -1f, 3f);
final BoundingBox boundingBoxResult1 = BoundingBox.getBoundingBox();
Assert.assertTrue(boundingBoxResult1 == null);
Assert.assertEquals(boundingBox1, BoundingBox.getBoundingBox(boundingBox1));
Assert.assertEquals(boundingBox2, BoundingBox.getBoundingBox(boundingBox2));
Assert.assertEquals(boundingBox3, BoundingBox.getBoundingBox(boundingBox3));
Assert.assertEquals(boundingBox4, BoundingBox.getBoundingBox(boundingBox4));
final BoundingBox boundingBoxResult2 = BoundingBox.getBoundingBox(boundingBox1, boundingBox2);
Assert.assertEquals(2, boundingBoxResult2.getDimension());
Assert.assertEquals(boundingBoxResult2, boundingBox2);
// Wrong dimensions
final BoundingBox boundingBoxResult3 = BoundingBox.getBoundingBox(boundingBox1, boundingBox3);
Assert.assertTrue(boundingBoxResult3 == null);
final BoundingBox boundingBoxResult4 = BoundingBox.getBoundingBox(boundingBox3, boundingBox4);
Assert.assertEquals(3, boundingBoxResult4.getDimension());
Assert.assertEquals(-1.0f, boundingBoxResult4.getCoordinateLow(0));
Assert.assertEquals(4.0f, boundingBoxResult4.getCoordinateHigh(0));
Assert.assertEquals(-1.0f, boundingBoxResult4.getCoordinateLow(1));
Assert.assertEquals(4.0f, boundingBoxResult4.getCoordinateHigh(1));
Assert.assertEquals(-1.0f, boundingBoxResult4.getCoordinateLow(2));
Assert.assertEquals(4.0f, boundingBoxResult4.getCoordinateHigh(2));
// Wrong dimensions
final BoundingBox boundingBoxResult5 = BoundingBox.getBoundingBox(boundingBox1, boundingBox2, boundingBox3, boundingBox4);
Assert.assertTrue(boundingBoxResult5 == null);
}
/**
* Test the comparable interface of the bounding box
*/
@Test
public void testBoundingBoxSorting() {
final BoundingBox boundingBox1 = new BoundingBox(1f, 2f, 3f, 4f);
final BoundingBox boundingBox2 = new BoundingBox(-1f, 2f, 3f, 4f);
final BoundingBox boundingBox3 = new BoundingBox(5f, 2f, 3f, 4f);
final BoundingBox boundingBox4 = new BoundingBox(-11f, 2f, 3f, 4f);
final BoundingBox boundingBox5 = new BoundingBox(-11f, 2f, -1f, 4f);
final List<BoundingBox> boundingBoxList = new ArrayList<BoundingBox>();
boundingBoxList.add(boundingBox1);
boundingBoxList.add(boundingBox2);
boundingBoxList.add(boundingBox3);
boundingBoxList.add(boundingBox4);
boundingBoxList.add(boundingBox5);
Collections.sort(boundingBoxList);
Assert.assertEquals(boundingBox5, boundingBoxList.get(0));
Assert.assertEquals(boundingBox4, boundingBoxList.get(1));
Assert.assertEquals(boundingBox2, boundingBoxList.get(2));
Assert.assertEquals(boundingBox1, boundingBoxList.get(3));
Assert.assertEquals(boundingBox3, boundingBoxList.get(4));
}
}
|
package de.slackspace.openkeepass.domain;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.Test;
import de.slackspace.openkeepass.crypto.RandomGenerator;
import de.slackspace.openkeepass.util.ByteUtils;
import de.slackspace.openkeepass.util.ResourceUtils;
import de.slackspace.openkeepass.util.StreamUtils;
public class KeepassHeaderTest {
@Test(expected = IllegalArgumentException.class)
public void whenCipherIsSetToInvalidValueShouldThrowException() {
createHeaderAndSetValue(2, new byte[1]);
}
@Test
public void whenCipherIsSetToByteArrayShouldReturnHeaderWithCipher() {
KeePassHeader header = createHeaderAndSetValue(2, ByteUtils.hexStringToByteArray("31C1F2E6BF714350BE5805216AFC5AFF"));
Assert.assertTrue("Cipher must be 31C1F2E6BF714350BE5805216AFC5AFF",
Arrays.equals(ByteUtils.hexStringToByteArray("31C1F2E6BF714350BE5805216AFC5AFF"), header.getCipher()));
}
@Test(expected = BufferUnderflowException.class)
public void whenCompressionIsSetToInvalidValueShouldThrowException() {
createHeaderAndSetValue(3, new byte[2]);
}
@Test
public void whenCompressionIsSetGzipShouldReturnHeaderWithGzipCompression() {
ByteBuffer b = ByteBuffer.allocate(4);
b.putInt(0x01000000);
KeePassHeader header = createHeaderAndSetValue(3, b.array());
Assert.assertEquals(CompressionAlgorithm.Gzip, header.getCompression());
}
@Test
public void whenCompressionIsSetNoneShouldReturnHeaderWithNoneCompression() {
KeePassHeader header = createHeaderAndSetValue(3, new byte[4]);
Assert.assertEquals(CompressionAlgorithm.None, header.getCompression());
}
@Test
public void whenCrsIsSetArcFourShouldReturnHeaderWithArgFourCrsAlgorithm() {
ByteBuffer b = ByteBuffer.allocate(4);
b.putInt(0x01000000);
KeePassHeader header = createHeaderAndSetValue(10, b.array());
Assert.assertEquals(CrsAlgorithm.ArcFourVariant, header.getCrsAlgorithm());
}
@Test
public void whenCrsIsSetSalsa20ShouldReturnHeaderWithSalsa20CrsAlgorithm() {
ByteBuffer b = ByteBuffer.allocate(4);
b.putInt(0x02000000);
KeePassHeader header = createHeaderAndSetValue(10, b.array());
Assert.assertEquals(CrsAlgorithm.Salsa20, header.getCrsAlgorithm());
}
@Test
public void whenCrsIsSetNullShouldReturnHeaderWithNullCrsAlgorithm() {
KeePassHeader header = createHeaderAndSetValue(10, new byte[4]);
Assert.assertEquals(CrsAlgorithm.Null, header.getCrsAlgorithm());
}
private KeePassHeader createHeaderAndSetValue(int headerId, byte[] value) {
KeePassHeader keepassHeader = new KeePassHeader();
keepassHeader.setValue(headerId, value);
return keepassHeader;
}
@Test
public void whenGetBytesIsCalledShouldReturnHeaderBytesCorrectly() {
KeePassHeader header = new KeePassHeader();
header.setValue(KeePassHeader.MASTER_SEED, ByteUtils.hexStringToByteArray("35ac8b529bc4f6e44194bccd0537fcb433a30bcb847e63156262c4df99c528ca"));
header.setValue(KeePassHeader.TRANSFORM_SEED, ByteUtils.hexStringToByteArray("0d52d93efc5493ae6623f0d5d69bb76bd976bb717f4ee67abbe43528ebfbb646"));
header.setTransformRounds(8000);
header.setValue(KeePassHeader.ENCRYPTION_IV, ByteUtils.hexStringToByteArray("2c605455f181fbc9462aefb817852b37"));
header.setValue(KeePassHeader.STREAM_START_BYTES, ByteUtils.hexStringToByteArray("69d788d9b01ea1facd1c0bf0187e7d74e4aa07b20d464f3d23d0b2dc2f059ff8"));
header.setValue(KeePassHeader.CIPHER, ByteUtils.hexStringToByteArray("31C1F2E6BF714350BE5805216AFC5AFF"));
header.setValue(KeePassHeader.PROTECTED_STREAM_KEY, ByteUtils.hexStringToByteArray("ec77a2169769734c5d26e5341401f8d7b11052058f8455d314879075d0b7e257"));
header.setCompression(CompressionAlgorithm.Gzip);
header.setCrsAlgorithm(CrsAlgorithm.Salsa20);
Assert.assertEquals(
"03d9a29a67fb4bb50000030002100031c1f2e6bf714350be5805216afc5aff0304000100000004200035ac8b529bc4f6e44194bccd0537fcb433a30bcb847e63156262c4df99c528ca0520000d52d93efc5493ae6623f0d5d69bb76bd976bb717f4ee67abbe43528ebfbb646060800401f0000000000000710002c605455f181fbc9462aefb817852b37082000ec77a2169769734c5d26e5341401f8d7b11052058f8455d314879075d0b7e25709200069d788d9b01ea1facd1c0bf0187e7d74e4aa07b20d464f3d23d0b2dc2f059ff80a0400020000000004000d0a0d0a",
ByteUtils.toHexString(header.getBytes()));
Assert.assertEquals(210, header.getHeaderSize());
}
@Test
public void shouldInitializeCryptoValues() {
KeePassHeader header = new KeePassHeader(new RandomGenerator());
Assert.assertEquals(32, header.getMasterSeed().length);
Assert.assertEquals(32, header.getTransformSeed().length);
Assert.assertEquals(16, header.getEncryptionIV().length);
Assert.assertEquals(32, header.getProtectedStreamKey().length);
Assert.assertEquals(CrsAlgorithm.Salsa20, header.getCrsAlgorithm());
Assert.assertEquals(32, header.getStreamStartBytes().length);
Assert.assertEquals(CompressionAlgorithm.Gzip, header.getCompression());
Assert.assertEquals(8000, header.getTransformRounds());
Assert.assertEquals("31c1f2e6bf714350be5805216afc5aff", ByteUtils.toHexString(header.getCipher()));
}
@Test(expected = UnsupportedOperationException.class)
public void whenVersionIsNotSupportedShouldThrowException() throws IOException {
KeePassHeader header = new KeePassHeader(new RandomGenerator());
// unsupported format --> e.g. v5
byte[] rawHeader = ByteUtils.hexStringToByteArray("03D9A29A67FB4BB501000500");
header.checkVersionSupport(rawHeader);
}
@Test
public void whenKdfParameterAreProvidedShouldReadKdfParameters() throws IOException {
KeePassHeader header = new KeePassHeader(new RandomGenerator());
FileInputStream fileInputStream = new FileInputStream(ResourceUtils.getResource("DatabaseWithV4Format.kdbx"));
byte[] rawFile = StreamUtils.toByteArray(fileInputStream);
header.checkVersionSupport(rawFile);
header.read(rawFile);
VariantDictionary kdfParameters = header.getKdfParameters();
Assert.assertArrayEquals(ByteUtils.hexStringToByteArray("ef636ddf8c29444b91f7a9a403e30a0c"), kdfParameters.getByteArray("$UUID"));
Assert.assertEquals(19, kdfParameters.getInt("V"));
Assert.assertEquals(2, kdfParameters.getLong("I"));
Assert.assertEquals(2, kdfParameters.getInt("P"));
Assert.assertEquals(1048576, kdfParameters.getLong("M"));
Assert.assertArrayEquals(ByteUtils.hexStringToByteArray("7ea16ccbf5f48cb5f77b01a9192123164c5f5f5245a10e5f9c848f47f0c93a4c"), kdfParameters.getByteArray("S"));
}
}
|
package design_patterns.structural.decorator;
import org.junit.*;
public class DecoratorTest {
@Test
public void mainTest() {
Coffee c = new SimpleCoffee();
Coffee custom = new Sugar(new Milk(c));
Assert.assertEquals(custom.getIngredients(), "SimpleCoffee, Milk, Sugar");
Assert.assertEquals(custom.getCost(), 1.5, 0);
}
}
|
package es.ehu.si.ixa.pipe.nerc;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import opennlp.tools.util.Span;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import es.ehu.si.ixa.pipe.nerc.dict.Dictionaries;
public class DictionariesNameFinderTest {
private static DictionariesNameFinder finder = null;
@BeforeClass
public static void setUpClass() throws IOException {
// copy to a temporary dir so that it can be loaded
File dictsDir = Files.createTempDirectory("dicts").toFile();
Files.copy(DictionariesNameFinderTest.class
.getResourceAsStream("/names.txt"),
new File(dictsDir, "names.txt").toPath());
// now load it into a Dictionaries instance
finder = new DictionariesNameFinder(
new Dictionaries(dictsDir.getAbsolutePath()));
}
@Test
public void oneOccurrence() throws IOException {
List<Span> spans = finder.nercToSpansExact(new String[] {"Achilles"});
assertEquals(1, spans.size());
}
@Test
public void twoOccurrences() throws IOException {
List<Span> spans = finder.nercToSpansExact(new String[] {
"Achilles", "Apollo", "Zeus", "Achilles"});
assertEquals(2, spans.size());
}
}
|
package eu.project.ttc.test.termino.export;
import java.io.StringWriter;
import java.util.Collection;
import java.util.Locale;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import eu.project.ttc.api.TsvOptions;
import eu.project.ttc.models.RelationType;
import eu.project.ttc.models.Term;
import eu.project.ttc.models.TermIndex;
import eu.project.ttc.models.TermRelation;
import eu.project.ttc.termino.export.TsvExporter;
import eu.project.ttc.test.TermSuiteAssertions;
import eu.project.ttc.test.unit.TermFactory;
public class TsvExporterSpec {
TermIndex termIndex;
Collection<Term> terms;
Term term1, term2, term3;
StringWriter writer;
@Before
public void setup() {
termIndex = Mockito.mock(TermIndex.class);
term1 = TermFactory.termMock("t1", 1, 3, 0.8);
term2 = TermFactory.termMock("t2", 2, 1, 0.8);
term3 = TermFactory.termMock("t3", 3, 2, 1);
TermRelation tv = Mockito.mock(TermRelation.class);
Mockito.when(tv.getTo()).thenReturn(term1);
Mockito.when(termIndex.getOutboundRelations(term3,
RelationType.SYNTACTICAL,
RelationType.MORPHOLOGICAL,
RelationType.GRAPHICAL,
RelationType.SYNONYMIC,
RelationType.DERIVES_INTO,
RelationType.IS_PREFIX_OF
)).thenReturn(Sets.newHashSet(tv));
terms = Lists.newArrayList(
term1,
term2,
term3
);
Mockito.when(termIndex.getTerms()).thenReturn(terms);
writer = new StringWriter();
defaultLocale = Locale.getDefault();
Locale.setDefault(Locale.ENGLISH);
}
Locale defaultLocale;
@After
public void tearDown() {
Locale.setDefault(defaultLocale);
}
@Test
public void testTsvExportNoScore() {
TsvExporter.export(termIndex, writer);
TermSuiteAssertions.assertThat(writer.toString())
.hasLineCount(5)
.tsvLineEquals(1, "#","type", "gkey", "f")
.tsvLineEquals(2, 1, "T", "t2", 2)
.tsvLineEquals(3, 2, "T", "t3", 3)
.tsvLineEquals(4, 2, "V", "t1", 1)
.tsvLineEquals(5, 3, "T", "t1", 1)
;
}
@Test
public void testTsvExportWithScores() {
TsvExporter.export(termIndex, writer, new TsvOptions().showScores(true));
TermSuiteAssertions.assertThat(writer.toString())
.hasLineCount(5)
.tsvLineEquals(1, "#","type", "gkey", "f")
.tsvLineEquals(2, 1, "T[]", "t2", 2)
.tsvLineEquals(3, 2, "T[]", "t3", 3)
.tsvLineEquals(4, 2, "V[0.00]", "t1", 1)
.tsvLineEquals(5, 3, "T[]", "t1", 1)
;
}
@Test
public void testTsvExportNoHeaders() {
TsvExporter.export(termIndex, writer, new TsvOptions().showHeaders(false));
TermSuiteAssertions.assertThat(writer.toString())
.hasLineCount(4)
.tsvLineEquals(1, 1, "T", "t2", 2)
.tsvLineEquals(2, 2, "T", "t3", 3)
.tsvLineEquals(3, 2, "V", "t1", 1)
.tsvLineEquals(4, 3, "T", "t1", 1)
;
}
@Test
public void testTsvExportNoVariant() {
TsvExporter.export(termIndex, writer, new TsvOptions().setShowVariants(false));
TermSuiteAssertions.assertThat(writer.toString())
.hasLineCount(4)
.tsvLineEquals(1, "#","type", "gkey", "f")
.tsvLineEquals(2, 1, "T", "t2", 2)
.tsvLineEquals(3, 2, "T", "t3", 3)
.tsvLineEquals(4, 3, "T", "t1", 1)
;
}
}
|
package ge.edu.freeuni.sdp.arkanoid.model;
import ge.edu.freeuni.sdp.arkanoid.model.geometry.Point;
import ge.edu.freeuni.sdp.arkanoid.model.geometry.Rectangle;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
import org.mockito.Mock;
import java.util.ArrayList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.mockito.Mockito.*;
public class WormholeBallTest {
@Mock ArrayList<PortalBrick> portalBricks;
@Mock Capsule capsule;
@Mock Point point;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void kind_is_ball() {
WormholeBall target = new WormholeBall(portalBricks);
GobjKind kind = target.getKind();
assertEquals(GobjKind.Ball, kind);
}
@Test
public void ball_teleports_to_other_portalbrick() {
Point point1 = new Point(0, 0);
Point point2 = new Point(10, 10);
PortalBrick pBrick1 = new PortalBrick(point1, BrickColor.Blue, capsule);
PortalBrick pBrick2 = new PortalBrick(point2, BrickColor.Blue, capsule);
ArrayList<PortalBrick> pBricks = new ArrayList<PortalBrick>();
pBricks.add(pBrick1);
pBricks.add(pBrick2);
WormholeBall target = new WormholeBall(pBricks);
target.interact(pBrick1);
assertEquals(point2, target.getPosition());
}
@Test
public void is_portlBricks_alive_after_interact() {
PortalBrick pBrick1 = new PortalBrick(point, BrickColor.Blue, capsule);
PortalBrick pBrick2 = new PortalBrick(point, BrickColor.Blue, capsule);
ArrayList<PortalBrick> pBricks = new ArrayList<PortalBrick>();
pBricks.add(pBrick1);
pBricks.add(pBrick2);
WormholeBall target = new WormholeBall(pBricks);
target.interact(pBrick1);
assertEquals(pBrick1.isAlive(), true);
assertEquals(pBrick2.isAlive(), true);
}
@Test
public void is_interact_not_called_on_other_portalBrick() {
PortalBrick pBrick1 = mock(PortalBrick.class);
PortalBrick pBrick2 = mock(PortalBrick.class);
when(pBrick2.getPosition()).thenReturn(point);
ArrayList<PortalBrick> pBricks = new ArrayList<PortalBrick>();
pBricks.add(pBrick1);
pBricks.add(pBrick2);
WormholeBall target = new WormholeBall(pBricks);
target.interact(pBrick1);
verify(pBrick2, never()).interact(target);
}
}
|
package hudson.plugins.cobertura.targets;
import junit.framework.TestCase;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class CoveragePaintTest extends TestCase {
public CoveragePaintTest(String string) {
super(string);
}
public void testTotalLines() {
CoveragePaint instance = new CoveragePaint(CoverageElement.JAVA_FILE);
assertEquals(0, instance.getTotalLines());
instance.setTotalLines(451);
assertEquals(451, instance.getTotalLines());
instance.setTotalLines(179);
assertEquals(179, instance.getTotalLines());
}
public void testSerializable() throws Exception {
CoveragePaint instance = new CoveragePaint(CoverageElement.JAVA_FILE);
instance.paint(5, 7, 4, 5);
instance.setTotalLines(314);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(instance);
oos.flush();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
CoveragePaint copy = (CoveragePaint) ois.readObject();
assertEquals(instance.getLineCoverage(), copy.getLineCoverage());
assertEquals(instance.getConditionalCoverage(), copy.getConditionalCoverage());
assertEquals(314, copy.getTotalLines());
}
}
|
package jp.ac.tsukuba.cs.kde.hfukuda.lemma_finder;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import org.junit.BeforeClass;
import org.junit.Test;
import net.didion.jwnl.JWNLException;
import net.didion.jwnl.data.POS;
public class MainTest {
@BeforeClass
public static void setUpBeforeClass() throws IOException, JWNLException {
final Path wordNetDictionaryPath = Paths.get("target/lemma-finder/wordnet/dictionary");
WordNetDictionaryDownloader.downloadDictionary(wordNetDictionaryPath);
LemmaFinder.initialize(wordNetDictionaryPath);
}
@Test
public void testUsualWord() throws JWNLException {
assertThat(LemmaFinder.findLemma("Linked", POS.NOUN), is(Optional.empty()));
assertThat(LemmaFinder.findLemma("Linked", POS.VERB), is(Optional.of("link")));
assertThat(LemmaFinder.findLemma("Linked", POS.ADJECTIVE), is(Optional.of("linked")));
assertThat(LemmaFinder.findLemma("Linked", POS.ADVERB), is(Optional.empty()));
}
@Test
public void testTrailingNumbers() throws JWNLException {
assertThat(LemmaFinder.findLemma("Version4", POS.NOUN), is(Optional.of("version")));
assertThat(LemmaFinder.findLemma("Version4", POS.VERB), is(Optional.empty()));
assertThat(LemmaFinder.findLemma("Version4", POS.ADJECTIVE), is(Optional.empty()));
assertThat(LemmaFinder.findLemma("Version4", POS.ADVERB), is(Optional.empty()));
}
@Test
public void testIllegularInflection() throws JWNLException {
assertThat(LemmaFinder.findLemma("Women", POS.NOUN), is(Optional.of("woman")));
assertThat(LemmaFinder.findLemma("Women", POS.VERB), is(Optional.empty()));
assertThat(LemmaFinder.findLemma("Women", POS.ADJECTIVE), is(Optional.empty()));
assertThat(LemmaFinder.findLemma("Women", POS.ADVERB), is(Optional.empty()));
}
}
|
package mho.qbar.iterableProviders;
import mho.qbar.objects.Interval;
import mho.qbar.objects.Rational;
import mho.qbar.objects.Variable;
import mho.qbar.testing.QBarDemos;
import mho.wheels.structures.Pair;
import mho.wheels.structures.Triple;
import java.util.List;
import static mho.wheels.iterables.IterableUtils.filterInfinite;
import static mho.wheels.iterables.IterableUtils.take;
import static mho.wheels.ordering.Ordering.le;
import static mho.wheels.testing.Testing.*;
@SuppressWarnings("UnusedDeclaration")
public class QBarRandomProviderDemos extends QBarDemos {
public QBarRandomProviderDemos(boolean useRandom) {
super(useRandom);
}
private void demoPositiveRationals() {
Iterable<QBarRandomProvider> rps = filterInfinite(
s -> s.getScale() >= 4,
P.qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
);
for (QBarRandomProvider rp : take(MEDIUM_LIMIT, rps)) {
System.out.println("positiveRationals(" + rp + ") = " + its(rp.positiveRationals()));
}
}
private void demoNegativeRationals() {
Iterable<QBarRandomProvider> rps = filterInfinite(
s -> s.getScale() >= 4,
P.qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
);
for (QBarRandomProvider rp : take(MEDIUM_LIMIT, rps)) {
System.out.println("negativeRationals(" + rp + ") = " + its(rp.negativeRationals()));
}
}
private void demoNonzeroRationals() {
Iterable<QBarRandomProvider> rps = filterInfinite(
s -> s.getScale() >= 4,
P.qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
);
for (QBarRandomProvider rp : take(MEDIUM_LIMIT, rps)) {
System.out.println("nonzeroRationals(" + rp + ") = " + its(rp.nonzeroRationals()));
}
}
private void demoRationals() {
Iterable<QBarRandomProvider> rps = filterInfinite(
s -> s.getScale() >= 3,
P.qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
);
for (QBarRandomProvider rp : take(MEDIUM_LIMIT, rps)) {
System.out.println("rationals(" + rp + ") = " + its(rp.rationals()));
}
}
private void demoNonNegativeRationalsLessThanOne() {
Iterable<QBarRandomProvider> rps = filterInfinite(
s -> s.getScale() >= 4,
P.qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
);
for (QBarRandomProvider rp : take(MEDIUM_LIMIT, rps)) {
System.out.println("nonNegativeRationalsLessThanOne(" + rp + ") = " +
its(rp.nonNegativeRationalsLessThanOne()));
}
}
private void demoRangeUp_Rational() {
Iterable<Pair<QBarRandomProvider, Rational>> ps = P.pairs(
filterInfinite(rp -> rp.getScale() >= 4, P.qbarRandomProvidersDefaultSecondaryAndTertiaryScale()),
P.rationals()
);
for (Pair<QBarRandomProvider, Rational> p : take(MEDIUM_LIMIT, ps)) {
System.out.println("rangeUp(" + p.a + ", " + p.b + ") = " + its(p.a.rangeUp(p.b)));
}
}
private void demoRangeDown_Rational() {
Iterable<Pair<QBarRandomProvider, Rational>> ps = P.pairs(
filterInfinite(rp -> rp.getScale() >= 4, P.qbarRandomProvidersDefaultSecondaryAndTertiaryScale()),
P.rationals()
);
for (Pair<QBarRandomProvider, Rational> p : take(MEDIUM_LIMIT, ps)) {
System.out.println("rangeDown(" + p.a + ", " + p.b + ") = " + its(p.a.rangeDown(p.b)));
}
}
private void demoRange_Rational_Rational() {
Iterable<Triple<QBarRandomProvider, Rational, Rational>> ts = filterInfinite(
t -> le(t.b, t.c),
P.triples(
filterInfinite(
rp -> rp.getScale() >= 4,
P.qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
),
P.rationals(),
P.rationals()
)
);
for (Triple<QBarRandomProvider, Rational, Rational> t : take(MEDIUM_LIMIT, ts)) {
System.out.println("range(" + t.a + ", " + t.b + ", " + t.c + ") = " + its(t.a.range(t.b, t.c)));
}
}
private void demoFinitelyBoundedIntervals() {
Iterable<QBarRandomProvider> rps = filterInfinite(
s -> s.getScale() >= 6,
P.qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
);
for (QBarRandomProvider rp : take(MEDIUM_LIMIT, rps)) {
System.out.println("finitelyBoundedIntervals(" + rp + ") = " + its(rp.finitelyBoundedIntervals()));
}
}
private void demoIntervals() {
Iterable<QBarRandomProvider> rps = filterInfinite(
s -> s.getScale() >= 6,
P.qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
);
for (QBarRandomProvider rp : take(MEDIUM_LIMIT, rps)) {
System.out.println("intervals(" + rp + ") = " + its(rp.intervals()));
}
}
private void demoRationalsIn() {
Iterable<Pair<QBarRandomProvider, Interval>> ps = P.pairs(
filterInfinite(
s -> s.getScale() >= 4,
P.qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
),
P.intervals()
);
for (Pair<QBarRandomProvider, Interval> p : take(MEDIUM_LIMIT, ps)) {
System.out.println("rationalsIn(" + p.a + ", " + p.b + ") = " + its(p.a.rationalsIn(p.b)));
}
}
private void demoRationalsNotIn() {
Iterable<Pair<QBarRandomProvider, Interval>> ps = P.pairs(
filterInfinite(
s -> s.getScale() >= 4,
P.qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
),
filterInfinite(a -> !a.equals(Interval.ALL), P.intervals())
);
for (Pair<QBarRandomProvider, Interval> p : take(MEDIUM_LIMIT, ps)) {
System.out.println("rationalsNotIn(" + p.a + ", " + p.b + ") = " + its(p.a.rationalsNotIn(p.b)));
}
}
private void demoVectors_int() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
),
P.withScale(4).naturalIntegersGeometric()
);
for (Pair<QBarRandomProvider, Integer> p : take(MEDIUM_LIMIT, ps)) {
System.out.println("vectors(" + p.a + ", " + p.b + ") = " + its(p.a.vectors(p.b)));
}
}
private void demoVectors() {
Iterable<QBarRandomProvider> rps = filterInfinite(
rp -> rp.getScale() > 0 && rp.getSecondaryScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
);
for (QBarRandomProvider rp : take(MEDIUM_LIMIT, rps)) {
System.out.println("vectors(" + rp + ") = " + its(rp.vectors()));
}
}
private void demoVectorsAtLeast() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = filterInfinite(
p -> p.a.getSecondaryScale() > p.b,
P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
),
P.withScale(4).naturalIntegersGeometric()
)
);
for (Pair<QBarRandomProvider, Integer> p : take(MEDIUM_LIMIT, ps)) {
System.out.println("vectorsAtLeast(" + p.a + ", " + p.b + ") = " +
its(p.a.vectorsAtLeast(p.b)));
}
}
private void demoRationalVectors_int() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() >= 3,
P.withScale(4).qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
),
P.withScale(4).naturalIntegersGeometric()
);
for (Pair<QBarRandomProvider, Integer> p : take(MEDIUM_LIMIT, ps)) {
System.out.println("rationalVectors(" + p.a + ", " + p.b + ") = " + its(p.a.rationalVectors(p.b)));
}
}
private void demoRationalVectors() {
Iterable<QBarRandomProvider> rps = filterInfinite(
rp -> rp.getScale() >= 3 && rp.getSecondaryScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
);
for (QBarRandomProvider rp : take(MEDIUM_LIMIT, rps)) {
System.out.println("rationalVectors(" + rp + ") = " + its(rp.rationalVectors()));
}
}
private void demoRationalVectorsAtLeast() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = filterInfinite(
p -> p.a.getSecondaryScale() > p.b,
P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() >= 3,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
),
P.withScale(4).naturalIntegersGeometric()
)
);
for (Pair<QBarRandomProvider, Integer> p : take(MEDIUM_LIMIT, ps)) {
System.out.println("rationalVectorsAtLeast(" + p.a + ", " + p.b + ") = " +
its(p.a.rationalVectorsAtLeast(p.b)));
}
}
private void demoReducedRationalVectors_int() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
),
P.withScale(4).naturalIntegersGeometric()
);
for (Pair<QBarRandomProvider, Integer> p : take(MEDIUM_LIMIT, ps)) {
System.out.println("reducedRationalVectors(" + p.a + ", " + p.b + ") = " +
its(p.a.reducedRationalVectors(p.b)));
}
}
private void demoReducedRationalVectors() {
Iterable<QBarRandomProvider> rps = filterInfinite(
rp -> rp.getScale() > 0 && rp.getSecondaryScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
);
for (QBarRandomProvider rp : take(MEDIUM_LIMIT, rps)) {
System.out.println("reducedRationalVectors(" + rp + ") = " + its(rp.reducedRationalVectors()));
}
}
private void demoReducedRationalVectorsAtLeast() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = filterInfinite(
p -> p.a.getSecondaryScale() > p.b,
P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
),
P.withScale(4).naturalIntegersGeometric()
)
);
for (Pair<QBarRandomProvider, Integer> p : take(MEDIUM_LIMIT, ps)) {
System.out.println("reducedRationalVectorsAtLeast(" + p.a + ", " + p.b + ") = " +
its(p.a.reducedRationalVectorsAtLeast(p.b)));
}
}
private void demoPolynomialVectors_int() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() > 0 && rp.getSecondaryScale() >= 0,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
),
P.withScale(4).naturalIntegersGeometric()
);
for (Pair<QBarRandomProvider, Integer> p : take(SMALL_LIMIT, ps)) {
System.out.println("polynomialVectors(" + p.a + ", " + p.b + ") = " + its(p.a.polynomialVectors(p.b)));
}
}
private void demoPolynomialVectors() {
Iterable<QBarRandomProvider> rps = filterInfinite(
rp -> rp.getScale() > 0 && rp.getSecondaryScale() >= 0 && rp.getTertiaryScale() > 0,
P.withScale(4).qbarRandomProviders()
);
for (QBarRandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("polynomialVectors(" + rp + ") = " + its(rp.polynomialVectors()));
}
}
private void demoPolynomialVectorsAtLeast() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = filterInfinite(
p -> p.a.getTertiaryScale() > p.b,
P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() > 0 && rp.getSecondaryScale() >= 0,
P.withScale(4).qbarRandomProviders()
),
P.withScale(4).naturalIntegersGeometric()
)
);
for (Pair<QBarRandomProvider, Integer> p : take(SMALL_LIMIT, ps)) {
System.out.println("polynomialVectorsAtLeast(" + p.a + ", " + p.b + ") = " +
its(p.a.polynomialVectorsAtLeast(p.b)));
}
}
private void demoRationalPolynomialVectors_int() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() >= 3 && rp.getSecondaryScale() >= 0,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
),
P.withScale(4).naturalIntegersGeometric()
);
for (Pair<QBarRandomProvider, Integer> p : take(SMALL_LIMIT, ps)) {
System.out.println("rationalPolynomialVectors(" + p.a + ", " + p.b + ") = " +
its(p.a.rationalPolynomialVectors(p.b)));
}
}
private void demoRationalPolynomialVectors() {
Iterable<QBarRandomProvider> rps = filterInfinite(
rp -> rp.getScale() >= 3 && rp.getSecondaryScale() >= 0 && rp.getTertiaryScale() > 0,
P.withScale(4).qbarRandomProviders()
);
for (QBarRandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("rationalPolynomialVectors(" + rp + ") = " + its(rp.rationalPolynomialVectors()));
}
}
private void demoRationalPolynomialVectorsAtLeast() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = filterInfinite(
p -> p.a.getTertiaryScale() > p.b,
P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() >= 3 && rp.getSecondaryScale() >= 0,
P.withScale(4).qbarRandomProviders()
),
P.withScale(4).naturalIntegersGeometric()
)
);
for (Pair<QBarRandomProvider, Integer> p : take(SMALL_LIMIT, ps)) {
System.out.println("rationalPolynomialVectorsAtLeast(" + p.a + ", " + p.b + ") = " +
its(p.a.rationalPolynomialVectorsAtLeast(p.b)));
}
}
private void demoMatrices_int_int() {
Iterable<Triple<QBarRandomProvider, Integer, Integer>> ts = P.triples(
filterInfinite(
rp -> rp.getScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
),
P.withScale(4).naturalIntegersGeometric(),
P.withScale(4).naturalIntegersGeometric()
);
for (Triple<QBarRandomProvider, Integer, Integer> t : take(SMALL_LIMIT, ts)) {
System.out.println("matrices(" + t.a + ", " + t.b + ", " + t.c + ") = " + its(t.a.matrices(t.b, t.c)));
}
}
private void demoMatrices() {
Iterable<QBarRandomProvider> rps = filterInfinite(
rp -> rp.getScale() > 0 && rp.getSecondaryScale() >= 2,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
);
for (QBarRandomProvider rp : take(MEDIUM_LIMIT, rps)) {
System.out.println("matrices(" + rp + ") = " + its(rp.matrices()));
}
}
private void demoSquareMatrices() {
Iterable<QBarRandomProvider> rps = filterInfinite(
rp -> rp.getScale() >= 2 && rp.getSecondaryScale() >= 2,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
);
for (QBarRandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("squareMatrices(" + rp + ") = " + its(rp.squareMatrices()));
}
}
private void demoInvertibleMatrices() {
Iterable<QBarRandomProvider> rps = filterInfinite(
rp -> rp.getScale() >= 2 && rp.getSecondaryScale() >= 2,
P.withScale(2).qbarRandomProvidersDefaultTertiaryScale()
);
for (QBarRandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("invertibleMatrices(" + rp + ") = " + its(rp.invertibleMatrices()));
}
}
private void demoRationalMatrices_int_int() {
Iterable<Triple<QBarRandomProvider, Integer, Integer>> ts = P.triples(
filterInfinite(
rp -> rp.getScale() >= 3,
P.withScale(4).qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
),
P.withScale(4).naturalIntegersGeometric(),
P.withScale(4).naturalIntegersGeometric()
);
for (Triple<QBarRandomProvider, Integer, Integer> t : take(SMALL_LIMIT, ts)) {
System.out.println("rationalMatrices(" + t.a + ", " + t.b + ", " + t.c + ") = " +
its(t.a.rationalMatrices(t.b, t.c)));
}
}
private void demoRationalMatrices() {
Iterable<QBarRandomProvider> rps = filterInfinite(
rp -> rp.getScale() >= 3 && rp.getSecondaryScale() >= 2,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
);
for (QBarRandomProvider rp : take(MEDIUM_LIMIT, rps)) {
System.out.println("rationalMatrices(" + rp + ") = " + its(rp.rationalMatrices()));
}
}
private void demoSquareRationalMatrices() {
Iterable<QBarRandomProvider> rps = filterInfinite(
rp -> rp.getScale() >= 3 && rp.getSecondaryScale() >= 2,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
);
for (QBarRandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("squareRationalMatrices(" + rp + ") = " + its(rp.squareRationalMatrices()));
}
}
private void demoInvertibleRationalMatrices() {
Iterable<QBarRandomProvider> rps = filterInfinite(
rp -> rp.getScale() >= 3 && rp.getSecondaryScale() >= 2,
P.withScale(2).qbarRandomProvidersDefaultTertiaryScale()
);
for (QBarRandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("invertibleRationalMatrices(" + rp + ") = " + its(rp.invertibleRationalMatrices()));
}
}
private void demoPolynomialMatrices_int_int() {
Iterable<Triple<QBarRandomProvider, Integer, Integer>> ts = P.triples(
filterInfinite(
rp -> rp.getScale() > 0 && rp.getSecondaryScale() >= 0,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
),
P.withScale(4).naturalIntegersGeometric(),
P.withScale(4).naturalIntegersGeometric()
);
for (Triple<QBarRandomProvider, Integer, Integer> t : take(SMALL_LIMIT, ts)) {
System.out.println("polynomialMatrices(" + t.a + ", " + t.b + ", " + t.c + ") = " +
its(t.a.polynomialMatrices(t.b, t.c)));
}
}
private void demoPolynomialMatrices() {
Iterable<QBarRandomProvider> rps = filterInfinite(
rp -> rp.getScale() > 0 && rp.getSecondaryScale() >= 0 && rp.getTertiaryScale() >= 2,
P.withScale(4).qbarRandomProviders()
);
for (QBarRandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("polynomialMatrices(" + rp + ") = " + its(rp.polynomialMatrices()));
}
}
private void demoSquarePolynomialMatrices() {
Iterable<QBarRandomProvider> rps = filterInfinite(
rp -> rp.getScale() >= 2 && rp.getSecondaryScale() >= 0 && rp.getTertiaryScale() >= 2,
P.withScale(4).qbarRandomProviders()
);
for (QBarRandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("squarePolynomialMatrices(" + rp + ") = " + its(rp.squarePolynomialMatrices()));
}
}
private void demoRationalPolynomialMatrices_int_int() {
Iterable<Triple<QBarRandomProvider, Integer, Integer>> ts = P.triples(
filterInfinite(
rp -> rp.getScale() >= 3 && rp.getSecondaryScale() >= 0,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
),
P.withScale(4).naturalIntegersGeometric(),
P.withScale(4).naturalIntegersGeometric()
);
for (Triple<QBarRandomProvider, Integer, Integer> t : take(SMALL_LIMIT, ts)) {
System.out.println("rationalPolynomialMatrices(" + t.a + ", " + t.b + ", " + t.c + ") = " +
its(t.a.rationalPolynomialMatrices(t.b, t.c)));
}
}
private void demoRationalPolynomialMatrices() {
Iterable<QBarRandomProvider> rps = filterInfinite(
rp -> rp.getScale() >= 3 && rp.getSecondaryScale() >= 0 && rp.getTertiaryScale() >= 2,
P.withScale(4).qbarRandomProviders()
);
for (QBarRandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("rationalPolynomialMatrices(" + rp + ") = " + its(rp.rationalPolynomialMatrices()));
}
}
private void demoSquareRationalPolynomialMatrices() {
Iterable<QBarRandomProvider> rps = filterInfinite(
rp -> rp.getScale() >= 3 && rp.getSecondaryScale() >= 0 && rp.getTertiaryScale() >= 2,
P.withScale(4).qbarRandomProviders()
);
for (QBarRandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("squareRationalPolynomialMatrices(" + rp + ") = " +
its(rp.squareRationalPolynomialMatrices()));
}
}
private void demoPolynomials_int() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
),
P.withScale(4).rangeUpGeometric(-1)
);
for (Pair<QBarRandomProvider, Integer> p : take(MEDIUM_LIMIT, ps)) {
System.out.println("polynomials(" + p.a + ", " + p.b + ") = " + its(p.a.polynomials(p.b)));
}
}
private void demoPolynomials() {
Iterable<QBarRandomProvider> rps = filterInfinite(
rp -> rp.getScale() > 0 && rp.getSecondaryScale() >= 0,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
);
for (QBarRandomProvider rp : take(MEDIUM_LIMIT, rps)) {
System.out.println("polynomials(" + rp + ") = " + its(rp.polynomials()));
}
}
private void demoPolynomialsAtLeast() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = filterInfinite(
p -> p.a.getSecondaryScale() > p.b,
P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
),
P.withScale(4).rangeUpGeometric(-1)
)
);
for (Pair<QBarRandomProvider, Integer> p : take(MEDIUM_LIMIT, ps)) {
System.out.println("polynomialsAtLeast(" + p.a + ", " + p.b + ") = " + its(p.a.polynomialsAtLeast(p.b)));
}
}
private void demoPrimitivePolynomials_int() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
),
P.withScale(4).naturalIntegersGeometric()
);
for (Pair<QBarRandomProvider, Integer> p : take(MEDIUM_LIMIT, ps)) {
System.out.println("primitivePolynomials(" + p.a + ", " + p.b + ") = " +
its(p.a.primitivePolynomials(p.b)));
}
}
private void demoPrimitivePolynomials() {
Iterable<QBarRandomProvider> rps = filterInfinite(
rp -> rp.getScale() > 0 && rp.getSecondaryScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
);
for (QBarRandomProvider rp : take(MEDIUM_LIMIT, rps)) {
System.out.println("primitivePolynomials(" + rp + ") = " + its(rp.primitivePolynomials()));
}
}
private void demoPrimitivePolynomialsAtLeast() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = filterInfinite(
p -> p.a.getSecondaryScale() > p.b && p.a.getSecondaryScale() > 0,
P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
),
P.withScale(4).rangeUpGeometric(-1)
)
);
for (Pair<QBarRandomProvider, Integer> p : take(MEDIUM_LIMIT, ps)) {
System.out.println("primitivePolynomialsAtLeast(" + p.a + ", " + p.b + ") = " +
its(p.a.primitivePolynomialsAtLeast(p.b)));
}
}
private void demoPositivePrimitivePolynomials_int() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
),
P.withScale(4).naturalIntegersGeometric()
);
for (Pair<QBarRandomProvider, Integer> p : take(MEDIUM_LIMIT, ps)) {
System.out.println("positivePrimitivePolynomials(" + p.a + ", " + p.b + ") = " +
its(p.a.positivePrimitivePolynomials(p.b)));
}
}
private void demoPositivePrimitivePolynomials() {
Iterable<QBarRandomProvider> rps = filterInfinite(
rp -> rp.getScale() > 0 && rp.getSecondaryScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
);
for (QBarRandomProvider rp : take(MEDIUM_LIMIT, rps)) {
System.out.println("positivePrimitivePolynomials(" + rp + ") = " + its(rp.positivePrimitivePolynomials()));
}
}
private void demoPositivePrimitivePolynomialsAtLeast() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = filterInfinite(
p -> p.a.getSecondaryScale() > p.b && p.a.getSecondaryScale() > 0,
P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
),
P.withScale(4).rangeUpGeometric(-1)
)
);
for (Pair<QBarRandomProvider, Integer> p : take(MEDIUM_LIMIT, ps)) {
System.out.println("positivePrimitivePolynomialsAtLeast(" + p.a + ", " + p.b + ") = " +
its(p.a.positivePrimitivePolynomialsAtLeast(p.b)));
}
}
private void demoSquareFreePolynomials_int() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
),
P.withScale(4).naturalIntegersGeometric()
);
for (Pair<QBarRandomProvider, Integer> p : take(MEDIUM_LIMIT, ps)) {
System.out.println("squareFreePolynomials(" + p.a + ", " + p.b + ") = " +
its(p.a.squareFreePolynomials(p.b)));
}
}
private void demoSquareFreePolynomials() {
Iterable<QBarRandomProvider> rps = filterInfinite(
rp -> rp.getScale() > 0 && rp.getSecondaryScale() >= 0,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
);
for (QBarRandomProvider rp : take(MEDIUM_LIMIT, rps)) {
System.out.println("squareFreePolynomials(" + rp + ") = " + its(rp.squareFreePolynomials()));
}
}
private void demoSquareFreePolynomialsAtLeast() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = filterInfinite(
p -> p.a.getSecondaryScale() > p.b && p.a.getSecondaryScale() >= 0,
P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
),
P.withScale(4).rangeUpGeometric(-1)
)
);
for (Pair<QBarRandomProvider, Integer> p : take(MEDIUM_LIMIT, ps)) {
System.out.println("squareFreePolynomialsAtLeast(" + p.a + ", " + p.b + ") = " +
its(p.a.squareFreePolynomialsAtLeast(p.b)));
}
}
private void demoPositivePrimitiveSquareFreePolynomials_int() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
),
P.withScale(4).naturalIntegersGeometric()
);
for (Pair<QBarRandomProvider, Integer> p : take(MEDIUM_LIMIT, ps)) {
System.out.println("positivePrimitiveSquareFreePolynomials(" + p.a + ", " + p.b + ") = " +
its(p.a.positivePrimitiveSquareFreePolynomials(p.b)));
}
}
private void demoPositivePrimitiveSquareFreePolynomials() {
Iterable<QBarRandomProvider> rps = filterInfinite(
rp -> rp.getScale() > 0 && rp.getSecondaryScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
);
for (QBarRandomProvider rp : take(MEDIUM_LIMIT, rps)) {
System.out.println("positivePrimitiveSquareFreePolynomials(" + rp + ") = " +
its(rp.positivePrimitiveSquareFreePolynomials()));
}
}
private void demoPositivePrimitiveSquareFreePolynomialsAtLeast() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = filterInfinite(
p -> p.a.getSecondaryScale() > p.b && p.a.getSecondaryScale() > 0,
P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() > 0 && rp.getSecondaryScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
),
P.withScale(4).rangeUpGeometric(-1)
)
);
for (Pair<QBarRandomProvider, Integer> p : take(MEDIUM_LIMIT, ps)) {
System.out.println("positivePrimitiveSquareFreePolynomialsAtLeast(" + p.a + ", " + p.b + ") = " +
its(p.a.positivePrimitiveSquareFreePolynomialsAtLeast(p.b)));
}
}
private void demoIrreduciblePolynomials_int() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() > 0,
P.withScale(1).qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
),
P.withScale(4).naturalIntegersGeometric()
);
for (Pair<QBarRandomProvider, Integer> p : take(MEDIUM_LIMIT, ps)) {
System.out.println("irreduciblePolynomials(" + p.a + ", " + p.b + ") = " +
its(p.a.irreduciblePolynomials(p.b)));
}
}
private void demoIrreduciblePolynomials() {
Iterable<QBarRandomProvider> rps = filterInfinite(
rp -> rp.getScale() >= 2 && rp.getSecondaryScale() >= 2,
P.withScale(1).qbarRandomProvidersDefaultTertiaryScale()
);
for (QBarRandomProvider rp : take(MEDIUM_LIMIT, rps)) {
System.out.println("irreduciblePolynomials(" + rp + ") = " + its(rp.irreduciblePolynomials()));
}
}
private void demoIrreduciblePolynomialsAtLeast() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = filterInfinite(
p -> p.a.getSecondaryScale() > p.b && p.a.getSecondaryScale() > 0,
P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() >= 2 && rp.getSecondaryScale() >= 2,
P.withScale(1).qbarRandomProvidersDefaultTertiaryScale()
),
P.withScale(4).rangeUpGeometric(-1)
)
);
for (Pair<QBarRandomProvider, Integer> p : take(MEDIUM_LIMIT, ps)) {
System.out.println("irreduciblePolynomialsAtLeast(" + p.a + ", " + p.b + ") = " +
its(p.a.irreduciblePolynomialsAtLeast(p.b)));
}
}
private void demoRationalPolynomials_int() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() >= 3,
P.withScale(4).qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
),
P.withScale(4).rangeUpGeometric(-1)
);
for (Pair<QBarRandomProvider, Integer> p : take(MEDIUM_LIMIT, ps)) {
System.out.println("rationalPolynomials(" + p.a + ", " + p.b + ") = " + its(p.a.rationalPolynomials(p.b)));
}
}
private void demoRationalPolynomials() {
Iterable<QBarRandomProvider> rps = filterInfinite(
rp -> rp.getScale() >= 3 && rp.getSecondaryScale() >= 0,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
);
for (QBarRandomProvider rp : take(MEDIUM_LIMIT, rps)) {
System.out.println("rationalPolynomials(" + rp + ") = " + its(rp.rationalPolynomials()));
}
}
private void demoRationalPolynomialsAtLeast() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = filterInfinite(
p -> p.a.getSecondaryScale() > p.b,
P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() >= 3,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
),
P.withScale(4).rangeUpGeometric(-1)
)
);
for (Pair<QBarRandomProvider, Integer> p : take(MEDIUM_LIMIT, ps)) {
System.out.println("rationalPolynomialsAtLeast(" + p.a + ", " + p.b + ") = " +
its(p.a.rationalPolynomialsAtLeast(p.b)));
}
}
private void demoMonicRationalPolynomials_int() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
),
P.withScale(4).naturalIntegersGeometric()
);
for (Pair<QBarRandomProvider, Integer> p : take(SMALL_LIMIT, ps)) {
System.out.println("monicRationalPolynomials(" + p.a + ", " + p.b + ") = " +
its(p.a.monicRationalPolynomials(p.b)));
}
}
private void demoMonicRationalPolynomials() {
Iterable<QBarRandomProvider> rps = filterInfinite(
rp -> rp.getScale() > 0 && rp.getSecondaryScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
);
for (QBarRandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("monicRationalPolynomials(" + rp + ") = " + its(rp.monicRationalPolynomials()));
}
}
private void demoMonicRationalPolynomialsAtLeast() {
Iterable<Pair<QBarRandomProvider, Integer>> ps = filterInfinite(
p -> p.a.getSecondaryScale() > p.b && p.a.getSecondaryScale() > 0,
P.pairsSquareRootOrder(
filterInfinite(
rp -> rp.getScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultTertiaryScale()
),
P.withScale(4).rangeUpGeometric(-1)
)
);
for (Pair<QBarRandomProvider, Integer> p : take(SMALL_LIMIT, ps)) {
System.out.println("monicRationalPolynomialsAtLeast(" + p.a + ", " + p.b + ") = " +
its(p.a.monicRationalPolynomialsAtLeast(p.b)));
}
}
private void demoVariables() {
Iterable<QBarRandomProvider> rps = filterInfinite(
s -> s.getScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
);
for (QBarRandomProvider rp : take(MEDIUM_LIMIT, rps)) {
System.out.println("variables(" + rp + ") = " + its(rp.variables()));
}
}
private void demoMonomialOrders() {
for (QBarRandomProvider rp : take(MEDIUM_LIMIT, P.qbarRandomProvidersDefault())) {
System.out.println("monomialOrders(" + rp + ") = " + its(rp.monomialOrders()));
}
}
private void demoExponentVectors() {
Iterable<QBarRandomProvider> rps = filterInfinite(
s -> s.getScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
);
for (QBarRandomProvider rp : take(MEDIUM_LIMIT, rps)) {
System.out.println("exponentVectors(" + rp + ") = " + its(rp.exponentVectors()));
}
}
private void demoExponentVectors_List_Variable() {
Iterable<Pair<QBarRandomProvider, List<Variable>>> ps = P.pairs(
filterInfinite(
s -> s.getScale() > 0,
P.withScale(4).qbarRandomProvidersDefaultSecondaryAndTertiaryScale()
),
P.subsets(P.variables())
);
for (Pair<QBarRandomProvider, List<Variable>> p : take(SMALL_LIMIT, ps)) {
System.out.println("exponentVectors(" + p.a + ", " + p.b + ") = " + its(p.a.exponentVectors(p.b)));
}
}
private void demoMultivariatePolynomials() {
Iterable<QBarRandomProvider> rps = filterInfinite(
s -> s.getScale() >= 2 && s.getSecondaryScale() > 0 && s.getTertiaryScale() >= 2,
P.withScale(4).qbarRandomProviders()
);
for (QBarRandomProvider rp : take(MEDIUM_LIMIT, rps)) {
System.out.println("multivariatePolynomials(" + rp + ") = " + its(rp.multivariatePolynomials()));
}
}
private void demoMultivariatePolynomials_List_Variable() {
Iterable<Pair<QBarRandomProvider, List<Variable>>> ps = P.pairs(
filterInfinite(
s -> s.getScale() >= 2 && s.getSecondaryScale() > 0 && s.getTertiaryScale() >= 2,
P.withScale(4).qbarRandomProviders()
),
P.subsets(P.variables())
);
for (Pair<QBarRandomProvider, List<Variable>> p : take(SMALL_LIMIT, ps)) {
System.out.println("multivariatePolynomials(" + p.a + ", " + p.b + ") = " +
its(p.a.multivariatePolynomials(p.b)));
}
}
}
|
package org.animotron.games.web;
import org.animotron.ATest;
import org.animotron.expression.Expression;
import org.animotron.expression.JExpression;
import org.animotron.statement.compare.WITH;
import org.animotron.statement.query.ANY;
import org.animotron.statement.query.GET;
import org.animotron.statement.relation.USE;
import org.junit.Test;
import static org.animotron.expression.AnimoExpression.__;
import static org.animotron.expression.JExpression._;
import static org.animotron.expression.JExpression.value;
/**
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
* @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a>
*
*/
public class CurrentGetWebFrameworkTest extends ATest {
private Expression query(String site, String service) {
return new JExpression(
_(ANY._, "service",
_(WITH._, "server-name", value(site)),
_(USE._, service)
)
);
}
private Expression mime(Expression query) {
return new JExpression(_(GET._, "type", _(GET._, "mime-type", _(query))));
}
@Test
public void test() throws Throwable {
__(
"the foo-site (site) (server-name \"foo.com\") (weak-use foo)",
"the bar-site (site) (server-name \"bar.com\") (weak-use bar)",
"the text-html (mime-type) (type \"text/html\") (extension \"htm\" \"html\")",
"the html-page (mime-tipe text-html) (\\html (\\head \\title get title) (\\body any layout))",
"the hello-foo (html-page) (foo-site, root) (title \"hello foo\") (content \"foo foo foo\")",
"the hello-bar (html-page) (bar-site, root) (title \"hello bar\") (content \"bar bar bar\")",
"the zzz (html-page) (all site) (title \"hello zzz\") (content \"zzz zzz zzz\")",
"the yyy (html-page) (all site) (title \"hello yyy\") (content \"yyy yyy yyy\")",
"the foo-root-layout (layout, foo, root) (\\h1 get title) (\\p get content)",
"the bar-root-layout (layout, bar, root) (\\h2 get title) (\\div get content)",
"the qLayout (layout, zzz, yyy) (\\h3 get title) (\\span get content)"
);
//root service
Expression fooRoot = query("foo.com", "root");
//this service wasn't defined, so root should be returned?
Expression fooXxx = query("foo.com", "xxx");
//this service defined, but do not allowed by site
Expression fooYyy = query("foo.com", "yyy");
Expression barRoot = query("bar.com", "root");
Expression barZzz = query("bar.com", "zzz");
Expression barYyy = query("bar.com", "yyy");
Expression barURI = query("bar.com", "uri");
assertStringResult(mime(fooRoot), "text/html");
assertStringResult(mime(fooXxx), "");
assertStringResult(mime(fooYyy), "");
assertStringResult(mime(barRoot), "text/html");
assertStringResult(mime(barZzz), "");
assertStringResult(mime(barYyy), "");
assertStringResult(mime(barURI), "");
assertHtmlResult(fooRoot,
"<html><head><title>hello foo</title></head><body><h1>hello foo</h1><p>foo foo foo</p></body></html>");
assertHtmlResult(fooXxx,
"<html><head><title>hello foo</title></head><body><h1>hello foo</h1><p>foo foo foo</p></body></html>");
assertHtmlResult(fooYyy, "");
assertHtmlResult(barRoot,
"<html><head><title>hello bar</title></head><body><h2>hello bar</h2><div>bar bar bar</div></body></html>");
assertHtmlResult(barZzz,
"");
assertHtmlResult(barYyy,
"<html><head><title>hello yyy</title></head><body><h3>hello yyy</h3><span>yyy yyy yyy</span></body></html>");
//wrong!!!
assertHtmlResult(barURI,
"<html><head><title>hello bar</title></head><body><h2>hello bar</h2><div>bar bar bar</div></body></html><html><head><title>hello yyy</title></head><body><h2>hello yyy</h2><div>yyy yyy yyy</div></body></html>");
}
}
|
package org.jitsi.meet.test.pageobjects.web;
import org.jitsi.meet.test.util.*;
import org.jitsi.meet.test.web.*;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.*;
import java.util.*;
public class SettingsDialog
{
/**
* Selectors to be used for finding WebElements within the
* {@link SettingsDialog}. While most are CSS selectors, some are XPath
* selectors, and prefixed as such, due to the extra functionality XPath
* provides.
*/
private final static String DISPLAY_NAME_FIELD
= "#setDisplayName";
private final static String EMAIL_FIELD = "#setEmail";
private final static String FOLLOW_ME_CHECKBOX = "[name='follow-me']";
private final static String MORE_TAB_CONTENT = ".more-tab";
private final static String SETTINGS_DIALOG = ".settings-dialog";
private final static String SETTINGS_DIALOG_CONTENT = ".settings-pane";
private final static String START_AUDIO_MUTED_CHECKBOX
= "[name='start-audio-muted']";
private final static String START_VIDEO_MUTED_CHECKBOX
= "[name='start-video-muted']";
private final static String X_PATH_MORE_TAB
/**
* The participant.
*/
private final WebParticipant participant;
/**
* Initializes a new {@link SettingsDialog} instance.
* @param participant the participant for this {@link SettingsDialog}.
*/
public SettingsDialog(WebParticipant participant)
{
this.participant = Objects.requireNonNull(participant, "participant");
}
/**
* Clicks the cancel button on the settings dialog to close the dialog
* without saving any changes.
*/
public void close()
{
ModalDialogHelper.clickCancelButton(participant.getDriver());
}
/**
* Returns the participant's display name displayed in the settings dialog.
*
* @return {@code string} The display name displayed in the settings dialog.
*/
public String getDisplayName()
{
openProfileTab();
return participant.getDriver()
.findElement(By.cssSelector(DISPLAY_NAME_FIELD))
.getAttribute("value");
}
/**
* Returns the participant's email displayed in the settings dialog.
*
* @return {@code string} The email displayed in the settings dialog.
*/
public String getEmail()
{
openProfileTab();
return participant.getDriver()
.findElement(By.cssSelector(EMAIL_FIELD))
.getAttribute("value");
}
/**
* Returns whether or not the Follow Me checkbox is visible to the user in
* the settings dialog.
*
* @return {@code boolean} True if the Follow Me checkbox is visible to the
* user.
*/
public boolean isFollowMeDisplayed()
{
openMoreTab();
WebDriver driver = participant.getDriver();
List<WebElement> followMeCheckboxes
= driver.findElements(By.cssSelector(FOLLOW_ME_CHECKBOX));
return followMeCheckboxes.size() > 0;
}
/**
* Selects the More tab to be displayed.
*/
public void openMoreTab()
{
openTab(X_PATH_MORE_TAB);
TestUtils.waitForElementBy(
participant.getDriver(),
By.cssSelector(MORE_TAB_CONTENT),
5);
}
/**
* Selects the Profile tab to be displayed.
*/
public void openProfileTab()
{
openTab(X_PATH_PROFILE_TAB);
}
/**
* Enters the passed in email into the email field.
*/
public void setEmail(String email)
{
openProfileTab();
WebDriver driver = participant.getDriver();
driver.findElement(By.cssSelector(EMAIL_FIELD)).sendKeys(email);
}
/**
* Sets the option for having other participants automatically perform the
* actions performed by the local participant.
*/
public void setFollowMe(boolean enable)
{
openMoreTab();
setCheckbox(FOLLOW_ME_CHECKBOX, enable);
}
/**
* Sets the option for having participants join as audio muted.
*/
public void setStartAudioMuted(boolean enable)
{
openMoreTab();
setCheckbox(START_AUDIO_MUTED_CHECKBOX, enable);
}
/**
* Sets the option for having participants join as video muted.
*/
public void setStartVideoMuted(boolean enable)
{
openMoreTab();
setCheckbox(START_VIDEO_MUTED_CHECKBOX, enable);
}
/**
* Clicks the OK button on the settings dialog to close the dialog
* and save any changes made.
*/
public void submit()
{
ModalDialogHelper.clickOKButton(participant.getDriver());
}
/**
* Waits for the settings dialog to be visible.
*/
public void waitForDisplay()
{
TestUtils.waitForElementBy(
participant.getDriver(),
By.cssSelector(SETTINGS_DIALOG),
5);
TestUtils.waitForElementBy(
participant.getDriver(),
By.cssSelector(SETTINGS_DIALOG_CONTENT),
5);
}
/**
* Displays a specific tab in the settings dialog.
*/
private void openTab(String xPathSelectorForTab)
{
WebDriver driver = participant.getDriver();
TestUtils.waitForElementBy(driver, By.xpath(xPathSelectorForTab), 5);
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(
By.xpath(xPathSelectorForTab)));
element.click();
}
/**
* Sets the state checked/selected of a checkbox in the settings dialog.
*/
private void setCheckbox(String cssSelector, boolean check)
{
WebDriver driver = participant.getDriver();
TestUtils.waitForElementBy(driver, By.cssSelector(cssSelector), 5);
WebElement checkbox = driver.findElement(By.cssSelector(cssSelector));
boolean isChecked = checkbox.isSelected();
if (check != isChecked)
{
((JavascriptExecutor)driver).executeScript("arguments[0].click();", checkbox);
}
}
}
|
package org.makersoft.shards.unit.persistence;
import java.util.List;
import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.makersoft.shards.domain.User;
import org.makersoft.shards.mapper.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
@TransactionConfiguration(transactionManager = "multiDataSourcesTransactionManager", defaultRollback = false)
@ActiveProfiles("test")
public class UserDaoTests {
@Autowired(required=true)
private UserDao userDao;
private static String firstId;
public static int rowsCount = 10000;
@Test
@Transactional
public void testInsert() throws Exception{
for(int i = 0; i < rowsCount; i++){
User user = new User();
user.setUsername("makersoft" + i);
user.setPassword("makersoft" + i);
if(i % 2 == 0){
user.setGender(User.SEX_MALE);
}else{
user.setGender(User.SEX_FEMALE);
}
userDao.insertUser(user);
if(i == 0){
firstId = user.getId();
System.out.println(firstId);
}
}
}
@Test
@Transactional
public void testUpdate() throws Exception{
User user = new User();
user.setPassword("www.makersoft.org");
int rows = userDao.udpateUser(user);
Assert.assertEquals(rowsCount, rows);
}
@Test
@Transactional
public void testUpdateById() throws Exception {
Assert.assertNotNull(firstId);
User user = new User();
user.setId(firstId);
user.setUsername("username");
user.setPassword("password");
int rows = userDao.updateById(user);
Assert.assertEquals(1, rows);
}
@Test
@Transactional(readOnly = true)
public void testGetAllCount() throws Exception{
int count = userDao.getAllCount();
Assert.assertEquals(rowsCount, count);
}
@Test
@Transactional(readOnly = true)
public void testFindAll() throws Exception{
List<User> users = userDao.findAll();
Assert.assertEquals(rowsCount, users.size());
}
@Test
@Transactional(readOnly = true)
public void testFindByGender() throws Exception{
List<User> users = userDao.findByGender(User.SEX_MALE);
Assert.assertEquals(rowsCount / 2, users.size());
}
@Test
@Transactional(readOnly = true)
public void testGetById() throws Exception{
User user = userDao.getById(firstId);
Assert.assertNotNull(user);
}
@Test
@Rollback
@Transactional
public void testDeleteById() throws Exception{
int rows = userDao.deleteById(firstId);
Assert.assertEquals(1, rows);
}
@Test
@Transactional
public void testDelete() throws Exception{
int rows = userDao.deleteAll();
Assert.assertEquals(rowsCount, rows);
}
}
|
package org.rundeck.api.parser;
import org.dom4j.Document;
import org.junit.Assert;
import org.junit.Test;
import org.rundeck.api.domain.*;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
public class WorkflowStepStateParserTest {
@Test
public void testParse1() {
InputStream input = getClass().getResourceAsStream("execution-state1.xml");
Document document = ParserHelper.loadDocument(input);
WorkflowStepState stepState = new WorkflowStepStateParser().parseXmlNode(document.selectSingleNode
("/result/executionState/steps/step[1]"));
Assert.assertNotNull(stepState);
Assert.assertEquals(true, stepState.isNodeStep());
Assert.assertEquals(null, stepState.getSubWorkflow());
Assert.assertNotNull(stepState.getNodeStates());
Assert.assertEquals(3, stepState.getNodeStates().size());
Assert.assertEquals("1", stepState.getStepContextId());
Assert.assertEquals(1, stepState.getStepNum());
Assert.assertEquals(1390066159000L, stepState.getStartTime().getTime());
Assert.assertEquals(1390066160000L, stepState.getEndTime().getTime());
Assert.assertEquals(1390066160000L, stepState.getUpdateTime().getTime());
Assert.assertEquals(RundeckWFExecState.SUCCEEDED, stepState.getExecutionState());
List<String> expectedTargetNodes = Arrays.asList(
"node-111.qa.subgroup.mycompany.com",
"node-6.qa.subgroup.mycompany.com",
"node-14.qa.subgroup.mycompany.com"
);
int i = 0;
for (String s : expectedTargetNodes) {
Assert.assertTrue(stepState.getNodeStates().containsKey(s));
WorkflowStepContextState workflowStepContextState = stepState.getNodeStates().get(s);
Assert.assertEquals("1", workflowStepContextState.getStepContextId());
Assert.assertEquals(1, workflowStepContextState.getStepNum());
Assert.assertEquals(1390066159000L + (i * 1000), workflowStepContextState.getStartTime().getTime());
Assert.assertEquals(1390066159000L + (i * 1000), workflowStepContextState.getEndTime().getTime());
Assert.assertEquals(1390066159000L + (i * 1000), workflowStepContextState.getUpdateTime().getTime());
Assert.assertEquals(RundeckWFExecState.SUCCEEDED, workflowStepContextState.getExecutionState());
i++;
}
}
@Test
public void testParseRunning1() {
InputStream input = getClass().getResourceAsStream("execution-state2.xml");
Document document = ParserHelper.loadDocument(input);
WorkflowStepState stepState = new WorkflowStepStateParser().parseXmlNode(document.selectSingleNode
("/result/executionState/steps/step[1]"));
Assert.assertNotNull(stepState);
Assert.assertEquals(true, stepState.isNodeStep());
Assert.assertEquals(null, stepState.getSubWorkflow());
Assert.assertEquals("1", stepState.getStepContextId());
Assert.assertEquals(1, stepState.getStepNum());
Assert.assertNotNull(stepState.getNodeStates());
Assert.assertEquals(1390066061000L, stepState.getStartTime().getTime());
Assert.assertEquals(1390066066000L, stepState.getEndTime().getTime());
Assert.assertEquals(1390066061000L, stepState.getUpdateTime().getTime());
Assert.assertEquals(RundeckWFExecState.SUCCEEDED, stepState.getExecutionState());
HashSet<String> expectedTargetNodes = new HashSet<String>(Arrays.asList(
"dignan"
));
WorkflowStepContextState workflowStepContextState = stepState.getNodeStates().get("dignan");
Assert.assertEquals("1", workflowStepContextState.getStepContextId());
Assert.assertEquals(1, workflowStepContextState.getStepNum());
Assert.assertEquals(1390066061000L, workflowStepContextState.getStartTime().getTime());
Assert.assertEquals(1390066066000L, workflowStepContextState.getEndTime().getTime());
Assert.assertEquals(1390066066000L, workflowStepContextState.getUpdateTime().getTime());
Assert.assertEquals(RundeckWFExecState.SUCCEEDED, workflowStepContextState.getExecutionState());
}
@Test
public void testParseRunning2() {
InputStream input = getClass().getResourceAsStream("execution-state2.xml");
Document document = ParserHelper.loadDocument(input);
WorkflowStepState stepState = new WorkflowStepStateParser().parseXmlNode(document.selectSingleNode
("/result/executionState/steps/step[2]"));
Assert.assertNotNull(stepState);
Assert.assertEquals(false, stepState.isNodeStep());
Assert.assertNotNull(stepState.getSubWorkflow());
Assert.assertNull(stepState.getNodeStates());
Assert.assertEquals("2", stepState.getStepContextId());
Assert.assertEquals(2, stepState.getStepNum());
Assert.assertEquals(1390066066000L, stepState.getStartTime().getTime());
Assert.assertNull(stepState.getEndTime());
Assert.assertEquals(1390066066000L, stepState.getUpdateTime().getTime());
Assert.assertEquals(RundeckWFExecState.RUNNING, stepState.getExecutionState());
//sub workflow
WorkflowState subWorkflow = stepState.getSubWorkflow();
Assert.assertEquals(1,subWorkflow.getSteps().size());
Assert.assertEquals(1,subWorkflow.getTargetNodes().size());
WorkflowStepState stepState1 = subWorkflow.getSteps().get(0);
Assert.assertEquals(true, stepState1.isNodeStep());
Assert.assertNull(stepState1.getSubWorkflow());
Assert.assertNotNull(stepState1.getNodeStates());
Assert.assertEquals("2/1", stepState1.getStepContextId());
Assert.assertEquals(1, stepState1.getStepNum());
Assert.assertEquals(1390066067000L, stepState1.getStartTime().getTime());
Assert.assertNull(stepState1.getEndTime());
Assert.assertEquals(1390066067000L, stepState1.getUpdateTime().getTime());
Assert.assertEquals(RundeckWFExecState.RUNNING, stepState1.getExecutionState());
}
}
|
package org.sinmetal.controller;
import org.slim3.tester.*;
import com.google.appengine.tools.development.testing.*;
/**
* UnitTestControllerTestCase
*
* @author sinmetal
*
*/
public abstract class AbstructControllerTestCase extends ControllerTestCase {
LocalServiceTestHelper helper;
@Override
public void setUp() throws Exception {
LocalDatastoreServiceTestConfig dsConfig = new LocalDatastoreServiceTestConfig();
dsConfig.setApplyAllHighRepJobPolicy();
dsConfig.setNoStorage(true);
dsConfig.setNoIndexAutoGen(true);
LocalMemcacheServiceTestConfig memcacheConfig = new LocalMemcacheServiceTestConfig();
LocalSearchServiceTestConfig ssConfig = new LocalSearchServiceTestConfig()
.setPersistent(false);
LocalBlobstoreServiceTestConfig blobConfig = new LocalBlobstoreServiceTestConfig();
LocalFileServiceTestConfig fileConfig = new LocalFileServiceTestConfig();
helper = new LocalServiceTestHelper(dsConfig, memcacheConfig, ssConfig,
blobConfig, fileConfig);
helper.setUp();
super.setUp();
}
@Override
public void tearDown() throws Exception {
super.tearDown();
helper.tearDown();
}
}
|
package hr.fer.zemris.vhdllab.applets.simulations;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Arrays;
import javax.swing.JPanel;
/**
* Skala uzima vrijednosti koje generira VcdParser i vrsi sve proracune kod
* event-hendlanja. Prilikom svakog povecanja proracunava trajanje valnih
* oblika u pikselima.
*
* @author Boris Ozegovic
*/
class Scale extends JPanel
{
private static final long serialVersionUID = -4934785363261778378L;
/**
* Konstanta s kojom se mnozi trenutne vrijednosti ako je mjerna jedinica u
* femto sekundama
*/
private final byte FEMTO_SECONDS = 1;
/**
* Konstanta s kojom se mnozi trenutne vrijednosti ako je mjerna jedinica u
* pico sekundama
*/
private final double PICO_SECONDS = 1e-3;
/**
* Konstanta s kojom se mnozi trenutne vrijednosti ako je mjerna jedinica u
* nano sekundama
*/
private final double NANO_SECONDS = 1e-6;
/**
* Konstanta s kojom se mnozi trenutne vrijednosti ako je mjerna jedinica u
* micro sekundama
*/
private final double MICRO_SECONDS = 1e-9;
/**
* Konstanta s kojom se mnozi trenutne vrijednosti ako je mjerna jedinica u
* mili sekundama
*/
private final double MILI_SECONDS = 1e-12;
/**
* Konstanta s kojom se mnozi trenutne vrijednosti ako je mjerna jedinica u
* sekundama
*/
private final double SECONDS = 1e-15;
/** Razmak izmedu dvije tocke na skali je uvijek 100 piksela */
private final int SCALE_STEP_IN_PIXELS = 100;
/** Visina skale */
private final int SCALE_HEIGHT = 30;
/** Piksel na kojem pocinje iscrtavanje skale */
private int SCALE_START_POINT_IN_PIXELS = 0;;
/** Svaki vrijednost na skali pocinje od 19. piksela */
private final int SCALE_VALUE_YAXIS = 19;
/** Os pocinje od 4. piksela */
private final int SCALE_MAIN_LINE_YAXIS = 4;
/** Svaka crtica pocinje od 2. piksela */
private final int SCALE_TAG_LINE_YSTART = 2;
/** Svaka crtica zavrsava na 6. pikselu */
private final int SCALE_TAG_LINE_YEND = 6;
/** Tocke u kojima nastaju promjene vrijednosti signala */
private long[] transitionPoints;
/** GHDL simulator generira sve u femtosekundama */
private double[] durationsInFemtoSeconds;
/** Trajanje pojedenih intervala u vremenskoj jedinici */
private int[] durationsInTime;
/** Trajanje u pikselima koje id direktno za crtanje valnih oblika */
private int[] durationsInPixels;
/** Minimalna vrijednost trajanja signala izemdu dvije promjene */
private int minimumDurationInTime;
/** Povecava/smanjuje skalu za neku vrijednost */
private double scaleFactor = 1f;
/** Povecava/smanjuje time/pixel faktor */
private double pixelFactor;
/** Ime mjerne jedinice */
private String measureUnitName;
/** Mjerna jedinica */
private double measureUnit;
/** U pikselima - odreduje tocno odredeni piksel na kojem skala zavrsava */
private int scaleEndPointInPixels;
/** Korak skale u vremenu, ovisno o scaleFactor */
private double scaleStepInTime;
/** Vrijednost koja se kumulativno povecava, ovisno o scaleStepInTime */
private double scaleValue;
/**
* Ovisno o trenutnom offsetu scrollbara. Ako je offset npr. 1350, onda se
* interno preracuna u 1300 i od 1300 se crta skala
*/
private int screenStartPointInPixels;
/**
* Podrazumijevana velicina ekrana - skale ne iscrtava automatski sve
* vrijednost vec vrsi proracuna na temelju offseta i iscrtava samo trenutnu
* velicinu komponente
*/
private int screenSizeInPixels;
/** ScreenStartPointInPixels + trenutna duljina komponente */
private int screenEndPointInPixels;
/** Sve podrzane mjerne jedinice **/
private final String[] units = {"fs", "ps", "ns", "us", "ms", "s", "ks", "ms"};
/** Offset trenutni */
private int offsetXAxis;
/** Boje */
private ThemeColor themeColor;
/**
* Constructor
*
* @param themeColor defaultna teme
*
*/
public Scale (ThemeColor themeColor)
{
this.themeColor = themeColor;
}
/**
* Postavlja vrijednosti potrebne za iscrtavanje skale
*
* @param results rezultati koje je parsirao GhdlResults
*/
public void setContent(GhdlResults results)
{
this.transitionPoints = results.getTransitionPoints();
durationsInFemtoSeconds = new double[transitionPoints.length - 1];
durationsInTime = new int[durationsInFemtoSeconds.length];
durationsInPixels = new int[durationsInFemtoSeconds.length];
for (int i = 0; i < durationsInFemtoSeconds.length; i++)
{
double operand1 = transitionPoints[i + 1];
double operand2 = transitionPoints[i];
durationsInFemtoSeconds[i] = operand1 - operand2;
/* crta pocetne valne oblike sa scaleFaktorom 1 */
drawDefaultWave();
}
}
/**
* Metoda koja crta pocetne oblike
*/
public void drawDefaultWave ()
{
/* radi lokalnu kopiju jer sortiranje mijenja poredak */
double[] temporaryDurations = durationsInFemtoSeconds.clone();
Arrays.sort(temporaryDurations);
/*
* nakon sortiranja minimalno se trajanje nalazi na prvom mjestu u polju
* i na temelju tog minimalnog trajanja odreduje pocetnu jedinicu (ns,
* ps, itd). Castanje zbog toga da ne produ znamenke iza dec. zareza.
* Pomocu string.length() izracunava broj znamenki i na temelju broj
* znamenki odreduje mjernu jedinicu. Odreduje se najmanja promjena, te
* se na temelju nje postavlja skala u najmanju jedinicu i mnozi ostatak s
* odgovarajucim 10^x faktorom.
* */
String minimumDuration = String.valueOf((int)temporaryDurations[0]);
//System.out.println("minimalna razlika je " + minimumDuration);
int numberOfEndZeroes = 0;
char[] tempArray = minimumDuration.toCharArray();
for (int i = tempArray.length - 1; i >= 0; i
if (tempArray[i] == '0') {
numberOfEndZeroes++;
} else {
break;
}
}
switch (numberOfEndZeroes)
{
case 0 :
case 1 :
case 2 :
measureUnitName = "fs";
measureUnit = FEMTO_SECONDS;
break;
case 3 :
case 4 :
case 5 :
measureUnitName = "ps";
measureUnit = PICO_SECONDS;
break;
case 6 :
case 7 :
case 8 :
measureUnitName = "ns";
measureUnit = NANO_SECONDS;
break;
case 9 :
case 10 :
case 11 :
measureUnitName = "us";
measureUnit = MICRO_SECONDS;
break;
case 12 :
case 13 :
case 14 :
measureUnitName = "ms";
measureUnit = MILI_SECONDS;
break;
case 15 :
case 16 :
case 17 :
measureUnitName = "s";
measureUnit = SECONDS;
break;
}
scaleEndPointInPixels = 0;
minimumDurationInTime = (int)(durationsInFemtoSeconds[0] * measureUnit);
for (int i = 0; i < durationsInTime.length; i++)
{
durationsInTime[i] = (int)(durationsInFemtoSeconds[i] * measureUnit);
if (durationsInTime[i] < minimumDurationInTime) {
minimumDurationInTime = durationsInTime[i];
}
scaleEndPointInPixels += durationsInTime[i];
}
scaleStepInTime = minimumDurationInTime;
pixelFactor = 100 / scaleStepInTime;
scaleEndPointInPixels *= pixelFactor;
}
/**
* Metoda koja se brine o trajanju piksela nakon event-hendlanja i o tocnom
* postavljanju scaleEndPointInPixels
*/
public void setDurationsInPixelsAfterZoom (double scaleFactor)
{
scaleStepInTime /= scaleFactor;
pixelFactor *= scaleFactor;
scaleEndPointInPixels = 0;
for (int i = 0; i < durationsInTime.length; i++)
{
/* s istim 10^x faktorom mnozi se cijelo vrijeme */
durationsInTime[i] = (int)(durationsInFemtoSeconds[i] * measureUnit);
scaleEndPointInPixels += durationsInTime[i];
}
scaleEndPointInPixels *= pixelFactor;
int i = 0;
for (int interval : durationsInTime) {
durationsInPixels[i++] = (int)(interval * pixelFactor);
}
this.scaleFactor *= scaleFactor;
}
/**
* Getter trajanje u pikselima za valne oblike
*/
public int[] getDurationInPixels()
{
int i = 0;
for (int interval : durationsInTime) {
durationsInPixels[i++] = (int)(interval * pixelFactor);
}
return durationsInPixels;
}
/**
* Setter postavlja scaleFactor
*
* @param scaleFactor Zeljeni faktor
*/
public void setScaleFactor (float scaleFactor)
{
this.scaleFactor = scaleFactor;
}
/**
* Vraca trenutni scale faktor
*/
public double getScaleFactor ()
{
return scaleFactor;
}
/**
* Getter koji je potreban event-hendleru za precizno oznacavanje pozicije
*/
public String getMeasureUnitName ()
{
return measureUnitName;
}
/**
* Setter koji postavlja horizontalni offset u ovisnosti i scrollbaru
*
* @param offset Zeljeni offset
*/
public void setHorizontalOffset (int offset)
{
this.offsetXAxis = offset;
}
/**
* Trenutni horizontalni offset
*/
public int getHorizontalOffset ()
{
return offsetXAxis;
}
/**
* Getter koji daje krajnju tocku u pikselima, potreban za postavljanje nove
* vrijednosti scrollbara prilikom povecanja/smanjenja
*/
public int getScaleEndPointInPixels ()
{
return scaleEndPointInPixels;
}
/**
* Getter koji daje trenutnu vrijednost skale u vremenu (npr. 345 ns na 100
* piksela)
*/
public double getScaleStepInTime ()
{
return scaleStepInTime;
}
/**
* Preferirane dimenzije
*/
public Dimension getPreferredSize ()
{
return new Dimension(scaleEndPointInPixels, SCALE_HEIGHT);
}
/**
* Crtanje komponente
*/
public void paintComponent(Graphics g)
{
super.paintComponent(g);
setBackground(themeColor.getScale());
g.setColor(themeColor.getLetters());
/*
* Bilo koja vrijednost postavlja se na visekratnik broja 100. Znaci, ako je
* offset bio 1450, stavit ce 1400 i poceti crtati od 1400
*/
screenStartPointInPixels = offsetXAxis - offsetXAxis % 100;
/*
* Duljina trenutno aktivnog ekrana koji ce se iscrtati je duljina panela + 200
* Skala se ne crta kompletno, vec samo dio koji trenutno upada u offset
*/
screenSizeInPixels = getWidth() + 200;
screenEndPointInPixels = screenStartPointInPixels + screenSizeInPixels;
//System.out.println(" end screen " + screenEndPointInPixels);
//System.out.println(" end scale " + scaleEndPointInPixels);
//System.out.println(" facotr scale " + scaleFactor);
scaleFactor = Math.round(scaleFactor * 1e13d) / 1e13d;
/* scaleStepInTime ostaje fiksan jer je potrebna pocetna vrijednost */
double tempScaleStepInTime = scaleStepInTime;
/* x se mijenja u koracima od 100 piksela */
int x = 0;
/*
* samo ako je screenStartPointInPixels == 0 npr offset = 30, crta od
* nultog piksela, ali pomatnut ulijevo za offset, pa 30 pocinje od
* nultog piksela
*/
if (screenStartPointInPixels == SCALE_START_POINT_IN_PIXELS)
{
g.drawLine(x - offsetXAxis, SCALE_TAG_LINE_YSTART, x - offsetXAxis,
SCALE_TAG_LINE_YEND);
g.drawString("0", x - offsetXAxis, SCALE_VALUE_YAXIS);
x = SCALE_STEP_IN_PIXELS;
scaleValue = scaleStepInTime;
}
/*
* inace moze biti npr. 2500. scaleValue se odmah postavlja na pocetnu
* vrijednost u skladu s brojem od kojeg pocinje crtanje
*/
else
{
x = screenStartPointInPixels;
scaleValue = screenStartPointInPixels / 100 * scaleStepInTime;
}
int endPoint = screenEndPointInPixels;
g.drawLine(screenStartPointInPixels - offsetXAxis, SCALE_MAIN_LINE_YAXIS,
endPoint - offsetXAxis, SCALE_MAIN_LINE_YAXIS);
String tempMeasureUnitName = measureUnitName;
int endPointInPixels = endPoint;
while (x < endPointInPixels)
{
/* svaka se vrijednost zaokruzuje na 10 decimala */
scaleValue = Math.round(scaleValue * 1e13d) / 1e13d;
/*
* ako vrijednost prijede 1000, prebacuje se na sljedecu vecu
* jedinicu i ujedno smanjuje scaleStepInTime za 1000
*/
if (scaleValue >= 1000)
{
for (int i = 0; i < units.length; i++)
{
if (units[i].equals(tempMeasureUnitName) && i < units.length - 1)
{
tempMeasureUnitName = units[i + 1];
scaleValue /= 1000.0;
tempScaleStepInTime /= 1000;
break;
}
}
}
/* inace ako prijede u manju jedinicu */
else if (scaleValue < 1 && scaleValue != 0)
{
for (int i = 0; i < units.length; i++)
{
if (units[i].equals(tempMeasureUnitName) && i > 0)
{
tempMeasureUnitName = units[i - 1];
scaleValue *= 1000;
tempScaleStepInTime *= 1000;
break;
}
}
}
/*
* bez obzira na vrijednost x, sve se crta pomaknuto za offset, tako
* da na ekranu bude slika od nultog piksela
*/
g.drawLine(x - offsetXAxis, SCALE_TAG_LINE_YSTART,
x - offsetXAxis, SCALE_TAG_LINE_YEND);
g.drawString((Math.round(scaleValue * 1000000d) / 1000000.0d)
+ tempMeasureUnitName,
x -(((Math.round(scaleValue * 1000000d) / 1000000.0d)
+ tempMeasureUnitName).length() * 5) / 2
- offsetXAxis, SCALE_VALUE_YAXIS);
scaleValue += tempScaleStepInTime;
x += SCALE_STEP_IN_PIXELS;
}
}
}
|
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import uk.co.uwcs.choob.modules.Modules;
import uk.co.uwcs.choob.support.ChoobNoSuchCallException;
import uk.co.uwcs.choob.support.IRCInterface;
import uk.co.uwcs.choob.support.events.ChannelJoin;
import uk.co.uwcs.choob.support.events.ChannelKick;
import uk.co.uwcs.choob.support.events.ChannelPart;
import uk.co.uwcs.choob.support.events.Message;
import uk.co.uwcs.choob.support.events.NickChange;
import uk.co.uwcs.choob.support.events.PrivateNotice;
import uk.co.uwcs.choob.support.events.QuitEvent;
import uk.co.uwcs.choob.support.events.ServerResponse;
/**
* Provides authentication for users based on their nickname.
*
* A configurable authentication mechanism is available.
* UWCS NickServ and File based authentication are currently supported.
*
* @author benji
*/
public class NickServ
{
private final Modules mods;
private final IRCInterface irc;
private static final int TIMEOUT_SECONDS = 20;
private static final int CACHE_TIMEOUT_SECONDS = 600;
public String[] info()
{
return new String[] {
"Authentication checker plugin.",
"The Choob Team",
"choob@uwcs.co.uk",
"0.2"
};
}
//List of providers that can be configured to provider authentication
private Map<String, CanProvideAuth> authProviders = new HashMap<String, CanProvideAuth>();
public NickServ(final Modules mods, final IRCInterface irc)
{
this.mods = mods;
this.irc = irc;
authProviders.put("ALL", new AllAuthMethods(mods,irc));
authProviders.put("UWCS", new UWCSNickServInterpreter(mods, irc));
authProviders.put("FILE", new UserFileAuthProvider(mods, irc));
authProviders.put("MOZNET", new MoznetNickServInterpreter(mods, irc));
}
/**
* Check the authentication status for a user.
* @param nick The nick of the user to check
* @return -1 if unknown, 0 if not registered, 1 if not identified, 3 if identified
*/
public int apiStatus(final String nick)
{
return checkCached(nick).getId();
}
/**
* Check the authentication status for a user.
* @param nick The nick of the user to check
* @return true if authenticated, false otherwise.
*/
public boolean apiCheck( final String nick )
{
return apiCheck( nick, false );
}
/**
* Check the authentication status for a user.
* @param nick The nick of the user to check
* @param assumption The authentication status to assume
* @return true if authenticated, assumption otherwise
*/
public boolean apiCheck(final String nick, boolean assumption)
{
AuthStatus status = checkCached(nick);
if (status.getId() == -1)
return assumption;
return status.getId() >= 3;
}
/**
* Check the authentication status for either the user specified or the requestor.
* @param mes The request message
*/
public void commandCheck(final Message mes)
{
// Clear the cache, makes the command appear to behave as expected
// and the side effects will be hillarious when people try and debug.
final String nick = getNick(mes);
clearCache(nick);
final AuthStatus status = checkCached(nick);
irc.sendContextReply(mes, nick + " " + status.getExplanation());
}
/**
* Clear the authentication cache for either the user specified or the requestor.
* @param mes The request message.
*/
public void commandClearCache(final Message mes)
{
String nick = getNick(mes);
clearCache(nick);
irc.sendContextReply(mes, "Ok, cleared cache for " + nick);
}
private void clearCache(final String nick)
{
cache.remove(nick);
}
/**
* Obtains the nick to check from a message.
* @param mes The message requesting a check
* @return Either the paramstring, or the requestor's nick if no parameters were supplied.
*/
private final String getNick(Message mes)
{
final String nick = mods.util.getParamString( mes );
if (nick.length() == 0)
return mes.getNick();
else
return nick;
}
/**
* Perform a check for the authentication status of a particular user.
* Utilising the cache.
* @param nick The nick to check the authentication status of
* @return
*/
private AuthStatus checkCached(final String nick)
{
//First check the cache
return cache.get(nick, new Invokable<AuthStatus>()
{
//If we missed te cache we'll...
@Override
public AuthStatus invoke()
{
//Update the cache with the directly retrieved result
return cache.put(nick,checkDirectly(nick), new InvokableI<AuthStatus, Boolean>()
{
//Except where the result is unknown
@Override
public Boolean invoke(AuthStatus t)
{
return t instanceof UnknownStatus;
}
});
}
});
}
// Options - Allow the authentication provider to be changed at runtime
// to switch to userip list if nickserv is not available
// or to switch to another provider on another network
public String[] optionsGeneral = { "AuthProvider" };
public String[] optionsGeneralDefaults = { "ALL" };
/**
* Ensure the new option is a valid configured provider
* @param optionValue The option value to check
* @return true if it is a valid value, false otherwise
*/
public boolean optionCheckGeneralAuthProvider( final String optionValue ) { return authProviders.containsKey(optionValue); }
/**
* Looks up the currently configured authentication provider via the options plugin
* @return
*/
private CanProvideAuth getCurrentAuthProvider()
{
try
{
CanProvideAuth configured = authProviders.get(mods.plugin.callAPI("Options", "GetGeneralOption", optionsGeneral[0], optionsGeneralDefaults[0]).toString());
if (configured == null)
return authProviders.get(optionsGeneralDefaults[0]);
return configured;
} catch (ChoobNoSuchCallException e)
{
return authProviders.get(optionsGeneralDefaults[0]);
}
}
private final ChoobSucksScope.SingleBlockingQueueWithTimeOut<AbstractReplyHandler> commands = new ChoobSucksScope().new SingleBlockingQueueWithTimeOut<AbstractReplyHandler>(TIMEOUT_SECONDS);
/**
* A cache with fixed timeout to cache authentication results in.
*/
private final ChoobSucksScope.CacheWithTimeout<AuthStatus> cache = new ChoobSucksScope().new CacheWithTimeout<AuthStatus>(CACHE_TIMEOUT_SECONDS);
/**
* Check the authentication status of a user directly, without going through the cache
* @param nick The nick to check the status of
* @return The determined authentication status
*/
private AuthStatus checkDirectly(final String nick)
{
final CanProvideAuth nickserv = getCurrentAuthProvider();
try
{
return commands.put(new CanProvideAuthReplyHandler(nickserv)).doThis(new Action<Void>()
{
@Override
public void doWith(Void t)
{
nickserv.sendRequest(nick);
}
}).get(TIMEOUT_SECONDS, TimeUnit.SECONDS, new UnknownStatus());
} catch (InterruptedException e)
{
return new UnknownStatus();
} catch (ExecutionException e)
{
throw new RuntimeException(e);
} catch (TimeoutException e)
{
return new UnknownStatus();
}
}
/**
* When we recieve a private notice from the bot we want to pass it off to any pending authentication requests.
* @param mes The notice we recieved
*/
public void onPrivateNotice( final Message mes )
{
AbstractReplyHandler handler = commands.peek();
if (handler != null)
{
try
{
handler.handle(mes);
commands.remove(handler);
} catch (NotInterestedInReplyException e)
{
//wait for next private notice.
}
}
}
/**
* When we recieve a server response from the bot we want to pass it off to any pending authentication requests.
* @param resp The response we recieved
*/
public void onServerResponse(final ServerResponse resp)
{
AbstractReplyHandler handler = commands.peek();
if (handler != null)
{
try
{
handler.handle(resp);
commands.remove(handler);
} catch (NotInterestedInReplyException e)
{
//wait for next private notice.
}
}
}
// Expire old cache when appropriate...
public void onNickChange( final NickChange nc )
{
cache.remove(nc.getNick());
cache.remove(nc.getNewNick());
}
public void onJoin( final ChannelJoin cj )
{
cache.remove(cj.getNick());
}
public void onKick( final ChannelKick ck )
{
cache.remove(ck.getTarget());
}
public void onPart( final ChannelPart cp )
{
cache.remove(cp.getNick());
}
public void onQuit( final QuitEvent qe )
{
cache.remove(qe.getNick());
}
}
/**
* Interface auth providers need to implement.
* sendRequest will be called to send message off to nickserv/userip/whatever
* recieveReply overloads will be called with responses.
*
* @author benji
*/
interface CanProvideAuth
{
/**
* Sends a request to whatever providers your authentication on the IRC server
* @param nick
*/
public void sendRequest(String nick);
/**
* Recieve a private message reply
* @param mes The message recieved
* @return The authstatus if we could determine it.
* @throws NotInterestedInReplyException If this reply does not allow us to determine the authstatus of the user.
*/
public AuthStatus receiveReply(Message mes) throws NotInterestedInReplyException;
/**
* Recieve a server-response reply
* @param resp The response recieved
* @return The authstatus if we could determine it.
* @throws NotInterestedInReplyException If this reply does not allow us to determine the authstatus of the user.
*/
public AuthStatus receiveReply(ServerResponse resp) throws NotInterestedInReplyException;
}
/**
* An exception to indicate that we're not interested
* in a particular server reply or message. So our handler
* should stay in the queue
*
* @author benji
*/
class NotInterestedInReplyException extends Exception
{
}
/**
* Choob appears to dislike enums.
*
* An authentication status type.
*
* We need integer ids for backwards compatibility.
* We also need a human readable description.
*/
abstract class AuthStatus
{
private final int id;
private final String name;
protected AuthStatus(int id, String name)
{
this.id = id;
this.name = name;
}
public int getId()
{
return id;
}
public String getExplanation()
{
return "is " + name + " (" + id + ")!";
}
}
class UnknownStatus extends AuthStatus
{
public UnknownStatus()
{
super(-1,"unknown");
}
}
class NotRegisteredStatus extends AuthStatus
{
public NotRegisteredStatus()
{
super(0, "not registered");
}
}
class NotIdentifiedStatus extends AuthStatus
{
public NotIdentifiedStatus()
{
super(1,"not identified");
}
}
class AuthenticatedStatus extends AuthStatus
{
public AuthenticatedStatus()
{
super(3,"authed");
}
}
interface Action<T>
{
public void doWith(T t);
}
interface Invokable<T>
{
public T invoke();
}
interface InvokableI<T,R>
{
public R invoke(T t);
}
interface ReplyHandler extends DefaultFuture<AuthStatus>
{
public void handle(Message reply) throws NotInterestedInReplyException;
}
interface CanGetStatus
{
public AuthStatus replyToStatus(Message reply) throws NotInterestedInReplyException;
}
/**
* A Future that allows us to specify a default value instead of null when the timeout expires.
* @author benji
*/
interface DefaultFuture<T> extends Future<T>
{
public T get(long timeout, TimeUnit unit, T defaultValue) throws InterruptedException, ExecutionException, TimeoutException;
}
/**
* Handle replies from the server, delegating to abstract methods.
*
* Implements Future so that we can retreive the result of the authentication.
*
* @author benji
*/
abstract class AbstractReplyHandler implements ReplyHandler, CanGetStatus
{
private boolean canceled = false;
private final Object cancelledLock = new Object();
//We can only have one Future result
private final BlockingQueue<AuthStatus> queue = new ArrayBlockingQueue<AuthStatus>(1);
@Override
public abstract AuthStatus replyToStatus(Message reply) throws NotInterestedInReplyException;
public abstract AuthStatus replyToStatus(ServerResponse response) throws NotInterestedInReplyException;
/**
* Handles a message reply, converting the implemented handler to a Future result.
* @param reply The reply to handle
* @throws NotInterestedInReplyException If the implementation is not interested in this reply.
*/
@Override
public void handle(Message reply) throws NotInterestedInReplyException
{
try
{
queue.put(replyToStatus(reply));
} catch (InterruptedException e)
{
//meh
}
}
/**
* Handles a message reply, converting the implemented handler to a Future result.
* @param resp The reply to handle
* @throws NotInterestedInReplyException If the implementation is not interested in this reply.
*/
public void handle(ServerResponse resp) throws NotInterestedInReplyException
{
try
{
queue.put(replyToStatus(resp));
} catch (InterruptedException e)
{
//meh
}
}
/**
* @{@inheritDoc}
*/
@Override
public boolean cancel(boolean mayInterrupt)
{
if (this.isDone())
return false;
synchronized(cancelledLock)
{
return this.canceled = true;
}
}
/**
* @{@inheritDoc}
*/
@Override
public boolean isCancelled()
{
synchronized(cancelledLock)
{
return this.canceled;
}
}
/**
* @{@inheritDoc}
*/
@Override
public boolean isDone()
{
return queue.peek() != null;
}
/**
* @{@inheritDoc}
*/
@Override
public AuthStatus get() throws InterruptedException, ExecutionException
{
return queue.poll();
}
/**
* @{@inheritDoc}
*/
@Override
public AuthStatus get(long timeout , TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
{
return queue.poll(timeout, unit);
}
/**
* @{@inheritDoc}
*/
@Override
public AuthStatus get(long timeout, TimeUnit unit, AuthStatus defaultStatus) throws InterruptedException, ExecutionException, TimeoutException
{
AuthStatus status = get(timeout,unit);
if (status != null)
return status;
return defaultStatus;
}
}
/**
* Implementation of AbstractReplyHandler that delegates
* authentication to an auth provider
*
* @author benji
*/
class CanProvideAuthReplyHandler extends AbstractReplyHandler
{
private final CanProvideAuth nickserv;
public CanProvideAuthReplyHandler(CanProvideAuth nickserv)
{
this.nickserv = nickserv;
}
@Override
public AuthStatus replyToStatus(Message reply) throws NotInterestedInReplyException
{
return nickserv.receiveReply(reply);
}
@Override
public AuthStatus replyToStatus(ServerResponse reply) throws NotInterestedInReplyException
{
return nickserv.receiveReply(reply);
}
}
class PatternStatusPair
{
private final Pattern pattern;
private final AuthStatus status;
public PatternStatusPair(String pattern, AuthStatus status)
{
this.pattern = Pattern.compile(pattern);
this.status = status;
}
public Pattern getPattern()
{
return pattern;
}
public AuthStatus getStatus()
{
return status;
}
}
/**
* Default implementation of CanProvideAuth.
*
* Talks to UWCS Nickserv or Freenode Nickserv
*
* @author benji
*/
class UWCSNickServInterpreter implements CanProvideAuth
{
private final Modules mods;
private final IRCInterface irc;
/**
* Mappings of replies to statuses
*/
private final List<PatternStatusPair> statuses = Arrays.asList
(
new PatternStatusPair("^([^\\s]+?) is not registered.$", new NotRegisteredStatus()),
new PatternStatusPair("^Last seen.*?: now$", new AuthenticatedStatus()),
new PatternStatusPair("^Last seen.*?:.*", new NotIdentifiedStatus()),
new PatternStatusPair("^\\*\\*\\* End of Info \\*\\*\\*$", new UnknownStatus())
);
public UWCSNickServInterpreter(final Modules mods, final IRCInterface irc)
{
this.mods = mods;
this.irc = irc;
}
/**
* Ask Nickserv for info on a user.
* @param nick The user to request info for
*/
@Override
public void sendRequest(final String nick)
{
irc.sendMessage("NickServ", "INFO " + nick);
}
/**
* Tries to convert nickserv replies to an Authentication Status
* @param mes The message recieved back from the server
* @return The determined authentication status
* @throws NotInterestedInReplyException If we couldn't determine the authentication status from this message.
*/
@Override
public AuthStatus receiveReply(final Message mes) throws NotInterestedInReplyException
{
if ( ! (mes instanceof PrivateNotice) )
throw new NotInterestedInReplyException(); // Only interested in private notices
if ( ! mes.getNick().toLowerCase().equals( "nickserv" ) )
throw new NotInterestedInReplyException(); // Not from NickServ --> also don't care
final String reply = mes.getMessage();
for (PatternStatusPair status : statuses)
{
if (status.getPattern().matcher(reply).matches())
{
return status.getStatus();
}
}
throw new NotInterestedInReplyException();
}
/**
* For Nickserv we're not interested in server responses
* @param resp The response from the server
* @return Never
* @throws NotInterestedInReplyException Always
*/
@Override
public AuthStatus receiveReply(ServerResponse resp) throws NotInterestedInReplyException
{
throw new NotInterestedInReplyException();
}
}
/**
* Tries all authentication methods, to allow you to choose the one that works.
*/
class AllAuthMethods implements CanProvideAuth
{
private final Modules mods;
private final IRCInterface irc;
public AllAuthMethods(final Modules mods, final IRCInterface irc)
{
this.mods = mods;
this.irc = irc;
this.authMethods = Arrays.asList
(
new UWCSNickServInterpreter(mods,irc),
new MoznetNickServInterpreter(mods,irc),
new UserFileAuthProvider(mods,irc)
);
}
private final List<CanProvideAuth> authMethods;
@Override
public void sendRequest(final String nick)
{
for (CanProvideAuth auth : authMethods)
auth.sendRequest(nick);
}
@Override
public AuthStatus receiveReply(final Message mes) throws NotInterestedInReplyException
{
return new WithMultipleAuthProviders(authMethods)
{
@Override protected AuthStatus checkEach(CanProvideAuth auth) throws NotInterestedInReplyException
{
return auth.receiveReply(mes);
}
}.getResult();
}
@Override
public AuthStatus receiveReply(final ServerResponse resp) throws NotInterestedInReplyException
{
return new WithMultipleAuthProviders(authMethods)
{
@Override protected AuthStatus checkEach(CanProvideAuth auth) throws NotInterestedInReplyException
{
return auth.receiveReply(resp);
}
}.getResult();
}
abstract class WithMultipleAuthProviders
{
private final List<CanProvideAuth> authProviders;
private AuthStatus result = null;
public WithMultipleAuthProviders(List<CanProvideAuth> authProviders)
{
this.authProviders = authProviders;
for (CanProvideAuth auth : authMethods)
{
try
{
// continue until one provider claims it knows the status.
if (!((result = checkEach(auth)) instanceof UnknownStatus))
break;
} catch (NotInterestedInReplyException ex)
{
// ignore
}
}
}
public AuthStatus getResult() throws NotInterestedInReplyException
{
if (result == null)
throw new NotInterestedInReplyException();
return result;
}
protected abstract AuthStatus checkEach(CanProvideAuth auth) throws NotInterestedInReplyException;
}
}
/**
* Mozilla implementation of CanProvideAuth.
*
* Talks to Mozilla Nickserv
*
* @author benji
*/
class MoznetNickServInterpreter implements CanProvideAuth
{
private final Modules mods;
private final IRCInterface irc;
public MoznetNickServInterpreter(final Modules mods, final IRCInterface irc)
{
this.mods = mods;
this.irc = irc;
}
/**
* Mappings of replies to statuses
*/
private final List<PatternStatusPair> statuses = Arrays.asList
(
new PatternStatusPair("^STATUS.*0$", new NotRegisteredStatus()),
new PatternStatusPair("^STATUS.*3$", new AuthenticatedStatus()),
new PatternStatusPair("^STATUS.*2$", new NotIdentifiedStatus()),
new PatternStatusPair("^STATUS.*1$", new UnknownStatus())
);
/**
* Ask Nickserv for info on a user.
* @param nick The user to request info for
*/
@Override
public void sendRequest(final String nick)
{
irc.sendMessage("NickServ", "STATUS " + nick);
}
/**
* Tries to convert nickserv replies to an Authentication Status
* @param mes The message recieved back from the server
* @return The determined authentication status
* @throws NotInterestedInReplyException If we couldn't determine the authentication status from this message.
*/
@Override
public AuthStatus receiveReply(final Message mes) throws NotInterestedInReplyException
{
if ( ! (mes instanceof PrivateNotice) )
throw new NotInterestedInReplyException(); // Only interested in private notices
if ( ! mes.getNick().toLowerCase().equals( "nickserv" ) )
throw new NotInterestedInReplyException(); // Not from NickServ --> also don't care
final String reply = mes.getMessage();
for (PatternStatusPair status : statuses)
{
if (status.getPattern().matcher(reply).matches())
{
return status.getStatus();
}
}
throw new NotInterestedInReplyException();
}
/**
* For Nickserv we're not interested in server responses
* @param resp The response from the server
* @return Never
* @throws NotInterestedInReplyException Always
*/
@Override
public AuthStatus receiveReply(ServerResponse resp) throws NotInterestedInReplyException
{
throw new NotInterestedInReplyException();
}
}
/**
* Implementation of authentication provider backed onto a userip.list file.
*
* Useful when Nickserv is unavailable.
*
* @author benji
*/
class UserFileAuthProvider implements CanProvideAuth
{
private final Modules mods;
private final IRCInterface irc;
public UserFileAuthProvider(final Modules mods, final IRCInterface irc)
{
this.mods = mods;
this.irc = irc;
}
/**
* Request both the USERIP and USERHOST of the user
* @param nick The user to request details for
*/
@Override
public void sendRequest(final String nick)
{
irc.sendRawLine("USERIP " + nick);
irc.sendRawLine("USERHOST " + nick);
}
/**
* We're not interested in message replies
* @param mes The message recieved
* @return Never
* @throws NotInterestedInReplyException Always
*/
@Override
public AuthStatus receiveReply(final Message mes) throws NotInterestedInReplyException
{
throw new NotInterestedInReplyException();
}
/**
* Converts a server response into an Authentication Status
* @param resp The response from the server
* @return The determined authentication status
* @throws NotInterestedInReplyException If this server response does not allow us to determine the authentication status
*/
@Override
public AuthStatus receiveReply(ServerResponse resp) throws NotInterestedInReplyException
{
if (!(resp.getCode()==340 || resp.getCode()==302)) // USERIP (and USERHOST) response, not avaliable through PircBOT, gogo magic numbers.
throw new NotInterestedInReplyException();
/*
* General response ([]s as quotes):
* [Botnick] :[Nick]=+[User]@[ip, or, more likely, hash]
*
* for (a terrible) example:
* Choobie| :Faux=+Faux@87029A85.60BE439B.C4C3F075.IP
*/
final Matcher ma=Pattern.compile("^[^ ]+ :([^=]+)=(.*)").matcher(resp.getResponse().trim());
if (!ma.find())
throw new NotInterestedInReplyException();
System.out.println("Checking the file for \"" + ma.group(2) + "\".");
try
{
String line;
// Looks in src/ directory for file called userip.list with lines in form +<hostmask> e.g. +~benji@benjiweber.co.uk
final BufferedReader allowed = new BufferedReader(new FileReader("userip.list"));
while((line=allowed.readLine())!=null)
{
if (ma.group(2).equals(line))
{
return new AuthenticatedStatus();
}
}
return new UnknownStatus();
}
catch (final IOException e)
{
throw new NotInterestedInReplyException();
}
}
}
/***
* Interface to perform an action while still waiting on a blocking method.
*
* @author benji
*/
interface AndThen<T>
{
public T doThis(Action<Void> action);
public T value();
}
/**
* Can't have top level generic types in choob
* @author benji
*/
class ChoobSucksScope
{
/**
* A blocking queue with a capacity of 1
* Items in the queue time out and are removed after the specified timeout.
*
* @param <T>
*/
class SingleBlockingQueueWithTimeOut<T>
{
private final ArrayBlockingQueue<T> queue = new ArrayBlockingQueue<T>(1);
private final int timeout;
public SingleBlockingQueueWithTimeOut(int timeoutInSeconds)
{
this.timeout = timeoutInSeconds;
}
public AndThen<T> put(final T t) throws InterruptedException
{
queue.put(t);
new Timer().schedule(new TimerTask()
{
@Override
public void run()
{
//Remove this object, if it still exists in the queue.
queue.remove(t);
}
}, timeout * 1000);
return new AndThen<T>()
{
@Override
public T doThis(Action<Void> action)
{
action.doWith(null);
return t;
}
@Override
public T value()
{
return t;
}
};
}
public T peek()
{
return queue.peek();
}
public T poll()
{
return queue.poll();
}
public boolean remove(T o)
{
return queue.remove(o);
}
}
/**
* Exception thrown when the specified item is not in the cache.
*/
class ItemNotCachedException extends Exception
{
}
/**
* A cache that caches items for the fixed time, with no sliding window.
*
*/
class CacheWithTimeout<T>
{
private ConcurrentHashMap<String,T> map = new ConcurrentHashMap<String, T>();
private int timeout;
public CacheWithTimeout(int timeoutInSeconds)
{
this.timeout = timeoutInSeconds;
}
/**
* remove the item with specified key from the cache
* @param key The key of the item to remove
* @return The removed item.
*/
public T remove(final String key)
{
return map.remove(key);
}
/**
* Put the specified key/value pair into the cache
* @param key The key
* @param t The value
* @return The added value, for method chaining
*/
public T put(final String key, final T t)
{
map.put(key, t);
new Timer().schedule(new TimerTask()
{
@Override
public void run()
{
//Remove this object, if it still exists in the cache.
map.remove(key,t);
}
}, timeout * 1000);
return t;
}
/**
* Put the specified key/value pair in the cache, except when the supplied condition returns true.
* @param key The key
* @param t The value
* @param exceptWhen A condition to check on the added item. If this returns true it will NOT add it to the cache.
* @return The possibly-added item for method chaining.
*/
public T put(final String key, final T t, final InvokableI<T,Boolean> exceptWhen)
{
if (!(exceptWhen.invoke(t)))
return put(key,t);
return t;
}
/**
* Put the specified key/value pair into the cache.
* @param key The key to add
* @param t An invokable that when evaluated will yeild an item to add to the cache.
* @return The added item
*/
public T put(final String key, final Invokable<T> t)
{
return put(key,t.invoke());
}
/**
* Put the specified key/value pair in the cache, except when the supplied condition returns true.
* @param key The key
* @param t An invokable that when evaluated will yeild an item to add to the cache.
* @param exceptWhen A condition to check on the added item. If this returns true it will NOT add it to the cache.
* @return The possibly-added item for method chaining.
*/
public T put(final String key, final Invokable<T> t, final InvokableI<T,Boolean> exceptWhen)
{
T value = t.invoke();
if (!(exceptWhen.invoke(value)))
return put(key,t.invoke());
return value;
}
/**
* Get the item with the specified key from the cache
* @param key The key to look up
* @return The cached item
* @throws ChoobSucksScope.ItemNotCachedException if there is no item with this key in the cache.
*/
public T get(final String key) throws ItemNotCachedException
{
T value = map.get(key);
if (value == null)
throw new ItemNotCachedException();
return value;
}
/**
* Get the item with the specified key from the cache
* @param key The key to look up
* @param defaultValue The value to return if the item is not in the cache.
* @return The cached item
* @throws ChoobSucksScope.ItemNotCachedException if there is no item with this key in the cache.
*/
public T get(final String key, T defaultValue)
{
try
{
return get(key);
} catch (ItemNotCachedException e)
{
return defaultValue;
}
}
/**
* Get the item with the specified key from the cache
* @param key The key to look up
* @param defaultValueObtainer The invokable to obtain the default value to return if the item is not in the cache.
* @return The cached item
* @throws ChoobSucksScope.ItemNotCachedException if there is no item with this key in the cache.
*/
public T get(final String key, Invokable<T> defaultValueObtainer)
{
try
{
return get(key);
} catch (ItemNotCachedException e)
{
return defaultValueObtainer.invoke();
}
}
}
}
|
package com.example.baard;
import android.app.ActionBar;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Spannable;
import android.text.SpannableString;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* Activity to view a habit
* @see MainActivity
* @see Habit
* @see AllHabitsFragment
* @see DailyHabitsFragment
* @see AppCompatActivity
* @author rderbysh, minsoung
* @since 1.0
* @version 3.0
*/
public class ViewHabitActivity extends AppCompatActivity {
private final DateFormat formatter = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
private int position;
private String username;
private HabitList habitList;
private Habit habit;
private FileController fc;
private User user;
/**
* This create method sets the text based on habit retrieved
* @param savedInstanceState Bundle for the saved state
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_habit);
fc = new FileController();
// grab the index of the item in the list
Bundle extras = getIntent().getExtras();
position = extras.getInt("position");
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Gson gson = new Gson();
String json = sharedPrefs.getString("username", "");
username = gson.fromJson(json, new TypeToken<String>() {}.getType());
setActionBarTitle("View Habit");
}
/**
* Load the user to display the updated habit
*/
@Override
public void onStart() {
super.onStart();
// load required data
user = fc.loadUser(getApplicationContext(), username);
habitList = user.getHabits();
habit = habitList.getHabit(position);
// set all of the values for the habit to be viewed
TextView titleView = findViewById(R.id.title);
TextView reasonView = findViewById(R.id.reason);
TextView startDateView = findViewById(R.id.startDate);
TextView frequencyView = findViewById(R.id.frequency);
titleView.setText(habit.getTitle());
reasonView.setText(habit.getReason());
startDateView.setText(formatter.format(habit.getStartDate()));
frequencyView.setText(habit.getFrequencyString());
createPieChart();
createLineChart();
listHabitEvents();
TextView milestoneTextView = findViewById(R.id.milestoneTextView);
int milestone = habit.milestone();
if (milestone > 0) {
milestoneTextView.setText("Milestone reached: \n"+Integer.toString(milestone)+" habit events completed!");
milestoneTextView.setVisibility(View.VISIBLE);
} else {
milestoneTextView.setVisibility(View.GONE);
}
TextView streakTextView = findViewById(R.id.streakTextView);
int streak = habit.streak();
if (streak > 4) {
streakTextView.setText("Current Streak: "+Integer.toString(streak));
streakTextView.setVisibility(View.VISIBLE);
} else {
streakTextView.setVisibility(View.GONE);
}
Button edit = findViewById(R.id.edit);
Button delete = findViewById(R.id.delete);
edit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(ViewHabitActivity.this, EditHabitActivity.class);
intent.putExtra("position", position);
startActivity(intent);
}
});
delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
habitList.delete(habit);
fc.saveUser(getApplicationContext(), user);
finish();
}
});
}
private void changeFont() {
Typeface ralewayRegular = Typeface.createFromAsset(getAssets(), "fonts/Raleway-Regular.ttf");
TextView titleText = findViewById(R.id.title);
TextView reasonText = findViewById(R.id.textViewReason);
TextView startDateText = findViewById(R.id.textViewStartDate);
TextView freqText = findViewById(R.id.textViewFreq);
TextView reason = findViewById(R.id.reason);
TextView startDate = findViewById(R.id.startDate);
TextView frequency = findViewById(R.id.frequency);
TextView streakText = findViewById(R.id.streakTextView);
TextView milestoneText = findViewById(R.id.milestoneTextView);
titleText.setTypeface(ralewayRegular);
reasonText.setTypeface(ralewayRegular);
startDateText.setTypeface(ralewayRegular);
freqText.setTypeface(ralewayRegular);
reason.setTypeface(ralewayRegular);
startDate.setTypeface(ralewayRegular);
frequency.setTypeface(ralewayRegular);
streakText.setTypeface(ralewayRegular);
milestoneText.setTypeface(ralewayRegular);
}
@Override
public void onBackPressed() {
setResult(RESULT_OK);
finish();
super.onBackPressed();
}
private void setActionBarTitle(String str) {
String fontPath = "Raleway-Regular.ttf";
SpannableString s = new SpannableString(str);
s.setSpan(new TypefaceSpan(this, fontPath), 0, s.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// Update the action bar title with the TypefaceSpan instance
getSupportActionBar().setTitle(s);
}
/**
* Ensures the app returns to the proper fragment of main when back pressed
* @param item the menu item of the toolbar (only home in this case)
* @return boolean true if success
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
setResult(RESULT_OK);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Calculates and creates the Pie chart of events to be displayed
*/
private void createPieChart() {
HabitStatistics.HabitCompletionData habitCompletionData = new HabitStatistics().calcHabitCompletion(habit, new Date(Long.MIN_VALUE), new Date());
// Create Pie Chart
PieChart pieChart = (PieChart) findViewById(R.id.habit_pieChart);
pieChart.setHoleRadius(0);
pieChart.setTransparentCircleRadius(0);
pieChart.setMaxHighlightDistance(0);
pieChart.setDragDecelerationFrictionCoef(0.9f);
pieChart.getDescription().setEnabled(false);
ArrayList<PieEntry> yValues = new ArrayList<>();
yValues.add(new PieEntry(habitCompletionData.completed, "Completed"));
yValues.add(new PieEntry(habitCompletionData.notCompleted, "Not Completed"));
PieDataSet dataSet = new PieDataSet(yValues, "# of Habits");
dataSet.setColors(ColorTemplate.MATERIAL_COLORS);
dataSet.setSliceSpace(3f);
dataSet.setValueFormatter(new IValueFormatter() {
@Override
public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
return "" + ((int)value);
}
});
PieData data = new PieData(dataSet);
pieChart.setEntryLabelColor(Color.DKGRAY);
pieChart.setData(data);
if (habitCompletionData.notCompleted == 0 && habitCompletionData.completed == 0) {
pieChart.setVisibility(View.GONE);
} else {
pieChart.setData(data);
}
}
/**
* Calculates and creates the line chart of events to be displayed
*/
private void createLineChart() {
final ArrayList<HabitStatistics.HabitCompletionVsTimeData> habitCompletionVsTimesData = new HabitStatistics().getHabitCompletionVsTimeData(habit, new Date(Long.MIN_VALUE), new Date());
// Create Line Chart
LineChart lineChart = (LineChart) findViewById(R.id.habit_lineChart);
lineChart.setDragEnabled(true);
lineChart.setScaleEnabled(false);
lineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
lineChart.getXAxis().setDrawGridLines(false);
lineChart.getAxisLeft().setDrawGridLines(false);
lineChart.getAxisRight().setDrawGridLines(false);
lineChart.getDescription().setEnabled(false);
lineChart.getAxisRight().setEnabled(false);
ArrayList<Entry> yValues = new ArrayList<>();
for (HabitStatistics.HabitCompletionVsTimeData data : habitCompletionVsTimesData) {
yValues.add(new Entry(data.time, data.habitCompletion));
}
LineDataSet set1 = new LineDataSet(yValues, "DataSet");
set1.setColor(Color.BLACK);
set1.setLineWidth(1f);
set1.setValueTextSize(10f);
set1.setValueTextColor(Color.BLACK);
ArrayList<ILineDataSet> dataSets = new ArrayList<>();
dataSets.add(set1);
LineData data = new LineData(dataSets);
if (habitCompletionVsTimesData.size() > 0) {
lineChart.setData(data);
} else {
lineChart.setVisibility(View.GONE);
}
lineChart.getXAxis().setValueFormatter(new MyAxisValueFormatter());
lineChart.getXAxis().setGranularity(1f);
}
/**
* Formats the scale of the x axis for the line chart
*/
private class MyAxisValueFormatter implements IAxisValueFormatter {
@Override
public String getFormattedValue(float value, AxisBase axis) {
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd",Locale.ENGLISH);
Calendar calendar = Calendar.getInstance();
// Log.d("LineChart", Float.toString(value));
calendar.setTimeInMillis((long)value);
return sdf.format(calendar.getTime());
}
}
private void listHabitEvents() {
ListView eventsList = findViewById(R.id.habit_events_scroller_ListView);
final List<HabitEvent> habitEventList = habit.getEvents().getArrayList();
if (habitEventList.size() > 0) {
for (HabitEvent e : habitEventList) {
e.setHabit(habit);
}
ArrayAdapter<HabitEvent> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, habitEventList);
eventsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//tell the ViewRecordActivity which list item has been selected and start it
Intent intent = new Intent(ViewHabitActivity.this, ViewHabitEventActivity.class);
intent.putExtra("habitEventDate", habitEventList.get(i).getEventDate().toString());
habitEventList.get(i).getHabit().sendToSharedPreferences(getApplicationContext());
startActivity(intent);
}
});
eventsList.setAdapter(adapter);
adapter.notifyDataSetChanged();
if (habitEventList.size()*150 < 450) {
eventsList.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, habitEventList.size()*150));
} else {
eventsList.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 450));
eventsList.setOnTouchListener(new View.OnTouchListener() {
// Setting on Touch Listener for handling the touch inside ScrollView
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
// Disallow the touch request for parent scroll on touch of child view
view.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
});
}
} else {
eventsList.setVisibility(View.GONE);
findViewById(R.id.no_events_textView).setVisibility(View.VISIBLE);
}
}
}
|
package com.james.status.data.icon;
import android.content.Context;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.preference.PreferenceManager;
import android.support.annotation.ColorInt;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import com.james.status.R;
import com.james.status.data.IconStyleData;
import com.james.status.data.PreferenceData;
import com.james.status.data.preference.BasePreferenceData;
import com.james.status.data.preference.BooleanPreferenceData;
import com.james.status.data.preference.ColorPreferenceData;
import com.james.status.data.preference.FontPreferenceData;
import com.james.status.data.preference.IconPreferenceData;
import com.james.status.data.preference.IntegerPreferenceData;
import com.james.status.data.preference.ListPreferenceData;
import com.james.status.receivers.IconUpdateReceiver;
import com.james.status.utils.AnimatedColor;
import com.james.status.utils.AnimatedFloat;
import com.james.status.utils.AnimatedInteger;
import com.james.status.utils.ColorUtils;
import com.james.status.utils.StaticUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public abstract class IconData<T extends IconUpdateReceiver> {
public static final int LEFT_GRAVITY = -1, CENTER_GRAVITY = 0, RIGHT_GRAVITY = 1;
private Context context;
private ReDrawListener reDrawListener;
private Typeface typeface;
private T receiver;
private int backgroundColor;
private List<IconStyleData> styles;
private IconStyleData style;
private int level;
private Bitmap bitmap;
private String text;
Paint iconPaint, textPaint;
private boolean isIcon, isText;
private AnimatedColor textColor;
private AnimatedFloat textSize;
private AnimatedInteger textAlpha;
private int defaultTextDarkColor;
private int defaultTextLightColor;
private AnimatedInteger textOffsetX, textOffsetY;
private AnimatedColor iconColor;
AnimatedInteger iconSize;
private AnimatedInteger iconAlpha;
private int defaultIconDarkColor;
private int defaultIconLightColor;
private AnimatedInteger iconOffsetX, iconOffsetY;
AnimatedInteger padding;
boolean isAnimations;
public IconData(Context context) {
this.context = context;
iconPaint = new Paint();
iconPaint.setAntiAlias(true);
iconPaint.setDither(true);
textPaint = new Paint();
textPaint.setAntiAlias(true);
textPaint.setDither(true);
styles = getIconStyles();
level = 0;
textColor = new AnimatedColor(Color.WHITE);
textSize = new AnimatedFloat(0);
textAlpha = new AnimatedInteger(0);
textOffsetX = new AnimatedInteger(0);
textOffsetY = new AnimatedInteger(0);
iconColor = new AnimatedColor(Color.WHITE);
iconSize = new AnimatedInteger(0);
iconAlpha = new AnimatedInteger(0);
iconOffsetX = new AnimatedInteger(0);
iconOffsetY = new AnimatedInteger(0);
padding = new AnimatedInteger(0);
init(true);
}
public void init() {
init(false);
}
private void init(boolean isFirstInit) {
iconColor.setDefault((int) PreferenceData.ICON_ICON_COLOR.getSpecificOverriddenValue(getContext(),
PreferenceData.STATUS_ICON_COLOR.getValue(getContext()), getIdentifierArgs()));
defaultIconDarkColor = PreferenceData.STATUS_DARK_ICON_COLOR.getValue(getContext());
defaultIconLightColor = PreferenceData.STATUS_LIGHT_ICON_COLOR.getValue(getContext());
textColor.setDefault((int) PreferenceData.ICON_TEXT_COLOR.getSpecificOverriddenValue(getContext(),
PreferenceData.STATUS_ICON_TEXT_COLOR.getValue(getContext()), getIdentifierArgs()));
defaultTextDarkColor = PreferenceData.STATUS_DARK_ICON_TEXT_COLOR.getValue(getContext());
defaultTextLightColor = PreferenceData.STATUS_LIGHT_ICON_TEXT_COLOR.getValue(getContext());
iconSize.setDefault((int) StaticUtils.getPixelsFromDp((int) PreferenceData.ICON_ICON_SCALE.getSpecificValue(getContext(), getIdentifierArgs())));
iconOffsetX.to((int) PreferenceData.ICON_ICON_OFFSET_X.getSpecificValue(getContext(), getIdentifierArgs()));
iconOffsetY.to((int) PreferenceData.ICON_ICON_OFFSET_Y.getSpecificValue(getContext(), getIdentifierArgs()));
textSize.setDefault((float) StaticUtils.getPixelsFromSp(getContext(), (float) (int) PreferenceData.ICON_TEXT_SIZE.getSpecificValue(getContext(), getIdentifierArgs())));
textOffsetX.to((int) PreferenceData.ICON_TEXT_OFFSET_X.getSpecificValue(getContext(), getIdentifierArgs()));
textOffsetY.to((int) PreferenceData.ICON_TEXT_OFFSET_Y.getSpecificValue(getContext(), getIdentifierArgs()));
padding.to((int) StaticUtils.getPixelsFromDp((int) PreferenceData.ICON_ICON_PADDING.getSpecificValue(getContext(), getIdentifierArgs())));
backgroundColor = PreferenceData.STATUS_COLOR.getValue(getContext());
Typeface typefaceFont = Typeface.DEFAULT;
String typefaceName = PreferenceData.ICON_TEXT_TYPEFACE.getSpecificOverriddenValue(getContext(), null, getIdentifierArgs());
if (typefaceName != null) {
try {
typefaceFont = Typeface.createFromAsset(getContext().getAssets(), typefaceName);
} catch (Exception ignored) {
}
}
typeface = Typeface.create(typefaceFont, (int) PreferenceData.ICON_TEXT_EFFECT.getSpecificValue(getContext(), getIdentifierArgs()));
isAnimations = PreferenceData.STATUS_ICON_ANIMATIONS.getValue(getContext());
if (styles.size() > 0) {
String name = PreferenceData.ICON_ICON_STYLE.getSpecificOverriddenValue(context, styles.get(0).name, getIdentifierArgs());
if (name != null) {
for (IconStyleData style : styles) {
if (style.name.equals(name)) {
this.style = style;
break;
}
}
}
if (style == null) style = styles.get(0);
onIconUpdate(level);
}
if (isFirstInit) {
textAlpha.to(255);
iconAlpha.to(255);
textColor.setCurrent(textColor.getDefault());
iconColor.setCurrent(iconColor.getDefault());
textSize.toDefault();
textOffsetX.setCurrent(textOffsetX.getTarget());
textOffsetY.setCurrent(textOffsetY.getTarget());
iconSize.toDefault();
iconOffsetX.setCurrent(iconOffsetX.getTarget());
iconOffsetY.setCurrent(iconOffsetY.getTarget());
} else {
if (isText)
textSize.toDefault();
if (isIcon)
iconSize.toDefault();
}
}
public final Context getContext() {
return context;
}
public final void setReDrawListener(ReDrawListener listener) {
reDrawListener = listener;
}
public final void onIconUpdate(int level) {
this.level = level;
if (hasIcon()) {
Bitmap bitmap = style.getBitmap(context, level);
isIcon = bitmap != null;
if (isIcon) {
this.bitmap = bitmap;
iconSize.toDefault();
} else iconSize.to(0);
if (reDrawListener != null)
reDrawListener.onRequestReDraw();
}
}
public final void onTextUpdate(@Nullable String text) {
isText = text != null;
if (isText) {
this.text = text;
textSize.toDefault();
} else textSize.to(0f);
if (hasText() && reDrawListener != null)
reDrawListener.onRequestReDraw();
}
public final void requestReDraw() {
if (reDrawListener != null)
reDrawListener.onRequestReDraw();
}
public final boolean isVisible() {
return PreferenceData.ICON_VISIBILITY.getSpecificOverriddenValue(getContext(), isDefaultVisible(), getIdentifierArgs()) && StaticUtils.isPermissionsGranted(getContext(), getPermissions());
}
boolean isDefaultVisible() {
return true;
}
public boolean canHazIcon() {
//i can haz drawable resource
return true;
}
public boolean hasIcon() {
return canHazIcon() && PreferenceData.ICON_ICON_VISIBILITY.getSpecificOverriddenValue(getContext(), true, getIdentifierArgs()) && style != null;
}
public boolean canHazText() {
//u can not haz text tho
return false;
}
public boolean hasText() {
return canHazText() && PreferenceData.ICON_TEXT_VISIBILITY.getSpecificOverriddenValue(getContext(), !canHazIcon(), getIdentifierArgs());
}
public String[] getPermissions() {
return new String[]{};
}
public T getReceiver() {
return null;
}
public IntentFilter getIntentFilter() {
return new IntentFilter();
}
public void register() {
if (receiver == null) receiver = getReceiver();
if (receiver != null) getContext().registerReceiver(receiver, getIntentFilter());
onIconUpdate(-1);
}
public void unregister() {
if (receiver != null) getContext().unregisterReceiver(receiver);
}
public final int getIconPadding() {
return PreferenceData.ICON_ICON_PADDING.getSpecificValue(getContext(), getIdentifierArgs());
}
public final int getIconScale() {
return PreferenceData.ICON_ICON_SCALE.getSpecificValue(getContext(), getIdentifierArgs());
}
public final float getTextSize() {
return (float) (int) PreferenceData.ICON_TEXT_SIZE.getSpecificValue(getContext(), getIdentifierArgs());
}
@ColorInt
public final Integer getTextColor() {
return PreferenceData.ICON_TEXT_COLOR.getSpecificValue(getContext(), getIdentifierArgs());
}
public final int getPosition() {
return PreferenceData.ICON_POSITION.getSpecificValue(getContext(), getIdentifierArgs());
}
public int getDefaultGravity() {
return RIGHT_GRAVITY;
}
public final int getGravity() {
return PreferenceData.ICON_GRAVITY.getSpecificOverriddenValue(getContext(), getDefaultGravity(), getIdentifierArgs());
}
/**
* Determines the color of the icon based on various settings,
* some of which are icon-specific.
*
* @param color the color to be drawn behind the icon
*/
public void setBackgroundColor(@ColorInt int color) {
backgroundColor = color;
if (PreferenceData.STATUS_TINTED_ICONS.getValue(getContext())) {
iconColor.to(color);
textColor.to(color);
} else {
boolean isIconContrast = PreferenceData.STATUS_DARK_ICONS.getValue(getContext());
iconColor.to(isIconContrast && ColorUtils.getDifference(color, iconColor.getDefault()) < 100 ?
(ColorUtils.isColorDark(color) ? defaultIconLightColor : defaultIconDarkColor) : iconColor.getDefault());
textColor.to(isIconContrast && ColorUtils.getDifference(color, textColor.getDefault()) < 100 ?
(ColorUtils.isColorDark(color) ? defaultTextLightColor : defaultTextDarkColor) : textColor.getDefault());
}
requestReDraw();
}
@Nullable
public Bitmap getBitmap() {
if (hasIcon()) return bitmap;
else return null;
}
@Nullable
public String getText() {
if (hasText()) return text;
else return null;
}
public String getTitle() {
return getClass().getSimpleName();
}
@LayoutRes
public int getIconLayout() {
return R.layout.item_icon;
}
public boolean needsDraw() {
return !iconSize.isTarget() ||
!iconOffsetX.isTarget() ||
!iconOffsetY.isTarget() ||
!iconColor.isTarget() ||
!textSize.isTarget() ||
!textOffsetX.isTarget() ||
!textOffsetY.isTarget() ||
!textColor.isTarget() ||
!padding.isTarget() ||
!textAlpha.isTarget() ||
!iconAlpha.isTarget();
}
public void updateAnimatedValues() {
iconColor.next(isAnimations);
iconSize.next(isAnimations);
iconOffsetX.next(isAnimations);
iconOffsetY.next(isAnimations);
textColor.next(isAnimations);
textSize.next(isAnimations);
textOffsetX.next(isAnimations);
textOffsetY.next(isAnimations);
padding.next(isAnimations);
textAlpha.next(isAnimations);
iconAlpha.next(isAnimations);
}
/**
* Draws the icon on a canvas.
*
* @param canvas the canvas to draw on
* @param x the x position (LTR px) to start drawing the icon at
* @param width the available width for the icon to be drawn within
*/
public void draw(Canvas canvas, int x, int width) {
updateAnimatedValues();
int drawnIconColor = iconColor.val();
int iconColor = Color.rgb(
StaticUtils.getMergedValue(Color.red(drawnIconColor), Color.red(backgroundColor), (float) iconAlpha.val() / 255),
StaticUtils.getMergedValue(Color.green(drawnIconColor), Color.green(backgroundColor), (float) iconAlpha.val() / 255),
StaticUtils.getMergedValue(Color.blue(drawnIconColor), Color.blue(backgroundColor), (float) iconAlpha.val() / 255)
);
iconPaint.setColor(iconColor);
iconPaint.setColorFilter(new PorterDuffColorFilter(iconColor, PorterDuff.Mode.SRC_IN));
textPaint.setColor(textColor.val());
textPaint.setAlpha(textAlpha.val());
textPaint.setTextSize(textSize.val());
textPaint.setTypeface(typeface);
x += padding.val();
if (hasIcon() && bitmap != null && iconSize.val() > 0) {
x += iconOffsetX.val();
if (iconSize.isTarget() && iconSize.val() != bitmap.getWidth()) {
if (bitmap.getWidth() > iconSize.val())
bitmap = Bitmap.createScaledBitmap(bitmap, iconSize.val(), iconSize.val(), true);
else {
Bitmap bitmap = style.getBitmap(context, level);
if (bitmap != null) {
this.bitmap = bitmap;
if (this.bitmap.getWidth() != iconSize.val())
this.bitmap = Bitmap.createScaledBitmap(bitmap, iconSize.val(), iconSize.val(), true);
}
}
}
Matrix matrix = new Matrix();
matrix.postScale((float) iconSize.val() / bitmap.getWidth(), (float) iconSize.val() / bitmap.getWidth());
matrix.postTranslate(x, (((float) canvas.getHeight() - iconSize.val()) / 2) - iconOffsetY.val());
canvas.drawBitmap(bitmap, matrix, iconPaint);
x += iconSize.val() + padding.val() - iconOffsetX.val();
}
if (hasText() && text != null) {
Paint.FontMetrics metrics = textPaint.getFontMetrics();
canvas.drawText(text, x + textOffsetX.val(), ((canvas.getHeight() - metrics.descent - metrics.ascent) / 2) - textOffsetY.val(), textPaint);
}
}
/**
* Returns the estimated width (px) of the icon, or -1
* if the icon needs to know the available space
* first.
*
* @param height the height (px) to scale the icon to
* @param available the available width for the icon, or -1 if not yet calculated
* @return the estimated width (px) of the icon
*/
public int getWidth(int height, int available) {
if ((!hasIcon() || iconSize.nextVal() == 0) && (!hasText() || textSize.nextVal() == 0))
return 0;
int width = 0;
if ((hasIcon() && bitmap != null) || (hasText() && text != null))
width += padding.nextVal();
if (hasIcon() && bitmap != null) {
width += iconSize.nextVal();
width += padding.nextVal();
}
if (hasText() && text != null) {
Paint textPaint = new Paint();
textPaint.setTextSize(textSize.nextVal());
textPaint.setTypeface(typeface);
Rect bounds = new Rect();
textPaint.getTextBounds(text, 0, text.length(), bounds);
width += hasText() ? bounds.width() : 0;
width += padding.nextVal();
}
return width;
}
public List<BasePreferenceData> getPreferences() {
List<BasePreferenceData> preferences = new ArrayList<>();
if (canHazIcon() && (hasText() || !hasIcon())) {
preferences.add(new BooleanPreferenceData(
getContext(),
new BasePreferenceData.Identifier<Boolean>(
PreferenceData.ICON_ICON_VISIBILITY,
getContext().getString(R.string.preference_show_drawable),
getIdentifierArgs()
),
new BasePreferenceData.OnPreferenceChangeListener<Boolean>() {
@Override
public void onPreferenceChange(Boolean preference) {
StaticUtils.updateStatusService(getContext(), true);
}
}
));
}
if (canHazText() && (hasIcon() || !hasText())) {
preferences.add(new BooleanPreferenceData(
getContext(),
new BasePreferenceData.Identifier<Boolean>(
PreferenceData.ICON_TEXT_VISIBILITY,
getContext().getString(R.string.preference_show_text),
getIdentifierArgs()
),
new BasePreferenceData.OnPreferenceChangeListener<Boolean>() {
@Override
public void onPreferenceChange(Boolean preference) {
StaticUtils.updateStatusService(getContext(), true);
}
}
));
}
preferences.addAll(Arrays.asList(
new ListPreferenceData(
getContext(),
new BasePreferenceData.Identifier<>(
PreferenceData.ICON_GRAVITY,
getContext().getString(R.string.preference_gravity),
getDefaultGravity(),
getIdentifierArgs()
),
new BasePreferenceData.OnPreferenceChangeListener<Integer>() {
@Override
public void onPreferenceChange(Integer preference) {
StaticUtils.updateStatusService(getContext(), true);
}
},
new ListPreferenceData.ListPreference(
getContext().getString(R.string.gravity_left),
LEFT_GRAVITY
),
new ListPreferenceData.ListPreference(
getContext().getString(R.string.gravity_center),
CENTER_GRAVITY
),
new ListPreferenceData.ListPreference(
getContext().getString(R.string.gravity_right),
RIGHT_GRAVITY
)
),
new IntegerPreferenceData(
getContext(),
new BasePreferenceData.Identifier<Integer>(
PreferenceData.ICON_ICON_PADDING,
getContext().getString(R.string.preference_icon_padding),
getIdentifierArgs()
),
getContext().getString(R.string.unit_dp),
null,
null,
new BasePreferenceData.OnPreferenceChangeListener<Integer>() {
@Override
public void onPreferenceChange(Integer preference) {
StaticUtils.updateStatusService(getContext(), true);
}
}
)
));
if (hasIcon()) {
preferences.add(new IntegerPreferenceData(
getContext(),
new BasePreferenceData.Identifier<Integer>(
PreferenceData.ICON_ICON_SCALE,
getContext().getString(R.string.preference_icon_scale),
getIdentifierArgs()
),
getContext().getString(R.string.unit_dp),
0,
null,
new BasePreferenceData.OnPreferenceChangeListener<Integer>() {
@Override
public void onPreferenceChange(Integer preference) {
StaticUtils.updateStatusService(getContext(), true);
}
}
));
}
if (hasText()) {
preferences.add(new IntegerPreferenceData(
getContext(),
new BasePreferenceData.Identifier<Integer>(
PreferenceData.ICON_TEXT_SIZE,
getContext().getString(R.string.preference_text_size),
getIdentifierArgs()
),
getContext().getString(R.string.unit_sp),
0,
null,
new BasePreferenceData.OnPreferenceChangeListener<Integer>() {
@Override
public void onPreferenceChange(Integer preference) {
StaticUtils.updateStatusService(getContext(), true);
}
}
));
preferences.add(new ColorPreferenceData(
getContext(),
new BasePreferenceData.Identifier<Integer>(
PreferenceData.ICON_TEXT_COLOR,
getContext().getString(R.string.preference_text_color),
getIdentifierArgs()
),
new BasePreferenceData.OnPreferenceChangeListener<Integer>() {
@Override
public void onPreferenceChange(Integer preference) {
StaticUtils.updateStatusService(getContext(), true);
}
}
));
preferences.add(new FontPreferenceData(
getContext(),
new BasePreferenceData.Identifier<String>(
PreferenceData.ICON_TEXT_TYPEFACE,
getContext().getString(R.string.preference_text_font),
getIdentifierArgs()
),
new BasePreferenceData.OnPreferenceChangeListener<String>() {
@Override
public void onPreferenceChange(String preference) {
StaticUtils.updateStatusService(getContext(), true);
}
},
"Audiowide.ttf",
"BlackOpsOne.ttf",
"HennyPenny.ttf",
"Iceland.ttf",
"Megrim.ttf",
"Monoton.ttf",
"NewRocker.ttf",
"Nosifer.ttf",
"PermanentMarker.ttf",
"Playball.ttf",
"Righteous.ttf",
"Roboto.ttf",
"RobotoCondensed.ttf",
"RobotoSlab.ttf",
"VT323.ttf",
"Wallpoet.ttf"
));
preferences.add(new ListPreferenceData(
getContext(),
new BasePreferenceData.Identifier<Integer>(
PreferenceData.ICON_TEXT_EFFECT,
getContext().getString(R.string.preference_text_effect),
getIdentifierArgs()
),
new BasePreferenceData.OnPreferenceChangeListener<Integer>() {
@Override
public void onPreferenceChange(Integer preference) {
StaticUtils.updateStatusService(getContext(), true);
}
},
new ListPreferenceData.ListPreference(getContext().getString(R.string.text_effect_none), Typeface.NORMAL),
new ListPreferenceData.ListPreference(getContext().getString(R.string.text_effect_bold), Typeface.BOLD),
new ListPreferenceData.ListPreference(getContext().getString(R.string.text_effect_italic), Typeface.ITALIC),
new ListPreferenceData.ListPreference(getContext().getString(R.string.text_effect_bold_italic), Typeface.BOLD_ITALIC)
));
//TODO: uncomment after fixing #115
/*preferences.add(new IntegerPreferenceData(
getContext(),
new BasePreferenceData.Identifier<Integer>(
PreferenceData.ICON_TEXT_OFFSET_X,
"Horizontal Text Offset",
getIdentifierArgs()
),
"px",
-100,
100,
new BasePreferenceData.OnPreferenceChangeListener<Integer>() {
@Override
public void onPreferenceChange(Integer preference) {
StaticUtils.updateStatusService(getContext(), true);
}
}
));
preferences.add(new IntegerPreferenceData(
getContext(),
new BasePreferenceData.Identifier<Integer>(
PreferenceData.ICON_TEXT_OFFSET_Y,
"Vertical Text Offset",
getIdentifierArgs()
),
"px",
-100,
100,
new BasePreferenceData.OnPreferenceChangeListener<Integer>() {
@Override
public void onPreferenceChange(Integer preference) {
StaticUtils.updateStatusService(getContext(), true);
}
}
));*/
}
if (hasIcon()) {
preferences.add(new IconPreferenceData(
getContext(),
new BasePreferenceData.Identifier<String>(
PreferenceData.ICON_ICON_STYLE,
getContext().getString(R.string.preference_icon_style),
getIdentifierArgs()
),
this,
new BasePreferenceData.OnPreferenceChangeListener<IconStyleData>() {
@Override
public void onPreferenceChange(IconStyleData preference) {
style = preference;
StaticUtils.updateStatusService(getContext(), true);
}
}
));
//TODO: uncomment after fixing #115
/*preferences.add(new IntegerPreferenceData(
getContext(),
new BasePreferenceData.Identifier<Integer>(
PreferenceData.ICON_ICON_OFFSET_X,
"Horizontal Icon Offset",
getIdentifierArgs()
),
"px",
-100,
100,
new BasePreferenceData.OnPreferenceChangeListener<Integer>() {
@Override
public void onPreferenceChange(Integer preference) {
StaticUtils.updateStatusService(getContext(), true);
}
}
));
preferences.add(new IntegerPreferenceData(
getContext(),
new BasePreferenceData.Identifier<Integer>(
PreferenceData.ICON_ICON_OFFSET_Y,
"Vertical Icon Offset",
getIdentifierArgs()
),
"px",
-100,
100,
new BasePreferenceData.OnPreferenceChangeListener<Integer>() {
@Override
public void onPreferenceChange(Integer preference) {
StaticUtils.updateStatusService(getContext(), true);
}
}
));*/
}
return preferences;
}
public int getIconStyleSize() {
return 0;
}
public String[] getIconNames() {
return new String[]{};
}
public List<IconStyleData> getIconStyles() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
List<IconStyleData> styles = new ArrayList<>();
String[] names = PreferenceData.ICON_ICON_STYLE_NAMES.getSpecificValue(getContext(), getIdentifierArgs());
for (String name : names) {
IconStyleData style = IconStyleData.fromSharedPreferences(prefs, getClass().getName(), name);
if (style != null) styles.add(style);
}
return styles;
}
public final void addIconStyle(IconStyleData style) {
if (style.getSize() == getIconStyleSize()) {
List<String> list = new ArrayList<>(Arrays.asList((String[]) PreferenceData.ICON_ICON_STYLE_NAMES.getSpecificValue(getContext(), getIdentifierArgs())));
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
style.writeToSharedPreferences(editor, getClass().getName());
editor.apply();
list.add(style.name);
PreferenceData.ICON_ICON_STYLE_NAMES.setValue(context, list.toArray(new String[list.size()]), getIdentifierArgs());
}
}
public final void removeIconStyle(IconStyleData style) {
List<String> list = new ArrayList<>(Arrays.asList((String[]) PreferenceData.ICON_ICON_STYLE_NAMES.getSpecificValue(getContext(), getIdentifierArgs())));
list.remove(style.name);
PreferenceData.ICON_ICON_STYLE_NAMES.setValue(context, list.toArray(new String[list.size()]), getIdentifierArgs());
}
public String[] getIdentifierArgs() {
return new String[]{getClass().getName()};
}
public interface ReDrawListener {
void onRequestReDraw();
}
}
|
package com.kickstarter.services;
import com.kickstarter.models.Project;
import com.kickstarter.services.ApiResponses.AccessTokenEnvelope;
import com.kickstarter.services.ApiResponses.ActivityEnvelope;
import com.kickstarter.services.ApiResponses.CommentEnvelope;
import com.kickstarter.services.ApiResponses.DiscoverEnvelope;
import java.util.List;
import java.util.Map;
import retrofit.http.GET;
import retrofit.http.POST;
import retrofit.http.Path;
import retrofit.http.Query;
import retrofit.http.QueryMap;
import rx.Observable;
/*package*/ interface ApiService {
@GET("/v1/activities")
Observable<ActivityEnvelope> fetchActivities(@Query("categories[]") List<String> categories);
// todo: either this, with known path, or {url} with the api url from project
@GET("/v1/projects/{id}/comments")
Observable<CommentEnvelope> fetchComments(@Path("id") Integer id);
@GET("/v1/discover")
Observable<DiscoverEnvelope> fetchProjects(@QueryMap Map<String, String> params);
@GET("/v1/projects/{id}")
public Observable<Project> fetchProject(@Path("id") Integer id);
@POST("/xauth/access_token")
public Observable<AccessTokenEnvelope> login(@Query("email") String email,
@Query("password") String password);
@POST("/xauth/access_token")
public Observable<AccessTokenEnvelope> login(@Query("email") String email,
@Query("password") String password,
@Query("code") String code);
}
|
package com.marverenic.music.instances;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Parcel;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import com.marverenic.music.R;
import com.marverenic.music.data.store.MediaStoreUtil;
import com.marverenic.music.utils.Util;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import static com.marverenic.music.instances.Util.compareLong;
import static com.marverenic.music.instances.Util.parseUnknown;
public class Song implements Parcelable, Comparable<Song> {
public static final Parcelable.Creator<Song> CREATOR = new Parcelable.Creator<Song>() {
public Song createFromParcel(Parcel in) {
return new Song(in);
}
public Song[] newArray(int size) {
return new Song[size];
}
};
protected String songName;
protected long songId;
protected String artistName;
protected String albumName;
protected long songDuration;
protected String location;
protected int year;
protected long dateAdded; // seconds since Jan 1, 1970
protected long albumId;
protected long artistId;
protected long genreId;
protected int trackNumber;
private Song() {
}
private Song(Parcel in) {
songName = in.readString();
songId = in.readLong();
albumName = in.readString();
artistName = in.readString();
songDuration = in.readLong();
location = in.readString();
year = in.readInt();
dateAdded = in.readLong();
albumId = in.readLong();
artistId = in.readLong();
genreId = in.readLong();
}
public Song(Song s) {
this.songName = s.songName;
this.songId = s.songId;
this.artistName = s.artistName;
this.albumName = s.albumName;
this.songDuration = s.songDuration;
this.location = s.location;
this.year = s.year;
this.dateAdded = s.dateAdded;
this.albumId = s.albumId;
this.artistId = s.artistId;
this.genreId = s.genreId;
this.trackNumber = s.trackNumber;
}
/**
* Builds a {@link List} of Songs from a Cursor
* @param cur A {@link Cursor} to use when reading the {@link MediaStore}. This Cursor may have
* any filters and sorting, but MUST have AT LEAST the columns in
* {@link MediaStoreUtil#SONG_PROJECTION}. The caller is responsible for closing
* this Cursor.
* @param res A {@link Resources} Object from {@link Context#getResources()} used to get the
* default values if an unknown value is encountered
* @return A List of songs populated by entries in the Cursor
*/
public static List<Song> buildSongList(Cursor cur, Resources res) {
List<Song> songs = new ArrayList<>(cur.getCount());
int titleIndex = cur.getColumnIndex(MediaStore.Audio.Media.TITLE);
int idIndex = cur.getColumnIndex(MediaStore.Audio.Media._ID);
int artistIndex = cur.getColumnIndex(MediaStore.Audio.Media.ARTIST);
int albumIndex = cur.getColumnIndex(MediaStore.Audio.Media.ALBUM);
int durationIndex = cur.getColumnIndex(MediaStore.Audio.Media.DURATION);
int dataIndex = cur.getColumnIndex(MediaStore.Audio.Media.DATA);
int yearIndex = cur.getColumnIndex(MediaStore.Audio.Media.YEAR);
int dateIndex = cur.getColumnIndex(MediaStore.Audio.Media.DATE_ADDED);
int albumIdIndex = cur.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);
int artistIdIndex = cur.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID);
int trackIndex = cur.getColumnIndex(MediaStore.Audio.Media.TRACK);
if (idIndex == -1) {
idIndex = cur.getColumnIndex(MediaStore.Audio.Playlists.Members.AUDIO_ID);
}
final String unknownSong = res.getString(R.string.unknown);
final String unknownArtist = res.getString(R.string.unknown_artist);
final String unknownAlbum = res.getString(R.string.unknown_album);
final String unknownData = "";
for (int i = 0; i < cur.getCount(); i++) {
cur.moveToPosition(i);
Song next = new Song();
next.songName = parseUnknown(cur.getString(titleIndex), unknownSong);
next.songId = cur.getLong(idIndex);
next.artistName = parseUnknown(cur.getString(artistIndex), unknownArtist);
next.albumName = parseUnknown(cur.getString(albumIndex), unknownAlbum);
next.songDuration = cur.getLong(durationIndex);
next.location = parseUnknown(cur.getString(dataIndex), unknownData);
next.year = cur.getInt(yearIndex);
next.dateAdded = cur.getLong(dateIndex);
next.albumId = cur.getLong(albumIdIndex);
next.artistId = cur.getLong(artistIdIndex);
next.trackNumber = cur.getInt(trackIndex);
songs.add(next);
}
return songs;
}
public String getSongName() {
return songName;
}
public long getSongId() {
return songId;
}
public String getArtistName() {
return artistName;
}
public String getAlbumName() {
return albumName;
}
public long getSongDuration() {
return songDuration;
}
public String getLocation() {
return location;
}
public int getYear() {
return year;
}
public long getDateAdded() {
return dateAdded;
}
public long getAlbumId() {
return albumId;
}
public long getArtistId() {
return artistId;
}
public long getGenreId() {
return genreId;
}
public int getTrackNumber() {
return trackNumber;
}
public int getSkipCount() {
return Library.getSkipCount(songId);
}
public int getPlayCount() {
return Library.getPlayCount(songId);
}
public int getPlayDate() {
return Library.getPlayDate(songId);
}
@Override
public int hashCode() {
return Util.hashLong(songId);
}
@Override
public boolean equals(final Object obj) {
return this == obj
|| (obj != null && obj instanceof Song && songId == ((Song) obj).songId);
}
public String toString() {
return songName;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(songName);
dest.writeLong(songId);
dest.writeString(albumName);
dest.writeString(artistName);
dest.writeLong(songDuration);
dest.writeString(location);
dest.writeInt(year);
dest.writeLong(dateAdded);
dest.writeLong(albumId);
dest.writeLong(artistId);
dest.writeLong(genreId);
}
@Override
public int compareTo(@NonNull Song another) {
String o1c = songName.toLowerCase(Locale.ENGLISH);
String o2c = another.songName.toLowerCase(Locale.ENGLISH);
if (o1c.startsWith("the ")) {
o1c = o1c.substring(4);
} else if (o1c.startsWith("a ")) {
o1c = o1c.substring(2);
}
if (o2c.startsWith("the ")) {
o2c = o2c.substring(4);
} else if (o2c.startsWith("a ")) {
o2c = o2c.substring(2);
}
return o1c.compareTo(o2c);
}
public static final Comparator<Song> ARTIST_COMPARATOR = new Comparator<Song>() {
@Override
public int compare(Song s1, Song s2) {
String o1c = s1.artistName.toLowerCase(Locale.ENGLISH);
String o2c = s2.artistName.toLowerCase(Locale.ENGLISH);
if (o1c.startsWith("the ")) {
o1c = o1c.substring(4);
} else if (o1c.startsWith("a ")) {
o1c = o1c.substring(2);
}
if (o2c.startsWith("the ")) {
o2c = o2c.substring(4);
} else if (o2c.startsWith("a ")) {
o2c = o2c.substring(2);
}
if (!o1c.matches("[a-z]") && o2c.matches("[a-z]")) {
return o2c.compareTo(o1c);
}
return o1c.compareTo(o2c);
}
};
public static final Comparator<Song> ALBUM_COMPARATOR = new Comparator<Song>() {
@Override
public int compare(Song o1, Song o2) {
String o1c = o1.albumName.toLowerCase(Locale.ENGLISH);
String o2c = o2.albumName.toLowerCase(Locale.ENGLISH);
if (o1c.startsWith("the ")) {
o1c = o1c.substring(4);
} else if (o1c.startsWith("a ")) {
o1c = o1c.substring(2);
}
if (o2c.startsWith("the ")) {
o2c = o2c.substring(4);
} else if (o2c.startsWith("a ")) {
o2c = o2c.substring(2);
}
if (!o1c.matches("[a-z]") && o2c.matches("[a-z]")) {
return o2c.compareTo(o1c);
}
return o1c.compareTo(o2c);
}
};
public static final Comparator<Song> PLAY_COUNT_COMPARATOR = (s1, s2) ->
s2.getPlayCount() - s1.getPlayCount();
public static final Comparator<Song> SKIP_COUNT_COMPARATOR = (s1, s2) ->
s2.getSkipCount() - s1.getSkipCount();
public static final Comparator<Song> DATE_ADDED_COMPARATOR = (s1, s2) ->
compareLong(s1.getDateAdded(), s2.getDateAdded());
public static final Comparator<Song> DATE_PLAYED_COMPARATOR = (s1, s2) ->
s2.getPlayDate() - s1.getPlayDate();
public static final Comparator<Song> YEAR_COMPARATOR = (s1, s2) ->
s2.getYear() - s1.getYear();
}
|
package com.wisape.android.logic;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Message;
import android.util.Log;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.wisape.android.WisapeApplication;
import com.wisape.android.activity.StoryMusicActivity;
import com.wisape.android.api.ApiStory;
import com.wisape.android.common.StoryManager;
import com.wisape.android.database.DatabaseHelper;
import com.wisape.android.database.StoryEntity;
import com.wisape.android.database.StoryMusicEntity;
import com.wisape.android.database.StoryMusicTypeEntity;
import com.wisape.android.database.StoryTemplateEntity;
import com.wisape.android.http.HttpUrlConstancts;
import com.wisape.android.http.OkhttpUtil;
import com.wisape.android.model.StoryInfo;
import com.wisape.android.model.StoryMusicInfo;
import com.wisape.android.model.StoryMusicTypeInfo;
import com.wisape.android.model.StorySettingsInfo;
import com.wisape.android.model.StoryTemplateInfo;
import com.wisape.android.model.UserInfo;
import com.wisape.android.network.Downloader;
import com.wisape.android.network.Requester;
import com.wisape.android.util.EnvironmentUtils;
import com.wisape.android.util.Utils;
import com.wisape.android.util.ZipUtils;
import com.wisape.android.widget.StoryMusicAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static com.wisape.android.api.ApiStory.AttrStoryInfo.STORY_STATUS_DELETE;
import static com.wisape.android.api.ApiStory.AttrStoryInfo.STORY_STATUS_RELEASE;
import static com.wisape.android.api.ApiStory.AttrStoryInfo.STORY_STATUS_TEMPORARY;
public class StoryLogic {
private static final String TAG = StoryLogic.class.getSimpleName();
private static final String SUFFIX_STORY_COMPRESS = "wis";
public static final String PREFERENCES = "_story";
private static final String EXTRA_STORY_TEMPLATE_TYPE = "_story_template_type";
private static final String ATTR_ACCESS_TOKEN = "access_token";
public static StoryLogic instance() {
return new StoryLogic();
}
private StoryLogic() {
}
public StoryInfo update(Context context, ApiStory.AttrStoryInfo attr, Object tag) {
final String storyStatus = attr.storyStatus;
if (null == storyStatus || 0 == storyStatus.length() || STORY_STATUS_DELETE.equals(storyStatus)) {
return null;
}
UserInfo user = WisapeApplication.getInstance().getUserInfo();
attr.userId = user.user_id;
Uri storyUri = attr.story;
Log.d(TAG, "#update story' uri:" + storyUri);
StoryInfo story;
if (STORY_STATUS_RELEASE.equals(storyStatus)) {
try {
String zipName = String.format(Locale.US, "%1$s.%2$s", storyUri.getLastPathSegment(), SUFFIX_STORY_COMPRESS);
Log.d(TAG, "#update zipName:" + zipName);
Uri storyZip = ZipUtils.zip(storyUri, EnvironmentUtils.getAppTemporaryDirectory(), zipName);
attr.story = storyZip;
} catch (IOException e) {
throw new IllegalStateException(e);
}
String thumb = Utils.base64ForImage(attr.attrStoryThumb);
attr.storyThumb = thumb;
ApiStory api = ApiStory.instance();
story = api.update(context, attr, tag);
} else {
story = new StoryInfo();
story.createtime = System.currentTimeMillis() + "";
story.small_img = attr.attrStoryThumb.toString();
story.story_url = attr.story.toString();
story.story_name = attr.storyName;
story.description = attr.storyDescription;
story.rec_status = attr.storyStatus;
story.uid = attr.userId;
}
Log.d(TAG, "#update story:" + story);
//save to local
DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
SQLiteDatabase db = helper.getWritableDatabase();
db.beginTransaction();
StoryEntity entity = null;
try {
Dao<StoryEntity, Long> storyDao = helper.getDao(StoryEntity.class);
boolean createIfNeed = true;
if (STORY_STATUS_RELEASE.equals(storyStatus)) {
QueryBuilder<StoryEntity, Long> qb = storyDao.queryBuilder();
Where<StoryEntity, Long> where = qb.where();
where.eq("storyServerId", story.id);
List<StoryEntity> entities = where.query();
int size = (null == entities ? 0 : entities.size());
if (1 == size) {
entity = entities.get(0);
entity.createAt = Long.parseLong(story.createtime);
entity.updateAt = System.currentTimeMillis();
entity.storyThumbUri = story.small_img;
entity.storyUri = story.story_url;
entity.storyName = story.story_name;
entity.storyDesc = story.description;
entity.likeNum = story.like_num;
entity.viewNum = story.view_num;
entity.shareNum = story.share_num;
entity.status = story.rec_status;
storyDao.update(entity);
createIfNeed = false;
} else if (1 < size) {
storyDao.delete(entities);
}
}
if (createIfNeed) {
entity = StoryEntity.transform(story);
entity = storyDao.createIfNotExists(entity);
}
db.setTransactionSuccessful();
} catch (SQLException e) {
Log.e(TAG, "", e);
throw new IllegalStateException(e);
} finally {
db.endTransaction();
OpenHelperManager.releaseHelper();
}
if (STORY_STATUS_TEMPORARY.equals(storyStatus) && null != entity) {
story.id = entity.id;
}
return story;
}
public StoryInfo[] listReleaseStory(Context context, Object tag) {
return null;
}
public StoryInfo[] listStory(Context context, Object tag) {
DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
StoryInfo[] storyArray = null;
try {
Dao<StoryEntity, Long> storyDao = helper.getDao(StoryEntity.class);
QueryBuilder<StoryEntity, Long> builder = storyDao.queryBuilder();
Where<StoryEntity, Long> where = builder.where();
where.eq("status", ApiStory.AttrStoryInfo.STORY_STATUS_RELEASE);
where.eq("status", ApiStory.AttrStoryInfo.STORY_STATUS_TEMPORARY);
builder.orderBy("status", false);
List<StoryEntity> storyList = builder.query();
int size = (null == storyList ? 0 : storyList.size());
if (0 < size) {
storyArray = new StoryInfo[size];
int index = 0;
for (StoryEntity entity : storyList) {
storyArray[index] = StoryEntity.convert(entity);
}
}
} catch (SQLException e) {
Log.e(TAG, "", e);
throw new IllegalStateException(e);
} finally {
OpenHelperManager.releaseHelper();
}
return storyArray;
}
public StoryEntity getStoryLocalById(Context context, int id) {
DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
try {
Dao<StoryEntity, Integer> storyDao = helper.getDao(StoryEntity.class);
return storyDao.queryForId(id);
} catch (SQLException e) {
Log.e(TAG, "", e);
throw new IllegalStateException(e);
} finally {
OpenHelperManager.releaseHelper();
}
}
public boolean saveStoryLocal(Context context, StoryEntity story) {
DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
try {
Dao<StoryEntity, Integer> storyDao = helper.getDao(StoryEntity.class);
Dao.CreateOrUpdateStatus status = storyDao.createOrUpdate(story);
return status.isCreated();
} catch (Exception e) {
Log.e(TAG, "", e);
throw new IllegalStateException(e);
} finally {
OpenHelperManager.releaseHelper();
}
}
public StoryMusicEntity[] listStoryMusicLocal(Context context) {
DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
StoryMusicEntity storyMusicArray[];
Dao<StoryMusicEntity, Long> dao;
try {
dao = helper.getDao(StoryMusicEntity.class);
List<StoryMusicEntity> storyMusicList = dao.queryForAll();
int count = (null == storyMusicList ? 0 : storyMusicList.size());
if (0 == count) {
storyMusicArray = null;
} else {
storyMusicArray = new StoryMusicEntity[count];
storyMusicArray = storyMusicList.toArray(storyMusicArray);
}
} catch (SQLException e) {
Log.e(TAG, "", e);
throw new IllegalStateException(e);
} finally {
OpenHelperManager.releaseHelper();
}
return storyMusicArray;
}
public StoryMusicEntity getStoryMusicLocalById(Context context, int id) {
DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
Dao<StoryMusicEntity, Integer> dao;
try {
dao = helper.getDao(StoryMusicEntity.class);
return dao.queryForId(id);
} catch (SQLException e) {
Log.e(TAG, "", e);
throw new IllegalStateException(e);
} finally {
OpenHelperManager.releaseHelper();
}
}
public StoryMusicTypeEntity[] listStoryMusicTypeLocal(Context context) {
DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
StoryMusicTypeEntity storyMusicTypeArray[];
Dao<StoryMusicTypeEntity, Long> dao;
try {
dao = helper.getDao(StoryMusicTypeEntity.class);
List<StoryMusicTypeEntity> storyMusicTypeList = dao.queryForAll();
int count = (null == storyMusicTypeList ? 0 : storyMusicTypeList.size());
if (0 == count) {
storyMusicTypeArray = null;
} else {
storyMusicTypeArray = new StoryMusicTypeEntity[count];
storyMusicTypeArray = storyMusicTypeList.toArray(storyMusicTypeArray);
}
} catch (SQLException e) {
Log.e(TAG, "", e);
throw new IllegalStateException(e);
} finally {
OpenHelperManager.releaseHelper();
}
return storyMusicTypeArray;
}
public StoryMusicAdapter.StoryMusicDataInfo[] listMusicUIDataLocal(Context context) {
DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
Dao<StoryMusicTypeEntity, Long> musicTypeDao;
Dao<StoryMusicEntity, Long> musicDao;
StoryMusicAdapter.StoryMusicDataInfo[] musicDataArray;
try {
musicTypeDao = helper.getDao(StoryMusicTypeEntity.class);
List<StoryMusicTypeEntity> storyMusicTypeList = musicTypeDao.queryForAll();
int count = (null == storyMusicTypeList ? 0 : storyMusicTypeList.size());
if (0 == count) {
return null;
}
musicDao = helper.getDao(StoryMusicEntity.class);
QueryBuilder<StoryMusicEntity, Long> queryBuilder;
ArrayList<StoryMusicAdapter.StoryMusicDataInfo> storyMusicDataList = new ArrayList(count * 6);
List<StoryMusicEntity> musicList;
int musicCount;
Collections.sort(storyMusicTypeList, new Comparator<StoryMusicTypeEntity>() {
@Override
public int compare(StoryMusicTypeEntity lhs, StoryMusicTypeEntity rhs) {
int compare;
if (lhs.order < rhs.order) {
compare = -1;
} else if (lhs.order > rhs.order) {
compare = 1;
} else {
compare = 0;
}
return compare;
}
});
for (StoryMusicTypeEntity musicType : storyMusicTypeList) {
queryBuilder = musicDao.queryBuilder();
queryBuilder.where().eq("type", musicType.serverId);
queryBuilder.orderBy("name", true);
musicList = queryBuilder.query();
storyMusicDataList.add(musicType);
musicCount = (null == musicList ? 0 : musicList.size());
if (0 < musicCount) {
for (StoryMusicEntity music : musicList) {
if (StoryMusicEntity.STATUS_DOWNLOADING == music.status) {
if (!Downloader.containsDownloader(music.getDownloadUrl())) {
music.status = StoryMusicEntity.STATUS_NONE;
music.musicLocal = "";
musicDao.update(music);
} else {
StoryManager.addAction(StoryMusicActivity.ACTION_DOWNLOAD_MUSIC);
music.setProgress(10);
}
}
}
storyMusicDataList.addAll(musicList);
musicList.clear();
}
queryBuilder.reset();
}
musicDataArray = new StoryMusicAdapter.StoryMusicDataInfo[storyMusicDataList.size()];
musicDataArray = storyMusicDataList.toArray(musicDataArray);
} catch (SQLException e) {
Log.e(TAG, "", e);
throw new IllegalStateException(e);
} finally {
OpenHelperManager.releaseHelper();
}
return musicDataArray;
}
/**
* List music and music's type form server
*
* @param context
* @param tag
* @return maybe is null if no data update.
*/
public StoryMusicAdapter.StoryMusicDataInfo[] listMusicAndType(Context context, Object tag) {
ApiStory api = ApiStory.instance();
StoryMusicTypeInfo[] storyMusicTypeArray = api.listStoryMusicType(context, tag);
int count = (null == storyMusicTypeArray ? 0 : storyMusicTypeArray.length);
if (0 == count) {
return null;
}
StoryMusicInfo[] storyMusicArray = api.listStoryMusic(context, tag);
DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
Dao<StoryMusicTypeEntity, Long> musicTypeDao;
Dao<StoryMusicEntity, Long> musicDao;
SQLiteDatabase db = helper.getWritableDatabase();
boolean hasUpdate = false;
db.beginTransaction();
try {
musicTypeDao = helper.getDao(StoryMusicTypeEntity.class);
long updateAt = System.currentTimeMillis();
StoryMusicTypeEntity musicTypeEntity;
QueryBuilder queryBuilder = musicTypeDao.queryBuilder();
List<StoryMusicTypeEntity> musicTypeList;
int size;
for (StoryMusicTypeInfo musicTypeInfo : storyMusicTypeArray) {
queryBuilder.reset();
musicTypeList = queryBuilder.where().eq("serverId", musicTypeInfo.id).query();
size = (null == musicTypeList ? 0 : musicTypeList.size());
if (1 == size) {
musicTypeEntity = musicTypeList.get(0);
if (!musicTypeEntity.equals(musicTypeInfo)) {
musicTypeEntity.update(musicTypeInfo);
musicTypeEntity.updateAt = updateAt;
musicTypeDao.update(musicTypeEntity);
hasUpdate = true;
}
continue;
} else if (1 < size) {
musicTypeDao.delete(musicTypeList);
}
musicTypeEntity = StoryMusicTypeEntity.transform(musicTypeInfo);
musicTypeEntity.createAt = updateAt;
musicTypeEntity.updateAt = updateAt;
musicTypeDao.createIfNotExists(musicTypeEntity);
hasUpdate = true;
}
musicDao = helper.getDao(StoryMusicEntity.class);
count = (null == storyMusicArray ? 0 : storyMusicArray.length);
if (0 < count) {
StoryMusicEntity musicEntity;
queryBuilder = musicDao.queryBuilder();
List<StoryMusicEntity> musicList;
for (StoryMusicInfo storyMusic : storyMusicArray) {
queryBuilder.reset();
musicList = queryBuilder.where().eq("serverId", storyMusic.id).query();
size = (null == musicList ? 0 : musicList.size());
if (1 == size) {
musicEntity = musicList.get(0);
if (!musicEntity.equals(storyMusic)) {
musicEntity.update(storyMusic);
musicEntity.updateAt = updateAt;
musicDao.update(musicEntity);
hasUpdate = true;
}
continue;
} else if (1 < size) {
musicDao.delete(musicList);
}
musicEntity = StoryMusicEntity.transform(storyMusic);
musicEntity.createAt = updateAt;
musicEntity.updateAt = updateAt;
musicDao.createIfNotExists(musicEntity);
hasUpdate = true;
}
}
db.setTransactionSuccessful();
} catch (SQLException e) {
Log.e(TAG, "", e);
throw new IllegalStateException(e);
} finally {
db.endTransaction();
OpenHelperManager.releaseHelper();
}
StoryMusicAdapter.StoryMusicDataInfo[] dataArray = null;
if (hasUpdate) {
dataArray = listMusicUIDataLocal(context);
}
return dataArray;
}
public StoryTemplateEntity[] listStoryTemplateLocal(Context context) {
DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
StoryTemplateEntity storyTemplateArray[];
Dao<StoryTemplateEntity, Long> dao;
try {
dao = helper.getDao(StoryTemplateEntity.class);
List<StoryTemplateEntity> storyTemplateList = dao.queryForAll();
int count = (null == storyTemplateList ? 0 : storyTemplateList.size());
if (0 == count) {
storyTemplateArray = null;
} else {
storyTemplateArray = storyTemplateList.toArray(new StoryTemplateEntity[count]);
}
} catch (SQLException e) {
Log.e(TAG, "", e);
throw new IllegalStateException(e);
} finally {
OpenHelperManager.releaseHelper();
}
return storyTemplateArray;
}
public List<StoryTemplateInfo> listStoryTemplateLocalByType(Context context,long typeId) {
DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
List<StoryTemplateInfo> storyTemplateInfoList = new ArrayList<>();
Dao<StoryTemplateEntity, Long> dao;
try {
dao = helper.getDao(StoryTemplateEntity.class);
QueryBuilder<StoryTemplateEntity, Long> builder = dao.queryBuilder();
List<StoryTemplateEntity> storyTemplateList = builder.where().eq("type", typeId).query();
if (storyTemplateList == null || storyTemplateList.size() == 0){
return storyTemplateInfoList;
}
for (StoryTemplateEntity entity : storyTemplateList){
storyTemplateInfoList.add(StoryTemplateEntity.convert(entity));
}
} catch (SQLException e) {
Log.e(TAG, "", e);
throw new IllegalStateException(e);
} finally {
OpenHelperManager.releaseHelper();
}
return storyTemplateInfoList;
}
public StoryTemplateEntity getStoryTemplateLocalById(Context context, int id) {
DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
Dao<StoryTemplateEntity, Integer> dao;
try {
dao = helper.getDao(StoryTemplateEntity.class);
return dao.queryForId(id);
} catch (SQLException e) {
Log.e(TAG, "", e);
throw new IllegalStateException(e);
} finally {
OpenHelperManager.releaseHelper();
}
}
public StoryTemplateEntity[] listStoryTemplate(Context context, ApiStory.AttrTemplateInfo attrInfo, Object tag) {
ApiStory api = ApiStory.instance();
StoryTemplateInfo[] storyTemplateInfos = api.listStoryTemplate(context, attrInfo, tag);
int count = (null == storyTemplateInfos ? 0 : storyTemplateInfos.length);
if (0 == count) {
return new StoryTemplateEntity[]{};
}
//insert into database
DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
Dao<StoryTemplateEntity, Long> dao;
SQLiteDatabase db = helper.getWritableDatabase();
db.beginTransaction();
StoryTemplateEntity storyTemplateArray[] = null;
try {
dao = helper.getDao(StoryTemplateEntity.class);
QueryBuilder<StoryTemplateEntity, Long> builder = dao.queryBuilder();
List<StoryTemplateEntity> tempEntities;
tempEntities = builder.where().eq("type", attrInfo.type).query();
int num;
storyTemplateArray = new StoryTemplateEntity[count];
int index = 0;
long updateAt = System.currentTimeMillis();
StoryTemplateEntity oldEntity;
for (StoryTemplateInfo info : storyTemplateInfos) {
StoryTemplateEntity entity = StoryTemplateEntity.transform(info);
builder = dao.queryBuilder();
List<StoryTemplateEntity> entities = builder.where().eq("serverId", entity.serverId).query();
num = (null == entities ? 0 : entities.size());
if (0 < num) {
oldEntity = entities.get(0);
dao.delete(entities);
entity.updateAt = updateAt;
entity.createAt = oldEntity.createAt;
entity.templateLocal = oldEntity.templateLocal;
entity.thumbLocal = oldEntity.thumbLocal;
} else {
entity.createAt = updateAt;
entity.updateAt = updateAt;
if (tempEntities != null){
tempEntities.remove(entity);
}
}
entity = dao.createIfNotExists(entity);
storyTemplateArray[index++] = entity;
}
if (tempEntities != null){
for (StoryTemplateEntity entity : tempEntities){
DeleteBuilder deleteBuilder = dao.deleteBuilder();
deleteBuilder.where().eq("serverId",entity.serverId);
deleteBuilder.delete();
}
}
db.setTransactionSuccessful();
} catch (SQLException e) {
Log.e(TAG, "", e);
throw new IllegalStateException(e);
} finally {
db.endTransaction();
OpenHelperManager.releaseHelper();
}
return storyTemplateArray;
}
public void updateStoryTemplate(Context context, StoryTemplateEntity entity) {
DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
Dao<StoryTemplateEntity, Long> dao;
SQLiteDatabase db = helper.getWritableDatabase();
db.beginTransaction();
try {
dao = helper.getDao(StoryTemplateEntity.class);
dao.update(entity);
db.setTransactionSuccessful();
} catch (SQLException e) {
Log.e(TAG, "", e);
throw new IllegalStateException(e);
} finally {
db.endTransaction();
OpenHelperManager.releaseHelper();
}
}
public void updateStoryMusic(Context context, StoryMusicEntity music) {
DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
Dao<StoryMusicEntity, Long> dao;
SQLiteDatabase db = helper.getWritableDatabase();
db.beginTransaction();
try {
dao = helper.getDao(StoryMusicEntity.class);
dao.update(music);
db.setTransactionSuccessful();
} catch (SQLException e) {
Log.e(TAG, "", e);
} finally {
db.endTransaction();
OpenHelperManager.releaseHelper();
}
}
public JSONArray listStoryTemplateTypeLocal(Context context) {
SharedPreferences preferences = getSharedPreferences(context);
String templateTypeString = preferences.getString(EXTRA_STORY_TEMPLATE_TYPE, null);
if (null == templateTypeString) {
return new JSONArray();
}
JSONArray jsonArray;
try {
jsonArray = new JSONArray(templateTypeString);
} catch (JSONException e) {
Log.e(TAG, "", e);
throw new IllegalStateException(e);
}
return jsonArray;
}
public JSONArray listStoryTemplateType(Context context, Object tag) {
ApiStory api = ApiStory.instance();
JSONArray templateTypeJson = api.listStoryTemplateTypeJson(context, tag);
if (null == templateTypeJson) {
return new JSONArray();
}
//save to local
SharedPreferences preferences = getSharedPreferences(context);
preferences.edit().putString(EXTRA_STORY_TEMPLATE_TYPE, templateTypeJson.toString()).commit();
return templateTypeJson;
}
public Requester.ServerMessage getStoryTemplateUrl(Context context, ApiStory.AttrTemplateInfo attrInfo, Object tag) {
ApiStory api = ApiStory.instance();
return api.getStoryTemplateUrl(context, attrInfo, tag);
}
private SharedPreferences getSharedPreferences(Context context) {
return context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
}
/**
* story
* @param access_token
* @return
*/
public Message getUserStory(String access_token){
StoryInfo defaultStoryInfo = null;
List<StoryInfo> storyInfoList = null;
List<StoryInfo> localStoryInfoList = new ArrayList<>();
Message message = Message.obtain();
message.arg1 = HttpUrlConstancts.STATUS_SUCCESS;
try{
defaultStoryInfo = getDefaultStoryInfo();
if(null != defaultStoryInfo){
downLoadDefaultStory(defaultStoryInfo);
}
}catch (Exception e){
message.obj = e.getMessage();
}
List<StoryEntity> storyEntityList = getUserStoryFromLocal(WisapeApplication.getInstance().getApplicationContext());
localStoryConvertoStroyInfo(storyEntityList,localStoryInfoList);
try{
storyInfoList = getUserStoryFromServer(access_token);
}catch (Exception e){
message.obj = e.getMessage();
}
//story
if(storyInfoList == null){
storyInfoList = new ArrayList<>();
}
if(null != localStoryInfoList && localStoryInfoList.size() > 0){
storyInfoList.addAll(localStoryInfoList);
}
if(null != defaultStoryInfo){
storyInfoList.add(0, defaultStoryInfo);
}
if(storyInfoList.size() == 0){
message.arg1 = HttpUrlConstancts.STATUS_EXCEPTION;
return message;
}
message.obj = storyInfoList;
return message;
}
private void localStoryConvertoStroyInfo(List<StoryEntity> storyEntityList,List<StoryInfo> loacalStroyList){
if(null != storyEntityList && storyEntityList.size() > 0){
for (StoryEntity storyEntity : storyEntityList) {
loacalStroyList.add(StoryEntity.convert(storyEntity));
}
}
}
/**
* story
*/
private StoryInfo getDefaultStoryInfo() throws Exception{
try {
return OkhttpUtil.execute(HttpUrlConstancts.GET_DEFAULT_STORY_INTO, null, StoryInfo.class);
} catch (Exception e) {
throw e;
}
}
/**
* story
*
* @param context
*/
private List<StoryEntity> getUserStoryFromLocal(Context context) {
long userId = WisapeApplication.getInstance().getUserInfo().user_id;
DatabaseHelper databaseHelper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
Dao<StoryEntity, Log> dao;
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.beginTransaction();
try {
dao = databaseHelper.getDao(StoryEntity.class);
return dao.queryBuilder().where().eq("userId", userId).query();
} catch (SQLException e) {
Log.e(TAG, "", e);
return null;
} finally {
db.endTransaction();
OpenHelperManager.releaseHelper();
}
}
/**
* story
*/
private List<StoryInfo> getUserStoryFromServer(String access_token) throws Exception{
Map<String,String> params = new HashMap<>();
params.put(ATTR_ACCESS_TOKEN, access_token);
try{
return OkhttpUtil.execute(params, HttpUrlConstancts.GET_USER_STORY_FROM_SERVER, StoryInfo.class);
}catch (Exception e){
throw e;
}
}
/**
* story
**/
public void downLoadDefaultStory(StoryInfo defaultStroy) {
final File file = new File(StoryManager.getStoryDirectory(), defaultStroy.story_name + ".zip");
if(!file.exists()) {
Log.e(TAG,"story");
OkhttpUtil.downLoadFile(defaultStroy.story_url,file.getPath());
}
}
public StoryEntity saveStory(Context context,StoryEntity storyEntity) {
DatabaseHelper databaseHelper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
Dao<StoryEntity, Integer> dao;
SQLiteDatabase database = databaseHelper.getWritableDatabase();
database.beginTransaction();
try {
dao = databaseHelper.getDao(StoryEntity.class);
StoryEntity entity = dao.createIfNotExists(storyEntity);
database.setTransactionSuccessful();
return entity;
} catch (SQLException e) {
Log.e(TAG,e.getMessage());
return null;
} finally {
database.endTransaction();
OpenHelperManager.releaseHelper();
}
}
}
|
package dwai.textmessagebrowser;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.webkit.WebView;
import android.widget.Toast;
import dwai.textmessagebrowser.R;
public class SMSListener extends BroadcastReceiver {
private int streamSize;
private SharedPreferences preferences;
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String msg_from;
if (bundle != null){
try{
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for(int i=0; i<msgs.length; i++)
{
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
msg_from = msgs[i].getOriginatingAddress();
Log.d("stuff" , msg_from);
if(!msg_from.equals("+18443343982")){
return;
}
Toast.makeText(context,"Loading! Please wait!",
Toast.LENGTH_SHORT).show();
Log.d("stuff", msg_from);
String msgBody = msgs[i].getMessageBody();
Log.d("COSMOS", msgBody);
streamSize = Integer.parseInt(msgBody.substring(msgBody.indexOf("*")+1,msgBody.length()-1));
// Log.d("COSMOS", msgBody.substring(msgBody.indexOf("*")+1,msgBody.length()-1));
// Log.d("COSMOS", msgBody.substring(0,msgBody.indexOf("%")));
MainActivity.fullTextMessage.addText(msgBody);
//This, to my knowledge, gets rid of this text message.
abortBroadcast();
}
Log.d("COSMOS", "Texts-Size :\t"+MainActivity.fullTextMessage.texts.size());
if(MainActivity.fullTextMessage.texts.size() == streamSize) {
MainActivity.fullTextMessage.sortMessages();
Log.d("COSMOS", "Texts ArrayList:\t"+MainActivity.fullTextMessage.texts.toString());
String fullHTML = MainActivity.fullTextMessage.getDecompressedMessages();
Log.d("COSMOS", "Full HTML:\t"+fullHTML);
if (MainActivity.webView != null) {
(MainActivity.webView).loadMarkdown(fullHTML, "file:///android_asset/main.css");
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
|
package fi.jyu.ln.luontonurkka;
import android.*;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private static final int MY_PERMISSION_ACCESS_COARSE_LOCATION = 11;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng loc = new LatLng(62.232436, 25.737582);
mMap.addMarker(new MarkerOptions().position(loc).title("Marker in device location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
}
}
|
package io.github.aectann.fitwater;
import android.app.Application;
import dagger.ObjectGraph;
import timber.log.Timber;
public class FitWater extends Application {
private ObjectGraph objectGraph;
@Override
public void onCreate() {
if (BuildConfig.DEBUG) {
Timber.plant(new Timber.DebugTree());
} else {
// TODO Crashlytics.start(this);
// TODO Timber.plant(new CrashlyticsTree());
}
objectGraph = ObjectGraph.create(new FitWaterModule(this));
objectGraph.get(CredentialsStore.class);
}
public void inject(Object object) {
objectGraph.inject(object);
}
}
|
package jp.blanktar.ruumusic;
import java.io.File;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.os.Handler;
import android.widget.TextView;
import android.widget.SeekBar;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.app.AlertDialog;
import android.content.DialogInterface;
public class PlayerFragment extends Fragment {
private File currentMusicPath;
private boolean playing;
private int duration = -1;
private long basetime = -1;
private int current = -1;
private String repeatMode;
private boolean shuffleMode;
private Timer updateProgressTimer;
private boolean firstMessage = true;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_player, container, false);
view.findViewById(R.id.playButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startRuuService(playing ? "RUU_PAUSE" : "RUU_PLAY");
}
});
view.findViewById(R.id.nextButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startRuuService("RUU_NEXT");
}
});
view.findViewById(R.id.prevButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startRuuService("RUU_PREV");
}
});
view.findViewById(R.id.repeatButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), RuuService.class);
intent.setAction("RUU_REPEAT");
if (repeatMode != null && repeatMode.equals("loop")) {
intent.putExtra("mode", "one");
} else if (repeatMode != null && repeatMode.equals("one")) {
intent.putExtra("mode", "off");
} else {
intent.putExtra("mode", "loop");
}
getActivity().startService(intent);
}
});
view.findViewById(R.id.shuffleButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), RuuService.class);
intent.setAction("RUU_SHUFFLE");
intent.putExtra("mode", !shuffleMode);
getActivity().startService(intent);
}
});
view.findViewById(R.id.musicPath).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(currentMusicPath != null) {
MainActivity main = (MainActivity) getActivity();
if (main != null) {
main.moveToPlaylist(currentMusicPath.getParentFile());
}
}
}
});
((SeekBar)view.findViewById(R.id.seekBar)).setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
Intent intent = new Intent(getActivity(), RuuService.class);
intent.setAction("RUU_SEEK");
intent.putExtra("newtime", progress);
getActivity().startService(intent);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) { }
@Override
public void onStopTrackingTouch(SeekBar seekBar) { }
});
return view;
}
@Override
public void onResume() {
super.onResume();
startRuuService("RUU_PING");
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("RUU_STATUS");
intentFilter.addAction("RUU_FAILED_OPEN");
intentFilter.addAction("RUU_NOT_FOUND");
getActivity().registerReceiver(receiver, intentFilter);
final Handler handler = new Handler();
updateProgressTimer = new Timer(true);
updateProgressTimer.schedule(new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
updateProgress();
}
});
}
}, 500, 500);
}
@Override
public void onPause() {
super.onPause();
getActivity().unregisterReceiver(receiver);
updateProgressTimer.cancel();
}
final private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
switch(intent.getAction()) {
case "RUU_FAILED_OPEN":
onFailPlay(R.string.failed_open_music, intent.getStringExtra("path"));
break;
case "RUU_NOT_FOUND":
onFailPlay(R.string.music_not_found, intent.getStringExtra("path"));
break;
case "RUU_STATUS":
onReceiveStatus(intent);
break;
}
}
};
private void onReceiveStatus(Intent intent) {
playing = intent.getBooleanExtra("playing", false);
duration = intent.getIntExtra("duration", -1);
basetime = intent.getLongExtra("basetime", -1);
current = intent.getIntExtra("current", -1);
repeatMode = intent.getStringExtra("repeat");
shuffleMode = intent.getBooleanExtra("shuffle", false);
View view = getView();
if(view != null) {
ImageButton playButton = (ImageButton) view.findViewById(R.id.playButton);
if (playing) {
playButton.setImageResource(R.drawable.ic_pause);
} else {
playButton.setImageResource(R.drawable.ic_play_arrow);
}
ImageButton repeatButton = (ImageButton) view.findViewById(R.id.repeatButton);
switch (repeatMode) {
case "loop":
repeatButton.setImageResource(R.drawable.ic_repeat);
break;
case "one":
repeatButton.setImageResource(R.drawable.ic_repeat_one);
break;
default:
repeatButton.setImageResource(R.drawable.ic_trending_flat);
break;
}
ImageButton shuffleButton = (ImageButton) view.findViewById(R.id.shuffleButton);
if (shuffleMode) {
shuffleButton.setImageResource(R.drawable.ic_shuffle);
} else {
shuffleButton.setImageResource(R.drawable.ic_reorder);
}
((SeekBar) view.findViewById(R.id.seekBar)).setMax(duration);
}
String path = intent.getStringExtra("path");
if(path == null) {
if(firstMessage) {
((MainActivity) getActivity()).moveToPlaylist();
firstMessage = false;
}
}else{
currentMusicPath = new File(path);
updateRoot();
}
}
public void updateRoot() {
if(currentMusicPath != null) {
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(getActivity());
String path = currentMusicPath.getParent().substring(preference.getString("root_directory", "").length()) + "/";
if (!path.startsWith("/")) {
path = "/" + path;
}
View view = getView();
if(view != null) {
((TextView) view.findViewById(R.id.musicPath)).setText(path);
((TextView) view.findViewById(R.id.musicName)).setText(currentMusicPath.getName());
}
}
}
private String msec2str(long msec) {
return ((int)Math.floor(msec/1000/60)) + ":" + String.format("%02d", Math.round(msec/1000)%60);
}
private void updateProgress() {
if(getView() == null) {
return;
}
TextView text = (TextView)getView().findViewById(R.id.progress);
SeekBar bar = (SeekBar)getView().findViewById(R.id.seekBar);
String currentStr = "-";
if(playing && basetime >= 0) {
currentStr = msec2str(System.currentTimeMillis() - basetime);
bar.setProgress((int)(System.currentTimeMillis() - basetime));
}else if(!playing && current >= 0) {
currentStr = msec2str(current);
bar.setProgress(current);
}else {
bar.setProgress(0);
}
String durationStr = "-";
if(duration >= 0) {
durationStr = msec2str(duration);
}
text.setText(currentStr + " / " + durationStr);
}
private void onFailPlay(final int messageId, final String path) {
(new AlertDialog.Builder(getActivity()))
.setTitle(getString(messageId))
.setMessage(path)
.setPositiveButton(
getString(R.string.on_error_next_music),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startRuuService("RUU_NEXT");
}
}
)
.setNegativeButton(
getString(R.string.on_error_cancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { }
}
)
.create().show();
}
private void startRuuService(String action) {
Intent intent = new Intent(getActivity(), RuuService.class);
intent.setAction(action);
getActivity().startService(intent);
}
}
|
package org.redcross.openmapkit;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.TouchDelegate;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.mapbox.mapboxsdk.geometry.BoundingBox;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.overlay.Marker;
import com.mapbox.mapboxsdk.views.MapView;
import com.spatialdev.osm.OSMMap;
import com.spatialdev.osm.events.OSMSelectionListener;
import com.spatialdev.osm.model.OSMElement;
import com.spatialdev.osm.model.OSMNode;
import org.redcross.openmapkit.odkcollect.ODKCollectHandler;
import org.redcross.openmapkit.odkcollect.tag.ODKTag;
import org.redcross.openmapkit.tagswipe.TagSwipeActivity;
import java.io.File;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
public class MapActivity extends AppCompatActivity implements OSMSelectionListener {
protected static final String PREVIOUS_LAT = "org.redcross.openmapkit.PREVIOUS_LAT";
protected static final String PREVIOUS_LNG = "org.redcross.openmapkit.PREVIOUS_LNG";
protected static final String PREVIOUS_ZOOM = "org.redcross.openmapkit.PREVIOUS_ZOOM";
private static String version = "";
protected MapView mapView;
protected OSMMap osmMap;
protected ListView mTagListView;
protected ImageButton mCloseListViewButton;
protected ImageButton tagButton;
protected ImageButton deleteButton;
protected ImageButton moveButton;
protected Button nodeModeButton;
protected Button addTagsButton;
protected LinearLayout mTopLinearLayout;
protected LinearLayout mBottomLinearLayout;
protected TextView mTagTextView;
protected Basemap basemap;
protected TagListAdapter tagListAdapter;
private boolean nodeMode = false;
private boolean moveNodeMode = false;
/**
* intent request codes
*/
private static final int ODK_COLLECT_TAG_ACTIVITY_CODE = 2015;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
determineVersion();
if(android.os.Build.VERSION.SDK_INT >= 21) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(getResources().getColor(R.color.osm_light_green));
}
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setIcon(R.mipmap.ic_omk_nobg);
}
// create directory structure for app if needed
ExternalStorage.checkOrCreateAppDirs();
// Register the intent to the ODKCollect handler
// This will determine if we are in ODK Collect Mode or not.
ODKCollectHandler.registerIntent(getIntent());
//set layout
setContentView(R.layout.activity_map);
//get the layout the ListView is nested in
mBottomLinearLayout = (LinearLayout)findViewById(R.id.bottomLinearLayout);
//the ListView from layout
mTagListView = (ListView)findViewById(R.id.tagListView);
//the ListView close image button
mCloseListViewButton = (ImageButton)findViewById(R.id.imageViewCloseList);
//get the layout the Map is nested in
mTopLinearLayout = (LinearLayout)findViewById(R.id.topLinearLayout);
//get map from layout
mapView = (MapView)findViewById(R.id.mapView);
// initialize basemap object
basemap = new Basemap(this);
initializeOsmXml();
// add user location toggle button
initializeLocationButton();
// setup delete and move buttons
initializeDeleteAndMoveButtons();
initializeNodeModeButton();
initializeAddNodeButtons();
initializeMoveNodeButtons();
positionMap();
initializeListView();
}
@Override
protected void onPause() {
super.onPause();
saveMapPosition();
}
protected void saveMapPosition() {
LatLng c = mapView.getCenter();
float lat = (float) c.getLatitude();
float lng = (float) c.getLongitude();
float z = mapView.getZoomLevel();
SharedPreferences.Editor editor = getPreferences(Context.MODE_PRIVATE).edit();
editor.putFloat(PREVIOUS_LAT, lat);
editor.putFloat(PREVIOUS_LNG, lng);
editor.putFloat(PREVIOUS_ZOOM, z);
editor.apply();
}
protected void positionMap() {
SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);
double lat = (double) pref.getFloat(PREVIOUS_LAT, -999);
double lng = (double) pref.getFloat(PREVIOUS_LNG, -999);
float z = pref.getFloat(PREVIOUS_ZOOM, -999);
// no shared pref
if (lat == -999 || lng == -999 || z == -999) {
mapView.setUserLocationEnabled(true);
mapView.goToUserLocation(true);
}
// there is a shared pref
else {
LatLng c = new LatLng(lat, lng);
mapView.setCenter(c);
mapView.setZoom(z);
}
}
/**
* For initializing the ListView of tags
*/
protected void initializeListView() {
//the ListView title
mTagTextView = (TextView)findViewById(R.id.tagTextView);
mTagTextView.setText(R.string.tagListViewTitle);
//hide the ListView by default
proportionMapAndList(100, 0);
//handle when user taps on the close button in the list view
mCloseListViewButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
proportionMapAndList(100, 0);
}
});
//increase the 'hit area' of the down arrow
View parent = findViewById(R.id.bottomLinearLayout);
parent.post(new Runnable() {
public void run() {
Rect delegateArea = new Rect();
ImageButton delegate = mCloseListViewButton;
delegate.getHitRect(delegateArea);
delegateArea.top -= 100;
delegateArea.bottom += 100;
delegateArea.left -= 100;
delegateArea.right += 100;
TouchDelegate expandedArea = new TouchDelegate(delegateArea, delegate);
if (View.class.isInstance(delegate.getParent())) {
((View) delegate.getParent()).setTouchDelegate(expandedArea);
}
}
});
View.OnClickListener tagSwipeLaunchListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
//launch the TagSwipeActivity
Intent tagSwipe = new Intent(getApplicationContext(), TagSwipeActivity.class);
startActivityForResult(tagSwipe, ODK_COLLECT_TAG_ACTIVITY_CODE);
}
};
// tag button
tagButton = (ImageButton)findViewById(R.id.tagButton);
tagButton.setOnClickListener(tagSwipeLaunchListener);
// add tags button
addTagsButton = (Button)findViewById(R.id.addTagsBtn);
addTagsButton.setOnClickListener(tagSwipeLaunchListener);
//handle list view item taps
mTagListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String tappedKey = tagListAdapter.getTagKeyForIndex(position);
//launch the TagSwipeActivity and pass the key
Intent tagSwipe = new Intent(getApplicationContext(), TagSwipeActivity.class);
tagSwipe.putExtra("TAG_KEY", tappedKey);
startActivityForResult(tagSwipe, ODK_COLLECT_TAG_ACTIVITY_CODE);
}
});
}
/**
* For identifying an OSM element and presenting it's tags in the ListView
* @param osmElement The target OSMElement.
*/
protected void identifyOSMFeature(OSMElement osmElement) {
int numRequiredTags = 0;
if (ODKCollectHandler.isODKCollectMode()) {
Collection<ODKTag> requiredTags = ODKCollectHandler.getODKCollectData().getRequiredTags();
numRequiredTags = requiredTags.size();
}
int tagCount = osmElement.getTags().size();
if (tagCount > 0 || numRequiredTags > 0) {
mTagListView.setVisibility(View.VISIBLE);
addTagsButton.setVisibility(View.GONE);
} else {
mTagListView.setVisibility(View.GONE);
addTagsButton.setVisibility(View.VISIBLE);
}
/**
* If we have a node that is selected, we want to activate the
* delete and move buttons. Ways should not be editable.
*/
if (osmElement instanceof OSMNode) {
deleteButton.setVisibility(View.VISIBLE);
moveButton.setVisibility(View.VISIBLE);
} else {
deleteButton.setVisibility(View.GONE);
moveButton.setVisibility(View.GONE);
}
//pass the tags to the list adapter
tagListAdapter = new TagListAdapter(this, osmElement);
//set the ListView's adapter
mTagListView.setAdapter(tagListAdapter);
//show the ListView under the map
proportionMapAndList(50, 50);
}
/**
* For setting the proportions of the Map weight and the ListView weight for dual display
* @param topWeight Refers to the layout weight. Note, topWeight + bottomWeight must equal the weight sum of 100
* @param bottomWeight Referes to the layotu height. Note, bottomWeight + topWeight must equal the weight sum of 100
*/
protected void proportionMapAndList(int topWeight, int bottomWeight) {
LinearLayout.LayoutParams topLayoutParams = (LinearLayout.LayoutParams)mTopLinearLayout.getLayoutParams();
LinearLayout.LayoutParams bottomLayoutParams = (LinearLayout.LayoutParams)mBottomLinearLayout.getLayoutParams();
//update weight of top and bottom linear layouts
mTopLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(topLayoutParams.width, topLayoutParams.height, topWeight));
mBottomLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(bottomLayoutParams.width, bottomLayoutParams.height, bottomWeight));
}
/**
* Loads OSM XML stored on the device.
*/
protected void initializeOsmXml() {
try {
OSMMapBuilder.buildMapFromExternalStorage(this);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* For instantiating the location button and setting up its tap event handler
*/
protected void initializeLocationButton() {
final ImageButton locationButton = (ImageButton)findViewById(R.id.locationButton);
//set tap event
locationButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean userLocationIsEnabled = mapView.getUserLocationEnabled();
if (userLocationIsEnabled) {
mapView.setUserLocationEnabled(false);
locationButton.setBackground(getResources().getDrawable(R.drawable.roundedbutton));
} else {
mapView.setUserLocationEnabled(true);
mapView.goToUserLocation(true);
locationButton.setBackground(getResources().getDrawable(R.drawable.roundedbutton_blue));
}
}
});
}
protected void initializeDeleteAndMoveButtons() {
deleteButton = (ImageButton)findViewById(R.id.deleteBtn);
moveButton = (ImageButton)findViewById(R.id.moveNodeModeBtn);
deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
deleteNode();
}
});
moveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
toggleMoveNodeMode();
}
});
}
protected void initializeNodeModeButton() {
nodeModeButton = (Button)findViewById(R.id.nodeModeButton);
nodeModeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
toggleNodeMode();
}
});
}
protected void initializeAddNodeButtons() {
final Button addNodeBtn = (Button)findViewById(R.id.addNodeBtn);
final ImageButton addNodeMarkerBtn = (ImageButton)findViewById(R.id.addNodeMarkerBtn);
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
OSMNode node = osmMap.addNode();
toggleNodeMode();
node.select();
identifyOSMFeature(node);
}
};
addNodeMarkerBtn.setOnClickListener(listener);
addNodeBtn.setOnClickListener(listener);
}
protected void initializeMoveNodeButtons() {
final Button moveNodeBtn = (Button)findViewById(R.id.moveNodeBtn);
final ImageButton moveNodeMarkerBtn = (ImageButton)findViewById(R.id.moveNodeMarkerBtn);
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
osmMap.moveNode();
toggleMoveNodeMode();
}
};
moveNodeBtn.setOnClickListener(listener);
moveNodeMarkerBtn.setOnClickListener(listener);
}
private void toggleNodeMode() {
final Button addNodeBtn = (Button)findViewById(R.id.addNodeBtn);
final ImageButton addNodeMarkerBtn = (ImageButton)findViewById(R.id.addNodeMarkerBtn);
if (nodeMode) {
addNodeBtn.setVisibility(View.GONE);
addNodeMarkerBtn.setVisibility(View.GONE);
nodeModeButton.setBackground(getResources().getDrawable(R.drawable.roundedbutton));
} else {
addNodeBtn.setVisibility(View.VISIBLE);
addNodeMarkerBtn.setVisibility(View.VISIBLE);
nodeModeButton.setBackground(getResources().getDrawable(R.drawable.roundedbutton_green));
OSMElement.deselectAll();
mapView.invalidate();
}
nodeMode = !nodeMode;
}
private void deleteNode() {
final OSMNode deletedNode = osmMap.deleteNode();
Snackbar.make(findViewById(R.id.mapActivity),
"Deleted Node",
Snackbar.LENGTH_LONG)
.setAction("UNDO", new View.OnClickListener() {
// undo action
@Override
public void onClick(View v) {
osmMap.addNode(deletedNode);
}
})
.setActionTextColor(Color.rgb(126,188,111))
.show();
}
private void toggleMoveNodeMode() {
final ImageButton moveNodeModeBtn = (ImageButton)findViewById(R.id.moveNodeModeBtn);
final ImageButton moveNodeMarkerBtn = (ImageButton)findViewById(R.id.moveNodeMarkerBtn);
final Button moveNodeBtn = (Button)findViewById(R.id.moveNodeBtn);
if (moveNodeMode) {
moveNodeMarkerBtn.setVisibility(View.GONE);
moveNodeBtn.setVisibility(View.GONE);
moveNodeModeBtn.setBackground(getResources().getDrawable(R.drawable.roundedbutton));
showSelectedMarker();
} else {
moveNodeMarkerBtn.setVisibility(View.VISIBLE);
moveNodeBtn.setVisibility(View.VISIBLE);
moveNodeModeBtn.setBackground(getResources().getDrawable(R.drawable.roundedbutton_orange));
hideSelectedMarker();
proportionMapAndList(100, 0);
}
moveNodeMode = !moveNodeMode;
}
private void hideSelectedMarker() {
LinkedList<OSMElement> selectedElements = OSMElement.getSelectedElements();
if (selectedElements.size() < 1) return;
OSMNode node = (OSMNode)selectedElements.getFirst();
Marker marker = node.getMarker();
if (marker != null) {
node.getMarker().setVisibility(false);
}
mapView.invalidate();
}
private void showSelectedMarker() {
LinkedList<OSMElement> selectedElements = OSMElement.getSelectedElements();
if (selectedElements.size() < 1) return;
OSMNode node = (OSMNode)selectedElements.getFirst();
Marker marker = node.getMarker();
if (marker != null) {
node.getMarker().setVisibility(true);
}
mapView.invalidate();
}
/**
* For presenting a dialog to allow the user to choose which OSM XML files to use that have been uploaded to their device's openmapkit/osm folder
*/
private void presentOSMOptions() {
final File[] osmFiles = ExternalStorage.fetchOSMXmlFiles();
String[] osmFileNames = ExternalStorage.fetchOSMXmlFileNames();
final boolean[] checkedOsmFiles = OSMMapBuilder.isFileArraySelected(osmFiles);
final Set<File> filesToAdd = new HashSet<>();
final Set<File> filesToRemove = new HashSet<>();
if (osmFileNames.length > 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.osmChooserDialogTitle));
builder.setMultiChoiceItems(osmFileNames, checkedOsmFiles, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i, boolean isChecked) {
// load the file
if (isChecked) {
File fileToAdd = osmFiles[i];
filesToAdd.add(fileToAdd);
}
// remove the file
else {
File fileToRemove = osmFiles[i];
filesToRemove.add(fileToRemove);
}
}
});
//handle OK tap event of dialog
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
OSMMapBuilder.removeOSMFilesFromModel(filesToRemove);
OSMMapBuilder.addOSMFilesToModel(filesToAdd);
}
});
//handle cancel button tap event of dialog
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
//user clicked cancel
}
});
builder.show();
} else {
Toast prompt = Toast.makeText(getApplicationContext(), "Please add .osm files to " + ExternalStorage.getOSMDir(), Toast.LENGTH_LONG);
prompt.show();
}
}
private void askIfDownloadOSM() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.downloadOSMTitle);
builder.setMessage(R.string.downloadOSMMessage);
builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// just dismiss
}
});
builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
downloadOSM();
}
});
builder.show();
}
private void downloadOSM() {
BoundingBox bbox = mapView.getBoundingBox();
OSMDownloader downloader = new OSMDownloader(this, bbox);
downloader.execute();
}
/**
* OSMMapBuilder sets a reference to OSMMap in this class.
*
* @param osmMap
*/
public void setOSMMap(OSMMap osmMap) {
this.osmMap = osmMap;
}
/**
* For adding action items to the action bar
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_map, menu);
return true;
}
/**
* For handling when a user taps on a menu item (top right)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
super.onOptionsItemSelected(item);
int id = item.getItemId();
if (id == R.id.osmdownloader) {
askIfDownloadOSM();
return true;
} else if (id == R.id.mbtilessettings) {
basemap.presentMBTilesOptions();
return true;
} else if (id == R.id.osmsettings) {
presentOSMOptions();
return true;
} else if (id == R.id.action_save_to_odk_collect) {
saveToODKCollectAndExit();
return true;
}
return false;
}
@Override
public void selectedElementsChanged(LinkedList<OSMElement> selectedElements) {
if (selectedElements != null && selectedElements.size() > 0) {
// tagsButton.setVisibility(View.VISIBLE);
//fetch the tapped feature
OSMElement tappedOSMElement = selectedElements.get(0);
//present OSM Feature tags in bottom ListView
identifyOSMFeature(tappedOSMElement);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ( requestCode == ODK_COLLECT_TAG_ACTIVITY_CODE ) {
if(resultCode == RESULT_OK) {
saveToODKCollectAndExit();
}
}
}
protected void saveToODKCollectAndExit() {
String osmXmlFileFullPath = ODKCollectHandler.getODKCollectData().getOSMFileFullPath();
String osmXmlFileName = ODKCollectHandler.getODKCollectData().getOSMFileName();
Intent resultIntent = new Intent();
resultIntent.putExtra("OSM_PATH", osmXmlFileFullPath);
resultIntent.putExtra("OSM_FILE_NAME", osmXmlFileName);
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
public MapView getMapView() {
return mapView;
}
private void determineVersion() {
try {
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
version = pInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
public static String getVersion() {
return version;
}
}
|
package uk.ac.tees.donut.squad;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import uk.ac.tees.donut.squad.squads.Interest;
import uk.ac.tees.donut.squad.squads.Squad;
import uk.ac.tees.donut.squad.users.User;
import android.content.Intent;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import static uk.ac.tees.donut.squad.squads.Interest.*;
public class MainActivity extends AppCompatActivity
{
Button btnNewMeetup;
Button btnViewMeetups;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//TEST USER WITH MOVIES IN THEIR mySquads
// User user = new User("defaultUser");
// Squad movies = new Squad("Movie Squad", MOVIES, "A collection of avid movie-goers");
// User user = new User("defaultUser");
// Squad movies = new Squad("Movie Squad", MOVIES, "A collection of avid movie-goers");
// user.addInterest(MOVIES);
// user.setName("James");
// user.setHostable(true);
}
//Click functionality
public void openProfile(View view)
{
Intent intent = new Intent(this, ProfileActivity.class);
startActivity(intent);
}
public void openSquads(View view)
{
Intent intent = new Intent(this, SquadsActivity.class);
startActivity(intent);
}
public void openEvents(View view)
{
Intent intent = new Intent(this, ViewMeetups.class);
startActivity(intent);
}
public void openHost(View view)
{
Intent intent = new Intent(this, NewMeetup.class);
startActivity(intent);
}
public void openSettings(View view)
{
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
}
|
public class Board {
public int space;
public String[] cards = {"Everthing seems quiet, that's strange....",
"Time to take a rest....",
"Fight the odd battle.",
"This, I daresay, is quite strange...."
}
public String[] special = {"Ooh, a dragon!", "Hide!", "Ooh boy."}
public void start() {
space = 1;
}
public void nextTurn() {
if(space >= 25) {
System.out.println("You win!");
System.exit(0);
}
int s = Math.random();
if(s > 5 || s < 0) {
for(String str : cards) {
System.out.println(str);
}
space++;
}
else {
for(String str : special) {
System.out.println(str);
}
int nextSpace = space + Math.random();
nextSpace = space;
}
}
}
|
package com.axelor.db;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import com.axelor.db.mapper.Mapper;
import com.axelor.db.mapper.Property;
import com.axelor.inject.Beans;
public class JpaRepository<T extends Model> implements Repository<T> {
protected Class<T> modelClass;
protected JpaRepository(Class<T> modelClass) {
this.modelClass = modelClass;
}
@Override
public List<Property> fields() {
final Property[] fields = JPA.fields(modelClass);
if (fields == null) {
return null;
}
return Arrays.asList(fields);
}
@Override
public Query<T> all() {
return JPA.all(modelClass);
}
/**
* Get the {@link Query} instance of the given type.
*
* @param type
* the subtype of the managed model class.
* @return instance of {@link Query}
*/
public <U extends T> Query<U> all(Class<U> type) {
return JPA.all(type);
}
@Override
public T create(Map<String, Object> values) {
return Mapper.toBean(modelClass, values);
}
@Override
public T copy(T entity, boolean deep) {
return JPA.copy(entity, deep);
}
@Override
public T find(Long id) {
return JPA.find(modelClass, id);
}
@Override
public T save(T entity) {
return JPA.save(entity);
}
/**
* Make an entity managed and persistent.
*
* @see EntityManager#persist(Object)
*/
public void persist(T entity) {
JPA.persist(entity);
}
/**
* Merge the state of the given entity into the current persistence context.
*
* @see EntityManager#merge(Object)
*/
public T merge(T entity) {
return JPA.merge(entity);
}
@Override
public void remove(T entity) {
JPA.remove(entity);
}
/**
* Refresh the state of the instance from the database, overwriting changes
* made to the entity, if any.
*
* @see EntityManager#refresh(Object)
*/
@Override
public void refresh(T entity) {
JPA.refresh(entity);
}
/**
* Synchronize the persistence context to the underlying database.
*
* @see EntityManager#flush()
*/
@Override
public void flush() {
JPA.flush();
}
@Override
public Map<String, Object> validate(Map<String, Object> json, Map<String, Object> context) {
return json;
}
@Override
public Map<String, Object> populate(Map<String, Object> json, Map<String, Object> context) {
return json;
}
@SuppressWarnings("unchecked")
public static <U extends Model> JpaRepository<U> of(Class<U> type) {
final Class<?> klass = JpaScanner.findRepository(type.getSimpleName() + "Repository");
if (klass != null) {
final JpaRepository<U> repo = (JpaRepository<U>) Beans.get(klass);
if (repo.modelClass.isAssignableFrom(type)) {
return repo;
}
}
return Beans.inject(new JpaRepository<>(type));
}
}
|
package com.axelor.mail;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import com.axelor.common.StringUtils;
import com.google.common.base.Preconditions;
/**
* The default implementation of {@link MailAccount} for SMPT accounts.
*
*/
public class SmtpAccount implements MailAccount {
public static final String ENCRYPTION_TLS = "tls";
public static final String ENCRYPTION_SSL = "ssl";
public static final String DEFAULT_PORT = "25";
private String host;
private String port;
private String user;
private String password;
private String encryption;
private int connectionTimeout = DEFAULT_TIMEOUT;
private int timeout = DEFAULT_TIMEOUT;
private Properties properties;
private Session session;
/**
* Create a non-authenticating SMTP account.
*
* @param host
* the smtp server host
* @param port
* the smtp server port
*/
public SmtpAccount(String host, String port) {
Preconditions.checkNotNull(host, "host can't be null");
this.host = host;
this.port = port;
}
/**
* Create an authenticating SMTP account.
*
* @param host
* the smtp server host
* @param port
* the smtp server port
* @param user
* the smtp server login user name
* @param password
* the smtp server login passowrd
* @param encryption
* the smtp encryption scheme (tls or ssl)
*/
public SmtpAccount(String host, String port, String user, String password, String encryption) {
this(host, port);
this.user = user;
this.password = password;
this.encryption = encryption;
}
private Session init() {
final boolean authenticating = !StringUtils.isBlank(user);
final Properties props = new Properties();
final String port = StringUtils.isBlank(this.port) ? DEFAULT_PORT : this.port;
props.setProperty("mail.smtp.connectiontimeout", "" + DEFAULT_TIMEOUT);
props.setProperty("mail.smtp.timeout", "" + DEFAULT_TIMEOUT);
if (properties != null) {
props.putAll(properties);
}
props.setProperty("mail.smtp.host", host);
props.setProperty("mail.smtp.port", port);
props.setProperty("mail.smtp.auth", "" + authenticating);
if (!StringUtils.isBlank(user)) {
props.setProperty("mail.smtp.from", user);
}
// respect manually set timeout
if (connectionTimeout != DEFAULT_TIMEOUT) {
props.setProperty("mail.smtp.connectiontimeout", "" + connectionTimeout);
}
if (timeout != DEFAULT_TIMEOUT) {
props.setProperty("mail.smtp.timeout", "" + timeout);
}
if (!authenticating) {
return Session.getInstance(props);
}
if (ENCRYPTION_TLS.equals(encryption)) {
props.setProperty("mail.smtp.starttls.enable", "true");
}
if (ENCRYPTION_SSL.equals(encryption)) {
props.setProperty("mail.smtp.socketFactory.port", port);
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
}
final Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
};
return Session.getInstance(props, authenticator);
}
@Override
public void setConnectionTimeout(int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
@Override
public void setTimeout(int timeout) {
this.timeout = timeout;
}
@Override
public void setProperties(Properties properties) {
this.properties = new Properties(properties);
}
@Override
public Session getSession() {
if (session == null) {
session = init();
}
return session;
};
}
|
package afc.ant.modular;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import org.apache.tools.ant.MagicNames;
import org.apache.tools.ant.Project;
import junit.framework.Assert;
public class TestUtil
{
public static <T> HashSet<T> set(final T... elements)
{
return new HashSet<T>(Arrays.asList(elements));
}
public static <K, V> HashMap<K, V> map(final Object... parts)
{
Assert.assertTrue(parts.length % 2 == 0);
final HashMap<K, V> map = new HashMap<K, V>();
for (int i = 0; i < parts.length;) {
@SuppressWarnings("unchecked") // the caller is responsible for passing correct objects
final K key = (K) parts[i++];
@SuppressWarnings("unchecked") // the caller is responsible for passing correct objects
final V value = (V) parts[i++];
map.put(key, value);
}
return map;
}
public static void assertCallTargetState(final MockCallTargetTask task, final boolean executed,
final String target, final boolean inheritAll, final boolean inheritRefs, final String moduleProperty,
final ModuleInfo proto, final Map<String, Object> properties)
{
assertCallTargetState(task, executed, target, inheritAll, inheritRefs, moduleProperty, proto,
properties, Collections.<String, Object>emptyMap());
}
public static void assertCallTargetState(final MockCallTargetTask task, final boolean executed,
final String target, final boolean inheritAll, final boolean inheritRefs, final String moduleProperty,
final ModuleInfo proto, final Map<String, Object> properties, final Map<String, Object> references)
{
Assert.assertEquals(executed, task.executed);
Assert.assertEquals(target, task.target);
Assert.assertEquals(inheritAll, task.inheritAll);
Assert.assertEquals(inheritRefs, task.inheritRefs);
final Object moduleObj = task.ownProject.getProperties().get(moduleProperty);
Assert.assertTrue(moduleObj instanceof Module);
final Module module = (Module) moduleObj;
Assert.assertEquals(proto.getPath(), module.getPath());
Assert.assertEquals(proto.getAttributes(), module.getAttributes());
final HashSet<String> depPaths = new HashSet<String>();
for (final Module dep : module.getDependencies()) {
Assert.assertTrue(depPaths.add(dep.getPath()));
}
Assert.assertEquals(proto.getDependencies(), depPaths);
// merging module property into the properties passed. The module object is not freely available
final HashMap<String, Object> propsWithModule = new HashMap<String, Object>(properties);
propsWithModule.put(moduleProperty, module);
final Map<?, ?> actualProperties = task.ownProject.getProperties();
actualProperties.remove(MagicNames.PROJECT_BASEDIR);
Assert.assertEquals(propsWithModule, actualProperties);
assertReferences(task.ownProject, references);
}
public static void assertCallTargetState(final MockCallTargetTask task, final boolean executed,
final String target, final boolean inheritAll, final boolean inheritRefs,
final Map<String, Object> properties)
{
assertCallTargetState(task, executed, target, inheritAll, inheritRefs,
properties, Collections.<String, Object>emptyMap());
}
public static void assertCallTargetState(final MockCallTargetTask task, final boolean executed,
final String target, final boolean inheritAll, final boolean inheritRefs,
final Map<String, Object> properties, final Map<String, Object> references)
{
Assert.assertEquals(executed, task.executed);
Assert.assertEquals(target, task.target);
Assert.assertEquals(inheritAll, task.inheritAll);
Assert.assertEquals(inheritRefs, task.inheritRefs);
final Map<?, ?> actualProperties = task.ownProject.getProperties();
actualProperties.remove(MagicNames.PROJECT_BASEDIR);
Assert.assertEquals(properties, actualProperties);
assertReferences(task.ownProject, references);
}
private static void assertReferences(final Project project, final Map<String, Object> expectedReferences)
{
final Map<?, ?> actualReferences = project.getReferences();
for (final Iterator<?> i = actualReferences.keySet().iterator(); i.hasNext();) {
if (((String) i.next()).startsWith("ant.")) {
i.remove();
}
}
Assert.assertEquals(expectedReferences, actualReferences);
}
public static String getModulePath(final Project project, final String moduleProperty)
{
Assert.assertNotNull(project);
final Object module = project.getProperties().get(moduleProperty);
Assert.assertTrue(module instanceof Module);
return ((Module) module).getPath();
}
}
|
package net.gogo98901.ox;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import net.gogo98901.ox.web.GameClient;
import net.gogo98901.ox.web.GameServer;
import net.gogo98901.ox.web.packet.Packet02Move;
import net.gogo98901.ox.web.packet.Packet03Click;
public class Page extends JPanel {
private static final long serialVersionUID = 1L;
private final int WIDTH;
private final int HEIGHT;
private int boxX1 = 0;
private int boxX2 = 0;
private int boxY1 = 0;
private int boxY2 = 0;
private int boxSize = 32;
private int lines = 9;
private int blue = Color.BLUE.getRGB();
private int red = Color.RED.getRGB();
public int currentColor = blue;
private int winner = 0;
private int[] empty = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
private int[] box1 = (int[]) empty.clone();
private int[] box2 = (int[]) empty.clone();
private int[] box3 = (int[]) empty.clone();
private int[] box4 = (int[]) empty.clone();
private int[] box5 = (int[]) empty.clone();
private int[] box6 = (int[]) empty.clone();
private int[] box7 = (int[]) empty.clone();
private int[] box8 = (int[]) empty.clone();
private int[] box9 = (int[]) empty.clone();
private int[] boxFinal = (int[]) empty.clone();
private int mx;
private int my;
private boolean goodSwap = false;
private int currentSector = -1;
private JLabel title;
private int lastSector;
private int lastSquare;
private int turns = 0;
private JButton newGame;
private JButton reset;
private JButton undo;
private boolean isCurrent = true;
public GameClient socketClient;
public GameServer socketServer;
public Player player, playerMP;
public Page(int width, int height) {
setLayout(null);
WIDTH = width;
HEIGHT = height;
title = new JLabel();
title.setHorizontalAlignment(0);
title.setBounds(0, 0, width, 50);
title.setFont(getFont().deriveFont(21.0F));
add(title);
reset = new JButton("Reset");
reset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
reset();
}
});
reset.setBounds(10, 10, 75, 25);
add(reset);
newGame = new JButton("New");
newGame.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
reset();
Window.goToIntro();
}
});
newGame.setBounds(10, 40, 75, 25);
add(newGame);
undo = new JButton("Undo");
undo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
undo();
}
});
undo.setBounds(10, 70, 75, 25);
undo.setEnabled(false);
undo.setVisible(Bootstrap.showUndo);
add(undo);
addMouseMotionListener(new MouseMotionListener() {
public void mouseMoved(MouseEvent e) {
if (Window.isMultiplayer()) {
if (isCurrent) {
mouse(e.getX(), e.getY());
Packet02Move packet = new Packet02Move(player.getUsername(), e.getX(), e.getY());
packet.writeData(socketClient);
}
} else mouse(e.getX(), e.getY());
repaint();
}
public void mouseDragged(MouseEvent e) {
if (Window.isMultiplayer()) {
if (isCurrent) {
mouse(e.getX(), e.getY());
Packet02Move packet = new Packet02Move(player.getUsername(), e.getX(), e.getY());
packet.writeData(socketClient);
}
} else mouse(e.getX(), e.getY());
repaint();
}
});
addMouseListener(new MouseListener() {
public void mouseReleased(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
if (Window.isMultiplayer()) {
if (isCurrent) {
Packet03Click packet = new Packet03Click(true, getClientName());
packet.writeData(socketClient);
}
} else click();
repaint();
}
});
}
public void start() {
if (Window.isMultiplayer()) {
undo.setVisible(false);
reset.setVisible(false);
isCurrent = Lobby.hosting;
if (isCurrent) {
Intro.names[0] = player.getUsername();
Intro.names[1] = playerMP.getUsername();
} else {
Intro.names[0] = playerMP.getUsername();
Intro.names[1] = player.getUsername();
}
}
}
private void reset() {
box1 = (int[]) empty.clone();
box2 = (int[]) empty.clone();
box3 = (int[]) empty.clone();
box4 = (int[]) empty.clone();
box5 = (int[]) empty.clone();
box6 = (int[]) empty.clone();
box7 = (int[]) empty.clone();
box8 = (int[]) empty.clone();
box9 = (int[]) empty.clone();
boxFinal = ((int[]) empty.clone());
currentColor = blue;
currentSector = -1;
winner = 0;
repaint();
}
private void swapColors() {
if (currentColor == blue) {
currentColor = red;
} else {
currentColor = blue;
}
}
public void mouse(int x, int y) {
mx = x;
my = y + 25;
}
private void drawMouse(Graphics g) {
int offset = 2;
g.setColor(new Color(currentColor));
if (winner == 0) {
if ((mx >= boxX1 - offset) && (mx <= boxX2 + offset) && (my >= boxY1 + boxSize - (offset * 2 + 4)) && (my <= boxY2 + boxSize - (offset * 2 + 4))) {
g.fillOval(mx - boxSize / 3, my - boxSize, boxSize / 2, boxSize / 2);
g.setColor(new Color(0));
g.drawOval(mx - boxSize / 3, my - boxSize, boxSize / 2, boxSize / 2);
BufferedImage cursorImg = new BufferedImage(16, 16, 2);
Cursor blankCursor = Toolkit.getDefaultToolkit().createCustomCursor(cursorImg, new Point(0, 0), "blank cursor");
setCursor(blankCursor);
} else setCursor(null);
} else setCursor(null);
}
public void click() {
if ((mx >= boxX1) && (mx <= boxX2) && (my >= boxY1) && (my <= boxY2 + boxSize)) {
int currentColorINT = 0;
if (currentColor == blue) {
currentColorINT = 1;
}
if (currentColor == red) {
currentColorINT = 2;
}
int cusX = boxX1;
int cusY = boxY1;
for (int i = 1; i < 10; i++) {
if (i == 2) {
cusX = boxX1 + boxSize * 3;
cusY = boxY1;
} else if (i == 3) {
cusX = boxX1 + boxSize * 6;
cusY = boxY1;
} else if (i == 4) {
cusX = boxX1;
cusY = boxY1 + boxSize * 3;
} else if (i == 5) {
cusX = boxX1 + boxSize * 3;
cusY = boxY1 + boxSize * 3;
} else if (i == 6) {
cusX = boxX1 + boxSize * 6;
cusY = boxY1 + boxSize * 3;
} else if (i == 7) {
cusX = boxX1;
cusY = boxY1 + boxSize * 6;
} else if (i == 8) {
cusX = boxX1 + boxSize * 3;
cusY = boxY1 + boxSize * 6;
} else if (i == 9) {
cusX = boxX1 + boxSize * 6;
cusY = boxY1 + boxSize * 6;
}
if (mouseIn(cusX, cusY, boxSize * 3, boxSize * 3)) {
if (mouseIn(cusX + boxSize * 0, cusY + boxSize * 0, boxSize, boxSize)) addBox(i, 0, currentColorINT);
if (mouseIn(cusX + boxSize * 1, cusY + boxSize * 0, boxSize, boxSize)) addBox(i, 1, currentColorINT);
if (mouseIn(cusX + boxSize * 2, cusY + boxSize * 0, boxSize, boxSize)) addBox(i, 2, currentColorINT);
if (mouseIn(cusX + boxSize * 0, cusY + boxSize * 1, boxSize, boxSize)) addBox(i, 3, currentColorINT);
if (mouseIn(cusX + boxSize * 1, cusY + boxSize * 1, boxSize, boxSize)) addBox(i, 4, currentColorINT);
if (mouseIn(cusX + boxSize * 2, cusY + boxSize * 1, boxSize, boxSize)) addBox(i, 5, currentColorINT);
if (mouseIn(cusX + boxSize * 0, cusY + boxSize * 2, boxSize, boxSize)) addBox(i, 6, currentColorINT);
if (mouseIn(cusX + boxSize * 1, cusY + boxSize * 2, boxSize, boxSize)) addBox(i, 7, currentColorINT);
if (mouseIn(cusX + boxSize * 2, cusY + boxSize * 2, boxSize, boxSize)) addBox(i, 8, currentColorINT);
}
}
}
}
private boolean mouseIn(int x, int y, int xOffset, int yOffset) {
if ((mx >= x) && (mx <= x + xOffset) && (my >= y + boxSize) && (my <= y + boxSize + yOffset)) return true;
return false;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
private void draw(Graphics g) {
checkBoxes();
g.setColor(new Color(16777215));
g.fillRect(0, 0, WIDTH, HEIGHT);
drawBox(g);
setFade(g, 0.4F);
drawSector(g);
setFade(g, 1.0F);
drawGrid(g);
drawWinner();
g.setColor(new Color(currentColor));
g.drawRect(boxX1 - 1, boxY1 - 1, boxX2 - boxX1 + 2, boxY2 - boxY1 + 2);
g.drawRect(boxX1 - 2, boxY1 - 2, boxX2 - boxX1 + 4, boxY2 - boxY1 + 4);
g.drawRect(boxX1 - 3, boxY1 - 3, boxX2 - boxX1 + 6, boxY2 - boxY1 + 6);
drawMouse(g);
g.clearRect(boxX1 - boxSize - 3, boxY1 - 3, boxSize, boxY2 - boxY1 + 7);
g.clearRect(boxX1 - 3 - boxSize, boxY1 - boxSize - 3, boxX2 - boxX1 + (boxSize * 2) + 7, boxSize);
g.clearRect(boxX2 + 4, boxY1 - 3, boxSize, boxY2 - boxY1 + 7);
g.clearRect(boxX1 - 3 - boxSize, boxY2 + 4, boxX2 - boxX1 + (boxSize * 2) + 7, boxSize);
}
private void setFade(Graphics g, float value) {
AlphaComposite composite = AlphaComposite.getInstance(3, value);
Graphics2D g2d = (Graphics2D) g;
g2d.setComposite(composite);
}
private void drawSector(Graphics g) {
if (winner != 0) {
setFade(g, 0.01F);
}
g.setColor(new Color(10658466));
if (currentSector != -1) {
if (currentSector != 1) g.fillRect(boxX1 + boxSize * 0, boxY1 + boxSize * 0, boxSize * 3, boxSize * 3);
if (currentSector != 2) g.fillRect(boxX1 + boxSize * 3, boxY1 + boxSize * 0, boxSize * 3, boxSize * 3);
if (currentSector != 3) g.fillRect(boxX1 + boxSize * 6, boxY1 + boxSize * 0, boxSize * 3, boxSize * 3);
if (currentSector != 4) g.fillRect(boxX1 + boxSize * 0, boxY1 + boxSize * 3, boxSize * 3, boxSize * 3);
if (currentSector != 5) g.fillRect(boxX1 + boxSize * 3, boxY1 + boxSize * 3, boxSize * 3, boxSize * 3);
if (currentSector != 6) g.fillRect(boxX1 + boxSize * 6, boxY1 + boxSize * 3, boxSize * 3, boxSize * 3);
if (currentSector != 7) g.fillRect(boxX1 + boxSize * 0, boxY1 + boxSize * 6, boxSize * 3, boxSize * 3);
if (currentSector != 8) g.fillRect(boxX1 + boxSize * 3, boxY1 + boxSize * 6, boxSize * 3, boxSize * 3);
if (currentSector != 9) g.fillRect(boxX1 + boxSize * 6, boxY1 + boxSize * 6, boxSize * 3, boxSize * 3);
}
}
private void addBox(int sector, int square, int value) {
if ((sector == currentSector) || (currentSector == -1)) {
goodSwap = true;
if (sector == -1) goodSwap = false;
else if ((sector == 1) && (box1[square] == 0)) box1[square] = value;
else if ((sector == 2) && (box2[square] == 0)) box2[square] = value;
else if ((sector == 3) && (box3[square] == 0)) box3[square] = value;
else if ((sector == 4) && (box4[square] == 0)) box4[square] = value;
else if ((sector == 5) && (box5[square] == 0)) box5[square] = value;
else if ((sector == 6) && (box6[square] == 0)) box6[square] = value;
else if ((sector == 7) && (box7[square] == 0)) box7[square] = value;
else if ((sector == 8) && (box8[square] == 0)) box8[square] = value;
else if ((sector == 9) && (box9[square] == 0)) box9[square] = value;
else if ((sector == 0) && (boxFinal[square] == 0)) boxFinal[square] = value;
else goodSwap = false;
if (goodSwap) {
lastSector = sector;
lastSquare = square;
currentSector = square + 1;
turns += 1;
swapColors();
undo.setEnabled(true);
if (Window.isMultiplayer()) {
isCurrent = !isCurrent;
}
}
}
}
private void drawBox(Graphics g) {
int xp = WIDTH / 2 - boxSize * lines;
int yp = HEIGHT / 2 - boxSize * lines / 2;
int[] box = box1;
for (int s = 1; s < 10; s++) {
if (s == 2) {
xp = WIDTH / 2 - boxSize * lines + boxSize * 3;
yp = HEIGHT / 2 - boxSize * lines / 2;
box = box2;
} else if (s == 3) {
xp = WIDTH / 2 - boxSize * lines + boxSize * 6;
yp = HEIGHT / 2 - boxSize * lines / 2;
box = box3;
} else if (s == 4) {
xp = WIDTH / 2 - boxSize * lines;
yp = HEIGHT / 2 - boxSize * lines / 2 + boxSize * 3;
box = box4;
} else if (s == 5) {
xp = WIDTH / 2 - boxSize * lines + boxSize * 3;
yp = HEIGHT / 2 - boxSize * lines / 2 + boxSize * 3;
box = box5;
} else if (s == 6) {
xp = WIDTH / 2 - boxSize * lines + boxSize * 6;
yp = HEIGHT / 2 - boxSize * lines / 2 + boxSize * 3;
box = box6;
} else if (s == 7) {
xp = WIDTH / 2 - boxSize * lines;
yp = HEIGHT / 2 - boxSize * lines / 2 + boxSize * 6;
box = box7;
} else if (s == 8) {
xp = WIDTH / 2 - boxSize * lines + boxSize * 3;
yp = HEIGHT / 2 - boxSize * lines / 2 + boxSize * 6;
box = box8;
} else if (s == 9) {
xp = WIDTH / 2 - boxSize * lines + boxSize * 6;
yp = HEIGHT / 2 - boxSize * lines / 2 + boxSize * 6;
box = box9;
}
for (int i = 0; i < 9; i++) {
int color = 16777215;
if (box[i] == 1) color = blue;
if (box[i] == 2) color = red;
g.setColor(new Color(color));
if (i < 3) g.fillRect(xp + boxSize * i, yp, boxSize, boxSize);
else if (i < 6) g.fillRect(xp + boxSize * (i - 3), yp + boxSize, boxSize, boxSize);
else if (i < 9) g.fillRect(xp + boxSize * (i - 6), yp + boxSize + boxSize, boxSize, boxSize);
}
}
xp = WIDTH / 2 - boxSize * lines;
yp = HEIGHT / 2 - boxSize * lines / 2;
int xOffset = WIDTH / 2;
int yOffset = (int) Math.ceil(HEIGHT / 5.25D);
for (int i = 0; i < 9; i++) {
int color = Color.WHITE.getRGB();
if (boxFinal[i] == 1) color = blue;
if (boxFinal[i] == 2) color = red;
g.setColor(new Color(color));
if (i < 3) g.fillRect(xOffset + xp + boxSize * i, yOffset + yp, boxSize, boxSize);
else if (i < 6) g.fillRect(xOffset + xp + boxSize * (i - 3), yOffset + yp + boxSize, boxSize, boxSize);
else if (i < 9) g.fillRect(xOffset + xp + boxSize * (i - 6), yOffset + yp + boxSize + boxSize, boxSize, boxSize);
}
}
private void checkBoxes() {
int[][] boxes = { box1, box2, box3, box4, box5, box6, box7, box8, box9 };
for (int i = 0; i < 9; i++) {
if (boxFinal[i] == 0) {
if ((boxes[i][0] != 0) && (boxes[i][0] == boxes[i][1]) && (boxes[i][1] == boxes[i][2])) boxFinal[i] = boxes[i][2];
if ((boxes[i][3] != 0) && (boxes[i][3] == boxes[i][4]) && (boxes[i][4] == boxes[i][5])) boxFinal[i] = boxes[i][5];
if ((boxes[i][6] != 0) && (boxes[i][6] == boxes[i][7]) && (boxes[i][7] == boxes[i][8])) boxFinal[i] = boxes[i][8];
if ((boxes[i][0] != 0) && (boxes[i][0] == boxes[i][3]) && (boxes[i][3] == boxes[i][6])) boxFinal[i] = boxes[i][6];
if ((boxes[i][1] != 0) && (boxes[i][1] == boxes[i][4]) && (boxes[i][4] == boxes[i][7])) boxFinal[i] = boxes[i][7];
if ((boxes[i][2] != 0) && (boxes[i][2] == boxes[i][5]) && (boxes[i][5] == boxes[i][8])) boxFinal[i] = boxes[i][8];
if ((boxes[i][2] != 0) && (boxes[i][2] == boxes[i][4]) && (boxes[i][4] == boxes[i][6])) boxFinal[i] = boxes[i][6];
if ((boxes[i][0] != 0) && (boxes[i][0] == boxes[i][4]) && (boxes[i][4] == boxes[i][8])) boxFinal[i] = boxes[i][8];
}
}
if ((boxFinal[0] != 0) && (boxFinal[0] == boxFinal[1]) && (boxFinal[1] == boxFinal[2])) winner = boxFinal[2];
if ((boxFinal[3] != 0) && (boxFinal[3] == boxFinal[4]) && (boxFinal[4] == boxFinal[5])) winner = boxFinal[5];
if ((boxFinal[6] != 0) && (boxFinal[6] == boxFinal[7]) && (boxFinal[7] == boxFinal[8])) winner = boxFinal[8];
if ((boxFinal[0] != 0) && (boxFinal[0] == boxFinal[3]) && (boxFinal[3] == boxFinal[6])) winner = boxFinal[6];
if ((boxFinal[1] != 0) && (boxFinal[1] == boxFinal[4]) && (boxFinal[4] == boxFinal[7])) winner = boxFinal[7];
if ((boxFinal[2] != 0) && (boxFinal[2] == boxFinal[5]) && (boxFinal[5] == boxFinal[8])) winner = boxFinal[8];
if ((boxFinal[2] != 0) && (boxFinal[2] == boxFinal[4]) && (boxFinal[4] == boxFinal[6])) winner = boxFinal[6];
if ((boxFinal[0] != 0) && (boxFinal[0] == boxFinal[4]) && (boxFinal[4] == boxFinal[8])) winner = boxFinal[8];
if (winner != 0) currentSector = 10;
boolean full = true;
for (int i = 0; i < 9; i++) {
for (int s = 0; s < 9; s++) {
if (boxes[i][s] == 0) full = false;
}
}
if (full && winner == 0) winner = 3;
}
private void drawGrid(Graphics g) {
int xp = WIDTH / 2 - boxSize * lines;
int yp = HEIGHT / 2 - boxSize * lines / 2;
boxX1 = xp;
boxX2 = (boxX1 + boxSize * lines);
boxY1 = yp;
boxY2 = (boxY1 + boxSize * lines);
g.setColor(new Color(0));
for (int y = 0; y < lines + 1; y++) {
int ya = yp + boxSize * y;
g.drawLine(xp, ya, xp + boxSize * lines, ya);
}
for (int x = 0; x < lines + 1; x++) {
int xa = xp + boxSize * x;
g.drawLine(xa, yp, xa, yp + boxSize * lines);
}
int xOffset = WIDTH / 2;
int yOffset = (int) Math.ceil(HEIGHT / 5.25D);
for (int y = 0; y < 4; y++) {
int ya = yp + boxSize * y;
g.drawLine(xOffset + xp, yOffset + ya, xOffset + xp + boxSize * 3, yOffset + ya);
}
for (int x = 0; x < 4; x++) {
int xa = xp + boxSize * x;
g.drawLine(xOffset + xa, yOffset + yp, xOffset + xa, yOffset + yp + boxSize * 3);
}
g.drawRect(xp + xOffset - 1, yp + yOffset - 1, boxSize * 3 + 2, boxSize * 3 + 2);
g.drawRect(xp + xOffset - 2, yp + yOffset - 2, boxSize * 3 + 4, boxSize * 3 + 4);
g.drawRect(boxX1 + boxSize * 0 + 1, boxY1 + boxSize * 0 + 1, boxSize * 3 - 2, boxSize * 3 - 2);
g.drawRect(boxX1 + boxSize * 3 + 1, boxY1 + boxSize * 0 + 1, boxSize * 3 - 2, boxSize * 3 - 2);
g.drawRect(boxX1 + boxSize * 6 + 1, boxY1 + boxSize * 0 + 1, boxSize * 3 - 2, boxSize * 3 - 2);
g.drawRect(boxX1 + boxSize * 0 + 1, boxY1 + boxSize * 3 + 1, boxSize * 3 - 2, boxSize * 3 - 2);
g.drawRect(boxX1 + boxSize * 3 + 1, boxY1 + boxSize * 3 + 1, boxSize * 3 - 2, boxSize * 3 - 2);
g.drawRect(boxX1 + boxSize * 6 + 1, boxY1 + boxSize * 3 + 1, boxSize * 3 - 2, boxSize * 3 - 2);
g.drawRect(boxX1 + boxSize * 0 + 1, boxY1 + boxSize * 6 + 1, boxSize * 3 - 2, boxSize * 3 - 2);
g.drawRect(boxX1 + boxSize * 3 + 1, boxY1 + boxSize * 6 + 1, boxSize * 3 - 2, boxSize * 3 - 2);
g.drawRect(boxX1 + boxSize * 6 + 1, boxY1 + boxSize * 6 + 1, boxSize * 3 - 2, boxSize * 3 - 2);
}
private void drawWinner() {
String currentPlayer = "";
int player = 0;
if (currentColor == blue) player = 1;
if (currentColor == red) player = 2;
if (Intro.names[(player - 1)].length() != 0) currentPlayer = Intro.names[(player - 1)];
else currentPlayer = "Player " + player;
if (winner != 0) {
if (currentColor == red) player = 1;
if (currentColor == blue) player = 2;
if (Intro.names[(player - 1)].length() != 0) currentPlayer = Intro.names[(player - 1)];
else currentPlayer = "Player " + player;
if (winner == 3) title.setText("Its a draw");
else title.setText(currentPlayer + " is the winner");
undo.setEnabled(false);
} else title.setText(currentPlayer + "'s turn");
}
public void undo() {
undo.setEnabled(false);
if (lastSector - 1 == 0) box1[lastSquare] = 0;
if (lastSector - 1 == 1) box2[lastSquare] = 0;
if (lastSector - 1 == 2) box3[lastSquare] = 0;
if (lastSector - 1 == 3) box4[lastSquare] = 0;
if (lastSector - 1 == 4) box5[lastSquare] = 0;
if (lastSector - 1 == 5) box6[lastSquare] = 0;
if (lastSector - 1 == 6) box7[lastSquare] = 0;
if (lastSector - 1 == 7) box8[lastSquare] = 0;
if (lastSector - 1 == 8) box9[lastSquare] = 0;
currentSector = lastSector;
turns -= 1;
if (turns <= 0) currentSector = -1;
swapColors();
repaint();
}
public static String getClientName() {
if (Window.isMultiplayer()) return Intro.names[0];
else {
if (Intro.names[0].length() > 0) return Intro.names[0];
else return "Player 1";
}
}
}
|
package com.ecyrd.jspwiki;
import java.util.Properties;
import javax.servlet.*;
import java.io.*;
/**
* Simple test engine that always assumes pages are found.
*/
public class TestEngine extends WikiEngine
{
public TestEngine( Properties props )
throws NoRequiredPropertyException,
ServletException
{
super( props );
}
public boolean pageExists( String page )
{
return true;
}
/**
* Deletes all files under this directory, and does them recursively.
*/
public static void deleteAll( File file )
{
if( file.isDirectory() )
{
File[] files = file.listFiles();
for( int i = 0; i < files.length; i++ )
{
if( files[i].isDirectory() )
{
deleteAll(files[i]);
}
files[i].delete();
}
}
file.delete();
}
}
|
package org.basex.query.fs;
import java.io.IOException;
import org.basex.core.Context;
import org.basex.data.Data;
import org.basex.io.PrintOutput;
import org.basex.util.GetOpts;
public final class RM {
/** Data reference. */
private final Context context;
/** current dir. */
private int curDirPre;
/** PrintOutPutStream. */
private PrintOutput out;
/** Shows if an error occurs. */
private boolean fError;
/** Shows if job is done. */
private boolean fAccomplished;
/** Remove the all. */
private boolean fRecursive;
/**
* Simplified Constructor.
* @param ctx data context
* @param output output stream
*/
public RM(final Context ctx, final PrintOutput output) {
this.context = ctx;
curDirPre = ctx.current().pre[0];
this.out = output;
}
/**
* Performs a rm command.
*
* @param cmd - command line
* @throws IOException - in case of problems with the PrintOutput
*/
public void rmMain(final String cmd)
throws IOException {
GetOpts g = new GetOpts(cmd, "Rh");
// get all Options
int ch = g.getopt();
while (ch != -1) {
switch (ch) {
case 'h':
printHelp();
fAccomplished = true;
break;
case 'R':
fRecursive = true;
break;
case ':':
fError = true;
out.print("rm: missing argument");
break;
case '?':
fError = true;
out.print("rm: illegal option");
break;
}
if(fError || fAccomplished) {
return;
}
ch = g.getopt();
}
// if there is path expression remove it
if(g.getPath() != null) {
remove(g.getPath());
}
}
/**
* Performs a rm command.
*
* @param path The name of the file
* @throws IOException in case of problems with the PrintOutput
*/
private void remove(final String path) throws IOException {
Data data = context.data();
String file = "";
int beginIndex = path.lastIndexOf('/');
if(beginIndex == -1) {
file = path;
} else {
// go to Path
curDirPre = FSUtils.goToDir(data, curDirPre,
path.substring(0, beginIndex));
if(curDirPre == -1) {
out.print("rm: '" + path + "' No such file or directory");
} else {
// file to delete
file = path.substring(beginIndex + 1);
}
}
int[] del = FSUtils.getSpecificFilesOrDirs(data, curDirPre,
file.getBytes());
long sizeOfNode = 0;
for(int toDel : del) {
if(toDel == -1) {
out.print("rm: '" + file + "' No such file or directory");
return;
} else {
/*
* Pre Value of all nodes changes if one node is deleted.
* This is the adjustment of the former
*/
toDel -= sizeOfNode;
if((FSUtils.isDir(data, toDel) && fRecursive) ||
(FSUtils.isFile(data, toDel))) {
try {
sizeOfNode += data.size(toDel, Data.ELEM);
data.delete(toDel);
data.flush();
} catch(Exception e) {
e.printStackTrace();
}
} else {
out.print("rm: cannot remove '" +
FSUtils.getFileName(data, toDel) + "': Is a directory");
}
}
}
}
/**
* Print the help.
*
* @throws IOException in case of problems with the PrintOutput
*/
private void printHelp() throws IOException {
out.print("rm [-Rh] file ...");
}
}
|
package org.clapper.curn;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Iterator;
import java.util.Properties;
import java.util.TreeSet;
import org.clapper.curn.parser.RSSParserFactory;
import org.clapper.curn.parser.RSSParser;
import org.clapper.curn.parser.RSSParserException;
import org.clapper.curn.parser.RSSChannel;
import org.clapper.util.config.ConfigurationException;
import org.clapper.util.logging.Logger;
public class Curn
{
private CurnConfig config = null;
private FeedCache cache = null;
private Date currentTime = new Date();
private MetaPlugIn metaPlugIn = null;
private Collection<ConfiguredOutputHandler> configuredOutputHandlers =
new ArrayList<ConfiguredOutputHandler>();
/**
* For log messages
*/
private static Logger log = new Logger (Curn.class);
/**
* Instantiate a new <tt>Curn</tt> object and loads its plugins.
*
* @throws CurnException on error
*/
public Curn()
throws CurnException
{
metaPlugIn = MetaPlugIn.getMetaPlugIn();
logEnvironmentInfo();
}
/**
* Run <i>curn</i> against a configuration file.
*
* @param configPath path to the configuration data
* @param useCache whether or not to use the cache
*
* @throws CurnException on error
*/
public void run (String configPath, boolean useCache)
throws CurnException
{
metaPlugIn.runStartupPlugIn();
try
{
this.config = loadConfig (configPath);
processRSSFeeds (useCache);
}
catch (ConfigurationException ex)
{
throw new CurnException (ex);
}
catch (RSSParserException ex)
{
throw new CurnException (ex);
}
finally
{
metaPlugIn.runShutdownPlugIn();
}
}
/**
* Set the cache's notion of the current time. This method will change
* the time used when reading and pruning the cache from the current time
* to the specified time. This method must be called before
* <tt>processRSSFeeds()</tt>.
*
* @param newTime the time to pretend is the current time
*/
public void setCurrentTime (Date newTime)
{
this.currentTime = newTime;
}
/**
* Read the RSS feeds specified in a parsed configuration, writing them
* to the output handler(s) specified in the configuration.
*
* @param useCache whether or not to use the cache
*
* @throws IOException unable to open or read a required file
* @throws ConfigurationException error in configuration file
* @throws RSSParserException error parsing XML feed(s)
* @throws CurnException any other error
*/
private void processRSSFeeds (boolean useCache)
throws ConfigurationException,
RSSParserException,
CurnException
{
Map<FeedInfo,RSSChannel> channels;
boolean parsingEnabled = true;
File cacheFile = config.getCacheFile();
loadOutputHandlers (config);
if (useCache && (cacheFile != null))
{
cache = new FeedCache (config);
cache.setCurrentTime (currentTime);
cache.loadCache();
metaPlugIn.runCacheLoadedPlugIn (cache);
}
if (config.isDownloadOnly())
{
// No output handlers. No need to instantiate a parser.
log.debug ("Config is download-only. Skipping XML parse phase.");
parsingEnabled = false;
}
Collection<FeedInfo> feeds = config.getFeeds();
if (feeds.size() == 0)
{
throw new ConfigurationException (Constants.BUNDLE_NAME,
"Curn.noConfiguredFeeds",
"No configured RSS feed URLs.");
}
if ((config.getMaxThreads() == 1) || (feeds.size() == 1))
channels = doSingleThreadedFeedDownload (parsingEnabled,
cache,
config);
else
channels = doMultithreadedFeedDownload (parsingEnabled,
cache,
config);
log.debug ("After downloading, total (parsed) channels = " +
channels.size());
if (channels.size() > 0)
outputChannels (channels);
log.debug ("cacheFile=" +
((cacheFile == null) ? "null" : cacheFile.getPath()) +
", mustUpdateCache=" + config.mustUpdateCache());
if ((cache != null) && config.mustUpdateCache())
{
int totalCacheBackups = config.totalCacheBackups();
metaPlugIn.runPreCacheSavePlugIn (cache);
cache.saveCache (totalCacheBackups);
}
}
private CurnConfig loadConfig (String configPath)
throws CurnException
{
try
{
config = new CurnConfig (configPath);
MetaPlugIn.getMetaPlugIn().runPostConfigPlugIn (config);
return config;
}
catch (FileNotFoundException ex)
{
throw new CurnException (Constants.BUNDLE_NAME,
"Curn.cantFindConfig",
"Cannot find configuration file \"{0}\"",
new Object[] {configPath},
ex);
}
catch (IOException ex)
{
throw new CurnException (Constants.BUNDLE_NAME,
"Curn.cantReadConfig",
"I/O error reading configuration file " +
"\"{0}\"",
new Object[] {configPath},
ex);
}
catch (ConfigurationException ex)
{
throw new CurnException (ex);
}
}
private void loadOutputHandlers (CurnConfig configuration)
throws ConfigurationException,
CurnException
{
if (configuration.totalOutputHandlers() > 0)
{
for (ConfiguredOutputHandler cfgHandler : configuration.getOutputHandlers())
{
// Ensure that the output handler can be instantiated.
String className = cfgHandler.getClassName();
log.debug ("Instantiating output handler \"" +
cfgHandler.getName() +
"\", of type " +
className);
OutputHandler handler = cfgHandler.getOutputHandler();
log.debug ("Initializing output handler \"" +
cfgHandler.getName() +
"\", of type " +
className);
handler.init (config, cfgHandler);
// Save it.
configuredOutputHandlers.add (cfgHandler);
}
}
}
/**
* Download the configured feeds sequentially. This method is called
* when the configured number of concurrent download threads is 1.
*
* @param parsingEnabled <tt>true</tt> if parsing is to be done,
* <tt>false</tt> otherwise
* @param feedCache the loaded cache of feed data; may be modified
* @param configuration the parsed configuration
*
* @return a <tt>Map</tt> of <tt>RSSChannel</tt> objects, indexed
* by <tt>FeedInfo</tt>
*
* @throws RSSParserException error parsing feeds
* @throws CurnException some other error
*/
private Map<FeedInfo,RSSChannel>
doSingleThreadedFeedDownload (boolean parsingEnabled,
FeedCache feedCache,
CurnConfig configuration)
throws RSSParserException,
CurnException
{
// Instantiate a single FeedDownloadThread object, but call it
// within this thread, instead of spawning another thread.
final Map<FeedInfo,RSSChannel> channels =
new LinkedHashMap<FeedInfo,RSSChannel>();
FeedDownloadThread downloadThread;
log.info ("Doing single-threaded download of feeds.");
RSSParser parser = null;
if (parsingEnabled)
parser = getRSSParser(configuration);
downloadThread =
new FeedDownloadThread
("main",
parser,
feedCache,
configuration,
null,
new FeedDownloadDoneHandler()
{
public void feedFinished (FeedInfo feedInfo,
RSSChannel channel)
{
channels.put (feedInfo, channel);
}
});
for (FeedInfo feedInfo : configuration.getFeeds())
{
downloadThread.processFeed (feedInfo);
// Don't abort if an exception occurred. It might just be a
// parse error for this feed. Don't want to abort the whole
// run if one feed has problems.
/*
if (downloadThread.errorOccurred())
throw downloadThread.getException();
*/
RSSChannel channel = downloadThread.getParsedChannelData();
if (channel != null)
channels.put (feedInfo, channel);
}
return channels;
}
/**
* Download the configured feeds using multiple simultaneous threads.
* This method is called when the configured number of concurrent
* download threads is greater than 1.
*
* @param parsingEnabled <tt>true</tt> if parsing is to be done,
* <tt>false</tt> otherwise
* @param feedCache the loaded cache of feed data; may be modified
* @param configuration the parsed configuration
*
* @return a <tt>Map</tt> of <tt>RSSChannel</tt> objects, indexed
* by <tt>FeedInfo</tt>
*
* @throws RSSParserException error parsing feeds
* @throws CurnException some other error
*/
private Map<FeedInfo,RSSChannel>
doMultithreadedFeedDownload (boolean parsingEnabled,
FeedCache feedCache,
CurnConfig configuration)
throws RSSParserException,
CurnException
{
int maxThreads = configuration.getMaxThreads();
Collection<FeedInfo> feeds = configuration.getFeeds();
int totalFeeds = feeds.size();
final Map<FeedInfo,RSSChannel> channels =
new LinkedHashMap<FeedInfo,RSSChannel>();
List<FeedDownloadThread> threads = new ArrayList<FeedDownloadThread>();
List<FeedInfo> feedQueue = new LinkedList<FeedInfo>();
if (maxThreads > totalFeeds)
maxThreads = totalFeeds;
log.info ("Doing multithreaded download of feeds, using " +
maxThreads + " threads.");
// Fill the feed queue and make it a synchronized list. Also, prime
// the "channels" LinkedHashMap with the feeds. This ensures that
// the channels are traversed in the original order they were
// specified in the configuration file. If we don't do this, then
// the channels will be put in the LinkedHashMap in the order the
// feed threads finish with them, which might not match the
// original order.
for (FeedInfo feedInfo : feeds)
{
feedQueue.add (feedInfo);
channels.put (feedInfo, null);
}
if (feedQueue.size() == 0)
{
throw new CurnException (Constants.BUNDLE_NAME,
"Curn.allFeedsDisabled",
"All configured RSS feeds are disabled.");
}
// Create a synchronized view of the feed queue.
feedQueue = Collections.synchronizedList (feedQueue);
// Create the thread objects. They'll pull feeds off the queue
// themselves.
for (int i = 0; i < maxThreads; i++)
{
RSSParser parser = null;
if (parsingEnabled)
parser = getRSSParser (configuration);
FeedDownloadThread thread =
new FeedDownloadThread
(String.valueOf (i),
parser,
feedCache,
configuration,
feedQueue,
new FeedDownloadDoneHandler()
{
public void feedFinished (FeedInfo feedInfo,
RSSChannel channel)
{
channels.put (feedInfo, channel);
}
});
thread.start();
threads.add (thread);
}
log.debug ("Main thread priority is " +
Thread.currentThread().getPriority());
log.debug ("All feeds have been parceled out to threads. Waiting " +
"for threads to complete.");
for (FeedDownloadThread thread : threads)
{
String threadName = thread.getName();
log.info ("Waiting for thread " + threadName);
try
{
thread.join();
}
catch (InterruptedException ex)
{
log.debug ("Interrupted during thread join: " + ex.toString());
}
log.info ("Joined thread " + threadName);
}
// Finally, remove any entries that still have null channels. (This
// can happen if there's no new data in a feed.)
for (Iterator<Map.Entry<FeedInfo,RSSChannel>> it =
channels.entrySet().iterator();
it.hasNext(); )
{
Map.Entry<FeedInfo,RSSChannel> mapEntry = it.next();
if (mapEntry.getValue() == null)
it.remove();
}
return channels;
}
/**
* Get a new instance of an RSS parser.
*
* @param configuration the parsed configuration
*
* @return the RSSParser
*
* @throws RSSParserException error instantiating parser
*/
private RSSParser getRSSParser (CurnConfig configuration)
throws RSSParserException
{
String parserClassName = configuration.getRSSParserClassName();
log.info ("Getting parser \"" + parserClassName + "\"");
return RSSParserFactory.getRSSParser (parserClassName);
}
private void outputChannels (Map<FeedInfo,RSSChannel> channels)
throws CurnException,
ConfigurationException
{
OutputHandler handler;
Collection<OutputHandler> outputHandlers =
new ArrayList<OutputHandler>();
// Dump the output to each output handler
for (ConfiguredOutputHandler cfgHandler : configuredOutputHandlers)
{
log.info ("Preparing to call output handler \"" +
cfgHandler.getName() +
"\", of type " +
cfgHandler.getClassName());
handler = cfgHandler.getOutputHandler();
outputHandlers.add (handler);
for (FeedInfo fi : channels.keySet())
{
// Use a copy of the channel. That way, the plug-ins and
// the output handler can modify its content freely, without
// affecting anyone else.
RSSChannel channel = channels.get (fi).makeCopy();
metaPlugIn.runPreFeedOutputPlugIn (fi, channel, handler);
handler.displayChannel (channel, fi);
metaPlugIn.runPostFeedOutputPlugIn (fi, handler);
}
handler.flush();
ReadOnlyOutputHandler ro = new ReadOnlyOutputHandler (handler);
if (! metaPlugIn.runPostOutputHandlerFlushPlugIn (ro))
cfgHandler.disable();
}
metaPlugIn.runPostOutputPlugIn (outputHandlers);
outputHandlers.clear();
outputHandlers = null;
}
/**
* Log all system properties and other information about the Java VM.
*/
private void logEnvironmentInfo()
{
log.info (Version.getFullVersion());
Properties properties = System.getProperties();
TreeSet<String> sortedNames = new TreeSet<String>();
for (Enumeration<?> e = properties.propertyNames();
e.hasMoreElements(); )
{
sortedNames.add ((String) e.nextElement());
}
log.info ("--- Start of Java properties");
for (String name : sortedNames)
log.info (name + "=" + properties.getProperty (name));
log.info ("--- End of Java properties");
}
}
|
package org.exist.xquery;
import org.apache.log4j.Logger;
import org.exist.xquery.util.ExpressionDumper;
import org.exist.xquery.value.Item;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.Type;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public abstract class Step extends AbstractExpression {
protected final static Logger LOG = Logger.getLogger(Step.class);
protected int axis = Constants.UNKNOWN_AXIS;
protected boolean abbreviatedStep = false;
protected List<Predicate> predicates = new CopyOnWriteArrayList<Predicate>();
protected NodeTest test;
protected boolean inPredicate = false;
protected int staticReturnType = Type.ITEM;
protected boolean hasPositionalPredicate = false;
public Step( XQueryContext context, int axis ) {
super(context);
this.axis = axis;
}
public Step( XQueryContext context, int axis, NodeTest test ) {
this( context, axis );
this.test = test;
}
public void addPredicate( Expression expr ) {
predicates.add( (Predicate) expr );
}
public void insertPredicate(Expression previous, Expression predicate) {
int idx = predicates.indexOf(previous);
if (idx < 0) {
LOG.warn("Old predicate not found: " + ExpressionDumper.dump(previous) + "; in: " + ExpressionDumper.dump(this));
return;
}
predicates.add(idx + 1, (Predicate) predicate);
}
public boolean hasPredicates() {
return predicates.size() > 0;
}
public List<Predicate> getPredicates() {
return predicates;
}
/* (non-Javadoc)
* @see org.exist.xquery.Expression#analyze(org.exist.xquery.AnalyzeContextInfo)
*/
public void analyze(AnalyzeContextInfo contextInfo) throws XPathException {
//context.("t")
if (test != null && test.getName() != null && test.getName().getPrefix() != null &&
!test.getName().getPrefix().equals("") && context.inScopePrefixes != null &&
context.getURIForPrefix(test.getName().getPrefix()) == null)
throw new XPathException(this, "XPST0081 : undeclared prefix '" +
test.getName().getPrefix() + "'");
inPredicate = (contextInfo.getFlags() & IN_PREDICATE) > 0;
this.contextId = contextInfo.getContextId();
if (predicates.size() > 0) {
AnalyzeContextInfo newContext = new AnalyzeContextInfo(contextInfo);
newContext.setStaticType(this.axis == Constants.SELF_AXIS ? contextInfo.getStaticType() : Type.NODE);
newContext.setParent(this);
newContext.setContextStep(this);
for (Predicate pred : predicates) {
pred.analyze(newContext);
}
if (predicates.size() == 1 && (newContext.getFlags() & POSITIONAL_PREDICATE) != 0)
hasPositionalPredicate = true;
}
// if we are on the self axis, remember the static return type given in the context
if (this.axis == Constants.SELF_AXIS)
staticReturnType = contextInfo.getStaticType();
}
public abstract Sequence eval( Sequence contextSequence, Item contextItem ) throws XPathException;
public int getAxis() {
return axis;
}
/* (non-Javadoc)
* @see org.exist.xquery.AbstractExpression#setPrimaryAxis(int)
*/
public void setPrimaryAxis(int axis) {
this.axis = axis;
}
public int getPrimaryAxis() {
return this.axis;
}
public boolean isAbbreviated() {
return abbreviatedStep;
}
public void setAbbreviated(boolean abbrev) {
abbreviatedStep = abbrev;
}
/* (non-Javadoc)
* @see org.exist.xquery.Expression#dump(org.exist.xquery.util.ExpressionDumper)
*/
public void dump(ExpressionDumper dumper) {
if (axis != Constants.UNKNOWN_AXIS)
dumper.display( Constants.AXISSPECIFIERS[axis] );
dumper.display( "::" );
if ( test != null )
//TODO : toString() or... dump ?
dumper.display( test.toString() );
else
dumper.display( "node()" );
if ( predicates.size() > 0 )
for (Predicate pred : predicates) {
pred.dump(dumper);
}
}
public String toString() {
StringBuilder result = new StringBuilder();
if ( axis != Constants.UNKNOWN_AXIS)
result.append( Constants.AXISSPECIFIERS[axis] );
result.append( "::" );
if ( test != null )
result.append( test.toString() );
else
result.append( "node()" );
if ( predicates.size() > 0 )
for (Predicate pred : predicates) {
result.append(pred.toString());
}
return result.toString();
}
//TODO : not sure about this one...
/*
public int getDependencies() {
if (test == null)
return Dependency.CONTEXT_SET;
else
return Dependency.CONTEXT_SET + Dependency.CONTEXT_ITEM;
}
*/
public int returnsType() {
//Polysemy of "." which might be atomic if the context sequence is atomic itself
if (axis == Constants.SELF_AXIS) {
//Type.ITEM by default : this may change *after* evaluation
// LOG.debug("My static type: " + Type.getTypeName(staticReturnType));
return staticReturnType;
} else
return Type.NODE;
}
public int getCardinality() {
return Cardinality.ZERO_OR_MORE;
}
public void setAxis( int axis ) {
this.axis = axis;
}
public void setTest( NodeTest test ) {
this.test = test;
}
public NodeTest getTest() {
return test;
}
/* (non-Javadoc)
* @see org.exist.xquery.AbstractExpression#resetState()
*/
public void resetState(boolean postOptimization) {
super.resetState(postOptimization);
for (Predicate pred : predicates) {
pred.resetState(postOptimization);
}
}
}
|
/*
* $Id: Tdb.java,v 1.11 2010-08-15 13:23:40 pgust Exp $
*/
package org.lockss.config;
import java.io.*;
import java.util.*;
import org.lockss.util.*;
/**
* This class represents a title database (TDB). The TDB consists of
* hierarchy of <code>TdbPublisher</code>s, and <code>TdbAu</code>s.
* Special indexing provides fast access to all <code>TdbAu</code>s for
* a specified plugin ID.
*
* @author Philip Gust
* @version $Id: Tdb.java,v 1.11 2010-08-15 13:23:40 pgust Exp $
*/
public class Tdb {
@SuppressWarnings("serial")
static public class TdbException extends Exception {
/**
* Constructs a new exception with the specified detail message. The
* cause is not initialized, and may subsequently be initialized by
* a call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public TdbException(String message) {
super(message);
}
/**
* Constructs a new exception with the specified detail message and
* cause. <p>Note that the detail message associated with
* <code>cause</code> is <i>not</i> automatically incorporated in
* this exception's detail message.
*
* @param message the detail message (which is saved for later retrieval
* by the {@link #getMessage()} method).
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
* @since 1.4
*/
public TdbException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs a new exception with the specified cause and a detail
* message of <tt>(cause==null ? null : cause.toString())</tt> (which
* typically contains the class and detail message of <tt>cause</tt>).
* This constructor is useful for exceptions that are little more than
* wrappers for other throwables (for example, {@link
* java.security.PrivilegedActionException}).
*
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
* @since 1.4
*/
public TdbException(Throwable cause) {
super(cause);
}
}
/**
* Register the au with this Tdb for its plugin.
*
* @param au the TdbAu
* @return <code>false</code> if already registered, otherwise <code>true</code>
*/
private boolean addTdbAuForPlugin(TdbAu au) {
// add AU to list for plugins
String pluginId = au.getPluginId();
Collection<TdbAu> aus = pluginIdTdbAusMap.get(pluginId);
if (aus == null) {
aus = new HashSet<TdbAu>();
pluginIdTdbAusMap.put(pluginId, aus);
}
if (!aus.add(au)) {
return false;
}
// increment the total AU count;
tdbAuCount++;
return true;
}
/**
* Unregister the au with this Tdb for its plugin.
*
* @param au the TdbAu
* @return <code>false</code> if au was not registered, otherwise <code>true</code>
*/
private boolean removeTdbAuForPlugin(TdbAu au) {
// if can't add au to title, we need to undo the au
// registration and re-throw the exception we just caught
String pluginId = au.getPluginId();
Collection<TdbAu> c = pluginIdTdbAusMap.get(pluginId);
if (c.remove(au)) {
if (c.isEmpty()) {
pluginIdTdbAusMap.remove(c);
}
tdbAuCount
return true;
}
return false;
}
/**
* Add a new TdbAu to this title database. The TdbAu must have
* its pluginID, and title set. The TdbAu''s title must also have
* its titleId and publisher set. The publisher name must be unique
* to all publishers in this Tdb.
*
* @param au the TdbAu to add.
* @throws TdbException if Tdb is sealed, this is a duplicate au, or
* the au's publisher is a duplicate
*/
public void addTdbAu(TdbAu au) throws TdbException {
if (au == null) {
throw new IllegalArgumentException("TdbAu cannot be null");
}
// verify not sealed
if (isSealed()) {
throw new TdbException("Cannot add TdbAu to sealed Tdb");
}
// validate title
TdbTitle title = au.getTdbTitle();
if (title == null) {
throw new IllegalArgumentException("TdbAu's title not set");
}
// validate publisher
TdbPublisher publisher = title.getTdbPublisher();
if (publisher == null) {
throw new IllegalArgumentException("TdbAu's publisher not set");
}
// make sure publisher is not a duplicate
String pubName = publisher.getName();
TdbPublisher oldPublisher = tdbPublisherMap.put(pubName, publisher);
if ((oldPublisher != null) && (oldPublisher != publisher)) {
// restore old publisher and report error
tdbPublisherMap.put(pubName, oldPublisher);
throw new TdbException("New au publisher with duplicate name: " + pubName);
}
// register the au with this instance
if (!addTdbAuForPlugin(au)) {
// remove new publisher and report error
if (oldPublisher == null) {
tdbPublisherMap.remove(pubName);
}
throw new TdbException("Cannot register au " + au.getName());
}
}
/**
* Set up logger
*/
protected final static Logger logger = Logger.getLogger("Tdb");
/**
* A map of AUs per plugin, for this configuration
* (provides faster access for Plugins)
*/
private final Map<String, Collection<TdbAu>> pluginIdTdbAusMap = new HashMap<String,Collection<TdbAu>>();
/**
* Map of publisher names to TdBPublishers for this configuration
*/
private final Map<String, TdbPublisher> tdbPublisherMap = new HashMap<String,TdbPublisher>();
/**
* Determines whether more AUs can be added.
*/
private boolean isSealed = false;
/**
* The total number of TdbAus in this TDB (sum of collections in pluginIdTdbAus map
*/
private int tdbAuCount = 0;
/**
* Prefix appended to generated unknown title
*/
private static final String UNKNOWN_TITLE_PREFIX = "Title of ";
/**
* Prefix appended to generated unknown publisher
*/
private static final String UNKNOWN_PUBLISHER_PREFIX = "Publisher of ";
/**
* Seals a Tdb against further additions.
*/
public void seal() {
if (!isSealed) {
isSealed = true;
// convert map values to array lists to save space because
// they will not be modified now that the Tdb is sealed.
synchronized(pluginIdTdbAusMap) {
for (Map.Entry<String, Collection<TdbAu>> entry : pluginIdTdbAusMap.entrySet()) {
ArrayList<TdbAu> list = new ArrayList<TdbAu>(entry.getValue());
list.trimToSize();
entry.setValue(list);
}
}
}
}
/**
* Determines whether this Tdb is sealed.
*
* @return <code>true</code> if sealed
*/
public boolean isSealed() {
return isSealed;
}
/**
* Determines whether the title database is empty.
*
* @return <code> true</code> if the title database has no entries
*/
public boolean isEmpty() {
return pluginIdTdbAusMap.isEmpty();
}
/**
* Returns a collection of pluginIds for TdbAus that are
* different from those in this Tdb.
*
* @param otherTdb a Tdb
* @return a collection of pluginIds that are different,
* , or all plugin Ids in this Tdb if otherTdb is <code>null</code>
*/
public Set<String> getPluginIdsForDifferences(Tdb otherTdb) {
if (otherTdb == null) {
return pluginIdTdbAusMap.keySet();
}
if (otherTdb == this) {
return Collections.emptySet();
}
Set<String> pluginIds = new HashSet<String>();
addPluginIdsForDifferences (pluginIds, otherTdb);
return pluginIds;
}
/**
* Adds a collection of pluginIds for TdbAus that are
* different from those in this Tdb.
*
* @param pluginIds the set of pluginIds
* @param otherTdb a Tdb
*/
private void addPluginIdsForDifferences(Set<String> pluginIds, Tdb otherTdb) {
Map<String, TdbPublisher> tdbPublishers = otherTdb.getAllTdbPublishers();
for (TdbPublisher tdbPublisher : tdbPublishers.values()) {
if (!this.tdbPublisherMap.containsKey(tdbPublisher.getName())) {
// add pluginIds for publishers in tdb that are not in this Tdb
tdbPublisher.addAllPluginIds(pluginIds);
}
}
for (TdbPublisher thisPublisher : tdbPublisherMap.values()) {
TdbPublisher tdbPublisher = tdbPublishers.get(thisPublisher.getName());
if (tdbPublisher == null) {
// add pluginIds for publisher in this Tdb that is not in tdb
thisPublisher.addAllPluginIds(pluginIds);
} else {
// add pluginIds for publishers in both Tdbs that are different
thisPublisher.addPluginIdsForDifferences(pluginIds, tdbPublisher);
}
}
}
/**
* Determines two Tdbs are equal. Equality is based on having
* equal TdbPublishers, and their child TdbTitles and TdbAus.
*
* @param o the other object
* @return <code>true</code> iff they are equal Tdbs
*/
public boolean equals(Object o) {
// check for identity
if (this == o) {
return true;
}
if (o instanceof Tdb) {
try {
// if no exception thrown, there are no differences
// because the method did not try to modify the set
addPluginIdsForDifferences(Collections.<String>emptySet(), (Tdb)o);
return true;
} catch (UnsupportedOperationException ex) {
// differences because method tried to add to unmodifiable set
} catch (IllegalArgumentException ex) {
// if something was wrong with the other Tdb
} catch (IllegalStateException ex) {
// if something is wrong with this Tdb
}
}
return false;
}
/**
* Not supported for this class.
*
* @throws UnsupportedOperationException
*/
public int hashCode() {
throw new UnsupportedOperationException();
}
/**
* Merge other Tdb into this one. Makes copies of otherTdb's non-duplicate
* TdbPublisher, TdbTitle, and TdbAu objects and their non-duplicate children.
* The object themselves are not merged.
*
* @param otherTdb the other Tdb
* @throws TdbException if Tdb is sealed
*/
public void copyFrom(Tdb otherTdb) throws TdbException {
// ignore inappropriate Tdb values
if ((otherTdb == null) || (otherTdb == this)) {
return;
}
if (isSealed()) {
throw new TdbException("Cannot add otherTdb AUs to sealed Tdb");
}
// merge non-duplicate publishers of otherTdb
boolean tdbIsNew = tdbPublisherMap.isEmpty();
for (TdbPublisher otherPublisher : otherTdb.getAllTdbPublishers().values()) {
String pubName = otherPublisher.getName();
TdbPublisher thisPublisher;
boolean publisherIsNew = true;
if (tdbIsNew) {
// no need to check for existing publisher if TDB is new
thisPublisher = new TdbPublisher(pubName);
tdbPublisherMap.put(pubName, thisPublisher);
} else {
thisPublisher = tdbPublisherMap.get(pubName);
publisherIsNew = (thisPublisher == null);
if (publisherIsNew) {
// copy publisher if not present in this Tdb
thisPublisher = new TdbPublisher(pubName);
tdbPublisherMap.put(pubName, thisPublisher);
}
}
// merge non-duplicate titles of otherPublisher into thisPublisher
for (TdbTitle otherTitle : otherPublisher.getTdbTitles()) {
String otherId = otherTitle.getId();
TdbTitle thisTitle;
boolean titleIsNew = true;
if (publisherIsNew) {
// no need to check for existing title if publisher is new
thisTitle = otherTitle.copyForTdbPublisher(thisPublisher);
thisPublisher.addTdbTitle(thisTitle);
} else {
thisTitle = thisPublisher.getTdbTitleById(otherId);
titleIsNew = (thisTitle == null);
if (titleIsNew) {
// copy title if not present in this publisher
thisTitle = otherTitle.copyForTdbPublisher(thisPublisher);
thisPublisher.addTdbTitle(thisTitle);
} else if (! thisTitle.getName().equals(otherTitle.getName())) {
// error because it could lead to a missing title -- one probably has a typo
// (what about checking other title elements too?)
logger.error("Ignorning duplicate title entry: \"" + otherTitle.getName()
+ "\" with the same ID as \"" + thisTitle.getName() + "\"");
}
}
// merge non-duplicate TdbAus of otherTitle into thisTitle
for (TdbAu otherAu : otherTitle.getTdbAus()) {
// no need to check for existing au if title is new
String pluginId = otherAu.getPluginId();
if (titleIsNew || !getTdbAus(pluginId).contains(otherAu)) {
// always succeeds we've already checked for duplicate
TdbAu thisAu = otherAu.copyForTdbTitle(thisTitle);
addTdbAuForPlugin(thisAu);
} else {
TdbAu thisAu = findExistingTdbAu(otherAu);
if (!thisAu.getTdbTitle().getName().equals(otherAu.getTdbTitle().getName())) {
if (!thisAu.getName().equals(otherAu.getName())) {
logger.error("Ignorning duplicate au entry: \"" + otherAu.getName()
+ "\" for title \"" + otherAu.getTdbTitle().getName()
+ "\" with same definion as existing au entry: \""
+ thisAu.getName() + "\" for title \""
+ thisAu.getTdbTitle().getName() + "\"");
} else {
logger.error("Ignorning duplicate au entry: \"" + otherAu.getName()
+ "\" for title \"" + otherAu.getTdbTitle().getName()
+ "\" with same definion as existing one for title \""
+ thisAu.getTdbTitle().getName() + "\"");
}
} else if (!thisAu.getName().equals(otherAu.getName())) {
// error because it could lead to a missing AU -- one probably has a typo
logger.error("Ignorning duplicate au entry: \"" + otherAu.getName()
+ "\" with the same definition as \"" + thisAu.getName()
+ "\" for title \"" + otherAu.getTdbTitle().getName());
} else {
logger.warning("Ignoring duplicate au entry: \"" + otherAu.getName()
+ "\" for title \"" + otherAu.getTdbTitle().getName());
}
}
}
}
}
}
/**
* Find existing TdbAu with same Id as another one.
* @param otherAu another TdbAu
* @return an existing TdbAu already in thisTdb
*/
protected TdbAu findExistingTdbAu(TdbAu otherAu) {
// check for duplicate AU with same plugin for this Tdb
Collection<TdbAu> aus = getTdbAus(otherAu.getPluginId());
for (TdbAu au : aus) {
if (au.equals(otherAu)) {
return au;
}
}
return null;
}
/**
* Returns a collection of TdbAus for the specified plugin ID.
* <p>
* Note: the returned collection should not be modified.
*
* @param pluginId the plugin ID
* @return a collection of TdbAus for the plugin; <code>null</code>
* if no TdbAus for the specified plugin in this configuration.
*/
public Collection<TdbAu> getTdbAus(String pluginId) {
Collection<TdbAu> aus = pluginIdTdbAusMap.get(pluginId);
return (aus != null) ? aus : Collections.<TdbAu>emptyList();
}
/**
* Returns the TdbAus for all plugin IDs.
* <p>
* Note: the returned map should not be modified.
*
* @return the TdbAus for all plugin IDs
*/
public Map<String, Collection<TdbAu>> getAllTdbAus() {
return (pluginIdTdbAusMap != null) ? pluginIdTdbAusMap : Collections.<String,Collection<TdbAu>>emptyMap();
}
/**
* Return the number of TdbAus in this Tdb.
*
* @return the total TdbAu count
*/
public int getTdbAuCount() {
return tdbAuCount;
}
/**
* Return the number of TdbTitles in this Tdb.
*
* @return the total TdbTitle count
*/
public int getTdbTitleCount() {
int titleCount = 0;
for (TdbPublisher publisher : tdbPublisherMap.values()) {
titleCount += publisher.getTdbTitleCount();
}
return titleCount;
}
/**
* Return the number of TdbPublishers in this Tdb.
*
* @return the total TdbPublisher count
*/
public int getTdbPublisherCount() {
return tdbPublisherMap.size();
}
/**
* Add a new TdbAu from properties. This method recognizes
* properties of the following form:
* <pre>
* Properties p = new Properties();
* p.setProperty("title", "Air & Space Volume 1)");
* p.setProperty("journalTitle", "Air and Space");
* p.setProperty("plugin", org.lockss.plugin.smithsonian);
* p.setProperty("pluginVersion", "4");
* p.setProperty("issn", "0886-2257");
* p.setProperty("param.1.key", "volume");
* p.setProperty("param.1.value", "1");
* p.setProperty("param.2.key", "year");
* p.setProperty("param.2.value", "2001");
* p.setProperty("param.2.editable", "true");
* p.setProperty("param.3.key", "journal_id");
* p.setProperty("param.3.value", "0886-2257");
* p.setProperty("attributes.publisher", "Smithsonian Institution");
* </pre>
* <p>
* The "attributes.publisher" property is used to identify the publisher.
* If a unique journalID is specified it is used to select among titles
* for a publisher. A journalID can be specified indirectly through a
* "journal_id" param or an "issn" property. If a journalId is not
* specified, the "journalTitle" property is used to select the the title.
* <p>
* Properties other than "param", "attributes", "title", "journalTitle",
* "journalId", and "plugin" are converted to attributes of the AU. Only
* "title" and "plugin" are required properties. If "attributes.publisher"
* or "journalTitle" are missing, their values are synthesized from the
* "title" property.
*
* @param props a map of title properties
* @return the TdbAu that was added
* @throws TdbException if this Tdb is sealed, or the
* AU already exists in this Tdb
*/
public TdbAu addTdbAuFromProperties(Properties props) throws TdbException {
if (props == null) {
throw new IllegalArgumentException("properties cannot be null");
}
// verify not sealed
if (isSealed()) {
throw new TdbException("cannot add au to sealed TDB");
}
TdbAu au = newTdbAu(props);
addTdbAu(props, au);
return au;
}
/**
* Create a new TdbAu instance from the properties.
*
* @param props the properties
* @return a TdbAu instance set built from the properties
*/
private TdbAu newTdbAu(Properties props) {
String pluginId = (String)props.get("plugin");
if (pluginId == null) {
throw new IllegalArgumentException("TdbAu plugin ID not specified");
}
String auName = props.getProperty("title");
if (auName == null) {
throw new IllegalArgumentException("TdbAu title not specified");
}
// create a new TdbAu and set its elements
TdbAu au = new TdbAu(auName, pluginId);
// process attrs, and params
Map<String, Map<String,String>> paramMap = new HashMap<String, Map<String,String>>();
for (Map.Entry<Object,Object> entry : props.entrySet()) {
String key = String.valueOf(entry.getKey());
String value = String.valueOf(entry.getValue());
if (key.startsWith("attributes.")) {
// set attributes directly
String name = key.substring("attributes.".length());
try {
au.setAttr(name, value);
} catch (TdbException ex) {
logger.warning("Cannot set attribute \"" + name + "\" with value \"" + value + "\" -- ignoring");
}
} else if (key.startsWith("param.")) {
// skip to param name
String param = key.substring("param.".length());
int i;
if ( ((i = param.indexOf(".key")) < 0)
&& ((i = param.indexOf(".value")) < 0)) {
logger.warning("Ignoring unexpected param key for au \"" + auName + "\" key: \"" + key + "\" -- ignoring");
} else {
// get param map for pname
String pname = param.substring(0,i);
Map<String,String> pmap = paramMap.get(pname);
if (pmap == null) {
pmap = new HashMap<String,String>();
paramMap.put(pname, pmap);
}
// add name and value to param map for pname
String name = param.substring(i+1);
pmap.put(name, value);
}
} else if ( !key.equals("title") // TdbAu has "name" property
&& !key.equals("plugin") // TdbAu has "pluginId" property
&& !key.equals("journalTitle") // TdbAu has "title" TdbTitle property
&& !key.startsWith("journal.")) { // TdbAu has "title" TdbTitle property
// translate all other properties into AU properties
try {
au.setPropertyByName(key, value);
} catch (TdbException ex) {
logger.warning("Cannot set property \"" + key + "\" with value \"" + value + "\" -- ignoring");
}
}
}
// set param from accumulated "key", and "value" entries
for (Map<String, String> pmap : paramMap.values()) {
String name = pmap.get("key");
String value = pmap.get("value");
if (name == null) {
logger.warning("Ignoring property with null name");
} else if (value == null) {
logger.warning("Ignoring property \"" + name + "\" with null value");
} else {
try {
au.setParam(name, value);
} catch (TdbException ex) {
logger.warning("Cannot set param \"" + name + "\" with value \"" + value + "\" -- ignoring");
}
}
}
return au;
}
/**
* Add a TdbAu to a TdbTitle and TdbPubisher, and add links to
* the TdbTitle specified by the properties.
*
* @param props the properties
* @param au the TdbAu to add
* @throws TdbException if the AU already exists in this Tdb
*/
private void addTdbAu(Properties props, TdbAu au) throws TdbException {
// add au for plugin assuming it is not a duplicate
if (!addTdbAuForPlugin(au)) {
// au already registered -- report existing au
TdbAu existingAu = findExistingTdbAu(au);
String titleName = getTdbTitleName(props, au);
if (!titleName.equals(existingAu.getTdbTitle().getName())) {
throw new TdbException(
"Cannot add duplicate au entry: \"" + au.getName()
+ "\" for title \"" + titleName
+ "\" with same definition as existing au entry: \""
+ existingAu.getName() + "\" for title \""
+ existingAu.getTdbTitle().getName() + "\" to title database");
} else if (!existingAu.getName().equals(au.getName())) {
// error because it could lead to a missing AU -- one probably has a typo
throw new TdbException(
"Cannot add duplicate au entry: \"" + au.getName()
+ "\" with the same definition as \"" + existingAu.getName()
+ "\" for title \"" + titleName + "\" to title database");
} else {
throw new TdbException(
"Cannot add duplicate au entry: \"" + au.getName()
+ "\" for title \"" + titleName + "\" to title database");
}
}
// get or create the TdbTitle for this
TdbTitle title = getTdbTitle(props, au);
try {
// add AU to title
title.addTdbAu(au);
} catch (TdbException ex) {
// if we can't add au to title, remove for plugin and re-throw exception
removeTdbAuForPlugin(au);
throw ex;
}
// process title links
Map<String, Map<String,String>> linkMap = new HashMap<String, Map<String,String>>();
for (Map.Entry<Object,Object> entry : props.entrySet()) {
String key = ""+entry.getKey();
String value = ""+entry.getValue();
if (key.startsWith("journal.link.")) {
// skip to link name
String param = key.substring("link.".length());
int i;
if ( ((i = param.indexOf(".type")) < 0)
&& ((i = param.indexOf(".journalId")) < 0)) {
logger.warning("Ignoring nexpected link key for au \"" + au.getName() + "\" key: \"" + key + "\"");
} else {
// get link map for linkName
String lname = param.substring(0,i);
Map<String,String> lmap = linkMap.get(lname);
if (lmap == null) {
lmap = new HashMap<String,String>();
linkMap.put(lname, lmap);
}
// add name and value to link map for link
String name = param.substring(i+1);
lmap.put(name, value);
}
}
}
// add links to title from accumulated "type", "journalId" entries
for (Map<String, String> lmap : linkMap.values()) {
String name = lmap.get("type");
String value = lmap.get("journalId");
if ((name != null) && (value != null)) {
try {
TdbTitle.LinkType linkType = TdbTitle.LinkType.valueOf(name);
title.addLinkToTdbTitleId(linkType, value);
} catch (IllegalArgumentException ex) {
logger.warning("Ignoring unknown link type for au \"" + au.getName() + "\" name: \"" + name + "\"");
}
}
}
}
/**
* Get title ID from properties and TdbAu.
*
* @param props the properties
* @param au the TdbAu
* @return the title ID or <code>null</code> if not found
*/
private String getTdbTitleId(Properties props, TdbAu au) {
// get the title ID from one of several props
String titleId = props.getProperty("journal.id"); // proposed new property
if (titleId == null) {
// use "journal_id" param as title Id if not already set
// proposed to replace with "journal.id" property
titleId = au.getParam("journal_id");
}
// use isbn property as title id if not already set
if (titleId == null) {
titleId = props.getProperty("isbn");
}
// use eissn property as title id if not already set
if (titleId == null) {
titleId = props.getProperty("eissn");
}
// use issn property as title id if not already set
if (titleId == null) {
titleId = props.getProperty("issn");
}
return titleId;
}
/**
* Get or create TdbTitle for the specified properties and TdbAu.
*
* @param props the properties
* @param au the TdbAu
* @return the corresponding TdbTitle
*/
private TdbTitle getTdbTitle(Properties props, TdbAu au) {
TdbTitle title = null;
// get publisher name
String publisherNameFromProps = getTdbPublisherName(props, au);
// get the title name
String titleNameFromProps = getTdbTitleName(props, au);
// get the title ID
String titleIdFromProps = getTdbTitleId(props, au);
String titleId = titleIdFromProps;
if (titleId == null) {
// generate a titleId if one not specified, using the
// hash code of the combined title name and publisher names
int hash = (titleNameFromProps + publisherNameFromProps).hashCode();
titleId = (hash < 0) ? ("id:1" +(-hash)) : ("id:0" + hash);
}
// get publisher specified by property name
TdbPublisher publisher = tdbPublisherMap.get(publisherNameFromProps);
if (publisher != null) {
// find title from publisher
title = publisher.getTdbTitleById(titleId);
if (title != null) {
// warn that title name is different
if (!title.getName().equals(titleNameFromProps)) {
logger.warning("Title for au \"" + au.getName() + "\": \"" + titleNameFromProps
+ "\" is different than existing title \"" + title.getName()
+ "\" for id " + titleId + " -- using existing title.");
}
return title;
}
}
if (publisher == null) {
// warn of missing publisher name
if (publisherNameFromProps.startsWith(UNKNOWN_PUBLISHER_PREFIX)) {
logger.warning("Publisher missing for au \"" + au.getName() + "\" -- using \"" + publisherNameFromProps + "\"");
}
// create new publisher for specified publisher name
publisher = new TdbPublisher(publisherNameFromProps);
tdbPublisherMap.put(publisherNameFromProps, publisher);
}
// warn of missing title name and/or id
if (titleNameFromProps.startsWith(UNKNOWN_TITLE_PREFIX)) {
logger.warning("Title missing for au \"" + au.getName() + "\" -- using \"" + titleNameFromProps + "\"");
}
if (titleIdFromProps == null) {
logger.warning("Title ID missing for au \"" + au.getName() + "\" -- using " + titleId);
}
// create title and add to publisher
title = new TdbTitle(titleNameFromProps, titleId);
try {
publisher.addTdbTitle(title);
} catch (TdbException ex) {
// shouldn't happen: title already exists in publisher
logger.error(ex.getMessage(), ex);
}
return title;
}
/**
* Get publisher name from properties and TdbAu. Creates a name
* based on title name if not specified.
*
* @param props the properties
* @param au the TdbAu
* @return the publisher name
*/
private String getTdbPublisherName(Properties props, TdbAu au) {
// use "publisher" attribute if specified, or synthesize from titleName.
// proposed to replace with publisher.name property
String publisherName = props.getProperty("attributes.publisher");
if (publisherName == null) {
publisherName = props.getProperty("publisher.name"); // proposed new property
}
if (publisherName == null) {
// create publisher name from title name if not specified
String titleName = getTdbTitleName(props, au);
publisherName = UNKNOWN_PUBLISHER_PREFIX + "[" + titleName + "]";
}
return publisherName;
}
/**
* Get the TdbTitle name from the properties. Fall back to a name
* derived from the TdbAU name if not specified.
*
* @param props a group of properties
* @param au the TdbAu
* @return a TdbTitle name
*/
private String getTdbTitleName(Properties props, TdbAu au) {
// use "journalTitle" prop if specified, or synthesize it
// from auName and one of several properties
String titleName = props.getProperty("journalTitle");
if (titleName == null) {
titleName = props.getProperty("journal.title"); // proposed to replace journalTitle
}
if (titleName == null) {
String issue = au.getParam("issue");
String year = au.getParam("year");
String volume = au.getParam("volume");
if (volume == null) {
volume = au.getParam("volume_str");
}
String auName = au.getName();
String auNameLC = auName.toLowerCase();
if ((volume != null) && auNameLC.endsWith(" vol " + volume)) {
titleName = auName.substring(0, auName.length()-" vol ".length() - volume.length());
} else if ((volume != null) && auNameLC.endsWith(" volume " + volume)) {
titleName = auName.substring(0, auName.length()-" volume ".length() - volume.length());
} else if ((issue != null) && auNameLC.endsWith(" issue " + issue)) {
titleName = auName.substring(0, auName.length()-" issue ".length() - issue.length());
} else if ((year != null) && auNameLC.endsWith(" " + year)) {
titleName = auName.substring(0, auName.length()-" ".length() - year.length());
} else {
titleName = UNKNOWN_TITLE_PREFIX + "[" + auName + "]";
}
}
return titleName;
}
/**
* Get the linked titles for the specified link type.
*
* @param linkType the link type {@see TdbTitle} for description of link types
* @param title the TdbTitle with links
* @return a collection of linked titles for the specified type
*/
public Collection<TdbTitle> getLinkedTdbTitlesForType(TdbTitle.LinkType linkType, TdbTitle title) {
if (linkType == null) {
throw new IllegalArgumentException("linkType cannot be null");
}
if (title == null) {
throw new IllegalArgumentException("title cannot be null");
}
Collection<String> titleIds = title.getLinkedTdbTitleIdsForType(linkType);
if (titleIds.isEmpty()) {
return Collections.emptyList();
}
ArrayList<TdbTitle> titles = new ArrayList<TdbTitle>();
for (String titleId : titleIds) {
TdbTitle aTitle = getTdbTitleById(titleId);
if (aTitle != null) {
titles.add(aTitle);
}
}
titles.trimToSize();
return titles;
}
/**
* Get the title for the specified titleId.
*
* @param titleId the titleID
* @return the title for the titleId or <code>null</code. if not found
*/
public TdbTitle getTdbTitleById(String titleId)
{
if (titleId == null) {
throw new IllegalArgumentException("titleId cannot be null");
}
TdbTitle title = null;
for (TdbPublisher publisher : tdbPublisherMap.values()) {
title = publisher.getTdbTitleById(titleId);
if (title != null) {
break;
}
}
return title;
}
/**
* Returns a collection of TdbTitles for the specified title name
* across all publishers.
*
* @param titleName the title name
* @return a collection of TdbTitles that match the title name
*/
public Collection<TdbTitle> getTdbTitlesByName(String titleName)
{
if (titleName == null) {
return Collections.emptyList();
}
ArrayList<TdbTitle> titles = new ArrayList<TdbTitle>();
for (TdbPublisher publisher : tdbPublisherMap.values()) {
titles.addAll(publisher.getTdbTitlesByName(titleName));
}
titles.trimToSize();
return titles;
}
/**
* Get the publisher for the specified name.
*
* @param name the publisher name
* @return the publisher, or <code>null</code> if not found
*/
public TdbPublisher getTdbPublisher(String name) {
return (tdbPublisherMap != null) ? tdbPublisherMap.get(name) : null;
}
/**
* Returns all TdbPubishers in this configuration.
* <p>
* Note: The returned map should not be modified.
*
* @return a map of publisher names to publishers
*/
public Map<String, TdbPublisher> getAllTdbPublishers() {
return (tdbPublisherMap != null) ? tdbPublisherMap : Collections.<String,TdbPublisher>emptyMap();
}
/** Print a full description of all elements in the Tdb */
public void prettyPrint(PrintStream ps) {
ps.println("Tdb");
TreeMap<String, TdbPublisher> sorted =
new TreeMap<String, TdbPublisher>(CatalogueOrderComparator.SINGLETON);
sorted.putAll(getAllTdbPublishers());
for (TdbPublisher tdbPublisher : sorted.values()) {
tdbPublisher.prettyPrint(ps, 2);
}
}
}
|
package org.mapyrus;
import java.util.ArrayList;
import java.util.HashMap;
/**
* A parsed statement.
* Can be one of several types. A conditional statement,
* a block of statements making a procedure or just a plain command.
*/
public class Statement
{
/*
* Possible types of statements.
*/
public static final int CONDITIONAL = 2;
public static final int REPEAT_LOOP = 3;
public static final int WHILE_LOOP = 4;
public static final int FOR_LOOP = 5;
public static final int BLOCK = 6;
public static final int COLOR = 10;
public static final int LINESTYLE = 11;
public static final int FONT = 12;
public static final int JUSTIFY = 13;
public static final int MOVE = 14;
public static final int DRAW = 15;
public static final int RDRAW = 16;
public static final int ARC = 17;
public static final int CIRCLE = 18;
public static final int ELLIPSE = 19;
public static final int BEZIER = 20;
public static final int WEDGE = 21;
public static final int SPIRAL = 22;
public static final int BOX = 23;
public static final int ROUNDEDBOX = 24;
public static final int BOX3D = 25;
public static final int HEXAGON = 26;
public static final int PENTAGON = 27;
public static final int TRIANGLE = 28;
public static final int STAR = 29;
public static final int ADDPATH = 30;
public static final int CLEARPATH = 31;
public static final int CLOSEPATH = 32;
public static final int SAMPLEPATH = 33;
public static final int STRIPEPATH = 34;
public static final int SHIFTPATH = 35;
public static final int PARALLELPATH = 36;
public static final int SELECTPATH = 37;
public static final int SINKHOLE = 38;
public static final int GUILLOTINE = 39;
public static final int STROKE = 40;
public static final int FILL = 41;
public static final int GRADIENTFILL = 42;
public static final int PROTECT = 43;
public static final int UNPROTECT = 44;
public static final int CLIP = 45;
public static final int LABEL = 46;
public static final int FLOWLABEL = 47;
public static final int TABLE = 48;
public static final int ICON = 49;
public static final int GEOIMAGE = 50;
public static final int EPS = 51;
public static final int SCALE = 52;
public static final int ROTATE = 53;
public static final int WORLDS = 54;
public static final int PROJECT = 55;
public static final int DATASET = 56;
public static final int FETCH = 57;
public static final int NEWPAGE = 58;
public static final int ENDPAGE = 59;
public static final int PRINT = 60;
public static final int LOCAL = 61;
public static final int LET = 62;
public static final int EVAL = 63;
public static final int KEY = 64;
public static final int LEGEND = 65;
public static final int MIMETYPE = 66;
/*
* Statement type for call and return to/from user defined procedure block.
*/
public static final int CALL = 1000;
public static final int RETURN = 1001;
private int mType;
/*
* Statements in an if-then-else statement.
*/
private ArrayList mThenStatements;
private ArrayList mElseStatements;
/*
* Statements in a while loop statement.
*/
private ArrayList mLoopStatements;
/*
* Name of procedure block,
* variable names of parameters to this procedure
* and block of statements in a procedure in order of execution
*/
private String mBlockName;
private ArrayList mStatementBlock;
private ArrayList mParameters;
private Expression []mExpressions;
/*
* HashMap to walk through for a 'for' loop.
*/
private Expression mForHashMapExpression;
/*
* Filename and line number within file that this
* statement was read from.
*/
private String mFilename;
private int mLineNumber;
/*
* Static statement type lookup table for fast lookup.
*/
private static HashMap mStatementTypeLookup;
static
{
mStatementTypeLookup = new HashMap();
mStatementTypeLookup.put("color", new Integer(COLOR));
mStatementTypeLookup.put("colour", new Integer(COLOR));
mStatementTypeLookup.put("linestyle", new Integer(LINESTYLE));
mStatementTypeLookup.put("font", new Integer(FONT));
mStatementTypeLookup.put("justify", new Integer(JUSTIFY));
mStatementTypeLookup.put("move", new Integer(MOVE));
mStatementTypeLookup.put("draw", new Integer(DRAW));
mStatementTypeLookup.put("rdraw", new Integer(RDRAW));
mStatementTypeLookup.put("arc", new Integer(ARC));
mStatementTypeLookup.put("circle", new Integer(CIRCLE));
mStatementTypeLookup.put("ellipse", new Integer(ELLIPSE));
mStatementTypeLookup.put("bezier", new Integer(BEZIER));
mStatementTypeLookup.put("wedge", new Integer(WEDGE));
mStatementTypeLookup.put("spiral", new Integer(SPIRAL));
mStatementTypeLookup.put("box", new Integer(BOX));
mStatementTypeLookup.put("roundedbox", new Integer(ROUNDEDBOX));
mStatementTypeLookup.put("box3d", new Integer(BOX3D));
mStatementTypeLookup.put("hexagon", new Integer(HEXAGON));
mStatementTypeLookup.put("pentagon", new Integer(PENTAGON));
mStatementTypeLookup.put("triangle", new Integer(TRIANGLE));
mStatementTypeLookup.put("star", new Integer(STAR));
mStatementTypeLookup.put("addpath", new Integer(ADDPATH));
mStatementTypeLookup.put("clearpath", new Integer(CLEARPATH));
mStatementTypeLookup.put("closepath", new Integer(CLOSEPATH));
mStatementTypeLookup.put("samplepath", new Integer(SAMPLEPATH));
mStatementTypeLookup.put("stripepath", new Integer(STRIPEPATH));
mStatementTypeLookup.put("shiftpath", new Integer(SHIFTPATH));
mStatementTypeLookup.put("parallelpath", new Integer(PARALLELPATH));
mStatementTypeLookup.put("selectpath", new Integer(SELECTPATH));
mStatementTypeLookup.put("sinkhole", new Integer(SINKHOLE));
mStatementTypeLookup.put("guillotine", new Integer(GUILLOTINE));
mStatementTypeLookup.put("stroke", new Integer(STROKE));
mStatementTypeLookup.put("fill", new Integer(FILL));
mStatementTypeLookup.put("gradientfill", new Integer(GRADIENTFILL));
mStatementTypeLookup.put("protect", new Integer(PROTECT));
mStatementTypeLookup.put("unprotect", new Integer(UNPROTECT));
mStatementTypeLookup.put("clip", new Integer(CLIP));
mStatementTypeLookup.put("label", new Integer(LABEL));
mStatementTypeLookup.put("flowlabel", new Integer(FLOWLABEL));
mStatementTypeLookup.put("table", new Integer(TABLE));
mStatementTypeLookup.put("icon", new Integer(ICON));
mStatementTypeLookup.put("geoimage", new Integer(GEOIMAGE));
mStatementTypeLookup.put("eps", new Integer(EPS));
mStatementTypeLookup.put("scale", new Integer(SCALE));
mStatementTypeLookup.put("rotate", new Integer(ROTATE));
mStatementTypeLookup.put("worlds", new Integer(WORLDS));
mStatementTypeLookup.put("project", new Integer(PROJECT));
mStatementTypeLookup.put("dataset", new Integer(DATASET));
mStatementTypeLookup.put("fetch", new Integer(FETCH));
mStatementTypeLookup.put("newpage", new Integer(NEWPAGE));
mStatementTypeLookup.put("endpage", new Integer(ENDPAGE));
mStatementTypeLookup.put("print", new Integer(PRINT));
mStatementTypeLookup.put("local", new Integer(LOCAL));
mStatementTypeLookup.put("let", new Integer(LET));
mStatementTypeLookup.put("eval", new Integer(EVAL));
mStatementTypeLookup.put("key", new Integer(KEY));
mStatementTypeLookup.put("legend", new Integer(LEGEND));
mStatementTypeLookup.put("mimetype", new Integer(MIMETYPE));
}
/**
* Constant for 'return' statement.
*/
public static final Statement RETURN_STATEMENT;
static
{
RETURN_STATEMENT = new Statement("", null);
RETURN_STATEMENT.mType = RETURN;
}
/**
* Looks up identifier for a statement name.
* @param s is the name of the statement.
* @returns numeric code for this statement, or -1 if statement
* is unknown.
*/
private int getStatementType(String s)
{
int retval;
Integer type = (Integer)mStatementTypeLookup.get(s.toLowerCase());
if (type == null)
retval = CALL;
else
retval = type.intValue();
return(retval);
}
/**
* Creates a plain statement, either a built-in command or
* a call to a procedure block that the user has defined.
* @param keyword is the name statement.
* @param expressions are the arguments for this statement.
*/
public Statement(String keyword, Expression []expressions)
{
mType = getStatementType(keyword);
if (mType == CALL)
mBlockName = keyword;
mExpressions = expressions;
}
/**
* Creates a procedure, a block of statements to be executed together.
* @param blockName is name of procedure block.
* @param parameters variable names of parameters to this procedure.
* @param statements list of statements that make up this procedure block.
*/
public Statement(String blockName, ArrayList parameters, ArrayList statements)
{
mBlockName = blockName;
mParameters = parameters;
mStatementBlock = statements;
mType = BLOCK;
}
/**
* Create an if, then, else, endif block of statements.
* @param test is expression to test.
* @param thenStatements is statements to execute if expression is true.
* @param elseStatements is statements to execute if expression is false,
* or null if there is no statement to execute.
*/
public Statement(Expression test, ArrayList thenStatements,
ArrayList elseStatements)
{
mType = CONDITIONAL;
mExpressions = new Expression[1];
mExpressions[0] = test;
mThenStatements = thenStatements;
mElseStatements = elseStatements;
}
/**
* Create a repeat or while loop block of statements.
* @param test is expression to test before each iteration of loop.
* @param loopStatements is statements to execute for each loop iteration.
* @param isWhileLoop true for a while loop, false for a repeat loop.
*/
public Statement(Expression test, ArrayList loopStatements,
boolean isWhileLoop)
{
mType = isWhileLoop ? WHILE_LOOP : REPEAT_LOOP;
mExpressions = new Expression[1];
mExpressions[0] = test;
mLoopStatements = loopStatements;
}
/**
* Create a for loop block of statements.
* @param test is expression to test before each iteration of loop.
* @param loopStatements is statements to execute for each loop iteration.
*/
public Statement(Expression var, Expression arrayVar, ArrayList loopStatements)
{
mType = FOR_LOOP;
mExpressions = new Expression[1];
mExpressions[0] = var;
mForHashMapExpression = arrayVar;
mLoopStatements = loopStatements;
}
/**
* Sets the filename and line number that this statement was read from.
* This is for use in any error message for this statement.
* @param filename is name of file this statement was read from.
* @param lineNumber is line number within file containing this statement.
*/
public void setFilenameAndLineNumber(String filename, int lineNumber)
{
mFilename = filename;
mLineNumber = lineNumber;
}
/**
* Returns filename and line number that this statement was read from.
* @return string containing filename and line number.
*/
public String getFilenameAndLineNumber()
{
return(mFilename + ":" + mLineNumber);
}
/**
* Returns filename that this statement was read from.
* @return string containing filename.
*/
public String getFilename()
{
return(mFilename);
}
/**
* Returns the type of this statement.
* @return statement type.
*/
public int getType()
{
return(mType);
}
public Expression []getExpressions()
{
return(mExpressions);
}
/**
* Returns list of statements in "then" section of "if" statement.
* @return list of statements.
*/
public ArrayList getThenStatements()
{
return(mThenStatements);
}
/**
* Returns list of statements in "else" section of "if" statement.
* @return list of statements.
*/
public ArrayList getElseStatements()
{
return(mElseStatements);
}
/**
* Returns list of statements in while or for loop statement.
* @return list of statements.
*/
public ArrayList getLoopStatements()
{
return(mLoopStatements);
}
/**
* Returns hashmap expression to walk through in a for loop statement.
* @return expression evaluating to a hashmap.
*/
public Expression getForHashMap()
{
return(mForHashMapExpression);
}
/**
* Return name of procedure block.
* @return name of procedure.
*/
public String getBlockName()
{
return(mBlockName);
}
/**
* Return variable names of parameters to a procedure.
* @return list of parameter names.
*/
public ArrayList getBlockParameters()
{
return(mParameters);
}
/**
* Return statements in a procedure.
* @return ArrayList of statements that make up the procedure.
*/
public ArrayList getStatementBlock()
{
return(mStatementBlock);
}
}
|
public class RBTree<E extends Comparable<E>> {
private int size = 0;
private RBTreeNode<E> root;
public RBTree(){
}
public boolean isEmpty() {
return size == 0;
}
public void setRoot(RBTreeNode<E> node){
root = node;
}
/**
* Metodi getRoot palauttaa puun juuren
* @author
* @return puun juuri
*/
public RBTreeNode<E> getRoot(){
return root;
}
public boolean add(E data) {
RBTreeNode<E> n = this.getRoot();
if (n == null) {
RBTreeNode<E> node = new RBTreeNode<E>(data);
node.setColor(0);
root = node;
size++;
return true;
}
while (n != null) {
E nE = n.getElement();
if (nE.equals(data))
return false;
else if (nE.compareTo(data) < 0) {
if (n.getRightChild() == null) {
RBTreeNode<E> node = new RBTreeNode<E>(data);
node.setColor(0);
n.setRightChild(node);
RBTreeAddFixup(node);
size++;
return true;
}
else
n = n.getRightChild();
}
else {
if (n.getLeftChild() == null) {
RBTreeNode<E> node = new RBTreeNode<E>(data);
node.setColor(0);
n.setLeftChild(node);
RBTreeAddFixup(node);
size++;
return true;
}
else
n = n.getLeftChild();
}
}
return false;
}
/**
* Metodi remove poistaa parametrina annetun objektin puusta ja kutsuu tasapainotusmetodia
* RBTreeRemoveFixup
* @author Tero Kettunen
* @param data Puusta poistettava objekti
* @return true, jos data poistettiin; muuten false
*/
public boolean remove(E data){
RBTreeNode<E> rn = search(data);
RBTreeNode<E> y; //apusolmu
RBTreeNode<E> x; //apusolmu
if(rn==null){
return false;
}
if(rn.getLeftChild()==null || rn.getRightChild()==null){
y = rn;
}else{
y = successor(rn);
}
if(y.getLeftChild() != null){
x = y.getLeftChild();
}else{
x = y.getRightChild();
}
x.setParent(y.getParent());
if(y.getParent() == null){
setRoot(x);
}else if(y == y.getParent().getLeftChild()){
y.getParent().setLeftChild(x);
}else{
y.getParent().setRightChild(x);
}
if(y != rn){
rn.setElement(y.getElement());
}
if(y.getColor()==1){ //jos y on musta
RBTreeRemoveFixup(x);
}
return true;
}
public RBTreeNode<E> search(E data) {
if (size == 0)
return null;
RBTreeNode<E> n = this.getRoot();
while (n != null) {
if (data.compareTo(n.getElement()) == 0)
return n;
if (data.compareTo(n.getElement()) < 0)
n = n.getLeftChild();
else
n = n.getRightChild();
}
return null;
}
public RBTreeNode<E> successor(RBTreeNode<E> node) {
if (node.getRightChild() != null)
return min(node.getRightChild());
else {
RBTreeNode<E> n = node.getParent();
while (n != null && node == n.getRightChild()) {
node = n;
n = n.getParent();
}
return n;
}
}
public RBTreeNode<E> min(RBTreeNode<E> node) {
while (node.getLeftChild() != null)
node = node.getLeftChild();
return node;
}
public RBTree<E> union(RBTree<E> t) {
return t;
}
/**
* Metodi intersection muodostaa leikkauksen kutsuttavasta ja parametrina saadusta puusta
* @author Tero Kettunen
* @param t leikkaukseen tuleva puu
* @return Kahden puun joukko-opillista leikkausta kuvaava uusi puu
*
*/
public RBTree<E> intersection(RBTree<E> t) {
return t;
}
public RBTree<E> difference(RBTree<E> t) {
return t;
}
public int size(){
return size;
}
private void RBTreeRemoveFixup(RBTreeNode<E> node) {
}
private void RBTreeAddFixup(RBTreeNode<E> node) {
}
private void leftRotate(RBTreeNode<E> node) {
RBTreeNode<E> y = node.getRightChild(); //otetaan talteen noden oikea lapsi y
node.setRightChild(y.getLeftChild()); // y:n vasen alipuu noden oikeaksi alipuuksi
y.getLeftChild().setParent(node);
y.setParent(node.getParent()); // noden vanhempi y:n vanhemmaksi
if(node.getParent()==null){ // Jos node on juuri
setRoot(y);
}else if(node==node.getParent().getLeftChild()){ //Jos node on vasen lapsi
node.getParent().setLeftChild(y);
}else{ //Jos se on oikea lapsi
node.getParent().setRightChild(y);
}
y.setLeftChild(node);
node.setParent(y);
}
private void rightRotate(RBTreeNode<E> node) {
RBTreeNode<E> y = node.getLeftChild(); //otetaan talteen noden vasen lapsi y
node.setLeftChild(y.getRightChild()); // y:n oikea alipuu noden vasemmaksi alipuuksi
y.getRightChild().setParent(node);
y.setParent(node.getParent()); // noden vanhempi y:n vanhemmaksi
if(node.getParent()==null){ // Jos node on juuri
setRoot(y);
}else if(node==node.getParent().getRightChild()){ //Jos node on oikea lapsi
node.getParent().setRightChild(y);
}else{ //Jos se on vasen lapsi
node.getParent().setLeftChild(y);
}
y.setRightChild(node);
node.setParent(y);
}
}
|
package process;
import javafx.util.Pair;
import java.util.ArrayList;
// Pour chaque feature (ce que j'ai compris...)
public class DecisionStump {
private double threshold;
private int dim;
private boolean toggle;
private double error;
private double margin;
private double W1plus;
private double W0plus;
private double W1min;
private double W0min;
private ArrayList<Pair<Integer, Boolean>> features;
private ArrayList<Double> w;
// Initialisation
public DecisionStump(ArrayList<Pair<Integer, Boolean>> features, ArrayList<Double> w) {
this.margin = 0;
this.error = 2;
this.W1plus = 0;
this.W1min = 0;
this.W1min = 0;
this.W0min = 0;
// Should be arranged in ascending order
this.features = (ArrayList<Pair<Integer, Boolean>>) features.clone();
this.w = (ArrayList<Double>) w.clone();
this.threshold = this.features.get(0).getKey();
for (int i = 0; i < this.features.size(); i++) {
if (this.features.get(i).getKey() < this.threshold)
this.threshold = this.features.get(i).getKey();
// Pas sur...
if (this.w.get(i) == 1)
this.W1plus += this.w.get(i);
else
this.W0plus += this.w.get(i);
}
this.threshold
}
public void compute() {
int n = this.features.size() - 1;
int j = 0;
double tmp_threshold = this.threshold;
double tmp_margin = this.margin;
double tmp_error = 0;
boolean tmp_togle = false;
while (true) {
double errorPlus = W1plus + W0plus;
double errorMin = W1min + W0min;
if (errorPlus < errorMin) {
tmp_error = errorPlus;
tmp_togle = true;
} else {
tmp_error = errorMin;
tmp_togle = false;
}
if (tmp_error < this.error || tmp_error == this.error && tmp_margin > this.margin) {
this.error = tmp_error;
this.threshold = tmp_threshold;
this.margin = tmp_margin;
this.toggle = tmp_togle;
}
if (j == n)
break;
j++;
while (true) {
if (!this.features.get(j).getValue()) {
this.W0min += this.w.get(j);
this.W0plus -= this.w.get(j);
} else {
this.W1min += this.w.get(j);
this.W1plus -= this.w.get(j);
}
if (j == n || this.features.get(j).getKey() == this.features.get(j + 1).getKey())
break;
j++;
}
if (j == n) {
tmp_threshold = this.features.get(j).getKey();
tmp_margin = 0;
} else {
tmp_threshold = (this.features.get(j).getKey() + this.features.get(j + 1).getKey()) / 2;
tmp_margin = this.features.get(j + 1).getKey() + this.features.get(j).getKey();
}
}
}
public static DecisionStump bestStump(ArrayList<ArrayList<Pair<Integer, Boolean>>> features, ArrayList<Double> w) {
DecisionStump best = new DecisionStump(features.get(0), w);
best.compute();
for (int i = 1; i < features.size(); i++) {
DecisionStump decisionStump = new DecisionStump(features.get(i), w);
decisionStump.compute();
if (decisionStump.error < best.error || decisionStump.error == best.error && decisionStump.margin > best.margin) {
best = decisionStump;
}
}
return best;
}
}
|
package src.controller;
import java.util.ArrayList;
import src.model.MapEntity_Relation;
import java.io.Serializable;
/**
*
* @author JohnReedLOL
*/
abstract public class Entity extends DrawableThing implements Serializable {
// Converts an entity's name [which must be unique] into a unique base 35 number
private static final long serialVersionUID = Long.parseLong("ENTITY", 35);
// map_relationship_ is used in place of a map_referance_
private final MapEntity_Relation map_relationship_;
/**
* Use this to call functions contained within the MapEntity relationship
* @return map_relationship_
* @author Reed, John
*/
@Override
public MapEntity_Relation getMapRelation() {
return map_relationship_;
}
public Entity(String name, char representation,
int x_respawn_point, int y_respawn_point) {
super(name, representation);
map_relationship_ = new MapEntity_Relation( this, x_respawn_point, y_respawn_point );
inventory_ = new ArrayList<Item>();
}
private Occupation occupation_ = null;
ArrayList<Item> inventory_;
// Only 1 equipped item in iteration 1
Item equipped_item_;
//private final int max_level_;
private StatsPack my_stats_after_powerups_;
public StatsPack getModifiableStatsPack() {
return my_stats_after_powerups_;
}
/**
* Adds default stats to item stats and updates my_stats_after_powerups
* @author Jessan
*/
private void recalculateStats() {
//my_stats_after_powerups_.equals(my_stats_after_powerups_.add(equipped_item_.get_stats_pack_()));
my_stats_after_powerups_ = get_default_stats_pack_().add(equipped_item_.get_default_stats_pack_());
}
/**
* this function levels up an entity
* @author Jessan
*/
public void levelUp() {
if(occupation_ == null){
//levelup normally
StatsPack new_stats = new StatsPack(0,1,1,1,1,1,1,1,1);
set_default_stats_pack(get_default_stats_pack_().add(new_stats));
}
//if occupation is not null/have an occupation
else {
set_default_stats_pack(occupation_.change_stats(get_default_stats_pack_()));
}
}
/**
* Entities should check their health after they are damaged.
*/
public void checkHealth() {
if(this.getModifiableStatsPack().getCurrentLife() < 1) {
commitSuicide();
}
}
public void commitSuicide() {
super.get_default_stats_pack_().decrementLivesLeft();
if(super.get_default_stats_pack_().getLivesLeft() < 0) {
System.out.println("game over");
}
}
public void setOccupation(Occupation occupation) {
occupation_ = occupation;
}
public Occupation getOccupation(){
return occupation_;
}
public void addItemToInventory(Item item) {
inventory_.add(item);
}
public String toString(){
String s = "Entity name: " + name_;
if(!(equipped_item_ == null))
s += "\nequppied item: " + equipped_item_.name_;
else
s += "\nequppied item: null";
s+= "\nInventory " + "(" + inventory_.size() + ")" + ":";
for(int i = 0; i < inventory_.size(); ++i){
s+= " " + inventory_.get(i).name_;
}
s+="\n";
s+="map_relationship_: ";
if(map_relationship_ == null)
s += "null";
else
s += "Not null" ;
return s;
}
}
|
package stray.util;
import com.badlogic.gdx.math.MathUtils;
public class MathHelper {
private MathHelper() {
};
public static double getScaleFactor(float iMasterSize, float iTargetSize) {
double dScale = 1;
if (iMasterSize > iTargetSize) {
dScale = (double) iTargetSize / (double) iMasterSize;
} else {
dScale = (double) iTargetSize / (double) iMasterSize;
}
return dScale;
}
public static float calcRotationAngleInDegrees(float x, float y, float tx, float ty) {
float theta = MathUtils.atan2(tx - x, ty - y);
float angle = theta * MathUtils.radiansToDegrees;
if (angle < 0) {
angle += 360;
}
angle += 180;
return angle;
}
public static float calcRotationAngleInRadians(float x, float y, float tx, float ty) {
return calcRotationAngleInDegrees(x, y, tx, ty) * MathUtils.degreesToRadians;
}
public static double calcRadiansDiff(float x, float y, float tx, float ty) {
double d = calcRotationAngleInDegrees(x, y, tx, ty);
d -= 90;
d %= 360;
return Math.toRadians(d);
}
public static float timePulse(float num) {
return ((num > 0.5f ? (0.5f - (num - 0.5f)) : num)) - MathUtils.clamp(0.50000001f, 1f, 0.5f);
}
public static double calcDistance(double x1, double y1, double x2, double y2) {
return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
public static double clamp(double val, double min, double max) {
return Math.max(min, Math.min(max, val));
}
/**
* get a number from 0, 1 based on time
*
* @return
*/
public static float getNumberFromTime() {
return getNumberFromTime(System.currentTimeMillis(), 1);
}
public static float getNumberFromTime(float seconds) {
return getNumberFromTime(System.currentTimeMillis(), seconds);
}
public static float getNumberFromTime(long time, float seconds) {
return ((time % Math.round((seconds * 1000))) / (seconds * 1000f));
}
public static float clampHalf(float seconds){
float f = getNumberFromTime(seconds);
if(f >= 0.5f){
return 1f - f;
}else return f;
}
public static int getNthDigit(int number, int n) {
int base = 10;
return (int) ((number / Math.pow(base, n - 1)) % base);
}
public static int getNthDigit(long number, int n) {
int base = 10;
return (int) ((number / Math.pow(base, n - 1)) % base);
}
// original x, y, new x, y
public static double getScaleFactorToFit(float ox, float oy, float nx, float ny) {
double dScale = 1d;
double dScaleWidth = getScaleFactor(ox, nx);
double dScaleHeight = getScaleFactor(oy, ny);
dScale = Math.min(dScaleHeight, dScaleWidth);
return dScale;
}
public static boolean checkPowerOfTwo(int number) {
if (number <= 0) {
throw new IllegalArgumentException("Number is less than zero: " + number);
}
return ((number & (number - 1)) == 0);
}
// public static <T extends Comparable<T>> T clamp(T val, T min, T max) {
// if (val.compareTo(min) < 0) return min;
// else if (val.compareTo(max) > 0) return max;
// else return val;
public static float distanceSquared(float x, float y, float x2, float y2) {
return (x2 - x) * (x2 - x) + (y2 - y) * (y2 - y);
}
public static float lightingCalc(int l) {
return 1.0f - ((float) (logOfBase(15, l)));
}
public static double logOfBase(int base, int num) {
return Math.log(num) / Math.log(base);
}
public static boolean isOneOfThem(int check, int[] these) {
for (int i : these) {
if (check == i) return true;
}
return false;
}
public static boolean isOneOfThem(int check, int com) {
return check == com;
}
public static float getJumpVelo(double gravity, double distance){
return (float) (gravity * Math.sqrt((2 * distance) / gravity));
}
public static boolean intersects(double oldx, double oldy, double oldwidth, double oldheight, double oldx2,
double oldy2, double oldwidth2, double oldheight2) {
double x, y, width, height, x2, y2, width2, height2;
x = oldx;
y = oldy;
width = oldwidth;
height = oldheight;
if (oldwidth < 0) {
width = oldx + oldwidth;
x -= Math.abs(oldwidth);
}
if (oldheight < 0) {
height = oldy + oldheight;
y -= Math.abs(oldheight);
}
x2 = oldx2;
y2 = oldy2;
width2 = oldwidth2;
height2 = oldheight2;
if (oldwidth2 < 0) {
width2 = oldx2 + oldwidth2;
x2 -= Math.abs(oldwidth2);
}
if (oldheight2 < 0) {
height2 = oldy2 + oldheight2;
y -= Math.abs(oldheight2);
}
// System.out.print(x + ", " + y + ":" + width + ", " + height + " = ");
// System.out.println(x2 + ", " + y2 + ":" + width2 + ", " + height2);
if ((x > (x2 + width2))) {
// System.out.println("x > ");
return false;
}
if (((x + width) < x2)) {
// System.out.println("x2 >");
return false;
}
if ((y > (y2 + height2))) {
// System.out.println("y >");
return false;
}
if (((y + height) < y2)) {
// System.out.println("y2 >");
return false;
}
return true;
}
}
|
package tankattack;
import javafx.animation.*;
import javafx.application.*;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.effect.*;
import javafx.scene.image.*;
import javafx.scene.layout.*;
import javafx.scene.paint.*;
import javafx.scene.shape.*;
import javafx.scene.text.*;
import javafx.scene.transform.*;
import javafx.stage.Stage;
import javafx.util.*;
/**
*
* @author Ruslan
*/
public class TankAttack extends Application {
public static TankAttack sharedInstance;
public static final int NUM_FRAMES_PER_SECOND = 30;
public static final double gameWidth = 600;
public static final double gameHeight = 600;
public static double buttonWidth = gameWidth / 5;
public static double buttonHeight = gameWidth / 10;
public static double PLAYER_SPEED = 2.5;
public static double MINION_SPEED = 2.1;
public static double EVILMINION_SPEED = 3.5;
public static double KAMIKADZEEMINION_SPEED = 5;
public static double BOSS_SPEED = 1.4;
public static double BULLET_SPEED = 5.5;
public static double BULLET_DAMAGE = 10;
public static int DIFFICULTY_SETTING = 2;
private Stage stage;
private World world;
private Scene scene;
private Group root;
private VBox startQuitButtonsBox;
private VBox difficultyButtonsBox;
// Setters & Getters
public Stage stage() {
return this.stage;
}
// Actual Methods
@Override
public void start(Stage primaryStage) {
sharedInstance = this;
stage = primaryStage;
displayStartMenu();
}
public void displayStartMenu() {
stage.setTitle("Main Menu");
root = new Group();
final Scene mainMenu = new Scene(root, TankAttack.gameWidth, TankAttack.gameHeight, Color.SEAGREEN);
// Launch Background Animation
launchAnimationForDisplayMenu(stage);
// Create Buttons
createButtonsForDisplayMenu();
stage.setScene(mainMenu);
stage.show();
slideInTitle();
}
private void launchAnimationForDisplayMenu(Stage stage) {
animateTankGoingBackAndForth();
animateCircleExplosions();
}
private void createButtonsForDisplayMenu() {
VBox v = new VBox(TankAttack.gameHeight/20);
startQuitButtonsBox = v;
v.setTranslateY(TankAttack.gameHeight / 2);
v.setTranslateX(TankAttack.gameWidth/2 - TankAttack.buttonWidth/2);
Button start = this.createButton("START");
start.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
stage.setTitle("TANK ATTACK");
world = new FirstWorld();
initCurrWorld();
}
});
Button difficulty = this.createButton("DIFFICULTY");
difficulty.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
displayDifficultyMenu();
}
});
Button quit = this.createButton("QUIT");
quit.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
System.out.println("Quit button pressed.");
Platform.exit();
}
});
v.getChildren().addAll(start, difficulty, quit);
root.getChildren().add(v);
}
private void displayDifficultyMenu() {
root.getChildren().remove(this.startQuitButtonsBox);
VBox v = new VBox(TankAttack.gameHeight/20);
difficultyButtonsBox = v;
v.setTranslateY(TankAttack.gameHeight / 2);
v.setTranslateX(TankAttack.gameWidth/2 - TankAttack.buttonWidth/2);
Button easy = this.createButton("EASY");
easy.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
TankAttack.setEasy();
removeDifficultyButtonsAndDisplayMenuAgain();
}
});
Button medium = this.createButton("MEDIUM");
medium.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
TankAttack.setMedium();
removeDifficultyButtonsAndDisplayMenuAgain();
}
});
Button hard = this.createButton("HARD");
hard.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
TankAttack.setHard();
removeDifficultyButtonsAndDisplayMenuAgain();
}
});
v.getChildren().addAll(easy, medium, hard);
root.getChildren().add(v);
}
public static void setEasy() {
MINION_SPEED = 1.4;
EVILMINION_SPEED = 2.5;
KAMIKADZEEMINION_SPEED = 3;
BOSS_SPEED = 1;
DIFFICULTY_SETTING = 1;
}
public static void setMedium() {
MINION_SPEED = 2.1;
EVILMINION_SPEED = 3.5;
KAMIKADZEEMINION_SPEED = 5;
BOSS_SPEED = 1.4;
DIFFICULTY_SETTING = 2;
}
public static void setHard() {
MINION_SPEED = 3;
EVILMINION_SPEED = 4.2;
KAMIKADZEEMINION_SPEED = 5.6;
BOSS_SPEED = 3;
DIFFICULTY_SETTING = 3;
}
private void removeDifficultyButtonsAndDisplayMenuAgain() {
root.getChildren().remove(difficultyButtonsBox);
createButtonsForDisplayMenu();
}
private Button createButton(String text) {
Button returnButton = new Button();
if (!text.isEmpty()) {
returnButton.setText(text);
}
returnButton.setMinSize(buttonWidth, buttonHeight);
return returnButton;
}
public void transitionFromFirstWorldToSecondWorld() {
world = new SecondWorld();
initCurrWorld();
}
public void transitionFromSecondWorldToThirdWorld() {
world = new ThirdWorld();
initCurrWorld();
}
public void transitionFromThirdWorldToFourthWorld() {
world = new FourthWorld();
initCurrWorld();
}
private void initCurrWorld() {
// Prior to this method, set currWorld.
// rest is good to go.
scene = world.createScene();
stage.setScene(scene);
world.initAnimation();
}
public static void main(String[] args) {
launch(args);
}
private void slideInTitle() {
BorderPane b = new BorderPane();
b.setMinWidth(TankAttack.gameWidth);
b.translateYProperty().set(-60.0);
Label l = new Label("TANK ATTACK");
l.setFont(new Font("Arial", 80));
l.setTextFill(Color.GREEN);
b.setCenter(l);
KeyValue kVal = new KeyValue(b.translateYProperty(), TankAttack.gameHeight/3);
KeyFrame k = new KeyFrame(Duration.millis(3000), kVal);
Timeline timeL = new Timeline();
timeL.getKeyFrames().add(k);
timeL.setCycleCount(1);
timeL.play();
root.getChildren().add(b);
}
private void animateCircleExplosions() {
// Most of this method was obtained from stackoverflow.com
Group circles = new Group();
for(int cont = 0 ; cont < 30 ; cont++) {
Circle circle = new Circle();
if (Math.random() <= 0.5) {
circle.setFill(Color.CRIMSON);
}
else {
circle.setFill(Color.YELLOW);
}
circle.setEffect(new GaussianBlur(Math.random() * 8 + 2));
circle.setOpacity(Math.random());
circle.setRadius(Math.random()*30);
circle.setCenterX(TankAttack.gameWidth * Math.random());
circle.setCenterY(TankAttack.gameHeight * Math.random());
circles.getChildren().add(circle);
double randScale = (Math.random() * 4) + 1;
KeyValue kValueX = new KeyValue(circle.scaleXProperty() , randScale);
KeyValue kValueY = new KeyValue(circle.scaleYProperty() , randScale);
KeyFrame kFrame = new KeyFrame(Duration.millis(5000 + (Math.random() * 5000)) , kValueX , kValueY);
Timeline timeL = new Timeline();
timeL.getKeyFrames().add(kFrame);
timeL.setAutoReverse(true);
timeL.setCycleCount(Animation.INDEFINITE);
timeL.play();
}
root.getChildren().add(circles);
}
private void animateTankGoingBackAndForth() {
ImageView tank = new ImageView();
tank.xProperty().set(-gameWidth/3);
tank.translateYProperty().set(gameHeight*5/6);
tank.setImage(new Image(getClass().getResourceAsStream("tank.png")));
KeyValue kValueX = new KeyValue(tank.xProperty(), gameWidth+gameWidth/3);
KeyFrame kFrame = new KeyFrame(Duration.millis(8000) , kValueX);
Timeline timeL = new Timeline();
timeL.getKeyFrames().add(kFrame);
timeL.setAutoReverse(true);
timeL.setCycleCount(Animation.INDEFINITE);
timeL.play();
root.getChildren().add(tank);
}
}
|
import implementation.PhaseOneImpl;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.instanceOf;
/**
* implementation.PhaseOneImpl Tester.
*
* @author Group4
* @version 1.0
* @since <pre>Jan 30, 2017</pre>
*/
public class PhaseOneImplTest {
PhaseOneImpl phaseOne;
@Before
public void before() throws Exception {
phaseOne = new PhaseOneImpl();
}
@After
public void after() throws Exception {
}
/**
* Method: MoveForward()
*/
@Test
public void testMoveForwardOnce() throws Exception {
int i = phaseOne.whereIs();
phaseOne.moveForward();
Assert.assertEquals(i + 1, phaseOne.whereIs());
}
/**
* Method MoveForward()
* Move 500 times,
*/
@Test
public void testMoveForwardOOB() throws Exception {
int i = phaseOne.whereIs();
for (int j = 0; j < 501; j++) {
phaseOne.moveForward();
}
Assert.assertEquals(500, phaseOne.whereIs());
}
@Test
public void testMoveForward500carStatus() throws Exception {
for (int j = 0; j < 501; j++) {
phaseOne.moveForward();
}
Assert.assertNotEquals(0, phaseOne.carStatus[1]);
}
@Test
public void testMoveForwardParkStatus() throws Exception {
int i[] = phaseOne.moveForward();
Assert.assertEquals(phaseOne.isEmpty(), i[1]);
}
@Test
public void testMoveForwardAfterParked() throws Exception {
phaseOne.park();
int i = phaseOne.carStatus[0];
phaseOne.moveForward();
Assert.assertEquals(i, phaseOne.whereIs());
}
/**
* Method: MoveBackward()
*/
@Test
public void testMoveBackwardOnce() throws Exception {
int i = phaseOne.whereIs();
int j[] = phaseOne.moveBackward();
Assert.assertEquals(i, j[0]);
}
@Test
public void testMoveBackwardOOB() throws Exception {
int i = phaseOne.whereIs();
phaseOne.moveBackward();
Assert.assertEquals(0, phaseOne.whereIs());
}
@Test
public void testMoveBackwardParkStatus() throws Exception {
int i[] = phaseOne.moveBackward();
Assert.assertEquals(i[1], phaseOne.isEmpty());
}
@Test
public void testMoveBackwardAfterParked() throws Exception {
phaseOne.park();
int i = phaseOne.carStatus[0];
phaseOne.moveBackward();
Assert.assertEquals(i, phaseOne.whereIs());
}
/**
* Method: Park()
*/
@Test
public void testParkCarMovedForward() throws Exception {
int i = phaseOne.whereIs();
phaseOne.park();
int j = phaseOne.whereIs();
Assert.assertTrue(j > i);
}
@Test
public void testParkMoveFindParking() throws Exception {
phaseOne.park();
Assert.assertEquals(true, phaseOne.isParked);
}
@Test
public void testParkStopAtParking() throws Exception {
phaseOne.park();
Assert.assertEquals(phaseOne.whereIs(), phaseOne.carStatus[0]);
Assert.assertEquals(phaseOne.whereIs(), phaseOne.carStatus[0]);
}
@Test
public void testParkAfterMoveBackward() throws Exception {
for(int i = 0; i<501;i++){
phaseOne.moveForward();
}
for(int i = 500; i !=35; i
phaseOne.moveBackward();
}
phaseOne.park();
Assert.assertEquals(true, phaseOne.isParked);
}
/**
* Method: unPark()
*/
@Test
public void testUnPark() throws Exception {
phaseOne.park();
phaseOne.unPark();
Assert.assertEquals(false, phaseOne.isParked);
}
@Test
public void testUnParkMoveForward() throws Exception {
phaseOne.park();
phaseOne.unPark();
int i = phaseOne.whereIs();
phaseOne.moveForward();
Assert.assertNotEquals(i, phaseOne.carStatus[0]);
}
@Test
public void testUnParkMoveBackward() throws Exception {
phaseOne.park();
phaseOne.unPark();
int i = phaseOne.whereIs();
phaseOne.moveBackward();
Assert.assertNotEquals(i, phaseOne.carStatus[0]);
}
@Test
public void testUnParkAt500() {
phaseOne.park();
phaseOne.unPark();
phaseOne.park();
Assert.assertEquals(500,phaseOne.carStatus[0]);
}
@Test
public void testUnParkAt35() {
phaseOne.park();
phaseOne.unPark();
Assert.assertEquals(36,phaseOne.carStatus[0]);
}
/**
* Method: Wherels()
*/
@Test
public void testWhereIs() throws Exception {
Assert.assertEquals(0, phaseOne.whereIs());
Assert.assertThat(phaseOne.whereIs(), instanceOf(Integer.class));
}
/**
* Method: isEmpty()
*/
@Test
public void testIsEmpty() throws Exception {
Assert.assertThat(phaseOne.isEmpty(), instanceOf(Integer.class));
Assert.assertTrue(String.valueOf(phaseOne.isEmpty()), phaseOne.isEmpty() == 1 || phaseOne.isEmpty() == 0);
}
@Test
public void testIsEmptyMoveForwardOnce() throws Exception {
Assert.assertTrue(String.valueOf(phaseOne.isEmpty()), phaseOne.isEmpty() == 1 || phaseOne.isEmpty() == 0);
}
@Test
public void testFinalTest() {
phaseOne.park();
Assert.assertEquals(35, phaseOne.carStatus[0]);
Assert.assertEquals(true, phaseOne.isParked);
phaseOne.unPark();
Assert.assertEquals(36, phaseOne.carStatus[0]);
Assert.assertEquals(false, phaseOne.isParked);
phaseOne.park();
Assert.assertEquals(500, phaseOne.carStatus[0]);
Assert.assertEquals(true, phaseOne.isParked);
phaseOne.unPark();
Assert.assertEquals(500, phaseOne.carStatus[0]);
Assert.assertEquals(false, phaseOne.isParked);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.