lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
apache-2.0
dcae98eb164d2b93925f6d64b00fd4aa3b775e61
0
wuxinshui/boosters
algorithm/src/main/java/org/wuxinshui/boosters/designPatterns/singleton/LazySingletonTest.java
package org.wuxinshui.boosters.designPatterns.singleton; /** * Copyright [2017$] [Wuxinshui] * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Created by wuxinshui on 2017/2/7. */ public class LazySingletonTest { public static void main(String[] args) { new Thread(){ public void run(){ long bg = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { Singleton1.getInstance(); // LazySingleton.getInstance(); } System.out.println("spend:" + (System.currentTimeMillis() - bg)); } }.start(); } }
del test 延迟加载 使用同步关键字:synchronized
algorithm/src/main/java/org/wuxinshui/boosters/designPatterns/singleton/LazySingletonTest.java
del test 延迟加载 使用同步关键字:synchronized
<ide><path>lgorithm/src/main/java/org/wuxinshui/boosters/designPatterns/singleton/LazySingletonTest.java <del>package org.wuxinshui.boosters.designPatterns.singleton; <del> <del>/** <del> * Copyright [2017$] [Wuxinshui] <del> * <p> <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <p> <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <p> <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>/** <del> * Created by wuxinshui on 2017/2/7. <del> */ <del>public class LazySingletonTest { <del> public static void main(String[] args) { <del> new Thread(){ <del> public void run(){ <del> long bg = System.currentTimeMillis(); <del> for (int i = 0; i < 100000; i++) { <del> Singleton1.getInstance(); <del>// LazySingleton.getInstance(); <del> } <del> System.out.println("spend:" + (System.currentTimeMillis() - bg)); <del> } <del> }.start(); <del> } <del>}
Java
apache-2.0
38a9b4ba5bffacc8b46187e6f6515c5aeabe29b6
0
caskdata/tigon,caskdata/tigon,cdapio/tigon,cdapio/tigon,caskdata/tigon,cdapio/tigon,cdapio/tigon,caskdata/tigon,cdapio/tigon,caskdata/tigon,caskdata/tigon,caskdata/tigon,cdapio/tigon,cdapio/tigon,caskdata/tigon,cdapio/tigon
/* * Copyright © 2014 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package co.cask.tigon.flow; import co.cask.tigon.api.flow.Flow; import co.cask.tigon.api.flow.FlowSpecification; import co.cask.tigon.app.program.ManifestFields; import co.cask.tigon.app.program.Program; import co.cask.tigon.app.program.Programs; import co.cask.tigon.conf.CConfiguration; import co.cask.tigon.conf.Constants; import co.cask.tigon.internal.app.FlowSpecificationAdapter; import co.cask.tigon.internal.app.runtime.BasicArguments; import co.cask.tigon.internal.app.runtime.ProgramController; import co.cask.tigon.internal.app.runtime.ProgramRunnerFactory; import co.cask.tigon.internal.app.runtime.SimpleProgramOptions; import co.cask.tigon.internal.flow.DefaultFlowSpecification; import co.cask.tigon.internal.io.ReflectionSchemaGenerator; import co.cask.tigon.lang.ApiResourceListHolder; import co.cask.tigon.lang.ClassLoaders; import co.cask.tigon.lang.jar.ProgramClassLoader; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.io.ByteStreams; import com.google.common.io.Closeables; import com.google.common.io.Files; import com.google.common.io.InputSupplier; import com.google.gson.Gson; import com.google.inject.Inject; import org.apache.twill.filesystem.LocalLocationFactory; import org.apache.twill.filesystem.Location; import org.apache.twill.filesystem.LocationFactory; import org.apache.twill.internal.ApplicationBundler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.Map; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; /** * Client tool for AppFabricHttpHandler. */ public class DeployClient { private static final Logger LOG = LoggerFactory.getLogger(DeployClient.class); private static final Gson GSON = new Gson(); private final LocationFactory locationFactory; private final ProgramRunnerFactory programRunnerFactory; @Inject public DeployClient(CConfiguration cConf, ProgramRunnerFactory programRunnerFactory) { this.locationFactory = new LocalLocationFactory(new File(cConf.get(Constants.CFG_LOCAL_DATA_DIR))); this.programRunnerFactory = programRunnerFactory; } /** * Given a class generates a manifest file with main-class as class. * * @param klass to set as Main-Class in manifest file. * @return An instance {@link java.util.jar.Manifest} */ public static Manifest getManifestWithMainClass(Class<?> klass) { Manifest manifest = new Manifest(); manifest.getMainAttributes().put(ManifestFields.MANIFEST_VERSION, "1.0"); manifest.getMainAttributes().put(ManifestFields.MAIN_CLASS, klass.getName()); return manifest; } /** * Converts a POSIX compliant program argument array to a String-to-String Map. * @param args Array of Strings where each element is a POSIX compliant program argument (Ex: "--os=Linux" ). * @return Map of argument Keys and Values (Ex: Key = "os" and Value = "Linux"). */ public static Map<String, String> fromPosixArray(String[] args) { Map<String, String> kvMap = Maps.newHashMap(); for (String arg : args) { kvMap.putAll(Splitter.on("--").omitEmptyStrings().trimResults().withKeyValueSeparator("=").split(arg)); } return kvMap; } private static void expandJar(File jarPath, File unpackDir) throws Exception { JarFile jar = new JarFile(jarPath); Enumeration enumEntries = jar.entries(); while (enumEntries.hasMoreElements()) { JarEntry file = (JarEntry) enumEntries.nextElement(); File f = new File(unpackDir + File.separator + file.getName()); if (file.isDirectory()) { f.mkdirs(); continue; } else { f.getParentFile().mkdirs(); } InputStream is = jar.getInputStream(file); try { ByteStreams.copy(is, Files.newOutputStreamSupplier(f)); } finally { Closeables.closeQuietly(is); } } } public Program createProgram(File jarPath, String classToLoad, File jarUnpackDir) throws Exception { expandJar(jarPath, jarUnpackDir); ProgramClassLoader classLoader = ClassLoaders.newProgramClassLoader(jarUnpackDir, ApiResourceListHolder.getResourceList()); Class<?> clz = classLoader.loadClass(classToLoad); if (!(clz.newInstance() instanceof Flow)) { throw new Exception("Expected Flow class"); } ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(classLoader); Location deployJar = jarForTestBase(clz); LOG.info("Deploy Jar location : {}", deployJar.toURI()); try { return Programs.create(deployJar, classLoader); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } public ProgramController startFlow(Program program, Map<String, String> userArgs) throws Exception { return programRunnerFactory.create(ProgramRunnerFactory.Type.FLOW).run( program, new SimpleProgramOptions(program.getName(), new BasicArguments(), new BasicArguments(userArgs))); } public ProgramController startFlow(File jarPath, String classToLoad, File jarUnpackDir, Map<String, String> userArgs) throws Exception { Program program = createProgram(jarPath, classToLoad, jarUnpackDir); return programRunnerFactory.create(ProgramRunnerFactory.Type.FLOW).run( program, new SimpleProgramOptions(program.getName(), new BasicArguments(), new BasicArguments(userArgs))); } public Location jarForTestBase(Class<?> flowClz, File... bundleEmbeddedJars) throws Exception { return jarForTestBase(flowClz, ImmutableList.<Class<?>>of(), bundleEmbeddedJars); } public Location jarForTestBase(Class<?> flowClz, Iterable<Class<?>> classes, File... bundleEmbeddedJars) throws Exception { Preconditions.checkNotNull(flowClz, "Flow cannot be null."); Location deployedJar = locationFactory.create(createDeploymentJar( locationFactory, flowClz, classes, bundleEmbeddedJars).toURI()); LOG.info("Created deployedJar at {}", deployedJar.toURI().toASCIIString()); return deployedJar; } private static InputSupplier<InputStream> getInputSupplier(final FlowSpecification flowSpec) { return new InputSupplier<InputStream>() { @Override public InputStream getInput() throws IOException { String json = FlowSpecificationAdapter.create(new ReflectionSchemaGenerator()).toJson(flowSpec); return new ByteArrayInputStream(json.getBytes(Charsets.UTF_8)); } }; } private static File createDeploymentJar(LocationFactory locationFactory, Class<?> clz, Iterable<Class<?>> classes, File...bundleEmbeddedJars) throws IOException, InstantiationException, IllegalAccessException { ApplicationBundler bundler = new ApplicationBundler(ImmutableList.of("co.cask.tigon.api", "org.apache.hadoop", "org.apache.hbase")); Location jarLocation = locationFactory.create(clz.getName()).getTempFile(".jar"); bundler.createBundle(jarLocation, ImmutableSet.<Class<?>>builder().add(clz).addAll(classes).build()); Location deployJar = locationFactory.create(clz.getName()).getTempFile(".jar"); Flow flow = (Flow) clz.newInstance(); FlowSpecification flowSpec = new DefaultFlowSpecification(clz.getClass().getName(), flow.configure()); // Creates Manifest Manifest manifest = new Manifest(); manifest.getMainAttributes().put(ManifestFields.MANIFEST_VERSION, "1.0"); manifest.getMainAttributes().put(ManifestFields.MAIN_CLASS, clz.getName()); manifest.getMainAttributes().put(ManifestFields.SPEC_FILE, ManifestFields.MANIFEST_SPEC_FILE); // Create the program jar for deployment. It removes the "classes/" prefix as that's the convention taken // by the ApplicationBundler inside Twill. JarOutputStream jarOutput = new JarOutputStream(deployJar.getOutputStream(), manifest); try { JarInputStream jarInput = new JarInputStream(jarLocation.getInputStream()); try { JarEntry jarEntry = jarInput.getNextJarEntry(); Set<String> entriesAdded = Sets.newHashSet(); while (jarEntry != null) { boolean isDir = jarEntry.isDirectory(); String entryName = jarEntry.getName(); if (!entryName.equals("classes/") && !entryName.endsWith("META-INF/MANIFEST.MF") && !entriesAdded.contains(entryName)) { if (entryName.startsWith("classes/")) { jarEntry = new JarEntry(entryName.substring("classes/".length())); } else { jarEntry = new JarEntry(entryName); } jarOutput.putNextEntry(jarEntry); entriesAdded.add(jarEntry.getName()); if (!isDir) { ByteStreams.copy(jarInput, jarOutput); } } jarEntry = jarInput.getNextJarEntry(); } } finally { jarInput.close(); } for (File embeddedJar : bundleEmbeddedJars) { JarEntry jarEntry = new JarEntry("lib/" + embeddedJar.getName()); jarOutput.putNextEntry(jarEntry); Files.copy(embeddedJar, jarOutput); } JarEntry jarEntry = new JarEntry(ManifestFields.MANIFEST_SPEC_FILE); jarOutput.putNextEntry(jarEntry); ByteStreams.copy(getInputSupplier(flowSpec), jarOutput); } finally { jarOutput.close(); } return new File(deployJar.toURI()); } private static File createDeploymentJar(LocationFactory locationFactory, Class<?> clz, File...bundleEmbeddedJars) throws IOException, InstantiationException, IllegalAccessException { return createDeploymentJar(locationFactory, clz, ImmutableList.<Class<?>>of(), bundleEmbeddedJars); } }
tigon-flow/src/main/java/co/cask/tigon/flow/DeployClient.java
/* * Copyright © 2014 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package co.cask.tigon.flow; import co.cask.tigon.api.flow.Flow; import co.cask.tigon.api.flow.FlowSpecification; import co.cask.tigon.app.program.ManifestFields; import co.cask.tigon.app.program.Program; import co.cask.tigon.app.program.Programs; import co.cask.tigon.conf.CConfiguration; import co.cask.tigon.conf.Constants; import co.cask.tigon.internal.app.FlowSpecificationAdapter; import co.cask.tigon.internal.app.runtime.BasicArguments; import co.cask.tigon.internal.app.runtime.ProgramController; import co.cask.tigon.internal.app.runtime.ProgramRunnerFactory; import co.cask.tigon.internal.app.runtime.SimpleProgramOptions; import co.cask.tigon.internal.flow.DefaultFlowSpecification; import co.cask.tigon.internal.io.ReflectionSchemaGenerator; import co.cask.tigon.lang.ApiResourceListHolder; import co.cask.tigon.lang.ClassLoaders; import co.cask.tigon.lang.jar.ProgramClassLoader; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.io.ByteStreams; import com.google.common.io.Closeables; import com.google.common.io.Files; import com.google.common.io.InputSupplier; import com.google.gson.Gson; import com.google.inject.Inject; import org.apache.twill.filesystem.LocalLocationFactory; import org.apache.twill.filesystem.Location; import org.apache.twill.filesystem.LocationFactory; import org.apache.twill.internal.ApplicationBundler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.Map; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; /** * Client tool for AppFabricHttpHandler. */ public class DeployClient { private static final Logger LOG = LoggerFactory.getLogger(DeployClient.class); private static final Gson GSON = new Gson(); private final LocationFactory locationFactory; private final ProgramRunnerFactory programRunnerFactory; @Inject public DeployClient(CConfiguration cConf, ProgramRunnerFactory programRunnerFactory) { this.locationFactory = new LocalLocationFactory(new File(cConf.get(Constants.CFG_LOCAL_DATA_DIR))); this.programRunnerFactory = programRunnerFactory; } /** * Given a class generates a manifest file with main-class as class. * * @param klass to set as Main-Class in manifest file. * @return An instance {@link java.util.jar.Manifest} */ public static Manifest getManifestWithMainClass(Class<?> klass) { Manifest manifest = new Manifest(); manifest.getMainAttributes().put(ManifestFields.MANIFEST_VERSION, "1.0"); manifest.getMainAttributes().put(ManifestFields.MAIN_CLASS, klass.getName()); return manifest; } /** * Converts a POSIX compliant program argument array to a String-to-String Map. * @param args Array of Strings where each element is a POSIX compliant program argument (Ex: "--os=Linux" ). * @return Map of argument Keys and Values (Ex: Key = "os" and Value = "Linux"). */ public static Map<String, String> fromPosixArray(String[] args) { Map<String, String> kvMap = Maps.newHashMap(); for (String arg : args) { kvMap.putAll(Splitter.on("--").omitEmptyStrings().trimResults().withKeyValueSeparator("=").split(arg)); } return kvMap; } private static void expandJar(File jarPath, File unpackDir) throws Exception { JarFile jar = new JarFile(jarPath); Enumeration enumEntries = jar.entries(); while (enumEntries.hasMoreElements()) { JarEntry file = (JarEntry) enumEntries.nextElement(); File f = new File(unpackDir + File.separator + file.getName()); if (file.isDirectory()) { f.mkdirs(); continue; } else { f.getParentFile().mkdirs(); } InputStream is = jar.getInputStream(file); try { ByteStreams.copy(is, Files.newOutputStreamSupplier(f)); } finally { Closeables.closeQuietly(is); } } } public Program createProgram(File jarPath, String classToLoad, File jarUnpackDir) throws Exception { expandJar(jarPath, jarUnpackDir); ProgramClassLoader classLoader = ClassLoaders.newProgramClassLoader(jarUnpackDir, ApiResourceListHolder.getResourceList()); Class<?> clz = classLoader.loadClass(classToLoad); if (!(clz.newInstance() instanceof Flow)) { throw new Exception("Expected Flow class"); } ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(classLoader); Location deployJar = jarForTestBase(clz); LOG.info("Deloy Jar location : {}", deployJar.toURI()); try { return Programs.create(deployJar, classLoader); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } public ProgramController startFlow(Program program, Map<String, String> userArgs) throws Exception { return programRunnerFactory.create(ProgramRunnerFactory.Type.FLOW).run( program, new SimpleProgramOptions(program.getName(), new BasicArguments(), new BasicArguments(userArgs))); } public ProgramController startFlow(File jarPath, String classToLoad, File jarUnpackDir, Map<String, String> userArgs) throws Exception { Program program = createProgram(jarPath, classToLoad, jarUnpackDir); return programRunnerFactory.create(ProgramRunnerFactory.Type.FLOW).run( program, new SimpleProgramOptions(program.getName(), new BasicArguments(), new BasicArguments(userArgs))); } public Location jarForTestBase(Class<?> flowClz, File... bundleEmbeddedJars) throws Exception { return jarForTestBase(flowClz, ImmutableList.<Class<?>>of(), bundleEmbeddedJars); } public Location jarForTestBase(Class<?> flowClz, Iterable<Class<?>> classes, File... bundleEmbeddedJars) throws Exception { Preconditions.checkNotNull(flowClz, "Flow cannot be null."); Location deployedJar = locationFactory.create(createDeploymentJar( locationFactory, flowClz, classes, bundleEmbeddedJars).toURI()); LOG.info("Created deployedJar at {}", deployedJar.toURI().toASCIIString()); return deployedJar; } private static InputSupplier<InputStream> getInputSupplier(final FlowSpecification flowSpec) { return new InputSupplier<InputStream>() { @Override public InputStream getInput() throws IOException { String json = FlowSpecificationAdapter.create(new ReflectionSchemaGenerator()).toJson(flowSpec); return new ByteArrayInputStream(json.getBytes(Charsets.UTF_8)); } }; } private static File createDeploymentJar(LocationFactory locationFactory, Class<?> clz, Iterable<Class<?>> classes, File...bundleEmbeddedJars) throws IOException, InstantiationException, IllegalAccessException { ApplicationBundler bundler = new ApplicationBundler(ImmutableList.of("co.cask.tigon.api", "org.apache.hadoop", "org.apache.hbase")); Location jarLocation = locationFactory.create(clz.getName()).getTempFile(".jar"); bundler.createBundle(jarLocation, ImmutableSet.<Class<?>>builder().add(clz).addAll(classes).build()); Location deployJar = locationFactory.create(clz.getName()).getTempFile(".jar"); Flow flow = (Flow) clz.newInstance(); FlowSpecification flowSpec = new DefaultFlowSpecification(clz.getClass().getName(), flow.configure()); // Creates Manifest Manifest manifest = new Manifest(); manifest.getMainAttributes().put(ManifestFields.MANIFEST_VERSION, "1.0"); manifest.getMainAttributes().put(ManifestFields.MAIN_CLASS, clz.getName()); manifest.getMainAttributes().put(ManifestFields.SPEC_FILE, ManifestFields.MANIFEST_SPEC_FILE); // Create the program jar for deployment. It removes the "classes/" prefix as that's the convention taken // by the ApplicationBundler inside Twill. JarOutputStream jarOutput = new JarOutputStream(deployJar.getOutputStream(), manifest); try { JarInputStream jarInput = new JarInputStream(jarLocation.getInputStream()); try { JarEntry jarEntry = jarInput.getNextJarEntry(); Set<String> entriesAdded = Sets.newHashSet(); while (jarEntry != null) { boolean isDir = jarEntry.isDirectory(); String entryName = jarEntry.getName(); if (!entryName.equals("classes/") && !entryName.endsWith("META-INF/MANIFEST.MF") && !entriesAdded.contains(entryName)) { if (entryName.startsWith("classes/")) { jarEntry = new JarEntry(entryName.substring("classes/".length())); } else { jarEntry = new JarEntry(entryName); } jarOutput.putNextEntry(jarEntry); entriesAdded.add(jarEntry.getName()); if (!isDir) { ByteStreams.copy(jarInput, jarOutput); } } jarEntry = jarInput.getNextJarEntry(); } } finally { jarInput.close(); } for (File embeddedJar : bundleEmbeddedJars) { JarEntry jarEntry = new JarEntry("lib/" + embeddedJar.getName()); jarOutput.putNextEntry(jarEntry); Files.copy(embeddedJar, jarOutput); } JarEntry jarEntry = new JarEntry(ManifestFields.MANIFEST_SPEC_FILE); jarOutput.putNextEntry(jarEntry); ByteStreams.copy(getInputSupplier(flowSpec), jarOutput); } finally { jarOutput.close(); } return new File(deployJar.toURI()); } private static File createDeploymentJar(LocationFactory locationFactory, Class<?> clz, File...bundleEmbeddedJars) throws IOException, InstantiationException, IllegalAccessException { return createDeploymentJar(locationFactory, clz, ImmutableList.<Class<?>>of(), bundleEmbeddedJars); } }
Changed Deloy to Deploy
tigon-flow/src/main/java/co/cask/tigon/flow/DeployClient.java
Changed Deloy to Deploy
<ide><path>igon-flow/src/main/java/co/cask/tigon/flow/DeployClient.java <ide> ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); <ide> Thread.currentThread().setContextClassLoader(classLoader); <ide> Location deployJar = jarForTestBase(clz); <del> LOG.info("Deloy Jar location : {}", deployJar.toURI()); <add> LOG.info("Deploy Jar location : {}", deployJar.toURI()); <ide> try { <ide> return Programs.create(deployJar, classLoader); <ide> } finally {
Java
apache-2.0
49188c61846de488c3f8b6fe303f550d826e1d6e
0
janstey/mvn-plugins,fusesource/mvnplugins,jacekszymanski/mvnplugins,theHilikus/mvnplugins,KlausBrunner/mvnplugins
package org.fusesource.mvnplugins.updatesite; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.commons.lang.StringUtils; import org.apache.maven.artifact.manager.WagonConfigurationException; import org.apache.maven.artifact.manager.WagonManager; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import org.apache.maven.settings.Server; import org.apache.maven.settings.Settings; import org.apache.maven.wagon.CommandExecutor; import org.apache.maven.wagon.ConnectionException; import org.apache.maven.wagon.UnsupportedProtocolException; import org.apache.maven.wagon.Wagon; import org.apache.maven.wagon.observers.Debug; import org.apache.maven.wagon.proxy.ProxyInfo; import org.apache.maven.wagon.repository.Repository; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ComponentConfigurator; import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; import org.codehaus.plexus.context.Context; import org.codehaus.plexus.context.ContextException; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable; import org.codehaus.plexus.util.xml.Xpp3Dom; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; /** * Deploys an Eclipse update site using <code>scp</code> or <code>file</code> * protocol to the site URL specified in the * <code>remoteServerId</code> and <code>remoteServerUrl</code> values in the * <code>&lt;configuration&gt;</code> of this plugin. * <p> * For <code>scp</code> protocol, the website files are packaged into zip archive, * then the archive is transfered to the remote host, next it is un-archived. * This method of deployment should normally be much faster * than making a file by file copy. For <code>file</code> protocol, the files are copied * directly to the destination directory. * </p> * * @author <a href="mailto:[email protected]">Michal Maczka</a> * @phase("deploy") * @goal deploy */ public class UpdateSiteDeployMojo extends AbstractMojo implements Contextualizable { /** * Directory containing the generated site. * * @parameter alias="outputDirectory" expression="${project.build.directory}/site" * @required */ private File inputDirectory; /** * Name of the generated .htaccess file to use * * @parameter alias="outputDirectory" expression="${project.build.directory}/updateSiteHtaccess" * @required */ private String htaccessFileName; /** * Whether to generate a new update site for each build using a date/time postfix. * Defaults to "true". * * @parameter expression="${maven.updatesite.timestampDirectory}" default-value="true" */ private boolean timestampDirectory; /** * Whether to generate a <code>.htaccess</code> file if using timestampDirectory mode * * @parameter expression="${maven.updatesite.generateHtaccess}" default-value="true" */ private boolean generateHtaccess; /** * The name of the remote <code>.htaccess</code> file if using timestampDirectory mode. * * Defaults to ".htaccess". * * If your webdav provider won't let you upload files called ".htaccess" then you could * configure this property to be something like "tmp.htacces" then you could later on rename the file * using a cron job or something. * * @parameter expression="${maven.updatesite.remotehtAccessFile}" default-value=".htaccess" */ private String remotehtAccessFile; /** * Whether to run the "chmod" command on the remote site after the deploy. * Defaults to "true". * * @parameter expression="${maven.updatesite.chmod}" default-value="true" * @since 2.1 */ private boolean chmod; /** * The mode used by the "chmod" command. Only used if chmod = true. * Defaults to "g+w,a+rX". * * @parameter expression="${maven.updatesite.chmod.mode}" default-value="g+w,a+rX" * @since 2.1 */ private String chmodMode; /** * The Server ID used to deploy the site which should reference a &lt;server&gt; in your * ~/.m2/settings.xml file for username/pwd * * @parameter expression="${updatesite.remoteServerId}" */ private String remoteServerId; /** * The Server Server URL to deploy the site to which uses the same URL format as the * distributionManagement / site / url expression in the pom.xml * * @parameter expression="${updatesite.remoteServerUrl}" */ private String remoteServerUrl; /** * The directory used to put the update site in. Defaults to "update". * * If you use the htacess generation then this directory is used as part of the redirects * * @parameter default-value="update" */ private String remoteDirectory; /** * The options used by the "chmod" command. Only used if chmod = true. * Defaults to "-Rf". * * @parameter expression="${maven.updatesite.chmod.options}" default-value="-Rf" * @since 2.1 */ private String chmodOptions; /** * The options used by the "mv" command to move the current update site out of the way * Defaults to "". * * @parameter expression="${maven.updatesite.mv.options}" default-value="" * @since 2.1 */ private String mvOptions; /** * The date format to use for old build directories * * @parameter expression="${maven.updatesite.oldBuild.dateFormat}" default-value="yyyy-MM-dd-HH-mm-ss-SSS" */ private String oldBuildDateFormat = "yyyy-MM-dd-HH-mm-ss-SSS"; /** * @parameter expression="${project}" * @required * @readonly */ private MavenProject project; /** * @component */ private WagonManager wagonManager; /** * The current user system settings for use in Maven. * * @parameter expression="${settings}" * @required * @readonly */ private Settings settings; private PlexusContainer container; /** * {@inheritDoc} */ public void execute() throws MojoExecutionException { if (!inputDirectory.exists()) { throw new MojoExecutionException("The site does not exist, please run site:site first"); } String url = remoteServerUrl; String id = remoteServerId; if (id == null) { throw new MojoExecutionException("The remoteServerId is missing in the plugin configuration."); } if (url == null) { throw new MojoExecutionException("The remoteServerUrl is missing in the plugin configuration."); } getLog().debug("The site will be deployed to '" + url + "' with id '" + id + "'"); Repository repository = new Repository(id, url); // TODO: work on moving this into the deployer like the other deploy methods Wagon wagon; try { wagon = wagonManager.getWagon(repository); configureWagon(wagon, repository.getId(), settings, container, getLog()); } catch (UnsupportedProtocolException e) { throw new MojoExecutionException("Unsupported protocol: '" + repository.getProtocol() + "'", e); } catch (WagonConfigurationException e) { throw new MojoExecutionException("Unable to configure Wagon: '" + repository.getProtocol() + "'", e); } if (!wagon.supportsDirectoryCopy()) { throw new MojoExecutionException( "Wagon protocol '" + repository.getProtocol() + "' doesn't support directory copying"); } try { Debug debug = new Debug(); wagon.addSessionListener(debug); wagon.addTransferListener(debug); ProxyInfo proxyInfo = getProxyInfo(repository, wagonManager); if (proxyInfo != null) { wagon.connect(repository, wagonManager.getAuthenticationInfo(id), proxyInfo); } else { wagon.connect(repository, wagonManager.getAuthenticationInfo(id)); } SimpleDateFormat format = new SimpleDateFormat(oldBuildDateFormat); String postfix = "-" + format.format(new Date()); if (wagon instanceof CommandExecutor) { CommandExecutor exec = (CommandExecutor) wagon; String repositoryBasedir = repository.getBasedir(); // lets move the old directory first before we push... String newDir = repositoryBasedir + postfix; getLog().info("Moving the current update site to: " + newDir); if (mvOptions == null) { mvOptions = ""; } exec.executeCommand("mv " + mvOptions + " " + repositoryBasedir + " " + newDir); wagon.putDirectory(inputDirectory, remoteDirectory); if (chmod) { exec.executeCommand("chmod " + chmodOptions + " " + chmodMode + " " + repositoryBasedir); } } else { if (timestampDirectory) { String updateSiteDirectory = remoteDirectory + postfix; if (generateHtaccess) { PrintWriter out = new PrintWriter(new FileWriter(htaccessFileName)); out.println("RewriteEngine on"); out.println(); /* String[] paths = remoteDirectory.split("/"); int idx = paths.length - 1; String dirName = paths[idx]; while ((dirName == "" || dirName == null) && --idx >= 0) { dirName = paths[idx]; } if (dirName == "" || dirName == null) { getLog().warn("Could not deduce the last directory name ") dirName = "update"; } */ out.println("RewriteRule " + remoteDirectory + "/(.*) " + remoteDirectory + postfix + "/$1"); out.close(); getLog().info("Created .htaccess file " + htaccessFileName + " which will be uploaded to: " + remotehtAccessFile + " on completion"); } wagon.putDirectory(inputDirectory, updateSiteDirectory); if (generateHtaccess) { getLog().info("Uploading .htaccess file " + htaccessFileName + " to: " + remotehtAccessFile); File htAccessFile = new File(htaccessFileName); wagon.put(htAccessFile, remotehtAccessFile); } } else { wagon.putDirectory(inputDirectory, remoteDirectory); } } } catch (Exception e) { throw new MojoExecutionException("Error uploading site", e); } finally { try { wagon.disconnect(); } catch (ConnectionException e) { getLog().error("Error disconnecting wagon - ignored", e); } } } /** * <p> * Get the <code>ProxyInfo</code> of the proxy associated with the <code>host</code> * and the <code>protocol</code> of the given <code>repository</code>. * </p> * <p> * Extract from <a href="http://java.sun.com/j2se/1.5.0/docs/guide/net/properties.html"> * J2SE Doc : Networking Properties - nonProxyHosts</a> : "The value can be a list of hosts, * each separated by a |, and in addition a wildcard character (*) can be used for matching" * </p> * <p> * Defensively support for comma (",") and semi colon (";") in addition to pipe ("|") as separator. * </p> * * @param repository the Repository to extract the ProxyInfo from. * @param wagonManager the WagonManager used to connect to the Repository. * @return a ProxyInfo object instantiated or <code>null</code> if no matching proxy is found */ public static ProxyInfo getProxyInfo(Repository repository, WagonManager wagonManager) { ProxyInfo proxyInfo = wagonManager.getProxy(repository.getProtocol()); if (proxyInfo == null) { return null; } String host = repository.getHost(); String nonProxyHostsAsString = proxyInfo.getNonProxyHosts(); String[] nonProxyHosts = StringUtils.split(nonProxyHostsAsString, ",;|"); for (int i = 0; i < nonProxyHosts.length; i++) { String nonProxyHost = nonProxyHosts[i]; if (StringUtils.contains(nonProxyHost, "*")) { // Handle wildcard at the end, beginning or middle of the nonProxyHost String nonProxyHostPrefix = StringUtils.substringBefore(nonProxyHost, "*"); String nonProxyHostSuffix = StringUtils.substringAfter(nonProxyHost, "*"); // prefix* if (StringUtils.isNotEmpty(nonProxyHostPrefix) && host.startsWith(nonProxyHostPrefix) && StringUtils.isEmpty(nonProxyHostSuffix)) { return null; } // *suffix if (StringUtils.isEmpty(nonProxyHostPrefix) && StringUtils.isNotEmpty(nonProxyHostSuffix) && host.endsWith(nonProxyHostSuffix)) { return null; } // prefix*suffix if (StringUtils.isNotEmpty(nonProxyHostPrefix) && host.startsWith(nonProxyHostPrefix) && StringUtils.isNotEmpty(nonProxyHostSuffix) && host.endsWith(nonProxyHostSuffix)) { return null; } } else if (host.equals(nonProxyHost)) { return null; } } return proxyInfo; } /** * Configure the Wagon with the information from serverConfigurationMap ( which comes from settings.xml ) * * @param wagon * @param repositoryId * @param settings * @param container * @param log * @throws WagonConfigurationException * @todo Remove when {@link WagonManager#getWagon(Repository) is available}. It's available in Maven 2.0.5. */ static void configureWagon(Wagon wagon, String repositoryId, Settings settings, PlexusContainer container, Log log) throws WagonConfigurationException { // MSITE-25: Make sure that the server settings are inserted for (int i = 0; i < settings.getServers().size(); i++) { Server server = (Server) settings.getServers().get(i); String id = server.getId(); if (id != null && id.equals(repositoryId)) { if (server.getConfiguration() != null) { final PlexusConfiguration plexusConf = new XmlPlexusConfiguration((Xpp3Dom) server.getConfiguration()); ComponentConfigurator componentConfigurator = null; try { componentConfigurator = (ComponentConfigurator) container.lookup(ComponentConfigurator.ROLE); componentConfigurator.configureComponent(wagon, plexusConf, container.getContainerRealm()); } catch (final ComponentLookupException e) { throw new WagonConfigurationException(repositoryId, "Unable to lookup wagon configurator." + " Wagon configuration cannot be applied.", e); } catch (ComponentConfigurationException e) { throw new WagonConfigurationException(repositoryId, "Unable to apply wagon configuration.", e); } finally { if (componentConfigurator != null) { try { container.release(componentConfigurator); } catch (ComponentLifecycleException e) { log.error("Problem releasing configurator - ignoring: " + e.getMessage()); } } } } } } } public void contextualize(Context context) throws ContextException { container = (PlexusContainer) context.get(PlexusConstants.PLEXUS_KEY); } }
maven-updatesite-plugin/src/main/java/org/fusesource/mvnplugins/updatesite/UpdateSiteDeployMojo.java
package org.fusesource.mvnplugins.updatesite; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.commons.lang.StringUtils; import org.apache.maven.artifact.manager.WagonConfigurationException; import org.apache.maven.artifact.manager.WagonManager; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import org.apache.maven.settings.Server; import org.apache.maven.settings.Settings; import org.apache.maven.wagon.CommandExecutor; import org.apache.maven.wagon.ConnectionException; import org.apache.maven.wagon.UnsupportedProtocolException; import org.apache.maven.wagon.Wagon; import org.apache.maven.wagon.observers.Debug; import org.apache.maven.wagon.proxy.ProxyInfo; import org.apache.maven.wagon.repository.Repository; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ComponentConfigurator; import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; import org.codehaus.plexus.context.Context; import org.codehaus.plexus.context.ContextException; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable; import org.codehaus.plexus.util.xml.Xpp3Dom; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; /** * Deploys an Eclipse update site using <code>scp</code> or <code>file</code> * protocol to the site URL specified in the * <code>remoteServerId</code> and <code>remoteServerUrl</code> values in the * <code>&lt;configuration&gt;</code> of this plugin. * <p> * For <code>scp</code> protocol, the website files are packaged into zip archive, * then the archive is transfered to the remote host, next it is un-archived. * This method of deployment should normally be much faster * than making a file by file copy. For <code>file</code> protocol, the files are copied * directly to the destination directory. * </p> * * @author <a href="mailto:[email protected]">Michal Maczka</a> * @phase("deploy") * @goal deploy */ public class UpdateSiteDeployMojo extends AbstractMojo implements Contextualizable { /** * Directory containing the generated site. * * @parameter alias="outputDirectory" expression="${project.build.directory}/site" * @required */ private File inputDirectory; /** * Name of the generated .htaccess file to use * * @parameter alias="outputDirectory" expression="${project.build.directory}/updateSiteHtaccess" * @required */ private String htaccessFileName; /** * Whether to generate a new update site for each build using a date/time postfix. * Defaults to "true". * * @parameter expression="${maven.updatesite.timestampDirectory}" default-value="true" */ private boolean timestampDirectory; /** * Whether to generate a <code>.htaccess</code> file if using timestampDirectory mode * * @parameter expression="${maven.updatesite.generateHtaccess}" default-value="true" */ private boolean generateHtaccess; /** * The name of the remote <code>.htaccess</code> file if using timestampDirectory mode. * * Defaults to ".htaccess". * * If your webdav provider won't let you upload files called ".htaccess" then you could * configure this property to be something like "tmp.htacces" then you could later on rename the file * using a cron job or something. * * @parameter expression="${maven.updatesite.remotehtAccessFile}" default-value=".htaccess" */ private String remotehtAccessFile; /** * Whether to run the "chmod" command on the remote site after the deploy. * Defaults to "true". * * @parameter expression="${maven.updatesite.chmod}" default-value="true" * @since 2.1 */ private boolean chmod; /** * The mode used by the "chmod" command. Only used if chmod = true. * Defaults to "g+w,a+rX". * * @parameter expression="${maven.updatesite.chmod.mode}" default-value="g+w,a+rX" * @since 2.1 */ private String chmodMode; /** * The Server ID used to deploy the site which should reference a &lt;server&gt; in your * ~/.m2/settings.xml file for username/pwd * * @parameter expression="${updatesite.remoteServerId}" */ private String remoteServerId; /** * The Server Server URL to deploy the site to which uses the same URL format as the * distributionManagement / site / url expression in the pom.xml * * @parameter expression="${updatesite.remoteServerUrl}" */ private String remoteServerUrl; /** * The directory used to put the update site in. Defaults to "update". * * If you use the htacess generation then this directory is used as part of the redirects * * @parameter default-value="update" */ private String remoteDirectory; /** * The options used by the "chmod" command. Only used if chmod = true. * Defaults to "-Rf". * * @parameter expression="${maven.updatesite.chmod.options}" default-value="-Rf" * @since 2.1 */ private String chmodOptions; /** * The options used by the "mv" command to move the current update site out of the way * Defaults to "". * * @parameter expression="${maven.updatesite.mv.options}" default-value="" * @since 2.1 */ private String mvOptions; /** * The date format to use for old build directories * * @parameter expression="${maven.updatesite.oldBuild.dateFormat}" default-value="yyyy-MM-dd-HH-mm-ss-SSS" */ private String oldBuildDateFormat = "yyyy-MM-dd-HH-mm-ss-SSS"; /** * @parameter expression="${project}" * @required * @readonly */ private MavenProject project; /** * @component */ private WagonManager wagonManager; /** * The current user system settings for use in Maven. * * @parameter expression="${settings}" * @required * @readonly */ private Settings settings; private PlexusContainer container; /** * {@inheritDoc} */ public void execute() throws MojoExecutionException { if (!inputDirectory.exists()) { throw new MojoExecutionException("The site does not exist, please run site:site first"); } String url = remoteServerUrl; String id = remoteServerId; if (id == null) { throw new MojoExecutionException("The remoteServerId is missing in the plugin configuration."); } if (url == null) { throw new MojoExecutionException("The remoteServerUrl is missing in the plugin configuration."); } getLog().debug("The site will be deployed to '" + url + "' with id '" + id + "'"); Repository repository = new Repository(id, url); // TODO: work on moving this into the deployer like the other deploy methods Wagon wagon; try { wagon = wagonManager.getWagon(repository); configureWagon(wagon, repository.getId(), settings, container, getLog()); } catch (UnsupportedProtocolException e) { throw new MojoExecutionException("Unsupported protocol: '" + repository.getProtocol() + "'", e); } catch (WagonConfigurationException e) { throw new MojoExecutionException("Unable to configure Wagon: '" + repository.getProtocol() + "'", e); } if (!wagon.supportsDirectoryCopy()) { throw new MojoExecutionException( "Wagon protocol '" + repository.getProtocol() + "' doesn't support directory copying"); } try { Debug debug = new Debug(); wagon.addSessionListener(debug); wagon.addTransferListener(debug); ProxyInfo proxyInfo = getProxyInfo(repository, wagonManager); if (proxyInfo != null) { wagon.connect(repository, wagonManager.getAuthenticationInfo(id), proxyInfo); } else { wagon.connect(repository, wagonManager.getAuthenticationInfo(id)); } SimpleDateFormat format = new SimpleDateFormat(oldBuildDateFormat); String postfix = "-" + format.format(new Date()); if (wagon instanceof CommandExecutor) { CommandExecutor exec = (CommandExecutor) wagon; String repositoryBasedir = repository.getBasedir(); // lets move the old directory first before we push... String newDir = repositoryBasedir + postfix; getLog().info("Moving the current update site to: " + newDir); exec.executeCommand("mv " + mvOptions + " " + repositoryBasedir + " " + newDir); wagon.putDirectory(inputDirectory, remoteDirectory); if (chmod) { exec.executeCommand("chmod " + chmodOptions + " " + chmodMode + " " + repositoryBasedir); } } else { if (timestampDirectory) { String updateSiteDirectory = remoteDirectory + postfix; if (generateHtaccess) { PrintWriter out = new PrintWriter(new FileWriter(htaccessFileName)); out.println("RewriteEngine on"); out.println(); /* String[] paths = remoteDirectory.split("/"); int idx = paths.length - 1; String dirName = paths[idx]; while ((dirName == "" || dirName == null) && --idx >= 0) { dirName = paths[idx]; } if (dirName == "" || dirName == null) { getLog().warn("Could not deduce the last directory name ") dirName = "update"; } */ out.println("RewriteRule " + remoteDirectory + "/(.*) " + remoteDirectory + postfix + "/$1"); out.close(); getLog().info("Created .htaccess file " + htaccessFileName + " which will be uploaded to: " + remotehtAccessFile + " on completion"); } wagon.putDirectory(inputDirectory, updateSiteDirectory); if (generateHtaccess) { getLog().info("Uploading .htaccess file " + htaccessFileName + " to: " + remotehtAccessFile); File htAccessFile = new File(htaccessFileName); wagon.put(htAccessFile, remotehtAccessFile); } } else { wagon.putDirectory(inputDirectory, remoteDirectory); } } } catch (Exception e) { throw new MojoExecutionException("Error uploading site", e); } finally { try { wagon.disconnect(); } catch (ConnectionException e) { getLog().error("Error disconnecting wagon - ignored", e); } } } /** * <p> * Get the <code>ProxyInfo</code> of the proxy associated with the <code>host</code> * and the <code>protocol</code> of the given <code>repository</code>. * </p> * <p> * Extract from <a href="http://java.sun.com/j2se/1.5.0/docs/guide/net/properties.html"> * J2SE Doc : Networking Properties - nonProxyHosts</a> : "The value can be a list of hosts, * each separated by a |, and in addition a wildcard character (*) can be used for matching" * </p> * <p> * Defensively support for comma (",") and semi colon (";") in addition to pipe ("|") as separator. * </p> * * @param repository the Repository to extract the ProxyInfo from. * @param wagonManager the WagonManager used to connect to the Repository. * @return a ProxyInfo object instantiated or <code>null</code> if no matching proxy is found */ public static ProxyInfo getProxyInfo(Repository repository, WagonManager wagonManager) { ProxyInfo proxyInfo = wagonManager.getProxy(repository.getProtocol()); if (proxyInfo == null) { return null; } String host = repository.getHost(); String nonProxyHostsAsString = proxyInfo.getNonProxyHosts(); String[] nonProxyHosts = StringUtils.split(nonProxyHostsAsString, ",;|"); for (int i = 0; i < nonProxyHosts.length; i++) { String nonProxyHost = nonProxyHosts[i]; if (StringUtils.contains(nonProxyHost, "*")) { // Handle wildcard at the end, beginning or middle of the nonProxyHost String nonProxyHostPrefix = StringUtils.substringBefore(nonProxyHost, "*"); String nonProxyHostSuffix = StringUtils.substringAfter(nonProxyHost, "*"); // prefix* if (StringUtils.isNotEmpty(nonProxyHostPrefix) && host.startsWith(nonProxyHostPrefix) && StringUtils.isEmpty(nonProxyHostSuffix)) { return null; } // *suffix if (StringUtils.isEmpty(nonProxyHostPrefix) && StringUtils.isNotEmpty(nonProxyHostSuffix) && host.endsWith(nonProxyHostSuffix)) { return null; } // prefix*suffix if (StringUtils.isNotEmpty(nonProxyHostPrefix) && host.startsWith(nonProxyHostPrefix) && StringUtils.isNotEmpty(nonProxyHostSuffix) && host.endsWith(nonProxyHostSuffix)) { return null; } } else if (host.equals(nonProxyHost)) { return null; } } return proxyInfo; } /** * Configure the Wagon with the information from serverConfigurationMap ( which comes from settings.xml ) * * @param wagon * @param repositoryId * @param settings * @param container * @param log * @throws WagonConfigurationException * @todo Remove when {@link WagonManager#getWagon(Repository) is available}. It's available in Maven 2.0.5. */ static void configureWagon(Wagon wagon, String repositoryId, Settings settings, PlexusContainer container, Log log) throws WagonConfigurationException { // MSITE-25: Make sure that the server settings are inserted for (int i = 0; i < settings.getServers().size(); i++) { Server server = (Server) settings.getServers().get(i); String id = server.getId(); if (id != null && id.equals(repositoryId)) { if (server.getConfiguration() != null) { final PlexusConfiguration plexusConf = new XmlPlexusConfiguration((Xpp3Dom) server.getConfiguration()); ComponentConfigurator componentConfigurator = null; try { componentConfigurator = (ComponentConfigurator) container.lookup(ComponentConfigurator.ROLE); componentConfigurator.configureComponent(wagon, plexusConf, container.getContainerRealm()); } catch (final ComponentLookupException e) { throw new WagonConfigurationException(repositoryId, "Unable to lookup wagon configurator." + " Wagon configuration cannot be applied.", e); } catch (ComponentConfigurationException e) { throw new WagonConfigurationException(repositoryId, "Unable to apply wagon configuration.", e); } finally { if (componentConfigurator != null) { try { container.release(componentConfigurator); } catch (ComponentLifecycleException e) { log.error("Problem releasing configurator - ignoring: " + e.getMessage()); } } } } } } } public void contextualize(Context context) throws ContextException { container = (PlexusContainer) context.get(PlexusConstants.PLEXUS_KEY); } }
fixed up null bug
maven-updatesite-plugin/src/main/java/org/fusesource/mvnplugins/updatesite/UpdateSiteDeployMojo.java
fixed up null bug
<ide><path>aven-updatesite-plugin/src/main/java/org/fusesource/mvnplugins/updatesite/UpdateSiteDeployMojo.java <ide> String newDir = repositoryBasedir + postfix; <ide> <ide> getLog().info("Moving the current update site to: " + newDir); <add> if (mvOptions == null) { <add> mvOptions = ""; <add> } <ide> exec.executeCommand("mv " + mvOptions + " " + repositoryBasedir + " " + newDir); <ide> <ide> wagon.putDirectory(inputDirectory, remoteDirectory);
Java
apache-2.0
3e3a0ddb3b0d557ff9ef9542a1dafd32fb5479a3
0
qiscus/qiscus-sdk-android,rajapulau/qiscus-sdk-android
/* * Copyright (c) 2016 Qiscus. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.qiscus.sdk.data.remote; import android.provider.Settings; import android.support.annotation.Nullable; import android.util.Log; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.qiscus.sdk.Qiscus; import com.qiscus.sdk.data.model.QiscusAccount; import com.qiscus.sdk.data.model.QiscusChatRoom; import com.qiscus.sdk.data.model.QiscusComment; import com.qiscus.sdk.event.QiscusChatRoomEvent; import com.qiscus.sdk.event.QiscusCommentReceivedEvent; import com.qiscus.sdk.event.QiscusMqttStatusEvent; import com.qiscus.sdk.event.QiscusUserEvent; import com.qiscus.sdk.event.QiscusUserStatusEvent; import com.qiscus.sdk.util.QiscusAndroidUtil; import com.qiscus.sdk.util.QiscusErrorLogger; import com.qiscus.sdk.util.QiscusPushNotificationUtil; import org.eclipse.paho.android.service.MqttAndroidClient; import org.eclipse.paho.client.mqttv3.IMqttActionListener; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.IMqttToken; import org.eclipse.paho.client.mqttv3.MqttCallbackExtended; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; import java.util.TimeZone; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public enum QiscusPusherApi implements MqttCallbackExtended, IMqttActionListener { INSTANCE; private static final String TAG = QiscusPusherApi.class.getSimpleName(); private static final long RETRY_PERIOD = 2000; private static DateFormat dateFormat; private static Gson gson; private static long reconnectCounter; static { dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create(); } private String clientId; private String serverUri; private MqttAndroidClient mqttAndroidClient; private QiscusAccount qiscusAccount; private Runnable fallbackConnect = this::connect; private Runnable fallBackListenComment = this::listenComment; private Runnable fallBackListenRoom; private Runnable fallBackListenUserStatus; private ScheduledFuture<?> scheduledConnect; private ScheduledFuture<?> scheduledListenComment; private ScheduledFuture<?> scheduledListenRoom; private ScheduledFuture<?> scheduledListenUserStatus; private boolean connecting; private ScheduledFuture<?> scheduledUserStatus; private int setOfflineCounter; QiscusPusherApi() { Log.i("QiscusPusherApi", "Creating..."); if (!EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().register(this); } clientId = Qiscus.getApps().getPackageName() + "-"; clientId += Settings.Secure.getString(Qiscus.getApps().getContentResolver(), Settings.Secure.ANDROID_ID); serverUri = "ssl://mqtt.qiscus.com:1885"; buildClient(); connecting = false; } public static QiscusPusherApi getInstance() { return INSTANCE; } private void buildClient() { mqttAndroidClient = null; mqttAndroidClient = new MqttAndroidClient(Qiscus.getApps().getApplicationContext(), serverUri, clientId); mqttAndroidClient.setCallback(this); mqttAndroidClient.setTraceEnabled(false); } public void connect() { if (Qiscus.hasSetupUser() && !connecting && QiscusAndroidUtil.isNetworkAvailable()) { Log.i(TAG, "Connecting..."); connecting = true; qiscusAccount = Qiscus.getQiscusAccount(); MqttConnectOptions mqttConnectOptions = new MqttConnectOptions(); mqttConnectOptions.setAutomaticReconnect(false); mqttConnectOptions.setCleanSession(false); mqttConnectOptions.setWill("u/" + qiscusAccount.getEmail() + "/s", ("0:" + Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis()) .getBytes(), 2, true); try { mqttAndroidClient.connect(mqttConnectOptions, null, this); } catch (MqttException e) { //Do nothing } catch (NullPointerException | IllegalArgumentException e) { restartConnection(); } } } public boolean isConnected() { return mqttAndroidClient != null && mqttAndroidClient.isConnected(); } public void restartConnection() { Log.i(TAG, "Restart connection..."); try { connecting = false; mqttAndroidClient.disconnect(); mqttAndroidClient.close(); } catch (MqttException | NullPointerException | IllegalArgumentException e) { //Do nothing } clearTasks(); buildClient(); connect(); } private void clearTasks() { if (scheduledConnect != null) { scheduledConnect.cancel(true); scheduledConnect = null; } if (scheduledListenComment != null) { scheduledListenComment.cancel(true); scheduledListenComment = null; } if (scheduledListenRoom != null) { scheduledListenRoom.cancel(true); scheduledListenRoom = null; } if (scheduledListenUserStatus != null) { scheduledListenUserStatus.cancel(true); } } public void disconnect() { Log.i(TAG, "Disconnecting..."); setUserStatus(false); try { connecting = false; mqttAndroidClient.disconnect(); mqttAndroidClient.close(); } catch (MqttException | NullPointerException | IllegalArgumentException e) { //Do nothing } clearTasks(); stopUserStatus(); } private void listenComment() { Log.i(TAG, "Listening comment..."); try { mqttAndroidClient.subscribe(qiscusAccount.getToken() + "/c", 2); } catch (MqttException e) { //Do nothing } catch (NullPointerException | IllegalArgumentException e) { Log.e(TAG, "Failure listen comment, try again in " + RETRY_PERIOD + " ms"); connect(); scheduledListenComment = QiscusAndroidUtil.runOnBackgroundThread(fallBackListenComment, RETRY_PERIOD); } } public void listenRoom(QiscusChatRoom qiscusChatRoom) { Log.i(TAG, "Listening room..."); fallBackListenRoom = () -> listenRoom(qiscusChatRoom); try { int roomId = qiscusChatRoom.getId(); mqttAndroidClient.subscribe("r/" + roomId + "/+/+/t", 2); mqttAndroidClient.subscribe("r/" + roomId + "/+/+/d", 2); mqttAndroidClient.subscribe("r/" + roomId + "/+/+/r", 2); } catch (MqttException e) { //Do nothing } catch (NullPointerException | IllegalArgumentException e) { Log.e(TAG, "Failure listen room, try again in " + RETRY_PERIOD + " ms"); connect(); scheduledListenRoom = QiscusAndroidUtil.runOnBackgroundThread(fallBackListenRoom, RETRY_PERIOD); } } public void unListenRoom(QiscusChatRoom qiscusChatRoom) { try { int roomId = qiscusChatRoom.getId(); mqttAndroidClient.unsubscribe("r/" + roomId + "/+/+/t"); mqttAndroidClient.unsubscribe("r/" + roomId + "/+/+/d"); mqttAndroidClient.unsubscribe("r/" + roomId + "/+/+/r"); } catch (MqttException | NullPointerException | IllegalArgumentException e) { //Do nothing } if (scheduledListenRoom != null) { scheduledListenRoom.cancel(true); scheduledListenRoom = null; } fallBackListenRoom = null; } public void listenUserStatus(String user) { fallBackListenUserStatus = () -> listenUserStatus(user); try { mqttAndroidClient.subscribe("u/" + user + "/s", 2); } catch (MqttException e) { //Do nothing } catch (NullPointerException | IllegalArgumentException e) { connect(); scheduledListenUserStatus = QiscusAndroidUtil.runOnBackgroundThread(fallBackListenUserStatus, RETRY_PERIOD); } } public void unListenUserStatus(String user) { try { mqttAndroidClient.unsubscribe("u/" + user + "/s"); } catch (MqttException | NullPointerException | IllegalArgumentException e) { //Do nothing } if (scheduledListenUserStatus != null) { scheduledListenUserStatus.cancel(true); scheduledListenUserStatus = null; } fallBackListenUserStatus = null; } private void setUserStatus(boolean online) { checkAndConnect(); try { MqttMessage message = new MqttMessage(); message.setPayload(online ? "1".getBytes() : "0".getBytes()); message.setQos(2); message.setRetained(true); mqttAndroidClient.publish("u/" + qiscusAccount.getEmail() + "/s", message); } catch (MqttException | NullPointerException | IllegalArgumentException e) { //Do nothing } } public void setUserTyping(int roomId, int topicId, boolean typing) { checkAndConnect(); try { MqttMessage message = new MqttMessage(); message.setPayload((typing ? "1" : "0").getBytes()); mqttAndroidClient.publish("r/" + roomId + "/" + topicId + "/" + qiscusAccount.getEmail() + "/t", message); } catch (MqttException | NullPointerException | IllegalArgumentException e) { //Do nothing } } public void setUserRead(int roomId, int topicId, int commentId, String commentUniqueId) { QiscusApi.getInstance().updateCommentStatus(roomId, commentId, 0) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(aVoid -> { }, QiscusErrorLogger::print); } public void setUserDelivery(int roomId, int topicId, int commentId, String commentUniqueId) { QiscusApi.getInstance().updateCommentStatus(roomId, 0, commentId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(aVoid -> { }, QiscusErrorLogger::print); } private void checkAndConnect() { try { if (!mqttAndroidClient.isConnected()) { connect(); } } catch (NullPointerException e) { connect(); } catch (Exception ignored) { //ignored } } @Override public void connectionLost(Throwable cause) { if (reconnectCounter == 0) { EventBus.getDefault().post(QiscusMqttStatusEvent.DISCONNECTED); } reconnectCounter++; Log.e(TAG, "Lost connection, will try reconnect in " + RETRY_PERIOD * reconnectCounter + " ms"); connecting = false; scheduledConnect = QiscusAndroidUtil.runOnBackgroundThread(fallbackConnect, RETRY_PERIOD * reconnectCounter); } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { if (topic.contains(qiscusAccount.getToken())) { QiscusComment qiscusComment = jsonToComment(new String(message.getPayload())); if (qiscusComment == null) { return; } if (!qiscusComment.getSenderEmail().equals(qiscusAccount.getEmail())) { setUserDelivery(qiscusComment.getRoomId(), qiscusComment.getTopicId(), qiscusComment.getId(), qiscusComment.getUniqueId()); } QiscusPushNotificationUtil.handlePushNotification(Qiscus.getApps(), qiscusComment); EventBus.getDefault().post(new QiscusCommentReceivedEvent(qiscusComment)); } else if (topic.startsWith("r/") && topic.endsWith("/t")) { String[] data = topic.split("/"); if (!data[3].equals(qiscusAccount.getEmail())) { QiscusChatRoomEvent event = new QiscusChatRoomEvent() .setRoomId(Integer.parseInt(data[1])) .setTopicId(Integer.parseInt(data[2])) .setUser(data[3]) .setEvent(QiscusChatRoomEvent.Event.TYPING) .setTyping("1".equals(new String(message.getPayload()))); EventBus.getDefault().post(event); } } else if (topic.startsWith("r/") && topic.endsWith("/d")) { String[] data = topic.split("/"); if (!data[3].equals(qiscusAccount.getEmail())) { String[] payload = new String(message.getPayload()).split(":"); QiscusChatRoomEvent event = new QiscusChatRoomEvent() .setRoomId(Integer.parseInt(data[1])) .setTopicId(Integer.parseInt(data[2])) .setUser(data[3]) .setEvent(QiscusChatRoomEvent.Event.DELIVERED) .setCommentId(Integer.parseInt(payload[0])) .setCommentUniqueId(payload[1]); EventBus.getDefault().post(event); } } else if (topic.startsWith("r/") && topic.endsWith("/r")) { String[] data = topic.split("/"); if (!data[3].equals(qiscusAccount.getEmail())) { String[] payload = new String(message.getPayload()).split(":"); QiscusChatRoomEvent event = new QiscusChatRoomEvent() .setRoomId(Integer.parseInt(data[1])) .setTopicId(Integer.parseInt(data[2])) .setUser(data[3]) .setEvent(QiscusChatRoomEvent.Event.READ) .setCommentId(Integer.parseInt(payload[0])) .setCommentUniqueId(payload[1]); EventBus.getDefault().post(event); } } else if (topic.startsWith("u/") && topic.endsWith("/s")) { String[] data = topic.split("/"); if (!data[1].equals(qiscusAccount.getEmail())) { String[] status = new String(message.getPayload()).split(":"); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); calendar.setTimeInMillis(Long.parseLong(status[1])); QiscusUserStatusEvent event = new QiscusUserStatusEvent(data[1], "1".equals(status[0]), calendar.getTime()); EventBus.getDefault().post(event); } } } @Override public void deliveryComplete(IMqttDeliveryToken token) { } @Override public void connectComplete(boolean reconnect, String serverUri) { Log.i(TAG, "Connected..."); EventBus.getDefault().post(QiscusMqttStatusEvent.CONNECTED); try { connecting = false; reconnectCounter = 0; listenComment(); if (fallBackListenRoom != null) { scheduledListenRoom = QiscusAndroidUtil.runOnBackgroundThread(fallBackListenRoom); } if (fallBackListenUserStatus != null) { scheduledListenUserStatus = QiscusAndroidUtil.runOnBackgroundThread(fallBackListenUserStatus); } if (scheduledConnect != null) { scheduledConnect.cancel(true); scheduledConnect = null; } scheduleUserStatus(); } catch (NullPointerException | IllegalArgumentException ignored) { //Do nothing } } @Override public void onSuccess(IMqttToken asyncActionToken) { } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { if (reconnectCounter == 0) { EventBus.getDefault().post(QiscusMqttStatusEvent.DISCONNECTED); } reconnectCounter++; Log.e(TAG, "Failure to connect, try again in " + RETRY_PERIOD * reconnectCounter + " ms"); connecting = false; scheduledConnect = QiscusAndroidUtil.runOnBackgroundThread(fallbackConnect, RETRY_PERIOD * reconnectCounter); } @Subscribe public void onUserEvent(QiscusUserEvent userEvent) { switch (userEvent) { case LOGOUT: disconnect(); break; } } @Nullable public static QiscusComment jsonToComment(JsonObject jsonObject) { try { QiscusComment qiscusComment = new QiscusComment(); qiscusComment.setId(jsonObject.get("id").getAsInt()); qiscusComment.setTopicId(jsonObject.get("topic_id").getAsInt()); qiscusComment.setRoomId(jsonObject.get("room_id").getAsInt()); qiscusComment.setUniqueId(jsonObject.get("unique_temp_id").getAsString()); qiscusComment.setCommentBeforeId(jsonObject.get("comment_before_id").getAsInt()); qiscusComment.setMessage(jsonObject.get("message").getAsString()); qiscusComment.setSender(jsonObject.get("username").isJsonNull() ? null : jsonObject.get("username").getAsString()); qiscusComment.setSenderEmail(jsonObject.get("email").getAsString()); qiscusComment.setSenderAvatar(jsonObject.get("user_avatar").getAsString()); qiscusComment.setTime(dateFormat.parse(jsonObject.get("timestamp").getAsString())); qiscusComment.setState(QiscusComment.STATE_ON_QISCUS); qiscusComment.setRoomName(jsonObject.get("room_name").isJsonNull() ? qiscusComment.getSender() : jsonObject.get("room_name").getAsString()); if (jsonObject.has("room_avatar")) { qiscusComment.setRoomAvatar(jsonObject.get("room_avatar").getAsString()); } qiscusComment.setGroupMessage(!"single".equals(jsonObject.get("chat_type").getAsString())); if (!qiscusComment.isGroupMessage()) { qiscusComment.setRoomName(qiscusComment.getSender()); } if (jsonObject.has("type")) { qiscusComment.setRawType(jsonObject.get("type").getAsString()); qiscusComment.setExtraPayload(jsonObject.get("payload").toString()); if (qiscusComment.getType() == QiscusComment.Type.BUTTONS || qiscusComment.getType() == QiscusComment.Type.REPLY || qiscusComment.getType() == QiscusComment.Type.CARD) { JsonObject payload = jsonObject.get("payload").getAsJsonObject(); if (payload.has("text")) { String text = payload.get("text").getAsString(); if (text != null && !text.trim().isEmpty()) { qiscusComment.setMessage(text.trim()); } } } } return qiscusComment; } catch (Exception e) { e.printStackTrace(); } return null; } @Nullable public static QiscusComment jsonToComment(String json) { return jsonToComment(gson.fromJson(json, JsonObject.class)); } private void scheduleUserStatus() { scheduledUserStatus = Qiscus.getTaskExecutor() .scheduleWithFixedDelay(() -> { if (Qiscus.hasSetupUser() && isConnected()) { if (Qiscus.isOnForeground()) { setOfflineCounter = 0; setUserStatus(true); QiscusResendCommentHelper.tryResendFailedComment(); } else { if (setOfflineCounter <= 2) { setUserStatus(false); setOfflineCounter++; } } } else { stopUserStatus(); } }, 0, 10, TimeUnit.SECONDS); } private void stopUserStatus() { if (scheduledUserStatus != null) { scheduledUserStatus.cancel(true); } } }
chat/src/main/java/com/qiscus/sdk/data/remote/QiscusPusherApi.java
/* * Copyright (c) 2016 Qiscus. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.qiscus.sdk.data.remote; import android.provider.Settings; import android.support.annotation.Nullable; import android.util.Log; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.qiscus.sdk.Qiscus; import com.qiscus.sdk.data.model.QiscusAccount; import com.qiscus.sdk.data.model.QiscusChatRoom; import com.qiscus.sdk.data.model.QiscusComment; import com.qiscus.sdk.event.QiscusChatRoomEvent; import com.qiscus.sdk.event.QiscusCommentReceivedEvent; import com.qiscus.sdk.event.QiscusMqttStatusEvent; import com.qiscus.sdk.event.QiscusUserEvent; import com.qiscus.sdk.event.QiscusUserStatusEvent; import com.qiscus.sdk.util.QiscusAndroidUtil; import com.qiscus.sdk.util.QiscusErrorLogger; import com.qiscus.sdk.util.QiscusPushNotificationUtil; import org.eclipse.paho.android.service.MqttAndroidClient; import org.eclipse.paho.client.mqttv3.IMqttActionListener; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.IMqttToken; import org.eclipse.paho.client.mqttv3.MqttCallbackExtended; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; import java.util.TimeZone; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public enum QiscusPusherApi implements MqttCallbackExtended, IMqttActionListener { INSTANCE; private static final String TAG = QiscusPusherApi.class.getSimpleName(); private static final long RETRY_PERIOD = 2000; private static DateFormat dateFormat; private static Gson gson; private static long reconnectCounter; static { dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create(); } private String clientId; private String serverUri; private MqttAndroidClient mqttAndroidClient; private QiscusAccount qiscusAccount; private Runnable fallbackConnect = this::connect; private Runnable fallBackListenComment = this::listenComment; private Runnable fallBackListenRoom; private Runnable fallBackListenUserStatus; private ScheduledFuture<?> scheduledConnect; private ScheduledFuture<?> scheduledListenComment; private ScheduledFuture<?> scheduledListenRoom; private ScheduledFuture<?> scheduledListenUserStatus; private boolean connecting; private ScheduledFuture<?> scheduledUserStatus; private int setOfflineCounter; QiscusPusherApi() { Log.i("QiscusPusherApi", "Creating..."); if (!EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().register(this); } clientId = Qiscus.getApps().getPackageName() + "-"; clientId += Settings.Secure.getString(Qiscus.getApps().getContentResolver(), Settings.Secure.ANDROID_ID); serverUri = "ssl://mqtt.qiscus.com:1885"; buildClient(); connecting = false; } public static QiscusPusherApi getInstance() { return INSTANCE; } private void buildClient() { mqttAndroidClient = null; mqttAndroidClient = new MqttAndroidClient(Qiscus.getApps().getApplicationContext(), serverUri, clientId); mqttAndroidClient.setCallback(this); mqttAndroidClient.setTraceEnabled(false); } public void connect() { if (Qiscus.hasSetupUser() && !connecting && QiscusAndroidUtil.isNetworkAvailable()) { Log.i(TAG, "Connecting..."); connecting = true; qiscusAccount = Qiscus.getQiscusAccount(); MqttConnectOptions mqttConnectOptions = new MqttConnectOptions(); mqttConnectOptions.setAutomaticReconnect(false); mqttConnectOptions.setCleanSession(false); mqttConnectOptions.setWill("u/" + qiscusAccount.getEmail() + "/s", ("0:" + Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis()) .getBytes(), 2, true); try { mqttAndroidClient.connect(mqttConnectOptions, null, this); } catch (MqttException e) { //Do nothing } catch (NullPointerException | IllegalArgumentException e) { restartConnection(); } } } public boolean isConnected() { return mqttAndroidClient != null && mqttAndroidClient.isConnected(); } public void restartConnection() { Log.i(TAG, "Restart connection..."); try { connecting = false; mqttAndroidClient.disconnect(); mqttAndroidClient.close(); } catch (MqttException | NullPointerException | IllegalArgumentException e) { //Do nothing } clearTasks(); buildClient(); connect(); } private void clearTasks() { if (scheduledConnect != null) { scheduledConnect.cancel(true); scheduledConnect = null; } if (scheduledListenComment != null) { scheduledListenComment.cancel(true); scheduledListenComment = null; } if (scheduledListenRoom != null) { scheduledListenRoom.cancel(true); scheduledListenRoom = null; } if (scheduledListenUserStatus != null) { scheduledListenUserStatus.cancel(true); } } public void disconnect() { Log.i(TAG, "Disconnecting..."); setUserStatus(false); try { connecting = false; mqttAndroidClient.disconnect(); mqttAndroidClient.close(); } catch (MqttException | NullPointerException | IllegalArgumentException e) { //Do nothing } clearTasks(); stopUserStatus(); } private void listenComment() { Log.i(TAG, "Listening comment..."); try { mqttAndroidClient.subscribe(qiscusAccount.getToken() + "/c", 2); } catch (MqttException e) { //Do nothing } catch (NullPointerException | IllegalArgumentException e) { Log.e(TAG, "Failure listen comment, try again in " + RETRY_PERIOD + " ms"); connect(); scheduledListenComment = QiscusAndroidUtil.runOnBackgroundThread(fallBackListenComment, RETRY_PERIOD); } } public void listenRoom(QiscusChatRoom qiscusChatRoom) { Log.i(TAG, "Listening room..."); fallBackListenRoom = () -> listenRoom(qiscusChatRoom); try { int roomId = qiscusChatRoom.getId(); mqttAndroidClient.subscribe("r/" + roomId + "/+/+/t", 2); mqttAndroidClient.subscribe("r/" + roomId + "/+/+/d", 2); mqttAndroidClient.subscribe("r/" + roomId + "/+/+/r", 2); } catch (MqttException e) { //Do nothing } catch (NullPointerException | IllegalArgumentException e) { Log.e(TAG, "Failure listen room, try again in " + RETRY_PERIOD + " ms"); connect(); scheduledListenRoom = QiscusAndroidUtil.runOnBackgroundThread(fallBackListenRoom, RETRY_PERIOD); } } public void unListenRoom(QiscusChatRoom qiscusChatRoom) { try { int roomId = qiscusChatRoom.getId(); mqttAndroidClient.unsubscribe("r/" + roomId + "/+/+/t"); mqttAndroidClient.unsubscribe("r/" + roomId + "/+/+/d"); mqttAndroidClient.unsubscribe("r/" + roomId + "/+/+/r"); } catch (MqttException | NullPointerException | IllegalArgumentException e) { //Do nothing } if (scheduledListenRoom != null) { scheduledListenRoom.cancel(true); scheduledListenRoom = null; } fallBackListenRoom = null; } public void listenUserStatus(String user) { fallBackListenUserStatus = () -> listenUserStatus(user); try { mqttAndroidClient.subscribe("u/" + user + "/s", 2); } catch (MqttException e) { //Do nothing } catch (NullPointerException | IllegalArgumentException e) { connect(); scheduledListenUserStatus = QiscusAndroidUtil.runOnBackgroundThread(fallBackListenUserStatus, RETRY_PERIOD); } } public void unListenUserStatus(String user) { try { mqttAndroidClient.unsubscribe("u/" + user + "/s"); } catch (MqttException | NullPointerException | IllegalArgumentException e) { //Do nothing } if (scheduledListenUserStatus != null) { scheduledListenUserStatus.cancel(true); scheduledListenUserStatus = null; } fallBackListenUserStatus = null; } private void setUserStatus(boolean online) { checkAndConnect(); try { MqttMessage message = new MqttMessage(); message.setPayload(online ? "1".getBytes() : "0".getBytes()); message.setQos(2); message.setRetained(true); mqttAndroidClient.publish("u/" + qiscusAccount.getEmail() + "/s", message); } catch (MqttException | NullPointerException | IllegalArgumentException e) { //Do nothing } } public void setUserTyping(int roomId, int topicId, boolean typing) { checkAndConnect(); try { MqttMessage message = new MqttMessage(); message.setPayload((typing ? "1" : "0").getBytes()); mqttAndroidClient.publish("r/" + roomId + "/" + topicId + "/" + qiscusAccount.getEmail() + "/t", message); } catch (MqttException | NullPointerException | IllegalArgumentException e) { //Do nothing } } public void setUserRead(int roomId, int topicId, int commentId, String commentUniqueId) { QiscusApi.getInstance().updateCommentStatus(roomId, commentId, 0) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(aVoid -> { }, QiscusErrorLogger::print); } public void setUserDelivery(int roomId, int topicId, int commentId, String commentUniqueId) { QiscusApi.getInstance().updateCommentStatus(roomId, 0, commentId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(aVoid -> { }, QiscusErrorLogger::print); } private void checkAndConnect() { try { if (!mqttAndroidClient.isConnected()) { connect(); } } catch (NullPointerException e) { connect(); } catch (Exception ignored) { //ignored } } @Override public void connectionLost(Throwable cause) { if (reconnectCounter == 0) { EventBus.getDefault().post(QiscusMqttStatusEvent.DISCONNECTED); } reconnectCounter++; Log.e(TAG, "Lost connection, will try reconnect in " + RETRY_PERIOD * reconnectCounter + " ms"); connecting = false; scheduledConnect = QiscusAndroidUtil.runOnBackgroundThread(fallbackConnect, RETRY_PERIOD * reconnectCounter); } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { if (topic.contains(qiscusAccount.getToken())) { QiscusComment qiscusComment = jsonToComment(new String(message.getPayload())); if (qiscusComment == null) { return; } if (!qiscusComment.getSenderEmail().equals(qiscusAccount.getEmail())) { setUserDelivery(qiscusComment.getRoomId(), qiscusComment.getTopicId(), qiscusComment.getId(), qiscusComment.getUniqueId()); } QiscusPushNotificationUtil.handlePushNotification(Qiscus.getApps(), qiscusComment); EventBus.getDefault().post(new QiscusCommentReceivedEvent(qiscusComment)); } else if (topic.startsWith("r/") && topic.endsWith("/t")) { String[] data = topic.split("/"); if (!data[3].equals(qiscusAccount.getEmail())) { QiscusChatRoomEvent event = new QiscusChatRoomEvent() .setRoomId(Integer.parseInt(data[1])) .setTopicId(Integer.parseInt(data[2])) .setUser(data[3]) .setEvent(QiscusChatRoomEvent.Event.TYPING) .setTyping("1".equals(new String(message.getPayload()))); EventBus.getDefault().post(event); } } else if (topic.startsWith("r/") && topic.endsWith("/d")) { String[] data = topic.split("/"); if (!data[3].equals(qiscusAccount.getEmail())) { String[] payload = new String(message.getPayload()).split(":"); QiscusChatRoomEvent event = new QiscusChatRoomEvent() .setRoomId(Integer.parseInt(data[1])) .setTopicId(Integer.parseInt(data[2])) .setUser(data[3]) .setEvent(QiscusChatRoomEvent.Event.DELIVERED) .setCommentId(Integer.parseInt(payload[0])) .setCommentUniqueId(payload[1]); EventBus.getDefault().post(event); } } else if (topic.startsWith("r/") && topic.endsWith("/r")) { String[] data = topic.split("/"); if (!data[3].equals(qiscusAccount.getEmail())) { String[] payload = new String(message.getPayload()).split(":"); QiscusChatRoomEvent event = new QiscusChatRoomEvent() .setRoomId(Integer.parseInt(data[1])) .setTopicId(Integer.parseInt(data[2])) .setUser(data[3]) .setEvent(QiscusChatRoomEvent.Event.READ) .setCommentId(Integer.parseInt(payload[0])) .setCommentUniqueId(payload[1]); EventBus.getDefault().post(event); } } else if (topic.startsWith("u/") && topic.endsWith("/s")) { String[] data = topic.split("/"); if (!data[1].equals(qiscusAccount.getEmail())) { String[] status = new String(message.getPayload()).split(":"); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); calendar.setTimeInMillis(Long.parseLong(status[1])); QiscusUserStatusEvent event = new QiscusUserStatusEvent(data[1], "1".equals(status[0]), calendar.getTime()); EventBus.getDefault().post(event); } } } @Override public void deliveryComplete(IMqttDeliveryToken token) { } @Override public void connectComplete(boolean reconnect, String serverUri) { Log.i(TAG, "Connected..."); EventBus.getDefault().post(QiscusMqttStatusEvent.CONNECTED); if (Qiscus.isOnForeground()) { QiscusResendCommentHelper.tryResendFailedComment(); } try { connecting = false; reconnectCounter = 0; listenComment(); if (fallBackListenRoom != null) { scheduledListenRoom = QiscusAndroidUtil.runOnBackgroundThread(fallBackListenRoom); } if (fallBackListenUserStatus != null) { scheduledListenUserStatus = QiscusAndroidUtil.runOnBackgroundThread(fallBackListenUserStatus); } if (scheduledConnect != null) { scheduledConnect.cancel(true); scheduledConnect = null; } scheduleUserStatus(); } catch (NullPointerException | IllegalArgumentException ignored) { //Do nothing } } @Override public void onSuccess(IMqttToken asyncActionToken) { } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { if (reconnectCounter == 0) { EventBus.getDefault().post(QiscusMqttStatusEvent.DISCONNECTED); } reconnectCounter++; Log.e(TAG, "Failure to connect, try again in " + RETRY_PERIOD * reconnectCounter + " ms"); connecting = false; scheduledConnect = QiscusAndroidUtil.runOnBackgroundThread(fallbackConnect, RETRY_PERIOD * reconnectCounter); } @Subscribe public void onUserEvent(QiscusUserEvent userEvent) { switch (userEvent) { case LOGOUT: disconnect(); break; } } @Nullable public static QiscusComment jsonToComment(JsonObject jsonObject) { try { QiscusComment qiscusComment = new QiscusComment(); qiscusComment.setId(jsonObject.get("id").getAsInt()); qiscusComment.setTopicId(jsonObject.get("topic_id").getAsInt()); qiscusComment.setRoomId(jsonObject.get("room_id").getAsInt()); qiscusComment.setUniqueId(jsonObject.get("unique_temp_id").getAsString()); qiscusComment.setCommentBeforeId(jsonObject.get("comment_before_id").getAsInt()); qiscusComment.setMessage(jsonObject.get("message").getAsString()); qiscusComment.setSender(jsonObject.get("username").isJsonNull() ? null : jsonObject.get("username").getAsString()); qiscusComment.setSenderEmail(jsonObject.get("email").getAsString()); qiscusComment.setSenderAvatar(jsonObject.get("user_avatar").getAsString()); qiscusComment.setTime(dateFormat.parse(jsonObject.get("timestamp").getAsString())); qiscusComment.setState(QiscusComment.STATE_ON_QISCUS); qiscusComment.setRoomName(jsonObject.get("room_name").isJsonNull() ? qiscusComment.getSender() : jsonObject.get("room_name").getAsString()); if (jsonObject.has("room_avatar")) { qiscusComment.setRoomAvatar(jsonObject.get("room_avatar").getAsString()); } qiscusComment.setGroupMessage(!"single".equals(jsonObject.get("chat_type").getAsString())); if (!qiscusComment.isGroupMessage()) { qiscusComment.setRoomName(qiscusComment.getSender()); } if (jsonObject.has("type")) { qiscusComment.setRawType(jsonObject.get("type").getAsString()); qiscusComment.setExtraPayload(jsonObject.get("payload").toString()); if (qiscusComment.getType() == QiscusComment.Type.BUTTONS || qiscusComment.getType() == QiscusComment.Type.REPLY || qiscusComment.getType() == QiscusComment.Type.CARD) { JsonObject payload = jsonObject.get("payload").getAsJsonObject(); if (payload.has("text")) { String text = payload.get("text").getAsString(); if (text != null && !text.trim().isEmpty()) { qiscusComment.setMessage(text.trim()); } } } } return qiscusComment; } catch (Exception e) { e.printStackTrace(); } return null; } @Nullable public static QiscusComment jsonToComment(String json) { return jsonToComment(gson.fromJson(json, JsonObject.class)); } private void scheduleUserStatus() { scheduledUserStatus = Qiscus.getTaskExecutor() .scheduleWithFixedDelay(() -> { if (Qiscus.hasSetupUser() && isConnected()) { if (Qiscus.isOnForeground()) { setOfflineCounter = 0; setUserStatus(true); QiscusResendCommentHelper.tryResendFailedComment(); } else { if (setOfflineCounter <= 2) { setUserStatus(false); setOfflineCounter++; } } } else { stopUserStatus(); } }, 0, 10, TimeUnit.SECONDS); } private void stopUserStatus() { if (scheduledUserStatus != null) { scheduledUserStatus.cancel(true); } } }
Fix double retry resend comment
chat/src/main/java/com/qiscus/sdk/data/remote/QiscusPusherApi.java
Fix double retry resend comment
<ide><path>hat/src/main/java/com/qiscus/sdk/data/remote/QiscusPusherApi.java <ide> public void connectComplete(boolean reconnect, String serverUri) { <ide> Log.i(TAG, "Connected..."); <ide> EventBus.getDefault().post(QiscusMqttStatusEvent.CONNECTED); <del> if (Qiscus.isOnForeground()) { <del> QiscusResendCommentHelper.tryResendFailedComment(); <del> } <ide> try { <ide> connecting = false; <ide> reconnectCounter = 0;
Java
mit
340dadfba9d19da60256ca417364ff342e7e335c
0
crowdin/crowdin-cli,crowdin/crowdin-cli
package com.crowdin.cli.commands; import com.crowdin.cli.commands.parts.Command; import com.crowdin.cli.utils.console.ExecutionStatus; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import picocli.CommandLine; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import static com.crowdin.cli.properties.CliProperties.*; @CommandLine.Command( name = "generate", aliases = "init", customSynopsis = "@|fg(yellow) crowdin |@(@|fg(yellow) generate|@|@|fg(yellow) init|@) [CONFIG OPTIONS] [OPTIONS]", description = "Generate Crowdin CLI configuration skeleton") public class GenerateSubcommand extends Command { @CommandLine.Option(names = {"-d", "--destination"}, description = "Place where the configuration skeleton should be saved. Default: crowdin.yml", paramLabel = "...", defaultValue = "crowdin.yml") private Path destinationPath; @CommandLine.Option(names = "--skip-generate-description", hidden = true) private boolean skipGenerateDescription; public static final String BASE_PATH_DEFAULT = "."; public static final String BASE_URL_DEFAULT = "https://api.crowdin.com"; public static final String BASE_ENTERPRISE_URL_DEFAULT = "https://%s.crowdin.com"; private Scanner scanner = new Scanner(System.in); private boolean isEnterprise; public static final String LINK = "https://support.crowdin.com/configuration-file-v3/"; public static final String ENTERPRISE_LINK = "https://support.crowdin.com/enterprise/configuration-file/"; @Override public void run() { try { System.out.println(RESOURCE_BUNDLE.getString("command_generate_description") + " '" + destinationPath.toAbsolutePath() + "'"); if (Files.exists(destinationPath)) { System.out.println(ExecutionStatus.SKIPPED.getIcon() + "File '" + destinationPath.toAbsolutePath() + "' already exists."); return; } List<String> fileLines = this.readResource("/crowdin.yml"); if (!skipGenerateDescription) { this.updateWithUserInputs(fileLines); } this.write(destinationPath, fileLines); System.out.printf("Your configuration skeleton has been successfully generated. " + "%nSpecify the paths to your sources and translations in the files section. " + "%nFor more details see %s%n", (this.isEnterprise ? ENTERPRISE_LINK : LINK)); } catch (Exception e) { throw new RuntimeException("Error while creating config file", e); } } private void write(Path path, List<String> fileLines) { try { Files.write(destinationPath, fileLines); } catch (IOException e) { throw new RuntimeException("Couldn't write to file '" + destinationPath.toAbsolutePath() + "'", e); } } private void updateWithUserInputs(List<String> fileLines) { Map<String, String> values = new HashMap<>(); values.put(BASE_PATH, askWithDefault("Your project directory", BASE_PATH_DEFAULT)); this.isEnterprise = StringUtils.startsWithAny(ask("For Crowdin Enterprise: (N/y) "), "y", "Y", "+"); if (this.isEnterprise) { String organizationName = ask("Your organization name: "); if (StringUtils.isNotEmpty(organizationName)) { values.put(BASE_URL, String.format(BASE_ENTERPRISE_URL_DEFAULT, organizationName)); } else { this.isEnterprise = false; values.put(BASE_URL, BASE_URL_DEFAULT); } } else { values.put(BASE_URL, BASE_URL_DEFAULT); } values.put(PROJECT_ID, askParam(PROJECT_ID)); values.put(API_TOKEN, askParam(API_TOKEN)); for (String key : values.keySet()) { for (int i = 0; i < fileLines.size(); i++) { if (fileLines.get(i).contains(key)) { fileLines.set(i, fileLines.get(i).replaceFirst(": \"*\"", String.format(": \"%s\"", values.get(key)))); break; } } } } private List<String> readResource(String fileName) { try { return IOUtils.readLines(this.getClass().getResourceAsStream(fileName), "UTF-8"); } catch (IOException e) { throw new RuntimeException("Couldn't read from resource file", e); } } private String askParam(String key) { return ask(StringUtils.capitalize(key.replaceAll("_", " ")) + ": "); } private String askWithDefault(String question, String def) { String input = ask(question + ": (" + def + ") "); return StringUtils.isNotEmpty(input) ? input : def; } private String ask(String question) { System.out.print(question); return scanner.nextLine(); } }
src/main/java/com/crowdin/cli/commands/GenerateSubcommand.java
package com.crowdin.cli.commands; import com.crowdin.cli.commands.parts.Command; import com.crowdin.cli.utils.console.ExecutionStatus; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import picocli.CommandLine; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import static com.crowdin.cli.properties.CliProperties.*; @CommandLine.Command( name = "generate", aliases = "init", customSynopsis = "@|fg(yellow) crowdin |@(@|fg(yellow) generate|@|@|fg(yellow) init|@) [CONFIG OPTIONS] [OPTIONS]", description = "Generate Crowdin CLI configuration skeleton") public class GenerateSubcommand extends Command { @CommandLine.Option(names = {"-d", "--destination"}, description = "Place where the configuration skeleton should be saved. Default: crowdin.yml", paramLabel = "...", defaultValue = "crowdin.yml") private Path destinationPath; @CommandLine.Option(names = "--skip-generate-description", hidden = true) private boolean skipGenerateDescription; public static final String BASE_PATH_DEFAULT = "."; public static final String BASE_URL_DEFAULT = "https://api.crowdin.com"; public static final String BASE_ENTERPRISE_URL_DEFAULT = "https://%s.crowdin.com"; private Scanner scanner = new Scanner(System.in); private boolean isEnterprise; public static final String LINK = "https://support.crowdin.com/configuration-file-v3/"; public static final String ENTERPRISE_LINK = "https://support.crowdin.com/enterprise/configuration-file/"; @Override public void run() { try { System.out.println(RESOURCE_BUNDLE.getString("command_generate_description") + " '" + destinationPath.toAbsolutePath() + "'"); if (Files.exists(destinationPath)) { System.out.println(ExecutionStatus.SKIPPED.getIcon() + "File '" + destinationPath.toAbsolutePath() + "' already exists."); return; } List<String> fileLines = this.readResource("/crowdin.yml"); if (!skipGenerateDescription) { this.updateWithUserInputs(fileLines); } this.write(destinationPath, fileLines); System.out.printf("Your configuration skeleton has been successfully generated. " + "Specify the paths to your sources and translations in the files section. " + "For more details see %s%n", (this.isEnterprise ? ENTERPRISE_LINK : LINK)); } catch (Exception e) { throw new RuntimeException("Error while creating config file", e); } } private void write(Path path, List<String> fileLines) { try { Files.write(destinationPath, fileLines); } catch (IOException e) { throw new RuntimeException("Couldn't write to file '" + destinationPath.toAbsolutePath() + "'", e); } } private void updateWithUserInputs(List<String> fileLines) { Map<String, String> values = new HashMap<>(); values.put(BASE_PATH, askParamWithDefault(BASE_PATH, BASE_PATH_DEFAULT)); this.isEnterprise = StringUtils.startsWithAny(ask("For Crowdin Enterprise: (N/y) "), "y", "Y", "+"); if (this.isEnterprise) { String organizationName = ask("Your organization name: "); if (StringUtils.isNotEmpty(organizationName)) { values.put(BASE_URL, String.format(BASE_ENTERPRISE_URL_DEFAULT, organizationName)); } else { this.isEnterprise = false; values.put(BASE_URL, BASE_URL_DEFAULT); } } else { values.put(BASE_URL, BASE_URL_DEFAULT); } values.put(PROJECT_ID, askParam(PROJECT_ID)); values.put(API_TOKEN, askParam(API_TOKEN)); for (String key : values.keySet()) { for (int i = 0; i < fileLines.size(); i++) { if (fileLines.get(i).contains(key)) { fileLines.set(i, fileLines.get(i).replaceFirst(": \"*\"", String.format(": \"%s\"", values.get(key)))); break; } } } } private List<String> readResource(String fileName) { try { return IOUtils.readLines(this.getClass().getResourceAsStream(fileName), "UTF-8"); } catch (IOException e) { throw new RuntimeException("Couldn't read from resource file", e); } } private String askParamWithDefault(String key, String def) { String input = ask(StringUtils.capitalize(key.replaceAll("_", " ")) + ": (" + def + ") "); return StringUtils.isNotEmpty(input) ? input : def; } private String askParam(String key) { return ask(StringUtils.capitalize(key.replaceAll("_", " ")) + ": "); } private String ask(String question) { System.out.print(question); return scanner.nextLine(); } }
Improve init - change questions, minor changes
src/main/java/com/crowdin/cli/commands/GenerateSubcommand.java
Improve init - change questions, minor changes
<ide><path>rc/main/java/com/crowdin/cli/commands/GenerateSubcommand.java <ide> } <ide> this.write(destinationPath, fileLines); <ide> System.out.printf("Your configuration skeleton has been successfully generated. " + <del> "Specify the paths to your sources and translations in the files section. " + <del> "For more details see %s%n", (this.isEnterprise ? ENTERPRISE_LINK : LINK)); <add> "%nSpecify the paths to your sources and translations in the files section. " + <add> "%nFor more details see %s%n", (this.isEnterprise ? ENTERPRISE_LINK : LINK)); <ide> <ide> } catch (Exception e) { <ide> throw new RuntimeException("Error while creating config file", e); <ide> private void updateWithUserInputs(List<String> fileLines) { <ide> Map<String, String> values = new HashMap<>(); <ide> <del> values.put(BASE_PATH, askParamWithDefault(BASE_PATH, BASE_PATH_DEFAULT)); <add> values.put(BASE_PATH, askWithDefault("Your project directory", BASE_PATH_DEFAULT)); <ide> this.isEnterprise = StringUtils.startsWithAny(ask("For Crowdin Enterprise: (N/y) "), "y", "Y", "+"); <ide> if (this.isEnterprise) { <ide> String organizationName = ask("Your organization name: "); <ide> } <ide> } <ide> <del> private String askParamWithDefault(String key, String def) { <del> String input = ask(StringUtils.capitalize(key.replaceAll("_", " ")) + ": (" + def + ") "); <del> return StringUtils.isNotEmpty(input) ? input : def; <add> private String askParam(String key) { <add> return ask(StringUtils.capitalize(key.replaceAll("_", " ")) + ": "); <ide> } <ide> <del> private String askParam(String key) { <del> return ask(StringUtils.capitalize(key.replaceAll("_", " ")) + ": "); <add> private String askWithDefault(String question, String def) { <add> String input = ask(question + ": (" + def + ") "); <add> return StringUtils.isNotEmpty(input) ? input : def; <ide> } <ide> <ide> private String ask(String question) {
Java
apache-2.0
f0c4099f70aa53af09184996a43ceabbb9e4071b
0
arrowli/RsyncHadoop,arrowli/RsyncHadoop,arrowli/RsyncHadoop,arrowli/RsyncHadoop,arrowli/RsyncHadoop,arrowli/RsyncHadoop,arrowli/RsyncHadoop
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.tools; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_USE_DN_HOSTNAME; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_USE_DN_HOSTNAME_DEFAULT; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.URI; import java.util.ArrayList; import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.*; import javax.net.SocketFactory; import javax.swing.text.Segment; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CreateFlag; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FsServerDefaults; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.UnresolvedLinkException; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.hdfs.DFSClient.Conf; import org.apache.hadoop.hdfs.LeaseRenewer; import org.apache.hadoop.hdfs.protocol.AlreadyBeingCreatedException; import org.apache.hadoop.hdfs.protocol.ClientProtocol; import org.apache.hadoop.hdfs.protocol.DatanodeInfo; import org.apache.hadoop.hdfs.protocol.ExtendedBlock; import org.apache.hadoop.hdfs.protocol.HdfsConstants; import org.apache.hadoop.hdfs.protocol.HdfsFileStatus; import org.apache.hadoop.hdfs.protocol.LocatedBlock; import org.apache.hadoop.hdfs.protocol.LocatedBlocks; import org.apache.hadoop.hdfs.security.token.block.DataEncryptionKey; import org.apache.hadoop.hdfs.security.token.block.InvalidBlockTokenException; import org.apache.hadoop.hdfs.server.common.HdfsServerConstants; import org.apache.hadoop.hdfs.server.datanode.BlockMetadataHeader; import org.apache.hadoop.hdfs.server.datanode.CachingStrategy; import org.apache.hadoop.hdfs.server.namenode.NameNode; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.io.EnumSetWritable; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.io.MD5Hash; import org.apache.hadoop.io.retry.RetryPolicies; import org.apache.hadoop.io.retry.RetryPolicy; import org.apache.hadoop.io.retry.RetryProxy; import org.apache.hadoop.ipc.ProtocolProxy; import org.apache.hadoop.ipc.RemoteException; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.AccessControlException; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.util.DataChecksum; import org.apache.hadoop.util.Time; import org.apache.hadoop.util.DataChecksum.Type; /* new added */ import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.hdfs.protocol.datatransfer.DataTransferEncryptor; import org.apache.hadoop.hdfs.protocol.datatransfer.DataTransferProtocol; import org.apache.hadoop.hdfs.protocol.datatransfer.IOStreamPair; import org.apache.hadoop.hdfs.protocol.datatransfer.Op; import org.apache.hadoop.hdfs.protocol.datatransfer.Sender; import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BlockOpResponseProto; import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.ChecksumPairProto; import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpBlockChecksumResponseProto; import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCalculateSegmentsResponseProto; import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpChunksChecksumResponseProto; import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.SegmentProto; import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.Status; import org.apache.hadoop.hdfs.protocolPB.PBHelper; /** * rsynccopy复制一个文件的工作过程如下 : * * 1) 从NN获取文件所有block的位置,包括源文件src和目标文件dst的。 * * 2) 从src和dst的所有block中获取checksum列表。 * * 3) 比对后,把dst中部分block的checksum列表传递给src中的部分DN。 * * 4) 得到checksum列表的DN计算block差异,回传给rsynccopy。 * * 5) rsynccopy根据收到的信息,控制DN把block差异传递给需要的DN。 * * 6) DN之间传递block差异,并将差异存到本地的临时文件夹。 * * 7)rsynccopy确认所有差异传递完毕后,控制DN将block差异合成最后的文件 * **/ public class RsyncCopy { public static final long SERVER_DEFAULTS_VALIDITY_PERIOD = 60 * 60 * 1000L; // 1 // hour public static final Log LOG = LogFactory.getLog(RsyncCopy.class); public ClientProtocol srcNamenode; public ClientProtocol dstNamenode; // Namenode proxy that supports method-based compatibility public ProtocolProxy<ClientProtocol> srcNamenodeProtocolProxy = null; public ProtocolProxy<ClientProtocol> dstNamenodeProtocolProxy = null; static Random r = new Random(); String clientName; Configuration conf; SocketFactory socketFactory; FileSystem.Statistics stats; private long namenodeVersion = ClientProtocol.versionID; protected Integer dataTransferVersion = -1; protected volatile int namespaceId = 0; InetAddress localHost; InetSocketAddress nameNodeAddr; // int ipTosValue = NetUtils.NOT_SET_IP_TOS; volatile boolean clientRunning = true; private ClientProtocol rpcNamenode; int socketTimeout; int namenodeRPCSocketTimeout; public Object namenodeProxySyncObj = new Object(); private Path srcPath; private Path dstPath; private DistributedFileSystem srcDfs; private DistributedFileSystem dstDfs; UserGroupInformation ugi; volatile long lastLeaseRenewal; private String authority; private DataEncryptionKey encryptionKey; private volatile FsServerDefaults serverDefaults; private volatile long serverDefaultsLastUpdate; private boolean connectToDnViaHostname; private LeaseRenewer renewer; public RsyncCopy(String srcPath,String dstPath) throws IOException { conf = new Configuration(); this.srcPath = new Path(srcPath); this.dstPath = new Path(dstPath); srcDfs = (DistributedFileSystem)this.srcPath.getFileSystem(conf); dstDfs = (DistributedFileSystem)this.dstPath.getFileSystem(conf); RsyncCopyInit(NameNode.getAddress(conf), null, null,0); } /** * Create a new DFSClient connected to the given nameNodeAddr or * rpcNamenode. Exactly one of nameNodeAddr or rpcNamenode must be null. */ private void RsyncCopyInit(InetSocketAddress nameNodeAddr, ClientProtocol rpcNamenode, FileSystem.Statistics stats, long uniqueId) throws IOException { this.stats = stats; this.connectToDnViaHostname = conf.getBoolean( DFS_CLIENT_USE_DN_HOSTNAME, DFS_CLIENT_USE_DN_HOSTNAME_DEFAULT); this.socketFactory = NetUtils.getSocketFactory(conf, ClientProtocol.class); this.localHost = InetAddress.getLocalHost(); String taskId = conf.get("mapreduce.task.attempt.id"); if (taskId != null) { this.clientName = "RsyncCopy_" + taskId + "_" + r.nextInt() + "_" + Thread.currentThread().getId(); } else { this.clientName = "RsyncCopy_" + r.nextInt() + ((uniqueId == 0) ? "" : "_" + uniqueId); } if (nameNodeAddr != null && rpcNamenode == null) { this.nameNodeAddr = nameNodeAddr; getNameNode(); } else { throw new IllegalArgumentException( "Expecting exactly one of nameNodeAddr and rpcNamenode being null: " + "nameNodeAddr=" + nameNodeAddr + ", rpcNamenode=" + rpcNamenode); } this.ugi = UserGroupInformation.getCurrentUser(); URI nameNodeUri = NameNode.getUri(NameNode.getAddress(conf)); this.authority = nameNodeUri == null ? "null" : nameNodeUri .getAuthority(); this.socketTimeout = conf.getInt("dfs.client.socket-timeout", HdfsServerConstants.READ_TIMEOUT); this.namenodeRPCSocketTimeout = 60 * 1000; renewer = new LeaseRenewer(); renewer.setClientName(clientName); renewer.setNamenode(dstNamenode); //只需要更新dstNamenode的lease就可以了,因为并没有更改src的文件内容 Thread renewerThread = new Thread(renewer); renewerThread.start(); } private class LeaseRenewer implements Runnable { private long lastRenewalTime; /** A fixed lease renewal time period in milliseconds */ private long renewal = HdfsConstants.LEASE_SOFTLIMIT_PERIOD/2; private String clientName; private ClientProtocol namenode; public void setClientName(String clientName){ this.clientName = clientName; lastRenewalTime = Time.now(); } public void setNamenode(ClientProtocol namenode){ this.namenode = namenode; } public void run(){ try{ while(true){ namenode.renewLease(clientName); Thread.sleep(renewal); } }catch(IOException e){ } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private class RsyncCopyFile{ private Path srcPath; private Path dstPath; public ClientProtocol srcNamenode; public ClientProtocol dstNamenode; // Namenode proxy that supports method-based compatibility public ProtocolProxy<ClientProtocol> srcNamenodeProtocolProxy = null; public ProtocolProxy<ClientProtocol> dstNamenodeProtocolProxy = null; final String clientName; Configuration conf; SocketFactory socketFactory; final FileSystem.Statistics stats; private long namenodeVersion = ClientProtocol.versionID; protected Integer dataTransferVersion = -1; protected volatile int namespaceId = 0; // int ipTosValue = NetUtils.NOT_SET_IP_TOS; volatile boolean clientRunning = true; private ClientProtocol rpcNamenode; int socketTimeout; int namenodeRPCSocketTimeout; final UserGroupInformation ugi; volatile long lastLeaseRenewal; private final String authority; private DataEncryptionKey encryptionKey; private volatile FsServerDefaults serverDefaults; private volatile long serverDefaultsLastUpdate; private boolean connectToDnViaHostname; private int chunkSize; private class ChecksumPair{ private Integer simple; private byte[] md5; public ChecksumPair(Integer simple,byte[] bs){ this.simple = simple; this.md5 = bs; } public Integer getSimple() { return simple; } public void setSimple(Integer simple) { this.simple = simple; } public byte[] getMd5() { return md5; } public void setMd5(byte[] md5) { this.md5 = md5; } } private class BlockInfo{ private LocatedBlock locatedBlock; private LinkedList<ChecksumPair> checksums; private LinkedList<SegmentProto> segments; public BlockInfo(LocatedBlock locatedBlock){ this.locatedBlock = locatedBlock; this.checksums = new LinkedList<ChecksumPair>(); this.segments = new LinkedList<SegmentProto>(); } public BlockInfo(LocatedBlock locatedBlock,LinkedList<ChecksumPair> checksums,LinkedList<SegmentProto> segments){ this.locatedBlock = locatedBlock; this.checksums = checksums; this.segments = segments; } public LocatedBlock getLocatedBlock() { return locatedBlock; } public void setLocatedBlock(LocatedBlock locatedBlock) { this.locatedBlock = locatedBlock; } public List<ChecksumPair> getChecksums() { return checksums; } public void setChecksums(LinkedList<ChecksumPair> checksums) { this.checksums = checksums; } public void addChecksum(ChecksumPair checksum){ this.checksums.add(checksum); } public LinkedList<SegmentProto> getSegments() { return segments; } public void setSegments(LinkedList<SegmentProto> segments) { this.segments = segments; } } private class FileInfo{ private List<BlockInfo> blocks; private String filepath; private long fileSize; public FileInfo(String filepath){ this.setFilepath(filepath); this.blocks = new LinkedList<BlockInfo>(); } public List<BlockInfo> getBlocks() { return blocks; } public void setBlocks(List<BlockInfo> blocks) { this.blocks = blocks; } public void addBlock(BlockInfo block){ this.blocks.add(block); } public String getFilepath() { return filepath; } public void setFilepath(String filepath) { this.filepath = filepath; } public long getFileSize() { return fileSize; } public void setFileSize(long fileSize) { this.fileSize = fileSize; } } private FileInfo srcFileInfo; private FileInfo dstFileInfo; //private FileInfo newFileInfo; RsyncCopyFile(ClientProtocol srcNamenode,ProtocolProxy<ClientProtocol> srcNamenodeProtocolProxy,Path srcPath, ClientProtocol dstNamenode,ProtocolProxy<ClientProtocol> dstNamenodeProtocolProxy,Path dstPath, Configuration conf, FileSystem.Statistics stats, long uniqueId) throws IOException { this.srcNamenode = srcNamenode; this.srcNamenodeProtocolProxy = srcNamenodeProtocolProxy; this.srcPath = srcPath; this.dstNamenode = dstNamenode; this.dstNamenodeProtocolProxy = dstNamenodeProtocolProxy; this.dstPath = dstPath; this.conf = conf; this.stats = stats; this.connectToDnViaHostname = conf.getBoolean( DFS_CLIENT_USE_DN_HOSTNAME, DFS_CLIENT_USE_DN_HOSTNAME_DEFAULT); this.socketFactory = NetUtils.getSocketFactory(conf, ClientProtocol.class); String taskId = conf.get("mapreduce.task.attempt.id"); if (taskId != null) { this.clientName = "RsyncCopy_" + taskId + "_" + r.nextInt() + "_" + Thread.currentThread().getId(); } else { this.clientName = "RsyncCopy_" + r.nextInt() + ((uniqueId == 0) ? "" : "_" + uniqueId); } this.ugi = UserGroupInformation.getCurrentUser(); URI nameNodeUri = NameNode.getUri(NameNode.getAddress(conf)); this.authority = nameNodeUri == null ? "null" : nameNodeUri .getAuthority(); this.socketTimeout = conf.getInt("dfs.client.socket-timeout", HdfsServerConstants.READ_TIMEOUT); this.namenodeRPCSocketTimeout = 60 * 1000; this.chunkSize = 1024*1024; } /** * Get the source file blocks information from NN * Get the destination file blocks information from NN * Create the new temp file in dst file system. */ void getSDFileInfo() throws IOException { LocatedBlocks srcLocatedBlocks = callGetBlockLocations( srcNamenode,srcPath.toString(),0,Long.MAX_VALUE, isMetaInfoSupported(srcNamenodeProtocolProxy)); if (srcLocatedBlocks == null) { throw new IOException( "Null block locations, mostly because non-existent file " + srcPath.toString()); } LocatedBlocks dstLocatedBlocks = callGetBlockLocations( dstNamenode,dstPath.toString(),0,Long.MAX_VALUE, isMetaInfoSupported(dstNamenodeProtocolProxy)); if (dstLocatedBlocks == null) { throw new IOException( "Null block locations, mostly because non-existent file " + dstPath.toString()); } this.srcFileInfo = new FileInfo(srcPath.toString()); this.dstFileInfo = new FileInfo(dstPath.toString()); this.srcFileInfo.setFileSize(srcLocatedBlocks.getFileLength()); this.dstFileInfo.setFileSize(dstLocatedBlocks.getFileLength()); for(LocatedBlock lb : srcLocatedBlocks.getLocatedBlocks()){ srcFileInfo.addBlock(new BlockInfo(lb)); } for(LocatedBlock lb : dstLocatedBlocks.getLocatedBlocks()){ dstFileInfo.addBlock(new BlockInfo(lb)); } //this.newFileInfo = createNewFile(dstPath.toString()+".rsync",srcFileInfo); } /** * Get the checksum of a file. * * @param src * The file path * @return The checksum * @see DistributedFileSystem#getFileChecksum(Path) */ void getSDFileChecksum() throws IOException { checkOpen(); getFileChecksum(dataTransferVersion, srcFileInfo, srcNamenode, srcNamenodeProtocolProxy, socketFactory, socketTimeout); getFileChecksum(dataTransferVersion, dstFileInfo, dstNamenode, dstNamenodeProtocolProxy, socketFactory, socketTimeout); } /** * Get the checksum of a file. * * @param src * The file path * @return The checksum */ public void getFileChecksum(int dataTransferVersion, FileInfo fileInfo, ClientProtocol namenode, ProtocolProxy<ClientProtocol> namenodeProxy, SocketFactory socketFactory, int socketTimeout) throws IOException { LOG.warn("getFileShecksum start"); final DataOutputBuffer md5out = new DataOutputBuffer(); int namespaceId = 0; boolean refetchBlocks = false; int lastRetriedIndex = -1; dataTransferVersion = DataTransferProtocol.DATA_TRANSFER_VERSION; int bytesPerCRC = -1; DataChecksum.Type crcType = DataChecksum.Type.DEFAULT; long crcPerBlock = 0; // get block checksum for each block for (int i = 0; i < srcFileInfo.getBlocks().size(); i++) { LocatedBlock lb = srcFileInfo.getBlocks().get(i).locatedBlock; final ExtendedBlock block = lb.getBlock(); final DatanodeInfo[] datanodes = lb.getLocations(); // try each datanode location of the block final int timeout = 3000 * datanodes.length + socketTimeout; boolean done = false; for (int j = 0; !done && j < datanodes.length; j++) { DataOutputStream out = null; DataInputStream in = null; try { // connect to a datanode IOStreamPair pair = connectToDN(socketFactory, connectToDnViaHostname, getDataEncryptionKey(), datanodes[j], timeout); out = new DataOutputStream(new BufferedOutputStream( pair.out, HdfsConstants.SMALL_BUFFER_SIZE)); in = new DataInputStream(pair.in); if (LOG.isDebugEnabled()) { LOG.debug("write to " + datanodes[j] + ": " + Op.RSYNC_CHUNKS_CHECKSUM + ", block=" + block); } // get block MD5 new Sender(out).chunksChecksum(block, lb.getBlockToken()); final BlockOpResponseProto reply = BlockOpResponseProto .parseFrom(PBHelper.vintPrefixed(in)); if (reply.getStatus() != Status.SUCCESS) { if (reply.getStatus() == Status.ERROR_ACCESS_TOKEN) { throw new InvalidBlockTokenException(); } else { throw new IOException("Bad response " + reply + " for block " + block + " from datanode " + datanodes[j]); } } OpChunksChecksumResponseProto checksumData = reply .getChunksChecksumResponse(); // read byte-per-checksum final int bpc = checksumData.getBytesPerCrc(); if (i == 0) { // first block bytesPerCRC = bpc; } else if (bpc != bytesPerCRC) { throw new IOException( "Byte-per-checksum not matched: bpc=" + bpc + " but bytesPerCRC=" + bytesPerCRC); } // read crc-per-block final long cpb = checksumData.getCrcPerBlock(); if (srcFileInfo.getBlocks().size() > 1 && i == 0) { crcPerBlock = cpb; } final List<ChecksumPairProto> checksums = checksumData.getChecksumsList(); LOG.warn("checksum size : "+checksumData.getBytesPerChunk()); LOG.warn("checksum counts : "+checksumData.getChunksPerBlock()); LOG.warn("checksum list:"); for(ChecksumPairProto cs : checksums){ final MD5Hash md5s = new MD5Hash(cs.getMd5().toByteArray()); LOG.warn("Simple CS : "+ Integer.toHexString(cs.getSimple())+ " ; MD5 CS : "+md5s); fileInfo.getBlocks().get(i).getChecksums().add( new ChecksumPair(cs.getSimple(),md5s.getDigest())); } // read md5 final MD5Hash md5 = new MD5Hash(checksumData.getMd5() .toByteArray()); md5.write(md5out); LOG.warn("Block CS : "+md5); // read crc-type final DataChecksum.Type ct; if (checksumData.hasCrcType()) { ct = PBHelper.convert(checksumData.getCrcType()); } else { LOG.debug("Retrieving checksum from an earlier-version DataNode: " + "inferring checksum by reading first byte"); ct = inferChecksumTypeByReading(clientName, socketFactory, socketTimeout, lb, datanodes[j], encryptionKey, connectToDnViaHostname); } if (i == 0) { // first block crcType = ct; } else if (crcType != DataChecksum.Type.MIXED && crcType != ct) { // if crc types are mixed in a file crcType = DataChecksum.Type.MIXED; } done = true; if (LOG.isDebugEnabled()) { if (i == 0) { LOG.debug("set bytesPerCRC=" + bytesPerCRC + ", crcPerBlock=" + crcPerBlock); } LOG.debug("got reply from " + datanodes[j] + ": md5=" + md5); } } catch (InvalidBlockTokenException ibte) { if (i > lastRetriedIndex) { if (LOG.isDebugEnabled()) { LOG.debug("Got access token error in response to OP_BLOCK_CHECKSUM " + "for file " + fileInfo.getFilepath() + " for block " + block + " from datanode " + datanodes[j] + ". Will retry the block once."); } lastRetriedIndex = i; done = true; // actually it's not done; but we'll retry i--; // repeat at i-th block refetchBlocks = true; break; } } catch (IOException ie) { LOG.warn("src=" + fileInfo.getFilepath() + ", datanodes[" + j + "]=" + datanodes[j], ie); } finally { IOUtils.closeStream(in); IOUtils.closeStream(out); } } if (!done) { throw new IOException("Fail to get block MD5 for " + block); } } } private void calculateSegments(){ LOG.warn("calculateSegments start"); List<Integer> simples = new LinkedList<Integer>(); List<byte[]> md5s = new LinkedList<byte[]>(); for(BlockInfo bi : dstFileInfo.getBlocks()){ for(ChecksumPair cp : bi.getChecksums()){ simples.add(cp.getSimple()); md5s.add(cp.getMd5()); } } //去掉最后一个chunk的checksum,防止其未达到chunksize simples.remove(simples.size()-1); md5s.remove(md5s.size()-1); for(BlockInfo bi : srcFileInfo.getBlocks()){ DatanodeInfo[] datanodes = bi.getLocatedBlock().getLocations(); final int timeout = 3000 * datanodes.length + socketTimeout; for (int j = 0; j < datanodes.length; j++) { DataOutputStream out = null; DataInputStream in = null; try { // connect to a datanode IOStreamPair pair = connectToDN(socketFactory, connectToDnViaHostname, getDataEncryptionKey(), datanodes[j], timeout); out = new DataOutputStream(new BufferedOutputStream( pair.out, HdfsConstants.SMALL_BUFFER_SIZE)); in = new DataInputStream(pair.in); // call calculateSegments new Sender(out).calculateSegments( bi.getLocatedBlock().getBlock(), bi.getLocatedBlock().getBlockToken(), clientName, simples, md5s); //read reply final BlockOpResponseProto reply = BlockOpResponseProto .parseFrom(PBHelper.vintPrefixed(in)); if (reply.getStatus() != Status.SUCCESS) { if (reply.getStatus() == Status.ERROR_ACCESS_TOKEN) { throw new InvalidBlockTokenException(); } else { throw new IOException("Bad response " + reply + " for block " + bi.getLocatedBlock().getBlock() + " from datanode " + datanodes[j]); } } OpCalculateSegmentsResponseProto segmentsData = reply .getCalculateSegmentsResponse(); LinkedList<SegmentProto> segments = new LinkedList<SegmentProto>(segmentsData.getSegmentsList()); LOG.warn("Block "+bi.getLocatedBlock().getBlock().getBlockName()+ " divide into "+segments.size()+" segments."); bi.setSegments(segments); break; } catch (InvalidBlockTokenException ibte) { } catch (IOException ie) { }finally { IOUtils.closeStream(in); IOUtils.closeStream(out); } } } } /** * 传送一个block所需的segments,与updateBlock配合使用 * @param blockInfo 所需要传送的block信息 * @param addedBlock 所传送的block在目标文件中对应的block * @throws AccessControlException * @throws FileNotFoundException * @throws UnresolvedLinkException * @throws IOException */ private void sendSegments(BlockInfo blockInfo,LocatedBlock addedBlock) throws AccessControlException, FileNotFoundException, UnresolvedLinkException, IOException{ LOG.warn("sendSegments for block "+blockInfo.getLocatedBlock().getBlock()+" start."); long blockSize = dstNamenode.getFileInfo(dstFileInfo.getFilepath()).getBlockSize(); long chunksPerBlock = blockSize/chunkSize; if(dstFileInfo.getBlocks().size() != srcFileInfo.getBlocks().size()){ throw new IOException("newFileInfo size not match srcFileInfo."); } for(int j = 0 ; j < blockInfo.getSegments().size() ; j++){ SegmentProto segment = blockInfo.getSegments().get(j); DatanodeInfo[] srcDatanodes = null; DatanodeInfo[] dstDatanodes = null; LocatedBlock block = null; String segmentName = null; String blockDirName = addedBlock.getBlock().getBlockId() +"_"+addedBlock.getBlock().getGenerationStamp(); long offset = 0; long length = 0; //如果dstFile中没有这个segment if(segment.getIndex() == -1){ srcDatanodes = blockInfo.getLocatedBlock().getLocations(); block = blockInfo.getLocatedBlock(); offset = segment.getOffset(); length = segment.getLength(); segmentName = String.format("%064d", offset)+"_"+String.format("%064d", length); dstDatanodes = addedBlock.getLocations(); LOG.warn("SendSegment from srcFile "+ "index : "+segment.getIndex()+ "; offset : "+segment.getOffset()+ "; length : "+segment.getLength()); }else{ srcDatanodes = dstFileInfo.getBlocks() .get((int)(segment.getIndex()/chunksPerBlock)) .getLocatedBlock().getLocations(); block = dstFileInfo.getBlocks() .get((int)(segment.getIndex()/chunksPerBlock)) .getLocatedBlock(); offset = segment.getIndex()%chunksPerBlock*chunkSize; length = chunkSize; segmentName = String.format("%064d", segment.getOffset())+"_"+ String.format("%064d", segment.getLength()); dstDatanodes = addedBlock.getLocations(); LOG.warn("SendSegment from dstFile "+ "index : "+segment.getIndex()+ "; offset : "+segment.getOffset()+ "; length : "+segment.getLength()); } final int timeout = 3000 + socketTimeout; for (int k = 0; k < srcDatanodes.length; k++) { DataOutputStream out = null; DataInputStream in = null; try { // connect to a datanode IOStreamPair pair = connectToDN(socketFactory, connectToDnViaHostname, getDataEncryptionKey(), srcDatanodes[k], timeout); out = new DataOutputStream(new BufferedOutputStream( pair.out, HdfsConstants.SMALL_BUFFER_SIZE)); in = new DataInputStream(pair.in); // call sendSegment new Sender(out).sendSegment(block.getBlock(), block.getBlockToken(), clientName, segment.getOffset(), segment.getLength(), true, true, segmentName, blockDirName, dstDatanodes); //read reply final BlockOpResponseProto reply = BlockOpResponseProto .parseFrom(PBHelper.vintPrefixed(in)); if (reply.getStatus() != Status.SUCCESS) { LOG.warn("Bad response " + reply + " for block " + blockInfo.getLocatedBlock().getBlock() + " from datanode " + srcDatanodes[k]); }else{ break; } } catch (InvalidBlockTokenException ibte) { } catch (IOException ie) { }finally { IOUtils.closeStream(in); IOUtils.closeStream(out); } } }//for segment } /** * 用于构建新的block * @param block 目标文件块 * @throws IOException * @throws UnresolvedLinkException * @throws FileNotFoundException * @throws AccessControlException */ private void updateBlock(LocatedBlock block) throws AccessControlException, FileNotFoundException, UnresolvedLinkException, IOException{ LOG.warn("updateBlock for block "+block.getBlock()+" start."); DatanodeInfo[] datanodes = block.getLocations(); final int timeout = 3000 * datanodes.length + socketTimeout; for (int j = 0; j < datanodes.length; j++) { DataOutputStream out = null; DataInputStream in = null; try { // connect to a datanode IOStreamPair pair = connectToDN(socketFactory, connectToDnViaHostname, getDataEncryptionKey(), datanodes[j], timeout); out = new DataOutputStream(new BufferedOutputStream( pair.out, HdfsConstants.SMALL_BUFFER_SIZE)); in = new DataInputStream(pair.in); // call updateBlock LOG.warn("updateBlock "+block.getBlock()); new Sender(out).updateBlock(block.getBlock(), block.getBlockToken()); //read reply final BlockOpResponseProto reply = BlockOpResponseProto .parseFrom(PBHelper.vintPrefixed(in)); if (reply.getStatus() != Status.SUCCESS) { LOG.warn("Bad response " + reply + " for block " + block.getBlock() + " from datanode " + datanodes[j]); } } catch (InvalidBlockTokenException ibte) { } catch (IOException ie) { }finally { IOUtils.closeStream(in); IOUtils.closeStream(out); } } } private LocatedBlocks callGetBlockLocations(ClientProtocol namenode, String src, long start, long length, boolean supportMetaInfo) throws IOException { try { return namenode.getBlockLocations(src, start, length); } catch (RemoteException re) { throw re.unwrapRemoteException(AccessControlException.class, FileNotFoundException.class); } } /** * Connect to the given datanode's datantrasfer port, and return the * resulting IOStreamPair. This includes encryption wrapping, etc. */ private IOStreamPair connectToDN(SocketFactory socketFactory, boolean connectToDnViaHostname, DataEncryptionKey encryptionKey, DatanodeInfo dn, int timeout) throws IOException { boolean success = false; Socket sock = null; try { sock = socketFactory.createSocket(); String dnAddr = dn.getXferAddr(connectToDnViaHostname); if (LOG.isDebugEnabled()) { LOG.debug("Connecting to datanode " + dnAddr); } NetUtils.connect(sock, NetUtils.createSocketAddr(dnAddr), timeout); sock.setSoTimeout(timeout); OutputStream unbufOut = NetUtils.getOutputStream(sock); InputStream unbufIn = NetUtils.getInputStream(sock); IOStreamPair ret; if (encryptionKey != null) { ret = DataTransferEncryptor.getEncryptedStreams(unbufOut, unbufIn, encryptionKey); } else { ret = new IOStreamPair(unbufIn, unbufOut); } success = true; return ret; } finally { if (!success) { IOUtils.closeSocket(sock); } } } /** * Infer the checksum type for a replica by sending an OP_READ_BLOCK for the * first byte of that replica. This is used for compatibility with older * HDFS versions which did not include the checksum type in * OpBlockChecksumResponseProto. * * @param in * input stream from datanode * @param out * output stream to datanode * @param lb * the located block * @param clientName * the name of the DFSClient requesting the checksum * @param dn * the connected datanode * @return the inferred checksum type * @throws IOException * if an error occurs */ private Type inferChecksumTypeByReading(String clientName, SocketFactory socketFactory, int socketTimeout, LocatedBlock lb, DatanodeInfo dn, DataEncryptionKey encryptionKey, boolean connectToDnViaHostname) throws IOException { IOStreamPair pair = connectToDN(socketFactory, connectToDnViaHostname, encryptionKey, dn, socketTimeout); try { DataOutputStream out = new DataOutputStream( new BufferedOutputStream(pair.out, HdfsConstants.SMALL_BUFFER_SIZE)); DataInputStream in = new DataInputStream(pair.in); new Sender(out).readBlock(lb.getBlock(), lb.getBlockToken(), clientName, 0, 1, true, CachingStrategy.newDefaultStrategy()); final BlockOpResponseProto reply = BlockOpResponseProto .parseFrom(PBHelper.vintPrefixed(in)); if (reply.getStatus() != Status.SUCCESS) { if (reply.getStatus() == Status.ERROR_ACCESS_TOKEN) { throw new InvalidBlockTokenException(); } else { throw new IOException("Bad response " + reply + " trying to read " + lb.getBlock() + " from datanode " + dn); } } return PBHelper.convert(reply.getReadOpChecksumInfo().getChecksum() .getType()); } finally { IOUtils.cleanup(null, pair.in, pair.out); } } /** * 新建一个临时文件,文件名为dstFilePath+".rsync",在这个文件中恢复新的文件内容,再用这个文件替代原有文件 * @param filePath * @param src * @throws IOException * TODO:应该让重建的所有block尽量存放在dstFile对应block所在datanode上 * @throws InterruptedException */ private void updateDstFile() throws IOException, InterruptedException { String tmpFilePath = dstFileInfo.getFilepath()+".rsync"; //dstDfs.create(new Path(tmpFilePath)).close(); short replication = Short.parseShort(conf.get("dfs.replication","1")); long blockSize = Long.parseLong(conf.get("dfs.blocksize","134217728")); EnumSetWritable<CreateFlag> flag = new EnumSetWritable<CreateFlag>(EnumSet.of(CreateFlag.CREATE,CreateFlag.OVERWRITE)); HdfsFileStatus status = dstNamenode.create( tmpFilePath, FsPermission.getFileDefault(), clientName, flag, true/*createParent*/, replication, blockSize); long fileId = status.getFileId(); //TODO:用一次append操作只是为了能够得到lease //LocatedBlock lastBlock = srcNamenode.append(tmpFilePath, clientName);//文件没有内容的时候,append操作返回的是null!! //if(lastBlock != null) LOG.warn("append empty file return " + lastBlock.getBlock()); //else LOG.warn("append empty file return null"); ExtendedBlock lastBlock = null; for(int i = 0 ; i < srcFileInfo.getBlocks().size() ; i++){ LocatedBlock currentBlock = dstNamenode.addBlock(tmpFilePath, clientName, lastBlock, (DatanodeInfo[])null, fileId, (String[])null); LOG.warn("Add new block "+currentBlock.getBlock()); //sendSegments and updateBlock sendSegments(srcFileInfo.getBlocks().get(i),currentBlock); updateBlock(currentBlock); lastBlock = dstNamenode.getBlockLocations(tmpFilePath,i*blockSize, 1).get(0).getBlock(); LOG.warn("lastBlock "+lastBlock.getBlockName()+" size "+lastBlock.getNumBytes()); } int count = 0; boolean completed = false; while((completed = dstNamenode.complete(tmpFilePath, clientName, lastBlock, fileId)) != true && count < 10){ LOG.warn("File "+tmpFilePath+" can not complete"); count++; Thread.sleep(1000); } LOG.warn("File "+tmpFilePath+" complete "+completed); } /** * Get server default values for a number of configuration params. * * @see ClientProtocol#getServerDefaults() */ public FsServerDefaults getServerDefaults() throws IOException { long now = Time.now(); if (now - serverDefaultsLastUpdate > SERVER_DEFAULTS_VALIDITY_PERIOD) { serverDefaults = srcNamenode.getServerDefaults(); serverDefaultsLastUpdate = now; } return serverDefaults; } /** * @return true if data sent between this client and DNs should be * encrypted, false otherwise. * @throws IOException * in the event of error communicating with the NN */ boolean shouldEncryptData() throws IOException { FsServerDefaults d = getServerDefaults(); return d == null ? false : d.getEncryptDataTransfer(); } @InterfaceAudience.Private public DataEncryptionKey getDataEncryptionKey() throws IOException { if (shouldEncryptData()) { synchronized (this) { if (encryptionKey == null || encryptionKey.expiryDate < Time.now()) { LOG.debug("Getting new encryption token from NN"); encryptionKey = srcNamenode.getDataEncryptionKey(); } return encryptionKey; } } else { return null; } } public boolean isMetaInfoSupported(ProtocolProxy<ClientProtocol> proxy) throws IOException { return proxy != null && proxy.isMethodSupported("openAndFetchMetaInfo", String.class, long.class, long.class); } public void printFileInfo(FileInfo fileInfo){ LOG.warn("File Info of "+fileInfo.getFilepath()); LOG.warn("\tblock count : "+fileInfo.getBlocks().size()); for(BlockInfo bi : fileInfo.getBlocks()){ LOG.warn("\tblock id : "+bi.getLocatedBlock().getBlock().getBlockId()+ "; genstamp : "+bi.getLocatedBlock().getBlock().getGenerationStamp()+ "; checksum size :"+bi.getChecksums().size()+ "; segment size : "+bi.getSegments().size()); } } public void run() throws IOException, InterruptedException { getSDFileInfo(); getSDFileChecksum(); calculateSegments(); //printFileInfo(srcFileInfo); //printFileInfo(dstFileInfo); updateDstFile(); } } private void getNameNode() throws IOException { if (nameNodeAddr != null) { // The lock is to make sure namenode, namenodeProtocolProxy // and rpcNamenode are consistent ultimately. There is still // a small window where another thread can see inconsistent // version of namenodeProtocolProxy and namenode. But it will // only happen during the transit time when name-node upgrade // and the exception will likely to be resolved after a retry. // synchronized (namenodeProxySyncObj) { this.srcNamenode = srcDfs.getClient().getNamenode(); this.dstNamenode = dstDfs.getClient().getNamenode(); } } } private static void printUsage() { HelpFormatter formatter = new HelpFormatter(); Options options = new Options(); formatter.printHelp("Usage : RsyncCopy [options] <srcs....> <dst>", options); } protected void checkOpen() throws IOException { if (!clientRunning) { IOException result = new IOException("Filesystem closed"); throw result; } } public void run() throws IOException, InterruptedException { getNameNode(); long uniqueId = 0; RsyncCopyFile testCopyFile = new RsyncCopyFile( srcNamenode,srcNamenodeProtocolProxy,srcPath, dstNamenode,dstNamenodeProtocolProxy,dstPath, conf,stats,uniqueId ); testCopyFile.run(); } public static void main(String args[]) throws Exception { if (args.length < 2) { printUsage(); } RsyncCopy rc = new RsyncCopy("/test","/test"); rc.run(); System.exit(0); } }
hadoop-tools/hadoop-rsynccopy/src/main/java/org/apache/hadoop/tools/RsyncCopy.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.tools; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_USE_DN_HOSTNAME; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_USE_DN_HOSTNAME_DEFAULT; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.URI; import java.util.ArrayList; import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.*; import javax.net.SocketFactory; import javax.swing.text.Segment; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CreateFlag; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FsServerDefaults; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.UnresolvedLinkException; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.hdfs.DFSClient.Conf; import org.apache.hadoop.hdfs.LeaseRenewer; import org.apache.hadoop.hdfs.protocol.AlreadyBeingCreatedException; import org.apache.hadoop.hdfs.protocol.ClientProtocol; import org.apache.hadoop.hdfs.protocol.DatanodeInfo; import org.apache.hadoop.hdfs.protocol.ExtendedBlock; import org.apache.hadoop.hdfs.protocol.HdfsConstants; import org.apache.hadoop.hdfs.protocol.HdfsFileStatus; import org.apache.hadoop.hdfs.protocol.LocatedBlock; import org.apache.hadoop.hdfs.protocol.LocatedBlocks; import org.apache.hadoop.hdfs.security.token.block.DataEncryptionKey; import org.apache.hadoop.hdfs.security.token.block.InvalidBlockTokenException; import org.apache.hadoop.hdfs.server.common.HdfsServerConstants; import org.apache.hadoop.hdfs.server.datanode.BlockMetadataHeader; import org.apache.hadoop.hdfs.server.datanode.CachingStrategy; import org.apache.hadoop.hdfs.server.namenode.NameNode; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.io.EnumSetWritable; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.io.MD5Hash; import org.apache.hadoop.io.retry.RetryPolicies; import org.apache.hadoop.io.retry.RetryPolicy; import org.apache.hadoop.io.retry.RetryProxy; import org.apache.hadoop.ipc.ProtocolProxy; import org.apache.hadoop.ipc.RemoteException; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.AccessControlException; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.util.DataChecksum; import org.apache.hadoop.util.Time; import org.apache.hadoop.util.DataChecksum.Type; /* new added */ import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.hdfs.protocol.datatransfer.DataTransferEncryptor; import org.apache.hadoop.hdfs.protocol.datatransfer.DataTransferProtocol; import org.apache.hadoop.hdfs.protocol.datatransfer.IOStreamPair; import org.apache.hadoop.hdfs.protocol.datatransfer.Op; import org.apache.hadoop.hdfs.protocol.datatransfer.Sender; import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BlockOpResponseProto; import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.ChecksumPairProto; import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpBlockChecksumResponseProto; import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCalculateSegmentsResponseProto; import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpChunksChecksumResponseProto; import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.SegmentProto; import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.Status; import org.apache.hadoop.hdfs.protocolPB.PBHelper; /** * rsynccopy复制一个文件的工作过程如下 : * * 1) 从NN获取文件所有block的位置,包括源文件src和目标文件dst的。 * * 2) 从src和dst的所有block中获取checksum列表。 * * 3) 比对后,把dst中部分block的checksum列表传递给src中的部分DN。 * * 4) 得到checksum列表的DN计算block差异,回传给rsynccopy。 * * 5) rsynccopy根据收到的信息,控制DN把block差异传递给需要的DN。 * * 6) DN之间传递block差异,并将差异存到本地的临时文件夹。 * * 7)rsynccopy确认所有差异传递完毕后,控制DN将block差异合成最后的文件 * **/ public class RsyncCopy { public static final long SERVER_DEFAULTS_VALIDITY_PERIOD = 60 * 60 * 1000L; // 1 // hour public static final Log LOG = LogFactory.getLog(RsyncCopy.class); public ClientProtocol srcNamenode; public ClientProtocol dstNamenode; // Namenode proxy that supports method-based compatibility public ProtocolProxy<ClientProtocol> srcNamenodeProtocolProxy = null; public ProtocolProxy<ClientProtocol> dstNamenodeProtocolProxy = null; static Random r = new Random(); String clientName; Configuration conf; SocketFactory socketFactory; FileSystem.Statistics stats; private long namenodeVersion = ClientProtocol.versionID; protected Integer dataTransferVersion = -1; protected volatile int namespaceId = 0; InetAddress localHost; InetSocketAddress nameNodeAddr; // int ipTosValue = NetUtils.NOT_SET_IP_TOS; volatile boolean clientRunning = true; private ClientProtocol rpcNamenode; int socketTimeout; int namenodeRPCSocketTimeout; public Object namenodeProxySyncObj = new Object(); private Path srcPath; private Path dstPath; private DistributedFileSystem srcDfs; private DistributedFileSystem dstDfs; UserGroupInformation ugi; volatile long lastLeaseRenewal; private String authority; private DataEncryptionKey encryptionKey; private volatile FsServerDefaults serverDefaults; private volatile long serverDefaultsLastUpdate; private boolean connectToDnViaHostname; private LeaseRenewer renewer; public RsyncCopy(String srcPath,String dstPath) throws IOException { conf = new Configuration(); this.srcPath = new Path(srcPath); this.dstPath = new Path(dstPath); srcDfs = (DistributedFileSystem)this.srcPath.getFileSystem(conf); dstDfs = (DistributedFileSystem)this.dstPath.getFileSystem(conf); RsyncCopyInit(NameNode.getAddress(conf), null, null,0); } /** * Create a new DFSClient connected to the given nameNodeAddr or * rpcNamenode. Exactly one of nameNodeAddr or rpcNamenode must be null. */ private void RsyncCopyInit(InetSocketAddress nameNodeAddr, ClientProtocol rpcNamenode, FileSystem.Statistics stats, long uniqueId) throws IOException { this.stats = stats; this.connectToDnViaHostname = conf.getBoolean( DFS_CLIENT_USE_DN_HOSTNAME, DFS_CLIENT_USE_DN_HOSTNAME_DEFAULT); this.socketFactory = NetUtils.getSocketFactory(conf, ClientProtocol.class); this.localHost = InetAddress.getLocalHost(); String taskId = conf.get("mapreduce.task.attempt.id"); if (taskId != null) { this.clientName = "RsyncCopy_" + taskId + "_" + r.nextInt() + "_" + Thread.currentThread().getId(); } else { this.clientName = "RsyncCopy_" + r.nextInt() + ((uniqueId == 0) ? "" : "_" + uniqueId); } if (nameNodeAddr != null && rpcNamenode == null) { this.nameNodeAddr = nameNodeAddr; getNameNode(); } else { throw new IllegalArgumentException( "Expecting exactly one of nameNodeAddr and rpcNamenode being null: " + "nameNodeAddr=" + nameNodeAddr + ", rpcNamenode=" + rpcNamenode); } this.ugi = UserGroupInformation.getCurrentUser(); URI nameNodeUri = NameNode.getUri(NameNode.getAddress(conf)); this.authority = nameNodeUri == null ? "null" : nameNodeUri .getAuthority(); this.socketTimeout = conf.getInt("dfs.client.socket-timeout", HdfsServerConstants.READ_TIMEOUT); this.namenodeRPCSocketTimeout = 60 * 1000; renewer = new LeaseRenewer(); renewer.setClientName(clientName); renewer.setNamenode(dstNamenode); //只需要更新dstNamenode的lease就可以了,因为并没有更改src的文件内容 Thread renewerThread = new Thread(renewer); renewerThread.start(); } private class LeaseRenewer implements Runnable { private long lastRenewalTime; /** A fixed lease renewal time period in milliseconds */ private long renewal = HdfsConstants.LEASE_SOFTLIMIT_PERIOD/2; private String clientName; private ClientProtocol namenode; public void setClientName(String clientName){ this.clientName = clientName; lastRenewalTime = Time.now(); } public void setNamenode(ClientProtocol namenode){ this.namenode = namenode; } public void run(){ try{ while(true){ namenode.renewLease(clientName); Thread.sleep(renewal); } }catch(IOException e){ } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private class RsyncCopyFile{ private Path srcPath; private Path dstPath; public ClientProtocol srcNamenode; public ClientProtocol dstNamenode; // Namenode proxy that supports method-based compatibility public ProtocolProxy<ClientProtocol> srcNamenodeProtocolProxy = null; public ProtocolProxy<ClientProtocol> dstNamenodeProtocolProxy = null; final String clientName; Configuration conf; SocketFactory socketFactory; final FileSystem.Statistics stats; private long namenodeVersion = ClientProtocol.versionID; protected Integer dataTransferVersion = -1; protected volatile int namespaceId = 0; // int ipTosValue = NetUtils.NOT_SET_IP_TOS; volatile boolean clientRunning = true; private ClientProtocol rpcNamenode; int socketTimeout; int namenodeRPCSocketTimeout; final UserGroupInformation ugi; volatile long lastLeaseRenewal; private final String authority; private DataEncryptionKey encryptionKey; private volatile FsServerDefaults serverDefaults; private volatile long serverDefaultsLastUpdate; private boolean connectToDnViaHostname; private int chunkSize; private class ChecksumPair{ private Integer simple; private byte[] md5; public ChecksumPair(Integer simple,byte[] bs){ this.simple = simple; this.md5 = bs; } public Integer getSimple() { return simple; } public void setSimple(Integer simple) { this.simple = simple; } public byte[] getMd5() { return md5; } public void setMd5(byte[] md5) { this.md5 = md5; } } private class BlockInfo{ private LocatedBlock locatedBlock; private LinkedList<ChecksumPair> checksums; private LinkedList<SegmentProto> segments; public BlockInfo(LocatedBlock locatedBlock){ this.locatedBlock = locatedBlock; this.checksums = new LinkedList<ChecksumPair>(); this.segments = new LinkedList<SegmentProto>(); } public BlockInfo(LocatedBlock locatedBlock,LinkedList<ChecksumPair> checksums,LinkedList<SegmentProto> segments){ this.locatedBlock = locatedBlock; this.checksums = checksums; this.segments = segments; } public LocatedBlock getLocatedBlock() { return locatedBlock; } public void setLocatedBlock(LocatedBlock locatedBlock) { this.locatedBlock = locatedBlock; } public List<ChecksumPair> getChecksums() { return checksums; } public void setChecksums(LinkedList<ChecksumPair> checksums) { this.checksums = checksums; } public void addChecksum(ChecksumPair checksum){ this.checksums.add(checksum); } public LinkedList<SegmentProto> getSegments() { return segments; } public void setSegments(LinkedList<SegmentProto> segments) { this.segments = segments; } } private class FileInfo{ private List<BlockInfo> blocks; private String filepath; private long fileSize; public FileInfo(String filepath){ this.setFilepath(filepath); this.blocks = new LinkedList<BlockInfo>(); } public List<BlockInfo> getBlocks() { return blocks; } public void setBlocks(List<BlockInfo> blocks) { this.blocks = blocks; } public void addBlock(BlockInfo block){ this.blocks.add(block); } public String getFilepath() { return filepath; } public void setFilepath(String filepath) { this.filepath = filepath; } public long getFileSize() { return fileSize; } public void setFileSize(long fileSize) { this.fileSize = fileSize; } } private FileInfo srcFileInfo; private FileInfo dstFileInfo; //private FileInfo newFileInfo; RsyncCopyFile(ClientProtocol srcNamenode,ProtocolProxy<ClientProtocol> srcNamenodeProtocolProxy,Path srcPath, ClientProtocol dstNamenode,ProtocolProxy<ClientProtocol> dstNamenodeProtocolProxy,Path dstPath, Configuration conf, FileSystem.Statistics stats, long uniqueId) throws IOException { this.srcNamenode = srcNamenode; this.srcNamenodeProtocolProxy = srcNamenodeProtocolProxy; this.srcPath = srcPath; this.dstNamenode = dstNamenode; this.dstNamenodeProtocolProxy = dstNamenodeProtocolProxy; this.dstPath = dstPath; this.conf = conf; this.stats = stats; this.connectToDnViaHostname = conf.getBoolean( DFS_CLIENT_USE_DN_HOSTNAME, DFS_CLIENT_USE_DN_HOSTNAME_DEFAULT); this.socketFactory = NetUtils.getSocketFactory(conf, ClientProtocol.class); String taskId = conf.get("mapreduce.task.attempt.id"); if (taskId != null) { this.clientName = "RsyncCopy_" + taskId + "_" + r.nextInt() + "_" + Thread.currentThread().getId(); } else { this.clientName = "RsyncCopy_" + r.nextInt() + ((uniqueId == 0) ? "" : "_" + uniqueId); } this.ugi = UserGroupInformation.getCurrentUser(); URI nameNodeUri = NameNode.getUri(NameNode.getAddress(conf)); this.authority = nameNodeUri == null ? "null" : nameNodeUri .getAuthority(); this.socketTimeout = conf.getInt("dfs.client.socket-timeout", HdfsServerConstants.READ_TIMEOUT); this.namenodeRPCSocketTimeout = 60 * 1000; this.chunkSize = 1024*1024; } /** * Get the source file blocks information from NN * Get the destination file blocks information from NN * Create the new temp file in dst file system. */ void getSDFileInfo() throws IOException { LocatedBlocks srcLocatedBlocks = callGetBlockLocations( srcNamenode,srcPath.toString(),0,Long.MAX_VALUE, isMetaInfoSupported(srcNamenodeProtocolProxy)); if (srcLocatedBlocks == null) { throw new IOException( "Null block locations, mostly because non-existent file " + srcPath.toString()); } LocatedBlocks dstLocatedBlocks = callGetBlockLocations( dstNamenode,dstPath.toString(),0,Long.MAX_VALUE, isMetaInfoSupported(dstNamenodeProtocolProxy)); if (dstLocatedBlocks == null) { throw new IOException( "Null block locations, mostly because non-existent file " + dstPath.toString()); } this.srcFileInfo = new FileInfo(srcPath.toString()); this.dstFileInfo = new FileInfo(dstPath.toString()); this.srcFileInfo.setFileSize(srcLocatedBlocks.getFileLength()); this.dstFileInfo.setFileSize(dstLocatedBlocks.getFileLength()); for(LocatedBlock lb : srcLocatedBlocks.getLocatedBlocks()){ srcFileInfo.addBlock(new BlockInfo(lb)); } for(LocatedBlock lb : dstLocatedBlocks.getLocatedBlocks()){ dstFileInfo.addBlock(new BlockInfo(lb)); } //this.newFileInfo = createNewFile(dstPath.toString()+".rsync",srcFileInfo); } /** * Get the checksum of a file. * * @param src * The file path * @return The checksum * @see DistributedFileSystem#getFileChecksum(Path) */ void getSDFileChecksum() throws IOException { checkOpen(); getFileChecksum(dataTransferVersion, srcFileInfo, srcNamenode, srcNamenodeProtocolProxy, socketFactory, socketTimeout); getFileChecksum(dataTransferVersion, dstFileInfo, dstNamenode, dstNamenodeProtocolProxy, socketFactory, socketTimeout); } /** * Get the checksum of a file. * * @param src * The file path * @return The checksum */ public void getFileChecksum(int dataTransferVersion, FileInfo fileInfo, ClientProtocol namenode, ProtocolProxy<ClientProtocol> namenodeProxy, SocketFactory socketFactory, int socketTimeout) throws IOException { LOG.warn("getFileShecksum start"); final DataOutputBuffer md5out = new DataOutputBuffer(); int namespaceId = 0; boolean refetchBlocks = false; int lastRetriedIndex = -1; dataTransferVersion = DataTransferProtocol.DATA_TRANSFER_VERSION; int bytesPerCRC = -1; DataChecksum.Type crcType = DataChecksum.Type.DEFAULT; long crcPerBlock = 0; // get block checksum for each block for (int i = 0; i < srcFileInfo.getBlocks().size(); i++) { LocatedBlock lb = srcFileInfo.getBlocks().get(i).locatedBlock; final ExtendedBlock block = lb.getBlock(); final DatanodeInfo[] datanodes = lb.getLocations(); // try each datanode location of the block final int timeout = 3000 * datanodes.length + socketTimeout; boolean done = false; for (int j = 0; !done && j < datanodes.length; j++) { DataOutputStream out = null; DataInputStream in = null; try { // connect to a datanode IOStreamPair pair = connectToDN(socketFactory, connectToDnViaHostname, getDataEncryptionKey(), datanodes[j], timeout); out = new DataOutputStream(new BufferedOutputStream( pair.out, HdfsConstants.SMALL_BUFFER_SIZE)); in = new DataInputStream(pair.in); if (LOG.isDebugEnabled()) { LOG.debug("write to " + datanodes[j] + ": " + Op.RSYNC_CHUNKS_CHECKSUM + ", block=" + block); } // get block MD5 new Sender(out).chunksChecksum(block, lb.getBlockToken()); final BlockOpResponseProto reply = BlockOpResponseProto .parseFrom(PBHelper.vintPrefixed(in)); if (reply.getStatus() != Status.SUCCESS) { if (reply.getStatus() == Status.ERROR_ACCESS_TOKEN) { throw new InvalidBlockTokenException(); } else { throw new IOException("Bad response " + reply + " for block " + block + " from datanode " + datanodes[j]); } } OpChunksChecksumResponseProto checksumData = reply .getChunksChecksumResponse(); // read byte-per-checksum final int bpc = checksumData.getBytesPerCrc(); if (i == 0) { // first block bytesPerCRC = bpc; } else if (bpc != bytesPerCRC) { throw new IOException( "Byte-per-checksum not matched: bpc=" + bpc + " but bytesPerCRC=" + bytesPerCRC); } // read crc-per-block final long cpb = checksumData.getCrcPerBlock(); if (srcFileInfo.getBlocks().size() > 1 && i == 0) { crcPerBlock = cpb; } final List<ChecksumPairProto> checksums = checksumData.getChecksumsList(); LOG.warn("checksum size : "+checksumData.getBytesPerChunk()); LOG.warn("checksum counts : "+checksumData.getChunksPerBlock()); LOG.warn("checksum list:"); for(ChecksumPairProto cs : checksums){ final MD5Hash md5s = new MD5Hash(cs.getMd5().toByteArray()); LOG.warn("Simple CS : "+ Integer.toHexString(cs.getSimple())+ " ; MD5 CS : "+md5s); fileInfo.getBlocks().get(i).getChecksums().add( new ChecksumPair(cs.getSimple(),md5s.getDigest())); } // read md5 final MD5Hash md5 = new MD5Hash(checksumData.getMd5() .toByteArray()); md5.write(md5out); LOG.warn("Block CS : "+md5); // read crc-type final DataChecksum.Type ct; if (checksumData.hasCrcType()) { ct = PBHelper.convert(checksumData.getCrcType()); } else { LOG.debug("Retrieving checksum from an earlier-version DataNode: " + "inferring checksum by reading first byte"); ct = inferChecksumTypeByReading(clientName, socketFactory, socketTimeout, lb, datanodes[j], encryptionKey, connectToDnViaHostname); } if (i == 0) { // first block crcType = ct; } else if (crcType != DataChecksum.Type.MIXED && crcType != ct) { // if crc types are mixed in a file crcType = DataChecksum.Type.MIXED; } done = true; if (LOG.isDebugEnabled()) { if (i == 0) { LOG.debug("set bytesPerCRC=" + bytesPerCRC + ", crcPerBlock=" + crcPerBlock); } LOG.debug("got reply from " + datanodes[j] + ": md5=" + md5); } } catch (InvalidBlockTokenException ibte) { if (i > lastRetriedIndex) { if (LOG.isDebugEnabled()) { LOG.debug("Got access token error in response to OP_BLOCK_CHECKSUM " + "for file " + fileInfo.getFilepath() + " for block " + block + " from datanode " + datanodes[j] + ". Will retry the block once."); } lastRetriedIndex = i; done = true; // actually it's not done; but we'll retry i--; // repeat at i-th block refetchBlocks = true; break; } } catch (IOException ie) { LOG.warn("src=" + fileInfo.getFilepath() + ", datanodes[" + j + "]=" + datanodes[j], ie); } finally { IOUtils.closeStream(in); IOUtils.closeStream(out); } } if (!done) { throw new IOException("Fail to get block MD5 for " + block); } } } private void calculateSegments(){ LOG.warn("calculateSegments start"); List<Integer> simples = new LinkedList<Integer>(); List<byte[]> md5s = new LinkedList<byte[]>(); for(BlockInfo bi : dstFileInfo.getBlocks()){ for(ChecksumPair cp : bi.getChecksums()){ simples.add(cp.getSimple()); md5s.add(cp.getMd5()); } } //去掉最后一个chunk的checksum,防止其未达到chunksize simples.remove(simples.size()-1); md5s.remove(md5s.size()-1); for(BlockInfo bi : srcFileInfo.getBlocks()){ DatanodeInfo[] datanodes = bi.getLocatedBlock().getLocations(); final int timeout = 3000 * datanodes.length + socketTimeout; for (int j = 0; j < datanodes.length; j++) { DataOutputStream out = null; DataInputStream in = null; try { // connect to a datanode IOStreamPair pair = connectToDN(socketFactory, connectToDnViaHostname, getDataEncryptionKey(), datanodes[j], timeout); out = new DataOutputStream(new BufferedOutputStream( pair.out, HdfsConstants.SMALL_BUFFER_SIZE)); in = new DataInputStream(pair.in); // call calculateSegments new Sender(out).calculateSegments( bi.getLocatedBlock().getBlock(), bi.getLocatedBlock().getBlockToken(), clientName, simples, md5s); //read reply final BlockOpResponseProto reply = BlockOpResponseProto .parseFrom(PBHelper.vintPrefixed(in)); if (reply.getStatus() != Status.SUCCESS) { if (reply.getStatus() == Status.ERROR_ACCESS_TOKEN) { throw new InvalidBlockTokenException(); } else { throw new IOException("Bad response " + reply + " for block " + bi.getLocatedBlock().getBlock() + " from datanode " + datanodes[j]); } } OpCalculateSegmentsResponseProto segmentsData = reply .getCalculateSegmentsResponse(); LinkedList<SegmentProto> segments = new LinkedList<SegmentProto>(segmentsData.getSegmentsList()); LOG.warn("Block "+bi.getLocatedBlock().getBlock().getBlockName()+ " divide into "+segments.size()+" segments."); bi.setSegments(segments); break; } catch (InvalidBlockTokenException ibte) { } catch (IOException ie) { }finally { IOUtils.closeStream(in); IOUtils.closeStream(out); } } } } /** * 传送一个block所需的segments,与updateBlock配合使用 * @param blockInfo 所需要传送的block信息 * @param addedBlock 所传送的block在目标文件中对应的block * @throws AccessControlException * @throws FileNotFoundException * @throws UnresolvedLinkException * @throws IOException */ private void sendSegments(BlockInfo blockInfo,LocatedBlock addedBlock) throws AccessControlException, FileNotFoundException, UnresolvedLinkException, IOException{ LOG.warn("sendSegments for block "+blockInfo.getLocatedBlock().getBlock()+" start."); long blockSize = dstNamenode.getFileInfo(dstFileInfo.getFilepath()).getBlockSize(); long chunksPerBlock = blockSize/chunkSize; if(dstFileInfo.getBlocks().size() != srcFileInfo.getBlocks().size()){ throw new IOException("newFileInfo size not match srcFileInfo."); } for(int j = 0 ; j < blockInfo.getSegments().size() ; j++){ SegmentProto segment = blockInfo.getSegments().get(j); DatanodeInfo[] srcDatanodes = null; DatanodeInfo[] dstDatanodes = null; LocatedBlock block = null; String segmentName = null; String blockDirName = addedBlock.getBlock().getBlockId() +"_"+addedBlock.getBlock().getGenerationStamp(); long offset = 0; long length = 0; //如果dstFile中没有这个segment if(segment.getIndex() == -1){ srcDatanodes = blockInfo.getLocatedBlock().getLocations(); block = blockInfo.getLocatedBlock(); offset = segment.getOffset(); length = segment.getLength(); segmentName = String.format("%064d", offset)+"_"+String.format("%064d", length); dstDatanodes = addedBlock.getLocations(); LOG.warn("SendSegment from srcFile "+ "index : "+segment.getIndex()+ "; offset : "+segment.getOffset()+ "; length : "+segment.getLength()); }else{ srcDatanodes = dstFileInfo.getBlocks() .get((int)(segment.getIndex()/chunksPerBlock)) .getLocatedBlock().getLocations(); block = dstFileInfo.getBlocks() .get((int)(segment.getIndex()/chunksPerBlock)) .getLocatedBlock(); offset = segment.getIndex()%chunksPerBlock*chunkSize; length = chunkSize; segmentName = String.format("%064d", segment.getOffset())+"_"+ String.format("%064d", segment.getLength()); dstDatanodes = addedBlock.getLocations(); LOG.warn("SendSegment from dstFile "+ "index : "+segment.getIndex()+ "; offset : "+segment.getOffset()+ "; length : "+segment.getLength()); } final int timeout = 3000 + socketTimeout; for (int k = 0; k < srcDatanodes.length; k++) { DataOutputStream out = null; DataInputStream in = null; try { // connect to a datanode IOStreamPair pair = connectToDN(socketFactory, connectToDnViaHostname, getDataEncryptionKey(), srcDatanodes[k], timeout); out = new DataOutputStream(new BufferedOutputStream( pair.out, HdfsConstants.SMALL_BUFFER_SIZE)); in = new DataInputStream(pair.in); // call sendSegment new Sender(out).sendSegment(block.getBlock(), block.getBlockToken(), clientName, segment.getOffset(), segment.getLength(), true, true, segmentName, blockDirName, dstDatanodes); //read reply final BlockOpResponseProto reply = BlockOpResponseProto .parseFrom(PBHelper.vintPrefixed(in)); if (reply.getStatus() != Status.SUCCESS) { LOG.warn("Bad response " + reply + " for block " + blockInfo.getLocatedBlock().getBlock() + " from datanode " + srcDatanodes[k]); }else{ break; } } catch (InvalidBlockTokenException ibte) { } catch (IOException ie) { }finally { IOUtils.closeStream(in); IOUtils.closeStream(out); } } }//for segment } /** * 用于构建新的block * @param block 目标文件块 * @throws IOException * @throws UnresolvedLinkException * @throws FileNotFoundException * @throws AccessControlException */ private void updateBlock(LocatedBlock block) throws AccessControlException, FileNotFoundException, UnresolvedLinkException, IOException{ LOG.warn("updateBlock for block "+block.getBlock()+" start."); DatanodeInfo[] datanodes = block.getLocations(); final int timeout = 3000 * datanodes.length + socketTimeout; for (int j = 0; j < datanodes.length; j++) { DataOutputStream out = null; DataInputStream in = null; try { // connect to a datanode IOStreamPair pair = connectToDN(socketFactory, connectToDnViaHostname, getDataEncryptionKey(), datanodes[j], timeout); out = new DataOutputStream(new BufferedOutputStream( pair.out, HdfsConstants.SMALL_BUFFER_SIZE)); in = new DataInputStream(pair.in); // call updateBlock LOG.warn("updateBlock "+block.getBlock()); new Sender(out).updateBlock(block.getBlock(), block.getBlockToken()); //read reply final BlockOpResponseProto reply = BlockOpResponseProto .parseFrom(PBHelper.vintPrefixed(in)); if (reply.getStatus() != Status.SUCCESS) { LOG.warn("Bad response " + reply + " for block " + block.getBlock() + " from datanode " + datanodes[j]); } } catch (InvalidBlockTokenException ibte) { } catch (IOException ie) { }finally { IOUtils.closeStream(in); IOUtils.closeStream(out); } } } private LocatedBlocks callGetBlockLocations(ClientProtocol namenode, String src, long start, long length, boolean supportMetaInfo) throws IOException { try { return namenode.getBlockLocations(src, start, length); } catch (RemoteException re) { throw re.unwrapRemoteException(AccessControlException.class, FileNotFoundException.class); } } /** * Connect to the given datanode's datantrasfer port, and return the * resulting IOStreamPair. This includes encryption wrapping, etc. */ private IOStreamPair connectToDN(SocketFactory socketFactory, boolean connectToDnViaHostname, DataEncryptionKey encryptionKey, DatanodeInfo dn, int timeout) throws IOException { boolean success = false; Socket sock = null; try { sock = socketFactory.createSocket(); String dnAddr = dn.getXferAddr(connectToDnViaHostname); if (LOG.isDebugEnabled()) { LOG.debug("Connecting to datanode " + dnAddr); } NetUtils.connect(sock, NetUtils.createSocketAddr(dnAddr), timeout); sock.setSoTimeout(timeout); OutputStream unbufOut = NetUtils.getOutputStream(sock); InputStream unbufIn = NetUtils.getInputStream(sock); IOStreamPair ret; if (encryptionKey != null) { ret = DataTransferEncryptor.getEncryptedStreams(unbufOut, unbufIn, encryptionKey); } else { ret = new IOStreamPair(unbufIn, unbufOut); } success = true; return ret; } finally { if (!success) { IOUtils.closeSocket(sock); } } } /** * Infer the checksum type for a replica by sending an OP_READ_BLOCK for the * first byte of that replica. This is used for compatibility with older * HDFS versions which did not include the checksum type in * OpBlockChecksumResponseProto. * * @param in * input stream from datanode * @param out * output stream to datanode * @param lb * the located block * @param clientName * the name of the DFSClient requesting the checksum * @param dn * the connected datanode * @return the inferred checksum type * @throws IOException * if an error occurs */ private Type inferChecksumTypeByReading(String clientName, SocketFactory socketFactory, int socketTimeout, LocatedBlock lb, DatanodeInfo dn, DataEncryptionKey encryptionKey, boolean connectToDnViaHostname) throws IOException { IOStreamPair pair = connectToDN(socketFactory, connectToDnViaHostname, encryptionKey, dn, socketTimeout); try { DataOutputStream out = new DataOutputStream( new BufferedOutputStream(pair.out, HdfsConstants.SMALL_BUFFER_SIZE)); DataInputStream in = new DataInputStream(pair.in); new Sender(out).readBlock(lb.getBlock(), lb.getBlockToken(), clientName, 0, 1, true, CachingStrategy.newDefaultStrategy()); final BlockOpResponseProto reply = BlockOpResponseProto .parseFrom(PBHelper.vintPrefixed(in)); if (reply.getStatus() != Status.SUCCESS) { if (reply.getStatus() == Status.ERROR_ACCESS_TOKEN) { throw new InvalidBlockTokenException(); } else { throw new IOException("Bad response " + reply + " trying to read " + lb.getBlock() + " from datanode " + dn); } } return PBHelper.convert(reply.getReadOpChecksumInfo().getChecksum() .getType()); } finally { IOUtils.cleanup(null, pair.in, pair.out); } } /** * 新建一个临时文件,文件名为dstFilePath+".rsync",在这个文件中恢复新的文件内容,再用这个文件替代原有文件 * @param filePath * @param src * @throws IOException * TODO:应该让重建的所有block尽量存放在dstFile对应block所在datanode上 * @throws InterruptedException */ private void updateDstFile() throws IOException, InterruptedException { String tmpFilePath = dstFileInfo.getFilepath()+".rsync"; //dstDfs.create(new Path(tmpFilePath)).close(); short replication = Short.parseShort(conf.get("dfs.replication","1")); long blockSize = Long.parseLong(conf.get("dfs.blocksize","134217728")); EnumSetWritable<CreateFlag> flag = new EnumSetWritable<CreateFlag>(EnumSet.of(CreateFlag.CREATE,CreateFlag.OVERWRITE)); HdfsFileStatus status = dstNamenode.create( tmpFilePath, FsPermission.getFileDefault(), clientName, flag, true/*createParent*/, replication, blockSize); long fileId = status.getFileId(); //TODO:用一次append操作只是为了能够得到lease //LocatedBlock lastBlock = srcNamenode.append(tmpFilePath, clientName);//文件没有内容的时候,append操作返回的是null!! //if(lastBlock != null) LOG.warn("append empty file return " + lastBlock.getBlock()); //else LOG.warn("append empty file return null"); ExtendedBlock lastBlock = null; for(int i = 0 ; i < srcFileInfo.getBlocks().size() ; i++){ LocatedBlock currentBlock = dstNamenode.addBlock(tmpFilePath, clientName, lastBlock, (DatanodeInfo[])null, fileId, (String[])null); LOG.warn("Add new block "+currentBlock.getBlock()); //sendSegments and updateBlock sendSegments(srcFileInfo.getBlocks().get(i),currentBlock); updateBlock(currentBlock); lastBlock = currentBlock.getBlock(); } int count = 0; boolean completed = false; while((completed = dstNamenode.complete(tmpFilePath, clientName, lastBlock, fileId)) != true && count < 10){ LOG.warn("File "+tmpFilePath+" can not complete"); count++; Thread.sleep(1000); } LOG.warn("File "+tmpFilePath+" complete "+completed); } /** * Get server default values for a number of configuration params. * * @see ClientProtocol#getServerDefaults() */ public FsServerDefaults getServerDefaults() throws IOException { long now = Time.now(); if (now - serverDefaultsLastUpdate > SERVER_DEFAULTS_VALIDITY_PERIOD) { serverDefaults = srcNamenode.getServerDefaults(); serverDefaultsLastUpdate = now; } return serverDefaults; } /** * @return true if data sent between this client and DNs should be * encrypted, false otherwise. * @throws IOException * in the event of error communicating with the NN */ boolean shouldEncryptData() throws IOException { FsServerDefaults d = getServerDefaults(); return d == null ? false : d.getEncryptDataTransfer(); } @InterfaceAudience.Private public DataEncryptionKey getDataEncryptionKey() throws IOException { if (shouldEncryptData()) { synchronized (this) { if (encryptionKey == null || encryptionKey.expiryDate < Time.now()) { LOG.debug("Getting new encryption token from NN"); encryptionKey = srcNamenode.getDataEncryptionKey(); } return encryptionKey; } } else { return null; } } public boolean isMetaInfoSupported(ProtocolProxy<ClientProtocol> proxy) throws IOException { return proxy != null && proxy.isMethodSupported("openAndFetchMetaInfo", String.class, long.class, long.class); } public void printFileInfo(FileInfo fileInfo){ LOG.warn("File Info of "+fileInfo.getFilepath()); LOG.warn("\tblock count : "+fileInfo.getBlocks().size()); for(BlockInfo bi : fileInfo.getBlocks()){ LOG.warn("\tblock id : "+bi.getLocatedBlock().getBlock().getBlockId()+ "; genstamp : "+bi.getLocatedBlock().getBlock().getGenerationStamp()+ "; checksum size :"+bi.getChecksums().size()+ "; segment size : "+bi.getSegments().size()); } } public void run() throws IOException, InterruptedException { getSDFileInfo(); getSDFileChecksum(); calculateSegments(); //printFileInfo(srcFileInfo); //printFileInfo(dstFileInfo); updateDstFile(); } } private void getNameNode() throws IOException { if (nameNodeAddr != null) { // The lock is to make sure namenode, namenodeProtocolProxy // and rpcNamenode are consistent ultimately. There is still // a small window where another thread can see inconsistent // version of namenodeProtocolProxy and namenode. But it will // only happen during the transit time when name-node upgrade // and the exception will likely to be resolved after a retry. // synchronized (namenodeProxySyncObj) { this.srcNamenode = srcDfs.getClient().getNamenode(); this.dstNamenode = dstDfs.getClient().getNamenode(); } } } private static void printUsage() { HelpFormatter formatter = new HelpFormatter(); Options options = new Options(); formatter.printHelp("Usage : RsyncCopy [options] <srcs....> <dst>", options); } protected void checkOpen() throws IOException { if (!clientRunning) { IOException result = new IOException("Filesystem closed"); throw result; } } public void run() throws IOException, InterruptedException { getNameNode(); long uniqueId = 0; RsyncCopyFile testCopyFile = new RsyncCopyFile( srcNamenode,srcNamenodeProtocolProxy,srcPath, dstNamenode,dstNamenodeProtocolProxy,dstPath, conf,stats,uniqueId ); testCopyFile.run(); } public static void main(String args[]) throws Exception { if (args.length < 2) { printUsage(); } RsyncCopy rc = new RsyncCopy("/test","/test"); rc.run(); System.exit(0); } }
patch
hadoop-tools/hadoop-rsynccopy/src/main/java/org/apache/hadoop/tools/RsyncCopy.java
patch
<ide><path>adoop-tools/hadoop-rsynccopy/src/main/java/org/apache/hadoop/tools/RsyncCopy.java <ide> //sendSegments and updateBlock <ide> sendSegments(srcFileInfo.getBlocks().get(i),currentBlock); <ide> updateBlock(currentBlock); <del> lastBlock = currentBlock.getBlock(); <add> lastBlock = dstNamenode.getBlockLocations(tmpFilePath,i*blockSize, 1).get(0).getBlock(); <add> LOG.warn("lastBlock "+lastBlock.getBlockName()+" size "+lastBlock.getNumBytes()); <ide> } <ide> <ide> int count = 0;
JavaScript
mit
8495037f81c10955b047ab488a5e75dfe7e8363e
0
Sak32009/GetDLCInfoFromSteamDB,Sak32009/GetDLCInfoFromSteamDB
// ==UserScript== // @name Get DLC Info from SteamDB // @namespace sak32009-get-dlc-info-from-steamdb // @description Get DLC Info from SteamDB // @author Sak32009 // @year 2016 - 2020 // @version 4.1.1 // @license MIT // @homepageURL https://github.com/Sak32009/GetDLCInfoFromSteamDB/ // @supportURL https://cs.rin.ru/forum/viewtopic.php?f=10&t=71837 // @updateURL https://github.com/Sak32009/GetDLCInfoFromSteamDB/raw/master/sak32009-get-dlc-info-from-steamdb.user.js // @downloadURL https://github.com/Sak32009/GetDLCInfoFromSteamDB/raw/master/sak32009-get-dlc-info-from-steamdb.user.js // @icon https://github.com/Sak32009/GetDLCInfoFromSteamDB/raw/master/sak32009-get-dlc-info-from-steamdb-icon.png // @match *://steamdb.info/app/* // @match *://steamdb.info/depot/* // @match *://cs.rin.ru/forum/viewtopic.php?* // @match *://sak32009.github.io/getdlcinfofromsteamdb/* // @run-at document-end // @require https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js // @resource localIMG https://sak32009.github.io/sak32009.svg // @resource f1 https://rawcdn.githack.com/Sak32009/GetDLCInfoFromSteamDB/767f614f2b834aa497eb39d35e2359ab3e72f7fb/data/CreamAPI/V3.4.1.0.txt // @resource f2 https://rawcdn.githack.com/Sak32009/GetDLCInfoFromSteamDB/767f614f2b834aa497eb39d35e2359ab3e72f7fb/data/CreamAPI/V4.5.0.0.txt // @resource f3 https://rawcdn.githack.com/Sak32009/GetDLCInfoFromSteamDB/767f614f2b834aa497eb39d35e2359ab3e72f7fb/data/Only_DLCS_List/3DMGAME.txt // @resource f4 https://rawcdn.githack.com/Sak32009/GetDLCInfoFromSteamDB/767f614f2b834aa497eb39d35e2359ab3e72f7fb/data/Only_DLCS_List/CODEX_(DLC00000_=_DLCName).txt // @resource f5 https://rawcdn.githack.com/Sak32009/GetDLCInfoFromSteamDB/767f614f2b834aa497eb39d35e2359ab3e72f7fb/data/Only_DLCS_List/LUMAEMU.txt // @resource f6 https://rawcdn.githack.com/Sak32009/GetDLCInfoFromSteamDB/767f614f2b834aa497eb39d35e2359ab3e72f7fb/data/Only_DLCS_List/SKIDROW.txt // @resource f7 https://rawcdn.githack.com/Sak32009/GetDLCInfoFromSteamDB/767f614f2b834aa497eb39d35e2359ab3e72f7fb/data/APPID_APPIDNAME.txt // @resource f8 https://rawcdn.githack.com/Sak32009/GetDLCInfoFromSteamDB/767f614f2b834aa497eb39d35e2359ab3e72f7fb/data/APPIDNAME.txt // @resource f9 https://rawcdn.githack.com/Sak32009/GetDLCInfoFromSteamDB/767f614f2b834aa497eb39d35e2359ab3e72f7fb/data/GreenLuma_2020_BATCH_MODE.txt // @grant GM_xmlhttpRequest // @grant GM_getResourceText // @grant GM_addStyle // @grant unsafeWindow // ==/UserScript== GM_info.script.author = "Sak32009"; GM_info.script.year = "2016 - 2020"; GM_info.script.homepage = "https://github.com/Sak32009/GetDLCInfoFromSteamDB/"; GM_info.script.supportURL = "https://cs.rin.ru/forum/viewtopic.php?f=10&t=71837"; class m { constructor() { this.data = [{ name: "CreamAPI v4.5.0.0", header: { show: true, comment: "; " }, file: { name: "cream_api", ext: "ini", text: GM_getResourceText("f1") } }, { name: "CreamAPI v3.4.1.0", header: { show: true, comment: "; " }, file: { name: "cream_api", ext: "ini", text: GM_getResourceText("f2") } }, { name: "GreenLuma 2020 [BATCH MODE]", header: { show: true, comment: ":: " }, file: { name: "[steamdb]appID[/steamdb]_GreenLuma", ext: "bat", text: GM_getResourceText("f9") } }, { name: "LUMAEMU (ONLY DLCS LIST)", header: { show: true, comment: "; " }, file: { name: "", ext: "ini", text: GM_getResourceText("f5") } }, { name: "CODEX (DLC00000 = DLCName)", header: { show: true, comment: "; " }, file: { name: "", ext: "ini", text: GM_getResourceText("f4") } }, { name: "3DMGAME (ONLY DLCS LIST)", header: { show: true, comment: "; " }, file: { name: "", ext: "ini", text: GM_getResourceText("f3") } }, { name: "SKIDROW (ONLY DLCS LIST)", header: { show: true, comment: "; " }, file: { name: "", ext: "ini", text: GM_getResourceText("f6") } }, { name: "APPID = APPIDNAME", header: { show: true, comment: "; " }, file: { name: "", ext: "ini", text: GM_getResourceText("f7") } }, { name: "APPIDNAME", header: { show: true, comment: "; " }, file: { name: "", ext: "ini", text: GM_getResourceText("f8") } } ]; this.steamDB = { appID: "", name: "", count: 0, dlcs: {}, countUnknowns: 0, dlcsUnknowns: {}, appURL: "https://steamdb.info/app/", depotURL: "https://steamdb.info/depot/", linkedURL: "https://steamdb.info/search/?a=linked&q=" }; this.localURL = "https://sak32009.github.io/getdlcinfofromsteamdb/"; this.localIMG = "https://sak32009.github.io/sak32009.svg"; const url = new URL(window.location.href); this.$_GET = new URLSearchParams(url.search); this.isCSRINRU = url.hostname == "cs.rin.ru"; this.isSTEAMDBApp = url.pathname.startsWith("/app/"); this.isSTEAMDBDepot = url.pathname.startsWith("/depot/") && this.$_GET.has("show_hashes"); this.isLocal = url.hostname == "127.0.0.1" && this.$_GET.has("appid"); } getData() { const self = this; if (self.isLocal) { const appID = self.$_GET.get("appid"); if (appID.length) { self.steamDB.appID = appID; self.setDLCSRequests(); } } else if (self.isSTEAMDBApp || self.isCSRINRU) { if (self.isCSRINRU) { // TODO: APPID ISN'T ACCURATE const $findAppID = $("#pagecontent > .tablebg:nth-of-type(3) .postbody:first-child a.postlink[href^='http://store.steampowered.com/app/']"); if ($findAppID.length > 0) { self.steamDB.appID = new URL($findAppID.attr("href")).pathname.split("/")[2]; } } else { self.steamDB.appID = $(".scope-app[data-appid]").data("appid"); } self.createInterfaceButtons(); } else if (self.isSTEAMDBDepot) { self.createInterfaceDepots(); } } setDLCSRequests() { const self = this; GM_xmlhttpRequest({ url: `${self.steamDB.appURL + self.steamDB.appID}`, method: "GET", onload({responseText}) { const $dom = $($.parseHTML(responseText)); self.steamDB.name = $dom.find(".pagehead > h1").text().trim(); $dom.find("tr.app[data-appid] td.muted:nth-of-type(2)").each((_index, _dom) => { const $dom = $(_dom).closest("tr"); const appID = $dom.attr("data-appid"); const appName = $dom.find("td:nth-of-type(2)").text().trim(); self.steamDB.dlcsUnknowns[appID] = appName; self.steamDB.countUnknowns += 1; }); self.setLinkedDLCSRequest(); } }); } setLinkedDLCSRequest() { const self = this; GM_xmlhttpRequest({ url: `${self.steamDB.linkedURL + self.steamDB.appID}`, method: "GET", onload({responseText}) { const $dom = $($.parseHTML(responseText)); $dom.find("tr.app[data-appid] td:nth-of-type(2):contains('DLC')").each((_index, _dom) => { const $dom = $(_dom).closest("tr"); const appID = $dom.attr("data-appid"); const appName = $dom.find("td:nth-of-type(3)").text().trim(); self.steamDB.dlcs[appID] = appName; self.steamDB.count += 1; }); self.afterDLCSRequests(); } }); } afterDLCSRequests() { const self = this; unsafeWindow.getdlcinfofromsteamdb = { data: self.data, steamDB: self.steamDB, userscript: GM_info }; } createInterfaceButtons() { const self = this; GM_addStyle(`#WIZZpeAmov{display:block;margin:15px auto;background-color:#4b2e52;padding:12px;border:1px solid #000;border-radius:5px;text-decoration:none;color:#fff;text-align:center;font-weight:700}#WIZZpeAmov:hover{color:#fff;background-color:#522e47}#WIZZpeAmov.fixed{position:fixed;bottom:0;right:0;margin:0;margin-right:10px;z-index:999;border-bottom-left-radius:0;border-bottom-right-radius:0}#WIZZpeAmov img{max-width:70px;margin:auto;display:block;height:auto}`); const $a = $(`<a href="${self.localURL}?appid=${self.steamDB.appID}" id="WIZZpeAmov" target="_blank"><img src="${self.localIMG}" alt="Logo" /><span>${GM_info.script.name} v${GM_info.script.version} <small>by ${GM_info.script.author} | ${GM_info.script.year}</small></span></a>`); if (self.isCSRINRU) { $a.appendTo("#pagecontent > .tablebg:nth-of-type(3) .postbody:first-child").find("img").attr("src", self.localIMG); } else { $a.addClass("fixed").appendTo("body").find("img").attr("src", `${self.convertSVGToBase64(GM_getResourceText("localIMG"))}`); } } createInterfaceDepots() { const self = this; $(document).on("change", `div#files select[name="DataTables_Table_0_length"]`, (e) => { const depotID = $(`div[data-depotid]`).data("depotid"); const entries = $(`div#files select[name="DataTables_Table_0_length"] option:selected`).val(); const check = $("div#files > h2:first-child a").length; let output = `; ${GM_info.script.name} v${GM_info.script.version} by ${GM_info.script.author} | ${GM_info.script.year} | DEPOT URL: ${self.steamDB.depotURL + depotID}\n`; if (entries == "-1" && !check.length) { $(`div#files #DataTables_Table_0 tbody tr`).each((_index, _value) => { const $dom = $(_value); const filename = $dom.find("td:nth-of-type(1)").text().trim(); const filechecksum = $dom.find("td.code").text().trim(); if (filechecksum != "NULL") { output += `${filechecksum} *${filename}\n`; } }); const toBlob = self.toBlob(depotID, output, "sha1"); $(`<a href="${toBlob.blob}" download="${toBlob.name}" style="float:right">Download .sha1</a>`).appendTo("div#files > h2:first-child"); $(`<textarea rows="20" style="width:100%;resize:none"></textarea>`).text(output).insertAfter("div#files > h2:first-child"); } }); } convertSVGToBase64(str) { return `data:image/svg+xml;base64,${window.btoa(str)}`; } toBlob(name, content, extension) { return { name: `${name.toString().length > 0 ? name : Math.random().toString(36).substring(2)}.${extension}`, blob: window.URL.createObjectURL(new Blob([content.replace(/\n/g, "\r\n")], { type: "application/octet-stream;charset=utf-8" })) }; } } new m().getData();
sak32009-get-dlc-info-from-steamdb.user.js
// ==UserScript== // @name Get DLC Info from SteamDB // @namespace sak32009-get-dlc-info-from-steamdb // @description Get DLC Info from SteamDB // @author Sak32009 // @year 2016 - 2020 // @version 4.1.0 // @license MIT // @homepageURL https://github.com/Sak32009/GetDLCInfoFromSteamDB/ // @supportURL https://cs.rin.ru/forum/viewtopic.php?f=10&t=71837 // @updateURL https://github.com/Sak32009/GetDLCInfoFromSteamDB/raw/master/sak32009-get-dlc-info-from-steamdb.user.js // @downloadURL https://github.com/Sak32009/GetDLCInfoFromSteamDB/raw/master/sak32009-get-dlc-info-from-steamdb.user.js // @icon https://github.com/Sak32009/GetDLCInfoFromSteamDB/raw/master/sak32009-get-dlc-info-from-steamdb-icon.png // @match *://steamdb.info/app/* // @match *://steamdb.info/depot/* // @match *://cs.rin.ru/forum/viewtopic.php?* // @match *://sak32009.github.io/getdlcinfofromsteamdb/* // @run-at document-end // @require https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js // @resource localIMG https://sak32009.github.io/sak32009.svg // @resource f1 https://rawcdn.githack.com/Sak32009/GetDLCInfoFromSteamDB/767f614f2b834aa497eb39d35e2359ab3e72f7fb/data/CreamAPI/V3.4.1.0.txt // @resource f2 https://rawcdn.githack.com/Sak32009/GetDLCInfoFromSteamDB/767f614f2b834aa497eb39d35e2359ab3e72f7fb/data/CreamAPI/V4.5.0.0.txt // @resource f3 https://rawcdn.githack.com/Sak32009/GetDLCInfoFromSteamDB/767f614f2b834aa497eb39d35e2359ab3e72f7fb/data/Only_DLCS_List/3DMGAME.txt // @resource f4 https://rawcdn.githack.com/Sak32009/GetDLCInfoFromSteamDB/767f614f2b834aa497eb39d35e2359ab3e72f7fb/data/Only_DLCS_List/CODEX_(DLC00000_=_DLCName).txt // @resource f5 https://rawcdn.githack.com/Sak32009/GetDLCInfoFromSteamDB/767f614f2b834aa497eb39d35e2359ab3e72f7fb/data/Only_DLCS_List/LUMAEMU.txt // @resource f6 https://rawcdn.githack.com/Sak32009/GetDLCInfoFromSteamDB/767f614f2b834aa497eb39d35e2359ab3e72f7fb/data/Only_DLCS_List/SKIDROW.txt // @resource f7 https://rawcdn.githack.com/Sak32009/GetDLCInfoFromSteamDB/767f614f2b834aa497eb39d35e2359ab3e72f7fb/data/APPID_APPIDNAME.txt // @resource f8 https://rawcdn.githack.com/Sak32009/GetDLCInfoFromSteamDB/767f614f2b834aa497eb39d35e2359ab3e72f7fb/data/APPIDNAME.txt // @resource f9 https://rawcdn.githack.com/Sak32009/GetDLCInfoFromSteamDB/767f614f2b834aa497eb39d35e2359ab3e72f7fb/data/GreenLuma_2020_BATCH_MODE.txt // @grant GM_xmlhttpRequest // @grant GM_getResourceText // @grant GM_addStyle // @grant unsafeWindow // ==/UserScript== GM_info.script.author = "Sak32009"; GM_info.script.year = "2016 - 2020"; GM_info.script.homepage = "https://github.com/Sak32009/GetDLCInfoFromSteamDB/"; GM_info.script.supportURL = "https://cs.rin.ru/forum/viewtopic.php?f=10&t=71837"; class m { constructor() { this.data = [{ name: "CreamAPI v4.5.0.0", header: { show: true, comment: "; " }, file: { name: "cream_api", ext: "ini", text: GM_getResourceText("f1") } }, { name: "CreamAPI v3.4.1.0", header: { show: true, comment: "; " }, file: { name: "cream_api", ext: "ini", text: GM_getResourceText("f2") } }, { name: "GreenLuma 2020 [BATCH MODE]", header: { show: true, comment: ":: " }, file: { name: "[steamdb]appID[/steamdb]_GreenLuma", ext: "bat", text: GM_getResourceText("f9") } }, { name: "LUMAEMU (ONLY DLCS LIST)", header: { show: true, comment: "; " }, file: { name: "", ext: "ini", text: GM_getResourceText("f5") } }, { name: "CODEX (DLC00000 = DLCName)", header: { show: true, comment: "; " }, file: { name: "", ext: "ini", text: GM_getResourceText("f4") } }, { name: "3DMGAME (ONLY DLCS LIST)", header: { show: true, comment: "; " }, file: { name: "", ext: "ini", text: GM_getResourceText("f3") } }, { name: "SKIDROW (ONLY DLCS LIST)", header: { show: true, comment: "; " }, file: { name: "", ext: "ini", text: GM_getResourceText("f6") } }, { name: "APPID = APPIDNAME", header: { show: true, comment: "; " }, file: { name: "", ext: "ini", text: GM_getResourceText("f7") } }, { name: "APPIDNAME", header: { show: true, comment: "; " }, file: { name: "", ext: "ini", text: GM_getResourceText("f8") } } ]; this.steamDB = { appID: "", name: "", count: 0, dlcs: {}, countUnknowns: 0, dlcsUnknowns: {}, appURL: "https://steamdb.info/app/", depotURL: "https://steamdb.info/depot/", linkedURL: "https://steamdb.info/search/?a=linked&q=" }; this.localURL = "http://127.0.0.1:8887/"; this.localIMG = "https://sak32009.github.io/sak32009.svg"; const url = new URL(window.location.href); this.$_GET = new URLSearchParams(url.search); this.isCSRINRU = url.hostname == "cs.rin.ru"; this.isSTEAMDBApp = url.pathname.startsWith("/app/"); this.isSTEAMDBDepot = url.pathname.startsWith("/depot/") && this.$_GET.has("show_hashes"); this.isLocal = url.hostname == "127.0.0.1" && this.$_GET.has("appid"); } getData() { const self = this; if (self.isLocal) { const appID = self.$_GET.get("appid"); if (appID.length) { self.steamDB.appID = appID; self.setDLCSRequests(); } } else if (self.isSTEAMDBApp || self.isCSRINRU) { if (self.isCSRINRU) { // TODO: APPID ISN'T ACCURATE const $findAppID = $("#pagecontent > .tablebg:nth-of-type(3) .postbody:first-child a.postlink[href^='http://store.steampowered.com/app/']"); if ($findAppID.length > 0) { self.steamDB.appID = new URL($findAppID.attr("href")).pathname.split("/")[2]; } } else { self.steamDB.appID = $(".scope-app[data-appid]").data("appid"); } self.createInterfaceButtons(); } else if (self.isSTEAMDBDepot) { self.createInterfaceDepots(); } } setDLCSRequests() { const self = this; GM_xmlhttpRequest({ url: `${self.steamDB.appURL + self.steamDB.appID}`, method: "GET", onload({responseText}) { const $dom = $($.parseHTML(responseText)); self.steamDB.name = $dom.find(".pagehead > h1").text().trim(); $dom.find("tr.app[data-appid] td.muted:nth-of-type(2)").each((_index, _dom) => { const $dom = $(_dom).closest("tr"); const appID = $dom.attr("data-appid"); const appName = $dom.find("td:nth-of-type(2)").text().trim(); self.steamDB.dlcsUnknowns[appID] = appName; self.steamDB.countUnknowns += 1; }); self.setLinkedDLCSRequest(); } }); } setLinkedDLCSRequest() { const self = this; GM_xmlhttpRequest({ url: `${self.steamDB.linkedURL + self.steamDB.appID}`, method: "GET", onload({responseText}) { const $dom = $($.parseHTML(responseText)); $dom.find("tr.app[data-appid] td:nth-of-type(2):contains('DLC')").each((_index, _dom) => { const $dom = $(_dom).closest("tr"); const appID = $dom.attr("data-appid"); const appName = $dom.find("td:nth-of-type(3)").text().trim(); self.steamDB.dlcs[appID] = appName; self.steamDB.count += 1; }); self.afterDLCSRequests(); } }); } afterDLCSRequests() { const self = this; unsafeWindow.getdlcinfofromsteamdb = { data: self.data, steamDB: self.steamDB, userscript: GM_info }; } createInterfaceButtons() { const self = this; GM_addStyle(`#WIZZpeAmov{display:block;margin:15px auto;background-color:#4b2e52;padding:12px;border:1px solid #000;border-radius:5px;text-decoration:none;color:#fff;text-align:center;font-weight:700}#WIZZpeAmov:hover{color:#fff;background-color:#522e47}#WIZZpeAmov.fixed{position:fixed;bottom:0;right:0;margin:0;margin-right:10px;z-index:999;border-bottom-left-radius:0;border-bottom-right-radius:0}#WIZZpeAmov img{max-width:70px;margin:auto;display:block;height:auto}`); const $a = $(`<a href="${self.localURL}?appid=${self.steamDB.appID}" id="WIZZpeAmov" target="_blank"><img src="${self.localIMG}" alt="Logo" /><span>${GM_info.script.name} v${GM_info.script.version} <small>by ${GM_info.script.author} | ${GM_info.script.year}</small></span></a>`); if (self.isCSRINRU) { $a.appendTo("#pagecontent > .tablebg:nth-of-type(3) .postbody:first-child").find("img").attr("src", self.localIMG); } else { $a.addClass("fixed").appendTo("body").find("img").attr("src", `${self.convertSVGToBase64(GM_getResourceText("localIMG"))}`); } } createInterfaceDepots() { const self = this; $(document).on("change", `div#files select[name="DataTables_Table_0_length"]`, (e) => { const depotID = $(`div[data-depotid]`).data("depotid"); const entries = $(`div#files select[name="DataTables_Table_0_length"] option:selected`).val(); const check = $("div#files > h2:first-child a").length; let output = `; ${GM_info.script.name} v${GM_info.script.version} by ${GM_info.script.author} | ${GM_info.script.year} | DEPOT URL: ${self.steamDB.depotURL + depotID}\n`; if (entries == "-1" && !check.length) { $(`div#files #DataTables_Table_0 tbody tr`).each((_index, _value) => { const $dom = $(_value); const filename = $dom.find("td:nth-of-type(1)").text().trim(); const filechecksum = $dom.find("td.code").text().trim(); if (filechecksum != "NULL") { output += `${filechecksum} *${filename}\n`; } }); const toBlob = self.toBlob(depotID, output, "sha1"); $(`<a href="${toBlob.blob}" download="${toBlob.name}" style="float:right">Download .sha1</a>`).appendTo("div#files > h2:first-child"); $(`<textarea rows="20" style="width:100%;resize:none"></textarea>`).text(output).insertAfter("div#files > h2:first-child"); } }); } convertSVGToBase64(str) { return `data:image/svg+xml;base64,${window.btoa(str)}`; } toBlob(name, content, extension) { return { name: `${name.toString().length > 0 ? name : Math.random().toString(36).substring(2)}.${extension}`, blob: window.URL.createObjectURL(new Blob([content.replace(/\n/g, "\r\n")], { type: "application/octet-stream;charset=utf-8" })) }; } } new m().getData();
fast fix
sak32009-get-dlc-info-from-steamdb.user.js
fast fix
<ide><path>ak32009-get-dlc-info-from-steamdb.user.js <ide> // @description Get DLC Info from SteamDB <ide> // @author Sak32009 <ide> // @year 2016 - 2020 <del>// @version 4.1.0 <add>// @version 4.1.1 <ide> // @license MIT <ide> // @homepageURL https://github.com/Sak32009/GetDLCInfoFromSteamDB/ <ide> // @supportURL https://cs.rin.ru/forum/viewtopic.php?f=10&t=71837 <ide> depotURL: "https://steamdb.info/depot/", <ide> linkedURL: "https://steamdb.info/search/?a=linked&q=" <ide> }; <del> this.localURL = "http://127.0.0.1:8887/"; <add> this.localURL = "https://sak32009.github.io/getdlcinfofromsteamdb/"; <ide> this.localIMG = "https://sak32009.github.io/sak32009.svg"; <ide> const url = new URL(window.location.href); <ide> this.$_GET = new URLSearchParams(url.search);
JavaScript
mit
0f160ecadb5487f42f540eeb038197f924d25647
0
DispatchMe/meteor-mocha,meteortesting/meteor-mocha,meteortesting/meteor-mocha,DispatchMe/meteor-mocha,meteortesting/meteor-mocha,DispatchMe/meteor-mocha
Package.describe({ name: 'meteortesting:mocha', summary: 'Run Meteor package or app tests with Mocha', git: 'https://github.com/meteortesting/meteor-mocha.git', documentation: '../README.md', version: '0.5.1', testOnly: true, }); Package.onUse(function onUse(api) { api.use([ 'practicalmeteor:[email protected]', '[email protected]', 'lmieulet:[email protected] || 2.0.1', ]); api.use([ '[email protected]', '[email protected]', 'meteortesting:[email protected]' ], 'server'); api.mainModule('client.js', 'client'); api.mainModule('server.js', 'server'); });
package/package.js
Package.describe({ name: 'meteortesting:mocha', summary: 'Run Meteor package or app tests with Mocha', git: 'https://github.com/meteortesting/meteor-mocha.git', documentation: '../README.md', version: '0.5.1', testOnly: true, }); Package.onUse(function onUse(api) { api.use([ 'practicalmeteor:[email protected]', '[email protected]', 'lmieulet:[email protected]', ]); api.use([ '[email protected]', '[email protected]', 'meteortesting:[email protected]' ], 'server'); api.mainModule('client.js', 'client'); api.mainModule('server.js', 'server'); });
Allow using meteor-coverage 2.x.x, needed for code-coverage support from meteor 1.6.0 and onwards
package/package.js
Allow using meteor-coverage 2.x.x, needed for code-coverage support from meteor 1.6.0 and onwards
<ide><path>ackage/package.js <ide> api.use([ <ide> 'practicalmeteor:[email protected]', <ide> '[email protected]', <del> 'lmieulet:[email protected]', <add> 'lmieulet:[email protected] || 2.0.1', <ide> ]); <ide> <ide> api.use([
Java
apache-2.0
f58d763ed35efa19afa6807f42484fd7db5803c4
0
jeorme/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,nssales/OG-Platform,ChinaQuants/OG-Platform,nssales/OG-Platform,codeaudit/OG-Platform,jeorme/OG-Platform,DevStreet/FinanceAnalytics,nssales/OG-Platform,McLeodMoores/starling,codeaudit/OG-Platform,codeaudit/OG-Platform,jerome79/OG-Platform,jeorme/OG-Platform,McLeodMoores/starling,jerome79/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,ChinaQuants/OG-Platform,McLeodMoores/starling,jerome79/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,McLeodMoores/starling,jerome79/OG-Platform
/** * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.model.credit; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; import org.threeten.bp.ZoneId; import org.threeten.bp.ZonedDateTime; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import com.opengamma.analytics.financial.credit.creditdefaultswap.definition.legacy.LegacyVanillaCreditDefaultSwapDefinition; import com.opengamma.core.AbstractSourceWithExternalBundle; import com.opengamma.core.change.ChangeManager; import com.opengamma.core.change.DummyChangeManager; import com.opengamma.core.holiday.HolidaySource; import com.opengamma.core.holiday.impl.WeekendHolidaySource; import com.opengamma.core.region.Region; import com.opengamma.core.region.RegionSource; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.function.AbstractFunction.NonCompiledInvoker; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.function.FunctionExecutionContext; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.target.ComputationTargetType; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueRequirementNames; import com.opengamma.engine.value.ValueSpecification; import com.opengamma.financial.analytics.conversion.CreditDefaultSwapSecurityConverterDeprecated; import com.opengamma.financial.analytics.model.cds.ISDAFunctionConstants; import com.opengamma.financial.security.FinancialSecurityTypes; import com.opengamma.financial.security.cds.LegacyVanillaCDSSecurity; import com.opengamma.id.ExternalId; import com.opengamma.id.ExternalIdBundle; import com.opengamma.id.ObjectId; import com.opengamma.id.UniqueId; import com.opengamma.id.VersionCorrection; import com.opengamma.master.region.ManageableRegion; import com.opengamma.util.async.AsynchronousExecution; import com.opengamma.util.i18n.Country; import com.opengamma.util.money.Currency; /** * Abstract class for specific CS01 functions to derive from. */ public class ISDARiskMetricsVanillaCDSFunction extends NonCompiledInvoker { private CreditDefaultSwapSecurityConverterDeprecated _converter; protected static final String[] s_requirements = {ValueRequirementNames.ACCRUED_DAYS, ValueRequirementNames.ACCRUED_PREMIUM, ValueRequirementNames.CLEAN_PRICE, ValueRequirementNames.PRINCIPAL }; @Override public void init(final FunctionCompilationContext context) { // using hardcoded region and calendar for now final HolidaySource holidaySource = new WeekendHolidaySource(); //OpenGammaCompilationContext.getHolidaySource(context); @SuppressWarnings("synthetic-access") final RegionSource regionSource = new TestRegionSource(getTestRegion()); //OpenGammaCompilationContext.getRegionSource(context); _converter = new CreditDefaultSwapSecurityConverterDeprecated(holidaySource, regionSource); } @Override public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) throws AsynchronousExecution { final ZonedDateTime now = ZonedDateTime.now(executionContext.getValuationClock()); final LegacyVanillaCDSSecurity security = (LegacyVanillaCDSSecurity) target.getSecurity(); LegacyVanillaCreditDefaultSwapDefinition cds = _converter.visitLegacyVanillaCDSSecurity(security); final ValueProperties properties = Iterables.getFirst(desiredValues, null).getConstraints().copy().get(); // all share same properties final Object cleanPVObject = inputs.getValue(ValueRequirementNames.CLEAN_PRESENT_VALUE); final double cleanPresentValue = ((Double) cleanPVObject).doubleValue(); final Object dirtyPVObject = inputs.getValue(ValueRequirementNames.DIRTY_PRESENT_VALUE); final double dirtyPresentValue = ((Double) dirtyPVObject).doubleValue(); final Object upfrontObject = inputs.getValue(ValueRequirementNames.UPFRONT_AMOUNT); final double upfrontAmount = ((Double) upfrontObject).doubleValue(); cds = IMMDateGenerator.cdsModifiedForIMM(now, cds); final double accruedPremium = cleanPresentValue - dirtyPresentValue; final double accruedDays = Math.abs((accruedPremium * 360 / cds.getParSpread()) * (10000 / cds.getNotional())); final double cleanPrice = 100.0 * ((cds.getNotional() - dirtyPresentValue - accruedPremium) / cds.getNotional()); final double principal = accruedPremium + upfrontAmount; final ComputedValue accruedDaysSpec = new ComputedValue(new ValueSpecification(ValueRequirementNames.ACCRUED_DAYS, target.toSpecification(), properties), accruedDays); final ComputedValue accruedPremiumSpec = new ComputedValue(new ValueSpecification(ValueRequirementNames.ACCRUED_PREMIUM, target.toSpecification(), properties), accruedPremium); final ComputedValue cleanPriceSpec = new ComputedValue(new ValueSpecification(ValueRequirementNames.CLEAN_PRICE, target.toSpecification(), properties), cleanPrice); final ComputedValue principalSpec = new ComputedValue(new ValueSpecification(ValueRequirementNames.PRINCIPAL, target.toSpecification(), properties), principal); return Sets.newHashSet(accruedDaysSpec, accruedPremiumSpec, cleanPriceSpec, principalSpec); } @Override public ComputationTargetType getTargetType() { return FinancialSecurityTypes.LEGACY_VANILLA_CDS_SECURITY; } @Override public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) { final ValueProperties properties = createValueProperties() .withAny(ISDAFunctionConstants.ISDA_CURVE_OFFSET) .withAny(ISDAFunctionConstants.ISDA_CURVE_DATE) .withAny(ISDAFunctionConstants.ISDA_IMPLEMENTATION) .withAny(ISDAFunctionConstants.CDS_QUOTE_CONVENTION) .withAny(ISDAFunctionConstants.ISDA_BUCKET_TENORS) .with(ValuePropertyNames.CURVE_CALCULATION_METHOD, ISDAFunctionConstants.ISDA_METHOD_NAME) .get(); final Set<ValueSpecification> specs = new HashSet<>(); for (final String name : s_requirements) { specs.add(new ValueSpecification(name, target.toSpecification(), properties)); } return specs; } @Override public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) { final LegacyVanillaCDSSecurity cds = (LegacyVanillaCDSSecurity) target.getSecurity(); final String isdaOffset = desiredValue.getConstraint(ISDAFunctionConstants.ISDA_CURVE_OFFSET); if (isdaOffset == null) { return null; } final String isdaCurveDate = desiredValue.getConstraint(ISDAFunctionConstants.ISDA_CURVE_DATE); if (isdaCurveDate == null) { return null; } final String isdaCurveMethod = desiredValue.getConstraint(ISDAFunctionConstants.ISDA_IMPLEMENTATION); if (isdaCurveMethod == null) { return null; } final String quoteConvention = desiredValue.getConstraint(ISDAFunctionConstants.CDS_QUOTE_CONVENTION); if (quoteConvention == null) { return null; } final String bucketTenors = desiredValue.getConstraint(ISDAFunctionConstants.ISDA_BUCKET_TENORS); if (bucketTenors == null) { return null; } final ValueProperties properties = ValueProperties.builder() .with(ValuePropertyNames.CURVE_CALCULATION_METHOD, ISDAFunctionConstants.ISDA_METHOD_NAME) .with(ISDAFunctionConstants.ISDA_CURVE_OFFSET, isdaOffset) .with(ISDAFunctionConstants.ISDA_CURVE_DATE, isdaCurveDate) .with(ISDAFunctionConstants.ISDA_IMPLEMENTATION, isdaCurveMethod) .with(ISDAFunctionConstants.CDS_QUOTE_CONVENTION, quoteConvention) .with(ISDAFunctionConstants.ISDA_BUCKET_TENORS, bucketTenors) .get(); final ValueRequirement cleanPVRequirment = new ValueRequirement(ValueRequirementNames.CLEAN_PRESENT_VALUE, target.toSpecification(), properties); final ValueRequirement dirtyPVRequirment = new ValueRequirement(ValueRequirementNames.DIRTY_PRESENT_VALUE, target.toSpecification(), properties); final ValueRequirement upfrontRequirment = new ValueRequirement(ValueRequirementNames.UPFRONT_AMOUNT, target.toSpecification(), properties); return Sets.newHashSet(cleanPVRequirment, dirtyPVRequirment, upfrontRequirment); } protected static ManageableRegion getTestRegion() { final ManageableRegion region = new ManageableRegion(); region.setUniqueId(UniqueId.parse("Dummy~region")); region.setName("United States"); region.setCurrency(Currency.USD); region.setCountry(Country.US); region.setTimeZone(ZoneId.of("America/New_York")); region.setExternalIdBundle(ExternalIdBundle.of(ExternalId.parse("dummy~region"))); return region; } class TestRegionSource extends AbstractSourceWithExternalBundle<Region> implements RegionSource { private final AtomicLong _count = new AtomicLong(0); private final Region _testRegion; private TestRegionSource(final Region testRegion) { _testRegion = testRegion; } @Override public Collection<Region> get(final ExternalIdBundle bundle, final VersionCorrection versionCorrection) { _count.getAndIncrement(); Collection<Region> result = Collections.emptyList(); if (_testRegion.getExternalIdBundle().equals(bundle) && versionCorrection.equals(VersionCorrection.LATEST)) { result = Collections.singleton((Region) getTestRegion()); } return result; } @Override public Region get(final ObjectId objectId, final VersionCorrection versionCorrection) { _count.getAndIncrement(); Region result = null; if (_testRegion.getUniqueId().getObjectId().equals(objectId) && versionCorrection.equals(VersionCorrection.LATEST)) { result = _testRegion; } return result; } @Override public Region get(final UniqueId uniqueId) { _count.getAndIncrement(); Region result = null; if (_testRegion.getUniqueId().equals(uniqueId)) { result = _testRegion; } return result; } @Override public Region getHighestLevelRegion(final ExternalIdBundle bundle) { _count.getAndIncrement(); Region result = null; if (_testRegion.getExternalIdBundle().equals(bundle)) { result = _testRegion; } return result; } @Override public Region getHighestLevelRegion(final ExternalId externalId) { _count.getAndIncrement(); Region result = null; if (_testRegion.getExternalIdBundle().contains(externalId)) { result = _testRegion; } return result; } /** * Gets the count. * * @return the count */ public AtomicLong getCount() { return _count; } @Override public ChangeManager changeManager() { return DummyChangeManager.INSTANCE; } } }
projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/model/credit/ISDARiskMetricsVanillaCDSFunction.java
/** * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.model.credit; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; import org.threeten.bp.ZoneId; import org.threeten.bp.ZonedDateTime; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import com.opengamma.analytics.financial.credit.creditdefaultswap.definition.legacy.LegacyVanillaCreditDefaultSwapDefinition; import com.opengamma.core.AbstractSourceWithExternalBundle; import com.opengamma.core.change.ChangeManager; import com.opengamma.core.change.DummyChangeManager; import com.opengamma.core.holiday.HolidaySource; import com.opengamma.core.holiday.impl.WeekendHolidaySource; import com.opengamma.core.region.Region; import com.opengamma.core.region.RegionSource; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.function.AbstractFunction.NonCompiledInvoker; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.function.FunctionExecutionContext; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.target.ComputationTargetType; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueRequirementNames; import com.opengamma.engine.value.ValueSpecification; import com.opengamma.financial.analytics.conversion.CreditDefaultSwapSecurityConverterDeprecated; import com.opengamma.financial.analytics.model.cds.ISDAFunctionConstants; import com.opengamma.financial.security.FinancialSecurityTypes; import com.opengamma.financial.security.cds.LegacyVanillaCDSSecurity; import com.opengamma.id.ExternalId; import com.opengamma.id.ExternalIdBundle; import com.opengamma.id.ObjectId; import com.opengamma.id.UniqueId; import com.opengamma.id.VersionCorrection; import com.opengamma.master.region.ManageableRegion; import com.opengamma.util.async.AsynchronousExecution; import com.opengamma.util.i18n.Country; import com.opengamma.util.money.Currency; /** * Abstract class for specific CS01 functions to derive from. */ public class ISDARiskMetricsVanillaCDSFunction extends NonCompiledInvoker { private CreditDefaultSwapSecurityConverterDeprecated _converter; protected static final String[] s_requirements = {ValueRequirementNames.ACCRUED_DAYS, ValueRequirementNames.ACCRUED_PREMIUM, ValueRequirementNames.CLEAN_PRICE, ValueRequirementNames.PRINCIPAL }; @Override public void init(final FunctionCompilationContext context) { // using hardcoded region and calendar for now final HolidaySource holidaySource = new WeekendHolidaySource(); //OpenGammaCompilationContext.getHolidaySource(context); @SuppressWarnings("synthetic-access") final RegionSource regionSource = new TestRegionSource(getTestRegion()); //OpenGammaCompilationContext.getRegionSource(context); _converter = new CreditDefaultSwapSecurityConverterDeprecated(holidaySource, regionSource); } @Override public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) throws AsynchronousExecution { final ZonedDateTime now = ZonedDateTime.now(executionContext.getValuationClock()); final LegacyVanillaCDSSecurity security = (LegacyVanillaCDSSecurity) target.getSecurity(); LegacyVanillaCreditDefaultSwapDefinition cds = _converter.visitLegacyVanillaCDSSecurity(security); final ValueProperties properties = Iterables.getFirst(desiredValues, null).getConstraints().copy().get(); // all share same properties final Object cleanPVObject = inputs.getValue(ValueRequirementNames.CLEAN_PRESENT_VALUE); final double cleanPresentValue = ((Double) cleanPVObject).doubleValue(); final Object dirtyPVObject = inputs.getValue(ValueRequirementNames.DIRTY_PRESENT_VALUE); final double dirtyPresentValue = ((Double) dirtyPVObject).doubleValue(); final Object upfrontObject = inputs.getValue(ValueRequirementNames.UPFRONT_AMOUNT); final double upfrontAmount = ((Double) upfrontObject).doubleValue(); cds = IMMDateGenerator.cdsModifiedForIMM(now, cds); final double accruedPremium = cleanPresentValue - dirtyPresentValue; final double accruedDays = Math.abs((accruedPremium * 360 / cds.getParSpread()) * (10000 / cds.getNotional())); final double cleanPrice = 100.0 * ((cds.getNotional() - dirtyPresentValue - accruedPremium) / cds.getNotional()); final double principal = accruedPremium + upfrontAmount; final ComputedValue accruedDaysSpec = new ComputedValue(new ValueSpecification(ValueRequirementNames.ACCRUED_DAYS, target.toSpecification(), properties), accruedDays); final ComputedValue accruedPremiumSpec = new ComputedValue(new ValueSpecification(ValueRequirementNames.ACCRUED_PREMIUM, target.toSpecification(), properties), accruedPremium); final ComputedValue cleanPriceSpec = new ComputedValue(new ValueSpecification(ValueRequirementNames.CLEAN_PRICE, target.toSpecification(), properties), cleanPrice); final ComputedValue principalSpec = new ComputedValue(new ValueSpecification(ValueRequirementNames.PRINCIPAL, target.toSpecification(), properties), principal); return Sets.newHashSet(accruedDaysSpec, accruedPremiumSpec, cleanPriceSpec, principalSpec); } @Override public ComputationTargetType getTargetType() { return FinancialSecurityTypes.LEGACY_VANILLA_CDS_SECURITY; } @Override public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) { final ValueProperties properties = createValueProperties() .withAny(ISDAFunctionConstants.ISDA_CURVE_OFFSET) .withAny(ISDAFunctionConstants.ISDA_CURVE_DATE) .withAny(ISDAFunctionConstants.ISDA_IMPLEMENTATION) .withAny(ISDAFunctionConstants.CDS_QUOTE_CONVENTION) .with(ValuePropertyNames.CURVE_CALCULATION_METHOD, ISDAFunctionConstants.ISDA_METHOD_NAME) .get(); final Set<ValueSpecification> specs = new HashSet<>(); for (final String name : s_requirements) { specs.add(new ValueSpecification(name, target.toSpecification(), properties)); } return specs; } @Override public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) { final LegacyVanillaCDSSecurity cds = (LegacyVanillaCDSSecurity) target.getSecurity(); final String isdaOffset = desiredValue.getConstraint(ISDAFunctionConstants.ISDA_CURVE_OFFSET); if (isdaOffset == null) { return null; } final String isdaCurveDate = desiredValue.getConstraint(ISDAFunctionConstants.ISDA_CURVE_DATE); if (isdaCurveDate == null) { return null; } final String isdaCurveMethod = desiredValue.getConstraint(ISDAFunctionConstants.ISDA_IMPLEMENTATION); if (isdaCurveMethod == null) { return null; } final String quoteConvention = desiredValue.getConstraint(ISDAFunctionConstants.CDS_QUOTE_CONVENTION); if (quoteConvention == null) { return null; } final ValueProperties properties = ValueProperties.builder() .with(ValuePropertyNames.CURVE_CALCULATION_METHOD, ISDAFunctionConstants.ISDA_METHOD_NAME) .with(ISDAFunctionConstants.ISDA_CURVE_OFFSET, isdaOffset) .with(ISDAFunctionConstants.ISDA_CURVE_DATE, isdaCurveDate) .with(ISDAFunctionConstants.ISDA_IMPLEMENTATION, isdaCurveMethod) .with(ISDAFunctionConstants.CDS_QUOTE_CONVENTION, quoteConvention) .get(); final ValueRequirement cleanPVRequirment = new ValueRequirement(ValueRequirementNames.CLEAN_PRESENT_VALUE, target.toSpecification(), properties); final ValueRequirement dirtyPVRequirment = new ValueRequirement(ValueRequirementNames.DIRTY_PRESENT_VALUE, target.toSpecification(), properties); final ValueRequirement upfrontRequirment = new ValueRequirement(ValueRequirementNames.UPFRONT_AMOUNT, target.toSpecification(), properties); return Sets.newHashSet(cleanPVRequirment, dirtyPVRequirment, upfrontRequirment); } protected static ManageableRegion getTestRegion() { final ManageableRegion region = new ManageableRegion(); region.setUniqueId(UniqueId.parse("Dummy~region")); region.setName("United States"); region.setCurrency(Currency.USD); region.setCountry(Country.US); region.setTimeZone(ZoneId.of("America/New_York")); region.setExternalIdBundle(ExternalIdBundle.of(ExternalId.parse("dummy~region"))); return region; } class TestRegionSource extends AbstractSourceWithExternalBundle<Region> implements RegionSource { private final AtomicLong _count = new AtomicLong(0); private final Region _testRegion; private TestRegionSource(final Region testRegion) { _testRegion = testRegion; } @Override public Collection<Region> get(final ExternalIdBundle bundle, final VersionCorrection versionCorrection) { _count.getAndIncrement(); Collection<Region> result = Collections.emptyList(); if (_testRegion.getExternalIdBundle().equals(bundle) && versionCorrection.equals(VersionCorrection.LATEST)) { result = Collections.singleton((Region) getTestRegion()); } return result; } @Override public Region get(final ObjectId objectId, final VersionCorrection versionCorrection) { _count.getAndIncrement(); Region result = null; if (_testRegion.getUniqueId().getObjectId().equals(objectId) && versionCorrection.equals(VersionCorrection.LATEST)) { result = _testRegion; } return result; } @Override public Region get(final UniqueId uniqueId) { _count.getAndIncrement(); Region result = null; if (_testRegion.getUniqueId().equals(uniqueId)) { result = _testRegion; } return result; } @Override public Region getHighestLevelRegion(final ExternalIdBundle bundle) { _count.getAndIncrement(); Region result = null; if (_testRegion.getExternalIdBundle().equals(bundle)) { result = _testRegion; } return result; } @Override public Region getHighestLevelRegion(final ExternalId externalId) { _count.getAndIncrement(); Region result = null; if (_testRegion.getExternalIdBundle().contains(externalId)) { result = _testRegion; } return result; } /** * Gets the count. * * @return the count */ public AtomicLong getCount() { return _count; } @Override public ChangeManager changeManager() { return DummyChangeManager.INSTANCE; } } }
Fix bug that stopped some credit functions resolving
projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/model/credit/ISDARiskMetricsVanillaCDSFunction.java
Fix bug that stopped some credit functions resolving
<ide><path>rojects/OG-Financial/src/main/java/com/opengamma/financial/analytics/model/credit/ISDARiskMetricsVanillaCDSFunction.java <ide> .withAny(ISDAFunctionConstants.ISDA_CURVE_DATE) <ide> .withAny(ISDAFunctionConstants.ISDA_IMPLEMENTATION) <ide> .withAny(ISDAFunctionConstants.CDS_QUOTE_CONVENTION) <add> .withAny(ISDAFunctionConstants.ISDA_BUCKET_TENORS) <ide> .with(ValuePropertyNames.CURVE_CALCULATION_METHOD, ISDAFunctionConstants.ISDA_METHOD_NAME) <ide> .get(); <ide> final Set<ValueSpecification> specs = new HashSet<>(); <ide> <ide> final String quoteConvention = desiredValue.getConstraint(ISDAFunctionConstants.CDS_QUOTE_CONVENTION); <ide> if (quoteConvention == null) { <add> return null; <add> } <add> <add> final String bucketTenors = desiredValue.getConstraint(ISDAFunctionConstants.ISDA_BUCKET_TENORS); <add> if (bucketTenors == null) { <ide> return null; <ide> } <ide> <ide> .with(ISDAFunctionConstants.ISDA_CURVE_DATE, isdaCurveDate) <ide> .with(ISDAFunctionConstants.ISDA_IMPLEMENTATION, isdaCurveMethod) <ide> .with(ISDAFunctionConstants.CDS_QUOTE_CONVENTION, quoteConvention) <add> .with(ISDAFunctionConstants.ISDA_BUCKET_TENORS, bucketTenors) <ide> .get(); <ide> final ValueRequirement cleanPVRequirment = new ValueRequirement(ValueRequirementNames.CLEAN_PRESENT_VALUE, target.toSpecification(), properties); <ide> final ValueRequirement dirtyPVRequirment = new ValueRequirement(ValueRequirementNames.DIRTY_PRESENT_VALUE, target.toSpecification(), properties);
Java
bsd-3-clause
fba8911ea5ed69175fad8740cfc9a6f8206a1c9f
0
Whiley/WhileyRewriteLanguage
package wyrw.util; import java.util.ArrayList; import java.util.Arrays; import wyautl.core.Automaton; import wyautl.util.BinaryMatrix; import static wyautl.core.Automata.*; /** * <p> * Responsible for efficiently ensuring an automaton remains properly minimised * and compacted after a rewrite operation has occurred. Rewrites can result in * the presence of multiple equivalent states, though not always. For example, * consider this automaton: * </p> * * <pre> * Or * / \ * And And * | | * "X" "Y" * </pre> * * <p> * Now, suppose we rewrite state "X" to "Y", then their parent nodes become * equivalent and should be merged. The purpose of this algorithm is to do this * efficiently without traversing the entire automaton. * </p> * * <p> * The algorithm works by firstly maintaining the set of "parents" for each * state. That is the set of states for which this state is a direct child. * Since automata are directed graphs states can multiple parents (i.e. unlike * trees, where each node has exactly one parent). Since we expect relatively * few parents for each state, an array is used for this purpose. * </p> * <p> * Given knowledge of the parents for each state, the algorithm can now * efficiently determine the "cone" of states which could be equivalent after a * rewrite. Specifically, the parents of the states involved in the rewrite are * candidates for equivalence. Furthermore, if they are equivalent then their * parents are candidates for being equivalent and so on, until we fail to find * an equivalent pair of parents or we reach a root state. * </p> * <p> * <b>NOTE</b>: this algorithm should eventually be properly integrated with the * Automaton data structure. At this stage, I have avoided doing this simply * because of the work involved in doing it. * </p> * * @author David J. Pearce * */ public class IncrementalAutomatonMinimiser { /** * The automaton for which the incremental information is being maintained. */ private final Automaton automaton; /** * This represents the set of parents for each state in the automaton. This * is a list because we will need to expand it as the automaton increases in * size (which it likely will as rewrites occur). */ private final ArrayList<ParentInfo> parents; public IncrementalAutomatonMinimiser(Automaton automaton) { this.automaton = automaton; this.parents = determineParents(automaton); checkParentsInvariant(); checkReachabilityInvariant(); checkChildrenInvariant(); } /** * <p> * Update the automaton after a successful rewrite has occurred. The goal * here is to ensure: 1) the automaton remains in minimised form; 2) that * all unreachable states are nullified; 3) that the parents information is * up-to-date. * </p> * <p> * To ensure the automaton remains in minimised form, we need to collapse * any states which have been rendered equivalent by the rewrite. By * definition, these states must be parents of the two states involved in * the rewrite. There are two cases to consider. If the rewrite is to a * fresh state, then we are guaranteed that no equivalent states are * generated. On the otherhand, if the rewrite is to an existing state, then * there is potential for equivalent states to arise. In both cases, we must * first update the parents of those states involved. * </p> * * @param from * @param to */ public void rewrite(int from, int to, int pivot) { if(to > Automaton.K_VOID) { ParentInfo fromParents = parents.get(from); // expandParents(); // Copy parents to target state rewriteParents(from, to); // // Eliminate all states made unreachable eliminateUnreachableState(from); // Eliminate unreachable states above pivot eliminateUnreachableAbovePivot(pivot); // Second, collapse any equivalent vertices collapseEquivalentParents(from, to, fromParents); // TODO: resize to first unused slot above pivot; this should help // prevent the automaton grow too quickly. } else { eliminateUnreachableState(from); } checkReachabilityInvariant(); checkParentsInvariant(); checkChildrenInvariant(); int count = 0; for(int i=0;i!=automaton.nStates();++i) { if(automaton.get(i) == null) { count++; } } double ratio = ((double) count) / automaton.nStates(); System.out.println("RATIO: " + count + " / " + automaton.nStates() + " = " + ratio); compactAbovePivot(pivot); // TODO: get rid of any empty states at end // TODO: compact automaton over time } public void substitute(int source, int from, int to) { } /** * <p> * The given state has become unreachable. Therefore, we need to recursively * eliminate any children of this state which are also eliminated as a * result. To do this, we remove this state from the parents set of its * children. If any of those children now have an empty set of parents, then * we recursively eliminate them as well * </p> * <p> * <b>NOTE:</b> The major problem with this algorithm is, likely many * garbage collection algorithms, that it does not guarantee to eliminate * all unreachable states. In particular, no state involved in a cycle will * be reclaimed as it will always have at least one parent. <i>At this * stage, it remains to determine how best to resolve this problem. One * solution maybe to record the "dominator" for each state. That way, you * could tell whether a state which was unreachable dominated a child and, * hence, it too was unreachable.</i> * </p> * * @param parent * Index of the state in question. */ private void eliminateUnreachableState(int parent) { // FIXME: figure out solution for cycles (see above). Automaton.State state = automaton.get(parent); // First, check whether state already removed if (state != null) { // Second, physically remove the state in question automaton.set(parent, null); parents.set(parent, null); // Third, update parental information for any children switch (state.kind) { case Automaton.K_BOOL: case Automaton.K_INT: case Automaton.K_REAL: case Automaton.K_STRING: // no children return; case Automaton.K_LIST: case Automaton.K_SET: case Automaton.K_BAG: { // lots of children :) Automaton.Collection c = (Automaton.Collection) state; for (int i = 0; i != c.size(); ++i) { int child = c.get(i); if(child > Automaton.K_VOID) { ParentInfo pinfo = parents.get(child); // Check whether we have already eliminated this child // state. This can arise for a list or bag when multiple // occurrences of the same child are present. if(pinfo != null) { pinfo.removeAll(parent); if (pinfo.size() == 0 && !isRoot(child)) { // this state is now unreachable as well eliminateUnreachableState(child); } } } } return; } default: // terms Automaton.Term t = (Automaton.Term) state; int child = t.contents; if(child > Automaton.K_VOID) { ParentInfo pinfo = parents.get(child); pinfo.removeAll(parent); if (pinfo.size() == 0 && !isRoot(child)) { // this state is now unreachable as well eliminateUnreachableState(child); } } } } } private boolean isRoot(int index) { int nRoots = automaton.nRoots(); for(int i=0;i!=nRoots;++i) { if(automaton.getRoot(i) == index) { return true; } } return false; } private void eliminateUnreachableAbovePivot(int pivot) { for(int i=pivot;i!=automaton.nStates();++i) { Automaton.State s = automaton.get(i); if(s != null && parents.get(i) == null) { automaton.set(i, null); } } } /** * <p> * After a rewrite has occurred from one state to another, shift over * parents from one state to another. If the target state is fresh then we * need to create appropriate parents. Furthermore, there may be one or more * fresh children who need to have their parent sets initialised as well. In * such case, we recursively traverse them initialising their parent sets. * </p> * * @param child * --- state for which we are updating the parent information. * @param parent * --- single parent for the child in question */ private void rewriteParents(int from, int to) { ParentInfo fromParents = parents.get(from); ParentInfo toParents = parents.get(to); if(toParents == null) { parents.set(to, fromParents); addParentToChildren(to); } else { toParents.addAll(fromParents); } parents.set(from, null); } /** * <p> * Add a new parent to a given state (which may potentially be fresh). For a * fresh state, there may be one or more fresh children who need to have * their parent sets initialised as well. In such case, we recursively * traverse them initialising their parent sets. * </p> * * @param child * --- state for which we are updating the parent information. * @param parent * --- single parent for the child in question */ private void addParent(int parent, int child) { ParentInfo pinfo = parents.get(child); if(pinfo == null) { // This is a fresh state pinfo = new ParentInfo(1); parents.set(child, pinfo); addParentToChildren(child); } pinfo.add(parent); } /** * Add a given state as a parent for all its children. The assumption is * that this state would be fresh. * * @param child */ private void addParentToChildren(int child) { Automaton.State state = automaton.get(child); // switch (state.kind) { case Automaton.K_BOOL: case Automaton.K_INT: case Automaton.K_REAL: case Automaton.K_STRING: // no children break; case Automaton.K_LIST: case Automaton.K_SET: case Automaton.K_BAG: { // lots of children :) Automaton.Collection c = (Automaton.Collection) state; for (int i = 0; i != c.size(); ++i) { int grandChild = c.get(i); if(grandChild > Automaton.K_VOID) { addParent(child,grandChild); } } break; } default: // terms Automaton.Term t = (Automaton.Term) state; int grandChild = t.contents; if(grandChild > Automaton.K_VOID) { addParent(child,grandChild); } } } /** * Ensure there are enough entries in the parents array after a rewrite has occurred. */ private void expandParents() { int size = parents.size(); int nStates = automaton.nStates(); while(size < nStates) { parents.add(null); size = size + 1; } } /** * <p> * Given two states, collapse any parents which are now equivalent. To do * this, we compare each parent from the first state against all from the * second, etc. Whenever an equivalent pairing is found we must then explore * those parents of the pairing, etc. * </p> * <p> * The algorithm works using a worklist containing candidates pairs which * should be explored. The algorithm also maintains the set of states now * determined as equivalent. This is necessary when comparing two states to * determine if they are equivalent, as their equivalence may depend on two * child states which were previously determined as equivalent. Furthermore, * in the end, we need to determine which states to actually collapse. * </p> * <p> * <b>NOTE:</b> the algorithm potential does more work than necessary. This * is because it can end up retesting some candidate pairs more than once, * though this is perhaps a rather unusual case to encounter. To avoid this, * we could additionally record candidate pairs which are shown *not* to be * equivalent (but, actually, this might fail if children are subsequently * found to be equivalent). * </p> * * @param from * @param to * @param fromParents */ private void collapseEquivalentParents(int from, int to, ParentInfo fromParents) { ParentInfo toParents = parents.get(to); // FIXME: the following operations are linear (or worse) in the size of the // automaton. Therefore, we want to eliminate this by using a more compact representation. Worklist worklist = new Worklist(2 * (fromParents.size * toParents.size)); BinaryMatrix equivs = initialiseEquivalences(); // First, determine all potentially equivalent parents (if any) addCandidatesToWorklist(worklist,equivs,fromParents,toParents); // Second, iterate until all equivalences are determined. When an // equivalent is found recursively explore their parents. while (worklist.size > 0) { to = worklist.pop(); from = worklist.pop(); if (!equivs.get(from, to) && equivalent(automaton, equivs, from, to)) { equivs.set(from, to, true); equivs.set(to, from, true); addCandidatesToWorklist(worklist, equivs, parents.get(from), parents.get(to)); } } // Third, collapse all states now determined to be equivalent. collapseEquivalences(equivs); } private BinaryMatrix initialiseEquivalences() { BinaryMatrix equivs = new BinaryMatrix(automaton.nStates(),automaton.nStates(),false); for(int i=0;i!=automaton.nStates();++i) { equivs.set(i, i, true); } return equivs; } private void addCandidatesToWorklist(Worklist worklist, BinaryMatrix equivs, ParentInfo fromParents, ParentInfo toParents) { int[] from_parents = fromParents.parents; int[] to_parents = toParents.parents; for (int i = 0; i != fromParents.size; ++i) { int from_parent = from_parents[i]; Automaton.State from_state = automaton.get(from_parent); for (int j = 0; j != toParents.size; ++j) { int to_parent = to_parents[j]; Automaton.State to_state = automaton.get(to_parent); if (!equivs.get(from_parent, to_parent) && from_state.kind == to_state.kind) { // Only add candidates which could actually be the same. // This is a simple optimisation which should reduce work // considerably. worklist.push(from_parent); worklist.push(to_parent); } } } } /** * <p> * Collapse all states which are determined to be equivalent together. This * modifies the automaton in a potentially destructive fashion. The main * objective is to do this in time proportional to the number of equivalent * states (roughly speaking) rather than in time proportional to the size of * the automaton. This function does not compact the automaton, however. * Hence, there will be states remaining which are "null". * </p> * <p> * To collapse a set of equivalent states, we must remap their parent states * to now refer to the set's representative state. We must also update the * parent references for any child states. Finally, we delete (i.e. set to * null) any states which equivalent to some other representative. * </p> * * @param equivs */ private void collapseEquivalences(BinaryMatrix equivs) { // FIXME: these operations are all linear in size of automaton! int[] mapping = new int[automaton.nStates()]; // Determine representative states for all equivalence classes. In other // words, for any set of equivalent states, determine which one of them // is to be the "representative" which remains. determineRepresentativeStates(automaton,equivs,mapping); // Collapse all equivalence classes to a single state. Thus, the // representative for each class remains and all references to members of // that class are redirected to the representative. collapseEquivalenceClasses(automaton,mapping); // Finally, update the parent links for all vertices and delete those // records for states which are eliminated. int nStates = automaton.nStates(); for (int i = 0; i != nStates; ++i) { // ParentInfo pinfo = parents.get(i); if(pinfo != null) { // First, remap the parents of this state. pinfo.remap(mapping); // Second, if this state isn't the unique representative for its // equivalence class then move over all parents into that of the // unique representative. if(mapping[i] != i) { // This state has be subsumed by another state which was the // representative for its equivalence class. Therefore, the // state must now be unreachable. ParentInfo repInfo = parents.get(mapping[i]); repInfo.addAll(pinfo); parents.set(i, null); } } } } private void compactAbovePivot(int pivot) { // TODO: this could be way more aggressive. Specifically, we can // completely pack above the pivot. That's because, by exploiting the // parent information we can quickly remap all states. int i = automaton.nStates(); while (i > pivot) { if (automaton.get(i - 1) != null) { break; } i = i - 1; } automaton.resize(i); } /** * Check that every parent of a state has that state as a child. This is the * fundamental invariant which should be maintained by the parents array. */ private void checkParentsInvariant() { for(int i=0;i!=parents.size();++i) { ParentInfo pinfo = parents.get(i); if(pinfo != null) { if(automaton.get(i) == null) { throw new RuntimeException("*** INVALID PARENTS INVARIANT"); } for(int j=0;j!=pinfo.size();++j) { int parent = pinfo.get(j); checkIsChildOf(parent,i); } } } } /** * Check that one state is a child of another */ private void checkIsChildOf(int parent, int child) { Automaton.State state = automaton.get(parent); // if(state != null) { switch (state.kind) { case Automaton.K_BOOL: case Automaton.K_INT: case Automaton.K_REAL: case Automaton.K_STRING: // no children break; case Automaton.K_LIST: case Automaton.K_SET: case Automaton.K_BAG: { // lots of children :) Automaton.Collection c = (Automaton.Collection) state; if(c.contains(child)) { return; } break; } default: // terms Automaton.Term t = (Automaton.Term) state; if(t.contents == child) { return; } } } throw new RuntimeException("*** INVALID PARENTS INVARIANT: " + child + " NOT CHILD OF " + parent); } private void checkChildrenInvariant() { for(int i=0;i!=automaton.nStates();++i) { int[] children = children(i); for(int j=0;j!=children.length;++j) { if(automaton.get(children[j]) == null) { throw new RuntimeException("*** INVALID CHILDREN INVARIANT " + i + " " + children[j]); } } } } private int[] children(int parent) { Automaton.State state = automaton.get(parent); // if(state != null) { switch (state.kind) { case Automaton.K_BOOL: case Automaton.K_INT: case Automaton.K_REAL: case Automaton.K_STRING: // no children break; case Automaton.K_LIST: case Automaton.K_SET: case Automaton.K_BAG: { Automaton.Collection c = (Automaton.Collection) state; return c.toArray(); } default: // terms Automaton.Term t = (Automaton.Term) state; if(t.contents > Automaton.K_VOID) { return new int[]{t.contents}; } } } return new int[0]; } public void dumpState() { for(int i=0;i!=automaton.nStates();++i) { System.out.print("*** CHILDREN(" + i + ")=" + Arrays.toString(children(i))); if(i < parents.size()) { System.out.print(" PARENTS: " + parents.get(i)); } System.out.println(); } } /** * Check that the reachability invariant holds. The reachability invariant * states that all non-null states in either the automaton or the parents * array are reachable from one or more roots. */ private void checkReachabilityInvariant() { boolean[] reachable = new boolean[automaton.nStates()]; for(int i=0;i!=automaton.nRoots();++i) { findReachable(automaton,reachable,automaton.getRoot(i)); } for(int i=0;i!=automaton.nStates();++i) { if(reachable[i] && automaton.get(i) == null) { traceOut(automaton,new boolean[reachable.length],i); throw new RuntimeException("*** INVALID REACHABILITY INVARIANT(1), STATE: " + i); } else if(reachable[i] && automaton.get(i) == null) { traceOut(automaton,new boolean[reachable.length],i); throw new RuntimeException("*** INVALID REACHABILITY INVARIANT(2), STATE: " + i); } else if(!reachable[i] && automaton.get(i) != null){ traceOut(automaton,new boolean[reachable.length],i); throw new RuntimeException("*** INVALID REACHABILITY INVARIANT(3), STATE: " + i); } else if(!reachable[i] && parents.get(i) != null){ traceOut(automaton,new boolean[reachable.length],i); ParentInfo pinfo = parents.get(i); for(int j=0;j!=pinfo.size;++j) { int parent = pinfo.parents[j]; System.out.println("CHILDREN(" + parent + ")=" + Arrays.toString(children(parent)) + " isReachable: " + reachable[parent]); } throw new RuntimeException("*** INVALID REACHABILITY INVARIANT(4), STATE: " + i + " (parents " + parents.get(i) + ")"); } } } /** * Visit all states reachable from a given starting state in the given * automaton. In doing this, states which are visited are marked and, * furthermore, those which are "headers" are additionally identified. A * header state is one which is the target of a back-edge in the directed * graph reachable from the start state. * * @param automaton * --- automaton to traverse. * @param reachable * --- states marked with false are those which have not been * visited. * @param index * --- state to begin traversal from. * @return */ public static void findReachable(Automaton automaton, boolean[] reachable, int index) { if (index < 0) { return; } else if (reachable[index]) { // Already visited, so terminate here return; } else { // Not previously visited, so mark now and traverse any children reachable[index] = true; Automaton.State state = automaton.get(index); if (state instanceof Automaton.Term) { Automaton.Term term = (Automaton.Term) state; if (term.contents != Automaton.K_VOID) { findReachable(automaton, reachable, term.contents); } } else if (state instanceof Automaton.Collection) { Automaton.Collection compound = (Automaton.Collection) state; for (int i = 0; i != compound.size(); ++i) { findReachable(automaton, reachable, compound.get(i)); } } } } public static void traceOut(Automaton automaton, boolean[] reachable, int index) { if (index < 0) { return; } else if (reachable[index]) { // Already visited, so terminate here return; } else { // Not previously visited, so mark now and traverse any children reachable[index] = true; Automaton.State state = automaton.get(index); if (state instanceof Automaton.Term) { Automaton.Term term = (Automaton.Term) state; if (term.contents != Automaton.K_VOID) { System.out.println("Traversing: " + index + "=>" + term.contents); traceOut(automaton, reachable, term.contents); } } else if (state instanceof Automaton.Collection) { Automaton.Collection compound = (Automaton.Collection) state; for (int i = 0; i != compound.size(); ++i) { System.out.println("Traversing: " + index + "=>" + compound.get(i)); traceOut(automaton, reachable, compound.get(i)); } } } } /** * Compute the parents for each state in the automaton from scratch. This is * done using several linear traversals over the states to minimise the * amount of memory churn and ensure linear time. * * @param automaton * @return */ private static ArrayList<ParentInfo> determineParents(Automaton automaton) { int[] counts = new int[automaton.nStates()]; // first, visit all nodes for (int i = 0; i != automaton.nStates(); ++i) { updateParentCounts(automaton.get(i),i,counts); } // ArrayList<ParentInfo> parents = new ArrayList<ParentInfo>(); for (int i = 0; i != automaton.nStates(); ++i) { parents.add(new ParentInfo(counts[i])); } // for (int i = 0; i != automaton.nStates(); ++i) { updateParents(automaton.get(i),i,parents); } // return parents; } /** * Update the parent count for each child (if any) of the given state. * * @param state * --- The state whose children we are interested in. * @param parent * --- The index of the state whose children we are interested * in. * @param counts * --- The array of parent counts for each state. */ private static void updateParentCounts(Automaton.State state, int parent, int[] counts) { switch(state.kind) { case Automaton.K_BOOL: case Automaton.K_INT: case Automaton.K_REAL: case Automaton.K_STRING: return; case Automaton.K_LIST: case Automaton.K_SET: case Automaton.K_BAG: { Automaton.Collection c = (Automaton.Collection) state; for(int i=0;i!=c.size();++i) { int child = c.get(i); if(child > Automaton.K_VOID) { counts[child]++; } } break; } default: // terms Automaton.Term t = (Automaton.Term) state; int child = t.contents; if(child > Automaton.K_VOID) { counts[child]++; } } } /** * Update the parents for each child (if any) of the given state. * * @param state * --- The state whose children we are interested in. * @param parent * --- The index of the state whose children we are interested * in. * @param counts * --- The array of parent counts for each state. * @param parents * --- The list of parents for each state. */ private static void updateParents(Automaton.State state, int parent, ArrayList<ParentInfo> parents) { switch(state.kind) { case Automaton.K_BOOL: case Automaton.K_INT: case Automaton.K_REAL: case Automaton.K_STRING: return; case Automaton.K_LIST: case Automaton.K_SET: case Automaton.K_BAG: { Automaton.Collection c = (Automaton.Collection) state; for(int i=0;i!=c.size();++i) { int child = c.get(i); if(child > Automaton.K_VOID) { parents.get(child).add(parent); } } break; } default: // terms Automaton.Term t = (Automaton.Term) state; int child = t.contents; if(child > Automaton.K_VOID) { parents.get(child).add(parent); } } } /** * A simple data structure for representing the parent information. This * could be made more interesting, for example, by using a sorted array. Or, * perhaps, a compressed bitset. * * @author David J. Pearce * */ private static final class ParentInfo { private int[] parents; private int size; public ParentInfo(int capacity) { this.parents = new int[capacity]; this.size = 0; } public int size() { return size; } public int get(int index) { return parents[index]; } public void add(int parent) { int index = indexOf(parents,size,parent); if(index == -1) { ensureCapacity((size+1)*1); parents[size++] = parent; } } public void addAll(ParentInfo pinfo) { int pinfo_size = pinfo.size; ensureCapacity(size+pinfo_size); for(int i=0;i!=pinfo_size;++i) { int parent = pinfo.parents[i]; if(indexOf(parents,size,parent) == -1) { parents[size++] = parent; } } } public void removeAll(int parent) { int index; // FIXME: this could be optimised while ((index = indexOf(parents, size, parent)) != -1) { System.arraycopy(parents, index + 1, parents, index, size - (index + 1)); size = size - 1; } } public void remap(int[] mapping) { for (int i = 0; i != size; ++i) { parents[i] = mapping[parents[i]]; } } public void replace(int from, int to) { int j = indexOf(parents,size,to); if(j == -1) { for(int i=0;i!=size;++i) { if(parents[i] == from) { parents[i] = to; } } } else { removeAll(from); } } public boolean contains(int parent) { return indexOf(parents,size,parent) != -1; } public String toString() { String r = ""; for(int i=0;i!=size;++i) { if(i != 0) { r += ","; } r = r + parents[i]; } return "{" + r + "}"; } private void ensureCapacity(int capacity) { if(parents.length < capacity) { parents = Arrays.copyOf(parents, capacity); } } private static int indexOf(int[] array, int size, int element) { for(int i=0;i!=size;++i) { if(array[i] == element) { return i; } } return -1; } } public final static class Worklist { public int[] items; public int size; public Worklist(int size) { this.items = new int[size]; } public void push(int item) { if(size == items.length) { items = Arrays.copyOf(items, items.length*2); } items[size++] = item; } public int pop() { size = size - 1; return items[size]; } } }
src/wyrw/util/IncrementalAutomatonMinimiser.java
package wyrw.util; import java.util.ArrayList; import java.util.Arrays; import wyautl.core.Automaton; import wyautl.util.BinaryMatrix; import static wyautl.core.Automata.*; /** * <p> * Responsible for efficiently ensuring an automaton remains properly minimised * and compacted after a rewrite operation has occurred. Rewrites can result in * the presence of multiple equivalent states, though not always. For example, * consider this automaton: * </p> * * <pre> * Or * / \ * And And * | | * "X" "Y" * </pre> * * <p> * Now, suppose we rewrite state "X" to "Y", then their parent nodes become * equivalent and should be merged. The purpose of this algorithm is to do this * efficiently without traversing the entire automaton. * </p> * * <p> * The algorithm works by firstly maintaining the set of "parents" for each * state. That is the set of states for which this state is a direct child. * Since automata are directed graphs states can multiple parents (i.e. unlike * trees, where each node has exactly one parent). Since we expect relatively * few parents for each state, an array is used for this purpose. * </p> * <p> * Given knowledge of the parents for each state, the algorithm can now * efficiently determine the "cone" of states which could be equivalent after a * rewrite. Specifically, the parents of the states involved in the rewrite are * candidates for equivalence. Furthermore, if they are equivalent then their * parents are candidates for being equivalent and so on, until we fail to find * an equivalent pair of parents or we reach a root state. * </p> * <p> * <b>NOTE</b>: this algorithm should eventually be properly integrated with the * Automaton data structure. At this stage, I have avoided doing this simply * because of the work involved in doing it. * </p> * * @author David J. Pearce * */ public class IncrementalAutomatonMinimiser { /** * The automaton for which the incremental information is being maintained. */ private final Automaton automaton; /** * This represents the set of parents for each state in the automaton. This * is a list because we will need to expand it as the automaton increases in * size (which it likely will as rewrites occur). */ private final ArrayList<ParentInfo> parents; public IncrementalAutomatonMinimiser(Automaton automaton) { this.automaton = automaton; this.parents = determineParents(automaton); checkParentsInvariant(); checkReachabilityInvariant(); checkChildrenInvariant(); } /** * <p> * Update the automaton after a successful rewrite has occurred. The goal * here is to ensure: 1) the automaton remains in minimised form; 2) that * all unreachable states are nullified; 3) that the parents information is * up-to-date. * </p> * <p> * To ensure the automaton remains in minimised form, we need to collapse * any states which have been rendered equivalent by the rewrite. By * definition, these states must be parents of the two states involved in * the rewrite. There are two cases to consider. If the rewrite is to a * fresh state, then we are guaranteed that no equivalent states are * generated. On the otherhand, if the rewrite is to an existing state, then * there is potential for equivalent states to arise. In both cases, we must * first update the parents of those states involved. * </p> * * @param from * @param to */ public void rewrite(int from, int to, int pivot) { if(to > Automaton.K_VOID) { ParentInfo fromParents = parents.get(from); // expandParents(); // Copy parents to target state rewriteParents(from, to); // // Eliminate all states made unreachable eliminateUnreachableState(from); // Eliminate unreachable states above pivot eliminateUnreachableAbovePivot(pivot); // Second, collapse any equivalent vertices collapseEquivalentParents(from, to, fromParents); // TODO: resize to first unused slot above pivot; this should help // prevent the automaton grow too quickly. } else { eliminateUnreachableState(from); } checkReachabilityInvariant(); checkParentsInvariant(); checkChildrenInvariant(); int count = 0; for(int i=0;i!=automaton.nStates();++i) { if(automaton.get(i) == null) { count++; } } double ratio = ((double) count) / automaton.nStates(); System.out.println("RATIO: " + count + " / " + automaton.nStates() + " = " + ratio); compactAbovePivot(pivot); // TODO: get rid of any empty states at end // TODO: compact automaton over time } public void substitute(int source, int from, int to) { } /** * <p> * The given state has become unreachable. Therefore, we need to recursively * eliminate any children of this state which are also eliminated as a * result. To do this, we remove this state from the parents set of its * children. If any of those children now have an empty set of parents, then * we recursively eliminate them as well * </p> * <p> * <b>NOTE:</b> The major problem with this algorithm is, likely many * garbage collection algorithms, that it does not guarantee to eliminate * all unreachable states. In particular, no state involved in a cycle will * be reclaimed as it will always have at least one parent. <i>At this * stage, it remains to determine how best to resolve this problem. One * solution maybe to record the "dominator" for each state. That way, you * could tell whether a state which was unreachable dominated a child and, * hence, it too was unreachable.</i> * </p> * * @param parent * Index of the state in question. */ private void eliminateUnreachableState(int parent) { // FIXME: figure out solution for cycles (see above). Automaton.State state = automaton.get(parent); // First, check whether state already removed if (state != null) { // Second, physically remove the state in question automaton.set(parent, null); parents.set(parent, null); // Third, update parental information for any children switch (state.kind) { case Automaton.K_BOOL: case Automaton.K_INT: case Automaton.K_REAL: case Automaton.K_STRING: // no children return; case Automaton.K_LIST: case Automaton.K_SET: case Automaton.K_BAG: { // lots of children :) Automaton.Collection c = (Automaton.Collection) state; for (int i = 0; i != c.size(); ++i) { int child = c.get(i); if(child > Automaton.K_VOID) { ParentInfo pinfo = parents.get(child); // Check whether we have already eliminated this child // state. This can arise for a list or bag when multiple // occurrences of the same child are present. if(pinfo != null) { pinfo.removeAll(parent); if (pinfo.size() == 0 && !isRoot(child)) { // this state is now unreachable as well eliminateUnreachableState(child); } } } } return; } default: // terms Automaton.Term t = (Automaton.Term) state; int child = t.contents; if(child > Automaton.K_VOID) { ParentInfo pinfo = parents.get(child); pinfo.removeAll(parent); if (pinfo.size() == 0 && !isRoot(child)) { // this state is now unreachable as well eliminateUnreachableState(child); } } } } } private boolean isRoot(int index) { int nRoots = automaton.nRoots(); for(int i=0;i!=nRoots;++i) { if(automaton.getRoot(i) == index) { return true; } } return false; } private void eliminateUnreachableAbovePivot(int pivot) { for(int i=pivot;i!=automaton.nStates();++i) { Automaton.State s = automaton.get(i); if(s != null && parents.get(i) == null) { automaton.set(i, null); } } } /** * <p> * After a rewrite has occurred from one state to another, shift over * parents from one state to another. If the target state is fresh then we * need to create appropriate parents. Furthermore, there may be one or more * fresh children who need to have their parent sets initialised as well. In * such case, we recursively traverse them initialising their parent sets. * </p> * * @param child * --- state for which we are updating the parent information. * @param parent * --- single parent for the child in question */ private void rewriteParents(int from, int to) { ParentInfo fromParents = parents.get(from); ParentInfo toParents = parents.get(to); if(toParents == null) { parents.set(to, fromParents); addParentToChildren(to); } else { toParents.addAll(fromParents); } parents.set(from, null); } /** * <p> * Add a new parent to a given state (which may potentially be fresh). For a * fresh state, there may be one or more fresh children who need to have * their parent sets initialised as well. In such case, we recursively * traverse them initialising their parent sets. * </p> * * @param child * --- state for which we are updating the parent information. * @param parent * --- single parent for the child in question */ private void addParent(int parent, int child) { ParentInfo pinfo = parents.get(child); if(pinfo == null) { // This is a fresh state pinfo = new ParentInfo(1); parents.set(child, pinfo); addParentToChildren(child); } pinfo.add(parent); } /** * Add a given state as a parent for all its children. The assumption is * that this state would be fresh. * * @param child */ private void addParentToChildren(int child) { Automaton.State state = automaton.get(child); // switch (state.kind) { case Automaton.K_BOOL: case Automaton.K_INT: case Automaton.K_REAL: case Automaton.K_STRING: // no children break; case Automaton.K_LIST: case Automaton.K_SET: case Automaton.K_BAG: { // lots of children :) Automaton.Collection c = (Automaton.Collection) state; for (int i = 0; i != c.size(); ++i) { int grandChild = c.get(i); if(grandChild > Automaton.K_VOID) { addParent(child,grandChild); } } break; } default: // terms Automaton.Term t = (Automaton.Term) state; int grandChild = t.contents; if(grandChild > Automaton.K_VOID) { addParent(child,grandChild); } } } /** * Ensure there are enough entries in the parents array after a rewrite has occurred. */ private void expandParents() { int size = parents.size(); int nStates = automaton.nStates(); while(size < nStates) { parents.add(null); size = size + 1; } } /** * <p> * Given two states, collapse any parents which are now equivalent. To do * this, we compare each parent from the first state against all from the * second, etc. Whenever an equivalent pairing is found we must then explore * those parents of the pairing, etc. * </p> * <p> * The algorithm works using a worklist containing candidates pairs which * should be explored. The algorithm also maintains the set of states now * determined as equivalent. This is necessary when comparing two states to * determine if they are equivalent, as their equivalence may depend on two * child states which were previously determined as equivalent. Furthermore, * in the end, we need to determine which states to actually collapse. * </p> * <p> * <b>NOTE:</b> the algorithm potential does more work than necessary. This * is because it can end up retesting some candidate pairs more than once, * though this is perhaps a rather unusual case to encounter. To avoid this, * we could additionally record candidate pairs which are shown *not* to be * equivalent (but, actually, this might fail if children are subsequently * found to be equivalent). * </p> * * @param from * @param to * @param fromParents */ private void collapseEquivalentParents(int from, int to, ParentInfo fromParents) { ParentInfo toParents = parents.get(to); // FIXME: the following operations are linear (or worse) in the size of the // automaton. Therefore, we want to eliminate this by using a more compact representation. Worklist worklist = new Worklist(2 * (fromParents.size * toParents.size)); BinaryMatrix equivs = initialiseEquivalences(); // First, determine all potentially equivalent parents (if any) addCandidatesToWorklist(worklist,equivs,fromParents,toParents); // Second, iterate until all equivalences are determined. When an // equivalent is found recursively explore their parents. while (worklist.size > 0) { to = worklist.pop(); from = worklist.pop(); if (!equivs.get(from, to) && equivalent(automaton, equivs, from, to)) { equivs.set(from, to, true); equivs.set(to, from, true); addCandidatesToWorklist(worklist, equivs, parents.get(from), parents.get(to)); } } // Third, collapse all states now determined to be equivalent. collapseEquivalences(equivs); } private BinaryMatrix initialiseEquivalences() { BinaryMatrix equivs = new BinaryMatrix(automaton.nStates(),automaton.nStates(),false); for(int i=0;i!=automaton.nStates();++i) { equivs.set(i, i, true); } return equivs; } private void addCandidatesToWorklist(Worklist worklist, BinaryMatrix equivs, ParentInfo fromParents, ParentInfo toParents) { int[] from_parents = fromParents.parents; int[] to_parents = toParents.parents; for (int i = 0; i != fromParents.size; ++i) { int from_parent = from_parents[i]; Automaton.State from_state = automaton.get(from_parent); for (int j = 0; j != toParents.size; ++j) { int to_parent = to_parents[j]; Automaton.State to_state = automaton.get(to_parent); if (!equivs.get(from_parent, to_parent) && from_state.kind == to_state.kind) { // Only add candidates which could actually be the same. // This is a simple optimisation which should reduce work // considerably. worklist.push(from_parent); worklist.push(to_parent); } } } } /** * <p> * Collapse all states which are determined to be equivalent together. This * modifies the automaton in a potentially destructive fashion. The main * objective is to do this in time proportional to the number of equivalent * states (roughly speaking) rather than in time proportional to the size of * the automaton. This function does not compact the automaton, however. * Hence, there will be states remaining which are "null". * </p> * <p> * To collapse a set of equivalent states, we must remap their parent states * to now refer to the set's representative state. We must also update the * parent references for any child states. Finally, we delete (i.e. set to * null) any states which equivalent to some other representative. * </p> * * @param equivs */ private void collapseEquivalences(BinaryMatrix equivs) { // FIXME: these operations are all linear in size of automaton! int[] mapping = new int[automaton.nStates()]; // Determine representative states for all equivalence classes. In other // words, for any set of equivalent states, determine which one of them // is to be the "representative" which remains. determineRepresentativeStates(automaton,equivs,mapping); // Collapse all equivalence classes to a single state. Thus, the // representative for each class remains and all references to members of // that class are redirected to the representative. collapseEquivalenceClasses(automaton,mapping); // Finally, update the parent links for all vertices and delete those // records for states which are eliminated. int nStates = automaton.nStates(); for (int i = 0; i != nStates; ++i) { // ParentInfo pinfo = parents.get(i); if(pinfo != null) { // First, remap the parents of this state. pinfo.remap(mapping); // Second, if this state isn't the unique representative for its // equivalence class then move over all parents into that of the // unique representative. if(mapping[i] != i) { // This state has be subsumed by another state which was the // representative for its equivalence class. Therefore, the // state must now be unreachable. ParentInfo repInfo = parents.get(mapping[i]); repInfo.addAll(pinfo); parents.set(i, null); } } } } private void compactAbovePivot(int pivot) { // TODO: this could be way more aggressive. Specifically, we can // completely pack above the pivot. That's because, by exploiting the // parent information we can quickly remap all states. int i = automaton.nStates(); while(i > pivot) { if(automaton.get(i-1) != null) { break; } i = i - 1; } automaton.resize(i); } /** * Check that every parent of a state has that state as a child. This is the * fundamental invariant which should be maintained by the parents array. */ private void checkParentsInvariant() { for(int i=0;i!=parents.size();++i) { ParentInfo pinfo = parents.get(i); if(pinfo != null) { if(automaton.get(i) == null) { throw new RuntimeException("*** INVALID PARENTS INVARIANT"); } for(int j=0;j!=pinfo.size();++j) { int parent = pinfo.get(j); checkIsChildOf(parent,i); } } } } /** * Check that one state is a child of another */ private void checkIsChildOf(int parent, int child) { Automaton.State state = automaton.get(parent); // if(state != null) { switch (state.kind) { case Automaton.K_BOOL: case Automaton.K_INT: case Automaton.K_REAL: case Automaton.K_STRING: // no children break; case Automaton.K_LIST: case Automaton.K_SET: case Automaton.K_BAG: { // lots of children :) Automaton.Collection c = (Automaton.Collection) state; if(c.contains(child)) { return; } break; } default: // terms Automaton.Term t = (Automaton.Term) state; if(t.contents == child) { return; } } } throw new RuntimeException("*** INVALID PARENTS INVARIANT: " + child + " NOT CHILD OF " + parent); } private void checkChildrenInvariant() { for(int i=0;i!=automaton.nStates();++i) { int[] children = children(i); for(int j=0;j!=children.length;++j) { if(automaton.get(children[j]) == null) { throw new RuntimeException("*** INVALID CHILDREN INVARIANT " + i + " " + children[j]); } } } } private int[] children(int parent) { Automaton.State state = automaton.get(parent); // if(state != null) { switch (state.kind) { case Automaton.K_BOOL: case Automaton.K_INT: case Automaton.K_REAL: case Automaton.K_STRING: // no children break; case Automaton.K_LIST: case Automaton.K_SET: case Automaton.K_BAG: { Automaton.Collection c = (Automaton.Collection) state; return c.toArray(); } default: // terms Automaton.Term t = (Automaton.Term) state; if(t.contents > Automaton.K_VOID) { return new int[]{t.contents}; } } } return new int[0]; } public void dumpState() { for(int i=0;i!=automaton.nStates();++i) { System.out.print("*** CHILDREN(" + i + ")=" + Arrays.toString(children(i))); if(i < parents.size()) { System.out.print(" PARENTS: " + parents.get(i)); } System.out.println(); } } /** * Check that the reachability invariant holds. The reachability invariant * states that all non-null states in either the automaton or the parents * array are reachable from one or more roots. */ private void checkReachabilityInvariant() { boolean[] reachable = new boolean[automaton.nStates()]; for(int i=0;i!=automaton.nRoots();++i) { findReachable(automaton,reachable,automaton.getRoot(i)); } for(int i=0;i!=automaton.nStates();++i) { if(reachable[i] && automaton.get(i) == null) { traceOut(automaton,new boolean[reachable.length],i); throw new RuntimeException("*** INVALID REACHABILITY INVARIANT(1), STATE: " + i); } else if(reachable[i] && automaton.get(i) == null) { traceOut(automaton,new boolean[reachable.length],i); throw new RuntimeException("*** INVALID REACHABILITY INVARIANT(2), STATE: " + i); } else if(!reachable[i] && automaton.get(i) != null){ traceOut(automaton,new boolean[reachable.length],i); throw new RuntimeException("*** INVALID REACHABILITY INVARIANT(3), STATE: " + i); } else if(!reachable[i] && parents.get(i) != null){ traceOut(automaton,new boolean[reachable.length],i); ParentInfo pinfo = parents.get(i); for(int j=0;j!=pinfo.size;++j) { int parent = pinfo.parents[j]; System.out.println("CHILDREN(" + parent + ")=" + Arrays.toString(children(parent)) + " isReachable: " + reachable[parent]); } throw new RuntimeException("*** INVALID REACHABILITY INVARIANT(4), STATE: " + i + " (parents " + parents.get(i) + ")"); } } } /** * Visit all states reachable from a given starting state in the given * automaton. In doing this, states which are visited are marked and, * furthermore, those which are "headers" are additionally identified. A * header state is one which is the target of a back-edge in the directed * graph reachable from the start state. * * @param automaton * --- automaton to traverse. * @param reachable * --- states marked with false are those which have not been * visited. * @param index * --- state to begin traversal from. * @return */ public static void findReachable(Automaton automaton, boolean[] reachable, int index) { if (index < 0) { return; } else if (reachable[index]) { // Already visited, so terminate here return; } else { // Not previously visited, so mark now and traverse any children reachable[index] = true; Automaton.State state = automaton.get(index); if (state instanceof Automaton.Term) { Automaton.Term term = (Automaton.Term) state; if (term.contents != Automaton.K_VOID) { findReachable(automaton, reachable, term.contents); } } else if (state instanceof Automaton.Collection) { Automaton.Collection compound = (Automaton.Collection) state; for (int i = 0; i != compound.size(); ++i) { findReachable(automaton, reachable, compound.get(i)); } } } } public static void traceOut(Automaton automaton, boolean[] reachable, int index) { if (index < 0) { return; } else if (reachable[index]) { // Already visited, so terminate here return; } else { // Not previously visited, so mark now and traverse any children reachable[index] = true; Automaton.State state = automaton.get(index); if (state instanceof Automaton.Term) { Automaton.Term term = (Automaton.Term) state; if (term.contents != Automaton.K_VOID) { System.out.println("Traversing: " + index + "=>" + term.contents); traceOut(automaton, reachable, term.contents); } } else if (state instanceof Automaton.Collection) { Automaton.Collection compound = (Automaton.Collection) state; for (int i = 0; i != compound.size(); ++i) { System.out.println("Traversing: " + index + "=>" + compound.get(i)); traceOut(automaton, reachable, compound.get(i)); } } } } /** * Compute the parents for each state in the automaton from scratch. This is * done using several linear traversals over the states to minimise the * amount of memory churn and ensure linear time. * * @param automaton * @return */ private static ArrayList<ParentInfo> determineParents(Automaton automaton) { int[] counts = new int[automaton.nStates()]; // first, visit all nodes for (int i = 0; i != automaton.nStates(); ++i) { updateParentCounts(automaton.get(i),i,counts); } // ArrayList<ParentInfo> parents = new ArrayList<ParentInfo>(); for (int i = 0; i != automaton.nStates(); ++i) { parents.add(new ParentInfo(counts[i])); } // for (int i = 0; i != automaton.nStates(); ++i) { updateParents(automaton.get(i),i,parents); } // return parents; } /** * Update the parent count for each child (if any) of the given state. * * @param state * --- The state whose children we are interested in. * @param parent * --- The index of the state whose children we are interested * in. * @param counts * --- The array of parent counts for each state. */ private static void updateParentCounts(Automaton.State state, int parent, int[] counts) { switch(state.kind) { case Automaton.K_BOOL: case Automaton.K_INT: case Automaton.K_REAL: case Automaton.K_STRING: return; case Automaton.K_LIST: case Automaton.K_SET: case Automaton.K_BAG: { Automaton.Collection c = (Automaton.Collection) state; for(int i=0;i!=c.size();++i) { int child = c.get(i); if(child > Automaton.K_VOID) { counts[child]++; } } break; } default: // terms Automaton.Term t = (Automaton.Term) state; int child = t.contents; if(child > Automaton.K_VOID) { counts[child]++; } } } /** * Update the parents for each child (if any) of the given state. * * @param state * --- The state whose children we are interested in. * @param parent * --- The index of the state whose children we are interested * in. * @param counts * --- The array of parent counts for each state. * @param parents * --- The list of parents for each state. */ private static void updateParents(Automaton.State state, int parent, ArrayList<ParentInfo> parents) { switch(state.kind) { case Automaton.K_BOOL: case Automaton.K_INT: case Automaton.K_REAL: case Automaton.K_STRING: return; case Automaton.K_LIST: case Automaton.K_SET: case Automaton.K_BAG: { Automaton.Collection c = (Automaton.Collection) state; for(int i=0;i!=c.size();++i) { int child = c.get(i); if(child > Automaton.K_VOID) { parents.get(child).add(parent); } } break; } default: // terms Automaton.Term t = (Automaton.Term) state; int child = t.contents; if(child > Automaton.K_VOID) { parents.get(child).add(parent); } } } /** * A simple data structure for representing the parent information. This * could be made more interesting, for example, by using a sorted array. Or, * perhaps, a compressed bitset. * * @author David J. Pearce * */ private static final class ParentInfo { private int[] parents; private int size; public ParentInfo(int capacity) { this.parents = new int[capacity]; this.size = 0; } public int size() { return size; } public int get(int index) { return parents[index]; } public void add(int parent) { int index = indexOf(parents,size,parent); if(index == -1) { ensureCapacity((size+1)*1); parents[size++] = parent; } } public void addAll(ParentInfo pinfo) { int pinfo_size = pinfo.size; ensureCapacity(size+pinfo_size); for(int i=0;i!=pinfo_size;++i) { int parent = pinfo.parents[i]; if(indexOf(parents,size,parent) == -1) { parents[size++] = parent; } } } public void removeAll(int parent) { int index; // FIXME: this could be optimised while ((index = indexOf(parents, size, parent)) != -1) { System.arraycopy(parents, index + 1, parents, index, size - (index + 1)); size = size - 1; } } public void remap(int[] mapping) { for (int i = 0; i != size; ++i) { parents[i] = mapping[parents[i]]; } } public void replace(int from, int to) { int j = indexOf(parents,size,to); if(j == -1) { for(int i=0;i!=size;++i) { if(parents[i] == from) { parents[i] = to; } } } else { removeAll(from); } } public boolean contains(int parent) { return indexOf(parents,size,parent) != -1; } public String toString() { String r = ""; for(int i=0;i!=size;++i) { if(i != 0) { r += ","; } r = r + parents[i]; } return "{" + r + "}"; } private void ensureCapacity(int capacity) { if(parents.length < capacity) { parents = Arrays.copyOf(parents, capacity); } } private static int indexOf(int[] array, int size, int element) { for(int i=0;i!=size;++i) { if(array[i] == element) { return i; } } return -1; } } public final static class Worklist { public int[] items; public int size; public Worklist(int size) { this.items = new int[size]; } public void push(int item) { if(size == items.length) { items = Arrays.copyOf(items, items.length*2); } items[size++] = item; } public int pop() { size = size - 1; return items[size]; } } }
Add limited support for compacting above the pivot Compacting above the pivot needs to be done more aggressively. Also, need to compact in general.
src/wyrw/util/IncrementalAutomatonMinimiser.java
Add limited support for compacting above the pivot
<ide><path>rc/wyrw/util/IncrementalAutomatonMinimiser.java <ide> // completely pack above the pivot. That's because, by exploiting the <ide> // parent information we can quickly remap all states. <ide> int i = automaton.nStates(); <del> <del> while(i > pivot) { <del> if(automaton.get(i-1) != null) { <add> <add> while (i > pivot) { <add> if (automaton.get(i - 1) != null) { <ide> break; <ide> } <del> i = i - 1; <del> } <del> <add> i = i - 1; <add> } <add> <ide> automaton.resize(i); <ide> } <ide>
Java
lgpl-2.1
5cb4990a8b06b6949451770c9a6603dac26d484b
0
xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform
/** * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * <p/> * This is free software;you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation;either version2.1of * the License,or(at your option)any later version. * <p/> * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY;without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU * Lesser General Public License for more details. * <p/> * You should have received a copy of the GNU Lesser General Public * License along with this software;if not,write to the Free * Software Foundation,Inc.,51 Franklin St,Fifth Floor,Boston,MA * 02110-1301 USA,or see the FSF site:http://www.fsf.org. */ package com.xpn.xwiki.plugin.spacemanager.impl; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.List; import org.apache.commons.lang.ArrayUtils; import org.apache.velocity.VelocityContext; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.api.Api; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.classes.BaseClass; import com.xpn.xwiki.plugin.XWikiDefaultPlugin; import com.xpn.xwiki.plugin.XWikiPluginInterface; import com.xpn.xwiki.plugin.mailsender.Mail; import com.xpn.xwiki.plugin.mailsender.MailSenderPlugin; import com.xpn.xwiki.plugin.spacemanager.api.Space; import com.xpn.xwiki.plugin.spacemanager.api.SpaceManager; import com.xpn.xwiki.plugin.spacemanager.api.SpaceManagerException; import com.xpn.xwiki.plugin.spacemanager.api.SpaceManagerExtension; import com.xpn.xwiki.plugin.spacemanager.api.SpaceManagers; import com.xpn.xwiki.plugin.spacemanager.api.SpaceUserProfile; import com.xpn.xwiki.plugin.spacemanager.plugin.SpaceManagerPluginApi; import com.xpn.xwiki.render.XWikiVelocityRenderer; import com.xpn.xwiki.user.api.XWikiGroupService; /** * Space manager plug-in implementation class. Manages {@link Space} spaces * * @version $Id: $ */ public class SpaceManagerImpl extends XWikiDefaultPlugin implements SpaceManager { public final static String SPACEMANAGER_EXTENSION_CFG_PROP = "xwiki.spacemanager.extension"; public final static String SPACEMANAGER_PROTECTED_SUBSPACES_PROP = "xwiki.spacemanager.protectedsubspaces"; public final static String SPACEMANAGER_DEFAULT_PROTECTED_SUBSPACES = ""; public final static String SPACEMANAGER_DEFAULT_EXTENSION = "org.xwiki.plugin.spacemanager.impl.SpaceManagerExtensionImpl"; public final static String SPACEMANAGER_DEFAULT_MAIL_NOTIFICATION = "1"; /** * The extension that defines specific functions for this space manager */ protected SpaceManagerExtension spaceManagerExtension; protected boolean mailNotification; /** * Space manager constructor * * @param name * @param className * @param context */ public SpaceManagerImpl(String name, String className, XWikiContext context) { super(name, className, context); String mailNotificationCfg = context.getWiki().Param( "xwiki.spacemanager.mailnotification", SpaceManagerImpl.SPACEMANAGER_DEFAULT_MAIL_NOTIFICATION).trim(); mailNotification = "1".equals(mailNotificationCfg); } /** * {@inheritDoc} */ public void flushCache() { super.flushCache(); } /** * @param context * Xwiki context * @return Returns the Space Class as defined by the extension * @throws XWikiException */ protected BaseClass getSpaceClass(XWikiContext context) throws XWikiException { XWikiDocument doc; XWiki xwiki = context.getWiki(); boolean needsUpdate = false; try { doc = xwiki.getDocument(getSpaceClassName(), context); } catch (Exception e) { doc = new XWikiDocument(); doc.setFullName(getSpaceClassName()); needsUpdate = true; } BaseClass bclass = doc.getxWikiClass(); bclass.setName(getSpaceClassName()); needsUpdate |= bclass.addTextField(SpaceImpl.SPACE_DISPLAYTITLE, "Display Name", 64); needsUpdate |= bclass.addTextAreaField(SpaceImpl.SPACE_DESCRIPTION, "Description", 45, 4); needsUpdate |= bclass.addTextField(SpaceImpl.SPACE_TYPE, "Group or plain space", 32); needsUpdate |= bclass.addTextField(SpaceImpl.SPACE_URLSHORTCUT, "URL Shortcut", 40); needsUpdate |= bclass.addStaticListField(SpaceImpl.SPACE_POLICY, "Membership Policy", 1, false, "open=Open membership|closed=Closed membership", "radio"); needsUpdate |= bclass .addStaticListField( SpaceImpl.SPACE_LANGUAGE, "Language", "en=English|zh=Chinese|nl=Dutch|fr=French|de=German|it=Italian|jp=Japanese|kr=Korean|po=Portuguese|ru=Russian|sp=Spanish"); String content = doc.getContent(); if ((content == null) || (content.equals(""))) { needsUpdate = true; doc.setContent("1 XWikiSpaceClass"); } if (needsUpdate) xwiki.saveDocument(doc, context); return bclass; } /** * {@inheritDoc} */ public String getSpaceTypeName() { return getSpaceManagerExtension().getSpaceTypeName(); } /** * {@inheritDoc} */ public String getSpaceClassName() { return getSpaceManagerExtension().getSpaceClassName(); } /** * Checks if this space manager has custom mapping * * @return */ public boolean hasCustomMapping() { return getSpaceManagerExtension().hasCustomMapping(); } /** * {@inheritDoc} */ public void init(XWikiContext context) { try { getSpaceManagerExtension(context); getSpaceManagerExtension().init(this, context); SpaceManagers.addSpaceManager(this); getSpaceClass(context); SpaceUserProfileImpl.getSpaceUserProfileClass(context); } catch (Exception e) { e.printStackTrace(); } } /** * {@inheritDoc} */ public void virtualInit(XWikiContext context) { try { getSpaceClass(context); getSpaceManagerExtension().virtualInit(this, context); } catch (Exception e) { e.printStackTrace(); } } /** * {@inheritDoc} */ public Api getPluginApi(XWikiPluginInterface plugin, XWikiContext context) { return new SpaceManagerPluginApi((SpaceManager) plugin, context); } /** * {@inheritDoc} */ public SpaceManagerExtension getSpaceManagerExtension(XWikiContext context) throws SpaceManagerException { if (spaceManagerExtension == null) { String extensionName = context.getWiki().Param( SPACEMANAGER_EXTENSION_CFG_PROP, SPACEMANAGER_DEFAULT_EXTENSION); try { if (extensionName != null) { spaceManagerExtension = (SpaceManagerExtension) Class .forName(extensionName).newInstance(); } } catch (Throwable e) { try { spaceManagerExtension = (SpaceManagerExtension) Class .forName(SPACEMANAGER_DEFAULT_EXTENSION) .newInstance(); } catch (Throwable e2) { } } } if (spaceManagerExtension == null) { spaceManagerExtension = new SpaceManagerExtensionImpl(); } return spaceManagerExtension; } public SpaceManagerExtension getSpaceManagerExtension() { return spaceManagerExtension; } /** * {@inheritDoc} */ public String getName() { return "spacemanager"; } private Object notImplemented() throws SpaceManagerException { throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_XWIKI_NOT_IMPLEMENTED, "not implemented"); } /** * {@inheritDoc} */ public String getSpaceWikiName(String spaceTitle, boolean unique, XWikiContext context) { return getSpaceManagerExtension().getSpaceWikiName(spaceTitle, unique, context); } /** * @param spaceName * The name of the space * @return the name of the space document for a specific space */ protected String getSpaceDocumentName(String spaceName) { return spaceName + ".WebPreferences"; } /** * {@inheritDoc} */ public String[] getProtectedSubSpaces(XWikiContext context) { String protectedSubSpaces = context.getWiki().Param( SPACEMANAGER_PROTECTED_SUBSPACES_PROP, SPACEMANAGER_DEFAULT_PROTECTED_SUBSPACES); if ((protectedSubSpaces != null) && (!protectedSubSpaces.equals(""))) { return protectedSubSpaces.split(","); } else { return new String[0]; } } /** * Gives a group certain rights over a space * * @param spaceName * Name of the space * @param groupName * Name of the group that will have the value * @param level * Access level * @param allow * True if the right is allow, deny if not */ protected boolean addRightToGroup(String spaceName, String groupName, String level, boolean allow, boolean global, XWikiContext context) throws XWikiException { final String rightsClass = global ? "XWiki.XWikiGlobalRights" : "XWiki.XWikiRights"; final String prefDocName = spaceName + ".WebPreferences"; final String groupsField = "groups"; final String levelsField = "levels"; final String allowField = "allow"; XWikiDocument prefDoc; prefDoc = context.getWiki().getDocument(prefDocName, context); // checks to see if the right is not already given boolean exists = false; boolean isUpdated = false; int indx = -1; boolean foundlevel = false; int allowInt; if (allow) allowInt = 1; else allowInt = 0; List objs = prefDoc.getObjects(rightsClass); if (objs != null) { for (int i = 0; i < objs.size(); i++) { BaseObject bobj = (BaseObject) objs.get(i); if (bobj == null) continue; String groups = bobj.getStringValue(groupsField); String levels = bobj.getStringValue(levelsField); int allowDeny = bobj.getIntValue(allowField); boolean allowdeny = (bobj.getIntValue(allowField) == 1); String[] levelsarray = levels.split(" ,|"); String[] groupsarray = groups.split(" ,|"); if (ArrayUtils.contains(groupsarray, groupName)) { exists = true; if (!foundlevel) indx = i; if (ArrayUtils.contains(levelsarray, level)) { foundlevel = true; if (allowInt == allowDeny) { isUpdated = true; break; } } } } } // sets the rights. the aproach is to break rules/levels in as many // XWikiRigts elements so // we don't have to handle lots of situation when we change rights if (!exists) { BaseObject bobj = new BaseObject(); bobj.setClassName(rightsClass); bobj.setName(prefDoc.getFullName()); bobj.setStringValue(groupsField, groupName); bobj.setStringValue(levelsField, level); bobj.setIntValue(allowField, allowInt); prefDoc.addObject(rightsClass, bobj); context.getWiki().saveDocument(prefDoc, context); return true; } else { if (isUpdated) { return true; } else { BaseObject bobj = (BaseObject) objs.get(indx); String groups = bobj.getStringValue(groupsField); String levels = bobj.getStringValue(levelsField); String[] levelsarray = levels.split(" ,|"); String[] groupsarray = groups.split(" ,|"); if (levelsarray.length == 1 && groupsarray.length == 1 && levelsarray[0] == level) { // if there is only this group and this level in the rule // update this rule } else { // if there are more groups/levels, extract this one(s) bobj = new BaseObject(); bobj.setName(prefDoc.getFullName()); bobj.setClassName(rightsClass); bobj.setStringValue(levelsField, level); bobj.setIntValue(allowField, allowInt); bobj.setStringValue(groupsField, groupName); } prefDoc.addObject(rightsClass, bobj); context.getWiki().saveDocument(prefDoc, context); return true; } } } /** * Gives a group certain rights over a space * * @param spaceName * Name of the space * @param groupName * Name of the group that will have the value * @param level * Access level * @param allow * True if the right is allow, deny if not */ protected boolean removeRightFromGroup(String spaceName, String groupName, String level, boolean allow, boolean global, XWikiContext context) throws XWikiException { final String rightsClass = global ? "XWiki.XWikiGlobalRights" : "XWiki.XWikiRights"; final String prefDocName = spaceName + ".WebPreferences"; final String groupsField = "groups"; final String levelsField = "levels"; final String allowField = "allow"; XWikiDocument prefDoc; prefDoc = context.getWiki().getDocument(prefDocName, context); boolean foundlevel = false; int allowInt; if (allow) allowInt = 1; else allowInt = 0; List objs = prefDoc.getObjects(rightsClass); if (objs != null) { for (int i = 0; i < objs.size(); i++) { BaseObject bobj = (BaseObject) objs.get(i); if (bobj == null) continue; String groups = bobj.getStringValue(groupsField); String levels = bobj.getStringValue(levelsField); int allowDeny = bobj.getIntValue(allowField); boolean allowdeny = (bobj.getIntValue(allowField) == 1); String[] levelsarray = levels.split(" ,|"); String[] groupsarray = groups.split(" ,|"); if (ArrayUtils.contains(groupsarray, groupName)) { if (!foundlevel) if (ArrayUtils.contains(levelsarray, level)) { foundlevel = true; if (allowInt == allowDeny) { prefDoc.removeObject(bobj); context.getWiki() .saveDocument(prefDoc, context); return true; } } } } } return false; } /** * {@inheritDoc} */ public void setSpaceRights(Space newspace, XWikiContext context) throws SpaceManagerException { // Set admin edit rights on group prefs try { addRightToGroup(newspace.getSpaceName(), getAdminGroupName(newspace .getSpaceName()), "edit", true, false, context); // Set admin admin rights on group prefs addRightToGroup(newspace.getSpaceName(), getAdminGroupName(newspace .getSpaceName()), "admin", true, true, context); } catch (XWikiException e) { throw new SpaceManagerException(e); } String[] subSpaces = getProtectedSubSpaces(context); for (int i = 0; i < subSpaces.length; i++) { setSubSpaceRights(newspace, subSpaces[i], context); } } /** * {@inheritDoc} */ public void updateSpaceRights(Space space, String oldPolicy, String newPolicy, XWikiContext context) throws SpaceManagerException { try { if (oldPolicy.equals(newPolicy)) return; String[] subSpaces = getProtectedSubSpaces(context); for (int i = 0; i < subSpaces.length; i++) { if (newPolicy.equals("closed")) { addRightToGroup(subSpaces[i] + "_" + space.getSpaceName(), getMemberGroupName(space.getSpaceName()), "view", true, false, context); addRightToGroup(subSpaces[i] + "_" + space.getSpaceName(), getMemberGroupName(space.getSpaceName()), "comment", true, false, context); } else if (newPolicy.equals("open")) { removeRightFromGroup(subSpaces[i] + "_" + space.getSpaceName(), getMemberGroupName(space .getSpaceName()), "view", true, false, context); removeRightFromGroup(subSpaces[i] + "_" + space.getSpaceName(), getMemberGroupName(space .getSpaceName()), "comment", true, false, context); } } } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} */ public void setSubSpaceRights(Space space, String subSpace, XWikiContext context) throws SpaceManagerException { try { if ((subSpace != null) && (!subSpace.equals(""))) { // Set admin edit rights on Messages group prefs addRightToGroup(subSpace + "_" + space.getSpaceName(), getMemberGroupName(space.getSpaceName()), "edit", true, true, context); // Set admin admin rights on Messages group prefs addRightToGroup(subSpace + "_" + space.getSpaceName(), getAdminGroupName(space.getSpaceName()), "admin", true, true, context); // Set admin admin rights on Messages group prefs addRightToGroup(subSpace + "_" + space.getSpaceName(), getAdminGroupName(space.getSpaceName()), "edit", true, false, context); if ("closed".equals(space.getPolicy())) { addRightToGroup(subSpace + "_" + space.getSpaceName(), getMemberGroupName(space.getSpaceName()), "view", true, false, context); addRightToGroup(subSpace + "_" + space.getSpaceName(), getMemberGroupName(space.getSpaceName()), "comment", true, false, context); } } } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} */ public Space createSpace(String spaceTitle, XWikiContext context) throws SpaceManagerException { // Init out space object by creating the space // this will throw an exception when the space exists Space newspace = newSpace(null, spaceTitle, true, context); // execute precreate actions try { getSpaceManagerExtension().preCreateSpace(newspace.getSpaceName(), context); } catch (SpaceManagerException e) { throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_CREATION_ABORTED_BY_EXTENSION, "Space creation aborted by extension", e); } // Make sure we set the type newspace.setType(getSpaceTypeName()); try { newspace.saveWithProgrammingRights(); // we need to add the creator as a member and as an admin addAdmin(newspace.getSpaceName(), context.getUser(), context); addMember(newspace.getSpaceName(), context.getUser(), context); setSpaceRights(newspace, context); // execute post space creation getSpaceManagerExtension().postCreateSpace(newspace.getSpaceName(), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } sendMail(SpaceAction.CREATE, newspace, context); // this should be in // the extension's // postcreate return newspace; } /** * {@inheritDoc} */ public Space createSpaceFromTemplate(String spaceTitle, String templateSpaceName, XWikiContext context) throws SpaceManagerException { // Init out space object by creating the space // this will throw an exception when the space exists Space newspace = newSpace(null, spaceTitle, false, context); // execute precreate actions try { getSpaceManagerExtension().preCreateSpace(newspace.getSpaceName(), context); } catch (SpaceManagerException e) { throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_CREATION_ABORTED_BY_EXTENSION, "Space creation aborted by extension", e); } // Make sure this space does not already exist if (!newspace.isNew()) throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_ALREADY_EXISTS, "Space already exists"); // Copy over template data over our current data try { context.getWiki() .copyWikiWeb(templateSpaceName, context.getDatabase(), context.getDatabase(), null, context); } catch (XWikiException e) { throw new SpaceManagerException(e); } // Make sure we set the type newspace.setType(getSpaceTypeName()); newspace.setDisplayTitle(spaceTitle); newspace.setCreator(context.getUser()); newspace.setCreationDate(new Date()); try { newspace.saveWithProgrammingRights(); // we need to add the creator as a member and as an admin addAdmin(newspace.getSpaceName(), context.getUser(), context); addMember(newspace.getSpaceName(), context.getUser(), context); setSpaceRights(newspace, context); // execute post space creation getSpaceManagerExtension().postCreateSpace(newspace.getSpaceName(), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } sendMail(SpaceAction.CREATE, newspace, context); return newspace; } /** * {@inheritDoc} */ public Space createSpaceFromApplication(String spaceTitle, String applicationName, XWikiContext context) throws SpaceManagerException { notImplemented(); return null; } /** * {@inheritDoc} */ public Space createSpaceFromRequest(String templateSpaceName, XWikiContext context) throws SpaceManagerException { // Init out space object by creating the space // this will throw an exception when the space exists String spaceTitle = context.getRequest().get( spaceManagerExtension.getSpaceClassName() + "_0_displayTitle"); if (spaceTitle == null) { throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_TITLE_MISSING, "Space title is missing"); } Space newspace = newSpace(null, spaceTitle, true, context); // execute precreate actions try { getSpaceManagerExtension().preCreateSpace(newspace.getSpaceName(), context); } catch (SpaceManagerException e) { throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_CREATION_ABORTED_BY_EXTENSION, "Space creation aborted by extension", e); } newspace.updateSpaceFromRequest(); if (!newspace.validateSpaceData()) throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_DATA_INVALID, "Space data is not valid"); // Copy over template data over our current data if (templateSpaceName != null) { try { List list = context.getWiki().getStore().searchDocumentsNames( "where doc.web='" + templateSpaceName + "'", context); for (Iterator it = list.iterator(); it.hasNext();) { String docname = (String) it.next(); XWikiDocument doc = context.getWiki().getDocument(docname, context); context.getWiki().copyDocument(doc.getFullName(), newspace.getSpaceName() + "." + doc.getName(), null, null, null, true, false, true, context); } } catch (XWikiException e) { throw new SpaceManagerException(e); } } // Make sure we set the type newspace.setType(getSpaceTypeName()); // we need to do it twice because data could have been overwritten by // copyWikiWeb newspace.updateSpaceFromRequest(); newspace.setCreator(context.getUser()); newspace.setCreationDate(new Date()); try { newspace.saveWithProgrammingRights(); // we need to add the creator as a member and as an admin addAdmin(newspace.getSpaceName(), context.getUser(), context); addMember(newspace.getSpaceName(), context.getUser(), context); setSpaceRights(newspace, context); // execute precreate actions getSpaceManagerExtension().postCreateSpace(newspace.getSpaceName(), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } sendMail(SpaceAction.CREATE, newspace, context); return newspace; } protected Space newSpace(String spaceName, String spaceTitle, boolean create, XWikiContext context) throws SpaceManagerException { return new SpaceImpl(spaceName, spaceTitle, create, this, context); } /** * {@inheritDoc} */ public Space createSpaceFromRequest(XWikiContext context) throws SpaceManagerException { return createSpaceFromRequest(null, context); } /** * {@inheritDoc} */ public void deleteSpace(String spaceName, boolean deleteData, XWikiContext context) throws SpaceManagerException { if (deleteData) { // we are not implementing full delete yet throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_XWIKI_NOT_IMPLEMENTED, "Not implemented"); } Space space = getSpace(spaceName, context); // execute pre delete actions if (getSpaceManagerExtension().preDeleteSpace(space.getSpaceName(), deleteData, context)) { if (!space.isNew()) { space.setType("deleted"); try { space.saveWithProgrammingRights(); // execute post delete actions getSpaceManagerExtension().postDeleteSpace( space.getSpaceName(), deleteData, context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } } } /** * {@inheritDoc} */ public void deleteSpace(String spaceName, XWikiContext context) throws SpaceManagerException { deleteSpace(spaceName, false, context); } /** * {@inheritDoc} */ public void undeleteSpace(String spaceName, XWikiContext context) throws SpaceManagerException { Space space = getSpace(spaceName, context); if (space.isDeleted()) { space.setType(getSpaceTypeName()); try { space.saveWithProgrammingRights(); } catch (XWikiException e) { throw new SpaceManagerException(e); } } } /** * {@inheritDoc} */ public Space getSpace(String spaceName, XWikiContext context) throws SpaceManagerException { // Init the space object but do not create anything if it does not exist return newSpace(spaceName, spaceName, false, context); } /** * {@inheritDoc} */ public List getSpaces(int nb, int start, XWikiContext context) throws SpaceManagerException { List spaceNames = getSpaceNames(nb, start, context); return getSpaceObjects(spaceNames, context); } public List getSpaces(int nb, int start, String ordersql, XWikiContext context) throws SpaceManagerException { List spaceNames = getSpaceNames(nb, start, ordersql, context); return getSpaceObjects(spaceNames, context); } /** * Returns a list of nb space names starting at start * * @param context * The XWiki Context * @return list of Space objects * @throws SpaceManagerException */ protected List getSpaceObjects(List spaceNames, XWikiContext context) throws SpaceManagerException { if (spaceNames == null) return null; List spaceList = new ArrayList(); for (int i = 0; i < spaceNames.size(); i++) { String spaceName = (String) spaceNames.get(i); Space space = getSpace(spaceName, context); spaceList.add(space); } return spaceList; } public List getSpaceNames(int nb, int start, XWikiContext context) throws SpaceManagerException { return getSpaceNames(nb, start, "", context); } /** * {@inheritDoc} */ public List getSpaceNames(int nb, int start, String ordersql, XWikiContext context) throws SpaceManagerException { String type = getSpaceTypeName(); String className = getSpaceClassName(); String sql; if (hasCustomMapping()) sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, " + className + " as space where doc.fullName = obj.name and obj.className='" + className + "' and obj.id = space.id and space.type='" + type + "'" + ordersql; else sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, StringProperty typeprop where doc.fullName=obj.name and obj.className = '" + className + "' and obj.id=typeprop.id.id and typeprop.id.name='type' and typeprop.value='" + type + "'" + ordersql; List spaceList = null; try { spaceList = context.getWiki().getStore().search(sql, nb, start, context); } catch (XWikiException e) { throw new SpaceManagerException(e); } return spaceList; } /** * Performs a search for spaces * * @param fromsql * The sql fragment describing the source of the search * @param wheresql * The sql fragment describing the where clause of the search * @param ordersql * The sql fragment describing the order in wich the spaces * should be returned * @param nb * The number of spaces to return (limit) * @param start * Number of spaces to skip * @param context * XWiki context * @return A list with space objects matching the search * @throws SpaceManagerException */ public List searchSpaces(String fromsql, String wheresql, String ordersql, int nb, int start, XWikiContext context) throws SpaceManagerException { List spaceNames = searchSpaceNames(fromsql, wheresql, ordersql, nb, start, context); return getSpaceObjects(spaceNames, context); } /** * Performs a search for spaces. This variant returns the spaces ordered * ascending by creation date * * @param fromsql * The sql fragment describing the source of the search * @param wheresql * The sql fragment describing the where clause of the search * @param nb * The number of spaces to return (limit) * @param start * Number of spaces to skip * @param context * XWiki context * @return A list with space objects matching the search * @throws SpaceManagerException */ public List searchSpaces(String fromsql, String wheresql, int nb, int start, XWikiContext context) throws SpaceManagerException { return searchSpaces(fromsql, wheresql, "", nb, start, context); } /** * Performs a search for space names * * @param fromsql * The sql fragment describing the source of the search * @param wheresql * The sql fragment describing the where clause of the search * @param ordersql * The sql fragment describing the order in wich the spaces * should be returned * @param nb * The number of spaces to return (limit) * @param start * Number of spaces to skip * @param context * XWiki context * @return A list of strings representing the names of the spaces matching * the search * @throws SpaceManagerException */ public List searchSpaceNames(String fromsql, String wheresql, String ordersql, int nb, int start, XWikiContext context) throws SpaceManagerException { String type = getSpaceTypeName(); String className = getSpaceClassName(); String sql; if (hasCustomMapping()) sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, " + className + " as space" + fromsql + " where doc.fullName = obj.name and obj.className='" + className + "' and obj.id = space.id and space.type='" + type + "'" + wheresql + ordersql; else sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, StringProperty as typeprop" + fromsql + " where doc.fullName=obj.name and obj.className = '" + className + "' and obj.id=typeprop.id.id and typeprop.id.name='type' and typeprop.value='" + type + "'" + wheresql + ordersql; List spaceList = null; try { spaceList = context.getWiki().getStore().search(sql, nb, start, context); } catch (XWikiException e) { throw new SpaceManagerException(e); } return spaceList; } /** * Performs a search for space names. This variant returns the spaces * ordered ascending by creation date * * @param fromsql * The sql fragment describing the source of the search * @param wheresql * The sql fragment describing the where clause of the search * @param nb * The number of spaces to return (limit) * @param start * Number of spaces to skip * @param context * XWiki context * @return A list of strings representing the names of the spaces matching * the search * @throws SpaceManagerException */ public List searchSpaceNames(String fromsql, String wheresql, int nb, int start, XWikiContext context) throws SpaceManagerException { return searchSpaceNames(fromsql, wheresql, "", nb, start, context); } /** * {@inheritDoc} */ public List getSpaces(String userName, String role, XWikiContext context) throws SpaceManagerException { List spaceNames = getSpaceNames(userName, role, context); return getSpaceObjects(spaceNames, context); } /** * {@inheritDoc} */ public List getSpaceNames(String userName, String role, XWikiContext context) throws SpaceManagerException { String sql; if (role == null) sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, StringProperty as memberprop where doc.name='MemberGroup' and doc.fullName=obj.name and obj.className = 'XWiki.XWikiGroups'" + " and obj.id=memberprop.id.id and memberprop.id.name='member' and memberprop.value='" + userName + "'"; else { String roleGroupName = getRoleGroupName("", role).substring(1); sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, StringProperty as memberprop where doc.name='" + roleGroupName + "' and doc.fullName=obj.name and obj.className = 'XWiki.XWikiGroups'" + " and obj.id=memberprop.id.id and memberprop.id.name='member' and memberprop.value='" + userName + "'"; } List spaceList = null; try { spaceList = context.getWiki().getStore().search(sql, 0, 0, context); } catch (XWikiException e) { throw new SpaceManagerException(e); } return spaceList; } /** * {@inheritDoc} */ public boolean updateSpaceFromRequest(Space space, XWikiContext context) throws SpaceManagerException { space.updateSpaceFromRequest(); if (space.validateSpaceData()) return true; else return false; } /** * {@inheritDoc} */ public boolean validateSpaceData(Space space, XWikiContext context) throws SpaceManagerException { return space.validateSpaceData(); } /** * {@inheritDoc} */ public void saveSpace(Space space, XWikiContext context) throws SpaceManagerException { try { space.saveWithProgrammingRights(); } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} */ public void addAdmin(String spaceName, String username, XWikiContext context) throws SpaceManagerException { try { addUserToGroup(username, getAdminGroupName(spaceName), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} */ public void addAdmins(String spaceName, List usernames, XWikiContext context) throws SpaceManagerException { for (int i = 0; i < usernames.size(); i++) { addAdmin(spaceName, (String) usernames.get(i), context); } } /** * {@inheritDoc} */ public Collection getAdmins(String spaceName, XWikiContext context) throws SpaceManagerException { try { return getGroupService(context).getAllMembersNamesForGroup( getAdminGroupName(spaceName), 0, 0, context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} * * @see SpaceManager#removeAdmin(String, String, XWikiContext) */ public void removeAdmin(String spaceName, String userName, XWikiContext context) throws SpaceManagerException { try { removeUserFromGroup(userName, getAdminGroupName(spaceName), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} */ public boolean isAdmin(String spaceName, String userName, XWikiContext context) throws SpaceManagerException { try { return isMemberOfGroup(userName, getAdminGroupName(spaceName), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} */ public void addUserToRole(String spaceName, String username, String role, XWikiContext context) throws SpaceManagerException { try { addUserToGroup(username, getRoleGroupName(spaceName, role), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} */ public void addUsersToRole(String spaceName, List usernames, String role, XWikiContext context) throws SpaceManagerException { for (int i = 0; i < usernames.size(); i++) { addUserToRole(spaceName, (String) usernames.get(i), role, context); } } /** * {@inheritDoc} */ public Collection getUsersForRole(String spaceName, String role, XWikiContext context) throws SpaceManagerException { try { return sortUserNames(getGroupService(context) .getAllMembersNamesForGroup( getRoleGroupName(spaceName, role), 0, 0, context), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} */ public boolean isMember(String spaceName, String username, XWikiContext context) throws SpaceManagerException { try { return isMemberOfGroup(username, getMemberGroupName(spaceName), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} */ public void addUserToRoles(String spaceName, String username, List roles, XWikiContext context) throws SpaceManagerException { for (int i = 0; i < roles.size(); i++) { addUserToRole(spaceName, username, (String) roles.get(i), context); } } /** * {@inheritDoc} */ public void addUsersToRoles(String spaceName, List usernames, List roles, XWikiContext context) throws SpaceManagerException { for (int i = 0; i < usernames.size(); i++) { addUserToRoles(spaceName, (String) usernames.get(i), roles, context); } } /** * {@inheritDoc} * * @see SpaceManager#removeUserFromRoles(String, String, List, XWikiContext) */ public void removeUserFromRoles(String spaceName, String userName, List roles, XWikiContext context) throws SpaceManagerException { for (int i = 0; i < roles.size(); i++) { removeUserFromRole(spaceName, userName, (String) roles.get(i), context); } } /** * {@inheritDoc} */ public void removeUserFromRole(String spaceName, String userName, String role, XWikiContext context) throws SpaceManagerException { try { removeUserFromGroup(userName, getRoleGroupName(spaceName, role), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} */ public void addMember(String spaceName, String username, XWikiContext context) throws SpaceManagerException { try { addUserToGroup(username, getMemberGroupName(spaceName), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} * * @see SpaceManager#removeMember(String, String, XWikiContext) */ public void removeMember(String spaceName, String userName, XWikiContext context) throws SpaceManagerException { try { // remove admin role if (isAdmin(spaceName, userName, context)) { removeAdmin(spaceName, userName, context); } // remove all the other roles // Iterator it = getRoles(spaceName, context).iterator(); // while (it.hasNext()) { // String role = (String) it.next(); // removeUserFromRole(spaceName, userName, role, context); // } // delete space user profile deleteSpaceUserProfile(spaceName, userName, context); // remove member removeUserFromGroup(userName, getMemberGroupName(spaceName), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } protected boolean isMemberOfGroup(String username, String groupname, XWikiContext context) throws XWikiException { Collection coll = context.getWiki().getGroupService(context) .getAllGroupsNamesForMember(username, 0, 0, context); Iterator it = coll.iterator(); while (it.hasNext()) { if (groupname.equals((String) it.next())) return true; } return false; } /** * High speed user adding without resaving the whole groups doc * * @param username * @param groupName * @param context * @throws XWikiException */ protected void addUserToGroup(String username, String groupName, XWikiContext context) throws XWikiException { // don't add if he is already a member if (isMemberOfGroup(username, groupName, context)) return; XWiki xwiki = context.getWiki(); BaseClass groupClass = xwiki.getGroupClass(context); XWikiDocument groupDoc = xwiki.getDocument(groupName, context); BaseObject memberObject = (BaseObject) groupClass.newObject(context); memberObject.setClassName(groupClass.getName()); memberObject.setName(groupDoc.getFullName()); memberObject.setStringValue("member", username); groupDoc.addObject(groupClass.getName(), memberObject); String content = groupDoc.getContent(); if ((content == null) || (content.equals(""))) groupDoc.setContent("#includeForm(\"XWiki.XWikiGroupSheet\")"); xwiki.saveDocument(groupDoc, context.getMessageTool().get( "core.comment.addedUserToGroup"), context); /* * if (groupDoc.isNew()) { } else { * xwiki.getHibernateStore().saveXWikiObject(memberObject, context, * true); } // we need to make sure we add the user to the group cache * try { xwiki.getGroupService(context).addUserToGroup(username, * context.getDatabase(), groupName, context); } catch (Exception e) {} */ } private void removeUserFromGroup(String userName, String groupName, XWikiContext context) throws XWikiException { // don't remove if he's not a member if (!isMemberOfGroup(userName, groupName, context)) { return; } XWiki xwiki = context.getWiki(); BaseClass groupClass = xwiki.getGroupClass(context); XWikiDocument groupDoc = xwiki.getDocument(groupName, context); BaseObject memberObject = groupDoc.getObject(groupClass.getName(), "member", userName); if (memberObject == null) { return; } groupDoc.removeObject(memberObject); xwiki.saveDocument(groupDoc, context.getMessageTool().get( "core.comment.removedUserFromGroup"), context); } /** * {@inheritDoc} */ public void addMembers(String spaceName, List usernames, XWikiContext context) throws SpaceManagerException { for (int i = 0; i < usernames.size(); i++) { addMember(spaceName, (String) usernames.get(i), context); } } /** * {@inheritDoc} * * @see SpaceManager#getMembers(String, XWikiContext) */ public Collection getMembers(String spaceName, XWikiContext context) throws SpaceManagerException { try { return sortUserNames(getGroupService(context) .getAllMembersNamesForGroup(getMemberGroupName(spaceName), 0, 0, context), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } private List sortUserNames(Collection collectionOfUsers, final XWikiContext context) { List users = new ArrayList(collectionOfUsers); Collections.sort(users, new Comparator() { public int compare(Object a, Object b) { try { XWikiDocument aDoc = context.getWiki().getDocument( (String) a, context); XWikiDocument bDoc = context.getWiki().getDocument( (String) b, context); String aFirstName = aDoc.getObject("XWiki.XWikiUsers") .getStringValue("first_name"); String bFirstName = bDoc.getObject("XWiki.XWikiUsers") .getStringValue("first_name"); int cmp = aFirstName.compareToIgnoreCase(bFirstName); if (cmp == 0) { String aLastName = aDoc.getObject("XWiki.XWikiUsers") .getStringValue("last_name"); String bLastName = bDoc.getObject("XWiki.XWikiUsers") .getStringValue("last_name"); return aLastName.compareTo(bLastName); } else { return cmp; } } catch (Exception e) { return ((String) a).compareTo((String) b); } } }); return users; } public String getMemberGroupName(String spaceName) { return getSpaceManagerExtension().getMemberGroupName(spaceName); } public String getAdminGroupName(String spaceName) { return getSpaceManagerExtension().getAdminGroupName(spaceName); } public String getRoleGroupName(String spaceName, String role) { return getSpaceManagerExtension().getRoleGroupName(spaceName, role); } protected XWikiGroupService getGroupService(XWikiContext context) throws XWikiException { return context.getWiki().getGroupService(context); } public SpaceUserProfile getSpaceUserProfile(String spaceName, String username, XWikiContext context) throws SpaceManagerException { return newUserSpaceProfile(username, spaceName, context); } private void deleteSpaceUserProfile(String spaceName, String userName, XWikiContext context) throws SpaceManagerException { try { String docName = getSpaceUserProfilePageName(userName, spaceName); XWikiDocument doc = context.getWiki().getDocument(docName, context); if (!doc.isNew()) context.getWiki().deleteDocument(doc, context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } public String getSpaceUserProfilePageName(String userName, String spaceName) { return getSpaceManagerExtension().getSpaceUserProfilePageName(userName, spaceName); } protected SpaceUserProfile newUserSpaceProfile(String user, String space, XWikiContext context) throws SpaceManagerException { try { return new SpaceUserProfileImpl(user, space, this, context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} */ public List getLastModifiedDocuments(String spaceName, XWikiContext context, boolean recursive, int nb, int start) throws SpaceManagerException { notImplemented(); return null; } /** * {@inheritDoc} */ public Collection getRoles(String spaceName, XWikiContext context) throws SpaceManagerException { notImplemented(); return null; } /** * {@inheritDoc} * * @see SpaceManager#getRoles(String, String, XWikiContext) */ public Collection getRoles(String spaceName, String memberName, XWikiContext context) throws SpaceManagerException { try { Collection memberRoles = context.getWiki().getGroupService(context) .getAllGroupsNamesForMember(memberName, 0, 0, context); Collection spaceRoles = getRoles(spaceName, context); memberRoles.retainAll(spaceRoles); return memberRoles; } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} */ public List getLastModifiedDocuments(String spaceName, XWikiContext context) throws SpaceManagerException { notImplemented(); return null; } /** * {@inheritDoc} */ public List searchDocuments(String spaceName, String hql, XWikiContext context) throws SpaceManagerException { notImplemented(); return null; } /** * {@inheritDoc} */ public int countSpaces(XWikiContext context) throws SpaceManagerException { String type = getSpaceTypeName(); String className = getSpaceClassName(); String sql; if (hasCustomMapping()) sql = "select count(*) from XWikiDocument as doc, BaseObject as obj, " + className + " as space" + " where doc.fullName = obj.name and obj.className='" + className + "' and obj.id = space.id and space.type='" + type + "'"; else sql = "select count(*) from XWikiDocument as doc, BaseObject as obj, StringProperty as typeprop" + " where doc.fullName=obj.name and obj.className = '" + className + "' and obj.id=typeprop.id.id and typeprop.id.name='type' and typeprop.value='" + type + "'"; try { List result = context.getWiki().search(sql, context); Integer res = (Integer) result.get(0); return res.intValue(); } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} * * @see SpaceManager#joinSpace(String, XWikiContext) */ public boolean joinSpace(String spaceName, XWikiContext context) throws SpaceManagerException { try { SpaceUserProfile userProfile = newUserSpaceProfile(context .getUser(), spaceName, context); userProfile.updateProfileFromRequest(); userProfile.saveWithProgrammingRights(); addMember(spaceName, context.getUser(), context); sendMail(SpaceAction.JOIN, getSpace(spaceName, context), context); return true; } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * Helper function to send email after a space action. This mail template * full name is composed of the space name and the action with the following * convention : spaceName + "." + "MailTemplate" + action + "Space", as in * MySpace.MailTemplateJoinSpace * * @see getTemplateMailPageName * @param action * the action which triggered the mail sending. See * {@link SpaceManager.SpaceAction} for possible actions. * @param space * The space on which the action has triggered the mail sending * @throws SpaceManagerException */ private void sendMail(String action, Space space, XWikiContext context) throws SpaceManagerException { if (!mailNotification) { return; } VelocityContext vContext = new VelocityContext(); vContext.put("space", space); String fromUser = context.getWiki().getXWikiPreference("space_email", context); if (fromUser == null || fromUser.trim().length() == 0) { fromUser = context.getWiki().getXWikiPreference("admin_email", context); } String[] toUsers = new String[0]; if (SpaceAction.CREATE.equals(action)) { // notify space administrators upon space creation Collection admins = getAdmins(space.getSpaceName(), context); toUsers = (String[]) admins.toArray(new String[admins.size()]); } else if (SpaceAction.JOIN.equals(action)) { // send join group confirmation e-mail boolean optOutEmail = context.getWiki().getUserPreferenceAsInt("opt_out", context) != 0; if (optOutEmail) { return; } else { toUsers = new String[] {context.getUser()}; } } if (fromUser == null) { throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_SENDER_EMAIL_INVALID, "Sender email is invalid"); } boolean toUsersValid = toUsers.length > 0; for (int i = 0; i < toUsers.length && toUsersValid; i++) { if (!isEmailAddress(toUsers[i])) { toUsers[i] = getEmailAddress(toUsers[i], context); } if (toUsers[i] == null) { toUsersValid = false; } } if (!toUsersValid) { throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_TARGET_EMAIL_INVALID, "Target email is invalid"); } String strToUsers = join(toUsers, ","); MailSenderPlugin mailSender = getMailSenderPlugin(context); try { String templateDocFullName = getTemplateMailPageName(space .getSpaceName(), action, context); XWikiDocument mailDoc = context.getWiki().getDocument( templateDocFullName, context); XWikiDocument translatedMailDoc = mailDoc .getTranslatedDocument(context); mailSender.prepareVelocityContext(fromUser, strToUsers, "", vContext, context); vContext.put("xwiki", new com.xpn.xwiki.api.XWiki( context.getWiki(), context)); vContext.put("context", new com.xpn.xwiki.api.Context(context)); String mailSubject = XWikiVelocityRenderer .evaluate(translatedMailDoc.getTitle(), templateDocFullName, vContext); String mailContent = XWikiVelocityRenderer.evaluate( translatedMailDoc.getContent(), templateDocFullName, vContext); Mail mail = new Mail(fromUser, strToUsers, null, null, mailSubject, mailContent, null); mailSender.sendMail(mail, context); } catch (Exception e) { throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_SENDING_EMAIL_FAILED, "Sending notification email failed", e); } } private MailSenderPlugin getMailSenderPlugin(XWikiContext context) throws SpaceManagerException { MailSenderPlugin mailSender = (MailSenderPlugin) context.getWiki() .getPlugin("mailsender", context); if (mailSender == null) throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_MANAGER_REQUIRES_MAILSENDER_PLUGIN, "SpaceManager requires the mail sender plugin"); return mailSender; } // code duplicated from InvitationManagerImpl !!! private static final String join(String[] array, String separator) { StringBuffer result = new StringBuffer(""); if (array.length > 0) { result.append(array[0]); } for (int i = 1; i < array.length; i++) { result.append("," + array[i]); } return result.toString(); } // code duplicated from InvitationManagerImpl !!! private boolean isEmailAddress(String str) { return str.contains("@"); } // code duplicated from InvitationManagerImpl !!! private String getEmailAddress(String user, XWikiContext context) throws SpaceManagerException { try { String wikiuser = (user.startsWith("XWiki.")) ? user : "XWiki." + user; if (wikiuser == null) return null; XWikiDocument userDoc = null; userDoc = context.getWiki().getDocument(wikiuser, context); if (userDoc.isNew()) return null; String email = ""; try { email = userDoc.getObject("XWiki.XWikiUsers").getStringValue( "email"); } catch (Exception e) { return null; } if ((email == null) || (email.equals(""))) return null; return email; } catch (Exception e) { throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_CANNOT_FIND_EMAIL_ADDRESS, "Cannot find email address of user " + user, e); } } /** * Convention based private helper to retrieve a mail template full name * from a space name and an action name. TODO I think we should have the * possibility to select for each action a template that is not located in * the space itself, but in another web of the wiki. This would be to avoid * copying this template each time we create a space if its content is not * supposed to be modified, And thus reduce the impact of space creation on * the db size. */ private String getTemplateMailPageName(String spaceName, String action, XWikiContext context) { String docName = spaceName + "." + "MailTemplate" + action + "Space"; try { if (context.getWiki().getDocument(docName, context).isNew()) { docName = null; } } catch (XWikiException e) { docName = null; } if (docName == null) { docName = getDefaultResourceSpace(context) + "." + "MailTemplate" + action + "Space"; } return docName; } private String getDefaultResourceSpace(XWikiContext context) { return context.getWiki().Param("xwiki.spacemanager.resourcespace", SpaceManager.DEFAULT_RESOURCE_SPACE); } public boolean isMailNotification() { return mailNotification; } public void setMailNotification(boolean mailNotification) { this.mailNotification = mailNotification; } }
xwiki-platform-tag/plugin/spacemanager/src/main/java/com/xpn/xwiki/plugin/spacemanager/impl/SpaceManagerImpl.java
/** * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * <p/> * This is free software;you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation;either version2.1of * the License,or(at your option)any later version. * <p/> * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY;without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU * Lesser General Public License for more details. * <p/> * You should have received a copy of the GNU Lesser General Public * License along with this software;if not,write to the Free * Software Foundation,Inc.,51 Franklin St,Fifth Floor,Boston,MA * 02110-1301 USA,or see the FSF site:http://www.fsf.org. */ package com.xpn.xwiki.plugin.spacemanager.impl; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.List; import org.apache.commons.lang.ArrayUtils; import org.apache.velocity.VelocityContext; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.api.Api; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.classes.BaseClass; import com.xpn.xwiki.plugin.XWikiDefaultPlugin; import com.xpn.xwiki.plugin.XWikiPluginInterface; import com.xpn.xwiki.plugin.mailsender.Mail; import com.xpn.xwiki.plugin.mailsender.MailSenderPlugin; import com.xpn.xwiki.plugin.spacemanager.api.Space; import com.xpn.xwiki.plugin.spacemanager.api.SpaceManager; import com.xpn.xwiki.plugin.spacemanager.api.SpaceManagerException; import com.xpn.xwiki.plugin.spacemanager.api.SpaceManagerExtension; import com.xpn.xwiki.plugin.spacemanager.api.SpaceManagers; import com.xpn.xwiki.plugin.spacemanager.api.SpaceUserProfile; import com.xpn.xwiki.plugin.spacemanager.plugin.SpaceManagerPluginApi; import com.xpn.xwiki.render.XWikiVelocityRenderer; import com.xpn.xwiki.user.api.XWikiGroupService; /** * Space manager plug-in implementation class. Manages {@link Space} spaces * * @version $Id: $ */ public class SpaceManagerImpl extends XWikiDefaultPlugin implements SpaceManager { public final static String SPACEMANAGER_EXTENSION_CFG_PROP = "xwiki.spacemanager.extension"; public final static String SPACEMANAGER_PROTECTED_SUBSPACES_PROP = "xwiki.spacemanager.protectedsubspaces"; public final static String SPACEMANAGER_DEFAULT_PROTECTED_SUBSPACES = ""; public final static String SPACEMANAGER_DEFAULT_EXTENSION = "org.xwiki.plugin.spacemanager.impl.SpaceManagerExtensionImpl"; public final static String SPACEMANAGER_DEFAULT_MAIL_NOTIFICATION = "1"; /** * The extension that defines specific functions for this space manager */ protected SpaceManagerExtension spaceManagerExtension; protected boolean mailNotification; /** * Space manager constructor * * @param name * @param className * @param context */ public SpaceManagerImpl(String name, String className, XWikiContext context) { super(name, className, context); String mailNotificationCfg = context.getWiki().Param( "xwiki.spacemanager.mailnotification", SpaceManagerImpl.SPACEMANAGER_DEFAULT_MAIL_NOTIFICATION).trim(); mailNotification = "1".equals(mailNotificationCfg); } /** * {@inheritDoc} */ public void flushCache() { super.flushCache(); } /** * @param context * Xwiki context * @return Returns the Space Class as defined by the extension * @throws XWikiException */ protected BaseClass getSpaceClass(XWikiContext context) throws XWikiException { XWikiDocument doc; XWiki xwiki = context.getWiki(); boolean needsUpdate = false; try { doc = xwiki.getDocument(getSpaceClassName(), context); } catch (Exception e) { doc = new XWikiDocument(); doc.setFullName(getSpaceClassName()); needsUpdate = true; } BaseClass bclass = doc.getxWikiClass(); bclass.setName(getSpaceClassName()); needsUpdate |= bclass.addTextField(SpaceImpl.SPACE_DISPLAYTITLE, "Display Name", 64); needsUpdate |= bclass.addTextAreaField(SpaceImpl.SPACE_DESCRIPTION, "Description", 45, 4); needsUpdate |= bclass.addTextField(SpaceImpl.SPACE_TYPE, "Group or plain space", 32); needsUpdate |= bclass.addTextField(SpaceImpl.SPACE_URLSHORTCUT, "URL Shortcut", 40); needsUpdate |= bclass.addStaticListField(SpaceImpl.SPACE_POLICY, "Membership Policy", 1, false, "open=Open membership|closed=Closed membership", "radio"); needsUpdate |= bclass .addStaticListField( SpaceImpl.SPACE_LANGUAGE, "Language", "en=English|zh=Chinese|nl=Dutch|fr=French|de=German|it=Italian|jp=Japanese|kr=Korean|po=Portuguese|ru=Russian|sp=Spanish"); String content = doc.getContent(); if ((content == null) || (content.equals(""))) { needsUpdate = true; doc.setContent("1 XWikiSpaceClass"); } if (needsUpdate) xwiki.saveDocument(doc, context); return bclass; } /** * {@inheritDoc} */ public String getSpaceTypeName() { return getSpaceManagerExtension().getSpaceTypeName(); } /** * {@inheritDoc} */ public String getSpaceClassName() { return getSpaceManagerExtension().getSpaceClassName(); } /** * Checks if this space manager has custom mapping * * @return */ public boolean hasCustomMapping() { return getSpaceManagerExtension().hasCustomMapping(); } /** * {@inheritDoc} */ public void init(XWikiContext context) { try { getSpaceManagerExtension(context); getSpaceManagerExtension().init(this, context); SpaceManagers.addSpaceManager(this); getSpaceClass(context); SpaceUserProfileImpl.getSpaceUserProfileClass(context); } catch (Exception e) { e.printStackTrace(); } } /** * {@inheritDoc} */ public void virtualInit(XWikiContext context) { try { getSpaceClass(context); getSpaceManagerExtension().virtualInit(this, context); } catch (Exception e) { e.printStackTrace(); } } /** * {@inheritDoc} */ public Api getPluginApi(XWikiPluginInterface plugin, XWikiContext context) { return new SpaceManagerPluginApi((SpaceManager) plugin, context); } /** * {@inheritDoc} */ public SpaceManagerExtension getSpaceManagerExtension(XWikiContext context) throws SpaceManagerException { if (spaceManagerExtension == null) { String extensionName = context.getWiki().Param( SPACEMANAGER_EXTENSION_CFG_PROP, SPACEMANAGER_DEFAULT_EXTENSION); try { if (extensionName != null) { spaceManagerExtension = (SpaceManagerExtension) Class .forName(extensionName).newInstance(); } } catch (Throwable e) { try { spaceManagerExtension = (SpaceManagerExtension) Class .forName(SPACEMANAGER_DEFAULT_EXTENSION) .newInstance(); } catch (Throwable e2) { } } } if (spaceManagerExtension == null) { spaceManagerExtension = new SpaceManagerExtensionImpl(); } return spaceManagerExtension; } public SpaceManagerExtension getSpaceManagerExtension() { return spaceManagerExtension; } /** * {@inheritDoc} */ public String getName() { return "spacemanager"; } private Object notImplemented() throws SpaceManagerException { throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_XWIKI_NOT_IMPLEMENTED, "not implemented"); } /** * {@inheritDoc} */ public String getSpaceWikiName(String spaceTitle, boolean unique, XWikiContext context) { return getSpaceManagerExtension().getSpaceWikiName(spaceTitle, unique, context); } /** * @param spaceName * The name of the space * @return the name of the space document for a specific space */ protected String getSpaceDocumentName(String spaceName) { return spaceName + ".WebPreferences"; } /** * {@inheritDoc} */ public String[] getProtectedSubSpaces(XWikiContext context) { String protectedSubSpaces = context.getWiki().Param( SPACEMANAGER_PROTECTED_SUBSPACES_PROP, SPACEMANAGER_DEFAULT_PROTECTED_SUBSPACES); if ((protectedSubSpaces != null) && (!protectedSubSpaces.equals(""))) { return protectedSubSpaces.split(","); } else { return new String[0]; } } /** * Gives a group certain rights over a space * * @param spaceName * Name of the space * @param groupName * Name of the group that will have the value * @param level * Access level * @param allow * True if the right is allow, deny if not */ protected boolean addRightToGroup(String spaceName, String groupName, String level, boolean allow, boolean global, XWikiContext context) throws XWikiException { final String rightsClass = global ? "XWiki.XWikiGlobalRights" : "XWiki.XWikiRights"; final String prefDocName = spaceName + ".WebPreferences"; final String groupsField = "groups"; final String levelsField = "levels"; final String allowField = "allow"; XWikiDocument prefDoc; prefDoc = context.getWiki().getDocument(prefDocName, context); // checks to see if the right is not already given boolean exists = false; boolean isUpdated = false; int indx = -1; boolean foundlevel = false; int allowInt; if (allow) allowInt = 1; else allowInt = 0; List objs = prefDoc.getObjects(rightsClass); if (objs != null) { for (int i = 0; i < objs.size(); i++) { BaseObject bobj = (BaseObject) objs.get(i); if (bobj == null) continue; String groups = bobj.getStringValue(groupsField); String levels = bobj.getStringValue(levelsField); int allowDeny = bobj.getIntValue(allowField); boolean allowdeny = (bobj.getIntValue(allowField) == 1); String[] levelsarray = levels.split(" ,|"); String[] groupsarray = groups.split(" ,|"); if (ArrayUtils.contains(groupsarray, groupName)) { exists = true; if (!foundlevel) indx = i; if (ArrayUtils.contains(levelsarray, level)) { foundlevel = true; if (allowInt == allowDeny) { isUpdated = true; break; } } } } } // sets the rights. the aproach is to break rules/levels in as many // XWikiRigts elements so // we don't have to handle lots of situation when we change rights if (!exists) { BaseObject bobj = new BaseObject(); bobj.setClassName(rightsClass); bobj.setName(prefDoc.getFullName()); bobj.setStringValue(groupsField, groupName); bobj.setStringValue(levelsField, level); bobj.setIntValue(allowField, allowInt); prefDoc.addObject(rightsClass, bobj); context.getWiki().saveDocument(prefDoc, context); return true; } else { if (isUpdated) { return true; } else { BaseObject bobj = (BaseObject) objs.get(indx); String groups = bobj.getStringValue(groupsField); String levels = bobj.getStringValue(levelsField); String[] levelsarray = levels.split(" ,|"); String[] groupsarray = groups.split(" ,|"); if (levelsarray.length == 1 && groupsarray.length == 1 && levelsarray[0] == level) { // if there is only this group and this level in the rule // update this rule } else { // if there are more groups/levels, extract this one(s) bobj = new BaseObject(); bobj.setName(prefDoc.getFullName()); bobj.setClassName(rightsClass); bobj.setStringValue(levelsField, level); bobj.setIntValue(allowField, allowInt); bobj.setStringValue(groupsField, groupName); } prefDoc.addObject(rightsClass, bobj); context.getWiki().saveDocument(prefDoc, context); return true; } } } /** * Gives a group certain rights over a space * * @param spaceName * Name of the space * @param groupName * Name of the group that will have the value * @param level * Access level * @param allow * True if the right is allow, deny if not */ protected boolean removeRightFromGroup(String spaceName, String groupName, String level, boolean allow, boolean global, XWikiContext context) throws XWikiException { final String rightsClass = global ? "XWiki.XWikiGlobalRights" : "XWiki.XWikiRights"; final String prefDocName = spaceName + ".WebPreferences"; final String groupsField = "groups"; final String levelsField = "levels"; final String allowField = "allow"; XWikiDocument prefDoc; prefDoc = context.getWiki().getDocument(prefDocName, context); boolean foundlevel = false; int allowInt; if (allow) allowInt = 1; else allowInt = 0; List objs = prefDoc.getObjects(rightsClass); if (objs != null) { for (int i = 0; i < objs.size(); i++) { BaseObject bobj = (BaseObject) objs.get(i); if (bobj == null) continue; String groups = bobj.getStringValue(groupsField); String levels = bobj.getStringValue(levelsField); int allowDeny = bobj.getIntValue(allowField); boolean allowdeny = (bobj.getIntValue(allowField) == 1); String[] levelsarray = levels.split(" ,|"); String[] groupsarray = groups.split(" ,|"); if (ArrayUtils.contains(groupsarray, groupName)) { if (!foundlevel) if (ArrayUtils.contains(levelsarray, level)) { foundlevel = true; if (allowInt == allowDeny) { prefDoc.removeObject(bobj); context.getWiki() .saveDocument(prefDoc, context); return true; } } } } } return false; } /** * {@inheritDoc} */ public void setSpaceRights(Space newspace, XWikiContext context) throws SpaceManagerException { // Set admin edit rights on group prefs try { addRightToGroup(newspace.getSpaceName(), getAdminGroupName(newspace .getSpaceName()), "edit", true, false, context); // Set admin admin rights on group prefs addRightToGroup(newspace.getSpaceName(), getAdminGroupName(newspace .getSpaceName()), "admin", true, true, context); } catch (XWikiException e) { throw new SpaceManagerException(e); } String[] subSpaces = getProtectedSubSpaces(context); for (int i = 0; i < subSpaces.length; i++) { setSubSpaceRights(newspace, subSpaces[i], context); } } /** * {@inheritDoc} */ public void updateSpaceRights(Space space, String oldPolicy, String newPolicy, XWikiContext context) throws SpaceManagerException { try { if (oldPolicy.equals(newPolicy)) return; String[] subSpaces = getProtectedSubSpaces(context); for (int i = 0; i < subSpaces.length; i++) { if (newPolicy.equals("closed")) { addRightToGroup(subSpaces[i] + "_" + space.getSpaceName(), getMemberGroupName(space.getSpaceName()), "view", true, false, context); addRightToGroup(subSpaces[i] + "_" + space.getSpaceName(), getMemberGroupName(space.getSpaceName()), "comment", true, false, context); } else if (newPolicy.equals("open")) { removeRightFromGroup(subSpaces[i] + "_" + space.getSpaceName(), getMemberGroupName(space .getSpaceName()), "view", true, false, context); removeRightFromGroup(subSpaces[i] + "_" + space.getSpaceName(), getMemberGroupName(space .getSpaceName()), "comment", true, false, context); } } } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} */ public void setSubSpaceRights(Space space, String subSpace, XWikiContext context) throws SpaceManagerException { try { if ((subSpace != null) && (!subSpace.equals(""))) { // Set admin edit rights on Messages group prefs addRightToGroup(subSpace + "_" + space.getSpaceName(), getMemberGroupName(space.getSpaceName()), "edit", true, true, context); // Set admin admin rights on Messages group prefs addRightToGroup(subSpace + "_" + space.getSpaceName(), getAdminGroupName(space.getSpaceName()), "admin", true, true, context); // Set admin admin rights on Messages group prefs addRightToGroup(subSpace + "_" + space.getSpaceName(), getAdminGroupName(space.getSpaceName()), "edit", true, false, context); if ("closed".equals(space.getPolicy())) { addRightToGroup(subSpace + "_" + space.getSpaceName(), getMemberGroupName(space.getSpaceName()), "view", true, false, context); addRightToGroup(subSpace + "_" + space.getSpaceName(), getMemberGroupName(space.getSpaceName()), "comment", true, false, context); } } } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} */ public Space createSpace(String spaceTitle, XWikiContext context) throws SpaceManagerException { // Init out space object by creating the space // this will throw an exception when the space exists Space newspace = newSpace(null, spaceTitle, true, context); // execute precreate actions try { getSpaceManagerExtension().preCreateSpace(newspace.getSpaceName(), context); } catch (SpaceManagerException e) { throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_CREATION_ABORTED_BY_EXTENSION, "Space creation aborted by extension", e); } // Make sure we set the type newspace.setType(getSpaceTypeName()); try { newspace.saveWithProgrammingRights(); // we need to add the creator as a member and as an admin addAdmin(newspace.getSpaceName(), context.getUser(), context); addMember(newspace.getSpaceName(), context.getUser(), context); setSpaceRights(newspace, context); // execute post space creation getSpaceManagerExtension().postCreateSpace(newspace.getSpaceName(), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } sendMail(SpaceAction.CREATE, newspace, context); // this should be in // the extension's // postcreate return newspace; } /** * {@inheritDoc} */ public Space createSpaceFromTemplate(String spaceTitle, String templateSpaceName, XWikiContext context) throws SpaceManagerException { // Init out space object by creating the space // this will throw an exception when the space exists Space newspace = newSpace(null, spaceTitle, false, context); // execute precreate actions try { getSpaceManagerExtension().preCreateSpace(newspace.getSpaceName(), context); } catch (SpaceManagerException e) { throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_CREATION_ABORTED_BY_EXTENSION, "Space creation aborted by extension", e); } // Make sure this space does not already exist if (!newspace.isNew()) throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_ALREADY_EXISTS, "Space already exists"); // Copy over template data over our current data try { context.getWiki() .copyWikiWeb(templateSpaceName, context.getDatabase(), context.getDatabase(), null, context); } catch (XWikiException e) { throw new SpaceManagerException(e); } // Make sure we set the type newspace.setType(getSpaceTypeName()); newspace.setDisplayTitle(spaceTitle); newspace.setCreator(context.getUser()); newspace.setCreationDate(new Date()); try { newspace.saveWithProgrammingRights(); // we need to add the creator as a member and as an admin addAdmin(newspace.getSpaceName(), context.getUser(), context); addMember(newspace.getSpaceName(), context.getUser(), context); setSpaceRights(newspace, context); // execute post space creation getSpaceManagerExtension().postCreateSpace(newspace.getSpaceName(), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } sendMail(SpaceAction.CREATE, newspace, context); return newspace; } /** * {@inheritDoc} */ public Space createSpaceFromApplication(String spaceTitle, String applicationName, XWikiContext context) throws SpaceManagerException { notImplemented(); return null; } /** * {@inheritDoc} */ public Space createSpaceFromRequest(String templateSpaceName, XWikiContext context) throws SpaceManagerException { // Init out space object by creating the space // this will throw an exception when the space exists String spaceTitle = context.getRequest().get( spaceManagerExtension.getSpaceClassName() + "_0_displayTitle"); if (spaceTitle == null) { throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_TITLE_MISSING, "Space title is missing"); } Space newspace = newSpace(null, spaceTitle, true, context); // execute precreate actions try { getSpaceManagerExtension().preCreateSpace(newspace.getSpaceName(), context); } catch (SpaceManagerException e) { throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_CREATION_ABORTED_BY_EXTENSION, "Space creation aborted by extension", e); } newspace.updateSpaceFromRequest(); if (!newspace.validateSpaceData()) throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_DATA_INVALID, "Space data is not valid"); // Copy over template data over our current data if (templateSpaceName != null) { try { List list = context.getWiki().getStore().searchDocumentsNames( "where doc.web='" + templateSpaceName + "'", context); for (Iterator it = list.iterator(); it.hasNext();) { String docname = (String) it.next(); XWikiDocument doc = context.getWiki().getDocument(docname, context); context.getWiki().copyDocument(doc.getFullName(), newspace.getSpaceName() + "." + doc.getName(), null, null, null, true, false, true, context); } } catch (XWikiException e) { throw new SpaceManagerException(e); } } // Make sure we set the type newspace.setType(getSpaceTypeName()); // we need to do it twice because data could have been overwritten by // copyWikiWeb newspace.updateSpaceFromRequest(); newspace.setCreator(context.getUser()); newspace.setCreationDate(new Date()); try { newspace.saveWithProgrammingRights(); // we need to add the creator as a member and as an admin addAdmin(newspace.getSpaceName(), context.getUser(), context); addMember(newspace.getSpaceName(), context.getUser(), context); setSpaceRights(newspace, context); // execute precreate actions getSpaceManagerExtension().postCreateSpace(newspace.getSpaceName(), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } sendMail(SpaceAction.CREATE, newspace, context); return newspace; } protected Space newSpace(String spaceName, String spaceTitle, boolean create, XWikiContext context) throws SpaceManagerException { return new SpaceImpl(spaceName, spaceTitle, create, this, context); } /** * {@inheritDoc} */ public Space createSpaceFromRequest(XWikiContext context) throws SpaceManagerException { return createSpaceFromRequest(null, context); } /** * {@inheritDoc} */ public void deleteSpace(String spaceName, boolean deleteData, XWikiContext context) throws SpaceManagerException { if (deleteData) { // we are not implementing full delete yet throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_XWIKI_NOT_IMPLEMENTED, "Not implemented"); } Space space = getSpace(spaceName, context); // execute pre delete actions if (getSpaceManagerExtension().preDeleteSpace(space.getSpaceName(), deleteData, context)) { if (!space.isNew()) { space.setType("deleted"); try { space.saveWithProgrammingRights(); // execute post delete actions getSpaceManagerExtension().postDeleteSpace( space.getSpaceName(), deleteData, context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } } } /** * {@inheritDoc} */ public void deleteSpace(String spaceName, XWikiContext context) throws SpaceManagerException { deleteSpace(spaceName, false, context); } /** * {@inheritDoc} */ public void undeleteSpace(String spaceName, XWikiContext context) throws SpaceManagerException { Space space = getSpace(spaceName, context); if (space.isDeleted()) { space.setType(getSpaceTypeName()); try { space.saveWithProgrammingRights(); } catch (XWikiException e) { throw new SpaceManagerException(e); } } } /** * {@inheritDoc} */ public Space getSpace(String spaceName, XWikiContext context) throws SpaceManagerException { // Init the space object but do not create anything if it does not exist return newSpace(spaceName, spaceName, false, context); } /** * {@inheritDoc} */ public List getSpaces(int nb, int start, XWikiContext context) throws SpaceManagerException { List spaceNames = getSpaceNames(nb, start, context); return getSpaceObjects(spaceNames, context); } public List getSpaces(int nb, int start, String ordersql, XWikiContext context) throws SpaceManagerException { List spaceNames = getSpaceNames(nb, start, ordersql, context); return getSpaceObjects(spaceNames, context); } /** * Returns a list of nb space names starting at start * * @param context * The XWiki Context * @return list of Space objects * @throws SpaceManagerException */ protected List getSpaceObjects(List spaceNames, XWikiContext context) throws SpaceManagerException { if (spaceNames == null) return null; List spaceList = new ArrayList(); for (int i = 0; i < spaceNames.size(); i++) { String spaceName = (String) spaceNames.get(i); Space space = getSpace(spaceName, context); spaceList.add(space); } return spaceList; } public List getSpaceNames(int nb, int start, XWikiContext context) throws SpaceManagerException { return getSpaceNames(nb, start, "", context); } /** * {@inheritDoc} */ public List getSpaceNames(int nb, int start, String ordersql, XWikiContext context) throws SpaceManagerException { String type = getSpaceTypeName(); String className = getSpaceClassName(); String sql; if (hasCustomMapping()) sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, " + className + " as space where doc.fullName = obj.name and obj.className='" + className + "' and obj.id = space.id and space.type='" + type + "'" + ordersql; else sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, StringProperty typeprop where doc.fullName=obj.name and obj.className = '" + className + "' and obj.id=typeprop.id.id and typeprop.id.name='type' and typeprop.value='" + type + "'" + ordersql; List spaceList = null; try { spaceList = context.getWiki().getStore().search(sql, nb, start, context); } catch (XWikiException e) { throw new SpaceManagerException(e); } return spaceList; } /** * Performs a search for spaces * * @param fromsql * The sql fragment describing the source of the search * @param wheresql * The sql fragment describing the where clause of the search * @param ordersql * The sql fragment describing the order in wich the spaces * should be returned * @param nb * The number of spaces to return (limit) * @param start * Number of spaces to skip * @param context * XWiki context * @return A list with space objects matching the search * @throws SpaceManagerException */ public List searchSpaces(String fromsql, String wheresql, String ordersql, int nb, int start, XWikiContext context) throws SpaceManagerException { List spaceNames = searchSpaceNames(fromsql, wheresql, ordersql, nb, start, context); return getSpaceObjects(spaceNames, context); } /** * Performs a search for spaces. This variant returns the spaces ordered * ascending by creation date * * @param fromsql * The sql fragment describing the source of the search * @param wheresql * The sql fragment describing the where clause of the search * @param nb * The number of spaces to return (limit) * @param start * Number of spaces to skip * @param context * XWiki context * @return A list with space objects matching the search * @throws SpaceManagerException */ public List searchSpaces(String fromsql, String wheresql, int nb, int start, XWikiContext context) throws SpaceManagerException { return searchSpaces(fromsql, wheresql, "", nb, start, context); } /** * Performs a search for space names * * @param fromsql * The sql fragment describing the source of the search * @param wheresql * The sql fragment describing the where clause of the search * @param ordersql * The sql fragment describing the order in wich the spaces * should be returned * @param nb * The number of spaces to return (limit) * @param start * Number of spaces to skip * @param context * XWiki context * @return A list of strings representing the names of the spaces matching * the search * @throws SpaceManagerException */ public List searchSpaceNames(String fromsql, String wheresql, String ordersql, int nb, int start, XWikiContext context) throws SpaceManagerException { String type = getSpaceTypeName(); String className = getSpaceClassName(); String sql; if (hasCustomMapping()) sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, " + className + " as space" + fromsql + " where doc.fullName = obj.name and obj.className='" + className + "' and obj.id = space.id and space.type='" + type + "'" + wheresql + ordersql; else sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, StringProperty as typeprop" + fromsql + " where doc.fullName=obj.name and obj.className = '" + className + "' and obj.id=typeprop.id.id and typeprop.id.name='type' and typeprop.value='" + type + "'" + wheresql + ordersql; List spaceList = null; try { spaceList = context.getWiki().getStore().search(sql, nb, start, context); } catch (XWikiException e) { throw new SpaceManagerException(e); } return spaceList; } /** * Performs a search for space names. This variant returns the spaces * ordered ascending by creation date * * @param fromsql * The sql fragment describing the source of the search * @param wheresql * The sql fragment describing the where clause of the search * @param nb * The number of spaces to return (limit) * @param start * Number of spaces to skip * @param context * XWiki context * @return A list of strings representing the names of the spaces matching * the search * @throws SpaceManagerException */ public List searchSpaceNames(String fromsql, String wheresql, int nb, int start, XWikiContext context) throws SpaceManagerException { return searchSpaceNames(fromsql, wheresql, "", nb, start, context); } /** * {@inheritDoc} */ public List getSpaces(String userName, String role, XWikiContext context) throws SpaceManagerException { List spaceNames = getSpaceNames(userName, role, context); return getSpaceObjects(spaceNames, context); } /** * {@inheritDoc} */ public List getSpaceNames(String userName, String role, XWikiContext context) throws SpaceManagerException { String sql; if (role == null) sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, StringProperty as memberprop where doc.name='MemberGroup' and doc.fullName=obj.name and obj.className = 'XWiki.XWikiGroups'" + " and obj.id=memberprop.id.id and memberprop.id.name='member' and memberprop.value='" + userName + "'"; else { String roleGroupName = getRoleGroupName("", role).substring(1); sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, StringProperty as memberprop where doc.name='" + roleGroupName + "' and doc.fullName=obj.name and obj.className = 'XWiki.XWikiGroups'" + " and obj.id=memberprop.id.id and memberprop.id.name='member' and memberprop.value='" + userName + "'"; } List spaceList = null; try { spaceList = context.getWiki().getStore().search(sql, 0, 0, context); } catch (XWikiException e) { throw new SpaceManagerException(e); } return spaceList; } /** * {@inheritDoc} */ public boolean updateSpaceFromRequest(Space space, XWikiContext context) throws SpaceManagerException { space.updateSpaceFromRequest(); if (space.validateSpaceData()) return true; else return false; } /** * {@inheritDoc} */ public boolean validateSpaceData(Space space, XWikiContext context) throws SpaceManagerException { return space.validateSpaceData(); } /** * {@inheritDoc} */ public void saveSpace(Space space, XWikiContext context) throws SpaceManagerException { try { space.saveWithProgrammingRights(); } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} */ public void addAdmin(String spaceName, String username, XWikiContext context) throws SpaceManagerException { try { addUserToGroup(username, getAdminGroupName(spaceName), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} */ public void addAdmins(String spaceName, List usernames, XWikiContext context) throws SpaceManagerException { for (int i = 0; i < usernames.size(); i++) { addAdmin(spaceName, (String) usernames.get(i), context); } } /** * {@inheritDoc} */ public Collection getAdmins(String spaceName, XWikiContext context) throws SpaceManagerException { try { return getGroupService(context).getAllMembersNamesForGroup( getAdminGroupName(spaceName), 0, 0, context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} * * @see SpaceManager#removeAdmin(String, String, XWikiContext) */ public void removeAdmin(String spaceName, String userName, XWikiContext context) throws SpaceManagerException { try { removeUserFromGroup(userName, getAdminGroupName(spaceName), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} */ public boolean isAdmin(String spaceName, String userName, XWikiContext context) throws SpaceManagerException { try { return isMemberOfGroup(userName, getAdminGroupName(spaceName), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} */ public void addUserToRole(String spaceName, String username, String role, XWikiContext context) throws SpaceManagerException { try { addUserToGroup(username, getRoleGroupName(spaceName, role), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} */ public void addUsersToRole(String spaceName, List usernames, String role, XWikiContext context) throws SpaceManagerException { for (int i = 0; i < usernames.size(); i++) { addUserToRole(spaceName, (String) usernames.get(i), role, context); } } /** * {@inheritDoc} */ public Collection getUsersForRole(String spaceName, String role, XWikiContext context) throws SpaceManagerException { try { return sortUserNames(getGroupService(context) .getAllMembersNamesForGroup( getRoleGroupName(spaceName, role), 0, 0, context), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} */ public boolean isMember(String spaceName, String username, XWikiContext context) throws SpaceManagerException { try { return isMemberOfGroup(username, getMemberGroupName(spaceName), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} */ public void addUserToRoles(String spaceName, String username, List roles, XWikiContext context) throws SpaceManagerException { for (int i = 0; i < roles.size(); i++) { addUserToRole(spaceName, username, (String) roles.get(i), context); } } /** * {@inheritDoc} */ public void addUsersToRoles(String spaceName, List usernames, List roles, XWikiContext context) throws SpaceManagerException { for (int i = 0; i < usernames.size(); i++) { addUserToRoles(spaceName, (String) usernames.get(i), roles, context); } } /** * {@inheritDoc} * * @see SpaceManager#removeUserFromRoles(String, String, List, XWikiContext) */ public void removeUserFromRoles(String spaceName, String userName, List roles, XWikiContext context) throws SpaceManagerException { for (int i = 0; i < roles.size(); i++) { removeUserFromRole(spaceName, userName, (String) roles.get(i), context); } } /** * {@inheritDoc} */ public void removeUserFromRole(String spaceName, String userName, String role, XWikiContext context) throws SpaceManagerException { try { removeUserFromGroup(userName, getRoleGroupName(spaceName, role), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} */ public void addMember(String spaceName, String username, XWikiContext context) throws SpaceManagerException { try { addUserToGroup(username, getMemberGroupName(spaceName), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} * * @see SpaceManager#removeMember(String, String, XWikiContext) */ public void removeMember(String spaceName, String userName, XWikiContext context) throws SpaceManagerException { try { // remove admin role if (isAdmin(spaceName, userName, context)) { removeAdmin(spaceName, userName, context); } // remove all the other roles // Iterator it = getRoles(spaceName, context).iterator(); // while (it.hasNext()) { // String role = (String) it.next(); // removeUserFromRole(spaceName, userName, role, context); // } // delete space user profile deleteSpaceUserProfile(spaceName, userName, context); // remove member removeUserFromGroup(userName, getMemberGroupName(spaceName), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } protected boolean isMemberOfGroup(String username, String groupname, XWikiContext context) throws XWikiException { Collection coll = context.getWiki().getGroupService(context) .getAllGroupsNamesForMember(username, 0, 0, context); Iterator it = coll.iterator(); while (it.hasNext()) { if (groupname.equals((String) it.next())) return true; } return false; } /** * High speed user adding without resaving the whole groups doc * * @param username * @param groupName * @param context * @throws XWikiException */ protected void addUserToGroup(String username, String groupName, XWikiContext context) throws XWikiException { // don't add if he is already a member if (isMemberOfGroup(username, groupName, context)) return; XWiki xwiki = context.getWiki(); BaseClass groupClass = xwiki.getGroupClass(context); XWikiDocument groupDoc = xwiki.getDocument(groupName, context); BaseObject memberObject = (BaseObject) groupClass.newObject(context); memberObject.setClassName(groupClass.getName()); memberObject.setName(groupDoc.getFullName()); memberObject.setStringValue("member", username); groupDoc.addObject(groupClass.getName(), memberObject); String content = groupDoc.getContent(); if ((content == null) || (content.equals(""))) groupDoc.setContent("#includeForm(\"XWiki.XWikiGroupSheet\")"); xwiki.saveDocument(groupDoc, context.getMessageTool().get( "core.comment.addedUserToGroup"), context); /* * if (groupDoc.isNew()) { } else { * xwiki.getHibernateStore().saveXWikiObject(memberObject, context, * true); } // we need to make sure we add the user to the group cache * try { xwiki.getGroupService(context).addUserToGroup(username, * context.getDatabase(), groupName, context); } catch (Exception e) {} */ } private void removeUserFromGroup(String userName, String groupName, XWikiContext context) throws XWikiException { // don't remove if he's not a member if (!isMemberOfGroup(userName, groupName, context)) { return; } XWiki xwiki = context.getWiki(); BaseClass groupClass = xwiki.getGroupClass(context); XWikiDocument groupDoc = xwiki.getDocument(groupName, context); BaseObject memberObject = groupDoc.getObject(groupClass.getName(), "member", userName); if (memberObject == null) { return; } groupDoc.removeObject(memberObject); xwiki.saveDocument(groupDoc, context.getMessageTool().get( "core.comment.removedUserFromGroup"), context); } /** * {@inheritDoc} */ public void addMembers(String spaceName, List usernames, XWikiContext context) throws SpaceManagerException { for (int i = 0; i < usernames.size(); i++) { addMember(spaceName, (String) usernames.get(i), context); } } /** * {@inheritDoc} * * @see SpaceManager#getMembers(String, XWikiContext) */ public Collection getMembers(String spaceName, XWikiContext context) throws SpaceManagerException { try { return sortUserNames(getGroupService(context) .getAllMembersNamesForGroup(getMemberGroupName(spaceName), 0, 0, context), context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } private List sortUserNames(Collection collectionOfUsers, final XWikiContext context) { List users = new ArrayList(collectionOfUsers); Collections.sort(users, new Comparator() { public int compare(Object a, Object b) { try { XWikiDocument aDoc = context.getWiki().getDocument( (String) a, context); XWikiDocument bDoc = context.getWiki().getDocument( (String) b, context); String aFirstName = aDoc.getObject("XWiki.XWikiUsers") .getStringValue("first_name"); String bFirstName = bDoc.getObject("XWiki.XWikiUsers") .getStringValue("first_name"); int cmp = aFirstName.compareToIgnoreCase(bFirstName); if (cmp == 0) { String aLastName = aDoc.getObject("XWiki.XWikiUsers") .getStringValue("last_name"); String bLastName = bDoc.getObject("XWiki.XWikiUsers") .getStringValue("last_name"); return aLastName.compareTo(bLastName); } else { return cmp; } } catch (Exception e) { return ((String) a).compareTo((String) b); } } }); return users; } public String getMemberGroupName(String spaceName) { return getSpaceManagerExtension().getMemberGroupName(spaceName); } public String getAdminGroupName(String spaceName) { return getSpaceManagerExtension().getAdminGroupName(spaceName); } public String getRoleGroupName(String spaceName, String role) { return getSpaceManagerExtension().getRoleGroupName(spaceName, role); } protected XWikiGroupService getGroupService(XWikiContext context) throws XWikiException { return context.getWiki().getGroupService(context); } public SpaceUserProfile getSpaceUserProfile(String spaceName, String username, XWikiContext context) throws SpaceManagerException { return newUserSpaceProfile(username, spaceName, context); } private void deleteSpaceUserProfile(String spaceName, String userName, XWikiContext context) throws SpaceManagerException { try { String docName = getSpaceUserProfilePageName(userName, spaceName); XWikiDocument doc = context.getWiki().getDocument(docName, context); if (!doc.isNew()) context.getWiki().deleteDocument(doc, context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } public String getSpaceUserProfilePageName(String userName, String spaceName) { return getSpaceManagerExtension().getSpaceUserProfilePageName(userName, spaceName); } protected SpaceUserProfile newUserSpaceProfile(String user, String space, XWikiContext context) throws SpaceManagerException { try { return new SpaceUserProfileImpl(user, space, this, context); } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} */ public List getLastModifiedDocuments(String spaceName, XWikiContext context, boolean recursive, int nb, int start) throws SpaceManagerException { notImplemented(); return null; } /** * {@inheritDoc} */ public Collection getRoles(String spaceName, XWikiContext context) throws SpaceManagerException { notImplemented(); return null; } /** * {@inheritDoc} * * @see SpaceManager#getRoles(String, String, XWikiContext) */ public Collection getRoles(String spaceName, String memberName, XWikiContext context) throws SpaceManagerException { try { Collection memberRoles = context.getWiki().getGroupService(context) .getAllGroupsNamesForMember(memberName, 0, 0, context); Collection spaceRoles = getRoles(spaceName, context); memberRoles.retainAll(spaceRoles); return memberRoles; } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} */ public List getLastModifiedDocuments(String spaceName, XWikiContext context) throws SpaceManagerException { notImplemented(); return null; } /** * {@inheritDoc} */ public List searchDocuments(String spaceName, String hql, XWikiContext context) throws SpaceManagerException { notImplemented(); return null; } /** * {@inheritDoc} */ public int countSpaces(XWikiContext context) throws SpaceManagerException { String type = getSpaceTypeName(); String className = getSpaceClassName(); String sql; if (hasCustomMapping()) sql = "select count(*) from XWikiDocument as doc, BaseObject as obj, " + className + " as space" + " where doc.fullName = obj.name and obj.className='" + className + "' and obj.id = space.id and space.type='" + type + "'"; else sql = "select count(*) from XWikiDocument as doc, BaseObject as obj, StringProperty as typeprop" + " where doc.fullName=obj.name and obj.className = '" + className + "' and obj.id=typeprop.id.id and typeprop.id.name='type' and typeprop.value='" + type + "'"; try { List result = context.getWiki().search(sql, context); Integer res = (Integer) result.get(0); return res.intValue(); } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * {@inheritDoc} * * @see SpaceManager#joinSpace(String, XWikiContext) */ public boolean joinSpace(String spaceName, XWikiContext context) throws SpaceManagerException { try { SpaceUserProfile userProfile = newUserSpaceProfile(context .getUser(), spaceName, context); userProfile.updateProfileFromRequest(); userProfile.saveWithProgrammingRights(); addMember(spaceName, context.getUser(), context); sendMail(SpaceAction.JOIN, getSpace(spaceName, context), context); return true; } catch (XWikiException e) { throw new SpaceManagerException(e); } } /** * Helper function to send email after a space action. This mail template * full name is composed of the space name and the action with the following * convention : spaceName + "." + "MailTemplate" + action + "Space", as in * MySpace.MailTemplateJoinSpace * * @see getTemplateMailPageName * @param action * the action which triggered the mail sending. See * {@link SpaceManager.SpaceAction} for possible actions. * @param space * The space on which the action has triggered the mail sending * @throws SpaceManagerException */ private void sendMail(String action, Space space, XWikiContext context) throws SpaceManagerException { if (!mailNotification) { return; } VelocityContext vContext = new VelocityContext(); vContext.put("space", space); String fromUser = context.getWiki().getXWikiPreference("space_email", context); if (fromUser == null || fromUser.trim().length() == 0) { fromUser = context.getWiki().getXWikiPreference("admin_email", context); } String[] toUsers = new String[0]; if (SpaceAction.CREATE.equals(action)) { // notify space administrators upon space creation Collection admins = getAdmins(space.getSpaceName(), context); toUsers = (String[]) admins.toArray(new String[admins.size()]); } else if (SpaceAction.JOIN.equals(action)) { // send join group confirmation e-mail SpaceUserProfile profile = getSpaceUserProfile(space.getSpaceName(), context.getUser(), context); if (profile != null && profile.getAllowNotifications()) { toUsers = new String[] {context.getUser()}; } else { return; } } if (fromUser == null) { throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_SENDER_EMAIL_INVALID, "Sender email is invalid"); } boolean toUsersValid = toUsers.length > 0; for (int i = 0; i < toUsers.length && toUsersValid; i++) { if (!isEmailAddress(toUsers[i])) { toUsers[i] = getEmailAddress(toUsers[i], context); } if (toUsers[i] == null) { toUsersValid = false; } } if (!toUsersValid) { throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_TARGET_EMAIL_INVALID, "Target email is invalid"); } String strToUsers = join(toUsers, ","); MailSenderPlugin mailSender = getMailSenderPlugin(context); try { String templateDocFullName = getTemplateMailPageName(space .getSpaceName(), action, context); XWikiDocument mailDoc = context.getWiki().getDocument( templateDocFullName, context); XWikiDocument translatedMailDoc = mailDoc .getTranslatedDocument(context); mailSender.prepareVelocityContext(fromUser, strToUsers, "", vContext, context); vContext.put("xwiki", new com.xpn.xwiki.api.XWiki( context.getWiki(), context)); vContext.put("context", new com.xpn.xwiki.api.Context(context)); String mailSubject = XWikiVelocityRenderer .evaluate(translatedMailDoc.getTitle(), templateDocFullName, vContext); String mailContent = XWikiVelocityRenderer.evaluate( translatedMailDoc.getContent(), templateDocFullName, vContext); Mail mail = new Mail(fromUser, strToUsers, null, null, mailSubject, mailContent, null); mailSender.sendMail(mail, context); } catch (Exception e) { throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_SENDING_EMAIL_FAILED, "Sending notification email failed", e); } } private MailSenderPlugin getMailSenderPlugin(XWikiContext context) throws SpaceManagerException { MailSenderPlugin mailSender = (MailSenderPlugin) context.getWiki() .getPlugin("mailsender", context); if (mailSender == null) throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_MANAGER_REQUIRES_MAILSENDER_PLUGIN, "SpaceManager requires the mail sender plugin"); return mailSender; } // code duplicated from InvitationManagerImpl !!! private static final String join(String[] array, String separator) { StringBuffer result = new StringBuffer(""); if (array.length > 0) { result.append(array[0]); } for (int i = 1; i < array.length; i++) { result.append("," + array[i]); } return result.toString(); } // code duplicated from InvitationManagerImpl !!! private boolean isEmailAddress(String str) { return str.contains("@"); } // code duplicated from InvitationManagerImpl !!! private String getEmailAddress(String user, XWikiContext context) throws SpaceManagerException { try { String wikiuser = (user.startsWith("XWiki.")) ? user : "XWiki." + user; if (wikiuser == null) return null; XWikiDocument userDoc = null; userDoc = context.getWiki().getDocument(wikiuser, context); if (userDoc.isNew()) return null; String email = ""; try { email = userDoc.getObject("XWiki.XWikiUsers").getStringValue( "email"); } catch (Exception e) { return null; } if ((email == null) || (email.equals(""))) return null; return email; } catch (Exception e) { throw new SpaceManagerException( SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER, SpaceManagerException.ERROR_SPACE_CANNOT_FIND_EMAIL_ADDRESS, "Cannot find email address of user " + user, e); } } /** * Convention based private helper to retrieve a mail template full name * from a space name and an action name. TODO I think we should have the * possibility to select for each action a template that is not located in * the space itself, but in another web of the wiki. This would be to avoid * copying this template each time we create a space if its content is not * supposed to be modified, And thus reduce the impact of space creation on * the db size. */ private String getTemplateMailPageName(String spaceName, String action, XWikiContext context) { String docName = spaceName + "." + "MailTemplate" + action + "Space"; try { if (context.getWiki().getDocument(docName, context).isNew()) { docName = null; } } catch (XWikiException e) { docName = null; } if (docName == null) { docName = getDefaultResourceSpace(context) + "." + "MailTemplate" + action + "Space"; } return docName; } private String getDefaultResourceSpace(XWikiContext context) { return context.getWiki().Param("xwiki.spacemanager.resourcespace", SpaceManager.DEFAULT_RESOURCE_SPACE); } public boolean isMailNotification() { return mailNotification; } public void setMailNotification(boolean mailNotification) { this.mailNotification = mailNotification; } }
XPSM-6 Patch submited by Marius Florea. Applied without modifications. git-svn-id: dc11403b0ca3846ef16382eb5b645943ea8bd503@7808 f329d543-caf0-0310-9063-dda96c69346f
xwiki-platform-tag/plugin/spacemanager/src/main/java/com/xpn/xwiki/plugin/spacemanager/impl/SpaceManagerImpl.java
XPSM-6 Patch submited by Marius Florea. Applied without modifications.
<ide><path>wiki-platform-tag/plugin/spacemanager/src/main/java/com/xpn/xwiki/plugin/spacemanager/impl/SpaceManagerImpl.java <ide> toUsers = (String[]) admins.toArray(new String[admins.size()]); <ide> } else if (SpaceAction.JOIN.equals(action)) { <ide> // send join group confirmation e-mail <del> SpaceUserProfile profile = <del> getSpaceUserProfile(space.getSpaceName(), context.getUser(), context); <del> if (profile != null && profile.getAllowNotifications()) { <add> boolean optOutEmail = <add> context.getWiki().getUserPreferenceAsInt("opt_out", context) != 0; <add> if (optOutEmail) { <add> return; <add> } else { <ide> toUsers = new String[] {context.getUser()}; <del> } else { <del> return; <ide> } <ide> } <ide>
Java
mit
55647ce3ef2cb33971213ca435d94c66f6d80f7c
0
ammaraskar/KittehIRCClientLib,bendem/KittehIRCClientLib
/* * * Copyright (C) 2013-2014 Matt Baxter http://kitteh.org * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.kitteh.irc; import org.kitteh.irc.components.Command; import org.kitteh.irc.elements.Actor; import org.kitteh.irc.elements.Channel; import org.kitteh.irc.elements.User; import org.kitteh.irc.event.channel.*; import org.kitteh.irc.event.user.PrivateCTCPQueryEvent; import org.kitteh.irc.event.user.PrivateCTCPReplyEvent; import org.kitteh.irc.event.user.PrivateMessageEvent; import org.kitteh.irc.event.user.PrivateNoticeEvent; import org.kitteh.irc.util.LCSet; import org.kitteh.irc.util.Sanity; import org.kitteh.irc.util.StringUtil; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; import java.util.Date; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.regex.Matcher; import java.util.regex.Pattern; final class IRCBot implements Bot { private class BotManager extends Thread { private BotManager() { this.setName("Kitteh IRCBot Main (" + IRCBot.this.getName() + ")"); this.start(); } @Override public void run() { IRCBot.this.run(); } } private class BotProcessor extends Thread { private final Queue<String> queue = new ConcurrentLinkedQueue<>(); private BotProcessor() { this.setName("Kitteh IRCBot Input Processor (" + IRCBot.this.getName() + ")"); this.start(); } @Override public void run() { while (!this.isInterrupted()) { if (this.queue.isEmpty()) { synchronized (this.queue) { try { this.queue.wait(); } catch (InterruptedException e) { break; } } } try { IRCBot.this.handleLine(this.queue.poll()); } catch (final Throwable thrown) { // NOOP } } } private void queue(String message) { synchronized (this.queue) { this.queue.add(message); this.queue.notify(); } } } private enum MessageTarget { CHANNEL, PRIVATE, UNKNOWN } private final Config config; private final BotManager manager; private final BotProcessor processor; private String goalNick; private String currentNick; private String requestedNick; private final Set<String> channels = new LCSet(); private AuthType authType; private String auth; private String authReclaim; private IRCBotInput inputHandler; private IRCBotOutput outputHandler; private String shutdownReason = "KITTEH AWAY!"; private boolean connected; private long lastCheck; private final EventManager eventManager = new EventManager(); private Map<Character, Character> prefixes = new ConcurrentHashMap<Character, Character>() { { put('o', '@'); put('v', '+'); } }; private static final Pattern PREFIX_PATTERN = Pattern.compile("PREFIX=\\(([a-zA-Z]+)\\)([^ ]+)"); private Map<Character, ChannelModeType> modes = new ConcurrentHashMap<Character, ChannelModeType>() { { put('b', ChannelModeType.A_MASK); put('k', ChannelModeType.B_PARAMETER_ALWAYS); put('l', ChannelModeType.C_PARAMETER_ON_SET); put('i', ChannelModeType.D_PARAMETER_NEVER); put('m', ChannelModeType.D_PARAMETER_NEVER); put('n', ChannelModeType.D_PARAMETER_NEVER); put('p', ChannelModeType.D_PARAMETER_NEVER); put('s', ChannelModeType.D_PARAMETER_NEVER); put('t', ChannelModeType.D_PARAMETER_NEVER); } }; private static final Pattern CHANMODES_PATTERN = Pattern.compile("CHANMODES=(([,A-Za-z]+)(,([,A-Za-z]+)){0,3})"); IRCBot(Config config) { this.config = config; this.currentNick = this.requestedNick = this.goalNick = this.config.get(Config.NICK); this.manager = new BotManager(); this.processor = new BotProcessor(); } @Override public void addChannel(String... channels) { Sanity.nullCheck(channels, "Channels cannot be null"); Sanity.truthiness(channels.length > 0, "Channels cannot be empty array"); for (String channel : channels) { if (!Channel.isChannel(channel)) { continue; } this.channels.add(channel); if (this.connected) { this.sendRawLine("JOIN :" + channel, true); } } } @Override public EventManager getEventManager() { return this.eventManager; } @Override public String getIntendedNick() { return this.goalNick; } @Override public String getName() { return this.config.get(Config.BOT_NAME); } @Override public String getNick() { return this.currentNick; } @Override public void sendCTCPMessage(String target, String message) { Sanity.nullCheck(target, "Target cannot be null"); Sanity.nullCheck(message, "Message cannot be null"); Sanity.truthiness(target.indexOf(' ') == -1, "Target cannot have spaces"); this.sendRawLine("PRIVMSG " + target + " :" + CTCPUtil.toCTCP(message)); } @Override public void sendMessage(String target, String message) { Sanity.nullCheck(target, "Target cannot be null"); Sanity.nullCheck(message, "Message cannot be null"); Sanity.truthiness(target.indexOf(' ') == -1, "Target cannot have spaces"); this.sendRawLine("PRIVMSG " + target + " :" + message); } @Override public void sendRawLine(String message) { this.sendRawLine(message, false); } @Override public void sendRawLine(String message, boolean priority) { Sanity.nullCheck(message, "Message cannot be null"); this.outputHandler.queueMessage(message, priority); } @Override public void setAuth(AuthType type, String nick, String pass) { Sanity.nullCheck(type, "Auth type cannot be null"); this.authType = type; switch (type) { case GAMESURGE: this.auth = "PRIVMSG [email protected] :auth " + nick + " " + pass; this.authReclaim = ""; break; case NICKSERV: default: this.auth = "PRIVMSG NickServ :identify " + pass; this.authReclaim = "PRIVMSG NickServ :ghost " + nick + " " + pass; } } @Override public void setNick(String nick) { Sanity.nullCheck(nick, "Nick cannot be null"); this.goalNick = nick.trim(); this.sendNickChange(this.goalNick); } @Override public void shutdown(String reason) { this.shutdownReason = reason != null ? reason : ""; this.manager.interrupt(); this.processor.interrupt(); } /** * Queue up a line for processing. * * @param line line to be processed */ void processLine(String line) { if (!this.pingCheck(line)) { this.processor.queue(line); } } private boolean pingCheck(String line) { if (line.startsWith("PING ")) { this.sendRawLine("PONG " + line.substring(5), true); return true; } return false; } private void run() { try { this.connect(); } catch (final IOException e) { e.printStackTrace(); if ((this.inputHandler != null) && this.inputHandler.isAlive() && !this.inputHandler.isInterrupted()) { this.inputHandler.interrupt(); } return; } while (!this.manager.isInterrupted()) { try { Thread.sleep(1000); } catch (final InterruptedException e) { break; } if ((System.currentTimeMillis() - this.lastCheck) > 5000) { this.lastCheck = System.currentTimeMillis(); if (this.inputHandler.timeSinceInput() > 250000) { this.outputHandler.shutdown("Ping timeout! Reconnecting..."); // TODO event this.inputHandler.shutdown(); try { Thread.sleep(10000); } catch (final InterruptedException e) { break; } try { this.connect(); } catch (final IOException e) { // System.out.println("Unable to reconnect!"); // TODO log } } } } this.outputHandler.shutdown(this.shutdownReason); this.inputHandler.shutdown(); } private void connect() throws IOException { this.connected = false; final Socket socket = new Socket(); if (this.config.get(Config.BIND_ADDRESS) != null) { try { socket.bind(this.config.get(Config.BIND_ADDRESS)); } catch (final Exception e) { e.printStackTrace(); } } socket.connect(this.config.get(Config.SERVER_ADDRESS)); final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); final BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); this.outputHandler = new IRCBotOutput(bufferedWriter, this.getName()); this.outputHandler.start(); if (this.config.get(Config.SERVER_PASSWORD) != null) { this.sendRawLine("PASS " + this.config.get(Config.SERVER_PASSWORD), true); } this.sendRawLine("USER " + this.config.get(Config.USER) + " 8 * :" + this.config.get(Config.REAL_NAME), true); this.sendNickChange(this.goalNick); String line; while ((line = bufferedReader.readLine()) != null) { // TODO hacky if (this.pingCheck(line)) { continue; } try { this.handleLine(line); } catch (Throwable thrown) { // NOOP } final String[] split = line.split(" "); if (split.length > 3) { final String code = split[1]; if (code.equals("004")) { break; } else if (code.startsWith("5") || code.startsWith("4")) { socket.close(); throw new RuntimeException("Could not log into the IRC server: " + line); } } } if (this.authReclaim != null && !this.currentNick.equals(this.goalNick) && this.authType.isNickOwned()) { this.sendRawLine(this.authReclaim, true); this.sendNickChange(this.goalNick); } if (this.auth != null) { this.sendRawLine(this.auth, true); } for (final String channel : this.channels) { this.sendRawLine("JOIN :" + channel, true); } this.outputHandler.readyForLowPriority(); this.inputHandler = new IRCBotInput(socket, bufferedReader, this); this.inputHandler.start(); this.connected = true; } private String handleColon(String string) { return string.startsWith(":") ? string.substring(1) : string; } private void handleLine(String line) throws Throwable { if ((line == null) || (line.length() == 0)) { return; } final String[] split = line.split(" "); if ((split.length <= 1) || !split[0].startsWith(":")) { return; // Invalid! } final Actor actor = Actor.getActor(split[0].substring(1)); int numeric = -1; try { numeric = Integer.parseInt(split[1]); } catch (NumberFormatException ignored) { } if (numeric > -1) { switch (numeric) { case 1: // Welcome case 2: // Your host is... break; // More stuff sent on startup case 3: // server created break; case 4: // version / modes break; case 5: for (int i = 2; i < split.length; i++) { Matcher prefixMatcher = PREFIX_PATTERN.matcher(split[i]); if (prefixMatcher.find()) { String modes = prefixMatcher.group(1); String display = prefixMatcher.group(2); if (modes.length() == display.length()) { Map<Character, Character> map = new ConcurrentHashMap<>(); for (int x = 0; x < modes.length(); x++) { map.put(modes.charAt(x), display.charAt(x)); } this.prefixes = map; } continue; } Matcher modeMatcher = CHANMODES_PATTERN.matcher(split[i]); if (modeMatcher.find()) { String[] modes = modeMatcher.group(1).split(","); Map<Character, ChannelModeType> map = new ConcurrentHashMap<>(); for (int typeId = 0; typeId < modes.length; typeId++) { for (char c : modes[typeId].toCharArray()) { ChannelModeType type = null; switch (typeId) { case 0: type = ChannelModeType.A_MASK; break; case 1: type = ChannelModeType.B_PARAMETER_ALWAYS; break; case 2: type = ChannelModeType.C_PARAMETER_ON_SET; break; case 3: type = ChannelModeType.D_PARAMETER_NEVER; } map.put(c, type); } } this.modes = map; } } break; case 250: // Highest connection count case 251: // There are X users case 252: // X IRC OPs case 253: // X unknown connections case 254: // X channels formed case 255: // X clients, X servers case 265: // Local users, max case 266: // global users, max case 372: // info, such as continued motd case 375: // motd start case 376: // motd end break; // Channel info case 332: // Channel topic case 333: // Topic set by case 353: // Channel users list (/names). format is 353 nick = #channel :names case 366: // End of /names case 422: // MOTD missing break; case 431: // No nick given case 432: // Erroneous nickname case 433: // Nick in use if (!this.connected) { this.sendNickChange(this.requestedNick + '`'); } break; } } else { final Command command = Command.getByName(split[1]); // CTCP if ((command == Command.NOTICE || command == Command.PRIVMSG) && CTCPUtil.CTCP.matcher(line).matches()) { final String ctcp = CTCPUtil.fromCTCP(line); switch (command) { case NOTICE: if (this.getTypeByTarget(split[2]) == MessageTarget.PRIVATE) { this.eventManager.callEvent(new PrivateCTCPReplyEvent(actor, ctcp)); } break; case PRIVMSG: switch (this.getTypeByTarget(split[2])) { case PRIVATE: String reply = null; // Message to send as CTCP reply (NOTICE). Send nothing if null. if (ctcp.equals("VERSION")) { reply = "VERSION I am Kitteh!"; } else if (ctcp.equals("TIME")) { reply = "TIME " + new Date().toString(); } else if (ctcp.equals("FINGER")) { reply = "FINGER om nom nom tasty finger"; } else if (ctcp.startsWith("PING ")) { reply = ctcp; } PrivateCTCPQueryEvent event = new PrivateCTCPQueryEvent(actor, ctcp, reply); this.eventManager.callEvent(event); reply = event.getReply(); if (reply != null) { this.sendRawLine("NOTICE " + actor.getName() + " :" + CTCPUtil.toCTCP(reply), false); } break; case CHANNEL: this.eventManager.callEvent(new ChannelCTCPEvent(actor, (Channel) Actor.getActor(split[2]), ctcp)); break; } break; } return; // If handled as CTCP we don't care about further handling. } switch (command) { case NOTICE: final String noticeMessage = this.handleColon(StringUtil.combineSplit(split, 3)); switch (this.getTypeByTarget(split[2])) { case CHANNEL: this.eventManager.callEvent(new ChannelNoticeEvent(actor, (Channel) Actor.getActor(split[2]), noticeMessage)); break; case PRIVATE: this.eventManager.callEvent(new PrivateNoticeEvent(actor, noticeMessage)); break; } // TODO event break; case PRIVMSG: final String message = this.handleColon(StringUtil.combineSplit(split, 3)); switch (this.getTypeByTarget(split[2])) { case CHANNEL: this.eventManager.callEvent(new ChannelMessageEvent(actor, (Channel) Actor.getActor(split[2]), message)); break; case PRIVATE: this.eventManager.callEvent(new PrivateMessageEvent(actor, message)); break; } break; case MODE: if (this.getTypeByTarget(split[2]) == MessageTarget.CHANNEL) { Channel channel = (Channel) Actor.getActor(split[2]); String modechanges = split[3]; int currentArg = 4; boolean add; switch (modechanges.charAt(0)) { case '+': add = true; break; case '-': add = false; break; default: return; } for (int i = 1; i < modechanges.length() && currentArg < split.length; i++) { char next = modechanges.charAt(i); if (next == '+') { add = true; } else if (next == '-') { add = false; } else { boolean hasArg; if (this.prefixes.containsKey(next)) { hasArg = true; } else { ChannelModeType type = this.modes.get(next); if (type == null) { // TODO WHINE LOUDLY return; } hasArg = (add && type.isParameterOnSetting()) || (!add && type.isParameterOnRemoval()); } String arg = null; if (hasArg) { arg = split[currentArg++]; } this.eventManager.callEvent(new ChannelModeEvent(actor, channel, add, next, arg)); } } } break; case JOIN: if (actor instanceof User) { // Just in case this.eventManager.callEvent(new ChannelJoinEvent((Channel) Actor.getActor(split[2]), (User) actor)); } case PART: if (actor instanceof User) { // Just in case this.eventManager.callEvent(new ChannelPartEvent((Channel) Actor.getActor(split[2]), (User) actor, split.length > 2 ? this.handleColon(StringUtil.combineSplit(split, 3)) : "")); } case QUIT: break; case KICK: // System.out.println(split[2] + ": " + StringUtil.getNick(actor) + " kicked " + split[3] + ": " + this.handleColon(StringUtil.combineSplit(split, 4))); TODO EVENT break; case NICK: if (actor instanceof User) { User user = (User) actor; if (user.getNick().equals(this.currentNick)) { this.currentNick = split[2]; } // TODO NickChangeEvent } break; case INVITE: if (this.getTypeByTarget(split[2]) == MessageTarget.PRIVATE && this.channels.contains(split[3])) { this.sendRawLine("JOIN " + split[3], false); } break; } } } private MessageTarget getTypeByTarget(String target) { if (this.currentNick.equalsIgnoreCase(target)) { return MessageTarget.PRIVATE; } if (this.channels.contains(target)) { return MessageTarget.CHANNEL; } return MessageTarget.UNKNOWN; } private void sendNickChange(String newnick) { this.requestedNick = newnick; this.sendRawLine("NICK " + newnick, true); } }
src/main/java/org/kitteh/irc/IRCBot.java
/* * * Copyright (C) 2013-2014 Matt Baxter http://kitteh.org * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.kitteh.irc; import org.kitteh.irc.components.Command; import org.kitteh.irc.elements.Actor; import org.kitteh.irc.elements.Channel; import org.kitteh.irc.elements.User; import org.kitteh.irc.event.channel.*; import org.kitteh.irc.event.user.PrivateCTCPQueryEvent; import org.kitteh.irc.event.user.PrivateCTCPReplyEvent; import org.kitteh.irc.event.user.PrivateMessageEvent; import org.kitteh.irc.event.user.PrivateNoticeEvent; import org.kitteh.irc.util.LCSet; import org.kitteh.irc.util.Sanity; import org.kitteh.irc.util.StringUtil; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; import java.util.Date; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.regex.Matcher; import java.util.regex.Pattern; final class IRCBot implements Bot { private class BotManager extends Thread { private BotManager() { this.setName("Kitteh IRCBot Main (" + IRCBot.this.getName() + ")"); this.start(); } @Override public void run() { IRCBot.this.run(); } } private class BotProcessor extends Thread { private final Queue<String> queue = new ConcurrentLinkedQueue<>(); private BotProcessor() { this.setName("Kitteh IRCBot Input Processor (" + IRCBot.this.getName() + ")"); this.start(); } @Override public void run() { while (!this.isInterrupted()) { if (this.queue.isEmpty()) { synchronized (this.queue) { try { this.queue.wait(); } catch (InterruptedException e) { break; } } } try { IRCBot.this.handleLine(this.queue.poll()); } catch (final Throwable thrown) { // NOOP } } } private void queue(String message) { synchronized (this.queue) { this.queue.add(message); this.queue.notify(); } } } private enum MessageTarget { CHANNEL, PRIVATE, UNKNOWN } private final Config config; private final BotManager manager; private final BotProcessor processor; private String goalNick; private String currentNick; private String requestedNick; private final Set<String> channels = new LCSet(); private AuthType authType; private String auth; private String authReclaim; private IRCBotInput inputHandler; private IRCBotOutput outputHandler; private String shutdownReason = "KITTEH AWAY!"; private boolean connected; private long lastCheck; private final EventManager eventManager = new EventManager(); private Map<Character, Character> prefixes = new ConcurrentHashMap<Character, Character>() { { put('o', '@'); put('v', '+'); } }; private static final Pattern PREFIX_PATTERN = Pattern.compile("PREFIX=\\(([a-zA-Z]+)\\)([^ ]+)"); private Map<Character, ChannelModeType> modes = new ConcurrentHashMap<Character, ChannelModeType>() { { put('b', ChannelModeType.A_MASK); put('k', ChannelModeType.B_PARAMETER_ALWAYS); put('l', ChannelModeType.C_PARAMETER_ON_SET); put('i', ChannelModeType.D_PARAMETER_NEVER); put('m', ChannelModeType.D_PARAMETER_NEVER); put('n', ChannelModeType.D_PARAMETER_NEVER); put('p', ChannelModeType.D_PARAMETER_NEVER); put('s', ChannelModeType.D_PARAMETER_NEVER); put('t', ChannelModeType.D_PARAMETER_NEVER); } }; private static final Pattern CHANMODES_PATTERN = Pattern.compile("CHANMODES=(([,A-Za-z]+)(,([,A-Za-z]+)){0,3})"); IRCBot(Config config) { this.config = config; this.currentNick = this.requestedNick = this.goalNick = this.config.get(Config.NICK); this.manager = new BotManager(); this.processor = new BotProcessor(); } @Override public void addChannel(String... channels) { Sanity.nullCheck(channels, "Channels cannot be null"); Sanity.truthiness(channels.length > 0, "Channels cannot be empty array"); for (String channel : channels) { if (!Channel.isChannel(channel)) { continue; } this.channels.add(channel); if (this.connected) { this.sendRawLine("JOIN :" + channel, true); } } } @Override public EventManager getEventManager() { return this.eventManager; } @Override public String getIntendedNick() { return this.goalNick; } @Override public String getName() { return this.config.get(Config.BOT_NAME); } @Override public String getNick() { return this.currentNick; } @Override public void sendCTCPMessage(String target, String message) { Sanity.nullCheck(target, "Target cannot be null"); Sanity.nullCheck(message, "Message cannot be null"); Sanity.truthiness(target.indexOf(' ') == -1, "Target cannot have spaces"); this.sendRawLine("PRIVMSG " + target + " :" + CTCPUtil.toCTCP(message)); } @Override public void sendMessage(String target, String message) { Sanity.nullCheck(target, "Target cannot be null"); Sanity.nullCheck(message, "Message cannot be null"); Sanity.truthiness(target.indexOf(' ') == -1, "Target cannot have spaces"); this.sendRawLine("PRIVMSG " + target + " :" + message); } @Override public void sendRawLine(String message) { this.sendRawLine(message, false); } @Override public void sendRawLine(String message, boolean priority) { Sanity.nullCheck(message, "Message cannot be null"); this.outputHandler.queueMessage(message, priority); } @Override public void setAuth(AuthType type, String nick, String pass) { Sanity.nullCheck(type, "Auth type cannot be null"); this.authType = type; switch (type) { case GAMESURGE: this.auth = "PRIVMSG [email protected] :auth " + nick + " " + pass; this.authReclaim = ""; break; case NICKSERV: default: this.auth = "PRIVMSG NickServ :identify " + pass; this.authReclaim = "PRIVMSG NickServ :ghost " + nick + " " + pass; } } @Override public void setNick(String nick) { Sanity.nullCheck(nick, "Nick cannot be null"); this.goalNick = nick.trim(); this.sendNickChange(this.goalNick); } @Override public void shutdown(String reason) { this.shutdownReason = reason != null ? reason : ""; this.manager.interrupt(); this.processor.interrupt(); } /** * Queue up a line for processing. * * @param line line to be processed */ void processLine(String line) { if (!this.pingCheck(line)) { this.processor.queue(line); } } private boolean pingCheck(String line) { if (line.startsWith("PING ")) { this.sendRawLine("PONG " + line.substring(5), true); return true; } return false; } private void run() { try { this.connect(); } catch (final IOException e) { e.printStackTrace(); if ((this.inputHandler != null) && this.inputHandler.isAlive() && !this.inputHandler.isInterrupted()) { this.inputHandler.interrupt(); } return; } while (!this.manager.isInterrupted()) { try { Thread.sleep(1000); } catch (final InterruptedException e) { break; } if ((System.currentTimeMillis() - this.lastCheck) > 5000) { this.lastCheck = System.currentTimeMillis(); if (this.inputHandler.timeSinceInput() > 250000) { this.outputHandler.shutdown("Ping timeout! Reconnecting..."); // TODO event this.inputHandler.shutdown(); try { Thread.sleep(10000); } catch (final InterruptedException e) { break; } try { this.connect(); } catch (final IOException e) { // System.out.println("Unable to reconnect!"); // TODO log } } } } this.outputHandler.shutdown(this.shutdownReason); this.inputHandler.shutdown(); } private void connect() throws IOException { this.connected = false; final Socket socket = new Socket(); if (this.config.get(Config.BIND_ADDRESS) != null) { try { socket.bind(this.config.get(Config.BIND_ADDRESS)); } catch (final Exception e) { e.printStackTrace(); } } socket.connect(this.config.get(Config.SERVER_ADDRESS)); final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); final BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); this.outputHandler = new IRCBotOutput(bufferedWriter, this.getName()); this.outputHandler.start(); if (this.config.get(Config.SERVER_PASSWORD) != null) { this.sendRawLine("PASS " + this.config.get(Config.SERVER_PASSWORD), true); } this.sendRawLine("USER " + this.config.get(Config.USER) + " 8 * :" + this.config.get(Config.REAL_NAME), true); this.sendNickChange(this.goalNick); String line; while ((line = bufferedReader.readLine()) != null) { // TODO hacky if (this.pingCheck(line)) { continue; } try { this.handleLine(line); } catch (Throwable thrown) { // NOOP } final String[] split = line.split(" "); if (split.length > 3) { final String code = split[1]; if (code.equals("004")) { break; } else if (code.startsWith("5") || code.startsWith("4")) { socket.close(); throw new RuntimeException("Could not log into the IRC server: " + line); } } } if (this.authReclaim != null && !this.currentNick.equals(this.goalNick) && this.authType.isNickOwned()) { this.sendRawLine(this.authReclaim, true); this.sendNickChange(this.goalNick); } if (this.auth != null) { this.sendRawLine(this.auth, true); } for (final String channel : this.channels) { this.sendRawLine("JOIN :" + channel, true); } this.outputHandler.readyForLowPriority(); this.inputHandler = new IRCBotInput(socket, bufferedReader, this); this.inputHandler.start(); this.connected = true; } private String handleColon(String string) { return string.startsWith(":") ? string.substring(1) : string; } private void handleLine(String line) throws Throwable { if ((line == null) || (line.length() == 0)) { return; } final String[] split = line.split(" "); if ((split.length <= 1) || !split[0].startsWith(":")) { return; // Invalid! } final Actor actor = Actor.getActor(split[0].substring(1)); int numeric = -1; try { numeric = Integer.parseInt(split[1]); } catch (NumberFormatException ignored) { } if (numeric > -1) { switch (numeric) { case 1: // Welcome case 2: // Your host is... break; // More stuff sent on startup case 3: // server created break; case 4: // version / modes break; case 5: for (int i = 2; i < split.length; i++) { Matcher prefixMatcher = PREFIX_PATTERN.matcher(split[i]); if (prefixMatcher.find()) { String modes = prefixMatcher.group(1); String display = prefixMatcher.group(2); if (modes.length() == display.length()) { Map<Character, Character> map = new ConcurrentHashMap<>(); for (int x = 0; x < modes.length(); x++) { map.put(modes.charAt(x), display.charAt(x)); } this.prefixes = map; } continue; } Matcher modeMatcher = CHANMODES_PATTERN.matcher(split[i]); if (modeMatcher.find()) { String[] modes = modeMatcher.group(1).split(","); Map<Character, ChannelModeType> map = new ConcurrentHashMap<>(); for (int typeId = 0; typeId < modes.length; typeId++) { for (char c : modes[typeId].toCharArray()) { ChannelModeType type = null; switch (typeId) { case 0: type = ChannelModeType.A_MASK; break; case 1: type = ChannelModeType.B_PARAMETER_ALWAYS; break; case 2: type = ChannelModeType.C_PARAMETER_ON_SET; break; case 3: type = ChannelModeType.D_PARAMETER_NEVER; } map.put(c, type); } } this.modes = map; } } break; case 250: // Highest connection count case 251: // There are X users case 252: // X IRC OPs case 253: // X unknown connections case 254: // X channels formed case 255: // X clients, X servers case 265: // Local users, max case 266: // global users, max case 372: // info, such as continued motd case 375: // motd start case 376: // motd end break; // Channel info case 332: // Channel topic case 333: // Topic set by case 353: // Channel users list (/names). format is 353 nick = #channel :names case 366: // End of /names case 422: // MOTD missing break; case 431: // No nick given case 432: // Erroneous nickname case 433: // Nick in use if (!this.connected) { this.sendNickChange(this.requestedNick + '`'); } break; } } else { final MessageTarget messageTarget = this.getTypeByTarget(split[2]); // Only applicable if the command has a target, as many do final Command command = Command.getByName(split[1]); // CTCP if ((command == Command.NOTICE || command == Command.PRIVMSG) && CTCPUtil.CTCP.matcher(line).matches()) { final String ctcp = CTCPUtil.fromCTCP(line); switch (command) { case NOTICE: if (messageTarget == MessageTarget.PRIVATE) { this.eventManager.callEvent(new PrivateCTCPReplyEvent(actor, ctcp)); } break; case PRIVMSG: switch (messageTarget) { case PRIVATE: String reply = null; // Message to send as CTCP reply (NOTICE). Send nothing if null. if (ctcp.equals("VERSION")) { reply = "VERSION I am Kitteh!"; } else if (ctcp.equals("TIME")) { reply = "TIME " + new Date().toString(); } else if (ctcp.equals("FINGER")) { reply = "FINGER om nom nom tasty finger"; } else if (ctcp.startsWith("PING ")) { reply = ctcp; } PrivateCTCPQueryEvent event = new PrivateCTCPQueryEvent(actor, ctcp, reply); this.eventManager.callEvent(event); reply = event.getReply(); if (reply != null) { this.sendRawLine("NOTICE " + actor.getName() + " :" + CTCPUtil.toCTCP(reply), false); } break; case CHANNEL: this.eventManager.callEvent(new ChannelCTCPEvent(actor, (Channel) Actor.getActor(split[2]), ctcp)); break; } break; } return; // If handled as CTCP we don't care about further handling. } switch (command) { case NOTICE: final String noticeMessage = this.handleColon(StringUtil.combineSplit(split, 3)); switch (messageTarget) { case CHANNEL: this.eventManager.callEvent(new ChannelNoticeEvent(actor, (Channel) Actor.getActor(split[2]), noticeMessage)); break; case PRIVATE: this.eventManager.callEvent(new PrivateNoticeEvent(actor, noticeMessage)); break; } // TODO event break; case PRIVMSG: final String message = this.handleColon(StringUtil.combineSplit(split, 3)); switch (messageTarget) { case CHANNEL: this.eventManager.callEvent(new ChannelMessageEvent(actor, (Channel) Actor.getActor(split[2]), message)); break; case PRIVATE: this.eventManager.callEvent(new PrivateMessageEvent(actor, message)); break; } break; case MODE: if (messageTarget == MessageTarget.CHANNEL) { Channel channel = (Channel) Actor.getActor(split[2]); String modechanges = split[3]; int currentArg = 4; boolean add; switch (modechanges.charAt(0)) { case '+': add = true; break; case '-': add = false; break; default: return; } for (int i = 1; i < modechanges.length() && currentArg < split.length; i++) { char next = modechanges.charAt(i); if (next == '+') { add = true; } else if (next == '-') { add = false; } else { boolean hasArg; if (this.prefixes.containsKey(next)) { hasArg = true; } else { ChannelModeType type = this.modes.get(next); if (type == null) { // TODO WHINE LOUDLY return; } hasArg = (add && type.isParameterOnSetting()) || (!add && type.isParameterOnRemoval()); } String arg = null; if (hasArg) { arg = split[currentArg++]; } this.eventManager.callEvent(new ChannelModeEvent(actor, channel, add, next, arg)); } } } break; case JOIN: if (actor instanceof User) { // Just in case this.eventManager.callEvent(new ChannelJoinEvent((Channel) Actor.getActor(split[2]), (User) actor)); } case PART: if (actor instanceof User) { // Just in case this.eventManager.callEvent(new ChannelPartEvent((Channel) Actor.getActor(split[2]), (User) actor, split.length > 2 ? this.handleColon(StringUtil.combineSplit(split, 3)) : "")); } case QUIT: break; case KICK: // System.out.println(split[2] + ": " + StringUtil.getNick(actor) + " kicked " + split[3] + ": " + this.handleColon(StringUtil.combineSplit(split, 4))); TODO EVENT break; case NICK: if (actor instanceof User) { User user = (User) actor; if (user.getNick().equals(this.currentNick)) { this.currentNick = split[2]; } // TODO NickChangeEvent } break; case INVITE: if (messageTarget == MessageTarget.PRIVATE && this.channels.contains(split[3])) { this.sendRawLine("JOIN " + split[3], false); } break; } } } private MessageTarget getTypeByTarget(String target) { if (this.currentNick.equalsIgnoreCase(target)) { return MessageTarget.PRIVATE; } if (this.channels.contains(target)) { return MessageTarget.CHANNEL; } return MessageTarget.UNKNOWN; } private void sendNickChange(String newnick) { this.requestedNick = newnick; this.sendRawLine("NICK " + newnick, true); } }
Migrate some code for less confusion
src/main/java/org/kitteh/irc/IRCBot.java
Migrate some code for less confusion
<ide><path>rc/main/java/org/kitteh/irc/IRCBot.java <ide> break; <ide> } <ide> } else { <del> final MessageTarget messageTarget = this.getTypeByTarget(split[2]); // Only applicable if the command has a target, as many do <ide> final Command command = Command.getByName(split[1]); <ide> // CTCP <ide> if ((command == Command.NOTICE || command == Command.PRIVMSG) && CTCPUtil.CTCP.matcher(line).matches()) { <ide> final String ctcp = CTCPUtil.fromCTCP(line); <ide> switch (command) { <ide> case NOTICE: <del> if (messageTarget == MessageTarget.PRIVATE) { <add> if (this.getTypeByTarget(split[2]) == MessageTarget.PRIVATE) { <ide> this.eventManager.callEvent(new PrivateCTCPReplyEvent(actor, ctcp)); <ide> } <ide> break; <ide> case PRIVMSG: <del> switch (messageTarget) { <add> switch (this.getTypeByTarget(split[2])) { <ide> case PRIVATE: <ide> String reply = null; // Message to send as CTCP reply (NOTICE). Send nothing if null. <ide> if (ctcp.equals("VERSION")) { <ide> switch (command) { <ide> case NOTICE: <ide> final String noticeMessage = this.handleColon(StringUtil.combineSplit(split, 3)); <del> switch (messageTarget) { <add> switch (this.getTypeByTarget(split[2])) { <ide> case CHANNEL: <ide> this.eventManager.callEvent(new ChannelNoticeEvent(actor, (Channel) Actor.getActor(split[2]), noticeMessage)); <ide> break; <ide> break; <ide> case PRIVMSG: <ide> final String message = this.handleColon(StringUtil.combineSplit(split, 3)); <del> switch (messageTarget) { <add> switch (this.getTypeByTarget(split[2])) { <ide> case CHANNEL: <ide> this.eventManager.callEvent(new ChannelMessageEvent(actor, (Channel) Actor.getActor(split[2]), message)); <ide> break; <ide> } <ide> break; <ide> case MODE: <del> if (messageTarget == MessageTarget.CHANNEL) { <add> if (this.getTypeByTarget(split[2]) == MessageTarget.CHANNEL) { <ide> Channel channel = (Channel) Actor.getActor(split[2]); <ide> String modechanges = split[3]; <ide> int currentArg = 4; <ide> } <ide> break; <ide> case INVITE: <del> if (messageTarget == MessageTarget.PRIVATE && this.channels.contains(split[3])) { <add> if (this.getTypeByTarget(split[2]) == MessageTarget.PRIVATE && this.channels.contains(split[3])) { <ide> this.sendRawLine("JOIN " + split[3], false); <ide> } <ide> break;
Java
apache-2.0
288dc545a3befe1385f4b1c14b0ed656a95ac75f
0
samarthbhargav/feedback-ml,samarthbhargav/feedback-ml,maheshkkumar/feedback-ml,maheshkkumar/feedback-ml,maheshkkumar/feedback-ml,samarthbhargav/feedback-ml,samarthbhargav/feedback-ml,maheshkkumar/feedback-ml
package com.feedback.back.dao; import com.feedback.back.entities.*; import com.feedback.back.mongo.MongoConnector; import com.mongodb.Block; import com.mongodb.client.MongoCollection; import com.mongodb.client.model.Filters; import org.bson.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; /** * Created by Samarth Bhargav on 30/6/15. */ public class RecordDAO { private static final Logger LOG = LoggerFactory.getLogger( RecordDAO.class ); private static final RecordDAO INSTANCE = new RecordDAO(); public static RecordDAO getInstance() { return INSTANCE; } private Map<String, MongoCollection<Document>> collections = new HashMap<>(); private MetaDataDAO metaDataDAO = MetaDataDAO.getInstance(); private MongoCollection<Document> getCollection( String dataset ) { if ( !this.collections.containsKey( dataset ) ) { this.metaDataDAO.addDataset( dataset ); collections.put( dataset, MongoConnector.getDB( "feedback-records" ).getCollection( dataset ) ); } return this.collections.get( dataset ); } private RecordDAO() { List<String> datasetNames = this.metaDataDAO.getDatasets(); LOG.info( "Found data sets: {}", datasetNames ); for ( String dataset : datasetNames ) { collections.put( dataset, MongoConnector.getDB( "feedback-records" ).getCollection( dataset ) ); } LOG.info( "Loaded {} data sets", this.collections.size() ); } public void insert( Record record, String dataset ) { this.getCollection( dataset ).insertOne( record.toDocument() ); } public void save( Record record, String dataset ) { this.getCollection( dataset ) .replaceOne( new Document( "_id", record.getId() ), record.toDocument(), DAOUtil.UPSERT_TRUE ); } public Record getRecord( String dataset, String id ) { return Record.fromDocument( this.getCollection( dataset ).find( Filters.and( Filters.eq( "_id", id ) ) ).first() ); } public RecordsPage getRecordsPage( String dataset, int skip, int limit ) { List<Document> documents = new ArrayList<>(); this.getCollection( dataset ).find().skip( skip ).limit( limit ).into( documents ); List<Record> records = new ArrayList<>( documents.size() ); for ( Document document : documents ) { records.add( Record.fromDocument( document ) ); } RecordsPage recordsPage = new RecordsPage(); recordsPage.setLimit( limit ); recordsPage.setSkip( skip ); recordsPage.setRecords( records ); return recordsPage; } public DatasetStatistics getDatasetStatistics() { final List<DatasetStats> list = new ArrayList<>(); for ( Map.Entry<String, MongoCollection<Document>> entry : this.collections.entrySet() ) { DatasetStats datasetStats = new DatasetStats(); datasetStats.setDataset( entry.getKey() ); datasetStats.setNumberOfRecords( entry.getValue().count() ); list.add( datasetStats ); } DatasetStatistics statistics = new DatasetStatistics(); statistics.setDatasetStatistics( list ); return statistics; } public RecordStatistics getRecordStatistics( String dataset ) { Document group = new Document( "$group", new Document( "_id", "$label" ).append( "count", new Document( "$sum", 1L ) ) ); final List<RecordStats> list = new ArrayList<>(); this.getCollection( dataset ).aggregate( Arrays.asList( group ) ).allowDiskUse( true ).useCursor( true ) .forEach( new Block<Document>() { @Override public void apply( Document document ) { RecordStats recordStats = new RecordStats(); recordStats.setNumberOfRecords( document.getLong( "count" ) ); recordStats.setLabel( document.getString( "_id" ) ); list.add( recordStats ); } } ); RecordStatistics recordStatistics = new RecordStatistics(); recordStatistics.setStats( list ); return recordStatistics; } public static void main( String[] args ) { RecordDAO recordDAO = new RecordDAO(); Record record = new Record(); record.setId( "3" ); record.setContent( null ); recordDAO.save( record, "dataset2" ); System.out.println( recordDAO.getRecordStatistics( "dataset2" ) ); } }
feedback-back/src/main/java/com/feedback/back/dao/RecordDAO.java
package com.feedback.back.dao; import com.feedback.back.entities.*; import com.feedback.back.mongo.MongoConnector; import com.mongodb.Block; import com.mongodb.client.MongoCollection; import com.mongodb.client.model.Filters; import org.bson.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; /** * Created by Samarth Bhargav on 30/6/15. */ public class RecordDAO { private static final Logger LOG = LoggerFactory.getLogger( RecordDAO.class ); private static final RecordDAO INSTANCE = new RecordDAO(); public static RecordDAO getInstance() { return INSTANCE; } private Map<String, MongoCollection<Document>> collections = new HashMap<>(); private MetaDataDAO metaDataDAO = MetaDataDAO.getInstance(); private MongoCollection<Document> getCollection( String dataset ) { if ( !this.collections.containsKey( dataset ) ) { this.metaDataDAO.addDataset( dataset ); collections.put( dataset, MongoConnector.getDB( "feedback-records" ).getCollection( dataset ) ); } return this.collections.get( dataset ); } private RecordDAO() { List<String> datasetNames = this.metaDataDAO.getDatasets(); LOG.info( "Found data sets: {}", datasetNames ); for ( String dataset : datasetNames ) { collections.put( dataset, MongoConnector.getDB( "feedback-records" ).getCollection( dataset ) ); } LOG.info( "Loaded {} data sets", this.collections.size() ); } public void insert( Record record, String dataset ) { this.getCollection( dataset ).insertOne( record.toDocument() ); } public void save( Record record, String dataset ) { this.getCollection( dataset ) .replaceOne( new Document( "_id", record.getId() ), record.toDocument(), DAOUtil.UPSERT_TRUE ); } public Record getRecord( String dataset, String id ) { return Record.fromDocument( this.getCollection( dataset ).find( Filters.and( Filters.eq( "_id", id ) ) ).first() ); } public RecordsPage getRecordsPage( String dataset, int skip, int limit ) { List<Document> documents = new ArrayList<>(); this.getCollection( dataset ).find().skip( skip ).limit( limit ).into( documents ); List<Record> records = new ArrayList<>( documents.size() ); for ( Document document : documents ) { records.add( Record.fromDocument( document ) ); } RecordsPage recordsPage = new RecordsPage(); recordsPage.setLimit( limit ); recordsPage.setSkip( skip ); recordsPage.setRecords( records ); return recordsPage; } public DatasetStatistics getDatasetStatistics() { final List<DatasetStats> list = new ArrayList<>(); for ( Map.Entry<String, MongoCollection<Document>> entry : this.collections.entrySet() ) { DatasetStats datasetStats = new DatasetStats(); datasetStats.setDataset( entry.getKey() ); datasetStats.setNumberOfRecords( entry.getValue().count() ); list.add( datasetStats ); } DatasetStatistics statistics = new DatasetStatistics(); statistics.setDatasetStatistics( list ); return statistics; } public RecordStatistics getRecordStatistics( String dataset ) { Document group = new Document( "$group", new Document( "_id", "$label" ).append( "count", new Document( "$sum", 1L ) ) ); final List<RecordStats> list = new ArrayList<>(); this.getCollection( dataset ).aggregate( Arrays.asList( group ) ).allowDiskUse( true ).useCursor( true ) .forEach( new Block<Document>() { @Override public void apply( Document document ) { RecordStats recordStats = new RecordStats(); recordStats.setNumberOfRecords( document.getLong( "count" ) ); recordStats.setLabel( document.getString( "_id" ) ); list.add( recordStats ); } } ); RecordStatistics recordStatistics = new RecordStatistics(); recordStatistics.setStats( list ); return recordStatistics; } public static void main( String[] args ) { RecordDAO recordDAO = new RecordDAO(); Record record = new Record(); record.setId( "someI2d" ); record.setLabel( "lael" ); record.setContent( null ); recordDAO.save( record, "dataset2" ); System.out.println( recordDAO.getRecordStatistics( "dataset2" ) ); } }
[Backend] Test
feedback-back/src/main/java/com/feedback/back/dao/RecordDAO.java
[Backend] Test
<ide><path>eedback-back/src/main/java/com/feedback/back/dao/RecordDAO.java <ide> { <ide> RecordDAO recordDAO = new RecordDAO(); <ide> Record record = new Record(); <del> record.setId( "someI2d" ); <del> record.setLabel( "lael" ); <add> record.setId( "3" ); <ide> record.setContent( null ); <ide> recordDAO.save( record, "dataset2" ); <ide>
Java
apache-2.0
f4199aa548ecf51d1c516d1d7e495475a1678fd6
0
FabricMC/fabric-base
/* * Copyright 2016 FabricMC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.fabricmc.loader.impl.util.mappings; import java.util.ArrayDeque; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Queue; import java.util.Set; import org.spongepowered.asm.mixin.transformer.ClassInfo; import net.fabricmc.mapping.tree.ClassDef; import net.fabricmc.mapping.tree.Descriptored; import net.fabricmc.mapping.tree.TinyTree; import net.fabricmc.mapping.util.MixinRemapper; public class MixinIntermediaryDevRemapper extends MixinRemapper { private static final String ambiguousName = "<ambiguous>"; // dummy value for ambiguous mappings - needs querying with additional owner and/or desc info private final Set<String> allPossibleClassNames = new HashSet<>(); private final Map<String, String> nameFieldLookup = new HashMap<>(); private final Map<String, String> nameMethodLookup = new HashMap<>(); private final Map<String, String> nameDescFieldLookup = new HashMap<>(); private final Map<String, String> nameDescMethodLookup = new HashMap<>(); public MixinIntermediaryDevRemapper(TinyTree mappings, String from, String to) { super(mappings, from, to); for (ClassDef classDef : mappings.getClasses()) { allPossibleClassNames.add(classDef.getName(from)); allPossibleClassNames.add(classDef.getName(to)); putMemberInLookup(from, to, classDef.getFields(), nameFieldLookup, nameDescFieldLookup); putMemberInLookup(from, to, classDef.getMethods(), nameMethodLookup, nameDescMethodLookup); } } private <T extends Descriptored> void putMemberInLookup(String from, String to, Collection<T> descriptored, Map<String, String> nameMap, Map<String, String> nameDescMap) { for (T field : descriptored) { String nameFrom = field.getName(from); String descFrom = field.getDescriptor(from); String nameTo = field.getName(to); String prev = nameMap.putIfAbsent(nameFrom, nameTo); if (prev != null && prev != ambiguousName && !prev.equals(nameTo)) { nameDescMap.put(nameFrom, ambiguousName); } String key = getNameDescKey(nameFrom, descFrom); prev = nameDescMap.putIfAbsent(key, nameTo); if (prev != null && prev != ambiguousName && !prev.equals(nameTo)) { nameDescMap.put(key, ambiguousName); } } } private void throwAmbiguousLookup(String type, String name, String desc) { throw new RuntimeException("Ambiguous Mixin: " + type + " lookup " + name + " " + desc+" is not unique"); } private String mapMethodNameInner(String owner, String name, String desc) { String result = super.mapMethodName(owner, name, desc); if (result.equals(name)) { String otherClass = unmap(owner); return super.mapMethodName(otherClass, name, unmapDesc(desc)); } else { return result; } } private String mapFieldNameInner(String owner, String name, String desc) { String result = super.mapFieldName(owner, name, desc); if (result.equals(name)) { String otherClass = unmap(owner); return super.mapFieldName(otherClass, name, unmapDesc(desc)); } else { return result; } } @Override public String mapMethodName(String owner, String name, String desc) { // handle unambiguous values early if (owner == null || allPossibleClassNames.contains(owner)) { String newName; if (desc == null) { newName = nameMethodLookup.get(name); } else { newName = nameDescMethodLookup.get(getNameDescKey(name, desc)); } if (newName != null) { if (newName == ambiguousName) { if (owner == null) { throwAmbiguousLookup("method", name, desc); } } else { return newName; } } else if (owner == null) { return name; } else { // FIXME: this kind of namespace mixing shouldn't happen.. // TODO: this should not repeat more than once String unmapOwner = unmap(owner); String unmapDesc = unmapDesc(desc); if (!unmapOwner.equals(owner) || !unmapDesc.equals(desc)) { return mapMethodName(unmapOwner, name, unmapDesc); } else { // take advantage of the fact allPossibleClassNames // and nameDescLookup cover all sets; if none are present, // we don't have a mapping for it. return name; } } } ClassInfo classInfo = ClassInfo.forName(owner); if (classInfo == null) { // unknown class? return name; } Queue<ClassInfo> queue = new ArrayDeque<>(); do { String ownerO = unmap(classInfo.getName()); String s; if (!(s = mapMethodNameInner(ownerO, name, desc)).equals(name)) { return s; } if (!classInfo.getSuperName().startsWith("java/")) { ClassInfo cSuper = classInfo.getSuperClass(); if (cSuper != null) { queue.add(cSuper); } } for (String itf : classInfo.getInterfaces()) { if (itf.startsWith("java/")) { continue; } ClassInfo cItf = ClassInfo.forName(itf); if (cItf != null) { queue.add(cItf); } } } while ((classInfo = queue.poll()) != null); return name; } @Override public String mapFieldName(String owner, String name, String desc) { // handle unambiguous values early if (owner == null || allPossibleClassNames.contains(owner)) { String newName = nameDescFieldLookup.get(getNameDescKey(name, desc)); if (newName != null) { if (newName == ambiguousName) { if (owner == null) { throwAmbiguousLookup("field", name, desc); } } else { return newName; } } else if (owner == null) { return name; } else { // FIXME: this kind of namespace mixing shouldn't happen.. // TODO: this should not repeat more than once String unmapOwner = unmap(owner); String unmapDesc = unmapDesc(desc); if (!unmapOwner.equals(owner) || !unmapDesc.equals(desc)) { return mapFieldName(unmapOwner, name, unmapDesc); } else { // take advantage of the fact allPossibleClassNames // and nameDescLookup cover all sets; if none are present, // we don't have a mapping for it. return name; } } } ClassInfo c = ClassInfo.forName(map(owner)); while (c != null) { String nextOwner = unmap(c.getName()); String s = mapFieldNameInner(nextOwner, name, desc); if (!s.equals(name)) { return s; } if (c.getSuperName().startsWith("java/")) { break; } c = c.getSuperClass(); } return name; } private static String getNameDescKey(String name, String descriptor) { return name+ ";;" + descriptor; } }
src/main/java/net/fabricmc/loader/impl/util/mappings/MixinIntermediaryDevRemapper.java
/* * Copyright 2016 FabricMC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.fabricmc.loader.impl.util.mappings; import java.util.ArrayDeque; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Queue; import java.util.Set; import org.spongepowered.asm.mixin.transformer.ClassInfo; import net.fabricmc.mapping.tree.ClassDef; import net.fabricmc.mapping.tree.Descriptored; import net.fabricmc.mapping.tree.TinyTree; import net.fabricmc.mapping.util.MixinRemapper; public class MixinIntermediaryDevRemapper extends MixinRemapper { private static final String ambiguousName = "<ambiguous>"; // dummy value for ambiguous mappings - needs querying with additional owner and/or desc info private final Set<String> allPossibleClassNames = new HashSet<>(); private final Map<String, String> nameFieldLookup = new HashMap<>(); private final Map<String, String> nameMethodLookup = new HashMap<>(); private final Map<String, String> nameDescFieldLookup = new HashMap<>(); private final Map<String, String> nameDescMethodLookup = new HashMap<>(); public MixinIntermediaryDevRemapper(TinyTree mappings, String from, String to) { super(mappings, from, to); for (ClassDef classDef : mappings.getClasses()) { allPossibleClassNames.add(classDef.getName(from)); allPossibleClassNames.add(classDef.getName(to)); putMemberInLookup(from, to, classDef.getFields(), nameFieldLookup, nameDescFieldLookup); putMemberInLookup(from, to, classDef.getMethods(), nameMethodLookup, nameDescMethodLookup); } } private <T extends Descriptored> void putMemberInLookup(String from, String to, Collection<T> descriptored, Map<String, String> nameMap, Map<String, String> nameDescMap) { for (T field : descriptored) { String nameFrom = field.getName(from); String descFrom = field.getDescriptor(from); String nameTo = field.getName(to); String prev = nameMap.putIfAbsent(nameFrom, nameTo); if (prev != null && prev != ambiguousName && !prev.equals(nameTo)) { nameDescMap.put(nameFrom, ambiguousName); } String key = getNameDescKey(nameFrom, descFrom); prev = nameDescMap.putIfAbsent(key, nameTo); if (prev != null && prev != ambiguousName && !prev.equals(nameTo)) { nameDescMap.put(key, ambiguousName); } } } private void throwAmbiguousLookup(String type, String name, String desc) { throw new RuntimeException("Ambiguous Mixin: " + type + " lookup " + name + " " + desc+" is not unique"); } private String mapMethodNameInner(String owner, String name, String desc) { String result = super.mapMethodName(owner, name, desc); if (result.equals(name)) { String otherClass = unmap(owner); return super.mapMethodName(otherClass, name, unmapDesc(desc)); } else { return result; } } private String mapFieldNameInner(String owner, String name, String desc) { String result = super.mapFieldName(owner, name, desc); if (result.equals(name)) { String otherClass = unmap(owner); return super.mapFieldName(otherClass, name, unmapDesc(desc)); } else { return result; } } @Override public String mapMethodName(String owner, String name, String desc) { // handle unambiguous values early if (owner == null || allPossibleClassNames.contains(owner)) { String newName; if (desc == null) { newName = nameMethodLookup.get(name); } else { newName = nameDescMethodLookup.get(getNameDescKey(name, desc)); } if (newName != null) { if (newName == ambiguousName) { if (owner == null) { throwAmbiguousLookup("method", name, desc); } } else { return newName; } } else if (owner == null) { return name; } else { // FIXME: this kind of namespace mixing shouldn't happen.. // TODO: this should not repeat more than once String unmapOwner = unmap(owner); String unmapDesc = unmapDesc(desc); if (!unmapOwner.equals(owner) || !unmapDesc.equals(desc)) { return mapMethodName(unmapOwner, name, unmapDesc); } else { // take advantage of the fact allPossibleClassNames // and nameDescLookup cover all sets; if none are present, // we don't have a mapping for it. return name; } } } Queue<ClassInfo> classInfos = new ArrayDeque<>(); classInfos.add(ClassInfo.forName(owner)); while (!classInfos.isEmpty()) { ClassInfo c = classInfos.remove(); String ownerO = unmap(c.getName()); String s; if (!(s = mapMethodNameInner(ownerO, name, desc)).equals(name)) { return s; } if (!c.getSuperName().startsWith("java/")) { ClassInfo cSuper = c.getSuperClass(); if (cSuper != null) { classInfos.add(cSuper); } } for (String itf : c.getInterfaces()) { if (itf.startsWith("java/")) { continue; } ClassInfo cItf = ClassInfo.forName(itf); if (cItf != null) { classInfos.add(cItf); } } } return name; } @Override public String mapFieldName(String owner, String name, String desc) { // handle unambiguous values early if (owner == null || allPossibleClassNames.contains(owner)) { String newName = nameDescFieldLookup.get(getNameDescKey(name, desc)); if (newName != null) { if (newName == ambiguousName) { if (owner == null) { throwAmbiguousLookup("field", name, desc); } } else { return newName; } } else if (owner == null) { return name; } else { // FIXME: this kind of namespace mixing shouldn't happen.. // TODO: this should not repeat more than once String unmapOwner = unmap(owner); String unmapDesc = unmapDesc(desc); if (!unmapOwner.equals(owner) || !unmapDesc.equals(desc)) { return mapFieldName(unmapOwner, name, unmapDesc); } else { // take advantage of the fact allPossibleClassNames // and nameDescLookup cover all sets; if none are present, // we don't have a mapping for it. return name; } } } ClassInfo c = ClassInfo.forName(map(owner)); while (c != null) { String nextOwner = unmap(c.getName()); String s = mapFieldNameInner(nextOwner, name, desc); if (!s.equals(name)) { return s; } if (c.getSuperName().startsWith("java/")) { break; } c = c.getSuperClass(); } return name; } private static String getNameDescKey(String name, String descriptor) { return name+ ";;" + descriptor; } }
Fix MixinIntermediaryDevRemapper.mapMethodName crashing over unknown owner class
src/main/java/net/fabricmc/loader/impl/util/mappings/MixinIntermediaryDevRemapper.java
Fix MixinIntermediaryDevRemapper.mapMethodName crashing over unknown owner class
<ide><path>rc/main/java/net/fabricmc/loader/impl/util/mappings/MixinIntermediaryDevRemapper.java <ide> } <ide> } <ide> <del> Queue<ClassInfo> classInfos = new ArrayDeque<>(); <del> classInfos.add(ClassInfo.forName(owner)); <del> <del> while (!classInfos.isEmpty()) { <del> ClassInfo c = classInfos.remove(); <del> String ownerO = unmap(c.getName()); <add> ClassInfo classInfo = ClassInfo.forName(owner); <add> <add> if (classInfo == null) { // unknown class? <add> return name; <add> } <add> <add> Queue<ClassInfo> queue = new ArrayDeque<>(); <add> <add> do { <add> String ownerO = unmap(classInfo.getName()); <ide> String s; <ide> <ide> if (!(s = mapMethodNameInner(ownerO, name, desc)).equals(name)) { <ide> return s; <ide> } <ide> <del> if (!c.getSuperName().startsWith("java/")) { <del> ClassInfo cSuper = c.getSuperClass(); <add> if (!classInfo.getSuperName().startsWith("java/")) { <add> ClassInfo cSuper = classInfo.getSuperClass(); <ide> <ide> if (cSuper != null) { <del> classInfos.add(cSuper); <del> } <del> } <del> <del> for (String itf : c.getInterfaces()) { <add> queue.add(cSuper); <add> } <add> } <add> <add> for (String itf : classInfo.getInterfaces()) { <ide> if (itf.startsWith("java/")) { <ide> continue; <ide> } <ide> ClassInfo cItf = ClassInfo.forName(itf); <ide> <ide> if (cItf != null) { <del> classInfos.add(cItf); <del> } <del> } <del> } <add> queue.add(cItf); <add> } <add> } <add> } while ((classInfo = queue.poll()) != null); <ide> <ide> return name; <ide> }
Java
mit
94cdc9934278385ff1a50b9f616a8f61983ab6de
0
mtzaperas/burpbuddy,tomsteele/burpbuddy,tomsteele/burpbuddy,mtzaperas/burpbuddy
package burp; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.net.URL; import org.apache.commons.codec.binary.Base64; import com.google.gson.Gson; import static spark.Spark.*; public class ApiServer { public ApiServer(String ip, int port, IBurpExtenderCallbacks callbacks) { IExtensionHelpers helpers = callbacks.getHelpers(); setPort(port); setIpAddress(ip); BScanQueue scanQueue = BScanQueueFactory.create(); Gson gson = new Gson(); before((request, response) -> { String contentType = request.headers("content-type"); if (!request.requestMethod().equals("GET") && (contentType == null || !contentType.contains("application/json"))) { halt(400); } }); after((request, response) -> { response.type("application/json; charset=UTF8"); }); exception(Exception.class, (e, request, response) -> { response.status(400); response.body("{\"error\": \"" + e.getMessage() + "\"}"); }); get("/scope/:url", (request, response) -> { try { URL url = new URL(new String(Base64.decodeBase64(request.params("url")))); if (callbacks.isInScope(url)) { response.status(200); return ""; } else { response.status(404); return ""; } } catch (MalformedURLException e) { response.status(400); return e.getMessage(); } }); post("/scope", (request, response) -> { try { BURLMessage message = gson.fromJson(request.body(), BURLMessage.class); callbacks.includeInScope(new URL(message.url)); response.status(201); return gson.toJson(message); } catch (MalformedURLException e) { response.status(400); return e.getMessage(); } }); delete("/scope/:url", (request, response) -> { try { URL url = new URL(new String(Base64.decodeBase64(request.params("url")))); callbacks.excludeFromScope(url); response.status(204); return ""; } catch (MalformedURLException e) { response.status(400); return e.getMessage(); } }); get("/scanissues", (request, response) -> { IScanIssue[] rawIssues = callbacks.getScanIssues(""); List<BScanIssue> issues = new ArrayList<>(); for (IScanIssue issue : rawIssues) { issues.add(BScanIssueFactory.create(issue, callbacks)); } return gson.toJson(new BArrayWrapper(issues)); }); get("/scanissues/:url", (request, response) -> { byte[] encodedBytes = Base64.decodeBase64(request.params("url")); IScanIssue[] rawIssues = callbacks.getScanIssues(new String(encodedBytes)); List<BScanIssue> issues = new ArrayList<>(); for (IScanIssue issue : rawIssues) { issues.add(BScanIssueFactory.create(issue, callbacks)); } return gson.toJson(new BArrayWrapper(issues)); }); post("/scanissues", (request, response) -> { BScanIssue issue = gson.fromJson(request.body(), BScanIssue.class); callbacks.addScanIssue(issue); response.status(201); return gson.toJson(issue); }); post("/spider", (request, response) -> { BURLMessage message = gson.fromJson(request.body(), BURLMessage.class); try { callbacks.sendToSpider(new URL(message.url)); response.status(200); return ""; } catch (MalformedURLException e) { response.status(400); return e.getMessage(); } }); get("/jar", (request, response) -> { List<BCookie> cookies = new ArrayList<>(); for (ICookie burpCookie: callbacks.getCookieJarContents()) { BCookie cookie = new BCookie(); cookie.expiration = burpCookie.getExpiration(); cookie.domain = burpCookie.getDomain(); cookie.name = burpCookie.getName(); cookie.value = burpCookie.getValue(); cookies.add(cookie); } return gson.toJson(new BArrayWrapper(cookies)); }); post("/jar", (request, response) -> { BCookie cookie = gson.fromJson(request.body(), BCookie.class); callbacks.updateCookieJar(new ICookie() { @Override public String getDomain() { return cookie.domain; } @Override public Date getExpiration() { return cookie.expiration; } @Override public String getName() { return cookie.name; } @Override public String getValue() { return cookie.value; } }); response.status(201); return gson.toJson(cookie); }); post("/scan/active", (request, response) -> { BScanMessage message = gson.fromJson(request.body(), BScanMessage.class); IScanQueueItem item = callbacks.doActiveScan(message.host, message.port, message.useHttps, Base64.decodeBase64(message.request)); BScanQueueID id = scanQueue.addToQueue(item); response.status(201); return gson.toJson(id); }); get("/scan/active/:id", (request, response) -> { int id = Integer.parseInt(request.params("id")); IScanQueueItem item = scanQueue.getItem(id); if (item == null) { response.status(404); return ""; } response.status(200); BScanQueueItem bScanQueueItem = BScanQueueItemFactory.create(id, item, callbacks); return gson.toJson(bScanQueueItem); }); delete("/scan/active/:id", (request, response) -> { int id = Integer.parseInt(request.params("id")); IScanQueueItem item = scanQueue.getItem(id); if (item == null) { response.status(404); return ""; } response.status(204); item.cancel(); scanQueue.removeFromQueue(id); return ""; }); post("/scan/passive", (request, response) -> { BScanMessage message = gson.fromJson(request.body(), BScanMessage.class); callbacks.doPassiveScan(message.host, message.port, message.useHttps, Base64.decodeBase64(message.request), Base64.decodeBase64(message.response)); response.status(201); return "ok"; }); post("/send/:tool", (request, response) -> { String tool = request.params("tool"); BScanMessage message = gson.fromJson(request.body(), BScanMessage.class); switch (tool) { case "intruder": callbacks.sendToIntruder(message.host, message.port, message.useHttps, Base64.decodeBase64(message.request)); response.status(201); break; case "repeater": callbacks.sendToRepeater(message.host, message.port, message.useHttps, Base64.decodeBase64(message.request), "buddy"); response.status(201); break; default: response.status(404); break; } return ""; }); post("/alert", (request, response) -> { callbacks.issueAlert(gson.fromJson(request.body(), BMessage.class).message); response.status(201); return ""; }); get("/sitemap", (request, response) -> { List<BHttpRequestResponse> pairs = new ArrayList<>(); for (IHttpRequestResponse requestResponse: callbacks.getSiteMap("")) { pairs.add(BHttpRequestResponseFactory.create(requestResponse, callbacks, helpers)); } return gson.toJson(new BArrayWrapper(pairs)); }); get("/sitemap/:url", (request, response) -> { byte[] encodedBytes = Base64.decodeBase64(request.params("url")); List<BHttpRequestResponse> pairs = new ArrayList<>(); for (IHttpRequestResponse requestResponse: callbacks.getSiteMap(new String(encodedBytes))) { pairs.add(BHttpRequestResponseFactory.create(requestResponse, callbacks, helpers)); } return gson.toJson(new BArrayWrapper(pairs)); }); post("/sitemap", (request, response) -> { BHttpRequestResponse bHttpRequestResponse = gson.fromJson(request.body(), BHttpRequestResponse.class); callbacks.addToSiteMap(bHttpRequestResponse); response.status(201); return gson.toJson(bHttpRequestResponse); }); get("/proxyhistory", (request, response) -> { List<BHttpRequestResponse> pairs = new ArrayList<>(); for (IHttpRequestResponse requestResponse: callbacks.getProxyHistory()) { pairs.add(BHttpRequestResponseFactory.create(requestResponse, callbacks, helpers)); } return gson.toJson(new BArrayWrapper(pairs)); }); } public void stopServer() { stop(); } }
burp/src/main/java/burp/ApiServer.java
package burp; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.net.URL; import org.apache.commons.codec.binary.Base64; import com.google.gson.Gson; import static spark.Spark.*; public class ApiServer { public ApiServer(String ip, int port, IBurpExtenderCallbacks callbacks) { IExtensionHelpers helpers = callbacks.getHelpers(); setPort(port); setIpAddress(ip); BScanQueue scanQueue = BScanQueueFactory.create(); Gson gson = new Gson(); before((request, response) -> { String contentType = request.headers("content-type"); if (!request.requestMethod().equals("GET") && (contentType == null || !contentType.contains("application/json"))) { halt(400); } }); after((request, response) -> { response.type("application/json; charset=UTF8"); }); get("/scope/:url", (request, response) -> { try { URL url = new URL(new String(Base64.decodeBase64(request.params("url")))); if (callbacks.isInScope(url)) { response.status(200); return ""; } else { response.status(404); return ""; } } catch (MalformedURLException e) { response.status(400); return e.getMessage(); } }); post("/scope", (request, response) -> { try { BURLMessage message = gson.fromJson(request.body(), BURLMessage.class); callbacks.includeInScope(new URL(message.url)); response.status(201); return gson.toJson(message); } catch (MalformedURLException e) { response.status(400); return e.getMessage(); } }); delete("/scope/:url", (request, response) -> { try { URL url = new URL(new String(Base64.decodeBase64(request.params("url")))); callbacks.excludeFromScope(url); response.status(204); return ""; } catch (MalformedURLException e) { response.status(400); return e.getMessage(); } }); get("/scanissues", (request, response) -> { IScanIssue[] rawIssues = callbacks.getScanIssues(""); List<BScanIssue> issues = new ArrayList<>(); for (IScanIssue issue : rawIssues) { issues.add(BScanIssueFactory.create(issue, callbacks)); } return gson.toJson(new BArrayWrapper(issues)); }); get("/scanissues/:url", (request, response) -> { byte[] encodedBytes = Base64.decodeBase64(request.params("url")); IScanIssue[] rawIssues = callbacks.getScanIssues(new String(encodedBytes)); List<BScanIssue> issues = new ArrayList<>(); for (IScanIssue issue : rawIssues) { issues.add(BScanIssueFactory.create(issue, callbacks)); } return gson.toJson(new BArrayWrapper(issues)); }); post("/scanissues", (request, response) -> { BScanIssue issue = gson.fromJson(request.body(), BScanIssue.class); callbacks.addScanIssue(issue); response.status(201); return gson.toJson(issue); }); post("/spider", (request, response) -> { BURLMessage message = gson.fromJson(request.body(), BURLMessage.class); try { callbacks.sendToSpider(new URL(message.url)); response.status(200); return ""; } catch (MalformedURLException e) { response.status(400); return e.getMessage(); } }); get("/jar", (request, response) -> { List<BCookie> cookies = new ArrayList<>(); for (ICookie burpCookie: callbacks.getCookieJarContents()) { BCookie cookie = new BCookie(); cookie.expiration = burpCookie.getExpiration(); cookie.domain = burpCookie.getDomain(); cookie.name = burpCookie.getName(); cookie.value = burpCookie.getValue(); cookies.add(cookie); } return gson.toJson(new BArrayWrapper(cookies)); }); post("/jar", (request, response) -> { BCookie cookie = gson.fromJson(request.body(), BCookie.class); callbacks.updateCookieJar(new ICookie() { @Override public String getDomain() { return cookie.domain; } @Override public Date getExpiration() { return cookie.expiration; } @Override public String getName() { return cookie.name; } @Override public String getValue() { return cookie.value; } }); response.status(201); return gson.toJson(cookie); }); post("/scan/active", (request, response) -> { BScanMessage message = gson.fromJson(request.body(), BScanMessage.class); IScanQueueItem item = callbacks.doActiveScan(message.host, message.port, message.useHttps, Base64.decodeBase64(message.request)); BScanQueueID id = scanQueue.addToQueue(item); response.status(201); return gson.toJson(id); }); get("/scan/active/:id", (request, response) -> { int id = Integer.parseInt(request.params("id")); IScanQueueItem item = scanQueue.getItem(id); if (item == null) { response.status(404); return ""; } response.status(200); BScanQueueItem bScanQueueItem = BScanQueueItemFactory.create(id, item, callbacks); return gson.toJson(bScanQueueItem); }); delete("/scan/active/:id", (request, response) -> { int id = Integer.parseInt(request.params("id")); IScanQueueItem item = scanQueue.getItem(id); if (item == null) { response.status(404); return ""; } response.status(204); item.cancel(); scanQueue.removeFromQueue(id); return ""; }); post("/scan/passive", (request, response) -> { BScanMessage message = gson.fromJson(request.body(), BScanMessage.class); callbacks.doPassiveScan(message.host, message.port, message.useHttps, Base64.decodeBase64(message.request), Base64.decodeBase64(message.response)); response.status(201); return "ok"; }); post("/send/:tool", (request, response) -> { String tool = request.params("tool"); BScanMessage message = gson.fromJson(request.body(), BScanMessage.class); switch (tool) { case "intruder": callbacks.sendToIntruder(message.host, message.port, message.useHttps, Base64.decodeBase64(message.request)); response.status(201); break; case "repeater": callbacks.sendToRepeater(message.host, message.port, message.useHttps, Base64.decodeBase64(message.request), "buddy"); response.status(201); break; default: response.status(404); break; } return ""; }); post("/alert", (request, response) -> { callbacks.issueAlert(gson.fromJson(request.body(), BMessage.class).message); response.status(201); return ""; }); get("/sitemap", (request, response) -> { List<BHttpRequestResponse> pairs = new ArrayList<>(); for (IHttpRequestResponse requestResponse: callbacks.getSiteMap("")) { pairs.add(BHttpRequestResponseFactory.create(requestResponse, callbacks, helpers)); } return gson.toJson(new BArrayWrapper(pairs)); }); get("/sitemap/:url", (request, response) -> { byte[] encodedBytes = Base64.decodeBase64(request.params("url")); List<BHttpRequestResponse> pairs = new ArrayList<>(); for (IHttpRequestResponse requestResponse: callbacks.getSiteMap(new String(encodedBytes))) { pairs.add(BHttpRequestResponseFactory.create(requestResponse, callbacks, helpers)); } return gson.toJson(new BArrayWrapper(pairs)); }); post("/sitemap", (request, response) -> { BHttpRequestResponse bHttpRequestResponse = gson.fromJson(request.body(), BHttpRequestResponse.class); callbacks.addToSiteMap(bHttpRequestResponse); response.status(201); return gson.toJson(bHttpRequestResponse); }); get("/proxyhistory", (request, response) -> { List<BHttpRequestResponse> pairs = new ArrayList<>(); for (IHttpRequestResponse requestResponse: callbacks.getProxyHistory()) { pairs.add(BHttpRequestResponseFactory.create(requestResponse, callbacks, helpers)); } return gson.toJson(new BArrayWrapper(pairs)); }); } public void stopServer() { stop(); } }
Add exception handling route and error messages
burp/src/main/java/burp/ApiServer.java
Add exception handling route and error messages
<ide><path>urp/src/main/java/burp/ApiServer.java <ide> <ide> after((request, response) -> { <ide> response.type("application/json; charset=UTF8"); <add> }); <add> <add> exception(Exception.class, (e, request, response) -> { <add> response.status(400); <add> response.body("{\"error\": \"" + e.getMessage() + "\"}"); <ide> }); <ide> <ide> get("/scope/:url", (request, response) -> {
Java
apache-2.0
a0caee307768f89e7426014f3acc05c1d23941b5
0
SyncFree/SwiftCloud,SyncFree/SwiftCloud,SyncFree/SwiftCloud,SyncFree/SwiftCloud
package swift.application.ycsb; import java.util.HashMap; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.UUID; import java.util.Vector; import swift.client.SwiftImpl; import swift.client.SwiftOptions; import swift.crdt.core.CachePolicy; import swift.crdt.core.IsolationLevel; import swift.crdt.core.ObjectUpdatesListener; import swift.crdt.core.SwiftSession; import swift.crdt.core.TxnHandle; import swift.dc.DCConstants; import swift.exceptions.NetworkException; import swift.exceptions.NoSuchObjectException; import swift.exceptions.SwiftException; import swift.exceptions.VersionNotFoundException; import swift.exceptions.WrongTypeException; import swift.utils.SafeLog; import swift.utils.SafeLog.ReportType; import sys.Sys; import com.yahoo.ycsb.ByteIterator; import com.yahoo.ycsb.DB; import com.yahoo.ycsb.DBException; /** * Abstract YCSB client for SwiftCloud that handles connection, configuration * and errors, but does not define the actual database operations. * * @author mzawirski */ public abstract class AbstractSwiftClient extends DB { public static final int ERROR_NETWORK = -1; public static final int ERROR_NOT_FOUND = -2; public static final int ERROR_WRONG_TYPE = -3; public static final int ERROR_PRUNING_RACE = -4; public static final int ERROR_UNSUPPORTED = -5; public static final IsolationLevel DEFAULT_ISOLATION_LEVEL = IsolationLevel.SNAPSHOT_ISOLATION; public static final CachePolicy DEFAULT_CACHE_POLICY = CachePolicy.CACHED; public static final ObjectUpdatesListener DEFAULT_NOTIFICATIONS_SUBSCRIBER = TxnHandle.UPDATES_SUBSCRIBER; public static final boolean DEFAULT_ASYNC_COMMIT = false; public static final boolean REPORT_EVERY_OPERATION = false; protected SwiftSession session; protected IsolationLevel isolationLevel = DEFAULT_ISOLATION_LEVEL; protected CachePolicy cachePolicy = DEFAULT_CACHE_POLICY; protected ObjectUpdatesListener notificationsSubscriber = DEFAULT_NOTIFICATIONS_SUBSCRIBER; protected boolean asyncCommit = DEFAULT_ASYNC_COMMIT; private UUID sessionId; private boolean reportEveryOperation = REPORT_EVERY_OPERATION; @Override public void init() throws DBException { super.init(); Sys.init(); final Properties props = getProperties(); String hostname = props.getProperty("swift.hostname"); if (hostname == null) { hostname = "localhost"; } String portString = props.getProperty("swift.port"); final int port; if (portString != null) { port = Integer.parseInt(portString); } else { port = DCConstants.SURROGATE_PORT; } // TODO: document properties if (props.getProperty("swift.isolationLevel") != null) { try { isolationLevel = IsolationLevel.valueOf(props.getProperty("swift.isolationLevel")); } catch (IllegalArgumentException x) { System.err.println("Could not recognized isolationLevel=" + props.getProperty("swift.isolationLevel")); } } if (props.getProperty("swift.cachePolicy") != null) { try { cachePolicy = CachePolicy.valueOf(props.getProperty("swift.cachePolicy")); } catch (IllegalArgumentException x) { System.err.println("Could not recognized cachePolicy=" + props.getProperty("swift.cachePolicy")); } } if (props.getProperty("swift.notifications") != null) { notificationsSubscriber = Boolean.parseBoolean(props.getProperty("swift.notifications")) ? TxnHandle.UPDATES_SUBSCRIBER : null; } if (props.getProperty("swift.asyncCommit") != null) { asyncCommit = Boolean.parseBoolean(props.getProperty("swift.asyncCommit")); } if (props.getProperty("swift.reportEveryOperation") != null) { reportEveryOperation = Boolean.parseBoolean(props.getProperty("swift.reportEveryOperation")); } final SwiftOptions options = new SwiftOptions(hostname, port, props); sessionId = UUID.randomUUID(); session = SwiftImpl.newSingleSessionInstance(options, sessionId.toString()); } @Override public void cleanup() throws DBException { super.cleanup(); if (session == null) { return; } session.stopScout(true); session = null; } @Override public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result) { long startTimestamp = 0; if (reportEveryOperation) { startTimestamp = System.currentTimeMillis(); } TxnHandle txn = null; try { txn = session.beginTxn(isolationLevel, cachePolicy, true); int res = readImpl(txn, table, key, fields, result); if (res == 0) { txnCommit(txn); if (reportEveryOperation) { final long durationMs = System.currentTimeMillis() - startTimestamp; SafeLog.report(ReportType.APP_OP, sessionId, "read", durationMs); reportStalenessOnRead(table, key, result, startTimestamp); } } return res; } catch (SwiftException x) { return handleException(x); } finally { cleanUpTxn(txn); } } @Override public int scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { return ERROR_UNSUPPORTED; } @Override public int update(String table, String key, HashMap<String, ByteIterator> values) { long startTimestamp = 0; if (reportEveryOperation) { startTimestamp = System.currentTimeMillis(); reportStalenessOnWrite(table, key, values); } TxnHandle txn = null; try { txn = session.beginTxn(isolationLevel, cachePolicy, false); int res = updateImpl(txn, table, key, values); if (res == 0) { txnCommit(txn); if (reportEveryOperation) { final long durationMs = System.currentTimeMillis() - startTimestamp; SafeLog.report(ReportType.APP_OP, sessionId, "update", durationMs); } } return res; } catch (SwiftException x) { return handleException(x); } finally { cleanUpTxn(txn); } } @Override public int insert(String table, String key, HashMap<String, ByteIterator> values) { long startTimestamp = 0; if (reportEveryOperation) { startTimestamp = System.currentTimeMillis(); reportStalenessOnWrite(table, key, values); } TxnHandle txn = null; try { // WISHME: blind updates would help here txn = session.beginTxn(isolationLevel, cachePolicy, false); int res = insertImpl(txn, table, key, values); if (res == 0) { txnCommit(txn); if (reportEveryOperation) { final long durationMs = System.currentTimeMillis() - startTimestamp; SafeLog.report(ReportType.APP_OP, sessionId, "insert", durationMs); } } return res; } catch (SwiftException x) { return handleException(x); } finally { cleanUpTxn(txn); } } @Override public int delete(String table, String key) { return ERROR_UNSUPPORTED; } protected abstract int readImpl(TxnHandle txn, String table, String key, Set<String> fields, HashMap<String, ByteIterator> result) throws WrongTypeException, NoSuchObjectException, VersionNotFoundException, NetworkException; protected abstract int updateImpl(TxnHandle txn, String table, String key, HashMap<String, ByteIterator> values) throws WrongTypeException, NoSuchObjectException, VersionNotFoundException, NetworkException; protected abstract int insertImpl(TxnHandle txn, String table, String key, HashMap<String, ByteIterator> values) throws WrongTypeException, NoSuchObjectException, VersionNotFoundException, NetworkException; private void cleanUpTxn(TxnHandle txn) { if (txn != null && !txn.getStatus().isTerminated()) { txn.rollback(); } } private void txnCommit(TxnHandle txn) { if (asyncCommit) { txn.commitAsync(null); } else { txn.commit(); } } private int handleException(final SwiftException x) { x.printStackTrace(); if (x instanceof WrongTypeException) { return ERROR_WRONG_TYPE; } else if (x instanceof NoSuchObjectException) { return ERROR_NOT_FOUND; } else if (x instanceof VersionNotFoundException) { return ERROR_PRUNING_RACE; } else if (x instanceof NetworkException) { return ERROR_NETWORK; } else { System.err.println("Unexepcted type of exception"); return -666; } } private void reportStalenessOnRead(String table, String key, HashMap<String, ByteIterator> result, long readTimestamp) { if (!ReportType.STALENESS_YCSB_READ.isEnabled()) { return; } String prefixS = table + ":" + key + ":"; for (Entry<String, ByteIterator> entry : result.entrySet()) { ByteIterator it = entry.getValue(); long time = (long) it.nextByte(); time = time + ((long) it.nextByte()) << 7; time = time + ((long) it.nextByte()) << 14; time = time + ((long) it.nextByte()) << 21; SafeLog.report(ReportType.STALENESS_YCSB_READ, sessionId, prefixS + entry.getKey(), time, readTimestamp); } } private void reportStalenessOnWrite(String table, String key, HashMap<String, ByteIterator> values) { if (!ReportType.STALENESS_YCSB_WRITE.isEnabled()) { return; } String prefixS = table + ":" + key + ":"; for (Entry<String, ByteIterator> entry : values.entrySet()) { ByteIterator it = entry.getValue(); long time = (long) it.nextByte(); time = time + ((long) it.nextByte()) << 7; time = time + ((long) it.nextByte()) << 14; time = time + ((long) it.nextByte()) << 21; SafeLog.report(ReportType.STALENESS_YCSB_WRITE, sessionId, prefixS + entry.getKey(), time); } } }
src-contrib/swift/application/ycsb/AbstractSwiftClient.java
package swift.application.ycsb; import java.util.HashMap; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.UUID; import java.util.Vector; import swift.client.SwiftImpl; import swift.client.SwiftOptions; import swift.crdt.core.CachePolicy; import swift.crdt.core.IsolationLevel; import swift.crdt.core.ObjectUpdatesListener; import swift.crdt.core.SwiftSession; import swift.crdt.core.TxnHandle; import swift.dc.DCConstants; import swift.exceptions.NetworkException; import swift.exceptions.NoSuchObjectException; import swift.exceptions.SwiftException; import swift.exceptions.VersionNotFoundException; import swift.exceptions.WrongTypeException; import swift.utils.SafeLog; import swift.utils.SafeLog.ReportType; import sys.Sys; import com.yahoo.ycsb.ByteIterator; import com.yahoo.ycsb.DB; import com.yahoo.ycsb.DBException; /** * Abstract YCSB client for SwiftCloud that handles connection, configuration * and errors, but does not define the actual database operations. * * @author mzawirski */ public abstract class AbstractSwiftClient extends DB { public static final int ERROR_NETWORK = -1; public static final int ERROR_NOT_FOUND = -2; public static final int ERROR_WRONG_TYPE = -3; public static final int ERROR_PRUNING_RACE = -4; public static final int ERROR_UNSUPPORTED = -5; public static final IsolationLevel DEFAULT_ISOLATION_LEVEL = IsolationLevel.SNAPSHOT_ISOLATION; public static final CachePolicy DEFAULT_CACHE_POLICY = CachePolicy.CACHED; public static final ObjectUpdatesListener DEFAULT_NOTIFICATIONS_SUBSCRIBER = TxnHandle.UPDATES_SUBSCRIBER; public static final boolean DEFAULT_ASYNC_COMMIT = false; public static final boolean REPORT_EVERY_OPERATION = false; protected SwiftSession session; protected IsolationLevel isolationLevel = DEFAULT_ISOLATION_LEVEL; protected CachePolicy cachePolicy = DEFAULT_CACHE_POLICY; protected ObjectUpdatesListener notificationsSubscriber = DEFAULT_NOTIFICATIONS_SUBSCRIBER; protected boolean asyncCommit = DEFAULT_ASYNC_COMMIT; private UUID sessionId; private boolean reportEveryOperation = REPORT_EVERY_OPERATION; @Override public void init() throws DBException { super.init(); Sys.init(); final Properties props = getProperties(); String hostname = props.getProperty("swift.hostname"); if (hostname == null) { hostname = "localhost"; } String portString = props.getProperty("swift.port"); final int port; if (portString != null) { port = Integer.parseInt(portString); } else { port = DCConstants.SURROGATE_PORT; } // TODO: document properties if (props.getProperty("swift.isolationLevel") != null) { try { isolationLevel = IsolationLevel.valueOf(props.getProperty("swift.isolationLevel")); } catch (IllegalArgumentException x) { System.err.println("Could not recognized isolationLevel=" + props.getProperty("swift.isolationLevel")); } } if (props.getProperty("swift.cachePolicy") != null) { try { cachePolicy = CachePolicy.valueOf(props.getProperty("swift.cachePolicy")); } catch (IllegalArgumentException x) { System.err.println("Could not recognized cachePolicy=" + props.getProperty("swift.cachePolicy")); } } if (props.getProperty("swift.notifications") != null) { notificationsSubscriber = Boolean.parseBoolean(props.getProperty("swift.notifications")) ? TxnHandle.UPDATES_SUBSCRIBER : null; } if (props.getProperty("swift.asyncCommit") != null) { asyncCommit = Boolean.parseBoolean(props.getProperty("swift.asyncCommit")); } if (props.getProperty("swift.reportEveryOperation") != null) { reportEveryOperation = Boolean.parseBoolean(props.getProperty("swift.reportEveryOperation")); } final SwiftOptions options = new SwiftOptions(hostname, port, props); sessionId = UUID.randomUUID(); session = SwiftImpl.newSingleSessionInstance(options, sessionId.toString()); } @Override public void cleanup() throws DBException { super.cleanup(); if (session == null) { return; } session.stopScout(true); session = null; } @Override public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result) { long startTimestamp = 0; if (reportEveryOperation) { startTimestamp = System.currentTimeMillis(); } TxnHandle txn = null; try { txn = session.beginTxn(isolationLevel, cachePolicy, true); int res = readImpl(txn, table, key, fields, result); if (res == 0) { txnCommit(txn); } return res; } catch (SwiftException x) { return handleException(x); } finally { tryTerminateTxn(txn); if (reportEveryOperation) { final long durationMs = System.currentTimeMillis() - startTimestamp; SafeLog.report(ReportType.APP_OP, sessionId, "read", durationMs); reportStalenessOnRead(table, key, result, startTimestamp); } } } @Override public int scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { return ERROR_UNSUPPORTED; } @Override public int update(String table, String key, HashMap<String, ByteIterator> values) { long startTimestamp = 0; if (reportEveryOperation) { startTimestamp = System.currentTimeMillis(); reportStalenessOnWrite(table, key, values); } TxnHandle txn = null; try { txn = session.beginTxn(isolationLevel, cachePolicy, false); int res = updateImpl(txn, table, key, values); if (res == 0) { txnCommit(txn); } return res; } catch (SwiftException x) { return handleException(x); } finally { tryTerminateTxn(txn); if (reportEveryOperation) { final long durationMs = System.currentTimeMillis() - startTimestamp; SafeLog.report(ReportType.APP_OP, sessionId, "update", durationMs); } } } @Override public int insert(String table, String key, HashMap<String, ByteIterator> values) { long startTimestamp = 0; if (reportEveryOperation) { startTimestamp = System.currentTimeMillis(); reportStalenessOnWrite(table, key, values); } TxnHandle txn = null; try { // WISHME: blind updates would help here txn = session.beginTxn(isolationLevel, cachePolicy, false); int res = insertImpl(txn, table, key, values); if (res == 0) { txnCommit(txn); } return res; } catch (SwiftException x) { return handleException(x); } finally { tryTerminateTxn(txn); if (reportEveryOperation) { final long durationMs = System.currentTimeMillis() - startTimestamp; SafeLog.report(ReportType.APP_OP, sessionId, "insert", durationMs); } } } @Override public int delete(String table, String key) { return ERROR_UNSUPPORTED; } protected abstract int readImpl(TxnHandle txn, String table, String key, Set<String> fields, HashMap<String, ByteIterator> result) throws WrongTypeException, NoSuchObjectException, VersionNotFoundException, NetworkException; protected abstract int updateImpl(TxnHandle txn, String table, String key, HashMap<String, ByteIterator> values) throws WrongTypeException, NoSuchObjectException, VersionNotFoundException, NetworkException; protected abstract int insertImpl(TxnHandle txn, String table, String key, HashMap<String, ByteIterator> values) throws WrongTypeException, NoSuchObjectException, VersionNotFoundException, NetworkException; private void tryTerminateTxn(TxnHandle txn) { if (txn != null && !txn.getStatus().isTerminated()) { txn.rollback(); } } private void txnCommit(TxnHandle txn) { if (asyncCommit) { txn.commitAsync(null); } else { txn.commit(); } } private int handleException(final SwiftException x) { x.printStackTrace(); if (x instanceof WrongTypeException) { return ERROR_WRONG_TYPE; } else if (x instanceof NoSuchObjectException) { return ERROR_NOT_FOUND; } else if (x instanceof VersionNotFoundException) { return ERROR_PRUNING_RACE; } else if (x instanceof NetworkException) { return ERROR_NETWORK; } else { System.err.println("Unexepcted type of exception"); return -666; } } private void reportStalenessOnRead(String table, String key, HashMap<String, ByteIterator> result, long readTimestamp) { if (!ReportType.STALENESS_YCSB_READ.isEnabled()) { return; } String prefixS = table + ":" + key + ":"; for (Entry<String, ByteIterator> entry : result.entrySet()) { ByteIterator it = entry.getValue(); long time = (long) it.nextByte(); time = time + ((long) it.nextByte()) << 7; time = time + ((long) it.nextByte()) << 14; time = time + ((long) it.nextByte()) << 21; SafeLog.report(ReportType.STALENESS_YCSB_READ, sessionId, prefixS + entry.getKey(), time, readTimestamp); } } private void reportStalenessOnWrite(String table, String key, HashMap<String, ByteIterator> values) { if (!ReportType.STALENESS_YCSB_WRITE.isEnabled()) { return; } String prefixS = table + ":" + key + ":"; for (Entry<String, ByteIterator> entry : values.entrySet()) { ByteIterator it = entry.getValue(); long time = (long) it.nextByte(); time = time + ((long) it.nextByte()) << 7; time = time + ((long) it.nextByte()) << 14; time = time + ((long) it.nextByte()) << 21; SafeLog.report(ReportType.STALENESS_YCSB_WRITE, sessionId, prefixS + entry.getKey(), time); } } }
YCSB: report only successful operations response time
src-contrib/swift/application/ycsb/AbstractSwiftClient.java
YCSB: report only successful operations response time
<ide><path>rc-contrib/swift/application/ycsb/AbstractSwiftClient.java <ide> int res = readImpl(txn, table, key, fields, result); <ide> if (res == 0) { <ide> txnCommit(txn); <add> if (reportEveryOperation) { <add> final long durationMs = System.currentTimeMillis() - startTimestamp; <add> SafeLog.report(ReportType.APP_OP, sessionId, "read", durationMs); <add> reportStalenessOnRead(table, key, result, startTimestamp); <add> } <ide> } <ide> return res; <ide> } catch (SwiftException x) { <ide> return handleException(x); <ide> } finally { <del> tryTerminateTxn(txn); <del> if (reportEveryOperation) { <del> final long durationMs = System.currentTimeMillis() - startTimestamp; <del> SafeLog.report(ReportType.APP_OP, sessionId, "read", durationMs); <del> reportStalenessOnRead(table, key, result, startTimestamp); <del> } <add> cleanUpTxn(txn); <ide> } <ide> } <ide> <ide> int res = updateImpl(txn, table, key, values); <ide> if (res == 0) { <ide> txnCommit(txn); <add> if (reportEveryOperation) { <add> final long durationMs = System.currentTimeMillis() - startTimestamp; <add> SafeLog.report(ReportType.APP_OP, sessionId, "update", durationMs); <add> } <ide> } <ide> return res; <ide> } catch (SwiftException x) { <ide> return handleException(x); <ide> } finally { <del> tryTerminateTxn(txn); <del> if (reportEveryOperation) { <del> final long durationMs = System.currentTimeMillis() - startTimestamp; <del> SafeLog.report(ReportType.APP_OP, sessionId, "update", durationMs); <del> } <add> cleanUpTxn(txn); <ide> } <ide> } <ide> <ide> int res = insertImpl(txn, table, key, values); <ide> if (res == 0) { <ide> txnCommit(txn); <add> if (reportEveryOperation) { <add> final long durationMs = System.currentTimeMillis() - startTimestamp; <add> SafeLog.report(ReportType.APP_OP, sessionId, "insert", durationMs); <add> } <ide> } <ide> return res; <ide> } catch (SwiftException x) { <ide> return handleException(x); <ide> } finally { <del> tryTerminateTxn(txn); <del> if (reportEveryOperation) { <del> final long durationMs = System.currentTimeMillis() - startTimestamp; <del> SafeLog.report(ReportType.APP_OP, sessionId, "insert", durationMs); <del> } <add> cleanUpTxn(txn); <ide> } <ide> } <ide> <ide> protected abstract int insertImpl(TxnHandle txn, String table, String key, HashMap<String, ByteIterator> values) <ide> throws WrongTypeException, NoSuchObjectException, VersionNotFoundException, NetworkException; <ide> <del> private void tryTerminateTxn(TxnHandle txn) { <add> private void cleanUpTxn(TxnHandle txn) { <ide> if (txn != null && !txn.getStatus().isTerminated()) { <ide> txn.rollback(); <ide> }
Java
lgpl-2.1
8cd24fa6055cdd25d1fc42de51f6bfadc7d836e9
0
lucee/Lucee,lucee/Lucee,lucee/Lucee,lucee/Lucee
/** * Copyright (c) 2014, the Railo Company Ltd. * Copyright (c) 2015, Lucee Assosication Switzerland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * */ package lucee.runtime; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedDeque; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletRegistration; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.JspApplicationContext; import javax.servlet.jsp.JspEngineInfo; import lucee.cli.servlet.HTTPServletImpl; import lucee.commons.io.SystemUtil; import lucee.commons.io.log.Log; import lucee.commons.io.log.LogUtil; import lucee.commons.io.res.util.ResourceUtil; import lucee.commons.lang.ExceptionUtil; import lucee.commons.lang.SizeOf; import lucee.loader.engine.CFMLEngine; import lucee.runtime.config.ConfigImpl; import lucee.runtime.config.ConfigWeb; import lucee.runtime.config.ConfigWebImpl; import lucee.runtime.config.Constants; import lucee.runtime.engine.CFMLEngineImpl; import lucee.runtime.engine.JspEngineInfoImpl; import lucee.runtime.engine.MonitorState; import lucee.runtime.engine.ThreadLocalPageContext; import lucee.runtime.exp.PageException; import lucee.runtime.exp.PageExceptionImpl; import lucee.runtime.exp.RequestTimeoutException; import lucee.runtime.functions.string.Hash; import lucee.runtime.op.Caster; import lucee.runtime.type.Array; import lucee.runtime.type.ArrayImpl; import lucee.runtime.type.Struct; import lucee.runtime.type.StructImpl; import lucee.runtime.type.dt.DateTimeImpl; import lucee.runtime.type.scope.LocalNotSupportedScope; import lucee.runtime.type.scope.ScopeContext; import lucee.runtime.type.util.ArrayUtil; import lucee.runtime.type.util.KeyConstants; import lucee.runtime.type.util.ListUtil; /** * implements a JSP Factory, this class produces JSP compatible PageContext objects, as well as the * required ColdFusion specified interfaces */ public final class CFMLFactoryImpl extends CFMLFactory { private static final long MAX_AGE = 5 * 60000; // 5 minutes private static final int MAX_SIZE = 10000; private static JspEngineInfo info = new JspEngineInfoImpl("1.0"); private ConfigWebImpl config; ConcurrentLinkedDeque<PageContextImpl> pcs = new ConcurrentLinkedDeque<PageContextImpl>(); private final Map<Integer, PageContextImpl> runningPcs = new ConcurrentHashMap<Integer, PageContextImpl>(); private final Map<Integer, PageContextImpl> runningChildPcs = new ConcurrentHashMap<Integer, PageContextImpl>(); int idCounter = 1; private ScopeContext scopeContext = new ScopeContext(this); private HttpServlet _servlet; private URL url = null; private CFMLEngineImpl engine; private ArrayList<String> cfmlExtensions; private ArrayList<String> luceeExtensions; private ServletConfig servletConfig; public CFMLFactoryImpl(CFMLEngineImpl engine, ServletConfig sg) { this.engine = engine; this.servletConfig = sg; } /** * reset the PageContexes */ @Override public void resetPageContext() { LogUtil.log(config, Log.LEVEL_INFO, CFMLFactoryImpl.class.getName(), "Reset " + pcs.size() + " Unused PageContexts"); pcs.clear(); Iterator<PageContextImpl> it = runningPcs.values().iterator(); while (it.hasNext()) { it.next().reset(); } } @Override public javax.servlet.jsp.PageContext getPageContext(Servlet servlet, ServletRequest req, ServletResponse rsp, String errorPageURL, boolean needsSession, int bufferSize, boolean autoflush) { return getPageContextImpl((HttpServlet) servlet, (HttpServletRequest) req, (HttpServletResponse) rsp, errorPageURL, needsSession, bufferSize, autoflush, true, false, -1, true, false, false); } @Override @Deprecated public PageContext getLuceePageContext(HttpServlet servlet, HttpServletRequest req, HttpServletResponse rsp, String errorPageURL, boolean needsSession, int bufferSize, boolean autoflush) { // runningCount++; return getPageContextImpl(servlet, req, rsp, errorPageURL, needsSession, bufferSize, autoflush, true, false, -1, true, false, false); } @Override public PageContext getLuceePageContext(HttpServlet servlet, HttpServletRequest req, HttpServletResponse rsp, String errorPageURL, boolean needsSession, int bufferSize, boolean autoflush, boolean register, long timeout, boolean register2RunningThreads, boolean ignoreScopes) { // runningCount++; return getPageContextImpl(servlet, req, rsp, errorPageURL, needsSession, bufferSize, autoflush, register, false, timeout, register2RunningThreads, ignoreScopes, false); } public PageContextImpl getPageContextImpl(HttpServlet servlet, HttpServletRequest req, HttpServletResponse rsp, String errorPageURL, boolean needsSession, int bufferSize, boolean autoflush, boolean register2Thread, boolean isChild, long timeout, boolean register2RunningThreads, boolean ignoreScopes, boolean createNew) { PageContextImpl pc; if (createNew || pcs.isEmpty()) { pc = null; } else { try { pc = pcs.pop(); } catch (NoSuchElementException nsee) { pc = null; } } if (pc == null) pc = new PageContextImpl(scopeContext, config, idCounter++, servlet, ignoreScopes); if (timeout > 0) pc.setRequestTimeout(timeout); if (register2RunningThreads) { runningPcs.put(Integer.valueOf(pc.getId()), pc); if (isChild) runningChildPcs.put(Integer.valueOf(pc.getId()), pc); } this._servlet = servlet; if (register2Thread) ThreadLocalPageContext.register(pc); pc.initialize(servlet, req, rsp, errorPageURL, needsSession, bufferSize, autoflush, isChild, ignoreScopes); return pc; } @Override public void releasePageContext(javax.servlet.jsp.PageContext pc) { releaseLuceePageContext((PageContext) pc, true); } @Override public CFMLEngine getEngine() { return engine; } @Override @Deprecated public void releaseLuceePageContext(PageContext pc) { releaseLuceePageContext(pc, true); } /** * Similar to the releasePageContext Method, but take lucee PageContext as entry * * @param pc */ @Override public void releaseLuceePageContext(PageContext pc, boolean unregisterFromThread) { if (pc.getId() < 0) return; boolean isChild = pc.getParentPageContext() != null; // we need to get this check before release is executed // when pc was registered with an other thread, we register with this thread when calling release PageContext beforePC = ThreadLocalPageContext.get(); boolean tmpRegister = false; if (beforePC != pc) { ThreadLocalPageContext.register(pc); tmpRegister = true; } boolean releaseFailed = false; try { pc.release(); } catch (Exception e) { releaseFailed = true; config.getLog("application").error("release page context", e); } if (tmpRegister) ThreadLocalPageContext.register(beforePC); if (unregisterFromThread) ThreadLocalPageContext.release(); runningPcs.remove(Integer.valueOf(pc.getId())); if (isChild) { runningChildPcs.remove(Integer.valueOf(pc.getId())); } if (pcs.size() < 100 && ((PageContextImpl) pc).getTimeoutStackTrace() == null && !releaseFailed)// not more than 100 PCs pcs.push((PageContextImpl) pc); if (runningPcs.size() > MAX_SIZE) clean(runningPcs); if (runningChildPcs.size() > MAX_SIZE) clean(runningChildPcs); } private void clean(Map<Integer, PageContextImpl> map) { Iterator<PageContextImpl> it = map.values().iterator(); PageContextImpl pci; long now = System.currentTimeMillis(); while (it.hasNext()) { pci = it.next(); if (pci.isGatewayContext() || pci.getStartTime() + MAX_AGE > now) continue; } } /** * check timeout of all running threads, downgrade also priority from all thread run longer than 10 * seconds */ @Override public void checkTimeout() { if (!engine.allowRequestTimeout()) return; // print.e(MonitorState.checkForBlockedThreads(runningPcs.values())); // print.e(MonitorState.checkForBlockedThreads(runningChildPcs.values())); // synchronized (runningPcs) { // int len=runningPcs.size(); // we only terminate child threads Map<Integer, PageContextImpl> map = engine.exeRequestAsync() ? runningChildPcs : runningPcs; { Iterator<Entry<Integer, PageContextImpl>> it = map.entrySet().iterator(); PageContextImpl pc; Entry<Integer, PageContextImpl> e; while (it.hasNext()) { e = it.next(); pc = e.getValue(); long timeout = pc.getRequestTimeout(); if (pc.getStartTime() + timeout < System.currentTimeMillis() && Long.MAX_VALUE != timeout) { Log log = ((ConfigImpl) pc.getConfig()).getLog("requesttimeout"); if (log != null) { PageContext root = pc.getRootPageContext(); log.log(Log.LEVEL_ERROR, "controller", "stop " + (root != null && root != pc ? "thread" : "request") + " (" + pc.getId() + ") because run into a timeout. ATM we have " + getActiveRequests() + " active request(s) and " + getActiveThreads() + " active cfthreads " + getPath(pc) + "." + MonitorState.getBlockedThreads(pc) + RequestTimeoutException.locks(pc), ExceptionUtil.toThrowable(pc.getThread().getStackTrace())); } terminate(pc, true); runningPcs.remove(Integer.valueOf(pc.getId())); it.remove(); } // after 10 seconds downgrade priority of the thread else if (pc.getStartTime() + 10000 < System.currentTimeMillis() && pc.getThread().getPriority() != Thread.MIN_PRIORITY) { Log log = ((ConfigImpl) pc.getConfig()).getLog("requesttimeout"); if (log != null) { PageContext root = pc.getRootPageContext(); log.log(Log.LEVEL_WARN, "controller", "downgrade priority of the a " + (root != null && root != pc ? "thread" : "request") + " at " + getPath(pc) + ". " + MonitorState.getBlockedThreads(pc) + RequestTimeoutException.locks(pc), ExceptionUtil.toThrowable(pc.getThread().getStackTrace())); } try { pc.getThread().setPriority(Thread.MIN_PRIORITY); } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); } } } } } public static void terminate(PageContextImpl pc, boolean async) { pc.getConfig().getThreadQueue().exit(pc); SystemUtil.stop(pc, async); } private static String getPath(PageContext pc) { try { String base = ResourceUtil.getResource(pc, pc.getBasePageSource()).getAbsolutePath(); String current = ResourceUtil.getResource(pc, pc.getCurrentPageSource()).getAbsolutePath(); if (base.equals(current)) return "path: " + base; return "path: " + base + " (" + current + ")"; } catch (NullPointerException npe) { return "(no path available)"; } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); return "(fail to retrieve path:" + t.getClass().getName() + ":" + t.getMessage() + ")"; } } @Override public JspEngineInfo getEngineInfo() { return info; } /** * @return returns count of pagecontext in use */ @Override public int getUsedPageContextLength() { int length = 0; try { Iterator<PageContextImpl> it = runningPcs.values().iterator(); while (it.hasNext()) { PageContextImpl pc = it.next(); if (!pc.isGatewayContext()) length++; } } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); return length; } return length; } /** * @return Returns the config. */ @Override public ConfigWeb getConfig() { return config; } public ConfigWebImpl getConfigWebImpl() { return config; } /** * @return Returns the scopeContext. */ public ScopeContext getScopeContext() { return scopeContext; } /** * @return label of the factory */ @Override public Object getLabel() { return ((ConfigWebImpl) getConfig()).getLabel(); } /** * @param label */ @Override public void setLabel(String label) { // deprecated } @Override public URL getURL() { return url; } public void setURL(URL url) { this.url = url; } /** * @return the servlet */ @Override public HttpServlet getServlet() { if (_servlet == null) _servlet = new HTTPServletImpl(servletConfig, servletConfig.getServletContext(), servletConfig.getServletName()); return _servlet; } public void setConfig(ConfigWebImpl config) { this.config = config; } public Map<Integer, PageContextImpl> getActivePageContexts() { return runningPcs; } public long getPageContextsSize() { return SizeOf.size(pcs); } public long getActiveRequests() { return runningPcs.size(); } public long getActiveThreads() { return runningChildPcs.size(); } public Array getInfo() { Array info = new ArrayImpl(); // synchronized (runningPcs) { // int len=runningPcs.size(); Iterator<PageContextImpl> it = runningPcs.values().iterator(); PageContextImpl pc; Struct data, sctThread, scopes; Thread thread; Entry<Integer, PageContextImpl> e; ConfigWebImpl cw; while (it.hasNext()) { pc = it.next(); cw = (ConfigWebImpl) pc.getConfig(); data = new StructImpl(); sctThread = new StructImpl(); scopes = new StructImpl(); data.setEL("thread", sctThread); data.setEL("scopes", scopes); if (pc.isGatewayContext()) continue; thread = pc.getThread(); if (thread == Thread.currentThread()) continue; thread = pc.getThread(); if (thread == Thread.currentThread()) continue; data.setEL("startTime", new DateTimeImpl(pc.getStartTime(), false)); data.setEL("endTime", new DateTimeImpl(pc.getStartTime() + pc.getRequestTimeout(), false)); data.setEL(KeyConstants._timeout, new Double(pc.getRequestTimeout())); // thread sctThread.setEL(KeyConstants._name, thread.getName()); sctThread.setEL(KeyConstants._priority, Caster.toDouble(thread.getPriority())); sctThread.setEL(KeyConstants._state, thread.getState().name()); StackTraceElement[] stes = thread.getStackTrace(); data.setEL("TagContext", PageExceptionImpl.getTagContext(pc.getConfig(), stes)); // Java Stacktrace StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); Throwable t = new Throwable(); t.setStackTrace(stes); t.printStackTrace(pw); pw.close(); data.setEL("JavaStackTrace", sw.toString()); data.setEL(KeyConstants._urltoken, pc.getURLToken()); try { if (pc.getConfig().debug()) data.setEL("debugger", pc.getDebugger().getDebuggingData(pc)); } catch (PageException e2) {} try { data.setEL(KeyConstants._id, Hash.call(pc, pc.getId() + ":" + pc.getStartTime())); } catch (PageException e1) {} data.setEL(KeyConstants._hash, cw.getHash()); data.setEL("contextId", cw.getIdentification().getId()); data.setEL(KeyConstants._label, cw.getLabel()); data.setEL("requestId", pc.getId()); // Scopes scopes.setEL(KeyConstants._name, pc.getApplicationContext().getName()); try { scopes.setEL(KeyConstants._application, pc.applicationScope()); } catch (PageException pe) {} try { scopes.setEL(KeyConstants._session, pc.sessionScope()); } catch (PageException pe) {} try { scopes.setEL(KeyConstants._client, pc.clientScope()); } catch (PageException pe) {} scopes.setEL(KeyConstants._cookie, pc.cookieScope()); scopes.setEL(KeyConstants._variables, pc.variablesScope()); if (!(pc.localScope() instanceof LocalNotSupportedScope)) { scopes.setEL(KeyConstants._local, pc.localScope()); scopes.setEL(KeyConstants._arguments, pc.argumentsScope()); } scopes.setEL(KeyConstants._cgi, pc.cgiScope()); scopes.setEL(KeyConstants._form, pc.formScope()); scopes.setEL(KeyConstants._url, pc.urlScope()); scopes.setEL(KeyConstants._request, pc.requestScope()); info.appendEL(data); } return info; // } } public void stopThread(String threadId, String stopType) { // synchronized (runningPcs) { Iterator<PageContextImpl> it = runningPcs.values().iterator(); PageContext pc; while (it.hasNext()) { pc = it.next(); // Log log = ((ConfigImpl)pc.getConfig()).getLog("application"); try { String id = Hash.call(pc, pc.getId() + ":" + pc.getStartTime()); if (id.equals(threadId)) { stopType = stopType.trim(); // Throwable t; if ("abort".equalsIgnoreCase(stopType) || "cfabort".equalsIgnoreCase(stopType)) throw new RuntimeException("type [" + stopType + "] is no longer supported"); // t=new Abort(Abort.SCOPE_REQUEST); // else t=new RequestTimeoutException(pc.getThread(),"request has been forced to stop."); SystemUtil.stop(pc, true); SystemUtil.sleep(10); break; } } catch (PageException e1) {} } // } } @Override public JspApplicationContext getJspApplicationContext(ServletContext arg0) { throw new RuntimeException("not supported!"); } @Override public int toDialect(String ext) { // MUST improve perfomance if (cfmlExtensions == null) _initExtensions(); if (cfmlExtensions.contains(ext.toLowerCase())) return CFMLEngine.DIALECT_CFML; return CFMLEngine.DIALECT_CFML; } // FUTURE add to loader public int toDialect(String ext, int defaultValue) { if (ext == null) return defaultValue; if (cfmlExtensions == null) _initExtensions(); if (cfmlExtensions.contains(ext = ext.toLowerCase())) return CFMLEngine.DIALECT_CFML; if (luceeExtensions.contains(ext)) return CFMLEngine.DIALECT_LUCEE; return defaultValue; } private void _initExtensions() { cfmlExtensions = new ArrayList<String>(); luceeExtensions = new ArrayList<String>(); try { Iterator<?> it = getServlet().getServletContext().getServletRegistrations().entrySet().iterator(); Entry<String, ? extends ServletRegistration> e; String cn; while (it.hasNext()) { e = (Entry<String, ? extends ServletRegistration>) it.next(); cn = e.getValue().getClassName(); if (cn != null && cn.indexOf("LuceeServlet") != -1) { setExtensions(luceeExtensions, e.getValue().getMappings().iterator()); } else if (cn != null && cn.indexOf("CFMLServlet") != -1) { setExtensions(cfmlExtensions, e.getValue().getMappings().iterator()); } } } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); ArrayUtil.addAll(cfmlExtensions, Constants.getCFMLExtensions()); ArrayUtil.addAll(luceeExtensions, Constants.getLuceeExtensions()); } } private void setExtensions(ArrayList<String> extensions, Iterator<String> it) { String str, str2; Iterator<String> it2; while (it.hasNext()) { str = it.next(); it2 = ListUtil.listToSet(str, ',', true).iterator(); while (it2.hasNext()) { str2 = it2.next(); extensions.add(str2.substring(2));// MUSTMUST better impl } } } @Override public Iterator<String> getCFMLExtensions() { if (cfmlExtensions == null) _initExtensions(); return cfmlExtensions.iterator(); } @Override public Iterator<String> getLuceeExtensions() { if (luceeExtensions == null) _initExtensions(); return luceeExtensions.iterator(); } public static RequestTimeoutException createRequestTimeoutException(PageContext pc) { return new RequestTimeoutException(pc, pc.getThread().getStackTrace()); } }
core/src/main/java/lucee/runtime/CFMLFactoryImpl.java
/** * Copyright (c) 2014, the Railo Company Ltd. * Copyright (c) 2015, Lucee Assosication Switzerland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * */ package lucee.runtime; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedDeque; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletRegistration; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.JspApplicationContext; import javax.servlet.jsp.JspEngineInfo; import lucee.cli.servlet.HTTPServletImpl; import lucee.commons.io.SystemUtil; import lucee.commons.io.log.Log; import lucee.commons.io.log.LogUtil; import lucee.commons.io.res.util.ResourceUtil; import lucee.commons.lang.ExceptionUtil; import lucee.commons.lang.SizeOf; import lucee.loader.engine.CFMLEngine; import lucee.runtime.config.ConfigImpl; import lucee.runtime.config.ConfigWeb; import lucee.runtime.config.ConfigWebImpl; import lucee.runtime.config.Constants; import lucee.runtime.engine.CFMLEngineImpl; import lucee.runtime.engine.JspEngineInfoImpl; import lucee.runtime.engine.MonitorState; import lucee.runtime.engine.ThreadLocalPageContext; import lucee.runtime.exp.PageException; import lucee.runtime.exp.PageExceptionImpl; import lucee.runtime.exp.RequestTimeoutException; import lucee.runtime.functions.string.Hash; import lucee.runtime.op.Caster; import lucee.runtime.type.Array; import lucee.runtime.type.ArrayImpl; import lucee.runtime.type.Struct; import lucee.runtime.type.StructImpl; import lucee.runtime.type.dt.DateTimeImpl; import lucee.runtime.type.scope.LocalNotSupportedScope; import lucee.runtime.type.scope.ScopeContext; import lucee.runtime.type.util.ArrayUtil; import lucee.runtime.type.util.KeyConstants; import lucee.runtime.type.util.ListUtil; /** * implements a JSP Factory, this class produces JSP compatible PageContext objects, as well as the * required ColdFusion specified interfaces */ public final class CFMLFactoryImpl extends CFMLFactory { private static final long MAX_AGE = 5 * 60000; // 5 minutes private static final int MAX_SIZE = 10000; private static JspEngineInfo info = new JspEngineInfoImpl("1.0"); private ConfigWebImpl config; ConcurrentLinkedDeque<PageContextImpl> pcs = new ConcurrentLinkedDeque<PageContextImpl>(); private final Map<Integer, PageContextImpl> runningPcs = new ConcurrentHashMap<Integer, PageContextImpl>(); private final Map<Integer, PageContextImpl> runningChildPcs = new ConcurrentHashMap<Integer, PageContextImpl>(); int idCounter = 1; private ScopeContext scopeContext = new ScopeContext(this); private HttpServlet _servlet; private URL url = null; private CFMLEngineImpl engine; private ArrayList<String> cfmlExtensions; private ArrayList<String> luceeExtensions; private ServletConfig servletConfig; public CFMLFactoryImpl(CFMLEngineImpl engine, ServletConfig sg) { this.engine = engine; this.servletConfig = sg; } /** * reset the PageContexes */ @Override public void resetPageContext() { LogUtil.log(config, Log.LEVEL_INFO, CFMLFactoryImpl.class.getName(), "Reset " + pcs.size() + " Unused PageContexts"); pcs.clear(); Iterator<PageContextImpl> it = runningPcs.values().iterator(); while (it.hasNext()) { it.next().reset(); } } @Override public javax.servlet.jsp.PageContext getPageContext(Servlet servlet, ServletRequest req, ServletResponse rsp, String errorPageURL, boolean needsSession, int bufferSize, boolean autoflush) { return getPageContextImpl((HttpServlet) servlet, (HttpServletRequest) req, (HttpServletResponse) rsp, errorPageURL, needsSession, bufferSize, autoflush, true, false, -1, true, false, false); } @Override @Deprecated public PageContext getLuceePageContext(HttpServlet servlet, HttpServletRequest req, HttpServletResponse rsp, String errorPageURL, boolean needsSession, int bufferSize, boolean autoflush) { // runningCount++; return getPageContextImpl(servlet, req, rsp, errorPageURL, needsSession, bufferSize, autoflush, true, false, -1, true, false, false); } @Override public PageContext getLuceePageContext(HttpServlet servlet, HttpServletRequest req, HttpServletResponse rsp, String errorPageURL, boolean needsSession, int bufferSize, boolean autoflush, boolean register, long timeout, boolean register2RunningThreads, boolean ignoreScopes) { // runningCount++; return getPageContextImpl(servlet, req, rsp, errorPageURL, needsSession, bufferSize, autoflush, register, false, timeout, register2RunningThreads, ignoreScopes, false); } public PageContextImpl getPageContextImpl(HttpServlet servlet, HttpServletRequest req, HttpServletResponse rsp, String errorPageURL, boolean needsSession, int bufferSize, boolean autoflush, boolean register2Thread, boolean isChild, long timeout, boolean register2RunningThreads, boolean ignoreScopes, boolean createNew) { PageContextImpl pc; if (createNew || pcs.isEmpty()) { pc = null; } else { try { pc = pcs.pop(); } catch (NoSuchElementException nsee) { pc = null; } } if (pc == null) pc = new PageContextImpl(scopeContext, config, idCounter++, servlet, ignoreScopes); if (timeout > 0) pc.setRequestTimeout(timeout); if (register2RunningThreads) { runningPcs.put(Integer.valueOf(pc.getId()), pc); if (isChild) runningChildPcs.put(Integer.valueOf(pc.getId()), pc); } this._servlet = servlet; if (register2Thread) ThreadLocalPageContext.register(pc); pc.initialize(servlet, req, rsp, errorPageURL, needsSession, bufferSize, autoflush, isChild, ignoreScopes); return pc; } @Override public void releasePageContext(javax.servlet.jsp.PageContext pc) { releaseLuceePageContext((PageContext) pc, true); } @Override public CFMLEngine getEngine() { return engine; } @Override @Deprecated public void releaseLuceePageContext(PageContext pc) { releaseLuceePageContext(pc, true); } /** * Similar to the releasePageContext Method, but take lucee PageContext as entry * * @param pc */ @Override public void releaseLuceePageContext(PageContext pc, boolean unregisterFromThread) { if (pc.getId() < 0) return; boolean isChild = pc.getParentPageContext() != null; // we need to get this check before release is executed // when pc was registered with an other thread, we register with this thread when calling release PageContext beforePC = ThreadLocalPageContext.get(); boolean tmpRegister = false; if (beforePC != pc) { ThreadLocalPageContext.register(pc); tmpRegister = true; } boolean releaseFailed = false; try { pc.release(); } catch (Exception e) { releaseFailed = true; config.getLog("application").error("release page context", e); } if (tmpRegister) ThreadLocalPageContext.register(beforePC); if (unregisterFromThread) ThreadLocalPageContext.release(); runningPcs.remove(Integer.valueOf(pc.getId())); if (isChild) { runningChildPcs.remove(Integer.valueOf(pc.getId())); } if (pcs.size() < 100 && ((PageContextImpl) pc).getTimeoutStackTrace() == null && !releaseFailed)// not more than 100 PCs pcs.push((PageContextImpl) pc); if (runningPcs.size() > MAX_SIZE) clean(runningPcs); if (runningChildPcs.size() > MAX_SIZE) clean(runningChildPcs); } private void clean(Map<Integer, PageContextImpl> map) { Iterator<PageContextImpl> it = map.values().iterator(); PageContextImpl pci; long now = System.currentTimeMillis(); while (it.hasNext()) { pci = it.next(); if (pci.isGatewayContext() || pci.getStartTime() + MAX_AGE > now) continue; } } /** * check timeout of all running threads, downgrade also priority from all thread run longer than 10 * seconds */ @Override public void checkTimeout() { if (!engine.allowRequestTimeout()) return; // print.e(MonitorState.checkForBlockedThreads(runningPcs.values())); // print.e(MonitorState.checkForBlockedThreads(runningChildPcs.values())); // synchronized (runningPcs) { // int len=runningPcs.size(); // we only terminate child threads Map<Integer, PageContextImpl> map = engine.exeRequestAsync() ? runningChildPcs : runningPcs; { Iterator<Entry<Integer, PageContextImpl>> it = map.entrySet().iterator(); PageContextImpl pc; Entry<Integer, PageContextImpl> e; while (it.hasNext()) { e = it.next(); pc = e.getValue(); long timeout = pc.getRequestTimeout(); if (pc.getStartTime() + timeout < System.currentTimeMillis() && Long.MAX_VALUE != timeout) { Log log = ((ConfigImpl) pc.getConfig()).getLog("requesttimeout"); if (log != null) { PageContext root = pc.getRootPageContext(); log.log(Log.LEVEL_ERROR, "controller", "stop " + (root != null && root != pc ? "thread" : "request") + " (" + pc.getId() + ") because run into a timeout " + getPath(pc) + "." + MonitorState.getBlockedThreads(pc) + RequestTimeoutException.locks(pc), ExceptionUtil.toThrowable(pc.getThread().getStackTrace())); } terminate(pc, true); runningPcs.remove(Integer.valueOf(pc.getId())); it.remove(); } // after 10 seconds downgrade priority of the thread else if (pc.getStartTime() + 10000 < System.currentTimeMillis() && pc.getThread().getPriority() != Thread.MIN_PRIORITY) { Log log = ((ConfigImpl) pc.getConfig()).getLog("requesttimeout"); if (log != null) { PageContext root = pc.getRootPageContext(); log.log(Log.LEVEL_WARN, "controller", "downgrade priority of the a " + (root != null && root != pc ? "thread" : "request") + " at " + getPath(pc) + ". " + MonitorState.getBlockedThreads(pc) + RequestTimeoutException.locks(pc), ExceptionUtil.toThrowable(pc.getThread().getStackTrace())); } try { pc.getThread().setPriority(Thread.MIN_PRIORITY); } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); } } } } } public static void terminate(PageContextImpl pc, boolean async) { pc.getConfig().getThreadQueue().exit(pc); SystemUtil.stop(pc, async); } private static String getPath(PageContext pc) { try { String base = ResourceUtil.getResource(pc, pc.getBasePageSource()).getAbsolutePath(); String current = ResourceUtil.getResource(pc, pc.getCurrentPageSource()).getAbsolutePath(); if (base.equals(current)) return "path: " + base; return "path: " + base + " (" + current + ")"; } catch (NullPointerException npe) { return "(no path available)"; } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); return "(fail to retrieve path:" + t.getClass().getName() + ":" + t.getMessage() + ")"; } } @Override public JspEngineInfo getEngineInfo() { return info; } /** * @return returns count of pagecontext in use */ @Override public int getUsedPageContextLength() { int length = 0; try { Iterator<PageContextImpl> it = runningPcs.values().iterator(); while (it.hasNext()) { PageContextImpl pc = it.next(); if (!pc.isGatewayContext()) length++; } } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); return length; } return length; } /** * @return Returns the config. */ @Override public ConfigWeb getConfig() { return config; } public ConfigWebImpl getConfigWebImpl() { return config; } /** * @return Returns the scopeContext. */ public ScopeContext getScopeContext() { return scopeContext; } /** * @return label of the factory */ @Override public Object getLabel() { return ((ConfigWebImpl) getConfig()).getLabel(); } /** * @param label */ @Override public void setLabel(String label) { // deprecated } @Override public URL getURL() { return url; } public void setURL(URL url) { this.url = url; } /** * @return the servlet */ @Override public HttpServlet getServlet() { if (_servlet == null) _servlet = new HTTPServletImpl(servletConfig, servletConfig.getServletContext(), servletConfig.getServletName()); return _servlet; } public void setConfig(ConfigWebImpl config) { this.config = config; } public Map<Integer, PageContextImpl> getActivePageContexts() { return runningPcs; } public long getPageContextsSize() { return SizeOf.size(pcs); } public long getActiveRequests() { return runningPcs.size(); } public long getActiveThreads() { return runningChildPcs.size(); } public Array getInfo() { Array info = new ArrayImpl(); // synchronized (runningPcs) { // int len=runningPcs.size(); Iterator<PageContextImpl> it = runningPcs.values().iterator(); PageContextImpl pc; Struct data, sctThread, scopes; Thread thread; Entry<Integer, PageContextImpl> e; ConfigWebImpl cw; while (it.hasNext()) { pc = it.next(); cw = (ConfigWebImpl) pc.getConfig(); data = new StructImpl(); sctThread = new StructImpl(); scopes = new StructImpl(); data.setEL("thread", sctThread); data.setEL("scopes", scopes); if (pc.isGatewayContext()) continue; thread = pc.getThread(); if (thread == Thread.currentThread()) continue; thread = pc.getThread(); if (thread == Thread.currentThread()) continue; data.setEL("startTime", new DateTimeImpl(pc.getStartTime(), false)); data.setEL("endTime", new DateTimeImpl(pc.getStartTime() + pc.getRequestTimeout(), false)); data.setEL(KeyConstants._timeout, new Double(pc.getRequestTimeout())); // thread sctThread.setEL(KeyConstants._name, thread.getName()); sctThread.setEL(KeyConstants._priority, Caster.toDouble(thread.getPriority())); sctThread.setEL(KeyConstants._state, thread.getState().name()); StackTraceElement[] stes = thread.getStackTrace(); data.setEL("TagContext", PageExceptionImpl.getTagContext(pc.getConfig(), stes)); // Java Stacktrace StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); Throwable t = new Throwable(); t.setStackTrace(stes); t.printStackTrace(pw); pw.close(); data.setEL("JavaStackTrace", sw.toString()); data.setEL(KeyConstants._urltoken, pc.getURLToken()); try { if (pc.getConfig().debug()) data.setEL("debugger", pc.getDebugger().getDebuggingData(pc)); } catch (PageException e2) {} try { data.setEL(KeyConstants._id, Hash.call(pc, pc.getId() + ":" + pc.getStartTime())); } catch (PageException e1) {} data.setEL(KeyConstants._hash, cw.getHash()); data.setEL("contextId", cw.getIdentification().getId()); data.setEL(KeyConstants._label, cw.getLabel()); data.setEL("requestId", pc.getId()); // Scopes scopes.setEL(KeyConstants._name, pc.getApplicationContext().getName()); try { scopes.setEL(KeyConstants._application, pc.applicationScope()); } catch (PageException pe) {} try { scopes.setEL(KeyConstants._session, pc.sessionScope()); } catch (PageException pe) {} try { scopes.setEL(KeyConstants._client, pc.clientScope()); } catch (PageException pe) {} scopes.setEL(KeyConstants._cookie, pc.cookieScope()); scopes.setEL(KeyConstants._variables, pc.variablesScope()); if (!(pc.localScope() instanceof LocalNotSupportedScope)) { scopes.setEL(KeyConstants._local, pc.localScope()); scopes.setEL(KeyConstants._arguments, pc.argumentsScope()); } scopes.setEL(KeyConstants._cgi, pc.cgiScope()); scopes.setEL(KeyConstants._form, pc.formScope()); scopes.setEL(KeyConstants._url, pc.urlScope()); scopes.setEL(KeyConstants._request, pc.requestScope()); info.appendEL(data); } return info; // } } public void stopThread(String threadId, String stopType) { // synchronized (runningPcs) { Iterator<PageContextImpl> it = runningPcs.values().iterator(); PageContext pc; while (it.hasNext()) { pc = it.next(); // Log log = ((ConfigImpl)pc.getConfig()).getLog("application"); try { String id = Hash.call(pc, pc.getId() + ":" + pc.getStartTime()); if (id.equals(threadId)) { stopType = stopType.trim(); // Throwable t; if ("abort".equalsIgnoreCase(stopType) || "cfabort".equalsIgnoreCase(stopType)) throw new RuntimeException("type [" + stopType + "] is no longer supported"); // t=new Abort(Abort.SCOPE_REQUEST); // else t=new RequestTimeoutException(pc.getThread(),"request has been forced to stop."); SystemUtil.stop(pc, true); SystemUtil.sleep(10); break; } } catch (PageException e1) {} } // } } @Override public JspApplicationContext getJspApplicationContext(ServletContext arg0) { throw new RuntimeException("not supported!"); } @Override public int toDialect(String ext) { // MUST improve perfomance if (cfmlExtensions == null) _initExtensions(); if (cfmlExtensions.contains(ext.toLowerCase())) return CFMLEngine.DIALECT_CFML; return CFMLEngine.DIALECT_CFML; } // FUTURE add to loader public int toDialect(String ext, int defaultValue) { if (ext == null) return defaultValue; if (cfmlExtensions == null) _initExtensions(); if (cfmlExtensions.contains(ext = ext.toLowerCase())) return CFMLEngine.DIALECT_CFML; if (luceeExtensions.contains(ext)) return CFMLEngine.DIALECT_LUCEE; return defaultValue; } private void _initExtensions() { cfmlExtensions = new ArrayList<String>(); luceeExtensions = new ArrayList<String>(); try { Iterator<?> it = getServlet().getServletContext().getServletRegistrations().entrySet().iterator(); Entry<String, ? extends ServletRegistration> e; String cn; while (it.hasNext()) { e = (Entry<String, ? extends ServletRegistration>) it.next(); cn = e.getValue().getClassName(); if (cn != null && cn.indexOf("LuceeServlet") != -1) { setExtensions(luceeExtensions, e.getValue().getMappings().iterator()); } else if (cn != null && cn.indexOf("CFMLServlet") != -1) { setExtensions(cfmlExtensions, e.getValue().getMappings().iterator()); } } } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); ArrayUtil.addAll(cfmlExtensions, Constants.getCFMLExtensions()); ArrayUtil.addAll(luceeExtensions, Constants.getLuceeExtensions()); } } private void setExtensions(ArrayList<String> extensions, Iterator<String> it) { String str, str2; Iterator<String> it2; while (it.hasNext()) { str = it.next(); it2 = ListUtil.listToSet(str, ',', true).iterator(); while (it2.hasNext()) { str2 = it2.next(); extensions.add(str2.substring(2));// MUSTMUST better impl } } } @Override public Iterator<String> getCFMLExtensions() { if (cfmlExtensions == null) _initExtensions(); return cfmlExtensions.iterator(); } @Override public Iterator<String> getLuceeExtensions() { if (luceeExtensions == null) _initExtensions(); return luceeExtensions.iterator(); } public static RequestTimeoutException createRequestTimeoutException(PageContext pc) { return new RequestTimeoutException(pc, pc.getThread().getStackTrace()); } }
add active request amount info to the request timeout log
core/src/main/java/lucee/runtime/CFMLFactoryImpl.java
add active request amount info to the request timeout log
<ide><path>ore/src/main/java/lucee/runtime/CFMLFactoryImpl.java <ide> Log log = ((ConfigImpl) pc.getConfig()).getLog("requesttimeout"); <ide> if (log != null) { <ide> PageContext root = pc.getRootPageContext(); <del> log.log(Log.LEVEL_ERROR, "controller", "stop " + (root != null && root != pc ? "thread" : "request") + " (" + pc.getId() + ") because run into a timeout " <del> + getPath(pc) + "." + MonitorState.getBlockedThreads(pc) + RequestTimeoutException.locks(pc), <add> log.log(Log.LEVEL_ERROR, "controller", <add> "stop " + (root != null && root != pc ? "thread" : "request") + " (" + pc.getId() + ") because run into a timeout. ATM we have " <add> + getActiveRequests() + " active request(s) and " + getActiveThreads() + " active cfthreads " + getPath(pc) + "." <add> + MonitorState.getBlockedThreads(pc) + RequestTimeoutException.locks(pc), <ide> ExceptionUtil.toThrowable(pc.getThread().getStackTrace())); <ide> } <ide> terminate(pc, true);
Java
unlicense
518759c7fcf8107e15918ffc511d2726fe6aecae
0
charlesmadere/smash-ranks-android
package com.garpr.android.data2; import android.database.sqlite.SQLiteDatabase; import com.android.volley.toolbox.JsonObjectRequest; import com.garpr.android.misc.Constants; import com.garpr.android.models.Player; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public final class Players { static final String TAG = "Players"; static void createTable(final SQLiteDatabase db) { final String sql = "CREATE TABLE IF NOT EXISTS " + TAG + " (" + Constants.ID + " TEXT NOT NULL, " + Constants.NAME + " TEXT NOT NULL, " + Constants.REGION + " TEXT NOT NULL, " + "PRIMARY KEY (" + Constants.ID + "));"; db.execSQL(sql); } public static void get(final Response<ArrayList<Player>> response) { new PlayersCall(response).start(); } private final static class PlayersCall extends Call<ArrayList<Player>> { private PlayersCall(final Response<ArrayList<Player>> response) throws IllegalArgumentException { super(response); } @Override String getCallName() { return PlayersCall.class.getSimpleName(); } @Override JsonObjectRequest makeRequest() { final String url = Constants.API_URL + '/' + Constants.PLAYERS; return new JsonObjectRequest(url, null, this, this); } @Override public void onJSONResponse(final JSONObject json) throws JSONException { final JSONArray playersJSON = json.getJSONArray(Constants.PLAYERS); final int playersLength = playersJSON.length(); final ArrayList<Player> players = new ArrayList<>(playersLength); for (int i = 0; i < playersLength; ++i) { final JSONObject playerJSON = playersJSON.getJSONObject(i); final Player player = new Player(playerJSON); players.add(player); } // TODO // save the players to the database mResponse.success(players); } } }
smash-ranks-android/app/src/main/java/com/garpr/android/data2/Players.java
package com.garpr.android.data2; import android.database.sqlite.SQLiteDatabase; import com.android.volley.toolbox.JsonObjectRequest; import com.garpr.android.misc.Constants; import com.garpr.android.models.Player; import org.json.JSONObject; import java.util.ArrayList; public final class Players { static final String TAG = "Players"; static void createTable(final SQLiteDatabase db) { final String sql = "CREATE TABLE IF NOT EXISTS " + TAG + " (" + Constants.ID + " TEXT NOT NULL, " + Constants.NAME + " TEXT NOT NULL, " + Constants.REGION + " TEXT NOT NULL, " + "PRIMARY KEY (" + Constants.ID + "));"; db.execSQL(sql); } public static void get(final Response<ArrayList<Player>> response) { new PlayersCall(response).start(); } private final static class PlayersCall extends Call<ArrayList<Player>> { private PlayersCall(final Response<ArrayList<Player>> response) throws IllegalArgumentException { super(response); } @Override String getCallName() { return PlayersCall.class.getSimpleName(); } @Override JsonObjectRequest makeRequest() { final String url = Constants.API_URL + '/' + Constants.PLAYERS; return new JsonObjectRequest(url, null, this, this); } @Override public void onJSONResponse(final JSONObject json) { // TODO } } }
players are now parsed from PlayersCall
smash-ranks-android/app/src/main/java/com/garpr/android/data2/Players.java
players are now parsed from PlayersCall
<ide><path>mash-ranks-android/app/src/main/java/com/garpr/android/data2/Players.java <ide> import com.garpr.android.misc.Constants; <ide> import com.garpr.android.models.Player; <ide> <add>import org.json.JSONArray; <add>import org.json.JSONException; <ide> import org.json.JSONObject; <ide> <ide> import java.util.ArrayList; <ide> <ide> <ide> @Override <del> public void onJSONResponse(final JSONObject json) { <add> public void onJSONResponse(final JSONObject json) throws JSONException { <add> final JSONArray playersJSON = json.getJSONArray(Constants.PLAYERS); <add> final int playersLength = playersJSON.length(); <add> final ArrayList<Player> players = new ArrayList<>(playersLength); <add> <add> for (int i = 0; i < playersLength; ++i) { <add> final JSONObject playerJSON = playersJSON.getJSONObject(i); <add> final Player player = new Player(playerJSON); <add> players.add(player); <add> } <add> <ide> // TODO <add> // save the players to the database <add> <add> mResponse.success(players); <ide> } <ide> <ide>
JavaScript
mit
9bfb9a15b5c6e37fbe59a856b68cc2f748f04f06
0
jpero09/checkout-demo,jpero09/checkout-demo
var express = require('express'); var http = require('http'); var morgan = require('morgan'); var path = require('path'); var app = express(); var port = process.env.PORT || 3000; var host = process.env.HOST || 'localhost'; // app.set('name', ''); app.set('port', port); app.set('host', host); app.use(express.static(__dirname)); // TODO: Move these to a dist folder app.set('view engine', 'pug'); app.set('views', __dirname + '/views'); app.use(morgan('tiny')); // Morgan Formats: combined, common, dev, short, tiny // Routes var router = express.Router(); router.get('/', function(req, res) { return res.render('index'); }); app.use('/', router); http.createServer(app).listen(port, host, function() { // TODO: Replace with proper logger console.log('Starting: %s v%s', app.get('name'), app.get('version')); console.log('Running @ //%s:%s', app.get('host'), app.get('port')); console.log('Environment:', process.env.NODE_ENV); console.log('Software:', process.versions); });
app/server.js
var express = require('express'); var http = require('http'); var morgan = require('morgan'); var path = require('path'); var app = express(); var port = process.env.PORT || 3000; var host = process.env.HOST || 'localhost'; // app.set('name', ''); app.set('port', port); app.set('host', host); app.use(express.static(__dirname)); // TODO: Move these to a dist folder app.set('view engine', 'pug'); app.set('views', __dirname + '/views'); app.use(morgan('tiny')); // Morgan Formats: combined, common, dev, short, tiny // Routes var router = express.Router(); router.get('/', function(req, res) { return res.render('index'); }); app.use('/', router); http.createServer(app).listen(app.get('port'), app.get('host'), function() { // TODO: Replace with proper logger console.log('Starting: %s v%s', app.get('name'), app.get('version')); console.log('Running @ //%s:%s', app.get('host'), app.get('port')); console.log('Environment:', process.env.NODE_ENV); console.log('Software:', process.versions); });
Heroku Port fix
app/server.js
Heroku Port fix
<ide><path>pp/server.js <ide> app.use('/', router); <ide> <ide> <del>http.createServer(app).listen(app.get('port'), app.get('host'), function() { <add>http.createServer(app).listen(port, host, function() { <ide> // TODO: Replace with proper logger <ide> console.log('Starting: %s v%s', app.get('name'), app.get('version')); <ide> console.log('Running @ //%s:%s', app.get('host'), app.get('port'));
JavaScript
mit
d5c63029ba88b0adc697e06b59b930c654adeb26
0
Data4Cure/sigma.js,hannesrauhe/sigma.js,jay754/sigma.js,jacomyal/sigma.js,vivek8943/sigma.js,9040044/sigma.js,hdh3000/sigma.js,mdamien/sigma.js,duncdrum/sigma.js,vivek8943/sigma.js,wesako/sigma.js,deenjohn/sigma.js,jacomyal/sigma.js,hannesrauhe/sigma.js,avisheksharma/sigma.js,avorio/sigma.js,PeterDaveHello/sigma.js,meduza/sigma.js,deenjohn/sigma.js,meduza/sigma.js,conker84/sigma.js,victor-homyakov/sigma.js,conker84/sigma.js,madwed/sigma.js,sim51/sigma.js,alihalabyah/sigma.js,waleedovase/waleedovase.github.io,FangMath/sigma.js,rlugojr/sigma.js,wesako/sigma.js,jbuscher/sigma.js,alihalabyah/sigma.js,duncdrum/sigma.js,ohyeslk/sigma.js,jbuscher/sigma.js,nmoraes/sigma.js,jacomyal/sigma.js,pinghe/sigma.js,queenBNE/sigma.js,PeterDaveHello/sigma.js,gruzilla/sigma.js,AbstractPete/sigma.js,sim51/sigma.js,jay754/sigma.js,helt/sigma.js,pingjiang/sigma.js,Ao21/sigmajs,queenBNE/sigma.js,NicholasAntonov/sigma.js,helt/sigma.js,FangMath/sigma.js,bradparks/sigma.js,Data4Cure/sigma.js,nmoraes/sigma.js,AbstractPete/sigma.js,avisheksharma/sigma.js,gruzilla/sigma.js,9040044/sigma.js,mdamien/sigma.js,pinghe/sigma.js,avorio/sigma.js,mcanthony/sigma.js,rlugojr/sigma.js,bradparks/sigma.js,pingjiang/sigma.js,hdh3000/sigma.js,victor-homyakov/sigma.js,waleedovase/waleedovase.github.io,ohyeslk/sigma.js,A----/sigma.js,mcanthony/sigma.js,madwed/sigma.js,NicholasAntonov/sigma.js
/** * Mathieu Jacomy @ Sciences Po Médialab & WebAtlas * (requires sigma.js to be loaded) */ ;(function(undefined) { 'use strict'; if (typeof sigma === 'undefined') throw 'sigma is not declared'; var forceatlas2 = sigma.utils.pkg('sigma.layout.forceatlas2'); forceatlas2.ForceAtlas2 = function(graph, options) { var self = this; this.graph = graph; this.p = sigma.utils.extend( options || {}, forceatlas2.defaultSettings ); // The state tracked from one atomic "go" to another this.state = {step: 0, index: 0}; // Runtime (the ForceAtlas2 itself) this.init = function() { self.state = { step: 0, index: 0 }; self.graph.nodes().forEach(function(n) { n.fa2 = { mass: 1 + self.graph.degree(n.id), old_dx: 0, old_dy: 0, dx: 0, dy: 0 }; }); return self; }; this.go = function() { while (self.atomicGo()) {} }; this.atomicGo = function() { var i, n, e, l, fixed, swinging, factor, graph = self.graph, nIndex = graph.nodes, eIndex = graph.edges, nodes = nIndex(), edges = eIndex(), cInt = self.p.complexIntervals, sInt = self.p.simpleIntervals; switch (self.state.step) { // Pass init case 0: // Initialise layout data for (i = 0, l = nodes.length; i < l; i++) { n = nodes[i]; if (n.fa2) n.fa2 = { mass: 1 + self.graph.degree(n.id), old_dx: n.fa2.dx || 0, old_dy: n.fa2.dy || 0, dx: 0, dy: 0 }; else n.fa2 = { mass: 1 + self.graph.degree(n.id), old_dx: 0, old_dy: 0, dx: 0, dy: 0 }; } // If Barnes Hut is active, initialize root region if (self.p.barnesHutOptimize) { self.rootRegion = new forceatlas2.Region(nodes, 0); self.rootRegion.buildSubRegions(); } // If outboundAttractionDistribution active, compensate. if (self.p.outboundAttractionDistribution) { self.p.outboundAttCompensation = 0; for (i = 0, l = nodes.length; i < l; i++) { n = nodes[i]; self.p.outboundAttCompensation += n.fa2.mass; } self.p.outboundAttCompensation /= nodes.length; } self.state.step = 1; self.state.index = 0; return true; // Repulsion case 1: var n1, n2, i1, i2, rootRegion, barnesHutTheta, Repulsion = self.ForceFactory.buildRepulsion( self.p.adjustSizes, self.p.scalingRatio ); if (self.p.barnesHutOptimize) { rootRegion = self.rootRegion; // Pass to the scope of forEach barnesHutTheta = self.p.barnesHutTheta; i = self.state.index; while (i < nodes.length && i < self.state.index + cInt) if ((n = nodes[i++]).fa2) rootRegion.applyForce(n, Repulsion, barnesHutTheta); if (i === nodes.length) self.state = { step: 2, index: 0 }; else self.state.index = i; } else { i1 = self.state.index; while (i1 < nodes.length && i1 < self.state.index + cInt) if ((n1 = nodes[i1++]).fa2) for (i2 = 0; i2 < i1; i2++) if ((n2 = nodes[i2]).fa2) Repulsion.apply_nn(n1, n2); if (i1 === nodes.length) self.state = { step: 2, index: 0 }; else self.state.index = i1; } return true; // Gravity case 2: var Gravity = self.p.strongGravityMode ? self.ForceFactory.getStrongGravity( self.p.scalingRatio ) : self.ForceFactory.buildRepulsion( self.p.adjustSizes, self.p.scalingRatio ), // Pass gravity and scalingRatio to the scope of the function gravity = self.p.gravity, scalingRatio = self.p.scalingRatio; i = self.state.index; while (i < nodes.length && i < self.state.index + sInt) { n = nodes[i++]; if (n.fa2) Gravity.apply_g(n, gravity / scalingRatio); } if (i === nodes.length) self.state = { step: 3, index: 0 }; else self.state.index = i; return true; // Attraction case 3: var Attraction = self.ForceFactory.buildAttraction( self.p.linLogMode, self.p.outboundAttractionDistribution, self.p.adjustSizes, self.p.outboundAttractionDistribution ? self.p.outboundAttCompensation : 1 ); i = self.state.index; if (self.p.edgeWeightInfluence === 0) while (i < edges.length && i < self.state.index + cInt) { e = edges[i++]; Attraction.apply_nn(nIndex(e.source), nIndex(e.target), 1); } else if (self.p.edgeWeightInfluence === 1) while (i < edges.length && i < self.state.index + cInt) { e = edges[i++]; Attraction.apply_nn( nIndex(e.source), nIndex(e.target), e.weight || 1 ); } else while (i < edges.length && i < self.state.index + cInt) { e = edges[i++]; Attraction.apply_nn( nIndex(e.source), nIndex(e.target), Math.pow(e.weight || 1, self.p.edgeWeightInfluence) ); } if (i === edges.length) self.state = { step: 4, index: 0 }; else self.state.index = i; return true; // Auto adjust speed case 4: var maxRise, targetSpeed, totalSwinging = 0, // How much irregular movement totalEffectiveTraction = 0; // Hom much useful movement for (i = 0, l = nodes.length; i < l; i++) { n = nodes[i]; fixed = n.fixed || false; if (!fixed && n.fa2) { swinging = Math.sqrt(Math.pow(n.fa2.old_dx - n.fa2.dx, 2) + Math.pow(n.fa2.old_dy - n.fa2.dy, 2)); // If the node has a burst change of direction, // then it's not converging. totalSwinging += n.fa2.mass * swinging; totalEffectiveTraction += n.fa2.mass * 0.5 * Math.sqrt( Math.pow(n.fa2.old_dx + n.fa2.dx, 2) + Math.pow(n.fa2.old_dy + n.fa2.dy, 2) ); } } self.p.totalSwinging = totalSwinging; self.p.totalEffectiveTraction = totalEffectiveTraction; // We want that swingingMovement < tolerance * convergenceMovement targetSpeed = Math.pow(self.p.jitterTolerance, 2) * self.p.totalEffectiveTraction / self.p.totalSwinging; // But the speed shoudn't rise too much too quickly, // since it would make the convergence drop dramatically. // Max rise: 50% maxRise = 0.5; self.p.speed = self.p.speed + Math.min( targetSpeed - self.p.speed, maxRise * self.p.speed ); // Save old coordinates for (i = 0, l = nodes.length; i < l; i++) { n = nodes[i]; n.old_x = +n.x; n.old_y = +n.y; } self.state.step = 5; return true; // Apply forces case 5: var df, speed; i = self.state.index; if (self.p.adjustSizes) { speed = self.p.speed; // If nodes overlap prevention is active, // it's not possible to trust the swinging mesure. while (i < nodes.length && i < self.state.index + sInt) { n = nodes[i++]; fixed = n.fixed || false; if (!fixed && n.fa2) { // Adaptive auto-speed: the speed of each node is lowered // when the node swings. swinging = Math.sqrt( (n.fa2.old_dx - n.fa2.dx) * (n.fa2.old_dx - n.fa2.dx) + (n.fa2.old_dy - n.fa2.dy) * (n.fa2.old_dy - n.fa2.dy) ); factor = 0.1 * speed / (1 + speed * Math.sqrt(swinging)); df = Math.sqrt(Math.pow(n.fa2.dx, 2) + Math.pow(n.fa2.dy, 2)); factor = Math.min(factor * df, 10) / df; n.x += n.fa2.dx * factor; n.y += n.fa2.dy * factor; } } } else { speed = self.p.speed; while (i < nodes.length && i < self.state.index + sInt) { n = nodes[i++]; fixed = n.fixed || false; if (!fixed && n.fa2) { // Adaptive auto-speed: the speed of each node is lowered // when the node swings. swinging = Math.sqrt( (n.fa2.old_dx - n.fa2.dx) * (n.fa2.old_dx - n.fa2.dx) + (n.fa2.old_dy - n.fa2.dy) * (n.fa2.old_dy - n.fa2.dy) ); factor = speed / (1 + speed * Math.sqrt(swinging)); n.x += n.fa2.dx * factor; n.y += n.fa2.dy * factor; } } } if (i === nodes.length) { self.state = { step: 0, index: 0 }; return false; } else { self.state.index = i; return true; } break; default: throw new Error('ForceAtlas2 - atomic state error'); } }; this.clean = function() { var a = this.graph.nodes(), l = a.length, i; for (i = 0; i < l; i++) delete a[i].fa2; }; // Auto Settings this.setAutoSettings = function() { var graph = this.graph; // Tuning if (graph.nodes().length >= 100) this.p.scalingRatio = 2.0; else this.p.scalingRatio = 10.0; this.p.strongGravityMode = false; this.p.gravity = 1; // Behavior this.p.outboundAttractionDistribution = false; this.p.linLogMode = false; this.p.adjustSizes = false; this.p.edgeWeightInfluence = 1; // Performance if (graph.nodes().length >= 50000) this.p.jitterTolerance = 10; else if (graph.nodes().length >= 5000) this.p.jitterTolerance = 1; else this.p.jitterTolerance = 0.1; if (graph.nodes().length >= 1000) this.p.barnesHutOptimize = true; else this.p.barnesHutOptimize = false; this.p.barnesHutTheta = 1.2; return this; }; this.kill = function() { // TODO }; // All the different forces this.ForceFactory = { buildRepulsion: function(adjustBySize, coefficient) { if (adjustBySize) { return new this.linRepulsion_antiCollision(coefficient); } else { return new this.linRepulsion(coefficient); } }, getStrongGravity: function(coefficient) { return new this.strongGravity(coefficient); }, buildAttraction: function(logAttr, distributedAttr, adjustBySize, c) { if (adjustBySize) { if (logAttr) { if (distributedAttr) { return new this.logAttraction_degreeDistributed_antiCollision(c); } else { return new this.logAttraction_antiCollision(c); } } else { if (distributedAttr) { return new this.linAttraction_degreeDistributed_antiCollision(c); } else { return new this.linAttraction_antiCollision(c); } } } else { if (logAttr) { if (distributedAttr) { return new this.logAttraction_degreeDistributed(c); } else { return new this.logAttraction(c); } } else { if (distributedAttr) { return new this.linAttraction_massDistributed(c); } else { return new this.linAttraction(c); } } } }, // Repulsion force: Linear linRepulsion: function(c) { this.coefficient = c; this.apply_nn = function(n1, n2) { if (n1.fa2 && n2.fa2) { // Get the distance var xDist = n1.x - n2.x; var yDist = n1.y - n2.y; var distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { // NB: factor = force / distance var factor = this.coefficient * n1.fa2.mass * n2.fa2.mass / Math.pow(distance, 2); n1.fa2.dx += xDist * factor; n1.fa2.dy += yDist * factor; n2.fa2.dx -= xDist * factor; n2.fa2.dy -= yDist * factor; } } }; this.apply_nr = function(n, r) { // Get the distance var xDist = n.x - r.p.massCenterX; var yDist = n.y - r.p.massCenterY; var distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { // NB: factor = force / distance var factor = this.coefficient * n.fa2.mass * r.p.mass / Math.pow(distance, 2); n.fa2.dx += xDist * factor; n.fa2.dy += yDist * factor; } }; this.apply_g = function(n, g) { // Get the distance var xDist = n.x; var yDist = n.y; var distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { // NB: factor = force / distance var factor = this.coefficient * n.fa2.mass * g / distance; n.fa2.dx -= xDist * factor; n.fa2.dy -= yDist * factor; } }; }, linRepulsion_antiCollision: function(c) { this.coefficient = c; this.apply_nn = function(n1, n2) { var factor; if (n1.fa2 && n2.fa2) { // Get the distance var xDist = n1.x - n2.x; var yDist = n1.y - n2.y; var distance = Math.sqrt(xDist * xDist + yDist * yDist) - n1.size - n2.size; if (distance > 0) { // NB: factor = force / distance factor = this.coefficient * n1.fa2.mass * n2.fa2.mass / Math.pow(distance, 2); n1.fa2.dx += xDist * factor; n1.fa2.dy += yDist * factor; n2.fa2.dx -= xDist * factor; n2.fa2.dy -= yDist * factor; } else if (distance < 0) { factor = 100 * this.coefficient * n1.fa2.mass * n2.fa2.mass; n1.fa2.dx += xDist * factor; n1.fa2.dy += yDist * factor; n2.fa2.dx -= xDist * factor; n2.fa2.dy -= yDist * factor; } } }; this.apply_nr = function(n, r) { // Get the distance var factor, xDist = n.fa2.x() - r.getMassCenterX(), yDist = n.fa2.y() - r.getMassCenterY(), distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { // NB: factor = force / distance factor = this.coefficient * n.fa2.mass * r.getMass() / Math.pow(distance, 2); n.fa2.dx += xDist * factor; n.fa2.dy += yDist * factor; } else if (distance < 0) { factor = -this.coefficient * n.fa2.mass * r.getMass() / distance; n.fa2.dx += xDist * factor; n.fa2.dy += yDist * factor; } }; this.apply_g = function(n, g) { // Get the distance var xDist = n.x; var yDist = n.y; var distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { // NB: factor = force / distance var factor = this.coefficient * n.fa2.mass * g / distance; n.fa2.dx -= xDist * factor; n.fa2.dy -= yDist * factor; } }; }, // Repulsion force: Strong Gravity // (as a Repulsion Force because it is easier) strongGravity: function(c) { this.coefficient = c; this.apply_nn = function(n1, n2) { // Not Relevant }; this.apply_nr = function(n, r) { // Not Relevant }; this.apply_g = function(n, g) { // Get the distance var xDist = n.x; var yDist = n.y; var distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { // NB: factor = force / distance var factor = this.coefficient * n.fa2.mass * g; n.fa2.dx -= xDist * factor; n.fa2.dy -= yDist * factor; } }; }, // Attraction force: Linear linAttraction: function(c) { this.coefficient = c; this.apply_nn = function(n1, n2, e) { if (n1.fa2 && n2.fa2) { // Get the distance var xDist = n1.x - n2.x; var yDist = n1.y - n2.y; // NB: factor = force / distance var factor = -this.coefficient * e; n1.fa2.dx += xDist * factor; n1.fa2.dy += yDist * factor; n2.fa2.dx -= xDist * factor; n2.fa2.dy -= yDist * factor; } }; }, // Attraction force: Linear, distributed by mass (typically, degree) linAttraction_massDistributed: function(c) { this.coefficient = c; this.apply_nn = function(n1, n2, e) { if (n1.fa2 && n2.fa2) { // Get the distance var xDist = n1.x - n2.x; var yDist = n1.y - n2.y; // NB: factor = force / distance var factor = -this.coefficient * e / n1.fa2.mass; n1.fa2.dx += xDist * factor; n1.fa2.dy += yDist * factor; n2.fa2.dx -= xDist * factor; n2.fa2.dy -= yDist * factor; } }; }, // Attraction force: Logarithmic logAttraction: function(c) { this.coefficient = c; this.apply_nn = function(n1, n2, e) { if (n1.fa2 && n2.fa2) { // Get the distance var xDist = n1.x - n2.x; var yDist = n1.y - n2.y; var distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { // NB: factor = force / distance var factor = -this.coefficient * e * Math.log(1 + distance) / distance; n1.fa2.dx += xDist * factor; n1.fa2.dy += yDist * factor; n2.fa2.dx -= xDist * factor; n2.fa2.dy -= yDist * factor; } } }; }, // Attraction force: Linear, distributed by Degree logAttraction_degreeDistributed: function(c) { this.coefficient = c; this.apply_nn = function(n1, n2, e) { if (n1.fa2 && n2.fa2) { // Get the distance var xDist = n1.x - n2.x; var yDist = n1.y - n2.y; var distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { // NB: factor = force / distance var factor = -this.coefficient * e * Math.log(1 + distance) / distance / n1.fa2.mass; n1.fa2.dx += xDist * factor; n1.fa2.dy += yDist * factor; n2.fa2.dx -= xDist * factor; n2.fa2.dy -= yDist * factor; } } }; }, // Attraction force: Linear, with Anti-Collision linAttraction_antiCollision: function(c) { this.coefficient = c; this.apply_nn = function(n1, n2, e) { if (n1.fa2 && n2.fa2) { // Get the distance var xDist = n1.x - n2.x; var yDist = n1.y - n2.y; var distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { // NB: factor = force / distance var factor = -this.coefficient * e; n1.fa2.dx += xDist * factor; n1.fa2.dy += yDist * factor; n2.fa2.dx -= xDist * factor; n2.fa2.dy -= yDist * factor; } } }; }, // Attraction force: Linear, distributed by Degree, with Anti-Collision linAttraction_degreeDistributed_antiCollision: function(c) { this.coefficient = c; this.apply_nn = function(n1, n2, e) { if (n1.fa2 && n2.fa2) { // Get the distance var xDist = n1.x - n2.x; var yDist = n1.y - n2.y; var distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { // NB: factor = force / distance var factor = -this.coefficient * e / n1.fa2.mass; n1.fa2.dx += xDist * factor; n1.fa2.dy += yDist * factor; n2.fa2.dx -= xDist * factor; n2.fa2.dy -= yDist * factor; } } }; }, // Attraction force: Logarithmic, with Anti-Collision logAttraction_antiCollision: function(c) { this.coefficient = c; this.apply_nn = function(n1, n2, e) { if (n1.fa2 && n2.fa2) { // Get the distance var xDist = n1.x - n2.x; var yDist = n1.y - n2.y; var distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { // NB: factor = force / distance var factor = -this.coefficient * e * Math.log(1 + distance) / distance; n1.fa2.dx += xDist * factor; n1.fa2.dy += yDist * factor; n2.fa2.dx -= xDist * factor; n2.fa2.dy -= yDist * factor; } } }; }, // Attraction force: Linear, distributed by Degree, with Anti-Collision logAttraction_degreeDistributed_antiCollision: function(c) { this.coefficient = c; this.apply_nn = function(n1, n2, e) { if (n1.fa2 && n2.fa2) { // Get the distance var xDist = n1.x - n2.x; var yDist = n1.y - n2.y; var distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { // NB: factor = force / distance var factor = -this.coefficient * e * Math.log(1 + distance) / distance / n1.fa2.mass; n1.fa2.dx += xDist * factor; n1.fa2.dy += yDist * factor; n2.fa2.dx -= xDist * factor; n2.fa2.dy -= yDist * factor; } } }; } }; }; // The Region class, as used by the Barnes Hut optimization forceatlas2.Region = function(nodes, depth) { this.depthLimit = 20; this.size = 0; this.nodes = nodes; this.subregions = []; this.depth = depth; this.p = { mass: 0, massCenterX: 0, massCenterY: 0 }; this.updateMassAndGeometry(); }; forceatlas2.Region.prototype.updateMassAndGeometry = function() { if (this.nodes.length > 1) { // Compute Mass var mass = 0; var massSumX = 0; var massSumY = 0; this.nodes.forEach(function(n) { mass += n.fa2.mass; massSumX += n.x * n.fa2.mass; massSumY += n.y * n.fa2.mass; }); var massCenterX = massSumX / mass, massCenterY = massSumY / mass; // Compute size var size; this.nodes.forEach(function(n) { var distance = Math.sqrt( (n.x - massCenterX) * (n.x - massCenterX) + (n.y - massCenterY) * (n.y - massCenterY) ); size = Math.max(size || (2 * distance), 2 * distance); }); this.p.mass = mass; this.p.massCenterX = massCenterX; this.p.massCenterY = massCenterY; this.size = size; } }; forceatlas2.Region.prototype.buildSubRegions = function() { if (this.nodes.length > 1) { var leftNodes = [], rightNodes = [], subregions = [], massCenterX = this.p.massCenterX, massCenterY = this.p.massCenterY, nextDepth = this.depth + 1, self = this, tl = [], bl = [], br = [], tr = [], nodesColumn, nodesLine, oneNodeList, subregion; this.nodes.forEach(function(n) { nodesColumn = (n.x < massCenterX) ? (leftNodes) : (rightNodes); nodesColumn.push(n); }); leftNodes.forEach(function(n) { nodesLine = (n.y < massCenterY) ? (tl) : (bl); nodesLine.push(n); }); rightNodes.forEach(function(n) { nodesLine = (n.y < massCenterY) ? (tr) : (br); nodesLine.push(n); }); [tl, bl, br, tr].filter(function(a) { return a.length; }).forEach(function(a) { if (nextDepth <= self.depthLimit && a.length < self.nodes.length) { subregion = new forceatlas2.Region(a, nextDepth); subregions.push(subregion); } else { a.forEach(function(n) { oneNodeList = [n]; subregion = new forceatlas2.Region(oneNodeList, nextDepth); subregions.push(subregion); }); } }); this.subregions = subregions; subregions.forEach(function(subregion) { subregion.buildSubRegions(); }); } }; forceatlas2.Region.prototype.applyForce = function(n, Force, theta) { if (this.nodes.length < 2) { var regionNode = this.nodes[0]; Force.apply_nn(n, regionNode); } else { var distance = Math.sqrt( (n.x - this.p.massCenterX) * (n.x - this.p.massCenterX) + (n.y - this.p.massCenterY) * (n.y - this.p.massCenterY) ); if (distance * theta > this.size) { Force.apply_nr(n, this); } else { this.subregions.forEach(function(subregion) { subregion.applyForce(n, Force, theta); }); } } }; sigma.prototype.startForceAtlas2 = function(options) { if ((this.forceatlas2 || {}).isRunning) return this; if (!this.forceatlas2) { this.forceatlas2 = new forceatlas2.ForceAtlas2(this.graph, options || {}); this.forceatlas2.setAutoSettings(); this.forceatlas2.init(); } this.forceatlas2.isRunning = true; var self = this; function addJob() { if (!conrad.hasJob('forceatlas2_' + self.id)) conrad.addJob({ id: 'forceatlas2_' + self.id, job: self.forceatlas2.atomicGo, end: function() { self.refresh(); if (self.forceatlas2.isRunning) addJob(); } }); } addJob(); return this; }; sigma.prototype.stopForceAtlas2 = function() { if ((this.forceatlas2 || {}).isRunning) { this.forceatlas2.state = { step: 0, index: 0 }; this.forceatlas2.isRunning = false; this.forceatlas2.clean(); } if (conrad.hasJob('forceatlas2_' + this.id)) conrad.killJob('forceatlas2_' + this.id); return this; }; forceatlas2.defaultSettings = { autoSettings: true, linLogMode: false, outboundAttractionDistribution: false, adjustSizes: false, edgeWeightInfluence: 0, scalingRatio: 1, strongGravityMode: false, gravity: 1, jitterTolerance: 1, barnesHutOptimize: false, barnesHutTheta: 1.2, speed: 1, outboundAttCompensation: 1, totalSwinging: 0, totalEffectiveTraction: 0, complexIntervals: 500, simpleIntervals: 1000 }; })();
plugins/sigma.layout.forceAtlas2/sigma.layout.forceAtlas2.js
/** * Mathieu Jacomy @ Sciences Po Médialab & WebAtlas * (requires sigma.js to be loaded) */ ;(function(undefined) { 'use strict'; if (typeof sigma === 'undefined') throw 'sigma is not declared'; var forceatlas2 = sigma.utils.pkg('sigma.layout.forceatlas2'); forceatlas2.ForceAtlas2 = function(graph, options) { var self = this; this.graph = graph; this.p = sigma.utils.extend( options || {}, forceatlas2.defaultSettings ); // The state tracked from one atomic "go" to another this.state = {step: 0, index: 0}; // Runtime (the ForceAtlas2 itself) this.init = function() { self.state = { step: 0, index: 0 }; self.graph.nodes().forEach(function(n) { n.fa2 = { mass: 1 + self.graph.degree(n.id), old_dx: 0, old_dy: 0, dx: 0, dy: 0 }; }); return self; }; this.go = function() { while (self.atomicGo()) {} }; this.atomicGo = function() { var i, n, e, l, fixed, swinging, factor, graph = self.graph, nIndex = graph.nodes, eIndex = graph.edges, nodes = nIndex(), edges = eIndex(), cInt = self.p.complexIntervals, sInt = self.p.simpleIntervals; switch (self.state.step) { // Pass init case 0: // Initialise layout data for (i = 0, l = nodes.length; i < l; i++) { n = nodes[i]; if (n.fa2) n.fa2 = { mass: 1 + self.graph.degree(n.id), old_dx: n.fa2.dx || 0, old_dy: n.fa2.dy || 0, dx: 0, dy: 0 }; else n.fa2 = { mass: 1 + self.graph.degree(n.id), old_dx: 0, old_dy: 0, dx: 0, dy: 0 }; } // If Barnes Hut is active, initialize root region if (self.p.barnesHutOptimize) { self.rootRegion = new forceatlas2.Region(nodes, 0); self.rootRegion.buildSubRegions(); } // If outboundAttractionDistribution active, compensate. if (self.p.outboundAttractionDistribution) { self.p.outboundAttCompensation = 0; for (i = 0, l = nodes.length; i < l; i++) { n = nodes[i]; self.p.outboundAttCompensation += n.fa2.mass; } self.p.outboundAttCompensation /= nodes.length; } self.state.step = 1; self.state.index = 0; return true; // Repulsion case 1: var n1, n2, i1, i2, rootRegion, barnesHutTheta, Repulsion = self.ForceFactory.buildRepulsion( self.p.adjustSizes, self.p.scalingRatio ); if (self.p.barnesHutOptimize) { rootRegion = self.rootRegion; // Pass to the scope of forEach barnesHutTheta = self.p.barnesHutTheta; i = self.state.index; while (i < nodes.length && i < self.state.index + cInt) if ((n = nodes[i++]).fa2) rootRegion.applyForce(n, Repulsion, barnesHutTheta); if (i === nodes.length) self.state = { step: 2, index: 0 }; else self.state.index = i; } else { i1 = self.state.index; while (i1 < nodes.length && i1 < self.state.index + cInt) if ((n1 = nodes[i1++]).fa2) for (i2 = 0; i2 < i1; i2++) if ((n2 = nodes[i2]).fa2) Repulsion.apply_nn(n1, n2); if (i1 === nodes.length) self.state = { step: 2, index: 0 }; else self.state.index = i1; } return true; // Gravity case 2: var Gravity = self.p.strongGravityMode ? self.ForceFactory.getStrongGravity( self.p.scalingRatio ) : self.ForceFactory.buildRepulsion( self.p.adjustSizes, self.p.scalingRatio ), // Pass gravity and scalingRatio to the scope of the function gravity = self.p.gravity, scalingRatio = self.p.scalingRatio; i = self.state.index; while (i < nodes.length && i < self.state.index + sInt) { n = nodes[i++]; if (n.fa2) Gravity.apply_g(n, gravity / scalingRatio); } if (i === nodes.length) self.state = { step: 3, index: 0 }; else self.state.index = i; return true; // Attraction case 3: var Attraction = self.ForceFactory.buildAttraction( self.p.linLogMode, self.p.outboundAttractionDistribution, self.p.adjustSizes, self.p.outboundAttractionDistribution ? self.p.outboundAttCompensation : 1 ); i = self.state.index; if (self.p.edgeWeightInfluence === 0) while (i < edges.length && i < self.state.index + cInt) { e = edges[i++]; Attraction.apply_nn(nIndex(e.source), nIndex(e.target), 1); } else if (self.p.edgeWeightInfluence === 1) while (i < edges.length && i < self.state.index + cInt) { e = edges[i++]; Attraction.apply_nn( nIndex(e.source), nIndex(e.target), e.weight || 1 ); } else while (i < edges.length && i < self.state.index + cInt) { e = edges[i++]; Attraction.apply_nn( nIndex(e.source), nIndex(e.target), Math.pow(e.weight || 1, self.p.edgeWeightInfluence) ); } if (i === edges.length) self.state = { step: 4, index: 0 }; else self.state.index = i; return true; // Auto adjust speed case 4: var maxRise, targetSpeed, totalSwinging = 0, // How much irregular movement totalEffectiveTraction = 0; // Hom much useful movement for (i = 0, l = nodes.length; i < l; i++) { n = nodes[i]; fixed = n.fixed || false; if (!fixed && n.fa2) { swinging = Math.sqrt(Math.pow(n.fa2.old_dx - n.fa2.dx, 2) + Math.pow(n.fa2.old_dy - n.fa2.dy, 2)); // If the node has a burst change of direction, // then it's not converging. totalSwinging += n.fa2.mass * swinging; totalEffectiveTraction += n.fa2.mass * 0.5 * Math.sqrt( Math.pow(n.fa2.old_dx + n.fa2.dx, 2) + Math.pow(n.fa2.old_dy + n.fa2.dy, 2) ); } } self.p.totalSwinging = totalSwinging; self.p.totalEffectiveTraction = totalEffectiveTraction; // We want that swingingMovement < tolerance * convergenceMovement targetSpeed = Math.pow(self.p.jitterTolerance, 2) * self.p.totalEffectiveTraction / self.p.totalSwinging; // But the speed shoudn't rise too much too quickly, // since it would make the convergence drop dramatically. // Max rise: 50% maxRise = 0.5; self.p.speed = self.p.speed + Math.min( targetSpeed - self.p.speed, maxRise * self.p.speed ); // Save old coordinates for (i = 0, l = nodes.length; i < l; i++) { n = nodes[i]; n.old_x = +n.x; n.old_y = +n.y; } self.state.step = 5; return true; // Apply forces case 5: var df, speed; i = self.state.index; if (self.p.adjustSizes) { speed = self.p.speed; // If nodes overlap prevention is active, // it's not possible to trust the swinging mesure. while (i < nodes.length && i < self.state.index + sInt) { n = nodes[i++]; fixed = n.fixed || false; if (!fixed && n.fa2) { // Adaptive auto-speed: the speed of each node is lowered // when the node swings. swinging = Math.sqrt( (n.fa2.old_dx - n.fa2.dx) * (n.fa2.old_dx - n.fa2.dx) + (n.fa2.old_dy - n.fa2.dy) * (n.fa2.old_dy - n.fa2.dy) ); factor = 0.1 * speed / (1 + speed * Math.sqrt(swinging)); df = Math.sqrt(Math.pow(n.fa2.dx, 2) + Math.pow(n.fa2.dy, 2)); factor = Math.min(factor * df, 10) / df; n.x += n.fa2.dx * factor; n.y += n.fa2.dy * factor; } } } else { speed = self.p.speed; while (i < nodes.length && i < self.state.index + sInt) { n = nodes[i++]; fixed = n.fixed || false; if (!fixed && n.fa2) { // Adaptive auto-speed: the speed of each node is lowered // when the node swings. swinging = Math.sqrt( (n.fa2.old_dx - n.fa2.dx) * (n.fa2.old_dx - n.fa2.dx) + (n.fa2.old_dy - n.fa2.dy) * (n.fa2.old_dy - n.fa2.dy) ); factor = speed / (1 + speed * Math.sqrt(swinging)); n.x += n.fa2.dx * factor; n.y += n.fa2.dy * factor; } } } if (i === nodes.length) { self.state = { step: 0, index: 0 }; return false; } else { self.state.index = i; return true; } break; default: throw new Error('ForceAtlas2 - atomic state error'); } }; this.clean = function() { var a = this.graph.nodes(), l = a.length, i; for (i = 0; i < l; i++) delete a[i].fa2; }; // Auto Settings this.setAutoSettings = function() { var graph = this.graph; // Tuning if (graph.nodes().length >= 100) this.p.scalingRatio = 2.0; else this.p.scalingRatio = 10.0; this.p.strongGravityMode = false; this.p.gravity = 1; // Behavior this.p.outboundAttractionDistribution = false; this.p.linLogMode = false; this.p.adjustSizes = false; this.p.edgeWeightInfluence = 1; // Performance if (graph.nodes().length >= 50000) this.p.jitterTolerance = 10; else if (graph.nodes().length >= 5000) this.p.jitterTolerance = 1; else this.p.jitterTolerance = 0.1; if (graph.nodes().length >= 1000) this.p.barnesHutOptimize = true; else this.p.barnesHutOptimize = false; this.p.barnesHutTheta = 1.2; return this; }; this.kill = function() { // TODO }; // All the different forces this.ForceFactory = { buildRepulsion: function(adjustBySize, coefficient) { if (adjustBySize) { return new this.linRepulsion_antiCollision(coefficient); } else { return new this.linRepulsion(coefficient); } }, getStrongGravity: function(coefficient) { return new this.strongGravity(coefficient); }, buildAttraction: function(logAttr, distributedAttr, adjustBySize, c) { if (adjustBySize) { if (logAttr) { if (distributedAttr) { return new this.logAttraction_degreeDistributed_antiCollision(c); } else { return new this.logAttraction_antiCollision(c); } } else { if (distributedAttr) { return new this.linAttraction_degreeDistributed_antiCollision(c); } else { return new this.linAttraction_antiCollision(c); } } } else { if (logAttr) { if (distributedAttr) { return new this.logAttraction_degreeDistributed(c); } else { return new this.logAttraction(c); } } else { if (distributedAttr) { return new this.linAttraction_massDistributed(c); } else { return new this.linAttraction(c); } } } }, // Repulsion force: Linear linRepulsion: function(c) { this.coefficient = c; this.apply_nn = function(n1, n2) { if (n1.fa2 && n2.fa2) { // Get the distance var xDist = n1.x - n2.x; var yDist = n1.y - n2.y; var distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { // NB: factor = force / distance var factor = this.coefficient * n1.fa2.mass * n2.fa2.mass / Math.pow(distance, 2); n1.fa2.dx += xDist * factor; n1.fa2.dy += yDist * factor; n2.fa2.dx -= xDist * factor; n2.fa2.dy -= yDist * factor; } } }; this.apply_nr = function(n, r) { // Get the distance var xDist = n.x - r.p.massCenterX; var yDist = n.y - r.p.massCenterY; var distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { // NB: factor = force / distance var factor = this.coefficient * n.fa2.mass * r.p.mass / Math.pow(distance, 2); n.fa2.dx += xDist * factor; n.fa2.dy += yDist * factor; } }; this.apply_g = function(n, g) { // Get the distance var xDist = n.x; var yDist = n.y; var distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { // NB: factor = force / distance var factor = this.coefficient * n.fa2.mass * g / distance; n.fa2.dx -= xDist * factor; n.fa2.dy -= yDist * factor; } }; }, linRepulsion_antiCollision: function(c) { this.coefficient = c; this.apply_nn = function(n1, n2) { var factor; if (n1.fa2 && n2.fa2) { // Get the distance var xDist = n1.x - n2.x; var yDist = n1.y - n2.y; var distance = Math.sqrt(xDist * xDist + yDist * yDist) - n1.size - n2.size; if (distance > 0) { // NB: factor = force / distance factor = this.coefficient * n1.fa2.mass * n2.fa2.mass / Math.pow(distance, 2); n1.fa2.dx += xDist * factor; n1.fa2.dy += yDist * factor; n2.fa2.dx -= xDist * factor; n2.fa2.dy -= yDist * factor; } else if (distance < 0) { factor = 100 * this.coefficient * n1.fa2.mass * n2.fa2.mass; n1.fa2.dx += xDist * factor; n1.fa2.dy += yDist * factor; n2.fa2.dx -= xDist * factor; n2.fa2.dy -= yDist * factor; } } }; this.apply_nr = function(n, r) { // Get the distance var factor, xDist = n.fa2.x() - r.getMassCenterX(), yDist = n.fa2.y() - r.getMassCenterY(), distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { // NB: factor = force / distance factor = this.coefficient * n.fa2.mass * r.getMass() / Math.pow(distance, 2); n.fa2.dx += xDist * factor; n.fa2.dy += yDist * factor; } else if (distance < 0) { factor = -this.coefficient * n.fa2.mass * r.getMass() / distance; n.fa2.dx += xDist * factor; n.fa2.dy += yDist * factor; } }; this.apply_g = function(n, g) { // Get the distance var xDist = n.x; var yDist = n.y; var distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { // NB: factor = force / distance var factor = this.coefficient * n.fa2.mass * g / distance; n.fa2.dx -= xDist * factor; n.fa2.dy -= yDist * factor; } }; }, // Repulsion force: Strong Gravity // (as a Repulsion Force because it is easier) strongGravity: function(c) { this.coefficient = c; this.apply_nn = function(n1, n2) { // Not Relevant }; this.apply_nr = function(n, r) { // Not Relevant }; this.apply_g = function(n, g) { // Get the distance var xDist = n.x; var yDist = n.y; var distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { // NB: factor = force / distance var factor = this.coefficient * n.fa2.mass * g; n.fa2.dx -= xDist * factor; n.fa2.dy -= yDist * factor; } }; }, // Attraction force: Linear linAttraction: function(c) { this.coefficient = c; this.apply_nn = function(n1, n2, e) { if (n1.fa2 && n2.fa2) { // Get the distance var xDist = n1.x - n2.x; var yDist = n1.y - n2.y; // NB: factor = force / distance var factor = -this.coefficient * e; n1.fa2.dx += xDist * factor; n1.fa2.dy += yDist * factor; n2.fa2.dx -= xDist * factor; n2.fa2.dy -= yDist * factor; } }; }, // Attraction force: Linear, distributed by mass (typically, degree) linAttraction_massDistributed: function(c) { this.coefficient = c; this.apply_nn = function(n1, n2, e) { if (n1.fa2 && n2.fa2) { // Get the distance var xDist = n1.x - n2.x; var yDist = n1.y - n2.y; // NB: factor = force / distance var factor = -this.coefficient * e / n1.fa2.mass; n1.fa2.dx += xDist * factor; n1.fa2.dy += yDist * factor; n2.fa2.dx -= xDist * factor; n2.fa2.dy -= yDist * factor; } }; }, // Attraction force: Logarithmic logAttraction: function(c) { this.coefficient = c; this.apply_nn = function(n1, n2, e) { if (n1.fa2 && n2.fa2) { // Get the distance var xDist = n1.x - n2.x; var yDist = n1.y - n2.y; var distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { // NB: factor = force / distance var factor = -this.coefficient * e * Math.log(1 + distance) / distance; n1.fa2.dx += xDist * factor; n1.fa2.dy += yDist * factor; n2.fa2.dx -= xDist * factor; n2.fa2.dy -= yDist * factor; } } }; }, // Attraction force: Linear, distributed by Degree logAttraction_degreeDistributed: function(c) { this.coefficient = c; this.apply_nn = function(n1, n2, e) { if (n1.fa2 && n2.fa2) { // Get the distance var xDist = n1.x - n2.x; var yDist = n1.y - n2.y; var distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { // NB: factor = force / distance var factor = -this.coefficient * e * Math.log(1 + distance) / distance / n1.fa2.mass; n1.fa2.dx += xDist * factor; n1.fa2.dy += yDist * factor; n2.fa2.dx -= xDist * factor; n2.fa2.dy -= yDist * factor; } } }; }, // Attraction force: Linear, with Anti-Collision linAttraction_antiCollision: function(c) { this.coefficient = c; this.apply_nn = function(n1, n2, e) { if (n1.fa2 && n2.fa2) { // Get the distance var xDist = n1.x - n2.x; var yDist = n1.y - n2.y; var distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { // NB: factor = force / distance var factor = -this.coefficient * e; n1.fa2.dx += xDist * factor; n1.fa2.dy += yDist * factor; n2.fa2.dx -= xDist * factor; n2.fa2.dy -= yDist * factor; } } }; }, // Attraction force: Linear, distributed by Degree, with Anti-Collision linAttraction_degreeDistributed_antiCollision: function(c) { this.coefficient = c; this.apply_nn = function(n1, n2, e) { if (n1.fa2 && n2.fa2) { // Get the distance var xDist = n1.x - n2.x; var yDist = n1.y - n2.y; var distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { // NB: factor = force / distance var factor = -this.coefficient * e / n1.fa2.mass; n1.fa2.dx += xDist * factor; n1.fa2.dy += yDist * factor; n2.fa2.dx -= xDist * factor; n2.fa2.dy -= yDist * factor; } } }; }, // Attraction force: Logarithmic, with Anti-Collision logAttraction_antiCollision: function(c) { this.coefficient = c; this.apply_nn = function(n1, n2, e) { if (n1.fa2 && n2.fa2) { // Get the distance var xDist = n1.x - n2.x; var yDist = n1.y - n2.y; var distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { // NB: factor = force / distance var factor = -this.coefficient * e * Math.log(1 + distance) / distance; n1.fa2.dx += xDist * factor; n1.fa2.dy += yDist * factor; n2.fa2.dx -= xDist * factor; n2.fa2.dy -= yDist * factor; } } }; }, // Attraction force: Linear, distributed by Degree, with Anti-Collision logAttraction_degreeDistributed_antiCollision: function(c) { this.coefficient = c; this.apply_nn = function(n1, n2, e) { if (n1.fa2 && n2.fa2) { // Get the distance var xDist = n1.x - n2.x; var yDist = n1.y - n2.y; var distance = Math.sqrt(xDist * xDist + yDist * yDist); if (distance > 0) { // NB: factor = force / distance var factor = -this.coefficient * e * Math.log(1 + distance) / distance / n1.fa2.mass; n1.fa2.dx += xDist * factor; n1.fa2.dy += yDist * factor; n2.fa2.dx -= xDist * factor; n2.fa2.dy -= yDist * factor; } } }; } }; }; // The Region class, as used by the Barnes Hut optimization forceatlas2.Region = function(nodes, depth) { this.depthLimit = 20; this.size = 0; this.nodes = nodes; this.subregions = []; this.depth = depth; this.p = { mass: 0, massCenterX: 0, massCenterY: 0 }; this.updateMassAndGeometry(); }; forceatlas2.Region.prototype.updateMassAndGeometry = function() { if (this.nodes.length > 1) { // Compute Mass var mass = 0; var massSumX = 0; var massSumY = 0; this.nodes.forEach(function(n) { mass += n.fa2.mass; massSumX += n.x * n.fa2.mass; massSumY += n.y * n.fa2.mass; }); var massCenterX = massSumX / mass, massCenterY = massSumY / mass; // Compute size var size; this.nodes.forEach(function(n) { var distance = Math.sqrt( (n.x - massCenterX) * (n.x - massCenterX) + (n.y - massCenterY) * (n.y - massCenterY) ); size = Math.max(size || (2 * distance), 2 * distance); }); this.p.mass = mass; this.p.massCenterX = massCenterX; this.p.massCenterY = massCenterY; this.size = size; } }; forceatlas2.Region.prototype.buildSubRegions = function() { if (this.nodes.length > 1) { var leftNodes = [], rightNodes = [], subregions = [], massCenterX = this.p.massCenterX, massCenterY = this.p.massCenterY, nextDepth = this.depth + 1, self = this, tl = [], bl = [], br = [], tr = [], nodesColumn, nodesLine, oneNodeList, subregion; this.nodes.forEach(function(n) { nodesColumn = (n.x < massCenterX) ? (leftNodes) : (rightNodes); nodesColumn.push(n); }); leftNodes.forEach(function(n) { nodesLine = (n.y < massCenterY) ? (tl) : (bl); nodesLine.push(n); }); rightNodes.forEach(function(n) { nodesLine = (n.y < massCenterY) ? (tr) : (br); nodesLine.push(n); }); [tl, bl, br, tr].filter(function(a) { return a.length; }).forEach(function(a) { if (nextDepth <= self.depthLimit && a.length < self.nodes.length) { subregion = new forceatlas2.Region(a, nextDepth); subregions.push(subregion); } else { a.forEach(function(n) { oneNodeList = [n]; subregion = new forceatlas2.Region(oneNodeList, nextDepth); subregions.push(subregion); }); } }); this.subregions = subregions; subregions.forEach(function(subregion) { subregion.buildSubRegions(); }); } }; forceatlas2.Region.prototype.applyForce = function(n, Force, theta) { if (this.nodes.length < 2) { var regionNode = this.nodes[0]; Force.apply_nn(n, regionNode); } else { var distance = Math.sqrt( (n.x - this.p.massCenterX) * (n.x - this.p.massCenterX) + (n.y - this.p.massCenterY) * (n.y - this.p.massCenterY) ); if (distance * theta > this.size) { Force.apply_nr(n, this); } else { this.subregions.forEach(function(subregion) { subregion.applyForce(n, Force, theta); }); } } }; sigma.prototype.startForceAtlas2 = function() { if ((this.forceatlas2 || {}).isRunning) return this; if (!this.forceatlas2) { this.forceatlas2 = new forceatlas2.ForceAtlas2(this.graph); this.forceatlas2.setAutoSettings(); this.forceatlas2.init(); } this.forceatlas2.isRunning = true; var self = this; function addJob() { if (!conrad.hasJob('forceatlas2_' + self.id)) conrad.addJob({ id: 'forceatlas2_' + self.id, job: self.forceatlas2.atomicGo, end: function() { self.refresh(); if (self.forceatlas2.isRunning) addJob(); } }); } addJob(); return this; }; sigma.prototype.stopForceAtlas2 = function() { if ((this.forceatlas2 || {}).isRunning) { this.forceatlas2.state = { step: 0, index: 0 }; this.forceatlas2.isRunning = false; this.forceatlas2.clean(); } if (conrad.hasJob('forceatlas2_' + this.id)) conrad.killJob('forceatlas2_' + this.id); return this; }; forceatlas2.defaultSettings = { autoSettings: true, linLogMode: false, outboundAttractionDistribution: false, adjustSizes: false, edgeWeightInfluence: 0, scalingRatio: 1, strongGravityMode: false, gravity: 1, jitterTolerance: 1, barnesHutOptimize: false, barnesHutTheta: 1.2, speed: 1, outboundAttCompensation: 1, totalSwinging: 0, totalEffectiveTraction: 0, complexIntervals: 500, simpleIntervals: 1000 }; })();
adding ability to pass options to forceatlas
plugins/sigma.layout.forceAtlas2/sigma.layout.forceAtlas2.js
adding ability to pass options to forceatlas
<ide><path>lugins/sigma.layout.forceAtlas2/sigma.layout.forceAtlas2.js <ide> } <ide> }; <ide> <del> sigma.prototype.startForceAtlas2 = function() { <add> sigma.prototype.startForceAtlas2 = function(options) { <ide> if ((this.forceatlas2 || {}).isRunning) <ide> return this; <ide> <ide> if (!this.forceatlas2) { <del> this.forceatlas2 = new forceatlas2.ForceAtlas2(this.graph); <add> this.forceatlas2 = new forceatlas2.ForceAtlas2(this.graph, options || {}); <ide> this.forceatlas2.setAutoSettings(); <ide> this.forceatlas2.init(); <ide> }
Java
apache-2.0
bb9aac532f0e0cd1194bcee11571e4ac7554c8eb
0
evenjn/knit
/** * * Copyright 2017 Marco Trevisan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.github.evenjn.knit; import java.util.Collection; import java.util.Iterator; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import org.github.evenjn.yarn.ArrayMap; import org.github.evenjn.yarn.ArrayPurl; import org.github.evenjn.yarn.ArrayPurler; import org.github.evenjn.yarn.AutoRook; import org.github.evenjn.yarn.Bi; import org.github.evenjn.yarn.Cursable; import org.github.evenjn.yarn.CursableMap; import org.github.evenjn.yarn.CursablePurl; import org.github.evenjn.yarn.CursablePurler; import org.github.evenjn.yarn.CursableRookMap; import org.github.evenjn.yarn.CursableRookPurl; import org.github.evenjn.yarn.CursableRookPurler; import org.github.evenjn.yarn.Cursor; import org.github.evenjn.yarn.CursorMap; import org.github.evenjn.yarn.CursorPurl; import org.github.evenjn.yarn.CursorPurler; import org.github.evenjn.yarn.CursorRookMap; import org.github.evenjn.yarn.CursorRookPurl; import org.github.evenjn.yarn.CursorRookPurler; import org.github.evenjn.yarn.EndOfCursorException; import org.github.evenjn.yarn.Equivalencer; import org.github.evenjn.yarn.IterableMap; import org.github.evenjn.yarn.IterablePurl; import org.github.evenjn.yarn.IterablePurler; import org.github.evenjn.yarn.IterableRookMap; import org.github.evenjn.yarn.IterableRookPurl; import org.github.evenjn.yarn.IterableRookPurler; import org.github.evenjn.yarn.IteratorMap; import org.github.evenjn.yarn.IteratorPurl; import org.github.evenjn.yarn.IteratorPurler; import org.github.evenjn.yarn.IteratorRookMap; import org.github.evenjn.yarn.IteratorRookPurl; import org.github.evenjn.yarn.IteratorRookPurler; import org.github.evenjn.yarn.OptionalMap; import org.github.evenjn.yarn.OptionalPurl; import org.github.evenjn.yarn.OptionalPurler; import org.github.evenjn.yarn.OptionalRookMap; import org.github.evenjn.yarn.OptionalRookPurl; import org.github.evenjn.yarn.OptionalRookPurler; import org.github.evenjn.yarn.Rook; import org.github.evenjn.yarn.RookConsumer; import org.github.evenjn.yarn.RookFunction; import org.github.evenjn.yarn.StreamRookMap; import org.github.evenjn.yarn.StreamRookPurl; import org.github.evenjn.yarn.StreamRookPurler; /** * * <h1>KnittingCursable</h1> * * <p> * A {@code KnittingCursable} wraps a cursable and provides utility methods to * access its contents. * </p> * * <p> * Briefly, a {@code KnittingCursable} may be used in three ways: * </p> * * <ul> * <li>As a simple Cursable, invoking the * {@link org.github.evenjn.knit.KnittingCursable#pull(Rook) pull} method;</li> * <li>As a resource to be harvested, invoking a rolling method such as * {@link #collect(Collection)};</li> * <li>As a resource to transform, invoking a transformation method such as * {@link #map(Function)};</li> * </ul> * * <p> * Unlike {@code KnittingCursor}, these three modes of operation are not * exclusive: a {@code KnittingCursable} may be used several times, in any mode. * </p> * * <h2>Methods of a KnittingCursable</h2> * * <p> * Non-static public methods of {@code KnittingCursable} fall into one of the * following four categories: * </p> * * <ul> * <li>Object methods (inherited from {@link java.lang.Object Object})</li> * <li>Cursable methods ({@link #pull(Rook)})</li> * <li>Rolling methods (listed below)</li> * <li>Transformation methods (listed below)</li> * </ul> * * <p> * Rolling methods instantiate a {@link KnittingCursor} by invoking * {@link #pull(Rook)} and repeatedly invoke the method * {@link KnittingCursor#map(Rook, RookFunction)} typically (but not * necessarily) until the end is reached. The following methods are rolling: * </p> * * <ul> * <li>{@link #collect(Collection)}</li> * <li>{@link #consume(Function)}</li> * <li>{@link #count()}</li> * <li>{@link #equivalentTo(Cursable)}</li> * <li>{@link #equivalentTo(Cursable, Equivalencer)}</li> * <li>{@link #one()}</li> * <li>{@link #optionalOne()}</li> * <li>{@link #reduce(Object, BiFunction)}</li> * <li>{@link #roll()}</li> * </ul> * * * <p> * Transformations are a group of methods that return a new * {@code KnittingCursable} object (or something similar), which provides a new * view of the contents of the wrapped cursable. Transformation methods do not * instantiate cursors at the time of their invocation; they return lazy * wrappers. The following methods are transformations: * </p> * * <ul> * <li>{@link #append(Cursable)}</li> * <li>{@link #asIterator(Rook)}</li> * <li>{@link #asStream(Rook)}</li> * <li>{@link #crop(Predicate)}</li> * <li>{@link #entwine(Cursable, BiFunction)}</li> * <li>{@link #filter(Predicate)}</li> * <li>{@link #flatmapArray(ArrayMap)}</li> * <li>{@link #flatmapCursable(CursableMap)}</li> * <li>{@link #flatmapCursable(CursableRookMap)}</li> * <li>{@link #flatmapCursor(CursorMap)}</li> * <li>{@link #flatmapCursor(CursorRookMap)}</li> * <li>{@link #flatmapIterable(IterableMap)}</li> * <li>{@link #flatmapIterable(IterableRookMap)}</li> * <li>{@link #flatmapIterator(IteratorMap)}</li> * <li>{@link #flatmapIterator(IteratorRookMap)}</li> * <li>{@link #flatmapOptional(OptionalMap)}</li> * <li>{@link #flatmapOptional(OptionalRookMap)}</li> * <li>{@link #flatmapStream(StreamRookMap)}</li> * <li>{@link #head(int, int)}</li> * <li>{@link #headless(int)}</li> * <li>{@link #map(Function)}</li> * <li>{@link #map(RookFunction)}</li> * <li>{@link #numbered()}</li> * <li>{@link #peek(Consumer)}</li> * <li>{@link #prepend(Cursable)}</li> * <li>{@link #purlArray(ArrayPurler)}</li> * <li>{@link #purlCursable(CursablePurler)}</li> * <li>{@link #purlCursable(CursableRookPurler)}</li> * <li>{@link #purlCursor(CursorPurler)}</li> * <li>{@link #purlCursor(CursorRookPurler)}</li> * <li>{@link #purlIterable(IterablePurler)}</li> * <li>{@link #purlIterable(IterableRookPurler)}</li> * <li>{@link #purlIterator(IteratorPurler)}</li> * <li>{@link #purlIterator(IteratorRookPurler)}</li> * <li>{@link #purlOptional(OptionalPurler)}</li> * <li>{@link #purlOptional(OptionalRookPurler)}</li> * <li>{@link #purlStream(StreamRookPurler)}</li> * </ul> * * @param <I> * The type of elements accessible via this cursable. * @see org.github.evenjn.knit * @since 1.0 */ public class KnittingCursable<I> implements Cursable<I> { private final Cursable<I> wrapped; private KnittingCursable(Cursable<I> cursable) { this.wrapped = cursable; } /** * Returns a view of the concatenation of the argument cursable after this * cursable. * * @param tail * A cursable to concatenate after this cursable. * @return A view of the concatenation of the argument cursable after this * cursable. * @since 1.0 */ public KnittingCursable<I> append( final Cursable<? extends I> tail ) { return wrap( new ConcatenateCursable<I>( wrapped, tail ) ); } /** * <p> * Returns a view of this cursable as a {@link java.util.Iterator}. * </p> * * <p> * This is a transformation method. * </p> * * @param rook * A rook. * @return A view of this cursable as a {@link java.util.Iterator}. * @since 1.0 */ public Iterator<I> asIterator( Rook rook ) { return pull( rook ).asIterator( ); } /** * <p> * Returns a view of this cursable as a {@link java.util.stream.Stream}. * </p> * * <p> * This is a transformation method. * </p> * * @param rook * A rook. * @return A view of this cursable as a {@link java.util.stream.Stream}. * @since 1.0 */ public Stream<I> asStream( Rook rook ) { return pull( rook ).asStream( ); } /** * <p> * Adds all elements of this cursable to the argument collection, then returns * it. * </p> * * <p> * The objects collected may be dead. This is due to the fact that cursors do * not guarantee that the objects they return survive subsequent invocations * of {@link org.github.evenjn.yarn.Cursor#next() next()}, or closing the * rook. * </p> * * @param <K> * The type the argument collection. * @param collection * The collection to add elements to. * @return The argument collection. * @since 1.0 */ public <K extends Collection<? super I>> K collect( K collection ) { try ( AutoRook rook = new BasicAutoRook( ) ) { return pull( rook ).collect( collection ); } } /** * <p> * Feeds a consumer with the elements of this cursable. * </p> * * <p> * Obtains a consumer from the argument {@code consumer_provider}, hooking it * to a local, temporary rook. Then, this method obtains a cursor using this * cursable's {@link #pull(Rook)}, hooking it to the same local rook. * </p> * * <p> * Finally, this method invokes that cursor's * {@link org.github.evenjn.yarn.Cursor#next() next()} method, passing each * object obtained this way to the consumer, until the end of the cursor. * </p> * * <p> * This is a rolling method. * </p> * * @param consumer_provider * A system that provides a consumer. * @since 1.0 */ public void consume( RookConsumer<? super I> consumer_provider ) { try ( AutoRook rook = new BasicAutoRook( ) ) { Consumer<? super I> consumer = consumer_provider.get( rook ); pull( rook ).peek( consumer ).roll( ); } } /** * <p> * Returns a cursable where each element is a cursor providing access to a * subsequence of contiguous elements in this cursable that satisfy the * argument {@code stateless_predicate}. * </p> * * @param stateless_predicate * A stateless system that identifies elements that should be kept * together. * @return a cursable where each element is a cursor providing access to a * subsequence of contiguous elements in this cursable that satisfy * the argument {@code stateless_predicate}. * @since 1.0 */ public KnittingCursable<KnittingCursor<I>> crop( Predicate<I> stateless_predicate ) { return KnittingCursable.wrap( h -> pull( h ).crop( stateless_predicate ) ); } /** * <p> * Returns a cursable that traverses this cursable and the argument * {@code other_cursor} in parallel, applying the argument * {@code stateless_bifunction} to each pair of elements, and providing a view * of the result of each application. * </p> * * <p> * The returned cursable provides as many elements as the cursor with the * least elements. * </p> * * <p> * This is a transformation method. * </p> * * @param <R> * The type of elements accessible via the argument cursable. * @param <M> * The type of elements returned by the bifunction. * @param other_cursable * The cursable to roll in parallel to this cursable. * @param stateless_bifunction * The stateless bifunction to apply to each pair of element. * @return a cursable that traverses this cursable and the argument cursable * in parallel, applying the argument bifunction to each pair of * elements, and providing a view of the result of each application. * @since 1.0 */ public <R, M> KnittingCursable<M> entwine( Cursable<R> other_cursable, BiFunction<I, R, M> stateless_bifunction ) { KnittingCursable<I> outer = this; Cursable<M> result = new Cursable<M>( ) { @Override public Cursor<M> pull( Rook rook ) { return outer.pull( rook ).entwine( other_cursable.pull( rook ), stateless_bifunction ); } }; return wrap( result ); } private static <T> boolean equal_null( T first, T second ) { if ( first == null && second == null ) return true; if ( first == null || second == null ) return false; return first.equals( second ); } /** * <p> * Returns true when this cursable and the {@code other} cursable have the * same number of elements, and when each i-th element of this cursable is * equivalent to the i-th element of the {@code other} cursable. Returns false * otherwise. * </p> * * <p> * For the purposes of this method, two {@code null} elements are equivalent. * </p> * * <p> * This is a rolling method. * </p> * * @param other * Another cursable. * @return true when this cursable and the {@code other} cursable have the * same number of elements, and when each i-th element of this * cursable is equivalent to the i-th element of the {@code other} * cursable. False otherwise. * @since 1.0 */ public boolean equivalentTo( Cursable<?> other ) { if ( other == this ) return true; return equivalentTo( other, KnittingCursable::equal_null ); } /** * <p> * Returns true when this cursable and the {@code other} cursable have the * same number of elements, and when each i-th element of this cursable is * equivalent to the i-th element of the {@code other} cursable. Returns false * otherwise. * </p> * * <p> * This is a rolling method. * </p> * * @param other * Another cursable. * @param equivalencer * A function that tells whether two objects are equivalent. * @return true when this cursable and the {@code other} cursable have the * same number of elements, and when each i-th element of this * cursable is equivalent to the i-th element of the {@code other} * cursable. False otherwise. * @since 1.0 */ public <Y> boolean equivalentTo( Cursable<Y> other, Equivalencer<I, Y> equivalencer ) { if ( other == this ) return true; try ( AutoRook rook = new BasicAutoRook( ) ) { KnittingCursor<I> pull1 = this.pull( rook ); KnittingCursor<Y> pull2 = KnittingCursor.wrap( other.pull( rook ) ); for ( ;; ) { boolean hasNext1 = pull1.hasNext( ); boolean hasNext2 = pull2.hasNext( ); if ( hasNext1 != hasNext2 ) { return false; } if ( !hasNext1 ) { return true; } I next1 = pull1.next( ); Y next2 = pull2.next( ); if ( !equivalencer.equivalent( next1, next2 ) ) { return false; } } } catch ( EndOfCursorException e ) { throw new IllegalStateException( e ); } } /** * <p> * Returns a view hiding the elements which do not satisfy the argument * {@code stateless_predicate} in this cursable. * </p> * * <p> * This is a transformation method. * </p> * * @param stateless_predicate * A stateless system that decides to show or hide elements. * @return A view hiding the elements which do not satisfy the argument * {@code stateless_predicate} in this cursable. * @since 1.0 */ public KnittingCursable<I> filter( Predicate<? super I> stateless_predicate ) { return wrap( new Cursable<I>( ) { @Override public Cursor<I> pull( Rook rook ) { return new FilterCursor<>( wrapped.pull( rook ), stateless_predicate ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #flatmapCursor(CursorMap)} except that the view shows elements in * the arrays returned by the argument {@code stateless_array_map}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in the cursors returned by the argument * {@code stateless_array_map}. * @param stateless_array_map * A stateless function that returns arrays. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> flatmapArray( ArrayMap<? super I, O> stateless_array_map ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .flatmapArray( stateless_array_map ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #flatmapCursor(CursorMap)} except that the view shows elements in * the cursables returned by the argument {@code stateless_cursable_map}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in the cursables returned by the argument * {@code stateless_cursable_map}. * @param stateless_cursable_map * A stateless function that returns cursables. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> flatmapCursable( CursableMap<? super I, O> stateless_cursable_map ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .flatmapCursable( rook, stateless_cursable_map ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #flatmapCursor(CursorRookMap)} except that the view shows elements * in the cursables returned by the argument {@code stateless_cursable_map_h}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in the cursables returned by the argument * {@code stateless_cursable_map_h}. * @param stateless_cursable_map_h * A stateless function that returns cursables. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> flatmapCursable( CursableRookMap<? super I, O> stateless_cursable_map_h ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .flatmapCursable( rook, stateless_cursable_map_h ); } } ); } /** * <p> * Each invocation of {@link #pull(Rook)} on the returned * {@code KnittingCursable} pulls a new {@code KnittingCursor} from this * cursable, transforms it using * {@link KnittingCursor#flatmapCursor(CursorMap)} with the argument * {@code stateless_cursor_map}, then returns the resulting cursor. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in the cursors returned by the argument * {@code stateless_cursor_map}. * @param stateless_cursor_map * A stateless function that returns cursors. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> flatmapCursor( CursorMap<? super I, O> stateless_cursor_map ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .flatmapCursor( stateless_cursor_map ); } } ); } /** * <p> * Each invocation of {@link #pull(Rook)} on the returned * {@code KnittingCursable} pulls a new {@code KnittingCursor} from this * cursable, transforms it using * {@link KnittingCursor#flatmapCursor(Rook, CursorRookMap)} with the rook * already available and the argument {@code stateless_cursor_map_h}, then * returns the resulting cursor. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in the cursors returned by the argument * {@code stateless_cursor_map_h}. * @param stateless_cursor_map_h * A stateless function that returns cursors. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> flatmapCursor( CursorRookMap<? super I, O> stateless_cursor_map_h ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .flatmapCursor( rook, stateless_cursor_map_h ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #flatmapCursor(CursorMap)} except that the view shows elements in * the iterables returned by the argument {@code stateless_iterable_map}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in the iterables returned by the argument * {@code stateless_iterable_map}. * @param stateless_iterable_map * A stateless function that returns iterables. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> flatmapIterable( IterableMap<? super I, O> stateless_iterable_map ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .flatmapIterable( stateless_iterable_map ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #flatmapCursor(CursorRookMap)} except that the view shows elements * in the iterables returned by the argument {@code stateless_iterable_map_h}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in the iterables returned by the argument * {@code stateless_iterable_map_h}. * @param stateless_iterable_map_h * A stateless function that returns iterators. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> flatmapIterable( IterableRookMap<? super I, O> stateless_iterable_map_h ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .flatmapIterable( rook, stateless_iterable_map_h ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #flatmapCursor(CursorMap)} except that the view shows elements in * the iterators returned by the argument {@code stateless_iterator_map}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in the iterators returned by the argument * {@code stateless_iterator_map}. * @param stateless_iterator_map * A stateless function that returns iterators. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> flatmapIterator( IteratorMap<? super I, O> stateless_iterator_map ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .flatmapIterator( stateless_iterator_map ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #flatmapCursor(CursorRookMap)} except that the view shows elements * in the iterators returned by the argument {@code stateless_iterator_map_h}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in the iterators returned by the argument * {@code stateless_iterator_map_h}. * @param stateless_iterator_map_h * A stateless function that returns iterators. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> flatmapIterator( IteratorRookMap<? super I, O> stateless_iterator_map_h ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .flatmapIterator( rook, stateless_iterator_map_h ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #flatmapCursor(CursorMap)} except that the view shows elements in * the optionals returned by the argument {@code stateless_optional_map}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in the optionals returned by the argument * {@code stateless_optional_map}. * @param stateless_optional_map * A stateless function that returns optionals. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> flatmapOptional( OptionalMap<? super I, O> stateless_optional_map ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .flatmapOptional( stateless_optional_map ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #flatmapCursor(CursorRookMap)} except that the view shows elements * in the optionals returned by the argument {@code stateless_optional_map_h}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in the optionals returned by the argument * {@code stateless_optional_map_h}. * @param stateless_optional_map_h * A stateless function that returns optionals. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> flatmapOptional( OptionalRookMap<? super I, O> stateless_optional_map_h ) throws IllegalStateException { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .flatmapOptional( rook, stateless_optional_map_h ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #flatmapCursor(CursorRookMap)} except that the view shows elements * in the streams returned by the argument {@code stateless_stream_map_h}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in the streams returned by the argument * {@code stateless_stream_map_h}. * @param stateless_stream_map_h * A stateless function that returns streams. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> flatmapStream( StreamRookMap<? super I, O> stateless_stream_map_h ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .flatmapStream( rook, stateless_stream_map_h ); } } ); } /** * <p> * Returns a view showing the first {@code show} elements of this cursable * visible after hiding the first {@code hide} elements. * </p> * * <p> * The returned view may be empty. This happens when this cursable's size is * smaller than {@code hide}. * </p> * * <p> * The returned view may contain less than {@code show} elements. This happens * when this cursable's size is smaller than {@code hide + show}. * </p> * * <p> * This is a transformation method. * </p> * * @param hide * The number of elements to hide. A negative numbers counts as zero. * @param show * The number of elements to show. A negative numbers counts as zero. * @return A view showing the first {@code show} elements of this cursable * visible after hiding the first {@code hide} elements. * @since 1.0 */ public KnittingCursable<I> head( int hide, int show ) { int final_show = show < 0 ? 0 : show; int final_hide = hide < 0 ? 0 : hide; return wrap( new Cursable<I>( ) { @Override public Cursor<I> pull( Rook rook ) { return Subcursor.sub( wrapped.pull( rook ), final_hide, final_show ); } } ); } /** * <p> * Returns a view hiding the first {@code hide} elements of this cursable. * </p> * * <p> * The returned view may be empty. This happens when this cursable's size is * smaller than {@code hide}. * </p> * * <p> * This is a transformation method. * </p> * * @param hide * The number of elements to hide. A negative numbers counts as zero. * @return A view hiding the first {@code hide} elements of this cursable. * @since 1.0 */ public KnittingCursable<I> headless( int hide ) { int final_hide = hide < 0 ? 0 : hide; return wrap( new Cursable<I>( ) { @Override public Cursor<I> pull( Rook rook ) { return Subcursor.skip( wrapped.pull( rook ), final_hide ); } } ); } /** * <p> * Each invocation of {@link #pull(Rook)} on the returned * {@code KnittingCursable} pulls a new {@code KnittingCursor} from this * cursable, transforms it using {@link KnittingCursor#map(Function)} with the * argument {@code stateless_function}, then returns the resulting cursor. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements returned by the argument * {@code stateless_function}. * @param stateless_function * A stateless function. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> map( Function<? super I, O> stateless_function ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .map( stateless_function ); } } ); } /** * <p> * Each invocation of {@link #pull(Rook)} on the returned * {@code KnittingCursable} pulls a new {@code KnittingCursor} from this * cursable, transforms it using * {@link KnittingCursor#map(Rook, RookFunction)} with the rook already * available and the argument {@code stateless_function_h}, then returns the * resulting cursor. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements returned by the argument * {@code stateless_function_h}. * @param stateless_function_h * A stateless function. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> map( RookFunction<? super I, O> stateless_function_h ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .map( rook, stateless_function_h ); } } ); } /** * <p> * Returns a view that, for each element of this cursable, provides a * {@linkplain org.github.evenjn.yarn.Bi pair} containing the element itself * and the number of elements preceding it. * </p> * * <p> * This is a transformation method. * </p> * * @return A view that, for each element of this cursable, provides a * {@linkplain org.github.evenjn.yarn.Bi pair} containing the element * itself and the number of elements preceding it. * @since 1.0 */ public KnittingCursable<Bi<I, Integer>> numbered( ) { return wrap( new Cursable<Bi<I, Integer>>( ) { @Override public Cursor<Bi<I, Integer>> pull( Rook rook ) { return new NumberedCursor<>( wrapped.pull( rook ) ); } } ); } /** * <p> * When this cursable provides access to one element only, this method returns * it. Otherwise, it throws an {@code IllegalStateException}. * </p> * * <p> * The object returned may be dead. This is due to the fact that cursables do * not guarantee that the objects they return survive subsequent invocations * of {@link org.github.evenjn.yarn.Cursor#next() next()} on the cursors they * provide, or closing the rook. * </p> * * <p> * This is a rolling method. * </p> * * @return The only element accessible via this cursable. * @throws IllegalStateException * when it is not the case that there is exactly one element. * @since 1.0 */ public I one( ) { try ( AutoRook rook = new BasicAutoRook( ) ) { return pull( rook ).one( ); } } /** * <p> * When this cursable provides access to one non-null element only, this * method returns it wrapped in an optional. * </p> * * <p> * The object returned may be dead. This is due to the fact that cursables do * not guarantee that the objects they return survive subsequent invocations * of {@link org.github.evenjn.yarn.Cursor#next() next()} on the cursors they * provide, or closing the rook. * </p> * * <p> * When it not the case that there is exactly one element, or when the only * element accessible is {@code null}, this method returns an empty optional. * </p> * * <p> * This is a rolling method. * </p> * * @return The only element accessible via this cursable, if any, or an empty * optional. * @since 1.0 */ public Optional<I> optionalOne( ) { try ( AutoRook rook = new BasicAutoRook( ) ) { return pull( rook ).optionalOne( ); } } /** * <p> * Returns a view providing access to the elements of this cursable. The view * passes the elements to the argument consumer. * </p> * * <p> * For each {@code KnittingCursor} obtained invoking {@link #pull(Rook)} on * the returned {@code KnittingCursable}, at each invocation of * {@link org.github.evenjn.yarn.Cursor#next() next()}, that * {@code KnittingCursor} fetches the next element from the cursor it wraps, * then invokes the consumer using the fetched element as argument, then * returns the fetched element. * </p> * * <p> * This is a transformation method. * </p> * * @param consumer * A consumer that will consume each element retrieved from this * cursor. * @return A view providing access to the elements of this cursable. Before * retuning them, the view passes the elements to the argument * consumer. * @since 1.0 */ public KnittingCursable<I> peek( Consumer<? super I> consumer ) { return wrap( new Cursable<I>( ) { @Override public Cursor<I> pull( Rook rook ) { return new TapCursor<I>( wrapped.pull( rook ), consumer ); } } ); } /** * <p> * Returns a view of the concatenation of the argument cursable before this * cursable. * </p> * * <p> * This is a transformation method. * </p> * * @param head * A cursable to concatenate before this cursable. * @return A view of the concatenation of the argument cursable before this * cursable. * @since 1.0 */ public KnittingCursable<I> prepend( final Cursable<? extends I> head ) { KnittingCursable<I> outer_cursable = this; Cursable<I> result = new Cursable<I>( ) { @Override public Cursor<I> pull( Rook rook ) { return outer_cursable.pull( rook ).prepend( head.pull( rook ) ); } }; return wrap( result ); } /** * <p> * Returns a {@code KnittingCursor} wrapping a cursor obtained from the * wrapped cursable. * </p> * * @param rook * A rook. * @return A {@code KnittingCursor} wrapping a cursor obtained from the * wrapped cursable. * @since 1.0 */ @Override public KnittingCursor<I> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ); } /** * <p> * Returns a view realizing the same transformation as * {@link #purlCursor(CursorPurler)} except that the view shows elements * in arrays returned by {@link ArrayPurl} objects supplied by the argument * {@code factory}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in arrays returned by {@link ArrayPurl} * objects supplied by the argument {@code factory}. * @param factory * A supplier of {@link ArrayPurl} objects. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> purlArray( ArrayPurler<? super I, O> factory ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { Cursor<I> pull = wrapped.pull( rook ); return KnittingCursor.wrap( pull ).purlArray( factory.get( ) ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #purlCursor(CursorPurler)} except that the view shows elements * in cursables returned by {@link CursablePurl} objects supplied by the * argument {@code factory}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in cursables returned by {@link CursablePurl} * objects supplied by the argument {@code factory}. * @param factory * A supplier of {@link CursablePurl} objects. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> purlCursable( CursablePurler<? super I, O> factory ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { Cursor<I> pull = wrapped.pull( rook ); return KnittingCursor.wrap( pull ).purlCursable( factory.get( ) ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #purlCursor(CursorRookPurler)} except that the view shows * elements in arrays returned by {@link CursableRookPurl} objects supplied by * the argument {@code factory}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in cursables returned by * {@link CursableRookPurl} objects supplied by the argument * {@code factory}. * @param factory * A supplier of {@link CursableRookPurl} objects. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> purlCursable( CursableRookPurler<? super I, O> factory ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { Cursor<I> pull = wrapped.pull( rook ); return KnittingCursor.wrap( pull ).purlCursable( rook, factory.get( ) ); } } ); } /** * <p> * Returns a complex view. * </p> * * <p> * Pulling a cursor from the returned cursable returns a purl of a cursor * pulled from this cursable. For an introduction on purling see * {@link org.github.evenjn.yarn.CursorPurl CursorPurl}. * </p> * * <p> * In detail, when the client invokes {@link Cursable#pull(Rook) pull} on the * returned cursable, that cursable pulls a new {@link KnittingCursor} from * this cursable, then it obtains a new {@link CursorPurl} from the argument * factory, and finally returns the cursor obtained by invoking * {@link KnittingCursor#purlCursor(CursorPurl) purlCursor} using the argument * purl. * </p> * * <p> * This is a transformation method. * </p> * * * @param <O> * The type of elements in cursors produced by {@link CursorPurl} * objects supplied by the argument {@code factory}. * * @param factory * A supplier of {@link CursorPurl} objects. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> purlCursor( CursorPurler<? super I, O> factory ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { Cursor<I> pull = wrapped.pull( rook ); return KnittingCursor.wrap( pull ) .purlCursor( factory.get( ) ); } } ); } /** * <p> * Returns a complex view. * </p> * * <p> * Pulling a cursor from the returned cursable returns a purl of a cursor * pulled from this cursable. For an introduction on purling see * {@link org.github.evenjn.yarn.CursorPurl CursorPurl}. * </p> * * <p> * In detail, when the client invokes {@link Cursable#pull(Rook) pull} on the * returned cursable, that cursable pulls a new {@link KnittingCursor} from * this cursable, then it obtains a new {@link CursorRookPurl} from the * argument {@code factory}, and finally returns the cursor obtained by * invoking {@link KnittingCursor#purlCursor(Rook, CursorRookPurl) * purlCursable} using the argument purl. * </p> * * <p> * This is a transformation method. * </p> * * * @param <O> * The type of elements in cursors produced by {@link CursorRookPurl} * objects supplied by the argument {@code factory}. * * @param factory * A supplier of {@link CursorRookPurl} objects. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> purlCursor( CursorRookPurler<? super I, O> factory ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { Cursor<I> pull = wrapped.pull( rook ); return KnittingCursor.wrap( pull ) .purlCursor( rook, factory.get( ) ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #purlCursor(CursorPurler)} except that the view shows elements * in iterables returned by {@link IterablePurl} objects supplied by the * argument {@code factory}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in iterables returned by {@link IterablePurl} * objects supplied by the argument {@code factory}. * @param factory * A supplier of {@link IterablePurl} objects. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> purlIterable( IterablePurler<? super I, O> factory ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { Cursor<I> pull = wrapped.pull( rook ); return KnittingCursor.wrap( pull ).purlIterable( factory.get( ) ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #purlCursor(CursorRookPurler)} except that the view shows * elements in iterables returned by {@link IterableRookPurl} objects supplied * by the argument {@code factory}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in iterables returned by * {@link IterableRookPurl} objects supplied by the argument * {@code factory}. * @param factory * A supplier of {@link IterableRookPurl} objects. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> purlIterable( IterableRookPurler<? super I, O> factory ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { Cursor<I> pull = wrapped.pull( rook ); return KnittingCursor.wrap( pull ).purlIterable( rook, factory.get( ) ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #purlCursor(CursorPurler)} except that the view shows elements * in iterators returned by {@link IteratorPurl} objects supplied by the * argument {@code factory}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in iterators returned by {@link IteratorPurl} * objects supplied by the argument {@code factory}. * @param factory * A supplier of {@link IteratorPurl} objects. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> purlIterator( IteratorPurler<? super I, O> factory ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { Cursor<I> pull = wrapped.pull( rook ); return KnittingCursor.wrap( pull ).purlIterator( factory.get( ) ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #purlCursor(CursorRookPurler)} except that the view shows * elements in iterators returned by {@link IteratorRookPurl} objects supplied * by the argument {@code factory}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in iterators returned by * {@link IteratorRookPurl} objects supplied by the argument * {@code factory}. * @param factory * A supplier of {@link IteratorRookPurl} objects. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> purlIterator( IteratorRookPurler<? super I, O> factory ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { Cursor<I> pull = wrapped.pull( rook ); return KnittingCursor.wrap( pull ).purlIterator( rook, factory.get( ) ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #purlCursor(CursorPurler)} except that the view shows elements * in optionals returned by {@link OptionalPurl} objects supplied by the * argument {@code factory}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in optionals returned by {@link OptionalPurl} * objects supplied by the argument {@code factory}. * @param factory * A supplier of {@link OptionalPurl} objects. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> purlOptional( OptionalPurler<? super I, O> factory ) throws IllegalStateException { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ).purlOptional( factory.get( ) ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #purlCursor(CursorRookPurler)} except that the view shows * elements in optionals returned by {@link OptionalRookPurl} objects supplied * by the argument {@code factory}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in optionals returned by * {@link OptionalRookPurl} objects supplied by the argument * {@code factory}. * @param factory * A supplier of {@link OptionalRookPurl} objects. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> purlOptional( OptionalRookPurler<? super I, O> factory ) throws IllegalStateException { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ).purlOptional( rook, factory.get( ) ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #purlCursor(CursorRookPurler)} except that the view shows * elements in streams returned by {@link StreamRookPurl} objects supplied by * the argument {@code factory}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in streams returned by {@link StreamRookPurl} * objects supplied by the argument {@code factory}. * @param factory * A supplier of {@link StreamRookPurl} objects. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> purlStream( StreamRookPurler<? super I, O> factory ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ).purlStream( rook, factory.get( ) ); } } ); } /** * <p> * Returns the result of a computation taking into account all the elements of * this cursable. * </p> * * <p> * This method stores into a local variable the argument {@code zero}. Then, * for each element {@code E} in this cursable, this method invokes the * argument {@code bifunction} using the content of the local variable and * {@code E}. At the end of each such invocation, this method stores into the * local variable the result of the invocation. Finally, this method returns * the content of the local variable. * </p> * * <p> * This is a rolling method. * </p> * * @param <K> * The type of argument {@code zero} and of the elements returned by * the argument {@code bifunction}. * @param zero * The initial value for the reduction. * @param bifunction * A bifunction that will be invoked once for each element of this * cursable. * @return the result of a computation taking into account all the elements of * this cursable. * @since 1.0 */ public <K> K reduce( K zero, BiFunction<K, I, K> bifunction ) { K reduction = zero; try ( AutoRook rook = new BasicAutoRook( ) ) { Cursor<I> kc = wrapped.pull( rook ); try { for ( ;; ) { reduction = bifunction.apply( reduction, kc.next( ) ); } } catch ( EndOfCursorException e ) { } return reduction; } } /** * <p> * Pulls a {@code KnittingCursor} from this cursable and invokes * {@link KnittingCursor#roll() roll()} on it. * </p> * * <p> * This is a rolling method. * </p> * * @since 1.0 */ public void roll( ) { try ( AutoRook rook = new BasicAutoRook( ) ) { pull( rook ).roll( ); } } /** * <p> * Counts the number of elements in this cursable. * </p> * * <p> * Pulls a {@code KnittingCursor} from this cursable, invokes * {@link KnittingCursor#count()}, and returns the result of that invocation. * </p> * * <p> * This is a rolling method. * </p> * * @return The number of elements in this cursable. * @since 1.0 */ public int count( ) { try ( AutoRook rook = new BasicAutoRook( ) ) { return pull( rook ).count( ); } } /** * <p> * Returns a view of the last {@code show} elements visible after hiding the * last {@code hide} elements in this cursable. * </p> * * <p> * The returned view may be empty. This happens when this cursable's size is * smaller than {@code hide}. * </p> * * <p> * The returned view may contain less than {@code show} elements. This happens * when this cursable's size is smaller than {@code hide + show}. * </p> * * <p> * This operation relies on {@code size()}. Therefore, it has a one-time * computational time cost linear to the size of this cursable. * </p> * * @param hide * The number of elements to hide. A negative numbers counts as zero. * @param show * The number of elements to show. A negative numbers counts as zero. * @return A view of the last {@code show} elements visible after hiding the * last {@code hide} elements in this cursable. */ @SuppressWarnings("unused") private KnittingCursable<I> tail( int hide, int show ) { int final_show = show < 0 ? 0 : show; int final_hide = hide < 0 ? 0 : hide; int len = count( ) - final_hide; if ( len > final_show ) { len = final_show; } int skip = count( ) - ( final_hide + len ); if ( skip < 0 ) { skip = 0; } int final_len = len; int final_skip = skip; return wrap( new Cursable<I>( ) { @Override public Cursor<I> pull( Rook rook ) { return Subcursor.sub( wrapped.pull( rook ), final_skip, final_len ); } } ); } /** * <p> * Returns a view hiding the last {@code hide} elements in this cursable. * </p> * * <p> * The returned view may be empty. This happens when this cursable's size is * smaller than {@code hide}. * </p> * * <p> * This operation relies on {@code size()}. Therefore, it has a one-time * computational time cost linear to the size of this cursable. * </p> * * @param hide * The number of elements to hide. A negative numbers counts as zero. * @return A view hiding the last {@code hide} elements in this cursable. */ @SuppressWarnings("unused") private KnittingCursable<I> tailless( int hide ) { int final_hide = hide < 0 ? 0 : hide; int len = count( ) - final_hide; if ( len < 0 ) { len = 0; } int final_len = len; return wrap( new Cursable<I>( ) { @Override public Cursor<I> pull( Rook rook ) { return Subcursor.sub( wrapped.pull( rook ), 0, final_len ); } } ); } /** * <p> * Returns an empty cursable. * </p> * * @param <K> * The type of elements in the empty cursable. * @return An empty cursable. * * @since 1.0 */ public static <K> KnittingCursable<K> empty( ) { return private_empty( ); } @SuppressWarnings("unchecked") private static <K> KnittingCursable<K> private_empty( ) { return (KnittingCursable<K>) neo; } private static final KnittingCursable<Void> neo = wrap( new Cursable<Void>( ) { @Override public Cursor<Void> pull( Rook rook ) { return KnittingCursor.empty( ); } } ); /** * <p> * Returns new {@code KnittingCursable} providing access to the argument * elements. * </p> * * @param <K> * The type of the argument elements. * @param elements * Elements to be wrapped in a new {@code KnittingCursable}. * @return A new {@code KnittingCursable} providing access to the argument * elements. * @since 1.0 */ @SafeVarargs public static <K> KnittingCursable<K> on( K ... elements ) { Cursable<K> cursable = new Cursable<K>( ) { @Override public Cursor<K> pull( Rook rook ) { return new ArrayCursor<K>( elements ); } }; return wrap( cursable ); } /** * <p> * Returns a view of the elements in the argument cursable. * </p> * * @param <K> * The type of elements in the argument cursable. * @param cursable * A cursable of elements. * @return A view of the elements in the argument cursable. * @since 1.0 */ public static <K> KnittingCursable<K> wrap( Cursable<K> cursable ) { if ( cursable instanceof KnittingCursable ) { return (KnittingCursable<K>) cursable; } return new KnittingCursable<K>( cursable ); } /** * <p> * Returns a view of the elements in the argument iterable. * </p> * * @param <K> * The type of elements in the argument iterable. * @param iterable * An iterable of elements. * @return A view of the elements in the argument iterable. * @since 1.0 */ public static <K> KnittingCursable<K> wrap( Iterable<K> iterable ) { return wrap( new IterableCursable<K>( iterable ) ); } /** * <p> * Returns a view of the elements in the argument array. * </p> * * @param <K> * The type of elements in the argument array. * @param array * An array of elements. * @return A view of the elements in the argument array. * @since 1.0 */ public static <K> KnittingCursable<K> wrap( K[] array ) { return wrap( new ArrayCursable<K>( array ) ); } }
src/main/java/org/github/evenjn/knit/KnittingCursable.java
/** * * Copyright 2017 Marco Trevisan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.github.evenjn.knit; import java.util.Collection; import java.util.Iterator; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import org.github.evenjn.yarn.ArrayMap; import org.github.evenjn.yarn.ArrayPurl; import org.github.evenjn.yarn.ArrayPurlFactory; import org.github.evenjn.yarn.AutoRook; import org.github.evenjn.yarn.Bi; import org.github.evenjn.yarn.Cursable; import org.github.evenjn.yarn.CursableMap; import org.github.evenjn.yarn.CursablePurl; import org.github.evenjn.yarn.CursablePurlFactory; import org.github.evenjn.yarn.CursableRookMap; import org.github.evenjn.yarn.CursableRookPurl; import org.github.evenjn.yarn.CursableRookPurlFactory; import org.github.evenjn.yarn.Cursor; import org.github.evenjn.yarn.CursorMap; import org.github.evenjn.yarn.CursorPurl; import org.github.evenjn.yarn.CursorPurlFactory; import org.github.evenjn.yarn.CursorRookMap; import org.github.evenjn.yarn.CursorRookPurl; import org.github.evenjn.yarn.CursorRookPurlFactory; import org.github.evenjn.yarn.EndOfCursorException; import org.github.evenjn.yarn.Equivalencer; import org.github.evenjn.yarn.IterableMap; import org.github.evenjn.yarn.IterablePurl; import org.github.evenjn.yarn.IterablePurlFactory; import org.github.evenjn.yarn.IterableRookMap; import org.github.evenjn.yarn.IterableRookPurl; import org.github.evenjn.yarn.IterableRookPurlFactory; import org.github.evenjn.yarn.IteratorMap; import org.github.evenjn.yarn.IteratorPurl; import org.github.evenjn.yarn.IteratorPurlFactory; import org.github.evenjn.yarn.IteratorRookMap; import org.github.evenjn.yarn.IteratorRookPurl; import org.github.evenjn.yarn.IteratorRookPurlFactory; import org.github.evenjn.yarn.OptionalMap; import org.github.evenjn.yarn.OptionalPurl; import org.github.evenjn.yarn.OptionalPurlFactory; import org.github.evenjn.yarn.OptionalRookMap; import org.github.evenjn.yarn.OptionalRookPurl; import org.github.evenjn.yarn.OptionalRookPurlFactory; import org.github.evenjn.yarn.Rook; import org.github.evenjn.yarn.RookConsumer; import org.github.evenjn.yarn.RookFunction; import org.github.evenjn.yarn.StreamRookMap; import org.github.evenjn.yarn.StreamRookPurl; import org.github.evenjn.yarn.StreamRookPurlFactory; /** * * <h1>KnittingCursable</h1> * * <p> * A {@code KnittingCursable} wraps a cursable and provides utility methods to * access its contents. * </p> * * <p> * Briefly, a {@code KnittingCursable} may be used in three ways: * </p> * * <ul> * <li>As a simple Cursable, invoking the * {@link org.github.evenjn.knit.KnittingCursable#pull(Rook) pull} method;</li> * <li>As a resource to be harvested, invoking a rolling method such as * {@link #collect(Collection)};</li> * <li>As a resource to transform, invoking a transformation method such as * {@link #map(Function)};</li> * </ul> * * <p> * Unlike {@code KnittingCursor}, these three modes of operation are not * exclusive: a {@code KnittingCursable} may be used several times, in any mode. * </p> * * <h2>Methods of a KnittingCursable</h2> * * <p> * Non-static public methods of {@code KnittingCursable} fall into one of the * following four categories: * </p> * * <ul> * <li>Object methods (inherited from {@link java.lang.Object Object})</li> * <li>Cursable methods ({@link #pull(Rook)})</li> * <li>Rolling methods (listed below)</li> * <li>Transformation methods (listed below)</li> * </ul> * * <p> * Rolling methods instantiate a {@link KnittingCursor} by invoking * {@link #pull(Rook)} and repeatedly invoke the method * {@link KnittingCursor#map(Rook, RookFunction)} typically (but not * necessarily) until the end is reached. The following methods are rolling: * </p> * * <ul> * <li>{@link #collect(Collection)}</li> * <li>{@link #consume(Function)}</li> * <li>{@link #count()}</li> * <li>{@link #equivalentTo(Cursable)}</li> * <li>{@link #equivalentTo(Cursable, Equivalencer)}</li> * <li>{@link #one()}</li> * <li>{@link #optionalOne()}</li> * <li>{@link #reduce(Object, BiFunction)}</li> * <li>{@link #roll()}</li> * </ul> * * * <p> * Transformations are a group of methods that return a new * {@code KnittingCursable} object (or something similar), which provides a new * view of the contents of the wrapped cursable. Transformation methods do not * instantiate cursors at the time of their invocation; they return lazy * wrappers. The following methods are transformations: * </p> * * <ul> * <li>{@link #append(Cursable)}</li> * <li>{@link #asIterator(Rook)}</li> * <li>{@link #asStream(Rook)}</li> * <li>{@link #crop(Predicate)}</li> * <li>{@link #entwine(Cursable, BiFunction)}</li> * <li>{@link #filter(Predicate)}</li> * <li>{@link #flatmapArray(ArrayMap)}</li> * <li>{@link #flatmapCursable(CursableMap)}</li> * <li>{@link #flatmapCursable(CursableRookMap)}</li> * <li>{@link #flatmapCursor(CursorMap)}</li> * <li>{@link #flatmapCursor(CursorRookMap)}</li> * <li>{@link #flatmapIterable(IterableMap)}</li> * <li>{@link #flatmapIterable(IterableRookMap)}</li> * <li>{@link #flatmapIterator(IteratorMap)}</li> * <li>{@link #flatmapIterator(IteratorRookMap)}</li> * <li>{@link #flatmapOptional(OptionalMap)}</li> * <li>{@link #flatmapOptional(OptionalRookMap)}</li> * <li>{@link #flatmapStream(StreamRookMap)}</li> * <li>{@link #head(int, int)}</li> * <li>{@link #headless(int)}</li> * <li>{@link #map(Function)}</li> * <li>{@link #map(RookFunction)}</li> * <li>{@link #numbered()}</li> * <li>{@link #peek(Consumer)}</li> * <li>{@link #prepend(Cursable)}</li> * <li>{@link #purlArray(ArrayPurlFactory)}</li> * <li>{@link #purlCursable(CursablePurlFactory)}</li> * <li>{@link #purlCursable(CursableRookPurlFactory)}</li> * <li>{@link #purlCursor(CursorPurlFactory)}</li> * <li>{@link #purlCursor(CursorRookPurlFactory)}</li> * <li>{@link #purlIterable(IterablePurlFactory)}</li> * <li>{@link #purlIterable(IterableRookPurlFactory)}</li> * <li>{@link #purlIterator(IteratorPurlFactory)}</li> * <li>{@link #purlIterator(IteratorRookPurlFactory)}</li> * <li>{@link #purlOptional(OptionalPurlFactory)}</li> * <li>{@link #purlOptional(OptionalRookPurlFactory)}</li> * <li>{@link #purlStream(StreamRookPurlFactory)}</li> * </ul> * * @param <I> * The type of elements accessible via this cursable. * @see org.github.evenjn.knit * @since 1.0 */ public class KnittingCursable<I> implements Cursable<I> { private final Cursable<I> wrapped; private KnittingCursable(Cursable<I> cursable) { this.wrapped = cursable; } /** * Returns a view of the concatenation of the argument cursable after this * cursable. * * @param tail * A cursable to concatenate after this cursable. * @return A view of the concatenation of the argument cursable after this * cursable. * @since 1.0 */ public KnittingCursable<I> append( final Cursable<? extends I> tail ) { return wrap( new ConcatenateCursable<I>( wrapped, tail ) ); } /** * <p> * Returns a view of this cursable as a {@link java.util.Iterator}. * </p> * * <p> * This is a transformation method. * </p> * * @param rook * A rook. * @return A view of this cursable as a {@link java.util.Iterator}. * @since 1.0 */ public Iterator<I> asIterator( Rook rook ) { return pull( rook ).asIterator( ); } /** * <p> * Returns a view of this cursable as a {@link java.util.stream.Stream}. * </p> * * <p> * This is a transformation method. * </p> * * @param rook * A rook. * @return A view of this cursable as a {@link java.util.stream.Stream}. * @since 1.0 */ public Stream<I> asStream( Rook rook ) { return pull( rook ).asStream( ); } /** * <p> * Adds all elements of this cursable to the argument collection, then returns * it. * </p> * * <p> * The objects collected may be dead. This is due to the fact that cursors do * not guarantee that the objects they return survive subsequent invocations * of {@link org.github.evenjn.yarn.Cursor#next() next()}, or closing the * rook. * </p> * * @param <K> * The type the argument collection. * @param collection * The collection to add elements to. * @return The argument collection. * @since 1.0 */ public <K extends Collection<? super I>> K collect( K collection ) { try ( AutoRook rook = new BasicAutoRook( ) ) { return pull( rook ).collect( collection ); } } /** * <p> * Feeds a consumer with the elements of this cursable. * </p> * * <p> * Obtains a consumer from the argument {@code consumer_provider}, hooking it * to a local, temporary rook. Then, this method obtains a cursor using this * cursable's {@link #pull(Rook)}, hooking it to the same local rook. * </p> * * <p> * Finally, this method invokes that cursor's * {@link org.github.evenjn.yarn.Cursor#next() next()} method, passing each * object obtained this way to the consumer, until the end of the cursor. * </p> * * <p> * This is a rolling method. * </p> * * @param consumer_provider * A system that provides a consumer. * @since 1.0 */ public void consume( RookConsumer<? super I> consumer_provider ) { try ( AutoRook rook = new BasicAutoRook( ) ) { Consumer<? super I> consumer = consumer_provider.get( rook ); pull( rook ).peek( consumer ).roll( ); } } /** * <p> * Returns a cursable where each element is a cursor providing access to a * subsequence of contiguous elements in this cursable that satisfy the * argument {@code stateless_predicate}. * </p> * * @param stateless_predicate * A stateless system that identifies elements that should be kept * together. * @return a cursable where each element is a cursor providing access to a * subsequence of contiguous elements in this cursable that satisfy * the argument {@code stateless_predicate}. * @since 1.0 */ public KnittingCursable<KnittingCursor<I>> crop( Predicate<I> stateless_predicate ) { return KnittingCursable.wrap( h -> pull( h ).crop( stateless_predicate ) ); } /** * <p> * Returns a cursable that traverses this cursable and the argument * {@code other_cursor} in parallel, applying the argument * {@code stateless_bifunction} to each pair of elements, and providing a view * of the result of each application. * </p> * * <p> * The returned cursable provides as many elements as the cursor with the * least elements. * </p> * * <p> * This is a transformation method. * </p> * * @param <R> * The type of elements accessible via the argument cursable. * @param <M> * The type of elements returned by the bifunction. * @param other_cursable * The cursable to roll in parallel to this cursable. * @param stateless_bifunction * The stateless bifunction to apply to each pair of element. * @return a cursable that traverses this cursable and the argument cursable * in parallel, applying the argument bifunction to each pair of * elements, and providing a view of the result of each application. * @since 1.0 */ public <R, M> KnittingCursable<M> entwine( Cursable<R> other_cursable, BiFunction<I, R, M> stateless_bifunction ) { KnittingCursable<I> outer = this; Cursable<M> result = new Cursable<M>( ) { @Override public Cursor<M> pull( Rook rook ) { return outer.pull( rook ).entwine( other_cursable.pull( rook ), stateless_bifunction ); } }; return wrap( result ); } private static <T> boolean equal_null( T first, T second ) { if ( first == null && second == null ) return true; if ( first == null || second == null ) return false; return first.equals( second ); } /** * <p> * Returns true when this cursable and the {@code other} cursable have the * same number of elements, and when each i-th element of this cursable is * equivalent to the i-th element of the {@code other} cursable. Returns false * otherwise. * </p> * * <p> * For the purposes of this method, two {@code null} elements are equivalent. * </p> * * <p> * This is a rolling method. * </p> * * @param other * Another cursable. * @return true when this cursable and the {@code other} cursable have the * same number of elements, and when each i-th element of this * cursable is equivalent to the i-th element of the {@code other} * cursable. False otherwise. * @since 1.0 */ public boolean equivalentTo( Cursable<?> other ) { if ( other == this ) return true; return equivalentTo( other, KnittingCursable::equal_null ); } /** * <p> * Returns true when this cursable and the {@code other} cursable have the * same number of elements, and when each i-th element of this cursable is * equivalent to the i-th element of the {@code other} cursable. Returns false * otherwise. * </p> * * <p> * This is a rolling method. * </p> * * @param other * Another cursable. * @param equivalencer * A function that tells whether two objects are equivalent. * @return true when this cursable and the {@code other} cursable have the * same number of elements, and when each i-th element of this * cursable is equivalent to the i-th element of the {@code other} * cursable. False otherwise. * @since 1.0 */ public <Y> boolean equivalentTo( Cursable<Y> other, Equivalencer<I, Y> equivalencer ) { if ( other == this ) return true; try ( AutoRook rook = new BasicAutoRook( ) ) { KnittingCursor<I> pull1 = this.pull( rook ); KnittingCursor<Y> pull2 = KnittingCursor.wrap( other.pull( rook ) ); for ( ;; ) { boolean hasNext1 = pull1.hasNext( ); boolean hasNext2 = pull2.hasNext( ); if ( hasNext1 != hasNext2 ) { return false; } if ( !hasNext1 ) { return true; } I next1 = pull1.next( ); Y next2 = pull2.next( ); if ( !equivalencer.equivalent( next1, next2 ) ) { return false; } } } catch ( EndOfCursorException e ) { throw new IllegalStateException( e ); } } /** * <p> * Returns a view hiding the elements which do not satisfy the argument * {@code stateless_predicate} in this cursable. * </p> * * <p> * This is a transformation method. * </p> * * @param stateless_predicate * A stateless system that decides to show or hide elements. * @return A view hiding the elements which do not satisfy the argument * {@code stateless_predicate} in this cursable. * @since 1.0 */ public KnittingCursable<I> filter( Predicate<? super I> stateless_predicate ) { return wrap( new Cursable<I>( ) { @Override public Cursor<I> pull( Rook rook ) { return new FilterCursor<>( wrapped.pull( rook ), stateless_predicate ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #flatmapCursor(CursorMap)} except that the view shows elements in * the arrays returned by the argument {@code stateless_array_map}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in the cursors returned by the argument * {@code stateless_array_map}. * @param stateless_array_map * A stateless function that returns arrays. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> flatmapArray( ArrayMap<? super I, O> stateless_array_map ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .flatmapArray( stateless_array_map ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #flatmapCursor(CursorMap)} except that the view shows elements in * the cursables returned by the argument {@code stateless_cursable_map}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in the cursables returned by the argument * {@code stateless_cursable_map}. * @param stateless_cursable_map * A stateless function that returns cursables. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> flatmapCursable( CursableMap<? super I, O> stateless_cursable_map ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .flatmapCursable( rook, stateless_cursable_map ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #flatmapCursor(CursorRookMap)} except that the view shows elements * in the cursables returned by the argument {@code stateless_cursable_map_h}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in the cursables returned by the argument * {@code stateless_cursable_map_h}. * @param stateless_cursable_map_h * A stateless function that returns cursables. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> flatmapCursable( CursableRookMap<? super I, O> stateless_cursable_map_h ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .flatmapCursable( rook, stateless_cursable_map_h ); } } ); } /** * <p> * Each invocation of {@link #pull(Rook)} on the returned * {@code KnittingCursable} pulls a new {@code KnittingCursor} from this * cursable, transforms it using * {@link KnittingCursor#flatmapCursor(CursorMap)} with the argument * {@code stateless_cursor_map}, then returns the resulting cursor. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in the cursors returned by the argument * {@code stateless_cursor_map}. * @param stateless_cursor_map * A stateless function that returns cursors. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> flatmapCursor( CursorMap<? super I, O> stateless_cursor_map ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .flatmapCursor( stateless_cursor_map ); } } ); } /** * <p> * Each invocation of {@link #pull(Rook)} on the returned * {@code KnittingCursable} pulls a new {@code KnittingCursor} from this * cursable, transforms it using * {@link KnittingCursor#flatmapCursor(Rook, CursorRookMap)} with the rook * already available and the argument {@code stateless_cursor_map_h}, then * returns the resulting cursor. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in the cursors returned by the argument * {@code stateless_cursor_map_h}. * @param stateless_cursor_map_h * A stateless function that returns cursors. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> flatmapCursor( CursorRookMap<? super I, O> stateless_cursor_map_h ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .flatmapCursor( rook, stateless_cursor_map_h ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #flatmapCursor(CursorMap)} except that the view shows elements in * the iterables returned by the argument {@code stateless_iterable_map}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in the iterables returned by the argument * {@code stateless_iterable_map}. * @param stateless_iterable_map * A stateless function that returns iterables. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> flatmapIterable( IterableMap<? super I, O> stateless_iterable_map ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .flatmapIterable( stateless_iterable_map ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #flatmapCursor(CursorRookMap)} except that the view shows elements * in the iterables returned by the argument {@code stateless_iterable_map_h}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in the iterables returned by the argument * {@code stateless_iterable_map_h}. * @param stateless_iterable_map_h * A stateless function that returns iterators. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> flatmapIterable( IterableRookMap<? super I, O> stateless_iterable_map_h ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .flatmapIterable( rook, stateless_iterable_map_h ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #flatmapCursor(CursorMap)} except that the view shows elements in * the iterators returned by the argument {@code stateless_iterator_map}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in the iterators returned by the argument * {@code stateless_iterator_map}. * @param stateless_iterator_map * A stateless function that returns iterators. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> flatmapIterator( IteratorMap<? super I, O> stateless_iterator_map ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .flatmapIterator( stateless_iterator_map ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #flatmapCursor(CursorRookMap)} except that the view shows elements * in the iterators returned by the argument {@code stateless_iterator_map_h}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in the iterators returned by the argument * {@code stateless_iterator_map_h}. * @param stateless_iterator_map_h * A stateless function that returns iterators. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> flatmapIterator( IteratorRookMap<? super I, O> stateless_iterator_map_h ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .flatmapIterator( rook, stateless_iterator_map_h ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #flatmapCursor(CursorMap)} except that the view shows elements in * the optionals returned by the argument {@code stateless_optional_map}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in the optionals returned by the argument * {@code stateless_optional_map}. * @param stateless_optional_map * A stateless function that returns optionals. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> flatmapOptional( OptionalMap<? super I, O> stateless_optional_map ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .flatmapOptional( stateless_optional_map ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #flatmapCursor(CursorRookMap)} except that the view shows elements * in the optionals returned by the argument {@code stateless_optional_map_h}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in the optionals returned by the argument * {@code stateless_optional_map_h}. * @param stateless_optional_map_h * A stateless function that returns optionals. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> flatmapOptional( OptionalRookMap<? super I, O> stateless_optional_map_h ) throws IllegalStateException { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .flatmapOptional( rook, stateless_optional_map_h ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #flatmapCursor(CursorRookMap)} except that the view shows elements * in the streams returned by the argument {@code stateless_stream_map_h}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in the streams returned by the argument * {@code stateless_stream_map_h}. * @param stateless_stream_map_h * A stateless function that returns streams. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> flatmapStream( StreamRookMap<? super I, O> stateless_stream_map_h ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .flatmapStream( rook, stateless_stream_map_h ); } } ); } /** * <p> * Returns a view showing the first {@code show} elements of this cursable * visible after hiding the first {@code hide} elements. * </p> * * <p> * The returned view may be empty. This happens when this cursable's size is * smaller than {@code hide}. * </p> * * <p> * The returned view may contain less than {@code show} elements. This happens * when this cursable's size is smaller than {@code hide + show}. * </p> * * <p> * This is a transformation method. * </p> * * @param hide * The number of elements to hide. A negative numbers counts as zero. * @param show * The number of elements to show. A negative numbers counts as zero. * @return A view showing the first {@code show} elements of this cursable * visible after hiding the first {@code hide} elements. * @since 1.0 */ public KnittingCursable<I> head( int hide, int show ) { int final_show = show < 0 ? 0 : show; int final_hide = hide < 0 ? 0 : hide; return wrap( new Cursable<I>( ) { @Override public Cursor<I> pull( Rook rook ) { return Subcursor.sub( wrapped.pull( rook ), final_hide, final_show ); } } ); } /** * <p> * Returns a view hiding the first {@code hide} elements of this cursable. * </p> * * <p> * The returned view may be empty. This happens when this cursable's size is * smaller than {@code hide}. * </p> * * <p> * This is a transformation method. * </p> * * @param hide * The number of elements to hide. A negative numbers counts as zero. * @return A view hiding the first {@code hide} elements of this cursable. * @since 1.0 */ public KnittingCursable<I> headless( int hide ) { int final_hide = hide < 0 ? 0 : hide; return wrap( new Cursable<I>( ) { @Override public Cursor<I> pull( Rook rook ) { return Subcursor.skip( wrapped.pull( rook ), final_hide ); } } ); } /** * <p> * Each invocation of {@link #pull(Rook)} on the returned * {@code KnittingCursable} pulls a new {@code KnittingCursor} from this * cursable, transforms it using {@link KnittingCursor#map(Function)} with the * argument {@code stateless_function}, then returns the resulting cursor. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements returned by the argument * {@code stateless_function}. * @param stateless_function * A stateless function. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> map( Function<? super I, O> stateless_function ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .map( stateless_function ); } } ); } /** * <p> * Each invocation of {@link #pull(Rook)} on the returned * {@code KnittingCursable} pulls a new {@code KnittingCursor} from this * cursable, transforms it using * {@link KnittingCursor#map(Rook, RookFunction)} with the rook already * available and the argument {@code stateless_function_h}, then returns the * resulting cursor. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements returned by the argument * {@code stateless_function_h}. * @param stateless_function_h * A stateless function. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> map( RookFunction<? super I, O> stateless_function_h ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ) .map( rook, stateless_function_h ); } } ); } /** * <p> * Returns a view that, for each element of this cursable, provides a * {@linkplain org.github.evenjn.yarn.Bi pair} containing the element itself * and the number of elements preceding it. * </p> * * <p> * This is a transformation method. * </p> * * @return A view that, for each element of this cursable, provides a * {@linkplain org.github.evenjn.yarn.Bi pair} containing the element * itself and the number of elements preceding it. * @since 1.0 */ public KnittingCursable<Bi<I, Integer>> numbered( ) { return wrap( new Cursable<Bi<I, Integer>>( ) { @Override public Cursor<Bi<I, Integer>> pull( Rook rook ) { return new NumberedCursor<>( wrapped.pull( rook ) ); } } ); } /** * <p> * When this cursable provides access to one element only, this method returns * it. Otherwise, it throws an {@code IllegalStateException}. * </p> * * <p> * The object returned may be dead. This is due to the fact that cursables do * not guarantee that the objects they return survive subsequent invocations * of {@link org.github.evenjn.yarn.Cursor#next() next()} on the cursors they * provide, or closing the rook. * </p> * * <p> * This is a rolling method. * </p> * * @return The only element accessible via this cursable. * @throws IllegalStateException * when it is not the case that there is exactly one element. * @since 1.0 */ public I one( ) { try ( AutoRook rook = new BasicAutoRook( ) ) { return pull( rook ).one( ); } } /** * <p> * When this cursable provides access to one non-null element only, this * method returns it wrapped in an optional. * </p> * * <p> * The object returned may be dead. This is due to the fact that cursables do * not guarantee that the objects they return survive subsequent invocations * of {@link org.github.evenjn.yarn.Cursor#next() next()} on the cursors they * provide, or closing the rook. * </p> * * <p> * When it not the case that there is exactly one element, or when the only * element accessible is {@code null}, this method returns an empty optional. * </p> * * <p> * This is a rolling method. * </p> * * @return The only element accessible via this cursable, if any, or an empty * optional. * @since 1.0 */ public Optional<I> optionalOne( ) { try ( AutoRook rook = new BasicAutoRook( ) ) { return pull( rook ).optionalOne( ); } } /** * <p> * Returns a view providing access to the elements of this cursable. The view * passes the elements to the argument consumer. * </p> * * <p> * For each {@code KnittingCursor} obtained invoking {@link #pull(Rook)} on * the returned {@code KnittingCursable}, at each invocation of * {@link org.github.evenjn.yarn.Cursor#next() next()}, that * {@code KnittingCursor} fetches the next element from the cursor it wraps, * then invokes the consumer using the fetched element as argument, then * returns the fetched element. * </p> * * <p> * This is a transformation method. * </p> * * @param consumer * A consumer that will consume each element retrieved from this * cursor. * @return A view providing access to the elements of this cursable. Before * retuning them, the view passes the elements to the argument * consumer. * @since 1.0 */ public KnittingCursable<I> peek( Consumer<? super I> consumer ) { return wrap( new Cursable<I>( ) { @Override public Cursor<I> pull( Rook rook ) { return new TapCursor<I>( wrapped.pull( rook ), consumer ); } } ); } /** * <p> * Returns a view of the concatenation of the argument cursable before this * cursable. * </p> * * <p> * This is a transformation method. * </p> * * @param head * A cursable to concatenate before this cursable. * @return A view of the concatenation of the argument cursable before this * cursable. * @since 1.0 */ public KnittingCursable<I> prepend( final Cursable<? extends I> head ) { KnittingCursable<I> outer_cursable = this; Cursable<I> result = new Cursable<I>( ) { @Override public Cursor<I> pull( Rook rook ) { return outer_cursable.pull( rook ).prepend( head.pull( rook ) ); } }; return wrap( result ); } /** * <p> * Returns a {@code KnittingCursor} wrapping a cursor obtained from the * wrapped cursable. * </p> * * @param rook * A rook. * @return A {@code KnittingCursor} wrapping a cursor obtained from the * wrapped cursable. * @since 1.0 */ @Override public KnittingCursor<I> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ); } /** * <p> * Returns a view realizing the same transformation as * {@link #purlCursor(CursorPurlFactory)} except that the view shows elements * in arrays returned by {@link ArrayPurl} objects supplied by the argument * {@code factory}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in arrays returned by {@link ArrayPurl} * objects supplied by the argument {@code factory}. * @param factory * A supplier of {@link ArrayPurl} objects. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> purlArray( ArrayPurlFactory<? super I, O> factory ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { Cursor<I> pull = wrapped.pull( rook ); return KnittingCursor.wrap( pull ).purlArray( factory.get( ) ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #purlCursor(CursorPurlFactory)} except that the view shows elements * in cursables returned by {@link CursablePurl} objects supplied by the * argument {@code factory}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in cursables returned by {@link CursablePurl} * objects supplied by the argument {@code factory}. * @param factory * A supplier of {@link CursablePurl} objects. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> purlCursable( CursablePurlFactory<? super I, O> factory ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { Cursor<I> pull = wrapped.pull( rook ); return KnittingCursor.wrap( pull ).purlCursable( factory.get( ) ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #purlCursor(CursorRookPurlFactory)} except that the view shows * elements in arrays returned by {@link CursableRookPurl} objects supplied by * the argument {@code factory}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in cursables returned by * {@link CursableRookPurl} objects supplied by the argument * {@code factory}. * @param factory * A supplier of {@link CursableRookPurl} objects. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> purlCursable( CursableRookPurlFactory<? super I, O> factory ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { Cursor<I> pull = wrapped.pull( rook ); return KnittingCursor.wrap( pull ).purlCursable( rook, factory.get( ) ); } } ); } /** * <p> * Returns a complex view. * </p> * * <p> * Pulling a cursor from the returned cursable returns a purl of a cursor * pulled from this cursable. For an introduction on purling see * {@link org.github.evenjn.yarn.CursorPurl CursorPurl}. * </p> * * <p> * In detail, when the client invokes {@link Cursable#pull(Rook) pull} on the * returned cursable, that cursable pulls a new {@link KnittingCursor} from * this cursable, then it obtains a new {@link CursorPurl} from the argument * factory, and finally returns the cursor obtained by invoking * {@link KnittingCursor#purlCursor(CursorPurl) purlCursor} using the argument * purl. * </p> * * <p> * This is a transformation method. * </p> * * * @param <O> * The type of elements in cursors produced by {@link CursorPurl} * objects supplied by the argument {@code factory}. * * @param factory * A supplier of {@link CursorPurl} objects. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> purlCursor( CursorPurlFactory<? super I, O> factory ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { Cursor<I> pull = wrapped.pull( rook ); return KnittingCursor.wrap( pull ) .purlCursor( factory.get( ) ); } } ); } /** * <p> * Returns a complex view. * </p> * * <p> * Pulling a cursor from the returned cursable returns a purl of a cursor * pulled from this cursable. For an introduction on purling see * {@link org.github.evenjn.yarn.CursorPurl CursorPurl}. * </p> * * <p> * In detail, when the client invokes {@link Cursable#pull(Rook) pull} on the * returned cursable, that cursable pulls a new {@link KnittingCursor} from * this cursable, then it obtains a new {@link CursorRookPurl} from the * argument {@code factory}, and finally returns the cursor obtained by * invoking {@link KnittingCursor#purlCursor(Rook, CursorRookPurl) * purlCursable} using the argument purl. * </p> * * <p> * This is a transformation method. * </p> * * * @param <O> * The type of elements in cursors produced by {@link CursorRookPurl} * objects supplied by the argument {@code factory}. * * @param factory * A supplier of {@link CursorRookPurl} objects. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> purlCursor( CursorRookPurlFactory<? super I, O> factory ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { Cursor<I> pull = wrapped.pull( rook ); return KnittingCursor.wrap( pull ) .purlCursor( rook, factory.get( ) ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #purlCursor(CursorPurlFactory)} except that the view shows elements * in iterables returned by {@link IterablePurl} objects supplied by the * argument {@code factory}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in iterables returned by {@link IterablePurl} * objects supplied by the argument {@code factory}. * @param factory * A supplier of {@link IterablePurl} objects. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> purlIterable( IterablePurlFactory<? super I, O> factory ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { Cursor<I> pull = wrapped.pull( rook ); return KnittingCursor.wrap( pull ).purlIterable( factory.get( ) ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #purlCursor(CursorRookPurlFactory)} except that the view shows * elements in iterables returned by {@link IterableRookPurl} objects supplied * by the argument {@code factory}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in iterables returned by * {@link IterableRookPurl} objects supplied by the argument * {@code factory}. * @param factory * A supplier of {@link IterableRookPurl} objects. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> purlIterable( IterableRookPurlFactory<? super I, O> factory ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { Cursor<I> pull = wrapped.pull( rook ); return KnittingCursor.wrap( pull ).purlIterable( rook, factory.get( ) ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #purlCursor(CursorPurlFactory)} except that the view shows elements * in iterators returned by {@link IteratorPurl} objects supplied by the * argument {@code factory}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in iterators returned by {@link IteratorPurl} * objects supplied by the argument {@code factory}. * @param factory * A supplier of {@link IteratorPurl} objects. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> purlIterator( IteratorPurlFactory<? super I, O> factory ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { Cursor<I> pull = wrapped.pull( rook ); return KnittingCursor.wrap( pull ).purlIterator( factory.get( ) ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #purlCursor(CursorRookPurlFactory)} except that the view shows * elements in iterators returned by {@link IteratorRookPurl} objects supplied * by the argument {@code factory}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in iterators returned by * {@link IteratorRookPurl} objects supplied by the argument * {@code factory}. * @param factory * A supplier of {@link IteratorRookPurl} objects. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> purlIterator( IteratorRookPurlFactory<? super I, O> factory ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { Cursor<I> pull = wrapped.pull( rook ); return KnittingCursor.wrap( pull ).purlIterator( rook, factory.get( ) ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #purlCursor(CursorPurlFactory)} except that the view shows elements * in optionals returned by {@link OptionalPurl} objects supplied by the * argument {@code factory}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in optionals returned by {@link OptionalPurl} * objects supplied by the argument {@code factory}. * @param factory * A supplier of {@link OptionalPurl} objects. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> purlOptional( OptionalPurlFactory<? super I, O> factory ) throws IllegalStateException { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ).purlOptional( factory.get( ) ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #purlCursor(CursorRookPurlFactory)} except that the view shows * elements in optionals returned by {@link OptionalRookPurl} objects supplied * by the argument {@code factory}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in optionals returned by * {@link OptionalRookPurl} objects supplied by the argument * {@code factory}. * @param factory * A supplier of {@link OptionalRookPurl} objects. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> purlOptional( OptionalRookPurlFactory<? super I, O> factory ) throws IllegalStateException { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ).purlOptional( rook, factory.get( ) ); } } ); } /** * <p> * Returns a view realizing the same transformation as * {@link #purlCursor(CursorRookPurlFactory)} except that the view shows * elements in streams returned by {@link StreamRookPurl} objects supplied by * the argument {@code factory}. * </p> * * <p> * This is a transformation method. * </p> * * @param <O> * The type of elements in streams returned by {@link StreamRookPurl} * objects supplied by the argument {@code factory}. * @param factory * A supplier of {@link StreamRookPurl} objects. * @return A complex view. * @since 1.0 */ public <O> KnittingCursable<O> purlStream( StreamRookPurlFactory<? super I, O> factory ) { return wrap( new Cursable<O>( ) { @Override public Cursor<O> pull( Rook rook ) { return KnittingCursor.wrap( wrapped.pull( rook ) ).purlStream( rook, factory.get( ) ); } } ); } /** * <p> * Returns the result of a computation taking into account all the elements of * this cursable. * </p> * * <p> * This method stores into a local variable the argument {@code zero}. Then, * for each element {@code E} in this cursable, this method invokes the * argument {@code bifunction} using the content of the local variable and * {@code E}. At the end of each such invocation, this method stores into the * local variable the result of the invocation. Finally, this method returns * the content of the local variable. * </p> * * <p> * This is a rolling method. * </p> * * @param <K> * The type of argument {@code zero} and of the elements returned by * the argument {@code bifunction}. * @param zero * The initial value for the reduction. * @param bifunction * A bifunction that will be invoked once for each element of this * cursable. * @return the result of a computation taking into account all the elements of * this cursable. * @since 1.0 */ public <K> K reduce( K zero, BiFunction<K, I, K> bifunction ) { K reduction = zero; try ( AutoRook rook = new BasicAutoRook( ) ) { Cursor<I> kc = wrapped.pull( rook ); try { for ( ;; ) { reduction = bifunction.apply( reduction, kc.next( ) ); } } catch ( EndOfCursorException e ) { } return reduction; } } /** * <p> * Pulls a {@code KnittingCursor} from this cursable and invokes * {@link KnittingCursor#roll() roll()} on it. * </p> * * <p> * This is a rolling method. * </p> * * @since 1.0 */ public void roll( ) { try ( AutoRook rook = new BasicAutoRook( ) ) { pull( rook ).roll( ); } } /** * <p> * Counts the number of elements in this cursable. * </p> * * <p> * Pulls a {@code KnittingCursor} from this cursable, invokes * {@link KnittingCursor#count()}, and returns the result of that invocation. * </p> * * <p> * This is a rolling method. * </p> * * @return The number of elements in this cursable. * @since 1.0 */ public int count( ) { try ( AutoRook rook = new BasicAutoRook( ) ) { return pull( rook ).count( ); } } /** * <p> * Returns a view of the last {@code show} elements visible after hiding the * last {@code hide} elements in this cursable. * </p> * * <p> * The returned view may be empty. This happens when this cursable's size is * smaller than {@code hide}. * </p> * * <p> * The returned view may contain less than {@code show} elements. This happens * when this cursable's size is smaller than {@code hide + show}. * </p> * * <p> * This operation relies on {@code size()}. Therefore, it has a one-time * computational time cost linear to the size of this cursable. * </p> * * @param hide * The number of elements to hide. A negative numbers counts as zero. * @param show * The number of elements to show. A negative numbers counts as zero. * @return A view of the last {@code show} elements visible after hiding the * last {@code hide} elements in this cursable. */ @SuppressWarnings("unused") private KnittingCursable<I> tail( int hide, int show ) { int final_show = show < 0 ? 0 : show; int final_hide = hide < 0 ? 0 : hide; int len = count( ) - final_hide; if ( len > final_show ) { len = final_show; } int skip = count( ) - ( final_hide + len ); if ( skip < 0 ) { skip = 0; } int final_len = len; int final_skip = skip; return wrap( new Cursable<I>( ) { @Override public Cursor<I> pull( Rook rook ) { return Subcursor.sub( wrapped.pull( rook ), final_skip, final_len ); } } ); } /** * <p> * Returns a view hiding the last {@code hide} elements in this cursable. * </p> * * <p> * The returned view may be empty. This happens when this cursable's size is * smaller than {@code hide}. * </p> * * <p> * This operation relies on {@code size()}. Therefore, it has a one-time * computational time cost linear to the size of this cursable. * </p> * * @param hide * The number of elements to hide. A negative numbers counts as zero. * @return A view hiding the last {@code hide} elements in this cursable. */ @SuppressWarnings("unused") private KnittingCursable<I> tailless( int hide ) { int final_hide = hide < 0 ? 0 : hide; int len = count( ) - final_hide; if ( len < 0 ) { len = 0; } int final_len = len; return wrap( new Cursable<I>( ) { @Override public Cursor<I> pull( Rook rook ) { return Subcursor.sub( wrapped.pull( rook ), 0, final_len ); } } ); } /** * <p> * Returns an empty cursable. * </p> * * @param <K> * The type of elements in the empty cursable. * @return An empty cursable. * * @since 1.0 */ public static <K> KnittingCursable<K> empty( ) { return private_empty( ); } @SuppressWarnings("unchecked") private static <K> KnittingCursable<K> private_empty( ) { return (KnittingCursable<K>) neo; } private static final KnittingCursable<Void> neo = wrap( new Cursable<Void>( ) { @Override public Cursor<Void> pull( Rook rook ) { return KnittingCursor.empty( ); } } ); /** * <p> * Returns new {@code KnittingCursable} providing access to the argument * elements. * </p> * * @param <K> * The type of the argument elements. * @param elements * Elements to be wrapped in a new {@code KnittingCursable}. * @return A new {@code KnittingCursable} providing access to the argument * elements. * @since 1.0 */ @SafeVarargs public static <K> KnittingCursable<K> on( K ... elements ) { Cursable<K> cursable = new Cursable<K>( ) { @Override public Cursor<K> pull( Rook rook ) { return new ArrayCursor<K>( elements ); } }; return wrap( cursable ); } /** * <p> * Returns a view of the elements in the argument cursable. * </p> * * @param <K> * The type of elements in the argument cursable. * @param cursable * A cursable of elements. * @return A view of the elements in the argument cursable. * @since 1.0 */ public static <K> KnittingCursable<K> wrap( Cursable<K> cursable ) { if ( cursable instanceof KnittingCursable ) { return (KnittingCursable<K>) cursable; } return new KnittingCursable<K>( cursable ); } /** * <p> * Returns a view of the elements in the argument iterable. * </p> * * @param <K> * The type of elements in the argument iterable. * @param iterable * An iterable of elements. * @return A view of the elements in the argument iterable. * @since 1.0 */ public static <K> KnittingCursable<K> wrap( Iterable<K> iterable ) { return wrap( new IterableCursable<K>( iterable ) ); } /** * <p> * Returns a view of the elements in the argument array. * </p> * * @param <K> * The type of elements in the argument array. * @param array * An array of elements. * @return A view of the elements in the argument array. * @since 1.0 */ public static <K> KnittingCursable<K> wrap( K[] array ) { return wrap( new ArrayCursable<K>( array ) ); } }
Renamed PurlFactory to Purler.
src/main/java/org/github/evenjn/knit/KnittingCursable.java
Renamed PurlFactory to Purler.
<ide><path>rc/main/java/org/github/evenjn/knit/KnittingCursable.java <ide> <ide> import org.github.evenjn.yarn.ArrayMap; <ide> import org.github.evenjn.yarn.ArrayPurl; <del>import org.github.evenjn.yarn.ArrayPurlFactory; <add>import org.github.evenjn.yarn.ArrayPurler; <ide> import org.github.evenjn.yarn.AutoRook; <ide> import org.github.evenjn.yarn.Bi; <ide> import org.github.evenjn.yarn.Cursable; <ide> import org.github.evenjn.yarn.CursableMap; <ide> import org.github.evenjn.yarn.CursablePurl; <del>import org.github.evenjn.yarn.CursablePurlFactory; <add>import org.github.evenjn.yarn.CursablePurler; <ide> import org.github.evenjn.yarn.CursableRookMap; <ide> import org.github.evenjn.yarn.CursableRookPurl; <del>import org.github.evenjn.yarn.CursableRookPurlFactory; <add>import org.github.evenjn.yarn.CursableRookPurler; <ide> import org.github.evenjn.yarn.Cursor; <ide> import org.github.evenjn.yarn.CursorMap; <ide> import org.github.evenjn.yarn.CursorPurl; <del>import org.github.evenjn.yarn.CursorPurlFactory; <add>import org.github.evenjn.yarn.CursorPurler; <ide> import org.github.evenjn.yarn.CursorRookMap; <ide> import org.github.evenjn.yarn.CursorRookPurl; <del>import org.github.evenjn.yarn.CursorRookPurlFactory; <add>import org.github.evenjn.yarn.CursorRookPurler; <ide> import org.github.evenjn.yarn.EndOfCursorException; <ide> import org.github.evenjn.yarn.Equivalencer; <ide> import org.github.evenjn.yarn.IterableMap; <ide> import org.github.evenjn.yarn.IterablePurl; <del>import org.github.evenjn.yarn.IterablePurlFactory; <add>import org.github.evenjn.yarn.IterablePurler; <ide> import org.github.evenjn.yarn.IterableRookMap; <ide> import org.github.evenjn.yarn.IterableRookPurl; <del>import org.github.evenjn.yarn.IterableRookPurlFactory; <add>import org.github.evenjn.yarn.IterableRookPurler; <ide> import org.github.evenjn.yarn.IteratorMap; <ide> import org.github.evenjn.yarn.IteratorPurl; <del>import org.github.evenjn.yarn.IteratorPurlFactory; <add>import org.github.evenjn.yarn.IteratorPurler; <ide> import org.github.evenjn.yarn.IteratorRookMap; <ide> import org.github.evenjn.yarn.IteratorRookPurl; <del>import org.github.evenjn.yarn.IteratorRookPurlFactory; <add>import org.github.evenjn.yarn.IteratorRookPurler; <ide> import org.github.evenjn.yarn.OptionalMap; <ide> import org.github.evenjn.yarn.OptionalPurl; <del>import org.github.evenjn.yarn.OptionalPurlFactory; <add>import org.github.evenjn.yarn.OptionalPurler; <ide> import org.github.evenjn.yarn.OptionalRookMap; <ide> import org.github.evenjn.yarn.OptionalRookPurl; <del>import org.github.evenjn.yarn.OptionalRookPurlFactory; <add>import org.github.evenjn.yarn.OptionalRookPurler; <ide> import org.github.evenjn.yarn.Rook; <ide> import org.github.evenjn.yarn.RookConsumer; <ide> import org.github.evenjn.yarn.RookFunction; <ide> import org.github.evenjn.yarn.StreamRookMap; <ide> import org.github.evenjn.yarn.StreamRookPurl; <del>import org.github.evenjn.yarn.StreamRookPurlFactory; <add>import org.github.evenjn.yarn.StreamRookPurler; <ide> <ide> /** <ide> * <ide> * <li>{@link #numbered()}</li> <ide> * <li>{@link #peek(Consumer)}</li> <ide> * <li>{@link #prepend(Cursable)}</li> <del> * <li>{@link #purlArray(ArrayPurlFactory)}</li> <del> * <li>{@link #purlCursable(CursablePurlFactory)}</li> <del> * <li>{@link #purlCursable(CursableRookPurlFactory)}</li> <del> * <li>{@link #purlCursor(CursorPurlFactory)}</li> <del> * <li>{@link #purlCursor(CursorRookPurlFactory)}</li> <del> * <li>{@link #purlIterable(IterablePurlFactory)}</li> <del> * <li>{@link #purlIterable(IterableRookPurlFactory)}</li> <del> * <li>{@link #purlIterator(IteratorPurlFactory)}</li> <del> * <li>{@link #purlIterator(IteratorRookPurlFactory)}</li> <del> * <li>{@link #purlOptional(OptionalPurlFactory)}</li> <del> * <li>{@link #purlOptional(OptionalRookPurlFactory)}</li> <del> * <li>{@link #purlStream(StreamRookPurlFactory)}</li> <add> * <li>{@link #purlArray(ArrayPurler)}</li> <add> * <li>{@link #purlCursable(CursablePurler)}</li> <add> * <li>{@link #purlCursable(CursableRookPurler)}</li> <add> * <li>{@link #purlCursor(CursorPurler)}</li> <add> * <li>{@link #purlCursor(CursorRookPurler)}</li> <add> * <li>{@link #purlIterable(IterablePurler)}</li> <add> * <li>{@link #purlIterable(IterableRookPurler)}</li> <add> * <li>{@link #purlIterator(IteratorPurler)}</li> <add> * <li>{@link #purlIterator(IteratorRookPurler)}</li> <add> * <li>{@link #purlOptional(OptionalPurler)}</li> <add> * <li>{@link #purlOptional(OptionalRookPurler)}</li> <add> * <li>{@link #purlStream(StreamRookPurler)}</li> <ide> * </ul> <ide> * <ide> * @param <I> <ide> /** <ide> * <p> <ide> * Returns a view realizing the same transformation as <del> * {@link #purlCursor(CursorPurlFactory)} except that the view shows elements <add> * {@link #purlCursor(CursorPurler)} except that the view shows elements <ide> * in arrays returned by {@link ArrayPurl} objects supplied by the argument <ide> * {@code factory}. <ide> * </p> <ide> * @since 1.0 <ide> */ <ide> public <O> KnittingCursable<O> <del> purlArray( ArrayPurlFactory<? super I, O> factory ) { <add> purlArray( ArrayPurler<? super I, O> factory ) { <ide> return wrap( new Cursable<O>( ) { <ide> <ide> @Override <ide> /** <ide> * <p> <ide> * Returns a view realizing the same transformation as <del> * {@link #purlCursor(CursorPurlFactory)} except that the view shows elements <add> * {@link #purlCursor(CursorPurler)} except that the view shows elements <ide> * in cursables returned by {@link CursablePurl} objects supplied by the <ide> * argument {@code factory}. <ide> * </p> <ide> * @since 1.0 <ide> */ <ide> public <O> KnittingCursable<O> <del> purlCursable( CursablePurlFactory<? super I, O> factory ) { <add> purlCursable( CursablePurler<? super I, O> factory ) { <ide> return wrap( new Cursable<O>( ) { <ide> <ide> @Override <ide> /** <ide> * <p> <ide> * Returns a view realizing the same transformation as <del> * {@link #purlCursor(CursorRookPurlFactory)} except that the view shows <add> * {@link #purlCursor(CursorRookPurler)} except that the view shows <ide> * elements in arrays returned by {@link CursableRookPurl} objects supplied by <ide> * the argument {@code factory}. <ide> * </p> <ide> * @since 1.0 <ide> */ <ide> public <O> KnittingCursable<O> <del> purlCursable( CursableRookPurlFactory<? super I, O> factory ) { <add> purlCursable( CursableRookPurler<? super I, O> factory ) { <ide> return wrap( new Cursable<O>( ) { <ide> <ide> @Override <ide> * @since 1.0 <ide> */ <ide> public <O> KnittingCursable<O> <del> purlCursor( CursorPurlFactory<? super I, O> factory ) { <add> purlCursor( CursorPurler<? super I, O> factory ) { <ide> return wrap( new Cursable<O>( ) { <ide> <ide> @Override <ide> * @since 1.0 <ide> */ <ide> public <O> KnittingCursable<O> <del> purlCursor( CursorRookPurlFactory<? super I, O> factory ) { <add> purlCursor( CursorRookPurler<? super I, O> factory ) { <ide> return wrap( new Cursable<O>( ) { <ide> <ide> @Override <ide> /** <ide> * <p> <ide> * Returns a view realizing the same transformation as <del> * {@link #purlCursor(CursorPurlFactory)} except that the view shows elements <add> * {@link #purlCursor(CursorPurler)} except that the view shows elements <ide> * in iterables returned by {@link IterablePurl} objects supplied by the <ide> * argument {@code factory}. <ide> * </p> <ide> * @since 1.0 <ide> */ <ide> public <O> KnittingCursable<O> <del> purlIterable( IterablePurlFactory<? super I, O> factory ) { <add> purlIterable( IterablePurler<? super I, O> factory ) { <ide> return wrap( new Cursable<O>( ) { <ide> <ide> @Override <ide> /** <ide> * <p> <ide> * Returns a view realizing the same transformation as <del> * {@link #purlCursor(CursorRookPurlFactory)} except that the view shows <add> * {@link #purlCursor(CursorRookPurler)} except that the view shows <ide> * elements in iterables returned by {@link IterableRookPurl} objects supplied <ide> * by the argument {@code factory}. <ide> * </p> <ide> * @since 1.0 <ide> */ <ide> public <O> KnittingCursable<O> <del> purlIterable( IterableRookPurlFactory<? super I, O> factory ) { <add> purlIterable( IterableRookPurler<? super I, O> factory ) { <ide> return wrap( new Cursable<O>( ) { <ide> <ide> @Override <ide> /** <ide> * <p> <ide> * Returns a view realizing the same transformation as <del> * {@link #purlCursor(CursorPurlFactory)} except that the view shows elements <add> * {@link #purlCursor(CursorPurler)} except that the view shows elements <ide> * in iterators returned by {@link IteratorPurl} objects supplied by the <ide> * argument {@code factory}. <ide> * </p> <ide> * @since 1.0 <ide> */ <ide> public <O> KnittingCursable<O> <del> purlIterator( IteratorPurlFactory<? super I, O> factory ) { <add> purlIterator( IteratorPurler<? super I, O> factory ) { <ide> return wrap( new Cursable<O>( ) { <ide> <ide> @Override <ide> /** <ide> * <p> <ide> * Returns a view realizing the same transformation as <del> * {@link #purlCursor(CursorRookPurlFactory)} except that the view shows <add> * {@link #purlCursor(CursorRookPurler)} except that the view shows <ide> * elements in iterators returned by {@link IteratorRookPurl} objects supplied <ide> * by the argument {@code factory}. <ide> * </p> <ide> * @since 1.0 <ide> */ <ide> public <O> KnittingCursable<O> <del> purlIterator( IteratorRookPurlFactory<? super I, O> factory ) { <add> purlIterator( IteratorRookPurler<? super I, O> factory ) { <ide> return wrap( new Cursable<O>( ) { <ide> <ide> @Override <ide> /** <ide> * <p> <ide> * Returns a view realizing the same transformation as <del> * {@link #purlCursor(CursorPurlFactory)} except that the view shows elements <add> * {@link #purlCursor(CursorPurler)} except that the view shows elements <ide> * in optionals returned by {@link OptionalPurl} objects supplied by the <ide> * argument {@code factory}. <ide> * </p> <ide> * @since 1.0 <ide> */ <ide> public <O> KnittingCursable<O> purlOptional( <del> OptionalPurlFactory<? super I, O> factory ) <add> OptionalPurler<? super I, O> factory ) <ide> throws IllegalStateException { <ide> return wrap( new Cursable<O>( ) { <ide> <ide> /** <ide> * <p> <ide> * Returns a view realizing the same transformation as <del> * {@link #purlCursor(CursorRookPurlFactory)} except that the view shows <add> * {@link #purlCursor(CursorRookPurler)} except that the view shows <ide> * elements in optionals returned by {@link OptionalRookPurl} objects supplied <ide> * by the argument {@code factory}. <ide> * </p> <ide> * @since 1.0 <ide> */ <ide> public <O> KnittingCursable<O> purlOptional( <del> OptionalRookPurlFactory<? super I, O> factory ) <add> OptionalRookPurler<? super I, O> factory ) <ide> throws IllegalStateException { <ide> return wrap( new Cursable<O>( ) { <ide> <ide> /** <ide> * <p> <ide> * Returns a view realizing the same transformation as <del> * {@link #purlCursor(CursorRookPurlFactory)} except that the view shows <add> * {@link #purlCursor(CursorRookPurler)} except that the view shows <ide> * elements in streams returned by {@link StreamRookPurl} objects supplied by <ide> * the argument {@code factory}. <ide> * </p> <ide> * @since 1.0 <ide> */ <ide> public <O> KnittingCursable<O> <del> purlStream( StreamRookPurlFactory<? super I, O> factory ) { <add> purlStream( StreamRookPurler<? super I, O> factory ) { <ide> return wrap( new Cursable<O>( ) { <ide> <ide> @Override
Java
bsd-3-clause
74190520ac31a3d19a5c2063be62fe7be3258ee7
0
memcachier/examples-java
import java.io.IOException; import java.util.Random; import javax.servlet.ServletException; import javax.servlet.http.*; import net.spy.memcached.AddrUtil; import net.spy.memcached.ConnectionFactoryBuilder; import net.spy.memcached.MemcachedClient; import net.spy.memcached.auth.AuthDescriptor; import net.spy.memcached.auth.PlainCallbackHandler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.*; /** * MemCachier (minimal) Java example application. * * @author MemcCachier Inc. */ public class App extends HttpServlet { /** * Respond to a (any) HTTP GET request. */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int digit = (new Random()).nextInt(30); Result r = fib(digit); StringBuilder sb = new StringBuilder(); // static html... sb.append( "<html>\n" + "<head>\n" + "<title>MemCachier Fibonacci Example</title>\n" + "<style type='text/css'>\n" + "html, body { height: 100%; }\n " + "#wrap { min-height: 100%; height: auto !important; height: 100%; margin: 0 auto -60px; }\n" + "#push, #footer { height: 60px; }\n" + "#footer { background-color: #f5f5f5; }\n" + "@media (max-width: 767px) { #footer { margin-left: -20px; margin-right: -20px; padding-left: 20px; padding-right: 20px; }}\n" + ".container { width: auto; max-width: 680px; }\n" + ".container .credit { margin: 20px 0; }\n" + "</style>" + "<link href='//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/" + "css/bootstrap-combined.min.css' rel='stylesheet'>\n" + "<link rel='shortcut icon' href='https://www.memcachier.com/wp-content/uploads/2013/06/favicon.ico'>\n" + "</head>\n" + "<body>\n" + "<div id='wrap'><div class='container'>\n" + "<div class='page-header'><h1>MemCachier Fibonacci Example</h1></div>\n" + "<p class='lead'>This script computes a random digit of the Fibonacci " + "sequence. Before computing, though, it checks to see if " + "there's a cached value for the digit and serves the cached "+ "value if so.</p>\n"); // actual cache / result values... sb.append("<p class='lead'>Digit: <span class='text-info'>" + digit + "</span></p>\n"); sb.append("<p class='lead'>Value: <span class='text-info'>" + r.val + "</span></p>\n"); sb.append("<p class='lead'>Was in cache? <span class='text-info'>" + r.cached + "</span></p>\n"); // static html again... sb.append("</div></div>\n"); sb.append("<div id='footer'><div class='container'>\n" + "<p class='muted credit'>Example by " + "<a href='http://www.memcachier.com'>" + "<img class='brand' src='https://www.memcachier.com/wp-content/uploads/2013/06/memcachier-small.png' alt='MemCachier'" + "title='MemCachier' style='padding-left:8px;padding-right:3px;padding-bottom:3px;'/>" + "MemCachier</a></p></div> </div>"); sb.append("<script src='//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js'></script>"); sb.append("</body></html>"); resp.getWriter().print(sb.toString()); } /** * Start the server. */ public static void main(String[] args) throws Exception { Server server = new Server(Integer.valueOf(System.getenv("PORT"))); ServletContextHandler context = new ServletContextHandler( ServletContextHandler.SESSIONS); context.setContextPath("/"); server.setHandler(context); context.addServlet(new ServletHolder(new App()), "/*"); // ============================== // Connect to MemCachier // ============================== createMemCachierClient(); // ============================== server.start(); server.join(); } /** * A class for storing fibonacci results, indicating if they are cached or not. */ private static class Result { public int val; public boolean cached; public Result(int val, boolean cached) { this.val = val; this.cached = cached; } } // ============================== // Memcachier connection // ============================== private static MemcachedClient mc; // ============================== /** * Create a memcachier connection */ private static void createMemCachierClient() { try { AuthDescriptor ad = new AuthDescriptor( new String[] { "PLAIN" }, new PlainCallbackHandler(System.getenv("MEMCACHIER_USERNAME"), System.getenv("MEMCACHIER_PASSWORD"))); mc = new MemcachedClient( new ConnectionFactoryBuilder().setProtocol( ConnectionFactoryBuilder.Protocol.BINARY).setAuthDescriptor(ad).build(), AddrUtil.getAddresses(System.getenv("MEMCACHIER_SERVERS"))); } catch (Exception ex) { System.err.println( "Couldn't create a connection, bailing out:\nIOException " + ex.getMessage()); } } /** * Computes a fibonacci result of {@code n}, checking the cache for any answers. * * Note: You'd actually want to check the cache on recursive calls, but we * don't do that here for simplicity. */ private static Result fib(int n) { try { Object inCache = mc.get("" + n); if (inCache == null) { return new Result(computeAndSet(n), false); } else { return new Result((Integer) inCache, true); } } catch (Exception e) { // if any exception we simply shutdown the existing one an reconnect. // XXX: This is a very hacky way of dealing with the problem, thought // needs to be put in to your application to handle failures gracefully. mc.shutdown(); createMemCachierClient(); } return new Result(fibRaw(n), false); } /** * Perform fibonacci compuatation and store result in cache. */ private static int computeAndSet(int n) { int val = fibRaw(n); mc.set("" + n, 3600, val); return val; } /** * Perform actual fibonacci compuatation. */ private static int fibRaw(int n) { if (n < 2) { return n; } else { return fibRaw(n - 1) + fibRaw(n - 2); } } } /* vim: set sw=2 ts=2 sts=2 expandtab: */
src/main/java/App.java
import java.io.IOException; import java.util.Random; import javax.servlet.ServletException; import javax.servlet.http.*; import net.spy.memcached.AddrUtil; import net.spy.memcached.ConnectionFactoryBuilder; import net.spy.memcached.MemcachedClient; import net.spy.memcached.auth.AuthDescriptor; import net.spy.memcached.auth.PlainCallbackHandler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.*; /** * MemCachier (minimal) Java example application. * * @author MemcCachier Inc. */ public class App extends HttpServlet { /** * Respond to a (any) HTTP GET request. */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int digit = (new Random()).nextInt(50); Result r = fib(digit); StringBuilder sb = new StringBuilder(); sb.append("<html><head><title>MemCachier Fibonacci Example</title></head><body>"); sb.append("<h1>MemCachier Fibonacci Example</h1>"); sb.append("<p>This script computes a random digit of the Fibonacci " + "sequence. Before computing, though, it checks to see if there's " + "a cached value for the digit and serves the cached value if " + "there's a hit.</p>"); sb.append("<p>Digit: " + digit + "</p>"); sb.append("<p>Value: " + r.val + "</p>"); sb.append("<p>Was in cache? " + r.cached + "</p></body></html>"); resp.getWriter().print(sb.toString()); } /** * Start the server. */ public static void main(String[] args) throws Exception { Server server = new Server(Integer.valueOf(System.getenv("PORT"))); ServletContextHandler context = new ServletContextHandler( ServletContextHandler.SESSIONS); context.setContextPath("/"); server.setHandler(context); context.addServlet(new ServletHolder(new App()), "/*"); // ============================== // Connect to MemCachier // ============================== createMemCachierClient(); // ============================== server.start(); server.join(); } /** * A class for storing fibonacci results, indicating if they are cached or not. */ private static class Result { public int val; public boolean cached; public Result(int val, boolean cached) { this.val = val; this.cached = cached; } } // ============================== // Memcachier connection // ============================== private static MemcachedClient mc; // ============================== /** * Create a memcachier connection */ private static void createMemCachierClient() { try { AuthDescriptor ad = new AuthDescriptor( new String[] { "PLAIN" }, new PlainCallbackHandler(System.getenv("MEMCACHIER_USERNAME"), System.getenv("MEMCACHIER_PASSWORD"))); mc = new MemcachedClient( new ConnectionFactoryBuilder().setProtocol( ConnectionFactoryBuilder.Protocol.BINARY).setAuthDescriptor(ad).build(), AddrUtil.getAddresses(System.getenv("MEMCACHIER_SERVERS"))); } catch (Exception ex) { System.err.println( "Couldn't create a connection, bailing out:\nIOException " + ex.getMessage()); } } /** * Computes a fibonacci result of {@code n}, checking the cache for any answers. * * Note: You'd actually want to check the cache on recursive calls, but we * don't do that here for simplicity. */ private static Result fib(int n) { try { Object inCache = mc.get("" + n); if (inCache == null) { return new Result(computeAndSet(n), false); } else { return new Result((Integer) inCache, true); } } catch (Exception e) { // if any exception we simply shutdown the existing one an reconnect. // XXX: This is a very hacky way of dealing with the problem, thought // needs to be put in to your application to handle failures gracefully. mc.shutdown(); createMemCachierClient(); } return new Result(fibRaw(n), false); } /** * Perform fibonacci compuatation and store result in cache. */ private static int computeAndSet(int n) { int val = fibRaw(n); mc.set("" + n, 3600, val); return val; } /** * Perform actual fibonacci compuatation. */ private static int fibRaw(int n) { if (n < 2) { return n; } else { return fibRaw(n - 1) + fibRaw(n - 2); } } } /* vim: set sw=2 ts=2 sts=2 expandtab: */
update styling
src/main/java/App.java
update styling
<ide><path>rc/main/java/App.java <ide> @Override <ide> protected void doGet(HttpServletRequest req, HttpServletResponse resp) <ide> throws ServletException, IOException { <del> int digit = (new Random()).nextInt(50); <add> int digit = (new Random()).nextInt(30); <ide> Result r = fib(digit); <add> StringBuilder sb = new StringBuilder(); <ide> <del> StringBuilder sb = new StringBuilder(); <del> sb.append("<html><head><title>MemCachier Fibonacci Example</title></head><body>"); <del> sb.append("<h1>MemCachier Fibonacci Example</h1>"); <del> sb.append("<p>This script computes a random digit of the Fibonacci " + <del> "sequence. Before computing, though, it checks to see if there's " + <del> "a cached value for the digit and serves the cached value if " + <del> "there's a hit.</p>"); <del> sb.append("<p>Digit: " + digit + "</p>"); <del> sb.append("<p>Value: " + r.val + "</p>"); <del> sb.append("<p>Was in cache? " + r.cached + "</p></body></html>"); <add> // static html... <add> sb.append( <add> "<html>\n" + <add> "<head>\n" + <add> "<title>MemCachier Fibonacci Example</title>\n" + <add> "<style type='text/css'>\n" + <add> "html, body { height: 100%; }\n " + <add> "#wrap { min-height: 100%; height: auto !important; height: 100%; margin: 0 auto -60px; }\n" + <add> "#push, #footer { height: 60px; }\n" + <add> "#footer { background-color: #f5f5f5; }\n" + <add> "@media (max-width: 767px) { #footer { margin-left: -20px; margin-right: -20px; padding-left: 20px; padding-right: 20px; }}\n" + <add> ".container { width: auto; max-width: 680px; }\n" + <add> ".container .credit { margin: 20px 0; }\n" + <add> "</style>" + <add> "<link href='//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/" + <add> "css/bootstrap-combined.min.css' rel='stylesheet'>\n" + <add> "<link rel='shortcut icon' href='https://www.memcachier.com/wp-content/uploads/2013/06/favicon.ico'>\n" + <add> "</head>\n" + <add> "<body>\n" + <add> "<div id='wrap'><div class='container'>\n" + <add> "<div class='page-header'><h1>MemCachier Fibonacci Example</h1></div>\n" + <add> "<p class='lead'>This script computes a random digit of the Fibonacci " + <add> "sequence. Before computing, though, it checks to see if " + <add> "there's a cached value for the digit and serves the cached "+ <add> "value if so.</p>\n"); <add> <add> // actual cache / result values... <add> sb.append("<p class='lead'>Digit: <span class='text-info'>" + digit + "</span></p>\n"); <add> sb.append("<p class='lead'>Value: <span class='text-info'>" + r.val + "</span></p>\n"); <add> sb.append("<p class='lead'>Was in cache? <span class='text-info'>" + r.cached + "</span></p>\n"); <add> <add> // static html again... <add> sb.append("</div></div>\n"); <add> sb.append("<div id='footer'><div class='container'>\n" + <add> "<p class='muted credit'>Example by " + <add> "<a href='http://www.memcachier.com'>" + <add> "<img class='brand' src='https://www.memcachier.com/wp-content/uploads/2013/06/memcachier-small.png' alt='MemCachier'" + <add> "title='MemCachier' style='padding-left:8px;padding-right:3px;padding-bottom:3px;'/>" + <add> "MemCachier</a></p></div> </div>"); <add> sb.append("<script src='//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js'></script>"); <add> sb.append("</body></html>"); <ide> <ide> resp.getWriter().print(sb.toString()); <ide> }
Java
unlicense
6f2f7adafc662f23b8c946d1c6abd1144a2a1606
0
SkyLandTW/JXTN,AqD/JXTN,SkyLandTW/JXTN
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/> */ package jxtn.core.fmpp; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import fmpp.Engine; import fmpp.dataloaders.XmlDataLoader; /** * 資料庫來源為SQL-Server schema的載入器 * * @author AqD */ public class SqlSchemaDataLoader extends XmlDataLoader { @Override public Object load(Engine engine, @SuppressWarnings("rawtypes") java.util.List args) throws Exception { if (args.size() < 1) { throw new IllegalArgumentException("sql(url[, options]) needs at least 1 parameter."); } String jdbcUrl = (String) args.get(0); Document schemaDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element schemaRoot = schemaDoc.createElement("schema"); schemaDoc.appendChild(schemaRoot); // 載入表格 try (Connection connection = DriverManager.getConnection(jdbcUrl)) { try (PreparedStatement stmt = connection.prepareStatement(" select *, ( select pa.rows from sys.tables ta inner join sys.partitions pa on pa.object_id = ta.object_id inner join sys.schemas sc on ta.schema_id = sc.schema_id where pa.index_id IN (1,0) and sc.name = TABLE_SCHEMA and ta.name = TABLE_NAME ) as TABLE_ROWS from INFORMATION_SCHEMA.TABLES order by TABLE_NAME " )) { try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { String tableName = rs.getString("TABLE_NAME"); Element tableElem = schemaDoc.createElement("table"); tableElem.setAttribute("name", tableName); tableElem.setAttribute("rows", Integer.toString(rs.getInt("TABLE_ROWS"))); schemaRoot.appendChild(tableElem); } } } // 載入欄位 try (PreparedStatement stmt = connection.prepareStatement(" select * from INFORMATION_SCHEMA.COLUMNS order by TABLE_NAME, ORDINAL_POSITION " )) { try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { String tableName = rs.getString("TABLE_NAME"); Element tableElem = schemaRoot.getChildNodes().iterable() .ofType(Element.class) .filter(elem -> elem.getAttribute("name").equals(tableName)) .first(); Element columnElem = schemaDoc.createElement("column"); columnElem.setAttribute("name", rs.getString("COLUMN_NAME")); columnElem.setAttribute("type", rs.getString("DATA_TYPE")); columnElem.setAttribute("nullable", rs.getString("IS_NULLABLE")); tableElem.appendChild(columnElem); } } } // 載入索引 try (PreparedStatement stmt = connection.prepareStatement(" select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE in ('PRIMARY KEY', 'UNIQUE') order by TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_TYPE, CONSTRAINT_NAME " )) { try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { String tableName = rs.getString("TABLE_NAME"); Element tableElem = schemaRoot.getChildNodes().iterable() .ofType(Element.class) .filter(elem -> elem.getNodeName().equals("table") && elem.getAttribute("name").equals(tableName)) .first(); Element keyElem = schemaDoc.createElement("key"); keyElem.setAttribute("name", rs.getString("CONSTRAINT_NAME")); keyElem.setAttribute("type", rs.getString("CONSTRAINT_TYPE")); tableElem.appendChild(keyElem); } } } // 載入索引欄位 try (PreparedStatement stmt = connection.prepareStatement(" select * from INFORMATION_SCHEMA.KEY_COLUMN_USAGE order by TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_NAME, ORDINAL_POSITION " )) { try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { String tableName = rs.getString("TABLE_NAME"); Element tableElem = schemaRoot.getChildNodes().iterable() .ofType(Element.class) .filter(elem -> elem.getNodeName().equals("table") && elem.getAttribute("name").equals(tableName)) .first(); String keyName = rs.getString("CONSTRAINT_NAME"); Element keyElem = tableElem.getChildNodes().iterable() .ofType(Element.class) .filter(elem -> elem.getNodeName().equals("key") && elem.getAttribute("name").equals(keyName)) .firstOrNull(); if (keyElem != null) { String colName = rs.getString("COLUMN_NAME"); Element colElem = tableElem.getChildNodes().iterable() .ofType(Element.class) .filter(elem -> elem.getNodeName().equals("column") && elem.getAttribute("name").equals(colName)) .first(); Element colRefElem = schemaDoc.createElement("colRef"); colRefElem.setAttribute("name", colName); colRefElem.setAttribute("type", colElem.getAttribute("type")); keyElem.appendChild(colRefElem); } } } } } // 排除輔助欄位 for (Node tableNode : schemaRoot.getElementsByTagName("table").iterable()) { Element tableElem = (Element) tableNode; List<Node> columnListCopy = tableElem.getElementsByTagName("column").iterable().toArrayList(); Set<String> columnNameSet = new HashSet<>(); columnListCopy.forEach(cn -> columnNameSet.add(((Element) cn).getAttribute("name"))); for (Node columnNode : columnListCopy) { Element columnElem = (Element) columnNode; String columnName = columnElem.getAttribute("name"); if (columnName.endsWith("WKB") || columnName.endsWith("WKT")) { if (columnNameSet.contains(columnName.substring(0, columnName.length() - 3))) { tableElem.removeChild(columnElem); } } } } System.out.println(schemaRoot.toText()); return this.load(engine, args, schemaDoc); } }
jxtn.core.fmpp/src/jxtn/core/fmpp/SqlSchemaDataLoader.java
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/> */ package jxtn.core.fmpp; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import fmpp.Engine; import fmpp.dataloaders.XmlDataLoader; /** * 資料庫來源為SQL-Server schema的載入器 * * @author AqD */ public class SqlSchemaDataLoader extends XmlDataLoader { @Override public Object load(Engine engine, @SuppressWarnings("rawtypes") java.util.List args) throws Exception { if (args.size() < 1) { throw new IllegalArgumentException("sql(url[, options]) needs at least 1 parameter."); } String jdbcUrl = (String) args.get(0); Document schemaDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element schemaRoot = schemaDoc.createElement("schema"); schemaDoc.appendChild(schemaRoot); // 載入表格 try (Connection connection = DriverManager.getConnection(jdbcUrl)) { try (PreparedStatement stmt = connection.prepareStatement(" select *, ( select pa.rows from sys.tables ta inner join sys.partitions pa on pa.object_id = ta.object_id inner join sys.schemas sc on ta.schema_id = sc.schema_id where pa.index_id IN (1,0) and sc.name = TABLE_SCHEMA and ta.name = TABLE_NAME ) as TABLE_ROWS from INFORMATION_SCHEMA.TABLES order by TABLE_NAME " )) { try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { String tableName = rs.getString("TABLE_NAME"); Element tableElem = schemaDoc.createElement("table"); tableElem.setAttribute("name", tableName); tableElem.setAttribute("rows", Integer.toString(rs.getInt("TABLE_ROWS"))); schemaRoot.appendChild(tableElem); } } } // 載入欄位 try (PreparedStatement stmt = connection.prepareStatement(" select * from INFORMATION_SCHEMA.COLUMNS order by TABLE_NAME, ORDINAL_POSITION " )) { try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { String tableName = rs.getString("TABLE_NAME"); Element tableElem = schemaRoot.getChildNodes().iterable() .ofType(Element.class) .filter(elem -> elem.getAttribute("name").equals(tableName)) .first(); Element columnElem = schemaDoc.createElement("column"); columnElem.setAttribute("name", rs.getString("COLUMN_NAME")); columnElem.setAttribute("type", rs.getString("DATA_TYPE")); columnElem.setAttribute("nullable", rs.getString("IS_NULLABLE")); tableElem.appendChild(columnElem); } } } // 載入索引 try (PreparedStatement stmt = connection.prepareStatement(" select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE in ('PRIMARY KEY', 'UNIQUE') and TABLE_NAME <> 'sysdiagrams' order by TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_TYPE, CONSTRAINT_NAME " )) { try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { String tableName = rs.getString("TABLE_NAME"); Element tableElem = schemaRoot.getChildNodes().iterable() .ofType(Element.class) .filter(elem -> elem.getNodeName().equals("table") && elem.getAttribute("name").equals(tableName)) .first(); Element keyElem = schemaDoc.createElement("key"); keyElem.setAttribute("name", rs.getString("CONSTRAINT_NAME")); keyElem.setAttribute("type", rs.getString("CONSTRAINT_TYPE")); tableElem.appendChild(keyElem); } } } // 載入索引欄位 try (PreparedStatement stmt = connection.prepareStatement(" select * from INFORMATION_SCHEMA.KEY_COLUMN_USAGE order by TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_NAME, ORDINAL_POSITION " )) { try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { String tableName = rs.getString("TABLE_NAME"); Element tableElem = schemaRoot.getChildNodes().iterable() .ofType(Element.class) .filter(elem -> elem.getNodeName().equals("table") && elem.getAttribute("name").equals(tableName)) .first(); String keyName = rs.getString("CONSTRAINT_NAME"); Element keyElem = tableElem.getChildNodes().iterable() .ofType(Element.class) .filter(elem -> elem.getNodeName().equals("key") && elem.getAttribute("name").equals(keyName)) .firstOrNull(); if (keyElem != null) { String colName = rs.getString("COLUMN_NAME"); Element colElem = tableElem.getChildNodes().iterable() .ofType(Element.class) .filter(elem -> elem.getNodeName().equals("column") && elem.getAttribute("name").equals(colName)) .first(); Element colRefElem = schemaDoc.createElement("colRef"); colRefElem.setAttribute("name", colName); colRefElem.setAttribute("type", colElem.getAttribute("type")); keyElem.appendChild(colRefElem); } } } } } // 排除輔助欄位 for (Node tableNode : schemaRoot.getElementsByTagName("table").iterable()) { Element tableElem = (Element) tableNode; List<Node> columnListCopy = tableElem.getElementsByTagName("column").iterable().toArrayList(); Set<String> columnNameSet = new HashSet<>(); columnListCopy.forEach(cn -> columnNameSet.add(((Element) cn).getAttribute("name"))); for (Node columnNode : columnListCopy) { Element columnElem = (Element) columnNode; String columnName = columnElem.getAttribute("name"); if (columnName.endsWith("WKB") || columnName.endsWith("WKT")) { if (columnNameSet.contains(columnName.substring(0, columnName.length() - 3))) { tableElem.removeChild(columnElem); } } } } System.out.println(schemaRoot.toText()); return this.load(engine, args, schemaDoc); } }
SqlSchemaDataLoader.java: cleanup
jxtn.core.fmpp/src/jxtn/core/fmpp/SqlSchemaDataLoader.java
SqlSchemaDataLoader.java: cleanup
<ide><path>xtn.core.fmpp/src/jxtn/core/fmpp/SqlSchemaDataLoader.java <ide> select * <ide> from INFORMATION_SCHEMA.TABLE_CONSTRAINTS <ide> where CONSTRAINT_TYPE in ('PRIMARY KEY', 'UNIQUE') <del> and TABLE_NAME <> 'sysdiagrams' <ide> order by TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_TYPE, CONSTRAINT_NAME <ide> " <ide> ))
Java
apache-2.0
87c1952eef52b0f94b126af14a78ac3edbc8d91e
0
Wechat-Group/WxJava,Wechat-Group/WxJava
package me.chanjar.weixin.cp.api.impl; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; import lombok.NonNull; import lombok.RequiredArgsConstructor; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.common.error.WxRuntimeException; import me.chanjar.weixin.common.util.json.GsonParser; import me.chanjar.weixin.cp.api.WxCpOaService; import me.chanjar.weixin.cp.api.WxCpService; import me.chanjar.weixin.cp.bean.oa.*; import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder; import java.util.Date; import java.util.List; import static me.chanjar.weixin.cp.constant.WxCpApiPathConsts.Oa.*; /** * 企业微信 OA 接口实现 * * @author Element * @date 2019-04-06 11:20 */ @RequiredArgsConstructor public class WxCpOaServiceImpl implements WxCpOaService { private final WxCpService mainService; private static final int MONTH_SECONDS = 30 * 24 * 60 * 60; private static final int USER_IDS_LIMIT = 100; @Override public String apply(WxCpOaApplyEventRequest request) throws WxErrorException { String responseContent = this.mainService.post(this.mainService.getWxCpConfigStorage().getApiUrl(APPLY_EVENT), request.toJson()); return GsonParser.parse(responseContent).get("sp_no").getAsString(); } @Override public List<WxCpCheckinData> getCheckinData(Integer openCheckinDataType, Date startTime, Date endTime, List<String> userIdList) throws WxErrorException { if (startTime == null || endTime == null) { throw new WxRuntimeException("starttime and endtime can't be null"); } if (userIdList == null || userIdList.size() > USER_IDS_LIMIT) { throw new WxRuntimeException("用户列表不能为空,不超过 " + USER_IDS_LIMIT + " 个,若用户超过 " + USER_IDS_LIMIT + " 个,请分批获取"); } long endTimestamp = endTime.getTime() / 1000L; long startTimestamp = startTime.getTime() / 1000L; if (endTimestamp - startTimestamp < 0 || endTimestamp - startTimestamp >= MONTH_SECONDS * 1000L) { throw new WxRuntimeException("获取记录时间跨度不超过一个月"); } JsonObject jsonObject = new JsonObject(); JsonArray jsonArray = new JsonArray(); jsonObject.addProperty("opencheckindatatype", openCheckinDataType); jsonObject.addProperty("starttime", startTimestamp); jsonObject.addProperty("endtime", endTimestamp); for (String userid : userIdList) { jsonArray.add(userid); } jsonObject.add("useridlist", jsonArray); final String url = this.mainService.getWxCpConfigStorage().getApiUrl(GET_CHECKIN_DATA); String responseContent = this.mainService.post(url, jsonObject.toString()); JsonObject tmpJson = GsonParser.parse(responseContent); return WxCpGsonBuilder.create() .fromJson( tmpJson.get("checkindata"), new TypeToken<List<WxCpCheckinData>>() { }.getType() ); } @Override public List<WxCpCheckinOption> getCheckinOption(Date datetime, List<String> userIdList) throws WxErrorException { if (datetime == null) { throw new WxRuntimeException("datetime can't be null"); } if (userIdList == null || userIdList.size() > USER_IDS_LIMIT) { throw new WxRuntimeException("用户列表不能为空,不超过 " + USER_IDS_LIMIT + " 个,若用户超过 " + USER_IDS_LIMIT + " 个,请分批获取"); } JsonArray jsonArray = new JsonArray(); for (String userid : userIdList) { jsonArray.add(userid); } JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("datetime", datetime.getTime() / 1000L); jsonObject.add("useridlist", jsonArray); final String url = this.mainService.getWxCpConfigStorage().getApiUrl(GET_CHECKIN_OPTION); String responseContent = this.mainService.post(url, jsonObject.toString()); JsonObject tmpJson = GsonParser.parse(responseContent); return WxCpGsonBuilder.create() .fromJson( tmpJson.get("info"), new TypeToken<List<WxCpCheckinOption>>() { }.getType() ); } @Override public List<WxCpCropCheckinOption> getCropCheckinOption() throws WxErrorException { JsonObject jsonObject = new JsonObject(); final String url = this.mainService.getWxCpConfigStorage().getApiUrl(GET_CORP_CHECKIN_OPTION); String responseContent = this.mainService.post(url, jsonObject.toString()); JsonObject tmpJson = GsonParser.parse(responseContent); return WxCpGsonBuilder.create() .fromJson( tmpJson.get("group"), new TypeToken<List<WxCpCropCheckinOption>>() { }.getType() ); } @Override public WxCpApprovalInfo getApprovalInfo(@NonNull Date startTime, @NonNull Date endTime, Integer cursor, Integer size, List<WxCpApprovalInfoQueryFilter> filters) throws WxErrorException { if (cursor == null) { cursor = 0; } if (size == null) { size = 100; } if (size < 0 || size > 100) { throw new IllegalArgumentException("size参数错误,请使用[1-100]填充,默认100"); } JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("starttime", startTime.getTime() / 1000L); jsonObject.addProperty("endtime", endTime.getTime() / 1000L); jsonObject.addProperty("size", size); jsonObject.addProperty("cursor", cursor); if (filters != null && !filters.isEmpty()) { JsonArray filterJsonArray = new JsonArray(); for (WxCpApprovalInfoQueryFilter filter : filters) { filterJsonArray.add(new JsonParser().parse(filter.toJson())); } jsonObject.add("filters", filterJsonArray); } final String url = this.mainService.getWxCpConfigStorage().getApiUrl(GET_APPROVAL_INFO); String responseContent = this.mainService.post(url, jsonObject.toString()); return WxCpGsonBuilder.create().fromJson(responseContent, WxCpApprovalInfo.class); } @Override public WxCpApprovalInfo getApprovalInfo(@NonNull Date startTime, @NonNull Date endTime) throws WxErrorException { return this.getApprovalInfo(startTime, endTime, null, null, null); } @Override public WxCpApprovalDetailResult getApprovalDetail(@NonNull String spNo) throws WxErrorException { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("sp_no", spNo); final String url = this.mainService.getWxCpConfigStorage().getApiUrl(GET_APPROVAL_DETAIL); String responseContent = this.mainService.post(url, jsonObject.toString()); return WxCpGsonBuilder.create().fromJson(responseContent, WxCpApprovalDetailResult.class); } @Override public List<WxCpDialRecord> getDialRecord(Date startTime, Date endTime, Integer offset, Integer limit) throws WxErrorException { JsonObject jsonObject = new JsonObject(); if (offset == null) { offset = 0; } if (limit == null || limit <= 0) { limit = 100; } jsonObject.addProperty("offset", offset); jsonObject.addProperty("limit", limit); if (startTime != null && endTime != null) { long endtimestamp = endTime.getTime() / 1000L; long starttimestamp = startTime.getTime() / 1000L; if (endtimestamp - starttimestamp < 0 || endtimestamp - starttimestamp >= MONTH_SECONDS) { throw new WxRuntimeException("受限于网络传输,起止时间的最大跨度为30天,如超过30天,则以结束时间为基准向前取30天进行查询"); } jsonObject.addProperty("start_time", starttimestamp); jsonObject.addProperty("end_time", endtimestamp); } final String url = this.mainService.getWxCpConfigStorage().getApiUrl(GET_DIAL_RECORD); String responseContent = this.mainService.post(url, jsonObject.toString()); JsonObject tmpJson = GsonParser.parse(responseContent); return WxCpGsonBuilder.create().fromJson(tmpJson.get("record"), new TypeToken<List<WxCpDialRecord>>() { }.getType() ); } @Override public WxCpTemplateResult getTemplateDetail(@NonNull String templateId) throws WxErrorException { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("template_id", templateId); final String url = this.mainService.getWxCpConfigStorage().getApiUrl(GET_TEMPLATE_DETAIL); String responseContent = this.mainService.post(url, jsonObject.toString()); return WxCpGsonBuilder.create().fromJson(responseContent, WxCpTemplateResult.class); } @Override public List<WxCpCheckinDayData> getCheckinDayData(Date startTime, Date endTime, List<String> userIdList) throws WxErrorException { if (startTime == null || endTime == null) { throw new WxRuntimeException("starttime and endtime can't be null"); } if (userIdList == null || userIdList.size() > USER_IDS_LIMIT) { throw new WxRuntimeException("用户列表不能为空,不超过 " + USER_IDS_LIMIT + " 个,若用户超过 " + USER_IDS_LIMIT + " 个,请分批获取"); } long endTimestamp = endTime.getTime() / 1000L; long startTimestamp = startTime.getTime() / 1000L; JsonObject jsonObject = new JsonObject(); JsonArray jsonArray = new JsonArray(); jsonObject.addProperty("starttime", startTimestamp); jsonObject.addProperty("endtime", endTimestamp); for (String userid : userIdList) { jsonArray.add(userid); } jsonObject.add("useridlist", jsonArray); final String url = this.mainService.getWxCpConfigStorage().getApiUrl(GET_CHECKIN_DAY_DATA); String responseContent = this.mainService.post(url, jsonObject.toString()); JsonObject tmpJson = GsonParser.parse(responseContent); return WxCpGsonBuilder.create() .fromJson( tmpJson.get("datas"), new TypeToken<List<WxCpCheckinDayData>>() { }.getType() ); } @Override public List<WxCpCheckinMonthData> getCheckinMonthData(Date startTime, Date endTime, List<String> userIdList) throws WxErrorException { if (startTime == null || endTime == null) { throw new WxRuntimeException("starttime and endtime can't be null"); } if (userIdList == null || userIdList.size() > USER_IDS_LIMIT) { throw new WxRuntimeException("用户列表不能为空,不超过 " + USER_IDS_LIMIT + " 个,若用户超过 " + USER_IDS_LIMIT + " 个,请分批获取"); } long endTimestamp = endTime.getTime() / 1000L; long startTimestamp = startTime.getTime() / 1000L; JsonObject jsonObject = new JsonObject(); JsonArray jsonArray = new JsonArray(); jsonObject.addProperty("starttime", startTimestamp); jsonObject.addProperty("endtime", endTimestamp); for (String userid : userIdList) { jsonArray.add(userid); } jsonObject.add("useridlist", jsonArray); final String url = this.mainService.getWxCpConfigStorage().getApiUrl(GET_CHECKIN_MONTH_DATA); String responseContent = this.mainService.post(url, jsonObject.toString()); JsonObject tmpJson = GsonParser.parse(responseContent); return WxCpGsonBuilder.create() .fromJson( tmpJson.get("datas"), new TypeToken<List<WxCpCheckinMonthData>>() { }.getType() ); } @Override public List<WxCpCheckinSchedule> getCheckinScheduleList(Date startTime, Date endTime, List<String> userIdList) throws WxErrorException { if (startTime == null || endTime == null) { throw new WxRuntimeException("starttime and endtime can't be null"); } if (userIdList == null || userIdList.size() > USER_IDS_LIMIT) { throw new WxRuntimeException("用户列表不能为空,不超过 " + USER_IDS_LIMIT + " 个,若用户超过 " + USER_IDS_LIMIT + " 个,请分批获取"); } long endTimestamp = endTime.getTime() / 1000L; long startTimestamp = startTime.getTime() / 1000L; JsonObject jsonObject = new JsonObject(); JsonArray jsonArray = new JsonArray(); jsonObject.addProperty("starttime", startTimestamp); jsonObject.addProperty("endtime", endTimestamp); for (String userid : userIdList) { jsonArray.add(userid); } jsonObject.add("useridlist", jsonArray); final String url = this.mainService.getWxCpConfigStorage().getApiUrl(GET_CHECKIN_SCHEDULE_DATA); String responseContent = this.mainService.post(url, jsonObject.toString()); JsonObject tmpJson = GsonParser.parse(responseContent); return WxCpGsonBuilder.create() .fromJson( tmpJson.get("schedule_list"), new TypeToken<List<WxCpCheckinSchedule>>() { }.getType() ); } @Override public void setCheckinScheduleList(WxCpSetCheckinSchedule wxCpSetCheckinSchedule) throws WxErrorException { final String url = this.mainService.getWxCpConfigStorage().getApiUrl(SET_CHECKIN_SCHEDULE_DATA); this.mainService.post(url, WxCpGsonBuilder.create().toJson(wxCpSetCheckinSchedule)); } }
weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/impl/WxCpOaServiceImpl.java
package me.chanjar.weixin.cp.api.impl; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; import lombok.NonNull; import lombok.RequiredArgsConstructor; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.common.error.WxRuntimeException; import me.chanjar.weixin.common.util.json.GsonParser; import me.chanjar.weixin.cp.api.WxCpOaService; import me.chanjar.weixin.cp.api.WxCpService; import me.chanjar.weixin.cp.bean.oa.*; import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder; import java.util.Date; import java.util.List; import static me.chanjar.weixin.cp.constant.WxCpApiPathConsts.Oa.*; /** * 企业微信 OA 接口实现 * * @author Element * @date 2019-04-06 11:20 */ @RequiredArgsConstructor public class WxCpOaServiceImpl implements WxCpOaService { private final WxCpService mainService; private static final int MONTH_SECONDS = 30 * 24 * 60 * 60; private static final int USER_IDS_LIMIT = 100; @Override public String apply(WxCpOaApplyEventRequest request) throws WxErrorException { String responseContent = this.mainService.post(this.mainService.getWxCpConfigStorage().getApiUrl(APPLY_EVENT), request.toJson()); return GsonParser.parse(responseContent).get("sp_no").getAsString(); } @Override public List<WxCpCheckinData> getCheckinData(Integer openCheckinDataType, Date startTime, Date endTime, List<String> userIdList) throws WxErrorException { if (startTime == null || endTime == null) { throw new WxRuntimeException("starttime and endtime can't be null"); } if (userIdList == null || userIdList.size() > USER_IDS_LIMIT) { throw new WxRuntimeException("用户列表不能为空,不超过 " + USER_IDS_LIMIT + " 个,若用户超过 " + USER_IDS_LIMIT + " 个,请分批获取"); } long endTimestamp = endTime.getTime() / 1000L; long startTimestamp = startTime.getTime() / 1000L; if (endTimestamp - startTimestamp < 0 || endTimestamp - startTimestamp >= MONTH_SECONDS) { throw new WxRuntimeException("获取记录时间跨度不超过一个月"); } JsonObject jsonObject = new JsonObject(); JsonArray jsonArray = new JsonArray(); jsonObject.addProperty("opencheckindatatype", openCheckinDataType); jsonObject.addProperty("starttime", startTimestamp); jsonObject.addProperty("endtime", endTimestamp); for (String userid : userIdList) { jsonArray.add(userid); } jsonObject.add("useridlist", jsonArray); final String url = this.mainService.getWxCpConfigStorage().getApiUrl(GET_CHECKIN_DATA); String responseContent = this.mainService.post(url, jsonObject.toString()); JsonObject tmpJson = GsonParser.parse(responseContent); return WxCpGsonBuilder.create() .fromJson( tmpJson.get("checkindata"), new TypeToken<List<WxCpCheckinData>>() { }.getType() ); } @Override public List<WxCpCheckinOption> getCheckinOption(Date datetime, List<String> userIdList) throws WxErrorException { if (datetime == null) { throw new WxRuntimeException("datetime can't be null"); } if (userIdList == null || userIdList.size() > USER_IDS_LIMIT) { throw new WxRuntimeException("用户列表不能为空,不超过 " + USER_IDS_LIMIT + " 个,若用户超过 " + USER_IDS_LIMIT + " 个,请分批获取"); } JsonArray jsonArray = new JsonArray(); for (String userid : userIdList) { jsonArray.add(userid); } JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("datetime", datetime.getTime() / 1000L); jsonObject.add("useridlist", jsonArray); final String url = this.mainService.getWxCpConfigStorage().getApiUrl(GET_CHECKIN_OPTION); String responseContent = this.mainService.post(url, jsonObject.toString()); JsonObject tmpJson = GsonParser.parse(responseContent); return WxCpGsonBuilder.create() .fromJson( tmpJson.get("info"), new TypeToken<List<WxCpCheckinOption>>() { }.getType() ); } @Override public List<WxCpCropCheckinOption> getCropCheckinOption() throws WxErrorException { JsonObject jsonObject = new JsonObject(); final String url = this.mainService.getWxCpConfigStorage().getApiUrl(GET_CORP_CHECKIN_OPTION); String responseContent = this.mainService.post(url, jsonObject.toString()); JsonObject tmpJson = GsonParser.parse(responseContent); return WxCpGsonBuilder.create() .fromJson( tmpJson.get("group"), new TypeToken<List<WxCpCropCheckinOption>>() { }.getType() ); } @Override public WxCpApprovalInfo getApprovalInfo(@NonNull Date startTime, @NonNull Date endTime, Integer cursor, Integer size, List<WxCpApprovalInfoQueryFilter> filters) throws WxErrorException { if (cursor == null) { cursor = 0; } if (size == null) { size = 100; } if (size < 0 || size > 100) { throw new IllegalArgumentException("size参数错误,请使用[1-100]填充,默认100"); } JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("starttime", startTime.getTime() / 1000L); jsonObject.addProperty("endtime", endTime.getTime() / 1000L); jsonObject.addProperty("size", size); jsonObject.addProperty("cursor", cursor); if (filters != null && !filters.isEmpty()) { JsonArray filterJsonArray = new JsonArray(); for (WxCpApprovalInfoQueryFilter filter : filters) { filterJsonArray.add(new JsonParser().parse(filter.toJson())); } jsonObject.add("filters", filterJsonArray); } final String url = this.mainService.getWxCpConfigStorage().getApiUrl(GET_APPROVAL_INFO); String responseContent = this.mainService.post(url, jsonObject.toString()); return WxCpGsonBuilder.create().fromJson(responseContent, WxCpApprovalInfo.class); } @Override public WxCpApprovalInfo getApprovalInfo(@NonNull Date startTime, @NonNull Date endTime) throws WxErrorException { return this.getApprovalInfo(startTime, endTime, null, null, null); } @Override public WxCpApprovalDetailResult getApprovalDetail(@NonNull String spNo) throws WxErrorException { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("sp_no", spNo); final String url = this.mainService.getWxCpConfigStorage().getApiUrl(GET_APPROVAL_DETAIL); String responseContent = this.mainService.post(url, jsonObject.toString()); return WxCpGsonBuilder.create().fromJson(responseContent, WxCpApprovalDetailResult.class); } @Override public List<WxCpDialRecord> getDialRecord(Date startTime, Date endTime, Integer offset, Integer limit) throws WxErrorException { JsonObject jsonObject = new JsonObject(); if (offset == null) { offset = 0; } if (limit == null || limit <= 0) { limit = 100; } jsonObject.addProperty("offset", offset); jsonObject.addProperty("limit", limit); if (startTime != null && endTime != null) { long endtimestamp = endTime.getTime() / 1000L; long starttimestamp = startTime.getTime() / 1000L; if (endtimestamp - starttimestamp < 0 || endtimestamp - starttimestamp >= MONTH_SECONDS) { throw new WxRuntimeException("受限于网络传输,起止时间的最大跨度为30天,如超过30天,则以结束时间为基准向前取30天进行查询"); } jsonObject.addProperty("start_time", starttimestamp); jsonObject.addProperty("end_time", endtimestamp); } final String url = this.mainService.getWxCpConfigStorage().getApiUrl(GET_DIAL_RECORD); String responseContent = this.mainService.post(url, jsonObject.toString()); JsonObject tmpJson = GsonParser.parse(responseContent); return WxCpGsonBuilder.create().fromJson(tmpJson.get("record"), new TypeToken<List<WxCpDialRecord>>() { }.getType() ); } @Override public WxCpTemplateResult getTemplateDetail(@NonNull String templateId) throws WxErrorException { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("template_id", templateId); final String url = this.mainService.getWxCpConfigStorage().getApiUrl(GET_TEMPLATE_DETAIL); String responseContent = this.mainService.post(url, jsonObject.toString()); return WxCpGsonBuilder.create().fromJson(responseContent, WxCpTemplateResult.class); } @Override public List<WxCpCheckinDayData> getCheckinDayData(Date startTime, Date endTime, List<String> userIdList) throws WxErrorException { if (startTime == null || endTime == null) { throw new WxRuntimeException("starttime and endtime can't be null"); } if (userIdList == null || userIdList.size() > USER_IDS_LIMIT) { throw new WxRuntimeException("用户列表不能为空,不超过 " + USER_IDS_LIMIT + " 个,若用户超过 " + USER_IDS_LIMIT + " 个,请分批获取"); } long endTimestamp = endTime.getTime() / 1000L; long startTimestamp = startTime.getTime() / 1000L; JsonObject jsonObject = new JsonObject(); JsonArray jsonArray = new JsonArray(); jsonObject.addProperty("starttime", startTimestamp); jsonObject.addProperty("endtime", endTimestamp); for (String userid : userIdList) { jsonArray.add(userid); } jsonObject.add("useridlist", jsonArray); final String url = this.mainService.getWxCpConfigStorage().getApiUrl(GET_CHECKIN_DAY_DATA); String responseContent = this.mainService.post(url, jsonObject.toString()); JsonObject tmpJson = GsonParser.parse(responseContent); return WxCpGsonBuilder.create() .fromJson( tmpJson.get("datas"), new TypeToken<List<WxCpCheckinDayData>>() { }.getType() ); } @Override public List<WxCpCheckinMonthData> getCheckinMonthData(Date startTime, Date endTime, List<String> userIdList) throws WxErrorException { if (startTime == null || endTime == null) { throw new WxRuntimeException("starttime and endtime can't be null"); } if (userIdList == null || userIdList.size() > USER_IDS_LIMIT) { throw new WxRuntimeException("用户列表不能为空,不超过 " + USER_IDS_LIMIT + " 个,若用户超过 " + USER_IDS_LIMIT + " 个,请分批获取"); } long endTimestamp = endTime.getTime() / 1000L; long startTimestamp = startTime.getTime() / 1000L; JsonObject jsonObject = new JsonObject(); JsonArray jsonArray = new JsonArray(); jsonObject.addProperty("starttime", startTimestamp); jsonObject.addProperty("endtime", endTimestamp); for (String userid : userIdList) { jsonArray.add(userid); } jsonObject.add("useridlist", jsonArray); final String url = this.mainService.getWxCpConfigStorage().getApiUrl(GET_CHECKIN_MONTH_DATA); String responseContent = this.mainService.post(url, jsonObject.toString()); JsonObject tmpJson = GsonParser.parse(responseContent); return WxCpGsonBuilder.create() .fromJson( tmpJson.get("datas"), new TypeToken<List<WxCpCheckinMonthData>>() { }.getType() ); } @Override public List<WxCpCheckinSchedule> getCheckinScheduleList(Date startTime, Date endTime, List<String> userIdList) throws WxErrorException { if (startTime == null || endTime == null) { throw new WxRuntimeException("starttime and endtime can't be null"); } if (userIdList == null || userIdList.size() > USER_IDS_LIMIT) { throw new WxRuntimeException("用户列表不能为空,不超过 " + USER_IDS_LIMIT + " 个,若用户超过 " + USER_IDS_LIMIT + " 个,请分批获取"); } long endTimestamp = endTime.getTime() / 1000L; long startTimestamp = startTime.getTime() / 1000L; JsonObject jsonObject = new JsonObject(); JsonArray jsonArray = new JsonArray(); jsonObject.addProperty("starttime", startTimestamp); jsonObject.addProperty("endtime", endTimestamp); for (String userid : userIdList) { jsonArray.add(userid); } jsonObject.add("useridlist", jsonArray); final String url = this.mainService.getWxCpConfigStorage().getApiUrl(GET_CHECKIN_SCHEDULE_DATA); String responseContent = this.mainService.post(url, jsonObject.toString()); JsonObject tmpJson = GsonParser.parse(responseContent); return WxCpGsonBuilder.create() .fromJson( tmpJson.get("schedule_list"), new TypeToken<List<WxCpCheckinSchedule>>() { }.getType() ); } @Override public void setCheckinScheduleList(WxCpSetCheckinSchedule wxCpSetCheckinSchedule) throws WxErrorException { final String url = this.mainService.getWxCpConfigStorage().getApiUrl(SET_CHECKIN_SCHEDULE_DATA); this.mainService.post(url, WxCpGsonBuilder.create().toJson(wxCpSetCheckinSchedule)); } }
:bug: #2235 【企业微信】 修复获取打卡数据时间检查不正确的问题
weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/impl/WxCpOaServiceImpl.java
:bug: #2235 【企业微信】 修复获取打卡数据时间检查不正确的问题
<ide><path>eixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/impl/WxCpOaServiceImpl.java <ide> long endTimestamp = endTime.getTime() / 1000L; <ide> long startTimestamp = startTime.getTime() / 1000L; <ide> <del> if (endTimestamp - startTimestamp < 0 || endTimestamp - startTimestamp >= MONTH_SECONDS) { <add> if (endTimestamp - startTimestamp < 0 || endTimestamp - startTimestamp >= MONTH_SECONDS * 1000L) { <ide> throw new WxRuntimeException("获取记录时间跨度不超过一个月"); <ide> } <ide>
JavaScript
bsd-3-clause
62779418d998001d10e5320d20bdd3383ecdb2a4
0
oysnet/czagenda-api,oysnet/czagenda-api,oysnet/czagenda-api
var RestOAuthModel = require('./oAuthModel.js').RestOAuthModel; var statusCode = require('../statusCodes.js'); var util = require("util"); var models = require('../../models'); var ElasticSearchClient = require('elasticsearchclient'); var settings = require('../../settings.js'); var elasticSearchClient = new ElasticSearchClient(settings.elasticsearch); var restError = require('./errors'); var log = require('czagenda-log').from(__filename); var models = require('../../models'); var async = require('async'); var statusCodes = require('../statusCodes'); var mModelSearch = require('./mModelSearch'); var Lock = require('../lock'); var RestEvent = exports.RestEvent = function(server) { RestOAuthModel.call(this, 'event', models.Event, server); this._urls.get[this._urlPrefix + '/:id/perms/wu'] = { fn : this.permsUserWrite }; this._urls.get[this._urlPrefix + '/:id/perms/wg'] = { fn : this.permsGroupWrite }; this._urls.get[this._urlPrefix + '/:id/perms/ru'] = { fn : this.permsUserRead }; this._urls.get[this._urlPrefix + '/:id/perms/rg'] = { fn : this.permsGroupRead }; this._urls.post[this._urlPrefix + '/:id/moderate/approve'] = { fn : this.addApprove }; this._urls.post[this._urlPrefix + '/:id/moderate/disapprove'] = { fn : this.addDisapprove }; this._urls.del[this._urlPrefix + '/:id/moderate/approve'] = { fn : this.delApprove }; this._urls.del[this._urlPrefix + '/:id/moderate/disapprove'] = { fn : this.delDisapprove }; this._urls.get[this._urlPrefix + '/_search'] = { fn : this.search }; this._urls.post[this._urlPrefix + '/_search'] = { fn : this.search }; this._urls.put[this._urlPrefix + '/:id'].middleware.push(this.requireParentLock.bind(this)) this._urls.post[this._urlPrefix].middleware.push(this.requireParentLock.bind(this)) this._initServer(); } util.inherits(RestEvent, RestOAuthModel); for(k in mModelSearch) { RestEvent.prototype[k] = mModelSearch[k]; } RestEvent.prototype.searchFields = { 'agenda' : 'term', 'author' : 'term', 'createDate' : 'datetime', 'updateDate' : 'datetime', 'approvedBy' : 'term', 'disapprovedBy' : 'term', 'event.title' : 'text', 'event.content' : 'text', 'event.eventStatus' : 'term', 'event.when.startTime' : 'datetime', 'event.when.endTime' : 'datetime', 'event.where.city' : 'text', 'event.where.country' : 'text', 'event.where.admin_level_2' : 'text', 'event.where.admin_level_3' : 'text', 'event.where.geoPt' : 'geo', 'event.who.href' : 'term' } RestEvent.prototype.sortFields = { 'createDate' : 'createDate', 'updateDate' : 'updateDate', 'event.title' : 'event.title.untouched', 'event.when.startTime' : 'datetime', 'event.when.endTime' : 'datetime', 'distance' : 'distance' } RestEvent.prototype.requireParentLock = function(req, res, next) { if( typeof (req.body.event) !== 'undefined' && typeof (req.body.event.parentEvent) !== 'undefined') { var lock = new Lock(req.body.event.parentEvent); lock.acquire(function(err, locked) { if(err !== null || locked === false) { res.statusCode = statusCodes.LOCKED; res.end('Document is Locked'); return; } if( typeof (req.locks) == 'undefined') { req.locks = [lock]; } else { req.locks.push(lock); } next(); }); } else { next(); } } RestEvent.prototype._getDefaultSort = function() { return [{ "event.when.startTime" : { "order" : "desc", "missing" : "_last" } }, { "createDate" : { "order" : "desc" } }] } RestEvent.prototype._populateObject = function(obj, data, req, res) { if(obj.author === null) { obj.author = req.user.id; } return RestOAuthModel.prototype._populateObject.call(this, obj, data, req, res); } RestEvent.prototype._preCreate = function(obj, req, callback) { // add permissions to obj obj.computedWriteUsers.push(req.user.id); obj.computedReadUsers.push(req.user.id); obj.computedReadUsers.push('/user/all'); obj.computedReadGroups.push('/group/all'); var methods = [] req.preCreateObjects = []; // write user permission methods.push(function(cb) { // create write permission var p = new models.perms.EventWriteUser(); p.applyOn = obj.getId(); p.grantTo = req.user.id; p.setValidationDone(); obj.computedWriteUsersPerms.push(p.getId()); p.save(function(err, p) { if(err === null) { req.preCreateObjects.push(p); } // trivial but it's what we want... if( err instanceof models.errors.ObjectAlreadyExists) { err = null; } if(err !== null) { log.warning('RestAgenda.prototype.create: unable to create permission EventWriteUser on ', req.user.id, obj.getId(), err) cb(new models.errors.InternalError('Unable to create permission, aborting')); } else { cb(null); } }, false, false); }); // read user permission methods.push(function(cb) { // create write permission var p = new models.perms.EventReadUser(); p.applyOn = obj.getId(); p.grantTo = req.user.id; p.setValidationDone(); obj.computedReadUsersPerms.push(p.getId()); p.save(function(err, p) { if(err === null) { req.preCreateObjects.push(p); } // trivial but it's what we want... if( err instanceof models.errors.ObjectAlreadyExists) { err = null; } if(err !== null) { log.warning('RestAgenda.prototype.create: unable to create permission EventReadUser on ', req.user.id, obj.getId(), err) cb(new models.errors.InternalError('Unable to create permission, aborting')); } else { cb(null); } }, false, false); }); // read user permission methods.push(function(cb) { // create write permission var p = new models.perms.EventReadUser(); p.applyOn = obj.getId(); p.grantTo = '/user/all'; p.setValidationDone(); obj.computedReadUsersPerms.push(p.getId()); p.save(function(err, p) { if(err === null) { req.preCreateObjects.push(p); } // trivial but it's what we want... if( err instanceof models.errors.ObjectAlreadyExists) { err = null; } if(err !== null) { log.warning('RestAgenda.prototype.create: unable to create permission EventReadUser on ', '/user/all', obj.getId(), err) cb(new models.errors.InternalError('Unable to create permission, aborting')); } else { cb(null); } }, false, false); }); // read group permission methods.push(function(cb) { // create write permission var p = new models.perms.EventReadGroup(); p.applyOn = obj.getId(); p.grantTo = '/group/all'; p.setValidationDone(); obj.computedReadGroupsPerms.push(p.getId()); p.save(function(err, p) { if(err === null) { req.preCreateObjects.push(p); } // trivial but it's what we want... if( err instanceof models.errors.ObjectAlreadyExists) { err = null; } if(err !== null) { log.warning('RestAgenda.prototype.create: unable to create permission EventReadGroup on ', '/group/all', obj.getId(), err) cb(new models.errors.InternalError('Unable to create permission, aborting')); } else { cb(null); } }, false, false); }); async.parallel(methods, function(err) { if( typeof (err) === 'undefined') { err = null; } if(err !== null) { // rolling back var rollbackMethods = []; req.preCreateObjects.forEach(function(toDelObj) { rollbackMethods.push(function(cb) { toDelObj.del(function(err, obj) { if(err !== null) { log.warning('RestEvent.prototype._postCreate: rolling back failed', toDelObj.id) } cb(err); }); }); }); async.parallel(rollbackMethods, function(rollbackErr) { callback(err); }); } else { callback(err); } }); } RestEvent.prototype._postCreate = function(err, obj, req, callback) { if(err === null) { // update parent event.childEvents if needed if( typeof (obj.event.parentEvent) !== 'undefined' && obj.event.parentEvent !== null) { models.Event.get({ id : obj.event.parentEvent }, function(err, parent) { if( typeof (parent.event.childEvents) == 'undefined' || parent.event.childEvents.indexOf(obj.id) === -1) { if( typeof (parent.event.childEvents) == 'undefined') { parent.event.childEvents = []; } parent.event.childEvents.push(obj.id); parent.save(function(err) { if(err !== null) { log.critical('RestEvent.prototype._postCreate: error while saving parent event', obj.id, parent.id, JSON.stringify(err)); } callback(); }); } else { callback(); } }) } else { callback(); } } else if( typeof (req.preCreateObjects) !== 'undefined') { // rolling back var rollbackMethods = []; req.preCreateObjects.forEach(function(toDelObj) { rollbackMethods.push(function(callback) { toDelObj.del(function(err, obj) { if(err !== null) { log.warning('RestEvent.prototype._postCreate: rolling back failed', toDelObj.id) } callback(err); }, false); }); }); async.parallel(rollbackMethods, function(rollbackErr) { callback(); }); } } RestEvent.prototype._preUpdate = function(obj, req, callback) { if(obj.initialData.parentEvent !== null && obj.initialData.parentEvent != obj.event.parentEvent) { // try to acquire a lock on original parent event var lock = new Lock(obj.initialData.parentEvent); lock.acquire(function(err, locked) { if(err !== null || locked === false) { req.res.statusCode = statusCodes.LOCKED; req.res.end('Document is Locked'); return; } if( typeof (req.locks) == 'undefined') { req.locks = [lock]; } else { req.locks.push(lock); } callback(null); }); } else { callback(null); } } RestEvent.prototype._postUpdate = function(err, obj, req, callback) { if(err !== null) { callback(); return; } var methods = []; // delete current event from parent event childEvents if(obj.initialData.parentEvent !== null && obj.initialData.parentEvent != obj.event.parentEvent) { methods.push(function(cb) { models.Event.get({ id : obj.initialData.parentEvent }, function(err, parent) { if(err !== null) { log.critical('RestEvent.prototype._postUpdate unable to load parent event', obj.initialData.parentEvent, JSON.stringify(err)) cb(); } else { if( typeof (parent.event.childEvents) == 'undefined') { log.warning('RestEvent.prototype._postUpdate parent event has no attribute childEvents', obj.initialData.parentEvent); cb(); } else if(parent.event.childEvents.indexOf(obj.id) !== -1) { parent.event.childEvents.splice(parent.event.childEvents.indexOf(obj.id), 1); if (parent.event.childEvents.length===0) { delete parent.event.childEvents; } parent.save(function(err) { if(err !== null) { log.warning('RestEvent.prototype._postUpdate unable to save parent event', obj.initialData.parentEvent, JSON.stringify(err)); } cb(); }) } } }) }) } if( typeof (obj.event.parentEvent) !== 'undefined') { methods.push(function(cb) { models.Event.get({ id : obj.event.parentEvent }, function(err, parent) { if( typeof (parent.event.childEvents) == 'undefined' || parent.event.childEvents.indexOf(obj.id) === -1) { if( typeof (parent.event.childEvents) == 'undefined') { parent.event.childEvents = []; } parent.event.childEvents.push(obj.id); parent.save(function(err) { if(err !== null) { log.critical('RestEvent.prototype._postUpdate: error while saving parent event', obj.id, parent.id, JSON.stringify(err)); } cb(); }); } else { cb(); } }) }); } if(methods.length > 0) { async.parallel(methods, function() { callback(); }); } else { callback(); } } RestEvent.prototype._preDel = function(obj, req, callback) { var id = "/event/" + req.params.id; var query = { "query" : { "filtered" : { "query" : { "match_all" : {} }, "filter" : { "term" : { "event.parentEvent" : id } } } } } this._checkIntegrity(query, req, function(err) { if(err !== null) { callback(err); return; } if( typeof (obj.event.parentEvent) != 'undefined') { // try to acquire a lock on parent event var lock = new Lock(obj.event.parentEvent); lock.acquire(function(err, locked) { if(err !== null || locked === false) { req.res.statusCode = statusCodes.LOCKED; req.res.end('Document is Locked'); return; } if( typeof (req.locks) == 'undefined') { req.locks = [lock]; } else { req.locks.push(lock); } callback(null); }); } else { callback(null); } }); } RestEvent.prototype._postDel = function(err, obj, req, callback) { if(err !== null && !( err instanceof models.errors.ObjectDoesNotExist)) { callback(); return; } var methods = []; obj.computedWriteUsersPerms.forEach( function(id) { methods.push(this._getPermDeleteMethod(obj, id, 'EventWriteUser')); }.bind(this)); obj.computedWriteGroupsPerms.forEach( function(id) { methods.push(this._getPermDeleteMethod(obj, id, 'EventWriteGroup')); }.bind(this)); obj.computedReadUsersPerms.forEach( function(id) { methods.push(this._getPermDeleteMethod(obj, id, 'EventReadUser')); }.bind(this)); obj.computedReadGroupsPerms.forEach( function(id) { methods.push(this._getPermDeleteMethod(obj, id, 'EventReadGroup')); }.bind(this)); // add an async method to update parent event if needed if( typeof (obj.event.parentEvent) != 'undefined') { methods.push(function(cb) { models.Event.get({ id : obj.event.parentEvent }, function(err, parent) { if(err !== null) { log.critical('RestEvent.prototype._postDel unable to load parent event', obj.event.parentEvent, JSON.stringify(err)) cb(); } else { if( typeof (parent.event.childEvents) == 'undefined') { log.warning('RestEvent.prototype._postDel parent event has no attribute childEvents', obj.event.parentEvent); cb(); } else if(parent.event.childEvents.indexOf(obj.id) !== -1) { parent.event.childEvents.splice(parent.event.childEvents.indexOf(obj.id), 1); if (parent.event.childEvents.length===0) { delete parent.event.childEvents; } parent.save(function(err) { if(err !== null) { log.warning('RestEvent.prototype._postDel unable to save parent event', obj.event.parentEvent, JSON.stringify(err)); } cb(); }) } } }) }) } async.parallel(methods, function() { callback(); }); } RestEvent.prototype.__moderate = function(req, res, moderate) { var id = "/event/" + req.params.id; var lock = new Lock(id); lock.acquire(function(err, locked) { if(err !== null || locked === false) { res.statusCode = statusCodes.LOCKED; res.end('Document is Locked'); return; } req.locks = [lock]; models.Event.get({ id : id }, function(err, event) { if(err !== null) { if( err instanceof models.errors.ObjectDoesNotExist) { res.statusCode = statusCodes.NOT_FOUND; res.end('Not found') } else { res.statusCode = statusCodes.INTERNAL_ERROR; res.end('Internal error') } } else { moderate(event); event.save(function(err, obj) { if(err === null) { res.statusCode = statusCodes.ALL_OK; res.end(); } else { res.statusCode = statusCodes.INTERNAL_ERROR; res.end('Internal error') } }) } }); }); } RestEvent.prototype.addApprove = function(req, res) { this.__moderate(req, res, function(event) { if(event.approvedBy.indexOf(req.user.id) === -1) { event.approvedBy.push(req.user.id); } if(( pos = event.disapprovedBy.indexOf(req.user.id)) !== -1) { event.disapprovedBy.splice(pos, 1); } }); } RestEvent.prototype.addDisapprove = function(req, res) { this.__moderate(req, res, function(event) { if(event.disapprovedBy.indexOf(req.user.id) === -1) { event.disapprovedBy.push(req.user.id); } if(( pos = event.approvedBy.indexOf(req.user.id)) !== -1) { event.approvedBy.splice(pos, 1); } }); } RestEvent.prototype.delApprove = function(req, res) { this.__moderate(req, res, function(event) { if(( pos = event.approvedBy.indexOf(req.user.id)) !== -1) { event.approvedBy.splice(pos, 1); } }); } RestEvent.prototype.delDisapprove = function(req, res) { this.__moderate(req, res, function(event) { if(( pos = event.disapprovedBy.indexOf(req.user.id)) !== -1) { event.disapprovedBy.splice(pos, 1); } }); } RestEvent.prototype.permsUserWrite = function(req, res) { var permClass = models.perms.getPermClass('event', 'user', 'write'), grantToClass = models.User; this._perms(req, res, permClass, grantToClass); } RestEvent.prototype.permsGroupWrite = function(req, res) { var permClass = models.perms.getPermClass('event', 'group', 'write'), grantToClass = models.Group; this._perms(req, res, permClass, grantToClass); } RestEvent.prototype.permsUserRead = function(req, res) { var permClass = models.perms.getPermClass('event', 'user', 'read'), grantToClass = models.User; this._perms(req, res, permClass, grantToClass); } RestEvent.prototype.permsGroupRead = function(req, res) { var permClass = models.perms.getPermClass('event', 'group', 'read'), grantToClass = models.Group; this._perms(req, res, permClass, grantToClass); } RestEvent.prototype._setPermsOnQuery = function(req, q) { var hasQueryAttribute = typeof (q.query) !== 'undefined'; if(hasQueryAttribute === true) { q = q.query; } var query = {}; if( typeof (q.filtered) === 'undefined') { // assume that query is something like {match_all : {}} query.filtered = { query : q, filter : { "or" : [{ terms : { computedReadGroups : req.user.groups.concat(["/group/all"]), "minimum_match" : 1 } }, { terms : { computedReadUsers : ["/user/all", req.user.id], "minimum_match" : 1 } }] } } } else { query.filtered = { query : q.filtered.query, filter : { and : [{ "or" : [{ terms : { computedReadGroups : req.user.groups.concat(["/group/all"]), "minimum_match" : 1 } }, { terms : { computedReadUsers : ["/user/all", req.user.id], "minimum_match" : 1 } }] }, q.filtered.filter] } } } if(hasQueryAttribute === true) { query = { query : query }; } return query; }
libs/rest/event.js
var RestOAuthModel = require('./oAuthModel.js').RestOAuthModel; var statusCode = require('../statusCodes.js'); var util = require("util"); var models = require('../../models'); var ElasticSearchClient = require('elasticsearchclient'); var settings = require('../../settings.js'); var elasticSearchClient = new ElasticSearchClient(settings.elasticsearch); var restError = require('./errors'); var log = require('czagenda-log').from(__filename); var models = require('../../models'); var async = require('async'); var statusCodes = require('../statusCodes'); var mModelSearch = require('./mModelSearch'); var Lock = require('../lock'); var RestEvent = exports.RestEvent = function(server) { RestOAuthModel.call(this, 'event', models.Event, server); this._urls.get[this._urlPrefix + '/:id/perms/wu'] = { fn : this.permsUserWrite }; this._urls.get[this._urlPrefix + '/:id/perms/wg'] = { fn : this.permsGroupWrite }; this._urls.get[this._urlPrefix + '/:id/perms/ru'] = { fn : this.permsUserRead }; this._urls.get[this._urlPrefix + '/:id/perms/rg'] = { fn : this.permsGroupRead }; this._urls.post[this._urlPrefix + '/:id/moderate/approve'] = { fn : this.addApprove }; this._urls.post[this._urlPrefix + '/:id/moderate/disapprove'] = { fn : this.addDisapprove }; this._urls.del[this._urlPrefix + '/:id/moderate/approve'] = { fn : this.delApprove }; this._urls.del[this._urlPrefix + '/:id/moderate/disapprove'] = { fn : this.delDisapprove }; this._urls.get[this._urlPrefix + '/_search'] = { fn : this.search }; this._urls.post[this._urlPrefix + '/_search'] = { fn : this.search }; this._urls.put[this._urlPrefix + '/:id'].middleware.push(this.requireParentLock.bind(this)) this._urls.post[this._urlPrefix].middleware.push(this.requireParentLock.bind(this)) this._initServer(); } util.inherits(RestEvent, RestOAuthModel); for(k in mModelSearch) { RestEvent.prototype[k] = mModelSearch[k]; } RestEvent.prototype.searchFields = { 'agenda' : 'term', 'author' : 'term', 'createDate' : 'datetime', 'updateDate' : 'datetime', 'approvedBy' : 'term', 'disapprovedBy' : 'term', 'event.title' : 'text', 'event.content' : 'text', 'event.eventStatus' : 'term', 'event.when.startTime' : 'datetime', 'event.when.endTime' : 'datetime', 'event.where.city' : 'text', 'event.where.country' : 'text', 'event.where.admin_level_2' : 'text', 'event.where.admin_level_3' : 'text', 'event.where.geoPt' : 'geo', 'event.who.href' : 'term' } RestEvent.prototype.sortFields = { 'createDate' : 'createDate', 'updateDate' : 'updateDate', 'event.title' : 'event.title.untouched', 'event.when.startTime' : 'datetime', 'event.when.endTime' : 'datetime', 'distance' : 'distance' } RestEvent.prototype.requireParentLock = function(req, res, next) { if( typeof (req.body.event) !== 'undefined' && typeof (req.body.event.parentEvent) !== 'undefined') { var lock = new Lock(req.body.event.parentEvent); lock.acquire(function(err, locked) { if(err !== null || locked === false) { res.statusCode = statusCodes.LOCKED; res.end('Document is Locked'); return; } if( typeof (req.locks) == 'undefined') { req.locks = [lock]; } else { req.locks.push(lock); } next(); }); } else { next(); } } RestEvent.prototype._getDefaultSort = function() { return [{ "event.when.startTime" : { "order" : "desc", "missing" : "_last" } }, { "createDate" : { "order" : "desc" } }] } RestEvent.prototype._populateObject = function(obj, data, req, res) { if(obj.author === null) { obj.author = req.user.id; } return RestOAuthModel.prototype._populateObject.call(this, obj, data, req, res); } RestEvent.prototype._preCreate = function(obj, req, callback) { // add permissions to obj obj.computedWriteUsers.push(req.user.id); obj.computedReadUsers.push(req.user.id); obj.computedReadUsers.push('/user/all'); obj.computedReadGroups.push('/group/all'); var methods = [] req.preCreateObjects = []; // write user permission methods.push(function(cb) { // create write permission var p = new models.perms.EventWriteUser(); p.applyOn = obj.getId(); p.grantTo = req.user.id; p.setValidationDone(); obj.computedWriteUsersPerms.push(p.getId()); p.save(function(err, p) { if(err === null) { req.preCreateObjects.push(p); } // trivial but it's what we want... if( err instanceof models.errors.ObjectAlreadyExists) { err = null; } if(err !== null) { log.warning('RestAgenda.prototype.create: unable to create permission EventWriteUser on ', req.user.id, obj.getId(), err) cb(new models.errors.InternalError('Unable to create permission, aborting')); } else { cb(null); } }, false, false); }); // read user permission methods.push(function(cb) { // create write permission var p = new models.perms.EventReadUser(); p.applyOn = obj.getId(); p.grantTo = req.user.id; p.setValidationDone(); obj.computedReadUsersPerms.push(p.getId()); p.save(function(err, p) { if(err === null) { req.preCreateObjects.push(p); } // trivial but it's what we want... if( err instanceof models.errors.ObjectAlreadyExists) { err = null; } if(err !== null) { log.warning('RestAgenda.prototype.create: unable to create permission EventReadUser on ', req.user.id, obj.getId(), err) cb(new models.errors.InternalError('Unable to create permission, aborting')); } else { cb(null); } }, false, false); }); // read user permission methods.push(function(cb) { // create write permission var p = new models.perms.EventReadUser(); p.applyOn = obj.getId(); p.grantTo = '/user/all'; p.setValidationDone(); obj.computedReadUsersPerms.push(p.getId()); p.save(function(err, p) { if(err === null) { req.preCreateObjects.push(p); } // trivial but it's what we want... if( err instanceof models.errors.ObjectAlreadyExists) { err = null; } if(err !== null) { log.warning('RestAgenda.prototype.create: unable to create permission EventReadUser on ', '/user/all', obj.getId(), err) cb(new models.errors.InternalError('Unable to create permission, aborting')); } else { cb(null); } }, false, false); }); // read group permission methods.push(function(cb) { // create write permission var p = new models.perms.EventReadGroup(); p.applyOn = obj.getId(); p.grantTo = '/group/all'; p.setValidationDone(); obj.computedReadGroupsPerms.push(p.getId()); p.save(function(err, p) { if(err === null) { req.preCreateObjects.push(p); } // trivial but it's what we want... if( err instanceof models.errors.ObjectAlreadyExists) { err = null; } if(err !== null) { log.warning('RestAgenda.prototype.create: unable to create permission EventReadGroup on ', '/group/all', obj.getId(), err) cb(new models.errors.InternalError('Unable to create permission, aborting')); } else { cb(null); } }, false, false); }); async.parallel(methods, function(err) { if( typeof (err) === 'undefined') { err = null; } if(err !== null) { // rolling back var rollbackMethods = []; req.preCreateObjects.forEach(function(toDelObj) { rollbackMethods.push(function(cb) { toDelObj.del(function(err, obj) { if(err !== null) { log.warning('RestEvent.prototype._postCreate: rolling back failed', toDelObj.id) } cb(err); }); }); }); async.parallel(rollbackMethods, function(rollbackErr) { callback(err); }); } else { callback(err); } }); } RestEvent.prototype._postCreate = function(err, obj, req, callback) { if(err === null) { // update parent event.childEvents if needed if( typeof (obj.event.parentEvent) !== 'undefined' && obj.event.parentEvent !== null) { models.Event.get({ id : obj.event.parentEvent }, function(err, parent) { if( typeof (parent.event.childEvents) == 'undefined' || parent.event.childEvents.indexOf(obj.id) === -1) { if( typeof (parent.event.childEvents) == 'undefined') { parent.event.childEvents = []; } parent.event.childEvents.push(obj.id); parent.save(function(err) { if(err !== null) { log.critical('RestEvent.prototype._postCreate: error while saving parent event', obj.id, parent.id, JSON.stringify(err)); } callback(); }); } else { callback(); } }) } else { callback(); } } else if( typeof (req.preCreateObjects) !== 'undefined') { // rolling back var rollbackMethods = []; req.preCreateObjects.forEach(function(toDelObj) { rollbackMethods.push(function(callback) { toDelObj.del(function(err, obj) { if(err !== null) { log.warning('RestEvent.prototype._postCreate: rolling back failed', toDelObj.id) } callback(err); }, false); }); }); async.parallel(rollbackMethods, function(rollbackErr) { callback(); }); } } RestEvent.prototype._preUpdate = function(obj, req, callback) { if(obj.initialData.parentEvent !== null && obj.initialData.parentEvent != obj.event.parentEvent) { // try to acquire a lock on original parent event var lock = new Lock(obj.initialData.parentEvent); lock.acquire(function(err, locked) { if(err !== null || locked === false) { req.res.statusCode = statusCodes.LOCKED; req.res.end('Document is Locked'); return; } if( typeof (req.locks) == 'undefined') { req.locks = [lock]; } else { req.locks.push(lock); } callback(null); }); } else { callback(null); } } RestEvent.prototype._postUpdate = function(err, obj, req, callback) { if(err !== null) { callback(); return; } var methods = []; // delete current event from parent event childEvents if(obj.initialData.parentEvent !== null && obj.initialData.parentEvent != obj.event.parentEvent) { methods.push(function(cb) { models.Event.get({ id : obj.initialData.parentEvent }, function(err, parent) { if(err !== null) { log.critical('RestEvent.prototype._postUpdate unable to load parent event', obj.initialData.parentEvent, JSON.stringify(err)) cb(); } else { if( typeof (parent.event.childEvents) == 'undefined') { log.warning('RestEvent.prototype._postUpdate parent event has no attribute childEvents', obj.initialData.parentEvent); cb(); } else if(parent.event.childEvents.indexOf(obj.id) !== -1) { parent.event.childEvents.splice(parent.event.childEvents.indexOf(obj.id), 1); if (parent.event.childEvents.length===0) { delete parent.event.childEvents; } parent.save(function(err) { if(err !== null) { log.warning('RestEvent.prototype._postUpdate unable to save parent event', obj.initialData.parentEvent, JSON.stringify(err)); } cb(); }) } } }) }) } if( typeof (obj.event.parentEvent) !== 'undefined') { methods.push(function(cb) { models.Event.get({ id : obj.event.parentEvent }, function(err, parent) { if( typeof (parent.event.childEvents) == 'undefined' || parent.event.childEvents.indexOf(obj.id) === -1) { if( typeof (parent.event.childEvents) == 'undefined') { parent.event.childEvents = []; } parent.event.childEvents.push(obj.id); parent.save(function(err) { if(err !== null) { log.critical('RestEvent.prototype._postUpdate: error while saving parent event', obj.id, parent.id, JSON.stringify(err)); } cb(); }); } else { cb(); } }) }); } if(methods.length > 0) { async.parallel(methods, function() { callback(); }); } else { callback(); } } RestEvent.prototype._preDel = function(obj, req, callback) { var id = "/event/" + req.params.id; var query = { "query" : { "filtered" : { "query" : { "match_all" : {} }, "filter" : { "term" : { "event.childEvents" : id } } } } } this._checkIntegrity(query, req, function(err) { if(err !== null) { callback(err); return; } if( typeof (obj.event.parentEvent) != 'undefined') { // try to acquire a lock on parent event var lock = new Lock(obj.event.parentEvent); lock.acquire(function(err, locked) { if(err !== null || locked === false) { req.res.statusCode = statusCodes.LOCKED; req.res.end('Document is Locked'); return; } if( typeof (req.locks) == 'undefined') { req.locks = [lock]; } else { req.locks.push(lock); } callback(null); }); } else { callback(null); } }); } RestEvent.prototype._postDel = function(err, obj, req, callback) { if(err !== null && !( err instanceof models.errors.ObjectDoesNotExist)) { callback(); return; } var methods = []; obj.computedWriteUsersPerms.forEach( function(id) { methods.push(this._getPermDeleteMethod(obj, id, 'EventWriteUser')); }.bind(this)); obj.computedWriteGroupsPerms.forEach( function(id) { methods.push(this._getPermDeleteMethod(obj, id, 'EventWriteGroup')); }.bind(this)); obj.computedReadUsersPerms.forEach( function(id) { methods.push(this._getPermDeleteMethod(obj, id, 'EventReadUser')); }.bind(this)); obj.computedReadGroupsPerms.forEach( function(id) { methods.push(this._getPermDeleteMethod(obj, id, 'EventReadGroup')); }.bind(this)); // add an async method to update parent event if needed if( typeof (obj.event.parentEvent) != 'undefined') { methods.push(function(cb) { models.event.get({ id : obj.event.parentEvent }, function(err, parent) { if(err !== null) { log.critical('RestEvent.prototype._postDel unable to load parent event', obj.event.parentEvent, JSON.stringify(err)) cb(); } else { if( typeof (parent.event.childEvents) == 'undefined') { log.warning('RestEvent.prototype._postDel parent event has no attribute childEvents', obj.event.parentEvent); cb(); } else if(parent.event.childEvents.indexOf(obj.id) !== -1) { parent.event.childEvents.splice(parent.event.childEvents.indexOf(obj.id), 1); if (parent.event.childEvents.length===0) { delete parent.event.childEvents; } parent.save(function(err) { if(err !== null) { log.warning('RestEvent.prototype._postDel unable to save parent event', obj.event.parentEvent, JSON.stringify(err)); } cb(); }) } } }) }) } async.parallel(methods, function() { callback(); }); } RestEvent.prototype.__moderate = function(req, res, moderate) { var id = "/event/" + req.params.id; var lock = new Lock(id); lock.acquire(function(err, locked) { if(err !== null || locked === false) { res.statusCode = statusCodes.LOCKED; res.end('Document is Locked'); return; } req.locks = [lock]; models.Event.get({ id : id }, function(err, event) { if(err !== null) { if( err instanceof models.errors.ObjectDoesNotExist) { res.statusCode = statusCodes.NOT_FOUND; res.end('Not found') } else { res.statusCode = statusCodes.INTERNAL_ERROR; res.end('Internal error') } } else { moderate(event); event.save(function(err, obj) { if(err === null) { res.statusCode = statusCodes.ALL_OK; res.end(); } else { res.statusCode = statusCodes.INTERNAL_ERROR; res.end('Internal error') } }) } }); }); } RestEvent.prototype.addApprove = function(req, res) { this.__moderate(req, res, function(event) { if(event.approvedBy.indexOf(req.user.id) === -1) { event.approvedBy.push(req.user.id); } if(( pos = event.disapprovedBy.indexOf(req.user.id)) !== -1) { event.disapprovedBy.splice(pos, 1); } }); } RestEvent.prototype.addDisapprove = function(req, res) { this.__moderate(req, res, function(event) { if(event.disapprovedBy.indexOf(req.user.id) === -1) { event.disapprovedBy.push(req.user.id); } if(( pos = event.approvedBy.indexOf(req.user.id)) !== -1) { event.approvedBy.splice(pos, 1); } }); } RestEvent.prototype.delApprove = function(req, res) { this.__moderate(req, res, function(event) { if(( pos = event.approvedBy.indexOf(req.user.id)) !== -1) { event.approvedBy.splice(pos, 1); } }); } RestEvent.prototype.delDisapprove = function(req, res) { this.__moderate(req, res, function(event) { if(( pos = event.disapprovedBy.indexOf(req.user.id)) !== -1) { event.disapprovedBy.splice(pos, 1); } }); } RestEvent.prototype.permsUserWrite = function(req, res) { var permClass = models.perms.getPermClass('event', 'user', 'write'), grantToClass = models.User; this._perms(req, res, permClass, grantToClass); } RestEvent.prototype.permsGroupWrite = function(req, res) { var permClass = models.perms.getPermClass('event', 'group', 'write'), grantToClass = models.Group; this._perms(req, res, permClass, grantToClass); } RestEvent.prototype.permsUserRead = function(req, res) { var permClass = models.perms.getPermClass('event', 'user', 'read'), grantToClass = models.User; this._perms(req, res, permClass, grantToClass); } RestEvent.prototype.permsGroupRead = function(req, res) { var permClass = models.perms.getPermClass('event', 'group', 'read'), grantToClass = models.Group; this._perms(req, res, permClass, grantToClass); } RestEvent.prototype._setPermsOnQuery = function(req, q) { var hasQueryAttribute = typeof (q.query) !== 'undefined'; if(hasQueryAttribute === true) { q = q.query; } var query = {}; if( typeof (q.filtered) === 'undefined') { // assume that query is something like {match_all : {}} query.filtered = { query : q, filter : { "or" : [{ terms : { computedReadGroups : req.user.groups.concat(["/group/all"]), "minimum_match" : 1 } }, { terms : { computedReadUsers : ["/user/all", req.user.id], "minimum_match" : 1 } }] } } } else { query.filtered = { query : q.filtered.query, filter : { and : [{ "or" : [{ terms : { computedReadGroups : req.user.groups.concat(["/group/all"]), "minimum_match" : 1 } }, { terms : { computedReadUsers : ["/user/all", req.user.id], "minimum_match" : 1 } }] }, q.filtered.filter] } } } if(hasQueryAttribute === true) { query = { query : query }; } return query; }
bugfix subevent/master delete
libs/rest/event.js
bugfix subevent/master delete
<ide><path>ibs/rest/event.js <ide> }, <ide> "filter" : { <ide> "term" : { <del> "event.childEvents" : id <add> "event.parentEvent" : id <ide> } <ide> } <ide> } <ide> if( typeof (obj.event.parentEvent) != 'undefined') { <ide> methods.push(function(cb) { <ide> <del> models.event.get({ <add> models.Event.get({ <ide> id : obj.event.parentEvent <ide> }, function(err, parent) { <ide> if(err !== null) {
Java
lgpl-2.1
0d106ad0503bb03fe19ad7ba88fb393e365ab2ae
0
alkacon/opencms-core,MenZil/opencms-core,serrapos/opencms-core,ggiudetti/opencms-core,serrapos/opencms-core,it-tavis/opencms-core,gallardo/opencms-core,victos/opencms-core,sbonoc/opencms-core,serrapos/opencms-core,gallardo/opencms-core,alkacon/opencms-core,sbonoc/opencms-core,ggiudetti/opencms-core,alkacon/opencms-core,mediaworx/opencms-core,mediaworx/opencms-core,gallardo/opencms-core,it-tavis/opencms-core,MenZil/opencms-core,gallardo/opencms-core,victos/opencms-core,victos/opencms-core,it-tavis/opencms-core,sbonoc/opencms-core,mediaworx/opencms-core,serrapos/opencms-core,serrapos/opencms-core,alkacon/opencms-core,MenZil/opencms-core,it-tavis/opencms-core,victos/opencms-core,serrapos/opencms-core,MenZil/opencms-core,serrapos/opencms-core,ggiudetti/opencms-core,mediaworx/opencms-core,ggiudetti/opencms-core,sbonoc/opencms-core
/* * File : $Source: /alkacon/cvs/opencms/src/org/opencms/db/CmsSecurityManager.java,v $ * Date : $Date: 2005/06/24 15:51:09 $ * Version: $Revision: 1.85 $ * * This library is part of OpenCms - * the Open Source Content Mananagement System * * Copyright (c) 2005 Alkacon Software GmbH (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software GmbH, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.db; import org.opencms.configuration.CmsConfigurationManager; import org.opencms.configuration.CmsSystemConfiguration; import org.opencms.file.CmsBackupProject; import org.opencms.file.CmsBackupResource; import org.opencms.file.CmsFile; import org.opencms.file.CmsFolder; import org.opencms.file.CmsGroup; import org.opencms.file.CmsObject; import org.opencms.file.CmsProject; import org.opencms.file.CmsProperty; import org.opencms.file.CmsPropertyDefinition; import org.opencms.file.CmsRequestContext; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.file.CmsUser; import org.opencms.file.CmsVfsException; import org.opencms.file.CmsVfsResourceNotFoundException; import org.opencms.file.types.CmsResourceTypeJsp; import org.opencms.i18n.CmsMessageContainer; import org.opencms.lock.CmsLock; import org.opencms.lock.CmsLockException; import org.opencms.main.CmsException; import org.opencms.main.CmsInitException; import org.opencms.main.CmsLog; import org.opencms.main.I_CmsConstants; import org.opencms.main.OpenCms; import org.opencms.report.I_CmsReport; import org.opencms.security.CmsAccessControlEntry; import org.opencms.security.CmsAccessControlList; import org.opencms.security.CmsPermissionSet; import org.opencms.security.CmsPermissionSetCustom; import org.opencms.security.CmsPermissionViolationException; import org.opencms.security.CmsRole; import org.opencms.security.CmsRoleViolationException; import org.opencms.security.CmsSecurityException; import org.opencms.security.I_CmsPrincipal; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import org.opencms.workflow.CmsTask; import org.opencms.workflow.CmsTaskLog; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.apache.commons.collections.map.LRUMap; import org.apache.commons.logging.Log; /** * The OpenCms security manager.<p> * * The security manager checks the permissions required for a user action invoke by the Cms object. If permissions * are granted, the security manager invokes a method on the OpenCms driver manager to access the database.<p> * * @author Thomas Weckert * @author Michael Moossen * * @version $Revision: 1.85 $ * * @since 6.0.0 */ public final class CmsSecurityManager { /** Indicates allowed permissions. */ public static final int PERM_ALLOWED = 0; /** Indicates denied permissions. */ public static final int PERM_DENIED = 1; /** Indicates a resource was filtered during permission check. */ public static final int PERM_FILTERED = 2; /** Indicates a resource was not locked for a write / control operation. */ public static final int PERM_NOTLOCKED = 3; /** The log object for this class. */ private static final Log LOG = CmsLog.getLog(CmsSecurityManager.class); /** Indicates allowed permissions. */ private static final Integer PERM_ALLOWED_INTEGER = new Integer(PERM_ALLOWED); /** Indicates denied permissions. */ private static final Integer PERM_DENIED_INTEGER = new Integer(PERM_DENIED); /** The factory to create runtime info objects. */ protected I_CmsDbContextFactory m_dbContextFactory; /** The initialized OpenCms driver manager to access the database. */ protected CmsDriverManager m_driverManager; /** The class used for cache key generation. */ private I_CmsCacheKey m_keyGenerator; /** Cache for permission checks. */ private Map m_permissionCache; /** * Default constructor.<p> */ private CmsSecurityManager() { // intentionally left blank } /** * Creates a new instance of the OpenCms security manager.<p> * * @param configurationManager the configuation manager * @param runtimeInfoFactory the initialized OpenCms runtime info factory * * @return a new instance of the OpenCms security manager * * @throws CmsInitException if the securtiy manager could not be initialized */ public static CmsSecurityManager newInstance( CmsConfigurationManager configurationManager, I_CmsDbContextFactory runtimeInfoFactory) throws CmsInitException { if (OpenCms.getRunLevel() > OpenCms.RUNLEVEL_2_INITIALIZING) { // OpenCms is already initialized throw new CmsInitException(org.opencms.main.Messages.get().container( org.opencms.main.Messages.ERR_ALREADY_INITIALIZED_0)); } CmsSecurityManager securityManager = new CmsSecurityManager(); securityManager.init(configurationManager, runtimeInfoFactory); return securityManager; } /** * Updates the state of the given task as accepted by the current user.<p> * * @param context the current request context * @param taskId the Id of the task to accept * * @throws CmsException if something goes wrong */ public void acceptTask(CmsRequestContext context, int taskId) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.acceptTask(dbc, taskId); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_ACCEPT_TASK_1, new Integer(taskId)), e); } finally { dbc.clear(); } } /** * Adds a user to a group.<p> * * @param context the current request context * @param username the name of the user that is to be added to the group * @param groupname the name of the group * * @throws CmsException if operation was not succesfull */ public void addUserToGroup(CmsRequestContext context, String username, String groupname) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.USER_MANAGER); m_driverManager.addUserToGroup(dbc, username, groupname); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_ADD_USER_GROUP_FAILED_2, username, groupname), e); } finally { dbc.clear(); } } /** * Creates a new web user.<p> * * A web user has no access to the workplace but is able to access personalized * functions controlled by the OpenCms.<br> * * Moreover, a web user can be created by any user, the intention being that * a "Guest" user can create a personalized account for himself.<p> * * @param context the current request context * @param name the new name for the user * @param password the new password for the user * @param group the default groupname for the user * @param description the description for the user * @param additionalInfos a <code>{@link Map}</code> with additional infos for the user * * @return the new user will be returned * * @throws CmsException if operation was not succesfull */ public CmsUser addWebUser( CmsRequestContext context, String name, String password, String group, String description, Map additionalInfos) throws CmsException { CmsUser result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.addWebUser(dbc, name, password, group, description, additionalInfos); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_ADD_USER_WEB_1, name), e); } finally { dbc.clear(); } return result; } /** * Adds a web user to the Cms.<p> * * A web user has no access to the workplace but is able to access personalized * functions controlled by the OpenCms.<p> * * @param context the current request context * @param name the new name for the user * @param password the new password for the user * @param group the default groupname for the user * @param additionalGroup an additional group for the user * @param description the description for the user * @param additionalInfos a Hashtable with additional infos for the user, these infos may be stored into the Usertables (depending on the implementation) * * @return the new user will be returned * @throws CmsException if operation was not succesfull */ public CmsUser addWebUser( CmsRequestContext context, String name, String password, String group, String additionalGroup, String description, Map additionalInfos) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.addWebUser( dbc, name, password, group, additionalGroup, description, additionalInfos); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_ADD_USER_WEB_1, name), e); } finally { dbc.clear(); } return result; } /** * Creates a backup of the current project.<p> * * @param context the current request context * @param tagId the version of the backup * @param publishDate the date of publishing * * @throws CmsException if operation was not succesful */ public void backupProject(CmsRequestContext context, int tagId, long publishDate) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.backupProject(dbc, tagId, publishDate); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_BACKUP_PROJECT_4, new Object[] { new Integer(tagId), dbc.currentProject().getName(), new Integer(dbc.currentProject().getId()), new Long(publishDate)}), e); } finally { dbc.clear(); } } /** * Changes the project id of the resource to the current project, indicating that * the resource was last modified in this project.<p> * * @param context the current request context * @param resource theresource to apply this operation to * @throws CmsException if something goes wrong * @see org.opencms.file.types.I_CmsResourceType#changeLastModifiedProjectId(CmsObject, CmsSecurityManager, CmsResource) */ public void changeLastModifiedProjectId(CmsRequestContext context, CmsResource resource) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.changeLastModifiedProjectId(dbc, resource); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_CHANGE_LAST_MODIFIED_RESOURCE_IN_PROJECT_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Changes the lock of a resource to the current user, that is "steals" the lock from another user.<p> * * @param context the current request context * @param resource the resource to change the lock for * @throws CmsException if something goes wrong * @see org.opencms.file.types.I_CmsResourceType#changeLock(CmsObject, CmsSecurityManager, CmsResource) */ public void changeLock(CmsRequestContext context, CmsResource resource) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); checkOfflineProject(dbc); try { m_driverManager.changeLock(dbc, resource); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_CHANGE_LOCK_OF_RESOURCE_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Returns a list with all sub resources of a given folder that have set the given property, * matching the current property's value with the given old value and replacing it by a given new value.<p> * * @param context the current request context * @param resource the resource on which property definition values are changed * @param propertyDefinition the name of the propertydefinition to change the value * @param oldValue the old value of the propertydefinition * @param newValue the new value of the propertydefinition * @param recursive if true, change recursively all property values on sub-resources (only for folders) * * @return a list with the <code>{@link CmsResource}</code>'s where the property value has been changed * * @throws CmsVfsException for now only when the search for the oldvalue failed. * @throws CmsException if operation was not successful */ public synchronized List changeResourcesInFolderWithProperty( CmsRequestContext context, CmsResource resource, String propertyDefinition, String oldValue, String newValue, boolean recursive) throws CmsException, CmsVfsException { int todo = 0; // check if this belongs here - should be in driver manager (?) // collect the resources to look up List resources = new ArrayList(); if (recursive) { resources = readResourcesWithProperty(context, resource.getRootPath(), propertyDefinition); } else { resources.add(resource); } Pattern oldPattern; try { // compile regular expression pattern oldPattern = Pattern.compile(oldValue); } catch (PatternSyntaxException e) { throw new CmsVfsException(Messages.get().container( Messages.ERR_CHANGE_RESOURCES_IN_FOLDER_WITH_PROP_4, new Object[] {propertyDefinition, oldValue, newValue, context.getSitePath(resource)}), e); } List changedResources = new ArrayList(resources.size()); // create permission set and filter to check each resource CmsPermissionSet perm = CmsPermissionSet.ACCESS_WRITE; CmsResourceFilter filter = CmsResourceFilter.IGNORE_EXPIRATION; for (int i = 0; i < resources.size(); i++) { // loop through found resources and check property values CmsResource res = (CmsResource)resources.get(i); // check resource state and permissions try { checkPermissions(context, res, perm, true, filter); } catch (Exception e) { // resource is deleted or not writable for current user continue; } CmsProperty property = readPropertyObject(context, res, propertyDefinition, false); String structureValue = property.getStructureValue(); String resourceValue = property.getResourceValue(); boolean changed = false; if (structureValue != null && oldPattern.matcher(structureValue).matches()) { // change structure value property.setStructureValue(newValue); changed = true; } if (resourceValue != null && oldPattern.matcher(resourceValue).matches()) { // change resource value property.setResourceValue(newValue); changed = true; } if (changed) { // write property object if something has changed writePropertyObject(context, res, property); changedResources.add(res); } } return changedResources; } /** * Changes the user type of the user.<p> * * @param context the current request context * @param userId the id of the user to change * @param userType the new usertype of the user * * @throws CmsException if something goes wrong */ public void changeUserType(CmsRequestContext context, CmsUUID userId, int userType) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.USER_MANAGER); m_driverManager.changeUserType(dbc, userId, userType); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CHANGE_USER_TYPE_WITH_ID_1, userId.toString()), e); } finally { dbc.clear(); } } /** * Changes the user type of the user.<p> * Only the administrator can change the type.<p> * * @param context the current request context * @param username the name of the user to change * @param userType the new usertype of the user * @throws CmsException if something goes wrong */ public void changeUserType(CmsRequestContext context, String username, int userType) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.USER_MANAGER); m_driverManager.changeUserType(dbc, username, userType); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CHANGE_USER_TYPE_WITH_NAME_1, username), e); } finally { dbc.clear(); } } /** * Checks if the current user has management access to the given project.<p> * * @param dbc the current database context * @param project the project to check * * @throws CmsRoleViolationException if the user does not have the required role permissions */ public void checkManagerOfProjectRole(CmsDbContext dbc, CmsProject project) throws CmsRoleViolationException { if (!hasManagerOfProjectRole(dbc, project)) { throw new CmsRoleViolationException(org.opencms.security.Messages.get().container( org.opencms.security.Messages.ERR_NOT_MANAGER_OF_PROJECT_2, dbc.currentUser().getName(), dbc.currentProject().getName())); } } /** * Checks if the project in the given database context is not the "Online" project, * and throws an Exception if this is the case.<p> * * This is used to ensure a user is in an "Offline" project * before write access to VFS resources is granted.<p> * * @param dbc the current OpenCms users database context * * @throws CmsVfsException if the project in the given database context is the "Online" project */ public void checkOfflineProject(CmsDbContext dbc) throws CmsVfsException { if (dbc.currentProject().isOnlineProject()) { throw new CmsVfsException(org.opencms.file.Messages.get().container( org.opencms.file.Messages.ERR_NOT_ALLOWED_IN_ONLINE_PROJECT_0)); } } /** * Performs a blocking permission check on a resource.<p> * * If the required permissions are not satisfied by the permissions the user has on the resource, * an exception is thrown.<p> * * @param context the current request context * @param resource the resource on which permissions are required * @param requiredPermissions the set of permissions required to access the resource * @param checkLock if true, the lock status of the resource is also checked * @param filter the filter for the resource * * @throws CmsException in case of any i/o error * @throws CmsSecurityException if the required permissions are not satisfied * * @see #checkPermissions(CmsRequestContext, CmsResource, CmsPermissionSet, int) */ public void checkPermissions( CmsRequestContext context, CmsResource resource, CmsPermissionSet requiredPermissions, boolean checkLock, CmsResourceFilter filter) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { // check the access permissions checkPermissions(dbc, resource, requiredPermissions, checkLock, filter); } finally { dbc.clear(); } } /** * Checks if the given resource or the current project can be published by the current user * using his current OpenCms context.<p> * * If the resource parameter is <code>null</code>, then the current project is checked, * otherwise the resource is checked for direct publish permissions.<p> * * @param context the current request context * @param directPublishResource the direct publish resource (optional, if null only the current project is checked) * * @throws CmsException if the user does not have the required permissions * @throws CmsSecurityException if a direct publish is attempted on a resource * whose parent folder is new or deleted in the offline project. * @throws CmsRoleViolationException if the current user has no management access to the current project. */ public void checkPublishPermissions(CmsRequestContext context, CmsResource directPublishResource) throws CmsException, CmsSecurityException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); // is the current project an "offline" project? checkOfflineProject(dbc); // check if the current project is unlocked if (context.currentProject().getFlags() != I_CmsConstants.C_PROJECT_STATE_UNLOCKED) { CmsMessageContainer errMsg = org.opencms.security.Messages.get().container( org.opencms.security.Messages.ERR_RESOURCE_LOCKED_1, context.currentProject().getName()); throw new CmsLockException(errMsg); } // check if this is a "direct publish" attempt if (directPublishResource != null) { // the parent folder must not be new or deleted String parentFolder = CmsResource.getParentFolder(directPublishResource.getRootPath()); if (parentFolder != null) { CmsResource parent = readResource(context, parentFolder, CmsResourceFilter.ALL); if (parent.getState() == I_CmsConstants.C_STATE_DELETED) { // parent folder is deleted - direct publish not allowed throw new CmsVfsException(Messages.get().container( Messages.ERR_DIRECT_PUBLISH_PARENT_DELETED_2, dbc.getRequestContext().removeSiteRoot(directPublishResource.getRootPath()), parentFolder)); } if (parent.getState() == I_CmsConstants.C_STATE_NEW) { // parent folder is new - direct publish not allowed throw new CmsVfsException(Messages.get().container( Messages.ERR_DIRECT_PUBLISH_PARENT_NEW_2, context.removeSiteRoot(directPublishResource.getRootPath()), parentFolder)); } } // check if the user has the explicit permission to direct publish the selected resource if (PERM_ALLOWED == hasPermissions( context, directPublishResource, CmsPermissionSet.ACCESS_DIRECT_PUBLISH, true, CmsResourceFilter.ALL)) { // the user has "direct publish" permissions on the resource return; } } // check if the user is a manager of the current project, in this case he has publish permissions try { checkManagerOfProjectRole(dbc, dbc.getRequestContext().currentProject()); } finally { dbc.clear(); } } /** * Checks if the user of the current database context * has permissions to impersonate the given role.<p> * * @param dbc the current OpenCms users database context * @param role the role to check * * @throws CmsRoleViolationException if the user does not have the required role permissions */ public void checkRole(CmsDbContext dbc, CmsRole role) throws CmsRoleViolationException { if (!hasRole(dbc, role)) { throw role.createRoleViolationException(dbc.getRequestContext()); } } /** * Checks if the user of the current database context * has permissions to impersonate the given role.<p> * * @param context the current request context * @param role the role to check * * @throws CmsRoleViolationException if the user does not have the required role permissions */ public void checkRole(CmsRequestContext context, CmsRole role) throws CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, role); } finally { dbc.clear(); } } /** * Changes the resource flags of a resource.<p> * * The resource flags are used to indicate various "special" conditions * for a resource. Most notably, the "internal only" setting which signals * that a resource can not be directly requested with it's URL.<p> * * @param context the current request context * @param resource the resource to change the flags for * @param flags the new resource flags for this resource * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (({@link CmsPermissionSet#ACCESS_WRITE} required). * @see org.opencms.file.types.I_CmsResourceType#chflags(CmsObject, CmsSecurityManager, CmsResource, int) */ public void chflags(CmsRequestContext context, CmsResource resource, int flags) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.chflags(dbc, resource, flags); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_CHANGE_RESOURCE_FLAGS_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Changes the resource type of a resource.<p> * * OpenCms handles resources according to the resource type, * not the file suffix. This is e.g. why a JSP in OpenCms can have the * suffix ".html" instead of ".jsp" only. Changing the resource type * makes sense e.g. if you want to make a plain text file a JSP resource, * or a binary file an image, etc.<p> * * @param context the current request context * @param resource the resource to change the type for * @param type the new resource type for this resource * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (({@link CmsPermissionSet#ACCESS_WRITE} required)). * * @see org.opencms.file.types.I_CmsResourceType#chtype(CmsObject, CmsSecurityManager, CmsResource, int) * @see CmsObject#chtype(String, int) */ public void chtype(CmsRequestContext context, CmsResource resource, int type) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.chtype(dbc, resource, type); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_CHANGE_RESOURCE_TYPE_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Copies the access control entries of a given resource to a destination resorce.<p> * * Already existing access control entries of the destination resource are removed.<p> * * @param context the current request context * @param source the resource to copy the access control entries from * @param destination the resource to which the access control entries are copied * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource ({@link CmsPermissionSet#ACCESS_CONTROL} required). */ public void copyAccessControlEntries(CmsRequestContext context, CmsResource source, CmsResource destination) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, source, CmsPermissionSet.ACCESS_READ, true, CmsResourceFilter.ALL); checkPermissions(dbc, destination, CmsPermissionSet.ACCESS_CONTROL, true, CmsResourceFilter.ALL); m_driverManager.copyAccessControlEntries(dbc, source, destination); } catch (Exception e) { CmsRequestContext rc = context; dbc.report(null, Messages.get().container( Messages.ERR_COPY_ACE_2, rc.removeSiteRoot(source.getRootPath()), rc.removeSiteRoot(destination.getRootPath())), e); } finally { dbc.clear(); } } /** * Copies a resource.<p> * * You must ensure that the destination path is an absolute, valid and * existing VFS path. Relative paths from the source are currently not supported.<p> * * The copied resource will always be locked to the current user * after the copy operation.<p> * * In case the target resource already exists, it is overwritten with the * source resource.<p> * * The <code>siblingMode</code> parameter controls how to handle siblings * during the copy operation.<br> * Possible values for this parameter are: <br> * <ul> * <li><code>{@link org.opencms.main.I_CmsConstants#C_COPY_AS_NEW}</code></li> * <li><code>{@link org.opencms.main.I_CmsConstants#C_COPY_AS_SIBLING}</code></li> * <li><code>{@link org.opencms.main.I_CmsConstants#C_COPY_PRESERVE_SIBLING}</code></li> * </ul><p> * * @param context the current request context * @param source the resource to copy * @param destination the name of the copy destination with complete path * @param siblingMode indicates how to handle siblings during copy * * @throws CmsException if something goes wrong * @throws CmsSecurityException if resource could not be copied * * @see CmsObject#copyResource(String, String, int) * @see org.opencms.file.types.I_CmsResourceType#copyResource(CmsObject, CmsSecurityManager, CmsResource, String, int) */ public void copyResource(CmsRequestContext context, CmsResource source, String destination, int siblingMode) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsRequestContext rc = context; try { checkOfflineProject(dbc); checkPermissions(dbc, source, CmsPermissionSet.ACCESS_READ, true, CmsResourceFilter.ALL); // target permissions will be checked later m_driverManager.copyResource(dbc, source, destination, siblingMode); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_COPY_RESOURCE_2, rc.removeSiteRoot(source.getRootPath()), rc.removeSiteRoot(destination)), e); } finally { dbc.clear(); } } /** * Copies a resource to the current project of the user.<p> * * @param context the current request context * @param resource the resource to apply this operation to * @throws CmsException if something goes wrong * @throws CmsRoleViolationException if the current user does not have management access to the project. * @see org.opencms.file.types.I_CmsResourceType#copyResourceToProject(CmsObject, CmsSecurityManager, CmsResource) */ public void copyResourceToProject(CmsRequestContext context, CmsResource resource) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkManagerOfProjectRole(dbc, context.currentProject()); if (dbc.currentProject().getFlags() != I_CmsConstants.C_PROJECT_STATE_UNLOCKED) { throw new CmsLockException(org.opencms.lock.Messages.get().container( org.opencms.lock.Messages.ERR_RESOURCE_LOCKED_1, dbc.currentProject().getName())); } m_driverManager.copyResourceToProject(dbc, resource); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_COPY_RESOURCE_TO_PROJECT_2, context.getSitePath(resource), context.currentProject().getName()), e); } finally { dbc.clear(); } } /** * Counts the locked resources in this project.<p> * * @param context the current request context * @param id the id of the project * * @return the amount of locked resources in this project * * @throws CmsException if something goes wrong * @throws CmsRoleViolationException if the current user does not have management access to the project. */ public int countLockedResources(CmsRequestContext context, int id) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsProject project = null; int result = 0; try { project = m_driverManager.readProject(dbc, id); checkManagerOfProjectRole(dbc, project); result = m_driverManager.countLockedResources(project); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_COUNT_LOCKED_RESOURCES_PROJECT_2, (project == null) ? "<failed to read>" : project.getName(), new Integer(id)), e); } finally { dbc.clear(); } return result; } /** * Counts the locked resources in a given folder.<p> * * @param context the current request context * @param foldername the folder to search in * * @return the amount of locked resources in this project * * @throws CmsException if something goes wrong */ public int countLockedResources(CmsRequestContext context, String foldername) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); // perform a test for read permissions on the folder readResource(dbc, foldername, CmsResourceFilter.ALL); int result = 0; try { result = m_driverManager.countLockedResources(dbc, foldername); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_COUNT_LOCKED_RESOURCES_FOLDER_1, foldername), e); } finally { dbc.clear(); } return result; } /** * Creates a new user group.<p> * * @param context the current request context * @param name the name of the new group * @param description the description for the new group * @param flags the flags for the new group * @param parent the name of the parent group (or <code>null</code>) * * @return a <code>{@link CmsGroup}</code> object representing the newly created group * * @throws CmsException if operation was not successful. * @throws CmsRoleViolationException if the role {@link CmsRole#USER_MANAGER} is not owned by the current user. * */ public CmsGroup createGroup(CmsRequestContext context, String name, String description, int flags, String parent) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsGroup result = null; try { checkRole(dbc, CmsRole.USER_MANAGER); result = m_driverManager.createGroup(dbc, new CmsUUID(), name, description, flags, parent); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_GROUP_1, name), e); } finally { dbc.clear(); } return result; } /** * Creates a project.<p> * * @param context the current request context * @param name the name of the project to create * @param description the description of the project * @param groupname the project user group to be set * @param managergroupname the project manager group to be set * @param projecttype the type of the project * * @return the created project * * @throws CmsException if something goes wrong * @throws CmsRoleViolationException if the current user does not own the role {@link CmsRole#PROJECT_MANAGER}. */ public CmsProject createProject( CmsRequestContext context, String name, String description, String groupname, String managergroupname, int projecttype) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsProject result = null; try { checkRole(dbc, CmsRole.PROJECT_MANAGER); result = m_driverManager.createProject(dbc, name, description, groupname, managergroupname, projecttype); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_PROJECT_1, name), e); } finally { dbc.clear(); } return result; } /** * Creates a property definition.<p> * * Property definitions are valid for all resource types.<p> * * @param context the current request context * @param name the name of the property definition to create * * @return the created property definition * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the current project is online. * @throws CmsRoleViolationException if the current user does not own the role {@link CmsRole#PROPERTY_MANAGER}. */ public CmsPropertyDefinition createPropertyDefinition(CmsRequestContext context, String name) throws CmsException, CmsSecurityException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsPropertyDefinition result = null; try { checkOfflineProject(dbc); checkRole(dbc, CmsRole.PROPERTY_MANAGER); result = m_driverManager.createPropertyDefinition(dbc, name); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_PROPDEF_1, name), e); } finally { dbc.clear(); } return result; } /** * Creates a new resource of the given resource type with the provided content and properties.<p> * * If the provided content is null and the resource is not a folder, the content will be set to an empty byte array.<p> * * @param context the current request context * @param resourcename the name of the resource to create (full path) * @param type the type of the resource to create * @param content the content for the new resource * @param properties the properties for the new resource * @return the created resource * @throws CmsException if something goes wrong * * @see org.opencms.file.types.I_CmsResourceType#createResource(CmsObject, CmsSecurityManager, String, byte[], List) */ public CmsResource createResource( CmsRequestContext context, String resourcename, int type, byte[] content, List properties) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsResource newResource = null; try { checkOfflineProject(dbc); newResource = m_driverManager.createResource(dbc, resourcename, type, content, properties); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_RESOURCE_1, resourcename), e); } finally { dbc.clear(); } return newResource; } /** * Creates a new sibling of the source resource.<p> * * @param context the current request context * @param source the resource to create a sibling for * @param destination the name of the sibling to create with complete path * @param properties the individual properties for the new sibling * @throws CmsException if something goes wrong * @see org.opencms.file.types.I_CmsResourceType#createSibling(CmsObject, CmsSecurityManager, CmsResource, String, List) */ public void createSibling(CmsRequestContext context, CmsResource source, String destination, List properties) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); m_driverManager.createSibling(dbc, source, destination, properties); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_CREATE_SIBLING_1, context.removeSiteRoot(source.getRootPath())), e); } finally { dbc.clear(); } } /** * Creates a new task.<p> * * @param context the current request context * @param currentUser the current user * @param projectid the current project id * @param agentName user who will edit the task * @param roleName usergroup for the task * @param taskName name of the task * @param taskType type of the task * @param taskComment description of the task * @param timeout time when the task must finished * @param priority Id for the priority * * @return a new task object * * @throws CmsException if something goes wrong */ public CmsTask createTask( CmsRequestContext context, CmsUser currentUser, int projectid, String agentName, String roleName, String taskName, String taskComment, int taskType, long timeout, int priority) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsTask result = null; try { result = m_driverManager.createTask( dbc, currentUser, projectid, agentName, roleName, taskName, taskComment, taskType, timeout, priority); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_TASK_1, taskName), e); } finally { dbc.clear(); } return result; } /** * Creates a new task.<p> * * This is just a more limited version of the * <code>{@link #createTask(CmsRequestContext, CmsUser, int, String, String, String, String, int, long, int)}</code> * method, where: <br> * <ul> * <il>the project id is the current project id.</il> * <il>the task type is the standard task type <b>1</b>.</il> * <il>with no comments</il> * </ul><p> * * @param context the current request context * @param agentName the user who will edit the task * @param roleName a usergroup for the task * @param taskname the name of the task * @param timeout the time when the task must finished * @param priority the id for the priority of the task * * @return the created task * * @throws CmsException if something goes wrong */ public CmsTask createTask( CmsRequestContext context, String agentName, String roleName, String taskname, long timeout, int priority) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsTask result = null; try { result = m_driverManager.createTask(dbc, agentName, roleName, taskname, timeout, priority); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_TASK_1, taskname), e); } finally { dbc.clear(); } return result; } /** * Creates the project for the temporary workplace files.<p> * * @param context the current request context * * @return the created project for the temporary workplace files * * @throws CmsException if something goes wrong */ public CmsProject createTempfileProject(CmsRequestContext context) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsProject result = null; try { checkRole(dbc, CmsRole.PROJECT_MANAGER); result = m_driverManager.createTempfileProject(dbc); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_TEMPFILE_PROJECT_0), e); } finally { dbc.clear(); } return result; } /** * Creates a new user.<p> * * @param context the current request context * @param name the name for the new user * @param password the password for the new user * @param description the description for the new user * @param additionalInfos the additional infos for the user * * @return the created user * * @see CmsObject#createUser(String, String, String, Map) * * @throws CmsException if something goes wrong * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#USER_MANAGER} */ public CmsUser createUser( CmsRequestContext context, String name, String password, String description, Map additionalInfos) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { checkRole(dbc, CmsRole.USER_MANAGER); result = m_driverManager.createUser(dbc, name, password, description, additionalInfos); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_USER_1, name), e); } finally { dbc.clear(); } return result; } /** * Deletes all entries in the published resource table.<p> * * @param context the current request context * @param linkType the type of resource deleted (0= non-paramter, 1=parameter) * * @throws CmsException if something goes wrong */ public void deleteAllStaticExportPublishedResources(CmsRequestContext context, int linkType) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.deleteAllStaticExportPublishedResources(dbc, linkType); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DELETE_STATEXP_PUBLISHED_RESOURCES_0), e); } finally { dbc.clear(); } } /** * Deletes the versions from the backup tables that are older then the given timestamp * and/or number of remaining versions.<p> * * The number of verions always wins, i.e. if the given timestamp would delete more versions * than given in the versions parameter, the timestamp will be ignored. <p> * * Deletion will delete file header, content and properties. <p> * * @param context the current request context * @param timestamp timestamp which defines the date after which backup resources must be deleted * @param versions the number of versions per file which should kept in the system * @param report the report for output logging * * @throws CmsException if operation was not succesful * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#HISTORY_MANAGER} */ public void deleteBackups(CmsRequestContext context, long timestamp, int versions, I_CmsReport report) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.HISTORY_MANAGER); m_driverManager.deleteBackups(dbc, timestamp, versions, report); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_DELETE_BACKUPS_2, new Date(timestamp), new Integer(versions)), e); } finally { dbc.clear(); } } /** * Delete a user group.<p> * * Only groups that contain no subgroups can be deleted.<p> * * @param context the current request context * @param name the name of the group that is to be deleted * * @throws CmsException if operation was not succesful * @throws CmsSecurityException if the group is a default group. * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#USER_MANAGER} * */ public void deleteGroup(CmsRequestContext context, String name) throws CmsException, CmsRoleViolationException, CmsSecurityException { if (OpenCms.getDefaultUsers().isDefaultGroup(name)) { throw new CmsSecurityException(Messages.get().container( Messages.ERR_CONSTRAINT_DELETE_GROUP_DEFAULT_1, name)); } CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { // catch own exception as special cause for general "Error deleting group". checkRole(dbc, CmsRole.USER_MANAGER); m_driverManager.deleteGroup(dbc, name); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DELETE_GROUP_1, name), e); } finally { dbc.clear(); } } /** * Deletes a project.<p> * * All modified resources currently inside this project will be reset to their online state.<p> * * @param context the current request context * @param projectId the ID of the project to be deleted * * @throws CmsException if something goes wrong * @throws CmsRoleViolationException if the current user does not own management access to the project */ public void deleteProject(CmsRequestContext context, int projectId) throws CmsException, CmsRoleViolationException { if (projectId == I_CmsConstants.C_PROJECT_ONLINE_ID) { // online project must not be deleted throw new CmsVfsException(org.opencms.file.Messages.get().container( org.opencms.file.Messages.ERR_NOT_ALLOWED_IN_ONLINE_PROJECT_0)); } if (projectId == context.currentProject().getId()) { // current project must not be deleted throw new CmsVfsException(Messages.get().container( Messages.ERR_DELETE_PROJECT_CURRENT_1, context.currentProject().getName())); } CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsProject deleteProject = null; try { // read the project that should be deleted deleteProject = m_driverManager.readProject(dbc, projectId); checkManagerOfProjectRole(dbc, context.currentProject()); m_driverManager.deleteProject(dbc, deleteProject); } catch (Exception e) { String projectName = deleteProject == null ? String.valueOf(projectId) : deleteProject.getName(); dbc.report(null, Messages.get().container(Messages.ERR_DELETE_PROJECT_1, projectName), e); } finally { dbc.clear(); } } /** * Deletes a property definition.<p> * * @param context the current request context * @param name the name of the property definition to delete * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the project to delete is the "Online" project * @throws CmsRoleViolationException if the current user does not own the role {@link CmsRole#PROPERTY_MANAGER} */ public void deletePropertyDefinition(CmsRequestContext context, String name) throws CmsException, CmsSecurityException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkRole(dbc, CmsRole.PROPERTY_MANAGER); m_driverManager.deletePropertyDefinition(dbc, name); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DELETE_PROPERTY_1, name), e); } finally { dbc.clear(); } } /** * Deletes a resource given its name.<p> * * The <code>siblingMode</code> parameter controls how to handle siblings * during the delete operation.<br> * Possible values for this parameter are: <br> * <ul> * <li><code>{@link org.opencms.main.I_CmsConstants#C_DELETE_OPTION_DELETE_SIBLINGS}</code></li> * <li><code>{@link org.opencms.main.I_CmsConstants#C_DELETE_OPTION_PRESERVE_SIBLINGS}</code></li> * </ul><p> * * @param context the current request context * @param resource the name of the resource to delete (full path) * @param siblingMode indicates how to handle siblings of the deleted resource * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user does not have {@link CmsPermissionSet#ACCESS_WRITE} on the given resource. * @see org.opencms.file.types.I_CmsResourceType#deleteResource(CmsObject, CmsSecurityManager, CmsResource, int) */ public void deleteResource(CmsRequestContext context, CmsResource resource, int siblingMode) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.deleteResource(dbc, resource, siblingMode); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DELETE_RESOURCE_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Deletes an entry in the published resource table.<p> * * @param context the current request context * @param resourceName The name of the resource to be deleted in the static export * @param linkType the type of resource deleted (0= non-paramter, 1=parameter) * @param linkParameter the parameters ofthe resource * * @throws CmsException if something goes wrong */ public void deleteStaticExportPublishedResource( CmsRequestContext context, String resourceName, int linkType, String linkParameter) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.deleteStaticExportPublishedResource(dbc, resourceName, linkType, linkParameter); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_DELETE_STATEXP_PUBLISHES_RESOURCE_1, resourceName), e); } finally { dbc.clear(); } } /** * Deletes a user.<p> * * @param context the current request context * @param userId the Id of the user to be deleted * * @throws CmsException if something goes wrong */ public void deleteUser(CmsRequestContext context, CmsUUID userId) throws CmsException { CmsUser user = readUser(context, userId); deleteUser(context, user); } /** * Deletes a user.<p> * * @param context the current request context * @param username the name of the user to be deleted * * @throws CmsException if something goes wrong */ public void deleteUser(CmsRequestContext context, String username) throws CmsException { CmsUser user = readUser(context, username, CmsUser.USER_TYPE_SYSTEMUSER); deleteUser(context, user); } /** * Deletes a web user.<p> * * @param context the current request context * @param userId the Id of the web user to be deleted * * @throws CmsException if something goes wrong */ public void deleteWebUser(CmsRequestContext context, CmsUUID userId) throws CmsException { CmsUser user = readUser(context, userId); deleteUser(context, user); } /** * Destroys this security manager.<p> * * @throws Throwable if something goes wrong */ public void destroy() throws Throwable { finalize(); if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().key(Messages.INIT_SECURITY_MANAGER_SHUTDOWN_1, this.getClass().getName())); } } /** * Ends a task.<p> * * @param context the current request context * @param taskid the ID of the task to end * * @throws CmsException if something goes wrong */ public void endTask(CmsRequestContext context, int taskid) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.endTask(dbc, taskid); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_END_TASK_1, new Integer(taskid)), e); } finally { dbc.clear(); } } /** * Checks the availability of a resource in the VFS, * using the <code>{@link CmsResourceFilter#DEFAULT}</code> filter.<p> * * A resource may be of type <code>{@link CmsFile}</code> or * <code>{@link CmsFolder}</code>.<p> * * The specified filter controls what kind of resources should be "found" * during the read operation. This will depend on the application. For example, * using <code>{@link CmsResourceFilter#DEFAULT}</code> will only return currently * "valid" resources, while using <code>{@link CmsResourceFilter#IGNORE_EXPIRATION}</code> * will ignore the date release / date expired information of the resource.<p> * * This method also takes into account the user permissions, so if * the given resource exists, but the current user has not the required * permissions, then this method will return <code>false</code>.<p> * * @param context the current request context * @param resourcePath the name of the resource to read (full path) * @param filter the resource filter to use while reading * * @return <code>true</code> if the resource is available * * @see CmsObject#existsResource(String, CmsResourceFilter) * @see CmsObject#existsResource(String) */ public boolean existsResource(CmsRequestContext context, String resourcePath, CmsResourceFilter filter) { boolean result = false; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { readResource(dbc, resourcePath, filter); result = true; } catch (Exception e) { result = false; } finally { dbc.clear(); } return result; } /** * Forwards a task to a new user.<p> * * @param context the current request context * @param taskid the Id of the task to forward * @param newRoleName the new group name for the task * @param newUserName the new user who gets the task. if it is empty, a new agent will automatic selected * * @throws CmsException if something goes wrong */ public void forwardTask(CmsRequestContext context, int taskid, String newRoleName, String newUserName) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.forwardTask(dbc, taskid, newRoleName, newUserName); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_FORWARD_TASK_3, new Integer(taskid), newUserName, newRoleName), e); } finally { dbc.clear(); } } /** * Returns the list of access control entries of a resource given its name.<p> * * @param context the current request context * @param resource the resource to read the access control entries for * @param getInherited true if the result should include all access control entries inherited by parent folders * * @return a list of <code>{@link CmsAccessControlEntry}</code> objects defining all permissions for the given resource * * @throws CmsException if something goes wrong */ public List getAccessControlEntries(CmsRequestContext context, CmsResource resource, boolean getInherited) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.getAccessControlEntries(dbc, resource, getInherited); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_ACL_ENTRIES_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Returns the access control list (summarized access control entries) of a given resource.<p> * * If <code>inheritedOnly</code> is set, only inherited access control entries are returned.<p> * * @param context the current request context * @param resource the resource * @param inheritedOnly skip non-inherited entries if set * * @return the access control list of the resource * * @throws CmsException if something goes wrong */ public CmsAccessControlList getAccessControlList( CmsRequestContext context, CmsResource resource, boolean inheritedOnly) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsAccessControlList result = null; try { result = m_driverManager.getAccessControlList(dbc, resource, inheritedOnly); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_ACL_ENTRIES_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Returns all projects which are owned by the current user or which are * accessible for the group of the user.<p> * * @param context the current request context * * @return a list of objects of type <code>{@link CmsProject}</code> * * @throws CmsException if something goes wrong */ public List getAllAccessibleProjects(CmsRequestContext context) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.getAllAccessibleProjects(dbc); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_GET_ALL_ACCESSIBLE_PROJECTS_1, dbc.currentUser().getName()), e); } finally { dbc.clear(); } return result; } /** * Returns a list with all projects from history.<p> * * @param context the current request context * * @return list of <code>{@link CmsBackupProject}</code> objects * with all projects from history. * * @throws CmsException if operation was not succesful */ public List getAllBackupProjects(CmsRequestContext context) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.getAllBackupProjects(dbc); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_GET_ALL_ACCESSIBLE_PROJECTS_1, dbc.currentUser().getName()), e); } finally { dbc.clear(); } return result; } /** * Returns all projects which are owned by the current user or which are manageable * for the group of the user.<p> * * @param context the current request context * * @return a list of objects of type <code>{@link CmsProject}</code> * * @throws CmsException if operation was not succesful */ public List getAllManageableProjects(CmsRequestContext context) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.getAllManageableProjects(dbc); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_GET_ALL_MANAGEABLE_PROJECTS_1, dbc.currentUser().getName()), e); } finally { dbc.clear(); } return result; } /** * Returns the next version id for the published backup resources.<p> * * @param context the current request context * * @return the new version id */ public int getBackupTagId(CmsRequestContext context) { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); int result = 0; try { result = m_driverManager.getBackupTagId(dbc); } finally { dbc.clear(); } return result; } /** * Returns all child groups of a group.<p> * * @param context the current request context * @param groupname the name of the group * * @return a list of all child <code>{@link CmsGroup}</code> objects or <code>null</code> * * @throws CmsException if operation was not succesful */ public List getChild(CmsRequestContext context, String groupname) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { checkRole(dbc, CmsRole.SYSTEM_USER); result = m_driverManager.getChild(dbc, groupname); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_CHILD_GROUPS_1, groupname), e); } finally { dbc.clear(); } return result; } /** * Returns all child groups of a group.<p> * * This method also returns all sub-child groups of the current group.<p> * * @param context the current request context * @param groupname the name of the group * * @return a list of all child <code>{@link CmsGroup}</code> objects or <code>null</code> * * @throws CmsException if operation was not succesful */ public List getChilds(CmsRequestContext context, String groupname) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { checkRole(dbc, CmsRole.SYSTEM_USER); result = m_driverManager.getChilds(dbc, groupname); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_CHILD_GROUPS_TRANSITIVE_1, groupname), e); } finally { dbc.clear(); } return result; } /** * Gets the configurations of the OpenCms properties file.<p> * * @return the configurations of the properties file */ public Map getConfigurations() { return m_driverManager.getConfigurations(); } /** * Returns the list of groups to which the user directly belongs to.<p> * * @param context the current request context * @param username The name of the user * * @return a list of <code>{@link CmsGroup}</code> objects * * @throws CmsException if operation was not succesful */ public List getDirectGroupsOfUser(CmsRequestContext context, String username) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.getDirectGroupsOfUser(dbc, username); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_DIRECT_GROUP_OF_USER_1, username), e); } finally { dbc.clear(); } return result; } /** * Returns all available groups.<p> * * @param context the current request context * * @return a list of all available <code>{@link CmsGroup}</code> objects * * @throws CmsException if operation was not succesful */ public List getGroups(CmsRequestContext context) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { checkRole(dbc, CmsRole.SYSTEM_USER); result = m_driverManager.getGroups(dbc); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_GROUPS_0), e); } finally { dbc.clear(); } return result; } /** * Returns the groups of a user.<p> * * @param context the current request context * @param username the name of the user * * @return a list of <code>{@link CmsGroup}</code> objects * * @throws CmsException if operation was not succesful */ public List getGroupsOfUser(CmsRequestContext context, String username) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.getGroupsOfUser(dbc, username); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_GROUPS_OF_USER_1, username), e); } finally { dbc.clear(); } return result; } /** * Returns the groups of a Cms user filtered by the specified IP address.<p> * * @param context the current request context * @param username the name of the user * @param remoteAddress the IP address to filter the groups in the result list * * @return a list of <code>{@link CmsGroup}</code> objects filtered by the specified IP address * * @throws CmsException if operation was not succesful */ public List getGroupsOfUser(CmsRequestContext context, String username, String remoteAddress) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.getGroupsOfUser(dbc, username, remoteAddress); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_GROUPS_OF_USER_2, username, remoteAddress), e); } finally { dbc.clear(); } return result; } /** * Returns the lock state of a resource.<p> * * @param context the current request context * @param resource the resource to return the lock state for * @return the lock state of the resource * @throws CmsException if something goes wrong */ public CmsLock getLock(CmsRequestContext context, CmsResource resource) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsLock result = null; try { result = m_driverManager.getLock(dbc, resource); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_LOCK_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Returns the parent group of a group.<p> * * @param context the current request context * @param groupname the name of the group * * @return group the parent group or <code>null</code> * * @throws CmsException if operation was not succesful */ public CmsGroup getParent(CmsRequestContext context, String groupname) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsGroup result = null; try { result = m_driverManager.getParent(dbc, groupname); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_PARENT_GROUP_1, groupname), e); } finally { dbc.clear(); } return result; } /** * Returns the set of permissions of the current user for a given resource.<p> * * @param context the current request context * @param resource the resource * @param user the user * * @return bitset with allowed permissions * * @throws CmsException if something goes wrong */ public CmsPermissionSetCustom getPermissions(CmsRequestContext context, CmsResource resource, CmsUser user) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsPermissionSetCustom result = null; try { result = m_driverManager.getPermissions(dbc, resource, user); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_GET_PERMISSIONS_2, user.getName(), context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Returns a Cms publish list object containing the Cms resources that actually get published.<p> * * <ul> * <li> * <b>Case 1 (publish project)</b>: all new/changed/deleted Cms file resources in the current (offline) * project are inspected whether they would get published or not. * </li> * <li> * <b>Case 2 (direct publish a resource)</b>: a specified Cms file resource and optionally it's siblings * are inspected whether they get published. * </li> * </ul> * * All <code>{@link CmsResource}</code> objects inside the publish ist are equipped with their full * resource name including the site root.<p> * * Please refer to the source code of this method for the rules on how to decide whether a * new/changed/deleted <code>{@link CmsResource}</code> object can be published or not.<p> * * @param context the current request context * @param directPublishResource a <code>{@link CmsResource}</code> to be published directly (in case 2), * or <code>null</code> (in case 1). * @param publishSiblings <code>true</code>, if all eventual siblings of the direct published resource * should also get published (in case 2). * * @return a publish list with all new/changed/deleted files from the current (offline) project that will be published actually * * @throws CmsException if something goes wrong * * @see org.opencms.db.CmsPublishList */ public synchronized CmsPublishList getPublishList( CmsRequestContext context, CmsResource directPublishResource, boolean publishSiblings) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsPublishList result = null; try { result = m_driverManager.getPublishList(dbc, directPublishResource, publishSiblings); } catch (Exception e) { if (directPublishResource != null) { dbc.report(null, Messages.get().container( Messages.ERR_GET_PUBLISH_LIST_DIRECT_1, context.removeSiteRoot(directPublishResource.getRootPath())), e); } else { dbc.report(null, Messages.get().container( Messages.ERR_GET_PUBLISH_LIST_PROJECT_1, context.currentProject().getName()), e); } } finally { dbc.clear(); } return result; } /** * Returns a list with all sub resources of the given parent folder (and all of it's subfolders) * that have been modified in the given time range.<p> * * The result list is descending sorted (newest resource first).<p> * * @param context the current request context * @param folder the folder to get the subresources from * @param starttime the begin of the time range * @param endtime the end of the time range * * @return a list with all <code>{@link CmsResource}</code> objects * that have been modified in the given time range. * * @throws CmsException if operation was not succesful */ public List getResourcesInTimeRange(CmsRequestContext context, String folder, long starttime, long endtime) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.getResourcesInTimeRange(dbc, folder, starttime, endtime); } catch (Exception e) { // todo: possibly the folder arg is a root path, then use // context.removeSiteRoot(folder) before output. dbc.report(null, Messages.get().container( Messages.ERR_GET_RESOURCES_IN_TIME_RANGE_3, folder, new Date(starttime), new Date(endtime)), e); } finally { dbc.clear(); } return result; } /** * Returns an instance of the common sql manager.<p> * * @return an instance of the common sql manager */ public CmsSqlManager getSqlManager() { return m_driverManager.getSqlManager(); } /** * Returns the value of the given parameter for the given task.<p> * * @param context the current request context * @param taskId the Id of the task * @param parName name of the parameter * * @return task parameter value * * @throws CmsException if something goes wrong */ public String getTaskPar(CmsRequestContext context, int taskId, String parName) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); String result = null; try { result = m_driverManager.getTaskPar(dbc, taskId, parName); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_TASK_PARAM_2, parName, new Integer(taskId)), e); } finally { dbc.clear(); } return result; } /** * Get the template task id for a given taskname.<p> * * @param context the current request context * @param taskName name of the task * * @return id from the task template * * @throws CmsException if something goes wrong */ public int getTaskType(CmsRequestContext context, String taskName) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); int result = 0; try { result = m_driverManager.getTaskType(dbc, taskName); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_TASK_TYPE_1, taskName), e); } finally { dbc.clear(); } return result; } /** * Returns all available users.<p> * * @param context the current request context * * @return a list of all available <code>{@link CmsUser}</code> objects * * @throws CmsException if operation was not succesful */ public List getUsers(CmsRequestContext context) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { checkRole(dbc, CmsRole.SYSTEM_USER); result = m_driverManager.getUsers(dbc); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_USERS_0), e); } finally { dbc.clear(); } return result; } /** * Returns all users from a given type.<p> * * @param context the current request context * @param type the type of the users * * @return a list of all <code>{@link CmsUser}</code> objects of the given type * * @throws CmsException if operation was not succesful */ public List getUsers(CmsRequestContext context, int type) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { checkRole(dbc, CmsRole.SYSTEM_USER); result = m_driverManager.getUsers(dbc, type); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_USERS_OF_TYPE_1, new Integer(type)), e); } finally { dbc.clear(); } return result; } /** * Returns a list of users in a group.<p> * * @param context the current request context * @param groupname the name of the group to list users from * * @return all <code>{@link CmsUser}</code> objects in the group * * @throws CmsException if operation was not succesful */ public List getUsersOfGroup(CmsRequestContext context, String groupname) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { checkRole(dbc, CmsRole.SYSTEM_USER); result = m_driverManager.getUsersOfGroup(dbc, groupname); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_USERS_OF_GROUP_1, groupname), e); } finally { dbc.clear(); } return result; } /** * Checks if the current user has management access to the given project.<p> * * @param dbc the current database context * @param project the project to check * * @return <code>true</code>, if the user has management access to the project */ public boolean hasManagerOfProjectRole(CmsDbContext dbc, CmsProject project) { if (dbc.currentProject().isOnlineProject()) { // no user is the project manager of the "Online" project return false; } if (dbc.currentUser().getId().equals(project.getOwnerId())) { // user is the owner of the current project return true; } if (hasRole(dbc, CmsRole.PROJECT_MANAGER)) { // user is admin return true; } // get all groups of the user List groups; try { groups = m_driverManager.getGroupsOfUser(dbc, dbc.currentUser().getName()); } catch (CmsException e) { // any exception: result is false return false; } for (int i = 0; i < groups.size(); i++) { // check if the user is a member in the current projects manager group if (((CmsGroup)groups.get(i)).getId().equals(project.getManagerGroupId())) { // this group is manager of the project return true; } } // the user is not manager of the current project return false; } /** * Performs a non-blocking permission check on a resource.<p> * * This test will not throw an exception in case the required permissions are not * available for the requested operation. Instead, it will return one of the * following values:<ul> * <li><code>{@link #PERM_ALLOWED}</code></li> * <li><code>{@link #PERM_FILTERED}</code></li> * <li><code>{@link #PERM_DENIED}</code></li></ul><p> * * @param context the current request context * @param resource the resource on which permissions are required * @param requiredPermissions the set of permissions required for the operation * @param checkLock if true, a lock for the current user is required for * all write operations, if false it's ok to write as long as the resource * is not locked by another user * @param filter the resource filter to use * * @return <code>{@link #PERM_ALLOWED}</code> if the user has sufficient permissions on the resource * for the requested operation * * @throws CmsException in case of i/o errors (NOT because of insufficient permissions) * * @see #hasPermissions(CmsDbContext, CmsResource, CmsPermissionSet, boolean, CmsResourceFilter) */ public int hasPermissions( CmsRequestContext context, CmsResource resource, CmsPermissionSet requiredPermissions, boolean checkLock, CmsResourceFilter filter) throws CmsException { int result = 0; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = hasPermissions(dbc, resource, requiredPermissions, checkLock, filter); } finally { dbc.clear(); } return result; } /** * Checks if the given resource or the current project can be published by the current user * using his current OpenCms context.<p> * * If the resource parameter is <code>null</code>, then the current project is checked, * otherwise the resource is checked for direct publish permissions.<p> * * @param context the current request context * @param directPublishResource the direct publish resource (optional, if null only the current project is checked) * * @return <code>true</code>, if the current user can direct publish the given resource in his current context */ public boolean hasPublishPermissions(CmsRequestContext context, CmsResource directPublishResource) { try { checkPublishPermissions(context, directPublishResource); } catch (CmsException e) { return false; } return true; } /** * Checks if the user of the current database context is a member of the given role.<p> * * @param dbc the current OpenCms users database context * @param role the role to check * * @return <code>true</code> if the user of the current database context is at a member of at last * one of the roles in the given role set */ public boolean hasRole(CmsDbContext dbc, CmsRole role) { return hasRole(dbc, dbc.currentUser(), role); } /** * Checks if the given user is a member of the given role.<p> * * @param dbc the current OpenCms users database context * @param user the user to check the role for * @param role the role to check * * @return <code>true</code> if the user of the current database context is at a member of at last * one of the roles in the given role set */ public boolean hasRole(CmsDbContext dbc, CmsUser user, CmsRole role) { // read all groups of the current user List groups; try { groups = m_driverManager.getGroupsOfUser(dbc, user.getName(), dbc.getRequestContext().getRemoteAddress()); } catch (CmsException e) { // any exception: return false return false; } return role.hasRole(groups); } /** * Checks if the user of the given request context * is a member of at last one of the roles in the given role set.<p> * * @param context the current request context * @param role the role to check * * @return <code>true</code> if the user of given request context is at a member of at last * one of the roles in the given role set */ public boolean hasRole(CmsRequestContext context, CmsRole role) { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); boolean result; try { result = hasRole(dbc, role); } finally { dbc.clear(); } return result; } /** * Writes a list of access control entries as new access control entries of a given resource.<p> * * Already existing access control entries of this resource are removed before.<p> * * Access is granted, if:<p> * <ul> * <li>the current user has control permission on the resource</li> * </ul><p> * * @param context the current request context * @param resource the resource * @param acEntries a list of <code>{@link CmsAccessControlEntry}</code> objects * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the required permissions are not satisfied */ public void importAccessControlEntries(CmsRequestContext context, CmsResource resource, List acEntries) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_CONTROL, true, CmsResourceFilter.ALL); m_driverManager.importAccessControlEntries(dbc, resource, acEntries); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_IMPORT_ACL_ENTRIES_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Creates a new resource with the provided content and properties.<p> * * The <code>content</code> parameter may be null if the resource id already exists. * If so, the created resource will be made a sibling of the existing resource, * the existing content will remain unchanged. * This is used during file import for import of siblings as the * <code>manifest.xml</code> only contains one binary copy per file. * If the resource id exists but the <code>content</code> is not null, * the created resource will be made a sibling of the existing resource, * and both will share the new content.<p> * * Note: the id used to identify the content record (pk of the record) is generated * on each call of this method (with valid content) ! * * @param context the current request context * @param resourcePath the name of the resource to create (full path) * @param resource the new resource to create * @param content the content for the new resource * @param properties the properties for the new resource * @param importCase if true, signals that this operation is done while importing resource, causing different lock behaviour and potential "lost and found" usage * @return the created resource * @throws CmsException if something goes wrong */ public CmsResource importResource( CmsRequestContext context, String resourcePath, CmsResource resource, byte[] content, List properties, boolean importCase) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsResource newResource = null; try { checkOfflineProject(dbc); newResource = m_driverManager.createResource(dbc, resourcePath, resource, content, properties, importCase); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_IMPORT_RESOURCE_2, context.getSitePath(resource), resourcePath), e); } finally { dbc.clear(); } return newResource; } /** * Creates a new user by import.<p> * * @param context the current request context * @param id the id of the user * @param name the new name for the user * @param password the new password for the user * @param description the description for the user * @param firstname the firstname of the user * @param lastname the lastname of the user * @param email the email of the user * @param address the address of the user * @param flags the flags for a user (for example <code>{@link I_CmsConstants#C_FLAG_ENABLED}</code>) * @param type the type of the user * @param additionalInfos the additional user infos * * @return the imported user * * @throws CmsException if something goes wrong * @throws CmsRoleViolationException if the role {@link CmsRole#USER_MANAGER} is not owned by the current user. */ public CmsUser importUser( CmsRequestContext context, String id, String name, String password, String description, String firstname, String lastname, String email, String address, int flags, int type, Map additionalInfos) throws CmsException, CmsRoleViolationException { CmsUser newUser = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.USER_MANAGER); newUser = m_driverManager.importUser( dbc, id, name, password, description, firstname, lastname, email, address, flags, type, additionalInfos); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_IMPORT_USER_9, new Object[] { id, name, description, firstname, lastname, email, address, new Integer(flags), new Integer(type), additionalInfos}), e); } finally { dbc.clear(); } return newUser; } /** * Initializes this security manager with a given runtime info factory.<p> * * @param configurationManager the configurationManager * @param dbContextFactory the initialized OpenCms runtime info factory * * @throws CmsInitException if the initialization fails */ public void init(CmsConfigurationManager configurationManager, I_CmsDbContextFactory dbContextFactory) throws CmsInitException { if (dbContextFactory == null) { throw new CmsInitException(org.opencms.main.Messages.get().container( org.opencms.main.Messages.ERR_CRITICAL_NO_DB_CONTEXT_0)); } m_dbContextFactory = dbContextFactory; CmsSystemConfiguration systemConfiguation = (CmsSystemConfiguration)configurationManager.getConfiguration(CmsSystemConfiguration.class); CmsCacheSettings settings = systemConfiguation.getCacheSettings(); String className = settings.getCacheKeyGenerator(); try { // initialize the key generator m_keyGenerator = (I_CmsCacheKey)Class.forName(className).newInstance(); } catch (Exception e) { throw new CmsInitException(org.opencms.main.Messages.get().container( org.opencms.main.Messages.ERR_CRITICAL_CLASS_CREATION_1, className)); } LRUMap hashMap = new LRUMap(settings.getPermissionCacheSize()); m_permissionCache = Collections.synchronizedMap(hashMap); if (OpenCms.getMemoryMonitor().enabled()) { OpenCms.getMemoryMonitor().register(this.getClass().getName() + ".m_permissionCache", hashMap); } m_driverManager = CmsDriverManager.newInstance(configurationManager, this, dbContextFactory); if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().key(Messages.INIT_SECURITY_MANAGER_INIT_0)); } } /** * Checks if the specified resource is inside the current project.<p> * * The project "view" is determined by a set of path prefixes. * If the resource starts with any one of this prefixes, it is considered to * be "inside" the project.<p> * * @param context the current request context * @param resourcename the specified resource name (full path) * * @return <code>true</code>, if the specified resource is inside the current project */ public boolean isInsideCurrentProject(CmsRequestContext context, String resourcename) { boolean result = false; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.isInsideCurrentProject(dbc, resourcename); } finally { dbc.clear(); } return result; } /** * Checks if the current user has management access to the current project.<p> * * @param context the current request context * * @return <code>true</code>, if the user has management access to the current project */ public boolean isManagerOfProject(CmsRequestContext context) { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); return hasManagerOfProjectRole(dbc, context.currentProject()); } /** * Locks a resource.<p> * * The <code>mode</code> parameter controls what kind of lock is used.<br> * Possible values for this parameter are: <br> * <ul> * <li><code>{@link org.opencms.lock.CmsLock#C_MODE_COMMON}</code></li> * <li><code>{@link org.opencms.lock.CmsLock#C_MODE_TEMP}</code></li> * </ul><p> * * @param context the current request context * @param resource the resource to lock * @param mode flag indicating the mode for the lock * * @throws CmsException if something goes wrong * * @see CmsObject#lockResource(String, int) * @see org.opencms.file.types.I_CmsResourceType#lockResource(CmsObject, CmsSecurityManager, CmsResource, int) */ public void lockResource(CmsRequestContext context, CmsResource resource, int mode) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL); m_driverManager.lockResource(dbc, resource, mode); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_LOCK_RESOURCE_2, context.getSitePath(resource), (mode == CmsLock.C_MODE_COMMON) ? "CmsLock.C_MODE_COMMON" : "CmsLock.C_MODE_TEMP"), e); } finally { dbc.clear(); } } /** * Attempts to authenticate a user into OpenCms with the given password.<p> * * @param context the current request context * @param username the name of the user to be logged in * @param password the password of the user * @param remoteAddress the ip address of the request * @param userType the user type to log in (System user or Web user) * * @return the logged in user * * @throws CmsException if the login was not succesful */ public CmsUser loginUser( CmsRequestContext context, String username, String password, String remoteAddress, int userType) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.loginUser(dbc, username, password, remoteAddress, userType); } finally { dbc.clear(); } return result; } /** * Lookup and read the user or group with the given UUID.<p> * * @param context the current request context * @param principalId the UUID of the principal to lookup * * @return the principal (group or user) if found, otherwise <code>null</code> */ public I_CmsPrincipal lookupPrincipal(CmsRequestContext context, CmsUUID principalId) { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); I_CmsPrincipal result = null; try { result = m_driverManager.lookupPrincipal(dbc, principalId); } finally { dbc.clear(); } return result; } /** * Lookup and read the user or group with the given name.<p> * * @param context the current request context * @param principalName the name of the principal to lookup * * @return the principal (group or user) if found, otherwise <code>null</code> */ public I_CmsPrincipal lookupPrincipal(CmsRequestContext context, String principalName) { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); I_CmsPrincipal result = null; try { result = m_driverManager.lookupPrincipal(dbc, principalName); } finally { dbc.clear(); } return result; } /** * Moves a resource to the "lost and found" folder.<p> * * The method can also be used to check get the name of a resource * in the "lost and found" folder only without actually moving the * the resource. To do this, the <code>returnNameOnly</code> flag * must be set to <code>true</code>.<p> * * In general, it is the same name as the given resource has, the only exception is * if a resource in the "lost and found" folder with the same name already exists. * In such case, a counter is added to the resource name.<p> * * @param context the current request context * @param resourcename the name of the resource to apply this operation to * @param returnNameOnly if <code>true</code>, only the name of the resource in the "lost and found" * folder is returned, the move operation is not really performed * * @return the name of the resource inside the "lost and found" folder * * @throws CmsException if something goes wrong * * @see CmsObject#moveToLostAndFound(String) * @see CmsObject#getLostAndFoundName(String) */ public String moveToLostAndFound(CmsRequestContext context, String resourcename, boolean returnNameOnly) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); String result = null; try { result = m_driverManager.moveToLostAndFound(dbc, resourcename, returnNameOnly); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_MOVE_TO_LOST_AND_FOUND_1, resourcename), e); } finally { dbc.clear(); } return result; } /** * Publishes the resources of a specified publish list.<p> * * @param cms the current request context * @param publishList a publish list * @param report an instance of <code>{@link I_CmsReport}</code> to print messages * * @return the publish history id of the published project * * @throws CmsException if something goes wrong * * @see #getPublishList(CmsRequestContext, CmsResource, boolean) */ public synchronized CmsUUID publishProject(CmsObject cms, CmsPublishList publishList, I_CmsReport report) throws CmsException { CmsRequestContext context = cms.getRequestContext(); // check if the current user has the required publish permissions if (publishList.isDirectPublish()) { // pass the direct publish resource to the permission test CmsResource directPublishResource = publishList.getDirectPublishResource(); checkPublishPermissions(context, directPublishResource); } else { // pass null, will only check the current project checkPublishPermissions(context, null); } CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.publishProject(cms, dbc, publishList, report); } finally { dbc.clear(); } return publishList.getPublishHistoryId(); } /** * Reactivates a task.<p> * * Setting its state to <code>{@link org.opencms.workflow.CmsTaskService#TASK_STATE_STARTED}</code> and * the percentage to <b>zero</b>.<p> * * @param context the current request context * @param taskId the id of the task to reactivate * * @throws CmsException if something goes wrong */ public void reactivateTask(CmsRequestContext context, int taskId) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.reactivateTask(dbc, taskId); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_REACTIVATE_TASK_1, new Integer(taskId)), e); } finally { dbc.clear(); } } /** * Reads the agent of a task.<p> * * @param context the current request context * @param task the task to read the agent from * * @return the owner of a task * * @throws CmsException if something goes wrong */ public CmsUser readAgent(CmsRequestContext context, CmsTask task) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.readAgent(dbc, task); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_TASK_OWNER_2, task.getName(), new Integer(task.getId())), e); } finally { dbc.clear(); } return result; } /** * Reads all file headers of a file.<br> * * This method returns a list with the history of all file headers, i.e. * the file headers of a file, independent of the project they were attached to.<br> * * The reading excludes the file content.<p> * * @param context the current request context * @param resource the resource to be read * * @return a list of file headers, as <code>{@link CmsBackupResource}</code> objects, read from the Cms * * @throws CmsException if something goes wrong */ public List readAllBackupFileHeaders(CmsRequestContext context, CmsResource resource) throws CmsException { List result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.readAllBackupFileHeaders(dbc, resource); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_ALL_BKP_FILE_HEADERS_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Reads all propertydefinitions for the given mapping type.<p> * * @param context the current request context * @param mappingtype the mapping type to read the propertydefinitions for * * @return a list with the <code>{@link CmsPropertyDefinition}</code> objects (may be empty) * * @throws CmsException if something goes wrong */ public List readAllPropertyDefinitions(CmsRequestContext context, int mappingtype) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readAllPropertyDefinitions(dbc, mappingtype); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_ALL_PROPDEF_MAPPING_TYPE_1, (mappingtype == CmsProperty.C_RESOURCE_RECORD_MAPPING) ? "CmsProperty.C_RESOURCE_RECORD_MAPPING" : "CmsProperty.C_STRUCTURE_RECORD_MAPPING"), e); } finally { dbc.clear(); } return result; } /** * Returns the first ancestor folder matching the filter criteria.<p> * * If no folder matching the filter criteria is found, null is returned.<p> * * @param context the context of the current request * @param resource the resource to start * @param filter the resource filter to match while reading the ancestors * * @return the first ancestor folder matching the filter criteria or null if no folder was found * * @throws CmsException if something goes wrong */ public CmsFolder readAncestor(CmsRequestContext context, CmsResource resource, CmsResourceFilter filter) throws CmsException { // get the full folder path of the resource to start from String path = CmsResource.getFolderPath(resource.getRootPath()); do { // check if the current folder matches the given filter if (existsResource(context, path, filter)) { // folder matches, return it return readFolder(context, path, filter); } else { // folder does not match filter criteria, go up one folder path = CmsResource.getParentFolder(path); } if (CmsStringUtil.isEmpty(path) || !path.startsWith(context.getSiteRoot())) { // site root or root folder reached and no matching folder found return null; } } while (true); } /** * Returns a file from the history.<br> * * The reading includes the file content.<p> * * @param context the current request context * @param tagId the id of the tag of the file * @param resource the resource to be read * * @return the file read * * @throws CmsException if operation was not succesful */ public CmsBackupResource readBackupFile(CmsRequestContext context, int tagId, CmsResource resource) throws CmsException { CmsBackupResource result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.readBackupFile(dbc, tagId, resource); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_BKP_FILE_2, context.getSitePath(resource), new Integer(tagId)), e); } finally { dbc.clear(); } return result; } /** * Returns a backup project.<p> * * @param context the current request context * @param tagId the tagId of the project * * @return the requested backup project * * @throws CmsException if something goes wrong */ public CmsBackupProject readBackupProject(CmsRequestContext context, int tagId) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsBackupProject result = null; try { result = m_driverManager.readBackupProject(dbc, tagId); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_BKP_PROJECT_2, new Integer(tagId), dbc.currentProject().getName()), e); } finally { dbc.clear(); } return result; } /** * Returns the child resources of a resource, that is the resources * contained in a folder.<p> * * With the parameters <code>getFolders</code> and <code>getFiles</code> * you can control what type of resources you want in the result list: * files, folders, or both.<p> * * This method is mainly used by the workplace explorer.<p> * * @param context the current request context * @param resource the resource to return the child resources for * @param filter the resource filter to use * @param getFolders if true the child folders are included in the result * @param getFiles if true the child files are included in the result * * @return a list of all child resources * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (read is required). * */ public List readChildResources( CmsRequestContext context, CmsResource resource, CmsResourceFilter filter, boolean getFolders, boolean getFiles) throws CmsException, CmsSecurityException { List result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { // check the access permissions checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_READ, true, CmsResourceFilter.ALL); result = m_driverManager.readChildResources(dbc, resource, filter, getFolders, getFiles); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_CHILD_RESOURCES_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Reads a file resource (including it's binary content) from the VFS, * using the specified resource filter.<p> * * In case you do not need the file content, * use <code>{@link #readResource(CmsRequestContext, String, CmsResourceFilter)}</code> instead.<p> * * The specified filter controls what kind of resources should be "found" * during the read operation. This will depend on the application. For example, * using <code>{@link CmsResourceFilter#DEFAULT}</code> will only return currently * "valid" resources, while using <code>{@link CmsResourceFilter#IGNORE_EXPIRATION}</code> * will ignore the date release / date expired information of the resource.<p> * * @param context the current request context * @param resource the resource to be read * @param filter the filter object * * @return the file read from the VFS * * @throws CmsException if something goes wrong */ public CmsFile readFile(CmsRequestContext context, CmsResource resource, CmsResourceFilter filter) throws CmsException { CmsFile result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.readFile(dbc, resource, filter); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_FILE_2, context.getSitePath(resource), String.valueOf(filter)), e); } finally { dbc.clear(); } return result; } /** * Reads a folder resource from the VFS, * using the specified resource filter.<p> * * The specified filter controls what kind of resources should be "found" * during the read operation. This will depend on the application. For example, * using <code>{@link CmsResourceFilter#DEFAULT}</code> will only return currently * "valid" resources, while using <code>{@link CmsResourceFilter#IGNORE_EXPIRATION}</code> * will ignore the date release / date expired information of the resource.<p> * * @param context the current request context * @param resourcename the name of the folder to read (full path) * @param filter the resource filter to use while reading * * @return the folder that was read * * @throws CmsException if something goes wrong */ public CmsFolder readFolder(CmsRequestContext context, String resourcename, CmsResourceFilter filter) throws CmsException { CmsFolder result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = readFolder(dbc, resourcename, filter); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_FOLDER_2, resourcename, String.valueOf(filter)), e); } finally { dbc.clear(); } return result; } /** * Reads all given tasks from a user for a project.<p> * * The <code>tasktype</code> parameter will filter the tasks. * The possible values for this parameter are:<br> * <ul> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_ALL}</code>: Reads all tasks</il> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_OPEN}</code>: Reads all open tasks</il> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_DONE}</code>: Reads all finished tasks</il> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_NEW}</code>: Reads all new tasks</il> * </ul> * * @param context the current request context * @param projectId the id of the project in which the tasks are defined * @param ownerName the owner of the task * @param taskType the type of task you want to read * @param orderBy specifies how to order the tasks * @param sort sorting of the tasks * * @return a list of given <code>{@link CmsTask}</code> objects for a user for a project * * @throws CmsException if operation was not successful */ public List readGivenTasks( CmsRequestContext context, int projectId, String ownerName, int taskType, String orderBy, String sort) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readGivenTasks(dbc, projectId, ownerName, taskType, orderBy, sort); } catch (Exception e) { dbc.report(null, Messages.get().container( org.opencms.workflow.Messages.toTaskTypeString(taskType, context), new Integer(projectId), ownerName), e); } finally { dbc.clear(); } return result; } /** * Reads the group of a project.<p> * * @param context the current request context * @param project the project to read from * * @return the group of a resource */ public CmsGroup readGroup(CmsRequestContext context, CmsProject project) { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsGroup result = null; try { result = m_driverManager.readGroup(dbc, project); } finally { dbc.clear(); } return result; } /** * Reads the group (role) of a task from the OpenCms.<p> * * @param context the current request context * @param task the task to read from * * @return the group of a resource * * @throws CmsException if operation was not succesful */ public CmsGroup readGroup(CmsRequestContext context, CmsTask task) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsGroup result = null; try { result = m_driverManager.readGroup(dbc, task); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_GROUP_TASK_1, task.getName()), e); } finally { dbc.clear(); } return result; } /** * Reads a group based on its id.<p> * * @param context the current request context * @param groupId the id of the group that is to be read * * @return the requested group * * @throws CmsException if operation was not succesful */ public CmsGroup readGroup(CmsRequestContext context, CmsUUID groupId) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsGroup result = null; try { result = m_driverManager.readGroup(dbc, groupId); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_GROUP_FOR_ID_1, groupId.toString()), e); } finally { dbc.clear(); } return result; } /** * Reads a group based on its name.<p> * * @param context the current request context * @param groupname the name of the group that is to be read * * @return the requested group * * @throws CmsException if operation was not succesful */ public CmsGroup readGroup(CmsRequestContext context, String groupname) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsGroup result = null; try { result = m_driverManager.readGroup(dbc, groupname); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_GROUP_FOR_NAME_1, groupname), e); } finally { dbc.clear(); } return result; } /** * Reads the manager group of a project.<p> * * @param context the current request context * @param project the project to read from * * @return the group of a resource */ public CmsGroup readManagerGroup(CmsRequestContext context, CmsProject project) { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsGroup result = null; try { result = m_driverManager.readManagerGroup(dbc, project); } finally { dbc.clear(); } return result; } /** * Reads the original agent of a task.<p> * * @param context the current request context * @param task the task to read the original agent from * * @return the owner of a task * * @throws CmsException if something goes wrong */ public CmsUser readOriginalAgent(CmsRequestContext context, CmsTask task) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.readOriginalAgent(dbc, task); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_ORIGINAL_TASK_OWNER_2, task.getName(), new Integer(task.getId())), e); } finally { dbc.clear(); } return result; } /** * Reads the owner of a project from the OpenCms.<p> * * @param context the current request context * @param project the project to get the owner from * * @return the owner of a resource * * @throws CmsException if something goes wrong */ public CmsUser readOwner(CmsRequestContext context, CmsProject project) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.readOwner(dbc, project); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_OWNER_FOR_PROJECT_2, project.getName(), new Integer(project.getId())), e); } finally { dbc.clear(); } return result; } /** * Reads the owner (initiator) of a task.<p> * * @param context the current request context * @param task the task to read the owner from * * @return the owner of a task * * @throws CmsException if something goes wrong */ public CmsUser readOwner(CmsRequestContext context, CmsTask task) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.readOwner(dbc, task); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_OWNER_FOR_TASK_2, task.getName(), new Integer(task.getId())), e); } finally { dbc.clear(); } return result; } /** * Reads the owner of a tasklog.<p> * * @param context the current request context * @param log the tasklog * * @return the owner of a resource * * @throws CmsException if something goes wrong */ public CmsUser readOwner(CmsRequestContext context, CmsTaskLog log) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.readOwner(dbc, log); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_OWNER_FOR_TASKLOG_1, new Integer(log.getId())), e); } finally { dbc.clear(); } return result; } /** * Builds a list of resources for a given path.<p> * * @param context the current request context * @param projectId the project to lookup the resource * @param path the requested path * @param filter a filter object (only "includeDeleted" information is used!) * * @return list of <code>{@link CmsResource}</code>s * * @throws CmsException if something goes wrong */ public List readPath(CmsRequestContext context, int projectId, String path, CmsResourceFilter filter) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readPath(dbc, projectId, path, filter); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_PATH_2, new Integer(projectId), path), e); } finally { dbc.clear(); } return result; } /** * Reads a project of a given task.<p> * * @param context the current request context * @param task the task to read the project of * * @return the project of the task * * @throws CmsException if something goes wrong */ public CmsProject readProject(CmsRequestContext context, CmsTask task) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsProject result = null; try { result = m_driverManager.readProject(dbc, task); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_PROJECT_FOR_TASK_2, task.getName(), new Integer(task.getId())), e); } finally { dbc.clear(); } return result; } /** * Reads a project given the projects id.<p> * * @param id the id of the project * * @return the project read * * @throws CmsException if something goes wrong */ public CmsProject readProject(int id) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(); CmsProject result = null; try { result = m_driverManager.readProject(dbc, id); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_PROJECT_FOR_ID_1, new Integer(id)), e); } finally { dbc.clear(); } return result; } /** * Reads a project.<p> * * Important: Since a project name can be used multiple times, this is NOT the most efficient * way to read the project. This is only a convenience for front end developing. * Reading a project by name will return the first project with that name. * All core classes must use the id version {@link #readProject(int)} to ensure the right project is read.<p> * * @param name the name of the project * * @return the project read * * @throws CmsException if something goes wrong */ public CmsProject readProject(String name) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(); CmsProject result = null; try { result = m_driverManager.readProject(dbc, name); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_PROJECT_FOR_NAME_1, name), e); } finally { dbc.clear(); } return result; } /** * Reads all task log entries for a project. * * @param context the current request context * @param projectId the id of the project for which the tasklog will be read * * @return a list of <code>{@link CmsTaskLog}</code> objects * * @throws CmsException if something goes wrong */ public List readProjectLogs(CmsRequestContext context, int projectId) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readProjectLogs(dbc, projectId); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_TASKLOGS_FOR_PROJECT_1, new Integer(projectId)), e); } finally { dbc.clear(); } return result; } /** * Returns the list of all resource names that define the "view" of the given project.<p> * * @param context the current request context * @param project the project to get the project resources for * * @return the list of all resources, as <code>{@link String}</code> objects * that define the "view" of the given project. * * @throws CmsException if something goes wrong */ public List readProjectResources(CmsRequestContext context, CmsProject project) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readProjectResources(dbc, project); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_PROJECT_RESOURCES_2, project.getName(), new Integer(project.getId())), e); } finally { dbc.clear(); } return result; } /** * Reads all resources of a project that match a given state from the VFS.<p> * * Possible values for the <code>state</code> parameter are:<br> * <ul> * <li><code>{@link I_CmsConstants#C_STATE_CHANGED}</code>: Read all "changed" resources in the project</li> * <li><code>{@link I_CmsConstants#C_STATE_NEW}</code>: Read all "new" resources in the project</li> * <li><code>{@link I_CmsConstants#C_STATE_DELETED}</code>: Read all "deleted" resources in the project</li> * <li><code>{@link I_CmsConstants#C_STATE_KEEP}</code>: Read all resources either "changed", "new" or "deleted" in the project</li> * </ul><p> * * @param context the current request context * @param projectId the id of the project to read the file resources for * @param state the resource state to match * * @return a list of <code>{@link CmsResource}</code> objects matching the filter criteria * * @throws CmsException if something goes wrong * * @see CmsObject#readProjectView(int, int) */ public List readProjectView(CmsRequestContext context, int projectId, int state) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readProjectView(dbc, projectId, state); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_PROJECT_VIEW_2, new Integer(projectId), org.opencms.workflow.Messages.toTaskTypeString(state, context)), e); } finally { dbc.clear(); } return result; } /** * Reads a property definition.<p> * * If no property definition with the given name is found, * <code>null</code> is returned.<p> * * @param context the current request context * @param name the name of the property definition to read * * @return the property definition that was read, * or <code>null</code> if there is no property definition with the given name. * * @throws CmsException if something goes wrong */ public CmsPropertyDefinition readPropertyDefinition(CmsRequestContext context, String name) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsPropertyDefinition result = null; try { result = m_driverManager.readPropertyDefinition(dbc, name); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_PROPDEF_1, name), e); } finally { dbc.clear(); } return result; } /** * Reads a property object from a resource specified by a property name.<p> * * Returns <code>{@link CmsProperty#getNullProperty()}</code> if the property is not found.<p> * * @param context the context of the current request * @param resource the resource where the property is mapped to * @param key the property key name * @param search if <code>true</code>, the property is searched on all parent folders of the resource. * if it's not found attached directly to the resource. * * @return the required property, or <code>{@link CmsProperty#getNullProperty()}</code> if the property was not found * * @throws CmsException if something goes wrong */ public CmsProperty readPropertyObject(CmsRequestContext context, CmsResource resource, String key, boolean search) throws CmsException { CmsProperty result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.readPropertyObject(dbc, resource, key, search); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_PROP_FOR_RESOURCE_2, key, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Reads all property objects from a resource.<p> * * Returns an empty list if no properties are found.<p> * * If the <code>search</code> parameter is <code>true</code>, the properties of all * parent folders of the resource are also read. The results are merged with the * properties directly attached to the resource. While merging, a property * on a parent folder that has already been found will be ignored. * So e.g. if a resource has a property "Title" attached, and it's parent folder * has the same property attached but with a differrent value, the result list will * contain only the property with the value from the resource, not form the parent folder(s).<p> * * @param context the context of the current request * @param resource the resource where the property is mapped to * @param search <code>true</code>, if the properties should be searched on all parent folders if not found on the resource * * @return a list of <code>{@link CmsProperty}</code> objects * * @throws CmsException if something goes wrong */ public List readPropertyObjects(CmsRequestContext context, CmsResource resource, boolean search) throws CmsException { List result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.readPropertyObjects(dbc, resource, search); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_PROPS_FOR_RESOURCE_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Reads the resources that were published in a publish task for a given publish history ID.<p> * * @param context the current request context * @param publishHistoryId unique int ID to identify each publish task in the publish history * * @return a list of <code>{@link org.opencms.db.CmsPublishedResource}</code> objects * * @throws CmsException if something goes wrong */ public List readPublishedResources(CmsRequestContext context, CmsUUID publishHistoryId) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readPublishedResources(dbc, publishHistoryId); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_PUBLISHED_RESOURCES_FOR_ID_1, publishHistoryId.toString()), e); } finally { dbc.clear(); } return result; } /** * Reads a resource from the VFS, * using the specified resource filter.<p> * * A resource may be of type <code>{@link CmsFile}</code> or * <code>{@link CmsFolder}</code>. In case of * a file, the resource will not contain the binary file content. Since reading * the binary content is a cost-expensive database operation, it's recommended * to work with resources if possible, and only read the file content when absolutly * required. To "upgrade" a resource to a file, * use <code>{@link CmsFile#upgrade(CmsResource, CmsObject)}</code>.<p> * * The specified filter controls what kind of resources should be "found" * during the read operation. This will depend on the application. For example, * using <code>{@link CmsResourceFilter#DEFAULT}</code> will only return currently * "valid" resources, while using <code>{@link CmsResourceFilter#IGNORE_EXPIRATION}</code> * will ignore the date release / date expired information of the resource.<p> * * @param context the current request context * @param resourcePath the name of the resource to read (full path) * @param filter the resource filter to use while reading * * @return the resource that was read * * @throws CmsException if the resource could not be read for any reason * * @see CmsObject#readResource(String, CmsResourceFilter) * @see CmsObject#readResource(String) * @see CmsFile#upgrade(CmsResource, CmsObject) */ public CmsResource readResource(CmsRequestContext context, String resourcePath, CmsResourceFilter filter) throws CmsException { CmsResource result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = readResource(dbc, resourcePath, filter); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_RESOURCE_1, dbc.removeSiteRoot(resourcePath)), e); } finally { dbc.clear(); } return result; } /** * Reads all resources below the given path matching the filter criteria, * including the full tree below the path only in case the <code>readTree</code> * parameter is <code>true</code>.<p> * * @param context the current request context * @param parent the parent path to read the resources from * @param filter the filter * @param readTree <code>true</code> to read all subresources * * @return a list of <code>{@link CmsResource}</code> objects matching the filter criteria * * @throws CmsSecurityException if the user has insufficient permission for the given resource (read is required). * @throws CmsException if something goes wrong * */ public List readResources(CmsRequestContext context, CmsResource parent, CmsResourceFilter filter, boolean readTree) throws CmsException, CmsSecurityException { List result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { // check the access permissions checkPermissions(dbc, parent, CmsPermissionSet.ACCESS_READ, true, CmsResourceFilter.ALL); result = m_driverManager.readResources(dbc, parent, filter, readTree); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_RESOURCES_1, context.removeSiteRoot(parent.getRootPath())), e); } finally { dbc.clear(); } return result; } /** * Reads all resources that have a value set for the specified property (definition) in the given path.<p> * * Both individual and shared properties of a resource are checked.<p> * * @param context the current request context * @param path the folder to get the resources with the property from * @param propertyDefinition the name of the property (definition) to check for * * @return a list of all <code>{@link CmsResource}</code> objects * that have a value set for the specified property. * * @throws CmsException if something goes wrong */ public List readResourcesWithProperty(CmsRequestContext context, String path, String propertyDefinition) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readResourcesWithProperty(dbc, path, propertyDefinition); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_RESOURCES_FOR_PROP_SET_2, path, propertyDefinition), e); } finally { dbc.clear(); } return result; } /** * Reads all resources that have a value (containing the specified value) set * for the specified property (definition) in the given path.<p> * * Both individual and shared properties of a resource are checked.<p> * * @param context the current request context * @param path the folder to get the resources with the property from * @param propertyDefinition the name of the property (definition) to check for * @param value the string to search in the value of the property * * @return a list of all <code>{@link CmsResource}</code> objects * that have a value set for the specified property. * * @throws CmsException if something goes wrong */ public List readResourcesWithProperty( CmsRequestContext context, String path, String propertyDefinition, String value) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readResourcesWithProperty(dbc, path, propertyDefinition, value); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_RESOURCES_FOR_PROP_VALUE_3, path, propertyDefinition, value), e); } finally { dbc.clear(); } return result; } /** * Returns a List of all siblings of the specified resource, * the specified resource being always part of the result set.<p> * * @param context the request context * @param resource the specified resource * @param filter a filter object * * @return a list of <code>{@link CmsResource}</code>s that * are siblings to the specified resource, * including the specified resource itself. * * @throws CmsException if something goes wrong */ public List readSiblings(CmsRequestContext context, CmsResource resource, CmsResourceFilter filter) throws CmsException { List result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.readSiblings(dbc, resource, filter); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_SIBLINGS_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Returns the parameters of a resource in the table of all published template resources.<p> * * @param context the current request context * @param rfsName the rfs name of the resource * * @return the paramter string of the requested resource * * @throws CmsException if something goes wrong */ public String readStaticExportPublishedResourceParameters(CmsRequestContext context, String rfsName) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); String result = null; try { result = m_driverManager.readStaticExportPublishedResourceParameters(dbc, rfsName); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_STATEXP_PUBLISHED_RESOURCE_PARAMS_1, rfsName), e); } finally { dbc.clear(); } return result; } /** * Returns a list of all template resources which must be processed during a static export.<p> * * @param context the current request context * @param parameterResources flag for reading resources with parameters (1) or without (0) * @param timestamp for reading the data from the db * * @return a list of template resources as <code>{@link String}</code> objects * * @throws CmsException if something goes wrong */ public List readStaticExportResources(CmsRequestContext context, int parameterResources, long timestamp) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readStaticExportResources(dbc, parameterResources, timestamp); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_STATEXP_RESOURCES_1, new Date(timestamp)), e); } finally { dbc.clear(); } return result; } /** * Reads the task with the given id.<p> * * @param context the current request context * @param id the id for the task to read * * @return the task with the given id * * @throws CmsException if something goes wrong */ public CmsTask readTask(CmsRequestContext context, int id) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsTask result = null; try { result = m_driverManager.readTask(dbc, id); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_TASK_FOR_ID_1, new Integer(id)), e); } finally { dbc.clear(); } return result; } /** * Reads log entries for a task.<p> * * @param context the current request context * @param taskid the task for the tasklog to read * * @return a list of <code>{@link CmsTaskLog}</code> objects * * @throws CmsException if something goes wrong */ public List readTaskLogs(CmsRequestContext context, int taskid) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readTaskLogs(dbc, taskid); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_TASKLOGS_FOR_ID_1, new Integer(taskid)), e); } finally { dbc.clear(); } return result; } /** * Reads all tasks for a project.<p> * * The <code>tasktype</code> parameter will filter the tasks. * The possible values are:<br> * <ul> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_ALL}</code>: Reads all tasks</il> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_OPEN}</code>: Reads all open tasks</il> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_DONE}</code>: Reads all finished tasks</il> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_NEW}</code>: Reads all new tasks</il> * </ul><p> * * @param context the current request context * @param projectId the id of the project in which the tasks are defined. Can be null to select all tasks * @param tasktype the type of task you want to read * @param orderBy specifies how to order the tasks * @param sort sort order: C_SORT_ASC, C_SORT_DESC, or null * * @return a list of <code>{@link CmsTask}</code> objects for the project * * @throws CmsException if operation was not successful */ public List readTasksForProject(CmsRequestContext context, int projectId, int tasktype, String orderBy, String sort) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readTasksForProject(dbc, projectId, tasktype, orderBy, sort); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_TASK_FOR_PROJECT_AND_TYPE_2, new Integer(projectId), org.opencms.workflow.Messages.toTaskTypeString(tasktype, context)), e); } finally { dbc.clear(); } return result; } /** * Reads all tasks for a role in a project.<p> * * The <code>tasktype</code> parameter will filter the tasks. * The possible values for this parameter are:<br> * <ul> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_ALL}</code>: Reads all tasks</il> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_OPEN}</code>: Reads all open tasks</il> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_DONE}</code>: Reads all finished tasks</il> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_NEW}</code>: Reads all new tasks</il> * </ul><p> * * @param context the current request context * @param projectId the id of the Project in which the tasks are defined * @param roleName the role who has to process the task * @param tasktype the type of task you want to read * @param orderBy specifies how to order the tasks * @param sort sort order C_SORT_ASC, C_SORT_DESC, or null * * @return list of <code>{@link CmsTask}</code> objects for the role * * @throws CmsException if operation was not successful */ public List readTasksForRole( CmsRequestContext context, int projectId, String roleName, int tasktype, String orderBy, String sort) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readTasksForRole(dbc, projectId, roleName, tasktype, orderBy, sort); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_TASK_FOR_PROJECT_AND_ROLE_AND_TYPE_3, new Integer(projectId), roleName, org.opencms.workflow.Messages.toTaskTypeString(tasktype, context)), e); } finally { dbc.clear(); } return result; } /** * Reads all tasks for a user in a project.<p> * * The <code>tasktype</code> parameter will filter the tasks. * The possible values for this parameter are:<br> * <ul> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_ALL}</code>: Reads all tasks</il> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_OPEN}</code>: Reads all open tasks</il> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_DONE}</code>: Reads all finished tasks</il> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_NEW}</code>: Reads all new tasks</il> * </ul> * * @param context the current request context * @param projectId the id of the Project in which the tasks are defined * @param userName the user who has to process the task * @param taskType the type of task you want to read * @param orderBy specifies how to order the tasks * @param sort sort order C_SORT_ASC, C_SORT_DESC, or null * * @return a list of <code>{@link CmsTask}</code> objects for the user * * @throws CmsException if operation was not successful */ public List readTasksForUser( CmsRequestContext context, int projectId, String userName, int taskType, String orderBy, String sort) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readTasksForUser(dbc, projectId, userName, taskType, orderBy, sort); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_TASK_FOR_PROJECT_AND_USER_AND_TYPE_3, new Integer(projectId), userName, org.opencms.workflow.Messages.toTaskTypeString(taskType, context)), e); } finally { dbc.clear(); } return result; } /** * Returns a user object based on the id of a user.<p> * * @param context the current request context * @param id the id of the user to read * * @return the user read * * @throws CmsException if something goes wrong */ public CmsUser readUser(CmsRequestContext context, CmsUUID id) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.readUser(dbc, id); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_USER_FOR_ID_1, id.toString()), e); } finally { dbc.clear(); } return result; } /** * Returns a user object.<p> * * @param context the current request context * @param username the name of the user that is to be read * @param type the type of the user * * @return user read * * @throws CmsException if operation was not succesful */ public CmsUser readUser(CmsRequestContext context, String username, int type) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.readUser(dbc, username, type); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_USER_FOR_NAME_1, username), e); } finally { dbc.clear(); } return result; } /** * Returns a user object if the password for the user is correct.<p> * * If the user/pwd pair is not valid a <code>{@link CmsException}</code> is thrown.<p> * * @param context the current request context * @param username the username of the user that is to be read * @param password the password of the user that is to be read * * @return user read * * @throws CmsException if operation was not succesful */ public CmsUser readUser(CmsRequestContext context, String username, String password) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.readUser(dbc, username, password); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_USER_FOR_NAME_1, username), e); } finally { dbc.clear(); } return result; } /** * Returns a user object.<p> * * @param username the name of the user that is to be read * * @return user read form the cms * * @throws CmsException if operation was not succesful */ public CmsUser readUser(String username) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(); CmsUser result = null; try { result = m_driverManager.readUser(dbc, username); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_USER_FOR_NAME_1, username), e); } finally { dbc.clear(); } return result; } /** * Read a web user from the database.<p> * * @param context the current request context * @param username the web user to read * * @return the read web user * * @throws CmsException if the user could not be read. */ public CmsUser readWebUser(CmsRequestContext context, String username) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.readWebUser(dbc, username); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_USER_WEB_1, username), e); } finally { dbc.clear(); } return result; } /** * Returns a user object if the password for the user is correct.<p> * * If the user/pwd pair is not valid a <code>{@link CmsException}</code> is thrown.<p> * * @param context the current request context * @param username the username of the user that is to be read * @param password the password of the user that is to be read * * @return the webuser read * * @throws CmsException if operation was not succesful */ public CmsUser readWebUser(CmsRequestContext context, String username, String password) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.readWebUser(dbc, username, password); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_USER_WEB_1, username), e); } finally { dbc.clear(); } return result; } /** * Removes an access control entry for a given resource and principal.<p> * * @param context the current request context * @param resource the resource * @param principal the id of the principal to remove the the access control entry for * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (conrol of access control is required). * */ public void removeAccessControlEntry(CmsRequestContext context, CmsResource resource, CmsUUID principal) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_CONTROL, true, CmsResourceFilter.ALL); m_driverManager.removeAccessControlEntry(dbc, resource, principal); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_REMOVE_ACL_ENTRY_2, context.getSitePath(resource), principal.toString()), e); } finally { dbc.clear(); } } /** * Removes a user from a group.<p> * * @param context the current request context * @param username the name of the user that is to be removed from the group * @param groupname the name of the group * * @throws CmsException if operation was not succesful * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#USER_MANAGER} * */ public void removeUserFromGroup(CmsRequestContext context, String username, String groupname) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.USER_MANAGER); m_driverManager.removeUserFromGroup(dbc, username, groupname); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_REMOVE_USER_FROM_GROUP_2, username, groupname), e); } finally { dbc.clear(); } } /** * Replaces the content, type and properties of a resource.<p> * * @param context the current request context * @param resource the name of the resource to apply this operation to * @param type the new type of the resource * @param content the new content of the resource * @param properties the new properties of the resource * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (write access permission is required). * * @see CmsObject#replaceResource(String, int, byte[], List) * @see org.opencms.file.types.I_CmsResourceType#replaceResource(CmsObject, CmsSecurityManager, CmsResource, int, byte[], List) */ public void replaceResource( CmsRequestContext context, CmsResource resource, int type, byte[] content, List properties) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.replaceResource(dbc, resource, type, content, properties); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_REPLACE_RESOURCE_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Resets the password for a specified user.<p> * * @param context the current request context * @param username the name of the user * @param oldPassword the old password * @param newPassword the new password * * @throws CmsException if the user data could not be read from the database * @throws CmsSecurityException if the specified username and old password could not be verified */ public void resetPassword(CmsRequestContext context, String username, String oldPassword, String newPassword) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.resetPassword(dbc, username, oldPassword, newPassword); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_RESET_PASSWORD_1, username), e); } finally { dbc.clear(); } } /** * Restores a file in the current project with a version from the backup archive.<p> * * @param context the current request context * @param resource the resource to restore from the archive * @param tag the tag (version) id to resource form the archive * * @throws CmsException if something goes wrong * * @see CmsObject#restoreResourceBackup(String, int) * @see org.opencms.file.types.I_CmsResourceType#restoreResourceBackup(CmsObject, CmsSecurityManager, CmsResource, int) * @throws CmsSecurityException if the user has insufficient permission for the given resource (write access permission is required). */ public void restoreResource(CmsRequestContext context, CmsResource resource, int tag) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.restoreResource(dbc, resource, tag); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_RESTORE_RESOURCE_2, context.getSitePath(resource), new Integer(tag)), e); } finally { dbc.clear(); } } /** * Set a new name for a task.<p> * * @param context the current request context * @param taskId the Id of the task to set the percentage * @param name the new name value * * @throws CmsException if something goes wrong */ public void setName(CmsRequestContext context, int taskId, String name) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.setName(dbc, taskId, name); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_SET_TASK_NAME_2, name, new Integer(taskId)), e); } finally { dbc.clear(); } } /** * Sets a new parent-group for an already existing group.<p> * * @param context the current request context * @param groupName the name of the group that should be written * @param parentGroupName the name of the parent group to set, * or <code>null</code> if the parent * group should be deleted. * * @throws CmsException if operation was not succesful * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#USER_MANAGER} * */ public void setParentGroup(CmsRequestContext context, String groupName, String parentGroupName) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.USER_MANAGER); m_driverManager.setParentGroup(dbc, groupName, parentGroupName); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_SET_PARENT_GROUP_2, parentGroupName, groupName), e); } finally { dbc.clear(); } } /** * Sets the password for a user.<p> * * @param context the current request context * @param username the name of the user * @param newPassword the new password * * @throws CmsException if operation was not succesfull * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#USER_MANAGER} */ public void setPassword(CmsRequestContext context, String username, String newPassword) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.USER_MANAGER); m_driverManager.setPassword(dbc, username, newPassword); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_SET_PASSWORD_1, username), e); } finally { dbc.clear(); } } /** * Set priority of a task.<p> * * @param context the current request context * @param taskId the Id of the task to set the percentage * @param priority the priority value * * @throws CmsException if something goes wrong */ public void setPriority(CmsRequestContext context, int taskId, int priority) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.setPriority(dbc, taskId, priority); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_SET_TASK_PRIORITY_2, new Integer(taskId), new Integer(priority)), e); } finally { dbc.clear(); } } /** * Set a Parameter for a task.<p> * * @param context the current request context * @param taskId the Id of the task * @param parName name of the parameter * @param parValue value if the parameter * * @throws CmsException if something goes wrong */ public void setTaskPar(CmsRequestContext context, int taskId, String parName, String parValue) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.setTaskPar(dbc, taskId, parName, parValue); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_SET_TASK_PARAM_3, parName, parValue, new Integer(taskId)), e); } finally { dbc.clear(); } } /** * Set timeout of a task.<p> * * @param context the current request context * @param taskId the Id of the task to set the percentage * @param timeout new timeout value * * @throws CmsException if something goes wrong */ public void setTimeout(CmsRequestContext context, int taskId, long timeout) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.setTimeout(dbc, taskId, timeout); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_SET_TASK_TIMEOUT_2, new Date(timeout), new Integer(taskId)), e); } finally { dbc.clear(); } } /** * Changes the timestamp information of a resource.<p> * * This method is used to set the "last modified" date * of a resource, the "release" date of a resource, * and also the "expire" date of a resource.<p> * * @param context the current request context * @param resource the resource to touch * @param dateLastModified timestamp the new timestamp of the changed resource * @param dateReleased the new release date of the changed resource, * set it to <code>{@link I_CmsConstants#C_DATE_UNCHANGED}</code> to keep it unchanged. * @param dateExpired the new expire date of the changed resource, * set it to <code>{@link I_CmsConstants#C_DATE_UNCHANGED}</code> to keep it unchanged. * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (write access permission is required). * * @see CmsObject#touch(String, long, long, long, boolean) * @see org.opencms.file.types.I_CmsResourceType#touch(CmsObject, CmsSecurityManager, CmsResource, long, long, long, boolean) */ public void touch( CmsRequestContext context, CmsResource resource, long dateLastModified, long dateReleased, long dateExpired) throws CmsException, CmsSecurityException { int todo = 0; // TODO: Make 3 methods out of this (setDateLastModified, setDateReleased, setDateExpired) CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.IGNORE_EXPIRATION); m_driverManager.touch(dbc, resource, dateLastModified, dateReleased, dateExpired); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_TOUCH_RESOURCE_4, new Object[] { new Date(dateLastModified), new Date(dateReleased), new Date(dateExpired), context.getSitePath(resource)}), e); } finally { dbc.clear(); } } /** * Undos all changes in the resource by restoring the version from the * online project to the current offline project.<p> * * @param context the current request context * @param resource the name of the resource to apply this operation to * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (write access permission is required). * * @see CmsObject#undoChanges(String, boolean) * @see org.opencms.file.types.I_CmsResourceType#undoChanges(CmsObject, CmsSecurityManager, CmsResource, boolean) */ public void undoChanges(CmsRequestContext context, CmsResource resource) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.undoChanges(dbc, resource); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_UNDO_CHANGES_FOR_RESOURCE_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Unlocks all resources in this project.<p> * * @param context the current request context * @param projectId the id of the project to be published * * @throws CmsException if something goes wrong * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#PROJECT_MANAGER} for the current project. */ public void unlockProject(CmsRequestContext context, int projectId) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsProject project = m_driverManager.readProject(dbc, projectId); try { checkManagerOfProjectRole(dbc, project); m_driverManager.unlockProject(project); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_UNLOCK_PROJECT_2, new Integer(projectId), dbc.currentUser().getName()), e); } finally { dbc.clear(); } } /** * Unlocks a resource.<p> * * @param context the current request context * @param resource the resource to unlock * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (write access permission is required). * * @see CmsObject#unlockResource(String) * @see org.opencms.file.types.I_CmsResourceType#unlockResource(CmsObject, CmsSecurityManager, CmsResource) */ public void unlockResource(CmsRequestContext context, CmsResource resource) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.unlockResource(dbc, resource); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_UNLOCK_RESOURCE_2, context.getSitePath(resource), dbc.currentUser().getName()), e); } finally { dbc.clear(); } } /** * Tests if a user is member of the given group.<p> * * @param context the current request context * @param username the name of the user to check * @param groupname the name of the group to check * * @return <code>true</code>, if the user is in the group; or <code>false</code> otherwise * * @throws CmsException if operation was not succesful */ public boolean userInGroup(CmsRequestContext context, String username, String groupname) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); boolean result = false; try { result = m_driverManager.userInGroup(dbc, username, groupname); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_USER_IN_GROUP_2, username, groupname), e); } finally { dbc.clear(); } return result; } /** * Validates the HTML links in the unpublished files of the specified * publish list, if a file resource type implements the interface * <code>{@link org.opencms.validation.I_CmsXmlDocumentLinkValidatable}</code>.<p> * * @param cms the current user's Cms object * @param publishList an OpenCms publish list * @param report a report to write the messages to * * @return a map with lists of invalid links (<code>String</code> objects) keyed by resource names * * @throws Exception if something goes wrong * * @see #getPublishList(CmsRequestContext, CmsResource, boolean) */ public Map validateHtmlLinks(CmsObject cms, CmsPublishList publishList, I_CmsReport report) throws Exception { return m_driverManager.validateHtmlLinks(cms, publishList, report); } /** * This method checks if a new password follows the rules for * new passwords, which are defined by a Class implementing the * <code>{@link org.opencms.security.I_CmsPasswordHandler}</code> * interface and configured in the opencms.properties file.<p> * * If this method throws no exception the password is valid.<p> * * @param password the new password that has to be checked * * @throws CmsSecurityException if the password is not valid */ public void validatePassword(String password) throws CmsSecurityException { m_driverManager.validatePassword(password); } /** * Writes an access control entries to a given resource.<p> * * @param context the current request context * @param resource the resource * @param ace the entry to write * * @throws CmsSecurityException if the user has insufficient permission for the given resource ({@link CmsPermissionSet#ACCESS_CONTROL} required). * @throws CmsException if something goes wrong */ public void writeAccessControlEntry(CmsRequestContext context, CmsResource resource, CmsAccessControlEntry ace) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_CONTROL, true, CmsResourceFilter.ALL); m_driverManager.writeAccessControlEntry(dbc, resource, ace); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_ACL_ENTRY_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Writes a resource to the OpenCms VFS, including it's content.<p> * * Applies only to resources of type <code>{@link CmsFile}</code> * i.e. resources that have a binary content attached.<p> * * Certain resource types might apply content validation or transformation rules * before the resource is actually written to the VFS. The returned result * might therefore be a modified version from the provided original.<p> * * @param context the current request context * @param resource the resource to apply this operation to * * @return the written resource (may have been modified) * * @throws CmsSecurityException if the user has insufficient permission for the given resource ({@link CmsPermissionSet#ACCESS_WRITE} required). * @throws CmsException if something goes wrong * * @see CmsObject#writeFile(CmsFile) * @see org.opencms.file.types.I_CmsResourceType#writeFile(CmsObject, CmsSecurityManager, CmsFile) */ public CmsFile writeFile(CmsRequestContext context, CmsFile resource) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsFile result = null; try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); result = m_driverManager.writeFile(dbc, resource); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_FILE_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Writes an already existing group.<p> * * The group id has to be a valid OpenCms group id.<br> * * The group with the given id will be completely overriden * by the given data.<p> * * @param context the current request context * @param group the group that should be written * * @throws CmsRoleViolationException if the current user does not own the role {@link CmsRole#USER_MANAGER} for the current project. * @throws CmsException if operation was not succesfull */ public void writeGroup(CmsRequestContext context, CmsGroup group) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.USER_MANAGER); m_driverManager.writeGroup(dbc, group); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_GROUP_1, group.getName()), e); } finally { dbc.clear(); } } /** * Writes an already existing project.<p> * * The project id has to be a valid OpenCms project id.<br> * * The project with the given id will be completely overriden * by the given data.<p> * * @param project the project that should be written * @param context the current request context * * @throws CmsRoleViolationException if the current user does not own the role {@link CmsRole#PROJECT_MANAGER} for the current project. * @throws CmsException if operation was not successful */ public void writeProject(CmsRequestContext context, CmsProject project) throws CmsRoleViolationException, CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.PROJECT_MANAGER); m_driverManager.writeProject(dbc, project); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_PROJECT_1, project.getName()), e); } finally { dbc.clear(); } } /** * Writes a property for a specified resource.<p> * * @param context the current request context * @param resource the resource to write the property for * @param property the property to write * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource ({@link CmsPermissionSet#ACCESS_WRITE} required). * * @see CmsObject#writePropertyObject(String, CmsProperty) * @see org.opencms.file.types.I_CmsResourceType#writePropertyObject(CmsObject, CmsSecurityManager, CmsResource, CmsProperty) */ public void writePropertyObject(CmsRequestContext context, CmsResource resource, CmsProperty property) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.IGNORE_EXPIRATION); m_driverManager.writePropertyObject(dbc, resource, property); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_WRITE_PROP_2, property.getName(), context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Writes a list of properties for a specified resource.<p> * * Code calling this method has to ensure that the no properties * <code>a, b</code> are contained in the specified list so that <code>a.equals(b)</code>, * otherwise an exception is thrown.<p> * * @param context the current request context * @param resource the resource to write the properties for * @param properties the list of properties to write * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource ({@link CmsPermissionSet#ACCESS_WRITE} required). * * @see CmsObject#writePropertyObjects(String, List) * @see org.opencms.file.types.I_CmsResourceType#writePropertyObjects(CmsObject, CmsSecurityManager, CmsResource, List) */ public void writePropertyObjects(CmsRequestContext context, CmsResource resource, List properties) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.IGNORE_EXPIRATION); // write the properties m_driverManager.writePropertyObjects(dbc, resource, properties); // update the resource state resource.setUserLastModified(context.currentUser().getId()); m_driverManager.getVfsDriver().writeResource( dbc, context.currentProject(), resource, CmsDriverManager.C_UPDATE_RESOURCE_STATE); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_PROPS_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Writes a resource to the OpenCms VFS.<p> * * @param context the current request context * @param resource the resource to write * * @throws CmsSecurityException if the user has insufficient permission for the given resource ({@link CmsPermissionSet#ACCESS_WRITE} required). * @throws CmsException if something goes wrong */ public void writeResource(CmsRequestContext context, CmsResource resource) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.writeResource(dbc, resource); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_RESOURCE_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Inserts an entry in the published resource table.<p> * * This is done during static export.<p> * * @param context the current request context * @param resourceName The name of the resource to be added to the static export * @param linkType the type of resource exported (0= non-paramter, 1=parameter) * @param linkParameter the parameters added to the resource * @param timestamp a timestamp for writing the data into the db * * @throws CmsException if something goes wrong */ public void writeStaticExportPublishedResource( CmsRequestContext context, String resourceName, int linkType, String linkParameter, long timestamp) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.writeStaticExportPublishedResource(dbc, resourceName, linkType, linkParameter, timestamp); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_WRITE_STATEXP_PUBLISHED_RESOURCES_3, resourceName, linkParameter, new Date(timestamp)), e); } finally { dbc.clear(); } } /** * Writes a new user tasklog for a task.<p> * * @param context the current request context * @param taskid the Id of the task * @param comment description for the log * * @throws CmsException if something goes wrong */ public void writeTaskLog(CmsRequestContext context, int taskid, String comment) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.writeTaskLog(dbc, taskid, comment); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_TASK_LOG_1, new Integer(taskid)), e); } finally { dbc.clear(); } } /** * Writes a new user tasklog for a task.<p> * * @param context the current request context * @param taskId the Id of the task * @param comment description for the log * @param type type of the tasklog. User tasktypes must be greater than 100 * * @throws CmsException something goes wrong */ public void writeTaskLog(CmsRequestContext context, int taskId, String comment, int type) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.writeTaskLog(dbc, taskId, comment, type); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_TASK_LOG_1, new Integer(taskId)), e); } finally { dbc.clear(); } } /** * Updates the user information. <p> * * The user id has to be a valid OpenCms user id.<br> * * The user with the given id will be completely overriden * by the given data.<p> * * @param context the current request context * @param user the user to be updated * * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#USER_MANAGER} for the current project. * @throws CmsException if operation was not succesful */ public void writeUser(CmsRequestContext context, CmsUser user) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { if (!context.currentUser().equals(user)) { // a user is allowed to write his own data (e.g. for "change preferences") checkRole(dbc, CmsRole.USER_MANAGER); } m_driverManager.writeUser(dbc, user); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_USER_1, user.getName()), e); } finally { dbc.clear(); } } /** * Updates the user information of a web user.<br> * * Only a web user can be updated this way.<p> * * The user id has to be a valid OpenCms user id.<br> * * The user with the given id will be completely overriden * by the given data.<p> * * @param context the current request context * @param user the user to be updated * * @throws CmsException if operation was not succesful */ public void writeWebUser(CmsRequestContext context, CmsUser user) throws CmsException { if (!user.isWebUser()) { throw new CmsSecurityException(Messages.get().container(Messages.ERR_WRITE_WEB_USER_CONSTRAINT_0)); } CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.writeWebUser(dbc, user); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_WEB_USER_1, user.getName()), e); } finally { dbc.clear(); } } /** * Performs a blocking permission check on a resource.<p> * * If the required permissions are not satisfied by the permissions the user has on the resource, * an exception is thrown.<p> * * @param dbc the current database context * @param resource the resource on which permissions are required * @param requiredPermissions the set of permissions required to access the resource * @param checkLock if true, the lock status of the resource is also checked * @param filter the filter for the resource * * @throws CmsException in case of any i/o error * @throws CmsSecurityException if the required permissions are not satisfied * * @see #hasPermissions(CmsRequestContext, CmsResource, CmsPermissionSet, boolean, CmsResourceFilter) */ protected void checkPermissions( CmsDbContext dbc, CmsResource resource, CmsPermissionSet requiredPermissions, boolean checkLock, CmsResourceFilter filter) throws CmsException, CmsSecurityException { // get the permissions int permissions = hasPermissions(dbc, resource, requiredPermissions, checkLock, filter); if (permissions != 0) { checkPermissions(dbc.getRequestContext(), resource, requiredPermissions, permissions); } } /** * Clears the permission cache.<p> */ protected void clearPermissionCache() { m_permissionCache.clear(); } /** * @see java.lang.Object#finalize() */ protected void finalize() throws Throwable { try { if (m_driverManager != null) { m_driverManager.destroy(); } } catch (Throwable t) { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().key(Messages.LOG_ERR_DRIVER_MANAGER_CLOSE_0), t); } } m_driverManager = null; m_dbContextFactory = null; super.finalize(); } /** * Performs a non-blocking permission check on a resource.<p> * * This test will not throw an exception in case the required permissions are not * available for the requested operation. Instead, it will return one of the * following values:<ul> * <li><code>{@link #PERM_ALLOWED}</code></li> * <li><code>{@link #PERM_FILTERED}</code></li> * <li><code>{@link #PERM_DENIED}</code></li></ul><p> * * @param dbc the current database context * @param resource the resource on which permissions are required * @param requiredPermissions the set of permissions required for the operation * @param checkLock if true, a lock for the current user is required for * all write operations, if false it's ok to write as long as the resource * is not locked by another user * @param filter the resource filter to use * * @return <code>PERM_ALLOWED</code> if the user has sufficient permissions on the resource * for the requested operation * * @throws CmsException in case of i/o errors (NOT because of insufficient permissions) */ protected int hasPermissions( CmsDbContext dbc, CmsResource resource, CmsPermissionSet requiredPermissions, boolean checkLock, CmsResourceFilter filter) throws CmsException { // check if the resource is valid according to the current filter // if not, throw a CmsResourceNotFoundException if (!filter.isValid(dbc.getRequestContext(), resource)) { return PERM_FILTERED; } // checking the filter is less cost intensive then checking the cache, // this is why basic filter results are not cached String cacheKey = m_keyGenerator.getCacheKeyForUserPermissions( String.valueOf(filter.requireVisible()), dbc, resource, requiredPermissions); Integer cacheResult = (Integer)m_permissionCache.get(cacheKey); if (cacheResult != null) { return cacheResult.intValue(); } int denied = 0; // if this is the onlineproject, write is rejected if (dbc.currentProject().isOnlineProject()) { denied |= CmsPermissionSet.PERMISSION_WRITE; } // check if the current user is admin boolean canIgnorePermissions = hasRole(dbc, CmsRole.VFS_MANAGER); // check lock status boolean writeRequired = requiredPermissions.requiresWritePermission() || requiredPermissions.requiresControlPermission(); // if the resource type is jsp // write is only allowed for administrators if (writeRequired && !canIgnorePermissions && (resource.getTypeId() == CmsResourceTypeJsp.getStaticTypeId())) { if (!hasRole(dbc, CmsRole.DEVELOPER)) { denied |= CmsPermissionSet.PERMISSION_WRITE; denied |= CmsPermissionSet.PERMISSION_CONTROL; } } if (writeRequired) { // check lock state only if required CmsLock lock = m_driverManager.getLock(dbc, resource); // if the resource is not locked by the current user, write and control // access must cause a permission error that must not be cached if (checkLock || !lock.isNullLock()) { if (!dbc.currentUser().getId().equals(lock.getUserId())) { return PERM_NOTLOCKED; } } } CmsPermissionSetCustom permissions; if (canIgnorePermissions) { // if the current user is administrator, anything is allowed permissions = new CmsPermissionSetCustom(~0); } else { // otherwise, get the permissions from the access control list permissions = m_driverManager.getPermissions(dbc, resource, dbc.currentUser()); } // revoke the denied permissions permissions.denyPermissions(denied); if ((permissions.getPermissions() & CmsPermissionSet.PERMISSION_VIEW) == 0) { // resource "invisible" flag is set for this user if (filter.requireVisible()) { // filter requires visible permission - extend required permission set requiredPermissions = new CmsPermissionSet(requiredPermissions.getAllowedPermissions() | CmsPermissionSet.PERMISSION_VIEW, requiredPermissions.getDeniedPermissions()); } else { // view permissions can be ignored by filter permissions.setPermissions( // modify permissions so that view is allowed permissions.getAllowedPermissions() | CmsPermissionSet.PERMISSION_VIEW, permissions.getDeniedPermissions() & ~CmsPermissionSet.PERMISSION_VIEW); } } Integer result; if ((requiredPermissions.getPermissions() & (permissions.getPermissions())) == requiredPermissions.getPermissions()) { result = PERM_ALLOWED_INTEGER; } else { result = PERM_DENIED_INTEGER; } m_permissionCache.put(cacheKey, result); if ((result != PERM_ALLOWED_INTEGER) && LOG.isDebugEnabled()) { LOG.debug(Messages.get().key( Messages.LOG_NO_PERMISSION_RESOURCE_USER_4, new Object[] { dbc.getRequestContext().removeSiteRoot(resource.getRootPath()), dbc.currentUser().getName(), requiredPermissions.getPermissionString(), permissions.getPermissionString()})); } return result.intValue(); } /** * Reads a folder from the VFS, using the specified resource filter.<p> * * @param dbc the current database context * @param resourcename the name of the folder to read (full path) * @param filter the resource filter to use while reading * * @return the folder that was read * * @throws CmsException if something goes wrong */ protected CmsFolder readFolder(CmsDbContext dbc, String resourcename, CmsResourceFilter filter) throws CmsException { CmsResource resource = readResource(dbc, resourcename, filter); return m_driverManager.convertResourceToFolder(resource); } /** * Reads a resource from the OpenCms VFS, using the specified resource filter.<p> * * @param dbc the current database context * @param resourcePath the name of the resource to read (full path) * @param filter the resource filter to use while reading * * @return the resource that was read * * @throws CmsException if something goes wrong * * @see CmsObject#readResource(String, CmsResourceFilter) * @see CmsObject#readResource(String) * @see CmsFile#upgrade(CmsResource, CmsObject) */ protected CmsResource readResource(CmsDbContext dbc, String resourcePath, CmsResourceFilter filter) throws CmsException { // read the resource from the VFS CmsResource resource = m_driverManager.readResource(dbc, resourcePath, filter); // check if the user has read access to the resource checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_READ, true, filter); // access was granted - return the resource return resource; } /** * Applies the permission check result of a previous call * to {@link #hasPermissions(CmsRequestContext, CmsResource, CmsPermissionSet, boolean, CmsResourceFilter)}.<p> * * @param context the current request context * @param resource the resource on which permissions are required * @param requiredPermissions the set of permissions required to access the resource * @param permissions the permissions to check * * @throws CmsSecurityException if the required permissions are not satisfied * @throws CmsLockException if the lock status is not as required * @throws CmsVfsResourceNotFoundException if the required resource has been filtered */ protected void checkPermissions( CmsRequestContext context, CmsResource resource, CmsPermissionSet requiredPermissions, int permissions) throws CmsSecurityException, CmsLockException, CmsVfsResourceNotFoundException { switch (permissions) { case PERM_FILTERED: throw new CmsVfsResourceNotFoundException(Messages.get().container( Messages.ERR_PERM_FILTERED_1, context.getSitePath(resource))); case PERM_DENIED: throw new CmsPermissionViolationException(Messages.get().container( Messages.ERR_PERM_DENIED_2, context.getSitePath(resource), requiredPermissions.getPermissionString())); case PERM_NOTLOCKED: throw new CmsLockException(Messages.get().container( Messages.ERR_PERM_NOTLOCKED_2, context.getSitePath(resource), context.currentUser().getName())); case PERM_ALLOWED: default: return; } } /** * Deletes a user.<p> * * @param context the current request context * @param user the user to be deleted * * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#USER_MANAGER} * @throws CmsSecurityException in case the user is a default user * @throws CmsException if something goes wrong */ private void deleteUser(CmsRequestContext context, CmsUser user) throws CmsException { if (OpenCms.getDefaultUsers().isDefaultUser(user.getName())) { throw new CmsSecurityException(org.opencms.security.Messages.get().container( org.opencms.security.Messages.ERR_CANT_DELETE_DEFAULT_USER_1, user.getName())); } CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.USER_MANAGER); m_driverManager.deleteUser(dbc, context.currentProject(), user.getId()); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DELETE_USER_1, user.getName()), e); } finally { dbc.clear(); } } }
src/org/opencms/db/CmsSecurityManager.java
/* * File : $Source: /alkacon/cvs/opencms/src/org/opencms/db/CmsSecurityManager.java,v $ * Date : $Date: 2005/06/23 18:06:27 $ * Version: $Revision: 1.84 $ * * This library is part of OpenCms - * the Open Source Content Mananagement System * * Copyright (c) 2005 Alkacon Software GmbH (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software GmbH, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.db; import org.opencms.configuration.CmsConfigurationManager; import org.opencms.configuration.CmsSystemConfiguration; import org.opencms.file.CmsBackupProject; import org.opencms.file.CmsBackupResource; import org.opencms.file.CmsFile; import org.opencms.file.CmsFolder; import org.opencms.file.CmsGroup; import org.opencms.file.CmsObject; import org.opencms.file.CmsProject; import org.opencms.file.CmsProperty; import org.opencms.file.CmsPropertyDefinition; import org.opencms.file.CmsRequestContext; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.file.CmsUser; import org.opencms.file.CmsVfsException; import org.opencms.file.CmsVfsResourceNotFoundException; import org.opencms.file.types.CmsResourceTypeJsp; import org.opencms.i18n.CmsMessageContainer; import org.opencms.lock.CmsLock; import org.opencms.lock.CmsLockException; import org.opencms.main.CmsException; import org.opencms.main.CmsInitException; import org.opencms.main.CmsLog; import org.opencms.main.I_CmsConstants; import org.opencms.main.OpenCms; import org.opencms.report.I_CmsReport; import org.opencms.security.CmsAccessControlEntry; import org.opencms.security.CmsAccessControlList; import org.opencms.security.CmsPermissionSet; import org.opencms.security.CmsPermissionSetCustom; import org.opencms.security.CmsPermissionViolationException; import org.opencms.security.CmsRole; import org.opencms.security.CmsRoleViolationException; import org.opencms.security.CmsSecurityException; import org.opencms.security.I_CmsPrincipal; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import org.opencms.workflow.CmsTask; import org.opencms.workflow.CmsTaskLog; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.apache.commons.collections.map.LRUMap; import org.apache.commons.logging.Log; /** * The OpenCms security manager.<p> * * The security manager checks the permissions required for a user action invoke by the Cms object. If permissions * are granted, the security manager invokes a method on the OpenCms driver manager to access the database.<p> * * @author Thomas Weckert * @author Michael Moossen * * @version $Revision: 1.84 $ * * @since 6.0.0 */ public final class CmsSecurityManager { /** Indicates allowed permissions. */ public static final int PERM_ALLOWED = 0; /** Indicates denied permissions. */ public static final int PERM_DENIED = 1; /** Indicates a resource was filtered during permission check. */ public static final int PERM_FILTERED = 2; /** Indicates a resource was not locked for a write / control operation. */ public static final int PERM_NOTLOCKED = 3; /** The log object for this class. */ private static final Log LOG = CmsLog.getLog(CmsSecurityManager.class); /** Indicates allowed permissions. */ private static final Integer PERM_ALLOWED_INTEGER = new Integer(PERM_ALLOWED); /** Indicates denied permissions. */ private static final Integer PERM_DENIED_INTEGER = new Integer(PERM_DENIED); /** The factory to create runtime info objects. */ protected I_CmsDbContextFactory m_dbContextFactory; /** The initialized OpenCms driver manager to access the database. */ protected CmsDriverManager m_driverManager; /** The class used for cache key generation. */ private I_CmsCacheKey m_keyGenerator; /** Cache for permission checks. */ private Map m_permissionCache; /** * Default constructor.<p> */ private CmsSecurityManager() { // intentionally left blank } /** * Creates a new instance of the OpenCms security manager.<p> * * @param configurationManager the configuation manager * @param runtimeInfoFactory the initialized OpenCms runtime info factory * * @return a new instance of the OpenCms security manager * * @throws CmsInitException if the securtiy manager could not be initialized */ public static CmsSecurityManager newInstance( CmsConfigurationManager configurationManager, I_CmsDbContextFactory runtimeInfoFactory) throws CmsInitException { if (OpenCms.getRunLevel() > OpenCms.RUNLEVEL_2_INITIALIZING) { // OpenCms is already initialized throw new CmsInitException(org.opencms.main.Messages.get().container( org.opencms.main.Messages.ERR_ALREADY_INITIALIZED_0)); } CmsSecurityManager securityManager = new CmsSecurityManager(); securityManager.init(configurationManager, runtimeInfoFactory); return securityManager; } /** * Updates the state of the given task as accepted by the current user.<p> * * @param context the current request context * @param taskId the Id of the task to accept * * @throws CmsException if something goes wrong */ public void acceptTask(CmsRequestContext context, int taskId) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.acceptTask(dbc, taskId); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_ACCEPT_TASK_1, new Integer(taskId)), e); } finally { dbc.clear(); } } /** * Adds a user to a group.<p> * * @param context the current request context * @param username the name of the user that is to be added to the group * @param groupname the name of the group * * @throws CmsException if operation was not succesfull */ public void addUserToGroup(CmsRequestContext context, String username, String groupname) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.USER_MANAGER); m_driverManager.addUserToGroup(dbc, username, groupname); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_ADD_USER_GROUP_FAILED_2, username, groupname), e); } finally { dbc.clear(); } } /** * Creates a new web user.<p> * * A web user has no access to the workplace but is able to access personalized * functions controlled by the OpenCms.<br> * * Moreover, a web user can be created by any user, the intention being that * a "Guest" user can create a personalized account for himself.<p> * * @param context the current request context * @param name the new name for the user * @param password the new password for the user * @param group the default groupname for the user * @param description the description for the user * @param additionalInfos a <code>{@link Map}</code> with additional infos for the user * * @return the new user will be returned * * @throws CmsException if operation was not succesfull */ public CmsUser addWebUser( CmsRequestContext context, String name, String password, String group, String description, Map additionalInfos) throws CmsException { CmsUser result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.addWebUser(dbc, name, password, group, description, additionalInfos); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_ADD_USER_WEB_1, name), e); } finally { dbc.clear(); } return result; } /** * Adds a web user to the Cms.<p> * * A web user has no access to the workplace but is able to access personalized * functions controlled by the OpenCms.<p> * * @param context the current request context * @param name the new name for the user * @param password the new password for the user * @param group the default groupname for the user * @param additionalGroup an additional group for the user * @param description the description for the user * @param additionalInfos a Hashtable with additional infos for the user, these infos may be stored into the Usertables (depending on the implementation) * * @return the new user will be returned * @throws CmsException if operation was not succesfull */ public CmsUser addWebUser( CmsRequestContext context, String name, String password, String group, String additionalGroup, String description, Map additionalInfos) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.addWebUser( dbc, name, password, group, additionalGroup, description, additionalInfos); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_ADD_USER_WEB_1, name), e); } finally { dbc.clear(); } return result; } /** * Creates a backup of the current project.<p> * * @param context the current request context * @param tagId the version of the backup * @param publishDate the date of publishing * * @throws CmsException if operation was not succesful */ public void backupProject(CmsRequestContext context, int tagId, long publishDate) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.backupProject(dbc, tagId, publishDate); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_BACKUP_PROJECT_4, new Object[] { new Integer(tagId), dbc.currentProject().getName(), new Integer(dbc.currentProject().getId()), new Long(publishDate)}), e); } finally { dbc.clear(); } } /** * Changes the project id of the resource to the current project, indicating that * the resource was last modified in this project.<p> * * @param context the current request context * @param resource theresource to apply this operation to * @throws CmsException if something goes wrong * @see org.opencms.file.types.I_CmsResourceType#changeLastModifiedProjectId(CmsObject, CmsSecurityManager, CmsResource) */ public void changeLastModifiedProjectId(CmsRequestContext context, CmsResource resource) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.changeLastModifiedProjectId(dbc, resource); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_CHANGE_LAST_MODIFIED_RESOURCE_IN_PROJECT_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Changes the lock of a resource to the current user, that is "steals" the lock from another user.<p> * * @param context the current request context * @param resource the resource to change the lock for * @throws CmsException if something goes wrong * @see org.opencms.file.types.I_CmsResourceType#changeLock(CmsObject, CmsSecurityManager, CmsResource) */ public void changeLock(CmsRequestContext context, CmsResource resource) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); checkOfflineProject(dbc); try { m_driverManager.changeLock(dbc, resource); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_CHANGE_LOCK_OF_RESOURCE_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Returns a list with all sub resources of a given folder that have set the given property, * matching the current property's value with the given old value and replacing it by a given new value.<p> * * @param context the current request context * @param resource the resource on which property definition values are changed * @param propertyDefinition the name of the propertydefinition to change the value * @param oldValue the old value of the propertydefinition * @param newValue the new value of the propertydefinition * @param recursive if true, change recursively all property values on sub-resources (only for folders) * * @return a list with the <code>{@link CmsResource}</code>'s where the property value has been changed * * @throws CmsVfsException for now only when the search for the oldvalue failed. * @throws CmsException if operation was not successful */ public List changeResourcesInFolderWithProperty( CmsRequestContext context, CmsResource resource, String propertyDefinition, String oldValue, String newValue, boolean recursive) throws CmsException, CmsVfsException { int todo = 0; // check if this belongs here - should be in driver manager (?) // collect the resources to look up List resources = new ArrayList(); if (recursive) { resources = readResourcesWithProperty(context, resource.getRootPath(), propertyDefinition); } else { resources.add(resource); } Pattern oldPattern; try { // compile regular expression pattern oldPattern = Pattern.compile(oldValue); } catch (PatternSyntaxException e) { throw new CmsVfsException(Messages.get().container( Messages.ERR_CHANGE_RESOURCES_IN_FOLDER_WITH_PROP_4, new Object[] {propertyDefinition, oldValue, newValue, context.getSitePath(resource)}), e); } List changedResources = new ArrayList(resources.size()); // create permission set and filter to check each resource CmsPermissionSet perm = CmsPermissionSet.ACCESS_WRITE; CmsResourceFilter filter = CmsResourceFilter.IGNORE_EXPIRATION; for (int i = 0; i < resources.size(); i++) { // loop through found resources and check property values CmsResource res = (CmsResource)resources.get(i); // check resource state and permissions try { checkPermissions(context, res, perm, true, filter); } catch (Exception e) { // resource is deleted or not writable for current user continue; } CmsProperty property = readPropertyObject(context, res, propertyDefinition, false); String structureValue = property.getStructureValue(); String resourceValue = property.getResourceValue(); boolean changed = false; if (structureValue != null && oldPattern.matcher(structureValue).matches()) { // change structure value property.setStructureValue(newValue); changed = true; } if (resourceValue != null && oldPattern.matcher(resourceValue).matches()) { // change resource value property.setResourceValue(newValue); changed = true; } if (changed) { // write property object if something has changed writePropertyObject(context, res, property); changedResources.add(res); } } return changedResources; } /** * Changes the user type of the user.<p> * * @param context the current request context * @param userId the id of the user to change * @param userType the new usertype of the user * * @throws CmsException if something goes wrong */ public void changeUserType(CmsRequestContext context, CmsUUID userId, int userType) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.USER_MANAGER); m_driverManager.changeUserType(dbc, userId, userType); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CHANGE_USER_TYPE_WITH_ID_1, userId.toString()), e); } finally { dbc.clear(); } } /** * Changes the user type of the user.<p> * Only the administrator can change the type.<p> * * @param context the current request context * @param username the name of the user to change * @param userType the new usertype of the user * @throws CmsException if something goes wrong */ public void changeUserType(CmsRequestContext context, String username, int userType) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.USER_MANAGER); m_driverManager.changeUserType(dbc, username, userType); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CHANGE_USER_TYPE_WITH_NAME_1, username), e); } finally { dbc.clear(); } } /** * Checks if the current user has management access to the given project.<p> * * @param dbc the current database context * @param project the project to check * * @throws CmsRoleViolationException if the user does not have the required role permissions */ public void checkManagerOfProjectRole(CmsDbContext dbc, CmsProject project) throws CmsRoleViolationException { if (!hasManagerOfProjectRole(dbc, project)) { throw new CmsRoleViolationException(org.opencms.security.Messages.get().container( org.opencms.security.Messages.ERR_NOT_MANAGER_OF_PROJECT_2, dbc.currentUser().getName(), dbc.currentProject().getName())); } } /** * Checks if the project in the given database context is not the "Online" project, * and throws an Exception if this is the case.<p> * * This is used to ensure a user is in an "Offline" project * before write access to VFS resources is granted.<p> * * @param dbc the current OpenCms users database context * * @throws CmsVfsException if the project in the given database context is the "Online" project */ public void checkOfflineProject(CmsDbContext dbc) throws CmsVfsException { if (dbc.currentProject().isOnlineProject()) { throw new CmsVfsException(org.opencms.file.Messages.get().container( org.opencms.file.Messages.ERR_NOT_ALLOWED_IN_ONLINE_PROJECT_0)); } } /** * Performs a blocking permission check on a resource.<p> * * If the required permissions are not satisfied by the permissions the user has on the resource, * an exception is thrown.<p> * * @param context the current request context * @param resource the resource on which permissions are required * @param requiredPermissions the set of permissions required to access the resource * @param checkLock if true, the lock status of the resource is also checked * @param filter the filter for the resource * * @throws CmsException in case of any i/o error * @throws CmsSecurityException if the required permissions are not satisfied * * @see #checkPermissions(CmsRequestContext, CmsResource, CmsPermissionSet, int) */ public void checkPermissions( CmsRequestContext context, CmsResource resource, CmsPermissionSet requiredPermissions, boolean checkLock, CmsResourceFilter filter) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { // check the access permissions checkPermissions(dbc, resource, requiredPermissions, checkLock, filter); } finally { dbc.clear(); } } /** * Checks if the given resource or the current project can be published by the current user * using his current OpenCms context.<p> * * If the resource parameter is <code>null</code>, then the current project is checked, * otherwise the resource is checked for direct publish permissions.<p> * * @param context the current request context * @param directPublishResource the direct publish resource (optional, if null only the current project is checked) * * @throws CmsException if the user does not have the required permissions * @throws CmsSecurityException if a direct publish is attempted on a resource * whose parent folder is new or deleted in the offline project. * @throws CmsRoleViolationException if the current user has no management access to the current project. */ public void checkPublishPermissions(CmsRequestContext context, CmsResource directPublishResource) throws CmsException, CmsSecurityException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); // is the current project an "offline" project? checkOfflineProject(dbc); // check if the current project is unlocked if (context.currentProject().getFlags() != I_CmsConstants.C_PROJECT_STATE_UNLOCKED) { CmsMessageContainer errMsg = org.opencms.security.Messages.get().container( org.opencms.security.Messages.ERR_RESOURCE_LOCKED_1, context.currentProject().getName()); throw new CmsLockException(errMsg); } // check if this is a "direct publish" attempt if (directPublishResource != null) { // the parent folder must not be new or deleted String parentFolder = CmsResource.getParentFolder(directPublishResource.getRootPath()); if (parentFolder != null) { CmsResource parent = readResource(context, parentFolder, CmsResourceFilter.ALL); if (parent.getState() == I_CmsConstants.C_STATE_DELETED) { // parent folder is deleted - direct publish not allowed throw new CmsVfsException(Messages.get().container( Messages.ERR_DIRECT_PUBLISH_PARENT_DELETED_2, dbc.getRequestContext().removeSiteRoot(directPublishResource.getRootPath()), parentFolder)); } if (parent.getState() == I_CmsConstants.C_STATE_NEW) { // parent folder is new - direct publish not allowed throw new CmsVfsException(Messages.get().container( Messages.ERR_DIRECT_PUBLISH_PARENT_NEW_2, context.removeSiteRoot(directPublishResource.getRootPath()), parentFolder)); } } // check if the user has the explicit permission to direct publish the selected resource if (PERM_ALLOWED == hasPermissions( context, directPublishResource, CmsPermissionSet.ACCESS_DIRECT_PUBLISH, true, CmsResourceFilter.ALL)) { // the user has "direct publish" permissions on the resource return; } } // check if the user is a manager of the current project, in this case he has publish permissions try { checkManagerOfProjectRole(dbc, dbc.getRequestContext().currentProject()); } finally { dbc.clear(); } } /** * Checks if the user of the current database context * has permissions to impersonate the given role.<p> * * @param dbc the current OpenCms users database context * @param role the role to check * * @throws CmsRoleViolationException if the user does not have the required role permissions */ public void checkRole(CmsDbContext dbc, CmsRole role) throws CmsRoleViolationException { if (!hasRole(dbc, role)) { throw role.createRoleViolationException(dbc.getRequestContext()); } } /** * Checks if the user of the current database context * has permissions to impersonate the given role.<p> * * @param context the current request context * @param role the role to check * * @throws CmsRoleViolationException if the user does not have the required role permissions */ public void checkRole(CmsRequestContext context, CmsRole role) throws CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, role); } finally { dbc.clear(); } } /** * Changes the resource flags of a resource.<p> * * The resource flags are used to indicate various "special" conditions * for a resource. Most notably, the "internal only" setting which signals * that a resource can not be directly requested with it's URL.<p> * * @param context the current request context * @param resource the resource to change the flags for * @param flags the new resource flags for this resource * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (({@link CmsPermissionSet#ACCESS_WRITE} required). * @see org.opencms.file.types.I_CmsResourceType#chflags(CmsObject, CmsSecurityManager, CmsResource, int) */ public void chflags(CmsRequestContext context, CmsResource resource, int flags) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.chflags(dbc, resource, flags); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_CHANGE_RESOURCE_FLAGS_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Changes the resource type of a resource.<p> * * OpenCms handles resources according to the resource type, * not the file suffix. This is e.g. why a JSP in OpenCms can have the * suffix ".html" instead of ".jsp" only. Changing the resource type * makes sense e.g. if you want to make a plain text file a JSP resource, * or a binary file an image, etc.<p> * * @param context the current request context * @param resource the resource to change the type for * @param type the new resource type for this resource * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (({@link CmsPermissionSet#ACCESS_WRITE} required)). * * @see org.opencms.file.types.I_CmsResourceType#chtype(CmsObject, CmsSecurityManager, CmsResource, int) * @see CmsObject#chtype(String, int) */ public void chtype(CmsRequestContext context, CmsResource resource, int type) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.chtype(dbc, resource, type); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_CHANGE_RESOURCE_TYPE_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Copies the access control entries of a given resource to a destination resorce.<p> * * Already existing access control entries of the destination resource are removed.<p> * * @param context the current request context * @param source the resource to copy the access control entries from * @param destination the resource to which the access control entries are copied * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource ({@link CmsPermissionSet#ACCESS_CONTROL} required). */ public void copyAccessControlEntries(CmsRequestContext context, CmsResource source, CmsResource destination) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, source, CmsPermissionSet.ACCESS_READ, true, CmsResourceFilter.ALL); checkPermissions(dbc, destination, CmsPermissionSet.ACCESS_CONTROL, true, CmsResourceFilter.ALL); m_driverManager.copyAccessControlEntries(dbc, source, destination); } catch (Exception e) { CmsRequestContext rc = context; dbc.report(null, Messages.get().container( Messages.ERR_COPY_ACE_2, rc.removeSiteRoot(source.getRootPath()), rc.removeSiteRoot(destination.getRootPath())), e); } finally { dbc.clear(); } } /** * Copies a resource.<p> * * You must ensure that the destination path is an absolute, valid and * existing VFS path. Relative paths from the source are currently not supported.<p> * * The copied resource will always be locked to the current user * after the copy operation.<p> * * In case the target resource already exists, it is overwritten with the * source resource.<p> * * The <code>siblingMode</code> parameter controls how to handle siblings * during the copy operation.<br> * Possible values for this parameter are: <br> * <ul> * <li><code>{@link org.opencms.main.I_CmsConstants#C_COPY_AS_NEW}</code></li> * <li><code>{@link org.opencms.main.I_CmsConstants#C_COPY_AS_SIBLING}</code></li> * <li><code>{@link org.opencms.main.I_CmsConstants#C_COPY_PRESERVE_SIBLING}</code></li> * </ul><p> * * @param context the current request context * @param source the resource to copy * @param destination the name of the copy destination with complete path * @param siblingMode indicates how to handle siblings during copy * * @throws CmsException if something goes wrong * @throws CmsSecurityException if resource could not be copied * * @see CmsObject#copyResource(String, String, int) * @see org.opencms.file.types.I_CmsResourceType#copyResource(CmsObject, CmsSecurityManager, CmsResource, String, int) */ public void copyResource(CmsRequestContext context, CmsResource source, String destination, int siblingMode) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsRequestContext rc = context; try { checkOfflineProject(dbc); checkPermissions(dbc, source, CmsPermissionSet.ACCESS_READ, true, CmsResourceFilter.ALL); // target permissions will be checked later m_driverManager.copyResource(dbc, source, destination, siblingMode); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_COPY_RESOURCE_2, rc.removeSiteRoot(source.getRootPath()), rc.removeSiteRoot(destination)), e); } finally { dbc.clear(); } } /** * Copies a resource to the current project of the user.<p> * * @param context the current request context * @param resource the resource to apply this operation to * @throws CmsException if something goes wrong * @throws CmsRoleViolationException if the current user does not have management access to the project. * @see org.opencms.file.types.I_CmsResourceType#copyResourceToProject(CmsObject, CmsSecurityManager, CmsResource) */ public void copyResourceToProject(CmsRequestContext context, CmsResource resource) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkManagerOfProjectRole(dbc, context.currentProject()); if (dbc.currentProject().getFlags() != I_CmsConstants.C_PROJECT_STATE_UNLOCKED) { throw new CmsLockException(org.opencms.lock.Messages.get().container( org.opencms.lock.Messages.ERR_RESOURCE_LOCKED_1, dbc.currentProject().getName())); } m_driverManager.copyResourceToProject(dbc, resource); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_COPY_RESOURCE_TO_PROJECT_2, context.getSitePath(resource), context.currentProject().getName()), e); } finally { dbc.clear(); } } /** * Counts the locked resources in this project.<p> * * @param context the current request context * @param id the id of the project * * @return the amount of locked resources in this project * * @throws CmsException if something goes wrong * @throws CmsRoleViolationException if the current user does not have management access to the project. */ public int countLockedResources(CmsRequestContext context, int id) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsProject project = null; int result = 0; try { project = m_driverManager.readProject(dbc, id); checkManagerOfProjectRole(dbc, project); result = m_driverManager.countLockedResources(project); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_COUNT_LOCKED_RESOURCES_PROJECT_2, (project == null) ? "<failed to read>" : project.getName(), new Integer(id)), e); } finally { dbc.clear(); } return result; } /** * Counts the locked resources in a given folder.<p> * * @param context the current request context * @param foldername the folder to search in * * @return the amount of locked resources in this project * * @throws CmsException if something goes wrong */ public int countLockedResources(CmsRequestContext context, String foldername) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); // perform a test for read permissions on the folder readResource(dbc, foldername, CmsResourceFilter.ALL); int result = 0; try { result = m_driverManager.countLockedResources(dbc, foldername); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_COUNT_LOCKED_RESOURCES_FOLDER_1, foldername), e); } finally { dbc.clear(); } return result; } /** * Creates a new user group.<p> * * @param context the current request context * @param name the name of the new group * @param description the description for the new group * @param flags the flags for the new group * @param parent the name of the parent group (or <code>null</code>) * * @return a <code>{@link CmsGroup}</code> object representing the newly created group * * @throws CmsException if operation was not successful. * @throws CmsRoleViolationException if the role {@link CmsRole#USER_MANAGER} is not owned by the current user. * */ public CmsGroup createGroup(CmsRequestContext context, String name, String description, int flags, String parent) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsGroup result = null; try { checkRole(dbc, CmsRole.USER_MANAGER); result = m_driverManager.createGroup(dbc, new CmsUUID(), name, description, flags, parent); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_GROUP_1, name), e); } finally { dbc.clear(); } return result; } /** * Creates a project.<p> * * @param context the current request context * @param name the name of the project to create * @param description the description of the project * @param groupname the project user group to be set * @param managergroupname the project manager group to be set * @param projecttype the type of the project * * @return the created project * * @throws CmsException if something goes wrong * @throws CmsRoleViolationException if the current user does not own the role {@link CmsRole#PROJECT_MANAGER}. */ public CmsProject createProject( CmsRequestContext context, String name, String description, String groupname, String managergroupname, int projecttype) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsProject result = null; try { checkRole(dbc, CmsRole.PROJECT_MANAGER); result = m_driverManager.createProject(dbc, name, description, groupname, managergroupname, projecttype); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_PROJECT_1, name), e); } finally { dbc.clear(); } return result; } /** * Creates a property definition.<p> * * Property definitions are valid for all resource types.<p> * * @param context the current request context * @param name the name of the property definition to create * * @return the created property definition * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the current project is online. * @throws CmsRoleViolationException if the current user does not own the role {@link CmsRole#PROPERTY_MANAGER}. */ public CmsPropertyDefinition createPropertyDefinition(CmsRequestContext context, String name) throws CmsException, CmsSecurityException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsPropertyDefinition result = null; try { checkOfflineProject(dbc); checkRole(dbc, CmsRole.PROPERTY_MANAGER); result = m_driverManager.createPropertyDefinition(dbc, name); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_PROPDEF_1, name), e); } finally { dbc.clear(); } return result; } /** * Creates a new resource of the given resource type with the provided content and properties.<p> * * If the provided content is null and the resource is not a folder, the content will be set to an empty byte array.<p> * * @param context the current request context * @param resourcename the name of the resource to create (full path) * @param type the type of the resource to create * @param content the content for the new resource * @param properties the properties for the new resource * @return the created resource * @throws CmsException if something goes wrong * * @see org.opencms.file.types.I_CmsResourceType#createResource(CmsObject, CmsSecurityManager, String, byte[], List) */ public CmsResource createResource( CmsRequestContext context, String resourcename, int type, byte[] content, List properties) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsResource newResource = null; try { checkOfflineProject(dbc); newResource = m_driverManager.createResource(dbc, resourcename, type, content, properties); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_RESOURCE_1, resourcename), e); } finally { dbc.clear(); } return newResource; } /** * Creates a new sibling of the source resource.<p> * * @param context the current request context * @param source the resource to create a sibling for * @param destination the name of the sibling to create with complete path * @param properties the individual properties for the new sibling * @throws CmsException if something goes wrong * @see org.opencms.file.types.I_CmsResourceType#createSibling(CmsObject, CmsSecurityManager, CmsResource, String, List) */ public void createSibling(CmsRequestContext context, CmsResource source, String destination, List properties) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); m_driverManager.createSibling(dbc, source, destination, properties); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_CREATE_SIBLING_1, context.removeSiteRoot(source.getRootPath())), e); } finally { dbc.clear(); } } /** * Creates a new task.<p> * * @param context the current request context * @param currentUser the current user * @param projectid the current project id * @param agentName user who will edit the task * @param roleName usergroup for the task * @param taskName name of the task * @param taskType type of the task * @param taskComment description of the task * @param timeout time when the task must finished * @param priority Id for the priority * * @return a new task object * * @throws CmsException if something goes wrong */ public CmsTask createTask( CmsRequestContext context, CmsUser currentUser, int projectid, String agentName, String roleName, String taskName, String taskComment, int taskType, long timeout, int priority) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsTask result = null; try { result = m_driverManager.createTask( dbc, currentUser, projectid, agentName, roleName, taskName, taskComment, taskType, timeout, priority); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_TASK_1, taskName), e); } finally { dbc.clear(); } return result; } /** * Creates a new task.<p> * * This is just a more limited version of the * <code>{@link #createTask(CmsRequestContext, CmsUser, int, String, String, String, String, int, long, int)}</code> * method, where: <br> * <ul> * <il>the project id is the current project id.</il> * <il>the task type is the standard task type <b>1</b>.</il> * <il>with no comments</il> * </ul><p> * * @param context the current request context * @param agentName the user who will edit the task * @param roleName a usergroup for the task * @param taskname the name of the task * @param timeout the time when the task must finished * @param priority the id for the priority of the task * * @return the created task * * @throws CmsException if something goes wrong */ public CmsTask createTask( CmsRequestContext context, String agentName, String roleName, String taskname, long timeout, int priority) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsTask result = null; try { result = m_driverManager.createTask(dbc, agentName, roleName, taskname, timeout, priority); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_TASK_1, taskname), e); } finally { dbc.clear(); } return result; } /** * Creates the project for the temporary workplace files.<p> * * @param context the current request context * * @return the created project for the temporary workplace files * * @throws CmsException if something goes wrong */ public CmsProject createTempfileProject(CmsRequestContext context) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsProject result = null; try { checkRole(dbc, CmsRole.PROJECT_MANAGER); result = m_driverManager.createTempfileProject(dbc); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_TEMPFILE_PROJECT_0), e); } finally { dbc.clear(); } return result; } /** * Creates a new user.<p> * * @param context the current request context * @param name the name for the new user * @param password the password for the new user * @param description the description for the new user * @param additionalInfos the additional infos for the user * * @return the created user * * @see CmsObject#createUser(String, String, String, Map) * * @throws CmsException if something goes wrong * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#USER_MANAGER} */ public CmsUser createUser( CmsRequestContext context, String name, String password, String description, Map additionalInfos) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { checkRole(dbc, CmsRole.USER_MANAGER); result = m_driverManager.createUser(dbc, name, password, description, additionalInfos); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_USER_1, name), e); } finally { dbc.clear(); } return result; } /** * Deletes all entries in the published resource table.<p> * * @param context the current request context * @param linkType the type of resource deleted (0= non-paramter, 1=parameter) * * @throws CmsException if something goes wrong */ public void deleteAllStaticExportPublishedResources(CmsRequestContext context, int linkType) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.deleteAllStaticExportPublishedResources(dbc, linkType); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DELETE_STATEXP_PUBLISHED_RESOURCES_0), e); } finally { dbc.clear(); } } /** * Deletes the versions from the backup tables that are older then the given timestamp * and/or number of remaining versions.<p> * * The number of verions always wins, i.e. if the given timestamp would delete more versions * than given in the versions parameter, the timestamp will be ignored. <p> * * Deletion will delete file header, content and properties. <p> * * @param context the current request context * @param timestamp timestamp which defines the date after which backup resources must be deleted * @param versions the number of versions per file which should kept in the system * @param report the report for output logging * * @throws CmsException if operation was not succesful * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#HISTORY_MANAGER} */ public void deleteBackups(CmsRequestContext context, long timestamp, int versions, I_CmsReport report) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.HISTORY_MANAGER); m_driverManager.deleteBackups(dbc, timestamp, versions, report); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_DELETE_BACKUPS_2, new Date(timestamp), new Integer(versions)), e); } finally { dbc.clear(); } } /** * Delete a user group.<p> * * Only groups that contain no subgroups can be deleted.<p> * * @param context the current request context * @param name the name of the group that is to be deleted * * @throws CmsException if operation was not succesful * @throws CmsSecurityException if the group is a default group. * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#USER_MANAGER} * */ public void deleteGroup(CmsRequestContext context, String name) throws CmsException, CmsRoleViolationException, CmsSecurityException { if (OpenCms.getDefaultUsers().isDefaultGroup(name)) { throw new CmsSecurityException(Messages.get().container( Messages.ERR_CONSTRAINT_DELETE_GROUP_DEFAULT_1, name)); } CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { // catch own exception as special cause for general "Error deleting group". checkRole(dbc, CmsRole.USER_MANAGER); m_driverManager.deleteGroup(dbc, name); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DELETE_GROUP_1, name), e); } finally { dbc.clear(); } } /** * Deletes a project.<p> * * All modified resources currently inside this project will be reset to their online state.<p> * * @param context the current request context * @param projectId the ID of the project to be deleted * * @throws CmsException if something goes wrong * @throws CmsRoleViolationException if the current user does not own management access to the project */ public void deleteProject(CmsRequestContext context, int projectId) throws CmsException, CmsRoleViolationException { if (projectId == I_CmsConstants.C_PROJECT_ONLINE_ID) { // online project must not be deleted throw new CmsVfsException(org.opencms.file.Messages.get().container( org.opencms.file.Messages.ERR_NOT_ALLOWED_IN_ONLINE_PROJECT_0)); } if (projectId == context.currentProject().getId()) { // current project must not be deleted throw new CmsVfsException(Messages.get().container( Messages.ERR_DELETE_PROJECT_CURRENT_1, context.currentProject().getName())); } CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsProject deleteProject = null; try { // read the project that should be deleted deleteProject = m_driverManager.readProject(dbc, projectId); checkManagerOfProjectRole(dbc, context.currentProject()); m_driverManager.deleteProject(dbc, deleteProject); } catch (Exception e) { String projectName = deleteProject == null ? String.valueOf(projectId) : deleteProject.getName(); dbc.report(null, Messages.get().container(Messages.ERR_DELETE_PROJECT_1, projectName), e); } finally { dbc.clear(); } } /** * Deletes a property definition.<p> * * @param context the current request context * @param name the name of the property definition to delete * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the project to delete is the "Online" project * @throws CmsRoleViolationException if the current user does not own the role {@link CmsRole#PROPERTY_MANAGER} */ public void deletePropertyDefinition(CmsRequestContext context, String name) throws CmsException, CmsSecurityException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkRole(dbc, CmsRole.PROPERTY_MANAGER); m_driverManager.deletePropertyDefinition(dbc, name); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DELETE_PROPERTY_1, name), e); } finally { dbc.clear(); } } /** * Deletes a resource given its name.<p> * * The <code>siblingMode</code> parameter controls how to handle siblings * during the delete operation.<br> * Possible values for this parameter are: <br> * <ul> * <li><code>{@link org.opencms.main.I_CmsConstants#C_DELETE_OPTION_DELETE_SIBLINGS}</code></li> * <li><code>{@link org.opencms.main.I_CmsConstants#C_DELETE_OPTION_PRESERVE_SIBLINGS}</code></li> * </ul><p> * * @param context the current request context * @param resource the name of the resource to delete (full path) * @param siblingMode indicates how to handle siblings of the deleted resource * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user does not have {@link CmsPermissionSet#ACCESS_WRITE} on the given resource. * @see org.opencms.file.types.I_CmsResourceType#deleteResource(CmsObject, CmsSecurityManager, CmsResource, int) */ public void deleteResource(CmsRequestContext context, CmsResource resource, int siblingMode) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.deleteResource(dbc, resource, siblingMode); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DELETE_RESOURCE_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Deletes an entry in the published resource table.<p> * * @param context the current request context * @param resourceName The name of the resource to be deleted in the static export * @param linkType the type of resource deleted (0= non-paramter, 1=parameter) * @param linkParameter the parameters ofthe resource * * @throws CmsException if something goes wrong */ public void deleteStaticExportPublishedResource( CmsRequestContext context, String resourceName, int linkType, String linkParameter) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.deleteStaticExportPublishedResource(dbc, resourceName, linkType, linkParameter); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_DELETE_STATEXP_PUBLISHES_RESOURCE_1, resourceName), e); } finally { dbc.clear(); } } /** * Deletes a user.<p> * * @param context the current request context * @param userId the Id of the user to be deleted * * @throws CmsException if something goes wrong */ public void deleteUser(CmsRequestContext context, CmsUUID userId) throws CmsException { CmsUser user = readUser(context, userId); deleteUser(context, user); } /** * Deletes a user.<p> * * @param context the current request context * @param username the name of the user to be deleted * * @throws CmsException if something goes wrong */ public void deleteUser(CmsRequestContext context, String username) throws CmsException { CmsUser user = readUser(context, username, CmsUser.USER_TYPE_SYSTEMUSER); deleteUser(context, user); } /** * Deletes a web user.<p> * * @param context the current request context * @param userId the Id of the web user to be deleted * * @throws CmsException if something goes wrong */ public void deleteWebUser(CmsRequestContext context, CmsUUID userId) throws CmsException { CmsUser user = readUser(context, userId); deleteUser(context, user); } /** * Destroys this security manager.<p> * * @throws Throwable if something goes wrong */ public void destroy() throws Throwable { finalize(); if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().key(Messages.INIT_SECURITY_MANAGER_SHUTDOWN_1, this.getClass().getName())); } } /** * Ends a task.<p> * * @param context the current request context * @param taskid the ID of the task to end * * @throws CmsException if something goes wrong */ public void endTask(CmsRequestContext context, int taskid) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.endTask(dbc, taskid); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_END_TASK_1, new Integer(taskid)), e); } finally { dbc.clear(); } } /** * Checks the availability of a resource in the VFS, * using the <code>{@link CmsResourceFilter#DEFAULT}</code> filter.<p> * * A resource may be of type <code>{@link CmsFile}</code> or * <code>{@link CmsFolder}</code>.<p> * * The specified filter controls what kind of resources should be "found" * during the read operation. This will depend on the application. For example, * using <code>{@link CmsResourceFilter#DEFAULT}</code> will only return currently * "valid" resources, while using <code>{@link CmsResourceFilter#IGNORE_EXPIRATION}</code> * will ignore the date release / date expired information of the resource.<p> * * This method also takes into account the user permissions, so if * the given resource exists, but the current user has not the required * permissions, then this method will return <code>false</code>.<p> * * @param context the current request context * @param resourcePath the name of the resource to read (full path) * @param filter the resource filter to use while reading * * @return <code>true</code> if the resource is available * * @see CmsObject#existsResource(String, CmsResourceFilter) * @see CmsObject#existsResource(String) */ public boolean existsResource(CmsRequestContext context, String resourcePath, CmsResourceFilter filter) { boolean result = false; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { readResource(dbc, resourcePath, filter); result = true; } catch (Exception e) { result = false; } finally { dbc.clear(); } return result; } /** * Forwards a task to a new user.<p> * * @param context the current request context * @param taskid the Id of the task to forward * @param newRoleName the new group name for the task * @param newUserName the new user who gets the task. if it is empty, a new agent will automatic selected * * @throws CmsException if something goes wrong */ public void forwardTask(CmsRequestContext context, int taskid, String newRoleName, String newUserName) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.forwardTask(dbc, taskid, newRoleName, newUserName); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_FORWARD_TASK_3, new Integer(taskid), newUserName, newRoleName), e); } finally { dbc.clear(); } } /** * Returns the list of access control entries of a resource given its name.<p> * * @param context the current request context * @param resource the resource to read the access control entries for * @param getInherited true if the result should include all access control entries inherited by parent folders * * @return a list of <code>{@link CmsAccessControlEntry}</code> objects defining all permissions for the given resource * * @throws CmsException if something goes wrong */ public List getAccessControlEntries(CmsRequestContext context, CmsResource resource, boolean getInherited) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.getAccessControlEntries(dbc, resource, getInherited); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_ACL_ENTRIES_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Returns the access control list (summarized access control entries) of a given resource.<p> * * If <code>inheritedOnly</code> is set, only inherited access control entries are returned.<p> * * @param context the current request context * @param resource the resource * @param inheritedOnly skip non-inherited entries if set * * @return the access control list of the resource * * @throws CmsException if something goes wrong */ public CmsAccessControlList getAccessControlList( CmsRequestContext context, CmsResource resource, boolean inheritedOnly) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsAccessControlList result = null; try { result = m_driverManager.getAccessControlList(dbc, resource, inheritedOnly); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_ACL_ENTRIES_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Returns all projects which are owned by the current user or which are * accessible for the group of the user.<p> * * @param context the current request context * * @return a list of objects of type <code>{@link CmsProject}</code> * * @throws CmsException if something goes wrong */ public List getAllAccessibleProjects(CmsRequestContext context) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.getAllAccessibleProjects(dbc); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_GET_ALL_ACCESSIBLE_PROJECTS_1, dbc.currentUser().getName()), e); } finally { dbc.clear(); } return result; } /** * Returns a list with all projects from history.<p> * * @param context the current request context * * @return list of <code>{@link CmsBackupProject}</code> objects * with all projects from history. * * @throws CmsException if operation was not succesful */ public List getAllBackupProjects(CmsRequestContext context) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.getAllBackupProjects(dbc); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_GET_ALL_ACCESSIBLE_PROJECTS_1, dbc.currentUser().getName()), e); } finally { dbc.clear(); } return result; } /** * Returns all projects which are owned by the current user or which are manageable * for the group of the user.<p> * * @param context the current request context * * @return a list of objects of type <code>{@link CmsProject}</code> * * @throws CmsException if operation was not succesful */ public List getAllManageableProjects(CmsRequestContext context) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.getAllManageableProjects(dbc); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_GET_ALL_MANAGEABLE_PROJECTS_1, dbc.currentUser().getName()), e); } finally { dbc.clear(); } return result; } /** * Returns the next version id for the published backup resources.<p> * * @param context the current request context * * @return the new version id */ public int getBackupTagId(CmsRequestContext context) { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); int result = 0; try { result = m_driverManager.getBackupTagId(dbc); } finally { dbc.clear(); } return result; } /** * Returns all child groups of a group.<p> * * @param context the current request context * @param groupname the name of the group * * @return a list of all child <code>{@link CmsGroup}</code> objects or <code>null</code> * * @throws CmsException if operation was not succesful */ public List getChild(CmsRequestContext context, String groupname) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { checkRole(dbc, CmsRole.SYSTEM_USER); result = m_driverManager.getChild(dbc, groupname); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_CHILD_GROUPS_1, groupname), e); } finally { dbc.clear(); } return result; } /** * Returns all child groups of a group.<p> * * This method also returns all sub-child groups of the current group.<p> * * @param context the current request context * @param groupname the name of the group * * @return a list of all child <code>{@link CmsGroup}</code> objects or <code>null</code> * * @throws CmsException if operation was not succesful */ public List getChilds(CmsRequestContext context, String groupname) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { checkRole(dbc, CmsRole.SYSTEM_USER); result = m_driverManager.getChilds(dbc, groupname); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_CHILD_GROUPS_TRANSITIVE_1, groupname), e); } finally { dbc.clear(); } return result; } /** * Gets the configurations of the OpenCms properties file.<p> * * @return the configurations of the properties file */ public Map getConfigurations() { return m_driverManager.getConfigurations(); } /** * Returns the list of groups to which the user directly belongs to.<p> * * @param context the current request context * @param username The name of the user * * @return a list of <code>{@link CmsGroup}</code> objects * * @throws CmsException if operation was not succesful */ public List getDirectGroupsOfUser(CmsRequestContext context, String username) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.getDirectGroupsOfUser(dbc, username); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_DIRECT_GROUP_OF_USER_1, username), e); } finally { dbc.clear(); } return result; } /** * Returns all available groups.<p> * * @param context the current request context * * @return a list of all available <code>{@link CmsGroup}</code> objects * * @throws CmsException if operation was not succesful */ public List getGroups(CmsRequestContext context) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { checkRole(dbc, CmsRole.SYSTEM_USER); result = m_driverManager.getGroups(dbc); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_GROUPS_0), e); } finally { dbc.clear(); } return result; } /** * Returns the groups of a user.<p> * * @param context the current request context * @param username the name of the user * * @return a list of <code>{@link CmsGroup}</code> objects * * @throws CmsException if operation was not succesful */ public List getGroupsOfUser(CmsRequestContext context, String username) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.getGroupsOfUser(dbc, username); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_GROUPS_OF_USER_1, username), e); } finally { dbc.clear(); } return result; } /** * Returns the groups of a Cms user filtered by the specified IP address.<p> * * @param context the current request context * @param username the name of the user * @param remoteAddress the IP address to filter the groups in the result list * * @return a list of <code>{@link CmsGroup}</code> objects filtered by the specified IP address * * @throws CmsException if operation was not succesful */ public List getGroupsOfUser(CmsRequestContext context, String username, String remoteAddress) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.getGroupsOfUser(dbc, username, remoteAddress); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_GROUPS_OF_USER_2, username, remoteAddress), e); } finally { dbc.clear(); } return result; } /** * Returns the lock state of a resource.<p> * * @param context the current request context * @param resource the resource to return the lock state for * @return the lock state of the resource * @throws CmsException if something goes wrong */ public CmsLock getLock(CmsRequestContext context, CmsResource resource) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsLock result = null; try { result = m_driverManager.getLock(dbc, resource); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_LOCK_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Returns the parent group of a group.<p> * * @param context the current request context * @param groupname the name of the group * * @return group the parent group or <code>null</code> * * @throws CmsException if operation was not succesful */ public CmsGroup getParent(CmsRequestContext context, String groupname) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsGroup result = null; try { result = m_driverManager.getParent(dbc, groupname); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_PARENT_GROUP_1, groupname), e); } finally { dbc.clear(); } return result; } /** * Returns the set of permissions of the current user for a given resource.<p> * * @param context the current request context * @param resource the resource * @param user the user * * @return bitset with allowed permissions * * @throws CmsException if something goes wrong */ public CmsPermissionSetCustom getPermissions(CmsRequestContext context, CmsResource resource, CmsUser user) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsPermissionSetCustom result = null; try { result = m_driverManager.getPermissions(dbc, resource, user); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_GET_PERMISSIONS_2, user.getName(), context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Returns a Cms publish list object containing the Cms resources that actually get published.<p> * * <ul> * <li> * <b>Case 1 (publish project)</b>: all new/changed/deleted Cms file resources in the current (offline) * project are inspected whether they would get published or not. * </li> * <li> * <b>Case 2 (direct publish a resource)</b>: a specified Cms file resource and optionally it's siblings * are inspected whether they get published. * </li> * </ul> * * All <code>{@link CmsResource}</code> objects inside the publish ist are equipped with their full * resource name including the site root.<p> * * Please refer to the source code of this method for the rules on how to decide whether a * new/changed/deleted <code>{@link CmsResource}</code> object can be published or not.<p> * * @param context the current request context * @param directPublishResource a <code>{@link CmsResource}</code> to be published directly (in case 2), * or <code>null</code> (in case 1). * @param publishSiblings <code>true</code>, if all eventual siblings of the direct published resource * should also get published (in case 2). * * @return a publish list with all new/changed/deleted files from the current (offline) project that will be published actually * * @throws CmsException if something goes wrong * * @see org.opencms.db.CmsPublishList */ public synchronized CmsPublishList getPublishList( CmsRequestContext context, CmsResource directPublishResource, boolean publishSiblings) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsPublishList result = null; try { result = m_driverManager.getPublishList(dbc, directPublishResource, publishSiblings); } catch (Exception e) { if (directPublishResource != null) { dbc.report(null, Messages.get().container( Messages.ERR_GET_PUBLISH_LIST_DIRECT_1, context.removeSiteRoot(directPublishResource.getRootPath())), e); } else { dbc.report(null, Messages.get().container( Messages.ERR_GET_PUBLISH_LIST_PROJECT_1, context.currentProject().getName()), e); } } finally { dbc.clear(); } return result; } /** * Returns a list with all sub resources of the given parent folder (and all of it's subfolders) * that have been modified in the given time range.<p> * * The result list is descending sorted (newest resource first).<p> * * @param context the current request context * @param folder the folder to get the subresources from * @param starttime the begin of the time range * @param endtime the end of the time range * * @return a list with all <code>{@link CmsResource}</code> objects * that have been modified in the given time range. * * @throws CmsException if operation was not succesful */ public List getResourcesInTimeRange(CmsRequestContext context, String folder, long starttime, long endtime) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.getResourcesInTimeRange(dbc, folder, starttime, endtime); } catch (Exception e) { // todo: possibly the folder arg is a root path, then use // context.removeSiteRoot(folder) before output. dbc.report(null, Messages.get().container( Messages.ERR_GET_RESOURCES_IN_TIME_RANGE_3, folder, new Date(starttime), new Date(endtime)), e); } finally { dbc.clear(); } return result; } /** * Returns an instance of the common sql manager.<p> * * @return an instance of the common sql manager */ public CmsSqlManager getSqlManager() { return m_driverManager.getSqlManager(); } /** * Returns the value of the given parameter for the given task.<p> * * @param context the current request context * @param taskId the Id of the task * @param parName name of the parameter * * @return task parameter value * * @throws CmsException if something goes wrong */ public String getTaskPar(CmsRequestContext context, int taskId, String parName) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); String result = null; try { result = m_driverManager.getTaskPar(dbc, taskId, parName); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_TASK_PARAM_2, parName, new Integer(taskId)), e); } finally { dbc.clear(); } return result; } /** * Get the template task id for a given taskname.<p> * * @param context the current request context * @param taskName name of the task * * @return id from the task template * * @throws CmsException if something goes wrong */ public int getTaskType(CmsRequestContext context, String taskName) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); int result = 0; try { result = m_driverManager.getTaskType(dbc, taskName); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_TASK_TYPE_1, taskName), e); } finally { dbc.clear(); } return result; } /** * Returns all available users.<p> * * @param context the current request context * * @return a list of all available <code>{@link CmsUser}</code> objects * * @throws CmsException if operation was not succesful */ public List getUsers(CmsRequestContext context) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { checkRole(dbc, CmsRole.SYSTEM_USER); result = m_driverManager.getUsers(dbc); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_USERS_0), e); } finally { dbc.clear(); } return result; } /** * Returns all users from a given type.<p> * * @param context the current request context * @param type the type of the users * * @return a list of all <code>{@link CmsUser}</code> objects of the given type * * @throws CmsException if operation was not succesful */ public List getUsers(CmsRequestContext context, int type) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { checkRole(dbc, CmsRole.SYSTEM_USER); result = m_driverManager.getUsers(dbc, type); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_USERS_OF_TYPE_1, new Integer(type)), e); } finally { dbc.clear(); } return result; } /** * Returns a list of users in a group.<p> * * @param context the current request context * @param groupname the name of the group to list users from * * @return all <code>{@link CmsUser}</code> objects in the group * * @throws CmsException if operation was not succesful */ public List getUsersOfGroup(CmsRequestContext context, String groupname) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { checkRole(dbc, CmsRole.SYSTEM_USER); result = m_driverManager.getUsersOfGroup(dbc, groupname); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_USERS_OF_GROUP_1, groupname), e); } finally { dbc.clear(); } return result; } /** * Checks if the current user has management access to the given project.<p> * * @param dbc the current database context * @param project the project to check * * @return <code>true</code>, if the user has management access to the project */ public boolean hasManagerOfProjectRole(CmsDbContext dbc, CmsProject project) { if (dbc.currentProject().isOnlineProject()) { // no user is the project manager of the "Online" project return false; } if (dbc.currentUser().getId().equals(project.getOwnerId())) { // user is the owner of the current project return true; } if (hasRole(dbc, CmsRole.PROJECT_MANAGER)) { // user is admin return true; } // get all groups of the user List groups; try { groups = m_driverManager.getGroupsOfUser(dbc, dbc.currentUser().getName()); } catch (CmsException e) { // any exception: result is false return false; } for (int i = 0; i < groups.size(); i++) { // check if the user is a member in the current projects manager group if (((CmsGroup)groups.get(i)).getId().equals(project.getManagerGroupId())) { // this group is manager of the project return true; } } // the user is not manager of the current project return false; } /** * Performs a non-blocking permission check on a resource.<p> * * This test will not throw an exception in case the required permissions are not * available for the requested operation. Instead, it will return one of the * following values:<ul> * <li><code>{@link #PERM_ALLOWED}</code></li> * <li><code>{@link #PERM_FILTERED}</code></li> * <li><code>{@link #PERM_DENIED}</code></li></ul><p> * * @param context the current request context * @param resource the resource on which permissions are required * @param requiredPermissions the set of permissions required for the operation * @param checkLock if true, a lock for the current user is required for * all write operations, if false it's ok to write as long as the resource * is not locked by another user * @param filter the resource filter to use * * @return <code>{@link #PERM_ALLOWED}</code> if the user has sufficient permissions on the resource * for the requested operation * * @throws CmsException in case of i/o errors (NOT because of insufficient permissions) * * @see #hasPermissions(CmsDbContext, CmsResource, CmsPermissionSet, boolean, CmsResourceFilter) */ public int hasPermissions( CmsRequestContext context, CmsResource resource, CmsPermissionSet requiredPermissions, boolean checkLock, CmsResourceFilter filter) throws CmsException { int result = 0; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = hasPermissions(dbc, resource, requiredPermissions, checkLock, filter); } finally { dbc.clear(); } return result; } /** * Checks if the given resource or the current project can be published by the current user * using his current OpenCms context.<p> * * If the resource parameter is <code>null</code>, then the current project is checked, * otherwise the resource is checked for direct publish permissions.<p> * * @param context the current request context * @param directPublishResource the direct publish resource (optional, if null only the current project is checked) * * @return <code>true</code>, if the current user can direct publish the given resource in his current context */ public boolean hasPublishPermissions(CmsRequestContext context, CmsResource directPublishResource) { try { checkPublishPermissions(context, directPublishResource); } catch (CmsException e) { return false; } return true; } /** * Checks if the user of the current database context is a member of the given role.<p> * * @param dbc the current OpenCms users database context * @param role the role to check * * @return <code>true</code> if the user of the current database context is at a member of at last * one of the roles in the given role set */ public boolean hasRole(CmsDbContext dbc, CmsRole role) { return hasRole(dbc, dbc.currentUser(), role); } /** * Checks if the given user is a member of the given role.<p> * * @param dbc the current OpenCms users database context * @param user the user to check the role for * @param role the role to check * * @return <code>true</code> if the user of the current database context is at a member of at last * one of the roles in the given role set */ public boolean hasRole(CmsDbContext dbc, CmsUser user, CmsRole role) { // read all groups of the current user List groups; try { groups = m_driverManager.getGroupsOfUser(dbc, user.getName(), dbc.getRequestContext().getRemoteAddress()); } catch (CmsException e) { // any exception: return false return false; } return role.hasRole(groups); } /** * Checks if the user of the given request context * is a member of at last one of the roles in the given role set.<p> * * @param context the current request context * @param role the role to check * * @return <code>true</code> if the user of given request context is at a member of at last * one of the roles in the given role set */ public boolean hasRole(CmsRequestContext context, CmsRole role) { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); boolean result; try { result = hasRole(dbc, role); } finally { dbc.clear(); } return result; } /** * Writes a list of access control entries as new access control entries of a given resource.<p> * * Already existing access control entries of this resource are removed before.<p> * * Access is granted, if:<p> * <ul> * <li>the current user has control permission on the resource</li> * </ul><p> * * @param context the current request context * @param resource the resource * @param acEntries a list of <code>{@link CmsAccessControlEntry}</code> objects * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the required permissions are not satisfied */ public void importAccessControlEntries(CmsRequestContext context, CmsResource resource, List acEntries) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_CONTROL, true, CmsResourceFilter.ALL); m_driverManager.importAccessControlEntries(dbc, resource, acEntries); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_IMPORT_ACL_ENTRIES_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Creates a new resource with the provided content and properties.<p> * * The <code>content</code> parameter may be null if the resource id already exists. * If so, the created resource will be made a sibling of the existing resource, * the existing content will remain unchanged. * This is used during file import for import of siblings as the * <code>manifest.xml</code> only contains one binary copy per file. * If the resource id exists but the <code>content</code> is not null, * the created resource will be made a sibling of the existing resource, * and both will share the new content.<p> * * Note: the id used to identify the content record (pk of the record) is generated * on each call of this method (with valid content) ! * * @param context the current request context * @param resourcePath the name of the resource to create (full path) * @param resource the new resource to create * @param content the content for the new resource * @param properties the properties for the new resource * @param importCase if true, signals that this operation is done while importing resource, causing different lock behaviour and potential "lost and found" usage * @return the created resource * @throws CmsException if something goes wrong */ public CmsResource importResource( CmsRequestContext context, String resourcePath, CmsResource resource, byte[] content, List properties, boolean importCase) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsResource newResource = null; try { checkOfflineProject(dbc); newResource = m_driverManager.createResource(dbc, resourcePath, resource, content, properties, importCase); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_IMPORT_RESOURCE_2, context.getSitePath(resource), resourcePath), e); } finally { dbc.clear(); } return newResource; } /** * Creates a new user by import.<p> * * @param context the current request context * @param id the id of the user * @param name the new name for the user * @param password the new password for the user * @param description the description for the user * @param firstname the firstname of the user * @param lastname the lastname of the user * @param email the email of the user * @param address the address of the user * @param flags the flags for a user (for example <code>{@link I_CmsConstants#C_FLAG_ENABLED}</code>) * @param type the type of the user * @param additionalInfos the additional user infos * * @return the imported user * * @throws CmsException if something goes wrong * @throws CmsRoleViolationException if the role {@link CmsRole#USER_MANAGER} is not owned by the current user. */ public CmsUser importUser( CmsRequestContext context, String id, String name, String password, String description, String firstname, String lastname, String email, String address, int flags, int type, Map additionalInfos) throws CmsException, CmsRoleViolationException { CmsUser newUser = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.USER_MANAGER); newUser = m_driverManager.importUser( dbc, id, name, password, description, firstname, lastname, email, address, flags, type, additionalInfos); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_IMPORT_USER_9, new Object[] { id, name, description, firstname, lastname, email, address, new Integer(flags), new Integer(type), additionalInfos}), e); } finally { dbc.clear(); } return newUser; } /** * Initializes this security manager with a given runtime info factory.<p> * * @param configurationManager the configurationManager * @param dbContextFactory the initialized OpenCms runtime info factory * * @throws CmsInitException if the initialization fails */ public void init(CmsConfigurationManager configurationManager, I_CmsDbContextFactory dbContextFactory) throws CmsInitException { if (dbContextFactory == null) { throw new CmsInitException(org.opencms.main.Messages.get().container( org.opencms.main.Messages.ERR_CRITICAL_NO_DB_CONTEXT_0)); } m_dbContextFactory = dbContextFactory; CmsSystemConfiguration systemConfiguation = (CmsSystemConfiguration)configurationManager.getConfiguration(CmsSystemConfiguration.class); CmsCacheSettings settings = systemConfiguation.getCacheSettings(); String className = settings.getCacheKeyGenerator(); try { // initialize the key generator m_keyGenerator = (I_CmsCacheKey)Class.forName(className).newInstance(); } catch (Exception e) { throw new CmsInitException(org.opencms.main.Messages.get().container( org.opencms.main.Messages.ERR_CRITICAL_CLASS_CREATION_1, className)); } LRUMap hashMap = new LRUMap(settings.getPermissionCacheSize()); m_permissionCache = Collections.synchronizedMap(hashMap); if (OpenCms.getMemoryMonitor().enabled()) { OpenCms.getMemoryMonitor().register(this.getClass().getName() + ".m_permissionCache", hashMap); } m_driverManager = CmsDriverManager.newInstance(configurationManager, this, dbContextFactory); if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().key(Messages.INIT_SECURITY_MANAGER_INIT_0)); } } /** * Checks if the specified resource is inside the current project.<p> * * The project "view" is determined by a set of path prefixes. * If the resource starts with any one of this prefixes, it is considered to * be "inside" the project.<p> * * @param context the current request context * @param resourcename the specified resource name (full path) * * @return <code>true</code>, if the specified resource is inside the current project */ public boolean isInsideCurrentProject(CmsRequestContext context, String resourcename) { boolean result = false; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.isInsideCurrentProject(dbc, resourcename); } finally { dbc.clear(); } return result; } /** * Checks if the current user has management access to the current project.<p> * * @param context the current request context * * @return <code>true</code>, if the user has management access to the current project */ public boolean isManagerOfProject(CmsRequestContext context) { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); return hasManagerOfProjectRole(dbc, context.currentProject()); } /** * Locks a resource.<p> * * The <code>mode</code> parameter controls what kind of lock is used.<br> * Possible values for this parameter are: <br> * <ul> * <li><code>{@link org.opencms.lock.CmsLock#C_MODE_COMMON}</code></li> * <li><code>{@link org.opencms.lock.CmsLock#C_MODE_TEMP}</code></li> * </ul><p> * * @param context the current request context * @param resource the resource to lock * @param mode flag indicating the mode for the lock * * @throws CmsException if something goes wrong * * @see CmsObject#lockResource(String, int) * @see org.opencms.file.types.I_CmsResourceType#lockResource(CmsObject, CmsSecurityManager, CmsResource, int) */ public void lockResource(CmsRequestContext context, CmsResource resource, int mode) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL); m_driverManager.lockResource(dbc, resource, mode); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_LOCK_RESOURCE_2, context.getSitePath(resource), (mode == CmsLock.C_MODE_COMMON) ? "CmsLock.C_MODE_COMMON" : "CmsLock.C_MODE_TEMP"), e); } finally { dbc.clear(); } } /** * Attempts to authenticate a user into OpenCms with the given password.<p> * * @param context the current request context * @param username the name of the user to be logged in * @param password the password of the user * @param remoteAddress the ip address of the request * @param userType the user type to log in (System user or Web user) * * @return the logged in user * * @throws CmsException if the login was not succesful */ public CmsUser loginUser( CmsRequestContext context, String username, String password, String remoteAddress, int userType) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.loginUser(dbc, username, password, remoteAddress, userType); } finally { dbc.clear(); } return result; } /** * Lookup and read the user or group with the given UUID.<p> * * @param context the current request context * @param principalId the UUID of the principal to lookup * * @return the principal (group or user) if found, otherwise <code>null</code> */ public I_CmsPrincipal lookupPrincipal(CmsRequestContext context, CmsUUID principalId) { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); I_CmsPrincipal result = null; try { result = m_driverManager.lookupPrincipal(dbc, principalId); } finally { dbc.clear(); } return result; } /** * Lookup and read the user or group with the given name.<p> * * @param context the current request context * @param principalName the name of the principal to lookup * * @return the principal (group or user) if found, otherwise <code>null</code> */ public I_CmsPrincipal lookupPrincipal(CmsRequestContext context, String principalName) { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); I_CmsPrincipal result = null; try { result = m_driverManager.lookupPrincipal(dbc, principalName); } finally { dbc.clear(); } return result; } /** * Moves a resource to the "lost and found" folder.<p> * * The method can also be used to check get the name of a resource * in the "lost and found" folder only without actually moving the * the resource. To do this, the <code>returnNameOnly</code> flag * must be set to <code>true</code>.<p> * * In general, it is the same name as the given resource has, the only exception is * if a resource in the "lost and found" folder with the same name already exists. * In such case, a counter is added to the resource name.<p> * * @param context the current request context * @param resourcename the name of the resource to apply this operation to * @param returnNameOnly if <code>true</code>, only the name of the resource in the "lost and found" * folder is returned, the move operation is not really performed * * @return the name of the resource inside the "lost and found" folder * * @throws CmsException if something goes wrong * * @see CmsObject#moveToLostAndFound(String) * @see CmsObject#getLostAndFoundName(String) */ public String moveToLostAndFound(CmsRequestContext context, String resourcename, boolean returnNameOnly) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); String result = null; try { result = m_driverManager.moveToLostAndFound(dbc, resourcename, returnNameOnly); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_MOVE_TO_LOST_AND_FOUND_1, resourcename), e); } finally { dbc.clear(); } return result; } /** * Publishes the resources of a specified publish list.<p> * * @param cms the current request context * @param publishList a publish list * @param report an instance of <code>{@link I_CmsReport}</code> to print messages * * @return the publish history id of the published project * * @throws CmsException if something goes wrong * * @see #getPublishList(CmsRequestContext, CmsResource, boolean) */ public synchronized CmsUUID publishProject(CmsObject cms, CmsPublishList publishList, I_CmsReport report) throws CmsException { CmsRequestContext context = cms.getRequestContext(); // check if the current user has the required publish permissions if (publishList.isDirectPublish()) { // pass the direct publish resource to the permission test CmsResource directPublishResource = publishList.getDirectPublishResource(); checkPublishPermissions(context, directPublishResource); } else { // pass null, will only check the current project checkPublishPermissions(context, null); } CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.publishProject(cms, dbc, publishList, report); } finally { dbc.clear(); } return publishList.getPublishHistoryId(); } /** * Reactivates a task.<p> * * Setting its state to <code>{@link org.opencms.workflow.CmsTaskService#TASK_STATE_STARTED}</code> and * the percentage to <b>zero</b>.<p> * * @param context the current request context * @param taskId the id of the task to reactivate * * @throws CmsException if something goes wrong */ public void reactivateTask(CmsRequestContext context, int taskId) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.reactivateTask(dbc, taskId); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_REACTIVATE_TASK_1, new Integer(taskId)), e); } finally { dbc.clear(); } } /** * Reads the agent of a task.<p> * * @param context the current request context * @param task the task to read the agent from * * @return the owner of a task * * @throws CmsException if something goes wrong */ public CmsUser readAgent(CmsRequestContext context, CmsTask task) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.readAgent(dbc, task); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_TASK_OWNER_2, task.getName(), new Integer(task.getId())), e); } finally { dbc.clear(); } return result; } /** * Reads all file headers of a file.<br> * * This method returns a list with the history of all file headers, i.e. * the file headers of a file, independent of the project they were attached to.<br> * * The reading excludes the file content.<p> * * @param context the current request context * @param resource the resource to be read * * @return a list of file headers, as <code>{@link CmsBackupResource}</code> objects, read from the Cms * * @throws CmsException if something goes wrong */ public List readAllBackupFileHeaders(CmsRequestContext context, CmsResource resource) throws CmsException { List result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.readAllBackupFileHeaders(dbc, resource); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_ALL_BKP_FILE_HEADERS_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Reads all propertydefinitions for the given mapping type.<p> * * @param context the current request context * @param mappingtype the mapping type to read the propertydefinitions for * * @return a list with the <code>{@link CmsPropertyDefinition}</code> objects (may be empty) * * @throws CmsException if something goes wrong */ public List readAllPropertyDefinitions(CmsRequestContext context, int mappingtype) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readAllPropertyDefinitions(dbc, mappingtype); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_ALL_PROPDEF_MAPPING_TYPE_1, (mappingtype == CmsProperty.C_RESOURCE_RECORD_MAPPING) ? "CmsProperty.C_RESOURCE_RECORD_MAPPING" : "CmsProperty.C_STRUCTURE_RECORD_MAPPING"), e); } finally { dbc.clear(); } return result; } /** * Returns the first ancestor folder matching the filter criteria.<p> * * If no folder matching the filter criteria is found, null is returned.<p> * * @param context the context of the current request * @param resource the resource to start * @param filter the resource filter to match while reading the ancestors * * @return the first ancestor folder matching the filter criteria or null if no folder was found * * @throws CmsException if something goes wrong */ public CmsFolder readAncestor(CmsRequestContext context, CmsResource resource, CmsResourceFilter filter) throws CmsException { // get the full folder path of the resource to start from String path = CmsResource.getFolderPath(resource.getRootPath()); do { // check if the current folder matches the given filter if (existsResource(context, path, filter)) { // folder matches, return it return readFolder(context, path, filter); } else { // folder does not match filter criteria, go up one folder path = CmsResource.getParentFolder(path); } if (CmsStringUtil.isEmpty(path) || !path.startsWith(context.getSiteRoot())) { // site root or root folder reached and no matching folder found return null; } } while (true); } /** * Returns a file from the history.<br> * * The reading includes the file content.<p> * * @param context the current request context * @param tagId the id of the tag of the file * @param resource the resource to be read * * @return the file read * * @throws CmsException if operation was not succesful */ public CmsBackupResource readBackupFile(CmsRequestContext context, int tagId, CmsResource resource) throws CmsException { CmsBackupResource result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.readBackupFile(dbc, tagId, resource); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_BKP_FILE_2, context.getSitePath(resource), new Integer(tagId)), e); } finally { dbc.clear(); } return result; } /** * Returns a backup project.<p> * * @param context the current request context * @param tagId the tagId of the project * * @return the requested backup project * * @throws CmsException if something goes wrong */ public CmsBackupProject readBackupProject(CmsRequestContext context, int tagId) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsBackupProject result = null; try { result = m_driverManager.readBackupProject(dbc, tagId); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_BKP_PROJECT_2, new Integer(tagId), dbc.currentProject().getName()), e); } finally { dbc.clear(); } return result; } /** * Returns the child resources of a resource, that is the resources * contained in a folder.<p> * * With the parameters <code>getFolders</code> and <code>getFiles</code> * you can control what type of resources you want in the result list: * files, folders, or both.<p> * * This method is mainly used by the workplace explorer.<p> * * @param context the current request context * @param resource the resource to return the child resources for * @param filter the resource filter to use * @param getFolders if true the child folders are included in the result * @param getFiles if true the child files are included in the result * * @return a list of all child resources * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (read is required). * */ public List readChildResources( CmsRequestContext context, CmsResource resource, CmsResourceFilter filter, boolean getFolders, boolean getFiles) throws CmsException, CmsSecurityException { List result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { // check the access permissions checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_READ, true, CmsResourceFilter.ALL); result = m_driverManager.readChildResources(dbc, resource, filter, getFolders, getFiles); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_CHILD_RESOURCES_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Reads a file resource (including it's binary content) from the VFS, * using the specified resource filter.<p> * * In case you do not need the file content, * use <code>{@link #readResource(CmsRequestContext, String, CmsResourceFilter)}</code> instead.<p> * * The specified filter controls what kind of resources should be "found" * during the read operation. This will depend on the application. For example, * using <code>{@link CmsResourceFilter#DEFAULT}</code> will only return currently * "valid" resources, while using <code>{@link CmsResourceFilter#IGNORE_EXPIRATION}</code> * will ignore the date release / date expired information of the resource.<p> * * @param context the current request context * @param resource the resource to be read * @param filter the filter object * * @return the file read from the VFS * * @throws CmsException if something goes wrong */ public CmsFile readFile(CmsRequestContext context, CmsResource resource, CmsResourceFilter filter) throws CmsException { CmsFile result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.readFile(dbc, resource, filter); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_FILE_2, context.getSitePath(resource), String.valueOf(filter)), e); } finally { dbc.clear(); } return result; } /** * Reads a folder resource from the VFS, * using the specified resource filter.<p> * * The specified filter controls what kind of resources should be "found" * during the read operation. This will depend on the application. For example, * using <code>{@link CmsResourceFilter#DEFAULT}</code> will only return currently * "valid" resources, while using <code>{@link CmsResourceFilter#IGNORE_EXPIRATION}</code> * will ignore the date release / date expired information of the resource.<p> * * @param context the current request context * @param resourcename the name of the folder to read (full path) * @param filter the resource filter to use while reading * * @return the folder that was read * * @throws CmsException if something goes wrong */ public CmsFolder readFolder(CmsRequestContext context, String resourcename, CmsResourceFilter filter) throws CmsException { CmsFolder result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = readFolder(dbc, resourcename, filter); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_FOLDER_2, resourcename, String.valueOf(filter)), e); } finally { dbc.clear(); } return result; } /** * Reads all given tasks from a user for a project.<p> * * The <code>tasktype</code> parameter will filter the tasks. * The possible values for this parameter are:<br> * <ul> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_ALL}</code>: Reads all tasks</il> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_OPEN}</code>: Reads all open tasks</il> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_DONE}</code>: Reads all finished tasks</il> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_NEW}</code>: Reads all new tasks</il> * </ul> * * @param context the current request context * @param projectId the id of the project in which the tasks are defined * @param ownerName the owner of the task * @param taskType the type of task you want to read * @param orderBy specifies how to order the tasks * @param sort sorting of the tasks * * @return a list of given <code>{@link CmsTask}</code> objects for a user for a project * * @throws CmsException if operation was not successful */ public List readGivenTasks( CmsRequestContext context, int projectId, String ownerName, int taskType, String orderBy, String sort) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readGivenTasks(dbc, projectId, ownerName, taskType, orderBy, sort); } catch (Exception e) { dbc.report(null, Messages.get().container( org.opencms.workflow.Messages.toTaskTypeString(taskType, context), new Integer(projectId), ownerName), e); } finally { dbc.clear(); } return result; } /** * Reads the group of a project.<p> * * @param context the current request context * @param project the project to read from * * @return the group of a resource */ public CmsGroup readGroup(CmsRequestContext context, CmsProject project) { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsGroup result = null; try { result = m_driverManager.readGroup(dbc, project); } finally { dbc.clear(); } return result; } /** * Reads the group (role) of a task from the OpenCms.<p> * * @param context the current request context * @param task the task to read from * * @return the group of a resource * * @throws CmsException if operation was not succesful */ public CmsGroup readGroup(CmsRequestContext context, CmsTask task) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsGroup result = null; try { result = m_driverManager.readGroup(dbc, task); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_GROUP_TASK_1, task.getName()), e); } finally { dbc.clear(); } return result; } /** * Reads a group based on its id.<p> * * @param context the current request context * @param groupId the id of the group that is to be read * * @return the requested group * * @throws CmsException if operation was not succesful */ public CmsGroup readGroup(CmsRequestContext context, CmsUUID groupId) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsGroup result = null; try { result = m_driverManager.readGroup(dbc, groupId); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_GROUP_FOR_ID_1, groupId.toString()), e); } finally { dbc.clear(); } return result; } /** * Reads a group based on its name.<p> * * @param context the current request context * @param groupname the name of the group that is to be read * * @return the requested group * * @throws CmsException if operation was not succesful */ public CmsGroup readGroup(CmsRequestContext context, String groupname) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsGroup result = null; try { result = m_driverManager.readGroup(dbc, groupname); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_GROUP_FOR_NAME_1, groupname), e); } finally { dbc.clear(); } return result; } /** * Reads the manager group of a project.<p> * * @param context the current request context * @param project the project to read from * * @return the group of a resource */ public CmsGroup readManagerGroup(CmsRequestContext context, CmsProject project) { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsGroup result = null; try { result = m_driverManager.readManagerGroup(dbc, project); } finally { dbc.clear(); } return result; } /** * Reads the original agent of a task.<p> * * @param context the current request context * @param task the task to read the original agent from * * @return the owner of a task * * @throws CmsException if something goes wrong */ public CmsUser readOriginalAgent(CmsRequestContext context, CmsTask task) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.readOriginalAgent(dbc, task); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_ORIGINAL_TASK_OWNER_2, task.getName(), new Integer(task.getId())), e); } finally { dbc.clear(); } return result; } /** * Reads the owner of a project from the OpenCms.<p> * * @param context the current request context * @param project the project to get the owner from * * @return the owner of a resource * * @throws CmsException if something goes wrong */ public CmsUser readOwner(CmsRequestContext context, CmsProject project) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.readOwner(dbc, project); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_OWNER_FOR_PROJECT_2, project.getName(), new Integer(project.getId())), e); } finally { dbc.clear(); } return result; } /** * Reads the owner (initiator) of a task.<p> * * @param context the current request context * @param task the task to read the owner from * * @return the owner of a task * * @throws CmsException if something goes wrong */ public CmsUser readOwner(CmsRequestContext context, CmsTask task) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.readOwner(dbc, task); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_OWNER_FOR_TASK_2, task.getName(), new Integer(task.getId())), e); } finally { dbc.clear(); } return result; } /** * Reads the owner of a tasklog.<p> * * @param context the current request context * @param log the tasklog * * @return the owner of a resource * * @throws CmsException if something goes wrong */ public CmsUser readOwner(CmsRequestContext context, CmsTaskLog log) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.readOwner(dbc, log); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_OWNER_FOR_TASKLOG_1, new Integer(log.getId())), e); } finally { dbc.clear(); } return result; } /** * Builds a list of resources for a given path.<p> * * @param context the current request context * @param projectId the project to lookup the resource * @param path the requested path * @param filter a filter object (only "includeDeleted" information is used!) * * @return list of <code>{@link CmsResource}</code>s * * @throws CmsException if something goes wrong */ public List readPath(CmsRequestContext context, int projectId, String path, CmsResourceFilter filter) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readPath(dbc, projectId, path, filter); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_PATH_2, new Integer(projectId), path), e); } finally { dbc.clear(); } return result; } /** * Reads a project of a given task.<p> * * @param context the current request context * @param task the task to read the project of * * @return the project of the task * * @throws CmsException if something goes wrong */ public CmsProject readProject(CmsRequestContext context, CmsTask task) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsProject result = null; try { result = m_driverManager.readProject(dbc, task); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_PROJECT_FOR_TASK_2, task.getName(), new Integer(task.getId())), e); } finally { dbc.clear(); } return result; } /** * Reads a project given the projects id.<p> * * @param id the id of the project * * @return the project read * * @throws CmsException if something goes wrong */ public CmsProject readProject(int id) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(); CmsProject result = null; try { result = m_driverManager.readProject(dbc, id); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_PROJECT_FOR_ID_1, new Integer(id)), e); } finally { dbc.clear(); } return result; } /** * Reads a project.<p> * * Important: Since a project name can be used multiple times, this is NOT the most efficient * way to read the project. This is only a convenience for front end developing. * Reading a project by name will return the first project with that name. * All core classes must use the id version {@link #readProject(int)} to ensure the right project is read.<p> * * @param name the name of the project * * @return the project read * * @throws CmsException if something goes wrong */ public CmsProject readProject(String name) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(); CmsProject result = null; try { result = m_driverManager.readProject(dbc, name); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_PROJECT_FOR_NAME_1, name), e); } finally { dbc.clear(); } return result; } /** * Reads all task log entries for a project. * * @param context the current request context * @param projectId the id of the project for which the tasklog will be read * * @return a list of <code>{@link CmsTaskLog}</code> objects * * @throws CmsException if something goes wrong */ public List readProjectLogs(CmsRequestContext context, int projectId) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readProjectLogs(dbc, projectId); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_TASKLOGS_FOR_PROJECT_1, new Integer(projectId)), e); } finally { dbc.clear(); } return result; } /** * Returns the list of all resource names that define the "view" of the given project.<p> * * @param context the current request context * @param project the project to get the project resources for * * @return the list of all resources, as <code>{@link String}</code> objects * that define the "view" of the given project. * * @throws CmsException if something goes wrong */ public List readProjectResources(CmsRequestContext context, CmsProject project) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readProjectResources(dbc, project); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_PROJECT_RESOURCES_2, project.getName(), new Integer(project.getId())), e); } finally { dbc.clear(); } return result; } /** * Reads all resources of a project that match a given state from the VFS.<p> * * Possible values for the <code>state</code> parameter are:<br> * <ul> * <li><code>{@link I_CmsConstants#C_STATE_CHANGED}</code>: Read all "changed" resources in the project</li> * <li><code>{@link I_CmsConstants#C_STATE_NEW}</code>: Read all "new" resources in the project</li> * <li><code>{@link I_CmsConstants#C_STATE_DELETED}</code>: Read all "deleted" resources in the project</li> * <li><code>{@link I_CmsConstants#C_STATE_KEEP}</code>: Read all resources either "changed", "new" or "deleted" in the project</li> * </ul><p> * * @param context the current request context * @param projectId the id of the project to read the file resources for * @param state the resource state to match * * @return a list of <code>{@link CmsResource}</code> objects matching the filter criteria * * @throws CmsException if something goes wrong * * @see CmsObject#readProjectView(int, int) */ public List readProjectView(CmsRequestContext context, int projectId, int state) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readProjectView(dbc, projectId, state); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_PROJECT_VIEW_2, new Integer(projectId), org.opencms.workflow.Messages.toTaskTypeString(state, context)), e); } finally { dbc.clear(); } return result; } /** * Reads a property definition.<p> * * If no property definition with the given name is found, * <code>null</code> is returned.<p> * * @param context the current request context * @param name the name of the property definition to read * * @return the property definition that was read, * or <code>null</code> if there is no property definition with the given name. * * @throws CmsException if something goes wrong */ public CmsPropertyDefinition readPropertyDefinition(CmsRequestContext context, String name) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsPropertyDefinition result = null; try { result = m_driverManager.readPropertyDefinition(dbc, name); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_PROPDEF_1, name), e); } finally { dbc.clear(); } return result; } /** * Reads a property object from a resource specified by a property name.<p> * * Returns <code>{@link CmsProperty#getNullProperty()}</code> if the property is not found.<p> * * @param context the context of the current request * @param resource the resource where the property is mapped to * @param key the property key name * @param search if <code>true</code>, the property is searched on all parent folders of the resource. * if it's not found attached directly to the resource. * * @return the required property, or <code>{@link CmsProperty#getNullProperty()}</code> if the property was not found * * @throws CmsException if something goes wrong */ public CmsProperty readPropertyObject(CmsRequestContext context, CmsResource resource, String key, boolean search) throws CmsException { CmsProperty result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.readPropertyObject(dbc, resource, key, search); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_PROP_FOR_RESOURCE_2, key, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Reads all property objects from a resource.<p> * * Returns an empty list if no properties are found.<p> * * If the <code>search</code> parameter is <code>true</code>, the properties of all * parent folders of the resource are also read. The results are merged with the * properties directly attached to the resource. While merging, a property * on a parent folder that has already been found will be ignored. * So e.g. if a resource has a property "Title" attached, and it's parent folder * has the same property attached but with a differrent value, the result list will * contain only the property with the value from the resource, not form the parent folder(s).<p> * * @param context the context of the current request * @param resource the resource where the property is mapped to * @param search <code>true</code>, if the properties should be searched on all parent folders if not found on the resource * * @return a list of <code>{@link CmsProperty}</code> objects * * @throws CmsException if something goes wrong */ public List readPropertyObjects(CmsRequestContext context, CmsResource resource, boolean search) throws CmsException { List result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.readPropertyObjects(dbc, resource, search); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_PROPS_FOR_RESOURCE_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Reads the resources that were published in a publish task for a given publish history ID.<p> * * @param context the current request context * @param publishHistoryId unique int ID to identify each publish task in the publish history * * @return a list of <code>{@link org.opencms.db.CmsPublishedResource}</code> objects * * @throws CmsException if something goes wrong */ public List readPublishedResources(CmsRequestContext context, CmsUUID publishHistoryId) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readPublishedResources(dbc, publishHistoryId); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_PUBLISHED_RESOURCES_FOR_ID_1, publishHistoryId.toString()), e); } finally { dbc.clear(); } return result; } /** * Reads a resource from the VFS, * using the specified resource filter.<p> * * A resource may be of type <code>{@link CmsFile}</code> or * <code>{@link CmsFolder}</code>. In case of * a file, the resource will not contain the binary file content. Since reading * the binary content is a cost-expensive database operation, it's recommended * to work with resources if possible, and only read the file content when absolutly * required. To "upgrade" a resource to a file, * use <code>{@link CmsFile#upgrade(CmsResource, CmsObject)}</code>.<p> * * The specified filter controls what kind of resources should be "found" * during the read operation. This will depend on the application. For example, * using <code>{@link CmsResourceFilter#DEFAULT}</code> will only return currently * "valid" resources, while using <code>{@link CmsResourceFilter#IGNORE_EXPIRATION}</code> * will ignore the date release / date expired information of the resource.<p> * * @param context the current request context * @param resourcePath the name of the resource to read (full path) * @param filter the resource filter to use while reading * * @return the resource that was read * * @throws CmsException if the resource could not be read for any reason * * @see CmsObject#readResource(String, CmsResourceFilter) * @see CmsObject#readResource(String) * @see CmsFile#upgrade(CmsResource, CmsObject) */ public CmsResource readResource(CmsRequestContext context, String resourcePath, CmsResourceFilter filter) throws CmsException { CmsResource result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = readResource(dbc, resourcePath, filter); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_RESOURCE_1, dbc.removeSiteRoot(resourcePath)), e); } finally { dbc.clear(); } return result; } /** * Reads all resources below the given path matching the filter criteria, * including the full tree below the path only in case the <code>readTree</code> * parameter is <code>true</code>.<p> * * @param context the current request context * @param parent the parent path to read the resources from * @param filter the filter * @param readTree <code>true</code> to read all subresources * * @return a list of <code>{@link CmsResource}</code> objects matching the filter criteria * * @throws CmsSecurityException if the user has insufficient permission for the given resource (read is required). * @throws CmsException if something goes wrong * */ public List readResources(CmsRequestContext context, CmsResource parent, CmsResourceFilter filter, boolean readTree) throws CmsException, CmsSecurityException { List result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { // check the access permissions checkPermissions(dbc, parent, CmsPermissionSet.ACCESS_READ, true, CmsResourceFilter.ALL); result = m_driverManager.readResources(dbc, parent, filter, readTree); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_RESOURCES_1, context.removeSiteRoot(parent.getRootPath())), e); } finally { dbc.clear(); } return result; } /** * Reads all resources that have a value set for the specified property (definition) in the given path.<p> * * Both individual and shared properties of a resource are checked.<p> * * @param context the current request context * @param path the folder to get the resources with the property from * @param propertyDefinition the name of the property (definition) to check for * * @return a list of all <code>{@link CmsResource}</code> objects * that have a value set for the specified property. * * @throws CmsException if something goes wrong */ public List readResourcesWithProperty(CmsRequestContext context, String path, String propertyDefinition) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readResourcesWithProperty(dbc, path, propertyDefinition); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_RESOURCES_FOR_PROP_SET_2, path, propertyDefinition), e); } finally { dbc.clear(); } return result; } /** * Reads all resources that have a value (containing the specified value) set * for the specified property (definition) in the given path.<p> * * Both individual and shared properties of a resource are checked.<p> * * @param context the current request context * @param path the folder to get the resources with the property from * @param propertyDefinition the name of the property (definition) to check for * @param value the string to search in the value of the property * * @return a list of all <code>{@link CmsResource}</code> objects * that have a value set for the specified property. * * @throws CmsException if something goes wrong */ public List readResourcesWithProperty( CmsRequestContext context, String path, String propertyDefinition, String value) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readResourcesWithProperty(dbc, path, propertyDefinition, value); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_RESOURCES_FOR_PROP_VALUE_3, path, propertyDefinition, value), e); } finally { dbc.clear(); } return result; } /** * Returns a List of all siblings of the specified resource, * the specified resource being always part of the result set.<p> * * @param context the request context * @param resource the specified resource * @param filter a filter object * * @return a list of <code>{@link CmsResource}</code>s that * are siblings to the specified resource, * including the specified resource itself. * * @throws CmsException if something goes wrong */ public List readSiblings(CmsRequestContext context, CmsResource resource, CmsResourceFilter filter) throws CmsException { List result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.readSiblings(dbc, resource, filter); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_SIBLINGS_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Returns the parameters of a resource in the table of all published template resources.<p> * * @param context the current request context * @param rfsName the rfs name of the resource * * @return the paramter string of the requested resource * * @throws CmsException if something goes wrong */ public String readStaticExportPublishedResourceParameters(CmsRequestContext context, String rfsName) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); String result = null; try { result = m_driverManager.readStaticExportPublishedResourceParameters(dbc, rfsName); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_STATEXP_PUBLISHED_RESOURCE_PARAMS_1, rfsName), e); } finally { dbc.clear(); } return result; } /** * Returns a list of all template resources which must be processed during a static export.<p> * * @param context the current request context * @param parameterResources flag for reading resources with parameters (1) or without (0) * @param timestamp for reading the data from the db * * @return a list of template resources as <code>{@link String}</code> objects * * @throws CmsException if something goes wrong */ public List readStaticExportResources(CmsRequestContext context, int parameterResources, long timestamp) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readStaticExportResources(dbc, parameterResources, timestamp); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_STATEXP_RESOURCES_1, new Date(timestamp)), e); } finally { dbc.clear(); } return result; } /** * Reads the task with the given id.<p> * * @param context the current request context * @param id the id for the task to read * * @return the task with the given id * * @throws CmsException if something goes wrong */ public CmsTask readTask(CmsRequestContext context, int id) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsTask result = null; try { result = m_driverManager.readTask(dbc, id); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_TASK_FOR_ID_1, new Integer(id)), e); } finally { dbc.clear(); } return result; } /** * Reads log entries for a task.<p> * * @param context the current request context * @param taskid the task for the tasklog to read * * @return a list of <code>{@link CmsTaskLog}</code> objects * * @throws CmsException if something goes wrong */ public List readTaskLogs(CmsRequestContext context, int taskid) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readTaskLogs(dbc, taskid); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_TASKLOGS_FOR_ID_1, new Integer(taskid)), e); } finally { dbc.clear(); } return result; } /** * Reads all tasks for a project.<p> * * The <code>tasktype</code> parameter will filter the tasks. * The possible values are:<br> * <ul> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_ALL}</code>: Reads all tasks</il> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_OPEN}</code>: Reads all open tasks</il> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_DONE}</code>: Reads all finished tasks</il> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_NEW}</code>: Reads all new tasks</il> * </ul><p> * * @param context the current request context * @param projectId the id of the project in which the tasks are defined. Can be null to select all tasks * @param tasktype the type of task you want to read * @param orderBy specifies how to order the tasks * @param sort sort order: C_SORT_ASC, C_SORT_DESC, or null * * @return a list of <code>{@link CmsTask}</code> objects for the project * * @throws CmsException if operation was not successful */ public List readTasksForProject(CmsRequestContext context, int projectId, int tasktype, String orderBy, String sort) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readTasksForProject(dbc, projectId, tasktype, orderBy, sort); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_TASK_FOR_PROJECT_AND_TYPE_2, new Integer(projectId), org.opencms.workflow.Messages.toTaskTypeString(tasktype, context)), e); } finally { dbc.clear(); } return result; } /** * Reads all tasks for a role in a project.<p> * * The <code>tasktype</code> parameter will filter the tasks. * The possible values for this parameter are:<br> * <ul> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_ALL}</code>: Reads all tasks</il> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_OPEN}</code>: Reads all open tasks</il> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_DONE}</code>: Reads all finished tasks</il> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_NEW}</code>: Reads all new tasks</il> * </ul><p> * * @param context the current request context * @param projectId the id of the Project in which the tasks are defined * @param roleName the role who has to process the task * @param tasktype the type of task you want to read * @param orderBy specifies how to order the tasks * @param sort sort order C_SORT_ASC, C_SORT_DESC, or null * * @return list of <code>{@link CmsTask}</code> objects for the role * * @throws CmsException if operation was not successful */ public List readTasksForRole( CmsRequestContext context, int projectId, String roleName, int tasktype, String orderBy, String sort) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readTasksForRole(dbc, projectId, roleName, tasktype, orderBy, sort); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_TASK_FOR_PROJECT_AND_ROLE_AND_TYPE_3, new Integer(projectId), roleName, org.opencms.workflow.Messages.toTaskTypeString(tasktype, context)), e); } finally { dbc.clear(); } return result; } /** * Reads all tasks for a user in a project.<p> * * The <code>tasktype</code> parameter will filter the tasks. * The possible values for this parameter are:<br> * <ul> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_ALL}</code>: Reads all tasks</il> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_OPEN}</code>: Reads all open tasks</il> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_DONE}</code>: Reads all finished tasks</il> * <il><code>{@link org.opencms.workflow.CmsTaskService#TASKS_NEW}</code>: Reads all new tasks</il> * </ul> * * @param context the current request context * @param projectId the id of the Project in which the tasks are defined * @param userName the user who has to process the task * @param taskType the type of task you want to read * @param orderBy specifies how to order the tasks * @param sort sort order C_SORT_ASC, C_SORT_DESC, or null * * @return a list of <code>{@link CmsTask}</code> objects for the user * * @throws CmsException if operation was not successful */ public List readTasksForUser( CmsRequestContext context, int projectId, String userName, int taskType, String orderBy, String sort) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List result = null; try { result = m_driverManager.readTasksForUser(dbc, projectId, userName, taskType, orderBy, sort); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_READ_TASK_FOR_PROJECT_AND_USER_AND_TYPE_3, new Integer(projectId), userName, org.opencms.workflow.Messages.toTaskTypeString(taskType, context)), e); } finally { dbc.clear(); } return result; } /** * Returns a user object based on the id of a user.<p> * * @param context the current request context * @param id the id of the user to read * * @return the user read * * @throws CmsException if something goes wrong */ public CmsUser readUser(CmsRequestContext context, CmsUUID id) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.readUser(dbc, id); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_USER_FOR_ID_1, id.toString()), e); } finally { dbc.clear(); } return result; } /** * Returns a user object.<p> * * @param context the current request context * @param username the name of the user that is to be read * @param type the type of the user * * @return user read * * @throws CmsException if operation was not succesful */ public CmsUser readUser(CmsRequestContext context, String username, int type) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.readUser(dbc, username, type); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_USER_FOR_NAME_1, username), e); } finally { dbc.clear(); } return result; } /** * Returns a user object if the password for the user is correct.<p> * * If the user/pwd pair is not valid a <code>{@link CmsException}</code> is thrown.<p> * * @param context the current request context * @param username the username of the user that is to be read * @param password the password of the user that is to be read * * @return user read * * @throws CmsException if operation was not succesful */ public CmsUser readUser(CmsRequestContext context, String username, String password) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.readUser(dbc, username, password); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_USER_FOR_NAME_1, username), e); } finally { dbc.clear(); } return result; } /** * Returns a user object.<p> * * @param username the name of the user that is to be read * * @return user read form the cms * * @throws CmsException if operation was not succesful */ public CmsUser readUser(String username) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(); CmsUser result = null; try { result = m_driverManager.readUser(dbc, username); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_USER_FOR_NAME_1, username), e); } finally { dbc.clear(); } return result; } /** * Read a web user from the database.<p> * * @param context the current request context * @param username the web user to read * * @return the read web user * * @throws CmsException if the user could not be read. */ public CmsUser readWebUser(CmsRequestContext context, String username) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.readWebUser(dbc, username); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_USER_WEB_1, username), e); } finally { dbc.clear(); } return result; } /** * Returns a user object if the password for the user is correct.<p> * * If the user/pwd pair is not valid a <code>{@link CmsException}</code> is thrown.<p> * * @param context the current request context * @param username the username of the user that is to be read * @param password the password of the user that is to be read * * @return the webuser read * * @throws CmsException if operation was not succesful */ public CmsUser readWebUser(CmsRequestContext context, String username, String password) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.readWebUser(dbc, username, password); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_USER_WEB_1, username), e); } finally { dbc.clear(); } return result; } /** * Removes an access control entry for a given resource and principal.<p> * * @param context the current request context * @param resource the resource * @param principal the id of the principal to remove the the access control entry for * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (conrol of access control is required). * */ public void removeAccessControlEntry(CmsRequestContext context, CmsResource resource, CmsUUID principal) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_CONTROL, true, CmsResourceFilter.ALL); m_driverManager.removeAccessControlEntry(dbc, resource, principal); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_REMOVE_ACL_ENTRY_2, context.getSitePath(resource), principal.toString()), e); } finally { dbc.clear(); } } /** * Removes a user from a group.<p> * * @param context the current request context * @param username the name of the user that is to be removed from the group * @param groupname the name of the group * * @throws CmsException if operation was not succesful * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#USER_MANAGER} * */ public void removeUserFromGroup(CmsRequestContext context, String username, String groupname) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.USER_MANAGER); m_driverManager.removeUserFromGroup(dbc, username, groupname); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_REMOVE_USER_FROM_GROUP_2, username, groupname), e); } finally { dbc.clear(); } } /** * Replaces the content, type and properties of a resource.<p> * * @param context the current request context * @param resource the name of the resource to apply this operation to * @param type the new type of the resource * @param content the new content of the resource * @param properties the new properties of the resource * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (write access permission is required). * * @see CmsObject#replaceResource(String, int, byte[], List) * @see org.opencms.file.types.I_CmsResourceType#replaceResource(CmsObject, CmsSecurityManager, CmsResource, int, byte[], List) */ public void replaceResource( CmsRequestContext context, CmsResource resource, int type, byte[] content, List properties) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.replaceResource(dbc, resource, type, content, properties); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_REPLACE_RESOURCE_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Resets the password for a specified user.<p> * * @param context the current request context * @param username the name of the user * @param oldPassword the old password * @param newPassword the new password * * @throws CmsException if the user data could not be read from the database * @throws CmsSecurityException if the specified username and old password could not be verified */ public void resetPassword(CmsRequestContext context, String username, String oldPassword, String newPassword) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.resetPassword(dbc, username, oldPassword, newPassword); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_RESET_PASSWORD_1, username), e); } finally { dbc.clear(); } } /** * Restores a file in the current project with a version from the backup archive.<p> * * @param context the current request context * @param resource the resource to restore from the archive * @param tag the tag (version) id to resource form the archive * * @throws CmsException if something goes wrong * * @see CmsObject#restoreResourceBackup(String, int) * @see org.opencms.file.types.I_CmsResourceType#restoreResourceBackup(CmsObject, CmsSecurityManager, CmsResource, int) * @throws CmsSecurityException if the user has insufficient permission for the given resource (write access permission is required). */ public void restoreResource(CmsRequestContext context, CmsResource resource, int tag) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.restoreResource(dbc, resource, tag); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_RESTORE_RESOURCE_2, context.getSitePath(resource), new Integer(tag)), e); } finally { dbc.clear(); } } /** * Set a new name for a task.<p> * * @param context the current request context * @param taskId the Id of the task to set the percentage * @param name the new name value * * @throws CmsException if something goes wrong */ public void setName(CmsRequestContext context, int taskId, String name) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.setName(dbc, taskId, name); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_SET_TASK_NAME_2, name, new Integer(taskId)), e); } finally { dbc.clear(); } } /** * Sets a new parent-group for an already existing group.<p> * * @param context the current request context * @param groupName the name of the group that should be written * @param parentGroupName the name of the parent group to set, * or <code>null</code> if the parent * group should be deleted. * * @throws CmsException if operation was not succesful * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#USER_MANAGER} * */ public void setParentGroup(CmsRequestContext context, String groupName, String parentGroupName) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.USER_MANAGER); m_driverManager.setParentGroup(dbc, groupName, parentGroupName); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_SET_PARENT_GROUP_2, parentGroupName, groupName), e); } finally { dbc.clear(); } } /** * Sets the password for a user.<p> * * @param context the current request context * @param username the name of the user * @param newPassword the new password * * @throws CmsException if operation was not succesfull * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#USER_MANAGER} */ public void setPassword(CmsRequestContext context, String username, String newPassword) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.USER_MANAGER); m_driverManager.setPassword(dbc, username, newPassword); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_SET_PASSWORD_1, username), e); } finally { dbc.clear(); } } /** * Set priority of a task.<p> * * @param context the current request context * @param taskId the Id of the task to set the percentage * @param priority the priority value * * @throws CmsException if something goes wrong */ public void setPriority(CmsRequestContext context, int taskId, int priority) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.setPriority(dbc, taskId, priority); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_SET_TASK_PRIORITY_2, new Integer(taskId), new Integer(priority)), e); } finally { dbc.clear(); } } /** * Set a Parameter for a task.<p> * * @param context the current request context * @param taskId the Id of the task * @param parName name of the parameter * @param parValue value if the parameter * * @throws CmsException if something goes wrong */ public void setTaskPar(CmsRequestContext context, int taskId, String parName, String parValue) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.setTaskPar(dbc, taskId, parName, parValue); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_SET_TASK_PARAM_3, parName, parValue, new Integer(taskId)), e); } finally { dbc.clear(); } } /** * Set timeout of a task.<p> * * @param context the current request context * @param taskId the Id of the task to set the percentage * @param timeout new timeout value * * @throws CmsException if something goes wrong */ public void setTimeout(CmsRequestContext context, int taskId, long timeout) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.setTimeout(dbc, taskId, timeout); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_SET_TASK_TIMEOUT_2, new Date(timeout), new Integer(taskId)), e); } finally { dbc.clear(); } } /** * Changes the timestamp information of a resource.<p> * * This method is used to set the "last modified" date * of a resource, the "release" date of a resource, * and also the "expire" date of a resource.<p> * * @param context the current request context * @param resource the resource to touch * @param dateLastModified timestamp the new timestamp of the changed resource * @param dateReleased the new release date of the changed resource, * set it to <code>{@link I_CmsConstants#C_DATE_UNCHANGED}</code> to keep it unchanged. * @param dateExpired the new expire date of the changed resource, * set it to <code>{@link I_CmsConstants#C_DATE_UNCHANGED}</code> to keep it unchanged. * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (write access permission is required). * * @see CmsObject#touch(String, long, long, long, boolean) * @see org.opencms.file.types.I_CmsResourceType#touch(CmsObject, CmsSecurityManager, CmsResource, long, long, long, boolean) */ public void touch( CmsRequestContext context, CmsResource resource, long dateLastModified, long dateReleased, long dateExpired) throws CmsException, CmsSecurityException { int todo = 0; // TODO: Make 3 methods out of this (setDateLastModified, setDateReleased, setDateExpired) CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.IGNORE_EXPIRATION); m_driverManager.touch(dbc, resource, dateLastModified, dateReleased, dateExpired); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_TOUCH_RESOURCE_4, new Object[] { new Date(dateLastModified), new Date(dateReleased), new Date(dateExpired), context.getSitePath(resource)}), e); } finally { dbc.clear(); } } /** * Undos all changes in the resource by restoring the version from the * online project to the current offline project.<p> * * @param context the current request context * @param resource the name of the resource to apply this operation to * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (write access permission is required). * * @see CmsObject#undoChanges(String, boolean) * @see org.opencms.file.types.I_CmsResourceType#undoChanges(CmsObject, CmsSecurityManager, CmsResource, boolean) */ public void undoChanges(CmsRequestContext context, CmsResource resource) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.undoChanges(dbc, resource); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_UNDO_CHANGES_FOR_RESOURCE_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Unlocks all resources in this project.<p> * * @param context the current request context * @param projectId the id of the project to be published * * @throws CmsException if something goes wrong * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#PROJECT_MANAGER} for the current project. */ public void unlockProject(CmsRequestContext context, int projectId) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsProject project = m_driverManager.readProject(dbc, projectId); try { checkManagerOfProjectRole(dbc, project); m_driverManager.unlockProject(project); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_UNLOCK_PROJECT_2, new Integer(projectId), dbc.currentUser().getName()), e); } finally { dbc.clear(); } } /** * Unlocks a resource.<p> * * @param context the current request context * @param resource the resource to unlock * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (write access permission is required). * * @see CmsObject#unlockResource(String) * @see org.opencms.file.types.I_CmsResourceType#unlockResource(CmsObject, CmsSecurityManager, CmsResource) */ public void unlockResource(CmsRequestContext context, CmsResource resource) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.unlockResource(dbc, resource); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_UNLOCK_RESOURCE_2, context.getSitePath(resource), dbc.currentUser().getName()), e); } finally { dbc.clear(); } } /** * Tests if a user is member of the given group.<p> * * @param context the current request context * @param username the name of the user to check * @param groupname the name of the group to check * * @return <code>true</code>, if the user is in the group; or <code>false</code> otherwise * * @throws CmsException if operation was not succesful */ public boolean userInGroup(CmsRequestContext context, String username, String groupname) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); boolean result = false; try { result = m_driverManager.userInGroup(dbc, username, groupname); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_USER_IN_GROUP_2, username, groupname), e); } finally { dbc.clear(); } return result; } /** * Validates the HTML links in the unpublished files of the specified * publish list, if a file resource type implements the interface * <code>{@link org.opencms.validation.I_CmsXmlDocumentLinkValidatable}</code>.<p> * * @param cms the current user's Cms object * @param publishList an OpenCms publish list * @param report a report to write the messages to * * @return a map with lists of invalid links (<code>String</code> objects) keyed by resource names * * @throws Exception if something goes wrong * * @see #getPublishList(CmsRequestContext, CmsResource, boolean) */ public Map validateHtmlLinks(CmsObject cms, CmsPublishList publishList, I_CmsReport report) throws Exception { return m_driverManager.validateHtmlLinks(cms, publishList, report); } /** * This method checks if a new password follows the rules for * new passwords, which are defined by a Class implementing the * <code>{@link org.opencms.security.I_CmsPasswordHandler}</code> * interface and configured in the opencms.properties file.<p> * * If this method throws no exception the password is valid.<p> * * @param password the new password that has to be checked * * @throws CmsSecurityException if the password is not valid */ public void validatePassword(String password) throws CmsSecurityException { m_driverManager.validatePassword(password); } /** * Writes an access control entries to a given resource.<p> * * @param context the current request context * @param resource the resource * @param ace the entry to write * * @throws CmsSecurityException if the user has insufficient permission for the given resource ({@link CmsPermissionSet#ACCESS_CONTROL} required). * @throws CmsException if something goes wrong */ public void writeAccessControlEntry(CmsRequestContext context, CmsResource resource, CmsAccessControlEntry ace) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_CONTROL, true, CmsResourceFilter.ALL); m_driverManager.writeAccessControlEntry(dbc, resource, ace); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_ACL_ENTRY_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Writes a resource to the OpenCms VFS, including it's content.<p> * * Applies only to resources of type <code>{@link CmsFile}</code> * i.e. resources that have a binary content attached.<p> * * Certain resource types might apply content validation or transformation rules * before the resource is actually written to the VFS. The returned result * might therefore be a modified version from the provided original.<p> * * @param context the current request context * @param resource the resource to apply this operation to * * @return the written resource (may have been modified) * * @throws CmsSecurityException if the user has insufficient permission for the given resource ({@link CmsPermissionSet#ACCESS_WRITE} required). * @throws CmsException if something goes wrong * * @see CmsObject#writeFile(CmsFile) * @see org.opencms.file.types.I_CmsResourceType#writeFile(CmsObject, CmsSecurityManager, CmsFile) */ public CmsFile writeFile(CmsRequestContext context, CmsFile resource) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsFile result = null; try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); result = m_driverManager.writeFile(dbc, resource); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_FILE_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Writes an already existing group.<p> * * The group id has to be a valid OpenCms group id.<br> * * The group with the given id will be completely overriden * by the given data.<p> * * @param context the current request context * @param group the group that should be written * * @throws CmsRoleViolationException if the current user does not own the role {@link CmsRole#USER_MANAGER} for the current project. * @throws CmsException if operation was not succesfull */ public void writeGroup(CmsRequestContext context, CmsGroup group) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.USER_MANAGER); m_driverManager.writeGroup(dbc, group); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_GROUP_1, group.getName()), e); } finally { dbc.clear(); } } /** * Writes an already existing project.<p> * * The project id has to be a valid OpenCms project id.<br> * * The project with the given id will be completely overriden * by the given data.<p> * * @param project the project that should be written * @param context the current request context * * @throws CmsRoleViolationException if the current user does not own the role {@link CmsRole#PROJECT_MANAGER} for the current project. * @throws CmsException if operation was not successful */ public void writeProject(CmsRequestContext context, CmsProject project) throws CmsRoleViolationException, CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.PROJECT_MANAGER); m_driverManager.writeProject(dbc, project); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_PROJECT_1, project.getName()), e); } finally { dbc.clear(); } } /** * Writes a property for a specified resource.<p> * * @param context the current request context * @param resource the resource to write the property for * @param property the property to write * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource ({@link CmsPermissionSet#ACCESS_WRITE} required). * * @see CmsObject#writePropertyObject(String, CmsProperty) * @see org.opencms.file.types.I_CmsResourceType#writePropertyObject(CmsObject, CmsSecurityManager, CmsResource, CmsProperty) */ public void writePropertyObject(CmsRequestContext context, CmsResource resource, CmsProperty property) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.IGNORE_EXPIRATION); m_driverManager.writePropertyObject(dbc, resource, property); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_WRITE_PROP_2, property.getName(), context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Writes a list of properties for a specified resource.<p> * * Code calling this method has to ensure that the no properties * <code>a, b</code> are contained in the specified list so that <code>a.equals(b)</code>, * otherwise an exception is thrown.<p> * * @param context the current request context * @param resource the resource to write the properties for * @param properties the list of properties to write * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource ({@link CmsPermissionSet#ACCESS_WRITE} required). * * @see CmsObject#writePropertyObjects(String, List) * @see org.opencms.file.types.I_CmsResourceType#writePropertyObjects(CmsObject, CmsSecurityManager, CmsResource, List) */ public void writePropertyObjects(CmsRequestContext context, CmsResource resource, List properties) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.IGNORE_EXPIRATION); // write the properties m_driverManager.writePropertyObjects(dbc, resource, properties); // update the resource state resource.setUserLastModified(context.currentUser().getId()); m_driverManager.getVfsDriver().writeResource( dbc, context.currentProject(), resource, CmsDriverManager.C_UPDATE_RESOURCE_STATE); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_PROPS_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Writes a resource to the OpenCms VFS.<p> * * @param context the current request context * @param resource the resource to write * * @throws CmsSecurityException if the user has insufficient permission for the given resource ({@link CmsPermissionSet#ACCESS_WRITE} required). * @throws CmsException if something goes wrong */ public void writeResource(CmsRequestContext context, CmsResource resource) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.writeResource(dbc, resource); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_RESOURCE_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Inserts an entry in the published resource table.<p> * * This is done during static export.<p> * * @param context the current request context * @param resourceName The name of the resource to be added to the static export * @param linkType the type of resource exported (0= non-paramter, 1=parameter) * @param linkParameter the parameters added to the resource * @param timestamp a timestamp for writing the data into the db * * @throws CmsException if something goes wrong */ public void writeStaticExportPublishedResource( CmsRequestContext context, String resourceName, int linkType, String linkParameter, long timestamp) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.writeStaticExportPublishedResource(dbc, resourceName, linkType, linkParameter, timestamp); } catch (Exception e) { dbc.report(null, Messages.get().container( Messages.ERR_WRITE_STATEXP_PUBLISHED_RESOURCES_3, resourceName, linkParameter, new Date(timestamp)), e); } finally { dbc.clear(); } } /** * Writes a new user tasklog for a task.<p> * * @param context the current request context * @param taskid the Id of the task * @param comment description for the log * * @throws CmsException if something goes wrong */ public void writeTaskLog(CmsRequestContext context, int taskid, String comment) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.writeTaskLog(dbc, taskid, comment); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_TASK_LOG_1, new Integer(taskid)), e); } finally { dbc.clear(); } } /** * Writes a new user tasklog for a task.<p> * * @param context the current request context * @param taskId the Id of the task * @param comment description for the log * @param type type of the tasklog. User tasktypes must be greater than 100 * * @throws CmsException something goes wrong */ public void writeTaskLog(CmsRequestContext context, int taskId, String comment, int type) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.writeTaskLog(dbc, taskId, comment, type); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_TASK_LOG_1, new Integer(taskId)), e); } finally { dbc.clear(); } } /** * Updates the user information. <p> * * The user id has to be a valid OpenCms user id.<br> * * The user with the given id will be completely overriden * by the given data.<p> * * @param context the current request context * @param user the user to be updated * * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#USER_MANAGER} for the current project. * @throws CmsException if operation was not succesful */ public void writeUser(CmsRequestContext context, CmsUser user) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { if (!context.currentUser().equals(user)) { // a user is allowed to write his own data (e.g. for "change preferences") checkRole(dbc, CmsRole.USER_MANAGER); } m_driverManager.writeUser(dbc, user); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_USER_1, user.getName()), e); } finally { dbc.clear(); } } /** * Updates the user information of a web user.<br> * * Only a web user can be updated this way.<p> * * The user id has to be a valid OpenCms user id.<br> * * The user with the given id will be completely overriden * by the given data.<p> * * @param context the current request context * @param user the user to be updated * * @throws CmsException if operation was not succesful */ public void writeWebUser(CmsRequestContext context, CmsUser user) throws CmsException { if (!user.isWebUser()) { throw new CmsSecurityException(Messages.get().container(Messages.ERR_WRITE_WEB_USER_CONSTRAINT_0)); } CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.writeWebUser(dbc, user); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_WEB_USER_1, user.getName()), e); } finally { dbc.clear(); } } /** * Performs a blocking permission check on a resource.<p> * * If the required permissions are not satisfied by the permissions the user has on the resource, * an exception is thrown.<p> * * @param dbc the current database context * @param resource the resource on which permissions are required * @param requiredPermissions the set of permissions required to access the resource * @param checkLock if true, the lock status of the resource is also checked * @param filter the filter for the resource * * @throws CmsException in case of any i/o error * @throws CmsSecurityException if the required permissions are not satisfied * * @see #hasPermissions(CmsRequestContext, CmsResource, CmsPermissionSet, boolean, CmsResourceFilter) */ protected void checkPermissions( CmsDbContext dbc, CmsResource resource, CmsPermissionSet requiredPermissions, boolean checkLock, CmsResourceFilter filter) throws CmsException, CmsSecurityException { // get the permissions int permissions = hasPermissions(dbc, resource, requiredPermissions, checkLock, filter); if (permissions != 0) { checkPermissions(dbc.getRequestContext(), resource, requiredPermissions, permissions); } } /** * Clears the permission cache.<p> */ protected void clearPermissionCache() { m_permissionCache.clear(); } /** * @see java.lang.Object#finalize() */ protected void finalize() throws Throwable { try { if (m_driverManager != null) { m_driverManager.destroy(); } } catch (Throwable t) { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().key(Messages.LOG_ERR_DRIVER_MANAGER_CLOSE_0), t); } } m_driverManager = null; m_dbContextFactory = null; super.finalize(); } /** * Performs a non-blocking permission check on a resource.<p> * * This test will not throw an exception in case the required permissions are not * available for the requested operation. Instead, it will return one of the * following values:<ul> * <li><code>{@link #PERM_ALLOWED}</code></li> * <li><code>{@link #PERM_FILTERED}</code></li> * <li><code>{@link #PERM_DENIED}</code></li></ul><p> * * @param dbc the current database context * @param resource the resource on which permissions are required * @param requiredPermissions the set of permissions required for the operation * @param checkLock if true, a lock for the current user is required for * all write operations, if false it's ok to write as long as the resource * is not locked by another user * @param filter the resource filter to use * * @return <code>PERM_ALLOWED</code> if the user has sufficient permissions on the resource * for the requested operation * * @throws CmsException in case of i/o errors (NOT because of insufficient permissions) */ protected int hasPermissions( CmsDbContext dbc, CmsResource resource, CmsPermissionSet requiredPermissions, boolean checkLock, CmsResourceFilter filter) throws CmsException { // check if the resource is valid according to the current filter // if not, throw a CmsResourceNotFoundException if (!filter.isValid(dbc.getRequestContext(), resource)) { return PERM_FILTERED; } // checking the filter is less cost intensive then checking the cache, // this is why basic filter results are not cached String cacheKey = m_keyGenerator.getCacheKeyForUserPermissions( String.valueOf(filter.requireVisible()), dbc, resource, requiredPermissions); Integer cacheResult = (Integer)m_permissionCache.get(cacheKey); if (cacheResult != null) { return cacheResult.intValue(); } int denied = 0; // if this is the onlineproject, write is rejected if (dbc.currentProject().isOnlineProject()) { denied |= CmsPermissionSet.PERMISSION_WRITE; } // check if the current user is admin boolean canIgnorePermissions = hasRole(dbc, CmsRole.VFS_MANAGER); // check lock status boolean writeRequired = requiredPermissions.requiresWritePermission() || requiredPermissions.requiresControlPermission(); // if the resource type is jsp // write is only allowed for administrators if (writeRequired && !canIgnorePermissions && (resource.getTypeId() == CmsResourceTypeJsp.getStaticTypeId())) { if (!hasRole(dbc, CmsRole.DEVELOPER)) { denied |= CmsPermissionSet.PERMISSION_WRITE; denied |= CmsPermissionSet.PERMISSION_CONTROL; } } if (writeRequired) { // check lock state only if required CmsLock lock = m_driverManager.getLock(dbc, resource); // if the resource is not locked by the current user, write and control // access must cause a permission error that must not be cached if (checkLock || !lock.isNullLock()) { if (!dbc.currentUser().getId().equals(lock.getUserId())) { return PERM_NOTLOCKED; } } } CmsPermissionSetCustom permissions; if (canIgnorePermissions) { // if the current user is administrator, anything is allowed permissions = new CmsPermissionSetCustom(~0); } else { // otherwise, get the permissions from the access control list permissions = m_driverManager.getPermissions(dbc, resource, dbc.currentUser()); } // revoke the denied permissions permissions.denyPermissions(denied); if ((permissions.getPermissions() & CmsPermissionSet.PERMISSION_VIEW) == 0) { // resource "invisible" flag is set for this user if (filter.requireVisible()) { // filter requires visible permission - extend required permission set requiredPermissions = new CmsPermissionSet(requiredPermissions.getAllowedPermissions() | CmsPermissionSet.PERMISSION_VIEW, requiredPermissions.getDeniedPermissions()); } else { // view permissions can be ignored by filter permissions.setPermissions( // modify permissions so that view is allowed permissions.getAllowedPermissions() | CmsPermissionSet.PERMISSION_VIEW, permissions.getDeniedPermissions() & ~CmsPermissionSet.PERMISSION_VIEW); } } Integer result; if ((requiredPermissions.getPermissions() & (permissions.getPermissions())) == requiredPermissions.getPermissions()) { result = PERM_ALLOWED_INTEGER; } else { result = PERM_DENIED_INTEGER; } m_permissionCache.put(cacheKey, result); if ((result != PERM_ALLOWED_INTEGER) && LOG.isDebugEnabled()) { LOG.debug(Messages.get().key( Messages.LOG_NO_PERMISSION_RESOURCE_USER_4, new Object[] { dbc.getRequestContext().removeSiteRoot(resource.getRootPath()), dbc.currentUser().getName(), requiredPermissions.getPermissionString(), permissions.getPermissionString()})); } return result.intValue(); } /** * Reads a folder from the VFS, using the specified resource filter.<p> * * @param dbc the current database context * @param resourcename the name of the folder to read (full path) * @param filter the resource filter to use while reading * * @return the folder that was read * * @throws CmsException if something goes wrong */ protected CmsFolder readFolder(CmsDbContext dbc, String resourcename, CmsResourceFilter filter) throws CmsException { CmsResource resource = readResource(dbc, resourcename, filter); return m_driverManager.convertResourceToFolder(resource); } /** * Reads a resource from the OpenCms VFS, using the specified resource filter.<p> * * @param dbc the current database context * @param resourcePath the name of the resource to read (full path) * @param filter the resource filter to use while reading * * @return the resource that was read * * @throws CmsException if something goes wrong * * @see CmsObject#readResource(String, CmsResourceFilter) * @see CmsObject#readResource(String) * @see CmsFile#upgrade(CmsResource, CmsObject) */ protected CmsResource readResource(CmsDbContext dbc, String resourcePath, CmsResourceFilter filter) throws CmsException { // read the resource from the VFS CmsResource resource = m_driverManager.readResource(dbc, resourcePath, filter); // check if the user has read access to the resource checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_READ, true, filter); // access was granted - return the resource return resource; } /** * Applies the permission check result of a previous call * to {@link #hasPermissions(CmsRequestContext, CmsResource, CmsPermissionSet, boolean, CmsResourceFilter)}.<p> * * @param context the current request context * @param resource the resource on which permissions are required * @param requiredPermissions the set of permissions required to access the resource * @param permissions the permissions to check * * @throws CmsSecurityException if the required permissions are not satisfied * @throws CmsLockException if the lock status is not as required * @throws CmsVfsResourceNotFoundException if the required resource has been filtered */ protected void checkPermissions( CmsRequestContext context, CmsResource resource, CmsPermissionSet requiredPermissions, int permissions) throws CmsSecurityException, CmsLockException, CmsVfsResourceNotFoundException { switch (permissions) { case PERM_FILTERED: throw new CmsVfsResourceNotFoundException(Messages.get().container( Messages.ERR_PERM_FILTERED_1, context.getSitePath(resource))); case PERM_DENIED: throw new CmsPermissionViolationException(Messages.get().container( Messages.ERR_PERM_DENIED_2, context.getSitePath(resource), requiredPermissions.getPermissionString())); case PERM_NOTLOCKED: throw new CmsLockException(Messages.get().container( Messages.ERR_PERM_NOTLOCKED_2, context.getSitePath(resource), context.currentUser().getName())); case PERM_ALLOWED: default: return; } } /** * Deletes a user.<p> * * @param context the current request context * @param user the user to be deleted * * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#USER_MANAGER} * @throws CmsSecurityException in case the user is a default user * @throws CmsException if something goes wrong */ private void deleteUser(CmsRequestContext context, CmsUser user) throws CmsException { if (OpenCms.getDefaultUsers().isDefaultUser(user.getName())) { throw new CmsSecurityException(org.opencms.security.Messages.get().container( org.opencms.security.Messages.ERR_CANT_DELETE_DEFAULT_USER_1, user.getName())); } CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.USER_MANAGER); m_driverManager.deleteUser(dbc, context.currentProject(), user.getId()); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DELETE_USER_1, user.getName()), e); } finally { dbc.clear(); } } }
bug 684 fixed
src/org/opencms/db/CmsSecurityManager.java
bug 684 fixed
<ide><path>rc/org/opencms/db/CmsSecurityManager.java <ide> /* <ide> * File : $Source: /alkacon/cvs/opencms/src/org/opencms/db/CmsSecurityManager.java,v $ <del> * Date : $Date: 2005/06/23 18:06:27 $ <del> * Version: $Revision: 1.84 $ <add> * Date : $Date: 2005/06/24 15:51:09 $ <add> * Version: $Revision: 1.85 $ <ide> * <ide> * This library is part of OpenCms - <ide> * the Open Source Content Mananagement System <ide> * @author Thomas Weckert <ide> * @author Michael Moossen <ide> * <del> * @version $Revision: 1.84 $ <add> * @version $Revision: 1.85 $ <ide> * <ide> * @since 6.0.0 <ide> */ <ide> * @throws CmsVfsException for now only when the search for the oldvalue failed. <ide> * @throws CmsException if operation was not successful <ide> */ <del> public List changeResourcesInFolderWithProperty( <add> public synchronized List changeResourcesInFolderWithProperty( <ide> CmsRequestContext context, <ide> CmsResource resource, <ide> String propertyDefinition,
Java
apache-2.0
b6ffed97c21055f70515984001ce2d3e06cb21bd
0
jior/glaf,jior/glaf,jior/glaf,jior/glaf,jior/glaf,jior/glaf
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.glaf.core.xml; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import com.glaf.core.base.ClassDefinition; import com.glaf.core.base.FieldDefinition; public class XmlWriter { public Document write(ClassDefinition classDefinition) { List<ClassDefinition> rows = new java.util.ArrayList<ClassDefinition>(); rows.add(classDefinition); return this.write(rows); } public Document write(List<ClassDefinition> rows) { Document doc = DocumentHelper.createDocument(); Element root = doc.addElement("mapping"); for (ClassDefinition classDefinition : rows) { Element element = root.addElement("entity"); element.addAttribute("name", classDefinition.getEntityName()); element.addAttribute("package", classDefinition.getPackageName()); element.addAttribute("moduleName", classDefinition.getModuleName()); element.addAttribute("table", classDefinition.getTableName()); element.addAttribute("title", classDefinition.getTitle()); element.addAttribute("englishTitle", classDefinition.getEnglishTitle()); FieldDefinition idField = classDefinition.getIdField(); if (idField != null) { Element idElement = element.addElement("id"); idElement.addAttribute("name", idField.getName()); idElement.addAttribute("column", idField.getColumnName()); idElement.addAttribute("type", idField.getType()); idElement.addAttribute("title", idField.getTitle()); idElement.addAttribute("englishTitle", idField.getEnglishTitle()); if (idField.getLength() > 0) { idElement.addAttribute("length", String.valueOf(idField.getLength())); } } Map<String, FieldDefinition> fields = classDefinition.getFields(); Set<Entry<String, FieldDefinition>> entrySet = fields.entrySet(); for (Entry<String, FieldDefinition> entry : entrySet) { String name = entry.getKey(); FieldDefinition field = entry.getValue(); if (idField != null && StringUtils.equalsIgnoreCase( idField.getColumnName(), field.getColumnName())) { continue; } Element elem = element.addElement("property"); elem.addAttribute("name", name); elem.addAttribute("column", field.getColumnName()); elem.addAttribute("type", field.getType()); elem.addAttribute("title", field.getTitle()); elem.addAttribute("englishTitle", field.getEnglishTitle()); if (StringUtils.equals(field.getType(), "String") && field.getLength() > 0) { elem.addAttribute("length", String.valueOf(field.getLength())); } if (field.isUnique()) { elem.addAttribute("unique", String.valueOf(field.isUnique())); } if (field.isSearchable()) { elem.addAttribute("searchable", String.valueOf(field.isSearchable())); } if (!field.isNullable()) { elem.addAttribute("nullable", String.valueOf(field.isNullable())); } if (field.isEditable()) { elem.addAttribute("editable", String.valueOf(field.isEditable())); } if (field.getDisplayType() > 0) { elem.addAttribute("displayType", String.valueOf(field.getDisplayType())); } } } return doc; } }
workspace/glaf-core/src/main/java/com/glaf/core/xml/XmlWriter.java
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.glaf.core.xml; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import com.glaf.core.base.ClassDefinition; import com.glaf.core.base.FieldDefinition; public class XmlWriter { public Document write(ClassDefinition classDefinition) { List<ClassDefinition> rows = new java.util.ArrayList<ClassDefinition>(); rows.add(classDefinition); return this.write(rows); } public Document write(List<ClassDefinition> rows) { Document doc = DocumentHelper.createDocument(); Element root = doc.addElement("mapping"); for (ClassDefinition classDefinition : rows) { Element element = root.addElement("entity"); element.addAttribute("name", classDefinition.getEntityName()); element.addAttribute("package", classDefinition.getPackageName()); element.addAttribute("moduleName", classDefinition.getModuleName()); element.addAttribute("table", classDefinition.getTableName()); element.addAttribute("title", classDefinition.getTitle()); element.addAttribute("englishTitle", classDefinition.getEnglishTitle()); FieldDefinition idField = classDefinition.getIdField(); if (idField != null) { Element idElement = element.addElement("id"); idElement.addAttribute("name", idField.getName()); idElement.addAttribute("column", idField.getColumnName()); idElement.addAttribute("type", idField.getType()); idElement.addAttribute("title", idField.getTitle()); idElement.addAttribute("englishTitle", idField.getEnglishTitle()); if (idField.getLength() > 0) { idElement.addAttribute("length", String.valueOf(idField.getLength())); } } Map<String, FieldDefinition> fields = classDefinition.getFields(); Set<Entry<String, FieldDefinition>> entrySet = fields.entrySet(); for (Entry<String, FieldDefinition> entry : entrySet) { String name = entry.getKey(); FieldDefinition field = entry.getValue(); if (idField != null && StringUtils.equalsIgnoreCase( idField.getColumnName(), field.getColumnName())) { continue; } Element elem = element.addElement("property"); elem.addAttribute("name", name); elem.addAttribute("column", field.getColumnName()); elem.addAttribute("type", field.getType()); elem.addAttribute("title", field.getTitle()); elem.addAttribute("englishTitle", field.getEnglishTitle()); if (field.getLength() > 0) { elem.addAttribute("length", String.valueOf(field.getLength())); } if (field.isUnique()) { elem.addAttribute("unique", String.valueOf(field.isUnique())); } if (field.isSearchable()) { elem.addAttribute("searchable", String.valueOf(field.isSearchable())); } if (!field.isNullable()) { elem.addAttribute("nullable", String.valueOf(field.isNullable())); } if (field.isEditable()) { elem.addAttribute("editable", String.valueOf(field.isEditable())); } if (field.getDisplayType() > 0) { elem.addAttribute("displayType", String.valueOf(field.getDisplayType())); } } } return doc; } }
update
workspace/glaf-core/src/main/java/com/glaf/core/xml/XmlWriter.java
update
<ide><path>orkspace/glaf-core/src/main/java/com/glaf/core/xml/XmlWriter.java <ide> elem.addAttribute("title", field.getTitle()); <ide> elem.addAttribute("englishTitle", field.getEnglishTitle()); <ide> <del> if (field.getLength() > 0) { <add> if (StringUtils.equals(field.getType(), "String") <add> && field.getLength() > 0) { <ide> elem.addAttribute("length", <ide> String.valueOf(field.getLength())); <ide> }
Java
apache-2.0
56dad4882b6854c59edbcf1cce0acc889d910d9c
0
DwayneJengSage/BridgeJavaSDK,Sage-Bionetworks/BridgeJavaSDK,DwayneJengSage/BridgeJavaSDK,alxdarksage/BridgeJavaSDK,alxdarksage/BridgeJavaSDK,Sage-Bionetworks/BridgeJavaSDK
package org.sagebionetworks.bridge.rest; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import java.util.concurrent.TimeUnit; import com.google.common.base.Strings; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import org.sagebionetworks.bridge.rest.api.AuthenticationApi; import org.sagebionetworks.bridge.rest.model.ClientInfo; import org.sagebionetworks.bridge.rest.model.SignIn; import org.sagebionetworks.bridge.rest.model.UserSessionInfo; /** * Base class for creating clients that are correctly configured to communicate with the * Bridge server. */ public class ApiClientProvider { private static final Interceptor WARNING_INTERCEPTOR = new WarningHeaderInterceptor(); private static final Interceptor ERROR_INTERCEPTOR = new ErrorResponseInterceptor(); private static final Interceptor LOGGING_INTERCEPTOR = new LoggingInterceptor(); private final UserSessionInfoProvider userSessionInfoProvider; private final LoadingCache<Class<?>, ?> unauthenticatedServices; private final LoadingCache<Class<?>, ?> authenticatedServices; private ApiClientProvider(final UserSessionInfoProvider userSessionInfoProvider, final Retrofit unauthenticatedRetrofit, final Retrofit authenticatedRetrofit) { this.userSessionInfoProvider = userSessionInfoProvider; this.unauthenticatedServices = CacheBuilder.newBuilder() .build(new RetrofitServiceLoader(unauthenticatedRetrofit)); this.authenticatedServices = CacheBuilder.newBuilder() .build(new RetrofitServiceLoader(authenticatedRetrofit)); } private static class RetrofitServiceLoader extends CacheLoader<Class<?>, Object> { private final Retrofit retrofit; RetrofitServiceLoader(Retrofit retrofit) { this.retrofit = retrofit; } @SuppressWarnings("NullableProblems") // superclass uses nullity-analysis annotations which we are not using @Override public Object load(Class<?> serviceClass) { return retrofit.create(serviceClass); } } // To build the ClientManager on this class, we need to have access to the session that is persisted // by the HTTP interceptors. public UserSessionInfoProvider getUserSessionInfoProvider() { return userSessionInfoProvider; } /** * Create an unauthenticated client (this client cannot authenticate automatically, and is only used for * public APIs not requiring a server user to access). * * @param <T> * One of the Api classes in the org.sagebionetworks.bridge.rest.api package. * @param service * Class representing the service * @return service client */ public <T> T getClient(Class<T> service) { checkNotNull(service); //noinspection unchecked return (T) unauthenticatedServices.getUnchecked(service); } /** * @param <T> * One of the Api classes in the org.sagebionetworks.bridge.rest.api package. * @param service * Class representing the service * @param signIn * credentials for the user, or null for an unauthenticated client * @return service client that is authenticated with the user's credentials */ public <T> T getClient(Class<T> service, SignIn signIn) { checkNotNull(service); checkNotNull(signIn); //noinspection unchecked return (T) authenticatedServices.getUnchecked(service); } public static class Builder { private String baseUrl; private String userAgent; private String acceptLanguage; private String study; private String email; private String password; private UserSessionInfo session; /** * Creates a builder for accessing services associated with an environment, study, and participant. * * @param baseUrl base url for Bridge service * @param userAgent * user-agent string in Bridge's expected format, see {@link RestUtils#getUserAgent(ClientInfo)} * @param acceptLanguage * optional comma-separated list of preferred languages for this client (most to least * preferred * @param study * study identifier * @param email * email of participant */ public Builder(String baseUrl, String userAgent, String acceptLanguage, String study, String email) { checkState(!Strings.isNullOrEmpty(baseUrl)); checkState(!Strings.isNullOrEmpty(userAgent)); checkState(!Strings.isNullOrEmpty(study)); checkState(!Strings.isNullOrEmpty(email)); this.baseUrl = baseUrl; this.userAgent = userAgent; this.acceptLanguage = acceptLanguage; this.study = study; this.email = email; } /** * @param password participant's password, if available * @return this builder, for chaining operations */ public Builder withPassword(String password) { this.password = password; return this; } /** * @param session participant's last active session, if available * @return this builder, for chaining operations */ public Builder withSession(UserSessionInfo session) { this.session = session; return this; } public ApiClientProvider build() { checkState(!Strings.isNullOrEmpty(password) || session != null, "requires at least one of password or session"); Retrofit unauthenticatedRetrofit = getRetrofit(getHttpClientBuilder().build()); AuthenticationApi authenticationApi = unauthenticatedRetrofit.create(AuthenticationApi.class); UserSessionInfoProvider sessionProvider = new UserSessionInfoProvider(authenticationApi, study, email, password, session); UserSessionInterceptor sessionInterceptor = new UserSessionInterceptor(sessionProvider); AuthenticationHandler authenticationHandler = new AuthenticationHandler(sessionProvider); OkHttpClient.Builder httpClientBuilder = getHttpClientBuilder(sessionInterceptor, authenticationHandler); httpClientBuilder.authenticator(authenticationHandler); Retrofit authenticatedRetrofit = getRetrofit(httpClientBuilder.build()); return new ApiClientProvider(sessionProvider, unauthenticatedRetrofit, authenticatedRetrofit); } OkHttpClient.Builder getHttpClientBuilder(Interceptor... interceptors) { OkHttpClient.Builder builder = new OkHttpClient.Builder() .connectTimeout(2, TimeUnit.MINUTES) .readTimeout(2, TimeUnit.MINUTES) .writeTimeout(2, TimeUnit.MINUTES); for (Interceptor interceptor : interceptors) { builder.addInterceptor(interceptor); } return builder .addInterceptor(new HeaderInterceptor(userAgent, acceptLanguage)) .addInterceptor(WARNING_INTERCEPTOR) .addInterceptor(ERROR_INTERCEPTOR) .addInterceptor(LOGGING_INTERCEPTOR); } Retrofit getRetrofit(OkHttpClient client) { return new Retrofit.Builder() .baseUrl(baseUrl) .client(client) .addConverterFactory(GsonConverterFactory.create(RestUtils.GSON)) .build(); } } }
rest-client/src/main/java/org/sagebionetworks/bridge/rest/ApiClientProvider.java
package org.sagebionetworks.bridge.rest; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import java.util.concurrent.TimeUnit; import com.google.common.base.Strings; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import org.sagebionetworks.bridge.rest.api.AuthenticationApi; import org.sagebionetworks.bridge.rest.model.ClientInfo; import org.sagebionetworks.bridge.rest.model.SignIn; import org.sagebionetworks.bridge.rest.model.UserSessionInfo; /** * Base class for creating clients that are correctly configured to communicate with the * Bridge server. */ public class ApiClientProvider { private static final Interceptor WARNING_INTERCEPTOR = new WarningHeaderInterceptor(); private static final Interceptor ERROR_INTERCEPTOR = new ErrorResponseInterceptor(); private static final Interceptor LOGGING_INTERCEPTOR = new LoggingInterceptor(); private final UserSessionInfoProvider userSessionInfoProvider; private final LoadingCache<Class<?>, ?> unauthenticatedServices; private final LoadingCache<Class<?>, ?> authenticatedServices; private ApiClientProvider(final UserSessionInfoProvider userSessionInfoProvider, final Retrofit unauthenticatedRetrofit, final Retrofit authenticatedRetrofit) { this.userSessionInfoProvider = userSessionInfoProvider; this.unauthenticatedServices = CacheBuilder.newBuilder() .build(new CacheLoader<Class<?>, Object>() { @Override public Object load(Class<?> serviceClass) { return unauthenticatedRetrofit.create(serviceClass); } }); this.authenticatedServices = CacheBuilder.newBuilder() .build(new CacheLoader<Class<?>, Object>() { @Override public Object load(Class<?> serviceClass) { return authenticatedRetrofit.create(serviceClass); } }); } // To build the ClientManager on this class, we need to have access to the session that is persisted // by the HTTP interceptors. public UserSessionInfoProvider getUserSessionInfoProvider() { return userSessionInfoProvider; } /** * Create an unauthenticated client (this client cannot authenticate automatically, and is only used for * public APIs not requiring a server user to access). * * @param <T> * One of the Api classes in the org.sagebionetworks.bridge.rest.api package. * @param service * Class representing the service * @return service client */ public <T> T getClient(Class<T> service) { checkNotNull(service); //noinspection unchecked return (T) unauthenticatedServices.getUnchecked(service); } /** * @param <T> * One of the Api classes in the org.sagebionetworks.bridge.rest.api package. * @param service * Class representing the service * @param signIn * credentials for the user, or null for an unauthenticated client * @return service client that is authenticated with the user's credentials */ public <T> T getClient(Class<T> service, SignIn signIn) { checkNotNull(service); checkNotNull(signIn); //noinspection unchecked return (T) authenticatedServices.getUnchecked(service); } public static class Builder { private String baseUrl; private String userAgent; private String acceptLanguage; private String study; private String email; private String password; private UserSessionInfo session; /** * Creates a builder for accessing services associated with an environment, study, and participant. * * @param baseUrl base url for Bridge service * @param userAgent * user-agent string in Bridge's expected format, see {@link RestUtils#getUserAgent(ClientInfo)} * @param acceptLanguage * optional comma-separated list of preferred languages for this client (most to least * preferred * @param study * study identifier * @param email * email of participant */ public Builder(String baseUrl, String userAgent, String acceptLanguage, String study, String email) { checkState(!Strings.isNullOrEmpty(baseUrl)); checkState(!Strings.isNullOrEmpty(userAgent)); checkState(!Strings.isNullOrEmpty(study)); checkState(!Strings.isNullOrEmpty(email)); this.baseUrl = baseUrl; this.userAgent = userAgent; this.acceptLanguage = acceptLanguage; this.study = study; this.email = email; } /** * @param password participant's password, if available * @return this builder, for chaining operations */ public Builder withPassword(String password) { this.password = password; return this; } /** * @param session participant's last active session, if available * @return this builder, for chaining operations */ public Builder withSession(UserSessionInfo session) { this.session = session; return this; } public ApiClientProvider build() { checkState(!Strings.isNullOrEmpty(password) || session != null, "requires at least one of password or session"); Retrofit unauthenticatedRetrofit = getRetrofit(getHttpClientBuilder().build()); AuthenticationApi authenticationApi = unauthenticatedRetrofit.create(AuthenticationApi.class); UserSessionInfoProvider sessionProvider = new UserSessionInfoProvider(authenticationApi, study, email, password, session); UserSessionInterceptor sessionInterceptor = new UserSessionInterceptor(sessionProvider); AuthenticationHandler authenticationHandler = new AuthenticationHandler(sessionProvider); OkHttpClient.Builder httpClientBuilder = getHttpClientBuilder(sessionInterceptor, authenticationHandler); httpClientBuilder.authenticator(authenticationHandler); Retrofit authenticatedRetrofit = getRetrofit(httpClientBuilder.build()); return new ApiClientProvider(sessionProvider, unauthenticatedRetrofit, authenticatedRetrofit); } OkHttpClient.Builder getHttpClientBuilder(Interceptor... interceptors) { OkHttpClient.Builder builder = new OkHttpClient.Builder() .connectTimeout(2, TimeUnit.MINUTES) .readTimeout(2, TimeUnit.MINUTES) .writeTimeout(2, TimeUnit.MINUTES); for (Interceptor interceptor : interceptors) { builder.addInterceptor(interceptor); } return builder .addInterceptor(new HeaderInterceptor(userAgent, acceptLanguage)) .addInterceptor(WARNING_INTERCEPTOR) .addInterceptor(ERROR_INTERCEPTOR) .addInterceptor(LOGGING_INTERCEPTOR); } Retrofit getRetrofit(OkHttpClient client) { return new Retrofit.Builder() .baseUrl(baseUrl) .client(client) .addConverterFactory(GsonConverterFactory.create(RestUtils.GSON)) .build(); } } }
Refactor out a Retrofit service loader
rest-client/src/main/java/org/sagebionetworks/bridge/rest/ApiClientProvider.java
Refactor out a Retrofit service loader
<ide><path>est-client/src/main/java/org/sagebionetworks/bridge/rest/ApiClientProvider.java <ide> this.userSessionInfoProvider = userSessionInfoProvider; <ide> <ide> this.unauthenticatedServices = CacheBuilder.newBuilder() <del> .build(new CacheLoader<Class<?>, Object>() { <del> @Override public Object load(Class<?> serviceClass) { <del> return unauthenticatedRetrofit.create(serviceClass); <del> } <del> }); <add> .build(new RetrofitServiceLoader(unauthenticatedRetrofit)); <ide> <ide> this.authenticatedServices = CacheBuilder.newBuilder() <del> .build(new CacheLoader<Class<?>, Object>() { <del> @Override public Object load(Class<?> serviceClass) { <del> return authenticatedRetrofit.create(serviceClass); <del> } <del> }); <add> .build(new RetrofitServiceLoader(authenticatedRetrofit)); <add> } <add> <add> private static class RetrofitServiceLoader extends CacheLoader<Class<?>, Object> { <add> private final Retrofit retrofit; <add> <add> RetrofitServiceLoader(Retrofit retrofit) { <add> this.retrofit = retrofit; <add> } <add> <add> @SuppressWarnings("NullableProblems") // superclass uses nullity-analysis annotations which we are not using <add> @Override public Object load(Class<?> serviceClass) { <add> return retrofit.create(serviceClass); <add> } <ide> } <ide> <ide> // To build the ClientManager on this class, we need to have access to the session that is persisted
JavaScript
mit
1ef5a3e3e17f9d7234388d21e491972d0f6b244b
0
whitef0x0/tellform,whitef0x0/tellform,whitef0x0/medforms,whitef0x0/nodeforms,whitef0x0/nodeforms,whitef0x0/tellform,whitef0x0/nodeforms,whitef0x0/medforms,whitef0x0/medforms
'use strict'; /** * Module dependencies. */ var fs = require('fs-extra'), http = require('http'), https = require('https'), express = require('express'), morgan = require('morgan'), logger = require('./logger'), bodyParser = require('body-parser'), session = require('express-session'), compression = require('compression'), methodOverride = require('method-override'), cookieParser = require('cookie-parser'), helmet = require('helmet'), multer = require('multer'), passport = require('passport'), raven = require('raven'), MongoStore = require('connect-mongo')(session), flash = require('connect-flash'), config = require('./config'), consolidate = require('consolidate'), path = require('path'), device = require('express-device'), client = new raven.Client(config.DSN); module.exports = function(db) { // Initialize express app var app = express(); // Globbing model files config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) { require(path.resolve(modelPath)); }); // Setting application local variables app.locals.google_analytics_id = config.app.google_analytics_id; app.locals.title = config.app.title; app.locals.description = config.app.description; app.locals.keywords = config.app.keywords; app.locals.bowerJSFiles = config.getBowerJSAssets(); app.locals.bowerCssFiles = config.getBowerCSSAssets(); app.locals.bowerOtherFiles = config.getBowerOtherAssets(); app.locals.jsFiles = config.getJavaScriptAssets(); app.locals.cssFiles = config.getCSSAssets(); //Setup Prerender.io app.use(require('prerender-node').set('prerenderToken', process.env.PRERENDER_TOKEN)); // Passing the request url to environment locals app.use(function(req, res, next) { if(config.baseUrl === ''){ config.baseUrl = req.protocol + '://' + req.headers.host; } res.locals.url = req.protocol + '://' + req.headers.host + req.url; next(); }); // Should be placed before express.static app.use(compression({ // only compress files for the following content types filter: function(req, res) { return (/json|text|javascript|css/).test(res.getHeader('Content-Type')); }, // zlib option for compression level level: 3 })); // Showing stack errors app.set('showStackError', true); // Set swig as the template engine app.engine('server.view.html', consolidate[config.templateEngine]); // Set views path and view engine app.set('view engine', 'server.view.html'); app.set('views', './app/views'); // Enable logger (morgan) app.use(morgan(logger.getLogFormat(), logger.getLogOptions())); // Environment dependent middleware if (process.env.NODE_ENV === 'development') { // Disable views cache app.set('view cache', false); } else if (process.env.NODE_ENV === 'production') { app.locals.cache = 'memory'; } // Request body parsing middleware should be above methodOverride app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(methodOverride()); // Use helmet to secure Express headers app.use(helmet.xframe()); app.use(helmet.xssFilter()); app.use(helmet.nosniff()); app.use(helmet.ienoopen()); app.disable('x-powered-by'); // Setting the app router and static folder app.use('/', express.static(path.resolve('./public'))); app.use('/uploads', express.static(path.resolve('./uploads'))); // CookieParser should be above session app.use(cookieParser()); // Express MongoDB session storage app.use(session({ saveUninitialized: true, resave: true, secret: config.sessionSecret, store: new MongoStore({ mongooseConnection: db.connection, collection: config.sessionCollection }), cookie: config.sessionCookie, name: config.sessionName })); // use passport session app.use(passport.initialize()); app.use(passport.session()); // setup express-device app.use(device.capture({ parseUserAgent: true })); // connect flash for flash messages app.use(flash()); // Globbing routing files config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) { require(path.resolve(routePath))(app); }); // Add headers for Sentry /* app.use(function (req, res, next) { // Website you wish to allow to connect res.setHeader('Access-Control-Allow-Origin', 'http://sentry.polydaic.com'); // Request methods you wish to allow res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // Request headers you wish to allow res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // Set to true if you need the website to include cookies in the requests sent // to the API (e.g. in case you use sessions) res.setHeader('Access-Control-Allow-Credentials', true); // Pass to next layer of middleware next(); }); */ // Sentry (Raven) middleware // app.use(raven.middleware.express.requestHandler(config.DSN)); // Should come before any other error middleware // app.use(raven.middleware.express.errorHandler(config.DSN)); // Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc. app.use(function(err, req, res, next) { // If the error object doesn't exists if (!err) return next(); // Log it console.error(err.stack); client.captureError(err); // Error page res.status(500).render('500', { error: err.stack }); }); // Assume 404 since no middleware responded app.use(function(req, res) { client.captureError(new Error('Page Not Found')); res.status(404).render('404', { url: req.originalUrl, error: 'Not Found' }); }); if (process.env.NODE_ENV === 'secure') { // Load SSL key and certificate var privateKey = fs.readFileSync('./config/sslcerts/key.pem', 'utf8'); var certificate = fs.readFileSync('./config/sslcerts/cert.pem', 'utf8'); // Create HTTPS Server var httpsServer = https.createServer({ key: privateKey, cert: certificate }, app); // Return HTTPS server instance return httpsServer; } // Return Express server instance return app; };
config/express.js
'use strict'; /** * Module dependencies. */ var fs = require('fs-extra'), http = require('http'), https = require('https'), express = require('express'), morgan = require('morgan'), logger = require('./logger'), bodyParser = require('body-parser'), session = require('express-session'), compression = require('compression'), methodOverride = require('method-override'), cookieParser = require('cookie-parser'), helmet = require('helmet'), multer = require('multer'), passport = require('passport'), raven = require('raven'), MongoStore = require('connect-mongo')(session), flash = require('connect-flash'), config = require('./config'), consolidate = require('consolidate'), path = require('path'), device = require('express-device'), client = new raven.Client(config.DSN); module.exports = function(db) { // Initialize express app var app = express(); // Globbing model files config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) { require(path.resolve(modelPath)); }); // Setting application local variables app.locals.google_analytics_id = config.app.oogle_analytics_id; app.locals.title = config.app.title; app.locals.description = config.app.description; app.locals.keywords = config.app.keywords; app.locals.bowerJSFiles = config.getBowerJSAssets(); app.locals.bowerCssFiles = config.getBowerCSSAssets(); app.locals.bowerOtherFiles = config.getBowerOtherAssets(); app.locals.jsFiles = config.getJavaScriptAssets(); app.locals.cssFiles = config.getCSSAssets(); //Setup Prerender.io app.use(require('prerender-node').set('prerenderToken', process.env.PRERENDER_TOKEN)); // Passing the request url to environment locals app.use(function(req, res, next) { if(config.baseUrl === ''){ config.baseUrl = req.protocol + '://' + req.headers.host; } res.locals.url = req.protocol + '://' + req.headers.host + req.url; next(); }); // Should be placed before express.static app.use(compression({ // only compress files for the following content types filter: function(req, res) { return (/json|text|javascript|css/).test(res.getHeader('Content-Type')); }, // zlib option for compression level level: 3 })); // Showing stack errors app.set('showStackError', true); // Set swig as the template engine app.engine('server.view.html', consolidate[config.templateEngine]); // Set views path and view engine app.set('view engine', 'server.view.html'); app.set('views', './app/views'); // Enable logger (morgan) app.use(morgan(logger.getLogFormat(), logger.getLogOptions())); // Environment dependent middleware if (process.env.NODE_ENV === 'development') { // Disable views cache app.set('view cache', false); } else if (process.env.NODE_ENV === 'production') { app.locals.cache = 'memory'; } // Request body parsing middleware should be above methodOverride app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(methodOverride()); // Use helmet to secure Express headers app.use(helmet.xframe()); app.use(helmet.xssFilter()); app.use(helmet.nosniff()); app.use(helmet.ienoopen()); app.disable('x-powered-by'); // Setting the app router and static folder app.use('/', express.static(path.resolve('./public'))); app.use('/uploads', express.static(path.resolve('./uploads'))); // CookieParser should be above session app.use(cookieParser()); // Express MongoDB session storage app.use(session({ saveUninitialized: true, resave: true, secret: config.sessionSecret, store: new MongoStore({ mongooseConnection: db.connection, collection: config.sessionCollection }), cookie: config.sessionCookie, name: config.sessionName })); // use passport session app.use(passport.initialize()); app.use(passport.session()); // setup express-device app.use(device.capture({ parseUserAgent: true })); // connect flash for flash messages app.use(flash()); // Globbing routing files config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) { require(path.resolve(routePath))(app); }); // Add headers for Sentry /* app.use(function (req, res, next) { // Website you wish to allow to connect res.setHeader('Access-Control-Allow-Origin', 'http://sentry.polydaic.com'); // Request methods you wish to allow res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // Request headers you wish to allow res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // Set to true if you need the website to include cookies in the requests sent // to the API (e.g. in case you use sessions) res.setHeader('Access-Control-Allow-Credentials', true); // Pass to next layer of middleware next(); }); */ // Sentry (Raven) middleware // app.use(raven.middleware.express.requestHandler(config.DSN)); // Should come before any other error middleware // app.use(raven.middleware.express.errorHandler(config.DSN)); // Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc. app.use(function(err, req, res, next) { // If the error object doesn't exists if (!err) return next(); // Log it console.error(err.stack); client.captureError(err); // Error page res.status(500).render('500', { error: err.stack }); }); // Assume 404 since no middleware responded app.use(function(req, res) { client.captureError(new Error('Page Not Found')); res.status(404).render('404', { url: req.originalUrl, error: 'Not Found' }); }); if (process.env.NODE_ENV === 'secure') { // Load SSL key and certificate var privateKey = fs.readFileSync('./config/sslcerts/key.pem', 'utf8'); var certificate = fs.readFileSync('./config/sslcerts/cert.pem', 'utf8'); // Create HTTPS Server var httpsServer = https.createServer({ key: privateKey, cert: certificate }, app); // Return HTTPS server instance return httpsServer; } // Return Express server instance return app; };
fixed google analytics app.local
config/express.js
fixed google analytics app.local
<ide><path>onfig/express.js <ide> }); <ide> <ide> // Setting application local variables <del> app.locals.google_analytics_id = config.app.oogle_analytics_id; <add> app.locals.google_analytics_id = config.app.google_analytics_id; <ide> app.locals.title = config.app.title; <ide> app.locals.description = config.app.description; <ide> app.locals.keywords = config.app.keywords;
Java
mit
f9508cf568b60437d1c3ac99420adf589b56cfb2
0
Adyen/adyen-java-api-library,Adyen/adyen-java-api-library,Adyen/adyen-java-api-library
/** * ###### * ###### * ############ ####( ###### #####. ###### ############ ############ * ############# #####( ###### #####. ###### ############# ############# * ###### #####( ###### #####. ###### ##### ###### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ###### * ############# ############# ############# ############# ##### ###### * ############ ############ ############# ############ ##### ###### * ###### * ############# * ############ * * Adyen Java API Library * * Copyright (c) 2017 Adyen B.V. * This file is open source and available under the MIT license. * See the LICENSE file for more info. */ package com.adyen.httpclient; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.Map; import java.util.Scanner; import org.apache.commons.codec.binary.Base64; import com.adyen.Client; import com.adyen.Config; public class HttpURLConnectionClient implements ClientInterface { private HttpURLConnection httpConnection; private static final String CHARSET = "UTF-8"; /** * Does a POST request. * config is used to obtain basic auth username, password and User-Agent * * @param requestUrl * @param requestBody * @param config * @return * @throws IOException */ @Override public String request(String requestUrl, String requestBody, Config config) throws IOException, HTTPClientException { String response = createRequest(requestUrl, config.getApplicationName()) .setBasicAuthentication(config.getUsername(), config.getPassword()) .setContentType("application/json") .doPostRequest(requestBody); return response; } private static String getResponseBody(InputStream responseStream) throws IOException { //\A is the beginning of the stream boundary Scanner scanner = new Scanner(responseStream, CHARSET); String rBody = scanner.useDelimiter("\\A").next(); scanner.close(); responseStream.close(); return rBody; } /** * Does a POST request with HTTP key-value pairs * * @param requestUrl * @param params * @param config * @return * @throws IOException * @throws HTTPClientException */ @Override public String post(String requestUrl, Map<String, String> params, Config config) throws IOException, HTTPClientException { String postQuery = getQuery(params); String response = createRequest(requestUrl, config.getApplicationName()) .doPostRequest(postQuery); return response; } /** * Get HTTP querystring from Map<String,String> * * @param params * @return * @throws UnsupportedEncodingException */ private String getQuery(Map<String, String> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; for (Map.Entry<String, String> pair : params.entrySet()) { if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(pair.getKey(), CHARSET)); result.append("="); result.append(URLEncoder.encode(pair.getValue(), CHARSET)); } return result.toString(); } /** * Initialize the httpConnection * * @param requestUrl * @param applicationName * @return * @throws IOException */ private HttpURLConnectionClient createRequest(String requestUrl, String applicationName) throws IOException { URL targetUrl = new URL(requestUrl); // set configurations httpConnection = (HttpURLConnection) targetUrl.openConnection(); httpConnection.setUseCaches(false); httpConnection.setDoOutput(true); httpConnection.setRequestMethod("POST"); httpConnection.setRequestProperty("Accept-Charset", CHARSET); httpConnection.setRequestProperty("User-Agent", String.format("%s %s%s", applicationName, Client.USER_AGENT_SUFFIX, Client.LIB_VERSION)); return this; } /** * Adds Basic Authentication headers * * @param username * @param password * @return */ private HttpURLConnectionClient setBasicAuthentication(String username, String password) { // set basic authentication String authString = username + ":" + password; byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); httpConnection.setRequestProperty("Authorization", "Basic " + authStringEnc); return this; } /** * Sets content type * * @param contentType * @return */ private HttpURLConnectionClient setContentType(String contentType) { httpConnection.setRequestProperty("Content-Type", contentType); return this; } /** * Does a POST request with raw body * * @param requestBody * @return * @throws IOException * @throws HTTPClientException */ private String doPostRequest(String requestBody) throws IOException, HTTPClientException { String response = null; OutputStream outputStream = httpConnection.getOutputStream(); outputStream.write(requestBody.getBytes()); outputStream.flush(); int responseCode = httpConnection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { //Read the response from the error stream if(httpConnection.getErrorStream() != null) { response = getResponseBody(httpConnection.getErrorStream()); } HTTPClientException httpClientException = new HTTPClientException( responseCode, "HTTP Exception", httpConnection.getHeaderFields(), response ); throw httpClientException; } //InputStream is only available on successful requests >= 200 <400 response = getResponseBody(httpConnection.getInputStream()); // close the connection httpConnection.disconnect(); return response; } }
src/main/java/com/adyen/httpclient/HttpURLConnectionClient.java
/** * ###### * ###### * ############ ####( ###### #####. ###### ############ ############ * ############# #####( ###### #####. ###### ############# ############# * ###### #####( ###### #####. ###### ##### ###### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ###### * ############# ############# ############# ############# ##### ###### * ############ ############ ############# ############ ##### ###### * ###### * ############# * ############ * * Adyen Java API Library * * Copyright (c) 2017 Adyen B.V. * This file is open source and available under the MIT license. * See the LICENSE file for more info. */ package com.adyen.httpclient; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.Map; import java.util.Scanner; import org.apache.commons.codec.binary.Base64; import com.adyen.Client; import com.adyen.Config; public class HttpURLConnectionClient implements ClientInterface { private HttpURLConnection httpConnection; private static final String CHARSET = "UTF-8"; /** * Does a POST request. * config is used to obtain basic auth username, password and User-Agent * * @param requestUrl * @param requestBody * @param config * @return * @throws IOException */ @Override public String request(String requestUrl, String requestBody, Config config) throws IOException, HTTPClientException { String response = createRequest(requestUrl, config.getApplicationName()) .setBasicAuthentication(config.getUsername(), config.getPassword()) .setContentType("application/json") .doPostRequest(requestBody); return response; } private static String getResponseBody(InputStream responseStream) throws IOException { //\A is the beginning of the stream boundary Scanner scanner = new Scanner(responseStream, CHARSET); scanner.useDelimiter("\\A"); String rBody = scanner.useDelimiter("\\A").next(); scanner.close(); responseStream.close(); return rBody; } /** * Does a POST request with HTTP key-value pairs * * @param requestUrl * @param params * @param config * @return * @throws IOException * @throws HTTPClientException */ @Override public String post(String requestUrl, Map<String, String> params, Config config) throws IOException, HTTPClientException { String postQuery = getQuery(params); String response = createRequest(requestUrl, config.getApplicationName()) .doPostRequest(postQuery); return response; } /** * Get HTTP querystring from Map<String,String> * * @param params * @return * @throws UnsupportedEncodingException */ private String getQuery(Map<String, String> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; for (Map.Entry<String, String> pair : params.entrySet()) { if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(pair.getKey(), CHARSET)); result.append("="); result.append(URLEncoder.encode(pair.getValue(), CHARSET)); } return result.toString(); } /** * Initialize the httpConnection * * @param requestUrl * @param applicationName * @return * @throws IOException */ private HttpURLConnectionClient createRequest(String requestUrl, String applicationName) throws IOException { URL targetUrl = new URL(requestUrl); // set configurations httpConnection = (HttpURLConnection) targetUrl.openConnection(); httpConnection.setUseCaches(false); httpConnection.setDoOutput(true); httpConnection.setRequestMethod("POST"); httpConnection.setRequestProperty("Accept-Charset", CHARSET); httpConnection.setRequestProperty("User-Agent", String.format("%s %s%s", applicationName, Client.USER_AGENT_SUFFIX, Client.LIB_VERSION)); return this; } /** * Adds Basic Authentication headers * * @param username * @param password * @return */ private HttpURLConnectionClient setBasicAuthentication(String username, String password) { // set basic authentication String authString = username + ":" + password; byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); httpConnection.setRequestProperty("Authorization", "Basic " + authStringEnc); return this; } /** * Sets content type * * @param contentType * @return */ private HttpURLConnectionClient setContentType(String contentType) { httpConnection.setRequestProperty("Content-Type", contentType); return this; } /** * Does a POST request with raw body * * @param requestBody * @return * @throws IOException * @throws HTTPClientException */ private String doPostRequest(String requestBody) throws IOException, HTTPClientException { String response = null; OutputStream outputStream = httpConnection.getOutputStream(); outputStream.write(requestBody.getBytes()); outputStream.flush(); int responseCode = httpConnection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { //Read the response from the error stream if(httpConnection.getErrorStream() != null) { response = getResponseBody(httpConnection.getErrorStream()); } HTTPClientException httpClientException = new HTTPClientException( responseCode, "HTTP Exception", httpConnection.getHeaderFields(), response ); throw httpClientException; } //InputStream is only available on successful requests >= 200 <400 response = getResponseBody(httpConnection.getInputStream()); // close the connection httpConnection.disconnect(); return response; } }
[issue-51]: HttpURLConnectionClient line fix
src/main/java/com/adyen/httpclient/HttpURLConnectionClient.java
[issue-51]: HttpURLConnectionClient line fix
<ide><path>rc/main/java/com/adyen/httpclient/HttpURLConnectionClient.java <ide> throws IOException { <ide> //\A is the beginning of the stream boundary <ide> Scanner scanner = new Scanner(responseStream, CHARSET); <del> scanner.useDelimiter("\\A"); <ide> String rBody = scanner.useDelimiter("\\A").next(); <ide> scanner.close(); <ide> responseStream.close();
Java
mit
d5dfe0e0aa819456def90184682ac03ab5e43539
0
remigourdon/sound-editors
package framework; import java.util.ArrayList; import java.util.Observable; import framework.generators.Generator; import framework.editors.SoundEditor; import framework.views.View; import framework.modifiers.Modifier; /** * Represents a sound entity. * * A sound is represented basically by a frequency and a duration. * The basic wave is synthetised using a generator object. * It is the core of the model in our MVC design pattern implementation. */ public class Sound extends Observable { /** * Creates a Sound object. * @param g the generator to be used * @param f the frequency of the signal * @param d the duration of the sound * @param a the amplitude of the sound */ public Sound(Generator g, Double f, Double d, Double a) { generator = g; frequency = f; duration = d; amplitude = a; modifiers = new ArrayList<Modifier>(); generateSignal(); } /** * Generate the signal data from the basic wave. */ public void generateSignal() { Double[] signal = generator.generate(frequency, duration, amplitude); data = signal; applyModifiers(modifiers); setChanged(); notifyObservers(true); // Signal to observers that the data has changed } /** * Attach a new SoundEditor to the Sound object. * @return the SoundEditor newly attached */ public SoundEditor attachEditor() { SoundEditor editor = new SoundEditor(this); addObserver(editor); return editor; } /** * Attach a new View to the Sound object. * @param v the View to be attached */ public void attachView(View v) { addObserver(v); } /** * Add a new Modifier to the Sound object. * @param m the Modifier to be added */ public void addModfier(Modifier m) { modifiers.add(m); } /** * Apply a list of modifiers to the Sound object. * @param ms the list of modifiers to be applied */ public void applyModifiers(ArrayList<Modifier> ms) { Double[] newData = data; for(Modifier m : ms) { newData = m.apply(newData); } data = newData; } /** * Get the frequency of the Sound. * @return the frequency in hertz */ public Double getFrequency() { return frequency; } /** * Set the frequency of the Sound. * @param f the new frequency in hertz */ public void setFrequency(Double f) { if(f >= 0 && f != frequency) { frequency = f; generateSignal(); } else { setChanged(); notifyObservers(false); } } /** * Get the duration of the Sound. * @return the duration in seconds */ public Double getDuration() { return duration; } /** * Set the duration of the Sound. * @param d the new duration in seconds */ public void setDuration(Double d) { if(d >= 0 && d != duration) { duration = d; generateSignal(); } else { setChanged(); notifyObservers(false); } } /** * Get the amplitude of the Sound. * @return the amplitude */ public Double getAmplitude() { return amplitude; } /** * Set the amplitude of the Sound. * @param a the new amplitude */ public void setAmplitude(Double a) { if(a >= 0 && a != amplitude) { amplitude = a; generateSignal(); } else { setChanged(); notifyObservers(false); } } /** * Get the generator of the Sound. * @return the generator */ public Generator getGenerator() { return generator; } /** * Set the generator of the Sound * @param g the new generator */ public void setGenerator(Generator g) { generator = g; generateSignal(); } /** * Get the data of the Sound. * @return the data as an array of Doubles */ public Double[] getData() { return data; } private Generator generator; private Double frequency; // Hertzs private Double duration; // Seconds private Double amplitude; private Double[] data; private ArrayList<Modifier> modifiers; }
framework/Sound.java
package framework; import java.util.ArrayList; import java.util.Observable; import framework.generators.Generator; import framework.editors.SoundEditor; import framework.views.View; import framework.modifiers.Modifier; /** * Represents a sound entity. * * A sound is represented basically by a frequency and a duration. * The basic wave is synthetised using a generator object. * It is the core of the model in our MVC design pattern implementation. */ public class Sound extends Observable { /** * Creates a Sound object. * @param g the generator to be used * @param f the frequency of the signal * @param d the duration of the sound * @param a the amplitude of the sound */ public Sound(Generator g, Double f, Double d, Double a) { generator = g; frequency = f; duration = d; amplitude = a; modifiers = new ArrayList<Modifier>(); generateSignal(); } /** * Generate the signal data from the basic wave. */ public void generateSignal() { Double[] signal = generator.generate(frequency, duration, amplitude); data = signal; setChanged(); notifyObservers(true); // Signal to observers that the data has changed } /** * Attach a new SoundEditor to the Sound object. * @return the SoundEditor newly attached */ public SoundEditor attachEditor() { SoundEditor editor = new SoundEditor(this); addObserver(editor); return editor; } /** * Attach a new View to the Sound object. * @param v the View to be attached */ public void attachView(View v) { addObserver(v); } /** * Add a new Modifier to the Sound object. * @param m the Modifier to be added */ public void addModfier(Modifier m) { modifiers.add(m); } /** * Get the frequency of the Sound. * @return the frequency in hertz */ public Double getFrequency() { return frequency; } /** * Set the frequency of the Sound. * @param f the new frequency in hertz */ public void setFrequency(Double f) { if(f >= 0 && f != frequency) { frequency = f; generateSignal(); } else { setChanged(); notifyObservers(false); } } /** * Get the duration of the Sound. * @return the duration in seconds */ public Double getDuration() { return duration; } /** * Set the duration of the Sound. * @param d the new duration in seconds */ public void setDuration(Double d) { if(d >= 0 && d != duration) { duration = d; generateSignal(); } else { setChanged(); notifyObservers(false); } } /** * Get the amplitude of the Sound. * @return the amplitude */ public Double getAmplitude() { return amplitude; } /** * Set the amplitude of the Sound. * @param a the new amplitude */ public void setAmplitude(Double a) { if(a >= 0 && a != amplitude) { amplitude = a; generateSignal(); } else { setChanged(); notifyObservers(false); } } /** * Get the generator of the Sound. * @return the generator */ public Generator getGenerator() { return generator; } /** * Set the generator of the Sound * @param g the new generator */ public void setGenerator(Generator g) { generator = g; generateSignal(); } /** * Get the data of the Sound. * @return the data as an array of Doubles */ public Double[] getData() { return data; } private Generator generator; private Double frequency; // Hertzs private Double duration; // Seconds private Double amplitude; private Double[] data; private ArrayList<Modifier> modifiers; }
Add function applyModifiers and use it in generateSignal.
framework/Sound.java
Add function applyModifiers and use it in generateSignal.
<ide><path>ramework/Sound.java <ide> <ide> data = signal; <ide> <add> applyModifiers(modifiers); <add> <ide> setChanged(); <ide> notifyObservers(true); // Signal to observers that the data has changed <ide> } <ide> */ <ide> public void addModfier(Modifier m) { <ide> modifiers.add(m); <add> } <add> <add> /** <add> * Apply a list of modifiers to the Sound object. <add> * @param ms the list of modifiers to be applied <add> */ <add> public void applyModifiers(ArrayList<Modifier> ms) { <add> Double[] newData = data; <add> for(Modifier m : ms) { <add> newData = m.apply(newData); <add> } <add> data = newData; <ide> } <ide> <ide> /**
JavaScript
mit
4ff3f71afdbb485eddc1f3c5a26d39ef6fd0a3fa
0
HexChronicle/Fwibble,HexChronicle/Fwibble
app/components/index/Index.js
var React = require('react'); module.exports = React.createClass({ render: function() { return ( <div> </div> ) } })
Removed Index.js and index component
app/components/index/Index.js
Removed Index.js and index component
<ide><path>pp/components/index/Index.js <del>var React = require('react'); <del> <del>module.exports = React.createClass({ <del> render: function() { <del> return ( <del> <div> <del> </div> <del> ) <del> } <del>})
Java
mit
207418a595262cde89ff4095c77eb07386677410
0
shamoh/mega-examples
package cz.kramolis.mega.examples.helloworld; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.event.Observes; import cz.kramolis.mega.runtime.Context; import cz.kramolis.mega.runtime.Environment; @ApplicationScoped public class HelloWorldApp implements Context { private void onEnvironmentAvailable(@Observes Environment environment) { if (environment.getArgs().size() > 0) { for (String name : environment.getArgs()) { System.out.println("Hello " + name + "!"); } } else { System.out.println("Hello World!"); } environment.shutdown(); } }
hello-world/src/main/java/cz/kramolis/mega/examples/helloworld/HelloWorldApp.java
package cz.kramolis.mega.examples.helloworld; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.event.Observes; import cz.kramolis.mega.runtime.Context; import cz.kramolis.mega.runtime.Environment; @ApplicationScoped public class HelloWorldApp implements Context { private void onEnvironmentAvailable(@Observes Environment environment) { if (environment.getArgs().size() > 0) { for (String name : environment.getArgs()) { System.out.println("Hello " + name + "!"); } } else { System.out.println("Hello World!"); } environment.shutdown(); }
Fixing problem.
hello-world/src/main/java/cz/kramolis/mega/examples/helloworld/HelloWorldApp.java
Fixing problem.
<ide><path>ello-world/src/main/java/cz/kramolis/mega/examples/helloworld/HelloWorldApp.java <ide> environment.shutdown(); <ide> } <ide> <add>}
Java
apache-2.0
66c70b211edb25b5c98fe345e8746ae147717c68
0
zhic5352/robotium,hypest/robotium,shibenli/robotium,NetEase/robotium,lczgywzyy/robotium,RobotiumTech/robotium,hypest/robotium,RobotiumTech/robotium,luohaoyu/robotium,acanta2014/robotium,XRacoon/robotiumEx,Eva1123/robotium,luohaoyu/robotium,lczgywzyy/robotium,MattGong/robotium,Eva1123/robotium,darker50/robotium,shibenli/robotium,lgs3137/robotium,NetEase/robotium,zhic5352/robotium,acanta2014/robotium,MattGong/robotium,darker50/robotium,pefilekill/robotiumCode,XRacoon/robotiumEx,pefilekill/robotiumCode,lgs3137/robotium
package com.jayway.android.robotium.solo; import java.util.ArrayList; import android.app.Activity; import android.app.Instrumentation; import android.content.pm.ActivityInfo; import android.view.KeyEvent; import android.view.View; import android.widget.AbsListView; import android.widget.Button; import android.widget.CheckBox; import android.widget.CheckedTextView; import android.widget.CompoundButton; import android.widget.DatePicker; import android.widget.EditText; import android.widget.GridView; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RadioButton; import android.widget.ScrollView; import android.widget.SlidingDrawer; import android.widget.Spinner; import android.widget.TextView; import android.widget.ListView; import android.widget.TimePicker; import android.widget.ToggleButton; import android.app.Instrumentation.ActivityMonitor; /** * Contains all the methods that the sub-classes have. It supports test * cases that span over multiple activities. * * Robotium has full support for Activities, Dialogs, Toasts, Menus and Context Menus. * * When writing tests there is no need to plan for or expect new activities in the test case. * All is handled automatically by Robotium-Solo. Robotium-Solo can be used in conjunction with * ActivityInstrumentationTestCase2. The test cases are written from a user * perspective were technical details are not needed. * * * Example of usage (test case spanning over multiple activities): * * <pre> * * public void setUp() throws Exception { * solo = new Solo(getInstrumentation(), getActivity()); * } * * public void testTextShows() throws Exception { * * solo.clickOnText(&quot;Categories&quot;); * solo.clickOnText(&quot;Other&quot;); * solo.clickOnButton(&quot;Edit&quot;); * solo.searchText(&quot;Edit Window&quot;); * solo.clickOnButton(&quot;Commit&quot;); * assertTrue(solo.searchText(&quot;Changes have been made successfully&quot;)); * } * * </pre> * * * @author Renas Reda, [email protected] * */ public class Solo { protected final Asserter asserter; protected final ViewFetcher viewFetcher; protected final Checker checker; protected final Clicker clicker; protected final Presser presser; protected final Searcher searcher; protected final ActivityUtils activityUtils; protected final DialogUtils dialogUtils; protected final TextEnterer textEnterer; protected final Scroller scroller; protected final RobotiumUtils robotiumUtils; protected final Sleeper sleeper; protected final Waiter waiter; protected final Setter setter; protected final Getter getter; protected final int TIMEOUT = 20000; protected final int SMALLTIMEOUT = 10000; public final static int LANDSCAPE = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; // 0 public final static int PORTRAIT = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; // 1 public final static int RIGHT = KeyEvent.KEYCODE_DPAD_RIGHT; public final static int LEFT = KeyEvent.KEYCODE_DPAD_LEFT; public final static int UP = KeyEvent.KEYCODE_DPAD_UP; public final static int DOWN = KeyEvent.KEYCODE_DPAD_DOWN; public final static int ENTER = KeyEvent.KEYCODE_ENTER; public final static int MENU = KeyEvent.KEYCODE_MENU; public final static int DELETE = KeyEvent.KEYCODE_DEL; public final static int CLOSED = 0; public final static int OPENED = 1; /** * Constructor that takes in the instrumentation and the start activity. * * @param instrumentation the {@link Instrumentation} instance * @param activity the start {@link Activity} or {@code null} * if no start activity is provided * */ public Solo(Instrumentation instrumentation, Activity activity) { this.sleeper = new Sleeper(); this.activityUtils = new ActivityUtils(instrumentation, activity, sleeper); this.viewFetcher = new ViewFetcher(activityUtils); this.dialogUtils = new DialogUtils(viewFetcher, sleeper); this.scroller = new Scroller(instrumentation, activityUtils, viewFetcher, sleeper); this.searcher = new Searcher(viewFetcher, scroller, sleeper); this.waiter = new Waiter(activityUtils, viewFetcher, searcher,scroller, sleeper); this.setter = new Setter(activityUtils); this.getter = new Getter(activityUtils, viewFetcher, waiter); this.asserter = new Asserter(activityUtils, waiter); this.checker = new Checker(viewFetcher, waiter); this.robotiumUtils = new RobotiumUtils(instrumentation,activityUtils, sleeper); this.clicker = new Clicker(activityUtils, viewFetcher, scroller,robotiumUtils, instrumentation, sleeper, waiter); this.presser = new Presser(clicker, instrumentation, sleeper, waiter); this.textEnterer = new TextEnterer(instrumentation, activityUtils, clicker); } /** * Constructor that takes in the instrumentation. * * @param instrumentation the {@link Instrumentation} instance * */ public Solo(Instrumentation instrumentation) { this(instrumentation, null); } /** * Returns the ActivityMonitor used by Robotium. * * @return the ActivityMonitor used by Robotium */ public ActivityMonitor getActivityMonitor(){ return activityUtils.getActivityMonitor(); } /** * Returns an ArrayList of all the View objects located in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link View} objects located in the focused window * */ public ArrayList<View> getViews() { try { return viewFetcher.getViews(null, false); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Returns an ArrayList of the View objects contained in the parent View. * * @param parent the parent view from which to return the views * @return an {@code ArrayList} of the {@link View} objects contained in the given {@code View} * */ public ArrayList<View> getViews(View parent) { try { return viewFetcher.getViews(parent, false); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Returns the absolute top parent View for a given View. * * @param view the {@link View} whose top parent is requested * @return the top parent {@link View} * */ public View getTopParent(View view) { View topParent = viewFetcher.getTopParent(view); return topParent; } /** * Waits for a text to be shown. Default timeout is 20 seconds. * * @param text the text to wait for * @return {@code true} if text is shown and {@code false} if it is not shown before the timeout * */ public boolean waitForText(String text) { return waiter.waitForText(text); } /** * Waits for a text to be shown. * * @param text the text to wait for * @param minimumNumberOfMatches the minimum number of matches that are expected to be shown. {@code 0} means any number of matches * @param timeout the the amount of time in milliseconds to wait * @return {@code true} if text is shown and {@code false} if it is not shown before the timeout * */ public boolean waitForText(String text, int minimumNumberOfMatches, long timeout) { return waiter.waitForText(text, minimumNumberOfMatches, timeout); } /** * Waits for a text to be shown. * * @param text the text to wait for * @param minimumNumberOfMatches the minimum number of matches that are expected to be shown. {@code 0} means any number of matches * @param timeout the the amount of time in milliseconds to wait * @param scroll {@code true} if scrolling should be performed * @return {@code true} if text is shown and {@code false} if it is not shown before the timeout * */ public boolean waitForText(String text, int minimumNumberOfMatches, long timeout, boolean scroll) { return waiter.waitForText(text, minimumNumberOfMatches, timeout, scroll); } /** * Waits for a text to be shown. * * @param text the text to wait for * @param minimumNumberOfMatches the minimum number of matches that are expected to be shown. {@code 0} means any number of matches * @param timeout the the amount of time in milliseconds to wait * @param scroll {@code true} if scrolling should be performed * @param onlyVisible {@code true} if only visible text views should be waited for * @return {@code true} if text is shown and {@code false} if it is not shown before the timeout * */ public boolean waitForText(String text, int minimumNumberOfMatches, long timeout, boolean scroll, boolean onlyVisible) { return waiter.waitForText(text, minimumNumberOfMatches, timeout, scroll, onlyVisible); } /** * Waits for a View of a certain class to be shown. Default timeout is 20 seconds. * * @param viewClass the {@link View} class to wait for */ public <T extends View> boolean waitForView(final Class<T> viewClass){ return waiter.waitForView(viewClass, 0, TIMEOUT, true); } /** * Waits for a given View to be shown. Default timeout is 20 seconds. * * @param view the {@link View} object to wait for * * @return {@code true} if view is shown and {@code false} if it is not shown before the timeout */ public <T extends View> boolean waitForView(View view){ return waiter.waitForView(view); } /** * Waits for a given View to be shown. * * @param view the {@link View} object to wait for * @param timeout the amount of time in milliseconds to wait * @param scroll {@code true} if scrolling should be performed * * @return {@code true} if view is shown and {@code false} if it is not shown before the timeout */ public <T extends View> boolean waitForView(View view, int timeout, boolean scroll){ return waiter.waitForView(view, timeout, scroll); } /** * Waits for a View of a certain class to be shown. * * @param viewClass the {@link View} class to wait for * @param minimumNumberOfMatches the minimum number of matches that are expected to be shown. {@code 0} means any number of matches * @param timeout the amount of time in milliseconds to wait * @return {@code true} if view is shown and {@code false} if it is not shown before the timeout */ public <T extends View> boolean waitForView(final Class<T> viewClass, final int minimumNumberOfMatches, final int timeout){ int index = minimumNumberOfMatches-1; if(index < 1) index = 0; return waiter.waitForView(viewClass, index, timeout, true); } /** * Waits for a View of a certain class to be shown. * * @param viewClass the {@link View} class to wait for * @param minimumNumberOfMatches the minimum number of matches that are expected to be shown. {@code 0} means any number of matches * @param timeout the amount of time in milliseconds to wait * @param scroll {@code true} if scrolling should be performed * @return {@code true} if the {@link View} is shown and {@code false} if it is not shown before the timeout */ public <T extends View> boolean waitForView(final Class<T> viewClass, final int minimumNumberOfMatches, final int timeout,final boolean scroll){ int index = minimumNumberOfMatches-1; if(index < 1) index = 0; return waiter.waitForView(viewClass, index, timeout, scroll); } /** * Searches for a text string in the EditText objects currently shown and returns true if found. Will automatically scroll when needed. * * @param text the text to search for * @return {@code true} if an {@link EditText} with the given text is found or {@code false} if it is not found * */ public boolean searchEditText(String text) { return searcher.searchWithTimeoutFor(EditText.class, text, 1, true, false); } /** * Searches for a Button with the given text string and returns true if at least one Button * is found. Will automatically scroll when needed. * * @param text the text to search for. The parameter will be interpreted as a regular expression * @return {@code true} if a {@link Button} with the given text is found and {@code false} if it is not found * */ public boolean searchButton(String text) { return searcher.searchWithTimeoutFor(Button.class, text, 0, true, false); } /** * Searches for a Button with the given text string and returns true if at least one Button * is found. Will automatically scroll when needed. * * @param text the text to search for. The parameter will be interpreted as a regular expression * @param onlyVisible {@code true} if only {@link Button} visible on the screen should be searched * @return {@code true} if a {@link Button} with the given text is found and {@code false} if it is not found * */ public boolean searchButton(String text, boolean onlyVisible) { return searcher.searchWithTimeoutFor(Button.class, text, 0, true, onlyVisible); } /** * Searches for a ToggleButton with the given text string and returns {@code true} if at least one ToggleButton * is found. Will automatically scroll when needed. * * @param text the text to search for. The parameter will be interpreted as a regular expression * @return {@code true} if a {@link ToggleButton} with the given text is found and {@code false} if it is not found * */ public boolean searchToggleButton(String text) { return searcher.searchWithTimeoutFor(ToggleButton.class, text, 0, true, false); } /** * Searches for a Button with the given text string and returns {@code true} if the * searched Button is found a given number of times. Will automatically scroll when needed. * * @param text the text to search for. The parameter will be interpreted as a regular expression * @param minimumNumberOfMatches the minimum number of matches expected to be found. {@code 0} matches means that one or more * matches are expected to be found * @return {@code true} if a {@link Button} with the given text is found a given number of times and {@code false} * if it is not found * */ public boolean searchButton(String text, int minimumNumberOfMatches) { return searcher.searchWithTimeoutFor(Button.class, text, minimumNumberOfMatches, true, false); } /** * Searches for a Button with the given text string and returns {@code true} if the * searched Button is found a given number of times. Will automatically scroll when needed. * * @param text the text to search for. The parameter will be interpreted as a regular expression * @param minimumNumberOfMatches the minimum number of matches expected to be found. {@code 0} matches means that one or more * matches are expected to be found * @param onlyVisible {@code true} if only {@link Button} visible on the screen should be searched * @return {@code true} if a {@link Button} with the given text is found a given number of times and {@code false} * if it is not found * */ public boolean searchButton(String text, int minimumNumberOfMatches, boolean onlyVisible) { return searcher.searchWithTimeoutFor(Button.class, text, minimumNumberOfMatches, true, onlyVisible); } /** * Searches for a ToggleButton with the given text string and returns {@code true} if the * searched ToggleButton is found a given number of times. Will automatically scroll when needed. * * @param text the text to search for. The parameter will be interpreted as a regular expression * @param minimumNumberOfMatches the minimum number of matches expected to be found. {@code 0} matches means that one or more * matches are expected to be found * @return {@code true} if a {@link ToggleButton} with the given text is found a given number of times and {@code false} * if it is not found * */ public boolean searchToggleButton(String text, int minimumNumberOfMatches) { return searcher.searchWithTimeoutFor(ToggleButton.class, text, minimumNumberOfMatches, true, false); } /** * Searches for a text string and returns {@code true} if at least one item * is found with the expected text. Will automatically scroll when needed. * * @param text the text to search for. The parameter will be interpreted as a regular expression * @return {@code true} if the search string is found and {@code false} if it is not found * */ public boolean searchText(String text) { return searcher.searchWithTimeoutFor(TextView.class, text, 0, true, false); } /** * Searches for a text string and returns {@code true} if at least one item * is found with the expected text. Will automatically scroll when needed. * * @param text the text to search for. The parameter will be interpreted as a regular expression * @param onlyVisible {@code true} if only texts visible on the screen should be searched * @return {@code true} if the search string is found and {@code false} if it is not found * */ public boolean searchText(String text, boolean onlyVisible) { return searcher.searchWithTimeoutFor(TextView.class, text, 0, true, onlyVisible); } /** * Searches for a text string and returns {@code true} if the searched text is found a given * number of times. Will automatically scroll when needed. * * @param text the text to search for. The parameter will be interpreted as a regular expression * @param minimumNumberOfMatches the minimum number of matches expected to be found. {@code 0} matches means that one or more * matches are expected to be found * @return {@code true} if text string is found a given number of times and {@code false} if the text string * is not found * */ public boolean searchText(String text, int minimumNumberOfMatches) { return searcher.searchWithTimeoutFor(TextView.class, text, minimumNumberOfMatches, true, false); } /** * Searches for a text string and returns {@code true} if the searched text is found a given * number of times. * * @param text the text to search for. The parameter will be interpreted as a regular expression. * @param minimumNumberOfMatches the minimum number of matches expected to be found. {@code 0} matches means that one or more * matches are expected to be found * @param scroll {@code true} if scrolling should be performed * @return {@code true} if text string is found a given number of times and {@code false} if the text string * is not found * */ public boolean searchText(String text, int minimumNumberOfMatches, boolean scroll) { return searcher.searchWithTimeoutFor(TextView.class, text, minimumNumberOfMatches, scroll, false); } /** * Searches for a text string and returns {@code true} if the searched text is found a given * number of times. * * @param text the text to search for. The parameter will be interpreted as a regular expression. * @param minimumNumberOfMatches the minimum number of matches expected to be found. {@code 0} matches means that one or more * matches are expected to be found * @param scroll {@code true} if scrolling should be performed * @param onlyVisible {@code true} if only texts visible on the screen should be searched * @return {@code true} if text string is found a given number of times and {@code false} if the text string * is not found * */ public boolean searchText(String text, int minimumNumberOfMatches, boolean scroll, boolean onlyVisible) { return searcher.searchWithTimeoutFor(TextView.class, text, minimumNumberOfMatches, scroll, onlyVisible); } /** * Sets the Orientation (Landscape/Portrait) for the current activity. * * @param orientation the orientation to be set. <code>Solo.</code>{@link #LANDSCAPE} for landscape or * <code>Solo.</code>{@link #PORTRAIT} for portrait. * */ public void setActivityOrientation(int orientation) { activityUtils.setActivityOrientation(orientation); } /** * Returns an ArrayList of all the opened/active activities. * * @return an ArrayList of all the opened/active activities * */ public ArrayList<Activity> getAllOpenedActivities() { return activityUtils.getAllOpenedActivities(); } /** * Returns the current Activity. * * @return the current Activity * */ public Activity getCurrentActivity() { return activityUtils.getCurrentActivity(false); } /** * Asserts that the expected Activity is the currently active one. * * @param message the message that should be displayed if the assert fails * @param name the name of the {@link Activity} that is expected to be active e.g. {@code "MyActivity"} * */ public void assertCurrentActivity(String message, String name) { asserter.assertCurrentActivity(message, name); } /** * Asserts that the expected Activity is the currently active one. * * @param message the message that should be displayed if the assert fails * @param expectedClass the {@code Class} object that is expected to be active e.g. {@code MyActivity.class} * */ @SuppressWarnings("unchecked") public void assertCurrentActivity(String message, @SuppressWarnings("rawtypes") Class expectedClass) { asserter.assertCurrentActivity(message, expectedClass); } /** * Asserts that the expected Activity is the currently active one, with the possibility to * verify that the expected Activity is a new instance of the Activity. * * @param message the message that should be displayed if the assert fails * @param name the name of the activity that is expected to be active e.g. {@code "MyActivity"} * @param isNewInstance {@code true} if the expected {@link Activity} is a new instance of the {@link Activity} * */ public void assertCurrentActivity(String message, String name, boolean isNewInstance) { asserter.assertCurrentActivity(message, name, isNewInstance); } /** * Asserts that the expected Activity is the currently active one, with the possibility to * verify that the expected Activity is a new instance of the Activity. * * @param message the message that should be displayed if the assert fails * @param expectedClass the {@code Class} object that is expected to be active e.g. {@code MyActivity.class} * @param isNewInstance {@code true} if the expected {@link Activity} is a new instance of the {@link Activity} * */ @SuppressWarnings("unchecked") public void assertCurrentActivity(String message, @SuppressWarnings("rawtypes") Class expectedClass, boolean isNewInstance) { asserter.assertCurrentActivity(message, expectedClass, isNewInstance); } /** * Asserts that the available memory in the system is not low. * */ public void assertMemoryNotLow() { asserter.assertMemoryNotLow(); } /** * Waits for a Dialog to close. * * @param timeout the amount of time in milliseconds to wait * @return {@code true} if the {@link android.app.Dialog} is closed before the timeout and {@code false} if it is not closed * */ public boolean waitForDialogToClose(long timeout) { return dialogUtils.waitForDialogToClose(timeout); } /** * Simulates pressing the hardware back key. * */ public void goBack() { robotiumUtils.goBack(); } /** * Clicks on a given coordinate on the screen. * * @param x the x coordinate * @param y the y coordinate * */ public void clickOnScreen(float x, float y) { sleeper.sleep(); clicker.clickOnScreen(x, y); } /** * Long clicks a given coordinate on the screen. * * @param x the x coordinate * @param y the y coordinate * */ public void clickLongOnScreen(float x, float y) { clicker.clickLongOnScreen(x, y, 0); } /** * Long clicks a given coordinate on the screen for a given amount of time. * * @param x the x coordinate * @param y the y coordinate * @param time the amount of time to long click * */ public void clickLongOnScreen(float x, float y, int time) { clicker.clickLongOnScreen(x, y, time); } /** * Clicks on a Button with a given text. Will automatically scroll when needed. * * @param name the name of the {@link Button} presented to the user. The parameter will be interpreted as a regular expression * */ public void clickOnButton(String name) { clicker.clickOn(Button.class, name); } /** * Clicks on an ImageButton with a given index. * * @param index the index of the {@link ImageButton} to be clicked. 0 if only one is available * */ public void clickOnImageButton(int index) { clicker.clickOn(ImageButton.class, index); } /** * Clicks on a ToggleButton with a given text. * * @param name the name of the {@link ToggleButton} presented to the user. The parameter will be interpreted as a regular expression * */ public void clickOnToggleButton(String name) { clicker.clickOn(ToggleButton.class, name); } /** * Clicks on a MenuItem with a given text. * @param text the menu text that should be clicked on. The parameter will be interpreted as a regular expression * */ public void clickOnMenuItem(String text) { clicker.clickOnMenuItem(text); } /** * Clicks on a MenuItem with a given text. * * @param text the menu text that should be clicked on. The parameter will be interpreted as a regular expression * @param subMenu true if the menu item could be located in a sub menu * */ public void clickOnMenuItem(String text, boolean subMenu) { clicker.clickOnMenuItem(text, subMenu); } /** * Presses a MenuItem with a given index. Index {@code 0} is the first item in the * first row, Index {@code 3} is the first item in the second row and * index {@code 6} is the first item in the third row. * * @param index the index of the {@link android.view.MenuItem} to be pressed * */ public void pressMenuItem(int index) { presser.pressMenuItem(index); } /** * Presses a MenuItem with a given index. Supports three rows with a given amount * of items. If itemsPerRow equals 5 then index 0 is the first item in the first row, * index 5 is the first item in the second row and index 10 is the first item in the third row. * * @param index the index of the {@link android.view.MenuItem} to be pressed * @param itemsPerRow the amount of menu items there are per row. * */ public void pressMenuItem(int index, int itemsPerRow) { presser.pressMenuItem(index, itemsPerRow); } /** * Presses on a Spinner (drop-down menu) item. * * @param spinnerIndex the index of the {@link Spinner} menu to be used * @param itemIndex the index of the {@link Spinner} item to be pressed relative to the currently selected item * A Negative number moves up on the {@link Spinner}, positive moves down * */ public void pressSpinnerItem(int spinnerIndex, int itemIndex) { presser.pressSpinnerItem(spinnerIndex, itemIndex); } /** * Clicks on a given View. * * @param view the {@link View} to be clicked * */ public void clickOnView(View view) { waiter.waitForView(view, SMALLTIMEOUT); clicker.clickOnScreen(view); } /** * Clicks on a given View. * * @param view the {@link View} to be clicked * @param immediately true if view is to be clicked without any wait */ public void clickOnView(View view, boolean immediately){ if(immediately) clicker.clickOnScreen(view); else{ waiter.waitForView(view, SMALLTIMEOUT); clicker.clickOnScreen(view); } } /** * Long clicks on a given View. * * @param view the {@link View} to be long clicked * */ public void clickLongOnView(View view) { waiter.waitForView(view, SMALLTIMEOUT); clicker.clickOnScreen(view, true, 0); } /** * Long clicks on a given View for a given amount of time. * * @param view the {@link View} to be long clicked * @param time the amount of time to long click * */ public void clickLongOnView(View view, int time) { clicker.clickOnScreen(view, true, time); } /** * Clicks on a View displaying a given * text. Will automatically scroll when needed. * * @param text the text to be clicked. The parameter will be interpreted as a regular expression * */ public void clickOnText(String text) { clicker.clickOnText(text, false, 1, true, 0); } /** * Clicks on a View displaying a given text. Will automatically scroll when needed. * * @param text the text to be clicked. The parameter will be interpreted as a regular expression * @param match if multiple objects match the text, this determines which one will be clicked * */ public void clickOnText(String text, int match) { clicker.clickOnText(text, false, match, true, 0); } /** * Clicks on a View displaying a given text. * * @param text the text to be clicked. The parameter will be interpreted as a regular expression * @param match if multiple objects match the text, this determines which one will be clicked * @param scroll true if scrolling should be performed * */ public void clickOnText(String text, int match, boolean scroll) { clicker.clickOnText(text, false, match, scroll, 0); } /** * Long clicks on a given View. Will automatically scroll when needed. {@link #clickOnText(String)} can then be * used to click on the context menu items that appear after the long click. * * @param text the text to be clicked. The parameter will be interpreted as a regular expression * */ public void clickLongOnText(String text) { clicker.clickOnText(text, true, 1, true, 0); } /** * Long clicks on a given View. Will automatically scroll when needed. {@link #clickOnText(String)} can then be * used to click on the context menu items that appear after the long click. * * @param text the text to be clicked. The parameter will be interpreted as a regular expression * @param match if multiple objects match the text, this determines which one will be clicked * */ public void clickLongOnText(String text, int match) { clicker.clickOnText(text, true, match, true, 0); } /** * Long clicks on a given View. {@link #clickOnText(String)} can then be * used to click on the context menu items that appear after the long click. * * @param text the text to be clicked. The parameter will be interpreted as a regular expression * @param match if multiple objects match the text, this determines which one will be clicked * @param scroll true if scrolling should be performed * */ public void clickLongOnText(String text, int match, boolean scroll) { clicker.clickOnText(text, true, match, scroll, 0); } /** * Long clicks on a given View. {@link #clickOnText(String)} can then be * used to click on the context menu items that appear after the long click. * * @param text the text to be clicked. The parameter will be interpreted as a regular expression * @param match if multiple objects match the text, this determines which one will be clicked * @param time the amount of time to long click */ public void clickLongOnText(String text, int match, int time) { clicker.clickOnText(text, true, match, true, time); } /** * Long clicks on a given View and then selects * an item from the context menu that appears. Will automatically scroll when needed. * * @param text the text to be clicked. The parameter will be interpreted as a regular expression * @param index the index of the menu item to be pressed. {@code 0} if only one is available * */ public void clickLongOnTextAndPress(String text, int index) { clicker.clickLongOnTextAndPress(text, index); } /** * Clicks on a Button with a given index. * * @param index the index of the {@link Button} to be clicked. {@code 0} if only one is available * */ public void clickOnButton(int index) { clicker.clickOn(Button.class, index); } /** * Clicks on a RadioButton with a given index. * * @param index the index of the {@link RadioButton} to be clicked. {@code 0} if only one is available * */ public void clickOnRadioButton(int index) { clicker.clickOn(RadioButton.class, index); } /** * Clicks on a CheckBox with a given index. * * @param index the index of the {@link CheckBox} to be clicked. {@code 0} if only one is available * */ public void clickOnCheckBox(int index) { clicker.clickOn(CheckBox.class, index); } /** * Clicks on an EditText with a given index. * * @param index the index of the {@link EditText} to be clicked. {@code 0} if only one is available * */ public void clickOnEditText(int index) { clicker.clickOn(EditText.class, index); } /** * Clicks on a given list line and returns an ArrayList of the TextView objects that * the list line is showing. Will use the first list it finds. * * @param line the line to be clicked * @return an {@code ArrayList} of the {@link TextView} objects located in the list line * */ public ArrayList<TextView> clickInList(int line) { return clicker.clickInList(line); } /** * Clicks on a given list line on a specified list and * returns an ArrayList of the TextView objects that the list line is showing. * * @param line the line to be clicked * @param index the index of the list. 1 if two lists are available * @return an {@code ArrayList} of the {@link TextView} objects located in the list line * */ public ArrayList<TextView> clickInList(int line, int index) { return clicker.clickInList(line, index, false, 0); } /** * Long clicks on a given list line and returns an ArrayList of the TextView objects that * the list line is showing. Will use the first list it finds. * * @param line the line to be clicked * @return an {@code ArrayList} of the {@link TextView} objects located in the list line * */ public ArrayList<TextView> clickLongInList(int line){ return clicker.clickInList(line, 0, true, 0); } /** * Long clicks on a given list line on a specified list and * returns an ArrayList of the TextView objects that the list line is showing. * * @param line the line to be clicked * @param index the index of the list. 1 if two lists are available * @return an {@code ArrayList} of the {@link TextView} objects located in the list line * */ public ArrayList<TextView> clickLongInList(int line, int index){ return clicker.clickInList(line, index, true, 0); } /** * Long clicks on a given list line on a specified list and * returns an ArrayList of the TextView objects that the list line is showing. * * @param line the line to be clicked * @param index the index of the list. 1 if two lists are available * @param time the amount of time to long click * @return an {@code ArrayList} of the {@link TextView} objects located in the list line * */ public ArrayList<TextView> clickLongInList(int line, int index, int time){ return clicker.clickInList(line, index, true, time); } /** * Clicks on an ActionBar item with a given resource id. * * @param resourceId the R.id of the ActionBar item */ public void clickOnActionBarItem(int resourceId){ clicker.clickOnActionBarItem(resourceId); } /** * Clicks on an ActionBar Home/Up button. */ public void clickOnActionBarHomeButton() { clicker.clickOnActionBarHomeButton(); } /** * Simulate touching a given location and dragging it to a new location. * * This method was copied from {@code TouchUtils.java} in the Android Open Source Project, and modified here. * * @param fromX X coordinate of the initial touch, in screen coordinates * @param toX X coordinate of the drag destination, in screen coordinates * @param fromY X coordinate of the initial touch, in screen coordinates * @param toY Y coordinate of the drag destination, in screen coordinates * @param stepCount How many move steps to include in the drag * */ public void drag(float fromX, float toX, float fromY, float toY, int stepCount) { scroller.drag(fromX, toX, fromY, toY, stepCount); } /** * Scrolls down the screen. * * @return {@code true} if more scrolling can be done and {@code false} if it is at the end of * the screen * */ public boolean scrollDown() { waiter.waitForViews(AbsListView.class, ScrollView.class); return scroller.scroll(Scroller.DOWN); } /** * Scrolls to the bottom of the screen. */ public void scrollToBottom() { waiter.waitForViews(AbsListView.class, ScrollView.class); scroller.scroll(Scroller.DOWN, true); } /** * Scrolls up the screen. * * @return {@code true} if more scrolling can be done and {@code false} if it is at the top of * the screen * */ public boolean scrollUp(){ waiter.waitForViews(AbsListView.class, ScrollView.class); return scroller.scroll(Scroller.UP); } /** * Scrolls to the top of the screen. */ public void scrollToTop() { waiter.waitForViews(AbsListView.class, ScrollView.class); scroller.scroll(Scroller.UP, true); } /** * Scrolls down a given list. * * @param list the {@link AbsListView} to be scrolled * @return {@code true} if more scrolling can be done * */ public boolean scrollDownList(AbsListView list) { return scroller.scrollList(list, Scroller.DOWN, false); } /** * Scrolls to the bottom of a given list. * * @param list the {@link AbsListView} to be scrolled * @return {@code true} if more scrolling can be done * */ public boolean scrollListToBottom(AbsListView list) { return scroller.scrollList(list, Scroller.DOWN, true); } /** * Scrolls up a given list. * * @param list the {@link AbsListView} to be scrolled * @return {@code true} if more scrolling can be done * */ public boolean scrollUpList(AbsListView list) { return scroller.scrollList(list, Scroller.UP, false); } /** * Scrolls to the top of a given list. * * @param list the {@link AbsListView} to be scrolled * @return {@code true} if more scrolling can be done * */ public boolean scrollListToTop(AbsListView list) { return scroller.scrollList(list, Scroller.UP, true); } /** * Scrolls down a list with a given index. * * @param index the {@link ListView} to be scrolled. {@code 0} if only one list is available * @return {@code true} if more scrolling can be done * */ public boolean scrollDownList(int index) { return scroller.scrollList(waiter.waitForAndGetView(index, ListView.class), Scroller.DOWN, false); } /** * Scrolls a list with a given index to the bottom. * * @param index the {@link ListView} to be scrolled. {@code 0} if only one list is available * @return {@code true} if more scrolling can be done * */ public boolean scrollListToBottom(int index) { return scroller.scrollList(waiter.waitForAndGetView(index, ListView.class), Scroller.DOWN, true); } /** * Scrolls up a list with a given index. * * @param index the {@link ListView} to be scrolled. {@code 0} if only one list is available * @return {@code true} if more scrolling can be done * */ public boolean scrollUpList(int index) { return scroller.scrollList(waiter.waitForAndGetView(index, ListView.class), Scroller.UP, false); } /** * Scrolls a list with a given index to the top. * * @param index the {@link ListView} to be scrolled. {@code 0} if only one list is available * @return {@code true} if more scrolling can be done * */ public boolean scrollListToTop(int index) { return scroller.scrollList(waiter.waitForAndGetView(index, ListView.class), Scroller.UP, true); } /** * Scrolls horizontally. * * @param side the side to which to scroll; {@link #RIGHT} or {@link #LEFT} * */ public void scrollToSide(int side) { switch (side){ case RIGHT: scroller.scrollToSide(Scroller.Side.RIGHT); break; case LEFT: scroller.scrollToSide(Scroller.Side.LEFT); break; } } /** * Sets the date in a DatePicker with a given index. * * @param index the index of the {@link DatePicker}. {@code 0} if only one is available * @param year the year e.g. 2011 * @param monthOfYear the month which starts from zero e.g. 0 for January * @param dayOfMonth the day e.g. 10 * */ public void setDatePicker(int index, int year, int monthOfYear, int dayOfMonth) { setDatePicker(waiter.waitForAndGetView(index, DatePicker.class), year, monthOfYear, dayOfMonth); } /** * Sets the date in a given DatePicker. * * @param datePicker the {@link DatePicker} object. * @param year the year e.g. 2011 * @param monthOfYear the month which starts from zero e.g. 03 for April * @param dayOfMonth the day e.g. 10 * */ public void setDatePicker(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) { waiter.waitForView(datePicker, SMALLTIMEOUT); setter.setDatePicker(datePicker, year, monthOfYear, dayOfMonth); } /** * Sets the time in a TimePicker with a given index. * * @param index the index of the {@link TimePicker}. {@code 0} if only one is available * @param hour the hour e.g. 15 * @param minute the minute e.g. 30 * */ public void setTimePicker(int index, int hour, int minute) { setTimePicker(waiter.waitForAndGetView(index, TimePicker.class), hour, minute); } /** * Sets the time in a given TimePicker. * * @param timePicker the {@link TimePicker} object. * @param hour the hour e.g. 15 * @param minute the minute e.g. 30 * */ public void setTimePicker(TimePicker timePicker, int hour, int minute) { waiter.waitForView(timePicker, SMALLTIMEOUT); setter.setTimePicker(timePicker, hour, minute); } /** * Sets the progress of a ProgressBar with a given index. Examples are SeekBar and RatingBar. * * @param index the index of the {@link ProgressBar} * @param progress the progress that the {@link ProgressBar} should be set to * */ public void setProgressBar(int index, int progress){ setProgressBar(waiter.waitForAndGetView(index, ProgressBar.class),progress); } /** * Sets the progress of a given ProgressBar. Examples are SeekBar and RatingBar. * * @param progressBar the {@link ProgressBar} * @param progress the progress that the {@link ProgressBar} should be set to * */ public void setProgressBar(ProgressBar progressBar, int progress){ waiter.waitForView(progressBar, SMALLTIMEOUT); setter.setProgressBar(progressBar, progress); } /** * Sets the status of a SlidingDrawer with a given index. Examples are Solo.CLOSED and Solo.OPENED. * * @param index the index of the {@link SlidingDrawer} * @param status the status that the {@link SlidingDrawer} should be set to * */ public void setSlidingDrawer(int index, int status){ setSlidingDrawer(waiter.waitForAndGetView(index, SlidingDrawer.class),status); } /** * Sets the status of a given SlidingDrawer. Examples are Solo.CLOSED and Solo.OPENED. * * @param slidingDrawer the {@link SlidingDrawer} * @param status the status that the {@link SlidingDrawer} should be set to * */ public void setSlidingDrawer(SlidingDrawer slidingDrawer, int status){ waiter.waitForView(slidingDrawer, SMALLTIMEOUT); setter.setSlidingDrawer(slidingDrawer, status); } /** * Enters text in an EditText with a given index. * * @param index the index of the {@link EditText}. {@code 0} if only one is available * @param text the text string to enter into the {@link EditText} field * */ public void enterText(int index, String text) { textEnterer.setEditText(waiter.waitForAndGetView(index, EditText.class), text); } /** * Enters text in a given EditText. * * @param editText the {@link EditText} to enter text into * @param text the text string to enter into the {@link EditText} field * */ public void enterText(EditText editText, String text) { waiter.waitForView(editText, SMALLTIMEOUT); textEnterer.setEditText(editText, text); } /** * Types text in an EditText with a given index. * * @param index the index of the {@link EditText}. {@code 0} if only one is available * @param text the text string to type in the {@link EditText} field * */ public void typeText(int index, String text) { textEnterer.typeText(waiter.waitForAndGetView(index, EditText.class), text); } /** * Types text in a given EditText. * * @param editText the {@link EditText} to type text in * @param text the text string to type in the {@link EditText} field * */ public void typeText(EditText editText, String text) { waiter.waitForView(editText, SMALLTIMEOUT); textEnterer.typeText(editText, text); } /** * Clears the value of an EditText. * * @param index the index of the {@link EditText} that should be cleared. 0 if only one is available * */ public void clearEditText(int index) { textEnterer.setEditText(waiter.waitForAndGetView(index, EditText.class), ""); } /** * Clears the value of an EditText. * * @param editText the {@link EditText} that should be cleared * */ public void clearEditText(EditText editText) { waiter.waitForView(editText, SMALLTIMEOUT); textEnterer.setEditText(editText, ""); } /** * Clicks on an ImageView with a given index. * * @param index the index of the {@link ImageView} to be clicked. {@code 0} if only one is available * */ public void clickOnImage(int index) { clicker.clickOn(ImageView.class, index); } /** * Returns an EditText with a given index. * * @param index the index of the {@link EditText}. {@code 0} if only one is available * @return the {@link EditText} with a specified index or {@code null} if index is invalid * */ public EditText getEditText(int index) { return getter.getView(EditText.class, index); } /** * Returns a Button with a given index. * * @param index the index of the {@link Button}. {@code 0} if only one is available * @return the {@link Button} with a specified index or {@code null} if index is invalid * */ public Button getButton(int index) { return getter.getView(Button.class, index); } /** * Returns a TextView with a given index. * * @param index the index of the {@link TextView}. {@code 0} if only one is available * @return the {@link TextView} with a specified index or {@code null} if index is invalid * */ public TextView getText(int index) { return getter.getView(TextView.class, index); } /** * Returns an ImageView with a given index. * * @param index the index of the {@link ImageView}. {@code 0} if only one is available * @return the {@link ImageView} with a specified index or {@code null} if index is invalid * */ public ImageView getImage(int index) { return getter.getView(ImageView.class, index); } /** * Returns an ImageButton with a given index. * * @param index the index of the {@link ImageButton}. {@code 0} if only one is available * @return the {@link ImageButton} with a specified index or {@code null} if index is invalid * */ public ImageButton getImageButton(int index) { return getter.getView(ImageButton.class, index); } /** * Returns a TextView which shows a given text. * * @param text the text that is shown * @return the {@link TextView} that shows the given text */ public TextView getText(String text) { return getter.getView(TextView.class, text, false); } /** * Returns a TextView which shows a given text. * * @param text the text that is shown * @param onlyVisible {@code true} if only visible texts on the screen should be returned * @return the {@link TextView} that shows the given text */ public TextView getText(String text, boolean onlyVisible) { return getter.getView(TextView.class, text, onlyVisible); } /** * Returns a Button which shows a given text. * * @param text the text that is shown * @return the {@link Button} that shows the given text */ public Button getButton(String text) { return getter.getView(Button.class, text, false); } /** * Returns a Button which shows a given text. * * @param text the text that is shown * @param onlyVisible {@code true} if only visible buttons on the screen should be returned * @return the {@link Button} that shows the given text */ public Button getButton(String text, boolean onlyVisible) { return getter.getView(Button.class, text, onlyVisible); } /** * Returns an EditText which shows a given text. * * @param text the text that is shown * @return the {@link EditText} which shows the given text */ public EditText getEditText(String text) { return getter.getView(EditText.class, text, false); } /** * Returns an EditText which shows a given text. * * @param text the text that is shown * @param onlyVisible {@code true} if only visible EditTexts on the screen should be returned * @return the {@link EditText} which shows the given text */ public EditText getEditText(String text, boolean onlyVisible) { return getter.getView(EditText.class, text, onlyVisible); } /** * Returns a View with a given resource id. * * @param id the R.id of the {@link View} to be returned * @return a {@link View} with a given id */ public View getView(int id){ return getter.getView(id); } /** * Returns a View of a given class and index. * * @param viewClass the class of the requested view * @param index the index of the {@link View}. {@code 0} if only one is available * @return a {@link View} with a given class and index */ public <T extends View> View getView(Class<T> viewClass, int index){ return waiter.waitForAndGetView(index, viewClass); } /** * Returns an ArrayList of the View objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link View} objects currently shown in the * focused window * */ public ArrayList<View> getCurrentViews() { return viewFetcher.getViews(null, true); } /** * Returns an ArrayList of the ImageView objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link ImageView} objects currently shown in the * focused window * */ public ArrayList<ImageView> getCurrentImageViews() { return viewFetcher.getCurrentViews(ImageView.class); } /** * Returns an ArrayList of the ImageView objects currently shown in the focused * Activity or Dialog. * * @param parent the parent {@link View} from which the {@link ImageView} objects should be returned. {@code null} if * all TextView objects from the currently focused window e.g. Activity should be returned * * @return an {@code ArrayList} of the {@link ImageView} objects currently shown in the * focused window * */ public ArrayList<ImageView> getCurrentImageViews(View parent) { return viewFetcher.getCurrentViews(ImageView.class, parent); } /** * Returns an ArrayList of the EditText objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link EditText} objects currently shown in the * focused window * */ public ArrayList<EditText> getCurrentEditTexts() { return viewFetcher.getCurrentViews(EditText.class); } /** * Returns an ArrayList of the ListView objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link ListView} objects currently shown in the * focused window * */ public ArrayList<ListView> getCurrentListViews() { return viewFetcher.getCurrentViews(ListView.class); } /** * Returns an ArrayList of the ScrollView objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link ScrollView} objects currently shown in the * focused window * */ public ArrayList<ScrollView> getCurrentScrollViews() { return viewFetcher.getCurrentViews(ScrollView.class); } /** * Returns an ArrayList of the Spinner objects (drop-down menus) currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link Spinner} objects (drop-down menus) currently shown in the * focused window * */ public ArrayList<Spinner> getCurrentSpinners() { return viewFetcher.getCurrentViews(Spinner.class); } /** * Returns an ArrayList of the TextView objects currently shown in the focused * Activity or Dialog. * * @param parent the parent {@link View} from which the {@link TextView} objects should be returned. {@code null} if * all TextView objects from the currently focused window e.g. Activity should be returned * * @return an {@code ArrayList} of the {@link TextView} objects currently shown in the * focused window * */ public ArrayList<TextView> getCurrentTextViews(View parent) { return viewFetcher.getCurrentViews(TextView.class, parent); } /** * Returns an ArrayList of the GridView objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link GridView} objects currently shown in the * focused window * */ public ArrayList<GridView> getCurrentGridViews() { return viewFetcher.getCurrentViews(GridView.class); } /** * Returns an ArrayList of the Button objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link Button} objects currently shown in the * focused window * */ public ArrayList<Button> getCurrentButtons() { return viewFetcher.getCurrentViews(Button.class); } /** * Returns an ArrayList of the ToggleButton objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link ToggleButton} objects currently shown in the * focused window * */ public ArrayList<ToggleButton> getCurrentToggleButtons() { return viewFetcher.getCurrentViews(ToggleButton.class); } /** * Returns an ArrayList of the RadioButton objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link RadioButton} objects currently shown in the * focused window * */ public ArrayList<RadioButton> getCurrentRadioButtons() { return viewFetcher.getCurrentViews(RadioButton.class); } /** * Returns an ArrayList of the CheckBox objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link CheckBox} objects currently shown in the * focused window * */ public ArrayList<CheckBox> getCurrentCheckBoxes() { return viewFetcher.getCurrentViews(CheckBox.class); } /** * Returns an ArrayList of the ImageButton objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link ImageButton} objects currently shown in the * focused window * */ public ArrayList<ImageButton> getCurrentImageButtons() { return viewFetcher.getCurrentViews(ImageButton.class); } /** * Returns an ArrayList of the DatePicker objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link DatePicker} objects currently shown in the * focused window * */ public ArrayList<DatePicker> getCurrentDatePickers() { return viewFetcher.getCurrentViews(DatePicker.class); } /** * Returns an ArrayList of the TimePicker objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link TimePicker} objects currently shown in the * focused window * */ public ArrayList<TimePicker> getCurrentTimePickers() { return viewFetcher.getCurrentViews(TimePicker.class); } /** * Returns an ArrayList of the NumberPicker objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link NumberPicker} objects currently shown in the * focused window * */ @SuppressWarnings({ "rawtypes", "unchecked" }) public <T extends LinearLayout> ArrayList<T> getCurrentNumberPickers() { try { Class numberPickerClass = Class.forName("android.widget.NumberPicker"); if (numberPickerClass != null) { return viewFetcher.getCurrentViews(numberPickerClass); } } catch(ClassNotFoundException cnfe) { cnfe.printStackTrace(); } return new ArrayList<T>(); } /** * Returns an ArrayList of the SlidingDrawer objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link SlidingDrawer} objects currently shown in the * focused window * */ public ArrayList<SlidingDrawer> getCurrentSlidingDrawers() { return viewFetcher.getCurrentViews(SlidingDrawer.class); } /** * Returns an ArrayList of the ProgressBar objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link ProgressBar} objects currently shown in the * focused window * */ public ArrayList<ProgressBar> getCurrentProgressBars() { return viewFetcher.getCurrentViews(ProgressBar.class); } /** * Checks if a RadioButton with a given index is checked. * * @param index of the {@link RadioButton} to check. {@code 0} if only one is available * @return {@code true} if {@link RadioButton} is checked and {@code false} if it is not checked * */ public boolean isRadioButtonChecked(int index) { return checker.isButtonChecked(RadioButton.class, index); } /** * Checks if a RadioButton with a given text is checked. * * @param text the text that the {@link RadioButton} shows * @return {@code true} if a {@link RadioButton} with the given text is checked and {@code false} if it is not checked * */ public boolean isRadioButtonChecked(String text) { return checker.isButtonChecked(RadioButton.class, text); } /** * Checks if a CheckBox with a given index is checked. * * @param index of the {@link CheckBox} to check. {@code 0} if only one is available * @return {@code true} if {@link CheckBox} is checked and {@code false} if it is not checked * */ public boolean isCheckBoxChecked(int index) { return checker.isButtonChecked(CheckBox.class, index); } /** * Checks if a ToggleButton with a given text is checked. * * @param text the text that the {@link ToggleButton} shows * @return {@code true} if a {@link ToggleButton} with the given text is checked and {@code false} if it is not checked * */ public boolean isToggleButtonChecked(String text) { return checker.isButtonChecked(ToggleButton.class, text); } /** * Checks if a ToggleButton with a given index is checked. * * @param index of the {@link ToggleButton} to check. {@code 0} if only one is available * @return {@code true} if {@link ToggleButton} is checked and {@code false} if it is not checked * */ public boolean isToggleButtonChecked(int index) { return checker.isButtonChecked(ToggleButton.class, index); } /** * Checks if a CheckBox with a given text is checked. * * @param text the text that the {@link CheckBox} shows * @return {@code true} if a {@link CheckBox} with the given text is checked and {@code false} if it is not checked * */ public boolean isCheckBoxChecked(String text) { return checker.isButtonChecked(CheckBox.class, text); } /** * Checks if the given text is checked. * * @param text the text that the {@link CheckedTextView} or {@link CompoundButton} objects show * @return {@code true} if the given text is checked and {@code false} if it is not checked */ public boolean isTextChecked(String text){ waiter.waitForViews(CheckedTextView.class, CompoundButton.class); if(viewFetcher.getCurrentViews(CheckedTextView.class).size() > 0 && checker.isCheckedTextChecked(text)) return true; if(viewFetcher.getCurrentViews(CompoundButton.class).size() > 0 && checker.isButtonChecked(CompoundButton.class, text)) return true; return false; } /** * Checks if a given text is selected in any Spinner located in the current screen. * * @param text the text that is expected to be selected * @return {@code true} if the given text is selected in any {@link Spinner} and false if it is not * */ public boolean isSpinnerTextSelected(String text) { return checker.isSpinnerTextSelected(text); } /** * Checks if a given text is selected in a given Spinner. * * @param index the index of the spinner to check. {@code 0} if only one spinner is available * @param text the text that is expected to be selected * @return true if the given text is selected in the given {@link Spinner} and false if it is not */ public boolean isSpinnerTextSelected(int index, String text) { return checker.isSpinnerTextSelected(index, text); } /** * Sends a key: Right, Left, Up, Down, Enter, Menu or Delete. * * @param key the key to be sent. Use {@code Solo.}{@link #RIGHT}, {@link #LEFT}, {@link #UP}, {@link #DOWN}, * {@link #ENTER}, {@link #MENU}, {@link #DELETE} * */ public void sendKey(int key) { robotiumUtils.sendKeyCode(key); } /** * Returns to the given Activity. * * @param name the name of the {@link Activity} to return to, e.g. {@code "MyActivity"} * */ public void goBackToActivity(String name) { activityUtils.goBackToActivity(name); } /** * Waits for the given Activity. Default timeout is 20 seconds. * * @param name the name of the {@code Activity} to wait for e.g. {@code "MyActivity"} * @return {@code true} if {@code Activity} appears before the timeout and {@code false} if it does not * */ public boolean waitForActivity(String name){ return waiter.waitForActivity(name, TIMEOUT); } /** * Waits for the given Activity. * * @param name the name of the {@link Activity} to wait for e.g. {@code "MyActivity"} * @param timeout the amount of time in milliseconds to wait * @return {@code true} if {@link Activity} appears before the timeout and {@code false} if it does not * */ public boolean waitForActivity(String name, int timeout) { return waiter.waitForActivity(name, timeout); } /** * Waits for a Fragment with a given tag to appear. Default timeout is 20 seconds. * * @param tag the name of the tag * @return true if fragment appears and false if it does not appear before the timeout * */ public boolean waitForFragmentByTag(String tag){ return waiter.waitForFragment(tag, 0, TIMEOUT); } /** * Waits for a Fragment with a given tag to appear. * * @param tag the name of the tag * @param timeout the amount of time in milliseconds to wait * @return true if fragment appears and false if it does not appear before the timeout * */ public boolean waitForFragmentByTag(String tag, int timeout){ return waiter.waitForFragment(tag, 0, timeout); } /** * Waits for a Fragment with a given id to appear. Default timeout is 20 seconds. * * @param id the id of the fragment * @return true if fragment appears and false if it does not appear before the timeout * */ public boolean waitForFragmentById(int id){ return waiter.waitForFragment(null, id, TIMEOUT); } /** * Waits for a Fragment with a given id to appear. * * @param id the id of the fragment * @param timeout the amount of time in milliseconds to wait * @return true if fragment appears and false if it does not appear before the timeout * */ public boolean waitForFragmentById(int id, int timeout){ return waiter.waitForFragment(null, id, timeout); } /** * Waits for a log message to appear. Default timeout is 20 seconds. * Requires read logs permission (android.permission.READ_LOGS) in AndroidManifest.xml of the application under test. * * @param logMessage the log message to wait for * * @return true if log message appears and false if it does not appear before the timeout */ public boolean waitForLogMessage(String logMessage){ return waiter.waitForLogMessage(logMessage, TIMEOUT); } /** * Waits for a log message to appear. * Requires read logs permission (android.permission.READ_LOGS) in AndroidManifest.xml of the application under test. * * @param logMessage the log message to wait for * @param timeout the amount of time in milliseconds to wait * * @return true if log message appears and false if it does not appear before the timeout */ public boolean waitForLogMessage(String logMessage, int timeout){ return waiter.waitForLogMessage(logMessage, timeout); } /** * Returns a localized string. * * @param resId the resource id of the string * @return the localized string * */ public String getString(int resId) { return activityUtils.getString(resId); } /** * Robotium will sleep for a specified time. * * @param time the time in milliseconds that Robotium should sleep * */ public void sleep(int time) { sleeper.sleep(time); } /** * * Finalizes the solo object and removes the ActivityMonitor. * * @see #finishOpenedActivities() finishOpenedActivities() to close the activities that have been active. * */ public void finalize() throws Throwable { activityUtils.finalize(); } /** * All inactive activities are finished. * * @deprecated Method has been deprecated as there are no longer strong references to activities. * */ public void finishInactiveActivities(){ activityUtils.finishInactiveActivities(); } /** * The activities that are alive are finished. Usually used in tearDown(). * */ public void finishOpenedActivities(){ activityUtils.finishOpenedActivities(); } /** * Takes a screenshot and saves it in "/sdcard/Robotium-Screenshots/". * Requires write permission (android.permission.WRITE_EXTERNAL_STORAGE) in AndroidManifest.xml of the application under test. * */ public void takeScreenshot(){ View decorView = viewFetcher.getRecentDecorView(viewFetcher.getWindowDecorViews()); robotiumUtils.takeScreenshot(decorView, null); } /** * Takes a screenshot and saves it with a given name in "/sdcard/Robotium-Screenshots/". * Requires write permission (android.permission.WRITE_EXTERNAL_STORAGE) in AndroidManifest.xml of the application under test. * * @param name the name to give the screenshot * */ public void takeScreenshot(String name){ View decorView = viewFetcher.getRecentDecorView(viewFetcher.getWindowDecorViews()); robotiumUtils.takeScreenshot(decorView, name); } }
robotium-solo/src/main/java/com/jayway/android/robotium/solo/Solo.java
package com.jayway.android.robotium.solo; import java.util.ArrayList; import android.app.Activity; import android.app.Instrumentation; import android.content.pm.ActivityInfo; import android.view.KeyEvent; import android.view.View; import android.widget.AbsListView; import android.widget.Button; import android.widget.CheckBox; import android.widget.CheckedTextView; import android.widget.CompoundButton; import android.widget.DatePicker; import android.widget.EditText; import android.widget.GridView; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RadioButton; import android.widget.ScrollView; import android.widget.SlidingDrawer; import android.widget.Spinner; import android.widget.TextView; import android.widget.ListView; import android.widget.TimePicker; import android.widget.ToggleButton; import android.app.Instrumentation.ActivityMonitor; /** * Contains all the methods that the sub-classes have. It supports test * cases that span over multiple activities. * * Robotium has full support for Activities, Dialogs, Toasts, Menus and Context Menus. * * When writing tests there is no need to plan for or expect new activities in the test case. * All is handled automatically by Robotium-Solo. Robotium-Solo can be used in conjunction with * ActivityInstrumentationTestCase2. The test cases are written from a user * perspective were technical details are not needed. * * * Example of usage (test case spanning over multiple activities): * * <pre> * * public void setUp() throws Exception { * solo = new Solo(getInstrumentation(), getActivity()); * } * * public void testTextShows() throws Exception { * * solo.clickOnText(&quot;Categories&quot;); * solo.clickOnText(&quot;Other&quot;); * solo.clickOnButton(&quot;Edit&quot;); * solo.searchText(&quot;Edit Window&quot;); * solo.clickOnButton(&quot;Commit&quot;); * assertTrue(solo.searchText(&quot;Changes have been made successfully&quot;)); * } * * </pre> * * * @author Renas Reda, [email protected] * */ public class Solo { protected final Asserter asserter; protected final ViewFetcher viewFetcher; protected final Checker checker; protected final Clicker clicker; protected final Presser presser; protected final Searcher searcher; protected final ActivityUtils activityUtils; protected final DialogUtils dialogUtils; protected final TextEnterer textEnterer; protected final Scroller scroller; protected final RobotiumUtils robotiumUtils; protected final Sleeper sleeper; protected final Waiter waiter; protected final Setter setter; protected final Getter getter; protected final int TIMEOUT = 20000; protected final int SMALLTIMEOUT = 10000; public final static int LANDSCAPE = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; // 0 public final static int PORTRAIT = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; // 1 public final static int RIGHT = KeyEvent.KEYCODE_DPAD_RIGHT; public final static int LEFT = KeyEvent.KEYCODE_DPAD_LEFT; public final static int UP = KeyEvent.KEYCODE_DPAD_UP; public final static int DOWN = KeyEvent.KEYCODE_DPAD_DOWN; public final static int ENTER = KeyEvent.KEYCODE_ENTER; public final static int MENU = KeyEvent.KEYCODE_MENU; public final static int DELETE = KeyEvent.KEYCODE_DEL; public final static int CLOSED = 0; public final static int OPENED = 1; /** * Constructor that takes in the instrumentation and the start activity. * * @param instrumentation the {@link Instrumentation} instance * @param activity the start {@link Activity} or {@code null} * if no start activity is provided * */ public Solo(Instrumentation instrumentation, Activity activity) { this.sleeper = new Sleeper(); this.activityUtils = new ActivityUtils(instrumentation, activity, sleeper); this.viewFetcher = new ViewFetcher(activityUtils); this.dialogUtils = new DialogUtils(viewFetcher, sleeper); this.scroller = new Scroller(instrumentation, activityUtils, viewFetcher, sleeper); this.searcher = new Searcher(viewFetcher, scroller, sleeper); this.waiter = new Waiter(activityUtils, viewFetcher, searcher,scroller, sleeper); this.setter = new Setter(activityUtils); this.getter = new Getter(activityUtils, viewFetcher, waiter); this.asserter = new Asserter(activityUtils, waiter); this.checker = new Checker(viewFetcher, waiter); this.robotiumUtils = new RobotiumUtils(instrumentation,activityUtils, sleeper); this.clicker = new Clicker(activityUtils, viewFetcher, scroller,robotiumUtils, instrumentation, sleeper, waiter); this.presser = new Presser(clicker, instrumentation, sleeper, waiter); this.textEnterer = new TextEnterer(instrumentation, activityUtils, clicker); } /** * Constructor that takes in the instrumentation. * * @param instrumentation the {@link Instrumentation} instance * */ public Solo(Instrumentation instrumentation) { this(instrumentation, null); } /** * Returns the ActivityMonitor used by Robotium. * * @return the ActivityMonitor used by Robotium */ public ActivityMonitor getActivityMonitor(){ return activityUtils.getActivityMonitor(); } /** * Returns an ArrayList of all the View objects located in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link View} objects located in the focused window * */ public ArrayList<View> getViews() { try { return viewFetcher.getViews(null, false); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Returns an ArrayList of the View objects contained in the parent View. * * @param parent the parent view from which to return the views * @return an {@code ArrayList} of the {@link View} objects contained in the given {@code View} * */ public ArrayList<View> getViews(View parent) { try { return viewFetcher.getViews(parent, false); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Returns the absolute top parent View for a given View. * * @param view the {@link View} whose top parent is requested * @return the top parent {@link View} * */ public View getTopParent(View view) { View topParent = viewFetcher.getTopParent(view); return topParent; } /** * Waits for a text to be shown. Default timeout is 20 seconds. * * @param text the text to wait for * @return {@code true} if text is shown and {@code false} if it is not shown before the timeout * */ public boolean waitForText(String text) { return waiter.waitForText(text); } /** * Waits for a text to be shown. * * @param text the text to wait for * @param minimumNumberOfMatches the minimum number of matches that are expected to be shown. {@code 0} means any number of matches * @param timeout the the amount of time in milliseconds to wait * @return {@code true} if text is shown and {@code false} if it is not shown before the timeout * */ public boolean waitForText(String text, int minimumNumberOfMatches, long timeout) { return waiter.waitForText(text, minimumNumberOfMatches, timeout); } /** * Waits for a text to be shown. * * @param text the text to wait for * @param minimumNumberOfMatches the minimum number of matches that are expected to be shown. {@code 0} means any number of matches * @param timeout the the amount of time in milliseconds to wait * @param scroll {@code true} if scrolling should be performed * @return {@code true} if text is shown and {@code false} if it is not shown before the timeout * */ public boolean waitForText(String text, int minimumNumberOfMatches, long timeout, boolean scroll) { return waiter.waitForText(text, minimumNumberOfMatches, timeout, scroll); } /** * Waits for a text to be shown. * * @param text the text to wait for * @param minimumNumberOfMatches the minimum number of matches that are expected to be shown. {@code 0} means any number of matches * @param timeout the the amount of time in milliseconds to wait * @param scroll {@code true} if scrolling should be performed * @param onlyVisible {@code true} if only visible text views should be waited for * @return {@code true} if text is shown and {@code false} if it is not shown before the timeout * */ public boolean waitForText(String text, int minimumNumberOfMatches, long timeout, boolean scroll, boolean onlyVisible) { return waiter.waitForText(text, minimumNumberOfMatches, timeout, scroll, onlyVisible); } /** * Waits for a View of a certain class to be shown. Default timeout is 20 seconds. * * @param viewClass the {@link View} class to wait for */ public <T extends View> boolean waitForView(final Class<T> viewClass){ return waiter.waitForView(viewClass, 0, TIMEOUT, true); } /** * Waits for a given View to be shown. Default timeout is 20 seconds. * * @param view the {@link View} object to wait for * * @return {@code true} if view is shown and {@code false} if it is not shown before the timeout */ public <T extends View> boolean waitForView(View view){ return waiter.waitForView(view); } /** * Waits for a given View to be shown. * * @param view the {@link View} object to wait for * @param timeout the amount of time in milliseconds to wait * @param scroll {@code true} if scrolling should be performed * * @return {@code true} if view is shown and {@code false} if it is not shown before the timeout */ public <T extends View> boolean waitForView(View view, int timeout, boolean scroll){ return waiter.waitForView(view, timeout, scroll); } /** * Waits for a View of a certain class to be shown. * * @param viewClass the {@link View} class to wait for * @param minimumNumberOfMatches the minimum number of matches that are expected to be shown. {@code 0} means any number of matches * @param timeout the amount of time in milliseconds to wait * @return {@code true} if view is shown and {@code false} if it is not shown before the timeout */ public <T extends View> boolean waitForView(final Class<T> viewClass, final int minimumNumberOfMatches, final int timeout){ int index = minimumNumberOfMatches-1; if(index < 1) index = 0; return waiter.waitForView(viewClass, index, timeout, true); } /** * Waits for a View of a certain class to be shown. * * @param viewClass the {@link View} class to wait for * @param minimumNumberOfMatches the minimum number of matches that are expected to be shown. {@code 0} means any number of matches * @param timeout the amount of time in milliseconds to wait * @param scroll {@code true} if scrolling should be performed * @return {@code true} if the {@link View} is shown and {@code false} if it is not shown before the timeout */ public <T extends View> boolean waitForView(final Class<T> viewClass, final int minimumNumberOfMatches, final int timeout,final boolean scroll){ int index = minimumNumberOfMatches-1; if(index < 1) index = 0; return waiter.waitForView(viewClass, index, timeout, scroll); } /** * Searches for a text string in the EditText objects currently shown and returns true if found. Will automatically scroll when needed. * * @param text the text to search for * @return {@code true} if an {@link EditText} with the given text is found or {@code false} if it is not found * */ public boolean searchEditText(String text) { return searcher.searchWithTimeoutFor(EditText.class, text, 1, true, false); } /** * Searches for a Button with the given text string and returns true if at least one Button * is found. Will automatically scroll when needed. * * @param text the text to search for. The parameter will be interpreted as a regular expression * @return {@code true} if a {@link Button} with the given text is found and {@code false} if it is not found * */ public boolean searchButton(String text) { return searcher.searchWithTimeoutFor(Button.class, text, 0, true, false); } /** * Searches for a Button with the given text string and returns true if at least one Button * is found. Will automatically scroll when needed. * * @param text the text to search for. The parameter will be interpreted as a regular expression * @param onlyVisible {@code true} if only {@link Button} visible on the screen should be searched * @return {@code true} if a {@link Button} with the given text is found and {@code false} if it is not found * */ public boolean searchButton(String text, boolean onlyVisible) { return searcher.searchWithTimeoutFor(Button.class, text, 0, true, onlyVisible); } /** * Searches for a ToggleButton with the given text string and returns {@code true} if at least one ToggleButton * is found. Will automatically scroll when needed. * * @param text the text to search for. The parameter will be interpreted as a regular expression * @return {@code true} if a {@link ToggleButton} with the given text is found and {@code false} if it is not found * */ public boolean searchToggleButton(String text) { return searcher.searchWithTimeoutFor(ToggleButton.class, text, 0, true, false); } /** * Searches for a Button with the given text string and returns {@code true} if the * searched Button is found a given number of times. Will automatically scroll when needed. * * @param text the text to search for. The parameter will be interpreted as a regular expression * @param minimumNumberOfMatches the minimum number of matches expected to be found. {@code 0} matches means that one or more * matches are expected to be found * @return {@code true} if a {@link Button} with the given text is found a given number of times and {@code false} * if it is not found * */ public boolean searchButton(String text, int minimumNumberOfMatches) { return searcher.searchWithTimeoutFor(Button.class, text, minimumNumberOfMatches, true, false); } /** * Searches for a Button with the given text string and returns {@code true} if the * searched Button is found a given number of times. Will automatically scroll when needed. * * @param text the text to search for. The parameter will be interpreted as a regular expression * @param minimumNumberOfMatches the minimum number of matches expected to be found. {@code 0} matches means that one or more * matches are expected to be found * @param onlyVisible {@code true} if only {@link Button} visible on the screen should be searched * @return {@code true} if a {@link Button} with the given text is found a given number of times and {@code false} * if it is not found * */ public boolean searchButton(String text, int minimumNumberOfMatches, boolean onlyVisible) { return searcher.searchWithTimeoutFor(Button.class, text, minimumNumberOfMatches, true, onlyVisible); } /** * Searches for a ToggleButton with the given text string and returns {@code true} if the * searched ToggleButton is found a given number of times. Will automatically scroll when needed. * * @param text the text to search for. The parameter will be interpreted as a regular expression * @param minimumNumberOfMatches the minimum number of matches expected to be found. {@code 0} matches means that one or more * matches are expected to be found * @return {@code true} if a {@link ToggleButton} with the given text is found a given number of times and {@code false} * if it is not found * */ public boolean searchToggleButton(String text, int minimumNumberOfMatches) { return searcher.searchWithTimeoutFor(ToggleButton.class, text, minimumNumberOfMatches, true, false); } /** * Searches for a text string and returns {@code true} if at least one item * is found with the expected text. Will automatically scroll when needed. * * @param text the text to search for. The parameter will be interpreted as a regular expression * @return {@code true} if the search string is found and {@code false} if it is not found * */ public boolean searchText(String text) { return searcher.searchWithTimeoutFor(TextView.class, text, 0, true, false); } /** * Searches for a text string and returns {@code true} if at least one item * is found with the expected text. Will automatically scroll when needed. * * @param text the text to search for. The parameter will be interpreted as a regular expression * @param onlyVisible {@code true} if only texts visible on the screen should be searched * @return {@code true} if the search string is found and {@code false} if it is not found * */ public boolean searchText(String text, boolean onlyVisible) { return searcher.searchWithTimeoutFor(TextView.class, text, 0, true, onlyVisible); } /** * Searches for a text string and returns {@code true} if the searched text is found a given * number of times. Will automatically scroll when needed. * * @param text the text to search for. The parameter will be interpreted as a regular expression * @param minimumNumberOfMatches the minimum number of matches expected to be found. {@code 0} matches means that one or more * matches are expected to be found * @return {@code true} if text string is found a given number of times and {@code false} if the text string * is not found * */ public boolean searchText(String text, int minimumNumberOfMatches) { return searcher.searchWithTimeoutFor(TextView.class, text, minimumNumberOfMatches, true, false); } /** * Searches for a text string and returns {@code true} if the searched text is found a given * number of times. * * @param text the text to search for. The parameter will be interpreted as a regular expression. * @param minimumNumberOfMatches the minimum number of matches expected to be found. {@code 0} matches means that one or more * matches are expected to be found * @param scroll {@code true} if scrolling should be performed * @return {@code true} if text string is found a given number of times and {@code false} if the text string * is not found * */ public boolean searchText(String text, int minimumNumberOfMatches, boolean scroll) { return searcher.searchWithTimeoutFor(TextView.class, text, minimumNumberOfMatches, scroll, false); } /** * Searches for a text string and returns {@code true} if the searched text is found a given * number of times. * * @param text the text to search for. The parameter will be interpreted as a regular expression. * @param minimumNumberOfMatches the minimum number of matches expected to be found. {@code 0} matches means that one or more * matches are expected to be found * @param scroll {@code true} if scrolling should be performed * @param onlyVisible {@code true} if only texts visible on the screen should be searched * @return {@code true} if text string is found a given number of times and {@code false} if the text string * is not found * */ public boolean searchText(String text, int minimumNumberOfMatches, boolean scroll, boolean onlyVisible) { return searcher.searchWithTimeoutFor(TextView.class, text, minimumNumberOfMatches, scroll, onlyVisible); } /** * Sets the Orientation (Landscape/Portrait) for the current activity. * * @param orientation the orientation to be set. <code>Solo.</code>{@link #LANDSCAPE} for landscape or * <code>Solo.</code>{@link #PORTRAIT} for portrait. * */ public void setActivityOrientation(int orientation) { activityUtils.setActivityOrientation(orientation); } /** * Returns an ArrayList of all the opened/active activities. * * @return an ArrayList of all the opened/active activities * */ public ArrayList<Activity> getAllOpenedActivities() { return activityUtils.getAllOpenedActivities(); } /** * Returns the current Activity. * * @return the current Activity * */ public Activity getCurrentActivity() { return activityUtils.getCurrentActivity(false); } /** * Asserts that the expected Activity is the currently active one. * * @param message the message that should be displayed if the assert fails * @param name the name of the {@link Activity} that is expected to be active e.g. {@code "MyActivity"} * */ public void assertCurrentActivity(String message, String name) { asserter.assertCurrentActivity(message, name); } /** * Asserts that the expected Activity is the currently active one. * * @param message the message that should be displayed if the assert fails * @param expectedClass the {@code Class} object that is expected to be active e.g. {@code MyActivity.class} * */ @SuppressWarnings("unchecked") public void assertCurrentActivity(String message, @SuppressWarnings("rawtypes") Class expectedClass) { asserter.assertCurrentActivity(message, expectedClass); } /** * Asserts that the expected Activity is the currently active one, with the possibility to * verify that the expected Activity is a new instance of the Activity. * * @param message the message that should be displayed if the assert fails * @param name the name of the activity that is expected to be active e.g. {@code "MyActivity"} * @param isNewInstance {@code true} if the expected {@link Activity} is a new instance of the {@link Activity} * */ public void assertCurrentActivity(String message, String name, boolean isNewInstance) { asserter.assertCurrentActivity(message, name, isNewInstance); } /** * Asserts that the expected Activity is the currently active one, with the possibility to * verify that the expected Activity is a new instance of the Activity. * * @param message the message that should be displayed if the assert fails * @param expectedClass the {@code Class} object that is expected to be active e.g. {@code MyActivity.class} * @param isNewInstance {@code true} if the expected {@link Activity} is a new instance of the {@link Activity} * */ @SuppressWarnings("unchecked") public void assertCurrentActivity(String message, @SuppressWarnings("rawtypes") Class expectedClass, boolean isNewInstance) { asserter.assertCurrentActivity(message, expectedClass, isNewInstance); } /** * Asserts that the available memory in the system is not low. * */ public void assertMemoryNotLow() { asserter.assertMemoryNotLow(); } /** * Waits for a Dialog to close. * * @param timeout the amount of time in milliseconds to wait * @return {@code true} if the {@link android.app.Dialog} is closed before the timeout and {@code false} if it is not closed * */ public boolean waitForDialogToClose(long timeout) { return dialogUtils.waitForDialogToClose(timeout); } /** * Simulates pressing the hardware back key. * */ public void goBack() { robotiumUtils.goBack(); } /** * Clicks on a given coordinate on the screen. * * @param x the x coordinate * @param y the y coordinate * */ public void clickOnScreen(float x, float y) { sleeper.sleep(); clicker.clickOnScreen(x, y); } /** * Long clicks a given coordinate on the screen. * * @param x the x coordinate * @param y the y coordinate * */ public void clickLongOnScreen(float x, float y) { clicker.clickLongOnScreen(x, y, 0); } /** * Long clicks a given coordinate on the screen for a given amount of time. * * @param x the x coordinate * @param y the y coordinate * @param time the amount of time to long click * */ public void clickLongOnScreen(float x, float y, int time) { clicker.clickLongOnScreen(x, y, time); } /** * Clicks on a Button with a given text. Will automatically scroll when needed. * * @param name the name of the {@link Button} presented to the user. The parameter will be interpreted as a regular expression * */ public void clickOnButton(String name) { clicker.clickOn(Button.class, name); } /** * Clicks on an ImageButton with a given index. * * @param index the index of the {@link ImageButton} to be clicked. 0 if only one is available * */ public void clickOnImageButton(int index) { clicker.clickOn(ImageButton.class, index); } /** * Clicks on a ToggleButton with a given text. * * @param name the name of the {@link ToggleButton} presented to the user. The parameter will be interpreted as a regular expression * */ public void clickOnToggleButton(String name) { clicker.clickOn(ToggleButton.class, name); } /** * Clicks on a MenuItem with a given text. * @param text the menu text that should be clicked on. The parameter will be interpreted as a regular expression * */ public void clickOnMenuItem(String text) { clicker.clickOnMenuItem(text); } /** * Clicks on a MenuItem with a given text. * * @param text the menu text that should be clicked on. The parameter will be interpreted as a regular expression * @param subMenu true if the menu item could be located in a sub menu * */ public void clickOnMenuItem(String text, boolean subMenu) { clicker.clickOnMenuItem(text, subMenu); } /** * Presses a MenuItem with a given index. Index {@code 0} is the first item in the * first row, Index {@code 3} is the first item in the second row and * index {@code 6} is the first item in the third row. * * @param index the index of the {@link android.view.MenuItem} to be pressed * */ public void pressMenuItem(int index) { presser.pressMenuItem(index); } /** * Presses a MenuItem with a given index. Supports three rows with a given amount * of items. If itemsPerRow equals 5 then index 0 is the first item in the first row, * index 5 is the first item in the second row and index 10 is the first item in the third row. * * @param index the index of the {@link android.view.MenuItem} to be pressed * @param itemsPerRow the amount of menu items there are per row. * */ public void pressMenuItem(int index, int itemsPerRow) { presser.pressMenuItem(index, itemsPerRow); } /** * Presses on a Spinner (drop-down menu) item. * * @param spinnerIndex the index of the {@link Spinner} menu to be used * @param itemIndex the index of the {@link Spinner} item to be pressed relative to the currently selected item * A Negative number moves up on the {@link Spinner}, positive moves down * */ public void pressSpinnerItem(int spinnerIndex, int itemIndex) { presser.pressSpinnerItem(spinnerIndex, itemIndex); } /** * Clicks on a given View. * * @param view the {@link View} to be clicked * */ public void clickOnView(View view) { waiter.waitForView(view, SMALLTIMEOUT); clicker.clickOnScreen(view); } /** * Clicks on a given View. * * @param view the {@link View} to be clicked * @param immediately true if view is to be clicked without any wait */ public void clickOnView(View view, boolean immediately){ if(immediately) clicker.clickOnScreen(view); else{ waiter.waitForView(view, SMALLTIMEOUT); clicker.clickOnScreen(view); } } /** * Long clicks on a given View. * * @param view the {@link View} to be long clicked * */ public void clickLongOnView(View view) { waiter.waitForView(view, SMALLTIMEOUT); clicker.clickOnScreen(view, true, 0); } /** * Long clicks on a given View for a given amount of time. * * @param view the {@link View} to be long clicked * @param time the amount of time to long click * */ public void clickLongOnView(View view, int time) { clicker.clickOnScreen(view, true, time); } /** * Clicks on a View displaying a given * text. Will automatically scroll when needed. * * @param text the text to be clicked. The parameter will be interpreted as a regular expression * */ public void clickOnText(String text) { clicker.clickOnText(text, false, 1, true, 0); } /** * Clicks on a View displaying a given text. Will automatically scroll when needed. * * @param text the text to be clicked. The parameter will be interpreted as a regular expression * @param match if multiple objects match the text, this determines which one will be clicked * */ public void clickOnText(String text, int match) { clicker.clickOnText(text, false, match, true, 0); } /** * Clicks on a View displaying a given text. * * @param text the text to be clicked. The parameter will be interpreted as a regular expression * @param match if multiple objects match the text, this determines which one will be clicked * @param scroll true if scrolling should be performed * */ public void clickOnText(String text, int match, boolean scroll) { clicker.clickOnText(text, false, match, scroll, 0); } /** * Long clicks on a given View. Will automatically scroll when needed. {@link #clickOnText(String)} can then be * used to click on the context menu items that appear after the long click. * * @param text the text to be clicked. The parameter will be interpreted as a regular expression * */ public void clickLongOnText(String text) { clicker.clickOnText(text, true, 1, true, 0); } /** * Long clicks on a given View. Will automatically scroll when needed. {@link #clickOnText(String)} can then be * used to click on the context menu items that appear after the long click. * * @param text the text to be clicked. The parameter will be interpreted as a regular expression * @param match if multiple objects match the text, this determines which one will be clicked * */ public void clickLongOnText(String text, int match) { clicker.clickOnText(text, true, match, true, 0); } /** * Long clicks on a given View. {@link #clickOnText(String)} can then be * used to click on the context menu items that appear after the long click. * * @param text the text to be clicked. The parameter will be interpreted as a regular expression * @param match if multiple objects match the text, this determines which one will be clicked * @param scroll true if scrolling should be performed * */ public void clickLongOnText(String text, int match, boolean scroll) { clicker.clickOnText(text, true, match, scroll, 0); } /** * Long clicks on a given View. {@link #clickOnText(String)} can then be * used to click on the context menu items that appear after the long click. * * @param text the text to be clicked. The parameter will be interpreted as a regular expression * @param match if multiple objects match the text, this determines which one will be clicked * @param time the amount of time to long click */ public void clickLongOnText(String text, int match, int time) { clicker.clickOnText(text, true, match, true, time); } /** * Long clicks on a given View and then selects * an item from the context menu that appears. Will automatically scroll when needed. * * @param text the text to be clicked. The parameter will be interpreted as a regular expression * @param index the index of the menu item to be pressed. {@code 0} if only one is available * */ public void clickLongOnTextAndPress(String text, int index) { clicker.clickLongOnTextAndPress(text, index); } /** * Clicks on a Button with a given index. * * @param index the index of the {@link Button} to be clicked. {@code 0} if only one is available * */ public void clickOnButton(int index) { clicker.clickOn(Button.class, index); } /** * Clicks on a RadioButton with a given index. * * @param index the index of the {@link RadioButton} to be clicked. {@code 0} if only one is available * */ public void clickOnRadioButton(int index) { clicker.clickOn(RadioButton.class, index); } /** * Clicks on a CheckBox with a given index. * * @param index the index of the {@link CheckBox} to be clicked. {@code 0} if only one is available * */ public void clickOnCheckBox(int index) { clicker.clickOn(CheckBox.class, index); } /** * Clicks on an EditText with a given index. * * @param index the index of the {@link EditText} to be clicked. {@code 0} if only one is available * */ public void clickOnEditText(int index) { clicker.clickOn(EditText.class, index); } /** * Clicks on a given list line and returns an ArrayList of the TextView objects that * the list line is showing. Will use the first list it finds. * * @param line the line to be clicked * @return an {@code ArrayList} of the {@link TextView} objects located in the list line * */ public ArrayList<TextView> clickInList(int line) { return clicker.clickInList(line); } /** * Clicks on a given list line on a specified list and * returns an ArrayList of the TextView objects that the list line is showing. * * @param line the line to be clicked * @param index the index of the list. 1 if two lists are available * @return an {@code ArrayList} of the {@link TextView} objects located in the list line * */ public ArrayList<TextView> clickInList(int line, int index) { return clicker.clickInList(line, index, false, 0); } /** * Long clicks on a given list line and returns an ArrayList of the TextView objects that * the list line is showing. Will use the first list it finds. * * @param line the line to be clicked * @return an {@code ArrayList} of the {@link TextView} objects located in the list line * */ public ArrayList<TextView> clickLongInList(int line){ return clicker.clickInList(line, 0, true, 0); } /** * Long clicks on a given list line on a specified list and * returns an ArrayList of the TextView objects that the list line is showing. * * @param line the line to be clicked * @param index the index of the list. 1 if two lists are available * @return an {@code ArrayList} of the {@link TextView} objects located in the list line * */ public ArrayList<TextView> clickLongInList(int line, int index){ return clicker.clickInList(line, index, true, 0); } /** * Long clicks on a given list line on a specified list and * returns an ArrayList of the TextView objects that the list line is showing. * * @param line the line to be clicked * @param index the index of the list. 1 if two lists are available * @param time the amount of time to long click * @return an {@code ArrayList} of the {@link TextView} objects located in the list line * */ public ArrayList<TextView> clickLongInList(int line, int index, int time){ return clicker.clickInList(line, index, true, time); } /** * Clicks on an ActionBar item with a given resource id. * * @param resourceId the R.id of the ActionBar item */ public void clickOnActionBarItem(int resourceId){ clicker.clickOnActionBarItem(resourceId); } /** * Clicks on an ActionBar Home/Up button. */ public void clickOnActionBarHomeButton() { clicker.clickOnActionBarHomeButton(); } /** * Simulate touching a given location and dragging it to a new location. * * This method was copied from {@code TouchUtils.java} in the Android Open Source Project, and modified here. * * @param fromX X coordinate of the initial touch, in screen coordinates * @param toX X coordinate of the drag destination, in screen coordinates * @param fromY X coordinate of the initial touch, in screen coordinates * @param toY Y coordinate of the drag destination, in screen coordinates * @param stepCount How many move steps to include in the drag * */ public void drag(float fromX, float toX, float fromY, float toY, int stepCount) { scroller.drag(fromX, toX, fromY, toY, stepCount); } /** * Scrolls down the screen. * * @return {@code true} if more scrolling can be done and {@code false} if it is at the end of * the screen * */ public boolean scrollDown() { waiter.waitForViews(AbsListView.class, ScrollView.class); return scroller.scroll(Scroller.DOWN); } /** * Scrolls to the bottom of the screen. */ public void scrollToBottom() { waiter.waitForViews(AbsListView.class, ScrollView.class); scroller.scroll(Scroller.DOWN, true); } /** * Scrolls up the screen. * * @return {@code true} if more scrolling can be done and {@code false} if it is at the top of * the screen * */ public boolean scrollUp(){ waiter.waitForViews(AbsListView.class, ScrollView.class); return scroller.scroll(Scroller.UP); } /** * Scrolls to the top of the screen. */ public void scrollToTop() { waiter.waitForViews(AbsListView.class, ScrollView.class); scroller.scroll(Scroller.UP, true); } /** * Scrolls down a given list. * * @param list the {@link AbsListView} to be scrolled * @return {@code true} if more scrolling can be done * */ public boolean scrollDownList(AbsListView list) { return scroller.scrollList(list, Scroller.DOWN, false); } /** * Scrolls to the bottom of a given list. * * @param list the {@link AbsListView} to be scrolled * @return {@code true} if more scrolling can be done * */ public boolean scrollListToBottom(AbsListView list) { return scroller.scrollList(list, Scroller.DOWN, true); } /** * Scrolls up a given list. * * @param list the {@link AbsListView} to be scrolled * @return {@code true} if more scrolling can be done * */ public boolean scrollUpList(AbsListView list) { return scroller.scrollList(list, Scroller.UP, false); } /** * Scrolls to the top of a given list. * * @param list the {@link AbsListView} to be scrolled * @return {@code true} if more scrolling can be done * */ public boolean scrollListToTop(AbsListView list) { return scroller.scrollList(list, Scroller.UP, true); } /** * Scrolls down a list with a given index. * * @param index the {@link ListView} to be scrolled. {@code 0} if only one list is available * @return {@code true} if more scrolling can be done * */ public boolean scrollDownList(int index) { return scroller.scrollList(waiter.waitForAndGetView(index, ListView.class), Scroller.DOWN, false); } /** * Scrolls a list with a given index to the bottom. * * @param index the {@link ListView} to be scrolled. {@code 0} if only one list is available * @return {@code true} if more scrolling can be done * */ public boolean scrollListToBottom(int index) { return scroller.scrollList(waiter.waitForAndGetView(index, ListView.class), Scroller.DOWN, true); } /** * Scrolls up a list with a given index. * * @param index the {@link ListView} to be scrolled. {@code 0} if only one list is available * @return {@code true} if more scrolling can be done * */ public boolean scrollUpList(int index) { return scroller.scrollList(waiter.waitForAndGetView(index, ListView.class), Scroller.UP, false); } /** * Scrolls a list with a given index to the top. * * @param index the {@link ListView} to be scrolled. {@code 0} if only one list is available * @return {@code true} if more scrolling can be done * */ public boolean scrollListToTop(int index) { return scroller.scrollList(waiter.waitForAndGetView(index, ListView.class), Scroller.UP, true); } /** * Scrolls horizontally. * * @param side the side to which to scroll; {@link #RIGHT} or {@link #LEFT} * */ public void scrollToSide(int side) { switch (side){ case RIGHT: scroller.scrollToSide(Scroller.Side.RIGHT); break; case LEFT: scroller.scrollToSide(Scroller.Side.LEFT); break; } } /** * Sets the date in a DatePicker with a given index. * * @param index the index of the {@link DatePicker}. {@code 0} if only one is available * @param year the year e.g. 2011 * @param monthOfYear the month which starts from zero e.g. 0 for January * @param dayOfMonth the day e.g. 10 * */ public void setDatePicker(int index, int year, int monthOfYear, int dayOfMonth) { setDatePicker(waiter.waitForAndGetView(index, DatePicker.class), year, monthOfYear, dayOfMonth); } /** * Sets the date in a given DatePicker. * * @param datePicker the {@link DatePicker} object. * @param year the year e.g. 2011 * @param monthOfYear the month which starts from zero e.g. 03 for April * @param dayOfMonth the day e.g. 10 * */ public void setDatePicker(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) { waiter.waitForView(datePicker, SMALLTIMEOUT); setter.setDatePicker(datePicker, year, monthOfYear, dayOfMonth); } /** * Sets the time in a TimePicker with a given index. * * @param index the index of the {@link TimePicker}. {@code 0} if only one is available * @param hour the hour e.g. 15 * @param minute the minute e.g. 30 * */ public void setTimePicker(int index, int hour, int minute) { setTimePicker(waiter.waitForAndGetView(index, TimePicker.class), hour, minute); } /** * Sets the time in a given TimePicker. * * @param timePicker the {@link TimePicker} object. * @param hour the hour e.g. 15 * @param minute the minute e.g. 30 * */ public void setTimePicker(TimePicker timePicker, int hour, int minute) { waiter.waitForView(timePicker, SMALLTIMEOUT); setter.setTimePicker(timePicker, hour, minute); } /** * Sets the progress of a ProgressBar with a given index. Examples are SeekBar and RatingBar. * * @param index the index of the {@link ProgressBar} * @param progress the progress that the {@link ProgressBar} should be set to * */ public void setProgressBar(int index, int progress){ setProgressBar(waiter.waitForAndGetView(index, ProgressBar.class),progress); } /** * Sets the progress of a given ProgressBar. Examples are SeekBar and RatingBar. * * @param progressBar the {@link ProgressBar} * @param progress the progress that the {@link ProgressBar} should be set to * */ public void setProgressBar(ProgressBar progressBar, int progress){ waiter.waitForView(progressBar, SMALLTIMEOUT); setter.setProgressBar(progressBar, progress); } /** * Sets the status of a SlidingDrawer with a given index. Examples are Solo.CLOSED and Solo.OPENED. * * @param index the index of the {@link SlidingDrawer} * @param status the status that the {@link SlidingDrawer} should be set to * */ public void setSlidingDrawer(int index, int status){ setSlidingDrawer(waiter.waitForAndGetView(index, SlidingDrawer.class),status); } /** * Sets the status of a given SlidingDrawer. Examples are Solo.CLOSED and Solo.OPENED. * * @param slidingDrawer the {@link SlidingDrawer} * @param status the status that the {@link SlidingDrawer} should be set to * */ public void setSlidingDrawer(SlidingDrawer slidingDrawer, int status){ waiter.waitForView(slidingDrawer, SMALLTIMEOUT); setter.setSlidingDrawer(slidingDrawer, status); } /** * Enters text in an EditText with a given index. * * @param index the index of the {@link EditText}. {@code 0} if only one is available * @param text the text string to enter into the {@link EditText} field * */ public void enterText(int index, String text) { textEnterer.setEditText(waiter.waitForAndGetView(index, EditText.class), text); } /** * Enters text in a given EditText. * * @param editText the {@link EditText} to enter text into * @param text the text string to enter into the {@link EditText} field * */ public void enterText(EditText editText, String text) { waiter.waitForView(editText, SMALLTIMEOUT); textEnterer.setEditText(editText, text); } /** * Types text in an EditText with a given index. * * @param index the index of the {@link EditText}. {@code 0} if only one is available * @param text the text string to type in the {@link EditText} field * */ public void typeText(int index, String text) { textEnterer.typeText(waiter.waitForAndGetView(index, EditText.class), text); } /** * Types text in a given EditText. * * @param editText the {@link EditText} to type text in * @param text the text string to type in the {@link EditText} field * */ public void typeText(EditText editText, String text) { waiter.waitForView(editText, SMALLTIMEOUT); textEnterer.typeText(editText, text); } /** * Clears the value of an EditText. * * @param index the index of the {@link EditText} that should be cleared. 0 if only one is available * */ public void clearEditText(int index) { textEnterer.setEditText(waiter.waitForAndGetView(index, EditText.class), ""); } /** * Clears the value of an EditText. * * @param editText the {@link EditText} that should be cleared * */ public void clearEditText(EditText editText) { waiter.waitForView(editText, SMALLTIMEOUT); textEnterer.setEditText(editText, ""); } /** * Clicks on an ImageView with a given index. * * @param index the index of the {@link ImageView} to be clicked. {@code 0} if only one is available * */ public void clickOnImage(int index) { clicker.clickOn(ImageView.class, index); } /** * Returns an EditText with a given index. * * @param index the index of the {@link EditText}. {@code 0} if only one is available * @return the {@link EditText} with a specified index or {@code null} if index is invalid * */ public EditText getEditText(int index) { return getter.getView(EditText.class, index); } /** * Returns a Button with a given index. * * @param index the index of the {@link Button}. {@code 0} if only one is available * @return the {@link Button} with a specified index or {@code null} if index is invalid * */ public Button getButton(int index) { return getter.getView(Button.class, index); } /** * Returns a TextView with a given index. * * @param index the index of the {@link TextView}. {@code 0} if only one is available * @return the {@link TextView} with a specified index or {@code null} if index is invalid * */ public TextView getText(int index) { return getter.getView(TextView.class, index); } /** * Returns an ImageView with a given index. * * @param index the index of the {@link ImageView}. {@code 0} if only one is available * @return the {@link ImageView} with a specified index or {@code null} if index is invalid * */ public ImageView getImage(int index) { return getter.getView(ImageView.class, index); } /** * Returns an ImageButton with a given index. * * @param index the index of the {@link ImageButton}. {@code 0} if only one is available * @return the {@link ImageButton} with a specified index or {@code null} if index is invalid * */ public ImageButton getImageButton(int index) { return getter.getView(ImageButton.class, index); } /** * Returns a TextView which shows a given text. * * @param text the text that is shown * @return the {@link TextView} that shows the given text */ public TextView getText(String text) { return getter.getView(TextView.class, text, false); } /** * Returns a TextView which shows a given text. * * @param text the text that is shown * @param onlyVisible {@code true} if only visible texts on the screen should be returned * @return the {@link TextView} that shows the given text */ public TextView getText(String text, boolean onlyVisible) { return getter.getView(TextView.class, text, onlyVisible); } /** * Returns a Button which shows a given text. * * @param text the text that is shown * @return the {@link Button} that shows the given text */ public Button getButton(String text) { return getter.getView(Button.class, text, false); } /** * Returns a Button which shows a given text. * * @param text the text that is shown * @param onlyVisible {@code true} if only visible buttons on the screen should be returned * @return the {@link Button} that shows the given text */ public Button getButton(String text, boolean onlyVisible) { return getter.getView(Button.class, text, onlyVisible); } /** * Returns an EditText which shows a given text. * * @param text the text that is shown * @return the {@link EditText} which shows the given text */ public EditText getEditText(String text) { return getter.getView(EditText.class, text, false); } /** * Returns an EditText which shows a given text. * * @param text the text that is shown * @param onlyVisible {@code true} if only visible EditTexts on the screen should be returned * @return the {@link EditText} which shows the given text */ public EditText getEditText(String text, boolean onlyVisible) { return getter.getView(EditText.class, text, onlyVisible); } /** * Returns a View with a given resource id. * * @param id the R.id of the {@link View} to be returned * @return a {@link View} with a given id */ public View getView(int id){ return getter.getView(id); } /** * Returns a View of a given class and index. * * @param viewClass the class of the requested view * @param index the index of the {@link View}. {@code 0} if only one is available * @return a {@link View} with a given class and index */ public <T extends View> View getView(Class<T> viewClass, int index){ return waiter.waitForAndGetView(index, viewClass); } /** * Returns an ArrayList of the View objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link View} objects currently shown in the * focused window * */ public ArrayList<View> getCurrentViews() { return viewFetcher.getViews(null, true); } /** * Returns an ArrayList of the ImageView objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link ImageView} objects currently shown in the * focused window * */ public ArrayList<ImageView> getCurrentImageViews() { return viewFetcher.getCurrentViews(ImageView.class); } /** * Returns an ArrayList of the ImageView objects currently shown in the focused * Activity or Dialog. * * @param parent the parent {@link View} from which the {@link ImageView} objects should be returned. {@code null} if * all TextView objects from the currently focused window e.g. Activity should be returned * * @return an {@code ArrayList} of the {@link ImageView} objects currently shown in the * focused window * */ public ArrayList<ImageView> getCurrentImageViews(View parent) { return viewFetcher.getCurrentViews(ImageView.class, parent); } /** * Returns an ArrayList of the EditText objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link EditText} objects currently shown in the * focused window * */ public ArrayList<EditText> getCurrentEditTexts() { return viewFetcher.getCurrentViews(EditText.class); } /** * Returns an ArrayList of the ListView objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link ListView} objects currently shown in the * focused window * */ public ArrayList<ListView> getCurrentListViews() { return viewFetcher.getCurrentViews(ListView.class); } /** * Returns an ArrayList of the ScrollView objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link ScrollView} objects currently shown in the * focused window * */ public ArrayList<ScrollView> getCurrentScrollViews() { return viewFetcher.getCurrentViews(ScrollView.class); } /** * Returns an ArrayList of the Spinner objects (drop-down menus) currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link Spinner} objects (drop-down menus) currently shown in the * focused window * */ public ArrayList<Spinner> getCurrentSpinners() { return viewFetcher.getCurrentViews(Spinner.class); } /** * Returns an ArrayList of the TextView objects currently shown in the focused * Activity or Dialog. * * @param parent the parent {@link View} from which the {@link TextView} objects should be returned. {@code null} if * all TextView objects from the currently focused window e.g. Activity should be returned * * @return an {@code ArrayList} of the {@link TextView} objects currently shown in the * focused window * */ public ArrayList<TextView> getCurrentTextViews(View parent) { return viewFetcher.getCurrentViews(TextView.class, parent); } /** * Returns an ArrayList of the GridView objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link GridView} objects currently shown in the * focused window * */ public ArrayList<GridView> getCurrentGridViews() { return viewFetcher.getCurrentViews(GridView.class); } /** * Returns an ArrayList of the Button objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link Button} objects currently shown in the * focused window * */ public ArrayList<Button> getCurrentButtons() { return viewFetcher.getCurrentViews(Button.class); } /** * Returns an ArrayList of the ToggleButton objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link ToggleButton} objects currently shown in the * focused window * */ public ArrayList<ToggleButton> getCurrentToggleButtons() { return viewFetcher.getCurrentViews(ToggleButton.class); } /** * Returns an ArrayList of the RadioButton objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link RadioButton} objects currently shown in the * focused window * */ public ArrayList<RadioButton> getCurrentRadioButtons() { return viewFetcher.getCurrentViews(RadioButton.class); } /** * Returns an ArrayList of the CheckBox objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link CheckBox} objects currently shown in the * focused window * */ public ArrayList<CheckBox> getCurrentCheckBoxes() { return viewFetcher.getCurrentViews(CheckBox.class); } /** * Returns an ArrayList of the ImageButton objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link ImageButton} objects currently shown in the * focused window * */ public ArrayList<ImageButton> getCurrentImageButtons() { return viewFetcher.getCurrentViews(ImageButton.class); } /** * Returns an ArrayList of the DatePicker objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link DatePicker} objects currently shown in the * focused window * */ public ArrayList<DatePicker> getCurrentDatePickers() { return viewFetcher.getCurrentViews(DatePicker.class); } /** * Returns an ArrayList of the TimePicker objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link TimePicker} objects currently shown in the * focused window * */ public ArrayList<TimePicker> getCurrentTimePickers() { return viewFetcher.getCurrentViews(TimePicker.class); } /** * Returns an ArrayList of the NumberPicker objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link NumberPicker} objects currently shown in the * focused window * */ @SuppressWarnings({ "rawtypes", "unchecked" }) public ArrayList getCurrentNumberPickers() { try { Class numberPickerClass = Class.forName("android.widget.NumberPicker"); if (numberPickerClass != null) { return viewFetcher.getCurrentViews(numberPickerClass); } } catch(ClassNotFoundException cnfe) { cnfe.printStackTrace(); } return null; } /** * Returns an ArrayList of the SlidingDrawer objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link SlidingDrawer} objects currently shown in the * focused window * */ public ArrayList<SlidingDrawer> getCurrentSlidingDrawers() { return viewFetcher.getCurrentViews(SlidingDrawer.class); } /** * Returns an ArrayList of the ProgressBar objects currently shown in the focused * Activity or Dialog. * * @return an {@code ArrayList} of the {@link ProgressBar} objects currently shown in the * focused window * */ public ArrayList<ProgressBar> getCurrentProgressBars() { return viewFetcher.getCurrentViews(ProgressBar.class); } /** * Checks if a RadioButton with a given index is checked. * * @param index of the {@link RadioButton} to check. {@code 0} if only one is available * @return {@code true} if {@link RadioButton} is checked and {@code false} if it is not checked * */ public boolean isRadioButtonChecked(int index) { return checker.isButtonChecked(RadioButton.class, index); } /** * Checks if a RadioButton with a given text is checked. * * @param text the text that the {@link RadioButton} shows * @return {@code true} if a {@link RadioButton} with the given text is checked and {@code false} if it is not checked * */ public boolean isRadioButtonChecked(String text) { return checker.isButtonChecked(RadioButton.class, text); } /** * Checks if a CheckBox with a given index is checked. * * @param index of the {@link CheckBox} to check. {@code 0} if only one is available * @return {@code true} if {@link CheckBox} is checked and {@code false} if it is not checked * */ public boolean isCheckBoxChecked(int index) { return checker.isButtonChecked(CheckBox.class, index); } /** * Checks if a ToggleButton with a given text is checked. * * @param text the text that the {@link ToggleButton} shows * @return {@code true} if a {@link ToggleButton} with the given text is checked and {@code false} if it is not checked * */ public boolean isToggleButtonChecked(String text) { return checker.isButtonChecked(ToggleButton.class, text); } /** * Checks if a ToggleButton with a given index is checked. * * @param index of the {@link ToggleButton} to check. {@code 0} if only one is available * @return {@code true} if {@link ToggleButton} is checked and {@code false} if it is not checked * */ public boolean isToggleButtonChecked(int index) { return checker.isButtonChecked(ToggleButton.class, index); } /** * Checks if a CheckBox with a given text is checked. * * @param text the text that the {@link CheckBox} shows * @return {@code true} if a {@link CheckBox} with the given text is checked and {@code false} if it is not checked * */ public boolean isCheckBoxChecked(String text) { return checker.isButtonChecked(CheckBox.class, text); } /** * Checks if the given text is checked. * * @param text the text that the {@link CheckedTextView} or {@link CompoundButton} objects show * @return {@code true} if the given text is checked and {@code false} if it is not checked */ public boolean isTextChecked(String text){ waiter.waitForViews(CheckedTextView.class, CompoundButton.class); if(viewFetcher.getCurrentViews(CheckedTextView.class).size() > 0 && checker.isCheckedTextChecked(text)) return true; if(viewFetcher.getCurrentViews(CompoundButton.class).size() > 0 && checker.isButtonChecked(CompoundButton.class, text)) return true; return false; } /** * Checks if a given text is selected in any Spinner located in the current screen. * * @param text the text that is expected to be selected * @return {@code true} if the given text is selected in any {@link Spinner} and false if it is not * */ public boolean isSpinnerTextSelected(String text) { return checker.isSpinnerTextSelected(text); } /** * Checks if a given text is selected in a given Spinner. * * @param index the index of the spinner to check. {@code 0} if only one spinner is available * @param text the text that is expected to be selected * @return true if the given text is selected in the given {@link Spinner} and false if it is not */ public boolean isSpinnerTextSelected(int index, String text) { return checker.isSpinnerTextSelected(index, text); } /** * Sends a key: Right, Left, Up, Down, Enter, Menu or Delete. * * @param key the key to be sent. Use {@code Solo.}{@link #RIGHT}, {@link #LEFT}, {@link #UP}, {@link #DOWN}, * {@link #ENTER}, {@link #MENU}, {@link #DELETE} * */ public void sendKey(int key) { robotiumUtils.sendKeyCode(key); } /** * Returns to the given Activity. * * @param name the name of the {@link Activity} to return to, e.g. {@code "MyActivity"} * */ public void goBackToActivity(String name) { activityUtils.goBackToActivity(name); } /** * Waits for the given Activity. Default timeout is 20 seconds. * * @param name the name of the {@code Activity} to wait for e.g. {@code "MyActivity"} * @return {@code true} if {@code Activity} appears before the timeout and {@code false} if it does not * */ public boolean waitForActivity(String name){ return waiter.waitForActivity(name, TIMEOUT); } /** * Waits for the given Activity. * * @param name the name of the {@link Activity} to wait for e.g. {@code "MyActivity"} * @param timeout the amount of time in milliseconds to wait * @return {@code true} if {@link Activity} appears before the timeout and {@code false} if it does not * */ public boolean waitForActivity(String name, int timeout) { return waiter.waitForActivity(name, timeout); } /** * Waits for a Fragment with a given tag to appear. Default timeout is 20 seconds. * * @param tag the name of the tag * @return true if fragment appears and false if it does not appear before the timeout * */ public boolean waitForFragmentByTag(String tag){ return waiter.waitForFragment(tag, 0, TIMEOUT); } /** * Waits for a Fragment with a given tag to appear. * * @param tag the name of the tag * @param timeout the amount of time in milliseconds to wait * @return true if fragment appears and false if it does not appear before the timeout * */ public boolean waitForFragmentByTag(String tag, int timeout){ return waiter.waitForFragment(tag, 0, timeout); } /** * Waits for a Fragment with a given id to appear. Default timeout is 20 seconds. * * @param id the id of the fragment * @return true if fragment appears and false if it does not appear before the timeout * */ public boolean waitForFragmentById(int id){ return waiter.waitForFragment(null, id, TIMEOUT); } /** * Waits for a Fragment with a given id to appear. * * @param id the id of the fragment * @param timeout the amount of time in milliseconds to wait * @return true if fragment appears and false if it does not appear before the timeout * */ public boolean waitForFragmentById(int id, int timeout){ return waiter.waitForFragment(null, id, timeout); } /** * Waits for a log message to appear. Default timeout is 20 seconds. * Requires read logs permission (android.permission.READ_LOGS) in AndroidManifest.xml of the application under test. * * @param logMessage the log message to wait for * * @return true if log message appears and false if it does not appear before the timeout */ public boolean waitForLogMessage(String logMessage){ return waiter.waitForLogMessage(logMessage, TIMEOUT); } /** * Waits for a log message to appear. * Requires read logs permission (android.permission.READ_LOGS) in AndroidManifest.xml of the application under test. * * @param logMessage the log message to wait for * @param timeout the amount of time in milliseconds to wait * * @return true if log message appears and false if it does not appear before the timeout */ public boolean waitForLogMessage(String logMessage, int timeout){ return waiter.waitForLogMessage(logMessage, timeout); } /** * Returns a localized string. * * @param resId the resource id of the string * @return the localized string * */ public String getString(int resId) { return activityUtils.getString(resId); } /** * Robotium will sleep for a specified time. * * @param time the time in milliseconds that Robotium should sleep * */ public void sleep(int time) { sleeper.sleep(time); } /** * * Finalizes the solo object and removes the ActivityMonitor. * * @see #finishOpenedActivities() finishOpenedActivities() to close the activities that have been active. * */ public void finalize() throws Throwable { activityUtils.finalize(); } /** * All inactive activities are finished. * * @deprecated Method has been deprecated as there are no longer strong references to activities. * */ public void finishInactiveActivities(){ activityUtils.finishInactiveActivities(); } /** * The activities that are alive are finished. Usually used in tearDown(). * */ public void finishOpenedActivities(){ activityUtils.finishOpenedActivities(); } /** * Takes a screenshot and saves it in "/sdcard/Robotium-Screenshots/". * Requires write permission (android.permission.WRITE_EXTERNAL_STORAGE) in AndroidManifest.xml of the application under test. * */ public void takeScreenshot(){ View decorView = viewFetcher.getRecentDecorView(viewFetcher.getWindowDecorViews()); robotiumUtils.takeScreenshot(decorView, null); } /** * Takes a screenshot and saves it with a given name in "/sdcard/Robotium-Screenshots/". * Requires write permission (android.permission.WRITE_EXTERNAL_STORAGE) in AndroidManifest.xml of the application under test. * * @param name the name to give the screenshot * */ public void takeScreenshot(String name){ View decorView = viewFetcher.getRecentDecorView(viewFetcher.getWindowDecorViews()); robotiumUtils.takeScreenshot(decorView, name); } }
Modified getCurrentNumberPickers to behave like the other getCurrent methods
robotium-solo/src/main/java/com/jayway/android/robotium/solo/Solo.java
Modified getCurrentNumberPickers to behave like the other getCurrent methods
<ide><path>obotium-solo/src/main/java/com/jayway/android/robotium/solo/Solo.java <ide> import android.widget.GridView; <ide> import android.widget.ImageButton; <ide> import android.widget.ImageView; <add>import android.widget.LinearLayout; <ide> import android.widget.ProgressBar; <ide> import android.widget.RadioButton; <ide> import android.widget.ScrollView; <ide> */ <ide> <ide> @SuppressWarnings({ "rawtypes", "unchecked" }) <del> public ArrayList getCurrentNumberPickers() { <add> public <T extends LinearLayout> ArrayList<T> getCurrentNumberPickers() { <ide> try { <ide> Class numberPickerClass = Class.forName("android.widget.NumberPicker"); <ide> if (numberPickerClass != null) { <ide> } catch(ClassNotFoundException cnfe) { <ide> cnfe.printStackTrace(); <ide> } <del> return null; <add> return new ArrayList<T>(); <ide> } <ide> <ide> /**
Java
apache-2.0
fdcd365c9d5f57540d58e13dfd6bcb5a2bc65844
0
facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho
// Copyright 2004-present Facebook. All Rights Reserved. package com.facebook.litho.widget; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.OrientationHelper; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView.OnScrollListener; import com.facebook.litho.Component; import com.facebook.litho.ComponentContext; import com.facebook.litho.ComponentInfo; import com.facebook.litho.ComponentTree; import com.facebook.litho.LayoutHandler; import com.facebook.litho.Size; import com.facebook.litho.SizeSpec; import com.facebook.litho.testing.testrunner.ComponentsTestRunner; import junit.framework.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RuntimeEnvironment; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Tests for {@link RecyclerBinder} */ @RunWith(ComponentsTestRunner.class) @PrepareForTest(ComponentTreeHolder.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"}) public class RecyclerBinderTest { @Rule public PowerMockRule mPowerMockRule = new PowerMockRule(); private static final float RANGE_RATIO = 2.0f; private static final int RANGE_SIZE = 3; private final Map<Component, TestComponentTreeHolder> mHoldersForComponents = new HashMap<>(); private RecyclerBinder mRecyclerBinder; private LayoutInfo mLayoutInfo; private ComponentContext mComponentContext; private final Answer<ComponentTreeHolder> mComponentTreeHolderAnswer = new Answer<ComponentTreeHolder>() { @Override public ComponentTreeHolder answer(InvocationOnMock invocation) throws Throwable { final ComponentInfo componentInfo = (ComponentInfo) invocation.getArguments()[0]; final TestComponentTreeHolder holder = new TestComponentTreeHolder(componentInfo); mHoldersForComponents.put(componentInfo.getComponent(), holder); return holder; } }; @Before public void setup() { mComponentContext = new ComponentContext(RuntimeEnvironment.application); PowerMockito.mockStatic(ComponentTreeHolder.class); PowerMockito.when(ComponentTreeHolder.acquire( any(ComponentInfo.class), any(LayoutHandler.class))) .thenAnswer(mComponentTreeHolderAnswer); mLayoutInfo = mock(LayoutInfo.class); setupBaseLayoutInfoMock(); mRecyclerBinder = new RecyclerBinder(mComponentContext, RANGE_RATIO, mLayoutInfo); } private void setupBaseLayoutInfoMock() { Mockito.when(mLayoutInfo.getScrollDirection()).thenReturn(OrientationHelper.VERTICAL); Mockito.when(mLayoutInfo.getLayoutManager()) .thenReturn(new LinearLayoutManager(mComponentContext)); Mockito.when(mLayoutInfo.approximateRangeSize(anyInt(), anyInt(), anyInt(), anyInt())) .thenReturn(RANGE_SIZE); Mockito.when(mLayoutInfo.getChildHeightSpec(anyInt())) .thenReturn(SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY)); Mockito.when(mLayoutInfo.getChildWidthSpec(anyInt())) .thenReturn(SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY)); } @Test public void testComponentTreeHolderCreation() { final List<ComponentInfo> components = new ArrayList<>(); for (int i = 0; i < 100; i++) { components.add(ComponentInfo.create().component(mock(Component.class)).build()); mRecyclerBinder.insertItemAt(0, components.get(i)); } for (int i = 0; i < 100; i++) { Assert.assertNotNull(mHoldersForComponents.get(components.get(i).getComponent())); } } @Test public void testOnMeasureAfterAddingItems() { final List<ComponentInfo> components = new ArrayList<>(); for (int i = 0; i < 100; i++) { components.add(ComponentInfo.create().component(mock(Component.class)).build()); mRecyclerBinder.insertItemAt(i, components.get(i)); } for (int i = 0; i < 100; i++) { Assert.assertNotNull(mHoldersForComponents.get(components.get(i).getComponent())); } final Size size = new Size(); final int widthSpec = SizeSpec.makeSizeSpec(200, SizeSpec.AT_MOST); final int heightSpec = SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY); mRecyclerBinder.measure(size, widthSpec, heightSpec); TestComponentTreeHolder componentTreeHolder = mHoldersForComponents.get(components.get(0).getComponent()); assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutSyncCalled); int rangeTotal = RANGE_SIZE + (int) (RANGE_SIZE * RANGE_RATIO); for (int i = 1; i <= rangeTotal; i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } for (int k = rangeTotal + 1; k < components.size(); k++) { componentTreeHolder = mHoldersForComponents.get(components.get(k).getComponent()); assertFalse(componentTreeHolder.isTreeValid()); assertFalse(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } Assert.assertEquals(100, size.width); } @Test public void onBoundsDefined() { final List<ComponentInfo> components = prepareLoadedBinder(); for (int i = 0; i < components.size(); i++) { final TestComponentTreeHolder holder = mHoldersForComponents.get(components.get(i).getComponent()); holder.mLayoutAsyncCalled = false; holder.mLayoutSyncCalled = false; } mRecyclerBinder.setSize(200, 200); for (int i = 0; i < components.size(); i++) { final TestComponentTreeHolder holder = mHoldersForComponents.get(components.get(i).getComponent()); assertFalse(holder.mLayoutAsyncCalled); assertFalse(holder.mLayoutSyncCalled); } } @Test public void onBoundsDefinedWithDifferentSize() { final List<ComponentInfo> components = prepareLoadedBinder(); for (int i = 0; i < components.size(); i++) { final TestComponentTreeHolder holder = mHoldersForComponents.get(components.get(i).getComponent()); holder.mLayoutAsyncCalled = false; holder.mLayoutSyncCalled = false; } mRecyclerBinder.setSize(300, 200); final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); TestComponentTreeHolder holder = mHoldersForComponents.get(components.get(0).getComponent()); assertTrue(holder.isTreeValid()); assertTrue(holder.mLayoutSyncCalled); for (int i = 1; i <= rangeTotal; i++) { holder = mHoldersForComponents.get(components.get(i).getComponent()); assertTrue(holder.isTreeValid()); assertTrue(holder.mLayoutAsyncCalled); } for (int i = rangeTotal + 1; i < components.size(); i++) { holder = mHoldersForComponents.get(components.get(i).getComponent()); assertFalse(holder.isTreeValid()); assertFalse(holder.mLayoutAsyncCalled); assertFalse(holder.mLayoutSyncCalled); } } @Test public void testMount() { RecyclerView recyclerView = mock(RecyclerView.class); mRecyclerBinder.mount(recyclerView); verify(recyclerView).setLayoutManager(mLayoutInfo.getLayoutManager()); verify(recyclerView).setAdapter(any(RecyclerView.Adapter.class)); verify(recyclerView).addOnScrollListener(any(OnScrollListener.class)); } @Test public void testMountGrid() { when(mLayoutInfo.getSpanCount()).thenReturn(2); GridLayoutManager gridLayoutManager = mock(GridLayoutManager.class); when(mLayoutInfo.getLayoutManager()).thenReturn(gridLayoutManager); RecyclerView recyclerView = mock(RecyclerView.class); mRecyclerBinder.mount(recyclerView); verify(recyclerView).setLayoutManager(mLayoutInfo.getLayoutManager()); verify(gridLayoutManager).setSpanSizeLookup(any(GridLayoutManager.SpanSizeLookup.class)); verify(recyclerView).setAdapter(any(RecyclerView.Adapter.class)); verify(recyclerView).addOnScrollListener(any(OnScrollListener.class)); } @Test public void testMountWithStaleView() { RecyclerView recyclerView = mock(RecyclerView.class); mRecyclerBinder.mount(recyclerView); verify(recyclerView).setLayoutManager(mLayoutInfo.getLayoutManager()); verify(recyclerView).setAdapter(any(RecyclerView.Adapter.class)); verify(recyclerView).addOnScrollListener(any(OnScrollListener.class)); RecyclerView secondRecyclerView = mock(RecyclerView.class); mRecyclerBinder.mount(secondRecyclerView); verify(recyclerView).setLayoutManager(null); verify(recyclerView).setAdapter(null); verify(recyclerView).removeOnScrollListener(any(OnScrollListener.class)); verify(secondRecyclerView).setLayoutManager(mLayoutInfo.getLayoutManager()); verify(secondRecyclerView).setAdapter(any(RecyclerView.Adapter.class)); verify(secondRecyclerView).addOnScrollListener(any(OnScrollListener.class)); } @Test public void testUnmount() { RecyclerView recyclerView = mock(RecyclerView.class); mRecyclerBinder.mount(recyclerView); verify(recyclerView).setLayoutManager(mLayoutInfo.getLayoutManager()); verify(recyclerView).setAdapter(any(RecyclerView.Adapter.class)); verify(recyclerView).addOnScrollListener(any(OnScrollListener.class)); mRecyclerBinder.unmount(recyclerView); verify(recyclerView).setLayoutManager(null); verify(recyclerView).setAdapter(null); verify(recyclerView).removeOnScrollListener(any(OnScrollListener.class)); } @Test public void testUnmountGrid() { when(mLayoutInfo.getSpanCount()).thenReturn(2); GridLayoutManager gridLayoutManager = mock(GridLayoutManager.class); when(mLayoutInfo.getLayoutManager()).thenReturn(gridLayoutManager); RecyclerView recyclerView = mock(RecyclerView.class); mRecyclerBinder.mount(recyclerView); verify(recyclerView).setLayoutManager(mLayoutInfo.getLayoutManager()); verify(gridLayoutManager).setSpanSizeLookup(any(GridLayoutManager.SpanSizeLookup.class)); verify(recyclerView).setAdapter(any(RecyclerView.Adapter.class)); verify(recyclerView).addOnScrollListener(any(OnScrollListener.class)); mRecyclerBinder.unmount(recyclerView); verify(recyclerView).setLayoutManager(null); verify(gridLayoutManager).setSpanSizeLookup(null); verify(recyclerView).setAdapter(null); verify(recyclerView).removeOnScrollListener(any(OnScrollListener.class)); } @Test public void onRemeasureWithDifferentSize() { final List<ComponentInfo> components = prepareLoadedBinder(); for (int i = 0; i < components.size(); i++) { final TestComponentTreeHolder holder = mHoldersForComponents.get(components.get(i).getComponent()); holder.mLayoutAsyncCalled = false; holder.mLayoutSyncCalled = false; } int widthSpec = SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY); int heightSpec = SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY); mRecyclerBinder.measure(new Size(), widthSpec, heightSpec); final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); TestComponentTreeHolder holder = mHoldersForComponents.get(components.get(0).getComponent()); assertTrue(holder.isTreeValid()); assertTrue(holder.mLayoutSyncCalled); for (int i = 1; i <= rangeTotal; i++) { holder = mHoldersForComponents.get(components.get(i).getComponent()); assertTrue(holder.isTreeValid()); assertTrue(holder.mLayoutAsyncCalled); } for (int i = rangeTotal + 1; i < components.size(); i++) { holder = mHoldersForComponents.get(components.get(i).getComponent()); assertFalse(holder.isTreeValid()); assertFalse(holder.mLayoutAsyncCalled); assertFalse(holder.mLayoutSyncCalled); } } @Test public void testComponentWithDifferentSpanSize() { Mockito.when(mLayoutInfo.getLayoutManager()) .thenReturn(new GridLayoutManager(mComponentContext, 2)); final List<ComponentInfo> components = new ArrayList<>(); for (int i = 0; i < 100; i++) { components.add(ComponentInfo.create() .component(mock(Component.class)) .spanSize((i == 0 || i % 3 == 0) ? 2 : 1) .build()); mRecyclerBinder.insertItemAt(i, components.get(i)); } for (int i = 0; i < 100; i++) { Assert.assertNotNull(mHoldersForComponents.get(components.get(i).getComponent())); } Size size = new Size(); int widthSpec = SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY); int heightSpec = SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY); mRecyclerBinder.measure(size, widthSpec, heightSpec); TestComponentTreeHolder componentTreeHolder = mHoldersForComponents.get(components.get(0).getComponent()); assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutSyncCalled); Assert.assertEquals(200, size.width); final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); for (int i = 1; i <= rangeTotal; i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutAsyncCalled); final int expectedWidth = i % 3 == 0 ? 200 : 100; Assert.assertEquals(expectedWidth, componentTreeHolder.mChildWidth); Assert.assertEquals(100, componentTreeHolder.mChildHeight); } } @Test public void testAddItemsAfterMeasuring() { final Size size = new Size(); final int widthSpec = SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY); final int heightSpec = SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY); mRecyclerBinder.measure(size, widthSpec, heightSpec); Assert.assertEquals(200, size.width); final List<ComponentInfo> components = new ArrayList<>(); for (int i = 0; i < 100; i++) { components.add(ComponentInfo.create().component(mock(Component.class)).build()); mRecyclerBinder.insertItemAt(i, components.get(i)); } for (int i = 0; i < 100; i++) { Assert.assertNotNull(mHoldersForComponents.get(components.get(i).getComponent())); } TestComponentTreeHolder componentTreeHolder; int rangeTotal = RANGE_SIZE + (int) (RANGE_SIZE * RANGE_RATIO); for (int i = 0; i < RANGE_SIZE; i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutSyncCalled); } for (int i = RANGE_SIZE ; i <= rangeTotal; i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } for (int i = rangeTotal + 1; i < components.size(); i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); assertFalse(componentTreeHolder.isTreeValid()); assertFalse(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } } @Test public void testRangeBiggerThanContent() { final List<ComponentInfo> components = new ArrayList<>(); for (int i = 0; i < 2; i++) { components.add(ComponentInfo.create().component(mock(Component.class)).build()); mRecyclerBinder.insertItemAt(i, components.get(i)); } for (int i = 0; i < 2; i++) { Assert.assertNotNull(mHoldersForComponents.get(components.get(i).getComponent())); } Size size = new Size(); int widthSpec = SizeSpec.makeSizeSpec(200, SizeSpec.AT_MOST); int heightSpec = SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY); mRecyclerBinder.measure(size, widthSpec, heightSpec); TestComponentTreeHolder componentTreeHolder = mHoldersForComponents.get(components.get(0).getComponent()); assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutSyncCalled); for (int i = 1; i < 2; i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } Assert.assertEquals(100, size.width); } @Test public void testMoveRange() { final List<ComponentInfo> components = prepareLoadedBinder(); final int newRangeStart = 40; final int newRangeEnd = 42; final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); mRecyclerBinder.onNewVisibleRange(newRangeStart, newRangeEnd); TestComponentTreeHolder componentTreeHolder; for (int i = 0; i < components.size(); i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); if (i >= newRangeStart - (RANGE_RATIO * RANGE_SIZE) && i <= newRangeStart + rangeTotal) { assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } else { assertFalse(componentTreeHolder.isTreeValid()); assertFalse(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); if (i <= rangeTotal) { assertTrue(componentTreeHolder.mDidAcquireStateHandler); } else { assertFalse(componentTreeHolder.mDidAcquireStateHandler); } } } } @Test public void testRealRangeOverridesEstimatedRange() { final List<ComponentInfo> components = prepareLoadedBinder(); final int newRangeStart = 40; final int newRangeEnd = 50; int rangeSize = newRangeEnd - newRangeStart; final int rangeTotal = (int) (rangeSize + (RANGE_RATIO * rangeSize)); mRecyclerBinder.onNewVisibleRange(newRangeStart, newRangeEnd); TestComponentTreeHolder componentTreeHolder; for (int i = 0; i < components.size(); i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); if (i >= newRangeStart - (RANGE_RATIO * rangeSize) && i <= newRangeStart + rangeTotal) { assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } else { assertFalse(componentTreeHolder.isTreeValid()); assertFalse(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } } } @Test public void testMoveRangeToEnd() { final List<ComponentInfo> components = prepareLoadedBinder(); final int newRangeStart = 99; final int newRangeEnd = 99; final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); mRecyclerBinder.onNewVisibleRange(newRangeStart, newRangeEnd); TestComponentTreeHolder componentTreeHolder; for (int i = 0; i < components.size(); i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); if (i >= newRangeStart - (RANGE_RATIO * RANGE_SIZE) && i <= newRangeStart + rangeTotal) { assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } else { assertFalse(componentTreeHolder.isTreeValid()); assertFalse(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); if (i <= rangeTotal) { assertTrue(componentTreeHolder.mDidAcquireStateHandler); } else { assertFalse(componentTreeHolder.mDidAcquireStateHandler); } } } } @Test public void testMoveItemOutsideFromRange() { final List<ComponentInfo> components = prepareLoadedBinder(); mRecyclerBinder.moveItem(0, 99); final TestComponentTreeHolder movedHolder = mHoldersForComponents.get(components.get(0).getComponent()); assertFalse(movedHolder.isTreeValid()); assertFalse(movedHolder.mLayoutAsyncCalled); assertFalse(movedHolder.mLayoutSyncCalled); assertTrue(movedHolder.mDidAcquireStateHandler); final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); final TestComponentTreeHolder holderMovedIntoRange = mHoldersForComponents.get(components.get(rangeTotal + 1).getComponent()); assertTrue(holderMovedIntoRange.isTreeValid()); assertTrue(holderMovedIntoRange.mLayoutAsyncCalled); assertFalse(holderMovedIntoRange.mLayoutSyncCalled); } @Test public void testMoveItemInsideRange() { final List<ComponentInfo> components = prepareLoadedBinder(); mRecyclerBinder.moveItem(99, 4); TestComponentTreeHolder movedHolder = mHoldersForComponents.get(components.get(99).getComponent()); assertTrue(movedHolder.isTreeValid()); assertTrue(movedHolder.mLayoutAsyncCalled); assertFalse(movedHolder.mLayoutSyncCalled); assertFalse(movedHolder.mDidAcquireStateHandler); final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); TestComponentTreeHolder holderMovedOutsideRange = mHoldersForComponents.get(components.get(rangeTotal).getComponent()); assertFalse(holderMovedOutsideRange.isTreeValid()); assertFalse(holderMovedOutsideRange.mLayoutAsyncCalled); assertFalse(holderMovedOutsideRange.mLayoutSyncCalled); } @Test public void testMoveItemInsideVisibleRange() { final List<ComponentInfo> components = prepareLoadedBinder(); mRecyclerBinder.moveItem(99, 2); final TestComponentTreeHolder movedHolder = mHoldersForComponents.get(components.get(99).getComponent()); assertTrue(movedHolder.isTreeValid()); assertFalse(movedHolder.mLayoutAsyncCalled); assertTrue(movedHolder.mLayoutSyncCalled); assertFalse(movedHolder.mDidAcquireStateHandler); final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); final TestComponentTreeHolder holderMovedOutsideRange = mHoldersForComponents.get(components.get(rangeTotal).getComponent()); assertFalse(holderMovedOutsideRange.isTreeValid()); assertFalse(holderMovedOutsideRange.mLayoutAsyncCalled); assertFalse(holderMovedOutsideRange.mLayoutSyncCalled); assertTrue(holderMovedOutsideRange.mDidAcquireStateHandler); } @Test public void testMoveItemOutsideRange() { final List<ComponentInfo> components = prepareLoadedBinder(); mRecyclerBinder.moveItem(2, 99); final TestComponentTreeHolder movedHolder = mHoldersForComponents.get(components.get(2).getComponent()); assertFalse(movedHolder.isTreeValid()); assertFalse(movedHolder.mLayoutAsyncCalled); assertFalse(movedHolder.mLayoutSyncCalled); assertTrue(movedHolder.mDidAcquireStateHandler); final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); final TestComponentTreeHolder holderMovedInsideRange =
src/test/java/com/facebook/components/widget/RecyclerBinderTest.java
// Copyright 2004-present Facebook. All Rights Reserved. package com.facebook.litho.widget; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.OrientationHelper; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView.OnScrollListener; import com.facebook.litho.Component; import com.facebook.litho.ComponentContext; import com.facebook.litho.ComponentInfo; import com.facebook.litho.ComponentTree; import com.facebook.litho.LayoutHandler; import com.facebook.litho.Size; import com.facebook.litho.SizeSpec; import com.facebook.litho.testing.testrunner.ComponentsTestRunner; import junit.framework.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RuntimeEnvironment; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Tests for {@link RecyclerBinder} */ @RunWith(ComponentsTestRunner.class) @PrepareForTest(ComponentTreeHolder.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"}) public class RecyclerBinderTest { @Rule public PowerMockRule mPowerMockRule = new PowerMockRule(); private static final float RANGE_RATIO = 2.0f; private static final int RANGE_SIZE = 3; private final Map<Component, TestComponentTreeHolder> mHoldersForComponents = new HashMap<>(); private RecyclerBinder mRecyclerBinder; private LayoutInfo mLayoutInfo; private ComponentContext mComponentContext; private final Answer<ComponentTreeHolder> mComponentTreeHolderAnswer = new Answer<ComponentTreeHolder>() { @Override public ComponentTreeHolder answer(InvocationOnMock invocation) throws Throwable { final ComponentInfo componentInfo = (ComponentInfo) invocation.getArguments()[0]; final TestComponentTreeHolder holder = new TestComponentTreeHolder(componentInfo); mHoldersForComponents.put(componentInfo.getComponent(), holder); return holder; } }; @Before public void setup() { mComponentContext = new ComponentContext(RuntimeEnvironment.application); PowerMockito.mockStatic(ComponentTreeHolder.class); PowerMockito.when(ComponentTreeHolder.acquire( any(ComponentInfo.class), any(LayoutHandler.class))) .thenAnswer(mComponentTreeHolderAnswer); mLayoutInfo = mock(LayoutInfo.class); setupBaseLayoutInfoMock(); mRecyclerBinder = new RecyclerBinder(mComponentContext, RANGE_RATIO, mLayoutInfo); } private void setupBaseLayoutInfoMock() { Mockito.when(mLayoutInfo.getScrollDirection()).thenReturn(OrientationHelper.VERTICAL); Mockito.when(mLayoutInfo.getLayoutManager()) .thenReturn(new LinearLayoutManager(mComponentContext)); Mockito.when(mLayoutInfo.approximateRangeSize(anyInt(), anyInt(), anyInt(), anyInt())) .thenReturn(RANGE_SIZE); Mockito.when(mLayoutInfo.getChildHeightSpec(anyInt())) .thenReturn(SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY)); Mockito.when(mLayoutInfo.getChildWidthSpec(anyInt())) .thenReturn(SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY)); } @Test public void testComponentTreeHolderCreation() { final List<ComponentInfo> components = new ArrayList<>(); for (int i = 0; i < 100; i++) { components.add(ComponentInfo.create().component(mock(Component.class)).build()); mRecyclerBinder.insertItemAt(0, components.get(i)); } for (int i = 0; i < 100; i++) { Assert.assertNotNull(mHoldersForComponents.get(components.get(i).getComponent())); } } @Test public void testOnMeasureAfterAddingItems() { final List<ComponentInfo> components = new ArrayList<>(); for (int i = 0; i < 100; i++) { components.add(ComponentInfo.create().component(mock(Component.class)).build()); mRecyclerBinder.insertItemAt(i, components.get(i)); } for (int i = 0; i < 100; i++) { Assert.assertNotNull(mHoldersForComponents.get(components.get(i).getComponent())); } final Size size = new Size(); final int widthSpec = SizeSpec.makeSizeSpec(200, SizeSpec.AT_MOST); final int heightSpec = SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY); mRecyclerBinder.measure(size, widthSpec, heightSpec); TestComponentTreeHolder componentTreeHolder = mHoldersForComponents.get(components.get(0).getComponent()); assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutSyncCalled); int rangeTotal = RANGE_SIZE + (int) (RANGE_SIZE * RANGE_RATIO); for (int i = 1; i <= rangeTotal; i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } for (int k = rangeTotal + 1; k < components.size(); k++) { componentTreeHolder = mHoldersForComponents.get(components.get(k).getComponent()); assertFalse(componentTreeHolder.isTreeValid()); assertFalse(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } Assert.assertEquals(100, size.width); } @Test public void onBoundsDefined() { final List<ComponentInfo> components = prepareLoadedBinder(); for (int i = 0; i < components.size(); i++) { final TestComponentTreeHolder holder = mHoldersForComponents.get(components.get(i).getComponent()); holder.mLayoutAsyncCalled = false; holder.mLayoutSyncCalled = false; } mRecyclerBinder.setSize(200, 200); for (int i = 0; i < components.size(); i++) { final TestComponentTreeHolder holder = mHoldersForComponents.get(components.get(i).getComponent()); assertFalse(holder.mLayoutAsyncCalled); assertFalse(holder.mLayoutSyncCalled); } } @Test public void onBoundsDefinedWithDifferentSize() { final List<ComponentInfo> components = prepareLoadedBinder(); for (int i = 0; i < components.size(); i++) { final TestComponentTreeHolder holder = mHoldersForComponents.get(components.get(i).getComponent()); holder.mLayoutAsyncCalled = false; holder.mLayoutSyncCalled = false; } mRecyclerBinder.setSize(300, 200); final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); TestComponentTreeHolder holder = mHoldersForComponents.get(components.get(0).getComponent()); assertTrue(holder.isTreeValid()); assertTrue(holder.mLayoutSyncCalled); for (int i = 1; i <= rangeTotal; i++) { holder = mHoldersForComponents.get(components.get(i).getComponent()); assertTrue(holder.isTreeValid()); assertTrue(holder.mLayoutAsyncCalled); } for (int i = rangeTotal + 1; i < components.size(); i++) { holder = mHoldersForComponents.get(components.get(i).getComponent()); assertFalse(holder.isTreeValid()); assertFalse(holder.mLayoutAsyncCalled); assertFalse(holder.mLayoutSyncCalled); } } @Test public void testMount() { RecyclerView recyclerView = mock(RecyclerView.class); mRecyclerBinder.mount(recyclerView); verify(recyclerView).setLayoutManager(mLayoutInfo.getLayoutManager()); verify(recyclerView).setAdapter(any(RecyclerView.Adapter.class)); verify(recyclerView).addOnScrollListener(any(OnScrollListener.class)); } @Test public void testMountGrid() { when(mLayoutInfo.getSpanCount()).thenReturn(2); GridLayoutManager gridLayoutManager = mock(GridLayoutManager.class); when(mLayoutInfo.getLayoutManager()).thenReturn(gridLayoutManager); RecyclerView recyclerView = mock(RecyclerView.class); mRecyclerBinder.mount(recyclerView); verify(recyclerView).setLayoutManager(mLayoutInfo.getLayoutManager()); verify(gridLayoutManager).setSpanSizeLookup(any(GridLayoutManager.SpanSizeLookup.class)); verify(recyclerView).setAdapter(any(RecyclerView.Adapter.class)); verify(recyclerView).addOnScrollListener(any(OnScrollListener.class)); } @Test public void testMountWithStaleView() { RecyclerView recyclerView = mock(RecyclerView.class); mRecyclerBinder.mount(recyclerView); verify(recyclerView).setLayoutManager(mLayoutInfo.getLayoutManager()); verify(recyclerView).setAdapter(any(RecyclerView.Adapter.class)); verify(recyclerView).addOnScrollListener(any(OnScrollListener.class)); RecyclerView secondRecyclerView = mock(RecyclerView.class); mRecyclerBinder.mount(secondRecyclerView); verify(recyclerView).setLayoutManager(null); verify(recyclerView).setAdapter(null); verify(recyclerView).removeOnScrollListener(any(OnScrollListener.class)); verify(secondRecyclerView).setLayoutManager(mLayoutInfo.getLayoutManager()); verify(secondRecyclerView).setAdapter(any(RecyclerView.Adapter.class)); verify(secondRecyclerView).addOnScrollListener(any(OnScrollListener.class)); } @Test public void testUnmount() { RecyclerView recyclerView = mock(RecyclerView.class); mRecyclerBinder.mount(recyclerView); verify(recyclerView).setLayoutManager(mLayoutInfo.getLayoutManager()); verify(recyclerView).setAdapter(any(RecyclerView.Adapter.class)); verify(recyclerView).addOnScrollListener(any(OnScrollListener.class)); mRecyclerBinder.unmount(recyclerView); verify(recyclerView).setLayoutManager(null); verify(recyclerView).setAdapter(null); verify(recyclerView).removeOnScrollListener(any(OnScrollListener.class)); } @Test public void testUnmountGrid() { when(mLayoutInfo.getSpanCount()).thenReturn(2); GridLayoutManager gridLayoutManager = mock(GridLayoutManager.class); when(mLayoutInfo.getLayoutManager()).thenReturn(gridLayoutManager); RecyclerView recyclerView = mock(RecyclerView.class); mRecyclerBinder.mount(recyclerView); verify(recyclerView).setLayoutManager(mLayoutInfo.getLayoutManager()); verify(gridLayoutManager).setSpanSizeLookup(any(GridLayoutManager.SpanSizeLookup.class)); verify(recyclerView).setAdapter(any(RecyclerView.Adapter.class)); verify(recyclerView).addOnScrollListener(any(OnScrollListener.class)); mRecyclerBinder.unmount(recyclerView); verify(recyclerView).setLayoutManager(null); verify(gridLayoutManager).setSpanSizeLookup(null); verify(recyclerView).setAdapter(null); verify(recyclerView).removeOnScrollListener(any(OnScrollListener.class)); } @Test public void onRemeasureWithDifferentSize() { final List<ComponentInfo> components = prepareLoadedBinder(); for (int i = 0; i < components.size(); i++) { final TestComponentTreeHolder holder = mHoldersForComponents.get(components.get(i).getComponent()); holder.mLayoutAsyncCalled = false; holder.mLayoutSyncCalled = false; } int widthSpec = SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY); int heightSpec = SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY); mRecyclerBinder.measure(new Size(), widthSpec, heightSpec); final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); TestComponentTreeHolder holder = mHoldersForComponents.get(components.get(0).getComponent()); assertTrue(holder.isTreeValid()); assertTrue(holder.mLayoutSyncCalled); for (int i = 1; i <= rangeTotal; i++) { holder = mHoldersForComponents.get(components.get(i).getComponent()); assertTrue(holder.isTreeValid()); assertTrue(holder.mLayoutAsyncCalled); } for (int i = rangeTotal + 1; i < components.size(); i++) { holder = mHoldersForComponents.get(components.get(i).getComponent()); assertFalse(holder.isTreeValid()); assertFalse(holder.mLayoutAsyncCalled); assertFalse(holder.mLayoutSyncCalled); } } @Test public void testComponentWithDifferentSpanSize() { Mockito.when(mLayoutInfo.getLayoutManager()) .thenReturn(new GridLayoutManager(mComponentContext, 2)); final List<ComponentInfo> components = new ArrayList<>(); for (int i = 0; i < 100; i++) { components.add(ComponentInfo.create() .component(mock(Component.class)) .spanSize((i == 0 || i % 3 == 0) ? 2 : 1) .build()); mRecyclerBinder.insertItemAt(i, components.get(i)); } for (int i = 0; i < 100; i++) { Assert.assertNotNull(mHoldersForComponents.get(components.get(i).getComponent())); } Size size = new Size(); int widthSpec = SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY); int heightSpec = SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY); mRecyclerBinder.measure(size, widthSpec, heightSpec); TestComponentTreeHolder componentTreeHolder = mHoldersForComponents.get(components.get(0).getComponent()); assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutSyncCalled); Assert.assertEquals(200, size.width); final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); for (int i = 1; i <= rangeTotal; i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutAsyncCalled); final int expectedWidth = i % 3 == 0 ? 200 : 100; Assert.assertEquals(expectedWidth, componentTreeHolder.mChildWidth); Assert.assertEquals(100, componentTreeHolder.mChildHeight); } } @Test public void testAddItemsAfterMeasuring() { final Size size = new Size(); final int widthSpec = SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY); final int heightSpec = SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY); mRecyclerBinder.measure(size, widthSpec, heightSpec); Assert.assertEquals(200, size.width); final List<ComponentInfo> components = new ArrayList<>(); for (int i = 0; i < 100; i++) { components.add(ComponentInfo.create().component(mock(Component.class)).build()); mRecyclerBinder.insertItemAt(i, components.get(i)); } for (int i = 0; i < 100; i++) { Assert.assertNotNull(mHoldersForComponents.get(components.get(i).getComponent())); } TestComponentTreeHolder componentTreeHolder; int rangeTotal = RANGE_SIZE + (int) (RANGE_SIZE * RANGE_RATIO); for (int i = 0; i < RANGE_SIZE; i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutSyncCalled); } for (int i = RANGE_SIZE ; i <= rangeTotal; i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } for (int i = rangeTotal + 1; i < components.size(); i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); assertFalse(componentTreeHolder.isTreeValid()); assertFalse(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } } @Test public void testRangeBiggerThanContent() { final List<ComponentInfo> components = new ArrayList<>(); for (int i = 0; i < 2; i++) { components.add(ComponentInfo.create().component(mock(Component.class)).build()); mRecyclerBinder.insertItemAt(i, components.get(i)); } for (int i = 0; i < 2; i++) { Assert.assertNotNull(mHoldersForComponents.get(components.get(i).getComponent())); } Size size = new Size(); int widthSpec = SizeSpec.makeSizeSpec(200, SizeSpec.AT_MOST); int heightSpec = SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY); mRecyclerBinder.measure(size, widthSpec, heightSpec); TestComponentTreeHolder componentTreeHolder = mHoldersForComponents.get(components.get(0).getComponent()); assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutSyncCalled); for (int i = 1; i < 2; i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } Assert.assertEquals(100, size.width); } @Test public void testMoveRange() { final List<ComponentInfo> components = prepareLoadedBinder(); final int newRangeStart = 40; final int newRangeEnd = 42; final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); mRecyclerBinder.onNewVisibleRange(newRangeStart, newRangeEnd); TestComponentTreeHolder componentTreeHolder; for (int i = 0; i < components.size(); i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); if (i >= newRangeStart - (RANGE_RATIO * RANGE_SIZE) && i <= newRangeStart + rangeTotal) { assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } else { assertFalse(componentTreeHolder.isTreeValid()); assertFalse(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); if (i <= rangeTotal) { assertTrue(componentTreeHolder.mDidAcquireStateHandler); } else { assertFalse(componentTreeHolder.mDidAcquireStateHandler); } } } } @Test public void testRealRangeOverridesEstimatedRange() { final List<ComponentInfo> components = prepareLoadedBinder(); final int newRangeStart = 40; final int newRangeEnd = 50; int rangeSize = newRangeEnd - newRangeStart; final int rangeTotal = (int) (rangeSize + (RANGE_RATIO * rangeSize)); mRecyclerBinder.onNewVisibleRange(newRangeStart, newRangeEnd); TestComponentTreeHolder componentTreeHolder; for (int i = 0; i < components.size(); i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); if (i >= newRangeStart - (RANGE_RATIO * rangeSize) && i <= newRangeStart + rangeTotal) { assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } else { assertFalse(componentTreeHolder.isTreeValid()); assertFalse(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } } } @Test public void testMoveRangeToEnd() { final List<ComponentInfo> components = prepareLoadedBinder(); final int newRangeStart = 99; final int newRangeEnd = 99; final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); mRecyclerBinder.onNewVisibleRange(newRangeStart, newRangeEnd); TestComponentTreeHolder componentTreeHolder; for (int i = 0; i < components.size(); i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); if (i >= newRangeStart - (RANGE_RATIO * RANGE_SIZE) && i <= newRangeStart + rangeTotal) { assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } else { assertFalse(componentTreeHolder.isTreeValid()); assertFalse(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); if (i <= rangeTotal) { assertTrue(componentTreeHolder.mDidAcquireStateHandler); } else { assertFalse(componentTreeHolder.mDidAcquireStateHandler); } } } } @Test public void testMoveItemOutsideFromRange() { final List<ComponentInfo> components = prepareLoadedBinder(); mRecyclerBinder.moveItem(0, 99); final TestComponentTreeHolder movedHolder = mHoldersForComponents.get(components.get(0).getComponent()); assertFalse(movedHolder.isTreeValid()); assertFalse(movedHolder.mLayoutAsyncCalled); assertFalse(movedHolder.mLayoutSyncCalled); assertTrue(movedHolder.mDidAcquireStateHandler); final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); final TestComponentTreeHolder holderMovedIntoRange = mHoldersForComponents.get(components.get(rangeTotal + 1).getComponent()); assertTrue(holderMovedIntoRange.isTreeValid()); assertTrue(holderMovedIntoRange.mLayoutAsyncCalled); assertFalse(holderMovedIntoRange.mLayoutSyncCalled); } @Test public void testMoveItemInsideRange() { final List<ComponentInfo> components = prepareLoadedBinder(); mRecyclerBinder.moveItem(99, 4); TestComponentTreeHolder movedHolder = mHoldersForComponents.get(components.get(99).getComponent()); assertTrue(movedHolder.isTreeValid()); assertTrue(movedHolder.mLayoutAsyncCalled); assertFalse(movedHolder.mLayoutSyncCalled); assertFalse(movedHolder.mDidAcquireStateHandler); final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); TestComponentTreeHolder holderMovedOutsideRange = mHoldersForComponents.get(components.get(rangeTotal).getComponent()); assertFalse(holderMovedOutsideRange.isTreeValid()); assertFalse(holderMovedOutsideRange.mLayoutAsyncCalled); assertFalse(holderMovedOutsideRange.mLayoutSyncCalled); } @Test public void testMoveItemInsideVisibleRange() { final List<ComponentInfo> components = prepareLoadedBinder(); mRecyclerBinder.moveItem(99, 2); final TestComponentTreeHolder movedHolder = mHoldersForComponents.get(components.get(99).getComponent()); assertTrue(movedHolder.isTreeValid()); assertFalse(movedHolder.mLayoutAsyncCalled); assertTrue(movedHolder.mLayoutSyncCalled); assertFalse(movedHolder.mDidAcquireStateHandler); final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); final TestComponentTreeHolder holderMovedOutsideRange = mHoldersForComponents.get(components.get(rangeTotal).getComponent()); assertFalse(holderMovedOutsideRange.isTreeValid()); assertFalse(holderMovedOutsideRange.mLayoutAsyncCalled); assertFalse(holderMovedOutsideRange.mLayoutSyncCalled); assertTrue(holderMovedOutsideRange.mDidAcquireStateHandler); } @Test public void testMoveItemOutsideRange() { final List<ComponentInfo> components = prepareLoadedBinder(); mRecyclerBinder.moveItem(2, 99); final TestComponentTreeHolder movedHolder = mHoldersForComponents.get(components.get(2).getComponent());
Lines authored by pasqualea This commit forms part of the blame-preserving initial commit suite.
src/test/java/com/facebook/components/widget/RecyclerBinderTest.java
Lines authored by pasqualea
<ide><path>rc/test/java/com/facebook/components/widget/RecyclerBinderTest.java <ide> <ide> final TestComponentTreeHolder movedHolder = <ide> mHoldersForComponents.get(components.get(2).getComponent()); <add> assertFalse(movedHolder.isTreeValid()); <add> assertFalse(movedHolder.mLayoutAsyncCalled); <add> assertFalse(movedHolder.mLayoutSyncCalled); <add> assertTrue(movedHolder.mDidAcquireStateHandler); <add> <add> final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); <add> final TestComponentTreeHolder holderMovedInsideRange =
Java
agpl-3.0
e1d68ad1055da82b318eda449f0f74cf992d7c76
0
kelvinmbwilo/vims,joshzamor/open-lmis,USAID-DELIVER-PROJECT/elmis,OpenLMIS/open-lmis,vimsvarcode/elmis,jasolangi/jasolangi.github.io,joshzamor/open-lmis,OpenLMIS/open-lmis,vimsvarcode/elmis,joshzamor/open-lmis,OpenLMIS/open-lmis,vimsvarcode/elmis,kelvinmbwilo/vims,joshzamor/open-lmis,jasolangi/jasolangi.github.io,OpenLMIS/open-lmis,USAID-DELIVER-PROJECT/elmis,jasolangi/jasolangi.github.io,USAID-DELIVER-PROJECT/elmis,vimsvarcode/elmis,kelvinmbwilo/vims,vimsvarcode/elmis,USAID-DELIVER-PROJECT/elmis,kelvinmbwilo/vims
/* * This program is part of the OpenLMIS logistics management information system platform software. * Copyright © 2013 VillageReach * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. *   * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License along with this program.  If not, see http://www.gnu.org/licenses.  For additional information contact [email protected].  */ package org.openlmis.UiUtils; import java.sql.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static java.lang.String.format; import static java.lang.System.getProperty; public class DBWrapper { public static final int DEFAULT_MAX_MONTH_OF_STOCK = 3; public static final String DEFAULT_DB_URL = "jdbc:postgresql://localhost:5432/open_lmis"; public static final String DEFAULT_DB_USERNAME = "postgres"; public static final String DEFAULT_DB_PASSWORD = "p@ssw0rd"; Connection connection; public DBWrapper() throws SQLException { String dbUser = getProperty("dbUser", DEFAULT_DB_USERNAME); String dbPassword = getProperty("dbPassword", DEFAULT_DB_PASSWORD); String dbUrl = getProperty("dbUrl", DEFAULT_DB_URL); loadDriver(); connection = DriverManager.getConnection(dbUrl, dbUser, dbPassword); } public void closeConnection() throws SQLException { if (connection != null) connection.close(); } private void loadDriver() { try { Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException e) { System.exit(1); } } private void update(String sql) throws SQLException { try (Statement statement = connection.createStatement()) { statement.executeUpdate(sql); } } private void update(String sql, Object... params) throws SQLException { update(format(sql, params)); } private ResultSet query(String sql) throws SQLException { return connection.createStatement().executeQuery(sql); } private List<Map<String, String>> select(String sql, Object... params) throws SQLException { ResultSet rs = query(sql, params); ResultSetMetaData md = rs.getMetaData(); int columns = md.getColumnCount(); List<Map<String, String>> list = new ArrayList<>(); while (rs.next()) { Map<String, String> row = new HashMap<>(); for (int i = 1; i <= columns; ++i) { row.put(md.getColumnName(i), rs.getString(i)); } list.add(row); } return list; } private ResultSet query(String sql, Object... params) throws SQLException { return query(format(sql, params)); } public void insertUser(String userId, String userName, String password, String facilityCode, String email) throws SQLException { update("delete from users where userName like('%s')", userName); update("INSERT INTO users(id, userName, password, facilityId, firstName, lastName, email, active, verified) " + "VALUES ('%s', '%s', '%s', (SELECT id FROM facilities WHERE code = '%s'), 'Fatima', 'Doe', '%s','true','true')", userId, userName, password, facilityCode, email); } public void insertPeriodAndAssociateItWithSchedule(String period, String schedule) throws SQLException { insertProcessingPeriod(period, period, "2013-09-29", "2020-09-30", 66, schedule); } public List<String> getProductDetailsForProgram(String programCode) throws SQLException { List<String> prodDetails = new ArrayList<>(); ResultSet rs = query("select programs.code as programCode, programs.name as programName, " + "products.code as productCode, products.primaryName as productName, products.description as desc, " + "products.dosesPerDispensingUnit as unit, PG.name as pgName " + "from products, programs, program_products PP, product_categories PG " + "where programs.id = PP.programId and PP.productId=products.id and " + "PG.id = products.categoryId and programs.code='" + programCode + "' " + "and products.active='true' and PP.active='true'"); while (rs.next()) { String programName = rs.getString(2); String productCode = rs.getString(3); String productName = rs.getString(4); String desc = rs.getString(5); String unit = rs.getString(6); String pcName = rs.getString(7); prodDetails.add(programName + "," + productCode + "," + productName + "," + desc + "," + unit + "," + pcName); } return prodDetails; } public List<String> getProductDetailsForProgramAndFacilityType(String programCode, String facilityCode) throws SQLException { List<String> prodDetails = new ArrayList<>(); ResultSet rs = query("select program.code as programCode, program.name as programName, product.code as productCode, " + "product.primaryName as productName, product.description as desc, product.dosesPerDispensingUnit as unit, " + "pg.name as pgName from products product, programs program, program_products pp, product_categories pg, " + "facility_approved_products fap, facility_types ft where program.id=pp.programId and pp.productId=product.id and " + "pg.id = product.categoryId and fap. programProductId = pp.id and ft.id=fap.facilityTypeId and program.code='" + programCode + "' and ft.code='" + facilityCode + "' " + "and product.active='true' and pp.active='true'"); while (rs.next()) { String programName = rs.getString(2); String productCode = rs.getString(3); String productName = rs.getString(4); String desc = rs.getString(5); String unit = rs.getString(6); String pgName = rs.getString(7); prodDetails.add(programName + "," + productCode + "," + productName + "," + desc + "," + unit + "," + pgName); } return prodDetails; } public void updateActiveStatusOfProgramProduct(String productCode, String programCode, String active) throws SQLException { update("update program_products set active='%s' WHERE" + " programId = (select id from programs where code='%s') AND" + " productId = (select id from products where code='%s')", active, programCode, productCode); } public List<String> getFacilityCodeNameForDeliveryZoneAndProgram(String deliveryZoneName, String program, boolean active) throws SQLException { List<String> codeName = new ArrayList<>(); ResultSet rs = query( "select f.code, f.name from facilities f, programs p, programs_supported ps, delivery_zone_members dzm, delivery_zones dz where " + "dzm.DeliveryZoneId=dz.id and " + "f.active='" + active + "' and " + "p.id= ps.programId and " + "p.code='" + program + "' and " + "dz.id = dzm.DeliveryZoneId and " + "dz.name='" + deliveryZoneName + "' and " + "dzm.facilityId = f.id and " + "ps.facilityId = f.id;"); while (rs.next()) { String code = rs.getString("code"); String name = rs.getString("name"); codeName.add(code + " - " + name); } return codeName; } public void deleteDeliveryZoneMembers(String facilityCode) throws SQLException { update("delete from delivery_zone_members where facilityId in (select id from facilities where code ='%s')", facilityCode); } public void updateUser(String password, String email) throws SQLException { update("DELETE FROM user_password_reset_tokens"); update("update users set password = '%s', active = TRUE, verified = TRUE where email = '%s'", password, email); } public void updateRestrictLogin(String userName, boolean status) throws SQLException { update("update users set restrictLogin = '%s' where userName = '%s'", status, userName); } public void insertRequisitions(int numberOfRequisitions, String program, boolean withSupplyLine, String periodStartDate, String periodEndDate, String facilityCode, boolean emergency) throws SQLException { int numberOfRequisitionsAlreadyPresent = 0; boolean flag = true; ResultSet rs = query("select count(*) from requisitions"); if (rs.next()) { numberOfRequisitionsAlreadyPresent = Integer.parseInt(rs.getString(1)); } for (int i = numberOfRequisitionsAlreadyPresent + 1; i <= numberOfRequisitions + numberOfRequisitionsAlreadyPresent; i++) { insertProcessingPeriod("PeriodName" + i, "PeriodDesc" + i, periodStartDate, periodEndDate, 1, "M"); update("insert into requisitions (facilityId, programId, periodId, status, emergency, " + "fullSupplyItemsSubmittedCost, nonFullSupplyItemsSubmittedCost, supervisoryNodeId) " + "values ((Select id from facilities where code='" + facilityCode + "'),(Select id from programs where code='" + program + "')," + "(Select id from processing_periods where name='PeriodName" + i + "'), 'APPROVED', '" + emergency + "', 50.0000, 0.0000, " + "(select id from supervisory_nodes where code='N1'))"); update("INSERT INTO requisition_line_items " + "(rnrId, productCode,product,productDisplayOrder,productCategory,productCategoryDisplayOrder, beginningBalance, quantityReceived, quantityDispensed, stockInHand, " + "dispensingUnit, maxMonthsOfStock, dosesPerMonth, dosesPerDispensingUnit, packSize,fullSupply,totalLossesAndAdjustments,newPatientCount,stockOutDays,price,roundToZero,packRoundingThreshold) VALUES" + "((SELECT max(id) FROM requisitions), 'P10','antibiotic Capsule 300/200/600 mg',1,'Antibiotics',1, '0', '11' , '1', '10' ,'Strip','3', '30', '10', '10','t',0,0,0,12.5000,'f',1);"); } if (withSupplyLine) { ResultSet rs1 = query("select * from supply_lines where supervisoryNodeId = " + "(select id from supervisory_nodes where code = 'N1') and programId = " + "(select id from programs where code='" + program + "') and supplyingFacilityId = " + "(select id from facilities where code = 'F10')"); if (rs1.next()) { flag = false; } } if (withSupplyLine) { if (flag) { insertSupplyLines("N1", program, "F10", true); } } } public void insertFulfilmentRoleAssignment(String userName, String roleName, String facilityCode) throws SQLException { update("insert into fulfillment_role_assignments(userId, roleId, facilityId) values " + "((select id from users where username='" + userName + "')," + "(select id from roles where name='" + roleName + "'),(select id from facilities where code='" + facilityCode + "'))"); } public String getDeliveryZoneNameAssignedToUser(String user) throws SQLException { String deliveryZoneName = ""; ResultSet rs = query( "select name from delivery_zones where id in(select deliveryZoneId from role_assignments where " + "userId=(select id from users where username='" + user + "'))"); if (rs.next()) { deliveryZoneName = rs.getString("name"); } return deliveryZoneName; } public String getRoleNameAssignedToUser(String user) throws SQLException { String userName = ""; ResultSet rs = query("select name from roles where id in(select roleId from role_assignments where " + "userId=(select id from users where username='" + user + "'))"); if (rs.next()) { userName = rs.getString("name"); } return userName; } public void insertFacilities(String facility1, String facility2) throws SQLException { update("INSERT INTO facilities\n" + "(code, name, description, gln, mainPhone, fax, address1, address2, geographicZoneId, typeId, catchmentPopulation, latitude, longitude, altitude, operatedById, coldStorageGrossCapacity, coldStorageNetCapacity, suppliesOthers, sdp, hasElectricity, online, hasElectronicSCC, hasElectronicDAR, active, goLiveDate, goDownDate, satellite, comment, enabled, virtualFacility) values\n" + "('" + facility1 + "','Village Dispensary','IT department','G7645',9876234981,'fax','A','B',5,2,333,22.1,1.2,3.3,2,9.9,6.6,'TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','11/11/12','11/11/1887','TRUE','fc','TRUE', 'FALSE'),\n" + "('" + facility2 + "','Central Hospital','IT department','G7646',9876234981,'fax','A','B',5,2,333,22.3,1.2,3.3,3,9.9,6.6,'TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','11/11/12','11/11/2012','TRUE','fc','TRUE', 'FALSE');\n"); update("insert into programs_supported(facilityId, programId, startDate, active, modifiedBy) VALUES" + " ((SELECT id FROM facilities WHERE code = '" + facility1 + "'), 1, '11/11/12', true, 1)," + " ((SELECT id FROM facilities WHERE code = '" + facility1 + "'), 2, '11/11/12', true, 1)," + " ((SELECT id FROM facilities WHERE code = '" + facility1 + "'), 5, '11/11/12', true, 1)," + " ((SELECT id FROM facilities WHERE code = '" + facility2 + "'), 1, '11/11/12', true, 1)," + " ((SELECT id FROM facilities WHERE code = '" + facility2 + "'), 5, '11/11/12', true, 1)," + " ((SELECT id FROM facilities WHERE code = '" + facility2 + "'), 2, '11/11/12', true, 1)"); } public void insertVirtualFacility(String facilityCode, String parentFacilityCode) throws SQLException { update("INSERT INTO facilities\n" + "(code, name, description, gln, mainPhone, fax, address1, address2, geographicZoneId, typeId, catchmentPopulation, latitude, longitude, altitude, operatedById, coldStorageGrossCapacity, coldStorageNetCapacity, suppliesOthers, sdp, hasElectricity, online, hasElectronicSCC, hasElectronicDAR, active, goLiveDate, goDownDate, satellite, comment, enabled, virtualFacility,parentFacilityId) values\n" + "('" + facilityCode + "','Village Dispensary','IT department','G7645',9876234981,'fax','A','B',5,2,333,22.1,1.2,3.3,2,9.9,6.6,'TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','11/11/12','11/11/2012','TRUE','fc','TRUE', 'TRUE',(SELECT id FROM facilities WHERE code = '" + parentFacilityCode + "'))"); update("insert into programs_supported(facilityId, programId, startDate, active, modifiedBy) VALUES" + " ((SELECT id FROM facilities WHERE code = '" + facilityCode + "'), 1, '11/11/12', true, 1)," + " ((SELECT id FROM facilities WHERE code = '" + facilityCode + "'), 2, '11/11/12', true, 1)," + " ((SELECT id FROM facilities WHERE code = '" + facilityCode + "'), 5, '11/11/12', true, 1)"); update("insert into requisition_group_members (requisitionGroupId, facilityId, createdDate, modifiedDate) values " + "((select requisitionGroupId from requisition_group_members where facilityId=(SELECT id FROM facilities WHERE code = '" + parentFacilityCode + "'))," + "(SELECT id FROM facilities WHERE code = '" + facilityCode + "'),NOW(),NOW())"); } public void deleteRowFromTable(String tableName, String queryParam, String queryValue) throws SQLException { update("delete from " + tableName + " where " + queryParam + "='" + queryValue + "';"); } public void insertFacilitiesWithDifferentGeoZones(String facility1, String facility2, String geoZone1, String geoZone2) throws SQLException { update("INSERT INTO facilities\n" + "(code, name, description, gln, mainPhone, fax, address1, address2, geographicZoneId, typeId, catchmentPopulation, latitude, longitude, altitude, operatedById, coldStorageGrossCapacity, coldStorageNetCapacity, suppliesOthers, sdp, hasElectricity, online, hasElectronicSCC, hasElectronicDAR, active, goLiveDate, goDownDate, satellite, comment, enabled, virtualFacility) values\n" + "('" + facility1 + "','Village Dispensary','IT department','G7645',9876234981,'fax','A','B',(select id from geographic_zones where code='" + geoZone1 + "'),2,333,22.1,1.2,3.3,2,9.9,6.6,'TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','11/11/12','11/11/1887','TRUE','fc','TRUE', 'FALSE'),\n" + "('" + facility2 + "','Central Hospital','IT department','G7646',9876234981,'fax','A','B',(select id from geographic_zones where code='" + geoZone2 + "'),2,333,22.3,1.2,3.3,3,9.9,6.6,'TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','11/11/12','11/11/2012','TRUE','fc','TRUE', 'FALSE');\n"); update("insert into programs_supported(facilityId, programId, startDate, active, modifiedBy) VALUES\n" + "((SELECT id FROM facilities WHERE code = '" + facility1 + "'), 1, '11/11/12', true, 1),\n" + "((SELECT id FROM facilities WHERE code = '" + facility1 + "'), 2, '11/11/12', true, 1),\n" + "((SELECT id FROM facilities WHERE code = '" + facility1 + "'), 5, '11/11/12', true, 1),\n" + "((SELECT id FROM facilities WHERE code = '" + facility2 + "'), 1, '11/11/12', true, 1),\n" + "((SELECT id FROM facilities WHERE code = '" + facility2 + "'), 5, '11/11/12', true, 1),\n" + "((SELECT id FROM facilities WHERE code = '" + facility2 + "'), 2, '11/11/12', true, 1);"); } public void insertGeographicZone(String code, String name, String parentName) throws SQLException { update("insert into geographic_zones (code, name, levelId, parentId) " + "values ('%s','%s',(select max(levelId) from geographic_zones)," + "(select id from geographic_zones where code='%s'))", code, name, parentName); } public void allocateFacilityToUser(String userId, String facilityCode) throws SQLException { update("update users set facilityId = (Select id from facilities where code = '%s') where id = '%s'", facilityCode, userId); } public void updateSourceOfAProgramTemplate(String program, String label, String source) throws SQLException { update("update program_rnr_columns set source = '%s'" + " where programId = (select id from programs where code = '%s') and label = '%s'", source, program, label); } public void deleteData() throws SQLException { update("delete from budget_line_items"); update("delete from budget_file_info"); update("delete from role_rights where roleId not in(1)"); update("delete from role_assignments where userId not in (1)"); update("delete from fulfillment_role_assignments"); update("delete from roles where name not in ('Admin')"); update("delete from facility_approved_products"); update("delete from program_product_price_history"); update("delete from pod_line_items"); update("delete from pod"); update("delete from orders"); update("delete from requisition_status_changes"); update("delete from user_password_reset_tokens"); update("delete from comments"); update("delete from epi_use_line_items"); update("delete from epi_inventory_line_items"); update("delete from refrigerator_problems"); update("delete from refrigerator_readings"); update("delete from full_coverages"); update("delete from vaccination_child_coverage_line_items;"); update("delete from coverage_vaccination_products;"); update("delete from facility_visits"); update("delete from distributions"); update("delete from refrigerators"); update("delete from users where userName not like('Admin%')"); deleteRnrData(); update("delete from program_product_isa"); update("delete from facility_approved_products"); update("delete from facility_program_products"); update("delete from program_products"); update("delete from coverage_vaccination_products"); update("delete from products"); update("delete from product_categories"); update("delete from product_groups"); update("delete from supply_lines"); update("delete from programs_supported"); update("delete from requisition_group_members"); update("delete from program_rnr_columns"); update("delete from requisition_group_program_schedules"); update("delete from requisition_groups"); update("delete from requisition_group_members"); update("delete from delivery_zone_program_schedules"); update("delete from delivery_zone_warehouses"); update("delete from delivery_zone_members"); update("delete from role_assignments where deliveryZoneId in (select id from delivery_zones where code in('DZ1','DZ2'))"); update("delete from delivery_zones"); update("delete from supervisory_nodes"); update("delete from facility_ftp_details"); update("delete from facilities"); update("delete from geographic_zones where code not in ('Root','Arusha','Dodoma', 'Ngorongoro')"); update("delete from processing_periods"); update("delete from processing_schedules"); update("delete from atomfeed.event_records"); update("delete from regimens"); update("delete from program_regimen_columns"); } public void deleteRnrData() throws SQLException { update("delete from requisition_line_item_losses_adjustments"); update("delete from requisition_line_items"); update("delete from regimen_line_items"); update("delete from requisitions"); } public void insertRole(String role, String description) throws SQLException { ResultSet rs = query("Select id from roles where name='%s'", role); if (!rs.next()) { update("INSERT INTO roles(name, description) VALUES('%s', '%s')", role, description); } } public void insertSupervisoryNode(String facilityCode, String supervisoryNodeCode, String supervisoryNodeName, String supervisoryNodeParentCode) throws SQLException { update("delete from supervisory_nodes"); update("INSERT INTO supervisory_nodes (parentId, facilityId, name, code) " + "VALUES (%s, (SELECT id FROM facilities WHERE " + "code = '%s'), '%s', '%s')", supervisoryNodeParentCode, facilityCode, supervisoryNodeName, supervisoryNodeCode); } public void insertSupervisoryNodeSecond(String facilityCode, String supervisoryNodeCode, String supervisoryNodeName, String supervisoryNodeParentCode) throws SQLException { update("INSERT INTO supervisory_nodes" + " (parentId, facilityId, name, code) VALUES" + " ((select id from supervisory_nodes where code ='%s'), (SELECT id FROM facilities WHERE code = '%s'), '%s', '%s')", supervisoryNodeParentCode, facilityCode, supervisoryNodeName, supervisoryNodeCode); } public void insertRequisitionGroups(String code1, String code2, String supervisoryNodeCode1, String supervisoryNodeCode2) throws SQLException { ResultSet rs = query("Select id from requisition_groups;"); if (rs.next()) { update("delete from requisition_groups;"); } update("INSERT INTO requisition_groups ( code ,name,description,supervisoryNodeId )values\n" + "('" + code2 + "','Requisition Group 2','Supports EM(Q1M)',(select id from supervisory_nodes where code ='" + supervisoryNodeCode2 + "')),\n" + "('" + code1 + "','Requisition Group 1','Supports EM(Q2M)',(select id from supervisory_nodes where code ='" + supervisoryNodeCode1 + "'))"); } public void insertRequisitionGroupMembers(String RG1facility, String RG2facility) throws SQLException { ResultSet rs = query("Select requisitionGroupId from requisition_group_members;"); if (rs.next()) { update("delete from requisition_group_members;"); } update("INSERT INTO requisition_group_members ( requisitionGroupId ,facilityId )values\n" + "((select id from requisition_groups where code ='RG1'),(select id from facilities where code ='" + RG1facility + "')),\n" + "((select id from requisition_groups where code ='RG2'),(select id from facilities where code ='" + RG2facility + "'));"); } public void insertRequisitionGroupProgramSchedule() throws SQLException { ResultSet rs = query("Select requisitionGroupId from requisition_group_members;"); if (rs.next()) { update("delete from requisition_group_program_schedules;"); } update( "insert into requisition_group_program_schedules ( requisitionGroupId , programId , scheduleId , directDelivery ) values\n" + "((select id from requisition_groups where code='RG1'),(select id from programs where code='ESS_MEDS'),(select id from processing_schedules where code='Q1stM'),TRUE),\n" + "((select id from requisition_groups where code='RG1'),(select id from programs where code='MALARIA'),(select id from processing_schedules where code='Q1stM'),TRUE),\n" + "((select id from requisition_groups where code='RG1'),(select id from programs where code='HIV'),(select id from processing_schedules where code='M'),TRUE),\n" + "((select id from requisition_groups where code='RG2'),(select id from programs where code='ESS_MEDS'),(select id from processing_schedules where code='Q1stM'),TRUE),\n" + "((select id from requisition_groups where code='RG2'),(select id from programs where code='MALARIA'),(select id from processing_schedules where code='Q1stM'),TRUE),\n" + "((select id from requisition_groups where code='RG2'),(select id from programs where code='HIV'),(select id from processing_schedules where code='M'),TRUE);\n"); } //TODO public void insertRoleAssignment(String userID, String roleName) throws SQLException { update("delete from role_assignments where userId='" + userID + "';"); update(" INSERT INTO role_assignments\n" + " (userId, roleId, programId, supervisoryNodeId) VALUES \n" + " ('" + userID + "', (SELECT id FROM roles WHERE name = '" + roleName + "'), 1, null),\n" + " ('" + userID + "', (SELECT id FROM roles WHERE name = '" + roleName + "'), 1, (SELECT id from supervisory_nodes WHERE code = 'N1'));"); } //TODO public void insertRoleAssignmentForSupervisoryNodeForProgramId1(String userID, String roleName, String supervisoryNode) throws SQLException { update("delete from role_assignments where userId='" + userID + "';"); update(" INSERT INTO role_assignments\n" + " (userId, roleId, programId, supervisoryNodeId) VALUES \n" + " ('" + userID + "', (SELECT id FROM roles WHERE name = '" + roleName + "'), 1, null),\n" + " ('" + userID + "', (SELECT id FROM roles WHERE name = '" + roleName + "'), 1, (SELECT id from supervisory_nodes WHERE code = '" + supervisoryNode + "'));"); } public void updateRoleGroupMember(String facilityCode) throws SQLException { update("update requisition_group_members set facilityId = " + "(select id from facilities where code ='" + facilityCode + "') where " + "requisitionGroupId=(select id from requisition_groups where code='RG2');"); update("update requisition_group_members set facilityId = " + "(select id from facilities where code ='F11') where requisitionGroupId = " + "(select id from requisition_groups where code='RG1');"); } public void alterUserID(String userName, String userId) throws SQLException { update("delete from user_password_reset_tokens;"); update("delete from users where id='" + userId + "' ;"); update(" update users set id='" + userId + "' where username='" + userName + "'"); } public void insertProducts(String product1, String product2) throws SQLException { update("delete from facility_approved_products;"); update("delete from epi_inventory_line_items;"); update("delete from program_products;"); update("delete from products;"); update("delete from product_categories;"); update("INSERT INTO product_categories (code, name, displayOrder) values ('C1', 'Antibiotics', 1);"); update("INSERT INTO products\n" + "(code, alternateItemCode, manufacturer, manufacturerCode, manufacturerBarcode, mohBarcode, gtin, type, primaryName, fullName, genericName, alternateName, description, strength, formId, dosageUnitId, dispensingUnit, dosesPerDispensingUnit, packSize, alternatePackSize, storeRefrigerated, storeRoomTemperature, hazardous, flammable, controlledSubstance, lightSensitive, approvedByWho, contraceptiveCyp, packLength, packWidth, packHeight, packWeight, packsPerCarton, cartonLength, cartonWidth, cartonHeight, cartonsPerPallet, expectedShelfLife, specialStorageInstructions, specialTransportInstructions, active, fullSupply, tracer, packRoundingThreshold, roundToZero, archived, displayOrder, categoryId) values\n" + "('" + product1 + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, 1, (Select id from product_categories where code='C1')),\n" + "('" + product2 + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, FALSE, TRUE, 1, FALSE, TRUE, 5, (Select id from product_categories where code='C1'));\n"); } public void deleteCategoryFromProducts() throws SQLException { update("UPDATE products SET categoryId = null"); } public void deleteDescriptionFromProducts() throws SQLException { update("UPDATE products SET description = null"); } public void insertProductWithCategory(String product, String productName, String category) throws SQLException { update("INSERT INTO product_categories (code, name, displayOrder) values ('" + category + "', '" + productName + "', 1);"); update("INSERT INTO products\n" + "(code, alternateItemCode, manufacturer, manufacturerCode, manufacturerBarcode, mohBarcode, gtin, type, primaryName, fullName, genericName, alternateName, description, strength, formId, dosageUnitId, dispensingUnit, dosesPerDispensingUnit, packSize, alternatePackSize, storeRefrigerated, storeRoomTemperature, hazardous, flammable, controlledSubstance, lightSensitive, approvedByWho, contraceptiveCyp, packLength, packWidth, packHeight, packWeight, packsPerCarton, cartonLength, cartonWidth, cartonHeight, cartonsPerPallet, expectedShelfLife, specialStorageInstructions, specialTransportInstructions, active, fullSupply, tracer, packRoundingThreshold, roundToZero, archived, displayOrder, categoryId) values\n" + "('" + product + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', '" + productName + "', '" + productName + "', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, 1, (Select id from product_categories where code='C1'));\n"); } public void insertProductGroup(String group) throws SQLException { update("INSERT INTO product_groups (code, name) values ('" + group + "', '" + group + "-Name');"); } public void insertProductWithGroup(String product, String productName, String group, boolean status) throws SQLException { update("INSERT INTO products\n" + "(code, alternateItemCode, manufacturer, manufacturerCode, manufacturerBarcode, mohBarcode, gtin, type, primaryName, fullName," + " genericName, alternateName, description, strength, formId, dosageUnitId, dispensingUnit, dosesPerDispensingUnit, packSize, alternatePackSize," + " storeRefrigerated, storeRoomTemperature, hazardous, flammable, controlledSubstance, lightSensitive, approvedByWho, contraceptiveCyp, packLength, " + "packWidth, packHeight, packWeight, packsPerCarton, cartonLength, cartonWidth, cartonHeight, cartonsPerPallet, expectedShelfLife, specialStorageInstructions, " + "specialTransportInstructions, active, fullSupply, tracer, packRoundingThreshold, roundToZero, archived, displayOrder, productGroupId) values" + "('" + product + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', '" + productName + "', '" + productName + "', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE," + " 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', " + status + ",TRUE, TRUE, 1, FALSE, TRUE, 1, (Select id from product_groups where code='" + group + "'));"); } public void updateProgramToAPushType(String program, boolean flag) throws SQLException { update("update programs set push='" + flag + "' where code='" + program + "';"); } public void insertProgramProducts(String product1, String product2, String program) throws SQLException { ResultSet rs = query("Select id from program_products;"); if (rs.next()) { update("delete from facility_approved_products;"); update("delete from program_products;"); } update("INSERT INTO program_products(programId, productId, dosesPerMonth, currentPrice, active) VALUES\n" + "((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + product1 + "'), 30, 12.5, true),\n" + "((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + product2 + "'), 30, 12.5, true);"); } public void insertProgramProduct(String product, String program, String doses, String active) throws SQLException { update("INSERT INTO program_products(programId, productId, dosesPerMonth, currentPrice, active) VALUES\n" + "((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + product + "'), '" + doses + "', 12.5, '" + active + "');"); } public void insertProgramProductsWithCategory(String product, String program) throws SQLException { update("INSERT INTO program_products(programId, productId, dosesPerMonth, currentPrice, active) VALUES\n" + "((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + product + "'), 30, 12.5, true);"); } public void insertProgramProductISA(String program, String product, String whoRatio, String dosesPerYear, String wastageFactor, String bufferPercentage, String minimumValue, String maximumValue, String adjustmentValue) throws SQLException { update( "INSERT INTO program_product_isa(programProductId, whoRatio, dosesPerYear, wastageFactor, bufferPercentage, minimumValue, maximumValue, adjustmentValue) VALUES\n" + "((SELECT ID from program_products where programId = " + "(SELECT ID from programs where code='" + program + "') and productId = " + "(SELECT id from products WHERE code = '" + product + "'))," + whoRatio + "," + dosesPerYear + "," + wastageFactor + "," + bufferPercentage + "," + minimumValue + "," + maximumValue + "," + adjustmentValue + ");"); } public void insertFacilityApprovedProduct(String productCode, String programCode, String facilityTypeCode) throws SQLException { String facilityTypeIdQuery = format("(SELECT id FROM facility_types WHERE code = '%s')", facilityTypeCode); String productIdQuery = format("(SELECT id FROM products WHERE code = '%s')", productCode); String programIdQuery = format("(SELECT ID from programs where code = '%s' )", programCode); String programProductIdQuery = format("(SELECT id FROM program_products WHERE programId = %s AND productId = %s)", programIdQuery, productIdQuery); update(format( "INSERT INTO facility_approved_products(facilityTypeId, programProductId, maxMonthsOfStock) VALUES (%s,%s,%d)", facilityTypeIdQuery, programProductIdQuery, DEFAULT_MAX_MONTH_OF_STOCK)); } public String fetchNonFullSupplyData(String productCode, String facilityTypeID, String programID) throws SQLException { ResultSet rs = query("Select p.code, p.displayOrder, p.primaryName, pf.code as ProductForm," + "p.strength as Strength, du.code as DosageUnit from facility_approved_products fap, " + "program_products pp, products p, product_forms pf , dosage_units du where fap. facilityTypeId='" + facilityTypeID + "' " + "and p. fullSupply = false and p.active=true and pp.programId='" + programID + "' and p. code='" + productCode + "' " + "and pp.productId=p.id and fap. programProductId=pp.id and pp.active=true and pf.id=p.formId " + "and du.id = p.dosageUnitId order by p. displayOrder asc;"); String nonFullSupplyValues = null; if (rs.next()) { nonFullSupplyValues = rs.getString("primaryName") + " " + rs.getString("productForm") + " " + rs.getString("strength") + " " + rs.getString("dosageUnit"); } return nonFullSupplyValues; } public void insertSchedule(String scheduleCode, String scheduleName, String scheduleDesc) throws SQLException { update("INSERT INTO processing_schedules(code, name, description) values('" + scheduleCode + "', '" + scheduleName + "', '" + scheduleDesc + "');"); } public void insertProcessingPeriod(String periodName, String periodDesc, String periodStartDate, String periodEndDate, Integer numberOfMonths, String scheduleCode) throws SQLException { update("INSERT INTO processing_periods\n" + "(name, description, startDate, endDate, numberOfMonths, scheduleId, modifiedBy) VALUES\n" + "('" + periodName + "', '" + periodDesc + "', '" + periodStartDate + " 00:00:00', '" + periodEndDate + " 23:59:59', " + numberOfMonths + ", (SELECT id FROM processing_schedules WHERE code = '" + scheduleCode + "'), (SELECT id FROM users LIMIT 1));"); } public void insertCurrentPeriod(String periodName, String periodDesc, Integer numberOfMonths, String scheduleCode) throws SQLException { update("INSERT INTO processing_periods\n" + "(name, description, startDate, endDate, numberOfMonths, scheduleId, modifiedBy) VALUES\n" + "('" + periodName + "', '" + periodDesc + "', NOW() - interval '5' day, NOW() + interval '5' day, " + numberOfMonths + ", (SELECT id FROM processing_schedules WHERE code = '" + scheduleCode + "'), (SELECT id FROM users LIMIT 1));"); } public void configureTemplate(String program) throws SQLException { update("INSERT INTO program_rnr_columns\n" + "(masterColumnId, programId, visible, source, formulaValidationRequired, position, label) VALUES\n" + "(1, (select id from programs where code = '" + program + "'), true, 'U', false,1, 'Skip'),\n" + "(2, (select id from programs where code = '" + program + "'), true, 'R', false,2, 'Product Code'),\n" + "(3, (select id from programs where code = '" + program + "'), true, 'R', false,3, 'Product'),\n" + "(4, (select id from programs where code = '" + program + "'), true, 'R', false,4, 'Unit/Unit of Issue'),\n" + "(5, (select id from programs where code = '" + program + "'), true, 'U', false,5, 'Beginning Balance'),\n" + "(6, (select id from programs where code = '" + program + "'), true, 'U', false,6, 'Total Received Quantity'),\n" + "(7, (select id from programs where code = '" + program + "'), true, 'C', false,7, 'Total'),\n" + "(8, (select id from programs where code = '" + program + "'), true, 'U', false,8, 'Total Consumed Quantity'),\n" + "(9, (select id from programs where code = '" + program + "'), true, 'U', false,9, 'Total Losses / Adjustments'),\n" + "(10, (select id from programs where code = '" + program + "'), true, 'C', true,10, 'Stock on Hand'),\n" + "(11, (select id from programs where code = '" + program + "'), true, 'U', false,11, 'New Patients'),\n" + "(12, (select id from programs where code = '" + program + "'), true, 'U', false,12, 'Total StockOut days'),\n" + "(13, (select id from programs where code = '" + program + "'), true, 'C', false,13, 'Adjusted Total Consumption'),\n" + "(14, (select id from programs where code = '" + program + "'), true, 'C', false,14, 'Average Monthly Consumption(AMC)'),\n" + "(15, (select id from programs where code = '" + program + "'), true, 'C', false,15, 'Maximum Stock Quantity'),\n" + "(16, (select id from programs where code = '" + program + "'), true, 'C', false,16, 'Calculated Order Quantity'),\n" + "(17, (select id from programs where code = '" + program + "'), true, 'U', false,17, 'Requested quantity'),\n" + "(18, (select id from programs where code = '" + program + "'), true, 'U', false,18, 'Requested quantity explanation'),\n" + "(19, (select id from programs where code = '" + program + "'), true, 'U', false,19, 'Approved Quantity'),\n" + "(20, (select id from programs where code = '" + program + "'), true, 'C', false,20, 'Packs to Ship'),\n" + "(21, (select id from programs where code = '" + program + "'), true, 'R', false,21, 'Price per pack'),\n" + "(22, (select id from programs where code = '" + program + "'), true, 'C', false,22, 'Total cost'),\n" + "(23, (select id from programs where code = '" + program + "'), true, 'U', false,23, 'Expiration Date'),\n" + "(24, (select id from programs where code = '" + program + "'), true, 'U', false,24, 'Remarks');"); } public void configureTemplateForCommTrack(String program) throws SQLException { update("INSERT INTO program_rnr_columns\n" + "(masterColumnId, programId, visible, source, position, label) VALUES\n" + "(2, (select id from programs where code = '" + program + "'), true, 'R', 1, 'Product Code'),\n" + "(3, (select id from programs where code = '" + program + "'), true, 'R', 2, 'Product'),\n" + "(4, (select id from programs where code = '" + program + "'), true, 'R', 3, 'Unit/Unit of Issue'),\n" + "(5, (select id from programs where code = '" + program + "'), true, 'U', 4, 'Beginning Balance'),\n" + "(6, (select id from programs where code = '" + program + "'), true, 'U', 5, 'Total Received Quantity'),\n" + "(7, (select id from programs where code = '" + program + "'), true, 'C', 6, 'Total'),\n" + "(8, (select id from programs where code = '" + program + "'), true, 'C', 7, 'Total Consumed Quantity'),\n" + "(9, (select id from programs where code = '" + program + "'), true, 'U', 8, 'Total Losses / Adjustments'),\n" + "(10, (select id from programs where code = '" + program + "'), true, 'U', 9, 'Stock on Hand'),\n" + "(11, (select id from programs where code = '" + program + "'), true, 'U', 10, 'New Patients'),\n" + "(12, (select id from programs where code = '" + program + "'), true, 'U', 11, 'Total StockOut days'),\n" + "(13, (select id from programs where code = '" + program + "'), true, 'C', 12, 'Adjusted Total Consumption'),\n" + "(14, (select id from programs where code = '" + program + "'), true, 'C', 13, 'Average Monthly Consumption(AMC)'),\n" + "(15, (select id from programs where code = '" + program + "'), true, 'C', 14, 'Maximum Stock Quantity'),\n" + "(16, (select id from programs where code = '" + program + "'), true, 'C', 15, 'Calculated Order Quantity'),\n" + "(17, (select id from programs where code = '" + program + "'), true, 'U', 16, 'Requested quantity'),\n" + "(18, (select id from programs where code = '" + program + "'), true, 'U', 17, 'Requested quantity explanation'),\n" + "(19, (select id from programs where code = '" + program + "'), true, 'U', 18, 'Approved Quantity'),\n" + "(20, (select id from programs where code = '" + program + "'), true, 'C', 19, 'Packs to Ship'),\n" + "(21, (select id from programs where code = '" + program + "'), true, 'R', 20, 'Price per pack'),\n" + "(22, (select id from programs where code = '" + program + "'), true, 'C', 21, 'Total cost'),\n" + "(23, (select id from programs where code = '" + program + "'), true, 'U', 22, 'Expiration Date'),\n" + "(24, (select id from programs where code = '" + program + "'), true, 'U', 23, 'Remarks');"); } public void InsertOverriddenIsa(String facilityCode, String program, String product, int overriddenIsa) throws SQLException { update("INSERT INTO facility_program_products (facilityId, programProductId,overriddenIsa) VALUES (" + getAttributeFromTable("facilities", "id", "code", facilityCode) + ", (select id from program_products where programId='" + getAttributeFromTable("programs", "id", "code", program) + "' and productId='" + getAttributeFromTable("products", "id", "code", product) + "')," + overriddenIsa + ");"); } public void updateOverriddenIsa(String facilityCode, String program, String product, String overriddenIsa) throws SQLException { update("Update facility_program_products set overriddenIsa=" + overriddenIsa + " where facilityId='" + getAttributeFromTable("facilities", "id", "code", facilityCode) + "' and programProductId = (select id from program_products where programId='" + getAttributeFromTable("programs", "id", "code", program) + "' and productId='" + getAttributeFromTable("products", "id", "code", product) + "');"); } public void insertSupplyLines(String supervisoryNode, String programCode, String facilityCode, boolean exportOrders) throws SQLException { update("insert into supply_lines (description, supervisoryNodeId, programId, supplyingFacilityId,exportOrders) values" + "('supplying node for " + programCode + "', " + "(select id from supervisory_nodes where code = '" + supervisoryNode + "')," + "(select id from programs where code='" + programCode + "')," + "(select id from facilities where code = '" + facilityCode + "')," + exportOrders + ");"); } public void updateSupplyLines(String previousFacilityCode, String newFacilityCode) throws SQLException { update("update supply_lines SET supplyingFacilityId=(select id from facilities where code = '" + newFacilityCode + "') " + "where supplyingFacilityId=(select id from facilities where code = '" + previousFacilityCode + "');"); } public void insertValuesInRequisition(boolean emergencyRequisitionRequired) throws SQLException { update("update requisition_line_items set beginningBalance=1, quantityReceived=1, quantityDispensed = 1, " + "newPatientCount = 1, stockOutDays = 1, quantityRequested = 10, reasonForRequestedQuantity = 'bad climate', " + "normalizedConsumption = 10, packsToShip = 1"); update("update requisitions set fullSupplyItemsSubmittedCost = 12.5000, nonFullSupplyItemsSubmittedCost = 0.0000"); if (emergencyRequisitionRequired) { update("update requisitions set emergency='true'"); } } public void insertValuesInRegimenLineItems(String patientsOnTreatment, String patientsToInitiateTreatment, String patientsStoppedTreatment, String remarks) throws SQLException { update("update regimen_line_items set patientsOnTreatment='" + patientsOnTreatment + "', patientsToInitiateTreatment='" + patientsToInitiateTreatment + "', patientsStoppedTreatment='" + patientsStoppedTreatment + "',remarks='" + remarks + "';"); } public void updateFieldValue(String tableName, String fieldName, Integer quantity) throws SQLException { update("update " + tableName + " set " + fieldName + "=" + quantity + ";"); } public void updateFieldValue(String tableName, String fieldName, String value, String queryParam, String queryValue) throws SQLException { if (queryParam == null) update("update " + tableName + " set " + fieldName + "='" + value + "';"); else update("update " + tableName + " set " + fieldName + "='" + value + "' where " + queryParam + "='" + queryValue + "';"); } public void updateFieldValue(String tableName, String fieldName, Boolean value) throws SQLException { update("update " + tableName + " set " + fieldName + "=" + value + ";"); } public void updateRequisitionStatus(String status, String username, String program) throws SQLException { update("update requisitions set status='" + status + "';"); ResultSet rs = query("select id from requisitions where programId = (select id from programs where code='" + program + "');"); while (rs.next()) { update("insert into requisition_status_changes(rnrId, status, createdBy, modifiedBy) values(" + rs.getString("id") + ", '" + status + "', " + "(select id from users where username = '" + username + "'), (select id from users where username = '" + username + "'));"); } update("update requisitions set supervisoryNodeId = (select id from supervisory_nodes where code='N1');"); update("update requisitions set createdBy= (select id from users where username = '" + username + "') , modifiedBy= (select id from users where username = '" + username + "');"); } public void updateRequisitionStatusByRnrId(String status, String username, int rnrId) throws SQLException { update("update requisitions set status='" + status + "' where id=" + rnrId + ";"); update("insert into requisition_status_changes(rnrId, status, createdBy, modifiedBy) values(" + rnrId + ", '" + status + "', " + "(select id from users where username = '" + username + "'), (select id from users where username = '" + username + "'));"); update("update requisitions set supervisoryNodeId = (select id from supervisory_nodes where code='N1');"); update("update requisitions set createdBy= (select id from users where username = '" + username + "') , modifiedBy= (select id from users where username = '" + username + "');"); } public String getSupplyFacilityName(String supervisoryNode, String programCode) throws SQLException { String facilityName = null; ResultSet rs = query("select name from facilities where id=" + "(select supplyingFacilityId from supply_lines where supervisoryNodeId=" + "(select id from supervisory_nodes where code='" + supervisoryNode + "') and programId = " + "(select id from programs where code='" + programCode + "'));"); if (rs.next()) { facilityName = rs.getString("name"); } return facilityName; } public int getMaxRnrID() throws SQLException { int rnrId = 0; ResultSet rs = query("select max(id) from requisitions"); if (rs.next()) { rnrId = Integer.parseInt(rs.getString("max")); } return rnrId; } public void setupMultipleProducts(String program, String facilityType, int numberOfProductsOfEachType, boolean defaultDisplayOrder) throws SQLException { update("delete from facility_approved_products;"); update("delete from program_products;"); update("delete from products;"); update("delete from product_categories;"); String productCodeFullSupply = "F"; String productCodeNonFullSupply = "NF"; update("INSERT INTO product_categories (code, name, displayOrder) values ('C1', 'Antibiotics', 1);"); ResultSet rs = query("Select id from product_categories where code='C1';"); int categoryId = 0; if (rs.next()) { categoryId = rs.getInt("id"); } String insertSql; insertSql = "INSERT INTO products (code, alternateItemCode, manufacturer, manufacturerCode, manufacturerBarcode, mohBarcode, gtin, " + "type, primaryName, fullName, genericName, alternateName, description, strength, formId, dosageUnitId, dispensingUnit, " + "dosesPerDispensingUnit, packSize, alternatePackSize, storeRefrigerated, storeRoomTemperature, hazardous, flammable, " + "controlledSubstance, lightSensitive, approvedByWho, contraceptiveCyp, packLength, packWidth, packHeight, packWeight, " + "packsPerCarton, cartonLength, cartonWidth, cartonHeight, cartonsPerPallet, expectedShelfLife, specialStorageInstructions, " + "specialTransportInstructions, active, fullSupply, tracer, packRoundingThreshold, roundToZero, archived, displayOrder, categoryId) " + "values"; for (int i = 0; i < numberOfProductsOfEachType; i++) { if (defaultDisplayOrder) { insertSql = insertSql + "('" + productCodeFullSupply + i + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, 1, " + categoryId + "),\n"; insertSql = insertSql + "('" + productCodeNonFullSupply + i + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, FALSE, TRUE, 1, FALSE, TRUE, 1, " + categoryId + "),\n"; } else { insertSql = insertSql + "('" + productCodeFullSupply + i + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, " + i + ", " + categoryId + "),\n"; insertSql = insertSql + "('" + productCodeNonFullSupply + i + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, FALSE, TRUE, 1, FALSE, TRUE, " + i + ", " + categoryId + "),\n"; } } insertSql = insertSql.substring(0, insertSql.length() - 2) + ";\n"; update(insertSql); insertSql = "INSERT INTO program_products(programId, productId, dosesPerMonth, currentPrice, active) VALUES\n"; for (int i = 0; i < numberOfProductsOfEachType; i++) { insertSql = insertSql + "((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + productCodeFullSupply + i + "'), 30, 12.5, true),\n"; insertSql = insertSql + "((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + productCodeNonFullSupply + i + "'), 30, 12.5, true),\n"; } insertSql = insertSql.substring(0, insertSql.length() - 2) + ";"; update(insertSql); insertSql = "INSERT INTO facility_approved_products(facilityTypeId, programProductId, maxMonthsOfStock) VALUES\n"; for (int i = 0; i < numberOfProductsOfEachType; i++) { insertSql = insertSql + "((select id from facility_types where name='" + facilityType + "'), (SELECT id FROM program_products WHERE programId=(SELECT ID from programs where code='" + program + "') AND productId=(SELECT id FROM products WHERE code='" + productCodeFullSupply + i + "')), 3),\n"; insertSql = insertSql + "((select id from facility_types where name='" + facilityType + "'), (SELECT id FROM program_products WHERE programId=(SELECT ID from programs where code='" + program + "') AND productId=(SELECT id FROM products WHERE code='" + productCodeNonFullSupply + i + "')), 3),\n"; } insertSql = insertSql.substring(0, insertSql.length() - 2) + ";"; update(insertSql); } public void setupMultipleCategoryProducts(String program, String facilityType, int numberOfCategories, boolean defaultDisplayOrder) throws SQLException { update("delete from facility_approved_products;"); update("delete from program_products;"); update("delete from products;"); update("delete from product_categories;"); String productCodeFullSupply = "F"; String productCodeNonFullSupply = "NF"; String insertSql = "INSERT INTO product_categories (code, name, displayOrder) values\n"; for (int i = 0; i < numberOfCategories; i++) { if (defaultDisplayOrder) { insertSql = insertSql + "('C" + i + "', 'Antibiotics" + i + "',1),\n"; } else { insertSql = insertSql + "('C" + i + "', 'Antibiotics" + i + "'," + i + "),\n"; } } insertSql = insertSql.substring(0, insertSql.length() - 2) + ";"; update(insertSql); insertSql = "INSERT INTO products (code, alternateItemCode, manufacturer, manufacturerCode, manufacturerBarcode, mohBarcode, gtin, type, primaryName, fullName, genericName, alternateName, description, strength, formId, dosageUnitId, dispensingUnit, dosesPerDispensingUnit, packSize, alternatePackSize, storeRefrigerated, storeRoomTemperature, hazardous, flammable, controlledSubstance, lightSensitive, approvedByWho, contraceptiveCyp, packLength, packWidth, packHeight, packWeight, packsPerCarton, cartonLength, cartonWidth, cartonHeight, cartonsPerPallet, expectedShelfLife, specialStorageInstructions, specialTransportInstructions, active, fullSupply, tracer, packRoundingThreshold, roundToZero, archived, displayOrder, categoryId) values\n"; for (int i = 0; i < 11; i++) { insertSql = insertSql + "('" + productCodeFullSupply + i + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, 1, (select id from product_categories where code='C" + i + "')),\n"; insertSql = insertSql + "('" + productCodeNonFullSupply + i + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, FALSE, TRUE, 1, FALSE, TRUE, 1, (select id from product_categories where code='C" + i + "')),\n"; } insertSql = insertSql.substring(0, insertSql.length() - 2) + ";\n"; update(insertSql); insertSql = "INSERT INTO program_products(programId, productId, dosesPerMonth, currentPrice, active) VALUES\n"; for (int i = 0; i < 11; i++) { insertSql = insertSql + "((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + productCodeFullSupply + i + "'), 30, 12.5, true),\n"; insertSql = insertSql + "((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + productCodeNonFullSupply + i + "'), 30, 12.5, true),\n"; } insertSql = insertSql.substring(0, insertSql.length() - 2) + ";"; update(insertSql); insertSql = "INSERT INTO facility_approved_products(facilityTypeId, programProductId, maxMonthsOfStock) VALUES\n"; for (int i = 0; i < 11; i++) { insertSql = insertSql + "((select id from facility_types where name='" + facilityType + "'), (SELECT id FROM program_products WHERE programId=(SELECT ID from programs where code='" + program + "') AND productId=(SELECT id FROM products WHERE code='" + productCodeFullSupply + i + "')), 3),\n"; insertSql = insertSql + "((select id from facility_types where name='" + facilityType + "'), (SELECT id FROM program_products WHERE programId=(SELECT ID from programs where code='" + program + "') AND productId=(SELECT id FROM products WHERE code='" + productCodeNonFullSupply + i + "')), 3),\n"; } insertSql = insertSql.substring(0, insertSql.length() - 2) + ";"; update(insertSql); } public void assignRight(String roleName, String roleRight) throws SQLException { update("INSERT INTO role_rights (roleId, rightName) VALUES" + " ((select id from roles where name='" + roleName + "'), '" + roleRight + "');"); } public void updatePacksToShip(String packsToShip) throws SQLException { update("update requisition_line_items set packsToShip='" + packsToShip + "';"); } public void insertPastPeriodRequisitionAndLineItems(String facilityCode, String program, String periodName, String product) throws SQLException { deleteRnrData(); update("INSERT INTO requisitions " + "(facilityId, programId, periodId, status) VALUES " + "((SELECT id FROM facilities WHERE code = '" + facilityCode + "'), (SELECT ID from programs where code='" + program + "'), (select id from processing_periods where name='" + periodName + "'), 'RELEASED');"); update("INSERT INTO requisition_line_items " + "(rnrId, productCode, beginningBalance, quantityReceived, quantityDispensed, stockInHand, normalizedConsumption, " + "dispensingUnit, maxMonthsOfStock, dosesPerMonth, dosesPerDispensingUnit, packSize,fullSupply) VALUES" + "((SELECT id FROM requisitions), '" + product + "', '0', '11' , '1', '10', '1' ,'Strip','0', '0', '0', '10','t');"); } public void insertRoleAssignmentForDistribution(String userName, String roleName, String deliveryZoneCode) throws SQLException { update("INSERT INTO role_assignments\n" + " (userId, roleId, deliveryZoneId) VALUES\n" + " ((SELECT id FROM USERS WHERE username='" + userName + "'), (SELECT id FROM roles WHERE name = '" + roleName + "'),\n" + " (SELECT id FROM delivery_zones WHERE code='" + deliveryZoneCode + "'));"); } public void deleteDeliveryZoneToFacilityMapping(String deliveryZoneName) throws SQLException { update("delete from delivery_zone_members where deliveryZoneId in (select id from delivery_zones where name='" + deliveryZoneName + "');"); } public void deleteProgramToFacilityMapping(String programCode) throws SQLException { update("delete from programs_supported where programId in (select id from programs where code='" + programCode + "');"); } public void insertDeliveryZone(String code, String name) throws SQLException { update("INSERT INTO delivery_zones ( code ,name)values\n" + "('" + code + "','" + name + "');"); } public void insertWarehouseIntoSupplyLinesTable(String facilityCodeFirst, String programFirst, String supervisoryNode, boolean exportOrders) throws SQLException { update("INSERT INTO supply_lines (supplyingFacilityId, programId, supervisoryNodeId, description, exportOrders, createdBy, modifiedBy) values " + "(" + "(select id from facilities where code = '" + facilityCodeFirst + "')," + "(select id from programs where name ='" + programFirst + "')," + "(select id from supervisory_nodes where code='" + supervisoryNode + "'),'warehouse', " + exportOrders + ", '1', '1');"); } public void insertDeliveryZoneMembers(String code, String facility) throws SQLException { update("INSERT INTO delivery_zone_members ( deliveryZoneId ,facilityId )values\n" + "((select id from delivery_zones where code ='" + code + "'),(select id from facilities where code ='" + facility + "'));"); } public void insertDeliveryZoneProgramSchedule(String code, String program, String scheduleCode) throws SQLException { update("INSERT INTO delivery_zone_program_schedules\n" + "(deliveryZoneId, programId, scheduleId ) values(\n" + "(select id from delivery_zones where code='" + code + "'),\n" + "(select id from programs where code='" + program + "'),\n" + "(select id from processing_schedules where code='" + scheduleCode + "')\n" + ");"); } public void insertProcessingPeriodForDistribution(int numberOfPeriodsRequired, String schedule) throws SQLException { for (int counter = 1; counter <= numberOfPeriodsRequired; counter++) { String startDate = "2013-01-0" + counter; String endDate = "2013-01-0" + counter; insertProcessingPeriod("Period" + counter, "PeriodDecs" + counter, startDate, endDate, 1, schedule); } } public void insertRegimenTemplateColumnsForProgram(String programName) throws SQLException { update("INSERT INTO program_regimen_columns(name, programId, label, visible, dataType) values\n" + "('code',(SELECT id FROM programs WHERE name='" + programName + "'), 'header.code',true,'regimen.reporting.dataType.text'),\n" + "('name',(SELECT id FROM programs WHERE name='" + programName + "'),'header.name',true,'regimen.reporting.dataType.text'),\n" + "('patientsOnTreatment',(SELECT id FROM programs WHERE name='" + programName + "'),'Number of patients on treatment',true,'regimen.reporting.dataType.numeric'),\n" + "('patientsToInitiateTreatment',(SELECT id FROM programs WHERE name='" + programName + "'),'Number of patients to be initiated treatment',true,'regimen.reporting.dataType.numeric'),\n" + "('patientsStoppedTreatment',(SELECT id FROM programs WHERE name='" + programName + "'),'Number of patients stopped treatment',true,'regimen.reporting.dataType.numeric'),\n" + "('remarks',(SELECT id FROM programs WHERE name='" + programName + "'),'Remarks',true,'regimen.reporting.dataType.text');"); } public void insertRegimenTemplateConfiguredForProgram(String programName, String categoryCode, String code, String name, boolean active) throws SQLException { update("update programs set regimenTemplateConfigured='true' where name='" + programName + "';"); update("INSERT INTO regimens\n" + " (programId, categoryId, code, name, active,displayOrder) VALUES\n" + " ((SELECT id FROM programs WHERE name='" + programName + "'), (SELECT id FROM regimen_categories WHERE code = '" + categoryCode + "'),\n" + " '" + code + "','" + name + "','" + active + "',1);"); } public String getAllActivePrograms() throws SQLException { String programsString = ""; ResultSet rs = query("select * from programs where active=true;"); while (rs.next()) { programsString = programsString + rs.getString("name"); } return programsString; } public void updateProgramRegimenColumns(String programName, String regimenColumnName, boolean visible) throws SQLException { update("update program_regimen_columns set visible=" + visible + " where name ='" + regimenColumnName + "'and programId=(SELECT id FROM programs WHERE name='" + programName + "');"); } public void setupOrderFileConfiguration(String filePrefix, String headerInFile) throws SQLException { update("DELETE FROM order_configuration;"); update("INSERT INTO order_configuration \n" + " (filePrefix, headerInFile) VALUES\n" + " ('" + filePrefix + "', '" + headerInFile + "');"); } public void setupShipmentFileConfiguration(String headerInFile) throws SQLException { update("DELETE FROM shipment_configuration;"); update("INSERT INTO shipment_configuration(headerInFile) VALUES('" + headerInFile + "')"); } public void setupOrderFileOpenLMISColumns(String dataFieldLabel, String includeInOrderFile, String columnLabel, int position, String Format) throws SQLException { update("UPDATE order_file_columns SET " + "includeInOrderFile='" + includeInOrderFile + "', columnLabel='" + columnLabel + "', position=" + position + ", format='" + Format + "' where dataFieldLabel='" + dataFieldLabel + "'"); } public void setupOrderFileNonOpenLMISColumns(String dataFieldLabel, String includeInOrderFile, String columnLabel, int position) throws SQLException { update("INSERT INTO order_file_columns (dataFieldLabel, includeInOrderFile, columnLabel, position, openLMISField) " + "VALUES ('" + dataFieldLabel + "','" + includeInOrderFile + "','" + columnLabel + "'," + position + ", FALSE)"); } public void updateProductToHaveGroup(String product, String productGroup) throws SQLException { update("UPDATE products set productGroupId = (SELECT id from product_groups where code = '" + productGroup + "') where code = '" + product + "'"); } public void insertOrders(String status, String username, String program) throws SQLException { ResultSet rs = query("select id from requisitions where programId=(select id from programs where code='" + program + "');"); while (rs.next()) { update("update requisitions set status='RELEASED' where id =" + rs.getString("id")); update("insert into orders(Id, status,supplyLineId, createdBy, modifiedBy) values(" + rs.getString("id") + ", '" + status + "', (select id from supply_lines where supplyingFacilityId = " + "(select facilityId from fulfillment_role_assignments where userId = " + "(select id from users where username = '" + username + "')) limit 1) ," + "(select id from users where username = '" + username + "'), (select id from users where username = '" + username + "'));"); } } public void setupUserForFulfillmentRole(String username, String roleName, String facilityCode) throws SQLException { update("insert into fulfillment_role_assignments(userId, roleId,facilityId) values((select id from users where userName = '" + username + "'),(select id from roles where name = '" + roleName + "')," + "(select id from facilities where code = '" + facilityCode + "'));"); } public Map<String, String> getFacilityVisitDetails(String facilityCode) throws SQLException { Map<String, String> facilityVisitsDetails = new HashMap<>(); try (ResultSet rs = query("SELECT observations,confirmedByName,confirmedByTitle,verifiedByName,verifiedByTitle from facility_visits" + " WHERE facilityId = (SELECT id FROM facilities WHERE code = '" + facilityCode + "');")) { while (rs.next()) { facilityVisitsDetails.put("observations", rs.getString("observations")); facilityVisitsDetails.put("confirmedByName", rs.getString("confirmedByName")); facilityVisitsDetails.put("confirmedByTitle", rs.getString("confirmedByTitle")); facilityVisitsDetails.put("verifiedByName", rs.getString("verifiedByName")); facilityVisitsDetails.put("verifiedByTitle", rs.getString("verifiedByTitle")); } return facilityVisitsDetails; } } public int getPODLineItemQuantityReceived(long orderId, String productCode) throws Exception { try (ResultSet rs1 = query("SELECT id FROM pod WHERE OrderId = %d", orderId)) { if (rs1.next()) { int podId = rs1.getInt("id"); ResultSet rs2 = query("SELECT quantityReceived FROM pod_line_items WHERE podId = %d and productCode='%s'", podId, productCode); if (rs2.next()) { return rs2.getInt("quantityReceived"); } } } return -1; } public void setExportOrdersFlagInSupplyLinesTable(boolean flag, String facilityCode) throws SQLException { update("UPDATE supply_lines SET exportOrders='" + flag + "' WHERE supplyingFacilityId=(select id from facilities where code='" + facilityCode + "');"); } public void enterValidDetailsInFacilityFtpDetailsTable(String facilityCode) throws SQLException { update( "INSERT INTO facility_ftp_details(facilityId, serverHost, serverPort, username, password, localFolderPath) VALUES" + "((SELECT id FROM facilities WHERE code = '%s' ), '192.168.34.1', 21, 'openlmis', 'openlmis', '/ftp');", facilityCode); } public List<Integer> getAllProgramsOfFacility(String facilityCode) throws SQLException { List<Integer> l1 = new ArrayList<>(); ResultSet rs = query( "SELECT programId FROM programs_supported WHERE facilityId = (SELECT id FROM facilities WHERE code ='%s')", facilityCode); while (rs.next()) { l1.add(rs.getInt(1)); } return l1; } public String getProgramFieldForProgramIdAndFacilityCode(int programId, String facilityCode, String field) throws SQLException { String res = null; ResultSet rs = query( "SELECT %s FROM programs_supported WHERE programId = %d AND facilityId = (SELECT id FROM facilities WHERE code = '%s')", field, programId, facilityCode); if (rs.next()) { res = rs.getString(1); } return res; } public Date getProgramStartDateForProgramIdAndFacilityCode(int programId, String facilityCode) throws SQLException { Date date = null; ResultSet rs = query( "SELECT startDate FROM programs_supported WHERE programId = %d AND facilityId = (SELECT id FROM facilities WHERE code ='%s')", programId, facilityCode); if (rs.next()) { date = rs.getDate(1); } return date; } public void deleteCurrentPeriod() throws SQLException { update("delete from processing_periods where endDate>=NOW()"); } public void updateProgramsSupportedByField(String field, String newValue, String facilityCode) throws SQLException { update("Update programs_supported set " + field + "='" + newValue + "' where facilityId=(Select id from facilities where code ='" + facilityCode + "');"); } public void deleteSupervisoryRoleFromRoleAssignment() throws SQLException { update("delete from role_assignments where supervisoryNodeId is not null;"); } public void deleteProductAvailableAtFacility(String productCode, String programCode, String facilityCode) throws SQLException { update("delete from facility_approved_products where facilityTypeId=(select typeId from facilities where code='" + facilityCode + "') " + "and programProductId=(select id from program_products where programId=(select id from programs where code='" + programCode + "')" + "and productId=(select id from products where code='" + productCode + "'));"); } public void updateConfigureTemplateValidationFlag(String programCode, String flag) throws SQLException { update("UPDATE program_rnr_columns set formulaValidationRequired ='" + flag + "' WHERE programId=" + "(SELECT id from programs where code='" + programCode + "');"); } public void updateConfigureTemplate(String programCode, String fieldName, String fieldValue, String visibilityFlag, String rnrColumnName) throws SQLException { update("UPDATE program_rnr_columns SET visible ='" + visibilityFlag + "', " + fieldName + "='" + fieldValue + "' WHERE programId=" + "(SELECT id from programs where code='" + programCode + "')" + "AND masterColumnId =(SELECT id from master_rnr_columns WHERE name = '" + rnrColumnName + "') ;"); } public void deleteConfigureTemplate(String program) throws SQLException { update("DELETE FROM program_rnr_columns where programId=(select id from programs where code = '" + program + "');"); } public String getRequisitionLineItemFieldValue(Long requisitionId, String field, String productCode) throws SQLException { String value = null; ResultSet rs = query("SELECT %s FROM requisition_line_items WHERE rnrId = %d AND productCode = '%s'", field, requisitionId, productCode); if (rs.next()) { value = rs.getString(field); } return value; } public void insertRoleAssignmentForSupervisoryNode(String userID, String roleName, String supervisoryNode, String programCode) throws SQLException { update(" INSERT INTO role_assignments\n" + " (userId, roleId, programId, supervisoryNodeId) VALUES \n" + " ('" + userID + "', (SELECT id FROM roles WHERE name = '" + roleName + "')," + " (SELECT id from programs WHERE code='" + programCode + "'), " + "(SELECT id from supervisory_nodes WHERE code = '" + supervisoryNode + "'));"); } public void insertRequisitionGroupProgramScheduleForProgram(String requisitionGroupCode, String programCode, String scheduleCode) throws SQLException { update("delete from requisition_group_program_schedules where programId=(select id from programs where code='" + programCode + "');"); update( "insert into requisition_group_program_schedules ( requisitionGroupId , programId , scheduleId , directDelivery ) values\n" + "((select id from requisition_groups where code='" + requisitionGroupCode + "'),(select id from programs where code='" + programCode + "')," + "(select id from processing_schedules where code='" + scheduleCode + "'),TRUE);"); } public void updateCreatedDateInRequisitionStatusChanges(String newDate, Long rnrId) throws SQLException { update("update requisition_status_changes SET createdDate= '" + newDate + "' WHERE rnrId=" + rnrId + ";"); } public void updateSupervisoryNodeForRequisitionGroup(String requisitionGroup, String supervisoryNodeCode) throws SQLException { update("update requisition_groups set supervisoryNodeId=(select id from supervisory_nodes where code='" + supervisoryNodeCode + "') where code='" + requisitionGroup + "';"); } public void deleteSupplyLine() throws SQLException { update("delete from supply_lines where description='supplying node for MALARIA'"); } public Map<String, String> getEpiUseDetails(String productGroupCode, String facilityCode) throws SQLException { return select("SELECT * FROM epi_use_line_items WHERE productGroupName = " + "(SELECT name FROM product_groups where code = '%s') AND facilityVisitId=(Select id from facility_visits where facilityId=" + "(Select id from facilities where code ='%s'));", productGroupCode, facilityCode).get(0); } public ResultSet getEpiInventoryDetails(String productCode, String facilityCode) throws SQLException { ResultSet resultSet = query("SELECT * FROM epi_inventory_line_items WHERE productCode = '%s'" + "AND facilityVisitId=(Select id from facility_visits where facilityId=" + "(Select id from facilities where code ='%s'));", productCode, facilityCode); resultSet.next(); return resultSet; } public Map<String, String> getFullCoveragesDetails(String facilityCode) throws SQLException { return select("SELECT * FROM full_coverages WHERE facilityVisitId=(Select id from facility_visits where facilityId=" + "(Select id from facilities where code ='%s'));", facilityCode).get(0); } public void insertBudgetData() throws SQLException { update("INSERT INTO budget_file_info VALUES (1,'abc.csv','f',200,'12/12/13',200,'12/12/13');"); update( "INSERT INTO budget_line_items VALUES (1,(select id from processing_periods where name='current Period'),1,'01/01/2013',200,'hjhj',200,'12/12/2013',200,'12/12/2013',(select id from facilities where code='F10'),1);"); } public void addRefrigeratorToFacility(String brand, String model, String serialNumber, String facilityCode) throws SQLException { update("INSERT INTO refrigerators(brand, model, serialNumber, facilityId, createdBy , modifiedBy) VALUES" + "('" + brand + "','" + model + "','" + serialNumber + "',(SELECT id FROM facilities WHERE code = '" + facilityCode + "'),1,1);"); } public ResultSet getRefrigeratorReadings(String refrigeratorSerialNumber, String facilityCode) throws SQLException { ResultSet resultSet = query("SELECT * FROM refrigerator_readings WHERE refrigeratorId = " + "(SELECT id FROM refrigerators WHERE serialNumber = '%s' AND facilityId = " + "(SELECT id FROM facilities WHERE code = '%s'));", refrigeratorSerialNumber, facilityCode); resultSet.next(); return resultSet; } public ResultSet getRefrigeratorProblems(Long readingId) throws SQLException { return query("SELECT * FROM refrigerator_problems WHERE readingId = %d", readingId); } public void updateProcessingPeriodByField(String field, String fieldValue, String periodName, String scheduleCode) throws SQLException { update("update processing_periods set " + field + "=" + fieldValue + " where name='" + periodName + "'" + " and scheduleId =" + "(Select id from processing_schedules where code = '" + scheduleCode + "');"); } public ResultSet getRefrigeratorsData(String refrigeratorSerialNumber, String facilityCode) throws SQLException { ResultSet resultSet = query("SELECT * FROM refrigerators WHERE serialNumber = '" + refrigeratorSerialNumber + "' AND facilityId = " + getAttributeFromTable("facilities", "id", "code", facilityCode)); resultSet.next(); return resultSet; } public String getAttributeFromTable(String tableName, String attribute, String queryColumn, String queryParam) throws SQLException { String returnValue = null; ResultSet resultSet = query("select * from %s where %s in ('%s');", tableName, queryColumn, queryParam); if (resultSet.next()) { returnValue = resultSet.getString(attribute); } return returnValue; } public String getRowsCountFromDB(String tableName) throws SQLException { String rowCount = null; ResultSet rs = query("SELECT count(*) as count from " + tableName + ""); if (rs.next()) { rowCount = rs.getString("count"); } return rowCount; } public String getCreatedDate(String tableName, String dateFormat) throws SQLException { String createdDate = null; ResultSet rs = query("SELECT to_char(createdDate, '" + dateFormat + "' ) from " + tableName); if (rs.next()) { createdDate = rs.getString(1); } return createdDate; } public Integer getRequisitionGroupId(String facilityCode) throws SQLException { return Integer.parseInt(getAttributeFromTable("requisition_group_members", "requisitionGroupId", "facilityId", getAttributeFromTable("facilities", "id", "code", facilityCode))); } public void insertOneProduct(String product) throws SQLException { update("INSERT INTO products\n" + "(code, alternateItemCode, manufacturer, manufacturerCode, manufacturerBarcode, mohBarcode, gtin, type, primaryName, fullName, genericName, alternateName, description, strength, formId, dosageUnitId, dispensingUnit, dosesPerDispensingUnit, packSize, alternatePackSize, storeRefrigerated, storeRoomTemperature, hazardous, flammable, controlledSubstance, lightSensitive, approvedByWho, contraceptiveCyp, packLength, packWidth, packHeight, packWeight, packsPerCarton, cartonLength, cartonWidth, cartonHeight, cartonsPerPallet, expectedShelfLife, specialStorageInstructions, specialTransportInstructions, active, fullSupply, tracer, packRoundingThreshold, roundToZero, archived, displayOrder, categoryId) values\n" + "('" + product + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, FALSE, TRUE, 1, FALSE, TRUE, 5, (Select id from product_categories where code='C1'));\n"); } public void deleteAllProducts() throws SQLException { update("delete from facility_approved_products;"); update("delete from program_products;"); update("delete from products;"); } public void setUpDataForChildCoverage() throws SQLException { update("INSERT INTO products\n" + "(code, alternateItemCode, manufacturer, manufacturerCode, manufacturerBarcode, mohBarcode, gtin, type, primaryName, fullName, genericName, alternateName, description, strength, formId, dosageUnitId, dispensingUnit, dosesPerDispensingUnit, packSize, alternatePackSize, storeRefrigerated, storeRoomTemperature, hazardous, flammable, controlledSubstance, lightSensitive, approvedByWho, contraceptiveCyp, packLength, packWidth, packHeight, packWeight, packsPerCarton, cartonLength, cartonWidth, cartonHeight, cartonsPerPallet, expectedShelfLife, specialStorageInstructions, specialTransportInstructions, active, fullSupply, tracer, packRoundingThreshold, roundToZero, archived, displayOrder, categoryId) values\n" + "('Measles', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'Measles', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, 1, (Select id from product_categories where code='C1')),\n" + "('BCG', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'BCG', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, FALSE, TRUE, 1, FALSE, TRUE, 5, (Select id from product_categories where code='C1')),\n" + "('polio10dose','a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'polio10dose', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, 1, (Select id from product_categories where code='C1')),\n" + "('polio20dose','a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'polio20dose', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, FALSE, TRUE, 1, FALSE, TRUE, 5, (Select id from product_categories where code='C1')),\n" + "('penta1', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'penta1', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, 1, (Select id from product_categories where code='C1')),\n" + "('penta10', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'penta10', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, FALSE, TRUE, 1, FALSE, TRUE, 5, (Select id from product_categories where code='C1'));\n"); } public void insertRegimenProductMapping() throws SQLException { update("INSERT INTO coverage_vaccination_products\n" + "(vaccination, productCode, childCoverage) values\n" + "('BCG', 'BCG', TRUE),\n" + "('Polio (Newborn)', 'polio10dose',TRUE),\n" + "('Polio 1st dose', 'polio20dose' ,TRUE),\n" + "('Polio 2nd dose', 'polio10dose' ,TRUE),\n" + "('Polio 3rd dose', 'polio20dose' ,TRUE),\n" + "('Penta 1st dose', 'penta1',TRUE),\n" + "('Penta 2nd dose', 'penta10',TRUE),\n" + "('Penta 3rd dose', 'penta1',TRUE),\n" + "('PCV10 1st dose', 'P10',TRUE),\n" + "('PCV10 2nd dose', 'P10', TRUE),\n" + "('PCV10 3rd dose', 'P10', TRUE),\n" + "('Measles', 'Measles',TRUE);\n"); } public ResultSet getChildCoverageDetails(String vaccination, String facilityCode) throws SQLException { ResultSet resultSet = query("SELECT * FROM vaccination_child_coverage_line_items WHERE vaccination = '%s'" + "AND facilityVisitId=(Select id from facility_visits where facilityId=" + "(Select id from facilities where code ='%s'));", vaccination, facilityCode); resultSet.next(); return resultSet; } public void insertRequisitionWithMultipleLineItems(int numberOfLineItems, String program, boolean withSupplyLine, String facilityCode, boolean emergency) throws SQLException { boolean flag = true; update("insert into requisitions (facilityId, programId, periodId, status, emergency, fullSupplyItemsSubmittedCost, " + "nonFullSupplyItemsSubmittedCost, supervisoryNodeId) " + "values ((Select id from facilities where code='" + facilityCode + "'),(Select id from programs where code='" + program + "')," + "(Select id from processing_periods where name='Period1'), 'APPROVED', '" + emergency + "', 50.0000, 0.0000, " + "(select id from supervisory_nodes where code='N1'))"); String insertSql = "INSERT INTO requisition_line_items (rnrId, productCode,product,productDisplayOrder,productCategory," + "productCategoryDisplayOrder, beginningBalance, quantityReceived, quantityDispensed, stockInHand, dispensingUnit, maxMonthsOfStock, " + "dosesPerMonth, dosesPerDispensingUnit, packSize, fullSupply,totalLossesAndAdjustments,newPatientCount,stockOutDays,price," + "roundToZero,packRoundingThreshold,packsToShip) VALUES"; for (int i = 0; i < numberOfLineItems; i++) { String productDisplayOrder = getAttributeFromTable("products", "displayOrder", "code", "F" + i); String categoryId = getAttributeFromTable("products", "categoryId", "code", "F" + i); String categoryCode = getAttributeFromTable("product_categories", "code", "id", categoryId); String categoryDisplayOrder = getAttributeFromTable("product_categories", "displayOrder", "id", categoryId); update(insertSql + "((SELECT max(id) FROM requisitions), 'F" + i + "','antibiotic Capsule 300/200/600 mg', %s, '%s', %s, '0', '11' , " + "'1', '10' ,'Strip','3', '30', '10', '10','t',0,0,0,12.5000,'f',1,5);", productDisplayOrder, categoryCode, categoryDisplayOrder); update(insertSql + "((SELECT max(id) FROM requisitions), 'NF" + i + "','antibiotic Capsule 300/200/600 mg', %s, '%s', %s, '0', '11' ," + " '1', '10' ,'Strip','3', '30', '10', '10','f',0,0,0,12.5000,'f',1,50);", productDisplayOrder, categoryCode, categoryDisplayOrder); } if (withSupplyLine) { ResultSet rs1 = query("select * from supply_lines where supervisoryNodeId = " + "(select id from supervisory_nodes where code = 'N1') and programId = " + "(select id from programs where code='" + program + "') and supplyingFacilityId = " + "(select id from facilities where code = 'F10')"); if (rs1.next()) { flag = false; } } if (withSupplyLine) { if (flag) { insertSupplyLines("N1", program, "F10", true); } } } public void convertRequisitionToOrder(int maxRnrID, String orderStatus, String userName) throws SQLException { update("update requisitions set status = 'RELEASED' where id = %d", maxRnrID); String supervisoryNodeId = getAttributeFromTable("supervisory_nodes", "id", "code", "N1"); Integer supplyingLineId = Integer.valueOf(getAttributeFromTable("supply_lines", "id", "supervisoryNodeId", supervisoryNodeId)); Integer userId = Integer.valueOf(getAttributeFromTable("users", "id", "username", userName)); update("INSERT INTO orders(id, status, ftpComment, supplyLineId, createdBy, modifiedBy) VALUES (%d, '%s', %s, %d, %d, %d)", maxRnrID, orderStatus, null, supplyingLineId, userId, userId); } public void deleteTable(String tableName) throws SQLException { update("delete from " + tableName); } public void updatePopulationOfFacility(String facility, String population) throws SQLException { update("update facilities set catchmentPopulation=" + population + " where code='" + facility + "';"); } }
test-modules/test-core/src/main/java/org/openlmis/UiUtils/DBWrapper.java
/* * This program is part of the OpenLMIS logistics management information system platform software. * Copyright © 2013 VillageReach * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. *   * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License along with this program.  If not, see http://www.gnu.org/licenses.  For additional information contact [email protected].  */ package org.openlmis.UiUtils; import java.sql.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static java.lang.String.format; import static java.lang.System.getProperty; public class DBWrapper { public static final int DEFAULT_MAX_MONTH_OF_STOCK = 3; public static final String DEFAULT_DB_URL = "jdbc:postgresql://localhost:5432/open_lmis"; public static final String DEFAULT_DB_USERNAME = "postgres"; public static final String DEFAULT_DB_PASSWORD = "p@ssw0rd"; Connection connection; public DBWrapper() throws SQLException { String dbUser = getProperty("dbUser", DEFAULT_DB_USERNAME); String dbPassword = getProperty("dbPassword", DEFAULT_DB_PASSWORD); String dbUrl = getProperty("dbUrl", DEFAULT_DB_URL); loadDriver(); connection = DriverManager.getConnection(dbUrl, dbUser, dbPassword); } public void closeConnection() throws SQLException { if (connection != null) connection.close(); } private void loadDriver() { try { Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException e) { System.exit(1); } } private void update(String sql) throws SQLException { try (Statement statement = connection.createStatement()) { statement.executeUpdate(sql); } } private void update(String sql, Object... params) throws SQLException { update(format(sql, params)); } private ResultSet query(String sql) throws SQLException { return connection.createStatement().executeQuery(sql); } private List<Map<String, String>> select(String sql, Object... params) throws SQLException { ResultSet rs = query(sql, params); ResultSetMetaData md = rs.getMetaData(); int columns = md.getColumnCount(); List<Map<String, String>> list = new ArrayList<>(); while (rs.next()) { Map<String, String> row = new HashMap<>(); for (int i = 1; i <= columns; ++i) { row.put(md.getColumnName(i), rs.getString(i)); } list.add(row); } return list; } private ResultSet query(String sql, Object... params) throws SQLException { return query(format(sql, params)); } public void insertUser(String userId, String userName, String password, String facilityCode, String email) throws SQLException { update("delete from users where userName like('%s')", userName); update("INSERT INTO users(id, userName, password, facilityId, firstName, lastName, email, active, verified) " + "VALUES ('%s', '%s', '%s', (SELECT id FROM facilities WHERE code = '%s'), 'Fatima', 'Doe', '%s','true','true')", userId, userName, password, facilityCode, email); } public void insertPeriodAndAssociateItWithSchedule(String period, String schedule) throws SQLException { insertProcessingPeriod(period, period, "2013-09-29", "2020-09-30", 66, schedule); } public List<String> getProductDetailsForProgram(String programCode) throws SQLException { List<String> prodDetails = new ArrayList<>(); ResultSet rs = query("select programs.code as programCode, programs.name as programName, " + "products.code as productCode, products.primaryName as productName, products.description as desc, " + "products.dosesPerDispensingUnit as unit, PG.name as pgName " + "from products, programs, program_products PP, product_categories PG " + "where programs.id = PP.programId and PP.productId=products.id and " + "PG.id = products.categoryId and programs.code='" + programCode + "' " + "and products.active='true' and PP.active='true'"); while (rs.next()) { String programName = rs.getString(2); String productCode = rs.getString(3); String productName = rs.getString(4); String desc = rs.getString(5); String unit = rs.getString(6); String pcName = rs.getString(7); prodDetails.add(programName + "," + productCode + "," + productName + "," + desc + "," + unit + "," + pcName); } return prodDetails; } public List<String> getProductDetailsForProgramAndFacilityType(String programCode, String facilityCode) throws SQLException { List<String> prodDetails = new ArrayList<>(); ResultSet rs = query("select program.code as programCode, program.name as programName, product.code as productCode, " + "product.primaryName as productName, product.description as desc, product.dosesPerDispensingUnit as unit, " + "pg.name as pgName from products product, programs program, program_products pp, product_categories pg, " + "facility_approved_products fap, facility_types ft where program.id=pp.programId and pp.productId=product.id and " + "pg.id = product.categoryId and fap. programProductId = pp.id and ft.id=fap.facilityTypeId and program.code='" + programCode + "' and ft.code='" + facilityCode + "' " + "and product.active='true' and pp.active='true'"); while (rs.next()) { String programName = rs.getString(2); String productCode = rs.getString(3); String productName = rs.getString(4); String desc = rs.getString(5); String unit = rs.getString(6); String pgName = rs.getString(7); prodDetails.add(programName + "," + productCode + "," + productName + "," + desc + "," + unit + "," + pgName); } return prodDetails; } public void updateActiveStatusOfProgramProduct(String productCode, String programCode, String active) throws SQLException { update("update program_products set active='%s' WHERE" + " programId = (select id from programs where code='%s') AND" + " productId = (select id from products where code='%s')", active, programCode, productCode); } public List<String> getFacilityCodeNameForDeliveryZoneAndProgram(String deliveryZoneName, String program, boolean active) throws SQLException { List<String> codeName = new ArrayList<>(); ResultSet rs = query( "select f.code, f.name from facilities f, programs p, programs_supported ps, delivery_zone_members dzm, delivery_zones dz where " + "dzm.DeliveryZoneId=dz.id and " + "f.active='" + active + "' and " + "p.id= ps.programId and " + "p.code='" + program + "' and " + "dz.id = dzm.DeliveryZoneId and " + "dz.name='" + deliveryZoneName + "' and " + "dzm.facilityId = f.id and " + "ps.facilityId = f.id;"); while (rs.next()) { String code = rs.getString("code"); String name = rs.getString("name"); codeName.add(code + " - " + name); } return codeName; } public void deleteDeliveryZoneMembers(String facilityCode) throws SQLException { update("delete from delivery_zone_members where facilityId in (select id from facilities where code ='%s')", facilityCode); } public void updateUser(String password, String email) throws SQLException { update("DELETE FROM user_password_reset_tokens"); update("update users set password = '%s', active = TRUE, verified = TRUE where email = '%s'", password, email); } public void updateRestrictLogin(String userName, boolean status) throws SQLException { update("update users set restrictLogin = '%s' where userName = '%s'", status, userName); } public void insertRequisitions(int numberOfRequisitions, String program, boolean withSupplyLine, String periodStartDate, String periodEndDate, String facilityCode, boolean emergency) throws SQLException { int numberOfRequisitionsAlreadyPresent = 0; boolean flag = true; ResultSet rs = query("select count(*) from requisitions"); if (rs.next()) { numberOfRequisitionsAlreadyPresent = Integer.parseInt(rs.getString(1)); } for (int i = numberOfRequisitionsAlreadyPresent + 1; i <= numberOfRequisitions + numberOfRequisitionsAlreadyPresent; i++) { insertProcessingPeriod("PeriodName" + i, "PeriodDesc" + i, periodStartDate, periodEndDate, 1, "M"); update("insert into requisitions (facilityId, programId, periodId, status, emergency, " + "fullSupplyItemsSubmittedCost, nonFullSupplyItemsSubmittedCost, supervisoryNodeId) " + "values ((Select id from facilities where code='" + facilityCode + "'),(Select id from programs where code='" + program + "')," + "(Select id from processing_periods where name='PeriodName" + i + "'), 'APPROVED', '" + emergency + "', 50.0000, 0.0000, " + "(select id from supervisory_nodes where code='N1'))"); update("INSERT INTO requisition_line_items " + "(rnrId, productCode,product,productDisplayOrder,productCategory,productCategoryDisplayOrder, beginningBalance, quantityReceived, quantityDispensed, stockInHand, " + "dispensingUnit, maxMonthsOfStock, dosesPerMonth, dosesPerDispensingUnit, packSize,fullSupply,totalLossesAndAdjustments,newPatientCount,stockOutDays,price,roundToZero,packRoundingThreshold) VALUES" + "((SELECT max(id) FROM requisitions), 'P10','antibiotic Capsule 300/200/600 mg',1,'Antibiotics',1, '0', '11' , '1', '10' ,'Strip','3', '30', '10', '10','t',0,0,0,12.5000,'f',1);"); } if (withSupplyLine) { ResultSet rs1 = query("select * from supply_lines where supervisoryNodeId = " + "(select id from supervisory_nodes where code = 'N1') and programId = " + "(select id from programs where code='" + program + "') and supplyingFacilityId = " + "(select id from facilities where code = 'F10')"); if (rs1.next()) { flag = false; } } if (withSupplyLine) { if (flag) { insertSupplyLines("N1", program, "F10", true); } } } public void insertFulfilmentRoleAssignment(String userName, String roleName, String facilityCode) throws SQLException { update("insert into fulfillment_role_assignments(userId, roleId, facilityId) values " + "((select id from users where username='" + userName + "')," + "(select id from roles where name='" + roleName + "'),(select id from facilities where code='" + facilityCode + "'))"); } public String getDeliveryZoneNameAssignedToUser(String user) throws SQLException { String deliveryZoneName = ""; ResultSet rs = query( "select name from delivery_zones where id in(select deliveryZoneId from role_assignments where " + "userId=(select id from users where username='" + user + "'))"); if (rs.next()) { deliveryZoneName = rs.getString("name"); } return deliveryZoneName; } public String getRoleNameAssignedToUser(String user) throws SQLException { String userName = ""; ResultSet rs = query("select name from roles where id in(select roleId from role_assignments where " + "userId=(select id from users where username='" + user + "'))"); if (rs.next()) { userName = rs.getString("name"); } return userName; } public void insertFacilities(String facility1, String facility2) throws SQLException { update("INSERT INTO facilities\n" + "(code, name, description, gln, mainPhone, fax, address1, address2, geographicZoneId, typeId, catchmentPopulation, latitude, longitude, altitude, operatedById, coldStorageGrossCapacity, coldStorageNetCapacity, suppliesOthers, sdp, hasElectricity, online, hasElectronicSCC, hasElectronicDAR, active, goLiveDate, goDownDate, satellite, comment, enabled, virtualFacility) values\n" + "('" + facility1 + "','Village Dispensary','IT department','G7645',9876234981,'fax','A','B',5,2,333,22.1,1.2,3.3,2,9.9,6.6,'TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','11/11/12','11/11/1887','TRUE','fc','TRUE', 'FALSE'),\n" + "('" + facility2 + "','Central Hospital','IT department','G7646',9876234981,'fax','A','B',5,2,333,22.3,1.2,3.3,3,9.9,6.6,'TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','11/11/12','11/11/2012','TRUE','fc','TRUE', 'FALSE');\n"); update("insert into programs_supported(facilityId, programId, startDate, active, modifiedBy) VALUES" + " ((SELECT id FROM facilities WHERE code = '" + facility1 + "'), 1, '11/11/12', true, 1)," + " ((SELECT id FROM facilities WHERE code = '" + facility1 + "'), 2, '11/11/12', true, 1)," + " ((SELECT id FROM facilities WHERE code = '" + facility1 + "'), 5, '11/11/12', true, 1)," + " ((SELECT id FROM facilities WHERE code = '" + facility2 + "'), 1, '11/11/12', true, 1)," + " ((SELECT id FROM facilities WHERE code = '" + facility2 + "'), 5, '11/11/12', true, 1)," + " ((SELECT id FROM facilities WHERE code = '" + facility2 + "'), 2, '11/11/12', true, 1)"); } public void insertVirtualFacility(String facilityCode, String parentFacilityCode) throws SQLException { update("INSERT INTO facilities\n" + "(code, name, description, gln, mainPhone, fax, address1, address2, geographicZoneId, typeId, catchmentPopulation, latitude, longitude, altitude, operatedById, coldStorageGrossCapacity, coldStorageNetCapacity, suppliesOthers, sdp, hasElectricity, online, hasElectronicSCC, hasElectronicDAR, active, goLiveDate, goDownDate, satellite, comment, enabled, virtualFacility,parentFacilityId) values\n" + "('" + facilityCode + "','Village Dispensary','IT department','G7645',9876234981,'fax','A','B',5,2,333,22.1,1.2,3.3,2,9.9,6.6,'TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','11/11/12','11/11/2012','TRUE','fc','TRUE', 'TRUE',(SELECT id FROM facilities WHERE code = '" + parentFacilityCode + "'))"); update("insert into programs_supported(facilityId, programId, startDate, active, modifiedBy) VALUES" + " ((SELECT id FROM facilities WHERE code = '" + facilityCode + "'), 1, '11/11/12', true, 1)," + " ((SELECT id FROM facilities WHERE code = '" + facilityCode + "'), 2, '11/11/12', true, 1)," + " ((SELECT id FROM facilities WHERE code = '" + facilityCode + "'), 5, '11/11/12', true, 1)"); update("insert into requisition_group_members (requisitionGroupId, facilityId, createdDate, modifiedDate) values " + "((select requisitionGroupId from requisition_group_members where facilityId=(SELECT id FROM facilities WHERE code = '" + parentFacilityCode + "'))," + "(SELECT id FROM facilities WHERE code = '" + facilityCode + "'),NOW(),NOW())"); } public void deleteRowFromTable(String tableName, String queryParam, String queryValue) throws SQLException { update("delete from " + tableName + " where " + queryParam + "='" + queryValue + "';"); } public void insertFacilitiesWithDifferentGeoZones(String facility1, String facility2, String geoZone1, String geoZone2) throws SQLException { update("INSERT INTO facilities\n" + "(code, name, description, gln, mainPhone, fax, address1, address2, geographicZoneId, typeId, catchmentPopulation, latitude, longitude, altitude, operatedById, coldStorageGrossCapacity, coldStorageNetCapacity, suppliesOthers, sdp, hasElectricity, online, hasElectronicSCC, hasElectronicDAR, active, goLiveDate, goDownDate, satellite, comment, enabled, virtualFacility) values\n" + "('" + facility1 + "','Village Dispensary','IT department','G7645',9876234981,'fax','A','B',(select id from geographic_zones where code='" + geoZone1 + "'),2,333,22.1,1.2,3.3,2,9.9,6.6,'TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','11/11/12','11/11/1887','TRUE','fc','TRUE', 'FALSE'),\n" + "('" + facility2 + "','Central Hospital','IT department','G7646',9876234981,'fax','A','B',(select id from geographic_zones where code='" + geoZone2 + "'),2,333,22.3,1.2,3.3,3,9.9,6.6,'TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','11/11/12','11/11/2012','TRUE','fc','TRUE', 'FALSE');\n"); update("insert into programs_supported(facilityId, programId, startDate, active, modifiedBy) VALUES\n" + "((SELECT id FROM facilities WHERE code = '" + facility1 + "'), 1, '11/11/12', true, 1),\n" + "((SELECT id FROM facilities WHERE code = '" + facility1 + "'), 2, '11/11/12', true, 1),\n" + "((SELECT id FROM facilities WHERE code = '" + facility1 + "'), 5, '11/11/12', true, 1),\n" + "((SELECT id FROM facilities WHERE code = '" + facility2 + "'), 1, '11/11/12', true, 1),\n" + "((SELECT id FROM facilities WHERE code = '" + facility2 + "'), 5, '11/11/12', true, 1),\n" + "((SELECT id FROM facilities WHERE code = '" + facility2 + "'), 2, '11/11/12', true, 1);"); } public void insertGeographicZone(String code, String name, String parentName) throws SQLException { update("insert into geographic_zones (code, name, levelId, parentId) " + "values ('%s','%s',(select max(levelId) from geographic_zones)," + "(select id from geographic_zones where code='%s'))", code, name, parentName); } public void allocateFacilityToUser(String userId, String facilityCode) throws SQLException { update("update users set facilityId = (Select id from facilities where code = '%s') where id = '%s'", facilityCode, userId); } public void updateSourceOfAProgramTemplate(String program, String label, String source) throws SQLException { update("update program_rnr_columns set source = '%s'" + " where programId = (select id from programs where code = '%s') and label = '%s'", source, program, label); } public void deleteData() throws SQLException { update("delete from budget_line_items"); update("delete from budget_file_info"); update("delete from role_rights where roleId not in(1)"); update("delete from role_assignments where userId not in (1)"); update("delete from fulfillment_role_assignments"); update("delete from roles where name not in ('Admin')"); update("delete from facility_approved_products"); update("delete from program_product_price_history"); update("delete from pod_line_items"); update("delete from pod"); update("delete from orders"); update("delete from requisition_status_changes"); update("delete from user_password_reset_tokens"); update("delete from comments"); update("delete from epi_use_line_items"); update("delete from epi_inventory_line_items"); update("delete from refrigerator_problems"); update("delete from refrigerator_readings"); update("delete from full_coverages"); update("delete from vaccination_child_coverage_line_items;"); update("delete from coverage_vaccination_products;"); update("delete from facility_visits"); update("delete from distributions"); update("delete from refrigerators"); update("delete from users where userName not like('Admin%')"); deleteRnrData(); update("delete from program_product_isa"); update("delete from facility_approved_products"); update("delete from facility_program_products"); update("delete from program_products"); update("delete from coverage_vaccination_products"); update("delete from products"); update("delete from product_categories"); update("delete from product_groups"); update("delete from supply_lines"); update("delete from programs_supported"); update("delete from requisition_group_members"); update("delete from program_rnr_columns"); update("delete from requisition_group_program_schedules"); update("delete from requisition_groups"); update("delete from requisition_group_members"); update("delete from delivery_zone_program_schedules"); update("delete from delivery_zone_warehouses"); update("delete from delivery_zone_members"); update("delete from role_assignments where deliveryZoneId in (select id from delivery_zones where code in('DZ1','DZ2'))"); update("delete from delivery_zones"); update("delete from supervisory_nodes"); update("delete from facility_ftp_details"); update("delete from facilities"); update("delete from geographic_zones where code not in ('Root','Arusha','Dodoma', 'Ngorongoro')"); update("delete from processing_periods"); update("delete from processing_schedules"); update("delete from atomfeed.event_records"); update("delete from regimens"); update("delete from program_regimen_columns"); } public void deleteRnrData() throws SQLException { update("delete from requisition_line_item_losses_adjustments"); update("delete from requisition_line_items"); update("delete from regimen_line_items"); update("delete from requisitions"); } public void insertRole(String role, String description) throws SQLException { ResultSet rs = query("Select id from roles where name='%s'", role); if (!rs.next()) { update("INSERT INTO roles(name, description) VALUES('%s', '%s')", role, description); } } public void insertSupervisoryNode(String facilityCode, String supervisoryNodeCode, String supervisoryNodeName, String supervisoryNodeParentCode) throws SQLException { update("delete from supervisory_nodes"); update("INSERT INTO supervisory_nodes (parentId, facilityId, name, code) " + "VALUES (%s, (SELECT id FROM facilities WHERE " + "code = '%s'), '%s', '%s')", supervisoryNodeParentCode, facilityCode, supervisoryNodeName, supervisoryNodeCode); } public void insertSupervisoryNodeSecond(String facilityCode, String supervisoryNodeCode, String supervisoryNodeName, String supervisoryNodeParentCode) throws SQLException { update("INSERT INTO supervisory_nodes" + " (parentId, facilityId, name, code) VALUES" + " ((select id from supervisory_nodes where code ='%s'), (SELECT id FROM facilities WHERE code = '%s'), '%s', '%s')", supervisoryNodeParentCode, facilityCode, supervisoryNodeName, supervisoryNodeCode); } public void insertRequisitionGroups(String code1, String code2, String supervisoryNodeCode1, String supervisoryNodeCode2) throws SQLException { ResultSet rs = query("Select id from requisition_groups;"); if (rs.next()) { update("delete from requisition_groups;"); } update("INSERT INTO requisition_groups ( code ,name,description,supervisoryNodeId )values\n" + "('" + code2 + "','Requisition Group 2','Supports EM(Q1M)',(select id from supervisory_nodes where code ='" + supervisoryNodeCode2 + "')),\n" + "('" + code1 + "','Requisition Group 1','Supports EM(Q2M)',(select id from supervisory_nodes where code ='" + supervisoryNodeCode1 + "'))"); } public void insertRequisitionGroupMembers(String RG1facility, String RG2facility) throws SQLException { ResultSet rs = query("Select requisitionGroupId from requisition_group_members;"); if (rs.next()) { update("delete from requisition_group_members;"); } update("INSERT INTO requisition_group_members ( requisitionGroupId ,facilityId )values\n" + "((select id from requisition_groups where code ='RG1'),(select id from facilities where code ='" + RG1facility + "')),\n" + "((select id from requisition_groups where code ='RG2'),(select id from facilities where code ='" + RG2facility + "'));"); } public void insertRequisitionGroupProgramSchedule() throws SQLException { ResultSet rs = query("Select requisitionGroupId from requisition_group_members;"); if (rs.next()) { update("delete from requisition_group_program_schedules;"); } update( "insert into requisition_group_program_schedules ( requisitionGroupId , programId , scheduleId , directDelivery ) values\n" + "((select id from requisition_groups where code='RG1'),(select id from programs where code='ESS_MEDS'),(select id from processing_schedules where code='Q1stM'),TRUE),\n" + "((select id from requisition_groups where code='RG1'),(select id from programs where code='MALARIA'),(select id from processing_schedules where code='Q1stM'),TRUE),\n" + "((select id from requisition_groups where code='RG1'),(select id from programs where code='HIV'),(select id from processing_schedules where code='M'),TRUE),\n" + "((select id from requisition_groups where code='RG2'),(select id from programs where code='ESS_MEDS'),(select id from processing_schedules where code='Q1stM'),TRUE),\n" + "((select id from requisition_groups where code='RG2'),(select id from programs where code='MALARIA'),(select id from processing_schedules where code='Q1stM'),TRUE),\n" + "((select id from requisition_groups where code='RG2'),(select id from programs where code='HIV'),(select id from processing_schedules where code='M'),TRUE);\n"); } //TODO public void insertRoleAssignment(String userID, String roleName) throws SQLException { update("delete from role_assignments where userId='" + userID + "';"); update(" INSERT INTO role_assignments\n" + " (userId, roleId, programId, supervisoryNodeId) VALUES \n" + " ('" + userID + "', (SELECT id FROM roles WHERE name = '" + roleName + "'), 1, null),\n" + " ('" + userID + "', (SELECT id FROM roles WHERE name = '" + roleName + "'), 1, (SELECT id from supervisory_nodes WHERE code = 'N1'));"); } //TODO public void insertRoleAssignmentForSupervisoryNodeForProgramId1(String userID, String roleName, String supervisoryNode) throws SQLException { update("delete from role_assignments where userId='" + userID + "';"); update(" INSERT INTO role_assignments\n" + " (userId, roleId, programId, supervisoryNodeId) VALUES \n" + " ('" + userID + "', (SELECT id FROM roles WHERE name = '" + roleName + "'), 1, null),\n" + " ('" + userID + "', (SELECT id FROM roles WHERE name = '" + roleName + "'), 1, (SELECT id from supervisory_nodes WHERE code = '" + supervisoryNode + "'));"); } public void updateRoleGroupMember(String facilityCode) throws SQLException { update("update requisition_group_members set facilityId = " + "(select id from facilities where code ='" + facilityCode + "') where " + "requisitionGroupId=(select id from requisition_groups where code='RG2');"); update("update requisition_group_members set facilityId = " + "(select id from facilities where code ='F11') where requisitionGroupId = " + "(select id from requisition_groups where code='RG1');"); } public void alterUserID(String userName, String userId) throws SQLException { update("delete from user_password_reset_tokens;"); update("delete from users where id='" + userId + "' ;"); update(" update users set id='" + userId + "' where username='" + userName + "'"); } public void insertProducts(String product1, String product2) throws SQLException { update("delete from facility_approved_products;"); update("delete from epi_inventory_line_items;"); update("delete from program_products;"); update("delete from products;"); update("delete from product_categories;"); update("INSERT INTO product_categories (code, name, displayOrder) values ('C1', 'Antibiotics', 1);"); update("INSERT INTO products\n" + "(code, alternateItemCode, manufacturer, manufacturerCode, manufacturerBarcode, mohBarcode, gtin, type, primaryName, fullName, genericName, alternateName, description, strength, formId, dosageUnitId, dispensingUnit, dosesPerDispensingUnit, packSize, alternatePackSize, storeRefrigerated, storeRoomTemperature, hazardous, flammable, controlledSubstance, lightSensitive, approvedByWho, contraceptiveCyp, packLength, packWidth, packHeight, packWeight, packsPerCarton, cartonLength, cartonWidth, cartonHeight, cartonsPerPallet, expectedShelfLife, specialStorageInstructions, specialTransportInstructions, active, fullSupply, tracer, packRoundingThreshold, roundToZero, archived, displayOrder, categoryId) values\n" + "('" + product1 + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, 1, (Select id from product_categories where code='C1')),\n" + "('" + product2 + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, FALSE, TRUE, 1, FALSE, TRUE, 5, (Select id from product_categories where code='C1'));\n"); } public void deleteCategoryFromProducts() throws SQLException { update("UPDATE products SET categoryId = null"); } public void deleteDescriptionFromProducts() throws SQLException { update("UPDATE products SET description = null"); } public void insertProductWithCategory(String product, String productName, String category) throws SQLException { update("INSERT INTO product_categories (code, name, displayOrder) values ('" + category + "', '" + productName + "', 1);"); update("INSERT INTO products\n" + "(code, alternateItemCode, manufacturer, manufacturerCode, manufacturerBarcode, mohBarcode, gtin, type, primaryName, fullName, genericName, alternateName, description, strength, formId, dosageUnitId, dispensingUnit, dosesPerDispensingUnit, packSize, alternatePackSize, storeRefrigerated, storeRoomTemperature, hazardous, flammable, controlledSubstance, lightSensitive, approvedByWho, contraceptiveCyp, packLength, packWidth, packHeight, packWeight, packsPerCarton, cartonLength, cartonWidth, cartonHeight, cartonsPerPallet, expectedShelfLife, specialStorageInstructions, specialTransportInstructions, active, fullSupply, tracer, packRoundingThreshold, roundToZero, archived, displayOrder, categoryId) values\n" + "('" + product + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', '" + productName + "', '" + productName + "', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, 1, (Select id from product_categories where code='C1'));\n"); } public void insertProductGroup(String group) throws SQLException { update("INSERT INTO product_groups (code, name) values ('" + group + "', '" + group + "-Name');"); } public void insertProductWithGroup(String product, String productName, String group, boolean status) throws SQLException { update("INSERT INTO products\n" + "(code, alternateItemCode, manufacturer, manufacturerCode, manufacturerBarcode, mohBarcode, gtin, type, primaryName, fullName," + " genericName, alternateName, description, strength, formId, dosageUnitId, dispensingUnit, dosesPerDispensingUnit, packSize, alternatePackSize," + " storeRefrigerated, storeRoomTemperature, hazardous, flammable, controlledSubstance, lightSensitive, approvedByWho, contraceptiveCyp, packLength, " + "packWidth, packHeight, packWeight, packsPerCarton, cartonLength, cartonWidth, cartonHeight, cartonsPerPallet, expectedShelfLife, specialStorageInstructions, " + "specialTransportInstructions, active, fullSupply, tracer, packRoundingThreshold, roundToZero, archived, displayOrder, productGroupId) values" + "('" + product + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', '" + productName + "', '" + productName + "', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE," + " 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', " + status + ",TRUE, TRUE, 1, FALSE, TRUE, 1, (Select id from product_groups where code='" + group + "'));"); } public void updateProgramToAPushType(String program, boolean flag) throws SQLException { update("update programs set push='" + flag + "' where code='" + program + "';"); } public void insertProgramProducts(String product1, String product2, String program) throws SQLException { ResultSet rs = query("Select id from program_products;"); if (rs.next()) { update("delete from facility_approved_products;"); update("delete from program_products;"); } update("INSERT INTO program_products(programId, productId, dosesPerMonth, currentPrice, active) VALUES\n" + "((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + product1 + "'), 30, 12.5, true),\n" + "((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + product2 + "'), 30, 12.5, true);"); } public void insertProgramProduct(String product, String program, String doses, String active) throws SQLException { update("INSERT INTO program_products(programId, productId, dosesPerMonth, currentPrice, active) VALUES\n" + "((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + product + "'), '" + doses + "', 12.5, '" + active + "');"); } public void insertProgramProductsWithCategory(String product, String program) throws SQLException { update("INSERT INTO program_products(programId, productId, dosesPerMonth, currentPrice, active) VALUES\n" + "((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + product + "'), 30, 12.5, true);"); } public void insertProgramProductISA(String program, String product, String whoRatio, String dosesPerYear, String wastageFactor, String bufferPercentage, String minimumValue, String maximumValue, String adjustmentValue) throws SQLException { update( "INSERT INTO program_product_isa(programProductId, whoRatio, dosesPerYear, wastageFactor, bufferPercentage, minimumValue, maximumValue, adjustmentValue) VALUES\n" + "((SELECT ID from program_products where programId = " + "(SELECT ID from programs where code='" + program + "') and productId = " + "(SELECT id from products WHERE code = '" + product + "'))," + whoRatio + "," + dosesPerYear + "," + wastageFactor + "," + bufferPercentage + "," + minimumValue + "," + maximumValue + "," + adjustmentValue + ");"); } public void insertFacilityApprovedProduct(String productCode, String programCode, String facilityTypeCode) throws SQLException { String facilityTypeIdQuery = format("(SELECT id FROM facility_types WHERE code = '%s')", facilityTypeCode); String productIdQuery = format("(SELECT id FROM products WHERE code = '%s')", productCode); String programIdQuery = format("(SELECT ID from programs where code = '%s' )", programCode); String programProductIdQuery = format("(SELECT id FROM program_products WHERE programId = %s AND productId = %s)", programIdQuery, productIdQuery); update(format( "INSERT INTO facility_approved_products(facilityTypeId, programProductId, maxMonthsOfStock) VALUES (%s,%s,%d)", facilityTypeIdQuery, programProductIdQuery, DEFAULT_MAX_MONTH_OF_STOCK)); } public String fetchNonFullSupplyData(String productCode, String facilityTypeID, String programID) throws SQLException { ResultSet rs = query("Select p.code, p.displayOrder, p.primaryName, pf.code as ProductForm," + "p.strength as Strength, du.code as DosageUnit from facility_approved_products fap, " + "program_products pp, products p, product_forms pf , dosage_units du where fap. facilityTypeId='" + facilityTypeID + "' " + "and p. fullSupply = false and p.active=true and pp.programId='" + programID + "' and p. code='" + productCode + "' " + "and pp.productId=p.id and fap. programProductId=pp.id and pp.active=true and pf.id=p.formId " + "and du.id = p.dosageUnitId order by p. displayOrder asc;"); String nonFullSupplyValues = null; if (rs.next()) { nonFullSupplyValues = rs.getString("primaryName") + " " + rs.getString("productForm") + " " + rs.getString("strength") + " " + rs.getString("dosageUnit"); } return nonFullSupplyValues; } public void insertSchedule(String scheduleCode, String scheduleName, String scheduleDesc) throws SQLException { update("INSERT INTO processing_schedules(code, name, description) values('" + scheduleCode + "', '" + scheduleName + "', '" + scheduleDesc + "');"); } public void insertProcessingPeriod(String periodName, String periodDesc, String periodStartDate, String periodEndDate, Integer numberOfMonths, String scheduleCode) throws SQLException { update("INSERT INTO processing_periods\n" + "(name, description, startDate, endDate, numberOfMonths, scheduleId, modifiedBy) VALUES\n" + "('" + periodName + "', '" + periodDesc + "', '" + periodStartDate + " 00:00:00', '" + periodEndDate + " 23:59:59', " + numberOfMonths + ", (SELECT id FROM processing_schedules WHERE code = '" + scheduleCode + "'), (SELECT id FROM users LIMIT 1));"); } public void configureTemplate(String program) throws SQLException { update("INSERT INTO program_rnr_columns\n" + "(masterColumnId, programId, visible, source, formulaValidationRequired, position, label) VALUES\n" + "(1, (select id from programs where code = '" + program + "'), true, 'U', false,1, 'Skip'),\n" + "(2, (select id from programs where code = '" + program + "'), true, 'R', false,2, 'Product Code'),\n" + "(3, (select id from programs where code = '" + program + "'), true, 'R', false,3, 'Product'),\n" + "(4, (select id from programs where code = '" + program + "'), true, 'R', false,4, 'Unit/Unit of Issue'),\n" + "(5, (select id from programs where code = '" + program + "'), true, 'U', false,5, 'Beginning Balance'),\n" + "(6, (select id from programs where code = '" + program + "'), true, 'U', false,6, 'Total Received Quantity'),\n" + "(7, (select id from programs where code = '" + program + "'), true, 'C', false,7, 'Total'),\n" + "(8, (select id from programs where code = '" + program + "'), true, 'U', false,8, 'Total Consumed Quantity'),\n" + "(9, (select id from programs where code = '" + program + "'), true, 'U', false,9, 'Total Losses / Adjustments'),\n" + "(10, (select id from programs where code = '" + program + "'), true, 'C', true,10, 'Stock on Hand'),\n" + "(11, (select id from programs where code = '" + program + "'), true, 'U', false,11, 'New Patients'),\n" + "(12, (select id from programs where code = '" + program + "'), true, 'U', false,12, 'Total StockOut days'),\n" + "(13, (select id from programs where code = '" + program + "'), true, 'C', false,13, 'Adjusted Total Consumption'),\n" + "(14, (select id from programs where code = '" + program + "'), true, 'C', false,14, 'Average Monthly Consumption(AMC)'),\n" + "(15, (select id from programs where code = '" + program + "'), true, 'C', false,15, 'Maximum Stock Quantity'),\n" + "(16, (select id from programs where code = '" + program + "'), true, 'C', false,16, 'Calculated Order Quantity'),\n" + "(17, (select id from programs where code = '" + program + "'), true, 'U', false,17, 'Requested quantity'),\n" + "(18, (select id from programs where code = '" + program + "'), true, 'U', false,18, 'Requested quantity explanation'),\n" + "(19, (select id from programs where code = '" + program + "'), true, 'U', false,19, 'Approved Quantity'),\n" + "(20, (select id from programs where code = '" + program + "'), true, 'C', false,20, 'Packs to Ship'),\n" + "(21, (select id from programs where code = '" + program + "'), true, 'R', false,21, 'Price per pack'),\n" + "(22, (select id from programs where code = '" + program + "'), true, 'C', false,22, 'Total cost'),\n" + "(23, (select id from programs where code = '" + program + "'), true, 'U', false,23, 'Expiration Date'),\n" + "(24, (select id from programs where code = '" + program + "'), true, 'U', false,24, 'Remarks');"); } public void configureTemplateForCommTrack(String program) throws SQLException { update("INSERT INTO program_rnr_columns\n" + "(masterColumnId, programId, visible, source, position, label) VALUES\n" + "(2, (select id from programs where code = '" + program + "'), true, 'R', 1, 'Product Code'),\n" + "(3, (select id from programs where code = '" + program + "'), true, 'R', 2, 'Product'),\n" + "(4, (select id from programs where code = '" + program + "'), true, 'R', 3, 'Unit/Unit of Issue'),\n" + "(5, (select id from programs where code = '" + program + "'), true, 'U', 4, 'Beginning Balance'),\n" + "(6, (select id from programs where code = '" + program + "'), true, 'U', 5, 'Total Received Quantity'),\n" + "(7, (select id from programs where code = '" + program + "'), true, 'C', 6, 'Total'),\n" + "(8, (select id from programs where code = '" + program + "'), true, 'C', 7, 'Total Consumed Quantity'),\n" + "(9, (select id from programs where code = '" + program + "'), true, 'U', 8, 'Total Losses / Adjustments'),\n" + "(10, (select id from programs where code = '" + program + "'), true, 'U', 9, 'Stock on Hand'),\n" + "(11, (select id from programs where code = '" + program + "'), true, 'U', 10, 'New Patients'),\n" + "(12, (select id from programs where code = '" + program + "'), true, 'U', 11, 'Total StockOut days'),\n" + "(13, (select id from programs where code = '" + program + "'), true, 'C', 12, 'Adjusted Total Consumption'),\n" + "(14, (select id from programs where code = '" + program + "'), true, 'C', 13, 'Average Monthly Consumption(AMC)'),\n" + "(15, (select id from programs where code = '" + program + "'), true, 'C', 14, 'Maximum Stock Quantity'),\n" + "(16, (select id from programs where code = '" + program + "'), true, 'C', 15, 'Calculated Order Quantity'),\n" + "(17, (select id from programs where code = '" + program + "'), true, 'U', 16, 'Requested quantity'),\n" + "(18, (select id from programs where code = '" + program + "'), true, 'U', 17, 'Requested quantity explanation'),\n" + "(19, (select id from programs where code = '" + program + "'), true, 'U', 18, 'Approved Quantity'),\n" + "(20, (select id from programs where code = '" + program + "'), true, 'C', 19, 'Packs to Ship'),\n" + "(21, (select id from programs where code = '" + program + "'), true, 'R', 20, 'Price per pack'),\n" + "(22, (select id from programs where code = '" + program + "'), true, 'C', 21, 'Total cost'),\n" + "(23, (select id from programs where code = '" + program + "'), true, 'U', 22, 'Expiration Date'),\n" + "(24, (select id from programs where code = '" + program + "'), true, 'U', 23, 'Remarks');"); } public void InsertOverriddenIsa(String facilityCode, String program, String product, int overriddenIsa) throws SQLException { update("INSERT INTO facility_program_products (facilityId, programProductId,overriddenIsa) VALUES (" + getAttributeFromTable("facilities", "id", "code", facilityCode) + ", (select id from program_products where programId='" + getAttributeFromTable("programs", "id", "code", program) + "' and productId='" + getAttributeFromTable("products", "id", "code", product) + "')," + overriddenIsa + ");"); } public void updateOverriddenIsa(String facilityCode, String program, String product, String overriddenIsa) throws SQLException { update("Update facility_program_products set overriddenIsa=" + overriddenIsa + " where facilityId='" + getAttributeFromTable("facilities", "id", "code", facilityCode) + "' and programProductId = (select id from program_products where programId='" + getAttributeFromTable("programs", "id", "code", program) + "' and productId='" + getAttributeFromTable("products", "id", "code", product) + "');"); } public void insertSupplyLines(String supervisoryNode, String programCode, String facilityCode, boolean exportOrders) throws SQLException { update("insert into supply_lines (description, supervisoryNodeId, programId, supplyingFacilityId,exportOrders) values" + "('supplying node for " + programCode + "', " + "(select id from supervisory_nodes where code = '" + supervisoryNode + "')," + "(select id from programs where code='" + programCode + "')," + "(select id from facilities where code = '" + facilityCode + "')," + exportOrders + ");"); } public void updateSupplyLines(String previousFacilityCode, String newFacilityCode) throws SQLException { update("update supply_lines SET supplyingFacilityId=(select id from facilities where code = '" + newFacilityCode + "') " + "where supplyingFacilityId=(select id from facilities where code = '" + previousFacilityCode + "');"); } public void insertValuesInRequisition(boolean emergencyRequisitionRequired) throws SQLException { update("update requisition_line_items set beginningBalance=1, quantityReceived=1, quantityDispensed = 1, " + "newPatientCount = 1, stockOutDays = 1, quantityRequested = 10, reasonForRequestedQuantity = 'bad climate', " + "normalizedConsumption = 10, packsToShip = 1"); update("update requisitions set fullSupplyItemsSubmittedCost = 12.5000, nonFullSupplyItemsSubmittedCost = 0.0000"); if (emergencyRequisitionRequired) { update("update requisitions set emergency='true'"); } } public void insertValuesInRegimenLineItems(String patientsOnTreatment, String patientsToInitiateTreatment, String patientsStoppedTreatment, String remarks) throws SQLException { update("update regimen_line_items set patientsOnTreatment='" + patientsOnTreatment + "', patientsToInitiateTreatment='" + patientsToInitiateTreatment + "', patientsStoppedTreatment='" + patientsStoppedTreatment + "',remarks='" + remarks + "';"); } public void updateFieldValue(String tableName, String fieldName, Integer quantity) throws SQLException { update("update " + tableName + " set " + fieldName + "=" + quantity + ";"); } public void updateFieldValue(String tableName, String fieldName, String value, String queryParam, String queryValue) throws SQLException { if (queryParam == null) update("update " + tableName + " set " + fieldName + "='" + value + "';"); else update("update " + tableName + " set " + fieldName + "='" + value + "' where " + queryParam + "='" + queryValue + "';"); } public void updateFieldValue(String tableName, String fieldName, Boolean value) throws SQLException { update("update " + tableName + " set " + fieldName + "=" + value + ";"); } public void updateRequisitionStatus(String status, String username, String program) throws SQLException { update("update requisitions set status='" + status + "';"); ResultSet rs = query("select id from requisitions where programId = (select id from programs where code='" + program + "');"); while (rs.next()) { update("insert into requisition_status_changes(rnrId, status, createdBy, modifiedBy) values(" + rs.getString("id") + ", '" + status + "', " + "(select id from users where username = '" + username + "'), (select id from users where username = '" + username + "'));"); } update("update requisitions set supervisoryNodeId = (select id from supervisory_nodes where code='N1');"); update("update requisitions set createdBy= (select id from users where username = '" + username + "') , modifiedBy= (select id from users where username = '" + username + "');"); } public void updateRequisitionStatusByRnrId(String status, String username, int rnrId) throws SQLException { update("update requisitions set status='" + status + "' where id=" + rnrId + ";"); update("insert into requisition_status_changes(rnrId, status, createdBy, modifiedBy) values(" + rnrId + ", '" + status + "', " + "(select id from users where username = '" + username + "'), (select id from users where username = '" + username + "'));"); update("update requisitions set supervisoryNodeId = (select id from supervisory_nodes where code='N1');"); update("update requisitions set createdBy= (select id from users where username = '" + username + "') , modifiedBy= (select id from users where username = '" + username + "');"); } public String getSupplyFacilityName(String supervisoryNode, String programCode) throws SQLException { String facilityName = null; ResultSet rs = query("select name from facilities where id=" + "(select supplyingFacilityId from supply_lines where supervisoryNodeId=" + "(select id from supervisory_nodes where code='" + supervisoryNode + "') and programId = " + "(select id from programs where code='" + programCode + "'));"); if (rs.next()) { facilityName = rs.getString("name"); } return facilityName; } public int getMaxRnrID() throws SQLException { int rnrId = 0; ResultSet rs = query("select max(id) from requisitions"); if (rs.next()) { rnrId = Integer.parseInt(rs.getString("max")); } return rnrId; } public void setupMultipleProducts(String program, String facilityType, int numberOfProductsOfEachType, boolean defaultDisplayOrder) throws SQLException { update("delete from facility_approved_products;"); update("delete from program_products;"); update("delete from products;"); update("delete from product_categories;"); String productCodeFullSupply = "F"; String productCodeNonFullSupply = "NF"; update("INSERT INTO product_categories (code, name, displayOrder) values ('C1', 'Antibiotics', 1);"); ResultSet rs = query("Select id from product_categories where code='C1';"); int categoryId = 0; if (rs.next()) { categoryId = rs.getInt("id"); } String insertSql; insertSql = "INSERT INTO products (code, alternateItemCode, manufacturer, manufacturerCode, manufacturerBarcode, mohBarcode, gtin, " + "type, primaryName, fullName, genericName, alternateName, description, strength, formId, dosageUnitId, dispensingUnit, " + "dosesPerDispensingUnit, packSize, alternatePackSize, storeRefrigerated, storeRoomTemperature, hazardous, flammable, " + "controlledSubstance, lightSensitive, approvedByWho, contraceptiveCyp, packLength, packWidth, packHeight, packWeight, " + "packsPerCarton, cartonLength, cartonWidth, cartonHeight, cartonsPerPallet, expectedShelfLife, specialStorageInstructions, " + "specialTransportInstructions, active, fullSupply, tracer, packRoundingThreshold, roundToZero, archived, displayOrder, categoryId) " + "values"; for (int i = 0; i < numberOfProductsOfEachType; i++) { if (defaultDisplayOrder) { insertSql = insertSql + "('" + productCodeFullSupply + i + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, 1, " + categoryId + "),\n"; insertSql = insertSql + "('" + productCodeNonFullSupply + i + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, FALSE, TRUE, 1, FALSE, TRUE, 1, " + categoryId + "),\n"; } else { insertSql = insertSql + "('" + productCodeFullSupply + i + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, " + i + ", " + categoryId + "),\n"; insertSql = insertSql + "('" + productCodeNonFullSupply + i + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, FALSE, TRUE, 1, FALSE, TRUE, " + i + ", " + categoryId + "),\n"; } } insertSql = insertSql.substring(0, insertSql.length() - 2) + ";\n"; update(insertSql); insertSql = "INSERT INTO program_products(programId, productId, dosesPerMonth, currentPrice, active) VALUES\n"; for (int i = 0; i < numberOfProductsOfEachType; i++) { insertSql = insertSql + "((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + productCodeFullSupply + i + "'), 30, 12.5, true),\n"; insertSql = insertSql + "((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + productCodeNonFullSupply + i + "'), 30, 12.5, true),\n"; } insertSql = insertSql.substring(0, insertSql.length() - 2) + ";"; update(insertSql); insertSql = "INSERT INTO facility_approved_products(facilityTypeId, programProductId, maxMonthsOfStock) VALUES\n"; for (int i = 0; i < numberOfProductsOfEachType; i++) { insertSql = insertSql + "((select id from facility_types where name='" + facilityType + "'), (SELECT id FROM program_products WHERE programId=(SELECT ID from programs where code='" + program + "') AND productId=(SELECT id FROM products WHERE code='" + productCodeFullSupply + i + "')), 3),\n"; insertSql = insertSql + "((select id from facility_types where name='" + facilityType + "'), (SELECT id FROM program_products WHERE programId=(SELECT ID from programs where code='" + program + "') AND productId=(SELECT id FROM products WHERE code='" + productCodeNonFullSupply + i + "')), 3),\n"; } insertSql = insertSql.substring(0, insertSql.length() - 2) + ";"; update(insertSql); } public void setupMultipleCategoryProducts(String program, String facilityType, int numberOfCategories, boolean defaultDisplayOrder) throws SQLException { update("delete from facility_approved_products;"); update("delete from program_products;"); update("delete from products;"); update("delete from product_categories;"); String productCodeFullSupply = "F"; String productCodeNonFullSupply = "NF"; String insertSql = "INSERT INTO product_categories (code, name, displayOrder) values\n"; for (int i = 0; i < numberOfCategories; i++) { if (defaultDisplayOrder) { insertSql = insertSql + "('C" + i + "', 'Antibiotics" + i + "',1),\n"; } else { insertSql = insertSql + "('C" + i + "', 'Antibiotics" + i + "'," + i + "),\n"; } } insertSql = insertSql.substring(0, insertSql.length() - 2) + ";"; update(insertSql); insertSql = "INSERT INTO products (code, alternateItemCode, manufacturer, manufacturerCode, manufacturerBarcode, mohBarcode, gtin, type, primaryName, fullName, genericName, alternateName, description, strength, formId, dosageUnitId, dispensingUnit, dosesPerDispensingUnit, packSize, alternatePackSize, storeRefrigerated, storeRoomTemperature, hazardous, flammable, controlledSubstance, lightSensitive, approvedByWho, contraceptiveCyp, packLength, packWidth, packHeight, packWeight, packsPerCarton, cartonLength, cartonWidth, cartonHeight, cartonsPerPallet, expectedShelfLife, specialStorageInstructions, specialTransportInstructions, active, fullSupply, tracer, packRoundingThreshold, roundToZero, archived, displayOrder, categoryId) values\n"; for (int i = 0; i < 11; i++) { insertSql = insertSql + "('" + productCodeFullSupply + i + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, 1, (select id from product_categories where code='C" + i + "')),\n"; insertSql = insertSql + "('" + productCodeNonFullSupply + i + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, FALSE, TRUE, 1, FALSE, TRUE, 1, (select id from product_categories where code='C" + i + "')),\n"; } insertSql = insertSql.substring(0, insertSql.length() - 2) + ";\n"; update(insertSql); insertSql = "INSERT INTO program_products(programId, productId, dosesPerMonth, currentPrice, active) VALUES\n"; for (int i = 0; i < 11; i++) { insertSql = insertSql + "((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + productCodeFullSupply + i + "'), 30, 12.5, true),\n"; insertSql = insertSql + "((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + productCodeNonFullSupply + i + "'), 30, 12.5, true),\n"; } insertSql = insertSql.substring(0, insertSql.length() - 2) + ";"; update(insertSql); insertSql = "INSERT INTO facility_approved_products(facilityTypeId, programProductId, maxMonthsOfStock) VALUES\n"; for (int i = 0; i < 11; i++) { insertSql = insertSql + "((select id from facility_types where name='" + facilityType + "'), (SELECT id FROM program_products WHERE programId=(SELECT ID from programs where code='" + program + "') AND productId=(SELECT id FROM products WHERE code='" + productCodeFullSupply + i + "')), 3),\n"; insertSql = insertSql + "((select id from facility_types where name='" + facilityType + "'), (SELECT id FROM program_products WHERE programId=(SELECT ID from programs where code='" + program + "') AND productId=(SELECT id FROM products WHERE code='" + productCodeNonFullSupply + i + "')), 3),\n"; } insertSql = insertSql.substring(0, insertSql.length() - 2) + ";"; update(insertSql); } public void assignRight(String roleName, String roleRight) throws SQLException { update("INSERT INTO role_rights (roleId, rightName) VALUES" + " ((select id from roles where name='" + roleName + "'), '" + roleRight + "');"); } public void updatePacksToShip(String packsToShip) throws SQLException { update("update requisition_line_items set packsToShip='" + packsToShip + "';"); } public void insertPastPeriodRequisitionAndLineItems(String facilityCode, String program, String periodName, String product) throws SQLException { deleteRnrData(); update("INSERT INTO requisitions " + "(facilityId, programId, periodId, status) VALUES " + "((SELECT id FROM facilities WHERE code = '" + facilityCode + "'), (SELECT ID from programs where code='" + program + "'), (select id from processing_periods where name='" + periodName + "'), 'RELEASED');"); update("INSERT INTO requisition_line_items " + "(rnrId, productCode, beginningBalance, quantityReceived, quantityDispensed, stockInHand, normalizedConsumption, " + "dispensingUnit, maxMonthsOfStock, dosesPerMonth, dosesPerDispensingUnit, packSize,fullSupply) VALUES" + "((SELECT id FROM requisitions), '" + product + "', '0', '11' , '1', '10', '1' ,'Strip','0', '0', '0', '10','t');"); } public void insertRoleAssignmentForDistribution(String userName, String roleName, String deliveryZoneCode) throws SQLException { update("INSERT INTO role_assignments\n" + " (userId, roleId, deliveryZoneId) VALUES\n" + " ((SELECT id FROM USERS WHERE username='" + userName + "'), (SELECT id FROM roles WHERE name = '" + roleName + "'),\n" + " (SELECT id FROM delivery_zones WHERE code='" + deliveryZoneCode + "'));"); } public void deleteDeliveryZoneToFacilityMapping(String deliveryZoneName) throws SQLException { update("delete from delivery_zone_members where deliveryZoneId in (select id from delivery_zones where name='" + deliveryZoneName + "');"); } public void deleteProgramToFacilityMapping(String programCode) throws SQLException { update("delete from programs_supported where programId in (select id from programs where code='" + programCode + "');"); } public void insertDeliveryZone(String code, String name) throws SQLException { update("INSERT INTO delivery_zones ( code ,name)values\n" + "('" + code + "','" + name + "');"); } public void insertWarehouseIntoSupplyLinesTable(String facilityCodeFirst, String programFirst, String supervisoryNode, boolean exportOrders) throws SQLException { update("INSERT INTO supply_lines (supplyingFacilityId, programId, supervisoryNodeId, description, exportOrders, createdBy, modifiedBy) values " + "(" + "(select id from facilities where code = '" + facilityCodeFirst + "')," + "(select id from programs where name ='" + programFirst + "')," + "(select id from supervisory_nodes where code='" + supervisoryNode + "'),'warehouse', " + exportOrders + ", '1', '1');"); } public void insertDeliveryZoneMembers(String code, String facility) throws SQLException { update("INSERT INTO delivery_zone_members ( deliveryZoneId ,facilityId )values\n" + "((select id from delivery_zones where code ='" + code + "'),(select id from facilities where code ='" + facility + "'));"); } public void insertDeliveryZoneProgramSchedule(String code, String program, String scheduleCode) throws SQLException { update("INSERT INTO delivery_zone_program_schedules\n" + "(deliveryZoneId, programId, scheduleId ) values(\n" + "(select id from delivery_zones where code='" + code + "'),\n" + "(select id from programs where code='" + program + "'),\n" + "(select id from processing_schedules where code='" + scheduleCode + "')\n" + ");"); } public void insertProcessingPeriodForDistribution(int numberOfPeriodsRequired, String schedule) throws SQLException { for (int counter = 1; counter <= numberOfPeriodsRequired; counter++) { String startDate = "2013-01-0" + counter; String endDate = "2013-01-0" + counter; insertProcessingPeriod("Period" + counter, "PeriodDecs" + counter, startDate, endDate, 1, schedule); } } public void insertRegimenTemplateColumnsForProgram(String programName) throws SQLException { update("INSERT INTO program_regimen_columns(name, programId, label, visible, dataType) values\n" + "('code',(SELECT id FROM programs WHERE name='" + programName + "'), 'header.code',true,'regimen.reporting.dataType.text'),\n" + "('name',(SELECT id FROM programs WHERE name='" + programName + "'),'header.name',true,'regimen.reporting.dataType.text'),\n" + "('patientsOnTreatment',(SELECT id FROM programs WHERE name='" + programName + "'),'Number of patients on treatment',true,'regimen.reporting.dataType.numeric'),\n" + "('patientsToInitiateTreatment',(SELECT id FROM programs WHERE name='" + programName + "'),'Number of patients to be initiated treatment',true,'regimen.reporting.dataType.numeric'),\n" + "('patientsStoppedTreatment',(SELECT id FROM programs WHERE name='" + programName + "'),'Number of patients stopped treatment',true,'regimen.reporting.dataType.numeric'),\n" + "('remarks',(SELECT id FROM programs WHERE name='" + programName + "'),'Remarks',true,'regimen.reporting.dataType.text');"); } public void insertRegimenTemplateConfiguredForProgram(String programName, String categoryCode, String code, String name, boolean active) throws SQLException { update("update programs set regimenTemplateConfigured='true' where name='" + programName + "';"); update("INSERT INTO regimens\n" + " (programId, categoryId, code, name, active,displayOrder) VALUES\n" + " ((SELECT id FROM programs WHERE name='" + programName + "'), (SELECT id FROM regimen_categories WHERE code = '" + categoryCode + "'),\n" + " '" + code + "','" + name + "','" + active + "',1);"); } public String getAllActivePrograms() throws SQLException { String programsString = ""; ResultSet rs = query("select * from programs where active=true;"); while (rs.next()) { programsString = programsString + rs.getString("name"); } return programsString; } public void updateProgramRegimenColumns(String programName, String regimenColumnName, boolean visible) throws SQLException { update("update program_regimen_columns set visible=" + visible + " where name ='" + regimenColumnName + "'and programId=(SELECT id FROM programs WHERE name='" + programName + "');"); } public void setupOrderFileConfiguration(String filePrefix, String headerInFile) throws SQLException { update("DELETE FROM order_configuration;"); update("INSERT INTO order_configuration \n" + " (filePrefix, headerInFile) VALUES\n" + " ('" + filePrefix + "', '" + headerInFile + "');"); } public void setupShipmentFileConfiguration(String headerInFile) throws SQLException { update("DELETE FROM shipment_configuration;"); update("INSERT INTO shipment_configuration(headerInFile) VALUES('" + headerInFile + "')"); } public void setupOrderFileOpenLMISColumns(String dataFieldLabel, String includeInOrderFile, String columnLabel, int position, String Format) throws SQLException { update("UPDATE order_file_columns SET " + "includeInOrderFile='" + includeInOrderFile + "', columnLabel='" + columnLabel + "', position=" + position + ", format='" + Format + "' where dataFieldLabel='" + dataFieldLabel + "'"); } public void setupOrderFileNonOpenLMISColumns(String dataFieldLabel, String includeInOrderFile, String columnLabel, int position) throws SQLException { update("INSERT INTO order_file_columns (dataFieldLabel, includeInOrderFile, columnLabel, position, openLMISField) " + "VALUES ('" + dataFieldLabel + "','" + includeInOrderFile + "','" + columnLabel + "'," + position + ", FALSE)"); } public void updateProductToHaveGroup(String product, String productGroup) throws SQLException { update("UPDATE products set productGroupId = (SELECT id from product_groups where code = '" + productGroup + "') where code = '" + product + "'"); } public void insertOrders(String status, String username, String program) throws SQLException { ResultSet rs = query("select id from requisitions where programId=(select id from programs where code='" + program + "');"); while (rs.next()) { update("update requisitions set status='RELEASED' where id =" + rs.getString("id")); update("insert into orders(Id, status,supplyLineId, createdBy, modifiedBy) values(" + rs.getString("id") + ", '" + status + "', (select id from supply_lines where supplyingFacilityId = " + "(select facilityId from fulfillment_role_assignments where userId = " + "(select id from users where username = '" + username + "')) limit 1) ," + "(select id from users where username = '" + username + "'), (select id from users where username = '" + username + "'));"); } } public void setupUserForFulfillmentRole(String username, String roleName, String facilityCode) throws SQLException { update("insert into fulfillment_role_assignments(userId, roleId,facilityId) values((select id from users where userName = '" + username + "'),(select id from roles where name = '" + roleName + "')," + "(select id from facilities where code = '" + facilityCode + "'));"); } public Map<String, String> getFacilityVisitDetails(String facilityCode) throws SQLException { Map<String, String> facilityVisitsDetails = new HashMap<>(); try (ResultSet rs = query("SELECT observations,confirmedByName,confirmedByTitle,verifiedByName,verifiedByTitle from facility_visits" + " WHERE facilityId = (SELECT id FROM facilities WHERE code = '" + facilityCode + "');")) { while (rs.next()) { facilityVisitsDetails.put("observations", rs.getString("observations")); facilityVisitsDetails.put("confirmedByName", rs.getString("confirmedByName")); facilityVisitsDetails.put("confirmedByTitle", rs.getString("confirmedByTitle")); facilityVisitsDetails.put("verifiedByName", rs.getString("verifiedByName")); facilityVisitsDetails.put("verifiedByTitle", rs.getString("verifiedByTitle")); } return facilityVisitsDetails; } } public int getPODLineItemQuantityReceived(long orderId, String productCode) throws Exception { try (ResultSet rs1 = query("SELECT id FROM pod WHERE OrderId = %d", orderId)) { if (rs1.next()) { int podId = rs1.getInt("id"); ResultSet rs2 = query("SELECT quantityReceived FROM pod_line_items WHERE podId = %d and productCode='%s'", podId, productCode); if (rs2.next()) { return rs2.getInt("quantityReceived"); } } } return -1; } public void setExportOrdersFlagInSupplyLinesTable(boolean flag, String facilityCode) throws SQLException { update("UPDATE supply_lines SET exportOrders='" + flag + "' WHERE supplyingFacilityId=(select id from facilities where code='" + facilityCode + "');"); } public void enterValidDetailsInFacilityFtpDetailsTable(String facilityCode) throws SQLException { update( "INSERT INTO facility_ftp_details(facilityId, serverHost, serverPort, username, password, localFolderPath) VALUES" + "((SELECT id FROM facilities WHERE code = '%s' ), '192.168.34.1', 21, 'openlmis', 'openlmis', '/ftp');", facilityCode); } public List<Integer> getAllProgramsOfFacility(String facilityCode) throws SQLException { List<Integer> l1 = new ArrayList<>(); ResultSet rs = query( "SELECT programId FROM programs_supported WHERE facilityId = (SELECT id FROM facilities WHERE code ='%s')", facilityCode); while (rs.next()) { l1.add(rs.getInt(1)); } return l1; } public String getProgramFieldForProgramIdAndFacilityCode(int programId, String facilityCode, String field) throws SQLException { String res = null; ResultSet rs = query( "SELECT %s FROM programs_supported WHERE programId = %d AND facilityId = (SELECT id FROM facilities WHERE code = '%s')", field, programId, facilityCode); if (rs.next()) { res = rs.getString(1); } return res; } public Date getProgramStartDateForProgramIdAndFacilityCode(int programId, String facilityCode) throws SQLException { Date date = null; ResultSet rs = query( "SELECT startDate FROM programs_supported WHERE programId = %d AND facilityId = (SELECT id FROM facilities WHERE code ='%s')", programId, facilityCode); if (rs.next()) { date = rs.getDate(1); } return date; } public void deleteCurrentPeriod() throws SQLException { update("delete from processing_periods where endDate>=NOW()"); } public void updateProgramsSupportedByField(String field, String newValue, String facilityCode) throws SQLException { update("Update programs_supported set " + field + "='" + newValue + "' where facilityId=(Select id from facilities where code ='" + facilityCode + "');"); } public void deleteSupervisoryRoleFromRoleAssignment() throws SQLException { update("delete from role_assignments where supervisoryNodeId is not null;"); } public void deleteProductAvailableAtFacility(String productCode, String programCode, String facilityCode) throws SQLException { update("delete from facility_approved_products where facilityTypeId=(select typeId from facilities where code='" + facilityCode + "') " + "and programProductId=(select id from program_products where programId=(select id from programs where code='" + programCode + "')" + "and productId=(select id from products where code='" + productCode + "'));"); } public void updateConfigureTemplateValidationFlag(String programCode, String flag) throws SQLException { update("UPDATE program_rnr_columns set formulaValidationRequired ='" + flag + "' WHERE programId=" + "(SELECT id from programs where code='" + programCode + "');"); } public void updateConfigureTemplate(String programCode, String fieldName, String fieldValue, String visibilityFlag, String rnrColumnName) throws SQLException { update("UPDATE program_rnr_columns SET visible ='" + visibilityFlag + "', " + fieldName + "='" + fieldValue + "' WHERE programId=" + "(SELECT id from programs where code='" + programCode + "')" + "AND masterColumnId =(SELECT id from master_rnr_columns WHERE name = '" + rnrColumnName + "') ;"); } public void deleteConfigureTemplate(String program) throws SQLException { update("DELETE FROM program_rnr_columns where programId=(select id from programs where code = '" + program + "');"); } public String getRequisitionLineItemFieldValue(Long requisitionId, String field, String productCode) throws SQLException { String value = null; ResultSet rs = query("SELECT %s FROM requisition_line_items WHERE rnrId = %d AND productCode = '%s'", field, requisitionId, productCode); if (rs.next()) { value = rs.getString(field); } return value; } public void insertRoleAssignmentForSupervisoryNode(String userID, String roleName, String supervisoryNode, String programCode) throws SQLException { update(" INSERT INTO role_assignments\n" + " (userId, roleId, programId, supervisoryNodeId) VALUES \n" + " ('" + userID + "', (SELECT id FROM roles WHERE name = '" + roleName + "')," + " (SELECT id from programs WHERE code='" + programCode + "'), " + "(SELECT id from supervisory_nodes WHERE code = '" + supervisoryNode + "'));"); } public void insertRequisitionGroupProgramScheduleForProgram(String requisitionGroupCode, String programCode, String scheduleCode) throws SQLException { update("delete from requisition_group_program_schedules where programId=(select id from programs where code='" + programCode + "');"); update( "insert into requisition_group_program_schedules ( requisitionGroupId , programId , scheduleId , directDelivery ) values\n" + "((select id from requisition_groups where code='" + requisitionGroupCode + "'),(select id from programs where code='" + programCode + "')," + "(select id from processing_schedules where code='" + scheduleCode + "'),TRUE);"); } public void updateCreatedDateInRequisitionStatusChanges(String newDate, Long rnrId) throws SQLException { update("update requisition_status_changes SET createdDate= '" + newDate + "' WHERE rnrId=" + rnrId + ";"); } public void updateSupervisoryNodeForRequisitionGroup(String requisitionGroup, String supervisoryNodeCode) throws SQLException { update("update requisition_groups set supervisoryNodeId=(select id from supervisory_nodes where code='" + supervisoryNodeCode + "') where code='" + requisitionGroup + "';"); } public void deleteSupplyLine() throws SQLException { update("delete from supply_lines where description='supplying node for MALARIA'"); } public Map<String, String> getEpiUseDetails(String productGroupCode, String facilityCode) throws SQLException { return select("SELECT * FROM epi_use_line_items WHERE productGroupName = " + "(SELECT name FROM product_groups where code = '%s') AND facilityVisitId=(Select id from facility_visits where facilityId=" + "(Select id from facilities where code ='%s'));", productGroupCode, facilityCode).get(0); } public ResultSet getEpiInventoryDetails(String productCode, String facilityCode) throws SQLException { ResultSet resultSet = query("SELECT * FROM epi_inventory_line_items WHERE productCode = '%s'" + "AND facilityVisitId=(Select id from facility_visits where facilityId=" + "(Select id from facilities where code ='%s'));", productCode, facilityCode); resultSet.next(); return resultSet; } public Map<String, String> getFullCoveragesDetails(String facilityCode) throws SQLException { return select("SELECT * FROM full_coverages WHERE facilityVisitId=(Select id from facility_visits where facilityId=" + "(Select id from facilities where code ='%s'));", facilityCode).get(0); } public void insertBudgetData() throws SQLException { update("INSERT INTO budget_file_info VALUES (1,'abc.csv','f',200,'12/12/13',200,'12/12/13');"); update( "INSERT INTO budget_line_items VALUES (1,(select id from processing_periods where name='current Period'),1,'01/01/2013',200,'hjhj',200,'12/12/2013',200,'12/12/2013',(select id from facilities where code='F10'),1);"); } public void addRefrigeratorToFacility(String brand, String model, String serialNumber, String facilityCode) throws SQLException { update("INSERT INTO refrigerators(brand, model, serialNumber, facilityId, createdBy , modifiedBy) VALUES" + "('" + brand + "','" + model + "','" + serialNumber + "',(SELECT id FROM facilities WHERE code = '" + facilityCode + "'),1,1);"); } public ResultSet getRefrigeratorReadings(String refrigeratorSerialNumber, String facilityCode) throws SQLException { ResultSet resultSet = query("SELECT * FROM refrigerator_readings WHERE refrigeratorId = " + "(SELECT id FROM refrigerators WHERE serialNumber = '%s' AND facilityId = " + "(SELECT id FROM facilities WHERE code = '%s'));", refrigeratorSerialNumber, facilityCode); resultSet.next(); return resultSet; } public ResultSet getRefrigeratorProblems(Long readingId) throws SQLException { return query("SELECT * FROM refrigerator_problems WHERE readingId = %d", readingId); } public void updateProcessingPeriodByField(String field, String fieldValue, String periodName, String scheduleCode) throws SQLException { update("update processing_periods set " + field + "=" + fieldValue + " where name='" + periodName + "'" + " and scheduleId =" + "(Select id from processing_schedules where code = '" + scheduleCode + "');"); } public ResultSet getRefrigeratorsData(String refrigeratorSerialNumber, String facilityCode) throws SQLException { ResultSet resultSet = query("SELECT * FROM refrigerators WHERE serialNumber = '" + refrigeratorSerialNumber + "' AND facilityId = " + getAttributeFromTable("facilities", "id", "code", facilityCode)); resultSet.next(); return resultSet; } public String getAttributeFromTable(String tableName, String attribute, String queryColumn, String queryParam) throws SQLException { String returnValue = null; ResultSet resultSet = query("select * from %s where %s in ('%s');", tableName, queryColumn, queryParam); if (resultSet.next()) { returnValue = resultSet.getString(attribute); } return returnValue; } public String getRowsCountFromDB(String tableName) throws SQLException { String rowCount = null; ResultSet rs = query("SELECT count(*) as count from " + tableName + ""); if (rs.next()) { rowCount = rs.getString("count"); } return rowCount; } public String getCreatedDate(String tableName, String dateFormat) throws SQLException { String createdDate = null; ResultSet rs = query("SELECT to_char(createdDate, '" + dateFormat + "' ) from " + tableName); if (rs.next()) { createdDate = rs.getString(1); } return createdDate; } public Integer getRequisitionGroupId(String facilityCode) throws SQLException { return Integer.parseInt(getAttributeFromTable("requisition_group_members", "requisitionGroupId", "facilityId", getAttributeFromTable("facilities", "id", "code", facilityCode))); } public void insertOneProduct(String product) throws SQLException { update("INSERT INTO products\n" + "(code, alternateItemCode, manufacturer, manufacturerCode, manufacturerBarcode, mohBarcode, gtin, type, primaryName, fullName, genericName, alternateName, description, strength, formId, dosageUnitId, dispensingUnit, dosesPerDispensingUnit, packSize, alternatePackSize, storeRefrigerated, storeRoomTemperature, hazardous, flammable, controlledSubstance, lightSensitive, approvedByWho, contraceptiveCyp, packLength, packWidth, packHeight, packWeight, packsPerCarton, cartonLength, cartonWidth, cartonHeight, cartonsPerPallet, expectedShelfLife, specialStorageInstructions, specialTransportInstructions, active, fullSupply, tracer, packRoundingThreshold, roundToZero, archived, displayOrder, categoryId) values\n" + "('" + product + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, FALSE, TRUE, 1, FALSE, TRUE, 5, (Select id from product_categories where code='C1'));\n"); } public void deleteAllProducts() throws SQLException { update("delete from facility_approved_products;"); update("delete from program_products;"); update("delete from products;"); } public void setUpDataForChildCoverage() throws SQLException { update("INSERT INTO products\n" + "(code, alternateItemCode, manufacturer, manufacturerCode, manufacturerBarcode, mohBarcode, gtin, type, primaryName, fullName, genericName, alternateName, description, strength, formId, dosageUnitId, dispensingUnit, dosesPerDispensingUnit, packSize, alternatePackSize, storeRefrigerated, storeRoomTemperature, hazardous, flammable, controlledSubstance, lightSensitive, approvedByWho, contraceptiveCyp, packLength, packWidth, packHeight, packWeight, packsPerCarton, cartonLength, cartonWidth, cartonHeight, cartonsPerPallet, expectedShelfLife, specialStorageInstructions, specialTransportInstructions, active, fullSupply, tracer, packRoundingThreshold, roundToZero, archived, displayOrder, categoryId) values\n" + "('Measles', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'Measles', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, 1, (Select id from product_categories where code='C1')),\n" + "('BCG', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'BCG', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, FALSE, TRUE, 1, FALSE, TRUE, 5, (Select id from product_categories where code='C1')),\n" + "('polio10dose','a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'polio10dose', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, 1, (Select id from product_categories where code='C1')),\n" + "('polio20dose','a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'polio20dose', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, FALSE, TRUE, 1, FALSE, TRUE, 5, (Select id from product_categories where code='C1')),\n" + "('penta1', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'penta1', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, 1, (Select id from product_categories where code='C1')),\n" + "('penta10', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'penta10', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, FALSE, TRUE, 1, FALSE, TRUE, 5, (Select id from product_categories where code='C1'));\n"); } public void insertRegimenProductMapping() throws SQLException { update("INSERT INTO coverage_vaccination_products\n" + "(vaccination, productCode, childCoverage) values\n" + "('BCG', 'BCG', TRUE),\n" + "('Polio (Newborn)', 'polio10dose',TRUE),\n" + "('Polio 1st dose', 'polio20dose' ,TRUE),\n" + "('Polio 2nd dose', 'polio10dose' ,TRUE),\n" + "('Polio 3rd dose', 'polio20dose' ,TRUE),\n" + "('Penta 1st dose', 'penta1',TRUE),\n" + "('Penta 2nd dose', 'penta10',TRUE),\n" + "('Penta 3rd dose', 'penta1',TRUE),\n" + "('PCV10 1st dose', 'P10',TRUE),\n" + "('PCV10 2nd dose', 'P10', TRUE),\n" + "('PCV10 3rd dose', 'P10', TRUE),\n" + "('Measles', 'Measles',TRUE);\n"); } public ResultSet getChildCoverageDetails(String vaccination, String facilityCode) throws SQLException { ResultSet resultSet = query("SELECT * FROM vaccination_child_coverage_line_items WHERE vaccination = '%s'" + "AND facilityVisitId=(Select id from facility_visits where facilityId=" + "(Select id from facilities where code ='%s'));", vaccination, facilityCode); resultSet.next(); return resultSet; } public void insertRequisitionWithMultipleLineItems(int numberOfLineItems, String program, boolean withSupplyLine, String facilityCode, boolean emergency) throws SQLException { boolean flag = true; update("insert into requisitions (facilityId, programId, periodId, status, emergency, fullSupplyItemsSubmittedCost, " + "nonFullSupplyItemsSubmittedCost, supervisoryNodeId) " + "values ((Select id from facilities where code='" + facilityCode + "'),(Select id from programs where code='" + program + "')," + "(Select id from processing_periods where name='Period1'), 'APPROVED', '" + emergency + "', 50.0000, 0.0000, " + "(select id from supervisory_nodes where code='N1'))"); String insertSql = "INSERT INTO requisition_line_items (rnrId, productCode,product,productDisplayOrder,productCategory," + "productCategoryDisplayOrder, beginningBalance, quantityReceived, quantityDispensed, stockInHand, dispensingUnit, maxMonthsOfStock, " + "dosesPerMonth, dosesPerDispensingUnit, packSize, fullSupply,totalLossesAndAdjustments,newPatientCount,stockOutDays,price," + "roundToZero,packRoundingThreshold,packsToShip) VALUES"; for (int i = 0; i < numberOfLineItems; i++) { String productDisplayOrder = getAttributeFromTable("products", "displayOrder", "code", "F" + i); String categoryId = getAttributeFromTable("products", "categoryId", "code", "F" + i); String categoryCode = getAttributeFromTable("product_categories", "code", "id", categoryId); String categoryDisplayOrder = getAttributeFromTable("product_categories", "displayOrder", "id", categoryId); update(insertSql + "((SELECT max(id) FROM requisitions), 'F" + i + "','antibiotic Capsule 300/200/600 mg', %s, '%s', %s, '0', '11' , " + "'1', '10' ,'Strip','3', '30', '10', '10','t',0,0,0,12.5000,'f',1,5);", productDisplayOrder, categoryCode, categoryDisplayOrder); update(insertSql + "((SELECT max(id) FROM requisitions), 'NF" + i + "','antibiotic Capsule 300/200/600 mg', %s, '%s', %s, '0', '11' ," + " '1', '10' ,'Strip','3', '30', '10', '10','f',0,0,0,12.5000,'f',1,50);", productDisplayOrder, categoryCode, categoryDisplayOrder); } if (withSupplyLine) { ResultSet rs1 = query("select * from supply_lines where supervisoryNodeId = " + "(select id from supervisory_nodes where code = 'N1') and programId = " + "(select id from programs where code='" + program + "') and supplyingFacilityId = " + "(select id from facilities where code = 'F10')"); if (rs1.next()) { flag = false; } } if (withSupplyLine) { if (flag) { insertSupplyLines("N1", program, "F10", true); } } } public void convertRequisitionToOrder(int maxRnrID, String orderStatus, String userName) throws SQLException { update("update requisitions set status = 'RELEASED' where id = %d", maxRnrID); String supervisoryNodeId = getAttributeFromTable("supervisory_nodes", "id", "code", "N1"); Integer supplyingLineId = Integer.valueOf(getAttributeFromTable("supply_lines", "id", "supervisoryNodeId", supervisoryNodeId)); Integer userId = Integer.valueOf(getAttributeFromTable("users", "id", "username", userName)); update("INSERT INTO orders(id, status, ftpComment, supplyLineId, createdBy, modifiedBy) VALUES (%d, '%s', %s, %d, %d, %d)", maxRnrID, orderStatus, null, supplyingLineId, userId, userId); } public void deleteTable(String tableName) throws SQLException { update("delete from " + tableName); } public void updatePopulationOfFacility(String facility, String population) throws SQLException { update("update facilities set catchmentPopulation=" + population + " where code='" + facility + "';"); } }
|#000| fixing FT Requisition - added a function to insert current period with respect to current date - adding missing dbWrapper changes"
test-modules/test-core/src/main/java/org/openlmis/UiUtils/DBWrapper.java
|#000| fixing FT Requisition - added a function to insert current period with respect to current date - adding missing dbWrapper changes"
<ide><path>est-modules/test-core/src/main/java/org/openlmis/UiUtils/DBWrapper.java <ide> update("INSERT INTO processing_periods\n" + <ide> "(name, description, startDate, endDate, numberOfMonths, scheduleId, modifiedBy) VALUES\n" + <ide> "('" + periodName + "', '" + periodDesc + "', '" + periodStartDate + " 00:00:00', '" + periodEndDate + " 23:59:59', " + numberOfMonths + ", (SELECT id FROM processing_schedules WHERE code = '" + scheduleCode + "'), (SELECT id FROM users LIMIT 1));"); <add> } <add> <add> public void insertCurrentPeriod(String periodName, String periodDesc, Integer numberOfMonths, String scheduleCode) throws SQLException { <add> update("INSERT INTO processing_periods\n" + <add> "(name, description, startDate, endDate, numberOfMonths, scheduleId, modifiedBy) VALUES\n" + <add> "('" + periodName + "', '" + periodDesc + "', NOW() - interval '5' day, NOW() + interval '5' day, " + numberOfMonths + ", (SELECT id FROM processing_schedules WHERE code = '" + scheduleCode + "'), (SELECT id FROM users LIMIT 1));"); <ide> } <ide> <ide> public void configureTemplate(String program) throws SQLException {
Java
apache-2.0
51bbe2c5c47d07d0913f533e882cdf6c4d3e0efc
0
henakamaMSFT/elasticsearch,lks21c/elasticsearch,awislowski/elasticsearch,elasticdog/elasticsearch,coding0011/elasticsearch,naveenhooda2000/elasticsearch,coding0011/elasticsearch,wangtuo/elasticsearch,pozhidaevak/elasticsearch,ThiagoGarciaAlves/elasticsearch,GlenRSmith/elasticsearch,JSCooke/elasticsearch,nilabhsagar/elasticsearch,nezirus/elasticsearch,girirajsharma/elasticsearch,nilabhsagar/elasticsearch,ZTE-PaaS/elasticsearch,Stacey-Gammon/elasticsearch,fred84/elasticsearch,mikemccand/elasticsearch,pozhidaevak/elasticsearch,nknize/elasticsearch,sneivandt/elasticsearch,fernandozhu/elasticsearch,obourgain/elasticsearch,liweinan0423/elasticsearch,vroyer/elasticassandra,masaruh/elasticsearch,fernandozhu/elasticsearch,HonzaKral/elasticsearch,IanvsPoplicola/elasticsearch,jimczi/elasticsearch,bawse/elasticsearch,masaruh/elasticsearch,HonzaKral/elasticsearch,yanjunh/elasticsearch,a2lin/elasticsearch,fernandozhu/elasticsearch,Helen-Zhao/elasticsearch,mjason3/elasticsearch,ricardocerq/elasticsearch,dongjoon-hyun/elasticsearch,kalimatas/elasticsearch,shreejay/elasticsearch,LewayneNaidoo/elasticsearch,markwalkom/elasticsearch,StefanGor/elasticsearch,mortonsykes/elasticsearch,mjason3/elasticsearch,winstonewert/elasticsearch,qwerty4030/elasticsearch,ThiagoGarciaAlves/elasticsearch,lks21c/elasticsearch,StefanGor/elasticsearch,JervyShi/elasticsearch,C-Bish/elasticsearch,C-Bish/elasticsearch,glefloch/elasticsearch,fernandozhu/elasticsearch,JSCooke/elasticsearch,a2lin/elasticsearch,elasticdog/elasticsearch,artnowo/elasticsearch,gingerwizard/elasticsearch,s1monw/elasticsearch,scottsom/elasticsearch,alexshadow007/elasticsearch,naveenhooda2000/elasticsearch,LeoYao/elasticsearch,JSCooke/elasticsearch,ThiagoGarciaAlves/elasticsearch,masaruh/elasticsearch,jprante/elasticsearch,LeoYao/elasticsearch,coding0011/elasticsearch,pozhidaevak/elasticsearch,MisterAndersen/elasticsearch,strapdata/elassandra5-rc,Shepard1212/elasticsearch,henakamaMSFT/elasticsearch,Shepard1212/elasticsearch,scorpionvicky/elasticsearch,ricardocerq/elasticsearch,gmarz/elasticsearch,JackyMai/elasticsearch,nezirus/elasticsearch,masaruh/elasticsearch,brandonkearby/elasticsearch,wuranbo/elasticsearch,GlenRSmith/elasticsearch,girirajsharma/elasticsearch,winstonewert/elasticsearch,vroyer/elasticassandra,jprante/elasticsearch,girirajsharma/elasticsearch,mohit/elasticsearch,alexshadow007/elasticsearch,MaineC/elasticsearch,a2lin/elasticsearch,a2lin/elasticsearch,nknize/elasticsearch,shreejay/elasticsearch,brandonkearby/elasticsearch,kalimatas/elasticsearch,i-am-Nathan/elasticsearch,glefloch/elasticsearch,yanjunh/elasticsearch,IanvsPoplicola/elasticsearch,kalimatas/elasticsearch,C-Bish/elasticsearch,wenpos/elasticsearch,bawse/elasticsearch,fforbeck/elasticsearch,njlawton/elasticsearch,gfyoung/elasticsearch,pozhidaevak/elasticsearch,geidies/elasticsearch,wuranbo/elasticsearch,nknize/elasticsearch,glefloch/elasticsearch,uschindler/elasticsearch,geidies/elasticsearch,markwalkom/elasticsearch,robin13/elasticsearch,shreejay/elasticsearch,IanvsPoplicola/elasticsearch,markwalkom/elasticsearch,HonzaKral/elasticsearch,henakamaMSFT/elasticsearch,nilabhsagar/elasticsearch,nazarewk/elasticsearch,markwalkom/elasticsearch,Stacey-Gammon/elasticsearch,wangtuo/elasticsearch,Shepard1212/elasticsearch,MisterAndersen/elasticsearch,LeoYao/elasticsearch,fred84/elasticsearch,strapdata/elassandra,dongjoon-hyun/elasticsearch,LeoYao/elasticsearch,spiegela/elasticsearch,obourgain/elasticsearch,MaineC/elasticsearch,sneivandt/elasticsearch,scottsom/elasticsearch,spiegela/elasticsearch,coding0011/elasticsearch,ThiagoGarciaAlves/elasticsearch,qwerty4030/elasticsearch,awislowski/elasticsearch,rajanm/elasticsearch,jprante/elasticsearch,naveenhooda2000/elasticsearch,yanjunh/elasticsearch,umeshdangat/elasticsearch,LeoYao/elasticsearch,obourgain/elasticsearch,rlugojr/elasticsearch,StefanGor/elasticsearch,LewayneNaidoo/elasticsearch,geidies/elasticsearch,ZTE-PaaS/elasticsearch,girirajsharma/elasticsearch,IanvsPoplicola/elasticsearch,brandonkearby/elasticsearch,strapdata/elassandra5-rc,LeoYao/elasticsearch,nknize/elasticsearch,wenpos/elasticsearch,spiegela/elasticsearch,Stacey-Gammon/elasticsearch,wuranbo/elasticsearch,jimczi/elasticsearch,fforbeck/elasticsearch,winstonewert/elasticsearch,artnowo/elasticsearch,i-am-Nathan/elasticsearch,Helen-Zhao/elasticsearch,JackyMai/elasticsearch,robin13/elasticsearch,shreejay/elasticsearch,kalimatas/elasticsearch,jprante/elasticsearch,masaruh/elasticsearch,nezirus/elasticsearch,alexshadow007/elasticsearch,alexshadow007/elasticsearch,artnowo/elasticsearch,fred84/elasticsearch,gingerwizard/elasticsearch,wangtuo/elasticsearch,MisterAndersen/elasticsearch,markwalkom/elasticsearch,wuranbo/elasticsearch,strapdata/elassandra,Stacey-Gammon/elasticsearch,JervyShi/elasticsearch,zkidkid/elasticsearch,njlawton/elasticsearch,nilabhsagar/elasticsearch,uschindler/elasticsearch,robin13/elasticsearch,Helen-Zhao/elasticsearch,obourgain/elasticsearch,wangtuo/elasticsearch,nazarewk/elasticsearch,njlawton/elasticsearch,girirajsharma/elasticsearch,sneivandt/elasticsearch,maddin2016/elasticsearch,pozhidaevak/elasticsearch,s1monw/elasticsearch,rlugojr/elasticsearch,wangtuo/elasticsearch,coding0011/elasticsearch,mjason3/elasticsearch,JervyShi/elasticsearch,jimczi/elasticsearch,shreejay/elasticsearch,sneivandt/elasticsearch,elasticdog/elasticsearch,mikemccand/elasticsearch,gmarz/elasticsearch,Helen-Zhao/elasticsearch,yanjunh/elasticsearch,henakamaMSFT/elasticsearch,rajanm/elasticsearch,HonzaKral/elasticsearch,rlugojr/elasticsearch,Helen-Zhao/elasticsearch,vroyer/elassandra,liweinan0423/elasticsearch,maddin2016/elasticsearch,awislowski/elasticsearch,maddin2016/elasticsearch,a2lin/elasticsearch,robin13/elasticsearch,LewayneNaidoo/elasticsearch,henakamaMSFT/elasticsearch,dongjoon-hyun/elasticsearch,StefanGor/elasticsearch,zkidkid/elasticsearch,GlenRSmith/elasticsearch,girirajsharma/elasticsearch,yanjunh/elasticsearch,rlugojr/elasticsearch,rajanm/elasticsearch,rlugojr/elasticsearch,kalimatas/elasticsearch,mohit/elasticsearch,mortonsykes/elasticsearch,mortonsykes/elasticsearch,s1monw/elasticsearch,brandonkearby/elasticsearch,robin13/elasticsearch,bawse/elasticsearch,zkidkid/elasticsearch,rajanm/elasticsearch,ZTE-PaaS/elasticsearch,s1monw/elasticsearch,sneivandt/elasticsearch,gingerwizard/elasticsearch,strapdata/elassandra,gmarz/elasticsearch,bawse/elasticsearch,winstonewert/elasticsearch,rajanm/elasticsearch,vroyer/elasticassandra,uschindler/elasticsearch,wuranbo/elasticsearch,C-Bish/elasticsearch,spiegela/elasticsearch,gmarz/elasticsearch,vroyer/elassandra,ThiagoGarciaAlves/elasticsearch,gfyoung/elasticsearch,JervyShi/elasticsearch,fernandozhu/elasticsearch,zkidkid/elasticsearch,wenpos/elasticsearch,nknize/elasticsearch,JackyMai/elasticsearch,gfyoung/elasticsearch,geidies/elasticsearch,wenpos/elasticsearch,mikemccand/elasticsearch,GlenRSmith/elasticsearch,fforbeck/elasticsearch,JervyShi/elasticsearch,markwalkom/elasticsearch,fforbeck/elasticsearch,spiegela/elasticsearch,bawse/elasticsearch,lks21c/elasticsearch,scorpionvicky/elasticsearch,uschindler/elasticsearch,fred84/elasticsearch,maddin2016/elasticsearch,mohit/elasticsearch,njlawton/elasticsearch,i-am-Nathan/elasticsearch,nilabhsagar/elasticsearch,lks21c/elasticsearch,JackyMai/elasticsearch,maddin2016/elasticsearch,strapdata/elassandra5-rc,vroyer/elassandra,geidies/elasticsearch,awislowski/elasticsearch,JervyShi/elasticsearch,lks21c/elasticsearch,naveenhooda2000/elasticsearch,artnowo/elasticsearch,scorpionvicky/elasticsearch,njlawton/elasticsearch,mohit/elasticsearch,elasticdog/elasticsearch,scottsom/elasticsearch,s1monw/elasticsearch,ricardocerq/elasticsearch,gingerwizard/elasticsearch,LewayneNaidoo/elasticsearch,i-am-Nathan/elasticsearch,artnowo/elasticsearch,nezirus/elasticsearch,mjason3/elasticsearch,scottsom/elasticsearch,jimczi/elasticsearch,mikemccand/elasticsearch,MisterAndersen/elasticsearch,naveenhooda2000/elasticsearch,GlenRSmith/elasticsearch,nezirus/elasticsearch,scottsom/elasticsearch,scorpionvicky/elasticsearch,JackyMai/elasticsearch,gmarz/elasticsearch,umeshdangat/elasticsearch,MaineC/elasticsearch,strapdata/elassandra5-rc,MaineC/elasticsearch,strapdata/elassandra5-rc,LeoYao/elasticsearch,MaineC/elasticsearch,mortonsykes/elasticsearch,nazarewk/elasticsearch,awislowski/elasticsearch,qwerty4030/elasticsearch,Stacey-Gammon/elasticsearch,umeshdangat/elasticsearch,dongjoon-hyun/elasticsearch,i-am-Nathan/elasticsearch,obourgain/elasticsearch,glefloch/elasticsearch,jimczi/elasticsearch,glefloch/elasticsearch,gingerwizard/elasticsearch,jprante/elasticsearch,strapdata/elassandra,mohit/elasticsearch,MisterAndersen/elasticsearch,strapdata/elassandra,qwerty4030/elasticsearch,gingerwizard/elasticsearch,gingerwizard/elasticsearch,qwerty4030/elasticsearch,ZTE-PaaS/elasticsearch,umeshdangat/elasticsearch,ricardocerq/elasticsearch,Shepard1212/elasticsearch,wenpos/elasticsearch,elasticdog/elasticsearch,liweinan0423/elasticsearch,ThiagoGarciaAlves/elasticsearch,brandonkearby/elasticsearch,C-Bish/elasticsearch,geidies/elasticsearch,scorpionvicky/elasticsearch,mjason3/elasticsearch,mortonsykes/elasticsearch,rajanm/elasticsearch,LewayneNaidoo/elasticsearch,umeshdangat/elasticsearch,fforbeck/elasticsearch,StefanGor/elasticsearch,nazarewk/elasticsearch,IanvsPoplicola/elasticsearch,mikemccand/elasticsearch,nazarewk/elasticsearch,alexshadow007/elasticsearch,dongjoon-hyun/elasticsearch,gfyoung/elasticsearch,ZTE-PaaS/elasticsearch,ricardocerq/elasticsearch,uschindler/elasticsearch,JSCooke/elasticsearch,Shepard1212/elasticsearch,liweinan0423/elasticsearch,fred84/elasticsearch,zkidkid/elasticsearch,JSCooke/elasticsearch,winstonewert/elasticsearch,gfyoung/elasticsearch,liweinan0423/elasticsearch
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.replication; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexNotFoundException; import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.store.AlreadyClosedException; import org.apache.lucene.store.Directory; import org.apache.lucene.util.Bits; import org.apache.lucene.util.IOUtils; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.Version; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.DocWriteResponse; import org.elasticsearch.action.admin.indices.flush.FlushRequest; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.index.TransportIndexAction; import org.elasticsearch.action.support.PlainActionFuture; import org.elasticsearch.action.support.replication.ReplicationOperation; import org.elasticsearch.action.support.replication.ReplicationResponse; import org.elasticsearch.action.support.replication.TransportWriteAction; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.ShardRoutingHelper; import org.elasticsearch.cluster.routing.ShardRoutingState; import org.elasticsearch.cluster.routing.TestShardRouting; import org.elasticsearch.common.collect.Iterators; import org.elasticsearch.common.compress.CompressedXContent; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.LocalTransportAddress; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.util.BigArrays; import org.elasticsearch.env.NodeEnvironment; import org.elasticsearch.index.Index; import org.elasticsearch.index.IndexSettings; import org.elasticsearch.index.MapperTestUtils; import org.elasticsearch.index.cache.IndexCache; import org.elasticsearch.index.cache.query.DisabledQueryCache; import org.elasticsearch.index.engine.Engine; import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.index.mapper.Uid; import org.elasticsearch.index.mapper.internal.UidFieldMapper; import org.elasticsearch.index.shard.IndexEventListener; import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.index.shard.IndexShardState; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.index.shard.ShardPath; import org.elasticsearch.index.similarity.SimilarityService; import org.elasticsearch.index.store.DirectoryService; import org.elasticsearch.index.store.Store; import org.elasticsearch.indices.recovery.RecoveryFailedException; import org.elasticsearch.indices.recovery.RecoverySourceHandler; import org.elasticsearch.indices.recovery.RecoveryState; import org.elasticsearch.indices.recovery.RecoveryTarget; import org.elasticsearch.indices.recovery.RecoveryTargetService; import org.elasticsearch.indices.recovery.StartRecoveryRequest; import org.elasticsearch.test.DummyShardLock; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.junit.annotations.TestLogging; import org.elasticsearch.threadpool.TestThreadPool; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportResponse; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; public abstract class ESIndexLevelReplicationTestCase extends ESTestCase { protected ThreadPool threadPool; private final Index index = new Index("test", "uuid"); private final ShardId shardId = new ShardId(index, 0); private final Map<String, String> indexMapping = Collections.singletonMap("type", "{ \"type\": {} }"); protected static final RecoveryTargetService.RecoveryListener recoveryListener = new RecoveryTargetService.RecoveryListener() { @Override public void onRecoveryDone(RecoveryState state) { } @Override public void onRecoveryFailure(RecoveryState state, RecoveryFailedException e, boolean sendShardFailure) { fail(ExceptionsHelper.detailedMessage(e)); } }; @TestLogging("index.shard:TRACE,index.replication:TRACE,indices.recovery:TRACE") public void testIndexingDuringFileRecovery() throws Exception { try (ReplicationGroup shards = createGroup(randomInt(1))) { shards.startAll(); int docs = shards.indexDocs(randomInt(50)); shards.flush(); IndexShard replica = shards.addReplica(); final CountDownLatch recoveryBlocked = new CountDownLatch(1); final CountDownLatch releaseRecovery = new CountDownLatch(1); final Future<Void> recoveryFuture = shards.asyncRecoverReplica(replica, new BiFunction<IndexShard, DiscoveryNode, RecoveryTarget>() { @Override public RecoveryTarget apply(IndexShard indexShard, DiscoveryNode node) { return new RecoveryTarget(indexShard, node, recoveryListener, version -> {}) { @Override public void renameAllTempFiles() throws IOException { super.renameAllTempFiles(); recoveryBlocked.countDown(); try { releaseRecovery.await(); } catch (InterruptedException e) { throw new IOException("terminated by interrupt", e); } } }; } }); recoveryBlocked.await(); docs += shards.indexDocs(randomInt(20)); releaseRecovery.countDown(); recoveryFuture.get(); shards.assertAllEqual(docs); } } @Override public void setUp() throws Exception { super.setUp(); threadPool = new TestThreadPool(getClass().getName()); } @Override public void tearDown() throws Exception { super.tearDown(); ThreadPool.terminate(threadPool, 30, TimeUnit.SECONDS); } private Store createStore(IndexSettings indexSettings, ShardPath shardPath) throws IOException { final ShardId shardId = shardPath.getShardId(); final DirectoryService directoryService = new DirectoryService(shardId, indexSettings) { @Override public Directory newDirectory() throws IOException { return newFSDirectory(shardPath.resolveIndex()); } @Override public long throttleTimeInNanos() { return 0; } }; return new Store(shardId, indexSettings, directoryService, new DummyShardLock(shardId)); } protected ReplicationGroup createGroup(int replicas) throws IOException { final Path homePath = createTempDir(); Settings build = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT) .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, replicas) .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) .build(); IndexMetaData metaData = IndexMetaData.builder(index.getName()).settings(build).primaryTerm(0, 1).build(); return new ReplicationGroup(metaData, homePath); } protected DiscoveryNode getDiscoveryNode(String id) { return new DiscoveryNode(id, id, new LocalTransportAddress(id), Collections.emptyMap(), Collections.singleton(DiscoveryNode.Role.DATA), Version.CURRENT); } private IndexShard newShard(boolean primary, DiscoveryNode node, IndexMetaData indexMetaData, Path homePath) throws IOException { // add node name to settings for propper logging final Settings nodeSettings = Settings.builder().put("node.name", node.getName()).build(); final IndexSettings indexSettings = new IndexSettings(indexMetaData, nodeSettings); ShardRouting shardRouting = TestShardRouting.newShardRouting(shardId, node.getId(), primary, ShardRoutingState.INITIALIZING); final Path path = Files.createDirectories(homePath.resolve(node.getId())); final NodeEnvironment.NodePath nodePath = new NodeEnvironment.NodePath(path); ShardPath shardPath = new ShardPath(false, nodePath.resolve(shardId), nodePath.resolve(shardId), shardId); Store store = createStore(indexSettings, shardPath); IndexCache indexCache = new IndexCache(indexSettings, new DisabledQueryCache(indexSettings), null); MapperService mapperService = MapperTestUtils.newMapperService(homePath, indexSettings.getSettings()); for (Map.Entry<String, String> type : indexMapping.entrySet()) { mapperService.merge(type.getKey(), new CompressedXContent(type.getValue()), MapperService.MergeReason.MAPPING_RECOVERY, true); } SimilarityService similarityService = new SimilarityService(indexSettings, Collections.emptyMap()); final IndexEventListener indexEventListener = new IndexEventListener() { }; final Engine.Warmer warmer = searcher -> { }; return new IndexShard(shardRouting, indexSettings, shardPath, store, indexCache, mapperService, similarityService, null, null, indexEventListener, null, threadPool, BigArrays.NON_RECYCLING_INSTANCE, warmer, Collections.emptyList(), Collections.emptyList()); } protected class ReplicationGroup implements AutoCloseable, Iterable<IndexShard> { private final IndexShard primary; private final List<IndexShard> replicas; private final IndexMetaData indexMetaData; private final Path homePath; private final AtomicInteger replicaId = new AtomicInteger(); private final AtomicInteger docId = new AtomicInteger(); boolean closed = false; ReplicationGroup(final IndexMetaData indexMetaData, Path homePath) throws IOException { primary = newShard(true, getDiscoveryNode("s0"), indexMetaData, homePath); replicas = new ArrayList<>(); this.indexMetaData = indexMetaData; this.homePath = homePath; for (int i = 0; i < indexMetaData.getNumberOfReplicas(); i++) { addReplica(); } } public int indexDocs(final int numOfDoc) throws Exception { for (int doc = 0; doc < numOfDoc; doc++) { final IndexRequest indexRequest = new IndexRequest(index.getName(), "type", Integer.toString(docId.incrementAndGet())) .source("{}"); final IndexResponse response = index(indexRequest); assertEquals(DocWriteResponse.Result.CREATED, response.getResult()); } return numOfDoc; } public IndexResponse index(IndexRequest indexRequest) throws Exception { PlainActionFuture<IndexingResult> listener = new PlainActionFuture<>(); IndexingOp op = new IndexingOp(indexRequest, listener, this); op.execute(); return listener.get().finalResponse; } public synchronized void startAll() throws IOException { final DiscoveryNode pNode = getDiscoveryNode(primary.routingEntry().currentNodeId()); primary.markAsRecovering("store", new RecoveryState(primary.shardId(), true, RecoveryState.Type.STORE, pNode, pNode)); primary.recoverFromStore(); primary.updateRoutingEntry(ShardRoutingHelper.moveToStarted(primary.routingEntry())); for (IndexShard replicaShard : replicas) { recoverReplica(replicaShard, (replica, sourceNode) -> new RecoveryTarget(replica, sourceNode, recoveryListener, version -> {})); } } public synchronized IndexShard addReplica() throws IOException { final IndexShard replica = newShard(false, getDiscoveryNode("s" + replicaId.incrementAndGet()), indexMetaData, homePath); replicas.add(replica); return replica; } public void recoverReplica(IndexShard replica, BiFunction<IndexShard, DiscoveryNode, RecoveryTarget> targetSupplier) throws IOException { recoverReplica(replica, targetSupplier, true); } public void recoverReplica(IndexShard replica, BiFunction<IndexShard, DiscoveryNode, RecoveryTarget> targetSupplier, boolean markAsRecovering) throws IOException { final DiscoveryNode pNode = getPrimaryNode(); final DiscoveryNode rNode = getDiscoveryNode(replica.routingEntry().currentNodeId()); if (markAsRecovering) { replica.markAsRecovering("remote", new RecoveryState(replica.shardId(), false, RecoveryState.Type.REPLICA, pNode, rNode)); } else { assertEquals(replica.state(), IndexShardState.RECOVERING); } replica.prepareForIndexRecovery(); RecoveryTarget recoveryTarget = targetSupplier.apply(replica, pNode); StartRecoveryRequest request = new StartRecoveryRequest(replica.shardId(), pNode, rNode, getMetadataSnapshotOrEmpty(replica), RecoveryState.Type.REPLICA, 0); RecoverySourceHandler recovery = new RecoverySourceHandler(primary, recoveryTarget, request, () -> 0L, e -> () -> {}, (int) ByteSizeUnit.MB.toKB(1), logger); recovery.recoverToTarget(); recoveryTarget.markAsDone(); replica.updateRoutingEntry(ShardRoutingHelper.moveToStarted(replica.routingEntry())); } private Store.MetadataSnapshot getMetadataSnapshotOrEmpty(IndexShard replica) throws IOException { Store.MetadataSnapshot result; try { result = replica.snapshotStoreMetadata(); } catch (IndexNotFoundException e) { // OK! result = Store.MetadataSnapshot.EMPTY; } catch (IOException e) { logger.warn("failed read store, treating as empty", e); result = Store.MetadataSnapshot.EMPTY; } return result; } public synchronized DiscoveryNode getPrimaryNode() { return getDiscoveryNode(primary.routingEntry().currentNodeId()); } public Future<Void> asyncRecoverReplica(IndexShard replica, BiFunction<IndexShard, DiscoveryNode, RecoveryTarget> targetSupplier) throws IOException { FutureTask<Void> task = new FutureTask<>(() -> { recoverReplica(replica, targetSupplier); return null; }); threadPool.generic().execute(task); return task; } public synchronized void assertAllEqual(int expectedCount) throws IOException { Set<Uid> primaryIds = getShardDocUIDs(primary); assertThat(primaryIds.size(), equalTo(expectedCount)); for (IndexShard replica : replicas) { Set<Uid> replicaIds = getShardDocUIDs(replica); Set<Uid> temp = new HashSet<>(primaryIds); temp.removeAll(replicaIds); assertThat(replica.routingEntry() + " is missing docs", temp, empty()); temp = new HashSet<>(replicaIds); temp.removeAll(primaryIds); assertThat(replica.routingEntry() + " has extra docs", temp, empty()); } } private Set<Uid> getShardDocUIDs(final IndexShard shard) throws IOException { shard.refresh("get_uids"); try (Engine.Searcher searcher = shard.acquireSearcher("test")) { Set<Uid> ids = new HashSet<>(); for (LeafReaderContext leafContext : searcher.reader().leaves()) { LeafReader reader = leafContext.reader(); Bits liveDocs = reader.getLiveDocs(); for (int i = 0; i < reader.maxDoc(); i++) { if (liveDocs == null || liveDocs.get(i)) { Document uuid = reader.document(i, Collections.singleton(UidFieldMapper.NAME)); ids.add(Uid.createUid(uuid.get(UidFieldMapper.NAME))); } } } return ids; } } public synchronized void refresh(String source) { for (IndexShard shard : this) { shard.refresh(source); } } public synchronized void flush() { final FlushRequest request = new FlushRequest(); for (IndexShard shard : this) { shard.flush(request); } } public synchronized List<ShardRouting> shardRoutings() { return StreamSupport.stream(this.spliterator(), false).map(IndexShard::routingEntry).collect(Collectors.toList()); } @Override public synchronized void close() throws Exception { if (closed == false) { closed = true; for (IndexShard shard : this) { shard.close("eol", false); IOUtils.close(shard.store()); } } else { throw new AlreadyClosedException("too bad"); } } @Override public Iterator<IndexShard> iterator() { return Iterators.<IndexShard>concat(replicas.iterator(), Collections.singleton(primary).iterator()); } public IndexShard getPrimary() { return primary; } } class IndexingOp extends ReplicationOperation<IndexRequest, IndexRequest, IndexingResult> { private final ReplicationGroup replicationGroup; public IndexingOp(IndexRequest request, ActionListener<IndexingResult> listener, ReplicationGroup replicationGroup) { super(request, new PrimaryRef(replicationGroup), listener, true, new ReplicasRef(replicationGroup), () -> null, logger, "indexing"); this.replicationGroup = replicationGroup; request.process(null, true, request.index()); } @Override protected List<ShardRouting> getShards(ShardId shardId, ClusterState state) { return replicationGroup.shardRoutings(); } @Override protected String checkActiveShardCount() { return null; } } private static class PrimaryRef implements ReplicationOperation.Primary<IndexRequest, IndexRequest, IndexingResult> { final IndexShard primary; private PrimaryRef(ReplicationGroup replicationGroup) { this.primary = replicationGroup.primary; } @Override public ShardRouting routingEntry() { return primary.routingEntry(); } @Override public void failShard(String message, Exception exception) { throw new UnsupportedOperationException(); } @Override public IndexingResult perform(IndexRequest request) throws Exception { TransportWriteAction.WriteResult<IndexResponse> result = TransportIndexAction.executeIndexRequestOnPrimary(request, primary, null); request.primaryTerm(primary.getPrimaryTerm()); return new IndexingResult(request, result.getResponse()); } } private static class ReplicasRef implements ReplicationOperation.Replicas<IndexRequest> { private final ReplicationGroup replicationGroup; private ReplicasRef(ReplicationGroup replicationGroup) { this.replicationGroup = replicationGroup; } @Override public void performOn(ShardRouting replicaRouting, IndexRequest request, ActionListener<TransportResponse.Empty> listener) { try { IndexShard replica = replicationGroup.replicas.stream() .filter(s -> replicaRouting.isSameAllocation(s.routingEntry())).findFirst().get(); TransportIndexAction.executeIndexRequestOnReplica(request, replica); listener.onResponse(TransportResponse.Empty.INSTANCE); } catch (Exception t) { listener.onFailure(t); } } @Override public void failShard(ShardRouting replica, ShardRouting primary, String message, Exception exception, Runnable onSuccess, Consumer<Exception> onPrimaryDemoted, Consumer<Exception> onIgnoredFailure) { throw new UnsupportedOperationException(); } } private static class IndexingResult implements ReplicationOperation.PrimaryResult<IndexRequest> { final IndexRequest replicaRequest; final IndexResponse finalResponse; public IndexingResult(IndexRequest replicaRequest, IndexResponse finalResponse) { this.replicaRequest = replicaRequest; this.finalResponse = finalResponse; } @Override public IndexRequest replicaRequest() { return replicaRequest; } @Override public void setShardInfo(ReplicationResponse.ShardInfo shardInfo) { finalResponse.setShardInfo(shardInfo); } public void respond(ActionListener<IndexResponse> listener) { listener.onResponse(finalResponse); } } }
core/src/test/java/org/elasticsearch/index/replication/ESIndexLevelReplicationTestCase.java
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.replication; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexNotFoundException; import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.store.AlreadyClosedException; import org.apache.lucene.store.Directory; import org.apache.lucene.util.Bits; import org.apache.lucene.util.IOUtils; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.Version; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.DocWriteResponse; import org.elasticsearch.action.admin.indices.flush.FlushRequest; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.index.TransportIndexAction; import org.elasticsearch.action.support.PlainActionFuture; import org.elasticsearch.action.support.replication.ReplicationOperation; import org.elasticsearch.action.support.replication.ReplicationResponse; import org.elasticsearch.action.support.replication.TransportWriteAction; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.ShardRoutingHelper; import org.elasticsearch.cluster.routing.ShardRoutingState; import org.elasticsearch.cluster.routing.TestShardRouting; import org.elasticsearch.common.collect.Iterators; import org.elasticsearch.common.compress.CompressedXContent; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.LocalTransportAddress; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.util.BigArrays; import org.elasticsearch.env.NodeEnvironment; import org.elasticsearch.index.Index; import org.elasticsearch.index.IndexSettings; import org.elasticsearch.index.MapperTestUtils; import org.elasticsearch.index.cache.IndexCache; import org.elasticsearch.index.cache.query.DisabledQueryCache; import org.elasticsearch.index.engine.Engine; import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.index.mapper.Uid; import org.elasticsearch.index.mapper.internal.UidFieldMapper; import org.elasticsearch.index.shard.IndexEventListener; import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.index.shard.IndexShardState; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.index.shard.ShardPath; import org.elasticsearch.index.similarity.SimilarityService; import org.elasticsearch.index.store.DirectoryService; import org.elasticsearch.index.store.Store; import org.elasticsearch.indices.recovery.RecoveryFailedException; import org.elasticsearch.indices.recovery.RecoverySourceHandler; import org.elasticsearch.indices.recovery.RecoveryState; import org.elasticsearch.indices.recovery.RecoveryTarget; import org.elasticsearch.indices.recovery.RecoveryTargetService; import org.elasticsearch.indices.recovery.StartRecoveryRequest; import org.elasticsearch.test.DummyShardLock; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.junit.annotations.TestLogging; import org.elasticsearch.threadpool.TestThreadPool; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportResponse; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; public abstract class ESIndexLevelReplicationTestCase extends ESTestCase { protected ThreadPool threadPool; private final Index index = new Index("test", "uuid"); private final ShardId shardId = new ShardId(index, 0); private final Map<String, String> indexMapping = Collections.singletonMap("type", "{ \"type\": {} }"); protected static final RecoveryTargetService.RecoveryListener recoveryListener = new RecoveryTargetService.RecoveryListener() { @Override public void onRecoveryDone(RecoveryState state) { } @Override public void onRecoveryFailure(RecoveryState state, RecoveryFailedException e, boolean sendShardFailure) { fail(ExceptionsHelper.detailedMessage(e)); } }; @TestLogging("index.shard:TRACE,index.replication:TRACE,indices.recovery:TRACE") public void testIndexingDuringFileRecovery() throws Exception { try (ReplicationGroup shards = createGroup(randomInt(1))) { shards.startAll(); int docs = shards.indexDocs(randomInt(50)); shards.flush(); IndexShard replica = shards.addReplica(); final CountDownLatch recoveryBlocked = new CountDownLatch(1); final CountDownLatch releaseRecovery = new CountDownLatch(1); final Future<Void> recoveryFuture = shards.asyncRecoverReplica(replica, new BiFunction<IndexShard, DiscoveryNode, RecoveryTarget>() { @Override public RecoveryTarget apply(IndexShard indexShard, DiscoveryNode node) { return new RecoveryTarget(indexShard, node, recoveryListener, version -> {}) { @Override public void renameAllTempFiles() throws IOException { super.renameAllTempFiles(); recoveryBlocked.countDown(); try { releaseRecovery.await(); } catch (InterruptedException e) { throw new IOException("terminated by interrupt", e); } } }; } }); recoveryBlocked.await(); docs += shards.indexDocs(randomInt(20)); releaseRecovery.countDown(); recoveryFuture.get(); shards.assertAllEqual(docs); } } @Override public void setUp() throws Exception { super.setUp(); threadPool = new TestThreadPool(getClass().getName()); } @Override public void tearDown() throws Exception { super.tearDown(); ThreadPool.terminate(threadPool, 30, TimeUnit.SECONDS); } private Store createStore(IndexSettings indexSettings, ShardPath shardPath) throws IOException { final ShardId shardId = shardPath.getShardId(); final DirectoryService directoryService = new DirectoryService(shardId, indexSettings) { @Override public Directory newDirectory() throws IOException { return newFSDirectory(shardPath.resolveIndex()); } @Override public long throttleTimeInNanos() { return 0; } }; return new Store(shardId, indexSettings, directoryService, new DummyShardLock(shardId)); } protected ReplicationGroup createGroup(int replicas) throws IOException { final Path homePath = createTempDir(); Settings build = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT) .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, replicas) .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) .build(); IndexMetaData metaData = IndexMetaData.builder(index.getName()).settings(build).primaryTerm(0, 1).build(); return new ReplicationGroup(metaData, homePath); } protected DiscoveryNode getDiscoveryNode(String id) { return new DiscoveryNode(id, id, new LocalTransportAddress(id), Collections.emptyMap(), Collections.singleton(DiscoveryNode.Role.DATA), Version.CURRENT); } private IndexShard newShard(boolean primary, DiscoveryNode node, IndexMetaData indexMetaData, Path homePath) throws IOException { // add node name to settings for propper logging final Settings nodeSettings = Settings.builder().put("node.name", node.getName()).build(); final IndexSettings indexSettings = new IndexSettings(indexMetaData, nodeSettings); ShardRouting shardRouting = TestShardRouting.newShardRouting(shardId, node.getId(), primary, ShardRoutingState.INITIALIZING); final Path path = Files.createDirectories(homePath.resolve(node.getId())); final NodeEnvironment.NodePath nodePath = new NodeEnvironment.NodePath(path); ShardPath shardPath = new ShardPath(false, nodePath.resolve(shardId), nodePath.resolve(shardId), shardId); Store store = createStore(indexSettings, shardPath); IndexCache indexCache = new IndexCache(indexSettings, new DisabledQueryCache(indexSettings), null); MapperService mapperService = MapperTestUtils.newMapperService(homePath, indexSettings.getSettings()); for (Map.Entry<String, String> type : indexMapping.entrySet()) { mapperService.merge(type.getKey(), new CompressedXContent(type.getValue()), MapperService.MergeReason.MAPPING_RECOVERY, true); } SimilarityService similarityService = new SimilarityService(indexSettings, Collections.emptyMap()); final IndexEventListener indexEventListener = new IndexEventListener() { }; final Engine.Warmer warmer = searcher -> { }; return new IndexShard(shardRouting, indexSettings, shardPath, store, indexCache, mapperService, similarityService, null, null, indexEventListener, null, threadPool, BigArrays.NON_RECYCLING_INSTANCE, warmer, Collections.emptyList(), Collections.emptyList()); } protected class ReplicationGroup implements AutoCloseable, Iterable<IndexShard> { private final IndexShard primary; private final List<IndexShard> replicas; private final IndexMetaData indexMetaData; private final Path homePath; private final AtomicInteger replicaId = new AtomicInteger(); private final AtomicInteger docId = new AtomicInteger(); boolean closed = false; ReplicationGroup(final IndexMetaData indexMetaData, Path homePath) throws IOException { primary = newShard(true, getDiscoveryNode("s0"), indexMetaData, homePath); replicas = new ArrayList<>(); this.indexMetaData = indexMetaData; this.homePath = homePath; for (int i = 0; i < indexMetaData.getNumberOfReplicas(); i++) { addReplica(); } } public int indexDocs(final int numOfDoc) throws Exception { for (int doc = 0; doc < numOfDoc; doc++) { final IndexRequest indexRequest = new IndexRequest(index.getName(), "type", Integer.toString(docId.incrementAndGet())) .source("{}"); final IndexResponse response = index(indexRequest); assertEquals(DocWriteResponse.Result.CREATED, response.getResult()); } return numOfDoc; } public IndexResponse index(IndexRequest indexRequest) throws Exception { PlainActionFuture<IndexingResult> listener = new PlainActionFuture<>(); IndexingOp op = new IndexingOp(indexRequest, listener, this); op.execute(); return listener.get().finalResponse; } public synchronized void startAll() throws IOException { final DiscoveryNode pNode = getDiscoveryNode(primary.routingEntry().currentNodeId()); primary.markAsRecovering("store", new RecoveryState(primary.shardId(), true, RecoveryState.Type.STORE, pNode, pNode)); primary.recoverFromStore(); primary.updateRoutingEntry(ShardRoutingHelper.moveToStarted(primary.routingEntry())); for (IndexShard replicaShard : replicas) { recoverReplica(replicaShard, (replica, sourceNode) -> new RecoveryTarget(replica, sourceNode, recoveryListener, version -> {})); } } public synchronized IndexShard addReplica() throws IOException { final IndexShard replica = newShard(false, getDiscoveryNode("s" + replicaId.incrementAndGet()), indexMetaData, homePath); replicas.add(replica); return replica; } public void recoverReplica(IndexShard replica, BiFunction<IndexShard, DiscoveryNode, RecoveryTarget> targetSupplier) throws IOException { recoverReplica(replica, targetSupplier, true); } public void recoverReplica(IndexShard replica, BiFunction<IndexShard, DiscoveryNode, RecoveryTarget> targetSupplier, boolean markAsRecovering) throws IOException { final DiscoveryNode pNode = getPrimaryNode(); final DiscoveryNode rNode = getDiscoveryNode(replica.routingEntry().currentNodeId()); if (markAsRecovering) { replica.markAsRecovering("remote", new RecoveryState(replica.shardId(), false, RecoveryState.Type.REPLICA, pNode, rNode)); } else { assertEquals(replica.state(), IndexShardState.RECOVERING); } replica.prepareForIndexRecovery(); RecoveryTarget recoveryTarget = targetSupplier.apply(replica, pNode); StartRecoveryRequest request = new StartRecoveryRequest(replica.shardId(), pNode, rNode, getMetadataSnapshotOrEmpty(replica), RecoveryState.Type.REPLICA, 0); RecoverySourceHandler recovery = new RecoverySourceHandler(primary, recoveryTarget, request, () -> 0L, e -> () -> {}, (int) ByteSizeUnit.MB.toKB(1), logger); recovery.recoverToTarget(); recoveryTarget.markAsDone(); replica.updateRoutingEntry(ShardRoutingHelper.moveToStarted(replica.routingEntry())); } private Store.MetadataSnapshot getMetadataSnapshotOrEmpty(IndexShard replica) throws IOException { Store.MetadataSnapshot result; try { result = replica.snapshotStoreMetadata(); } catch (IndexNotFoundException e) { // OK! result = Store.MetadataSnapshot.EMPTY; } catch (IOException e) { logger.warn("{} failed read store, treating as empty", e); result = Store.MetadataSnapshot.EMPTY; } return result; } public synchronized DiscoveryNode getPrimaryNode() { return getDiscoveryNode(primary.routingEntry().currentNodeId()); } public Future<Void> asyncRecoverReplica(IndexShard replica, BiFunction<IndexShard, DiscoveryNode, RecoveryTarget> targetSupplier) throws IOException { FutureTask<Void> task = new FutureTask<>(() -> { recoverReplica(replica, targetSupplier); return null; }); threadPool.generic().execute(task); return task; } public synchronized void assertAllEqual(int expectedCount) throws IOException { Set<Uid> primaryIds = getShardDocUIDs(primary); assertThat(primaryIds.size(), equalTo(expectedCount)); for (IndexShard replica : replicas) { Set<Uid> replicaIds = getShardDocUIDs(replica); Set<Uid> temp = new HashSet<>(primaryIds); temp.removeAll(replicaIds); assertThat(replica.routingEntry() + " is missing docs", temp, empty()); temp = new HashSet<>(replicaIds); temp.removeAll(primaryIds); assertThat(replica.routingEntry() + " has extra docs", temp, empty()); } } private Set<Uid> getShardDocUIDs(final IndexShard shard) throws IOException { shard.refresh("get_uids"); try (Engine.Searcher searcher = shard.acquireSearcher("test")) { Set<Uid> ids = new HashSet<>(); for (LeafReaderContext leafContext : searcher.reader().leaves()) { LeafReader reader = leafContext.reader(); Bits liveDocs = reader.getLiveDocs(); for (int i = 0; i < reader.maxDoc(); i++) { if (liveDocs == null || liveDocs.get(i)) { Document uuid = reader.document(i, Collections.singleton(UidFieldMapper.NAME)); ids.add(Uid.createUid(uuid.get(UidFieldMapper.NAME))); } } } return ids; } } public synchronized void refresh(String source) { for (IndexShard shard : this) { shard.refresh(source); } } public synchronized void flush() { final FlushRequest request = new FlushRequest(); for (IndexShard shard : this) { shard.flush(request); } } public synchronized List<ShardRouting> shardRoutings() { return StreamSupport.stream(this.spliterator(), false).map(IndexShard::routingEntry).collect(Collectors.toList()); } @Override public synchronized void close() throws Exception { if (closed == false) { closed = true; for (IndexShard shard : this) { shard.close("eol", false); IOUtils.close(shard.store()); } } else { throw new AlreadyClosedException("too bad"); } } @Override public Iterator<IndexShard> iterator() { return Iterators.<IndexShard>concat(replicas.iterator(), Collections.singleton(primary).iterator()); } public IndexShard getPrimary() { return primary; } } class IndexingOp extends ReplicationOperation<IndexRequest, IndexRequest, IndexingResult> { private final ReplicationGroup replicationGroup; public IndexingOp(IndexRequest request, ActionListener<IndexingResult> listener, ReplicationGroup replicationGroup) { super(request, new PrimaryRef(replicationGroup), listener, true, new ReplicasRef(replicationGroup), () -> null, logger, "indexing"); this.replicationGroup = replicationGroup; request.process(null, true, request.index()); } @Override protected List<ShardRouting> getShards(ShardId shardId, ClusterState state) { return replicationGroup.shardRoutings(); } @Override protected String checkActiveShardCount() { return null; } } private static class PrimaryRef implements ReplicationOperation.Primary<IndexRequest, IndexRequest, IndexingResult> { final IndexShard primary; private PrimaryRef(ReplicationGroup replicationGroup) { this.primary = replicationGroup.primary; } @Override public ShardRouting routingEntry() { return primary.routingEntry(); } @Override public void failShard(String message, Exception exception) { throw new UnsupportedOperationException(); } @Override public IndexingResult perform(IndexRequest request) throws Exception { TransportWriteAction.WriteResult<IndexResponse> result = TransportIndexAction.executeIndexRequestOnPrimary(request, primary, null); request.primaryTerm(primary.getPrimaryTerm()); return new IndexingResult(request, result.getResponse()); } } private static class ReplicasRef implements ReplicationOperation.Replicas<IndexRequest> { private final ReplicationGroup replicationGroup; private ReplicasRef(ReplicationGroup replicationGroup) { this.replicationGroup = replicationGroup; } @Override public void performOn(ShardRouting replicaRouting, IndexRequest request, ActionListener<TransportResponse.Empty> listener) { try { IndexShard replica = replicationGroup.replicas.stream() .filter(s -> replicaRouting.isSameAllocation(s.routingEntry())).findFirst().get(); TransportIndexAction.executeIndexRequestOnReplica(request, replica); listener.onResponse(TransportResponse.Empty.INSTANCE); } catch (Exception t) { listener.onFailure(t); } } @Override public void failShard(ShardRouting replica, ShardRouting primary, String message, Exception exception, Runnable onSuccess, Consumer<Exception> onPrimaryDemoted, Consumer<Exception> onIgnoredFailure) { throw new UnsupportedOperationException(); } } private static class IndexingResult implements ReplicationOperation.PrimaryResult<IndexRequest> { final IndexRequest replicaRequest; final IndexResponse finalResponse; public IndexingResult(IndexRequest replicaRequest, IndexResponse finalResponse) { this.replicaRequest = replicaRequest; this.finalResponse = finalResponse; } @Override public IndexRequest replicaRequest() { return replicaRequest; } @Override public void setShardInfo(ReplicationResponse.ShardInfo shardInfo) { finalResponse.setShardInfo(shardInfo); } public void respond(ActionListener<IndexResponse> listener) { listener.onResponse(finalResponse); } } }
[TEST] fix log statement in ESIndexLevelReplicationTestCase
core/src/test/java/org/elasticsearch/index/replication/ESIndexLevelReplicationTestCase.java
[TEST] fix log statement in ESIndexLevelReplicationTestCase
<ide><path>ore/src/test/java/org/elasticsearch/index/replication/ESIndexLevelReplicationTestCase.java <ide> // OK! <ide> result = Store.MetadataSnapshot.EMPTY; <ide> } catch (IOException e) { <del> logger.warn("{} failed read store, treating as empty", e); <add> logger.warn("failed read store, treating as empty", e); <ide> result = Store.MetadataSnapshot.EMPTY; <ide> } <ide> return result;
Java
apache-2.0
e7bf8bf1b313a332085288e05e410760d675a6ce
0
NitorCreations/javaxdelta,NitorCreations/javaxdelta
/* * Copyright (c) 2003, 2007 s IT Solutions AT Spardat GmbH. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. * */ package at.spardat.xma.xdelta; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.file.Path; import java.nio.file.Paths; import java.util.zip.ZipException; import org.apache.commons.compress.archivers.zip.ExtraFieldUtils; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.compress.archivers.zip.ZipFile; import com.nothome.delta.GDiffPatcher; import com.nothome.delta.PatchException; /** * This class applys a zip file containing deltas created with {@link JarDelta} using * {@link com.nothome.delta.GDiffPatcher} on the files contained in the jar file. * The result of this operation is not binary equal to the original target zip file. * Timestamps of files and directories are not reconstructed. But the contents of all * files in the reconstructed target zip file are complely equal to their originals. * * @author s2877 */ public class JarPatcher { /** The patch name. */ private final String patchName; /** The source name. */ private final String sourceName; /** The buffer. */ private final byte[] buffer = new byte[8 * 1024]; /** The next. */ private String next = null; /** * Applies the differences in patch to source to create the target file. All binary difference files * are applied to their corresponding file in source using {@link com.nothome.delta.GDiffPatcher}. * All other files listed in <code>META-INF/file.list</code> are copied from patch to output. * * @param patch a zip file created by {@link JarDelta#computeDelta(String, String, ZipFile, ZipFile, ZipArchiveOutputStream)} * containing the patches to apply * @param source the original zip file, where the patches have to be applied * @param output the patched zip file to create * @param list the list * @throws IOException if an error occures reading or writing any entry in a zip file */ public void applyDelta(ZipFile patch, ZipFile source, ZipArchiveOutputStream output, BufferedReader list) throws IOException { applyDelta(patch, source, output, list, ""); patch.close(); } /** * Apply delta. * * @param patch the patch * @param source the source * @param output the output * @param list the list * @param prefix the prefix * @throws IOException Signals that an I/O exception has occurred. */ public void applyDelta(ZipFile patch, ZipFile source, ZipArchiveOutputStream output, BufferedReader list, String prefix) throws IOException { String fileName = null; try { for (fileName = (next == null ? list.readLine() : next); fileName != null; fileName = (next == null ? list.readLine() : next)) { if (next != null) next = null; if (!fileName.startsWith(prefix)) { next = fileName; return; } int crcDelim = fileName.lastIndexOf(':'); int crcStart = fileName.lastIndexOf('|'); long crc = Long.valueOf(fileName.substring(crcStart + 1, crcDelim), 16); long crcSrc = Long.valueOf(fileName.substring(crcDelim + 1), 16); fileName = fileName.substring(prefix.length(), crcStart); if ("META-INF/file.list".equalsIgnoreCase(fileName)) continue; if (fileName.contains("!")) { String[] embeds = fileName.split("\\!"); ZipArchiveEntry original = getEntry(source, embeds[0], crcSrc); File originalFile = File.createTempFile("jardelta-tmp-origin-", ".zip"); File outputFile = File.createTempFile("jardelta-tmp-output-", ".zip"); Exception thrown = null; try (FileOutputStream out = new FileOutputStream(originalFile); InputStream in = source.getInputStream(original)) { int read = 0; while (-1 < (read = in.read(buffer))) { out.write(buffer, 0, read); } out.flush(); applyDelta(patch, new ZipFile(originalFile), new ZipArchiveOutputStream(outputFile), list, prefix + embeds[0] + "!"); } catch (Exception e) { thrown = e; throw e; } finally { originalFile.delete(); try (FileInputStream in = new FileInputStream(outputFile)) { if (thrown == null) { ZipArchiveEntry outEntry = copyEntry(original); output.putArchiveEntry(outEntry); int read = 0; while (-1 < (read = in.read(buffer))) { output.write(buffer, 0, read); } output.flush(); output.closeArchiveEntry(); } } finally { outputFile.delete(); } } } else { try { ZipArchiveEntry patchEntry = getEntry(patch, prefix + fileName, crc); if (patchEntry != null) { // new Entry ZipArchiveEntry outputEntry = JarDelta.entryToNewName(patchEntry, fileName); output.putArchiveEntry(outputEntry); if (!patchEntry.isDirectory()) { try (InputStream in = patch.getInputStream(patchEntry)) { int read = 0; while (-1 < (read = in.read(buffer))) { output.write(buffer, 0, read); } } } closeEntry(output, outputEntry, crc); } else { ZipArchiveEntry sourceEntry = getEntry(source, fileName, crcSrc); if (sourceEntry == null) { throw new FileNotFoundException(fileName + " not found in " + sourceName + " or " + patchName); } if (sourceEntry.isDirectory()) { ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry); output.putArchiveEntry(outputEntry); closeEntry(output, outputEntry, crc); continue; } patchEntry = getPatchEntry(patch, prefix + fileName + ".gdiff", crc); if (patchEntry != null) { // changed Entry ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry); outputEntry.setTime(patchEntry.getTime()); output.putArchiveEntry(outputEntry); byte[] sourceBytes = new byte[(int) sourceEntry.getSize()]; try (InputStream sourceStream = source.getInputStream(sourceEntry)) { for (int erg = sourceStream.read(sourceBytes); erg < sourceBytes.length; erg += sourceStream.read(sourceBytes, erg, sourceBytes.length - erg)); } InputStream patchStream = patch.getInputStream(patchEntry); GDiffPatcher diffPatcher = new GDiffPatcher(); diffPatcher.patch(sourceBytes, patchStream, output); patchStream.close(); outputEntry.setCrc(crc); closeEntry(output, outputEntry, crc); } else { // unchanged Entry ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry); if (JarDelta.zipFilesPattern.matcher(sourceEntry.getName()).matches()) { crc = sourceEntry.getCrc(); } output.putArchiveEntry(outputEntry); try (InputStream in = source.getInputStream(sourceEntry)) { int read = 0; while (-1 < (read = in.read(buffer))) { output.write(buffer, 0, read); } } output.flush(); closeEntry(output, outputEntry, crc); } } } catch (PatchException pe) { IOException ioe = new IOException(); ioe.initCause(pe); throw ioe; } } } } catch (Exception e) { System.err.println(prefix + fileName); throw e; } finally { source.close(); output.close(); } } /** * Gets the entry. * * @param source the source * @param name the name * @param crc the crc * @return the entry */ private ZipArchiveEntry getEntry(ZipFile source, String name, long crc) { for (ZipArchiveEntry next : source.getEntries(name)) { if (next.getCrc() == crc) return next; } if (!JarDelta.zipFilesPattern.matcher(name).matches()) { return null; } else { return source.getEntry(name); } } /** * Gets the patch entry. * * @param source the source * @param name the name * @param crc the crc * @return the patch entry */ private ZipArchiveEntry getPatchEntry(ZipFile source, String name, long crc) { for (ZipArchiveEntry next : source.getEntries(name)) { long nextCrc = Long.parseLong(next.getComment()); if (nextCrc == crc) return next; } return null; } /** * Close entry. * * @param output the output * @param outEntry the out entry * @param crc the crc * @throws IOException Signals that an I/O exception has occurred. */ private void closeEntry(ZipArchiveOutputStream output, ZipArchiveEntry outEntry, long crc) throws IOException { output.flush(); output.closeArchiveEntry(); if (outEntry.getCrc() != crc) throw new IOException("CRC mismatch for " + outEntry.getName()); } /** * Instantiates a new jar patcher. * * @param patchName the patch name * @param sourceName the source name */ public JarPatcher(String patchName, String sourceName) { this.patchName = patchName; this.sourceName = sourceName; } /** * Main method to make {@link #applyDelta(ZipFile, ZipFile, ZipArchiveOutputStream, BufferedReader)} available at * the command line.<br> * usage JarPatcher source patch output * * @param args the arguments * @throws IOException Signals that an I/O exception has occurred. */ public static void main(String[] args) throws IOException { String patchName = null; String outputName = null; String sourceName = null; if (args.length == 0) { System.err.println("usage JarPatcher patch [output [source]]"); System.exit(1); } else { patchName = args[0]; if (args.length > 1) { outputName = args[1]; if (args.length > 2) { sourceName = args[2]; } } } ZipFile patch = new ZipFile(patchName); ZipArchiveEntry listEntry = patch.getEntry("META-INF/file.list"); if (listEntry == null) { System.err.println("Invalid patch - list entry 'META-INF/file.list' not found"); System.exit(2); } BufferedReader list = new BufferedReader(new InputStreamReader(patch.getInputStream(listEntry))); String next = list.readLine(); if (sourceName == null) { sourceName = next; } next = list.readLine(); if (outputName == null) { outputName = next; } int ignoreSourcePaths = Integer.parseInt(System.getProperty("patcher.ignoreSourcePathElements", "0")); int ignoreOutputPaths = Integer.parseInt(System.getProperty("patcher.ignoreOutputPathElements", "0")); Path sourcePath = Paths.get(sourceName); Path outputPath = Paths.get(outputName); if (ignoreOutputPaths >= outputPath.getNameCount()) { patch.close(); StringBuilder b = new StringBuilder().append("Not enough path elements to ignore in output (").append(ignoreOutputPaths).append(" in ").append(outputName).append(")"); throw new IOException(b.toString()); } if (ignoreSourcePaths >= sourcePath.getNameCount()) { patch.close(); StringBuilder b = new StringBuilder().append("Not enough path elements to ignore in source (").append(sourcePath).append(" in ").append(sourceName).append(")"); throw new IOException(b.toString()); } if (ignoreSourcePaths > 0) { sourcePath = sourcePath.subpath(ignoreSourcePaths, sourcePath.getNameCount()); } if (ignoreOutputPaths > 0) { outputPath = outputPath.subpath(ignoreOutputPaths, outputPath.getNameCount()); } File sourceFile = sourcePath.toFile(); File outputFile = outputPath.toFile(); if (!(outputFile.getAbsoluteFile().getParentFile().mkdirs() || outputFile.getAbsoluteFile().getParentFile().exists())) { patch.close(); throw new IOException("Failed to create " + outputFile.getAbsolutePath()); } new JarPatcher(patchName, sourceFile.getName()).applyDelta(patch, new ZipFile(sourceFile), new ZipArchiveOutputStream(new FileOutputStream(outputFile)), list); list.close(); } /** * Entry to new name. * * @param source the source * @param name the name * @return the zip archive entry * @throws ZipException the zip exception */ private ZipArchiveEntry copyEntry(ZipArchiveEntry source) throws ZipException { ZipArchiveEntry ret = new ZipArchiveEntry(source.getName()); byte[] extra = source.getExtra(); if (extra != null) { ret.setExtraFields(ExtraFieldUtils.parse(extra, true, ExtraFieldUtils.UnparseableExtraField.READ)); } else { ret.setExtra(ExtraFieldUtils.mergeLocalFileDataData(source.getExtraFields(true))); } ret.setInternalAttributes(source.getInternalAttributes()); ret.setExternalAttributes(source.getExternalAttributes()); ret.setExtraFields(source.getExtraFields(true)); return ret; } }
src/main/java/at/spardat/xma/xdelta/JarPatcher.java
/* * Copyright (c) 2003, 2007 s IT Solutions AT Spardat GmbH. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. * */ package at.spardat.xma.xdelta; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.file.Path; import java.nio.file.Paths; import java.util.zip.ZipException; import org.apache.commons.compress.archivers.zip.ExtraFieldUtils; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.compress.archivers.zip.ZipFile; import com.nothome.delta.GDiffPatcher; import com.nothome.delta.PatchException; /** * This class applys a zip file containing deltas created with {@link JarDelta} using * {@link com.nothome.delta.GDiffPatcher} on the files contained in the jar file. * The result of this operation is not binary equal to the original target zip file. * Timestamps of files and directories are not reconstructed. But the contents of all * files in the reconstructed target zip file are complely equal to their originals. * * @author s2877 */ public class JarPatcher { /** The patch name. */ private final String patchName; /** The source name. */ private final String sourceName; /** The buffer. */ private final byte[] buffer = new byte[8 * 1024]; /** The next. */ private String next = null; /** * Applies the differences in patch to source to create the target file. All binary difference files * are applied to their corresponding file in source using {@link com.nothome.delta.GDiffPatcher}. * All other files listed in <code>META-INF/file.list</code> are copied from patch to output. * * @param patch a zip file created by {@link JarDelta#computeDelta(String, String, ZipFile, ZipFile, ZipArchiveOutputStream)} * containing the patches to apply * @param source the original zip file, where the patches have to be applied * @param output the patched zip file to create * @param list the list * @throws IOException if an error occures reading or writing any entry in a zip file */ public void applyDelta(ZipFile patch, ZipFile source, ZipArchiveOutputStream output, BufferedReader list) throws IOException { applyDelta(patch, source, output, list, ""); patch.close(); } /** * Apply delta. * * @param patch the patch * @param source the source * @param output the output * @param list the list * @param prefix the prefix * @throws IOException Signals that an I/O exception has occurred. */ public void applyDelta(ZipFile patch, ZipFile source, ZipArchiveOutputStream output, BufferedReader list, String prefix) throws IOException { String fileName = null; try { for (fileName = (next == null ? list.readLine() : next); fileName != null; fileName = (next == null ? list.readLine() : next)) { if (next != null) next = null; if (!fileName.startsWith(prefix)) { next = fileName; return; } int crcDelim = fileName.lastIndexOf(':'); int crcStart = fileName.lastIndexOf('|'); long crc = Long.valueOf(fileName.substring(crcStart + 1, crcDelim), 16); long crcSrc = Long.valueOf(fileName.substring(crcDelim + 1), 16); fileName = fileName.substring(prefix.length(), crcStart); if ("META-INF/file.list".equalsIgnoreCase(fileName)) continue; if (fileName.contains("!")) { String[] embeds = fileName.split("\\!"); ZipArchiveEntry original = getEntry(source, embeds[0], crcSrc); File originalFile = File.createTempFile("jardelta-tmp-origin-", ".zip"); File outputFile = File.createTempFile("jardelta-tmp-output-", ".zip"); Exception thrown = null; try (FileOutputStream out = new FileOutputStream(originalFile); InputStream in = source.getInputStream(original)) { int read = 0; while (-1 < (read = in.read(buffer))) { out.write(buffer, 0, read); } out.flush(); applyDelta(patch, new ZipFile(originalFile), new ZipArchiveOutputStream(outputFile), list, prefix + embeds[0] + "!"); } catch (Exception e) { thrown = e; throw e; } finally { originalFile.delete(); try (FileInputStream in = new FileInputStream(outputFile)) { if (thrown == null) { ZipArchiveEntry outEntry = copyEntry(original); output.putArchiveEntry(outEntry); int read = 0; while (-1 < (read = in.read(buffer))) { output.write(buffer, 0, read); } output.flush(); output.closeArchiveEntry(); } } finally { outputFile.delete(); } } } else { try { ZipArchiveEntry patchEntry = getEntry(patch, prefix + fileName, crc); if (patchEntry != null) { // new Entry ZipArchiveEntry outputEntry = JarDelta.entryToNewName(patchEntry, fileName); output.putArchiveEntry(outputEntry); if (!patchEntry.isDirectory()) { try (InputStream in = patch.getInputStream(patchEntry)) { int read = 0; while (-1 < (read = in.read(buffer))) { output.write(buffer, 0, read); } } } closeEntry(output, outputEntry, crc); } else { ZipArchiveEntry sourceEntry = getEntry(source, fileName, crcSrc); if (sourceEntry == null) { throw new FileNotFoundException(fileName + " not found in " + sourceName + " or " + patchName); } if (sourceEntry.isDirectory()) { ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry); output.putArchiveEntry(outputEntry); closeEntry(output, outputEntry, crc); continue; } patchEntry = getPatchEntry(patch, prefix + fileName + ".gdiff", crc); if (patchEntry != null) { // changed Entry ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry); outputEntry.setTime(patchEntry.getTime()); output.putArchiveEntry(outputEntry); byte[] sourceBytes = new byte[(int) sourceEntry.getSize()]; try (InputStream sourceStream = source.getInputStream(sourceEntry)) { for (int erg = sourceStream.read(sourceBytes); erg < sourceBytes.length; erg += sourceStream.read(sourceBytes, erg, sourceBytes.length - erg)); } InputStream patchStream = patch.getInputStream(patchEntry); GDiffPatcher diffPatcher = new GDiffPatcher(); diffPatcher.patch(sourceBytes, patchStream, output); patchStream.close(); outputEntry.setCrc(crc); closeEntry(output, outputEntry, crc); } else { // unchanged Entry ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry); if (JarDelta.zipFilesPattern.matcher(sourceEntry.getName()).matches()) { crc = sourceEntry.getCrc(); } output.putArchiveEntry(outputEntry); try (InputStream in = source.getInputStream(sourceEntry)) { int read = 0; while (-1 < (read = in.read(buffer))) { output.write(buffer, 0, read); } } output.flush(); closeEntry(output, outputEntry, crc); } } } catch (PatchException pe) { IOException ioe = new IOException(); ioe.initCause(pe); throw ioe; } } } } catch (Exception e) { System.err.println(prefix + fileName); throw e; } finally { source.close(); output.close(); } } /** * Gets the entry. * * @param source the source * @param name the name * @param crc the crc * @return the entry */ private ZipArchiveEntry getEntry(ZipFile source, String name, long crc) { for (ZipArchiveEntry next : source.getEntries(name)) { if (next.getCrc() == crc) return next; } if (!JarDelta.zipFilesPattern.matcher(name).matches()) { return null; } else { return source.getEntry(name); } } /** * Gets the patch entry. * * @param source the source * @param name the name * @param crc the crc * @return the patch entry */ private ZipArchiveEntry getPatchEntry(ZipFile source, String name, long crc) { for (ZipArchiveEntry next : source.getEntries(name)) { long nextCrc = Long.parseLong(next.getComment()); if (nextCrc == crc) return next; } return null; } /** * Close entry. * * @param output the output * @param outEntry the out entry * @param crc the crc * @throws IOException Signals that an I/O exception has occurred. */ private void closeEntry(ZipArchiveOutputStream output, ZipArchiveEntry outEntry, long crc) throws IOException { output.flush(); output.closeArchiveEntry(); if (outEntry.getCrc() != crc) throw new IOException("CRC mismatch for " + outEntry.getName()); } /** * Instantiates a new jar patcher. * * @param patchName the patch name * @param sourceName the source name */ public JarPatcher(String patchName, String sourceName) { this.patchName = patchName; this.sourceName = sourceName; } /** * Main method to make {@link #applyDelta(ZipFile, ZipFile, ZipArchiveOutputStream, BufferedReader)} available at * the command line.<br> * usage JarPatcher source patch output * * @param args the arguments * @throws IOException Signals that an I/O exception has occurred. */ public static void main(String[] args) throws IOException { String patchName = null; String outputName = null; String sourceName = null; if (args.length == 0) { System.err.println("usage JarPatcher patch [output [source]]"); System.exit(1); } else { patchName = args[0]; if (args.length > 1) { outputName = args[1]; if (args.length > 2) { sourceName = args[2]; } } } ZipFile patch = new ZipFile(patchName); ZipArchiveEntry listEntry = patch.getEntry("META-INF/file.list"); if (listEntry == null) { System.err.println("Invalid patch - list entry 'META-INF/file.list' not found"); System.exit(2); } BufferedReader list = new BufferedReader(new InputStreamReader(patch.getInputStream(listEntry))); String next = list.readLine(); if (sourceName == null) { sourceName = next; } next = list.readLine(); if (outputName == null) { outputName = next; } int ignoreSourcePaths = Integer.parseInt(System.getProperty("patcher.ignoreSourcePathElements", "0")); int ignoreOutputPaths = Integer.parseInt(System.getProperty("patcher.ignoreOutputPathElements", "0")); Path sourcePath = Paths.get(sourceName); Path outputPath = Paths.get(outputName); if (ignoreOutputPaths >= outputPath.getNameCount()) { patch.close(); StringBuilder b = new StringBuilder().append("Not enough path elements to ignore in output (").append(ignoreOutputPaths).append(" in ").append(outputName).append(")"); throw new IOException(b.toString()); } if (ignoreSourcePaths >= sourcePath.getNameCount()) { patch.close(); StringBuilder b = new StringBuilder().append("Not enough path elements to ignore in source (").append(sourcePath).append(" in ").append(sourceName).append(")"); throw new IOException(b.toString()); } sourcePath = sourcePath.subpath(ignoreSourcePaths, sourcePath.getNameCount()); outputPath = outputPath.subpath(ignoreOutputPaths, outputPath.getNameCount()); File sourceFile = sourcePath.toFile(); File outputFile = outputPath.toFile(); if (!(outputFile.getAbsoluteFile().getParentFile().mkdirs() || outputFile.getAbsoluteFile().getParentFile().exists())) { patch.close(); throw new IOException("Failed to create " + outputFile.getAbsolutePath()); } new JarPatcher(patchName, sourceFile.getName()).applyDelta(patch, new ZipFile(sourceFile), new ZipArchiveOutputStream(new FileOutputStream(outputFile)), list); list.close(); } /** * Entry to new name. * * @param source the source * @param name the name * @return the zip archive entry * @throws ZipException the zip exception */ private ZipArchiveEntry copyEntry(ZipArchiveEntry source) throws ZipException { ZipArchiveEntry ret = new ZipArchiveEntry(source.getName()); byte[] extra = source.getExtra(); if (extra != null) { ret.setExtraFields(ExtraFieldUtils.parse(extra, true, ExtraFieldUtils.UnparseableExtraField.READ)); } else { ret.setExtra(ExtraFieldUtils.mergeLocalFileDataData(source.getExtraFields(true))); } ret.setInternalAttributes(source.getInternalAttributes()); ret.setExternalAttributes(source.getExternalAttributes()); ret.setExtraFields(source.getExtraFields(true)); return ret; } }
Fix case where given absolute paths and no path elements are ignored
src/main/java/at/spardat/xma/xdelta/JarPatcher.java
Fix case where given absolute paths and no path elements are ignored
<ide><path>rc/main/java/at/spardat/xma/xdelta/JarPatcher.java <ide> StringBuilder b = new StringBuilder().append("Not enough path elements to ignore in source (").append(sourcePath).append(" in ").append(sourceName).append(")"); <ide> throw new IOException(b.toString()); <ide> } <del> sourcePath = sourcePath.subpath(ignoreSourcePaths, sourcePath.getNameCount()); <del> outputPath = outputPath.subpath(ignoreOutputPaths, outputPath.getNameCount()); <add> if (ignoreSourcePaths > 0) { <add> sourcePath = sourcePath.subpath(ignoreSourcePaths, sourcePath.getNameCount()); <add> } <add> if (ignoreOutputPaths > 0) { <add> outputPath = outputPath.subpath(ignoreOutputPaths, outputPath.getNameCount()); <add> } <ide> File sourceFile = sourcePath.toFile(); <ide> File outputFile = outputPath.toFile(); <ide> if (!(outputFile.getAbsoluteFile().getParentFile().mkdirs() || outputFile.getAbsoluteFile().getParentFile().exists())) {
Java
apache-2.0
39796e664e523f0f55d445b807ddbd35d4c50130
0
lirui-apache/hive,jcamachor/hive,lirui-apache/hive,jcamachor/hive,lirui-apache/hive,vineetgarg02/hive,alanfgates/hive,jcamachor/hive,alanfgates/hive,vineetgarg02/hive,anishek/hive,b-slim/hive,lirui-apache/hive,sankarh/hive,b-slim/hive,anishek/hive,sankarh/hive,nishantmonu51/hive,lirui-apache/hive,lirui-apache/hive,vergilchiu/hive,b-slim/hive,jcamachor/hive,b-slim/hive,b-slim/hive,sankarh/hive,alanfgates/hive,nishantmonu51/hive,anishek/hive,lirui-apache/hive,vergilchiu/hive,lirui-apache/hive,alanfgates/hive,sankarh/hive,alanfgates/hive,vergilchiu/hive,jcamachor/hive,alanfgates/hive,anishek/hive,alanfgates/hive,jcamachor/hive,vineetgarg02/hive,sankarh/hive,vineetgarg02/hive,nishantmonu51/hive,nishantmonu51/hive,jcamachor/hive,alanfgates/hive,b-slim/hive,b-slim/hive,anishek/hive,anishek/hive,vineetgarg02/hive,sankarh/hive,nishantmonu51/hive,nishantmonu51/hive,vineetgarg02/hive,vineetgarg02/hive,nishantmonu51/hive,vergilchiu/hive,vineetgarg02/hive,sankarh/hive,vergilchiu/hive,anishek/hive,alanfgates/hive,jcamachor/hive,lirui-apache/hive,anishek/hive,nishantmonu51/hive,anishek/hive,jcamachor/hive,vergilchiu/hive,nishantmonu51/hive,vergilchiu/hive,vergilchiu/hive,b-slim/hive,vergilchiu/hive,vineetgarg02/hive,b-slim/hive,sankarh/hive,sankarh/hive
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.exec; import java.io.Serializable; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; import org.apache.hadoop.hive.common.StatsSetupConst; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.conf.HiveConf.ConfVars; import org.apache.hadoop.hive.metastore.api.InvalidOperationException; import org.apache.hadoop.hive.ql.DriverContext; import org.apache.hadoop.hive.ql.QueryPlan; import org.apache.hadoop.hive.ql.io.StatsProvidingRecordReader; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.metadata.Partition; import org.apache.hadoop.hive.ql.metadata.Table; import org.apache.hadoop.hive.ql.parse.BaseSemanticAnalyzer.tableSpec; import org.apache.hadoop.hive.ql.plan.StatsNoJobWork; import org.apache.hadoop.hive.ql.plan.api.StageType; import org.apache.hadoop.hive.shims.ShimLoader; import org.apache.hadoop.mapred.FileSplit; import org.apache.hadoop.mapred.InputFormat; import org.apache.hadoop.mapred.InputSplit; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.util.ReflectionUtils; import org.apache.hadoop.util.StringUtils; import com.google.common.collect.Lists; import com.google.common.collect.MapMaker; import com.google.common.util.concurrent.ThreadFactoryBuilder; /** * StatsNoJobTask is used in cases where stats collection is the only task for the given query (no * parent MR or Tez job). It is used in the following cases 1) ANALYZE with partialscan/noscan for * file formats that implement StatsProvidingRecordReader interface: ORC format (implements * StatsProvidingRecordReader) stores column statistics for all columns in the file footer. Its much * faster to compute the table/partition statistics by reading the footer than scanning all the * rows. This task can be used for computing basic stats like numFiles, numRows, fileSize, * rawDataSize from ORC footer. **/ public class StatsNoJobTask extends Task<StatsNoJobWork> implements Serializable { private static final long serialVersionUID = 1L; private static transient final Log LOG = LogFactory.getLog(StatsNoJobTask.class); private static ConcurrentMap<String, Partition> partUpdates; private static Table table; private static String tableFullName; private static JobConf jc = null; public StatsNoJobTask() { super(); } @Override public void initialize(HiveConf conf, QueryPlan queryPlan, DriverContext driverContext) { super.initialize(conf, queryPlan, driverContext); jc = new JobConf(conf); } @Override public int execute(DriverContext driverContext) { LOG.info("Executing stats (no job) task"); String tableName = ""; ExecutorService threadPool = null; try { tableName = work.getTableSpecs().tableName; table = db.getTable(tableName); int numThreads = HiveConf.getIntVar(conf, ConfVars.HIVE_STATS_GATHER_NUM_THREADS); tableFullName = table.getDbName() + "." + table.getTableName(); threadPool = Executors.newFixedThreadPool(numThreads, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("StatsNoJobTask-Thread-%d") .build()); partUpdates = new MapMaker().concurrencyLevel(numThreads).makeMap(); LOG.info("Initialized threadpool for stats computation with " + numThreads + " threads"); } catch (HiveException e) { LOG.error("Cannot get table " + tableName, e); console.printError("Cannot get table " + tableName, e.toString()); } return aggregateStats(threadPool); } @Override public StageType getType() { return StageType.STATS; } @Override public String getName() { return "STATS-NO-JOB"; } class StatsCollection implements Runnable { private Partition partn; public StatsCollection(Partition part) { this.partn = part; } @Override public void run() { // get the list of partitions org.apache.hadoop.hive.metastore.api.Partition tPart = partn.getTPartition(); Map<String, String> parameters = tPart.getParameters(); try { Path dir = new Path(tPart.getSd().getLocation()); long numRows = 0; long rawDataSize = 0; long fileSize = 0; long numFiles = 0; FileSystem fs = dir.getFileSystem(conf); List<FileStatus> fileList = ShimLoader.getHadoopShims().listLocatedStatus(fs, dir, hiddenFileFilter); boolean statsAvailable = false; for(FileStatus file: fileList) { if (!file.isDir()) { InputFormat<?, ?> inputFormat = (InputFormat<?, ?>) ReflectionUtils.newInstance( partn.getInputFormatClass(), jc); InputSplit dummySplit = new FileSplit(file.getPath(), 0, 0, new String[] { partn.getLocation() }); org.apache.hadoop.mapred.RecordReader<?, ?> recordReader = (org.apache.hadoop.mapred.RecordReader<?, ?>) inputFormat.getRecordReader(dummySplit, jc, Reporter.NULL); StatsProvidingRecordReader statsRR; if (recordReader instanceof StatsProvidingRecordReader) { statsRR = (StatsProvidingRecordReader) recordReader; rawDataSize += statsRR.getStats().getRawDataSize(); numRows += statsRR.getStats().getRowCount(); fileSize += file.getLen(); numFiles += 1; statsAvailable = true; } recordReader.close(); } } if (statsAvailable) { parameters.put(StatsSetupConst.ROW_COUNT, String.valueOf(numRows)); parameters.put(StatsSetupConst.RAW_DATA_SIZE, String.valueOf(rawDataSize)); parameters.put(StatsSetupConst.TOTAL_SIZE, String.valueOf(fileSize)); parameters.put(StatsSetupConst.NUM_FILES, String.valueOf(numFiles)); parameters.put(StatsSetupConst.STATS_GENERATED_VIA_STATS_TASK, StatsSetupConst.TRUE); partUpdates.put(tPart.getSd().getLocation(), new Partition(table, tPart)); // printout console and debug logs String threadName = Thread.currentThread().getName(); String msg = "Partition " + tableFullName + partn.getSpec() + " stats: [" + toString(parameters) + ']'; LOG.debug(threadName + ": " + msg); console.printInfo(msg); } else { String threadName = Thread.currentThread().getName(); String msg = "Partition " + tableFullName + partn.getSpec() + " does not provide stats."; LOG.debug(threadName + ": " + msg); } } catch (Exception e) { console.printInfo("[Warning] could not update stats for " + tableFullName + partn.getSpec() + ".", "Failed with exception " + e.getMessage() + "\n" + StringUtils.stringifyException(e)); // Before updating the partition params, if any partition params is null // and if statsReliable is true then updatePartition() function will fail // the task by returning 1 if (work.isStatsReliable()) { partUpdates.put(tPart.getSd().getLocation(), null); } } } private String toString(Map<String, String> parameters) { StringBuilder builder = new StringBuilder(); for (String statType : StatsSetupConst.supportedStats) { String value = parameters.get(statType); if (value != null) { if (builder.length() > 0) { builder.append(", "); } builder.append(statType).append('=').append(value); } } return builder.toString(); } } private int aggregateStats(ExecutorService threadPool) { int ret = 0; try { List<Partition> partitions = getPartitionsList(); // non-partitioned table if (partitions == null) { org.apache.hadoop.hive.metastore.api.Table tTable = table.getTTable(); Map<String, String> parameters = tTable.getParameters(); try { Path dir = new Path(tTable.getSd().getLocation()); long numRows = 0; long rawDataSize = 0; long fileSize = 0; long numFiles = 0; FileSystem fs = dir.getFileSystem(conf); List<FileStatus> fileList = ShimLoader.getHadoopShims().listLocatedStatus(fs, dir, hiddenFileFilter); boolean statsAvailable = false; for(FileStatus file: fileList) { if (!file.isDir()) { InputFormat<?, ?> inputFormat = (InputFormat<?, ?>) ReflectionUtils.newInstance( table.getInputFormatClass(), jc); InputSplit dummySplit = new FileSplit(file.getPath(), 0, 0, new String[] { table .getDataLocation().toString() }); org.apache.hadoop.mapred.RecordReader<?, ?> recordReader = (org.apache.hadoop.mapred.RecordReader<?, ?>) inputFormat .getRecordReader(dummySplit, jc, Reporter.NULL); StatsProvidingRecordReader statsRR; if (recordReader instanceof StatsProvidingRecordReader) { statsRR = (StatsProvidingRecordReader) recordReader; numRows += statsRR.getStats().getRowCount(); rawDataSize += statsRR.getStats().getRawDataSize(); fileSize += file.getLen(); numFiles += 1; statsAvailable = true; } recordReader.close(); } } if (statsAvailable) { parameters.put(StatsSetupConst.ROW_COUNT, String.valueOf(numRows)); parameters.put(StatsSetupConst.RAW_DATA_SIZE, String.valueOf(rawDataSize)); parameters.put(StatsSetupConst.TOTAL_SIZE, String.valueOf(fileSize)); parameters.put(StatsSetupConst.NUM_FILES, String.valueOf(numFiles)); parameters.put(StatsSetupConst.STATS_GENERATED_VIA_STATS_TASK, StatsSetupConst.TRUE); db.alterTable(tableFullName, new Table(tTable)); String msg = "Table " + tableFullName + " stats: [" + toString(parameters) + ']'; LOG.debug(msg); console.printInfo(msg); } else { String msg = "Table " + tableFullName + " does not provide stats."; LOG.debug(msg); } } catch (Exception e) { console.printInfo("[Warning] could not update stats for " + tableFullName + ".", "Failed with exception " + e.getMessage() + "\n" + StringUtils.stringifyException(e)); } } else { // Partitioned table for (Partition partn : partitions) { threadPool.execute(new StatsCollection(partn)); } LOG.debug("Stats collection waiting for threadpool to shutdown.."); shutdownAndAwaitTermination(threadPool); LOG.debug("Stats collection threadpool shutdown successful."); ret = updatePartitions(); } } catch (Exception e) { // Fail the query if the stats are supposed to be reliable if (work.isStatsReliable()) { ret = -1; } } // The return value of 0 indicates success, // anything else indicates failure return ret; } private int updatePartitions() throws InvalidOperationException, HiveException { if (!partUpdates.isEmpty()) { List<Partition> updatedParts = Lists.newArrayList(partUpdates.values()); if (updatedParts.contains(null) && work.isStatsReliable()) { LOG.debug("Stats requested to be reliable. Empty stats found and hence failing the task."); return -1; } else { LOG.debug("Bulk updating partitions.."); db.alterPartitions(tableFullName, Lists.newArrayList(partUpdates.values())); LOG.debug("Bulk updated " + partUpdates.values().size() + " partitions."); } } return 0; } private void shutdownAndAwaitTermination(ExecutorService threadPool) { // Disable new tasks from being submitted threadPool.shutdown(); try { // Wait a while for existing tasks to terminate if (!threadPool.awaitTermination(100, TimeUnit.SECONDS)) { // Cancel currently executing tasks threadPool.shutdownNow(); // Wait a while for tasks to respond to being cancelled if (!threadPool.awaitTermination(100, TimeUnit.SECONDS)) { LOG.debug("Stats collection thread pool did not terminate"); } } } catch (InterruptedException ie) { // Cancel again if current thread also interrupted threadPool.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } } private static final PathFilter hiddenFileFilter = new PathFilter() { public boolean accept(Path p) { String name = p.getName(); return !name.startsWith("_") && !name.startsWith("."); } }; private String toString(Map<String, String> parameters) { StringBuilder builder = new StringBuilder(); for (String statType : StatsSetupConst.supportedStats) { String value = parameters.get(statType); if (value != null) { if (builder.length() > 0) { builder.append(", "); } builder.append(statType).append('=').append(value); } } return builder.toString(); } private List<Partition> getPartitionsList() throws HiveException { if (work.getTableSpecs() != null) { tableSpec tblSpec = work.getTableSpecs(); table = tblSpec.tableHandle; if (!table.isPartitioned()) { return null; } else { return tblSpec.partitions; } } return null; } }
ql/src/java/org/apache/hadoop/hive/ql/exec/StatsNoJobTask.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.exec; import java.io.Serializable; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; import org.apache.hadoop.hive.common.StatsSetupConst; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.conf.HiveConf.ConfVars; import org.apache.hadoop.hive.metastore.api.InvalidOperationException; import org.apache.hadoop.hive.ql.DriverContext; import org.apache.hadoop.hive.ql.QueryPlan; import org.apache.hadoop.hive.ql.io.StatsProvidingRecordReader; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.metadata.Partition; import org.apache.hadoop.hive.ql.metadata.Table; import org.apache.hadoop.hive.ql.parse.BaseSemanticAnalyzer.tableSpec; import org.apache.hadoop.hive.ql.plan.StatsNoJobWork; import org.apache.hadoop.hive.ql.plan.api.StageType; import org.apache.hadoop.hive.shims.ShimLoader; import org.apache.hadoop.mapred.FileSplit; import org.apache.hadoop.mapred.InputFormat; import org.apache.hadoop.mapred.InputSplit; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.util.ReflectionUtils; import org.apache.hadoop.util.StringUtils; import com.google.common.collect.Lists; import com.google.common.collect.MapMaker; import com.google.common.util.concurrent.ThreadFactoryBuilder; /** * StatsNoJobTask is used in cases where stats collection is the only task for the given query (no * parent MR or Tez job). It is used in the following cases 1) ANALYZE with partialscan/noscan for * file formats that implement StatsProvidingRecordReader interface: ORC format (implements * StatsProvidingRecordReader) stores column statistics for all columns in the file footer. Its much * faster to compute the table/partition statistics by reading the footer than scanning all the * rows. This task can be used for computing basic stats like numFiles, numRows, fileSize, * rawDataSize from ORC footer. **/ public class StatsNoJobTask extends Task<StatsNoJobWork> implements Serializable { private static final long serialVersionUID = 1L; private static transient final Log LOG = LogFactory.getLog(StatsNoJobTask.class); private static ConcurrentMap<String, Partition> partUpdates; private static Table table; private static String tableFullName; private static JobConf jc = null; public StatsNoJobTask() { super(); } @Override public void initialize(HiveConf conf, QueryPlan queryPlan, DriverContext driverContext) { super.initialize(conf, queryPlan, driverContext); jc = new JobConf(conf); } @Override public int execute(DriverContext driverContext) { LOG.info("Executing stats (no job) task"); String tableName = ""; ExecutorService threadPool = null; try { tableName = work.getTableSpecs().tableName; table = db.getTable(tableName); int numThreads = HiveConf.getIntVar(conf, ConfVars.HIVE_STATS_GATHER_NUM_THREADS); tableFullName = table.getDbName() + "." + table.getTableName(); threadPool = Executors.newFixedThreadPool(numThreads, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("StatsNoJobTask-Thread-%d") .build()); partUpdates = new MapMaker().concurrencyLevel(numThreads).makeMap(); LOG.info("Initialized threadpool for stats computation with " + numThreads + " threads"); } catch (HiveException e) { LOG.error("Cannot get table " + tableName, e); console.printError("Cannot get table " + tableName, e.toString()); } return aggregateStats(threadPool); } @Override public StageType getType() { return StageType.STATS; } @Override public String getName() { return "STATS-NO-JOB"; } class StatsCollection implements Runnable { private Partition partn; public StatsCollection(Partition part) { this.partn = part; } @Override public void run() { // get the list of partitions org.apache.hadoop.hive.metastore.api.Partition tPart = partn.getTPartition(); Map<String, String> parameters = tPart.getParameters(); try { Path dir = new Path(tPart.getSd().getLocation()); long numRows = 0; long rawDataSize = 0; long fileSize = 0; long numFiles = 0; FileSystem fs = dir.getFileSystem(conf); List<FileStatus> fileList = ShimLoader.getHadoopShims().listLocatedStatus(fs, dir, hiddenFileFilter); boolean statsAvailable = false; for(FileStatus file: fileList) { if (!file.isDir()) { InputFormat<?, ?> inputFormat = (InputFormat<?, ?>) ReflectionUtils.newInstance( partn.getInputFormatClass(), jc); InputSplit dummySplit = new FileSplit(file.getPath(), 0, 0, new String[] { partn.getLocation() }); Object recordReader = inputFormat.getRecordReader(dummySplit, jc, Reporter.NULL); StatsProvidingRecordReader statsRR; if (recordReader instanceof StatsProvidingRecordReader) { statsRR = (StatsProvidingRecordReader) recordReader; rawDataSize += statsRR.getStats().getRawDataSize(); numRows += statsRR.getStats().getRowCount(); fileSize += file.getLen(); numFiles += 1; statsAvailable = true; } } } if (statsAvailable) { parameters.put(StatsSetupConst.ROW_COUNT, String.valueOf(numRows)); parameters.put(StatsSetupConst.RAW_DATA_SIZE, String.valueOf(rawDataSize)); parameters.put(StatsSetupConst.TOTAL_SIZE, String.valueOf(fileSize)); parameters.put(StatsSetupConst.NUM_FILES, String.valueOf(numFiles)); parameters.put(StatsSetupConst.STATS_GENERATED_VIA_STATS_TASK, StatsSetupConst.TRUE); partUpdates.put(tPart.getSd().getLocation(), new Partition(table, tPart)); // printout console and debug logs String threadName = Thread.currentThread().getName(); String msg = "Partition " + tableFullName + partn.getSpec() + " stats: [" + toString(parameters) + ']'; LOG.debug(threadName + ": " + msg); console.printInfo(msg); } else { String threadName = Thread.currentThread().getName(); String msg = "Partition " + tableFullName + partn.getSpec() + " does not provide stats."; LOG.debug(threadName + ": " + msg); } } catch (Exception e) { console.printInfo("[Warning] could not update stats for " + tableFullName + partn.getSpec() + ".", "Failed with exception " + e.getMessage() + "\n" + StringUtils.stringifyException(e)); // Before updating the partition params, if any partition params is null // and if statsReliable is true then updatePartition() function will fail // the task by returning 1 if (work.isStatsReliable()) { partUpdates.put(tPart.getSd().getLocation(), null); } } } private String toString(Map<String, String> parameters) { StringBuilder builder = new StringBuilder(); for (String statType : StatsSetupConst.supportedStats) { String value = parameters.get(statType); if (value != null) { if (builder.length() > 0) { builder.append(", "); } builder.append(statType).append('=').append(value); } } return builder.toString(); } } private int aggregateStats(ExecutorService threadPool) { int ret = 0; try { List<Partition> partitions = getPartitionsList(); // non-partitioned table if (partitions == null) { org.apache.hadoop.hive.metastore.api.Table tTable = table.getTTable(); Map<String, String> parameters = tTable.getParameters(); try { Path dir = new Path(tTable.getSd().getLocation()); long numRows = 0; long rawDataSize = 0; long fileSize = 0; long numFiles = 0; FileSystem fs = dir.getFileSystem(conf); List<FileStatus> fileList = ShimLoader.getHadoopShims().listLocatedStatus(fs, dir, hiddenFileFilter); boolean statsAvailable = false; for(FileStatus file: fileList) { if (!file.isDir()) { InputFormat<?, ?> inputFormat = (InputFormat<?, ?>) ReflectionUtils.newInstance( table.getInputFormatClass(), jc); InputSplit dummySplit = new FileSplit(file.getPath(), 0, 0, new String[] { table .getDataLocation().toString() }); org.apache.hadoop.mapred.RecordReader<?, ?> recordReader = (org.apache.hadoop.mapred.RecordReader<?, ?>) inputFormat .getRecordReader(dummySplit, jc, Reporter.NULL); StatsProvidingRecordReader statsRR; if (recordReader instanceof StatsProvidingRecordReader) { statsRR = (StatsProvidingRecordReader) recordReader; numRows += statsRR.getStats().getRowCount(); rawDataSize += statsRR.getStats().getRawDataSize(); fileSize += file.getLen(); numFiles += 1; statsAvailable = true; } } } if (statsAvailable) { parameters.put(StatsSetupConst.ROW_COUNT, String.valueOf(numRows)); parameters.put(StatsSetupConst.RAW_DATA_SIZE, String.valueOf(rawDataSize)); parameters.put(StatsSetupConst.TOTAL_SIZE, String.valueOf(fileSize)); parameters.put(StatsSetupConst.NUM_FILES, String.valueOf(numFiles)); parameters.put(StatsSetupConst.STATS_GENERATED_VIA_STATS_TASK, StatsSetupConst.TRUE); db.alterTable(tableFullName, new Table(tTable)); String msg = "Table " + tableFullName + " stats: [" + toString(parameters) + ']'; LOG.debug(msg); console.printInfo(msg); } else { String msg = "Table " + tableFullName + " does not provide stats."; LOG.debug(msg); } } catch (Exception e) { console.printInfo("[Warning] could not update stats for " + tableFullName + ".", "Failed with exception " + e.getMessage() + "\n" + StringUtils.stringifyException(e)); } } else { // Partitioned table for (Partition partn : partitions) { threadPool.execute(new StatsCollection(partn)); } LOG.debug("Stats collection waiting for threadpool to shutdown.."); shutdownAndAwaitTermination(threadPool); LOG.debug("Stats collection threadpool shutdown successful."); ret = updatePartitions(); } } catch (Exception e) { // Fail the query if the stats are supposed to be reliable if (work.isStatsReliable()) { ret = -1; } } // The return value of 0 indicates success, // anything else indicates failure return ret; } private int updatePartitions() throws InvalidOperationException, HiveException { if (!partUpdates.isEmpty()) { List<Partition> updatedParts = Lists.newArrayList(partUpdates.values()); if (updatedParts.contains(null) && work.isStatsReliable()) { LOG.debug("Stats requested to be reliable. Empty stats found and hence failing the task."); return -1; } else { LOG.debug("Bulk updating partitions.."); db.alterPartitions(tableFullName, Lists.newArrayList(partUpdates.values())); LOG.debug("Bulk updated " + partUpdates.values().size() + " partitions."); } } return 0; } private void shutdownAndAwaitTermination(ExecutorService threadPool) { // Disable new tasks from being submitted threadPool.shutdown(); try { // Wait a while for existing tasks to terminate if (!threadPool.awaitTermination(100, TimeUnit.SECONDS)) { // Cancel currently executing tasks threadPool.shutdownNow(); // Wait a while for tasks to respond to being cancelled if (!threadPool.awaitTermination(100, TimeUnit.SECONDS)) { LOG.debug("Stats collection thread pool did not terminate"); } } } catch (InterruptedException ie) { // Cancel again if current thread also interrupted threadPool.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } } private static final PathFilter hiddenFileFilter = new PathFilter() { public boolean accept(Path p) { String name = p.getName(); return !name.startsWith("_") && !name.startsWith("."); } }; private String toString(Map<String, String> parameters) { StringBuilder builder = new StringBuilder(); for (String statType : StatsSetupConst.supportedStats) { String value = parameters.get(statType); if (value != null) { if (builder.length() > 0) { builder.append(", "); } builder.append(statType).append('=').append(value); } } return builder.toString(); } private List<Partition> getPartitionsList() throws HiveException { if (work.getTableSpecs() != null) { tableSpec tblSpec = work.getTableSpecs(); table = tblSpec.tableHandle; if (!table.isPartitioned()) { return null; } else { return tblSpec.partitions; } } return null; } }
HIVE-8497: StatsNoJobTask doesn't close RecordReader, FSDataInputStream of which keeps open to prevent stale data clean (Xiaobing Zhou via Prasanth J) git-svn-id: c2303eb81cb646bce052f55f7f0d14f181a5956c@1633231 13f79535-47bb-0310-9956-ffa450edef68
ql/src/java/org/apache/hadoop/hive/ql/exec/StatsNoJobTask.java
HIVE-8497: StatsNoJobTask doesn't close RecordReader, FSDataInputStream of which keeps open to prevent stale data clean (Xiaobing Zhou via Prasanth J)
<ide><path>l/src/java/org/apache/hadoop/hive/ql/exec/StatsNoJobTask.java <ide> partn.getInputFormatClass(), jc); <ide> InputSplit dummySplit = new FileSplit(file.getPath(), 0, 0, <ide> new String[] { partn.getLocation() }); <del> Object recordReader = inputFormat.getRecordReader(dummySplit, jc, Reporter.NULL); <add> org.apache.hadoop.mapred.RecordReader<?, ?> recordReader = <add> (org.apache.hadoop.mapred.RecordReader<?, ?>) <add> inputFormat.getRecordReader(dummySplit, jc, Reporter.NULL); <ide> StatsProvidingRecordReader statsRR; <ide> if (recordReader instanceof StatsProvidingRecordReader) { <ide> statsRR = (StatsProvidingRecordReader) recordReader; <ide> numFiles += 1; <ide> statsAvailable = true; <ide> } <add> recordReader.close(); <ide> } <ide> } <ide> <ide> numFiles += 1; <ide> statsAvailable = true; <ide> } <add> recordReader.close(); <ide> } <ide> } <ide>
Java
agpl-3.0
16d0f7c4d426f038b6f8ca37108d59e8d1bff0a2
0
mbrossard/cryptonit-applet
package org.cryptonit; import javacard.framework.APDU; import javacard.framework.Applet; import javacard.framework.ISO7816; import javacard.framework.ISOException; import javacard.framework.JCSystem; import javacard.framework.OwnerPIN; import javacard.framework.Util; import javacard.security.CryptoException; import javacard.security.DESKey; import javacard.security.ECPublicKey; import javacard.security.RandomData; import javacard.security.Key; import javacard.security.KeyBuilder; import javacard.security.KeyPair; import javacard.security.RSAPublicKey; import javacard.security.Signature; import javacardx.apdu.ExtendedLength; import javacardx.crypto.Cipher; /** * @author Mathias Brossard */ public class CryptonitApplet extends Applet implements ExtendedLength { private final OwnerPIN pin; private final OwnerPIN mgmt_counter; private Key[] keys = null; private Key mgmt_key = null; private byte[] challenge = null; private boolean[] authenticated = null; private Cipher rsa_cipher = null; private Signature ec_signature = null; private RandomData random = null; private IOBuffer io = null; private final static byte PIN_MAX_LENGTH = 8; private final static byte PIN_MAX_TRIES = 5; private final static byte MGMT_MAX_TRIES = 3; public static final byte INS_GET_DATA = (byte) 0xCB; public static final byte INS_GET_RESPONSE = (byte) 0xC0; public static final byte INS_PUT_DATA = (byte) 0xDB; public static final byte INS_VERIFY_PIN = (byte) 0x20; public static final byte INS_GENERAL_AUTHENTICATE = (byte) 0x87; public static final byte INS_CHANGE_REFERENCE_DATA = (byte) 0x24; public static final byte INS_GENERATE_ASYMMETRIC_KEYPAIR = (byte) 0x47; public static final short SW_PIN_TRIES_REMAINING = 0x63C0; public static final short SW_AUTHENTICATION_METHOD_BLOCKED = 0x6983; protected CryptonitApplet(byte[] bArray, short bOffset, byte bLength) { mgmt_key = KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_3KEY, false); ((DESKey) mgmt_key).setKey(new byte[]{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }, (short) 0); mgmt_counter = new OwnerPIN(MGMT_MAX_TRIES, (byte) 4); mgmt_counter.update(new byte[]{0x00, 0x00, 0x00, 0x00}, (short) 0, (byte) 4); challenge = JCSystem.makeTransientByteArray((short) 8, JCSystem.CLEAR_ON_DESELECT); pin = new OwnerPIN(PIN_MAX_TRIES, PIN_MAX_LENGTH); pin.update(new byte[]{ 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 }, (short) 0, (byte) 8); keys = new Key[(byte) 4]; random = RandomData.getInstance(RandomData.ALG_SECURE_RANDOM); authenticated = JCSystem.makeTransientBooleanArray((short) 1, JCSystem.CLEAR_ON_DESELECT); rsa_cipher = Cipher.getInstance(Cipher.ALG_RSA_NOPAD, false); try { ec_signature = Signature.getInstance(Signature.ALG_ECDSA_SHA, false); } catch (Exception e) { } FileIndex index = new FileIndex(); io = new IOBuffer(index); register(); } public static void install(byte[] bArray, short bOffset, byte bLength) { new CryptonitApplet(bArray, bOffset, bLength); } @Override public void process(APDU apdu) { byte buffer[] = apdu.getBuffer(); byte ins = buffer[ISO7816.OFFSET_INS]; if (apdu.isSecureMessagingCLA()) { ISOException.throwIt(ISO7816.SW_SECURE_MESSAGING_NOT_SUPPORTED); } switch (ins) { case ISO7816.INS_SELECT: doSelect(apdu); break; case INS_VERIFY_PIN: doVerifyPin(apdu); break; case INS_CHANGE_REFERENCE_DATA: doChangePIN(apdu); break; case INS_GET_DATA: doGetData(apdu); break; case INS_GET_RESPONSE: io.getResponse(apdu); break; case INS_PUT_DATA: doPutData(apdu); break; case INS_GENERATE_ASYMMETRIC_KEYPAIR: doGenerateKeyPair(apdu); break; case INS_GENERAL_AUTHENTICATE: doGeneralAuthenticate(apdu); break; default: ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED); break; } } private void doSelect(APDU apdu) throws ISOException { byte[] buf = apdu.getBuffer(); byte p1 = buf[ISO7816.OFFSET_P1]; byte p2 = buf[ISO7816.OFFSET_P2]; final byte[] apt = { /* Application property template */ (byte) 0x61, (byte) 0x16, /* - Application identifier of application */ (byte) 0x4F, (byte) 0x0B, (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x08, (byte) 0x00, (byte) 0x00, (byte) 0x10, (byte) 0x00, (byte) 0x01, (byte) 0x00, /* - Coexistent tag allocation authority */ (byte) 0x79, (byte) 0x07, /* - Application identifier */ (byte) 0x4F, (byte) 0x05, (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x08 }; if ((p1 == (byte) 0x04) && (p2 == (byte) 0x00)) { short l = apdu.setIncomingAndReceive(); short offset = apdu.getOffsetCdata(); final byte[] aid1 = { (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x08 }; final byte[] aid2 = { (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x08, (byte) 0x00, (byte) 0x00, (byte) 0x10, (byte) 0x00 }; if (((l == (short) aid1.length) && (Util.arrayCompare(buf, offset, aid1, (byte) 0, (byte) aid1.length) == 0)) || ((l == (short) aid2.length) && (Util.arrayCompare(buf, offset, aid2, (byte) 0, (byte) aid2.length) == 0))) { io.sendBuffer(apt, (short) apt.length, apdu); return; } } ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND); } private void doVerifyPin(APDU apdu) throws ISOException { byte[] buf = apdu.getBuffer(); byte p1 = buf[ISO7816.OFFSET_P1]; byte p2 = buf[ISO7816.OFFSET_P2]; short lc = apdu.setIncomingAndReceive(); if ((p1 != (byte) 0x00 && p1 != (byte) 0xFF) || (p2 != (byte) 0x80)) { ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2); } if (p1 == (byte) 0xFF) { authenticated[0] = false; ISOException.throwIt(ISO7816.SW_NO_ERROR); } if ((lc != apdu.getIncomingLength()) || lc != (short) 8) { ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); } if (pin.getTriesRemaining() == 0) { ISOException.throwIt(SW_AUTHENTICATION_METHOD_BLOCKED); } // Check the PIN. if (!pin.check(buf, apdu.getOffsetCdata(), (byte) lc)) { // Authentication failed authenticated[0] = false; ISOException.throwIt((short) (SW_PIN_TRIES_REMAINING | pin.getTriesRemaining())); } else { // Authentication successful authenticated[0] = true; ISOException.throwIt(ISO7816.SW_NO_ERROR); } } private void doChangePIN(APDU apdu) { byte[] buf = apdu.getBuffer(); byte p1 = buf[ISO7816.OFFSET_P1]; byte p2 = buf[ISO7816.OFFSET_P2]; short off, lc = apdu.setIncomingAndReceive(); if (p1 != (byte) 0x00 || (p2 != (byte) 0x80)) { ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2); } if (pin.getTriesRemaining() == 0) { ISOException.throwIt(SW_AUTHENTICATION_METHOD_BLOCKED); } if ((lc != apdu.getIncomingLength()) || lc != (short) 16) { ISOException.throwIt((short) 0x6480); } off = apdu.getOffsetCdata(); for (short i = 0; i < (short) 16; i++) { if (((buf[(short) (i + off)] < 0x30) || (buf[(short) (i + off)] > 0x39)) && (buf[(short) (i + off)] != 0xFF)) { ISOException.throwIt((short) 0x6480); } } if (!pin.check(buf, off, (byte) 8)) { // Authentication failed authenticated[0] = false; ISOException.throwIt((short) (SW_PIN_TRIES_REMAINING | pin.getTriesRemaining())); } pin.update(buf, (short) (off + 8), (byte) 8); } private void doGetData(APDU apdu) throws ISOException { byte[] buf = apdu.getBuffer(); byte p1 = buf[ISO7816.OFFSET_P1]; byte p2 = buf[ISO7816.OFFSET_P2]; short lc = apdu.setIncomingAndReceive(); short offset = apdu.getOffsetCdata(); if (p1 != (byte) 0x3F || p2 != (byte) 0xFF) { ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2); } if (lc != apdu.getIncomingLength()) { ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); } if (buf[offset] != (byte) 0x5C) { ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND); } switch (buf[(short) (offset + 1)]) { case 0x1: if (buf[(short) (offset + 2)] == (byte) 0x7E) { io.sendFile(FileIndex.DISCOVERY, apdu, (short) 0); return; } break; case 0x3: if ((buf[(short) (offset + 2)] != (byte) 0x5F) || (buf[(short) (offset + 3)] != (byte) 0xC1) || (buf[(short) (offset + 4)] == (byte) 0x4) || (buf[(short) (offset + 4)] > (byte) 0xA)) { ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND); } byte id = (byte) (buf[(byte) (offset + 4)] - 1); if (((id == (byte) 0x2) || (id == (byte) 0x7) || (id == (byte) 0x8)) && !authenticated[0]) { ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED); } io.sendFile(id, apdu, (short) 0); return; default: break; } ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND); } private void doPutData(APDU apdu) throws ISOException { byte[] buf = apdu.getBuffer(); byte p1 = buf[ISO7816.OFFSET_P1]; byte p2 = buf[ISO7816.OFFSET_P2]; byte cla = buf[ISO7816.OFFSET_CLA]; short lc = apdu.setIncomingAndReceive(); short offset = apdu.getOffsetCdata(); if (p1 != (byte) 0x3F || p2 != (byte) 0xFF) { ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2); } if ((cla != 0x0) && (cla != 0x10)) { ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED); } if (!authenticated[0]) { ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED); } if (io.isLoaded()) { io.receiveFile(buf, offset, lc); if (cla == 0x00) { io.clear(); } ISOException.throwIt(ISO7816.SW_NO_ERROR); } if (lc != apdu.getIncomingLength() || lc < (byte) 0x06) { ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); } byte id; if (buf[offset] == (byte) 0x5C) { if ((buf[(short) (offset + 1)] != (byte) 0x03) || (buf[(short) (offset + 2)] != (byte) 0x5F) || (buf[(short) (offset + 3)] != (byte) 0xC1)) { ISOException.throwIt(ISO7816.SW_DATA_INVALID); } id = (byte) (buf[(short) (offset + 4)] - 1); if ((id == (byte) 0x03) || (id > (byte) 0x0A)) { ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND); } if (buf[(short) (offset + 5)] != (byte) 0x53) { ISOException.throwIt(ISO7816.SW_DATA_INVALID); } offset += 5; } else if (buf[offset] == (byte) 0x7E) { id = FileIndex.DISCOVERY; } else { ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED); return; } short l = (short) buf[offset]; short off = (short) (offset + 1); if ((buf[off] & (byte) 0x80) == 0) { off += 1; } else if (buf[off] == (byte) 0x81) { l = (short) (buf[(short) (off + 1)]); off += 2; } else if (buf[off] == (byte) 0x82) { l = Util.getShort(buf, (short) (off + 1)); off += 3; } else { ISOException.throwIt(ISO7816.SW_UNKNOWN); } io.createFile(id, (short) (l + (off - offset))); io.receiveFile(buf, offset, (short) (lc - (offset - apdu.getOffsetCdata()))); if (cla == 0x00) { io.clear(); } } private static byte keyMapping(byte keyRef) { switch (keyRef) { case (byte) 0x9A: return 0; case (byte) 0x9C: return 1; case (byte) 0x9D: return 2; case (byte) 0x9E: return 3; default: return (byte) 0xFF; } } private void doGenerateKeyPair(APDU apdu) throws ISOException { byte[] buf = apdu.getBuffer(); byte p1 = buf[ISO7816.OFFSET_P1]; byte p2 = buf[ISO7816.OFFSET_P2]; short lc = apdu.setIncomingAndReceive(); short offset = apdu.getOffsetCdata(); if ((p1 != (byte) 0x00) || (keyMapping(p2) == (byte) 0xFF)) { ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2); } if (!authenticated[0]) { ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED); } if ((lc != apdu.getIncomingLength()) || (lc < 5)) { ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); } if (Util.arrayCompare(buf, offset, new byte[]{ (byte) 0xAC, (byte) 0x03, (byte) 0x80, (byte) 0x01 }, (byte) 0, (byte) 4) != 0) { ISOException.throwIt(ISO7816.SW_WRONG_DATA); } switch (buf[(short) (offset + 4)]) { case 0x07: // RSA: 2048 doGenRSA(apdu, buf[ISO7816.OFFSET_P2]); break; case 0x11: // ECC: Curve P-256 doGenEC(apdu, buf[ISO7816.OFFSET_P2], (short) 256); break; case 0x14: // ECC: Curve P-384 doGenEC(apdu, buf[ISO7816.OFFSET_P2], (short) 384); break; default: ISOException.throwIt(ISO7816.SW_WRONG_DATA); break; } } private void sendRSAPublicKey(APDU apdu, RSAPublicKey key) { // T:0x7F,0x49 L:0x82,0x01,09 (265) // - T:0x81 L:0x82,0x01,0x00 (256) V:[RSA Modulus 256 bytes] // - T:0x82 L:0x03 (3) V:[RSA Exponent 3 bytes] short off = 0; byte[] buf = new byte[271]; byte[] header = new byte[]{ (byte) 0x7F, (byte) 0x49, (byte) 0x82, (byte) 0x01, (byte) 0x09, (byte) 0x81, (byte) 0x82, (byte) 0x01, (byte) 0x00 }; Util.arrayCopy(header, (short) 0, buf, (short) 0, (short) header.length); off += header.length; short l = key.getModulus(buf, off); if (l > 0x0100) { buf[(short) 0x04] = (byte) (l - 0x0100 + 9); buf[(short) 0x08] = (byte) (l - 0x0100); } off += l; buf[off++] = (byte) 0x82; buf[off++] = (byte) 0x03; off += key.getExponent(buf, off); io.sendBuffer(buf, off, apdu); } private void doGenRSA(APDU apdu, byte keyRef) { KeyPair kp = null; byte id = keyMapping(keyRef); try { kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_2048); } catch (CryptoException e) { if (e.getReason() == CryptoException.NO_SUCH_ALGORITHM) { ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED); } ISOException.throwIt(ISO7816.SW_UNKNOWN); } if (kp != null) { kp.genKeyPair(); if (keys[id] != null) { keys[id].clearKey(); } keys[id] = kp.getPrivate(); sendRSAPublicKey(apdu, (RSAPublicKey) kp.getPublic()); } } private void sendECPublicKey(APDU apdu, ECPublicKey key) { // T:0x7F,0x49 L:0x43 (67) // - T:0x86 L:0x41 (65) V:[EC Point 65 bytes] byte buf[] = new byte[70]; Util.arrayCopy(new byte[]{ (byte) 0x7F, (byte) 0x49, (byte) 0x43, (byte) 0x86, (byte) 0x41 }, (short) 0, buf, (short) 0, (short) 5); short l = key.getW(buf, (short) 5); io.sendBuffer(buf, (short) buf.length, apdu); } private void doGenEC(APDU apdu, byte keyRef, short size) { KeyPair kp = null; byte id = keyMapping(keyRef); if (ec_signature == null) { ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED); } try { kp = new KeyPair(KeyPair.ALG_EC_FP, size); } catch (CryptoException e) { if (e.getReason() == CryptoException.NO_SUCH_ALGORITHM) { ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED); } ISOException.throwIt(ISO7816.SW_UNKNOWN); } if (kp != null) { kp.genKeyPair(); if (keys[id] != null) { keys[id].clearKey(); } keys[id] = kp.getPrivate(); sendECPublicKey(apdu, (ECPublicKey) kp.getPublic()); } } public static short lengthLength(short l) { return (short) ((l < 128) ? 1 : ((l < 256) ? 2 : 3)); } public static short getTag(byte[] buf, short offset, short length, byte tag) { short off = offset; short end = (short) (off + length - 1); while ((off < end) && (buf[off] != tag)) { short l = BERTLV.decodeLength(buf, (short) (off + 1)); off += lengthLength(l) + l + 1; } return off; } private void doGeneralAuthenticate(APDU apdu) throws ISOException { byte[] buf = apdu.getBuffer(); byte p1 = buf[ISO7816.OFFSET_P1]; byte p2 = buf[ISO7816.OFFSET_P2]; if ((p1 == (byte) 0x07 || p1 == (byte) 0x11 || p1 == (byte) 0x14) && (keyMapping(p2) != (byte) 0xFF)) { doPrivateKeyOperation(apdu); } else if ((p1 == (byte) 0x00 || p1 == (byte) 0x03) && (p2 == (byte) 0x9B)) { doAuthenticate(apdu); } else { ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2); } } private void doAuthenticate(APDU apdu) throws ISOException { byte[] buf = apdu.getBuffer(); short lc = apdu.setIncomingAndReceive(); short offset = apdu.getOffsetCdata(); if ((lc == (short) 4) && (Util.arrayCompare(buf, offset, new byte[]{ (byte) 0x7C, (byte) 0x02, (byte) 0x80, (byte) 0x00 }, (short) 0, (short) 4) == (short) 0)) { Cipher cipher = Cipher.getInstance(Cipher.ALG_DES_ECB_NOPAD, false); byte[] out = new byte[12]; Util.arrayCopy(new byte[]{ (byte) 0x7C, (byte) 0x0A, (byte) 0x80, (byte) 0x08 }, (short) 0, out, (short) 0, (short) 4); random.generateData(challenge, (short) 0, (short) 8); cipher.init(mgmt_key, Cipher.MODE_ENCRYPT); cipher.doFinal(challenge, (short) 0, (short) 8, out, (short) 4); io.sendBuffer(out, (short) 12, apdu); } else if ((lc == (short) 22) && (Util.arrayCompare(buf, offset, new byte[]{ (byte) 0x7C, (byte) 0x14, (byte) 0x80, (byte) 0x08 }, (short) 0, (short) 4) == (short) 0)) { if (mgmt_counter.getTriesRemaining() == 0) { ISOException.throwIt(SW_AUTHENTICATION_METHOD_BLOCKED); } if (Util.arrayCompare(buf, (short) (offset + 4), challenge, (short) 0, (short) 8) == 0) { mgmt_counter.resetAndUnblock(); authenticated[0] = true; if ((buf[(short) (offset + 0x0C)] == (byte) 0x81) && (buf[(short) (offset + 0x0D)] == (byte) 0x08)) { Cipher cipher = Cipher.getInstance(Cipher.ALG_DES_ECB_NOPAD, false); byte[] out = new byte[12]; Util.arrayCopy(new byte[]{ (byte) 0x7C, (byte) 0x0A, (byte) 0x82, (byte) 0x08 }, (short) 0, out, (short) 0, (short) 4); cipher.init(mgmt_key, Cipher.MODE_ENCRYPT); cipher.doFinal(buf, (short) (offset + 0x0E), (short) 8, out, (short) 4); io.sendBuffer(out, (short) 12, apdu); } } else { authenticated[0] = false; mgmt_counter.check(new byte[]{0x01, 0x01, 0x01, 0x01}, (short) 0, (byte) 4); ISOException.throwIt((short) (SW_PIN_TRIES_REMAINING | mgmt_counter.getTriesRemaining())); } } else { ISOException.throwIt(ISO7816.SW_DATA_INVALID); } } private void doPrivateKeyOperation(APDU apdu) throws ISOException { byte[] buf = apdu.getBuffer(); byte cla = buf[ISO7816.OFFSET_CLA]; byte p1 = buf[ISO7816.OFFSET_P1]; byte p2 = buf[ISO7816.OFFSET_P2]; short lc = apdu.setIncomingAndReceive(); short offset = apdu.getOffsetCdata(); short id = keyMapping(p2); if (keys[id] == null) { ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2); } if ((cla != 0x0) && (cla != 0x10)) { ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED); } if (cla == 0x10) { io.receiveBuffer(buf, offset, lc); ISOException.throwIt(ISO7816.SW_NO_ERROR); } if (io.isLoaded()) { buf = io.retrieveBuffer(buf, offset, lc); offset = 0; lc = (short) buf.length; } short cur = offset; if (buf[cur++] != (byte) 0x7C) { ISOException.throwIt(ISO7816.SW_DATA_INVALID); } cur += lengthLength(BERTLV.decodeLength(buf, cur)); short m = getTag(buf, cur, lc, (byte) 0x81); if (m < lc && buf[m] == (byte) 0x81) { short k = BERTLV.decodeLength(buf, (short) (m + 1)); m += lengthLength(k) + 1; byte[] signature = null; short l = 0; if (keys[id].getType() == KeyBuilder.TYPE_RSA_CRT_PRIVATE) { if (k != 256) { ISOException.throwIt(ISO7816.SW_DATA_INVALID); } l = (short) 264; // (256 + LL(256) + 1) + LL(260) + 1 signature = new byte[l]; Util.arrayCopy(new byte[]{ (byte) 0x7C, (byte) 0x82, (byte) 0x01, (byte) 0x04, (byte) 0x82, (byte) 0x82, (byte) 0x01, (byte) 0x00 }, (short) 0, signature, (short) 0, (short) 8); rsa_cipher.init(keys[id], Cipher.MODE_DECRYPT); try { k = rsa_cipher.doFinal(buf, m, k, signature, (short) 8); } catch (CryptoException e) { if (e.getReason() == CryptoException.NO_SUCH_ALGORITHM) { ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED); } ISOException.throwIt(ISO7816.SW_UNKNOWN); } if (k != 256) { ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); } } else if (keys[id].getType() == KeyBuilder.TYPE_EC_FP_PRIVATE) { if (ec_signature == null) { ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED); } signature = new byte[76]; ec_signature.init(keys[id], Signature.MODE_SIGN); try { k = ec_signature.sign(buf, m, k, signature, (short) 4); } catch (CryptoException e) { if (e.getReason() == CryptoException.NO_SUCH_ALGORITHM) { ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED); } ISOException.throwIt(ISO7816.SW_UNKNOWN); } if (k < 70) { ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); } signature[0] = (byte) 0x7C; signature[1] = (byte) ((k + 2) & 0xFF); signature[2] = (byte) 0x82; signature[3] = (byte) (k & 0xFF); l = (short) (k + 4); } io.sendBuffer(signature, l, apdu); } } }
src/org/cryptonit/CryptonitApplet.java
package org.cryptonit; import javacard.framework.APDU; import javacard.framework.Applet; import javacard.framework.ISO7816; import javacard.framework.ISOException; import javacard.framework.JCSystem; import javacard.framework.OwnerPIN; import javacard.framework.Util; import javacard.security.CryptoException; import javacard.security.DESKey; import javacard.security.ECPublicKey; import javacard.security.RandomData; import javacard.security.Key; import javacard.security.KeyBuilder; import javacard.security.KeyPair; import javacard.security.RSAPublicKey; import javacard.security.Signature; import javacardx.apdu.ExtendedLength; import javacardx.crypto.Cipher; /** * @author Mathias Brossard */ public class CryptonitApplet extends Applet implements ExtendedLength { private final OwnerPIN pin; private final OwnerPIN mgmt_counter; private Key[] keys = null; private Key mgmt_key = null; private byte[] challenge = null; private boolean[] authenticated = null; private Cipher rsa_cipher = null; private Signature ec_signature = null; private RandomData random = null; private IOBuffer io = null; private final static byte PIN_MAX_LENGTH = 8; private final static byte PIN_MAX_TRIES = 5; private final static byte MGMT_MAX_TRIES = 3; public static final byte INS_GET_DATA = (byte) 0xCB; public static final byte INS_GET_RESPONSE = (byte) 0xC0; public static final byte INS_PUT_DATA = (byte) 0xDB; public static final byte INS_VERIFY_PIN = (byte) 0x20; public static final byte INS_GENERAL_AUTHENTICATE = (byte) 0x87; public static final byte INS_CHANGE_REFERENCE_DATA = (byte) 0x24; public static final byte INS_GENERATE_ASYMMETRIC_KEYPAIR = (byte) 0x47; public static final short SW_PIN_TRIES_REMAINING = 0x63C0; public static final short SW_AUTHENTICATION_METHOD_BLOCKED = 0x6983; protected CryptonitApplet(byte[] bArray, short bOffset, byte bLength) { mgmt_key = KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_3KEY, false); ((DESKey) mgmt_key).setKey(new byte[]{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }, (short) 0); mgmt_counter = new OwnerPIN(MGMT_MAX_TRIES, (byte) 4); mgmt_counter.update(new byte[]{0x00, 0x00, 0x00, 0x00}, (short) 0, (byte) 4); challenge = JCSystem.makeTransientByteArray((short) 8, JCSystem.CLEAR_ON_DESELECT); pin = new OwnerPIN(PIN_MAX_TRIES, PIN_MAX_LENGTH); pin.update(new byte[]{ 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 }, (short) 0, (byte) 8); keys = new Key[(byte) 4]; random = RandomData.getInstance(RandomData.ALG_SECURE_RANDOM); authenticated = JCSystem.makeTransientBooleanArray((short) 1, JCSystem.CLEAR_ON_DESELECT); rsa_cipher = Cipher.getInstance(Cipher.ALG_RSA_NOPAD, false); try { ec_signature = Signature.getInstance(Signature.ALG_ECDSA_SHA, false); } catch (Exception e) { } FileIndex index = new FileIndex(); io = new IOBuffer(index); register(); } public static void install(byte[] bArray, short bOffset, byte bLength) { new CryptonitApplet(bArray, bOffset, bLength); } @Override public void process(APDU apdu) { byte buffer[] = apdu.getBuffer(); byte ins = buffer[ISO7816.OFFSET_INS]; if (apdu.isSecureMessagingCLA()) { ISOException.throwIt(ISO7816.SW_SECURE_MESSAGING_NOT_SUPPORTED); } switch (ins) { case ISO7816.INS_SELECT: doSelect(apdu); break; case INS_VERIFY_PIN: doVerifyPin(apdu); break; case INS_CHANGE_REFERENCE_DATA: doChangePIN(apdu); break; case INS_GET_DATA: doGetData(apdu); break; case INS_GET_RESPONSE: io.getResponse(apdu); break; case INS_PUT_DATA: doPutData(apdu); break; case INS_GENERATE_ASYMMETRIC_KEYPAIR: doGenerateKeyPair(apdu); break; case INS_GENERAL_AUTHENTICATE: doGeneralAuthenticate(apdu); break; default: ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED); break; } } private void doSelect(APDU apdu) throws ISOException { byte[] buf = apdu.getBuffer(); byte p1 = buf[ISO7816.OFFSET_P1]; byte p2 = buf[ISO7816.OFFSET_P2]; final byte[] apt = { /* Application property template */ (byte) 0x61, (byte) 0x16, /* - Application identifier of application */ (byte) 0x4F, (byte) 0x0B, (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x08, (byte) 0x00, (byte) 0x00, (byte) 0x10, (byte) 0x00, (byte) 0x01, (byte) 0x00, /* - Coexistent tag allocation authority */ (byte) 0x79, (byte) 0x07, /* - Application identifier */ (byte) 0x4F, (byte) 0x05, (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x08 }; if ((p1 == (byte) 0x04) && (p2 == (byte) 0x00)) { short l = apdu.setIncomingAndReceive(); short offset = apdu.getOffsetCdata(); final byte[] aid1 = { (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x08 }; final byte[] aid2 = { (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x08, (byte) 0x00, (byte) 0x00, (byte) 0x10, (byte) 0x00 }; if (((l == (short) aid1.length) && (Util.arrayCompare(buf, offset, aid1, (byte) 0, (byte) aid1.length) == 0)) || ((l == (short) aid2.length) && (Util.arrayCompare(buf, offset, aid2, (byte) 0, (byte) aid2.length) == 0))) { io.sendBuffer(apt, (short) apt.length, apdu); return; } } ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND); } private void doVerifyPin(APDU apdu) throws ISOException { byte[] buf = apdu.getBuffer(); byte p1 = buf[ISO7816.OFFSET_P1]; byte p2 = buf[ISO7816.OFFSET_P2]; short lc = apdu.setIncomingAndReceive(); if ((p1 != (byte) 0x00 && p1 != (byte) 0xFF) || (p2 != (byte) 0x80)) { ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2); } if (p1 == (byte) 0xFF) { authenticated[0] = false; ISOException.throwIt(ISO7816.SW_NO_ERROR); } if ((lc != apdu.getIncomingLength()) || lc != (short) 8) { ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); } if (pin.getTriesRemaining() == 0) { ISOException.throwIt(SW_AUTHENTICATION_METHOD_BLOCKED); } // Check the PIN. if (!pin.check(buf, apdu.getOffsetCdata(), (byte) lc)) { // Authentication failed authenticated[0] = false; ISOException.throwIt((short) (SW_PIN_TRIES_REMAINING | pin.getTriesRemaining())); } else { // Authentication successful authenticated[0] = true; ISOException.throwIt(ISO7816.SW_NO_ERROR); } } private void doChangePIN(APDU apdu) { byte[] buf = apdu.getBuffer(); byte p1 = buf[ISO7816.OFFSET_P1]; byte p2 = buf[ISO7816.OFFSET_P2]; short off, lc = apdu.setIncomingAndReceive(); if (p1 != (byte) 0x00 || (p2 != (byte) 0x80)) { ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2); } if (pin.getTriesRemaining() == 0) { ISOException.throwIt(SW_AUTHENTICATION_METHOD_BLOCKED); } if ((lc != apdu.getIncomingLength()) || lc != (short) 16) { ISOException.throwIt((short) 0x6480); } off = apdu.getOffsetCdata(); for (short i = 0; i < (short) 16; i++) { if (((buf[(short) (i + off)] < 0x30) || (buf[(short) (i + off)] > 0x39)) && (buf[(short) (i + off)] != 0xFF)) { ISOException.throwIt((short) 0x6480); } } if (!pin.check(buf, off, (byte) 8)) { // Authentication failed authenticated[0] = false; ISOException.throwIt((short) (SW_PIN_TRIES_REMAINING | pin.getTriesRemaining())); } pin.update(buf, (short) (off + 8), (byte) 8); } private void doGetData(APDU apdu) throws ISOException { byte[] buf = apdu.getBuffer(); byte p1 = buf[ISO7816.OFFSET_P1]; byte p2 = buf[ISO7816.OFFSET_P2]; short lc = apdu.setIncomingAndReceive(); short offset = apdu.getOffsetCdata(); if (p1 != (byte) 0x3F || p2 != (byte) 0xFF) { ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2); } if (lc != apdu.getIncomingLength()) { ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); } if (buf[offset] != (byte) 0x5C) { ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND); } switch (buf[(short) (offset + 1)]) { case 0x1: if (buf[(short) (offset + 2)] == (byte) 0x7E) { io.sendFile(FileIndex.DISCOVERY, apdu, (short) 0); return; } break; case 0x3: if ((buf[(short) (offset + 2)] != (byte) 0x5F) || (buf[(short) (offset + 3)] != (byte) 0xC1) || (buf[(short) (offset + 4)] == (byte) 0x4) || (buf[(short) (offset + 4)] > (byte) 0xA)) { ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND); } byte id = (byte) (buf[(byte) (offset + 4)] - 1); if (((id == (byte) 0x2) || (id == (byte) 0x7) || (id == (byte) 0x8)) && !authenticated[0]) { ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED); } io.sendFile(id, apdu, (short) 0); return; default: break; } ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND); } private void doPutData(APDU apdu) throws ISOException { byte[] buf = apdu.getBuffer(); byte p1 = buf[ISO7816.OFFSET_P1]; byte p2 = buf[ISO7816.OFFSET_P2]; byte cla = buf[ISO7816.OFFSET_CLA]; short lc = apdu.setIncomingAndReceive(); short offset = apdu.getOffsetCdata(); if (p1 != (byte) 0x3F || p2 != (byte) 0xFF) { ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2); } if ((cla != 0x0) && (cla != 0x10)) { ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED); } if (!authenticated[0]) { ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED); } if (io.isLoaded()) { io.receiveFile(buf, offset, lc); if (cla == 0x00) { io.clear(); } ISOException.throwIt(ISO7816.SW_NO_ERROR); } if (lc != apdu.getIncomingLength() || lc < (byte) 0x06) { ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); } byte id; if (buf[offset] == (byte) 0x5C) { if ((buf[(short) (offset + 1)] != (byte) 0x03) || (buf[(short) (offset + 2)] != (byte) 0x5F) || (buf[(short) (offset + 3)] != (byte) 0xC1)) { ISOException.throwIt(ISO7816.SW_DATA_INVALID); } id = (byte) (buf[(short) (offset + 4)] - 1); if ((id == (byte) 0x03) || (id > (byte) 0x0A)) { ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND); } if (buf[(short) (offset + 5)] != (byte) 0x53) { ISOException.throwIt(ISO7816.SW_DATA_INVALID); } offset += 5; } else if (buf[offset] == (byte) 0x7E) { id = FileIndex.DISCOVERY; } else { ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED); return; } short l = (short) buf[offset]; short off = (short) (offset + 1); if ((buf[off] & (byte) 0x80) == 0) { off += 1; } else if (buf[off] == (byte) 0x81) { l = (short) (buf[(short) (off + 1)]); off += 2; } else if (buf[off] == (byte) 0x82) { l = Util.getShort(buf, (short) (off + 1)); off += 3; } else { ISOException.throwIt(ISO7816.SW_UNKNOWN); } io.createFile(id, (short) (l + (off - offset))); io.receiveFile(buf, offset, (short) (lc - (offset - apdu.getOffsetCdata()))); if (cla == 0x00) { io.clear(); } } private static byte keyMapping(byte keyRef) { switch (keyRef) { case (byte) 0x9A: return 0; case (byte) 0x9C: return 1; case (byte) 0x9D: return 2; case (byte) 0x9E: return 3; default: return (byte) 0xFF; } } private void doGenerateKeyPair(APDU apdu) throws ISOException { byte[] buf = apdu.getBuffer(); byte p1 = buf[ISO7816.OFFSET_P1]; byte p2 = buf[ISO7816.OFFSET_P2]; short lc = apdu.setIncomingAndReceive(); short offset = apdu.getOffsetCdata(); if ((p1 != (byte) 0x00) || (keyMapping(p2) == (byte) 0xFF)) { ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2); } if (!authenticated[0]) { ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED); } if ((lc != apdu.getIncomingLength()) || (lc < 5)) { ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); } byte[] prefix = new byte[]{ (byte) 0xAC, (byte) 0x03, (byte) 0x80, (byte) 0x01 }; if (Util.arrayCompare(buf, offset, prefix, (byte) 0, (byte) prefix.length) != 0) { ISOException.throwIt(ISO7816.SW_WRONG_DATA); } switch (buf[(short) (offset + 4)]) { case 0x07: // RSA: 2048 doGenRSA(apdu, buf[ISO7816.OFFSET_P2]); break; case 0x11: // ECC: Curve P-256 doGenEC(apdu, buf[ISO7816.OFFSET_P2], (short) 256); break; case 0x14: // ECC: Curve P-384 doGenEC(apdu, buf[ISO7816.OFFSET_P2], (short) 384); break; default: ISOException.throwIt(ISO7816.SW_WRONG_DATA); break; } } private void sendRSAPublicKey(APDU apdu, RSAPublicKey key) { // T:0x7F,0x49 L:0x82,0x01,09 (265) // - T:0x81 L:0x82,0x01,0x00 (256) V:[RSA Modulus 256 bytes] // - T:0x82 L:0x03 (3) V:[RSA Exponent 3 bytes] short off = 0; byte[] buf = new byte[271]; byte[] header = new byte[]{ (byte) 0x7F, (byte) 0x49, (byte) 0x82, (byte) 0x01, (byte) 0x09, (byte) 0x81, (byte) 0x82, (byte) 0x01, (byte) 0x00 }; Util.arrayCopy(header, (short) 0, buf, (short) 0, (short) header.length); off += header.length; short l = key.getModulus(buf, off); if (l > 0x0100) { buf[(short) 0x04] = (byte) (l - 0x0100 + 9); buf[(short) 0x08] = (byte) (l - 0x0100); } off += l; buf[off++] = (byte) 0x82; buf[off++] = (byte) 0x03; off += key.getExponent(buf, off); io.sendBuffer(buf, off, apdu); } private void doGenRSA(APDU apdu, byte keyRef) { KeyPair kp = null; byte id = keyMapping(keyRef); try { kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_2048); } catch (CryptoException e) { if (e.getReason() == CryptoException.NO_SUCH_ALGORITHM) { ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED); } ISOException.throwIt(ISO7816.SW_UNKNOWN); } if (kp != null) { kp.genKeyPair(); if (keys[id] != null) { keys[id].clearKey(); } keys[id] = kp.getPrivate(); sendRSAPublicKey(apdu, (RSAPublicKey) kp.getPublic()); } } private void sendECPublicKey(APDU apdu, ECPublicKey key) { // T:0x7F,0x49 L:0x43 (67) // - T:0x86 L:0x41 (65) V:[EC Point 65 bytes] byte buf[] = new byte[70]; Util.arrayCopy(new byte[]{ (byte) 0x7F, (byte) 0x49, (byte) 0x43, (byte) 0x86, (byte) 0x41 }, (short) 0, buf, (short) 0, (short) 5); short l = key.getW(buf, (short) 5); io.sendBuffer(buf, (short) buf.length, apdu); } private void doGenEC(APDU apdu, byte keyRef, short size) { KeyPair kp = null; byte id = keyMapping(keyRef); if (ec_signature == null) { ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED); } try { kp = new KeyPair(KeyPair.ALG_EC_FP, size); } catch (CryptoException e) { if (e.getReason() == CryptoException.NO_SUCH_ALGORITHM) { ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED); } ISOException.throwIt(ISO7816.SW_UNKNOWN); } if (kp != null) { kp.genKeyPair(); if (keys[id] != null) { keys[id].clearKey(); } keys[id] = kp.getPrivate(); sendECPublicKey(apdu, (ECPublicKey) kp.getPublic()); } } public static short lengthLength(short l) { return (short) ((l < 128) ? 1 : ((l < 256) ? 2 : 3)); } public static short getTag(byte[] buf, short offset, short length, byte tag) { short off = offset; short end = (short) (off + length - 1); while ((off < end) && (buf[off] != tag)) { short l = BERTLV.decodeLength(buf, (short) (off + 1)); off += lengthLength(l) + l + 1; } return off; } private void doGeneralAuthenticate(APDU apdu) throws ISOException { byte[] buf = apdu.getBuffer(); byte p1 = buf[ISO7816.OFFSET_P1]; byte p2 = buf[ISO7816.OFFSET_P2]; if ((p1 == (byte) 0x07 || p1 == (byte) 0x11 || p1 == (byte) 0x14) && (keyMapping(p2) != (byte) 0xFF)) { doPrivateKeyOperation(apdu); } else if ((p1 == (byte) 0x00 || p1 == (byte) 0x03) && (p2 == (byte) 0x9B)) { doAuthenticate(apdu); } else { ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2); } } private void doAuthenticate(APDU apdu) throws ISOException { byte[] buf = apdu.getBuffer(); short lc = apdu.setIncomingAndReceive(); short offset = apdu.getOffsetCdata(); if ((lc == (short) 4) && (Util.arrayCompare(buf, offset, new byte[]{ (byte) 0x7C, (byte) 0x02, (byte) 0x80, (byte) 0x00 }, (short) 0, (short) 4) == (short) 0)) { Cipher cipher = Cipher.getInstance(Cipher.ALG_DES_ECB_NOPAD, false); byte[] out = new byte[12]; Util.arrayCopy(new byte[]{ (byte) 0x7C, (byte) 0x0A, (byte) 0x80, (byte) 0x08 }, (short) 0, out, (short) 0, (short) 4); random.generateData(challenge, (short) 0, (short) 8); cipher.init(mgmt_key, Cipher.MODE_ENCRYPT); cipher.doFinal(challenge, (short) 0, (short) 8, out, (short) 4); io.sendBuffer(out, (short) 12, apdu); } else if ((lc == (short) 22) && (Util.arrayCompare(buf, offset, new byte[]{ (byte) 0x7C, (byte) 0x14, (byte) 0x80, (byte) 0x08 }, (short) 0, (short) 4) == (short) 0)) { if (mgmt_counter.getTriesRemaining() == 0) { ISOException.throwIt(SW_AUTHENTICATION_METHOD_BLOCKED); } if (Util.arrayCompare(buf, (short) (offset + 4), challenge, (short) 0, (short) 8) == 0) { mgmt_counter.resetAndUnblock(); authenticated[0] = true; if ((buf[(short) (offset + 0x0C)] == (byte) 0x81) && (buf[(short) (offset + 0x0D)] == (byte) 0x08)) { Cipher cipher = Cipher.getInstance(Cipher.ALG_DES_ECB_NOPAD, false); byte[] out = new byte[12]; Util.arrayCopy(new byte[]{ (byte) 0x7C, (byte) 0x0A, (byte) 0x82, (byte) 0x08 }, (short) 0, out, (short) 0, (short) 4); cipher.init(mgmt_key, Cipher.MODE_ENCRYPT); cipher.doFinal(buf, (short) (offset + 0x0E), (short) 8, out, (short) 4); io.sendBuffer(out, (short) 12, apdu); } } else { authenticated[0] = false; mgmt_counter.check(new byte[]{0x01, 0x01, 0x01, 0x01}, (short) 0, (byte) 4); ISOException.throwIt((short) (SW_PIN_TRIES_REMAINING | mgmt_counter.getTriesRemaining())); } } else { ISOException.throwIt(ISO7816.SW_DATA_INVALID); } } private void doPrivateKeyOperation(APDU apdu) throws ISOException { byte[] buf = apdu.getBuffer(); byte cla = buf[ISO7816.OFFSET_CLA]; byte p1 = buf[ISO7816.OFFSET_P1]; byte p2 = buf[ISO7816.OFFSET_P2]; short lc = apdu.setIncomingAndReceive(); short offset = apdu.getOffsetCdata(); short id = keyMapping(p2); if (keys[id] == null) { ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2); } if ((cla != 0x0) && (cla != 0x10)) { ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED); } if (cla == 0x10) { io.receiveBuffer(buf, offset, lc); ISOException.throwIt(ISO7816.SW_NO_ERROR); } if (io.isLoaded()) { buf = io.retrieveBuffer(buf, offset, lc); offset = 0; lc = (short) buf.length; } short cur = offset; if (buf[cur++] != (byte) 0x7C) { ISOException.throwIt(ISO7816.SW_DATA_INVALID); } cur += lengthLength(BERTLV.decodeLength(buf, cur)); short m = getTag(buf, cur, lc, (byte) 0x81); if (m < lc && buf[m] == (byte) 0x81) { short k = BERTLV.decodeLength(buf, (short) (m + 1)); m += lengthLength(k) + 1; byte[] signature = null; short l = 0; if (keys[id].getType() == KeyBuilder.TYPE_RSA_CRT_PRIVATE) { if (k != 256) { ISOException.throwIt(ISO7816.SW_DATA_INVALID); } l = (short) 264; // (256 + LL(256) + 1) + LL(260) + 1 signature = new byte[l]; Util.arrayCopy(new byte[]{ (byte) 0x7C, (byte) 0x82, (byte) 0x01, (byte) 0x04, (byte) 0x82, (byte) 0x82, (byte) 0x01, (byte) 0x00 }, (short) 0, signature, (short) 0, (short) 8); rsa_cipher.init(keys[id], Cipher.MODE_DECRYPT); try { k = rsa_cipher.doFinal(buf, m, k, signature, (short) 8); } catch (CryptoException e) { if (e.getReason() == CryptoException.NO_SUCH_ALGORITHM) { ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED); } ISOException.throwIt(ISO7816.SW_UNKNOWN); } if (k != 256) { ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); } } else if (keys[id].getType() == KeyBuilder.TYPE_EC_FP_PRIVATE) { if (ec_signature == null) { ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED); } signature = new byte[76]; ec_signature.init(keys[id], Signature.MODE_SIGN); try { k = ec_signature.sign(buf, m, k, signature, (short) 4); } catch (CryptoException e) { if (e.getReason() == CryptoException.NO_SUCH_ALGORITHM) { ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED); } ISOException.throwIt(ISO7816.SW_UNKNOWN); } if (k < 70) { ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); } signature[0] = (byte) 0x7C; signature[1] = (byte) ((k + 2) & 0xFF); signature[2] = (byte) 0x82; signature[3] = (byte) (k & 0xFF); l = (short) (k + 4); } io.sendBuffer(signature, l, apdu); } } }
Remove superfluous temporary variable
src/org/cryptonit/CryptonitApplet.java
Remove superfluous temporary variable
<ide><path>rc/org/cryptonit/CryptonitApplet.java <ide> if ((lc != apdu.getIncomingLength()) || (lc < 5)) { <ide> ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); <ide> } <del> <del> byte[] prefix = new byte[]{ <add> if (Util.arrayCompare(buf, offset, new byte[]{ <ide> (byte) 0xAC, (byte) 0x03, (byte) 0x80, (byte) 0x01 <del> }; <del> if (Util.arrayCompare(buf, offset, prefix, <del> (byte) 0, (byte) prefix.length) != 0) { <add> }, (byte) 0, (byte) 4) != 0) { <ide> ISOException.throwIt(ISO7816.SW_WRONG_DATA); <ide> } <ide>
Java
apache-2.0
9e764a37266d7aa0f0a07e07ac643a812bd39e9f
0
box/mojito,box/mojito,box/mojito,box/mojito,box/mojito,box/mojito
package com.box.l10n.mojito.okapi.filters; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.sf.okapi.common.encoder.EncoderContext; import net.sf.okapi.filters.its.Parameters; import org.apache.commons.lang.StringUtils; /** * This overrides the {@link net.sf.okapi.common.encoder.XMLEncoder} for Android * strings. * * It does not escape supported HTML elements for Android strings unless there * are variables within the HTML elements. * For example, <b>songs</b> vs. &lt;b>%d songs&lt;/b> * * Also it overrides the default quotemode setting so the quotes do not get escaped. * * For detailed information, see to Android specification in * http://developer.android.com/guide/topics/resources/string-resource.html, * * @author jyi */ public class XMLEncoder extends net.sf.okapi.common.encoder.XMLEncoder { // trying to match variables between html tags, for example, <b>%d</b>, <i>%1$s</i>, <u>%2$s</u> Pattern androidVariableWithinHTML = Pattern.compile("(&lt;[b|i|u]&gt;)((.*?)%(([-0+ #]?)[-0+ #]?)((\\d\\$)?)(([\\d\\*]*)(\\.[\\d\\*]*)?)[dioxXucsfeEgGpn](.*?))+(&lt;/[b|i|u]&gt;)"); Pattern androidHTML = Pattern.compile("(&lt;)(/?)(b|i|u)(&gt;)"); Pattern unescapedDoubleQuote = Pattern.compile("([^\\\\])(\")"); Pattern startsWithDoubleQuote = Pattern.compile("(^\")"); Pattern unescapedSingleQuote = Pattern.compile("([^\\\\])(')"); Pattern startsWithSingleQuote = Pattern.compile("(^')"); @Override public String encode(String text, EncoderContext context) { String encoded = super.encode(text, context); if (isAndroidStrings()) { encoded = escapeAndroid(encoded); } return encoded; } private boolean isAndroidStrings() { Parameters params = (Parameters) getParameters(); if (params != null && params.getURI() != null && StringUtils.endsWith(params.getURI().toString(), XMLFilter.ANDROIDSTRINGS_CONFIG_FILE_NAME)) { return true; } else { return false; } } public String escapeAndroid(String text) { boolean enclosedInDoubleQuotes = StringUtils.startsWith(text, "\"") && StringUtils.endsWith(text, "\""); if (enclosedInDoubleQuotes) { text = text.substring(1, text.length() - 1); } String replacement; if (needsAndroidEscapeHTML(text)) { replacement = "$1$2$3>"; } else { replacement = "<$2$3>"; } text = androidHTML.matcher(text).replaceAll(replacement); text = text.replaceAll("\n", "\\\\n"); text = text.replaceAll("\r", "\\\\r"); text = escapeDoubleQuotes(text); if (!enclosedInDoubleQuotes) { text = escapeSingleQuotes(text); } return enclosedInDoubleQuotes ? "\"" + text + "\"" : text; } private boolean needsAndroidEscapeHTML(String text) { Matcher matcher = androidVariableWithinHTML.matcher(text); return matcher.find(); } private String escapeDoubleQuotes(String text) { String escaped = unescapedDoubleQuote.matcher(text).replaceAll("$1\\\\$2"); escaped = startsWithDoubleQuote.matcher(escaped).replaceFirst("\\\\$1"); return escaped; } private String escapeSingleQuotes(String text) { String escaped = unescapedSingleQuote.matcher(text).replaceAll("$1\\\\$2"); escaped = startsWithSingleQuote.matcher(escaped).replaceFirst("\\\\$1"); return escaped; } }
webapp/src/main/java/com/box/l10n/mojito/okapi/filters/XMLEncoder.java
package com.box.l10n.mojito.okapi.filters; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.sf.okapi.common.encoder.EncoderContext; import net.sf.okapi.filters.its.Parameters; import org.apache.commons.lang.StringUtils; /** * This overrides the {@link net.sf.okapi.common.encoder.XMLEncoder} for Android * strings. * * It does not escape supported HTML elements for Android strings unless there * are variables within the HTML elements, for example, <b>songs</b> vs. * &lt;b>%d songs&lt;/b> Also it overrides the default quotemode setting so the * quotes do not get escaped. * * According to Android specification in * http://developer.android.com/guide/topics/resources/string-resource.html, * <b>bold</b>, <i>italian</i> and <u>underline</u> should be in localized file * as-is. * * @author jyi */ public class XMLEncoder extends net.sf.okapi.common.encoder.XMLEncoder { // trying to match variables between html tags, for example, <b>%d</b>, <i>%1$s</i>, <u>%2$s</u> Pattern androidVariableWithinHTML = Pattern.compile("(&lt;[b|i|u]&gt;)((.*?)%(([-0+ #]?)[-0+ #]?)((\\d\\$)?)(([\\d\\*]*)(\\.[\\d\\*]*)?)[dioxXucsfeEgGpn](.*?))+(&lt;/[b|i|u]&gt;)"); Pattern androidHTML = Pattern.compile("(&lt;)(/?)(b|i|u)(&gt;)"); Pattern unescapedDoubleQuote = Pattern.compile("([^\\\\])(\")"); Pattern startsWithDoubleQuote = Pattern.compile("(^\")"); Pattern unescapedSingleQuote = Pattern.compile("([^\\\\])(')"); Pattern startsWithSingleQuote = Pattern.compile("(^')"); @Override public String encode(String text, EncoderContext context) { String encoded = super.encode(text, context); if (isAndroidStrings()) { encoded = escapeAndroid(encoded); } return encoded; } private boolean isAndroidStrings() { Parameters params = (Parameters) getParameters(); if (params != null && params.getURI() != null && StringUtils.endsWith(params.getURI().toString(), XMLFilter.ANDROIDSTRINGS_CONFIG_FILE_NAME)) { return true; } else { return false; } } public String escapeAndroid(String text) { boolean enclosedInDoubleQuotes = StringUtils.startsWith(text, "\"") && StringUtils.endsWith(text, "\""); if (enclosedInDoubleQuotes) { text = text.substring(1, text.length() - 1); } String replacement; if (needsAndroidEscapeHTML(text)) { replacement = "$1$2$3>"; } else { replacement = "<$2$3>"; } text = androidHTML.matcher(text).replaceAll(replacement); text = text.replaceAll("\n", "\\\\n"); text = text.replaceAll("\r", "\\\\r"); text = escapeDoubleQuotes(text); if (!enclosedInDoubleQuotes) { text = escapeSingleQuotes(text); } return enclosedInDoubleQuotes ? "\"" + text + "\"" : text; } private boolean needsAndroidEscapeHTML(String text) { Matcher matcher = androidVariableWithinHTML.matcher(text); return matcher.find(); } private String escapeDoubleQuotes(String text) { String escaped = unescapedDoubleQuote.matcher(text).replaceAll("$1\\\\$2"); escaped = startsWithDoubleQuote.matcher(escaped).replaceFirst("\\\\$1"); return escaped; } private String escapeSingleQuotes(String text) { String escaped = unescapedSingleQuote.matcher(text).replaceAll("$1\\\\$2"); escaped = startsWithSingleQuote.matcher(escaped).replaceFirst("\\\\$1"); return escaped; } }
documentation updated
webapp/src/main/java/com/box/l10n/mojito/okapi/filters/XMLEncoder.java
documentation updated
<ide><path>ebapp/src/main/java/com/box/l10n/mojito/okapi/filters/XMLEncoder.java <ide> * strings. <ide> * <ide> * It does not escape supported HTML elements for Android strings unless there <del> * are variables within the HTML elements, for example, <b>songs</b> vs. <del> * &lt;b>%d songs&lt;/b> Also it overrides the default quotemode setting so the <del> * quotes do not get escaped. <add> * are variables within the HTML elements. <add> * For example, <b>songs</b> vs. &lt;b>%d songs&lt;/b> <ide> * <del> * According to Android specification in <add> * Also it overrides the default quotemode setting so the quotes do not get escaped. <add> * <add> * For detailed information, see to Android specification in <ide> * http://developer.android.com/guide/topics/resources/string-resource.html, <del> * <b>bold</b>, <i>italian</i> and <u>underline</u> should be in localized file <del> * as-is. <ide> * <ide> * @author jyi <ide> */
Java
mit
error: pathspec 'src/main/java/de/dhbw/humbuch/event/MessageEvent.java' did not match any file(s) known to git
837ca30dc10b1674b88764a9f84dba758cf2ce34
1
HumBuch/HumBuch,HumBuch/HumBuch,HumBuch/HumBuch
package de.dhbw.humbuch.event; /** * Object for the Guava EventBus containing a message and a message tpye * */ public class MessageEvent { public final String message; public final Type type; public enum Type { INFO, WARNING, ERROR; } /** * Creates an event with the specified message and {@link Type}.INFO as * standard type * * @param message * {@link String} containing the message */ public MessageEvent(String message) { this(message, Type.INFO); } /** * Creates an event with the specified message and type * * @param message * {@link String} containing the message * @param type * {@link Type} defining the message type */ public MessageEvent(String message, Type type) { this.message = message; this.type = type; } }
src/main/java/de/dhbw/humbuch/event/MessageEvent.java
added class containing a message and a message type for a notification system via Guava EventBus
src/main/java/de/dhbw/humbuch/event/MessageEvent.java
added class containing a message and a message type for a notification system via Guava EventBus
<ide><path>rc/main/java/de/dhbw/humbuch/event/MessageEvent.java <add>package de.dhbw.humbuch.event; <add> <add>/** <add> * Object for the Guava EventBus containing a message and a message tpye <add> * <add> */ <add>public class MessageEvent { <add> <add> public final String message; <add> public final Type type; <add> <add> public enum Type { <add> INFO, WARNING, ERROR; <add> } <add> <add> /** <add> * Creates an event with the specified message and {@link Type}.INFO as <add> * standard type <add> * <add> * @param message <add> * {@link String} containing the message <add> */ <add> public MessageEvent(String message) { <add> this(message, Type.INFO); <add> } <add> <add> /** <add> * Creates an event with the specified message and type <add> * <add> * @param message <add> * {@link String} containing the message <add> * @param type <add> * {@link Type} defining the message type <add> */ <add> public MessageEvent(String message, Type type) { <add> this.message = message; <add> this.type = type; <add> } <add>}
Java
apache-2.0
c7467604497ddd7b166f57d84d00d53ef0812b1c
0
Teradata/kylo,Teradata/kylo,Teradata/kylo,Teradata/kylo,Teradata/kylo
package com.thinkbiganalytics.metadata.upgrade.v0_10_0; /*- * #%L * kylo-upgrade-service * %% * Copyright (C) 2017 ThinkBig Analytics * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.thinkbiganalytics.KyloVersion; import com.thinkbiganalytics.feedmgr.nifi.NifiControllerServiceProperties; import com.thinkbiganalytics.kylo.catalog.ConnectorPluginManager; import com.thinkbiganalytics.metadata.api.catalog.Connector; import com.thinkbiganalytics.metadata.api.catalog.ConnectorProvider; import com.thinkbiganalytics.metadata.api.catalog.DataSetSparkParameters; import com.thinkbiganalytics.metadata.api.datasource.DatasourceProvider; import com.thinkbiganalytics.metadata.api.feed.FeedProvider; import com.thinkbiganalytics.metadata.api.feed.FeedSource; import com.thinkbiganalytics.metadata.modeshape.JcrMetadataAccess; import com.thinkbiganalytics.metadata.modeshape.catalog.dataset.JcrDataSet; import com.thinkbiganalytics.metadata.modeshape.catalog.dataset.JcrDataSetProvider; import com.thinkbiganalytics.metadata.modeshape.catalog.datasource.JcrDataSource; import com.thinkbiganalytics.metadata.modeshape.catalog.datasource.JcrDataSourceProvider; import com.thinkbiganalytics.metadata.modeshape.common.MetadataPaths; import com.thinkbiganalytics.metadata.modeshape.common.mixin.IconableMixin; import com.thinkbiganalytics.metadata.modeshape.common.mixin.PropertiedMixin; import com.thinkbiganalytics.metadata.modeshape.common.mixin.SystemEntityMixin; import com.thinkbiganalytics.metadata.modeshape.datasource.JcrDatasource; import com.thinkbiganalytics.metadata.modeshape.datasource.JcrDerivedDatasource; import com.thinkbiganalytics.metadata.modeshape.datasource.JcrJdbcDatasourceDetails; import com.thinkbiganalytics.metadata.modeshape.datasource.JcrUserDatasource; import com.thinkbiganalytics.metadata.modeshape.feed.JcrFeed; import com.thinkbiganalytics.metadata.modeshape.feed.JcrFeedSource; import com.thinkbiganalytics.metadata.modeshape.security.action.JcrAllowedActions; import com.thinkbiganalytics.metadata.modeshape.security.action.JcrAllowedEntityActionsProvider; import com.thinkbiganalytics.metadata.modeshape.support.JcrPropertyUtil; import com.thinkbiganalytics.metadata.modeshape.support.JcrUtil; import com.thinkbiganalytics.security.AccessController; import com.thinkbiganalytics.security.action.AllowedActions; import com.thinkbiganalytics.security.role.SecurityRole; import com.thinkbiganalytics.security.role.SecurityRoleProvider; import com.thinkbiganalytics.server.upgrade.KyloUpgrader; import com.thinkbiganalytics.server.upgrade.UpgradeAction; import com.thinkbiganalytics.server.upgrade.UpgradeException; import org.modeshape.jcr.api.Workspace; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; import java.nio.file.Path; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import javax.inject.Inject; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.nodetype.NodeType; import javax.jcr.nodetype.NodeTypeManager; /** * This action defines the permissions and roles introduce for the catalog in Kylo v0.10.0. */ @Component("migrateLegacyDatasourcesUpgradeAction0.10.0") @Profile(KyloUpgrader.KYLO_UPGRADE) public class MigrateLegacyDatasourcesUpgradeAction implements UpgradeAction { private static final Logger log = LoggerFactory.getLogger(MigrateLegacyDatasourcesUpgradeAction.class); @Inject private DatasourceProvider legacyProvider; @Inject private ConnectorPluginManager pluginManager; @Inject private FeedProvider feedProvider; @Inject private ConnectorProvider connectorProvider; @Inject private JcrDataSourceProvider dataSourceProvider; @Inject private JcrDataSetProvider dataSetProvider; @Inject private JcrAllowedEntityActionsProvider actionsProvider; @Inject private SecurityRoleProvider roleProvider; @Inject private AccessController accessController; @Inject private NifiControllerServiceProperties controllerServiceProperties; @Override public boolean isTargetVersion(KyloVersion version) { return version.matches("0.10", "0", ""); } @Override public void upgradeTo(final KyloVersion targetVersion) { log.info("Setting up catalog access control: {}", targetVersion); try { NodeTypeManager typeMgr = JcrMetadataAccess.getActiveSession().getWorkspace().getNodeTypeManager(); NodeType dataSourceType = typeMgr.getNodeType("tba:DataSource"); Connector conn = pluginManager.getPlugin("jdbc") .flatMap(plugin -> connectorProvider.findByPlugin(plugin.getId())) .orElseThrow(() -> new IllegalStateException("No JDBC connector found")); legacyProvider.getDatasources().stream() .map(JcrDatasource.class::cast) .map(JcrDatasource::getNode) .filter(node -> JcrUtil.isNodeType(node, "tba:userDatasource")) .filter(node -> JcrUtil.isNodeType(JcrUtil.getNode(node, "tba:details"), "tba:jdbcDatasourceDetails")) .forEach(jdbcNode -> { try { // Move the legacy datasource node to a temporary parent that doesn't have any constraints (the catalog folder). Node tmpParent = JcrUtil.getNode(JcrUtil.getRootNode(jdbcNode), "metadata/catalog"); String dsSystemName = dataSourceProvider.generateSystemName(JcrUtil.getName(jdbcNode)); Path catDsPath = MetadataPaths.dataSourcePath(conn.getSystemName(), dsSystemName); Node catDsNode = JcrUtil.moveNode(jdbcNode, JcrUtil.path(tmpParent.getPath()).resolve(dsSystemName)); // Wrap the node as a legacy UserDataSource and collect its properties. JcrUserDatasource legacyDs = JcrUtil.getJcrObject(catDsNode, JcrUserDatasource.class); Set<? extends JcrFeed> referencingFeeds = legacyDs.getFeedSources().stream() .map(FeedSource::getFeed) .map(JcrFeed.class::cast) .collect(Collectors.toSet()); AtomicReference<String> controllerServiceId = new AtomicReference<>(); AtomicReference<String> password = new AtomicReference<>(); legacyDs.getDetails() .filter(JcrJdbcDatasourceDetails.class::isInstance) .map(JcrJdbcDatasourceDetails.class::cast) .ifPresent(details -> { controllerServiceId.set(details.getControllerServiceId().orElse(null)); password.set("{cipher}" + details.getPassword()); }); if (this.accessController.isEntityAccessControlled()) { legacyDs.disableAccessControl(legacyDs.getOwner()); } // Convert the legacy type into the catalog type. JcrDataSource catDs = convertToDataSource(catDsNode, catDsPath, dataSourceType, controllerServiceId.get(), password.get()); linkDataSets(catDs, referencingFeeds); if (this.accessController.isEntityAccessControlled()) { List<SecurityRole> roles = roleProvider.getEntityRoles(SecurityRole.DATASOURCE); actionsProvider.getAvailableActions(AllowedActions.DATASOURCE) .ifPresent(actions -> catDs.enableAccessControl((JcrAllowedActions) actions, legacyDs.getOwner(), roles)); } } catch (RepositoryException e) { throw new UpgradeException("Failed to migrate legacy datasources", e); } }); } catch (IllegalStateException | RepositoryException e) { throw new UpgradeException("Failed to migrate legacy datasources", e); } } private JcrDataSource convertToDataSource(Node catDsNode, Path targetPath, NodeType dataSourceType, String controllerServiceId, String password) { return this.controllerServiceProperties.parseControllerService(controllerServiceId) .map(props -> { try { NodeType[] legacyMixins = catDsNode.getMixinNodeTypes(); NodeType[] catMixins = Arrays.stream(dataSourceType.getDeclaredSupertypes()) .filter(NodeType::isMixin) .toArray(NodeType[]::new); // Strip off legacy nodes/properties JcrPropertyUtil.setProperty(catDsNode, IconableMixin.ICON, null); JcrPropertyUtil.setProperty(catDsNode, IconableMixin.ICON_COLOR, null); JcrPropertyUtil.setProperty(catDsNode, SystemEntityMixin.SYSTEM_NAME, null); JcrPropertyUtil.setProperty(catDsNode, JcrUserDatasource.SOURCE_NAME, null); JcrPropertyUtil.setProperty(catDsNode, JcrUserDatasource.TYPE, null); JcrUtil.removeNode(catDsNode, PropertiedMixin.PROPERTIES_NAME); JcrUtil.removeNode(catDsNode, JcrUserDatasource.DETAILS); JcrUtil.removeMixins(catDsNode, legacyMixins); catDsNode.setPrimaryType("tba:DataSource"); JcrUtil.addMixins(catDsNode, catMixins); JcrUtil.getOrCreateNode(catDsNode, "tba:sparkParams", "tba:DataSetSparkParams"); JcrDataSource catDs = JcrUtil.getJcrObject(catDsNode, JcrDataSource.class); DataSetSparkParameters sparProps = catDs.getSparkParameters(); catDs.setNifiControllerServiceId(controllerServiceId); sparProps.addOption("password", password); sparProps.setFormat("jdbc"); sparProps.addOption("url", props.getUrl()); sparProps.addOption("driver", props.getDriverClassName()); sparProps.addOption("user", props.getUser()); catDsNode.getSession().save(); Node movedNode = JcrUtil.moveNode(catDsNode, targetPath); return new JcrDataSource(movedNode); } catch (RepositoryException e) { throw new UpgradeException("Failed to migrate legacy datasources", e); } }) .orElseThrow(() -> new UpgradeException("Unable to obtain controller service properties for service with ID {} - NiFi must be available during upgrade")); } private void linkDataSets(JcrDataSource catDs, Set<? extends JcrFeed> referencingFeeds) { referencingFeeds.stream() .forEach(feed -> { String title = catDs.getTitle(); feed.getSources().stream() .map(JcrFeedSource.class::cast) .forEach(source -> { source.getDatasource() .map(JcrDatasource.class::cast) .ifPresent(datasource -> { // There will be a derived datasource of with a connection name matching the new data datasource // for each table. Create a data set from each table name. if (datasource instanceof JcrDerivedDatasource) { JcrDerivedDatasource dds = (JcrDerivedDatasource) datasource; if (dds.getProperty("tba:datasourceType").equals("DatabaseDatasource") && title.equals(dds.getAllProperties().get("Database Connection"))) { Map<String, Object> allProps = dds.getAllProperties(); if (allProps.containsKey("Table")) { String tableName = allProps.get("Table").toString(); JcrDataSet dataSet = (JcrDataSet) dataSetProvider.build(catDs.getId()) .title(tableName) .addOption("dbtable", tableName) .build(); feed.removeFeedSource(source); feedProvider.ensureFeedSource(feed.getId(), dataSet.getId()); } else { log.warn("No table name found in data source: " + dds); } } // Since we've converted a legacy datasource into a category data source with the same ID, // there will still be a reference to it in one of the FeedSources as a legacy datasource. // When we find it then remove that FeedSource. } else if (datasource.getNode().equals(catDs.getNode())) { feed.removeFeedSource(source); } }); }); }); } }
services/upgrade-service/src/main/java/com/thinkbiganalytics/metadata/upgrade/v0_10_0/MigrateLegacyDatasourcesUpgradeAction.java
package com.thinkbiganalytics.metadata.upgrade.v0_10_0; /*- * #%L * kylo-upgrade-service * %% * Copyright (C) 2017 ThinkBig Analytics * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.thinkbiganalytics.KyloVersion; import com.thinkbiganalytics.feedmgr.nifi.NifiControllerServiceProperties; import com.thinkbiganalytics.kylo.catalog.ConnectorPluginManager; import com.thinkbiganalytics.metadata.api.catalog.Connector; import com.thinkbiganalytics.metadata.api.catalog.ConnectorProvider; import com.thinkbiganalytics.metadata.api.catalog.DataSetSparkParameters; import com.thinkbiganalytics.metadata.api.datasource.DatasourceProvider; import com.thinkbiganalytics.metadata.api.feed.FeedProvider; import com.thinkbiganalytics.metadata.api.feed.FeedSource; import com.thinkbiganalytics.metadata.modeshape.JcrMetadataAccess; import com.thinkbiganalytics.metadata.modeshape.catalog.dataset.JcrDataSet; import com.thinkbiganalytics.metadata.modeshape.catalog.dataset.JcrDataSetProvider; import com.thinkbiganalytics.metadata.modeshape.catalog.datasource.JcrDataSource; import com.thinkbiganalytics.metadata.modeshape.catalog.datasource.JcrDataSourceProvider; import com.thinkbiganalytics.metadata.modeshape.common.MetadataPaths; import com.thinkbiganalytics.metadata.modeshape.common.mixin.IconableMixin; import com.thinkbiganalytics.metadata.modeshape.common.mixin.PropertiedMixin; import com.thinkbiganalytics.metadata.modeshape.common.mixin.SystemEntityMixin; import com.thinkbiganalytics.metadata.modeshape.datasource.JcrDatasource; import com.thinkbiganalytics.metadata.modeshape.datasource.JcrDerivedDatasource; import com.thinkbiganalytics.metadata.modeshape.datasource.JcrJdbcDatasourceDetails; import com.thinkbiganalytics.metadata.modeshape.datasource.JcrUserDatasource; import com.thinkbiganalytics.metadata.modeshape.feed.JcrFeed; import com.thinkbiganalytics.metadata.modeshape.feed.JcrFeedSource; import com.thinkbiganalytics.metadata.modeshape.security.action.JcrAllowedActions; import com.thinkbiganalytics.metadata.modeshape.security.action.JcrAllowedEntityActionsProvider; import com.thinkbiganalytics.metadata.modeshape.support.JcrPropertyUtil; import com.thinkbiganalytics.metadata.modeshape.support.JcrUtil; import com.thinkbiganalytics.security.AccessController; import com.thinkbiganalytics.security.action.AllowedActions; import com.thinkbiganalytics.security.role.SecurityRole; import com.thinkbiganalytics.security.role.SecurityRoleProvider; import com.thinkbiganalytics.server.upgrade.KyloUpgrader; import com.thinkbiganalytics.server.upgrade.UpgradeAction; import com.thinkbiganalytics.server.upgrade.UpgradeException; import org.modeshape.jcr.api.Workspace; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; import java.nio.file.Path; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import javax.inject.Inject; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.nodetype.NodeType; import javax.jcr.nodetype.NodeTypeManager; /** * This action defines the permissions and roles introduce for the catalog in Kylo v0.10.0. */ @Component("migrateLegacyDatasourcesUpgradeAction0.10.0") @Profile(KyloUpgrader.KYLO_UPGRADE) public class MigrateLegacyDatasourcesUpgradeAction implements UpgradeAction { private static final Logger log = LoggerFactory.getLogger(MigrateLegacyDatasourcesUpgradeAction.class); @Inject private DatasourceProvider legacyProvider; @Inject private ConnectorPluginManager pluginManager; @Inject private FeedProvider feedProvider; @Inject private ConnectorProvider connectorProvider; @Inject private JcrDataSourceProvider dataSourceProvider; @Inject private JcrDataSetProvider dataSetProvider; @Inject private JcrAllowedEntityActionsProvider actionsProvider; @Inject private SecurityRoleProvider roleProvider; @Inject private AccessController accessController; @Inject private NifiControllerServiceProperties controllerServiceProperties; @Override public boolean isTargetVersion(KyloVersion version) { return version.matches("0.10", "0", ""); } @Override public void upgradeTo(final KyloVersion targetVersion) { log.info("Setting up catalog access control: {}", targetVersion); try { NodeTypeManager typeMgr = JcrMetadataAccess.getActiveSession().getWorkspace().getNodeTypeManager(); NodeType dataSourceType = typeMgr.getNodeType("tba:DataSource"); Connector conn = pluginManager.getPlugin("jdbc") .flatMap(plugin -> connectorProvider.findByPlugin(plugin.getId())) .orElseThrow(() -> new IllegalStateException("No JDBC connector found")); legacyProvider.getDatasources().stream() .map(JcrDatasource.class::cast) .map(JcrDatasource::getNode) .filter(node -> JcrUtil.isNodeType(node, "tba:userDatasource")) .filter(node -> JcrUtil.isNodeType(JcrUtil.getNode(node, "tba:details"), "tba:jdbcDatasourceDetails")) .forEach(jdbcNode -> { try { // Move the legacy datasource node to a temporary parent that doesn't have any constraints (the catalog folder). Node tmpParent = JcrUtil.getNode(JcrUtil.getRootNode(jdbcNode), "metadata/catalog"); String dsSystemName = dataSourceProvider.generateSystemName(JcrUtil.getName(jdbcNode)); Path catDsPath = MetadataPaths.dataSourcePath(conn.getSystemName(), dsSystemName); Node catDsNode = JcrUtil.moveNode(jdbcNode, JcrUtil.path(tmpParent.getPath()).resolve(dsSystemName)); // Wrap the node as a legacy UserDataSource and collect its properties. JcrUserDatasource legacyDs = JcrUtil.getJcrObject(catDsNode, JcrUserDatasource.class); Set<? extends JcrFeed> referencingFeeds = legacyDs.getFeedSources().stream() .map(FeedSource::getFeed) .map(JcrFeed.class::cast) .collect(Collectors.toSet()); AtomicReference<String> controllerServiceId = new AtomicReference<>(); AtomicReference<String> password = new AtomicReference<>(); legacyDs.getDetails() .filter(JcrJdbcDatasourceDetails.class::isInstance) .map(JcrJdbcDatasourceDetails.class::cast) .ifPresent(details -> { controllerServiceId.set(details.getControllerServiceId().orElse(null)); password.set("{cypher}" + details.getPassword()); }); if (this.accessController.isEntityAccessControlled()) { legacyDs.disableAccessControl(legacyDs.getOwner()); } // Convert the legacy type into the catalog type. JcrDataSource catDs = convertToDataSource(catDsNode, catDsPath, dataSourceType, controllerServiceId.get(), password.get()); linkDataSets(catDs, referencingFeeds); if (this.accessController.isEntityAccessControlled()) { List<SecurityRole> roles = roleProvider.getEntityRoles(SecurityRole.DATASOURCE); actionsProvider.getAvailableActions(AllowedActions.DATASOURCE) .ifPresent(actions -> catDs.enableAccessControl((JcrAllowedActions) actions, legacyDs.getOwner(), roles)); } } catch (RepositoryException e) { throw new UpgradeException("Failed to migrate legacy datasources", e); } }); } catch (IllegalStateException | RepositoryException e) { throw new UpgradeException("Failed to migrate legacy datasources", e); } } private JcrDataSource convertToDataSource(Node catDsNode, Path targetPath, NodeType dataSourceType, String controllerServiceId, String password) { return this.controllerServiceProperties.parseControllerService(controllerServiceId) .map(props -> { try { NodeType[] legacyMixins = catDsNode.getMixinNodeTypes(); NodeType[] catMixins = Arrays.stream(dataSourceType.getDeclaredSupertypes()) .filter(NodeType::isMixin) .toArray(NodeType[]::new); // Strip off legacy nodes/properties JcrPropertyUtil.setProperty(catDsNode, IconableMixin.ICON, null); JcrPropertyUtil.setProperty(catDsNode, IconableMixin.ICON_COLOR, null); JcrPropertyUtil.setProperty(catDsNode, SystemEntityMixin.SYSTEM_NAME, null); JcrPropertyUtil.setProperty(catDsNode, JcrUserDatasource.SOURCE_NAME, null); JcrPropertyUtil.setProperty(catDsNode, JcrUserDatasource.TYPE, null); JcrUtil.removeNode(catDsNode, PropertiedMixin.PROPERTIES_NAME); JcrUtil.removeNode(catDsNode, JcrUserDatasource.DETAILS); JcrUtil.removeMixins(catDsNode, legacyMixins); catDsNode.setPrimaryType("tba:DataSource"); JcrUtil.addMixins(catDsNode, catMixins); JcrUtil.getOrCreateNode(catDsNode, "tba:sparkParams", "tba:DataSetSparkParams"); JcrDataSource catDs = JcrUtil.getJcrObject(catDsNode, JcrDataSource.class); DataSetSparkParameters sparProps = catDs.getSparkParameters(); catDs.setNifiControllerServiceId(controllerServiceId); sparProps.addOption("password", password); sparProps.setFormat("jdbc"); sparProps.addOption("url", props.getUrl()); sparProps.addOption("driver", props.getDriverClassName()); sparProps.addOption("user", props.getUser()); catDsNode.getSession().save(); Node movedNode = JcrUtil.moveNode(catDsNode, targetPath); return new JcrDataSource(movedNode); } catch (RepositoryException e) { throw new UpgradeException("Failed to migrate legacy datasources", e); } }) .orElseThrow(() -> new UpgradeException("Unable to obtain controller service properties for service with ID {} - NiFi must be available during upgrade")); } private void linkDataSets(JcrDataSource catDs, Set<? extends JcrFeed> referencingFeeds) { referencingFeeds.stream() .forEach(feed -> { String title = catDs.getTitle(); feed.getSources().stream() .map(JcrFeedSource.class::cast) .forEach(source -> { source.getDatasource() .map(JcrDatasource.class::cast) .ifPresent(datasource -> { // There will be a derived datasource of with a connection name matching the new data datasource // for each table. Create a data set from each table name. if (datasource instanceof JcrDerivedDatasource) { JcrDerivedDatasource dds = (JcrDerivedDatasource) datasource; if (dds.getProperty("tba:datasourceType").equals("DatabaseDatasource") && title.equals(dds.getAllProperties().get("Database Connection"))) { Map<String, Object> allProps = dds.getAllProperties(); if (allProps.containsKey("Table")) { String tableName = allProps.get("Table").toString(); JcrDataSet dataSet = (JcrDataSet) dataSetProvider.build(catDs.getId()) .title(tableName) .addOption("dbtable", tableName) .build(); feed.removeFeedSource(source); feedProvider.ensureFeedSource(feed.getId(), dataSet.getId()); } else { log.warn("No table name found in data source: " + dds); } } // Since we've converted a legacy datasource into a category data source with the same ID, // there will still be a reference to it in one of the FeedSources as a legacy datasource. // When we find it then remove that FeedSource. } else if (datasource.getNode().equals(catDs.getNode())) { feed.removeFeedSource(source); } }); }); }); } }
Help fix KYLO-3068
services/upgrade-service/src/main/java/com/thinkbiganalytics/metadata/upgrade/v0_10_0/MigrateLegacyDatasourcesUpgradeAction.java
Help fix KYLO-3068
<ide><path>ervices/upgrade-service/src/main/java/com/thinkbiganalytics/metadata/upgrade/v0_10_0/MigrateLegacyDatasourcesUpgradeAction.java <ide> .map(JcrJdbcDatasourceDetails.class::cast) <ide> .ifPresent(details -> { <ide> controllerServiceId.set(details.getControllerServiceId().orElse(null)); <del> password.set("{cypher}" + details.getPassword()); <add> password.set("{cipher}" + details.getPassword()); <ide> }); <ide> <ide> if (this.accessController.isEntityAccessControlled()) {
Java
apache-2.0
2e3694c61f09e162e2012ac1a5fb1d1b45f7f605
0
asoldano/wss4j,apache/wss4j,clibois/wss4j,apache/wss4j,asoldano/wss4j,jimma/wss4j,jimma/wss4j,clibois/wss4j
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.wss4j.dom.processor; import java.security.Key; import java.security.NoSuchProviderException; import java.security.Principal; import java.security.PublicKey; import java.security.cert.X509Certificate; import java.security.spec.AlgorithmParameterSpec; import java.text.DateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.crypto.MarshalException; import javax.xml.crypto.NodeSetData; import javax.xml.crypto.XMLStructure; import javax.xml.crypto.dom.DOMStructure; import javax.xml.crypto.dsig.Manifest; import javax.xml.crypto.dsig.Reference; import javax.xml.crypto.dsig.SignedInfo; import javax.xml.crypto.dsig.Transform; import javax.xml.crypto.dsig.XMLObject; import javax.xml.crypto.dsig.XMLSignature; import javax.xml.crypto.dsig.XMLSignatureFactory; import javax.xml.crypto.dsig.XMLValidateContext; import javax.xml.crypto.dsig.dom.DOMValidateContext; import javax.xml.crypto.dsig.keyinfo.KeyInfo; import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; import javax.xml.crypto.dsig.keyinfo.KeyValue; import javax.xml.crypto.dsig.spec.ExcC14NParameterSpec; import javax.xml.crypto.dsig.spec.HMACParameterSpec; import org.apache.wss4j.common.principal.PublicKeyPrincipalImpl; import org.apache.wss4j.common.principal.UsernameTokenPrincipal; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.apache.wss4j.common.bsp.BSPRule; import org.apache.wss4j.common.cache.ReplayCache; import org.apache.wss4j.common.crypto.AlgorithmSuite; import org.apache.wss4j.common.crypto.AlgorithmSuiteValidator; import org.apache.wss4j.common.crypto.Crypto; import org.apache.wss4j.common.crypto.CryptoType; import org.apache.wss4j.common.ext.WSSecurityException; import org.apache.wss4j.common.principal.WSDerivedKeyTokenPrincipal; import org.apache.wss4j.common.util.KeyUtils; import org.apache.wss4j.dom.WSConstants; import org.apache.wss4j.dom.WSDataRef; import org.apache.wss4j.dom.WSDocInfo; import org.apache.wss4j.dom.WSSecurityEngine; import org.apache.wss4j.dom.WSSecurityEngineResult; import org.apache.wss4j.dom.bsp.BSPEnforcer; import org.apache.wss4j.dom.handler.RequestData; import org.apache.wss4j.dom.message.CallbackLookup; import org.apache.wss4j.dom.message.DOMCallbackLookup; import org.apache.wss4j.dom.message.token.SecurityTokenReference; import org.apache.wss4j.dom.message.token.Timestamp; import org.apache.wss4j.dom.str.STRParser; import org.apache.wss4j.dom.str.STRParser.REFERENCE_TYPE; import org.apache.wss4j.dom.str.SignatureSTRParser; import org.apache.wss4j.dom.transform.STRTransform; import org.apache.wss4j.dom.transform.STRTransformUtil; import org.apache.wss4j.dom.util.WSSecurityUtil; import org.apache.wss4j.dom.util.XmlSchemaDateFormat; import org.apache.wss4j.dom.validate.Credential; import org.apache.wss4j.dom.validate.Validator; public class SignatureProcessor implements Processor { private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(SignatureProcessor.class); private XMLSignatureFactory signatureFactory; private KeyInfoFactory keyInfoFactory; public SignatureProcessor() { // Try to install the Santuario Provider - fall back to the JDK provider if this does // not work try { signatureFactory = XMLSignatureFactory.getInstance("DOM", "ApacheXMLDSig"); } catch (NoSuchProviderException ex) { signatureFactory = XMLSignatureFactory.getInstance("DOM"); } try { keyInfoFactory = KeyInfoFactory.getInstance("DOM", "ApacheXMLDSig"); } catch (NoSuchProviderException ex) { keyInfoFactory = KeyInfoFactory.getInstance("DOM"); } } public List<WSSecurityEngineResult> handleToken( Element elem, RequestData data, WSDocInfo wsDocInfo ) throws WSSecurityException { if (LOG.isDebugEnabled()) { LOG.debug("Found signature element"); } Element keyInfoElement = WSSecurityUtil.getDirectChildElement( elem, "KeyInfo", WSConstants.SIG_NS ); X509Certificate[] certs = null; Principal principal = null; PublicKey publicKey = null; byte[] secretKey = null; String signatureMethod = getSignatureMethod(elem); REFERENCE_TYPE referenceType = null; Validator validator = data.getValidator(WSSecurityEngine.SIGNATURE); if (keyInfoElement == null) { certs = getDefaultCerts(data.getSigVerCrypto()); principal = certs[0].getSubjectX500Principal(); } else { int result = 0; Node node = keyInfoElement.getFirstChild(); Element child = null; while (node != null) { if (Node.ELEMENT_NODE == node.getNodeType()) { result++; child = (Element)node; } node = node.getNextSibling(); } if (result != 1) { data.getBSPEnforcer().handleBSPRule(BSPRule.R5402); } if (!(SecurityTokenReference.SECURITY_TOKEN_REFERENCE.equals(child.getLocalName()) && WSConstants.WSSE_NS.equals(child.getNamespaceURI()))) { data.getBSPEnforcer().handleBSPRule(BSPRule.R5417); publicKey = parseKeyValue(keyInfoElement); if (validator != null) { Credential credential = new Credential(); credential.setPublicKey(publicKey); principal = new PublicKeyPrincipalImpl(publicKey); credential.setPrincipal(principal); validator.validate(credential, data); } } else { STRParser strParser = new SignatureSTRParser(); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put(SignatureSTRParser.SIGNATURE_METHOD, signatureMethod); strParser.parseSecurityTokenReference( child, data, wsDocInfo, parameters ); principal = strParser.getPrincipal(); certs = strParser.getCertificates(); publicKey = strParser.getPublicKey(); secretKey = strParser.getSecretKey(); referenceType = strParser.getCertificatesReferenceType(); boolean trusted = strParser.isTrustedCredential(); if (trusted && LOG.isDebugEnabled()) { LOG.debug("Direct Trust for SAML/BST credential"); } if (!trusted && (publicKey != null || certs != null) && validator != null) { Credential credential = new Credential(); credential.setPublicKey(publicKey); credential.setCertificates(certs); credential.setPrincipal(principal); validator.validate(credential, data); } } } // // Check that we have a certificate, a public key or a secret key with which to // perform signature verification // if ((certs == null || certs.length == 0 || certs[0] == null) && secretKey == null && publicKey == null) { throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK); } // Check for compliance against the defined AlgorithmSuite AlgorithmSuite algorithmSuite = data.getAlgorithmSuite(); if (algorithmSuite != null) { AlgorithmSuiteValidator algorithmSuiteValidator = new AlgorithmSuiteValidator(algorithmSuite); if (principal instanceof WSDerivedKeyTokenPrincipal) { algorithmSuiteValidator.checkDerivedKeyAlgorithm( ((WSDerivedKeyTokenPrincipal)principal).getAlgorithm() ); algorithmSuiteValidator.checkSignatureDerivedKeyLength( ((WSDerivedKeyTokenPrincipal)principal).getLength() ); } else { Key key = null; if (certs != null && certs[0] != null) { key = certs[0].getPublicKey(); } else if (publicKey != null) { key = publicKey; } if (key instanceof PublicKey) { algorithmSuiteValidator.checkAsymmetricKeyLength((PublicKey)key); } else { algorithmSuiteValidator.checkSymmetricKeyLength(secretKey.length); } } } XMLSignature xmlSignature = verifyXMLSignature(elem, certs, publicKey, secretKey, signatureMethod, data, wsDocInfo); byte[] signatureValue = xmlSignature.getSignatureValue().getValue(); String c14nMethod = xmlSignature.getSignedInfo().getCanonicalizationMethod().getAlgorithm(); List<WSDataRef> dataRefs = buildProtectedRefs( elem.getOwnerDocument(), xmlSignature.getSignedInfo(), data, wsDocInfo ); if (dataRefs.size() == 0) { throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK); } int actionPerformed = WSConstants.SIGN; if (principal instanceof UsernameTokenPrincipal) { actionPerformed = WSConstants.UT_SIGN; } WSSecurityEngineResult result = new WSSecurityEngineResult( actionPerformed, principal, certs, dataRefs, signatureValue); result.put(WSSecurityEngineResult.TAG_SIGNATURE_METHOD, signatureMethod); result.put(WSSecurityEngineResult.TAG_CANONICALIZATION_METHOD, c14nMethod); result.put(WSSecurityEngineResult.TAG_ID, elem.getAttributeNS(null, "Id")); result.put(WSSecurityEngineResult.TAG_SECRET, secretKey); result.put(WSSecurityEngineResult.TAG_PUBLIC_KEY, publicKey); result.put(WSSecurityEngineResult.TAG_X509_REFERENCE_TYPE, referenceType); if (validator != null) { result.put(WSSecurityEngineResult.TAG_VALIDATED_TOKEN, Boolean.TRUE); } wsDocInfo.addResult(result); wsDocInfo.addTokenElement(elem); return java.util.Collections.singletonList(result); } /** * Get the default certificates from the KeyStore * @param crypto The Crypto object containing the default alias * @return The default certificates * @throws WSSecurityException */ private X509Certificate[] getDefaultCerts( Crypto crypto ) throws WSSecurityException { if (crypto == null) { throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noSigCryptoFile"); } if (crypto.getDefaultX509Identifier() != null) { CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(crypto.getDefaultX509Identifier()); return crypto.getX509Certificates(cryptoType); } else { throw new WSSecurityException( WSSecurityException.ErrorCode.INVALID_SECURITY, "unsupportedKeyInfo" ); } } private PublicKey parseKeyValue( Element keyInfoElement ) throws WSSecurityException { KeyValue keyValue = null; try { // // Look for a KeyValue object // keyValue = getKeyValue(keyInfoElement); } catch (MarshalException ex) { throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK, ex); } if (keyValue != null) { try { // // Look for a Public Key in Key Value // return keyValue.getPublicKey(); } catch (java.security.KeyException ex) { LOG.error(ex.getMessage(), ex); throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK, ex); } } else { throw new WSSecurityException( WSSecurityException.ErrorCode.INVALID_SECURITY, "unsupportedKeyInfo" ); } } /** * Get the KeyValue object from the KeyInfo DOM element if it exists */ private KeyValue getKeyValue( Element keyInfoElement ) throws MarshalException { XMLStructure keyInfoStructure = new DOMStructure(keyInfoElement); KeyInfo keyInfo = keyInfoFactory.unmarshalKeyInfo(keyInfoStructure); List<?> list = keyInfo.getContent(); for (int i = 0; i < list.size(); i++) { XMLStructure xmlStructure = (XMLStructure) list.get(i); if (xmlStructure instanceof KeyValue) { return (KeyValue)xmlStructure; } } return null; } /** * Verify the WS-Security signature. * * The functions at first checks if then <code>KeyInfo</code> that is * contained in the signature contains standard X509 data. If yes then * get the certificate data via the standard <code>KeyInfo</code> methods. * * Otherwise, if the <code>KeyInfo</code> info does not contain X509 data, check * if we can find a <code>wsse:SecurityTokenReference</code> element. If yes, the next * step is to check how to get the certificate. Two methods are currently supported * here: * <ul> * <li> A URI reference to a binary security token contained in the <code>wsse:Security * </code> header. If the dereferenced token is * of the correct type the contained certificate is extracted. * </li> * <li> Issuer name an serial number of the certificate. In this case the method * looks up the certificate in the keystore via the <code>crypto</code> parameter. * </li> * </ul> * * @param elem the XMLSignature DOM Element. * @param crypto the object that implements the access to the keystore and the * handling of certificates. * @param protectedRefs A list of (references) to the signed elements * @param cb CallbackHandler instance to extract key passwords * @return the subject principal of the validated X509 certificate (the * authenticated subject). The calling function may use this * principal for further authentication or authorization. * @throws WSSecurityException */ private XMLSignature verifyXMLSignature( Element elem, X509Certificate[] certs, PublicKey publicKey, byte[] secretKey, String signatureMethod, RequestData data, WSDocInfo wsDocInfo ) throws WSSecurityException { if (LOG.isDebugEnabled()) { LOG.debug("Verify XML Signature"); } // // Perform the signature verification and build up a List of elements that the // signature refers to // Key key = null; if (certs != null && certs[0] != null) { key = certs[0].getPublicKey(); } else if (publicKey != null) { key = publicKey; } else { key = KeyUtils.prepareSecretKey(signatureMethod, secretKey); } XMLValidateContext context = new DOMValidateContext(key, elem); context.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE); context.setProperty("org.apache.jcp.xml.dsig.secureValidation", Boolean.TRUE); context.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.TRUE); context.setProperty(STRTransform.TRANSFORM_WS_DOC_INFO, wsDocInfo); try { XMLSignature xmlSignature = signatureFactory.unmarshalXMLSignature(context); checkBSPCompliance(xmlSignature, data.getBSPEnforcer()); // Check for compliance against the defined AlgorithmSuite AlgorithmSuite algorithmSuite = data.getAlgorithmSuite(); if (algorithmSuite != null) { AlgorithmSuiteValidator algorithmSuiteValidator = new AlgorithmSuiteValidator(algorithmSuite); algorithmSuiteValidator.checkSignatureAlgorithms(xmlSignature); } // Test for replay attacks testMessageReplay(elem, xmlSignature.getSignatureValue().getValue(), data, wsDocInfo); setElementsOnContext(xmlSignature, (DOMValidateContext)context, wsDocInfo, elem.getOwnerDocument()); boolean signatureOk = xmlSignature.validate(context); if (signatureOk) { return xmlSignature; } // // Log the exact signature error // if (LOG.isDebugEnabled()) { LOG.debug("XML Signature verification has failed"); boolean signatureValidationCheck = xmlSignature.getSignatureValue().validate(context); LOG.debug("Signature Validation check: " + signatureValidationCheck); java.util.Iterator<?> referenceIterator = xmlSignature.getSignedInfo().getReferences().iterator(); while (referenceIterator.hasNext()) { Reference reference = (Reference)referenceIterator.next(); boolean referenceValidationCheck = reference.validate(context); String id = reference.getId(); if (id == null) { id = reference.getURI(); } LOG.debug("Reference " + id + " check: " + referenceValidationCheck); } } } catch (WSSecurityException ex) { throw ex; } catch (Exception ex) { throw new WSSecurityException( WSSecurityException.ErrorCode.FAILED_CHECK, ex ); } throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK); } /** * Retrieve the Reference elements and set them on the ValidateContext * @param xmlSignature the XMLSignature object to get the references from * @param context the ValidateContext * @param wsDocInfo the WSDocInfo object where tokens are stored * @param doc the owner document from which to find elements * @throws WSSecurityException */ private void setElementsOnContext( XMLSignature xmlSignature, DOMValidateContext context, WSDocInfo wsDocInfo, Document doc ) throws WSSecurityException { java.util.Iterator<?> referenceIterator = xmlSignature.getSignedInfo().getReferences().iterator(); CallbackLookup callbackLookup = wsDocInfo.getCallbackLookup(); if (callbackLookup == null) { callbackLookup = new DOMCallbackLookup(doc); } while (referenceIterator.hasNext()) { Reference reference = (Reference)referenceIterator.next(); String uri = reference.getURI(); Element element = callbackLookup.getAndRegisterElement(uri, null, true, context); if (element == null) { element = wsDocInfo.getTokenElement(uri); if (element != null) { WSSecurityUtil.storeElementInContext(context, element); } } } } /** * Get the signature method algorithm URI from the associated signature element. * @param signatureElement The signature element * @return the signature method URI */ private static String getSignatureMethod( Element signatureElement ) { Element signedInfoElement = WSSecurityUtil.getDirectChildElement( signatureElement, "SignedInfo", WSConstants.SIG_NS ); if (signedInfoElement != null) { Element signatureMethodElement = WSSecurityUtil.getDirectChildElement( signedInfoElement, "SignatureMethod", WSConstants.SIG_NS ); if (signatureMethodElement != null) { return signatureMethodElement.getAttributeNS(null, "Algorithm"); } } return null; } /** * This method digs into the Signature element to get the elements that * this Signature covers. Build the QName of these Elements and return them * to caller * @param doc The owning document * @param signedInfo The SignedInfo object * @param requestData A RequestData instance * @param protectedRefs A list of protected references * @return A list of protected references * @throws WSSecurityException */ private List<WSDataRef> buildProtectedRefs( Document doc, SignedInfo signedInfo, RequestData requestData, WSDocInfo wsDocInfo ) throws WSSecurityException { List<WSDataRef> protectedRefs = new ArrayList<WSDataRef>(); List<?> referencesList = signedInfo.getReferences(); for (int i = 0; i < referencesList.size(); i++) { Reference siRef = (Reference)referencesList.get(i); String uri = siRef.getURI(); if (!"".equals(uri)) { Element se = dereferenceSTR(doc, siRef, requestData, wsDocInfo); // If an STR Transform is not used then just find the cached element if (se == null) { NodeSetData data = (NodeSetData)siRef.getDereferencedData(); if (data != null) { java.util.Iterator<?> iter = data.iterator(); while (iter.hasNext()) { Node n = (Node)iter.next(); if (n instanceof Element) { se = (Element)n; break; } } } } if (se == null) { throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK); } WSDataRef ref = new WSDataRef(); ref.setWsuId(uri); ref.setProtectedElement(se); ref.setAlgorithm(signedInfo.getSignatureMethod().getAlgorithm()); ref.setDigestAlgorithm(siRef.getDigestMethod().getAlgorithm()); // Set the Transform algorithms as well @SuppressWarnings("unchecked") List<Transform> transforms = (List<Transform>)siRef.getTransforms(); List<String> transformAlgorithms = new ArrayList<String>(transforms.size()); for (Transform transform : transforms) { transformAlgorithms.add(transform.getAlgorithm()); } ref.setTransformAlgorithms(transformAlgorithms); ref.setXpath(ReferenceListProcessor.getXPath(se)); protectedRefs.add(ref); } } return protectedRefs; } /** * Check to see if a SecurityTokenReference transform was used, if so then return the * dereferenced element. */ private Element dereferenceSTR( Document doc, Reference siRef, RequestData requestData, WSDocInfo wsDocInfo ) throws WSSecurityException { List<?> transformsList = siRef.getTransforms(); for (int j = 0; j < transformsList.size(); j++) { Transform transform = (Transform)transformsList.get(j); if (STRTransform.TRANSFORM_URI.equals(transform.getAlgorithm())) { NodeSetData data = (NodeSetData)siRef.getDereferencedData(); if (data != null) { java.util.Iterator<?> iter = data.iterator(); Node securityTokenReference = null; while (iter.hasNext()) { Node node = (Node)iter.next(); if ("SecurityTokenReference".equals(node.getLocalName())) { securityTokenReference = node; break; } } if (securityTokenReference != null) { SecurityTokenReference secTokenRef = new SecurityTokenReference( (Element)securityTokenReference, requestData.getBSPEnforcer() ); Element se = STRTransformUtil.dereferenceSTR(doc, secTokenRef, wsDocInfo); if (se != null) { return se; } } } } } return null; } /** * Test for a replayed message. The cache key is the Timestamp Created String and the signature value. * @param signatureElement * @param signatureValue * @param requestData * @param wsDocInfo * @throws WSSecurityException */ private void testMessageReplay( Element signatureElement, byte[] signatureValue, RequestData requestData, WSDocInfo wsDocInfo ) throws WSSecurityException { ReplayCache replayCache = requestData.getTimestampReplayCache(); if (replayCache == null) { return; } // Find the Timestamp List<WSSecurityEngineResult> foundResults = wsDocInfo.getResultsByTag(WSConstants.TS); Timestamp timeStamp = null; if (foundResults.isEmpty()) { // Search for a Timestamp below the Signature Node sibling = signatureElement.getNextSibling(); while (sibling != null) { if (sibling instanceof Element && WSConstants.TIMESTAMP_TOKEN_LN.equals(sibling.getLocalName()) && WSConstants.WSU_NS.equals(sibling.getNamespaceURI())) { timeStamp = new Timestamp((Element)sibling, requestData.getBSPEnforcer()); break; } sibling = sibling.getNextSibling(); } } else { timeStamp = (Timestamp)foundResults.get(0).get(WSSecurityEngineResult.TAG_TIMESTAMP); } if (timeStamp == null) { return; } // Test for replay attacks Date created = timeStamp.getCreated(); DateFormat zulu = new XmlSchemaDateFormat(); String identifier = zulu.format(created) + "" + Arrays.hashCode(signatureValue); if (replayCache.contains(identifier)) { throw new WSSecurityException( WSSecurityException.ErrorCode.INVALID_SECURITY, "invalidTimestamp", "A replay attack has been detected"); } // Store the Timestamp/SignatureValue combination in the cache Date expires = timeStamp.getExpires(); if (expires != null) { Date rightNow = new Date(); long currentTime = rightNow.getTime(); long expiresTime = expires.getTime(); replayCache.add(identifier, 1L + (expiresTime - currentTime) / 1000L); } else { replayCache.add(identifier); } } /** * Check BSP compliance (Note some other checks are done elsewhere in this class) * @throws WSSecurityException */ private void checkBSPCompliance( XMLSignature xmlSignature, BSPEnforcer bspEnforcer ) throws WSSecurityException { // Check for Manifests for (Object object : xmlSignature.getObjects()) { if (object instanceof XMLObject) { XMLObject xmlObject = (XMLObject)object; for (Object xmlStructure : xmlObject.getContent()) { if (xmlStructure instanceof Manifest) { bspEnforcer.handleBSPRule(BSPRule.R5403); } } } } // Check the c14n algorithm String c14nMethod = xmlSignature.getSignedInfo().getCanonicalizationMethod().getAlgorithm(); if (!WSConstants.C14N_EXCL_OMIT_COMMENTS.equals(c14nMethod)) { bspEnforcer.handleBSPRule(BSPRule.R5404); } // Not allowed HMAC OutputLength AlgorithmParameterSpec parameterSpec = xmlSignature.getSignedInfo().getSignatureMethod().getParameterSpec(); if (parameterSpec instanceof HMACParameterSpec) { bspEnforcer.handleBSPRule(BSPRule.R5401); } // Must have exclusive C14N without comments parameterSpec = xmlSignature.getSignedInfo().getCanonicalizationMethod().getParameterSpec(); if (!(parameterSpec instanceof ExcC14NParameterSpec)) { bspEnforcer.handleBSPRule(BSPRule.R5404); } // Check References for (Object refObject : xmlSignature.getSignedInfo().getReferences()) { Reference reference = (Reference)refObject; if (reference.getTransforms().isEmpty()) { bspEnforcer.handleBSPRule(BSPRule.R5416); } for (int i = 0; i < reference.getTransforms().size(); i++) { Transform transform = (Transform)reference.getTransforms().get(i); String algorithm = transform.getAlgorithm(); if (!(WSConstants.C14N_EXCL_OMIT_COMMENTS.equals(algorithm) || STRTransform.TRANSFORM_URI.equals(algorithm) || WSConstants.NS_XMLDSIG_FILTER2.equals(algorithm) || WSConstants.NS_XMLDSIG_ENVELOPED_SIGNATURE.equals(algorithm) || WSConstants.SWA_ATTACHMENT_COMPLETE_SIG_TRANS.equals(algorithm) || WSConstants.SWA_ATTACHMENT_CONTENT_SIG_TRANS.equals(algorithm))) { bspEnforcer.handleBSPRule(BSPRule.R5423); } if (i == (reference.getTransforms().size() - 1) && !(WSConstants.C14N_EXCL_OMIT_COMMENTS.equals(algorithm) || STRTransform.TRANSFORM_URI.equals(algorithm) || WSConstants.SWA_ATTACHMENT_COMPLETE_SIG_TRANS.equals(algorithm) || WSConstants.SWA_ATTACHMENT_CONTENT_SIG_TRANS.equals(algorithm))) { bspEnforcer.handleBSPRule(BSPRule.R5412); } if (WSConstants.C14N_EXCL_OMIT_COMMENTS.equals(algorithm)) { parameterSpec = transform.getParameterSpec(); if (!(parameterSpec instanceof ExcC14NParameterSpec)) { bspEnforcer.handleBSPRule(BSPRule.R5407); } } } } } }
ws-security-dom/src/main/java/org/apache/wss4j/dom/processor/SignatureProcessor.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.wss4j.dom.processor; import java.security.Key; import java.security.NoSuchProviderException; import java.security.Principal; import java.security.PublicKey; import java.security.cert.X509Certificate; import java.security.spec.AlgorithmParameterSpec; import java.text.DateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.crypto.MarshalException; import javax.xml.crypto.NodeSetData; import javax.xml.crypto.XMLStructure; import javax.xml.crypto.dom.DOMStructure; import javax.xml.crypto.dsig.Manifest; import javax.xml.crypto.dsig.Reference; import javax.xml.crypto.dsig.SignedInfo; import javax.xml.crypto.dsig.Transform; import javax.xml.crypto.dsig.XMLObject; import javax.xml.crypto.dsig.XMLSignature; import javax.xml.crypto.dsig.XMLSignatureFactory; import javax.xml.crypto.dsig.XMLValidateContext; import javax.xml.crypto.dsig.dom.DOMValidateContext; import javax.xml.crypto.dsig.keyinfo.KeyInfo; import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; import javax.xml.crypto.dsig.keyinfo.KeyValue; import javax.xml.crypto.dsig.spec.ExcC14NParameterSpec; import javax.xml.crypto.dsig.spec.HMACParameterSpec; import org.apache.wss4j.common.principal.PublicKeyPrincipalImpl; import org.apache.wss4j.common.principal.UsernameTokenPrincipal; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.apache.wss4j.common.bsp.BSPRule; import org.apache.wss4j.common.cache.ReplayCache; import org.apache.wss4j.common.crypto.AlgorithmSuite; import org.apache.wss4j.common.crypto.AlgorithmSuiteValidator; import org.apache.wss4j.common.crypto.Crypto; import org.apache.wss4j.common.crypto.CryptoType; import org.apache.wss4j.common.ext.WSSecurityException; import org.apache.wss4j.common.principal.WSDerivedKeyTokenPrincipal; import org.apache.wss4j.common.util.KeyUtils; import org.apache.wss4j.dom.WSConstants; import org.apache.wss4j.dom.WSDataRef; import org.apache.wss4j.dom.WSDocInfo; import org.apache.wss4j.dom.WSSecurityEngine; import org.apache.wss4j.dom.WSSecurityEngineResult; import org.apache.wss4j.dom.bsp.BSPEnforcer; import org.apache.wss4j.dom.handler.RequestData; import org.apache.wss4j.dom.message.CallbackLookup; import org.apache.wss4j.dom.message.DOMCallbackLookup; import org.apache.wss4j.dom.message.token.SecurityTokenReference; import org.apache.wss4j.dom.message.token.Timestamp; import org.apache.wss4j.dom.str.STRParser; import org.apache.wss4j.dom.str.STRParser.REFERENCE_TYPE; import org.apache.wss4j.dom.str.SignatureSTRParser; import org.apache.wss4j.dom.transform.STRTransform; import org.apache.wss4j.dom.transform.STRTransformUtil; import org.apache.wss4j.dom.util.WSSecurityUtil; import org.apache.wss4j.dom.util.XmlSchemaDateFormat; import org.apache.wss4j.dom.validate.Credential; import org.apache.wss4j.dom.validate.Validator; public class SignatureProcessor implements Processor { private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(SignatureProcessor.class); private XMLSignatureFactory signatureFactory; private KeyInfoFactory keyInfoFactory; public SignatureProcessor() { // Try to install the Santuario Provider - fall back to the JDK provider if this does // not work try { signatureFactory = XMLSignatureFactory.getInstance("DOM", "ApacheXMLDSig"); } catch (NoSuchProviderException ex) { signatureFactory = XMLSignatureFactory.getInstance("DOM"); } try { keyInfoFactory = KeyInfoFactory.getInstance("DOM", "ApacheXMLDSig"); } catch (NoSuchProviderException ex) { keyInfoFactory = KeyInfoFactory.getInstance("DOM"); } } public List<WSSecurityEngineResult> handleToken( Element elem, RequestData data, WSDocInfo wsDocInfo ) throws WSSecurityException { if (LOG.isDebugEnabled()) { LOG.debug("Found signature element"); } Element keyInfoElement = WSSecurityUtil.getDirectChildElement( elem, "KeyInfo", WSConstants.SIG_NS ); X509Certificate[] certs = null; Principal principal = null; PublicKey publicKey = null; byte[] secretKey = null; String signatureMethod = getSignatureMethod(elem); REFERENCE_TYPE referenceType = null; Validator validator = data.getValidator(WSSecurityEngine.SIGNATURE); if (keyInfoElement == null) { certs = getDefaultCerts(data.getSigVerCrypto()); principal = certs[0].getSubjectX500Principal(); } else { int result = 0; Node node = keyInfoElement.getFirstChild(); Element child = null; while (node != null) { if (Node.ELEMENT_NODE == node.getNodeType()) { result++; child = (Element)node; } node = node.getNextSibling(); } if (result != 1) { data.getBSPEnforcer().handleBSPRule(BSPRule.R5402); } if (!(SecurityTokenReference.SECURITY_TOKEN_REFERENCE.equals(child.getLocalName()) && WSConstants.WSSE_NS.equals(child.getNamespaceURI()))) { data.getBSPEnforcer().handleBSPRule(BSPRule.R5417); publicKey = parseKeyValue(keyInfoElement); if (validator != null) { Credential credential = new Credential(); credential.setPublicKey(publicKey); principal = new PublicKeyPrincipalImpl(publicKey); credential.setPrincipal(principal); validator.validate(credential, data); } } else { STRParser strParser = new SignatureSTRParser(); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put(SignatureSTRParser.SIGNATURE_METHOD, signatureMethod); strParser.parseSecurityTokenReference( child, data, wsDocInfo, parameters ); principal = strParser.getPrincipal(); certs = strParser.getCertificates(); publicKey = strParser.getPublicKey(); secretKey = strParser.getSecretKey(); referenceType = strParser.getCertificatesReferenceType(); boolean trusted = strParser.isTrustedCredential(); if (trusted && LOG.isDebugEnabled()) { LOG.debug("Direct Trust for SAML/BST credential"); } if (!trusted && (publicKey != null || certs != null) && validator != null) { Credential credential = new Credential(); credential.setPublicKey(publicKey); credential.setCertificates(certs); credential.setPrincipal(principal); validator.validate(credential, data); } } } // // Check that we have a certificate, a public key or a secret key with which to // perform signature verification // if ((certs == null || certs.length == 0 || certs[0] == null) && secretKey == null && publicKey == null) { throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK); } // Check for compliance against the defined AlgorithmSuite AlgorithmSuite algorithmSuite = data.getAlgorithmSuite(); if (algorithmSuite != null) { AlgorithmSuiteValidator algorithmSuiteValidator = new AlgorithmSuiteValidator(algorithmSuite); if (principal instanceof WSDerivedKeyTokenPrincipal) { algorithmSuiteValidator.checkDerivedKeyAlgorithm( ((WSDerivedKeyTokenPrincipal)principal).getAlgorithm() ); algorithmSuiteValidator.checkSignatureDerivedKeyLength( ((WSDerivedKeyTokenPrincipal)principal).getLength() ); } else { Key key = null; if (certs != null && certs[0] != null) { key = certs[0].getPublicKey(); } else if (publicKey != null) { key = publicKey; } if (key instanceof PublicKey) { algorithmSuiteValidator.checkAsymmetricKeyLength((PublicKey)key); } else { algorithmSuiteValidator.checkSymmetricKeyLength(secretKey.length); } } } XMLSignature xmlSignature = verifyXMLSignature(elem, certs, publicKey, secretKey, signatureMethod, data, wsDocInfo); byte[] signatureValue = xmlSignature.getSignatureValue().getValue(); String c14nMethod = xmlSignature.getSignedInfo().getCanonicalizationMethod().getAlgorithm(); List<WSDataRef> dataRefs = buildProtectedRefs( elem.getOwnerDocument(), xmlSignature.getSignedInfo(), data, wsDocInfo ); if (dataRefs.size() == 0) { throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK); } int actionPerformed = WSConstants.SIGN; if (principal instanceof UsernameTokenPrincipal) { actionPerformed = WSConstants.UT_SIGN; } WSSecurityEngineResult result = new WSSecurityEngineResult( actionPerformed, principal, certs, dataRefs, signatureValue); result.put(WSSecurityEngineResult.TAG_SIGNATURE_METHOD, signatureMethod); result.put(WSSecurityEngineResult.TAG_CANONICALIZATION_METHOD, c14nMethod); result.put(WSSecurityEngineResult.TAG_ID, elem.getAttributeNS(null, "Id")); result.put(WSSecurityEngineResult.TAG_SECRET, secretKey); result.put(WSSecurityEngineResult.TAG_PUBLIC_KEY, publicKey); result.put(WSSecurityEngineResult.TAG_X509_REFERENCE_TYPE, referenceType); if (validator != null) { result.put(WSSecurityEngineResult.TAG_VALIDATED_TOKEN, Boolean.TRUE); } wsDocInfo.addResult(result); wsDocInfo.addTokenElement(elem); return java.util.Collections.singletonList(result); } /** * Get the default certificates from the KeyStore * @param crypto The Crypto object containing the default alias * @return The default certificates * @throws WSSecurityException */ private X509Certificate[] getDefaultCerts( Crypto crypto ) throws WSSecurityException { if (crypto == null) { throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noSigCryptoFile"); } if (crypto.getDefaultX509Identifier() != null) { CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(crypto.getDefaultX509Identifier()); return crypto.getX509Certificates(cryptoType); } else { throw new WSSecurityException( WSSecurityException.ErrorCode.INVALID_SECURITY, "unsupportedKeyInfo" ); } } private PublicKey parseKeyValue( Element keyInfoElement ) throws WSSecurityException { KeyValue keyValue = null; try { // // Look for a KeyValue object // keyValue = getKeyValue(keyInfoElement); } catch (MarshalException ex) { throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK, ex); } if (keyValue != null) { try { // // Look for a Public Key in Key Value // return keyValue.getPublicKey(); } catch (java.security.KeyException ex) { LOG.error(ex.getMessage(), ex); throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK, ex); } } else { throw new WSSecurityException( WSSecurityException.ErrorCode.INVALID_SECURITY, "unsupportedKeyInfo" ); } } /** * Get the KeyValue object from the KeyInfo DOM element if it exists */ private KeyValue getKeyValue( Element keyInfoElement ) throws MarshalException { XMLStructure keyInfoStructure = new DOMStructure(keyInfoElement); KeyInfo keyInfo = keyInfoFactory.unmarshalKeyInfo(keyInfoStructure); List<?> list = keyInfo.getContent(); for (int i = 0; i < list.size(); i++) { XMLStructure xmlStructure = (XMLStructure) list.get(i); if (xmlStructure instanceof KeyValue) { return (KeyValue)xmlStructure; } } return null; } /** * Verify the WS-Security signature. * * The functions at first checks if then <code>KeyInfo</code> that is * contained in the signature contains standard X509 data. If yes then * get the certificate data via the standard <code>KeyInfo</code> methods. * * Otherwise, if the <code>KeyInfo</code> info does not contain X509 data, check * if we can find a <code>wsse:SecurityTokenReference</code> element. If yes, the next * step is to check how to get the certificate. Two methods are currently supported * here: * <ul> * <li> A URI reference to a binary security token contained in the <code>wsse:Security * </code> header. If the dereferenced token is * of the correct type the contained certificate is extracted. * </li> * <li> Issuer name an serial number of the certificate. In this case the method * looks up the certificate in the keystore via the <code>crypto</code> parameter. * </li> * </ul> * * @param elem the XMLSignature DOM Element. * @param crypto the object that implements the access to the keystore and the * handling of certificates. * @param protectedRefs A list of (references) to the signed elements * @param cb CallbackHandler instance to extract key passwords * @return the subject principal of the validated X509 certificate (the * authenticated subject). The calling function may use this * principal for further authentication or authorization. * @throws WSSecurityException */ private XMLSignature verifyXMLSignature( Element elem, X509Certificate[] certs, PublicKey publicKey, byte[] secretKey, String signatureMethod, RequestData data, WSDocInfo wsDocInfo ) throws WSSecurityException { if (LOG.isDebugEnabled()) { LOG.debug("Verify XML Signature"); } // // Perform the signature verification and build up a List of elements that the // signature refers to // Key key = null; if (certs != null && certs[0] != null) { key = certs[0].getPublicKey(); } else if (publicKey != null) { key = publicKey; } else { key = KeyUtils.prepareSecretKey(signatureMethod, secretKey); } XMLValidateContext context = new DOMValidateContext(key, elem); context.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE); context.setProperty("org.apache.jcp.xml.dsig.secureValidation", Boolean.TRUE); context.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.TRUE); context.setProperty(STRTransform.TRANSFORM_WS_DOC_INFO, wsDocInfo); try { XMLSignature xmlSignature = signatureFactory.unmarshalXMLSignature(context); checkBSPCompliance(xmlSignature, data.getBSPEnforcer()); // Check for compliance against the defined AlgorithmSuite AlgorithmSuite algorithmSuite = data.getAlgorithmSuite(); if (algorithmSuite != null) { AlgorithmSuiteValidator algorithmSuiteValidator = new AlgorithmSuiteValidator(algorithmSuite); algorithmSuiteValidator.checkSignatureAlgorithms(xmlSignature); } // Test for replay attacks testMessageReplay(elem, xmlSignature.getSignatureValue().getValue(), data, wsDocInfo); setElementsOnContext(xmlSignature, (DOMValidateContext)context, wsDocInfo, elem.getOwnerDocument()); boolean signatureOk = xmlSignature.validate(context); if (signatureOk) { return xmlSignature; } // // Log the exact signature error // if (LOG.isDebugEnabled()) { LOG.debug("XML Signature verification has failed"); boolean signatureValidationCheck = xmlSignature.getSignatureValue().validate(context); LOG.debug("Signature Validation check: " + signatureValidationCheck); java.util.Iterator<?> referenceIterator = xmlSignature.getSignedInfo().getReferences().iterator(); while (referenceIterator.hasNext()) { Reference reference = (Reference)referenceIterator.next(); boolean referenceValidationCheck = reference.validate(context); String id = reference.getId(); if (id == null) { id = reference.getURI(); } LOG.debug("Reference " + id + " check: " + referenceValidationCheck); } } } catch (WSSecurityException ex) { throw ex; } catch (Exception ex) { throw new WSSecurityException( WSSecurityException.ErrorCode.FAILED_CHECK, ex ); } throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK); } /** * Retrieve the Reference elements and set them on the ValidateContext * @param xmlSignature the XMLSignature object to get the references from * @param context the ValidateContext * @param wsDocInfo the WSDocInfo object where tokens are stored * @param doc the owner document from which to find elements * @throws WSSecurityException */ private void setElementsOnContext( XMLSignature xmlSignature, DOMValidateContext context, WSDocInfo wsDocInfo, Document doc ) throws WSSecurityException { java.util.Iterator<?> referenceIterator = xmlSignature.getSignedInfo().getReferences().iterator(); CallbackLookup callbackLookup = wsDocInfo.getCallbackLookup(); if (callbackLookup == null) { callbackLookup = new DOMCallbackLookup(doc); } while (referenceIterator.hasNext()) { Reference reference = (Reference)referenceIterator.next(); String uri = reference.getURI(); Element element = callbackLookup.getAndRegisterElement(uri, null, true, context); if (element == null) { element = wsDocInfo.getTokenElement(uri); if (element != null) { WSSecurityUtil.storeElementInContext(context, element); } } } } /** * Get the signature method algorithm URI from the associated signature element. * @param signatureElement The signature element * @return the signature method URI */ private static String getSignatureMethod( Element signatureElement ) { Element signedInfoElement = WSSecurityUtil.getDirectChildElement( signatureElement, "SignedInfo", WSConstants.SIG_NS ); if (signedInfoElement != null) { Element signatureMethodElement = WSSecurityUtil.getDirectChildElement( signedInfoElement, "SignatureMethod", WSConstants.SIG_NS ); if (signatureMethodElement != null) { return signatureMethodElement.getAttributeNS(null, "Algorithm"); } } return null; } /** * This method digs into the Signature element to get the elements that * this Signature covers. Build the QName of these Elements and return them * to caller * @param doc The owning document * @param signedInfo The SignedInfo object * @param requestData A RequestData instance * @param protectedRefs A list of protected references * @return A list of protected references * @throws WSSecurityException */ private List<WSDataRef> buildProtectedRefs( Document doc, SignedInfo signedInfo, RequestData requestData, WSDocInfo wsDocInfo ) throws WSSecurityException { List<WSDataRef> protectedRefs = new ArrayList<WSDataRef>(); List<?> referencesList = signedInfo.getReferences(); for (int i = 0; i < referencesList.size(); i++) { Reference siRef = (Reference)referencesList.get(i); String uri = siRef.getURI(); if (!"".equals(uri)) { Element se = dereferenceSTR(doc, siRef, requestData, wsDocInfo); // If an STR Transform is not used then just find the cached element if (se == null) { NodeSetData data = (NodeSetData)siRef.getDereferencedData(); if (data != null) { java.util.Iterator<?> iter = data.iterator(); while (iter.hasNext()) { Node n = (Node)iter.next(); if (n instanceof Element) { se = (Element)n; break; } } } } if (se == null) { throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK); } WSDataRef ref = new WSDataRef(); ref.setWsuId(uri); ref.setProtectedElement(se); ref.setAlgorithm(signedInfo.getSignatureMethod().getAlgorithm()); ref.setDigestAlgorithm(siRef.getDigestMethod().getAlgorithm()); // Set the Transform algorithms as well @SuppressWarnings("unchecked") List<Transform> transforms = (List<Transform>)siRef.getTransforms(); List<String> transformAlgorithms = new ArrayList<String>(transforms.size()); for (Transform transform : transforms) { transformAlgorithms.add(transform.getAlgorithm()); } ref.setTransformAlgorithms(transformAlgorithms); ref.setXpath(ReferenceListProcessor.getXPath(se)); protectedRefs.add(ref); } } return protectedRefs; } /** * Check to see if a SecurityTokenReference transform was used, if so then return the * dereferenced element. */ private Element dereferenceSTR( Document doc, Reference siRef, RequestData requestData, WSDocInfo wsDocInfo ) throws WSSecurityException { List<?> transformsList = siRef.getTransforms(); for (int j = 0; j < transformsList.size(); j++) { Transform transform = (Transform)transformsList.get(j); if (STRTransform.TRANSFORM_URI.equals(transform.getAlgorithm())) { NodeSetData data = (NodeSetData)siRef.getDereferencedData(); if (data != null) { java.util.Iterator<?> iter = data.iterator(); Node securityTokenReference = null; while (iter.hasNext()) { Node node = (Node)iter.next(); if ("SecurityTokenReference".equals(node.getLocalName())) { securityTokenReference = node; break; } } if (securityTokenReference != null) { SecurityTokenReference secTokenRef = new SecurityTokenReference( (Element)securityTokenReference, requestData.getBSPEnforcer() ); Element se = STRTransformUtil.dereferenceSTR(doc, secTokenRef, wsDocInfo); if (se != null) { return se; } } } } } return null; } /** * Test for a replayed message. The cache key is the Timestamp Created String and the signature value. * @param signatureElement * @param signatureValue * @param requestData * @param wsDocInfo * @throws WSSecurityException */ private void testMessageReplay( Element signatureElement, byte[] signatureValue, RequestData requestData, WSDocInfo wsDocInfo ) throws WSSecurityException { ReplayCache replayCache = requestData.getTimestampReplayCache(); if (replayCache == null) { return; } // Find the Timestamp List<WSSecurityEngineResult> foundResults = wsDocInfo.getResultsByTag(WSConstants.TS); Timestamp timeStamp = null; if (foundResults.isEmpty()) { // Search for a Timestamp below the Signature Node sibling = signatureElement.getNextSibling(); while (sibling != null) { if (sibling instanceof Element && WSConstants.TIMESTAMP_TOKEN_LN.equals(sibling.getLocalName()) && WSConstants.WSU_NS.equals(sibling.getNamespaceURI())) { timeStamp = new Timestamp((Element)sibling, requestData.getBSPEnforcer()); break; } sibling = sibling.getNextSibling(); } } else { timeStamp = (Timestamp)foundResults.get(0).get(WSSecurityEngineResult.TAG_TIMESTAMP); } if (timeStamp == null) { return; } // Test for replay attacks Date created = timeStamp.getCreated(); DateFormat zulu = new XmlSchemaDateFormat(); String identifier = zulu.format(created) + "" + Arrays.hashCode(signatureValue); if (replayCache.contains(identifier)) { throw new WSSecurityException( WSSecurityException.ErrorCode.INVALID_SECURITY, "invalidTimestamp", "A replay attack has been detected"); } // Store the Timestamp/SignatureValue combination in the cache Date expires = timeStamp.getExpires(); if (expires != null) { Date rightNow = new Date(); long currentTime = rightNow.getTime(); long expiresTime = expires.getTime(); replayCache.add(identifier, 1L + (expiresTime - currentTime) / 1000L); } else { replayCache.add(identifier); } } /** * Check BSP compliance (Note some other checks are done elsewhere in this class) * @throws WSSecurityException */ private void checkBSPCompliance( XMLSignature xmlSignature, BSPEnforcer bspEnforcer ) throws WSSecurityException { // Check for Manifests for (Object object : xmlSignature.getObjects()) { if (object instanceof XMLObject) { XMLObject xmlObject = (XMLObject)object; for (Object xmlStructure : xmlObject.getContent()) { if (xmlStructure instanceof Manifest) { bspEnforcer.handleBSPRule(BSPRule.R5403); } } } } // Check the c14n algorithm String c14nMethod = xmlSignature.getSignedInfo().getCanonicalizationMethod().getAlgorithm(); if (!WSConstants.C14N_EXCL_OMIT_COMMENTS.equals(c14nMethod)) { bspEnforcer.handleBSPRule(BSPRule.R5404); } // Not allowed HMAC OutputLength AlgorithmParameterSpec parameterSpec = xmlSignature.getSignedInfo().getSignatureMethod().getParameterSpec(); if (parameterSpec instanceof HMACParameterSpec) { bspEnforcer.handleBSPRule(BSPRule.R5401); } // Must have InclusiveNamespaces with a PrefixList parameterSpec = xmlSignature.getSignedInfo().getCanonicalizationMethod().getParameterSpec(); if (!(parameterSpec instanceof ExcC14NParameterSpec)) { bspEnforcer.handleBSPRule(BSPRule.R5406); } // Check References for (Object refObject : xmlSignature.getSignedInfo().getReferences()) { Reference reference = (Reference)refObject; if (reference.getTransforms().isEmpty()) { bspEnforcer.handleBSPRule(BSPRule.R5416); } for (int i = 0; i < reference.getTransforms().size(); i++) { Transform transform = (Transform)reference.getTransforms().get(i); String algorithm = transform.getAlgorithm(); if (!(WSConstants.C14N_EXCL_OMIT_COMMENTS.equals(algorithm) || STRTransform.TRANSFORM_URI.equals(algorithm) || WSConstants.NS_XMLDSIG_FILTER2.equals(algorithm) || WSConstants.NS_XMLDSIG_ENVELOPED_SIGNATURE.equals(algorithm) || WSConstants.SWA_ATTACHMENT_COMPLETE_SIG_TRANS.equals(algorithm) || WSConstants.SWA_ATTACHMENT_CONTENT_SIG_TRANS.equals(algorithm))) { bspEnforcer.handleBSPRule(BSPRule.R5423); } if (i == (reference.getTransforms().size() - 1) && !(WSConstants.C14N_EXCL_OMIT_COMMENTS.equals(algorithm) || STRTransform.TRANSFORM_URI.equals(algorithm) || WSConstants.SWA_ATTACHMENT_COMPLETE_SIG_TRANS.equals(algorithm) || WSConstants.SWA_ATTACHMENT_CONTENT_SIG_TRANS.equals(algorithm))) { bspEnforcer.handleBSPRule(BSPRule.R5412); } if (WSConstants.C14N_EXCL_OMIT_COMMENTS.equals(algorithm)) { parameterSpec = transform.getParameterSpec(); if (!(parameterSpec instanceof ExcC14NParameterSpec)) { bspEnforcer.handleBSPRule(BSPRule.R5407); } } /*else if (STRTransform.TRANSFORM_URI.equals(algorithm)) { parameterSpec = transform.getParameterSpec(); if (!(parameterSpec instanceof ExcC14NParameterSpec)) { bspEnforcer.handleBSPRule(BSPRule.R5413); } }*/ } } } }
Minor fix git-svn-id: 10bc45916fe30ae642aa5037c9a4b05727bba413@1540674 13f79535-47bb-0310-9956-ffa450edef68
ws-security-dom/src/main/java/org/apache/wss4j/dom/processor/SignatureProcessor.java
Minor fix
<ide><path>s-security-dom/src/main/java/org/apache/wss4j/dom/processor/SignatureProcessor.java <ide> bspEnforcer.handleBSPRule(BSPRule.R5401); <ide> } <ide> <del> // Must have InclusiveNamespaces with a PrefixList <add> // Must have exclusive C14N without comments <ide> parameterSpec = <ide> xmlSignature.getSignedInfo().getCanonicalizationMethod().getParameterSpec(); <ide> if (!(parameterSpec instanceof ExcC14NParameterSpec)) { <del> bspEnforcer.handleBSPRule(BSPRule.R5406); <add> bspEnforcer.handleBSPRule(BSPRule.R5404); <ide> } <ide> <ide> // Check References <ide> if (!(parameterSpec instanceof ExcC14NParameterSpec)) { <ide> bspEnforcer.handleBSPRule(BSPRule.R5407); <ide> } <del> } /*else if (STRTransform.TRANSFORM_URI.equals(algorithm)) { <del> parameterSpec = transform.getParameterSpec(); <del> if (!(parameterSpec instanceof ExcC14NParameterSpec)) { <del> bspEnforcer.handleBSPRule(BSPRule.R5413); <del> } <del> }*/ <add> } <ide> } <ide> } <ide> }
Java
mit
4f558accf98bac5da3686d4a6561348b5069e825
0
draoullig/docker-build-step-plugin,draoullig/docker-build-step-plugin
package org.jenkinsci.plugins.dockerbuildstep; import hudson.Extension; import hudson.Launcher; import hudson.matrix.MatrixProject; import hudson.model.BuildListener; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.FreeStyleProject; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Publisher; import hudson.tasks.Recorder; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.jenkinsci.plugins.dockerbuildstep.cmd.RemoveCommand; import org.jenkinsci.plugins.dockerbuildstep.cmd.StopCommand; import org.jenkinsci.plugins.dockerbuildstep.log.ConsoleLogger; import org.kohsuke.stapler.DataBoundConstructor; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.NotModifiedException; /** * Post build step which stops and removes the Docker container. Use to cleanup container(s) in case of a build failure. * */ @Extension public class DockerPostBuilder extends BuildStepDescriptor<Publisher> { public DockerPostBuilder() { super(DockerPostBuildStep.class); } @Override public boolean isApplicable(@SuppressWarnings("rawtypes") Class<? extends AbstractProject> jobType) { return FreeStyleProject.class.equals(jobType) || MatrixProject.class.equals(jobType); } @Override public String getDisplayName() { return "Stop and remove Docker container"; } public static class DockerPostBuildStep extends Recorder { private final String containerIds; private final boolean removeVolumes; private final boolean force; @DataBoundConstructor public DockerPostBuildStep(String containerIds, boolean removeVolumes, boolean force) { this.containerIds = containerIds; this.removeVolumes = removeVolumes; this.force = force; } public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.NONE; } public String getContainerIds() { return containerIds; } public boolean isRemoveVolumes() { return removeVolumes; } public boolean isForce() { return force; } @Override public boolean perform(@SuppressWarnings("rawtypes") AbstractBuild build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { ConsoleLogger clog = new ConsoleLogger(listener); List<String> ids = Arrays.asList(containerIds.split(",")); for (String id : ids) { StopCommand stopCommand = new StopCommand(id); try { stopCommand.execute(build, clog); } catch (NotFoundException e) { clog.logWarn("unable to stop container id " + id + ", container not found!"); } catch (NotModifiedException e) { // ignore, container already stopped } } RemoveCommand removeCommand = new RemoveCommand(containerIds, true, removeVolumes, force); removeCommand.execute(build, clog); return true; } } }
src/main/java/org/jenkinsci/plugins/dockerbuildstep/DockerPostBuilder.java
package org.jenkinsci.plugins.dockerbuildstep; import hudson.Extension; import hudson.Launcher; import hudson.matrix.MatrixProject; import hudson.model.BuildListener; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.FreeStyleProject; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Publisher; import hudson.tasks.Recorder; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.jenkinsci.plugins.dockerbuildstep.cmd.RemoveCommand; import org.jenkinsci.plugins.dockerbuildstep.cmd.StopCommand; import org.jenkinsci.plugins.dockerbuildstep.log.ConsoleLogger; import org.kohsuke.stapler.DataBoundConstructor; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.NotModifiedException; /** * Post build step which stops and removes the Docker container. Use to cleanup container(s) in case of a build failure. * */ @Extension public class DockerPostBuilder extends BuildStepDescriptor<Publisher> { public DockerPostBuilder() { super(DockerPostBuildStep.class); } @Override public boolean isApplicable(@SuppressWarnings("rawtypes") Class<? extends AbstractProject> jobType) { return FreeStyleProject.class.equals(jobType) || MatrixProject.class.equals(jobType);; } @Override public String getDisplayName() { return "Stop and remove Docker container"; } public static class DockerPostBuildStep extends Recorder { private final String containerIds; private final boolean removeVolumes; private final boolean force; @DataBoundConstructor public DockerPostBuildStep(String containerIds, boolean removeVolumes, boolean force) { this.containerIds = containerIds; this.removeVolumes = removeVolumes; this.force = force; } public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.NONE; } public String getContainerIds() { return containerIds; } public boolean isRemoveVolumes() { return removeVolumes; } public boolean isForce() { return force; } @Override public boolean perform(@SuppressWarnings("rawtypes") AbstractBuild build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { ConsoleLogger clog = new ConsoleLogger(listener); List<String> ids = Arrays.asList(containerIds.split(",")); for (String id : ids) { StopCommand stopCommand = new StopCommand(id); try { stopCommand.execute(build, clog); } catch (NotFoundException e) { clog.logWarn("unable to stop container id " + id + ", container not found!"); } catch (NotModifiedException e) { // ignore, container already stopped } } RemoveCommand removeCommand = new RemoveCommand(containerIds, true, removeVolumes, force); removeCommand.execute(build, clog); return true; } } }
Support the post-build action in a multi-configuration project fix
src/main/java/org/jenkinsci/plugins/dockerbuildstep/DockerPostBuilder.java
Support the post-build action in a multi-configuration project fix
<ide><path>rc/main/java/org/jenkinsci/plugins/dockerbuildstep/DockerPostBuilder.java <ide> <ide> @Override <ide> public boolean isApplicable(@SuppressWarnings("rawtypes") Class<? extends AbstractProject> jobType) { <del> return FreeStyleProject.class.equals(jobType) || MatrixProject.class.equals(jobType);; <add> return FreeStyleProject.class.equals(jobType) || MatrixProject.class.equals(jobType); <ide> } <ide> <ide> @Override
Java
bsd-3-clause
d73c2f52350dd50f4bb5762a6458b8e246f5b71c
0
sebastiangraf/treetank,sebastiangraf/treetank,sebastiangraf/treetank
/* * Copyright (c) 2007, Marc Kramis * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * $Id$ */ package org.treetank.xmllayer; import java.io.PipedOutputStream; import java.io.PrintWriter; import java.io.Writer; import org.treetank.api.IAxis; import org.treetank.api.IConstants; import org.treetank.api.IReadTransaction; import org.treetank.utils.FastStack; import org.treetank.utils.UTF; import org.xml.sax.ContentHandler; import org.xml.sax.helpers.AttributesImpl; import com.sun.org.apache.xml.internal.serializer.Method; import com.sun.org.apache.xml.internal.serializer.OutputPropertiesFactory; import com.sun.org.apache.xml.internal.serializer.Serializer; import com.sun.org.apache.xml.internal.serializer.SerializerFactory; /** * Reconstructs an XML document from XPathAccelerator encoding. */ public final class SAXGenerator implements Runnable { protected ContentHandler mHandler; private Writer mWriter; private boolean mIsSerialize = false; private final boolean mAsInputStream = false; private PipedOutputStream mPipedOut; private final boolean mPrettyPrint; /** The nodeKey of the next node to visit. */ private final IAxis mAxis; private final FastStack<Long> stack; /** * 'Callback' Constructor. * <p> * You'll get the SAX events emited during the roconstruction process. You can * use these as input for your application. * </p> */ public SAXGenerator( final IAxis axis, final ContentHandler contentHandler, final boolean prettyPrint) { mAxis = axis; mHandler = contentHandler; mPrettyPrint = prettyPrint; stack = new FastStack<Long>(); } /** * Constructor to write reconstructed XML to a specified Writer. * * @param aWriter * @see java.io.Writer */ public SAXGenerator( final IAxis axis, final Writer writer, final boolean prettyPrint) { mWriter = writer; mIsSerialize = true; mAxis = axis; mPrettyPrint = prettyPrint; stack = new FastStack<Long>(); } /** * Constructor for printing the reconstructed XML of global storage to stdout. */ public SAXGenerator(final IAxis axis, final boolean prettyPrint) { this(axis, new PrintWriter(System.out), prettyPrint); } private final String qName(final String prefix, final String localPart) { return (prefix.length() > 0 ? prefix + ":" + localPart : localPart); } private final AttributesImpl visitAttributes(final IReadTransaction rtx) { final AttributesImpl attributes = new AttributesImpl(); for (int index = 0, length = rtx.getAttributeCount(); index < length; index++) { attributes.addAttribute(rtx.getAttributeURI(index), rtx .getAttributeLocalPart(index), qName( rtx.getAttributePrefix(index), rtx.getAttributeLocalPart(index)), "", UTF.parseString(rtx .getAttributeValue(index))); } return attributes; } private final void emitNode(final IReadTransaction rtx) throws Exception { // Emit events of current node. switch (rtx.getKind()) { case IConstants.ELEMENT: // Emit start element. mHandler.startElement(rtx.getURI(), rtx.getLocalPart(), qName(rtx .getPrefix(), rtx.getLocalPart()), visitAttributes(rtx)); break; case IConstants.TEXT: final char[] text = UTF.parseString(rtx.getValue()).toCharArray(); mHandler.characters(text, 0, text.length); break; default: throw new IllegalStateException("Unknown kind: " + rtx.getKind()); } } private final void emitEndElement(final IReadTransaction rtx) throws Exception { mHandler.endElement(rtx.getURI(), rtx.getLocalPart(), qName( rtx.getPrefix(), rtx.getLocalPart())); } private final void visitDocument() throws Exception { final IReadTransaction rtx = mAxis.getTransaction(); boolean closeElements = false; for (final long key : mAxis) { // Emit all pending end elements. if (closeElements) { while (!stack.empty() && stack.peek() != rtx.getLeftSiblingKey()) { rtx.moveTo(stack.pop()); emitEndElement(rtx); } if (!stack.empty()) { rtx.moveTo(stack.pop()); emitEndElement(rtx); } rtx.moveTo(key); closeElements = false; } emitNode(rtx); // Emit corresponding end element or push it to stack. if (rtx.isElement()) { if (!rtx.hasFirstChild()) { emitEndElement(rtx); } else { stack.push(rtx.getNodeKey()); } } // Remember to emit all pending end elements from stack if required. if (!rtx.hasFirstChild() && !rtx.hasRightSibling()) { closeElements = true; } } // Finally emit all pending end elements. while (!stack.empty()) { rtx.moveTo(stack.pop()); emitEndElement(rtx); } } public void run() { try { // Start document. if (mIsSerialize) { // Set up serializer, why here? XML Declaration. java.util.Properties props = OutputPropertiesFactory.getDefaultMethodProperties(Method.XML); props.setProperty("indent", mPrettyPrint ? "yes" : "no"); props.setProperty("{http://xml.apache.org/xalan}indent-amount", "2"); // Process XML declaration. props.setProperty("version", "1.0"); props.setProperty("encoding", "UTF-8"); props.setProperty("standalone", "yes"); Serializer serializer = SerializerFactory.getSerializer(props); if (mAsInputStream) { serializer.setOutputStream(mPipedOut); serializer.setWriter(new PrintWriter(System.err)); } else { serializer.setWriter(mWriter); } mHandler = serializer.asContentHandler(); } mHandler.startDocument(); // Traverse all descendants in document order. visitDocument(); // End document. mHandler.endDocument(); if (mAsInputStream) { mPipedOut.close(); } } catch (Exception e) { throw new RuntimeException(e); } } // private final void debug() throws Exception { // System.out.println(">>> DEBUG >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); // System.out.println("nodeKey = " + rtx.getNodeKey()); // System.out.println("nextKey = " + mNextKey); // System.out.print("rightSiblingKeyStack = { "); // for (int i = 0; i < mRightSiblingKeyStack.size(); i++) { // System.out.print(mRightSiblingKeyStack.get(i) + "; "); // } // System.out.println("}"); // System.out.println("}"); // System.out.println("attributeCount = " + rtx.getAttributeCount()); // System.out.println("<<< DEBUG <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"); // } }
src/org/treetank/xmllayer/SAXGenerator.java
/* * Copyright (c) 2007, Marc Kramis * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * $Id$ */ package org.treetank.xmllayer; import java.io.PipedOutputStream; import java.io.PrintWriter; import java.io.Writer; import org.treetank.api.IAxis; import org.treetank.api.IConstants; import org.treetank.api.IReadTransaction; import org.treetank.utils.FastStack; import org.treetank.utils.UTF; import org.xml.sax.ContentHandler; import org.xml.sax.helpers.AttributesImpl; import com.sun.org.apache.xml.internal.serializer.Method; import com.sun.org.apache.xml.internal.serializer.OutputPropertiesFactory; import com.sun.org.apache.xml.internal.serializer.Serializer; import com.sun.org.apache.xml.internal.serializer.SerializerFactory; /** * Reconstructs an XML document from XPathAccelerator encoding. */ public final class SAXGenerator implements Runnable { protected ContentHandler mHandler; private Writer mWriter; private boolean mIsSerialize = false; private final boolean mAsInputStream = false; private PipedOutputStream mPipedOut; private final boolean mPrettyPrint; /** The nodeKey of the next node to visit. */ private final IAxis mAxis; private final FastStack<Long> stack; /** * 'Callback' Constructor. * <p> * You'll get the SAX events emited during the roconstruction process. You can * use these as input for your application. * </p> */ public SAXGenerator( final IAxis axis, final ContentHandler contentHandler, final boolean prettyPrint) throws Exception { mAxis = axis; mHandler = contentHandler; mPrettyPrint = prettyPrint; stack = new FastStack<Long>(); } /** * Constructor to write reconstructed XML to a specified Writer. * * @param aWriter * @see java.io.Writer */ public SAXGenerator( final IAxis axis, final Writer writer, final boolean prettyPrint) throws Exception { mWriter = writer; mIsSerialize = true; mAxis = axis; mPrettyPrint = prettyPrint; stack = new FastStack<Long>(); } /** * Constructor for printing the reconstructed XML of global storage to stdout. */ public SAXGenerator(final IAxis axis, final boolean prettyPrint) throws Exception { this(axis, new PrintWriter(System.out), prettyPrint); } private final String qName(final String prefix, final String localPart) { return (prefix.length() > 0 ? prefix + ":" + localPart : localPart); } private final AttributesImpl visitAttributes(final IReadTransaction rtx) { final AttributesImpl attributes = new AttributesImpl(); for (int index = 0, length = rtx.getAttributeCount(); index < length; index++) { attributes.addAttribute(rtx.getAttributeURI(index), rtx .getAttributeLocalPart(index), qName( rtx.getAttributePrefix(index), rtx.getAttributeLocalPart(index)), "", UTF.parseString(rtx .getAttributeValue(index))); } return attributes; } private final void emitNode(final IReadTransaction rtx) throws Exception { // Emit events of current node. switch (rtx.getKind()) { case IConstants.ELEMENT: // Emit start element. mHandler.startElement(rtx.getURI(), rtx.getLocalPart(), qName(rtx .getPrefix(), rtx.getLocalPart()), visitAttributes(rtx)); break; case IConstants.TEXT: final char[] text = UTF.parseString(rtx.getValue()).toCharArray(); mHandler.characters(text, 0, text.length); break; default: throw new IllegalStateException("Unknown kind: " + rtx.getKind()); } } private final void emitEndElement(final IReadTransaction rtx) throws Exception { mHandler.endElement(rtx.getURI(), rtx.getLocalPart(), qName( rtx.getPrefix(), rtx.getLocalPart())); } private final void visitDocument() throws Exception { final IReadTransaction rtx = mAxis.getTransaction(); boolean closeElements = false; for (final long key : mAxis) { // Emit all pending end elements. if (closeElements) { while (!stack.empty() && stack.peek() != rtx.getLeftSiblingKey()) { rtx.moveTo(stack.pop()); emitEndElement(rtx); } if (!stack.empty()) { rtx.moveTo(stack.pop()); emitEndElement(rtx); } rtx.moveTo(key); closeElements = false; } emitNode(rtx); // Emit corresponding end element or push it to stack. if (rtx.isElement()) { if (!rtx.hasFirstChild()) { emitEndElement(rtx); } else { stack.push(rtx.getNodeKey()); } } // Remember to emit all pending end elements from stack if required. if (!rtx.hasFirstChild() && !rtx.hasRightSibling()) { closeElements = true; } } // Finally emit all pending end elements. while (!stack.empty()) { rtx.moveTo(stack.pop()); emitEndElement(rtx); } } public void run() { try { // Start document. if (mIsSerialize) { // Set up serializer, why here? XML Declaration. java.util.Properties props = OutputPropertiesFactory.getDefaultMethodProperties(Method.XML); props.setProperty("indent", mPrettyPrint ? "yes" : "no"); props.setProperty("{http://xml.apache.org/xalan}indent-amount", "2"); // Process XML declaration. props.setProperty("version", "1.0"); props.setProperty("encoding", "UTF-8"); props.setProperty("standalone", "yes"); Serializer serializer = SerializerFactory.getSerializer(props); if (mAsInputStream) { serializer.setOutputStream(mPipedOut); serializer.setWriter(new PrintWriter(System.err)); } else { serializer.setWriter(mWriter); } mHandler = serializer.asContentHandler(); } mHandler.startDocument(); // Traverse all descendants in document order. visitDocument(); // End document. mHandler.endDocument(); if (mAsInputStream) { mPipedOut.close(); } } catch (Exception e) { throw new IllegalStateException(e); } } // private final void debug() throws Exception { // System.out.println(">>> DEBUG >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); // System.out.println("nodeKey = " + rtx.getNodeKey()); // System.out.println("nextKey = " + mNextKey); // System.out.print("rightSiblingKeyStack = { "); // for (int i = 0; i < mRightSiblingKeyStack.size(); i++) { // System.out.print(mRightSiblingKeyStack.get(i) + "; "); // } // System.out.println("}"); // System.out.println("}"); // System.out.println("attributeCount = " + rtx.getAttributeCount()); // System.out.println("<<< DEBUG <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"); // } }
SAXGenerator now throws unchecked exceptions. git-svn-id: a5379eb5ca3beb2b6e029be3b1b7f6aa53f2352b@3509 e3ddb328-5bfe-0310-b762-aafcbcbd2528
src/org/treetank/xmllayer/SAXGenerator.java
SAXGenerator now throws unchecked exceptions.
<ide><path>rc/org/treetank/xmllayer/SAXGenerator.java <ide> public SAXGenerator( <ide> final IAxis axis, <ide> final ContentHandler contentHandler, <del> final boolean prettyPrint) throws Exception { <add> final boolean prettyPrint) { <ide> mAxis = axis; <ide> mHandler = contentHandler; <ide> mPrettyPrint = prettyPrint; <ide> public SAXGenerator( <ide> final IAxis axis, <ide> final Writer writer, <del> final boolean prettyPrint) throws Exception { <add> final boolean prettyPrint) { <ide> mWriter = writer; <ide> mIsSerialize = true; <ide> mAxis = axis; <ide> /** <ide> * Constructor for printing the reconstructed XML of global storage to stdout. <ide> */ <del> public SAXGenerator(final IAxis axis, final boolean prettyPrint) <del> throws Exception { <add> public SAXGenerator(final IAxis axis, final boolean prettyPrint) { <ide> this(axis, new PrintWriter(System.out), prettyPrint); <ide> } <ide> <ide> } <ide> <ide> } catch (Exception e) { <del> throw new IllegalStateException(e); <add> throw new RuntimeException(e); <ide> } <ide> } <ide>
Java
apache-2.0
2da2d38f8836dac8bb95da196f5e0a8cf69f428b
0
louishust/incubator-ignite,DoudTechData/ignite,NSAmelchev/ignite,WilliamDo/ignite,irudyak/ignite,andrey-kuznetsov/ignite,sk0x50/ignite,nizhikov/ignite,SomeFire/ignite,thuTom/ignite,dmagda/incubator-ignite,thuTom/ignite,sylentprayer/ignite,vladisav/ignite,NSAmelchev/ignite,samaitra/ignite,alexzaitzev/ignite,dmagda/incubator-ignite,apacheignite/ignite,nizhikov/ignite,ptupitsyn/ignite,dream-x/ignite,SomeFire/ignite,gargvish/ignite,murador/ignite,kidaa/incubator-ignite,xtern/ignite,vsuslov/incubator-ignite,thuTom/ignite,dream-x/ignite,adeelmahmood/ignite,vladisav/ignite,agura/incubator-ignite,amirakhmedov/ignite,StalkXT/ignite,kidaa/incubator-ignite,f7753/ignite,apache/ignite,rfqu/ignite,WilliamDo/ignite,gargvish/ignite,dlnufox/ignite,SomeFire/ignite,agoncharuk/ignite,samaitra/ignite,xtern/ignite,arijitt/incubator-ignite,svladykin/ignite,ilantukh/ignite,amirakhmedov/ignite,alexzaitzev/ignite,pperalta/ignite,apache/ignite,thuTom/ignite,agura/incubator-ignite,alexzaitzev/ignite,voipp/ignite,chandresh-pancholi/ignite,f7753/ignite,rfqu/ignite,vsuslov/incubator-ignite,ryanzz/ignite,afinka77/ignite,avinogradovgg/ignite,shroman/ignite,chandresh-pancholi/ignite,abhishek-ch/incubator-ignite,f7753/ignite,nivanov/ignite,akuznetsov-gridgain/ignite,gridgain/apache-ignite,ryanzz/ignite,vldpyatkov/ignite,ascherbakoff/ignite,vladisav/ignite,wmz7year/ignite,vldpyatkov/ignite,abhishek-ch/incubator-ignite,psadusumilli/ignite,BiryukovVA/ignite,afinka77/ignite,DoudTechData/ignite,wmz7year/ignite,BiryukovVA/ignite,agoncharuk/ignite,arijitt/incubator-ignite,akuznetsov-gridgain/ignite,gargvish/ignite,f7753/ignite,agura/incubator-ignite,SomeFire/ignite,andrey-kuznetsov/ignite,VladimirErshov/ignite,afinka77/ignite,ascherbakoff/ignite,endian675/ignite,VladimirErshov/ignite,ilantukh/ignite,alexzaitzev/ignite,endian675/ignite,psadusumilli/ignite,zzcclp/ignite,zzcclp/ignite,endian675/ignite,endian675/ignite,louishust/incubator-ignite,daradurvs/ignite,dream-x/ignite,xtern/ignite,ptupitsyn/ignite,zzcclp/ignite,vsuslov/incubator-ignite,apache/ignite,sylentprayer/ignite,shroman/ignite,andrey-kuznetsov/ignite,sylentprayer/ignite,ascherbakoff/ignite,psadusumilli/ignite,StalkXT/ignite,NSAmelchev/ignite,wmz7year/ignite,amirakhmedov/ignite,dlnufox/ignite,vladisav/ignite,WilliamDo/ignite,amirakhmedov/ignite,vsuslov/incubator-ignite,apache/ignite,nivanov/ignite,a1vanov/ignite,endian675/ignite,andrey-kuznetsov/ignite,pperalta/ignite,pperalta/ignite,SharplEr/ignite,samaitra/ignite,shurun19851206/ignite,voipp/ignite,svladykin/ignite,irudyak/ignite,svladykin/ignite,gargvish/ignite,xtern/ignite,irudyak/ignite,tkpanther/ignite,DoudTechData/ignite,gridgain/apache-ignite,voipp/ignite,murador/ignite,arijitt/incubator-ignite,wmz7year/ignite,ntikhonov/ignite,irudyak/ignite,samaitra/ignite,ascherbakoff/ignite,gargvish/ignite,kidaa/incubator-ignite,sk0x50/ignite,vadopolski/ignite,BiryukovVA/ignite,iveselovskiy/ignite,StalkXT/ignite,thuTom/ignite,vsisko/incubator-ignite,WilliamDo/ignite,StalkXT/ignite,sk0x50/ignite,apacheignite/ignite,ptupitsyn/ignite,StalkXT/ignite,amirakhmedov/ignite,gargvish/ignite,pperalta/ignite,ascherbakoff/ignite,ryanzz/ignite,vldpyatkov/ignite,dream-x/ignite,StalkXT/ignite,vsisko/incubator-ignite,afinka77/ignite,ryanzz/ignite,ascherbakoff/ignite,ptupitsyn/ignite,apacheignite/ignite,rfqu/ignite,mcherkasov/ignite,vadopolski/ignite,tkpanther/ignite,tkpanther/ignite,dlnufox/ignite,vadopolski/ignite,ntikhonov/ignite,mcherkasov/ignite,SomeFire/ignite,afinka77/ignite,murador/ignite,murador/ignite,nivanov/ignite,DoudTechData/ignite,SomeFire/ignite,vsisko/incubator-ignite,NSAmelchev/ignite,gridgain/apache-ignite,chandresh-pancholi/ignite,a1vanov/ignite,alexzaitzev/ignite,adeelmahmood/ignite,andrey-kuznetsov/ignite,daradurvs/ignite,leveyj/ignite,agoncharuk/ignite,ilantukh/ignite,daradurvs/ignite,vladisav/ignite,dream-x/ignite,andrey-kuznetsov/ignite,avinogradovgg/ignite,vsisko/incubator-ignite,SharplEr/ignite,xtern/ignite,endian675/ignite,tkpanther/ignite,daradurvs/ignite,voipp/ignite,BiryukovVA/ignite,louishust/incubator-ignite,nivanov/ignite,xtern/ignite,wmz7year/ignite,voipp/ignite,BiryukovVA/ignite,nivanov/ignite,kromulan/ignite,avinogradovgg/ignite,agura/incubator-ignite,NSAmelchev/ignite,ptupitsyn/ignite,SharplEr/ignite,zzcclp/ignite,vladisav/ignite,afinka77/ignite,rfqu/ignite,daradurvs/ignite,SharplEr/ignite,vsuslov/incubator-ignite,SomeFire/ignite,adeelmahmood/ignite,nizhikov/ignite,iveselovskiy/ignite,mcherkasov/ignite,shroman/ignite,vadopolski/ignite,chandresh-pancholi/ignite,ntikhonov/ignite,nizhikov/ignite,samaitra/ignite,avinogradovgg/ignite,arijitt/incubator-ignite,xtern/ignite,SharplEr/ignite,sylentprayer/ignite,psadusumilli/ignite,amirakhmedov/ignite,apacheignite/ignite,alexzaitzev/ignite,dlnufox/ignite,apacheignite/ignite,shroman/ignite,apache/ignite,amirakhmedov/ignite,DoudTechData/ignite,xtern/ignite,ashutakGG/incubator-ignite,murador/ignite,louishust/incubator-ignite,ilantukh/ignite,shroman/ignite,SharplEr/ignite,mcherkasov/ignite,akuznetsov-gridgain/ignite,agura/incubator-ignite,leveyj/ignite,kromulan/ignite,rfqu/ignite,SomeFire/ignite,shroman/ignite,leveyj/ignite,VladimirErshov/ignite,andrey-kuznetsov/ignite,SomeFire/ignite,thuTom/ignite,kromulan/ignite,f7753/ignite,afinka77/ignite,kidaa/incubator-ignite,agoncharuk/ignite,dlnufox/ignite,nizhikov/ignite,gargvish/ignite,alexzaitzev/ignite,adeelmahmood/ignite,vladisav/ignite,nivanov/ignite,samaitra/ignite,andrey-kuznetsov/ignite,kromulan/ignite,shurun19851206/ignite,ashutakGG/incubator-ignite,daradurvs/ignite,alexzaitzev/ignite,BiryukovVA/ignite,adeelmahmood/ignite,leveyj/ignite,vadopolski/ignite,adeelmahmood/ignite,sk0x50/ignite,WilliamDo/ignite,zzcclp/ignite,f7753/ignite,irudyak/ignite,ntikhonov/ignite,dream-x/ignite,vldpyatkov/ignite,akuznetsov-gridgain/ignite,thuTom/ignite,irudyak/ignite,dmagda/incubator-ignite,alexzaitzev/ignite,avinogradovgg/ignite,vsisko/incubator-ignite,andrey-kuznetsov/ignite,voipp/ignite,ptupitsyn/ignite,thuTom/ignite,andrey-kuznetsov/ignite,BiryukovVA/ignite,DoudTechData/ignite,leveyj/ignite,shurun19851206/ignite,agura/incubator-ignite,VladimirErshov/ignite,StalkXT/ignite,a1vanov/ignite,ntikhonov/ignite,WilliamDo/ignite,xtern/ignite,samaitra/ignite,irudyak/ignite,ptupitsyn/ignite,nizhikov/ignite,dlnufox/ignite,psadusumilli/ignite,sk0x50/ignite,ilantukh/ignite,vsuslov/incubator-ignite,tkpanther/ignite,shroman/ignite,WilliamDo/ignite,ryanzz/ignite,tkpanther/ignite,ptupitsyn/ignite,ashutakGG/incubator-ignite,NSAmelchev/ignite,kromulan/ignite,pperalta/ignite,NSAmelchev/ignite,a1vanov/ignite,agoncharuk/ignite,dmagda/incubator-ignite,ascherbakoff/ignite,agura/incubator-ignite,samaitra/ignite,zzcclp/ignite,kidaa/incubator-ignite,amirakhmedov/ignite,tkpanther/ignite,apacheignite/ignite,dmagda/incubator-ignite,vadopolski/ignite,svladykin/ignite,sk0x50/ignite,ilantukh/ignite,zzcclp/ignite,sylentprayer/ignite,mcherkasov/ignite,wmz7year/ignite,BiryukovVA/ignite,voipp/ignite,a1vanov/ignite,ascherbakoff/ignite,tkpanther/ignite,dream-x/ignite,nizhikov/ignite,VladimirErshov/ignite,daradurvs/ignite,irudyak/ignite,iveselovskiy/ignite,ashutakGG/incubator-ignite,shurun19851206/ignite,vldpyatkov/ignite,avinogradovgg/ignite,a1vanov/ignite,svladykin/ignite,apache/ignite,psadusumilli/ignite,sk0x50/ignite,nizhikov/ignite,dmagda/incubator-ignite,iveselovskiy/ignite,zzcclp/ignite,ryanzz/ignite,ntikhonov/ignite,WilliamDo/ignite,sylentprayer/ignite,SharplEr/ignite,agoncharuk/ignite,dlnufox/ignite,sylentprayer/ignite,ilantukh/ignite,leveyj/ignite,leveyj/ignite,gargvish/ignite,shurun19851206/ignite,abhishek-ch/incubator-ignite,ptupitsyn/ignite,mcherkasov/ignite,louishust/incubator-ignite,rfqu/ignite,ashutakGG/incubator-ignite,pperalta/ignite,SharplEr/ignite,apacheignite/ignite,chandresh-pancholi/ignite,kromulan/ignite,samaitra/ignite,vsisko/incubator-ignite,kidaa/incubator-ignite,rfqu/ignite,shroman/ignite,svladykin/ignite,shroman/ignite,leveyj/ignite,voipp/ignite,a1vanov/ignite,DoudTechData/ignite,abhishek-ch/incubator-ignite,apache/ignite,shroman/ignite,SomeFire/ignite,vadopolski/ignite,StalkXT/ignite,kromulan/ignite,shurun19851206/ignite,pperalta/ignite,gridgain/apache-ignite,gridgain/apache-ignite,ashutakGG/incubator-ignite,daradurvs/ignite,chandresh-pancholi/ignite,svladykin/ignite,f7753/ignite,sylentprayer/ignite,ptupitsyn/ignite,VladimirErshov/ignite,adeelmahmood/ignite,apache/ignite,afinka77/ignite,amirakhmedov/ignite,murador/ignite,dmagda/incubator-ignite,iveselovskiy/ignite,murador/ignite,rfqu/ignite,dmagda/incubator-ignite,arijitt/incubator-ignite,nivanov/ignite,SharplEr/ignite,f7753/ignite,gridgain/apache-ignite,voipp/ignite,DoudTechData/ignite,gridgain/apache-ignite,kromulan/ignite,endian675/ignite,VladimirErshov/ignite,psadusumilli/ignite,vsisko/incubator-ignite,sk0x50/ignite,shurun19851206/ignite,BiryukovVA/ignite,iveselovskiy/ignite,ilantukh/ignite,agura/incubator-ignite,shurun19851206/ignite,agoncharuk/ignite,mcherkasov/ignite,louishust/incubator-ignite,ryanzz/ignite,murador/ignite,daradurvs/ignite,vladisav/ignite,StalkXT/ignite,a1vanov/ignite,vldpyatkov/ignite,apache/ignite,agoncharuk/ignite,abhishek-ch/incubator-ignite,akuznetsov-gridgain/ignite,psadusumilli/ignite,avinogradovgg/ignite,abhishek-ch/incubator-ignite,vldpyatkov/ignite,VladimirErshov/ignite,daradurvs/ignite,ntikhonov/ignite,wmz7year/ignite,samaitra/ignite,endian675/ignite,NSAmelchev/ignite,BiryukovVA/ignite,vsisko/incubator-ignite,mcherkasov/ignite,irudyak/ignite,apacheignite/ignite,chandresh-pancholi/ignite,arijitt/incubator-ignite,ryanzz/ignite,ilantukh/ignite,dlnufox/ignite,nizhikov/ignite,vldpyatkov/ignite,akuznetsov-gridgain/ignite,chandresh-pancholi/ignite,chandresh-pancholi/ignite,dream-x/ignite,NSAmelchev/ignite,sk0x50/ignite,ascherbakoff/ignite,pperalta/ignite,ilantukh/ignite,wmz7year/ignite,adeelmahmood/ignite,vadopolski/ignite,nivanov/ignite,ntikhonov/ignite
/* @java.file.header */ /* _________ _____ __________________ _____ * __ ____/___________(_)______ /__ ____/______ ____(_)_______ * _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \ * / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / / * \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/ */ package org.gridgain.grid.kernal.processors.hadoop.taskexecutor; import org.gridgain.grid.GridException; import org.gridgain.grid.GridInterruptedException; import org.gridgain.grid.hadoop.GridHadoopTaskInfo; import org.gridgain.grid.logger.GridLogger; import org.gridgain.grid.thread.GridThread; import org.gridgain.grid.util.worker.GridWorker; import org.gridgain.grid.util.worker.GridWorkerListener; import org.gridgain.grid.util.worker.GridWorkerListenerAdapter; import org.jdk8.backport.ConcurrentHashMap8; import java.util.Collection; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import static java.util.Collections.*; /** * Executor service. */ public class GridHadoopExecutorService { /** */ private final LinkedBlockingQueue<GridHadoopRunnableTask> queue; /** */ private final Collection<GridWorker> workers = newSetFromMap(new ConcurrentHashMap8<GridWorker, Boolean>()); /** */ private final AtomicInteger active = new AtomicInteger(); /** */ private final int maxTasks; /** */ private final String gridName; /** */ private final GridLogger log; /** */ private volatile boolean shutdown; /** */ private final GridWorkerListener lsnr = new GridWorkerListenerAdapter() { @Override public void onStopped(GridWorker w) { workers.remove(w); if (shutdown) { active.decrementAndGet(); return; } GridHadoopRunnableTask task = queue.poll(); if (task != null) startThread(task); else { active.decrementAndGet(); if (!queue.isEmpty()) startFromQueue(); } } }; /** * @param log Logger. * @param gridName Grid name. * @param maxTasks Max number of tasks. * @param maxQueue Max queue length. */ public GridHadoopExecutorService(GridLogger log, String gridName, int maxTasks, int maxQueue) { assert maxTasks > 0 : maxTasks; assert maxQueue > 0 : maxQueue; this.maxTasks = maxTasks; this.queue = new LinkedBlockingQueue<>(maxQueue); this.gridName = gridName; this.log = log.getLogger(GridHadoopExecutorService.class); } /** * Submit task. * * @param task Task. */ public void submit(GridHadoopRunnableTask task) { while (queue.isEmpty()) { int active0 = active.get(); if (active0 == maxTasks) break; if (active.compareAndSet(active0, active0 + 1)) { startThread(task); return; } } queue.add(task); startFromQueue(); } /** * */ private void startFromQueue() { do { int active0 = active.get(); if (active0 == maxTasks) break; if (active.compareAndSet(active0, active0 + 1)) { GridHadoopRunnableTask task = queue.poll(); if (task == null) { int res = active.decrementAndGet(); assert res >= 0 : res; break; } startThread(task); } } while (!queue.isEmpty()); } /** * @param task Task. */ private void startThread(final GridHadoopRunnableTask task) { final GridHadoopTaskInfo i = task.taskInfo(); GridWorker w = new GridWorker(gridName, "Hadoop-task-" + i.jobId() + "-" + i.type() + "-" + i.taskNumber() + "-" + i.attempt(), log, lsnr) { @Override protected void body() throws InterruptedException, GridInterruptedException { try { task.call(); } catch (GridException e) { log.error("Failed to execute task: " + i, e); } } }; workers.add(w); if (shutdown) return; new GridThread(w).start(); } /** * Shuts down this executor service. * * @param awaitTimeMillis Time in milliseconds to wait for tasks completion. * @return {@code true} If all tasks completed. */ public boolean shutdown(long awaitTimeMillis) { shutdown = true; for (GridWorker w : workers) w.cancel(); while (awaitTimeMillis > 0 && active.get() != 0) { try { Thread.sleep(100); awaitTimeMillis -= 100; } catch (InterruptedException e) { break; } } return active.get() == 0; } }
modules/hadoop/src/main/java/org/gridgain/grid/kernal/processors/hadoop/taskexecutor/GridHadoopExecutorService.java
/* @java.file.header */ /* _________ _____ __________________ _____ * __ ____/___________(_)______ /__ ____/______ ____(_)_______ * _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \ * / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / / * \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/ */ package org.gridgain.grid.kernal.processors.hadoop.taskexecutor; import org.gridgain.grid.GridException; import org.gridgain.grid.GridInterruptedException; import org.gridgain.grid.hadoop.GridHadoopTaskInfo; import org.gridgain.grid.logger.GridLogger; import org.gridgain.grid.thread.GridThread; import org.gridgain.grid.util.worker.GridWorker; import org.gridgain.grid.util.worker.GridWorkerListener; import org.gridgain.grid.util.worker.GridWorkerListenerAdapter; import org.jdk8.backport.ConcurrentHashMap8; import java.util.Collection; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import static java.util.Collections.*; /** * Executor service. */ public class GridHadoopExecutorService { /** */ private final LinkedBlockingQueue<GridHadoopRunnableTask> queue; /** */ private final Collection<GridWorker> workers = newSetFromMap(new ConcurrentHashMap8<GridWorker, Boolean>()); /** */ private final AtomicInteger active = new AtomicInteger(); /** */ private final int maxTasks; /** */ private final String gridName; /** */ private final GridLogger log; /** */ private volatile boolean shutdown; /** */ private final GridWorkerListener lsnr = new GridWorkerListenerAdapter() { @Override public void onStopped(GridWorker w) { workers.remove(w); if (shutdown) return; GridHadoopRunnableTask task = queue.poll(); if (task != null) startThread(task); else { active.decrementAndGet(); if (!queue.isEmpty()) startFromQueue(); } } }; /** * @param log Logger. * @param gridName Grid name. * @param maxTasks Max number of tasks. * @param maxQueue Max queue length. */ public GridHadoopExecutorService(GridLogger log, String gridName, int maxTasks, int maxQueue) { assert maxTasks > 0 : maxTasks; assert maxQueue > 0 : maxQueue; this.maxTasks = maxTasks; this.queue = new LinkedBlockingQueue<>(maxQueue); this.gridName = gridName; this.log = log.getLogger(GridHadoopExecutorService.class); } /** * Submit task. * * @param task Task. */ public void submit(GridHadoopRunnableTask task) { while (queue.isEmpty()) { int active0 = active.get(); if (active0 == maxTasks) break; if (active.compareAndSet(active0, active0 + 1)) { startThread(task); return; } } queue.add(task); startFromQueue(); } /** * */ private void startFromQueue() { do { int active0 = active.get(); if (active0 == maxTasks) break; if (active.compareAndSet(active0, active0 + 1)) { GridHadoopRunnableTask task = queue.poll(); if (task == null) { int res = active.decrementAndGet(); assert res >= 0 : res; break; } startThread(task); } } while (!queue.isEmpty()); } /** * @param task Task. */ private void startThread(final GridHadoopRunnableTask task) { final GridHadoopTaskInfo i = task.taskInfo(); GridWorker w = new GridWorker(gridName, "Hadoop-task-" + i.jobId() + "-" + i.type() + "-" + i.taskNumber() + "-" + i.attempt(), log, lsnr) { @Override protected void body() throws InterruptedException, GridInterruptedException { try { task.call(); } catch (GridException e) { log.error("Failed to execute task: " + i, e); } } }; workers.add(w); if (shutdown) return; new GridThread(w).start(); } /** * Shuts down this executor service. * * @param awaitTimeMillis Time in milliseconds to wait for tasks completion. * @return {@code true} If all tasks completed. */ public boolean shutdown(long awaitTimeMillis) { shutdown = true; for (GridWorker w : workers) w.cancel(); while (awaitTimeMillis > 0 && active.get() != 0) { try { Thread.sleep(100); awaitTimeMillis -= 100; } catch (InterruptedException e) { break; } } return active.get() == 0; } }
#gg-hdp - exec service fix
modules/hadoop/src/main/java/org/gridgain/grid/kernal/processors/hadoop/taskexecutor/GridHadoopExecutorService.java
#gg-hdp - exec service fix
<ide><path>odules/hadoop/src/main/java/org/gridgain/grid/kernal/processors/hadoop/taskexecutor/GridHadoopExecutorService.java <ide> @Override public void onStopped(GridWorker w) { <ide> workers.remove(w); <ide> <del> if (shutdown) <add> if (shutdown) { <add> active.decrementAndGet(); <add> <ide> return; <add> } <ide> <ide> GridHadoopRunnableTask task = queue.poll(); <ide>
JavaScript
mit
30cb4d7d205922ab74a2faba70799227b7c3d6b1
0
yaman/generator-ean-crud
/*global describe, beforeEach, it*/ 'use strict'; var path = require('path'); var helpers = require('yeoman-generator').test; describe('ean-crud generator', function () { beforeEach(function (done) { helpers.testDirectory(path.join(__dirname, 'temp'), function (err) { if (err) { return done(err); } this.app = helpers.createGenerator('ean-crud:app', [ '../../app' ]); done(); }.bind(this)); }); it('creates expected files', function (done) { var expected = [ // add files you expect to exist here. '.jshintrc', '.editorconfig', 'Gruntfile.coffee', 'app.coffee', 'src/client/modules/config', 'src/client/public', 'src/server/api', 'src/server/routes', 'test/mocha.opts', 'test/client/karma.conf.js', 'src/server/routes/client.coffee' ]; helpers.mockPrompt(this.app, { 'appName': "appName" }); this.app.options['skip-install'] = true; this.app.run({}, function () { helpers.assertFiles(expected); done(); }); }); });
test/test-creation.js
/*global describe, beforeEach, it*/ 'use strict'; var path = require('path'); var helpers = require('yeoman-generator').test; describe('ean-crud generator', function () { beforeEach(function (done) { helpers.testDirectory(path.join(__dirname, 'temp'), function (err) { if (err) { return done(err); } this.app = helpers.createGenerator('ean-crud:app', [ '../../app' ]); done(); }.bind(this)); }); it('creates expected files', function (done) { var expected = [ // add files you expect to exist here. '.jshintrc', '.editorconfig', 'Gruntfile.js', 'app.coffee', 'src/client/modules/config', 'src/client/public', 'src/server/api', 'src/server/routes', 'test/mocha.opts', 'test/client/karma.conf.js', 'src/server/routes/client.coffee' ]; helpers.mockPrompt(this.app, { 'appName': "appName" }); this.app.options['skip-install'] = true; this.app.run({}, function () { helpers.assertFiles(expected); done(); }); }); });
fixing js -> coffee
test/test-creation.js
fixing js -> coffee
<ide><path>est/test-creation.js <ide> // add files you expect to exist here. <ide> '.jshintrc', <ide> '.editorconfig', <del> 'Gruntfile.js', <add> 'Gruntfile.coffee', <ide> 'app.coffee', <ide> 'src/client/modules/config', <ide> 'src/client/public',
Java
apache-2.0
86313ed69b2082e82169c3f308be3311b513c883
0
kalaspuffar/pdfbox,apache/pdfbox,apache/pdfbox,kalaspuffar/pdfbox
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pdfbox.tools; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FileDialog; import java.awt.Toolkit; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowEvent; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.URL; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.KeyStroke; import javax.swing.TransferHandler; import javax.swing.UIManager; import javax.swing.border.BevelBorder; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.filechooser.FileFilter; import javax.swing.tree.TreePath; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSBoolean; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSFloat; import org.apache.pdfbox.cos.COSInteger; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.cos.COSNull; import org.apache.pdfbox.cos.COSObject; import org.apache.pdfbox.cos.COSStream; import org.apache.pdfbox.cos.COSString; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.tools.gui.ArrayEntry; import org.apache.pdfbox.tools.gui.DocumentEntry; import org.apache.pdfbox.tools.gui.MapEntry; import org.apache.pdfbox.tools.gui.OSXAdapter; import org.apache.pdfbox.tools.gui.PDFTreeCellRenderer; import org.apache.pdfbox.tools.gui.PDFTreeModel; import org.apache.pdfbox.tools.gui.PageEntry; import org.apache.pdfbox.tools.pdfdebugger.colorpane.CSArrayBased; import org.apache.pdfbox.tools.pdfdebugger.colorpane.CSDeviceN; import org.apache.pdfbox.tools.pdfdebugger.colorpane.CSIndexed; import org.apache.pdfbox.tools.pdfdebugger.colorpane.CSSeparation; import org.apache.pdfbox.tools.pdfdebugger.flagbitspane.FlagBitsPane; import org.apache.pdfbox.tools.pdfdebugger.fontencodingpane.FontEncodingPaneController; import org.apache.pdfbox.tools.pdfdebugger.pagepane.PagePane; import org.apache.pdfbox.tools.pdfdebugger.streampane.StreamPane; import org.apache.pdfbox.tools.pdfdebugger.treestatus.TreeStatus; import org.apache.pdfbox.tools.pdfdebugger.treestatus.TreeStatusPane; import org.apache.pdfbox.tools.pdfdebugger.ui.RotationMenu; import org.apache.pdfbox.tools.pdfdebugger.ui.Tree; import org.apache.pdfbox.tools.pdfdebugger.ui.ZoomMenu; import org.apache.pdfbox.tools.util.FileOpenSaveDialog; import org.apache.pdfbox.tools.util.RecentFiles; /** * PDF Debugger. * * @author wurtz * @author Ben Litchfield */ public class PDFDebugger extends JFrame { private static final Set<COSName> SPECIALCOLORSPACES = new HashSet<COSName>(Arrays.asList(COSName.INDEXED, COSName.SEPARATION, COSName.DEVICEN)); private static final Set<COSName> OTHERCOLORSPACES = new HashSet<COSName>(Arrays.asList(COSName.ICCBASED, COSName.PATTERN, COSName.CALGRAY, COSName.CALRGB, COSName.LAB)); private static final String PASSWORD = "-password"; private static final int SHORCUT_KEY_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); private TreeStatusPane statusPane; private RecentFiles recentFiles; private boolean isPageMode; private PDDocument document; private String currentFilePath; private static final String OS_NAME = System.getProperty("os.name").toLowerCase(); private static final boolean IS_MAC_OS = OS_NAME.startsWith("mac os x"); private JScrollPane jScrollPane1; private JScrollPane jScrollPane2; private javax.swing.JSplitPane jSplitPane1; private javax.swing.JTextPane jTextPane1; private Tree tree; private final JPanel documentPanel = new JPanel(); private javax.swing.JMenuBar menuBar; // file menu private JMenu fileMenu; private JMenuItem openMenuItem; private JMenuItem openUrlMenuItem; private JMenuItem saveAsMenuItem; private JMenuItem saveMenuItem; private JMenu recentFilesMenu; private JMenuItem exitMenuItem; // edit menu private JMenu editMenu; private JMenuItem copyMenuItem; private JMenuItem pasteMenuItem; private JMenuItem cutMenuItem; private JMenuItem deleteMenuItem; // edit > find meu private JMenu findMenu; private JMenuItem findMenuItem; private JMenuItem findNextMenuItem; private JMenuItem findPreviousMenuItem; // view menu private JMenu viewMenu; private JMenuItem viewModeItem; /** * Constructor. */ public PDFDebugger() { initComponents(); } /** * This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ private void initComponents() { jSplitPane1 = new javax.swing.JSplitPane(); jScrollPane1 = new JScrollPane(); tree = new Tree(this); jScrollPane2 = new JScrollPane(); jTextPane1 = new javax.swing.JTextPane(); menuBar = new javax.swing.JMenuBar(); tree.setCellRenderer(new PDFTreeCellRenderer()); tree.setModel(null); setTitle("PDFBox Debugger"); addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowOpened(WindowEvent windowEvent) { tree.requestFocusInWindow(); super.windowOpened(windowEvent); } @Override public void windowClosing(WindowEvent evt) { exitForm(evt); } }); jScrollPane1.setBorder(new BevelBorder(BevelBorder.RAISED)); jScrollPane1.setPreferredSize(new Dimension(300, 500)); tree.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent evt) { jTree1ValueChanged(evt); } }); jScrollPane1.setViewportView(tree); jSplitPane1.setRightComponent(jScrollPane2); jSplitPane1.setDividerSize(3); jScrollPane2.setPreferredSize(new Dimension(300, 500)); jScrollPane2.setViewportView(jTextPane1); jSplitPane1.setLeftComponent(jScrollPane1); JScrollPane documentScroller = new JScrollPane(); documentScroller.setViewportView(documentPanel); statusPane = new TreeStatusPane(tree); statusPane.getPanel().setBorder(new BevelBorder(BevelBorder.RAISED)); statusPane.getPanel().setPreferredSize(new Dimension(300, 25)); getContentPane().add(statusPane.getPanel(), BorderLayout.PAGE_START); getContentPane().add(jSplitPane1, BorderLayout.CENTER); // create menus menuBar.add(createFileMenu()); menuBar.add(createEditMenu()); menuBar.add(createViewMenu()); setJMenuBar(menuBar); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-700)/2, (screenSize.height-600)/2, 700, 600); // drag and drop to open files setTransferHandler(new TransferHandler() { @Override public boolean canImport(TransferSupport transferSupport) { return transferSupport.isDataFlavorSupported(DataFlavor.javaFileListFlavor); } @Override @SuppressWarnings("unchecked") public boolean importData(TransferSupport transferSupport) { try { Transferable transferable = transferSupport.getTransferable(); List<File> files = (List<File>) transferable.getTransferData( DataFlavor.javaFileListFlavor); readPDFFile(files.get(0), ""); return true; } catch (IOException e) { throw new RuntimeException(e); } catch (UnsupportedFlavorException e) { throw new RuntimeException(e); } } }); // Mac OS X file open/quit handler if (IS_MAC_OS) { try { Method osxOpenFiles = getClass().getDeclaredMethod("osxOpenFiles", String.class); osxOpenFiles.setAccessible(true); OSXAdapter.setFileHandler(this, osxOpenFiles); Method osxQuit = getClass().getDeclaredMethod("osxQuit"); osxQuit.setAccessible(true); OSXAdapter.setQuitHandler(this, osxQuit); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } } private JMenu createFileMenu() { fileMenu = new JMenu(); fileMenu.setText("File"); openMenuItem = new JMenuItem(); openMenuItem.setText("Open..."); openMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, SHORCUT_KEY_MASK)); openMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { openMenuItemActionPerformed(evt); } }); fileMenu.add(openMenuItem); openUrlMenuItem = new JMenuItem(); openUrlMenuItem.setText("Open URL..."); openUrlMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, SHORCUT_KEY_MASK)); openUrlMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { String urlString = JOptionPane.showInputDialog("Enter an URL"); try { readPDFurl(urlString, ""); } catch (IOException e) { throw new RuntimeException(e); } } }); fileMenu.add(openUrlMenuItem); try { recentFiles = new RecentFiles(this.getClass(), 5); } catch (Exception e) { throw new RuntimeException(e); } recentFilesMenu = new JMenu(); recentFilesMenu.setText("Open Recent"); recentFilesMenu.setEnabled(false); addRecentFileItems(); fileMenu.add(recentFilesMenu); exitMenuItem = new JMenuItem(); exitMenuItem.setText("Exit"); exitMenuItem.setAccelerator(KeyStroke.getKeyStroke("alt F4")); exitMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { exitMenuItemActionPerformed(evt); } }); if (!IS_MAC_OS) { fileMenu.addSeparator(); fileMenu.add(exitMenuItem); } return fileMenu; } private JMenu createEditMenu() { editMenu = new JMenu(); editMenu.setText("Edit"); cutMenuItem = new JMenuItem(); cutMenuItem.setText("Cut"); cutMenuItem.setEnabled(false); editMenu.add(cutMenuItem); copyMenuItem = new JMenuItem(); copyMenuItem.setText("Copy"); copyMenuItem.setEnabled(false); editMenu.add(copyMenuItem); pasteMenuItem = new JMenuItem(); pasteMenuItem.setText("Paste"); pasteMenuItem.setEnabled(false); editMenu.add(pasteMenuItem); deleteMenuItem = new JMenuItem(); deleteMenuItem.setText("Delete"); deleteMenuItem.setEnabled(false); editMenu.add(deleteMenuItem); editMenu.addSeparator(); editMenu.add(createFindMenu()); return editMenu; } private JMenu createViewMenu() { viewMenu = new JMenu(); viewMenu.setText("View"); viewModeItem = new JMenuItem(); viewModeItem.setText("Show Pages"); viewModeItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if (isPageMode) { viewModeItem.setText("Show Pages"); isPageMode = false; } else { viewModeItem.setText("Show Internal Structure"); isPageMode = true; } if (document != null) { initTree(); } } }); viewMenu.add(viewModeItem); ZoomMenu zoomMenu = ZoomMenu.getInstance(); zoomMenu.setEnableMenu(false); viewMenu.add(zoomMenu.getMenu()); RotationMenu rotationMenu = RotationMenu.getInstance(); rotationMenu.setEnableMenu(false); viewMenu.add(rotationMenu.getMenu()); return viewMenu; } private JMenu createFindMenu() { findMenu = new JMenu("Find"); findMenu.setEnabled(false); findMenuItem = new JMenuItem(); findMenuItem.setActionCommand("find"); findMenuItem.setText("Find..."); findMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, SHORCUT_KEY_MASK)); findNextMenuItem = new JMenuItem(); findNextMenuItem.setText("Find Next"); if (IS_MAC_OS) { findNextMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, SHORCUT_KEY_MASK)); } else { findNextMenuItem.setAccelerator(KeyStroke.getKeyStroke("F3")); } findPreviousMenuItem = new JMenuItem(); findPreviousMenuItem.setText("Find Previous"); if (IS_MAC_OS) { findPreviousMenuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_G, SHORCUT_KEY_MASK | InputEvent.SHIFT_DOWN_MASK)); } else { findPreviousMenuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_F3, InputEvent.SHIFT_DOWN_MASK)); } findMenu.add(findMenuItem); findMenu.add(findNextMenuItem); findMenu.add(findPreviousMenuItem); return findMenu; } /** * Returns the File menu. */ public JMenu getFindMenu() { return findMenu; } /** * Returns the Edit > Find > Find menu item. */ public JMenuItem getFindMenuItem() { return findMenuItem; } /** * Returns the Edit > Find > Find Next menu item. */ public JMenuItem getFindNextMenuItem() { return findNextMenuItem; } /** * Returns the Edit > Find > Find Previous menu item. */ public JMenuItem getFindPreviousMenuItem() { return findPreviousMenuItem; } /** * This method is called via reflection on Mac OS X. */ private void osxOpenFiles(String filename) { try { readPDFFile(filename, ""); } catch (IOException e) { throw new RuntimeException(e); } } /** * This method is called via reflection on Mac OS X. */ private void osxQuit() { exitMenuItemActionPerformed(null); } private void openMenuItemActionPerformed(ActionEvent evt) { try { if (IS_MAC_OS) { FileDialog openDialog = new FileDialog(this, "Open"); openDialog.setFilenameFilter(new FilenameFilter() { @Override public boolean accept(File file, String s) { return file.getName().toLowerCase().endsWith(".pdf"); } }); openDialog.setVisible(true); if (openDialog.getFile() != null) { readPDFFile(openDialog.getFile(), ""); } } else { String[] extensions = new String[] {"pdf", "PDF"}; FileFilter pdfFilter = new ExtensionFileFilter(extensions, "PDF Files (*.pdf)"); FileOpenSaveDialog openDialog = new FileOpenSaveDialog(this, pdfFilter); File file = openDialog.openFile(); if (file != null) { readPDFFile(file, ""); } } } catch (IOException e) { throw new RuntimeException(e); } } private void jTree1ValueChanged(TreeSelectionEvent evt) { TreePath path = tree.getSelectionPath(); if (path != null) { try { Object selectedNode = path.getLastPathComponent(); if (isPage(selectedNode)) { showPage(selectedNode); return; } if (isSpecialColorSpace(selectedNode) || isOtherColorSpace(selectedNode)) { showColorPane(selectedNode); return; } if (path.getParentPath() != null && isFlagNode(selectedNode, path.getParentPath().getLastPathComponent())) { Object parentNode = path.getParentPath().getLastPathComponent(); showFlagPane(parentNode, selectedNode); return; } if (isStream(selectedNode)) { showStream((COSStream)getUnderneathObject(selectedNode), path); return; } if (isFont(selectedNode)) { showFont(selectedNode, path); return; } if (!jSplitPane1.getRightComponent().equals(jScrollPane2)) { jSplitPane1.setRightComponent(jScrollPane2); } jTextPane1.setText(convertToString(selectedNode)); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } } private boolean isSpecialColorSpace(Object selectedNode) { selectedNode = getUnderneathObject(selectedNode); if (selectedNode instanceof COSArray && ((COSArray) selectedNode).size() > 0) { COSBase arrayEntry = ((COSArray)selectedNode).get(0); if (arrayEntry instanceof COSName) { COSName name = (COSName) arrayEntry; return SPECIALCOLORSPACES.contains(name); } } return false; } private boolean isOtherColorSpace(Object selectedNode) { selectedNode = getUnderneathObject(selectedNode); if (selectedNode instanceof COSArray && ((COSArray) selectedNode).size() > 0) { COSBase arrayEntry = ((COSArray)selectedNode).get(0); if (arrayEntry instanceof COSName) { COSName name = (COSName) arrayEntry; return OTHERCOLORSPACES.contains(name); } } return false; } private boolean isPage(Object selectedNode) { selectedNode = getUnderneathObject(selectedNode); if (selectedNode instanceof COSDictionary) { COSDictionary dict = (COSDictionary) selectedNode; COSBase typeItem = dict.getItem(COSName.TYPE); if (COSName.PAGE.equals(typeItem)) { return true; } } else if (selectedNode instanceof PageEntry) { return true; } return false; } private boolean isFlagNode(Object selectedNode, Object parentNode) { if (selectedNode instanceof MapEntry) { Object key = ((MapEntry) selectedNode).getKey(); return (COSName.FLAGS.equals(key) && isFontDescriptor(parentNode)) || (COSName.F.equals(key) && isAnnot(parentNode)) || COSName.FF.equals(key) || COSName.PANOSE.equals(key); } return false; } private boolean isFontDescriptor(Object obj) { Object underneathObject = getUnderneathObject(obj); return underneathObject instanceof COSDictionary && ((COSDictionary) underneathObject).containsKey(COSName.TYPE) && ((COSDictionary) underneathObject).getCOSName(COSName.TYPE).equals(COSName.FONT_DESC); } private boolean isAnnot(Object obj) { Object underneathObject = getUnderneathObject(obj); return underneathObject instanceof COSDictionary && ((COSDictionary) underneathObject).containsKey(COSName.TYPE) && ((COSDictionary) underneathObject).getCOSName(COSName.TYPE).equals(COSName.ANNOT); } private boolean isStream(Object selectedNode) { return getUnderneathObject(selectedNode) instanceof COSStream; } private boolean isFont(Object selectedNode) { selectedNode = getUnderneathObject(selectedNode); if (selectedNode instanceof COSDictionary) { COSDictionary dic = (COSDictionary)selectedNode; return dic.containsKey(COSName.TYPE) && dic.getCOSName(COSName.TYPE).equals(COSName.FONT) && !isCIDFont(dic); } return false; } private boolean isCIDFont(COSDictionary dic) { return dic.containsKey(COSName.SUBTYPE) && (dic.getCOSName(COSName.SUBTYPE).equals(COSName.CID_FONT_TYPE0) || dic.getCOSName(COSName.SUBTYPE).equals(COSName.CID_FONT_TYPE2)); } /** * Show a Panel describing color spaces in more detail and interactive way. * @param csNode the special color space containing node. */ private void showColorPane(Object csNode) { csNode = getUnderneathObject(csNode); if (csNode instanceof COSArray && ((COSArray) csNode).size() > 0) { COSArray array = (COSArray)csNode; COSBase arrayEntry = array.get(0); if (arrayEntry instanceof COSName) { COSName csName = (COSName) arrayEntry; if (csName.equals(COSName.SEPARATION)) { jSplitPane1.setRightComponent(new CSSeparation(array).getPanel()); } else if (csName.equals(COSName.DEVICEN)) { jSplitPane1.setRightComponent(new CSDeviceN(array).getPanel()); } else if (csName.equals(COSName.INDEXED)) { jSplitPane1.setRightComponent(new CSIndexed(array).getPanel()); } else if (OTHERCOLORSPACES.contains(csName)) { jSplitPane1.setRightComponent(new CSArrayBased(array).getPanel()); } } } } private void showPage(Object selectedNode) { selectedNode = getUnderneathObject(selectedNode); COSDictionary page; if (selectedNode instanceof COSDictionary) { page = (COSDictionary) selectedNode; } else { page = ((PageEntry) selectedNode).getDict(); } COSBase typeItem = page.getItem(COSName.TYPE); if (COSName.PAGE.equals(typeItem)) { PagePane pagePane = new PagePane(document, page); jSplitPane1.setRightComponent(new JScrollPane(pagePane.getPanel())); } } private void showFlagPane(Object parentNode, Object selectedNode) { parentNode = getUnderneathObject(parentNode); if (parentNode instanceof COSDictionary) { selectedNode = ((MapEntry)selectedNode).getKey(); selectedNode = getUnderneathObject(selectedNode); FlagBitsPane flagBitsPane = new FlagBitsPane((COSDictionary) parentNode, (COSName) selectedNode); jSplitPane1.setRightComponent(flagBitsPane.getPane()); } } private void showStream(COSStream stream, TreePath path) { boolean isContentStream = false; boolean isThumb = false; COSName key = getNodeKey(path.getLastPathComponent()); COSName parentKey = getNodeKey(path.getParentPath().getLastPathComponent()); COSDictionary resourcesDic = null; if (COSName.CONTENTS.equals(key)) { Object pageObj = path.getParentPath().getLastPathComponent(); COSDictionary page = (COSDictionary) getUnderneathObject(pageObj); resourcesDic = (COSDictionary) page.getDictionaryObject(COSName.RESOURCES); isContentStream = true; } else if (COSName.CONTENTS.equals(parentKey) || COSName.CHAR_PROCS.equals(parentKey)) { Object pageObj = path.getParentPath().getParentPath().getLastPathComponent(); COSDictionary page = (COSDictionary) getUnderneathObject(pageObj); resourcesDic = (COSDictionary) page.getDictionaryObject(COSName.RESOURCES); isContentStream = true; } else if (COSName.FORM.equals(stream.getCOSName(COSName.SUBTYPE)) || COSName.PATTERN.equals(stream.getCOSName(COSName.TYPE))) { if (stream.containsKey(COSName.RESOURCES)) { resourcesDic = (COSDictionary) stream.getDictionaryObject(COSName.RESOURCES); } isContentStream = true; } else if (COSName.IMAGE.equals((stream).getCOSName(COSName.SUBTYPE))) { Object resourcesObj = path.getParentPath().getParentPath().getLastPathComponent(); resourcesDic = (COSDictionary) getUnderneathObject(resourcesObj); } else if (COSName.THUMB.equals(key)) { resourcesDic = null; isThumb = true; } StreamPane streamPane = new StreamPane(stream, isContentStream, isThumb, resourcesDic); jSplitPane1.setRightComponent(streamPane.getPanel()); } private void showFont(Object selectedNode, TreePath path) { COSName fontName = getNodeKey(selectedNode); COSDictionary resourceDic = (COSDictionary) getUnderneathObject(path.getParentPath().getParentPath().getLastPathComponent()); FontEncodingPaneController fontEncodingPaneController = new FontEncodingPaneController(fontName, resourceDic); jSplitPane1.setRightComponent(fontEncodingPaneController.getPane()); } private COSName getNodeKey(Object selectedNode) { if (selectedNode instanceof MapEntry) { return ((MapEntry) selectedNode).getKey(); } return null; } private Object getUnderneathObject(Object selectedNode) { if (selectedNode instanceof MapEntry) { selectedNode = ((MapEntry) selectedNode).getValue(); } else if (selectedNode instanceof ArrayEntry) { selectedNode = ((ArrayEntry) selectedNode).getValue(); } else if (selectedNode instanceof PageEntry) { selectedNode = ((PageEntry) selectedNode).getDict(); } if (selectedNode instanceof COSObject) { selectedNode = ((COSObject) selectedNode).getObject(); } return selectedNode; } private String convertToString( Object selectedNode ) { String data = null; if(selectedNode instanceof COSBoolean) { data = "" + ((COSBoolean)selectedNode).getValue(); } else if( selectedNode instanceof COSFloat ) { data = "" + ((COSFloat)selectedNode).floatValue(); } else if( selectedNode instanceof COSNull ) { data = "null"; } else if( selectedNode instanceof COSInteger ) { data = "" + ((COSInteger)selectedNode).intValue(); } else if( selectedNode instanceof COSName ) { data = "" + ((COSName)selectedNode).getName(); } else if( selectedNode instanceof COSString ) { String text = ((COSString) selectedNode).getString(); // display unprintable strings as hex for (char c : text.toCharArray()) { if (Character.isISOControl(c)) { text = "<" + ((COSString) selectedNode).toHexString() + ">"; break; } } data = "" + text; } else if( selectedNode instanceof COSStream ) { try { COSStream stream = (COSStream)selectedNode; InputStream ioStream = stream.getUnfilteredStream(); ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int amountRead; while( (amountRead = ioStream.read( buffer, 0, buffer.length ) ) != -1 ) { byteArray.write( buffer, 0, amountRead ); } data = byteArray.toString(); } catch( IOException e ) { throw new RuntimeException(e); } } else if( selectedNode instanceof MapEntry ) { data = convertToString( ((MapEntry)selectedNode).getValue() ); } else if( selectedNode instanceof ArrayEntry ) { data = convertToString( ((ArrayEntry)selectedNode).getValue() ); } return data; } private void exitMenuItemActionPerformed(ActionEvent evt) { if( document != null ) { try { document.close(); if (!currentFilePath.startsWith("http")) { recentFiles.addFile(currentFilePath); } recentFiles.close(); } catch( IOException e ) { throw new RuntimeException(e); } } System.exit(0); } /** * Exit the Application. */ private void exitForm(WindowEvent evt) { if( document != null ) { try { document.close(); if (!currentFilePath.startsWith("http")) { recentFiles.addFile(currentFilePath); } recentFiles.close(); } catch( IOException e ) { throw new RuntimeException(e); } } System.exit(0); } /** * Entry point. * * @param args the command line arguments * @throws Exception If anything goes wrong. */ public static void main(String[] args) throws Exception { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); System.setProperty("apple.laf.useScreenMenuBar", "true"); // handle uncaught exceptions Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable throwable) { StringBuilder sb = new StringBuilder(); sb.append(throwable.toString()); for (StackTraceElement element : throwable.getStackTrace()) { sb.append('\n'); sb.append(element); } JOptionPane.showMessageDialog(null, "Error: " + sb.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }); final PDFDebugger viewer = new PDFDebugger(); // open file, if any String filename = null; String password = ""; for( int i = 0; i < args.length; i++ ) { if( args[i].equals( PASSWORD ) ) { i++; if( i >= args.length ) { usage(); } password = args[i]; } else { filename = args[i]; } } if (filename != null) { File file = new File(filename); if (file.exists()) { viewer.readPDFFile( filename, password ); } } viewer.setVisible(true); } private void readPDFFile(String filePath, String password) throws IOException { File file = new File(filePath); readPDFFile(file, password); } private void readPDFFile(File file, String password) throws IOException { if( document != null ) { document.close(); if (!currentFilePath.startsWith("http")) { recentFiles.addFile(currentFilePath); } } currentFilePath = file.getPath(); recentFiles.removeFile(file.getPath()); parseDocument( file, password ); initTree(); if (IS_MAC_OS) { setTitle(file.getName()); getRootPane().putClientProperty("Window.documentFile", file); } else { setTitle("PDF Debugger - " + file.getAbsolutePath()); } addRecentFileItems(); } private void readPDFurl(String urlString, String password) throws IOException { if (document != null) { document.close(); if (!currentFilePath.startsWith("http")) { recentFiles.addFile(currentFilePath); } } currentFilePath = urlString; URL url = new URL(urlString); document = PDDocument.load(url.openStream(), password); initTree(); if (IS_MAC_OS) { setTitle(urlString); } else { setTitle("PDF Debugger - " + urlString); } addRecentFileItems(); } private void initTree() { TreeStatus treeStatus = new TreeStatus(document.getDocument().getTrailer()); statusPane.updateTreeStatus(treeStatus); if (isPageMode) { File file = new File(currentFilePath); DocumentEntry documentEntry = new DocumentEntry(document, file.getName()); tree.setModel(new PDFTreeModel(documentEntry)); // Root/Pages/Kids/[0] is not always the first page, so use the first row instead: tree.setSelectionPath(tree.getPathForRow(1)); } else { tree.setModel(new PDFTreeModel(document)); tree.setSelectionPath(treeStatus.getPathForString("Root")); } } /** * This will parse a document. * * @param file The file addressing the document. * * @throws IOException If there is an error parsing the document. */ private void parseDocument( File file, String password )throws IOException { document = PDDocument.load(file, password); } private void addRecentFileItems() { Action recentMenuAction = new AbstractAction() { @Override public void actionPerformed(ActionEvent actionEvent) { String filePath = (String) ((JComponent) actionEvent.getSource()).getClientProperty("path"); try { readPDFFile(filePath, ""); } catch (Exception e) { throw new RuntimeException(e); } } }; if (!recentFiles.isEmpty()) { recentFilesMenu.removeAll(); List<String> files = recentFiles.getFiles(); for (int i = files.size() - 1; i >= 0; i--) { String path = files.get(i); String name = new File(path).getName(); JMenuItem recentFileMenuItem = new JMenuItem(name); recentFileMenuItem.putClientProperty("path", path); recentFileMenuItem.addActionListener(recentMenuAction); recentFilesMenu.add(recentFileMenuItem); } recentFilesMenu.setEnabled(true); } } /** * This will print out a message telling how to use this utility. */ private static void usage() { System.err.println( "usage: java -jar pdfbox-app-x.y.z.jar PDFDebugger [OPTIONS] <input-file>\n" + " -password <password> Password to decrypt the document\n" + " <input-file> The PDF document to be loaded\n" ); } }
tools/src/main/java/org/apache/pdfbox/tools/PDFDebugger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pdfbox.tools; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FileDialog; import java.awt.Toolkit; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowEvent; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.URL; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.KeyStroke; import javax.swing.TransferHandler; import javax.swing.UIManager; import javax.swing.border.BevelBorder; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.filechooser.FileFilter; import javax.swing.tree.TreePath; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSBoolean; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSFloat; import org.apache.pdfbox.cos.COSInteger; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.cos.COSNull; import org.apache.pdfbox.cos.COSObject; import org.apache.pdfbox.cos.COSStream; import org.apache.pdfbox.cos.COSString; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.tools.gui.ArrayEntry; import org.apache.pdfbox.tools.gui.DocumentEntry; import org.apache.pdfbox.tools.gui.MapEntry; import org.apache.pdfbox.tools.gui.OSXAdapter; import org.apache.pdfbox.tools.gui.PDFTreeCellRenderer; import org.apache.pdfbox.tools.gui.PDFTreeModel; import org.apache.pdfbox.tools.gui.PageEntry; import org.apache.pdfbox.tools.pdfdebugger.colorpane.CSArrayBased; import org.apache.pdfbox.tools.pdfdebugger.colorpane.CSDeviceN; import org.apache.pdfbox.tools.pdfdebugger.colorpane.CSIndexed; import org.apache.pdfbox.tools.pdfdebugger.colorpane.CSSeparation; import org.apache.pdfbox.tools.pdfdebugger.flagbitspane.FlagBitsPane; import org.apache.pdfbox.tools.pdfdebugger.fontencodingpane.FontEncodingPaneController; import org.apache.pdfbox.tools.pdfdebugger.pagepane.PagePane; import org.apache.pdfbox.tools.pdfdebugger.streampane.StreamPane; import org.apache.pdfbox.tools.pdfdebugger.treestatus.TreeStatus; import org.apache.pdfbox.tools.pdfdebugger.treestatus.TreeStatusPane; import org.apache.pdfbox.tools.pdfdebugger.ui.RotationMenu; import org.apache.pdfbox.tools.pdfdebugger.ui.Tree; import org.apache.pdfbox.tools.pdfdebugger.ui.ZoomMenu; import org.apache.pdfbox.tools.util.FileOpenSaveDialog; import org.apache.pdfbox.tools.util.RecentFiles; /** * PDF Debugger. * * @author wurtz * @author Ben Litchfield */ public class PDFDebugger extends JFrame { private static final Set<COSName> SPECIALCOLORSPACES = new HashSet<COSName>(Arrays.asList(COSName.INDEXED, COSName.SEPARATION, COSName.DEVICEN)); private static final Set<COSName> OTHERCOLORSPACES = new HashSet<COSName>(Arrays.asList(COSName.ICCBASED, COSName.PATTERN, COSName.CALGRAY, COSName.CALRGB, COSName.LAB)); private static final String PASSWORD = "-password"; private static final int SHORCUT_KEY_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); private TreeStatusPane statusPane; private RecentFiles recentFiles; private boolean isPageMode; private PDDocument document; private String currentFilePath; private static final String OS_NAME = System.getProperty("os.name").toLowerCase(); private static final boolean IS_MAC_OS = OS_NAME.startsWith("mac os x"); private JScrollPane jScrollPane1; private JScrollPane jScrollPane2; private javax.swing.JSplitPane jSplitPane1; private javax.swing.JTextPane jTextPane1; private Tree tree; private final JPanel documentPanel = new JPanel(); private javax.swing.JMenuBar menuBar; // file menu private JMenu fileMenu; private JMenuItem openMenuItem; private JMenuItem openUrlMenuItem; private JMenuItem saveAsMenuItem; private JMenuItem saveMenuItem; private JMenu recentFilesMenu; private JMenuItem exitMenuItem; // edit menu private JMenu editMenu; private JMenuItem copyMenuItem; private JMenuItem pasteMenuItem; private JMenuItem cutMenuItem; private JMenuItem deleteMenuItem; // edit > find meu private JMenu findMenu; private JMenuItem findMenuItem; private JMenuItem findNextMenuItem; private JMenuItem findPreviousMenuItem; // view menu private JMenu viewMenu; private JMenuItem viewModeItem; /** * Constructor. */ public PDFDebugger() { initComponents(); } /** * This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ private void initComponents() { jSplitPane1 = new javax.swing.JSplitPane(); jScrollPane1 = new JScrollPane(); tree = new Tree(this); jScrollPane2 = new JScrollPane(); jTextPane1 = new javax.swing.JTextPane(); menuBar = new javax.swing.JMenuBar(); tree.setCellRenderer(new PDFTreeCellRenderer()); tree.setModel(null); setTitle("PDFBox Debugger"); addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowOpened(WindowEvent windowEvent) { tree.requestFocusInWindow(); super.windowOpened(windowEvent); } @Override public void windowClosing(WindowEvent evt) { exitForm(evt); } }); jScrollPane1.setBorder(new BevelBorder(BevelBorder.RAISED)); jScrollPane1.setPreferredSize(new Dimension(300, 500)); tree.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent evt) { jTree1ValueChanged(evt); } }); jScrollPane1.setViewportView(tree); jSplitPane1.setRightComponent(jScrollPane2); jSplitPane1.setDividerSize(3); jScrollPane2.setPreferredSize(new Dimension(300, 500)); jScrollPane2.setViewportView(jTextPane1); jSplitPane1.setLeftComponent(jScrollPane1); JScrollPane documentScroller = new JScrollPane(); documentScroller.setViewportView(documentPanel); statusPane = new TreeStatusPane(tree); statusPane.getPanel().setBorder(new BevelBorder(BevelBorder.RAISED)); statusPane.getPanel().setPreferredSize(new Dimension(300, 25)); getContentPane().add(statusPane.getPanel(), BorderLayout.PAGE_START); getContentPane().add(jSplitPane1, BorderLayout.CENTER); // create menus menuBar.add(createFileMenu()); menuBar.add(createEditMenu()); menuBar.add(createViewMenu()); setJMenuBar(menuBar); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-700)/2, (screenSize.height-600)/2, 700, 600); // drag and drop to open files setTransferHandler(new TransferHandler() { @Override public boolean canImport(TransferSupport transferSupport) { return transferSupport.isDataFlavorSupported(DataFlavor.javaFileListFlavor); } @Override @SuppressWarnings("unchecked") public boolean importData(TransferSupport transferSupport) { try { Transferable transferable = transferSupport.getTransferable(); List<File> files = (List<File>) transferable.getTransferData( DataFlavor.javaFileListFlavor); readPDFFile(files.get(0), ""); return true; } catch (IOException e) { throw new RuntimeException(e); } catch (UnsupportedFlavorException e) { throw new RuntimeException(e); } } }); // Mac OS X file open/quit handler if (IS_MAC_OS) { try { Method osxOpenFiles = getClass().getDeclaredMethod("osxOpenFiles", String.class); osxOpenFiles.setAccessible(true); OSXAdapter.setFileHandler(this, osxOpenFiles); Method osxQuit = getClass().getDeclaredMethod("osxQuit"); osxQuit.setAccessible(true); OSXAdapter.setQuitHandler(this, osxQuit); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } } private JMenu createFileMenu() { fileMenu = new JMenu(); fileMenu.setText("File"); openMenuItem = new JMenuItem(); openMenuItem.setText("Open..."); openMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, SHORCUT_KEY_MASK)); openMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { openMenuItemActionPerformed(evt); } }); fileMenu.add(openMenuItem); openUrlMenuItem = new JMenuItem(); openUrlMenuItem.setText("Open URL..."); openUrlMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, SHORCUT_KEY_MASK)); openUrlMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { String urlString = JOptionPane.showInputDialog("Enter an URL"); try { readPDFurl(urlString, ""); } catch (IOException e) { throw new RuntimeException(e); } } }); fileMenu.add(openUrlMenuItem); try { recentFiles = new RecentFiles(this.getClass(), 5); } catch (Exception e) { throw new RuntimeException(e); } recentFilesMenu = new JMenu(); recentFilesMenu.setText("Open Recent"); recentFilesMenu.setEnabled(false); addRecentFileItems(); fileMenu.add(recentFilesMenu); exitMenuItem = new JMenuItem(); exitMenuItem.setText("Exit"); exitMenuItem.setAccelerator(KeyStroke.getKeyStroke("alt F4")); exitMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { exitMenuItemActionPerformed(evt); } }); if (!IS_MAC_OS) { fileMenu.addSeparator(); fileMenu.add(exitMenuItem); } return fileMenu; } private JMenu createEditMenu() { editMenu = new JMenu(); editMenu.setText("Edit"); cutMenuItem = new JMenuItem(); cutMenuItem.setText("Cut"); cutMenuItem.setEnabled(false); editMenu.add(cutMenuItem); copyMenuItem = new JMenuItem(); copyMenuItem.setText("Copy"); copyMenuItem.setEnabled(false); editMenu.add(copyMenuItem); pasteMenuItem = new JMenuItem(); pasteMenuItem.setText("Paste"); pasteMenuItem.setEnabled(false); editMenu.add(pasteMenuItem); deleteMenuItem = new JMenuItem(); deleteMenuItem.setText("Delete"); deleteMenuItem.setEnabled(false); editMenu.add(deleteMenuItem); editMenu.addSeparator(); editMenu.add(createFindMenu()); return editMenu; } private JMenu createViewMenu() { viewMenu = new JMenu(); viewMenu.setText("View"); viewModeItem = new JMenuItem(); viewModeItem.setText("Show Pages"); viewModeItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if (isPageMode) { viewModeItem.setText("Show Pages"); isPageMode = false; } else { viewModeItem.setText("Show Internal Structure"); isPageMode = true; } initTree(); } }); viewMenu.add(viewModeItem); ZoomMenu zoomMenu = ZoomMenu.getInstance(); zoomMenu.setEnableMenu(false); viewMenu.add(zoomMenu.getMenu()); RotationMenu rotationMenu = RotationMenu.getInstance(); rotationMenu.setEnableMenu(false); viewMenu.add(rotationMenu.getMenu()); return viewMenu; } private JMenu createFindMenu() { findMenu = new JMenu("Find"); findMenu.setEnabled(false); findMenuItem = new JMenuItem(); findMenuItem.setActionCommand("find"); findMenuItem.setText("Find..."); findMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, SHORCUT_KEY_MASK)); findNextMenuItem = new JMenuItem(); findNextMenuItem.setText("Find Next"); if (IS_MAC_OS) { findNextMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, SHORCUT_KEY_MASK)); } else { findNextMenuItem.setAccelerator(KeyStroke.getKeyStroke("F3")); } findPreviousMenuItem = new JMenuItem(); findPreviousMenuItem.setText("Find Previous"); if (IS_MAC_OS) { findPreviousMenuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_G, SHORCUT_KEY_MASK | InputEvent.SHIFT_DOWN_MASK)); } else { findPreviousMenuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_F3, InputEvent.SHIFT_DOWN_MASK)); } findMenu.add(findMenuItem); findMenu.add(findNextMenuItem); findMenu.add(findPreviousMenuItem); return findMenu; } /** * Returns the File menu. */ public JMenu getFindMenu() { return findMenu; } /** * Returns the Edit > Find > Find menu item. */ public JMenuItem getFindMenuItem() { return findMenuItem; } /** * Returns the Edit > Find > Find Next menu item. */ public JMenuItem getFindNextMenuItem() { return findNextMenuItem; } /** * Returns the Edit > Find > Find Previous menu item. */ public JMenuItem getFindPreviousMenuItem() { return findPreviousMenuItem; } /** * This method is called via reflection on Mac OS X. */ private void osxOpenFiles(String filename) { try { readPDFFile(filename, ""); } catch (IOException e) { throw new RuntimeException(e); } } /** * This method is called via reflection on Mac OS X. */ private void osxQuit() { exitMenuItemActionPerformed(null); } private void openMenuItemActionPerformed(ActionEvent evt) { try { if (IS_MAC_OS) { FileDialog openDialog = new FileDialog(this, "Open"); openDialog.setFilenameFilter(new FilenameFilter() { @Override public boolean accept(File file, String s) { return file.getName().toLowerCase().endsWith(".pdf"); } }); openDialog.setVisible(true); if (openDialog.getFile() != null) { readPDFFile(openDialog.getFile(), ""); } } else { String[] extensions = new String[] {"pdf", "PDF"}; FileFilter pdfFilter = new ExtensionFileFilter(extensions, "PDF Files (*.pdf)"); FileOpenSaveDialog openDialog = new FileOpenSaveDialog(this, pdfFilter); File file = openDialog.openFile(); if (file != null) { readPDFFile(file, ""); } } } catch (IOException e) { throw new RuntimeException(e); } } private void jTree1ValueChanged(TreeSelectionEvent evt) { TreePath path = tree.getSelectionPath(); if (path != null) { try { Object selectedNode = path.getLastPathComponent(); if (isPage(selectedNode)) { showPage(selectedNode); return; } if (isSpecialColorSpace(selectedNode) || isOtherColorSpace(selectedNode)) { showColorPane(selectedNode); return; } if (path.getParentPath() != null && isFlagNode(selectedNode, path.getParentPath().getLastPathComponent())) { Object parentNode = path.getParentPath().getLastPathComponent(); showFlagPane(parentNode, selectedNode); return; } if (isStream(selectedNode)) { showStream((COSStream)getUnderneathObject(selectedNode), path); return; } if (isFont(selectedNode)) { showFont(selectedNode, path); return; } if (!jSplitPane1.getRightComponent().equals(jScrollPane2)) { jSplitPane1.setRightComponent(jScrollPane2); } jTextPane1.setText(convertToString(selectedNode)); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } } private boolean isSpecialColorSpace(Object selectedNode) { selectedNode = getUnderneathObject(selectedNode); if (selectedNode instanceof COSArray && ((COSArray) selectedNode).size() > 0) { COSBase arrayEntry = ((COSArray)selectedNode).get(0); if (arrayEntry instanceof COSName) { COSName name = (COSName) arrayEntry; return SPECIALCOLORSPACES.contains(name); } } return false; } private boolean isOtherColorSpace(Object selectedNode) { selectedNode = getUnderneathObject(selectedNode); if (selectedNode instanceof COSArray && ((COSArray) selectedNode).size() > 0) { COSBase arrayEntry = ((COSArray)selectedNode).get(0); if (arrayEntry instanceof COSName) { COSName name = (COSName) arrayEntry; return OTHERCOLORSPACES.contains(name); } } return false; } private boolean isPage(Object selectedNode) { selectedNode = getUnderneathObject(selectedNode); if (selectedNode instanceof COSDictionary) { COSDictionary dict = (COSDictionary) selectedNode; COSBase typeItem = dict.getItem(COSName.TYPE); if (COSName.PAGE.equals(typeItem)) { return true; } } else if (selectedNode instanceof PageEntry) { return true; } return false; } private boolean isFlagNode(Object selectedNode, Object parentNode) { if (selectedNode instanceof MapEntry) { Object key = ((MapEntry) selectedNode).getKey(); return (COSName.FLAGS.equals(key) && isFontDescriptor(parentNode)) || (COSName.F.equals(key) && isAnnot(parentNode)) || COSName.FF.equals(key) || COSName.PANOSE.equals(key); } return false; } private boolean isFontDescriptor(Object obj) { Object underneathObject = getUnderneathObject(obj); return underneathObject instanceof COSDictionary && ((COSDictionary) underneathObject).containsKey(COSName.TYPE) && ((COSDictionary) underneathObject).getCOSName(COSName.TYPE).equals(COSName.FONT_DESC); } private boolean isAnnot(Object obj) { Object underneathObject = getUnderneathObject(obj); return underneathObject instanceof COSDictionary && ((COSDictionary) underneathObject).containsKey(COSName.TYPE) && ((COSDictionary) underneathObject).getCOSName(COSName.TYPE).equals(COSName.ANNOT); } private boolean isStream(Object selectedNode) { return getUnderneathObject(selectedNode) instanceof COSStream; } private boolean isFont(Object selectedNode) { selectedNode = getUnderneathObject(selectedNode); if (selectedNode instanceof COSDictionary) { COSDictionary dic = (COSDictionary)selectedNode; return dic.containsKey(COSName.TYPE) && dic.getCOSName(COSName.TYPE).equals(COSName.FONT) && !isCIDFont(dic); } return false; } private boolean isCIDFont(COSDictionary dic) { return dic.containsKey(COSName.SUBTYPE) && (dic.getCOSName(COSName.SUBTYPE).equals(COSName.CID_FONT_TYPE0) || dic.getCOSName(COSName.SUBTYPE).equals(COSName.CID_FONT_TYPE2)); } /** * Show a Panel describing color spaces in more detail and interactive way. * @param csNode the special color space containing node. */ private void showColorPane(Object csNode) { csNode = getUnderneathObject(csNode); if (csNode instanceof COSArray && ((COSArray) csNode).size() > 0) { COSArray array = (COSArray)csNode; COSBase arrayEntry = array.get(0); if (arrayEntry instanceof COSName) { COSName csName = (COSName) arrayEntry; if (csName.equals(COSName.SEPARATION)) { jSplitPane1.setRightComponent(new CSSeparation(array).getPanel()); } else if (csName.equals(COSName.DEVICEN)) { jSplitPane1.setRightComponent(new CSDeviceN(array).getPanel()); } else if (csName.equals(COSName.INDEXED)) { jSplitPane1.setRightComponent(new CSIndexed(array).getPanel()); } else if (OTHERCOLORSPACES.contains(csName)) { jSplitPane1.setRightComponent(new CSArrayBased(array).getPanel()); } } } } private void showPage(Object selectedNode) { selectedNode = getUnderneathObject(selectedNode); COSDictionary page; if (selectedNode instanceof COSDictionary) { page = (COSDictionary) selectedNode; } else { page = ((PageEntry) selectedNode).getDict(); } COSBase typeItem = page.getItem(COSName.TYPE); if (COSName.PAGE.equals(typeItem)) { PagePane pagePane = new PagePane(document, page); jSplitPane1.setRightComponent(new JScrollPane(pagePane.getPanel())); } } private void showFlagPane(Object parentNode, Object selectedNode) { parentNode = getUnderneathObject(parentNode); if (parentNode instanceof COSDictionary) { selectedNode = ((MapEntry)selectedNode).getKey(); selectedNode = getUnderneathObject(selectedNode); FlagBitsPane flagBitsPane = new FlagBitsPane((COSDictionary) parentNode, (COSName) selectedNode); jSplitPane1.setRightComponent(flagBitsPane.getPane()); } } private void showStream(COSStream stream, TreePath path) { boolean isContentStream = false; boolean isThumb = false; COSName key = getNodeKey(path.getLastPathComponent()); COSName parentKey = getNodeKey(path.getParentPath().getLastPathComponent()); COSDictionary resourcesDic = null; if (COSName.CONTENTS.equals(key)) { Object pageObj = path.getParentPath().getLastPathComponent(); COSDictionary page = (COSDictionary) getUnderneathObject(pageObj); resourcesDic = (COSDictionary) page.getDictionaryObject(COSName.RESOURCES); isContentStream = true; } else if (COSName.CONTENTS.equals(parentKey) || COSName.CHAR_PROCS.equals(parentKey)) { Object pageObj = path.getParentPath().getParentPath().getLastPathComponent(); COSDictionary page = (COSDictionary) getUnderneathObject(pageObj); resourcesDic = (COSDictionary) page.getDictionaryObject(COSName.RESOURCES); isContentStream = true; } else if (COSName.FORM.equals(stream.getCOSName(COSName.SUBTYPE)) || COSName.PATTERN.equals(stream.getCOSName(COSName.TYPE))) { if (stream.containsKey(COSName.RESOURCES)) { resourcesDic = (COSDictionary) stream.getDictionaryObject(COSName.RESOURCES); } isContentStream = true; } else if (COSName.IMAGE.equals((stream).getCOSName(COSName.SUBTYPE))) { Object resourcesObj = path.getParentPath().getParentPath().getLastPathComponent(); resourcesDic = (COSDictionary) getUnderneathObject(resourcesObj); } else if (COSName.THUMB.equals(key)) { resourcesDic = null; isThumb = true; } StreamPane streamPane = new StreamPane(stream, isContentStream, isThumb, resourcesDic); jSplitPane1.setRightComponent(streamPane.getPanel()); } private void showFont(Object selectedNode, TreePath path) { COSName fontName = getNodeKey(selectedNode); COSDictionary resourceDic = (COSDictionary) getUnderneathObject(path.getParentPath().getParentPath().getLastPathComponent()); FontEncodingPaneController fontEncodingPaneController = new FontEncodingPaneController(fontName, resourceDic); jSplitPane1.setRightComponent(fontEncodingPaneController.getPane()); } private COSName getNodeKey(Object selectedNode) { if (selectedNode instanceof MapEntry) { return ((MapEntry) selectedNode).getKey(); } return null; } private Object getUnderneathObject(Object selectedNode) { if (selectedNode instanceof MapEntry) { selectedNode = ((MapEntry) selectedNode).getValue(); } else if (selectedNode instanceof ArrayEntry) { selectedNode = ((ArrayEntry) selectedNode).getValue(); } else if (selectedNode instanceof PageEntry) { selectedNode = ((PageEntry) selectedNode).getDict(); } if (selectedNode instanceof COSObject) { selectedNode = ((COSObject) selectedNode).getObject(); } return selectedNode; } private String convertToString( Object selectedNode ) { String data = null; if(selectedNode instanceof COSBoolean) { data = "" + ((COSBoolean)selectedNode).getValue(); } else if( selectedNode instanceof COSFloat ) { data = "" + ((COSFloat)selectedNode).floatValue(); } else if( selectedNode instanceof COSNull ) { data = "null"; } else if( selectedNode instanceof COSInteger ) { data = "" + ((COSInteger)selectedNode).intValue(); } else if( selectedNode instanceof COSName ) { data = "" + ((COSName)selectedNode).getName(); } else if( selectedNode instanceof COSString ) { String text = ((COSString) selectedNode).getString(); // display unprintable strings as hex for (char c : text.toCharArray()) { if (Character.isISOControl(c)) { text = "<" + ((COSString) selectedNode).toHexString() + ">"; break; } } data = "" + text; } else if( selectedNode instanceof COSStream ) { try { COSStream stream = (COSStream)selectedNode; InputStream ioStream = stream.getUnfilteredStream(); ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int amountRead; while( (amountRead = ioStream.read( buffer, 0, buffer.length ) ) != -1 ) { byteArray.write( buffer, 0, amountRead ); } data = byteArray.toString(); } catch( IOException e ) { throw new RuntimeException(e); } } else if( selectedNode instanceof MapEntry ) { data = convertToString( ((MapEntry)selectedNode).getValue() ); } else if( selectedNode instanceof ArrayEntry ) { data = convertToString( ((ArrayEntry)selectedNode).getValue() ); } return data; } private void exitMenuItemActionPerformed(ActionEvent evt) { if( document != null ) { try { document.close(); if (!currentFilePath.startsWith("http")) { recentFiles.addFile(currentFilePath); } recentFiles.close(); } catch( IOException e ) { throw new RuntimeException(e); } } System.exit(0); } /** * Exit the Application. */ private void exitForm(WindowEvent evt) { if( document != null ) { try { document.close(); if (!currentFilePath.startsWith("http")) { recentFiles.addFile(currentFilePath); } recentFiles.close(); } catch( IOException e ) { throw new RuntimeException(e); } } System.exit(0); } /** * Entry point. * * @param args the command line arguments * @throws Exception If anything goes wrong. */ public static void main(String[] args) throws Exception { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); System.setProperty("apple.laf.useScreenMenuBar", "true"); // handle uncaught exceptions Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable throwable) { StringBuilder sb = new StringBuilder(); sb.append(throwable.toString()); for (StackTraceElement element : throwable.getStackTrace()) { sb.append('\n'); sb.append(element); } JOptionPane.showMessageDialog(null, "Error: " + sb.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }); final PDFDebugger viewer = new PDFDebugger(); // open file, if any String filename = null; String password = ""; for( int i = 0; i < args.length; i++ ) { if( args[i].equals( PASSWORD ) ) { i++; if( i >= args.length ) { usage(); } password = args[i]; } else { filename = args[i]; } } if (filename != null) { File file = new File(filename); if (file.exists()) { viewer.readPDFFile( filename, password ); } } viewer.setVisible(true); } private void readPDFFile(String filePath, String password) throws IOException { File file = new File(filePath); readPDFFile(file, password); } private void readPDFFile(File file, String password) throws IOException { if( document != null ) { document.close(); if (!currentFilePath.startsWith("http")) { recentFiles.addFile(currentFilePath); } } currentFilePath = file.getPath(); recentFiles.removeFile(file.getPath()); parseDocument( file, password ); initTree(); if (IS_MAC_OS) { setTitle(file.getName()); getRootPane().putClientProperty("Window.documentFile", file); } else { setTitle("PDF Debugger - " + file.getAbsolutePath()); } addRecentFileItems(); } private void readPDFurl(String urlString, String password) throws IOException { if (document != null) { document.close(); if (!currentFilePath.startsWith("http")) { recentFiles.addFile(currentFilePath); } } currentFilePath = urlString; URL url = new URL(urlString); document = PDDocument.load(url.openStream(), password); initTree(); if (IS_MAC_OS) { setTitle(urlString); } else { setTitle("PDF Debugger - " + urlString); } addRecentFileItems(); } private void initTree() { TreeStatus treeStatus = new TreeStatus(document.getDocument().getTrailer()); statusPane.updateTreeStatus(treeStatus); if (isPageMode) { File file = new File(currentFilePath); DocumentEntry documentEntry = new DocumentEntry(document, file.getName()); tree.setModel(new PDFTreeModel(documentEntry)); // Root/Pages/Kids/[0] is not always the first page, so use the first row instead: tree.setSelectionPath(tree.getPathForRow(1)); } else { tree.setModel(new PDFTreeModel(document)); tree.setSelectionPath(treeStatus.getPathForString("Root")); } } /** * This will parse a document. * * @param file The file addressing the document. * * @throws IOException If there is an error parsing the document. */ private void parseDocument( File file, String password )throws IOException { document = PDDocument.load(file, password); } private void addRecentFileItems() { Action recentMenuAction = new AbstractAction() { @Override public void actionPerformed(ActionEvent actionEvent) { String filePath = (String) ((JComponent) actionEvent.getSource()).getClientProperty("path"); try { readPDFFile(filePath, ""); } catch (Exception e) { throw new RuntimeException(e); } } }; if (!recentFiles.isEmpty()) { recentFilesMenu.removeAll(); List<String> files = recentFiles.getFiles(); for (int i = files.size() - 1; i >= 0; i--) { String path = files.get(i); String name = new File(path).getName(); JMenuItem recentFileMenuItem = new JMenuItem(name); recentFileMenuItem.putClientProperty("path", path); recentFileMenuItem.addActionListener(recentMenuAction); recentFilesMenu.add(recentFileMenuItem); } recentFilesMenu.setEnabled(true); } } /** * This will print out a message telling how to use this utility. */ private static void usage() { System.err.println( "usage: java -jar pdfbox-app-x.y.z.jar PDFDebugger [OPTIONS] <input-file>\n" + " -password <password> Password to decrypt the document\n" + " <input-file> The PDF document to be loaded\n" ); } }
PDFBOX-2530: Avoid NPE if no file is open when switching view mode git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1694785 13f79535-47bb-0310-9956-ffa450edef68
tools/src/main/java/org/apache/pdfbox/tools/PDFDebugger.java
PDFBOX-2530: Avoid NPE if no file is open when switching view mode
<ide><path>ools/src/main/java/org/apache/pdfbox/tools/PDFDebugger.java <ide> viewModeItem.setText("Show Internal Structure"); <ide> isPageMode = true; <ide> } <del> initTree(); <add> if (document != null) <add> { <add> initTree(); <add> } <ide> } <ide> }); <ide> viewMenu.add(viewModeItem);
JavaScript
apache-2.0
eed325a3415890ec7cff8ef04a596979fe15f635
0
thomascorriente/janis-fusion
'use strict'; const apiai = require('apiai'); const express = require('express'); const bodyParser = require('body-parser'); const uuid = require('uuid'); const request = require('request'); const JSONbig = require('json-bigint'); const async = require('async'); const janis = require('janis'); const REST_PORT = (process.env.PORT || 5000); const APIAI_ACCESS_TOKEN = process.env.APIAI_ACCESS_TOKEN; const APIAI_LANG = process.env.APIAI_LANG || 'en'; const FB_VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN; const FB_PAGE_ACCESS_TOKEN = process.env.FB_PAGE_ACCESS_TOKEN; const FB_TEXT_LIMIT = 640; // App Secret can be retrieved from the App Dashboard const APP_SECRET = "77d6c30390b30652169df4f4fe39196b"; // Arbitrary value used to validate a webhook const VALIDATION_TOKEN = FB_VERIFY_TOKEN; // Generate a page access token for your page from the App Dashboard const PAGE_ACCESS_TOKEN = FB_PAGE_ACCESS_TOKEN; const JANIS_API_KEY = "YDDhNdA5jZWT9AHu5Bwh3J5dOe1ODpd1ICk6jSE5fPL"; const JANIS_CLIENT_KEY = "70DSUenF9X5I45Y7K7R5cT2LOvHKafG9e5Klbk9BeUj"; var janis = require('janis')(JANIS_API_KEY, JANIS_CLIENT_KEY, {platform:'messenger', PAGE_ACCESS_TOKEN }); const FACEBOOK_LOCATION = "FACEBOOK_LOCATION"; const FACEBOOK_WELCOME = "FACEBOOK_WELCOME"; class FacebookBot { constructor() { this.apiAiService = apiai(APIAI_ACCESS_TOKEN, {language: APIAI_LANG, requestSource: "fb"}); this.sessionIds = new Map(); this.messagesDelay = 200; } doDataResponse(sender, facebookResponseData) { if (!Array.isArray(facebookResponseData)) { console.log('Response as formatted message'); this.sendFBMessage(sender, facebookResponseData) .catch(err => console.error(err)); } else { async.eachSeries(facebookResponseData, (facebookMessage, callback) => { if (facebookMessage.sender_action) { console.log('Response as sender action'); this.sendFBSenderAction(sender, facebookMessage.sender_action) .then(() => callback()) .catch(err => callback(err)); } else { console.log('Response as formatted message'); this.sendFBMessage(sender, facebookMessage) .then(() => callback()) .catch(err => callback(err)); } }, (err) => { if (err) { console.error(err); } else { console.log('Data response completed'); } }); } } doRichContentResponse(sender, messages) { let facebookMessages = []; // array with result messages for (let messageIndex = 0; messageIndex < messages.length; messageIndex++) { let message = messages[messageIndex]; switch (message.type) { //message.type 0 means text message case 0: // speech: ["hi"] // we have to get value from fulfillment.speech, because of here is raw speech if (message.speech) { let splittedText = this.splitResponse(message.speech); splittedText.forEach(s => { facebookMessages.push({text: s}); }); } break; //message.type 1 means card message case 1: { let carousel = [message]; for (messageIndex++; messageIndex < messages.length; messageIndex++) { if (messages[messageIndex].type == 1) { carousel.push(messages[messageIndex]); } else { messageIndex--; break; } } let facebookMessage = {}; carousel.forEach((c) => { // buttons: [ {text: "hi", postback: "postback"} ], imageUrl: "", title: "", subtitle: "" let card = {}; card.title = c.title; card.image_url = c.imageUrl; if (this.isDefined(c.subtitle)) { card.subtitle = c.subtitle; } //If button is involved in. if (c.buttons.length > 0) { let buttons = []; for (let buttonIndex = 0; buttonIndex < c.buttons.length; buttonIndex++) { let button = c.buttons[buttonIndex]; if (button.text) { let postback = button.postback; if (!postback) { postback = button.text; } let buttonDescription = { title: button.text }; if (postback.startsWith("http")) { buttonDescription.type = "web_url"; buttonDescription.url = postback; } else { buttonDescription.type = "postback"; buttonDescription.payload = postback; } buttons.push(buttonDescription); } } if (buttons.length > 0) { card.buttons = buttons; } } if (!facebookMessage.attachment) { facebookMessage.attachment = {type: "template"}; } if (!facebookMessage.attachment.payload) { facebookMessage.attachment.payload = {template_type: "generic", elements: []}; } facebookMessage.attachment.payload.elements.push(card); }); facebookMessages.push(facebookMessage); } break; //message.type 2 means quick replies message case 2: { if (message.replies && message.replies.length > 0) { let facebookMessage = {}; facebookMessage.text = message.title ? message.title : 'Choose an item'; facebookMessage.quick_replies = []; message.replies.forEach((r) => { facebookMessage.quick_replies.push({ content_type: "text", title: r, payload: r }); }); facebookMessages.push(facebookMessage); } } break; //message.type 3 means image message case 3: if (message.imageUrl) { let facebookMessage = {}; // "imageUrl": "http://example.com/image.jpg" facebookMessage.attachment = {type: "image"}; facebookMessage.attachment.payload = {url: message.imageUrl}; facebookMessages.push(facebookMessage); } break; //message.type 4 means custom payload message case 4: if (message.payload && message.payload.facebook) { facebookMessages.push(message.payload.facebook); } break; default: break; } } return new Promise((resolve, reject) => { async.eachSeries(facebookMessages, (msg, callback) => { this.sendFBSenderAction(sender, "typing_on") .then(() => this.sleep(this.messagesDelay)) .then(() => this.sendFBMessage(sender, msg)) .then(() => callback()) .catch(callback); }, (err) => { if (err) { console.error(err); reject(err); } else { console.log('Messages sent'); resolve(); } }); }); } doTextResponse(sender, responseText) { console.log('Response as text message'); // facebook API limit for text length is 640, // so we must split message if needed let splittedText = this.splitResponse(responseText); async.eachSeries(splittedText, (textPart, callback) => { this.sendFBMessage(sender, {text: textPart}) .then(() => callback()) .catch(err => callback(err)); }); } //which webhook event getEventText(event) { if (event.message) { if (event.message.quick_reply && event.message.quick_reply.payload) { return event.message.quick_reply.payload; } if (event.message.text) { return event.message.text; } } if (event.postback && event.postback.payload) { return event.postback.payload; } return null; } getFacebookEvent(event) { if (event.postback && event.postback.payload) { let payload = event.postback.payload; switch (payload) { case FACEBOOK_WELCOME: return {name: FACEBOOK_WELCOME}; case FACEBOOK_LOCATION: return {name: FACEBOOK_LOCATION, data: event.postback.data} } } return null; } processFacebookEvent(event) { const sender = event.sender.id.toString(); const eventObject = this.getFacebookEvent(event); if (eventObject) { // Handle a text message from this sender if (!this.sessionIds.has(sender)) { this.sessionIds.set(sender, uuid.v4()); } let apiaiRequest = this.apiAiService.eventRequest(eventObject, { sessionId: this.sessionIds.get(sender), originalRequest: { data: event, source: "facebook" } }); this.doApiAiRequest(apiaiRequest, sender); } } processMessageEvent(event) { const sender = event.sender.id.toString(); const text = this.getEventText(event); if (text) { // Handle a text message from this sender if (!this.sessionIds.has(sender)) { this.sessionIds.set(sender, uuid.v4()); } console.log("Text", text); //send user's text to api.ai service let apiaiRequest = this.apiAiService.textRequest(text, { sessionId: this.sessionIds.get(sender), originalRequest: { data: event, source: "facebook" } }); this.doApiAiRequest(apiaiRequest, sender); } } doApiAiRequest(apiaiRequest, sender) { apiaiRequest.on('response', (response) => { if (this.isDefined(response.result) && this.isDefined(response.result.fulfillment)) { let responseText = response.result.fulfillment.speech; let responseData = response.result.fulfillment.data; let responseMessages = response.result.fulfillment.messages; if (this.isDefined(responseData) && this.isDefined(responseData.facebook)) { let facebookResponseData = responseData.facebook; this.doDataResponse(sender, facebookResponseData); } else if (this.isDefined(responseMessages) && responseMessages.length > 0) { this.doRichContentResponse(sender, responseMessages); } else if (this.isDefined(responseText)) { this.doTextResponse(sender, responseText); } } }); apiaiRequest.on('error', (error) => console.error(error)); apiaiRequest.end(); } splitResponse(str) { if (str.length <= FB_TEXT_LIMIT) { return [str]; } return this.chunkString(str, FB_TEXT_LIMIT); } chunkString(s, len) { let curr = len, prev = 0; let output = []; while (s[curr]) { if (s[curr++] == ' ') { output.push(s.substring(prev, curr)); prev = curr; curr += len; } else { let currReverse = curr; do { if (s.substring(currReverse - 1, currReverse) == ' ') { output.push(s.substring(prev, currReverse)); prev = currReverse; curr = currReverse + len; break; } currReverse--; } while (currReverse > prev) } } output.push(s.substr(prev)); return output; } sendFBMessage(sender, messageData) { return new Promise((resolve, reject) => { request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token: FB_PAGE_ACCESS_TOKEN}, method: 'POST', json: { recipient: {id: sender}, message: messageData } }, (error, response) => { if (error) { console.log('Error sending message: ', error); reject(error); } else if (response.body.error) { console.log('Error: ', response.body.error); reject(new Error(response.body.error)); } resolve(); }); }); } sendFBSenderAction(sender, action) { return new Promise((resolve, reject) => { request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token: FB_PAGE_ACCESS_TOKEN}, method: 'POST', json: { recipient: {id: sender}, sender_action: action } }, (error, response) => { if (error) { console.error('Error sending action: ', error); reject(error); } else if (response.body.error) { console.error('Error: ', response.body.error); reject(new Error(response.body.error)); } resolve(); }); }); } doSubscribeRequest() { request({ method: 'POST', uri: `https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=${FB_PAGE_ACCESS_TOKEN}` }, (error, response, body) => { if (error) { console.error('Error while subscription: ', error); } else { console.log('Subscription result: ', response.body); } }); } configureGetStartedEvent() { request({ method: 'POST', uri: `https://graph.facebook.com/v2.6/me/thread_settings?access_token=${FB_PAGE_ACCESS_TOKEN}`, json: { setting_type: "call_to_actions", thread_state: "new_thread", call_to_actions: [ { payload: FACEBOOK_WELCOME } ] } }, (error, response, body) => { if (error) { console.error('Error while subscription', error); } else { console.log('Subscription result', response.body); } }); } isDefined(obj) { if (typeof obj == 'undefined') { return false; } if (!obj) { return false; } return obj != null; } sleep(delay) { return new Promise((resolve, reject) => { setTimeout(() => resolve(), delay); }); } } let facebookBot = new FacebookBot(); const app = express(); app.use(bodyParser.text({type: 'application/json'})); app.get('/webhook/', (req, res) => { if (req.query['hub.verify_token'] === FB_VERIFY_TOKEN) { res.send(req.query['hub.challenge']); setTimeout(() => { facebookBot.doSubscribeRequest(); }, 3000); } else { res.send('Error, wrong validation token'); } }); app.post('/webhook/', (req, res) => { try { const data = JSONbig.parse(req.body); if (data.entry) { let entries = data.entry; entries.forEach((entry) => { let messaging_events = entry.messaging; if (messaging_events) { messaging_events.forEach((event) => { if (event.message && !event.message.is_echo) { if (event.message.attachments) { let locations = event.message.attachments.filter(a => a.type === "location"); // delete all locations from original message event.message.attachments = event.message.attachments.filter(a => a.type !== "location"); if (locations.length > 0) { locations.forEach(l => { let locationEvent = { sender: event.sender, postback: { payload: "FACEBOOK_LOCATION", data: l.payload.coordinates } }; facebookBot.processFacebookEvent(locationEvent); }); } } facebookBot.processMessageEvent(event); } else if (event.postback && event.postback.payload) { if (event.postback.payload === "FACEBOOK_WELCOME") { facebookBot.processFacebookEvent(event); } else { facebookBot.processMessageEvent(event); } } }); } }); } return res.status(200).json({ status: "ok" }); } catch (err) { return res.status(400).json({ status: "error", error: err }); } }); app.listen(REST_PORT, () => { console.log('Rest service ready on port ' + REST_PORT); }); facebookBot.doSubscribeRequest();
src/app.js
'use strict'; const apiai = require('apiai'); const express = require('express'); const bodyParser = require('body-parser'); const uuid = require('uuid'); const request = require('request'); const JSONbig = require('json-bigint'); const async = require('async'); const janis = require('janis'); const REST_PORT = (process.env.PORT || 5000); const APIAI_ACCESS_TOKEN = process.env.APIAI_ACCESS_TOKEN; const APIAI_LANG = process.env.APIAI_LANG || 'en'; const FB_VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN; const FB_PAGE_ACCESS_TOKEN = process.env.FB_PAGE_ACCESS_TOKEN; const FB_TEXT_LIMIT = 640; const FACEBOOK_LOCATION = "FACEBOOK_LOCATION"; const FACEBOOK_WELCOME = "FACEBOOK_WELCOME"; class FacebookBot { constructor() { this.apiAiService = apiai(APIAI_ACCESS_TOKEN, {language: APIAI_LANG, requestSource: "fb"}); this.sessionIds = new Map(); this.messagesDelay = 200; } doDataResponse(sender, facebookResponseData) { if (!Array.isArray(facebookResponseData)) { console.log('Response as formatted message'); this.sendFBMessage(sender, facebookResponseData) .catch(err => console.error(err)); } else { async.eachSeries(facebookResponseData, (facebookMessage, callback) => { if (facebookMessage.sender_action) { console.log('Response as sender action'); this.sendFBSenderAction(sender, facebookMessage.sender_action) .then(() => callback()) .catch(err => callback(err)); } else { console.log('Response as formatted message'); this.sendFBMessage(sender, facebookMessage) .then(() => callback()) .catch(err => callback(err)); } }, (err) => { if (err) { console.error(err); } else { console.log('Data response completed'); } }); } } doRichContentResponse(sender, messages) { let facebookMessages = []; // array with result messages for (let messageIndex = 0; messageIndex < messages.length; messageIndex++) { let message = messages[messageIndex]; switch (message.type) { //message.type 0 means text message case 0: // speech: ["hi"] // we have to get value from fulfillment.speech, because of here is raw speech if (message.speech) { let splittedText = this.splitResponse(message.speech); splittedText.forEach(s => { facebookMessages.push({text: s}); }); } break; //message.type 1 means card message case 1: { let carousel = [message]; for (messageIndex++; messageIndex < messages.length; messageIndex++) { if (messages[messageIndex].type == 1) { carousel.push(messages[messageIndex]); } else { messageIndex--; break; } } let facebookMessage = {}; carousel.forEach((c) => { // buttons: [ {text: "hi", postback: "postback"} ], imageUrl: "", title: "", subtitle: "" let card = {}; card.title = c.title; card.image_url = c.imageUrl; if (this.isDefined(c.subtitle)) { card.subtitle = c.subtitle; } //If button is involved in. if (c.buttons.length > 0) { let buttons = []; for (let buttonIndex = 0; buttonIndex < c.buttons.length; buttonIndex++) { let button = c.buttons[buttonIndex]; if (button.text) { let postback = button.postback; if (!postback) { postback = button.text; } let buttonDescription = { title: button.text }; if (postback.startsWith("http")) { buttonDescription.type = "web_url"; buttonDescription.url = postback; } else { buttonDescription.type = "postback"; buttonDescription.payload = postback; } buttons.push(buttonDescription); } } if (buttons.length > 0) { card.buttons = buttons; } } if (!facebookMessage.attachment) { facebookMessage.attachment = {type: "template"}; } if (!facebookMessage.attachment.payload) { facebookMessage.attachment.payload = {template_type: "generic", elements: []}; } facebookMessage.attachment.payload.elements.push(card); }); facebookMessages.push(facebookMessage); } break; //message.type 2 means quick replies message case 2: { if (message.replies && message.replies.length > 0) { let facebookMessage = {}; facebookMessage.text = message.title ? message.title : 'Choose an item'; facebookMessage.quick_replies = []; message.replies.forEach((r) => { facebookMessage.quick_replies.push({ content_type: "text", title: r, payload: r }); }); facebookMessages.push(facebookMessage); } } break; //message.type 3 means image message case 3: if (message.imageUrl) { let facebookMessage = {}; // "imageUrl": "http://example.com/image.jpg" facebookMessage.attachment = {type: "image"}; facebookMessage.attachment.payload = {url: message.imageUrl}; facebookMessages.push(facebookMessage); } break; //message.type 4 means custom payload message case 4: if (message.payload && message.payload.facebook) { facebookMessages.push(message.payload.facebook); } break; default: break; } } return new Promise((resolve, reject) => { async.eachSeries(facebookMessages, (msg, callback) => { this.sendFBSenderAction(sender, "typing_on") .then(() => this.sleep(this.messagesDelay)) .then(() => this.sendFBMessage(sender, msg)) .then(() => callback()) .catch(callback); }, (err) => { if (err) { console.error(err); reject(err); } else { console.log('Messages sent'); resolve(); } }); }); } doTextResponse(sender, responseText) { console.log('Response as text message'); // facebook API limit for text length is 640, // so we must split message if needed let splittedText = this.splitResponse(responseText); async.eachSeries(splittedText, (textPart, callback) => { this.sendFBMessage(sender, {text: textPart}) .then(() => callback()) .catch(err => callback(err)); }); } //which webhook event getEventText(event) { if (event.message) { if (event.message.quick_reply && event.message.quick_reply.payload) { return event.message.quick_reply.payload; } if (event.message.text) { return event.message.text; } } if (event.postback && event.postback.payload) { return event.postback.payload; } return null; } getFacebookEvent(event) { if (event.postback && event.postback.payload) { let payload = event.postback.payload; switch (payload) { case FACEBOOK_WELCOME: return {name: FACEBOOK_WELCOME}; case FACEBOOK_LOCATION: return {name: FACEBOOK_LOCATION, data: event.postback.data} } } return null; } processFacebookEvent(event) { const sender = event.sender.id.toString(); const eventObject = this.getFacebookEvent(event); if (eventObject) { // Handle a text message from this sender if (!this.sessionIds.has(sender)) { this.sessionIds.set(sender, uuid.v4()); } let apiaiRequest = this.apiAiService.eventRequest(eventObject, { sessionId: this.sessionIds.get(sender), originalRequest: { data: event, source: "facebook" } }); this.doApiAiRequest(apiaiRequest, sender); } } processMessageEvent(event) { const sender = event.sender.id.toString(); const text = this.getEventText(event); if (text) { // Handle a text message from this sender if (!this.sessionIds.has(sender)) { this.sessionIds.set(sender, uuid.v4()); } console.log("Text", text); //send user's text to api.ai service let apiaiRequest = this.apiAiService.textRequest(text, { sessionId: this.sessionIds.get(sender), originalRequest: { data: event, source: "facebook" } }); this.doApiAiRequest(apiaiRequest, sender); } } doApiAiRequest(apiaiRequest, sender) { apiaiRequest.on('response', (response) => { if (this.isDefined(response.result) && this.isDefined(response.result.fulfillment)) { let responseText = response.result.fulfillment.speech; let responseData = response.result.fulfillment.data; let responseMessages = response.result.fulfillment.messages; if (this.isDefined(responseData) && this.isDefined(responseData.facebook)) { let facebookResponseData = responseData.facebook; this.doDataResponse(sender, facebookResponseData); } else if (this.isDefined(responseMessages) && responseMessages.length > 0) { this.doRichContentResponse(sender, responseMessages); } else if (this.isDefined(responseText)) { this.doTextResponse(sender, responseText); } } }); apiaiRequest.on('error', (error) => console.error(error)); apiaiRequest.end(); } splitResponse(str) { if (str.length <= FB_TEXT_LIMIT) { return [str]; } return this.chunkString(str, FB_TEXT_LIMIT); } chunkString(s, len) { let curr = len, prev = 0; let output = []; while (s[curr]) { if (s[curr++] == ' ') { output.push(s.substring(prev, curr)); prev = curr; curr += len; } else { let currReverse = curr; do { if (s.substring(currReverse - 1, currReverse) == ' ') { output.push(s.substring(prev, currReverse)); prev = currReverse; curr = currReverse + len; break; } currReverse--; } while (currReverse > prev) } } output.push(s.substr(prev)); return output; } sendFBMessage(sender, messageData) { return new Promise((resolve, reject) => { request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token: FB_PAGE_ACCESS_TOKEN}, method: 'POST', json: { recipient: {id: sender}, message: messageData } }, (error, response) => { if (error) { console.log('Error sending message: ', error); reject(error); } else if (response.body.error) { console.log('Error: ', response.body.error); reject(new Error(response.body.error)); } resolve(); }); }); } sendFBSenderAction(sender, action) { return new Promise((resolve, reject) => { request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token: FB_PAGE_ACCESS_TOKEN}, method: 'POST', json: { recipient: {id: sender}, sender_action: action } }, (error, response) => { if (error) { console.error('Error sending action: ', error); reject(error); } else if (response.body.error) { console.error('Error: ', response.body.error); reject(new Error(response.body.error)); } resolve(); }); }); } doSubscribeRequest() { request({ method: 'POST', uri: `https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=${FB_PAGE_ACCESS_TOKEN}` }, (error, response, body) => { if (error) { console.error('Error while subscription: ', error); } else { console.log('Subscription result: ', response.body); } }); } configureGetStartedEvent() { request({ method: 'POST', uri: `https://graph.facebook.com/v2.6/me/thread_settings?access_token=${FB_PAGE_ACCESS_TOKEN}`, json: { setting_type: "call_to_actions", thread_state: "new_thread", call_to_actions: [ { payload: FACEBOOK_WELCOME } ] } }, (error, response, body) => { if (error) { console.error('Error while subscription', error); } else { console.log('Subscription result', response.body); } }); } isDefined(obj) { if (typeof obj == 'undefined') { return false; } if (!obj) { return false; } return obj != null; } sleep(delay) { return new Promise((resolve, reject) => { setTimeout(() => resolve(), delay); }); } } let facebookBot = new FacebookBot(); const app = express(); app.use(bodyParser.text({type: 'application/json'})); app.get('/webhook/', (req, res) => { if (req.query['hub.verify_token'] === FB_VERIFY_TOKEN) { res.send(req.query['hub.challenge']); setTimeout(() => { facebookBot.doSubscribeRequest(); }, 3000); } else { res.send('Error, wrong validation token'); } }); app.post('/webhook/', (req, res) => { try { const data = JSONbig.parse(req.body); if (data.entry) { let entries = data.entry; entries.forEach((entry) => { let messaging_events = entry.messaging; if (messaging_events) { messaging_events.forEach((event) => { if (event.message && !event.message.is_echo) { if (event.message.attachments) { let locations = event.message.attachments.filter(a => a.type === "location"); // delete all locations from original message event.message.attachments = event.message.attachments.filter(a => a.type !== "location"); if (locations.length > 0) { locations.forEach(l => { let locationEvent = { sender: event.sender, postback: { payload: "FACEBOOK_LOCATION", data: l.payload.coordinates } }; facebookBot.processFacebookEvent(locationEvent); }); } } facebookBot.processMessageEvent(event); } else if (event.postback && event.postback.payload) { if (event.postback.payload === "FACEBOOK_WELCOME") { facebookBot.processFacebookEvent(event); } else { facebookBot.processMessageEvent(event); } } }); } }); } return res.status(200).json({ status: "ok" }); } catch (err) { return res.status(400).json({ status: "error", error: err }); } }); app.listen(REST_PORT, () => { console.log('Rest service ready on port ' + REST_PORT); }); facebookBot.doSubscribeRequest();
Update app.js
src/app.js
Update app.js
<ide><path>rc/app.js <ide> const FB_VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN; <ide> const FB_PAGE_ACCESS_TOKEN = process.env.FB_PAGE_ACCESS_TOKEN; <ide> const FB_TEXT_LIMIT = 640; <add> <add>// App Secret can be retrieved from the App Dashboard <add>const APP_SECRET = "77d6c30390b30652169df4f4fe39196b"; <add> <add> <add>// Arbitrary value used to validate a webhook <add>const VALIDATION_TOKEN = FB_VERIFY_TOKEN; <add> <add> <add>// Generate a page access token for your page from the App Dashboard <add>const PAGE_ACCESS_TOKEN = FB_PAGE_ACCESS_TOKEN; <add> <add>const JANIS_API_KEY = "YDDhNdA5jZWT9AHu5Bwh3J5dOe1ODpd1ICk6jSE5fPL"; <add>const JANIS_CLIENT_KEY = "70DSUenF9X5I45Y7K7R5cT2LOvHKafG9e5Klbk9BeUj"; <add> <add>var janis = require('janis')(JANIS_API_KEY, JANIS_CLIENT_KEY, <add> {platform:'messenger', <add> PAGE_ACCESS_TOKEN <add> }); <ide> <ide> const FACEBOOK_LOCATION = "FACEBOOK_LOCATION"; <ide> const FACEBOOK_WELCOME = "FACEBOOK_WELCOME";
Java
apache-2.0
876041b395595fa2b0e7b8f1a9a75929d2f168f7
0
JeffreyLyonsD2L/phoenix,elilevine/apache-phoenix,hendriksaragih/phoenix,wangbin83-gmail-com/phoenix,linearregression/phoenix-1,jongyoul/phoenix,ayingshu/unionall,ayingshu/unionall,djh4230/Apache-Phoenix,SiftScience/phoenix,ankitsinghal/phoenix,jongyoul/phoenix,apache/phoenix,mbrukman/phoenix,7shurik/phoenix,hendriksaragih/phoenix,apache/phoenix,djh4230/Apache-Phoenix,jfernandosf/phoenix,7shurik/phoenix,nickman/phoenix,mbrukman/phoenix,growingio/phoenix,d9liang/phoenix,AyolaJayamaha/phoenix,apurtell/phoenix,kidaa/phoenix-1,codymarcel/phoenix,codymarcel/phoenix,hendriksaragih/phoenix,bpanneton/phoenix,apache/phoenix,mbrukman/phoenix,JeffreyLyonsD2L/phoenix,shehzaadn/phoenix,lgscofield/phoenix,bpanneton/phoenix,milinda/phoenix,hendriksaragih/phoenix,JeffreyLyonsD2L/phoenix,growingio/phoenix,dawidwys/phoenix,RCheungIT/phoenix,7shurik/phoenix,twdsilva/phoenix,nickman/phoenix,AyolaJayamaha/phoenix,SiftScience/phoenix,zhudebin/phoenix,mbrukman/phoenix,RCheungIT/phoenix,apache/phoenix,jfernandosf/phoenix,ohadshacham/phoenix,chiastic-security/phoenix-for-cloudera,kidaa/phoenix-1,apurtell/phoenix,dumindux/phoenix,codymarcel/phoenix,chiastic-security/phoenix-for-cloudera,rvaleti/phoenix,apurtell/phoenix,d9liang/phoenix,simararneja/phoenix,nickman/phoenix,ohadshacham/phoenix,milinda/phoenix,ictwanglei/phoenix,milinda/phoenix,wangbin83-gmail-com/phoenix,glammedia/phoenix,Guavus/phoenix,dawidwys/phoenix,AyolaJayamaha/phoenix,linearregression/phoenix-1,lgscofield/phoenix,simararneja/phoenix,ictwanglei/phoenix,elilevine/apache-phoenix,djh4230/Apache-Phoenix,ayingshu/unionall,d9liang/phoenix,jongyoul/phoenix,ankitsinghal/phoenix,twdsilva/phoenix,djh4230/Apache-Phoenix,rvaleti/phoenix,codymarcel/phoenix,zhudebin/phoenix,jfernandosf/phoenix,simararneja/phoenix,chiastic-security/phoenix-for-cloudera,linearregression/phoenix-1,twdsilva/phoenix,wangbin83-gmail-com/phoenix,elilevine/apache-phoenix,Guavus/phoenix,jongyoul/phoenix,bpanneton/phoenix,shehzaadn/phoenix,dawidwys/phoenix,ictwanglei/phoenix,shehzaadn/phoenix,bpanneton/phoenix,JeffreyLyonsD2L/phoenix,jfernandosf/phoenix,nickman/phoenix,bpanneton/phoenix,dawidwys/phoenix,ohadshacham/phoenix,ictwanglei/phoenix,shehzaadn/phoenix,glammedia/phoenix,apache/phoenix,simararneja/phoenix,djh4230/Apache-Phoenix,RCheungIT/phoenix,ohadshacham/phoenix,ankitsinghal/phoenix,7shurik/phoenix,linearregression/phoenix-1,kidaa/phoenix-1,SiftScience/phoenix,rvaleti/phoenix,growingio/phoenix,RCheungIT/phoenix,RCheungIT/phoenix,Guavus/phoenix,growingio/phoenix,growingio/phoenix,dumindux/phoenix,ayingshu/unionall,hendriksaragih/phoenix,glammedia/phoenix,shehzaadn/phoenix,chiastic-security/phoenix-for-cloudera,ankitsinghal/phoenix,elilevine/apache-phoenix,AyolaJayamaha/phoenix,twdsilva/phoenix,zhudebin/phoenix,ankitsinghal/phoenix,glammedia/phoenix,jfernandosf/phoenix,wangbin83-gmail-com/phoenix,mbrukman/phoenix,AyolaJayamaha/phoenix,milinda/phoenix,apurtell/phoenix,SiftScience/phoenix,twdsilva/phoenix,Guavus/phoenix,lgscofield/phoenix,apurtell/phoenix,zhudebin/phoenix,lgscofield/phoenix,dawidwys/phoenix,rvaleti/phoenix,chiastic-security/phoenix-for-cloudera,Guavus/phoenix,ohadshacham/phoenix,rvaleti/phoenix,kidaa/phoenix-1
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.phoenix.end2end; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_CATALOG_TABLE; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TYPE_SEQUENCE; import static org.apache.phoenix.util.TestUtil.ATABLE_NAME; import static org.apache.phoenix.util.TestUtil.ATABLE_SCHEMA_NAME; import static org.apache.phoenix.util.TestUtil.BTABLE_NAME; import static org.apache.phoenix.util.TestUtil.CUSTOM_ENTITY_DATA_FULL_NAME; import static org.apache.phoenix.util.TestUtil.CUSTOM_ENTITY_DATA_NAME; import static org.apache.phoenix.util.TestUtil.CUSTOM_ENTITY_DATA_SCHEMA_NAME; import static org.apache.phoenix.util.TestUtil.GROUPBYTEST_NAME; import static org.apache.phoenix.util.TestUtil.MDTEST_NAME; import static org.apache.phoenix.util.TestUtil.MDTEST_SCHEMA_NAME; import static org.apache.phoenix.util.TestUtil.PTSDB_NAME; import static org.apache.phoenix.util.TestUtil.STABLE_NAME; import static org.apache.phoenix.util.TestUtil.TABLE_WITH_SALTING; import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.Map; import java.util.Properties; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HTableInterface; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter; import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding; import org.apache.hadoop.hbase.util.Bytes; import org.apache.phoenix.coprocessor.GroupedAggregateRegionObserver; import org.apache.phoenix.coprocessor.ServerCachingEndpointImpl; import org.apache.phoenix.coprocessor.UngroupedAggregateRegionObserver; import org.apache.phoenix.exception.SQLExceptionCode; import org.apache.phoenix.jdbc.PhoenixConnection; import org.apache.phoenix.jdbc.PhoenixDatabaseMetaData; import org.apache.phoenix.query.QueryServices; import org.apache.phoenix.schema.ColumnNotFoundException; import org.apache.phoenix.schema.PDataType; import org.apache.phoenix.schema.PTable.ViewType; import org.apache.phoenix.schema.PTableType; import org.apache.phoenix.schema.ReadOnlyTableException; import org.apache.phoenix.schema.TableNotFoundException; import org.apache.phoenix.util.PhoenixRuntime; import org.apache.phoenix.util.PropertiesUtil; import org.apache.phoenix.util.ReadOnlyProps; import org.apache.phoenix.util.SchemaUtil; import org.apache.phoenix.util.StringUtil; import org.apache.phoenix.util.TestUtil; import org.junit.BeforeClass; import org.junit.Test; public class QueryDatabaseMetaDataIT extends BaseClientManagedTimeIT { @BeforeClass @Shadower(classBeingShadowed = BaseClientManagedTimeIT.class) public static void doSetup() throws Exception { Map<String,String> props = getDefaultProps(); props.put(QueryServices.DEFAULT_KEEP_DELETED_CELLS_ATTRIB, "true"); setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator())); } @Test public void testTableMetadataScan() throws SQLException { long ts = nextTimestamp(); ensureTableCreated(getUrl(), ATABLE_NAME, null, ts); ensureTableCreated(getUrl(), STABLE_NAME, null, ts); ensureTableCreated(getUrl(), CUSTOM_ENTITY_DATA_FULL_NAME, null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn = DriverManager.getConnection(getUrl(), props); DatabaseMetaData dbmd = conn.getMetaData(); String aTableName = StringUtil.escapeLike(TestUtil.ATABLE_NAME); String aSchemaName = TestUtil.ATABLE_SCHEMA_NAME; ResultSet rs = dbmd.getTables(null, aSchemaName, aTableName, null); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_NAME"),aTableName); assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE")); assertEquals(rs.getString(3),aTableName); assertEquals(PTableType.TABLE.toString(), rs.getString(4)); assertFalse(rs.next()); rs = dbmd.getTables(null, null, null, null); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),SYSTEM_CATALOG_SCHEMA); assertEquals(rs.getString("TABLE_NAME"),SYSTEM_CATALOG_TABLE); assertEquals(PTableType.SYSTEM.toString(), rs.getString("TABLE_TYPE")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),SYSTEM_CATALOG_SCHEMA); assertEquals(rs.getString("TABLE_NAME"),TYPE_SEQUENCE); assertEquals(PTableType.SYSTEM.toString(), rs.getString("TABLE_TYPE")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),SYSTEM_CATALOG_SCHEMA); assertEquals(rs.getString("TABLE_NAME"),PhoenixDatabaseMetaData.SYSTEM_STATS_TABLE); assertEquals(PTableType.SYSTEM.toString(), rs.getString("TABLE_TYPE")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),ATABLE_NAME); assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),STABLE_NAME); assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE")); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE")); rs = dbmd.getTables(null, CUSTOM_ENTITY_DATA_SCHEMA_NAME, CUSTOM_ENTITY_DATA_NAME, null); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),CUSTOM_ENTITY_DATA_SCHEMA_NAME); assertEquals(rs.getString("TABLE_NAME"),CUSTOM_ENTITY_DATA_NAME); assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE")); assertFalse(rs.next()); try { rs.getString("RANDOM_COLUMN_NAME"); fail(); } catch (ColumnNotFoundException e) { // expected } assertFalse(rs.next()); rs = dbmd.getTables(null, "", "_TABLE", new String[] {PTableType.TABLE.toString()}); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),ATABLE_NAME); assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),STABLE_NAME); assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE")); assertFalse(rs.next()); } @Test public void testSchemaMetadataScan() throws SQLException { long ts = nextTimestamp(); ensureTableCreated(getUrl(), CUSTOM_ENTITY_DATA_FULL_NAME, null, ts); ensureTableCreated(getUrl(), PTSDB_NAME, null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn = DriverManager.getConnection(getUrl(), props); DatabaseMetaData dbmd = conn.getMetaData(); ResultSet rs; rs = dbmd.getSchemas(null, CUSTOM_ENTITY_DATA_SCHEMA_NAME); assertTrue(rs.next()); assertEquals(rs.getString(1),CUSTOM_ENTITY_DATA_SCHEMA_NAME); assertEquals(rs.getString(2),null); assertFalse(rs.next()); rs = dbmd.getSchemas(null, null); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_CATALOG"),null); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),CUSTOM_ENTITY_DATA_SCHEMA_NAME); assertEquals(rs.getString("TABLE_CATALOG"),null); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA); assertEquals(rs.getString("TABLE_CATALOG"),null); assertFalse(rs.next()); } @Test public void testColumnMetadataScan() throws SQLException { long ts = nextTimestamp(); ensureTableCreated(getUrl(), MDTEST_NAME, null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn = DriverManager.getConnection(getUrl(), props); DatabaseMetaData dbmd = conn.getMetaData(); ResultSet rs; rs = dbmd.getColumns(null, "", MDTEST_NAME, null); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("id"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNoNulls, rs.getShort("NULLABLE")); assertEquals(PDataType.CHAR.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(1, rs.getInt("ORDINAL_POSITION")); assertEquals(1, rs.getInt("COLUMN_SIZE")); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("a"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col1"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.INTEGER.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(2, rs.getInt("ORDINAL_POSITION")); assertEquals(0, rs.getInt("COLUMN_SIZE")); assertTrue(rs.wasNull()); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.wasNull()); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col2"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.LONG.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(3, rs.getInt("ORDINAL_POSITION")); assertEquals(0, rs.getInt("COLUMN_SIZE")); assertTrue(rs.wasNull()); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.wasNull()); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col3"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.DECIMAL.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(4, rs.getInt("ORDINAL_POSITION")); assertEquals(0, rs.getInt("COLUMN_SIZE")); assertTrue(rs.wasNull()); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.wasNull()); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col4"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.DECIMAL.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(5, rs.getInt("ORDINAL_POSITION")); assertEquals(5, rs.getInt("COLUMN_SIZE")); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col5"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.DECIMAL.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(6, rs.getInt("ORDINAL_POSITION")); assertEquals(6, rs.getInt("COLUMN_SIZE")); assertEquals(3, rs.getInt("DECIMAL_DIGITS")); assertFalse(rs.next()); // Look up only columns in a column family rs = dbmd.getColumns(null, "", MDTEST_NAME, "A."); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("a"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col1"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.INTEGER.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(2, rs.getInt("ORDINAL_POSITION")); assertEquals(0, rs.getInt("COLUMN_SIZE")); assertTrue(rs.wasNull()); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.wasNull()); assertFalse(rs.next()); // Look up KV columns in a column family rs = dbmd.getColumns("", "", MDTEST_NAME, "%.COL%"); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("a"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col1"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.INTEGER.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(2, rs.getInt("ORDINAL_POSITION")); assertEquals(0, rs.getInt("COLUMN_SIZE")); assertTrue(rs.wasNull()); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.wasNull()); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col2"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.LONG.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(3, rs.getInt("ORDINAL_POSITION")); assertEquals(0, rs.getInt("COLUMN_SIZE")); assertTrue(rs.wasNull()); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.wasNull()); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col3"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.DECIMAL.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(4, rs.getInt("ORDINAL_POSITION")); assertEquals(0, rs.getInt("COLUMN_SIZE")); assertTrue(rs.wasNull()); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.wasNull()); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col4"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.DECIMAL.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(5, rs.getInt("ORDINAL_POSITION")); assertEquals(5, rs.getInt("COLUMN_SIZE")); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertFalse(rs.wasNull()); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col5"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.DECIMAL.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(6, rs.getInt("ORDINAL_POSITION")); assertEquals(6, rs.getInt("COLUMN_SIZE")); assertEquals(3, rs.getInt("DECIMAL_DIGITS")); assertFalse(rs.next()); // Look up KV columns in a column family rs = dbmd.getColumns("", "", MDTEST_NAME, "B.COL2"); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col2"), rs.getString("COLUMN_NAME")); assertFalse(rs.next()); ensureTableCreated(getUrl(), TABLE_WITH_SALTING, null, ts); rs = dbmd.getColumns("", "", TABLE_WITH_SALTING, StringUtil.escapeLike("A_INTEGER")); assertTrue(rs.next()); assertEquals(1, rs.getInt("ORDINAL_POSITION")); assertFalse(rs.next()); } @Test public void testPrimaryKeyMetadataScan() throws SQLException { long ts = nextTimestamp(); ensureTableCreated(getUrl(), MDTEST_NAME, null, ts); ensureTableCreated(getUrl(), CUSTOM_ENTITY_DATA_FULL_NAME, null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn = DriverManager.getConnection(getUrl(), props); DatabaseMetaData dbmd = conn.getMetaData(); ResultSet rs; rs = dbmd.getPrimaryKeys(null, "", MDTEST_NAME); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("id"), rs.getString("COLUMN_NAME")); assertEquals(1, rs.getInt("KEY_SEQ")); assertEquals(null, rs.getString("PK_NAME")); assertFalse(rs.next()); rs = dbmd.getPrimaryKeys(null, CUSTOM_ENTITY_DATA_SCHEMA_NAME, CUSTOM_ENTITY_DATA_NAME); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("custom_entity_data_id"), rs.getString("COLUMN_NAME")); assertEquals(3, rs.getInt("KEY_SEQ")); assertEquals(SchemaUtil.normalizeIdentifier("pk"), rs.getString("PK_NAME")); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("key_prefix"), rs.getString("COLUMN_NAME")); assertEquals(2, rs.getInt("KEY_SEQ")); assertEquals(SchemaUtil.normalizeIdentifier("pk"), rs.getString("PK_NAME")); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("organization_id"), rs.getString("COLUMN_NAME")); assertEquals(1, rs.getInt("KEY_SEQ")); assertEquals(SchemaUtil.normalizeIdentifier("pk"), rs.getString("PK_NAME")); // TODO: this is on the table row assertFalse(rs.next()); rs = dbmd.getColumns("", CUSTOM_ENTITY_DATA_SCHEMA_NAME, CUSTOM_ENTITY_DATA_NAME, null); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("organization_id"), rs.getString("COLUMN_NAME")); assertEquals(rs.getInt("COLUMN_SIZE"), 15); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("key_prefix"), rs.getString("COLUMN_NAME")); assertEquals(rs.getInt("COLUMN_SIZE"), 3); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("custom_entity_data_id"), rs.getString("COLUMN_NAME")); // The above returns all columns, starting with the PK columns assertTrue(rs.next()); rs = dbmd.getColumns("", CUSTOM_ENTITY_DATA_SCHEMA_NAME, CUSTOM_ENTITY_DATA_NAME, "KEY_PREFIX"); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("key_prefix"), rs.getString("COLUMN_NAME")); rs = dbmd.getColumns("", CUSTOM_ENTITY_DATA_SCHEMA_NAME, CUSTOM_ENTITY_DATA_NAME, "KEY_PREFIX"); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("key_prefix"), rs.getString("COLUMN_NAME")); assertFalse(rs.next()); } @Test public void testMultiTableColumnsMetadataScan() throws SQLException { long ts = nextTimestamp(); ensureTableCreated(getUrl(), MDTEST_NAME, null, ts); ensureTableCreated(getUrl(), GROUPBYTEST_NAME, null, ts); ensureTableCreated(getUrl(), PTSDB_NAME, null, ts); ensureTableCreated(getUrl(), CUSTOM_ENTITY_DATA_FULL_NAME, null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn = DriverManager.getConnection(getUrl(), props); DatabaseMetaData dbmd = conn.getMetaData(); ResultSet rs = dbmd.getColumns(null, "", "%TEST%", null); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),GROUPBYTEST_NAME); assertEquals(null, rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("id"), rs.getString("COLUMN_NAME")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),GROUPBYTEST_NAME); assertEquals(PhoenixDatabaseMetaData.TABLE_FAMILY, rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("uri"), rs.getString("COLUMN_NAME")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),GROUPBYTEST_NAME); assertEquals(PhoenixDatabaseMetaData.TABLE_FAMILY, rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("appcpu"), rs.getString("COLUMN_NAME")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),MDTEST_NAME); assertEquals(null, rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("id"), rs.getString("COLUMN_NAME")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),MDTEST_NAME); assertEquals(SchemaUtil.normalizeIdentifier("a"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col1"), rs.getString("COLUMN_NAME")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),MDTEST_NAME); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col2"), rs.getString("COLUMN_NAME")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),MDTEST_NAME); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col3"), rs.getString("COLUMN_NAME")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),MDTEST_NAME); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col4"), rs.getString("COLUMN_NAME")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),MDTEST_NAME); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col5"), rs.getString("COLUMN_NAME")); assertFalse(rs.next()); } @Test public void testCreateDropTable() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); initATableValues(tenantId, getDefaultSplits(tenantId), null, ts); ensureTableCreated(getUrl(), BTABLE_NAME, null, ts-2); ensureTableCreated(getUrl(), PTSDB_NAME, null, ts-2); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn5 = DriverManager.getConnection(getUrl(), props); String query = "SELECT a_string FROM aTable"; // Data should still be there b/c we only dropped the schema props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 8)); assertTrue(conn5.prepareStatement(query).executeQuery().next()); conn5.createStatement().executeUpdate("DROP TABLE " + ATABLE_NAME); // Confirm that data is no longer there because we dropped the table // This needs to be done natively b/c the metadata is gone HTableInterface htable = conn5.unwrap(PhoenixConnection.class).getQueryServices().getTable(SchemaUtil.getTableNameAsBytes(ATABLE_SCHEMA_NAME, ATABLE_NAME)); Scan scan = new Scan(); scan.setFilter(new FirstKeyOnlyFilter()); scan.setTimeRange(0, ts+9); assertNull(htable.getScanner(scan).next()); conn5.close(); // Still should work b/c we're at an earlier timestamp than when table was deleted props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); Connection conn2 = DriverManager.getConnection(getUrl(), props); assertTrue(conn2.prepareStatement(query).executeQuery().next()); conn2.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 10)); Connection conn10 = DriverManager.getConnection(getUrl(), props); try { conn10.prepareStatement(query).executeQuery().next(); fail(); } catch (TableNotFoundException e) { } } @Test public void testCreateOnExistingTable() throws Exception { PhoenixConnection pconn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TEST_PROPERTIES)).unwrap(PhoenixConnection.class); String tableName = MDTEST_NAME; String schemaName = MDTEST_SCHEMA_NAME; byte[] cfA = Bytes.toBytes(SchemaUtil.normalizeIdentifier("a")); byte[] cfB = Bytes.toBytes(SchemaUtil.normalizeIdentifier("b")); byte[] cfC = Bytes.toBytes("c"); byte[][] familyNames = new byte[][] {cfB, cfC}; byte[] htableName = SchemaUtil.getTableNameAsBytes(schemaName, tableName); HBaseAdmin admin = pconn.getQueryServices().getAdmin(); try { admin.disableTable(htableName); admin.deleteTable(htableName); admin.enableTable(htableName); } catch (org.apache.hadoop.hbase.TableNotFoundException e) { } @SuppressWarnings("deprecation") HTableDescriptor descriptor = new HTableDescriptor(htableName); for (byte[] familyName : familyNames) { HColumnDescriptor columnDescriptor = new HColumnDescriptor(familyName); descriptor.addFamily(columnDescriptor); } admin.createTable(descriptor); long ts = nextTimestamp(); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); PhoenixConnection conn1 = DriverManager.getConnection(getUrl(), props).unwrap(PhoenixConnection.class); ensureTableCreated(getUrl(), tableName, null, ts); descriptor = admin.getTableDescriptor(htableName); assertEquals(3,descriptor.getColumnFamilies().length); HColumnDescriptor cdA = descriptor.getFamily(cfA); assertNotEquals(HColumnDescriptor.DEFAULT_KEEP_DELETED, cdA.getKeepDeletedCells()); assertEquals(DataBlockEncoding.NONE, cdA.getDataBlockEncoding()); // Overriden using WITH assertEquals(1,cdA.getMaxVersions());// Overriden using WITH HColumnDescriptor cdB = descriptor.getFamily(cfB); // Allow KEEP_DELETED_CELLS to be false for VIEW assertEquals(HColumnDescriptor.DEFAULT_KEEP_DELETED, cdB.getKeepDeletedCells()); assertEquals(DataBlockEncoding.NONE, cdB.getDataBlockEncoding()); // Should keep the original value. // CF c should stay the same since it's not a Phoenix cf. HColumnDescriptor cdC = descriptor.getFamily(cfC); assertNotNull("Column family not found", cdC); assertEquals(HColumnDescriptor.DEFAULT_KEEP_DELETED, cdC.getKeepDeletedCells()); assertFalse(SchemaUtil.DEFAULT_DATA_BLOCK_ENCODING == cdC.getDataBlockEncoding()); assertTrue(descriptor.hasCoprocessor(UngroupedAggregateRegionObserver.class.getName())); assertTrue(descriptor.hasCoprocessor(GroupedAggregateRegionObserver.class.getName())); assertTrue(descriptor.hasCoprocessor(ServerCachingEndpointImpl.class.getName())); admin.close(); int rowCount = 5; String upsert = "UPSERT INTO " + tableName + "(id,col1,col2) VALUES(?,?,?)"; PreparedStatement ps = conn1.prepareStatement(upsert); for (int i = 0; i < rowCount; i++) { ps.setString(1, Integer.toString(i)); ps.setInt(2, i+1); ps.setInt(3, i+2); ps.execute(); } conn1.commit(); conn1.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 6)); Connection conn2 = DriverManager.getConnection(getUrl(), props); String query = "SELECT count(1) FROM " + tableName; ResultSet rs = conn2.createStatement().executeQuery(query); assertTrue(rs.next()); assertEquals(rowCount, rs.getLong(1)); query = "SELECT id, col1,col2 FROM " + tableName; rs = conn2.createStatement().executeQuery(query); for (int i = 0; i < rowCount; i++) { assertTrue(rs.next()); assertEquals(Integer.toString(i),rs.getString(1)); assertEquals(i+1, rs.getInt(2)); assertEquals(i+2, rs.getInt(3)); } assertFalse(rs.next()); conn2.close(); } @SuppressWarnings("deprecation") @Test public void testCreateViewOnExistingTable() throws Exception { PhoenixConnection pconn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TEST_PROPERTIES)).unwrap(PhoenixConnection.class); String tableName = MDTEST_NAME; String schemaName = MDTEST_SCHEMA_NAME; byte[] cfB = Bytes.toBytes(SchemaUtil.normalizeIdentifier("b")); byte[] cfC = Bytes.toBytes("c"); byte[][] familyNames = new byte[][] {cfB, cfC}; byte[] htableName = SchemaUtil.getTableNameAsBytes(schemaName, tableName); HBaseAdmin admin = pconn.getQueryServices().getAdmin(); try { admin.disableTable(htableName); admin.deleteTable(htableName); admin.enableTable(htableName); } catch (org.apache.hadoop.hbase.TableNotFoundException e) { } finally { admin.close(); } HTableDescriptor descriptor = new HTableDescriptor(htableName); for (byte[] familyName : familyNames) { HColumnDescriptor columnDescriptor = new HColumnDescriptor(familyName); descriptor.addFamily(columnDescriptor); } admin.createTable(descriptor); long ts = nextTimestamp(); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn1 = DriverManager.getConnection(getUrl(), props); String createStmt = "create view bogusTable" + " (id char(1) not null primary key,\n" + " a.col1 integer,\n" + " d.col2 bigint)\n"; try { conn1.createStatement().execute(createStmt); fail(); } catch (TableNotFoundException e) { // expected to fail b/c table doesn't exist } catch (ReadOnlyTableException e) { // expected to fail b/c table doesn't exist } createStmt = "create view " + MDTEST_NAME + " (id char(1) not null primary key,\n" + " a.col1 integer,\n" + " b.col2 bigint)\n"; try { conn1.createStatement().execute(createStmt); fail(); } catch (ReadOnlyTableException e) { // expected to fail b/c cf a doesn't exist } createStmt = "create view " + MDTEST_NAME + " (id char(1) not null primary key,\n" + " b.col1 integer,\n" + " c.col2 bigint)\n"; try { conn1.createStatement().execute(createStmt); fail(); } catch (ReadOnlyTableException e) { // expected to fail b/c cf C doesn't exist (case issue) } createStmt = "create view " + MDTEST_NAME + " (id char(1) not null primary key,\n" + " b.col1 integer,\n" + " \"c\".col2 bigint) \n"; // should be ok now conn1.createStatement().execute(createStmt); conn1.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 6)); PhoenixConnection conn2 = DriverManager.getConnection(getUrl(), props).unwrap(PhoenixConnection.class); ResultSet rs = conn2.getMetaData().getTables(null, null, MDTEST_NAME, null); assertTrue(rs.next()); assertEquals(ViewType.MAPPED.name(), rs.getString(PhoenixDatabaseMetaData.VIEW_TYPE)); assertFalse(rs.next()); String deleteStmt = "DELETE FROM " + MDTEST_NAME; PreparedStatement ps = conn2.prepareStatement(deleteStmt); try { ps.execute(); fail(); } catch (ReadOnlyTableException e) { // expected to fail b/c table is read-only } try { String upsert = "UPSERT INTO " + MDTEST_NAME + "(id,col1,col2) VALUES(?,?,?)"; ps = conn2.prepareStatement(upsert); try { ps.setString(1, Integer.toString(0)); ps.setInt(2, 1); ps.setInt(3, 2); ps.execute(); fail(); } catch (ReadOnlyTableException e) { // expected to fail b/c table is read-only } conn2.createStatement().execute("ALTER VIEW " + MDTEST_NAME + " SET IMMUTABLE_ROWS=TRUE"); HTableInterface htable = conn2.getQueryServices().getTable(SchemaUtil.getTableNameAsBytes(MDTEST_SCHEMA_NAME,MDTEST_NAME)); Put put = new Put(Bytes.toBytes("0")); put.add(cfB, Bytes.toBytes("COL1"), ts+6, PDataType.INTEGER.toBytes(1)); put.add(cfC, Bytes.toBytes("COL2"), ts+6, PDataType.LONG.toBytes(2)); htable.put(put); conn2.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 10)); Connection conn7 = DriverManager.getConnection(getUrl(), props); // Should be ok b/c we've marked the view with IMMUTABLE_ROWS=true conn7.createStatement().execute("CREATE INDEX idx ON " + MDTEST_NAME + "(B.COL1)"); String select = "SELECT col1 FROM " + MDTEST_NAME + " WHERE col2=?"; ps = conn7.prepareStatement(select); ps.setInt(1, 2); rs = ps.executeQuery(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertFalse(rs.next()); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 12)); Connection conn75 = DriverManager.getConnection(getUrl(), props); String dropTable = "DROP TABLE " + MDTEST_NAME ; ps = conn75.prepareStatement(dropTable); try { ps.execute(); fail(); } catch (TableNotFoundException e) { // expected to fail b/c it is a view } String dropView = "DROP VIEW " + MDTEST_NAME ; ps = conn75.prepareStatement(dropView); ps.execute(); conn75.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 15)); Connection conn8 = DriverManager.getConnection(getUrl(), props); createStmt = "create view " + MDTEST_NAME + " (id char(1) not null primary key,\n" + " b.col1 integer,\n" + " \"c\".col2 bigint) IMMUTABLE_ROWS=true\n"; // should be ok to create a view with IMMUTABLE_ROWS = true conn8.createStatement().execute(createStmt); conn8.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 20)); Connection conn9 = DriverManager.getConnection(getUrl(), props); conn9.createStatement().execute("CREATE INDEX idx ON " + MDTEST_NAME + "(B.COL1)"); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 30)); Connection conn91 = DriverManager.getConnection(getUrl(), props); ps = conn91.prepareStatement(dropView); ps.execute(); conn91.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 35)); Connection conn92 = DriverManager.getConnection(getUrl(), props); createStmt = "create view " + MDTEST_NAME + " (id char(1) not null primary key,\n" + " b.col1 integer,\n" + " \"c\".col2 bigint) as\n" + " select * from " + MDTEST_NAME + " where b.col1 = 1"; conn92.createStatement().execute(createStmt); conn92.close(); put = new Put(Bytes.toBytes("1")); put.add(cfB, Bytes.toBytes("COL1"), ts+39, PDataType.INTEGER.toBytes(3)); put.add(cfC, Bytes.toBytes("COL2"), ts+39, PDataType.LONG.toBytes(4)); htable.put(put); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 40)); Connection conn92a = DriverManager.getConnection(getUrl(), props); rs = conn92a.createStatement().executeQuery("select count(*) from " + MDTEST_NAME); assertTrue(rs.next()); assertEquals(1,rs.getInt(1)); conn92a.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 45)); Connection conn93 = DriverManager.getConnection(getUrl(), props); try { String alterView = "alter view " + MDTEST_NAME + " drop column b.col1"; conn93.createStatement().execute(alterView); fail(); } catch (SQLException e) { assertEquals(SQLExceptionCode.CANNOT_MUTATE_TABLE.getErrorCode(), e.getErrorCode()); } conn93.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 50)); Connection conn94 = DriverManager.getConnection(getUrl(), props); String alterView = "alter view " + MDTEST_NAME + " drop column \"c\".col2"; conn94.createStatement().execute(alterView); conn94.close(); } finally { HTableInterface htable = pconn.getQueryServices().getTable(SchemaUtil.getTableNameAsBytes(MDTEST_SCHEMA_NAME,MDTEST_NAME)); Delete delete1 = new Delete(Bytes.toBytes("0")); Delete delete2 = new Delete(Bytes.toBytes("1")); htable.batch(Arrays.asList(delete1, delete2)); } } @Test public void testAddKVColumnToExistingFamily() throws Throwable { long ts = nextTimestamp(); String tenantId = getOrganizationId(); initATableValues(tenantId, getDefaultSplits(tenantId), null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn1 = DriverManager.getConnection(getUrl(), props); // Failed attempt to repro table not found bug // TestUtil.clearMetaDataCache(conn1); // PhoenixConnection pconn = conn1.unwrap(PhoenixConnection.class); // pconn.removeTable(ATABLE_SCHEMA_NAME, ATABLE_NAME); conn1.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " ADD z_integer integer"); conn1.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 6)); Connection conn2 = DriverManager.getConnection(getUrl(), props); String query = "SELECT z_integer FROM aTable"; assertTrue(conn2.prepareStatement(query).executeQuery().next()); conn2.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 3)); Connection conn3 = DriverManager.getConnection(getUrl(), props); try { conn3.prepareStatement(query).executeQuery().next(); fail(); } catch (ColumnNotFoundException e) { } } @Test public void testAddKVColumnToNewFamily() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); initATableValues(tenantId, getDefaultSplits(tenantId), null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn1 = DriverManager.getConnection(getUrl(), props); conn1.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " ADD newcf.z_integer integer"); conn1.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 6)); Connection conn2 = DriverManager.getConnection(getUrl(), props); String query = "SELECT z_integer FROM aTable"; assertTrue(conn2.prepareStatement(query).executeQuery().next()); conn2.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 3)); Connection conn3 = DriverManager.getConnection(getUrl(), props); try { conn3.prepareStatement(query).executeQuery().next(); fail(); } catch (ColumnNotFoundException e) { } } @Test public void testAddPKColumn() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); initATableValues(tenantId, getDefaultSplits(tenantId), null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn1 = DriverManager.getConnection(getUrl(), props); try { conn1.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " ADD z_string varchar not null primary key"); fail(); } catch (SQLException e) { assertTrue(e.getMessage(), e.getMessage().contains("ERROR 1006 (42J04): Only nullable columns may be added to a multi-part row key.")); } conn1.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " ADD z_string varchar primary key"); conn1.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 6)); Connection conn2 = DriverManager.getConnection(getUrl(), props); String query = "SELECT z_string FROM aTable"; assertTrue(conn2.prepareStatement(query).executeQuery().next()); conn2.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 3)); Connection conn3 = DriverManager.getConnection(getUrl(), props); try { conn3.prepareStatement(query).executeQuery().next(); fail(); } catch (ColumnNotFoundException e) { } } @Test public void testDropKVColumn() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); initATableValues(tenantId, getDefaultSplits(tenantId), null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn5 = DriverManager.getConnection(getUrl(), props); assertTrue(conn5.createStatement().executeQuery("SELECT 1 FROM atable WHERE b_string IS NOT NULL").next()); conn5.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " DROP COLUMN b_string"); conn5.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 6)); Connection conn2 = DriverManager.getConnection(getUrl(), props); String query = "SELECT b_string FROM aTable"; try { conn2.prepareStatement(query).executeQuery().next(); fail(); } catch (ColumnNotFoundException e) { } conn2.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 3)); Connection conn3 = DriverManager.getConnection(getUrl(), props); assertTrue(conn3.prepareStatement(query).executeQuery().next()); conn3.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 7)); Connection conn7 = DriverManager.getConnection(getUrl(), props); conn7.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " ADD b_string VARCHAR"); conn7.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 8)); Connection conn8 = DriverManager.getConnection(getUrl(), props); assertFalse(conn8.createStatement().executeQuery("SELECT 1 FROM atable WHERE b_string IS NOT NULL").next()); conn8.close(); } @Test public void testDropPKColumn() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); initATableValues(tenantId, getDefaultSplits(tenantId), null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn1 = DriverManager.getConnection(getUrl(), props); try { conn1.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " DROP COLUMN entity_id"); fail(); } catch (SQLException e) { assertTrue(e.getMessage(), e.getMessage().contains("ERROR 506 (42817): Primary key column may not be dropped.")); } conn1.close(); } @Test public void testDropAllKVCols() throws Exception { ResultSet rs; long ts = nextTimestamp(); ensureTableCreated(getUrl(), MDTEST_NAME, null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); Connection conn2 = DriverManager.getConnection(getUrl(), props); conn2.createStatement().executeUpdate("UPSERT INTO " + MDTEST_NAME + " VALUES('a',1,1)"); conn2.createStatement().executeUpdate("UPSERT INTO " + MDTEST_NAME + " VALUES('b',2,2)"); conn2.commit(); conn2.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 3)); Connection conn3 = DriverManager.getConnection(getUrl(), props); rs = conn3.createStatement().executeQuery("SELECT count(1) FROM " + MDTEST_NAME); assertTrue(rs.next()); assertEquals(2, rs.getLong(1)); conn3.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn5 = DriverManager.getConnection(getUrl(), props); conn5.createStatement().executeUpdate("ALTER TABLE " + MDTEST_NAME + " DROP COLUMN col1"); conn5.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 6)); Connection conn6 = DriverManager.getConnection(getUrl(), props); rs = conn6.createStatement().executeQuery("SELECT count(1) FROM " + MDTEST_NAME); assertTrue(rs.next()); assertEquals(2, rs.getLong(1)); conn6.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 7)); Connection conn7 = DriverManager.getConnection(getUrl(), props); conn7.createStatement().executeUpdate("ALTER TABLE " + MDTEST_NAME + " DROP COLUMN col2"); conn7.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 8)); Connection conn8 = DriverManager.getConnection(getUrl(), props); rs = conn8.createStatement().executeQuery("SELECT count(1) FROM " + MDTEST_NAME); assertTrue(rs.next()); assertEquals(2, rs.getLong(1)); conn8.close(); } @Test public void testNewerTableDisallowed() throws Exception { long ts = nextTimestamp(); ensureTableCreated(getUrl(), ATABLE_NAME, null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn5 = DriverManager.getConnection(getUrl(), props); conn5.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " DROP COLUMN x_integer"); try { conn5.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " DROP COLUMN y_integer"); fail(); } catch (SQLException e) { assertTrue(e.getMessage(), e.getMessage().contains("ERROR 1013 (42M04): Table already exists. tableName=ATABLE")); } conn5.close(); } @Test public void testTableWithScemaMetadataScan() throws SQLException { long ts = nextTimestamp(); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts)); Connection conn = DriverManager.getConnection(getUrl(), props); conn.createStatement().execute("create table foo.bar(k varchar primary key)"); conn.createStatement().execute("create table bar(k varchar primary key)"); conn.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 10)); conn = DriverManager.getConnection(getUrl(), props); DatabaseMetaData metaData = conn.getMetaData(); ResultSet rs; // Tricky case that requires returning false for null AND true expression rs = metaData.getTables(null, "FOO", "BAR", null); assertTrue(rs.next()); assertEquals("FOO",rs.getString("TABLE_SCHEM")); assertEquals("BAR", rs.getString("TABLE_NAME")); assertFalse(rs.next()); // Tricky case that requires end key to maintain trailing nulls rs = metaData.getTables("", "FOO", "BAR", null); assertTrue(rs.next()); assertEquals("FOO",rs.getString("TABLE_SCHEM")); assertEquals("BAR", rs.getString("TABLE_NAME")); assertFalse(rs.next()); rs = metaData.getTables("", null, "BAR", null); assertTrue(rs.next()); assertEquals(null,rs.getString("TABLE_SCHEM")); assertEquals("BAR", rs.getString("TABLE_NAME")); assertTrue(rs.next()); assertEquals("FOO",rs.getString("TABLE_SCHEM")); assertEquals("BAR", rs.getString("TABLE_NAME")); assertFalse(rs.next()); } }
phoenix-core/src/it/java/org/apache/phoenix/end2end/QueryDatabaseMetaDataIT.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.phoenix.end2end; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_CATALOG_TABLE; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TYPE_SEQUENCE; import static org.apache.phoenix.util.TestUtil.ATABLE_NAME; import static org.apache.phoenix.util.TestUtil.ATABLE_SCHEMA_NAME; import static org.apache.phoenix.util.TestUtil.BTABLE_NAME; import static org.apache.phoenix.util.TestUtil.CUSTOM_ENTITY_DATA_FULL_NAME; import static org.apache.phoenix.util.TestUtil.CUSTOM_ENTITY_DATA_NAME; import static org.apache.phoenix.util.TestUtil.CUSTOM_ENTITY_DATA_SCHEMA_NAME; import static org.apache.phoenix.util.TestUtil.GROUPBYTEST_NAME; import static org.apache.phoenix.util.TestUtil.MDTEST_NAME; import static org.apache.phoenix.util.TestUtil.MDTEST_SCHEMA_NAME; import static org.apache.phoenix.util.TestUtil.PTSDB_NAME; import static org.apache.phoenix.util.TestUtil.STABLE_NAME; import static org.apache.phoenix.util.TestUtil.TABLE_WITH_SALTING; import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.Map; import java.util.Properties; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HTableInterface; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter; import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding; import org.apache.hadoop.hbase.util.Bytes; import org.apache.phoenix.coprocessor.GroupedAggregateRegionObserver; import org.apache.phoenix.coprocessor.ServerCachingEndpointImpl; import org.apache.phoenix.coprocessor.UngroupedAggregateRegionObserver; import org.apache.phoenix.exception.SQLExceptionCode; import org.apache.phoenix.jdbc.PhoenixConnection; import org.apache.phoenix.jdbc.PhoenixDatabaseMetaData; import org.apache.phoenix.query.QueryServices; import org.apache.phoenix.schema.ColumnNotFoundException; import org.apache.phoenix.schema.PDataType; import org.apache.phoenix.schema.PTable.ViewType; import org.apache.phoenix.schema.PTableType; import org.apache.phoenix.schema.ReadOnlyTableException; import org.apache.phoenix.schema.TableNotFoundException; import org.apache.phoenix.util.PhoenixRuntime; import org.apache.phoenix.util.PropertiesUtil; import org.apache.phoenix.util.ReadOnlyProps; import org.apache.phoenix.util.SchemaUtil; import org.apache.phoenix.util.StringUtil; import org.apache.phoenix.util.TestUtil; import org.junit.BeforeClass; import org.junit.Test; public class QueryDatabaseMetaDataIT extends BaseClientManagedTimeIT { @BeforeClass @Shadower(classBeingShadowed = BaseClientManagedTimeIT.class) public static void doSetup() throws Exception { Map<String,String> props = getDefaultProps(); props.put(QueryServices.DEFAULT_KEEP_DELETED_CELLS_ATTRIB, "true"); setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator())); } @Test public void testTableMetadataScan() throws SQLException { long ts = nextTimestamp(); ensureTableCreated(getUrl(), ATABLE_NAME, null, ts); ensureTableCreated(getUrl(), STABLE_NAME, null, ts); ensureTableCreated(getUrl(), CUSTOM_ENTITY_DATA_FULL_NAME, null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn = DriverManager.getConnection(getUrl(), props); DatabaseMetaData dbmd = conn.getMetaData(); String aTableName = StringUtil.escapeLike(TestUtil.ATABLE_NAME); String aSchemaName = TestUtil.ATABLE_SCHEMA_NAME; ResultSet rs = dbmd.getTables(null, aSchemaName, aTableName, null); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_NAME"),aTableName); assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE")); assertEquals(rs.getString(3),aTableName); assertEquals(PTableType.TABLE.toString(), rs.getString(4)); assertFalse(rs.next()); rs = dbmd.getTables(null, null, null, null); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),SYSTEM_CATALOG_SCHEMA); assertEquals(rs.getString("TABLE_NAME"),SYSTEM_CATALOG_TABLE); assertEquals(PTableType.SYSTEM.toString(), rs.getString("TABLE_TYPE")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),SYSTEM_CATALOG_SCHEMA); assertEquals(rs.getString("TABLE_NAME"),TYPE_SEQUENCE); assertEquals(PTableType.SYSTEM.toString(), rs.getString("TABLE_TYPE")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),SYSTEM_CATALOG_SCHEMA); assertEquals(rs.getString("TABLE_NAME"),PhoenixDatabaseMetaData.SYSTEM_STATS_TABLE); assertEquals(PTableType.SYSTEM.toString(), rs.getString("TABLE_TYPE")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),ATABLE_NAME); assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),STABLE_NAME); assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE")); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE")); rs = dbmd.getTables(null, CUSTOM_ENTITY_DATA_SCHEMA_NAME, CUSTOM_ENTITY_DATA_NAME, null); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),CUSTOM_ENTITY_DATA_SCHEMA_NAME); assertEquals(rs.getString("TABLE_NAME"),CUSTOM_ENTITY_DATA_NAME); assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE")); assertFalse(rs.next()); try { rs.getString("RANDOM_COLUMN_NAME"); fail(); } catch (ColumnNotFoundException e) { // expected } assertFalse(rs.next()); rs = dbmd.getTables(null, "", "_TABLE", new String[] {PTableType.TABLE.toString()}); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),ATABLE_NAME); assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),STABLE_NAME); assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE")); assertFalse(rs.next()); } @Test public void testSchemaMetadataScan() throws SQLException { long ts = nextTimestamp(); ensureTableCreated(getUrl(), CUSTOM_ENTITY_DATA_FULL_NAME, null, ts); ensureTableCreated(getUrl(), PTSDB_NAME, null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn = DriverManager.getConnection(getUrl(), props); DatabaseMetaData dbmd = conn.getMetaData(); ResultSet rs; rs = dbmd.getSchemas(null, CUSTOM_ENTITY_DATA_SCHEMA_NAME); assertTrue(rs.next()); assertEquals(rs.getString(1),CUSTOM_ENTITY_DATA_SCHEMA_NAME); assertEquals(rs.getString(2),null); assertFalse(rs.next()); rs = dbmd.getSchemas(null, null); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_CATALOG"),null); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),CUSTOM_ENTITY_DATA_SCHEMA_NAME); assertEquals(rs.getString("TABLE_CATALOG"),null); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA); assertEquals(rs.getString("TABLE_CATALOG"),null); assertFalse(rs.next()); } @Test public void testColumnMetadataScan() throws SQLException { long ts = nextTimestamp(); ensureTableCreated(getUrl(), MDTEST_NAME, null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn = DriverManager.getConnection(getUrl(), props); DatabaseMetaData dbmd = conn.getMetaData(); ResultSet rs; rs = dbmd.getColumns(null, "", MDTEST_NAME, null); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("id"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNoNulls, rs.getShort("NULLABLE")); assertEquals(PDataType.CHAR.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(1, rs.getInt("ORDINAL_POSITION")); assertEquals(1, rs.getInt("COLUMN_SIZE")); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("a"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col1"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.INTEGER.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(2, rs.getInt("ORDINAL_POSITION")); assertEquals(0, rs.getInt("COLUMN_SIZE")); assertTrue(rs.wasNull()); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.wasNull()); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col2"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.LONG.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(3, rs.getInt("ORDINAL_POSITION")); assertEquals(0, rs.getInt("COLUMN_SIZE")); assertTrue(rs.wasNull()); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.wasNull()); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col3"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.DECIMAL.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(4, rs.getInt("ORDINAL_POSITION")); assertEquals(0, rs.getInt("COLUMN_SIZE")); assertTrue(rs.wasNull()); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.wasNull()); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col4"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.DECIMAL.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(5, rs.getInt("ORDINAL_POSITION")); assertEquals(5, rs.getInt("COLUMN_SIZE")); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col5"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.DECIMAL.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(6, rs.getInt("ORDINAL_POSITION")); assertEquals(6, rs.getInt("COLUMN_SIZE")); assertEquals(3, rs.getInt("DECIMAL_DIGITS")); assertFalse(rs.next()); // Look up only columns in a column family rs = dbmd.getColumns(null, "", MDTEST_NAME, "A."); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("a"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col1"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.INTEGER.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(2, rs.getInt("ORDINAL_POSITION")); assertEquals(0, rs.getInt("COLUMN_SIZE")); assertTrue(rs.wasNull()); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.wasNull()); assertFalse(rs.next()); // Look up KV columns in a column family rs = dbmd.getColumns("", "", MDTEST_NAME, "%.COL%"); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("a"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col1"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.INTEGER.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(2, rs.getInt("ORDINAL_POSITION")); assertEquals(0, rs.getInt("COLUMN_SIZE")); assertTrue(rs.wasNull()); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.wasNull()); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col2"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.LONG.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(3, rs.getInt("ORDINAL_POSITION")); assertEquals(0, rs.getInt("COLUMN_SIZE")); assertTrue(rs.wasNull()); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.wasNull()); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col3"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.DECIMAL.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(4, rs.getInt("ORDINAL_POSITION")); assertEquals(0, rs.getInt("COLUMN_SIZE")); assertTrue(rs.wasNull()); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.wasNull()); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col4"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.DECIMAL.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(5, rs.getInt("ORDINAL_POSITION")); assertEquals(5, rs.getInt("COLUMN_SIZE")); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertFalse(rs.wasNull()); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col5"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.DECIMAL.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(6, rs.getInt("ORDINAL_POSITION")); assertEquals(6, rs.getInt("COLUMN_SIZE")); assertEquals(3, rs.getInt("DECIMAL_DIGITS")); assertFalse(rs.next()); // Look up KV columns in a column family rs = dbmd.getColumns("", "", MDTEST_NAME, "B.COL2"); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col2"), rs.getString("COLUMN_NAME")); assertFalse(rs.next()); ensureTableCreated(getUrl(), TABLE_WITH_SALTING, null, ts); rs = dbmd.getColumns("", "", TABLE_WITH_SALTING, StringUtil.escapeLike("A_INTEGER")); assertTrue(rs.next()); assertEquals(1, rs.getInt("ORDINAL_POSITION")); assertFalse(rs.next()); } @Test public void testPrimaryKeyMetadataScan() throws SQLException { long ts = nextTimestamp(); ensureTableCreated(getUrl(), MDTEST_NAME, null, ts); ensureTableCreated(getUrl(), CUSTOM_ENTITY_DATA_FULL_NAME, null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn = DriverManager.getConnection(getUrl(), props); DatabaseMetaData dbmd = conn.getMetaData(); ResultSet rs; rs = dbmd.getPrimaryKeys(null, "", MDTEST_NAME); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("id"), rs.getString("COLUMN_NAME")); assertEquals(1, rs.getInt("KEY_SEQ")); assertEquals(null, rs.getString("PK_NAME")); assertFalse(rs.next()); rs = dbmd.getPrimaryKeys(null, CUSTOM_ENTITY_DATA_SCHEMA_NAME, CUSTOM_ENTITY_DATA_NAME); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("custom_entity_data_id"), rs.getString("COLUMN_NAME")); assertEquals(3, rs.getInt("KEY_SEQ")); assertEquals(SchemaUtil.normalizeIdentifier("pk"), rs.getString("PK_NAME")); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("key_prefix"), rs.getString("COLUMN_NAME")); assertEquals(2, rs.getInt("KEY_SEQ")); assertEquals(SchemaUtil.normalizeIdentifier("pk"), rs.getString("PK_NAME")); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("organization_id"), rs.getString("COLUMN_NAME")); assertEquals(1, rs.getInt("KEY_SEQ")); assertEquals(SchemaUtil.normalizeIdentifier("pk"), rs.getString("PK_NAME")); // TODO: this is on the table row assertFalse(rs.next()); rs = dbmd.getColumns("", CUSTOM_ENTITY_DATA_SCHEMA_NAME, CUSTOM_ENTITY_DATA_NAME, null); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("organization_id"), rs.getString("COLUMN_NAME")); assertEquals(rs.getInt("COLUMN_SIZE"), 15); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("key_prefix"), rs.getString("COLUMN_NAME")); assertEquals(rs.getInt("COLUMN_SIZE"), 3); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("custom_entity_data_id"), rs.getString("COLUMN_NAME")); // The above returns all columns, starting with the PK columns assertTrue(rs.next()); rs = dbmd.getColumns("", CUSTOM_ENTITY_DATA_SCHEMA_NAME, CUSTOM_ENTITY_DATA_NAME, "KEY_PREFIX"); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("key_prefix"), rs.getString("COLUMN_NAME")); rs = dbmd.getColumns("", CUSTOM_ENTITY_DATA_SCHEMA_NAME, CUSTOM_ENTITY_DATA_NAME, "KEY_PREFIX"); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("key_prefix"), rs.getString("COLUMN_NAME")); assertFalse(rs.next()); } @Test public void testMultiTableColumnsMetadataScan() throws SQLException { long ts = nextTimestamp(); ensureTableCreated(getUrl(), MDTEST_NAME, null, ts); ensureTableCreated(getUrl(), GROUPBYTEST_NAME, null, ts); ensureTableCreated(getUrl(), PTSDB_NAME, null, ts); ensureTableCreated(getUrl(), CUSTOM_ENTITY_DATA_FULL_NAME, null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn = DriverManager.getConnection(getUrl(), props); DatabaseMetaData dbmd = conn.getMetaData(); ResultSet rs = dbmd.getColumns(null, "", "%TEST%", null); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),GROUPBYTEST_NAME); assertEquals(null, rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("id"), rs.getString("COLUMN_NAME")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),GROUPBYTEST_NAME); assertEquals(PhoenixDatabaseMetaData.TABLE_FAMILY, rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("uri"), rs.getString("COLUMN_NAME")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),GROUPBYTEST_NAME); assertEquals(PhoenixDatabaseMetaData.TABLE_FAMILY, rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("appcpu"), rs.getString("COLUMN_NAME")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),MDTEST_NAME); assertEquals(null, rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("id"), rs.getString("COLUMN_NAME")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),MDTEST_NAME); assertEquals(SchemaUtil.normalizeIdentifier("a"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col1"), rs.getString("COLUMN_NAME")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),MDTEST_NAME); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col2"), rs.getString("COLUMN_NAME")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),MDTEST_NAME); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col3"), rs.getString("COLUMN_NAME")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),MDTEST_NAME); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col4"), rs.getString("COLUMN_NAME")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),MDTEST_NAME); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col5"), rs.getString("COLUMN_NAME")); assertFalse(rs.next()); } @Test public void testCreateDropTable() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); initATableValues(tenantId, getDefaultSplits(tenantId), null, ts); ensureTableCreated(getUrl(), BTABLE_NAME, null, ts-2); ensureTableCreated(getUrl(), PTSDB_NAME, null, ts-2); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn5 = DriverManager.getConnection(getUrl(), props); String query = "SELECT a_string FROM aTable"; // Data should still be there b/c we only dropped the schema props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 8)); assertTrue(conn5.prepareStatement(query).executeQuery().next()); conn5.createStatement().executeUpdate("DROP TABLE " + ATABLE_NAME); // Confirm that data is no longer there because we dropped the table // This needs to be done natively b/c the metadata is gone HTableInterface htable = conn5.unwrap(PhoenixConnection.class).getQueryServices().getTable(SchemaUtil.getTableNameAsBytes(ATABLE_SCHEMA_NAME, ATABLE_NAME)); Scan scan = new Scan(); scan.setFilter(new FirstKeyOnlyFilter()); scan.setTimeRange(0, ts+9); assertNull(htable.getScanner(scan).next()); conn5.close(); // Still should work b/c we're at an earlier timestamp than when table was deleted props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); Connection conn2 = DriverManager.getConnection(getUrl(), props); assertTrue(conn2.prepareStatement(query).executeQuery().next()); conn2.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 10)); Connection conn10 = DriverManager.getConnection(getUrl(), props); try { conn10.prepareStatement(query).executeQuery().next(); fail(); } catch (TableNotFoundException e) { } } @Test public void testCreateOnExistingTable() throws Exception { PhoenixConnection pconn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TEST_PROPERTIES)).unwrap(PhoenixConnection.class); String tableName = MDTEST_NAME; String schemaName = MDTEST_SCHEMA_NAME; byte[] cfA = Bytes.toBytes(SchemaUtil.normalizeIdentifier("a")); byte[] cfB = Bytes.toBytes(SchemaUtil.normalizeIdentifier("b")); byte[] cfC = Bytes.toBytes("c"); byte[][] familyNames = new byte[][] {cfB, cfC}; byte[] htableName = SchemaUtil.getTableNameAsBytes(schemaName, tableName); HBaseAdmin admin = pconn.getQueryServices().getAdmin(); try { admin.disableTable(htableName); admin.deleteTable(htableName); admin.enableTable(htableName); } catch (org.apache.hadoop.hbase.TableNotFoundException e) { } @SuppressWarnings("deprecation") HTableDescriptor descriptor = new HTableDescriptor(htableName); for (byte[] familyName : familyNames) { HColumnDescriptor columnDescriptor = new HColumnDescriptor(familyName); descriptor.addFamily(columnDescriptor); } admin.createTable(descriptor); long ts = nextTimestamp(); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); PhoenixConnection conn1 = DriverManager.getConnection(getUrl(), props).unwrap(PhoenixConnection.class); ensureTableCreated(getUrl(), tableName, null, ts); descriptor = admin.getTableDescriptor(htableName); assertEquals(3,descriptor.getColumnFamilies().length); HColumnDescriptor cdA = descriptor.getFamily(cfA); assertNotEquals(HColumnDescriptor.DEFAULT_KEEP_DELETED, cdA.getKeepDeletedCells()); assertEquals(DataBlockEncoding.NONE, cdA.getDataBlockEncoding()); // Overriden using WITH assertEquals(1,cdA.getMaxVersions());// Overriden using WITH HColumnDescriptor cdB = descriptor.getFamily(cfB); // Allow KEEP_DELETED_CELLS to be false for VIEW assertEquals(HColumnDescriptor.DEFAULT_KEEP_DELETED, cdA.getKeepDeletedCells()); assertEquals(DataBlockEncoding.NONE, cdB.getDataBlockEncoding()); // Should keep the original value. // CF c should stay the same since it's not a Phoenix cf. HColumnDescriptor cdC = descriptor.getFamily(cfC); assertNotNull("Column family not found", cdC); assertEquals(HColumnDescriptor.DEFAULT_KEEP_DELETED, cdA.getKeepDeletedCells()); assertFalse(SchemaUtil.DEFAULT_DATA_BLOCK_ENCODING == cdC.getDataBlockEncoding()); assertTrue(descriptor.hasCoprocessor(UngroupedAggregateRegionObserver.class.getName())); assertTrue(descriptor.hasCoprocessor(GroupedAggregateRegionObserver.class.getName())); assertTrue(descriptor.hasCoprocessor(ServerCachingEndpointImpl.class.getName())); admin.close(); int rowCount = 5; String upsert = "UPSERT INTO " + tableName + "(id,col1,col2) VALUES(?,?,?)"; PreparedStatement ps = conn1.prepareStatement(upsert); for (int i = 0; i < rowCount; i++) { ps.setString(1, Integer.toString(i)); ps.setInt(2, i+1); ps.setInt(3, i+2); ps.execute(); } conn1.commit(); conn1.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 6)); Connection conn2 = DriverManager.getConnection(getUrl(), props); String query = "SELECT count(1) FROM " + tableName; ResultSet rs = conn2.createStatement().executeQuery(query); assertTrue(rs.next()); assertEquals(rowCount, rs.getLong(1)); query = "SELECT id, col1,col2 FROM " + tableName; rs = conn2.createStatement().executeQuery(query); for (int i = 0; i < rowCount; i++) { assertTrue(rs.next()); assertEquals(Integer.toString(i),rs.getString(1)); assertEquals(i+1, rs.getInt(2)); assertEquals(i+2, rs.getInt(3)); } assertFalse(rs.next()); conn2.close(); } @SuppressWarnings("deprecation") @Test public void testCreateViewOnExistingTable() throws Exception { PhoenixConnection pconn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TEST_PROPERTIES)).unwrap(PhoenixConnection.class); String tableName = MDTEST_NAME; String schemaName = MDTEST_SCHEMA_NAME; byte[] cfB = Bytes.toBytes(SchemaUtil.normalizeIdentifier("b")); byte[] cfC = Bytes.toBytes("c"); byte[][] familyNames = new byte[][] {cfB, cfC}; byte[] htableName = SchemaUtil.getTableNameAsBytes(schemaName, tableName); HBaseAdmin admin = pconn.getQueryServices().getAdmin(); try { admin.disableTable(htableName); admin.deleteTable(htableName); admin.enableTable(htableName); } catch (org.apache.hadoop.hbase.TableNotFoundException e) { } finally { admin.close(); } HTableDescriptor descriptor = new HTableDescriptor(htableName); for (byte[] familyName : familyNames) { HColumnDescriptor columnDescriptor = new HColumnDescriptor(familyName); descriptor.addFamily(columnDescriptor); } admin.createTable(descriptor); long ts = nextTimestamp(); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn1 = DriverManager.getConnection(getUrl(), props); String createStmt = "create view bogusTable" + " (id char(1) not null primary key,\n" + " a.col1 integer,\n" + " d.col2 bigint)\n"; try { conn1.createStatement().execute(createStmt); fail(); } catch (TableNotFoundException e) { // expected to fail b/c table doesn't exist } catch (ReadOnlyTableException e) { // expected to fail b/c table doesn't exist } createStmt = "create view " + MDTEST_NAME + " (id char(1) not null primary key,\n" + " a.col1 integer,\n" + " b.col2 bigint)\n"; try { conn1.createStatement().execute(createStmt); fail(); } catch (ReadOnlyTableException e) { // expected to fail b/c cf a doesn't exist } createStmt = "create view " + MDTEST_NAME + " (id char(1) not null primary key,\n" + " b.col1 integer,\n" + " c.col2 bigint)\n"; try { conn1.createStatement().execute(createStmt); fail(); } catch (ReadOnlyTableException e) { // expected to fail b/c cf C doesn't exist (case issue) } createStmt = "create view " + MDTEST_NAME + " (id char(1) not null primary key,\n" + " b.col1 integer,\n" + " \"c\".col2 bigint) \n"; // should be ok now conn1.createStatement().execute(createStmt); conn1.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 6)); PhoenixConnection conn2 = DriverManager.getConnection(getUrl(), props).unwrap(PhoenixConnection.class); ResultSet rs = conn2.getMetaData().getTables(null, null, MDTEST_NAME, null); assertTrue(rs.next()); assertEquals(ViewType.MAPPED.name(), rs.getString(PhoenixDatabaseMetaData.VIEW_TYPE)); assertFalse(rs.next()); String deleteStmt = "DELETE FROM " + MDTEST_NAME; PreparedStatement ps = conn2.prepareStatement(deleteStmt); try { ps.execute(); fail(); } catch (ReadOnlyTableException e) { // expected to fail b/c table is read-only } try { String upsert = "UPSERT INTO " + MDTEST_NAME + "(id,col1,col2) VALUES(?,?,?)"; ps = conn2.prepareStatement(upsert); try { ps.setString(1, Integer.toString(0)); ps.setInt(2, 1); ps.setInt(3, 2); ps.execute(); fail(); } catch (ReadOnlyTableException e) { // expected to fail b/c table is read-only } conn2.createStatement().execute("ALTER VIEW " + MDTEST_NAME + " SET IMMUTABLE_ROWS=TRUE"); HTableInterface htable = conn2.getQueryServices().getTable(SchemaUtil.getTableNameAsBytes(MDTEST_SCHEMA_NAME,MDTEST_NAME)); Put put = new Put(Bytes.toBytes("0")); put.add(cfB, Bytes.toBytes("COL1"), ts+6, PDataType.INTEGER.toBytes(1)); put.add(cfC, Bytes.toBytes("COL2"), ts+6, PDataType.LONG.toBytes(2)); htable.put(put); conn2.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 10)); Connection conn7 = DriverManager.getConnection(getUrl(), props); // Should be ok b/c we've marked the view with IMMUTABLE_ROWS=true conn7.createStatement().execute("CREATE INDEX idx ON " + MDTEST_NAME + "(B.COL1)"); String select = "SELECT col1 FROM " + MDTEST_NAME + " WHERE col2=?"; ps = conn7.prepareStatement(select); ps.setInt(1, 2); rs = ps.executeQuery(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertFalse(rs.next()); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 12)); Connection conn75 = DriverManager.getConnection(getUrl(), props); String dropTable = "DROP TABLE " + MDTEST_NAME ; ps = conn75.prepareStatement(dropTable); try { ps.execute(); fail(); } catch (TableNotFoundException e) { // expected to fail b/c it is a view } String dropView = "DROP VIEW " + MDTEST_NAME ; ps = conn75.prepareStatement(dropView); ps.execute(); conn75.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 15)); Connection conn8 = DriverManager.getConnection(getUrl(), props); createStmt = "create view " + MDTEST_NAME + " (id char(1) not null primary key,\n" + " b.col1 integer,\n" + " \"c\".col2 bigint) IMMUTABLE_ROWS=true\n"; // should be ok to create a view with IMMUTABLE_ROWS = true conn8.createStatement().execute(createStmt); conn8.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 20)); Connection conn9 = DriverManager.getConnection(getUrl(), props); conn9.createStatement().execute("CREATE INDEX idx ON " + MDTEST_NAME + "(B.COL1)"); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 30)); Connection conn91 = DriverManager.getConnection(getUrl(), props); ps = conn91.prepareStatement(dropView); ps.execute(); conn91.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 35)); Connection conn92 = DriverManager.getConnection(getUrl(), props); createStmt = "create view " + MDTEST_NAME + " (id char(1) not null primary key,\n" + " b.col1 integer,\n" + " \"c\".col2 bigint) as\n" + " select * from " + MDTEST_NAME + " where b.col1 = 1"; conn92.createStatement().execute(createStmt); conn92.close(); put = new Put(Bytes.toBytes("1")); put.add(cfB, Bytes.toBytes("COL1"), ts+39, PDataType.INTEGER.toBytes(3)); put.add(cfC, Bytes.toBytes("COL2"), ts+39, PDataType.LONG.toBytes(4)); htable.put(put); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 40)); Connection conn92a = DriverManager.getConnection(getUrl(), props); rs = conn92a.createStatement().executeQuery("select count(*) from " + MDTEST_NAME); assertTrue(rs.next()); assertEquals(1,rs.getInt(1)); conn92a.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 45)); Connection conn93 = DriverManager.getConnection(getUrl(), props); try { String alterView = "alter view " + MDTEST_NAME + " drop column b.col1"; conn93.createStatement().execute(alterView); fail(); } catch (SQLException e) { assertEquals(SQLExceptionCode.CANNOT_MUTATE_TABLE.getErrorCode(), e.getErrorCode()); } conn93.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 50)); Connection conn94 = DriverManager.getConnection(getUrl(), props); String alterView = "alter view " + MDTEST_NAME + " drop column \"c\".col2"; conn94.createStatement().execute(alterView); conn94.close(); } finally { HTableInterface htable = pconn.getQueryServices().getTable(SchemaUtil.getTableNameAsBytes(MDTEST_SCHEMA_NAME,MDTEST_NAME)); Delete delete1 = new Delete(Bytes.toBytes("0")); Delete delete2 = new Delete(Bytes.toBytes("1")); htable.batch(Arrays.asList(delete1, delete2)); } } @Test public void testAddKVColumnToExistingFamily() throws Throwable { long ts = nextTimestamp(); String tenantId = getOrganizationId(); initATableValues(tenantId, getDefaultSplits(tenantId), null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn1 = DriverManager.getConnection(getUrl(), props); // Failed attempt to repro table not found bug // TestUtil.clearMetaDataCache(conn1); // PhoenixConnection pconn = conn1.unwrap(PhoenixConnection.class); // pconn.removeTable(ATABLE_SCHEMA_NAME, ATABLE_NAME); conn1.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " ADD z_integer integer"); conn1.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 6)); Connection conn2 = DriverManager.getConnection(getUrl(), props); String query = "SELECT z_integer FROM aTable"; assertTrue(conn2.prepareStatement(query).executeQuery().next()); conn2.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 3)); Connection conn3 = DriverManager.getConnection(getUrl(), props); try { conn3.prepareStatement(query).executeQuery().next(); fail(); } catch (ColumnNotFoundException e) { } } @Test public void testAddKVColumnToNewFamily() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); initATableValues(tenantId, getDefaultSplits(tenantId), null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn1 = DriverManager.getConnection(getUrl(), props); conn1.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " ADD newcf.z_integer integer"); conn1.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 6)); Connection conn2 = DriverManager.getConnection(getUrl(), props); String query = "SELECT z_integer FROM aTable"; assertTrue(conn2.prepareStatement(query).executeQuery().next()); conn2.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 3)); Connection conn3 = DriverManager.getConnection(getUrl(), props); try { conn3.prepareStatement(query).executeQuery().next(); fail(); } catch (ColumnNotFoundException e) { } } @Test public void testAddPKColumn() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); initATableValues(tenantId, getDefaultSplits(tenantId), null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn1 = DriverManager.getConnection(getUrl(), props); try { conn1.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " ADD z_string varchar not null primary key"); fail(); } catch (SQLException e) { assertTrue(e.getMessage(), e.getMessage().contains("ERROR 1006 (42J04): Only nullable columns may be added to a multi-part row key.")); } conn1.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " ADD z_string varchar primary key"); conn1.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 6)); Connection conn2 = DriverManager.getConnection(getUrl(), props); String query = "SELECT z_string FROM aTable"; assertTrue(conn2.prepareStatement(query).executeQuery().next()); conn2.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 3)); Connection conn3 = DriverManager.getConnection(getUrl(), props); try { conn3.prepareStatement(query).executeQuery().next(); fail(); } catch (ColumnNotFoundException e) { } } @Test public void testDropKVColumn() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); initATableValues(tenantId, getDefaultSplits(tenantId), null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn5 = DriverManager.getConnection(getUrl(), props); assertTrue(conn5.createStatement().executeQuery("SELECT 1 FROM atable WHERE b_string IS NOT NULL").next()); conn5.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " DROP COLUMN b_string"); conn5.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 6)); Connection conn2 = DriverManager.getConnection(getUrl(), props); String query = "SELECT b_string FROM aTable"; try { conn2.prepareStatement(query).executeQuery().next(); fail(); } catch (ColumnNotFoundException e) { } conn2.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 3)); Connection conn3 = DriverManager.getConnection(getUrl(), props); assertTrue(conn3.prepareStatement(query).executeQuery().next()); conn3.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 7)); Connection conn7 = DriverManager.getConnection(getUrl(), props); conn7.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " ADD b_string VARCHAR"); conn7.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 8)); Connection conn8 = DriverManager.getConnection(getUrl(), props); assertFalse(conn8.createStatement().executeQuery("SELECT 1 FROM atable WHERE b_string IS NOT NULL").next()); conn8.close(); } @Test public void testDropPKColumn() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); initATableValues(tenantId, getDefaultSplits(tenantId), null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn1 = DriverManager.getConnection(getUrl(), props); try { conn1.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " DROP COLUMN entity_id"); fail(); } catch (SQLException e) { assertTrue(e.getMessage(), e.getMessage().contains("ERROR 506 (42817): Primary key column may not be dropped.")); } conn1.close(); } @Test public void testDropAllKVCols() throws Exception { ResultSet rs; long ts = nextTimestamp(); ensureTableCreated(getUrl(), MDTEST_NAME, null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); Connection conn2 = DriverManager.getConnection(getUrl(), props); conn2.createStatement().executeUpdate("UPSERT INTO " + MDTEST_NAME + " VALUES('a',1,1)"); conn2.createStatement().executeUpdate("UPSERT INTO " + MDTEST_NAME + " VALUES('b',2,2)"); conn2.commit(); conn2.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 3)); Connection conn3 = DriverManager.getConnection(getUrl(), props); rs = conn3.createStatement().executeQuery("SELECT count(1) FROM " + MDTEST_NAME); assertTrue(rs.next()); assertEquals(2, rs.getLong(1)); conn3.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn5 = DriverManager.getConnection(getUrl(), props); conn5.createStatement().executeUpdate("ALTER TABLE " + MDTEST_NAME + " DROP COLUMN col1"); conn5.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 6)); Connection conn6 = DriverManager.getConnection(getUrl(), props); rs = conn6.createStatement().executeQuery("SELECT count(1) FROM " + MDTEST_NAME); assertTrue(rs.next()); assertEquals(2, rs.getLong(1)); conn6.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 7)); Connection conn7 = DriverManager.getConnection(getUrl(), props); conn7.createStatement().executeUpdate("ALTER TABLE " + MDTEST_NAME + " DROP COLUMN col2"); conn7.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 8)); Connection conn8 = DriverManager.getConnection(getUrl(), props); rs = conn8.createStatement().executeQuery("SELECT count(1) FROM " + MDTEST_NAME); assertTrue(rs.next()); assertEquals(2, rs.getLong(1)); conn8.close(); } @Test public void testNewerTableDisallowed() throws Exception { long ts = nextTimestamp(); ensureTableCreated(getUrl(), ATABLE_NAME, null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn5 = DriverManager.getConnection(getUrl(), props); conn5.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " DROP COLUMN x_integer"); try { conn5.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " DROP COLUMN y_integer"); fail(); } catch (SQLException e) { assertTrue(e.getMessage(), e.getMessage().contains("ERROR 1013 (42M04): Table already exists. tableName=ATABLE")); } conn5.close(); } @Test public void testTableWithScemaMetadataScan() throws SQLException { long ts = nextTimestamp(); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts)); Connection conn = DriverManager.getConnection(getUrl(), props); conn.createStatement().execute("create table foo.bar(k varchar primary key)"); conn.createStatement().execute("create table bar(k varchar primary key)"); conn.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 10)); conn = DriverManager.getConnection(getUrl(), props); DatabaseMetaData metaData = conn.getMetaData(); ResultSet rs; // Tricky case that requires returning false for null AND true expression rs = metaData.getTables(null, "FOO", "BAR", null); assertTrue(rs.next()); assertEquals("FOO",rs.getString("TABLE_SCHEM")); assertEquals("BAR", rs.getString("TABLE_NAME")); assertFalse(rs.next()); // Tricky case that requires end key to maintain trailing nulls rs = metaData.getTables("", "FOO", "BAR", null); assertTrue(rs.next()); assertEquals("FOO",rs.getString("TABLE_SCHEM")); assertEquals("BAR", rs.getString("TABLE_NAME")); assertFalse(rs.next()); rs = metaData.getTables("", null, "BAR", null); assertTrue(rs.next()); assertEquals(null,rs.getString("TABLE_SCHEM")); assertEquals("BAR", rs.getString("TABLE_NAME")); assertTrue(rs.next()); assertEquals("FOO",rs.getString("TABLE_SCHEM")); assertEquals("BAR", rs.getString("TABLE_NAME")); assertFalse(rs.next()); } }
PHOENIX-1470 amendment; fix test
phoenix-core/src/it/java/org/apache/phoenix/end2end/QueryDatabaseMetaDataIT.java
PHOENIX-1470 amendment; fix test
<ide><path>hoenix-core/src/it/java/org/apache/phoenix/end2end/QueryDatabaseMetaDataIT.java <ide> assertEquals(1,cdA.getMaxVersions());// Overriden using WITH <ide> HColumnDescriptor cdB = descriptor.getFamily(cfB); <ide> // Allow KEEP_DELETED_CELLS to be false for VIEW <del> assertEquals(HColumnDescriptor.DEFAULT_KEEP_DELETED, cdA.getKeepDeletedCells()); <add> assertEquals(HColumnDescriptor.DEFAULT_KEEP_DELETED, cdB.getKeepDeletedCells()); <ide> assertEquals(DataBlockEncoding.NONE, cdB.getDataBlockEncoding()); // Should keep the original value. <ide> // CF c should stay the same since it's not a Phoenix cf. <ide> HColumnDescriptor cdC = descriptor.getFamily(cfC); <ide> assertNotNull("Column family not found", cdC); <del> assertEquals(HColumnDescriptor.DEFAULT_KEEP_DELETED, cdA.getKeepDeletedCells()); <add> assertEquals(HColumnDescriptor.DEFAULT_KEEP_DELETED, cdC.getKeepDeletedCells()); <ide> assertFalse(SchemaUtil.DEFAULT_DATA_BLOCK_ENCODING == cdC.getDataBlockEncoding()); <ide> assertTrue(descriptor.hasCoprocessor(UngroupedAggregateRegionObserver.class.getName())); <ide> assertTrue(descriptor.hasCoprocessor(GroupedAggregateRegionObserver.class.getName()));
JavaScript
mit
37ac9ab5d3b7124ae1e16ea8811d19a389b38eef
0
isaacev/ArthurJS
var Gulp = require('gulp'); var GulpUtil = require('gulp-util'); var GulpArthur = require('gulp-arthur'); var GulpValidate = require('gulp-jsvalidate'); var Build = require('./build.js').build; // takes each *.arthur file in `/arthur/` and compiles // it to JavaScript, placing the output data inside // `/bin/modules/` directory Gulp.task('arthur', function () { Gulp.src('./arthur/*.arthur') .pipe(GulpArthur({ bare: true, basic: true }).on('error', GulpUtil.log)) .pipe(Gulp.dest('./bin/modules/')); }); // ensure that the JavaScript output by the parser // is valid before packaging into `arthur.js` else // the entire process becomes corrupted. no new files // can be written because the parser is corrupt making // it impossible to correct the mistake Gulp.task('validate', function () { Gulp.src('./bin/modules/*.js') .pipe(GulpValidate()); }); // runs `build.js` which concatenates all raw JavaScript // source files, wrapping them in a sercret sauce that // allows them to run in Node.js or client-side seamlessly Gulp.task('build', function () { Build(false); }); // different than `build`, `mayday` uses the previously generated // JavaScript files to creat the parser. this is in case the latest // files get malformed and therefore the parser becomes malformed // making it impossible to correct the files Gulp.task('mayday', function () { Build(true); }); // watches *.arthur files for changes // when detected, compiles the new file and // builds full `arthur.js` Gulp.task('watch', function () { Gulp.watch('./src/**', ['arthur', 'validate', 'build']); }); // the default task // builds all the *.arthur files in the arthur directory, // saving them into the modules folder. when completed, // it validates their JavaScript, checking for malformed // code. if the tests pass, it builds them all into a new // Arthur compiler Gulp.task('default', ['arthur', 'validate', 'build']);
gulpfile.js
var Gulp = require('gulp'); var GulpUtil = require('gulp-util'); var GulpArthur = require('gulp-arthur'); var GulpValidate = require('gulp-jsvalidate'); var Build = require('./build.js').build; // takes each *.arthur file in `/arthur/` and compiles // it to JavaScript, placing the output data inside // `/bin/modules/` directory Gulp.task('arthur', function () { // Gulp.src('./arthur/*.arthur') // .pipe(GulpArthur({ // bare: true // }).on('error', GulpUtil.log)) // .pipe(Gulp.dest('./bin/modules/')); Gulp.src('./arthur/*.arthur') .pipe(GulpArthur({ bare: true }).on('error', GulpUtil.log)) .pipe(Gulp.dest('./bin/modules/')); }); // ensure that the JavaScript output by the parser // is valid before packaging into `arthur.js` else // the entire process becomes corrupted. no new files // can be written because the parser is corrupt making // it impossible to correct the mistake Gulp.task('validate', function () { Gulp.src('./bin/modules/*.js') .pipe(GulpValidate()); }); // runs `build.js` which concatenates all raw JavaScript // source files, wrapping them in a sercret sauce that // allows them to run in Node.js or client-side seamlessly Gulp.task('build', function () { Build(); }); // different than `build`, `mayday` uses the previously generated // JavaScript files to creat the parser. this is in case the latest // files get malformed and therefore the parser becomes malformed // making it impossible to correct the files Gulp.task('mayday', function () { Build(true); }); // watches *.arthur files for changes // when detected, compiles the new file and // builds full `arthur.js` Gulp.task('watch', function () { Gulp.watch('./src/**', ['arthur', 'validate', 'build']); }); Gulp.task('default', ['arthur', 'validate', 'build']);
clarify code purpose also add debugging in gulp.build
gulpfile.js
clarify code purpose
<ide><path>ulpfile.js <ide> // it to JavaScript, placing the output data inside <ide> // `/bin/modules/` directory <ide> Gulp.task('arthur', function () { <del> // Gulp.src('./arthur/*.arthur') <del> // .pipe(GulpArthur({ <del> // bare: true <del> // }).on('error', GulpUtil.log)) <del> // .pipe(Gulp.dest('./bin/modules/')); <ide> Gulp.src('./arthur/*.arthur') <ide> .pipe(GulpArthur({ <del> bare: true <add> bare: true, <add> basic: true <ide> }).on('error', GulpUtil.log)) <ide> .pipe(Gulp.dest('./bin/modules/')); <ide> }); <ide> // source files, wrapping them in a sercret sauce that <ide> // allows them to run in Node.js or client-side seamlessly <ide> Gulp.task('build', function () { <del> Build(); <add> Build(false); <ide> }); <ide> <ide> <ide> Gulp.watch('./src/**', ['arthur', 'validate', 'build']); <ide> }); <ide> <add> <add>// the default task <add>// builds all the *.arthur files in the arthur directory, <add>// saving them into the modules folder. when completed, <add>// it validates their JavaScript, checking for malformed <add>// code. if the tests pass, it builds them all into a new <add>// Arthur compiler <ide> Gulp.task('default', ['arthur', 'validate', 'build']);
Java
mit
81365f527afdd77568da313982a735dc50f84034
0
dafe/Sentiment,lukeherron/Sentiment,lukeherron/Sentiment,dafe/Sentiment
package com.gofish.sentiment.sentimentservice.job; import com.gofish.sentiment.sentimentservice.article.SentimentArticle; import io.vertx.codegen.annotations.DataObject; import io.vertx.core.json.JsonObject; /** * @author Luke Herron */ @DataObject(generateConverter = true) public class LinkerJob extends AbstractJob { private final JsonObject article; public LinkerJob(SentimentArticle article) { // The AnalyserJobConverter class requires a constructor that accepts a JSON version of this, so unfortunately // we can't have another constructor to accept the native version of an article, so we accept the String version // instead and convert it to JsonObject inside this constructor. This has the downside of forcing clients to // encode the article before creating the job this.article = article.toJson(); } public LinkerJob(JsonObject json) { super(json.getString("jobId")); article = json.getJsonObject("payload"); LinkerJobConverter.fromJson(json, this); } @Override public LinkerJob copy() { return new LinkerJob(this.toJson().copy()); } @Override public JsonObject getPayload() { return article; } @Override public JsonObject toJson() { JsonObject json = new JsonObject(); LinkerJobConverter.toJson(this, json); return json; } }
sentiment-service/src/main/java/com/gofish/sentiment/sentimentservice/job/LinkerJob.java
package com.gofish.sentiment.sentimentservice.job; import com.gofish.sentiment.sentimentservice.article.SentimentArticle; import io.vertx.codegen.annotations.DataObject; import io.vertx.core.json.JsonObject; /** * @author Luke Herron */ @DataObject(generateConverter = true) public class LinkerJob extends AbstractJob { private final JsonObject article; public LinkerJob(SentimentArticle article) { // The AnalyserJobConverter class requires a constructor that accepts a JSON version of this, so unfortunately // we can't have another constructor to accept the native version of an article, so we accept the String version // instead and convert it to JsonObject inside this constructor. This has the downside of forcing clients to // encode the article before creating the job this.article = article.toJson(); } public LinkerJob(JsonObject json) { super(json.getString("jobId")); article = json.getJsonObject("article"); LinkerJobConverter.fromJson(json, this); } public JsonObject getArticle() { return article; } @Override public LinkerJob copy() { return new LinkerJob(this.toJson().copy()); } // @Override // public long getTimeout() { // return 0; // } @Override public JsonObject toJson() { JsonObject json = new JsonObject(); LinkerJobConverter.toJson(this, json); // Needs to be auto-generated first return json; } }
Adjusted job to retrieve abstract type 'payload' instead of the more specific 'article' from jobs JSON object.
sentiment-service/src/main/java/com/gofish/sentiment/sentimentservice/job/LinkerJob.java
Adjusted job to retrieve abstract type 'payload' instead of the more specific 'article' from jobs JSON object.
<ide><path>entiment-service/src/main/java/com/gofish/sentiment/sentimentservice/job/LinkerJob.java <ide> <ide> public LinkerJob(JsonObject json) { <ide> super(json.getString("jobId")); <del> article = json.getJsonObject("article"); <add> article = json.getJsonObject("payload"); <ide> <ide> LinkerJobConverter.fromJson(json, this); <del> } <del> <del> public JsonObject getArticle() { <del> return article; <ide> } <ide> <ide> @Override <ide> return new LinkerJob(this.toJson().copy()); <ide> } <ide> <del>// @Override <del>// public long getTimeout() { <del>// return 0; <del>// } <add> @Override <add> public JsonObject getPayload() { <add> return article; <add> } <ide> <ide> @Override <ide> public JsonObject toJson() { <ide> JsonObject json = new JsonObject(); <del> LinkerJobConverter.toJson(this, json); // Needs to be auto-generated first <add> LinkerJobConverter.toJson(this, json); <ide> <ide> return json; <ide> }
JavaScript
mit
3b58fdc6e78343b0324f8fa449f086be1c90dc74
0
jsonresume/registry-server,bartuspan/registry-server,vfulco/registry-server,bartuspan/registry-server,jsonresume/registry-server,bartuspan/registry-server,vfulco/registry-server,jsonresume/registry-server,vfulco/registry-server
var express = require("express"); var Mustache = require('mustache'); var resumeToText = require('resume-to-text'); var path = require('path'); var resumeToHTML = require('resume-to-html'); var resumeToMarkdown = require('resume-to-markdown'); var bodyParser = require('body-parser'); var bcrypt = require('bcrypt-nodejs'); var gravatar = require('gravatar'); var app = express(); var _ = require('lodash'); var postmark = require("postmark")(process.env.POSTMARK_API_KEY); var MongoClient = require('mongodb').MongoClient; var mongo = require('mongodb'); var templateHelper = require('./template-helper'); var pdf = require('pdfcrowd'); var request = require('superagent'); var sha256 = require('sha256'); var expressSession = require('express-session'); var cookieParser = require('cookie-parser'); var Pusher = require('pusher'); var pusher = null; if(process.env.PUSHER_KEY) { pusher = new Pusher({ appId: '83846', key: process.env.PUSHER_KEY, secret: process.env.PUSHER_SECRET }); }; var points = []; var realTimeViews = 0; if (process.env.REDISTOGO_URL) { var rtg = require("url").parse(process.env.REDISTOGO_URL); var redis = require("redis").createClient(rtg.port, rtg.hostname); redis.auth(rtg.auth.split(":")[1]); } else { var redis = require("redis").createClient(); } var RedisStore = require('connect-redis')(expressSession); redis.on("error", function(err) { console.log("error event - " + redis.host + ":" + redis.port + " - " + err); }); var allowCrossDomain = function(req, res, next) { // Added other domains you want the server to give access to // WARNING - Be careful with what origins you give access to var allowedHost = [ 'http://backbonetutorials.com', 'http://localhost' ]; res.header('Access-Control-Allow-Credentials', true); res.header('Access-Control-Allow-Origin', req.headers.origin) res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); res.header('Access-Control-Allow-Headers', 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version'); next(); } app.use(allowCrossDomain); app.use(cookieParser()); app.use(expressSession({ store: new RedisStore({client: redis}), secret: 'keyboard cat' })) //app.use(expressSession({secret:'somesecrettokenhere'})); app.use(express.static(__dirname + '/resume-editor', {maxAge: 7200 * 1000})); var client = new pdf.Pdfcrowd('thomasdavis', '7d2352eade77858f102032829a2ac64e'); app.use(bodyParser()); var fs = require('fs'); var guid = (function() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return function() { return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); }; })(); function S4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); }; var defaulMongoUrl = "mongodb://localhost:27017/jsonresume"; if (!process.env.MONGOHQ_URL) { console.log("Using default MONGOHQ_URL="+defaulMongoUrl); } var mongoUrl = process.env.MONGOHQ_URL || defaultMongoUrl; MongoClient.connect(process.env.MONGOHQ_URL, function(err, db) { app.all('/*', function(req, res, next) { //res.header("Access-Control-Allow-Origin", "*"); //res.header("Access-Control-Allow-Headers", "X-Requested-With"); next(); }); var renderHomePage = function(req, res) { db.collection('users').find({}).toArray(function(err, docs) { var usernameArray = []; docs.forEach(function(doc) { usernameArray.push({ username: doc.username, gravatar: gravatar.url(doc.email, { s: '80', r: 'pg', d: '404' }) }); }); var page = Mustache.render(templateHelper.get('home'), { usernames: usernameArray }); res.send(page); }); }; var renderResume = function(req, res) { realTimeViews++; redis.get('views', function(err, views) { if(err) { redis.set('views', 0); } else { redis.set('views', views*1+1, redis.print); } console.log(views); if(pusher !== null) { pusher.trigger('test_channel', 'my_event', { views: views }); }; }); var themeName = req.query.theme || 'modern'; var uid = req.params.uid; var format = req.params.format || req.headers.accept || 'html'; db.collection('resumes').findOne({ 'jsonresume.username': uid, }, function(err, resume) { if (!resume) { var page = Mustache.render(templateHelper.get('noresume'), {}); res.send(page); return; } if (typeof resume.jsonresume.passphrase === 'string' && typeof req.body.passphrase === 'undefined') { var page = Mustache.render(templateHelper.get('password'), {}); res.send(page); return; } if (typeof req.body.passphrase !== 'undefined' && req.body.passphrase !== resume.jsonresume.passphrase) { res.send('Password was wrong, go back and try again'); return; } var content = ''; if (/json/.test(format)) { if(typeof req.session.username === 'undefined') { delete resume.jsonresume; // This removes our registry server config vars from the resume.json } delete resume._id; // This removes the document id of mongo content = JSON.stringify(resume, undefined, 4); res.set({ 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(content, 'utf8') // TODO - This is a hack to try get the right content length // http://stackoverflow.com/questions/17922748/what-is-the-correct-method-for-calculating-the-content-length-header-in-node-js }); res.send(content); } else if (/txt/.test(format)) { content = resumeToText(resume, function(plainText) { res.set({ 'Content-Type': 'text/plain', 'Content-Length': plainText.length }); res.send(200, plainText); }); } else if (/md/.test(format)) { resumeToMarkdown(resume, function(markdown, errs) { res.set({ 'Content-Type': 'text/plain', 'Content-Length': markdown.length }); res.send(markdown); }) } else if (/pdf/.test(format)) { // this code is used for web-based pdf export such as http://registry.jsonresume.org/thomasdavis.pdf - see line ~310 for resume-cli export console.log('Come on PDFCROWD'); var theme = req.query.theme || resume.jsonresume.theme || themeName; request .post('http://themes.jsonresume.org/theme/' + theme) .send({ resume: resume }) .set('Content-Type', 'application/json') .end(function(response) { client.convertHtml(response.text, pdf.sendHttpResponse(res,null,uid+".pdf"), { use_print_media: "true" }); }); } else { var theme = req.query.theme || resume.jsonresume.theme || themeName; request .post('http://themes.jsonresume.org/theme/' + theme) .send({ resume: resume }) .set('Content-Type', 'application/json') .end(function(response) { res.send(response.text); }); /* resumeToHTML(resume, { }, function(content, errs) { console.log(content, errs); var page = Mustache.render(templateHelper.get('layout'), { output: content, resume: resume, username: uid }); res.send(content); }); */ } }); }; app.get('/session', function(req, res){ // This checks the current users auth // It runs before Backbones router is started // we should return a csrf token for Backbone to use if(typeof req.session.username !== 'undefined'){ res.send({auth: true, id: req.session.id, username: req.session.username, _csrf: req.session._csrf}); } else { res.send({auth: false, _csrf: req.session._csrf}); } }); app.del('/session/:id', function(req, res, next){ // Logout by clearing the session req.session.regenerate(function(err){ // Generate a new csrf token so the user can login again // This is pretty hacky, connect.csrf isn't built for rest // I will probably release a restful csrf module //csrf.generate(req, res, function () { res.send({auth: false, _csrf: req.session._csrf}); //}); }); }); //app.get('/', renderHomePage); var renderMembersPage = function(req, res) { console.log('================================'); db.collection('users').find({}).toArray(function(err, docs) { console.log(err); var usernameArray = []; docs.forEach(function(doc) { usernameArray.push({ username: doc.username, gravatar: gravatar.url(doc.email, { s: '80', r: 'pg', d: '404' }) }); }); var page = Mustache.render(templateHelper.get('members'), { usernames: usernameArray }); res.send(page); }); }; app.get('/members', renderMembersPage); app.get('/competition', function (req,res) { //{vote: {$ne: null}}, {username:1, vote: 1} var leaderboard = {}; var currentMonth = new Date().getMonth(); db.collection('tweets').find({vote: {$ne: null}}, {username:1, vote: 1}).toArray( function (e, tweets) { tweets = _.filter(tweets, function(tweet){ if(currentMonth === new Date(tweet.created_at).getMonth()){ return true; } else { return false; } }); console.log(tweets); var votes = []; _.each(tweets, function(tweet){ votes.push({username: tweet.username, vote: tweet.vote.substr(1)}) if(typeof leaderboard[tweet.vote.substr(1)] === 'undefined') { leaderboard[tweet.vote.substr(1)] = 1; } else { leaderboard[tweet.vote.substr(1)] += 1 } }); res.send({leaderboard: leaderboard, votes: votes}); }); }); app.get('/stats', function (req,res) { redis.get('views', function(err, views) { db.collection('users').find().count(function (e, usercount) { db.collection('resumes').find().count(function (e, resumecount) { res.send({userCount: usercount,resumeCount: resumecount, views: views*1}); }); }); }); }); // export pdf route // this code is used by resume-cli for pdf export, see line ~188 for web-based export app.get('/pdf', function(req, res) { console.log(req.body.resume, req.body.theme); request .post('http://themes.jsonresume.org/theme/' + req.body.theme) .send({ resume: req.body.resume }) .set('Content-Type', 'application/json') .end(function(response) { client.convertHtml(response.text, pdf.sendHttpResponse(res),{ use_print_media: "true" }); }); }); app.get('/:uid.:format', renderResume); app.get('/:uid', renderResume); redis.on("error", function(err) { console.log("Error " + err); res.send({ sessionError: err }); }); app.post('/resume', function(req, res) { var password = req.body.password; var email = req.body.email || req.session.email; // console.log(req.body); console.log('XXXXXXXXXXXXXXXX', req.session.username); if (!req.body.guest) { db.collection('users').findOne({ 'email': email }, function(err, user) { // console.log(err, user); redis.get(req.body.session, function(err, valueExists) { if ((user && password && bcrypt.compareSync(password, user.hash)) || (typeof req.session.username !== 'undefined')) { var resume = req.body && req.body.resume || {}; resume.jsonresume = { username: user.username, passphrase: req.body.passphrase || null, theme: req.body.theme || null }; console.log('inserted'); db.collection('resumes').update({ 'jsonresume.username': user.username }, resume, { upsert: true, safe: true }, function(err, resume) { res.send({ url: 'http://registry.jsonresume.org/' + user.username }); }); } else if (valueExists === null) { res.send({ sessionError: 'invalid session' }); } else if (valueExists) { console.log('success'); var resume = req.body && req.body.resume || {}; resume.jsonresume = { username: user.username, passphrase: req.body.passphrase || null, theme: req.body.theme || null }; console.log('inserted'); db.collection('resumes').update({ 'jsonresume.username': user.username }, resume, { upsert: true, safe: true }, function(err, resume) { res.send({ url: 'http://registry.jsonresume.org/' + user.username }); }); } else { res.send({ message: 'ERRORRRSSSS' }); } }); }); } else { var guestUsername = S4() + S4(); var resume = req.body && req.body.resume || {}; resume.jsonresume = { username: guestUsername, passphrase: req.body.passphrase || null, theme: req.body.theme || null }; console.log('inserted'); db.collection('resumes').insert(resume, { safe: true }, function(err, resume) { res.send({ url: 'http://registry.jsonresume.org/' + guestUsername }); }); } }); // update theme app.put('/resume', function(req, res) { console.log(req.body); var password = req.body.password; var email = req.body.email; var theme = req.body.theme; console.log(theme, "theme update!!!!!!!!!!!!1111"); // console.log(req.body); db.collection('users').findOne({ 'email': email }, function(err, user) { redis.get(req.body.session, function(err, valueExists) { console.log(err, valueExists, 'theme redis'); if (!valueExists && user && bcrypt.compareSync(password, user.hash)) { db.collection('resumes').update({ //query 'jsonresume.username': user.username }, { // update set new theme $set: { 'jsonresume.theme': theme } }, { //options upsert: true, safe: true }, function(err, resume) { res.send({ url: 'http://registry.jsonresume.org/' + user.username }); }); } else if (valueExists === null) { res.send({ sessionError: 'invalid session' }); } else if (valueExists === 'true') { console.log('redis session success'); db.collection('resumes').update({ //query 'jsonresume.username': user.username }, { // update set new theme $set: { 'jsonresume.theme': theme } }, { //options upsert: true, safe: true }, function(err, resume) { res.send({ url: 'http://registry.jsonresume.org/' + user.username }); }); } else { console.log('deleted'); res.send({ message: 'authentication error' }); } }); }); }); app.post('/user', function(req, res) { // console.log(req.body); db.collection('users').findOne({ 'email': req.body.email }, function(err, user) { if (user) { res.send({ error: { field: 'email', message: 'Email is already in use, maybe you forgot your password?' } }); } else { db.collection('users').findOne({ 'username': req.body.username }, function(err, user) { if (user) { res.send({ error: { field: 'username', message: 'This username is already taken, please try another one' } }); } else { var emailTemplate = fs.readFileSync('templates/email/welcome.html', 'utf8'); var emailCopy = Mustache.render(emailTemplate, { username: req.body.username }); var hash = bcrypt.hashSync(req.body.password); postmark.send({ "From": "[email protected]", "To": req.body.email, "Subject": "Json Resume - Community driven HR", "TextBody": emailCopy }, function(error, success) { if (error) { console.error("Unable to send via postmark: " + error.message); return; } console.info("Sent to postmark for delivery") }); db.collection('users').insert({ username: req.body.username, email: req.body.email, hash: hash }, { safe: true }, function(err, user) { req.session.username = user[0].username; req.session.email = user[0].email; console.log('USE CREATED', req.session, req.session.username); res.send({ // username: user.username, email: user[0].email, username: user[0].username, message: "success" }); }); } }); } }); }); function uid(len) { return Math.random().toString(35).substr(2, len); } app.post('/session', function(req, res) { var password = req.body.password; var email = req.body.email; // console.log(req.body); db.collection('users').findOne({ 'email': email }, function(err, user) { if (user && bcrypt.compareSync(password, user.hash)) { // console.log(email, bcrypt.hashSync(email)); // console.log(email, bcrypt.hashSync(email)); var sessionUID = uid(32); redis.set(sessionUID, true, redis.print); // var session = value.toString(); req.session.username = user.username; req.session.email = email; res.send({ message: 'loggedIn', username: user.username, email: email, session: sessionUID, auth: true }); // redis.quit(); } else { res.send({ message: 'authentication error' }); } }); }); //delete user app.delete('/account', function(req, res) { var password = req.body.password; var email = req.body.email; db.collection('users').findOne({ 'email': email }, function(err, user) { console.log(err, user, 'waafdkls'); if (!user) { res.send({ message: '\nemail not found' }); } else if (user && bcrypt.compareSync(password, user.hash)) { // console.log(req.body); //remove the users resume db.collection('resumes').remove({ 'jsonresume.username': user.username }, 1, function(err, numberRemoved) { console.log(err, numberRemoved, 'resume deleted'); // then remove user db.collection('users').remove({ 'email': email }, 1, function(err, numberRemoved) { console.log(err, numberRemoved, 'user deleted'); if (err) { res.send(err); } else { res.send({ message: '\nYour account has been successfully deleted.' }); } }); }); } else { res.send({ message: "\ninvalid Password" }); } }); }); //change password app.put('/account', function(req, res) { var email = req.body.email; var password = req.body.currentPassword; var hash = bcrypt.hashSync(req.body.newPassword); console.log(email, password, hash); db.collection('users').findOne({ 'email': email }, function(err, user) { if (user && bcrypt.compareSync(password, user.hash)) { // console.log(req.body); db.collection('users').update({ //query 'email': email }, { $set: { 'hash': hash } }, { //options upsert: true, safe: true }, function(err, user) { console.log(err, user); if (!err) { res.send({ message: "password updated" }); } }); } }); }); app.post('/:uid', renderResume); var port = Number(process.env.PORT || 5000); app.listen(port, function() { console.log("Listening on " + port); }); })
server.js
var express = require("express"); var Mustache = require('mustache'); var resumeToText = require('resume-to-text'); var path = require('path'); var resumeToHTML = require('resume-to-html'); var resumeToMarkdown = require('resume-to-markdown'); var bodyParser = require('body-parser'); var bcrypt = require('bcrypt-nodejs'); var gravatar = require('gravatar'); var app = express(); var _ = require('lodash'); var postmark = require("postmark")(process.env.POSTMARK_API_KEY); var MongoClient = require('mongodb').MongoClient; var mongo = require('mongodb'); var templateHelper = require('./template-helper'); var pdf = require('pdfcrowd'); var request = require('superagent'); var sha256 = require('sha256'); var expressSession = require('express-session'); var cookieParser = require('cookie-parser'); var Pusher = require('pusher'); var pusher = null; if(process.env.PUSHER_KEY) { pusher = new Pusher({ appId: '83846', key: process.env.PUSHER_KEY, secret: process.env.PUSHER_SECRET }); }; var points = []; var realTimeViews = 0; if (process.env.REDISTOGO_URL) { var rtg = require("url").parse(process.env.REDISTOGO_URL); var redis = require("redis").createClient(rtg.port, rtg.hostname); redis.auth(rtg.auth.split(":")[1]); } else { var redis = require("redis").createClient(); } var RedisStore = require('connect-redis')(expressSession); redis.on("error", function(err) { console.log("error event - " + redis.host + ":" + redis.port + " - " + err); }); var allowCrossDomain = function(req, res, next) { // Added other domains you want the server to give access to // WARNING - Be careful with what origins you give access to var allowedHost = [ 'http://backbonetutorials.com', 'http://localhost' ]; res.header('Access-Control-Allow-Credentials', true); res.header('Access-Control-Allow-Origin', req.headers.origin) res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); res.header('Access-Control-Allow-Headers', 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version'); next(); } app.use(allowCrossDomain); app.use(cookieParser()); app.use(expressSession({ store: new RedisStore({client: redis}), secret: 'keyboard cat' })) //app.use(expressSession({secret:'somesecrettokenhere'})); app.use(express.static(__dirname + '/resume-editor', {maxAge: 7200 * 1000})); var client = new pdf.Pdfcrowd('thomasdavis', '7d2352eade77858f102032829a2ac64e'); app.use(bodyParser()); var fs = require('fs'); var guid = (function() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return function() { return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); }; })(); function S4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); }; MongoClient.connect(process.env.MONGOHQ_URL, function(err, db) { app.all('/*', function(req, res, next) { //res.header("Access-Control-Allow-Origin", "*"); //res.header("Access-Control-Allow-Headers", "X-Requested-With"); next(); }); var renderHomePage = function(req, res) { db.collection('users').find({}).toArray(function(err, docs) { var usernameArray = []; docs.forEach(function(doc) { usernameArray.push({ username: doc.username, gravatar: gravatar.url(doc.email, { s: '80', r: 'pg', d: '404' }) }); }); var page = Mustache.render(templateHelper.get('home'), { usernames: usernameArray }); res.send(page); }); }; var renderResume = function(req, res) { realTimeViews++; redis.get('views', function(err, views) { if(err) { redis.set('views', 0); } else { redis.set('views', views*1+1, redis.print); } console.log(views); if(pusher !== null) { pusher.trigger('test_channel', 'my_event', { views: views }); }; }); var themeName = req.query.theme || 'modern'; var uid = req.params.uid; var format = req.params.format || req.headers.accept || 'html'; db.collection('resumes').findOne({ 'jsonresume.username': uid, }, function(err, resume) { if (!resume) { var page = Mustache.render(templateHelper.get('noresume'), {}); res.send(page); return; } if (typeof resume.jsonresume.passphrase === 'string' && typeof req.body.passphrase === 'undefined') { var page = Mustache.render(templateHelper.get('password'), {}); res.send(page); return; } if (typeof req.body.passphrase !== 'undefined' && req.body.passphrase !== resume.jsonresume.passphrase) { res.send('Password was wrong, go back and try again'); return; } var content = ''; if (/json/.test(format)) { if(typeof req.session.username === 'undefined') { delete resume.jsonresume; // This removes our registry server config vars from the resume.json } delete resume._id; // This removes the document id of mongo content = JSON.stringify(resume, undefined, 4); res.set({ 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(content, 'utf8') // TODO - This is a hack to try get the right content length // http://stackoverflow.com/questions/17922748/what-is-the-correct-method-for-calculating-the-content-length-header-in-node-js }); res.send(content); } else if (/txt/.test(format)) { content = resumeToText(resume, function(plainText) { res.set({ 'Content-Type': 'text/plain', 'Content-Length': plainText.length }); res.send(200, plainText); }); } else if (/md/.test(format)) { resumeToMarkdown(resume, function(markdown, errs) { res.set({ 'Content-Type': 'text/plain', 'Content-Length': markdown.length }); res.send(markdown); }) } else if (/pdf/.test(format)) { // this code is used for web-based pdf export such as http://registry.jsonresume.org/thomasdavis.pdf - see line ~310 for resume-cli export console.log('Come on PDFCROWD'); var theme = req.query.theme || resume.jsonresume.theme || themeName; request .post('http://themes.jsonresume.org/theme/' + theme) .send({ resume: resume }) .set('Content-Type', 'application/json') .end(function(response) { client.convertHtml(response.text, pdf.sendHttpResponse(res,null,uid+".pdf"), { use_print_media: "true" }); }); } else { var theme = req.query.theme || resume.jsonresume.theme || themeName; request .post('http://themes.jsonresume.org/theme/' + theme) .send({ resume: resume }) .set('Content-Type', 'application/json') .end(function(response) { res.send(response.text); }); /* resumeToHTML(resume, { }, function(content, errs) { console.log(content, errs); var page = Mustache.render(templateHelper.get('layout'), { output: content, resume: resume, username: uid }); res.send(content); }); */ } }); }; app.get('/session', function(req, res){ // This checks the current users auth // It runs before Backbones router is started // we should return a csrf token for Backbone to use if(typeof req.session.username !== 'undefined'){ res.send({auth: true, id: req.session.id, username: req.session.username, _csrf: req.session._csrf}); } else { res.send({auth: false, _csrf: req.session._csrf}); } }); app.del('/session/:id', function(req, res, next){ // Logout by clearing the session req.session.regenerate(function(err){ // Generate a new csrf token so the user can login again // This is pretty hacky, connect.csrf isn't built for rest // I will probably release a restful csrf module //csrf.generate(req, res, function () { res.send({auth: false, _csrf: req.session._csrf}); //}); }); }); //app.get('/', renderHomePage); var renderMembersPage = function(req, res) { console.log('================================'); db.collection('users').find({}).toArray(function(err, docs) { console.log(err); var usernameArray = []; docs.forEach(function(doc) { usernameArray.push({ username: doc.username, gravatar: gravatar.url(doc.email, { s: '80', r: 'pg', d: '404' }) }); }); var page = Mustache.render(templateHelper.get('members'), { usernames: usernameArray }); res.send(page); }); }; app.get('/members', renderMembersPage); app.get('/competition', function (req,res) { //{vote: {$ne: null}}, {username:1, vote: 1} var leaderboard = {}; var currentMonth = new Date().getMonth(); db.collection('tweets').find({vote: {$ne: null}}, {username:1, vote: 1}).toArray( function (e, tweets) { tweets = _.filter(tweets, function(tweet){ if(currentMonth === new Date(tweet.created_at).getMonth()){ return true; } else { return false; } }); console.log(tweets); var votes = []; _.each(tweets, function(tweet){ votes.push({username: tweet.username, vote: tweet.vote.substr(1)}) if(typeof leaderboard[tweet.vote.substr(1)] === 'undefined') { leaderboard[tweet.vote.substr(1)] = 1; } else { leaderboard[tweet.vote.substr(1)] += 1 } }); res.send({leaderboard: leaderboard, votes: votes}); }); }); app.get('/stats', function (req,res) { redis.get('views', function(err, views) { db.collection('users').find().count(function (e, usercount) { db.collection('resumes').find().count(function (e, resumecount) { res.send({userCount: usercount,resumeCount: resumecount, views: views*1}); }); }); }); }); // export pdf route // this code is used by resume-cli for pdf export, see line ~188 for web-based export app.get('/pdf', function(req, res) { console.log(req.body.resume, req.body.theme); request .post('http://themes.jsonresume.org/theme/' + req.body.theme) .send({ resume: req.body.resume }) .set('Content-Type', 'application/json') .end(function(response) { client.convertHtml(response.text, pdf.sendHttpResponse(res),{ use_print_media: "true" }); }); }); app.get('/:uid.:format', renderResume); app.get('/:uid', renderResume); redis.on("error", function(err) { console.log("Error " + err); res.send({ sessionError: err }); }); app.post('/resume', function(req, res) { var password = req.body.password; var email = req.body.email || req.session.email; // console.log(req.body); console.log('XXXXXXXXXXXXXXXX', req.session.username); if (!req.body.guest) { db.collection('users').findOne({ 'email': email }, function(err, user) { // console.log(err, user); redis.get(req.body.session, function(err, valueExists) { if ((user && password && bcrypt.compareSync(password, user.hash)) || (typeof req.session.username !== 'undefined')) { var resume = req.body && req.body.resume || {}; resume.jsonresume = { username: user.username, passphrase: req.body.passphrase || null, theme: req.body.theme || null }; console.log('inserted'); db.collection('resumes').update({ 'jsonresume.username': user.username }, resume, { upsert: true, safe: true }, function(err, resume) { res.send({ url: 'http://registry.jsonresume.org/' + user.username }); }); } else if (valueExists === null) { res.send({ sessionError: 'invalid session' }); } else if (valueExists) { console.log('success'); var resume = req.body && req.body.resume || {}; resume.jsonresume = { username: user.username, passphrase: req.body.passphrase || null, theme: req.body.theme || null }; console.log('inserted'); db.collection('resumes').update({ 'jsonresume.username': user.username }, resume, { upsert: true, safe: true }, function(err, resume) { res.send({ url: 'http://registry.jsonresume.org/' + user.username }); }); } else { res.send({ message: 'ERRORRRSSSS' }); } }); }); } else { var guestUsername = S4() + S4(); var resume = req.body && req.body.resume || {}; resume.jsonresume = { username: guestUsername, passphrase: req.body.passphrase || null, theme: req.body.theme || null }; console.log('inserted'); db.collection('resumes').insert(resume, { safe: true }, function(err, resume) { res.send({ url: 'http://registry.jsonresume.org/' + guestUsername }); }); } }); // update theme app.put('/resume', function(req, res) { console.log(req.body); var password = req.body.password; var email = req.body.email; var theme = req.body.theme; console.log(theme, "theme update!!!!!!!!!!!!1111"); // console.log(req.body); db.collection('users').findOne({ 'email': email }, function(err, user) { redis.get(req.body.session, function(err, valueExists) { console.log(err, valueExists, 'theme redis'); if (!valueExists && user && bcrypt.compareSync(password, user.hash)) { db.collection('resumes').update({ //query 'jsonresume.username': user.username }, { // update set new theme $set: { 'jsonresume.theme': theme } }, { //options upsert: true, safe: true }, function(err, resume) { res.send({ url: 'http://registry.jsonresume.org/' + user.username }); }); } else if (valueExists === null) { res.send({ sessionError: 'invalid session' }); } else if (valueExists === 'true') { console.log('redis session success'); db.collection('resumes').update({ //query 'jsonresume.username': user.username }, { // update set new theme $set: { 'jsonresume.theme': theme } }, { //options upsert: true, safe: true }, function(err, resume) { res.send({ url: 'http://registry.jsonresume.org/' + user.username }); }); } else { console.log('deleted'); res.send({ message: 'authentication error' }); } }); }); }); app.post('/user', function(req, res) { // console.log(req.body); db.collection('users').findOne({ 'email': req.body.email }, function(err, user) { if (user) { res.send({ error: { field: 'email', message: 'Email is already in use, maybe you forgot your password?' } }); } else { db.collection('users').findOne({ 'username': req.body.username }, function(err, user) { if (user) { res.send({ error: { field: 'username', message: 'This username is already taken, please try another one' } }); } else { var emailTemplate = fs.readFileSync('templates/email/welcome.html', 'utf8'); var emailCopy = Mustache.render(emailTemplate, { username: req.body.username }); var hash = bcrypt.hashSync(req.body.password); postmark.send({ "From": "[email protected]", "To": req.body.email, "Subject": "Json Resume - Community driven HR", "TextBody": emailCopy }, function(error, success) { if (error) { console.error("Unable to send via postmark: " + error.message); return; } console.info("Sent to postmark for delivery") }); db.collection('users').insert({ username: req.body.username, email: req.body.email, hash: hash }, { safe: true }, function(err, user) { req.session.username = user[0].username; req.session.email = user[0].email; console.log('USE CREATED', req.session, req.session.username); res.send({ // username: user.username, email: user[0].email, username: user[0].username, message: "success" }); }); } }); } }); }); function uid(len) { return Math.random().toString(35).substr(2, len); } app.post('/session', function(req, res) { var password = req.body.password; var email = req.body.email; // console.log(req.body); db.collection('users').findOne({ 'email': email }, function(err, user) { if (user && bcrypt.compareSync(password, user.hash)) { // console.log(email, bcrypt.hashSync(email)); // console.log(email, bcrypt.hashSync(email)); var sessionUID = uid(32); redis.set(sessionUID, true, redis.print); // var session = value.toString(); req.session.username = user.username; req.session.email = email; res.send({ message: 'loggedIn', username: user.username, email: email, session: sessionUID, auth: true }); // redis.quit(); } else { res.send({ message: 'authentication error' }); } }); }); //delete user app.delete('/account', function(req, res) { var password = req.body.password; var email = req.body.email; db.collection('users').findOne({ 'email': email }, function(err, user) { console.log(err, user, 'waafdkls'); if (!user) { res.send({ message: '\nemail not found' }); } else if (user && bcrypt.compareSync(password, user.hash)) { // console.log(req.body); //remove the users resume db.collection('resumes').remove({ 'jsonresume.username': user.username }, 1, function(err, numberRemoved) { console.log(err, numberRemoved, 'resume deleted'); // then remove user db.collection('users').remove({ 'email': email }, 1, function(err, numberRemoved) { console.log(err, numberRemoved, 'user deleted'); if (err) { res.send(err); } else { res.send({ message: '\nYour account has been successfully deleted.' }); } }); }); } else { res.send({ message: "\ninvalid Password" }); } }); }); //change password app.put('/account', function(req, res) { var email = req.body.email; var password = req.body.currentPassword; var hash = bcrypt.hashSync(req.body.newPassword); console.log(email, password, hash); db.collection('users').findOne({ 'email': email }, function(err, user) { if (user && bcrypt.compareSync(password, user.hash)) { // console.log(req.body); db.collection('users').update({ //query 'email': email }, { $set: { 'hash': hash } }, { //options upsert: true, safe: true }, function(err, user) { console.log(err, user); if (!err) { res.send({ message: "password updated" }); } }); } }); }); app.post('/:uid', renderResume); var port = Number(process.env.PORT || 5000); app.listen(port, function() { console.log("Listening on " + port); }); })
Set a default URL for Mongo
server.js
Set a default URL for Mongo
<ide><path>erver.js <ide> var bcrypt = require('bcrypt-nodejs'); <ide> var gravatar = require('gravatar'); <ide> var app = express(); <del>var _ = require('lodash'); <add>var _ = require('lodash'); <ide> var postmark = require("postmark")(process.env.POSTMARK_API_KEY); <ide> var MongoClient = require('mongodb').MongoClient; <ide> var mongo = require('mongodb'); <ide> 'http://backbonetutorials.com', <ide> 'http://localhost' <ide> ]; <del> <add> <ide> res.header('Access-Control-Allow-Credentials', true); <ide> res.header('Access-Control-Allow-Origin', req.headers.origin) <ide> res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); <ide> <ide> app.use(allowCrossDomain); <ide> app.use(cookieParser()); <del> app.use(expressSession({ store: new RedisStore({client: redis}), secret: 'keyboard cat' })) <add>app.use(expressSession({ store: new RedisStore({client: redis}), secret: 'keyboard cat' })) <ide> //app.use(expressSession({secret:'somesecrettokenhere'})); <ide> <ide> app.use(express.static(__dirname + '/resume-editor', {maxAge: 7200 * 1000})); <ide> .substring(1); <ide> }; <ide> <add>var defaulMongoUrl = "mongodb://localhost:27017/jsonresume"; <add>if (!process.env.MONGOHQ_URL) { <add> console.log("Using default MONGOHQ_URL="+defaulMongoUrl); <add>} <add>var mongoUrl = process.env.MONGOHQ_URL || defaultMongoUrl; <ide> MongoClient.connect(process.env.MONGOHQ_URL, function(err, db) { <ide> app.all('/*', function(req, res, next) { <ide> //res.header("Access-Control-Allow-Origin", "*"); <ide> <ide> var renderResume = function(req, res) { <ide> realTimeViews++; <del> <add> <ide> redis.get('views', function(err, views) { <ide> if(err) { <ide> redis.set('views', 0); <ide> }); <ide> /* <ide> resumeToHTML(resume, { <del> <add> <ide> }, function(content, errs) { <ide> console.log(content, errs); <ide> var page = Mustache.render(templateHelper.get('layout'), { <ide> }); <ide> }; <ide> <del> app.get('/session', function(req, res){ <add> app.get('/session', function(req, res){ <ide> // This checks the current users auth <ide> // It runs before Backbones router is started <ide> // we should return a csrf token for Backbone to use <ide> res.send({auth: false, _csrf: req.session._csrf}); <ide> } <ide> }); <del> app.del('/session/:id', function(req, res, next){ <add> app.del('/session/:id', function(req, res, next){ <ide> // Logout by clearing the session <ide> req.session.regenerate(function(err){ <ide> // Generate a new csrf token so the user can login again <ide> // This is pretty hacky, connect.csrf isn't built for rest <ide> // I will probably release a restful csrf module <ide> //csrf.generate(req, res, function () { <del> res.send({auth: false, _csrf: req.session._csrf}); <add> res.send({auth: false, _csrf: req.session._csrf}); <ide> //}); <del> }); <add> }); <ide> }); <ide> <ide>
Java
apache-2.0
deb4d42335c3211371559810f8c092a04686cca9
0
SerCeMan/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,clumsy/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,robovm/robovm-studio,holmes/intellij-community,apixandru/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,izonder/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,FHannes/intellij-community,fitermay/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,da1z/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,supersven/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,caot/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,petteyg/intellij-community,kool79/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,ibinti/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,ryano144/intellij-community,diorcety/intellij-community,supersven/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,izonder/intellij-community,joewalnes/idea-community,vladmm/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,diorcety/intellij-community,jexp/idea2,Distrotech/intellij-community,allotria/intellij-community,izonder/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,allotria/intellij-community,fitermay/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,consulo/consulo,orekyuu/intellij-community,supersven/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,kool79/intellij-community,da1z/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,holmes/intellij-community,adedayo/intellij-community,signed/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,FHannes/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,apixandru/intellij-community,slisson/intellij-community,consulo/consulo,FHannes/intellij-community,alphafoobar/intellij-community,signed/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,slisson/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,amith01994/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,apixandru/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,semonte/intellij-community,dslomov/intellij-community,consulo/consulo,ol-loginov/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,adedayo/intellij-community,blademainer/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,holmes/intellij-community,dslomov/intellij-community,adedayo/intellij-community,FHannes/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,slisson/intellij-community,kdwink/intellij-community,kool79/intellij-community,hurricup/intellij-community,ernestp/consulo,da1z/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,samthor/intellij-community,clumsy/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,jexp/idea2,idea4bsd/idea4bsd,blademainer/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,semonte/intellij-community,ibinti/intellij-community,izonder/intellij-community,caot/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,hurricup/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,da1z/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,fnouama/intellij-community,hurricup/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,apixandru/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,allotria/intellij-community,joewalnes/idea-community,Lekanich/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,da1z/intellij-community,dslomov/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,caot/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,holmes/intellij-community,caot/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,amith01994/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,hurricup/intellij-community,signed/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,amith01994/intellij-community,allotria/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,kool79/intellij-community,ryano144/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,allotria/intellij-community,adedayo/intellij-community,petteyg/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,slisson/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,semonte/intellij-community,vvv1559/intellij-community,allotria/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,caot/intellij-community,asedunov/intellij-community,slisson/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,consulo/consulo,mglukhikh/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,fitermay/intellij-community,joewalnes/idea-community,nicolargo/intellij-community,samthor/intellij-community,joewalnes/idea-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,joewalnes/idea-community,muntasirsyed/intellij-community,semonte/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,ibinti/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,samthor/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,da1z/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,jexp/idea2,mglukhikh/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,allotria/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,joewalnes/idea-community,petteyg/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,holmes/intellij-community,ernestp/consulo,Distrotech/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,signed/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,kool79/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,signed/intellij-community,robovm/robovm-studio,caot/intellij-community,joewalnes/idea-community,mglukhikh/intellij-community,ryano144/intellij-community,semonte/intellij-community,ibinti/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,jexp/idea2,suncycheng/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,signed/intellij-community,hurricup/intellij-community,da1z/intellij-community,apixandru/intellij-community,signed/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,caot/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,joewalnes/idea-community,supersven/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,ernestp/consulo,ibinti/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,adedayo/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,hurricup/intellij-community,ryano144/intellij-community,robovm/robovm-studio,robovm/robovm-studio,fitermay/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,da1z/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,joewalnes/idea-community,fengbaicanhe/intellij-community,holmes/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,ernestp/consulo,clumsy/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,consulo/consulo,dslomov/intellij-community,Distrotech/intellij-community,holmes/intellij-community,adedayo/intellij-community,izonder/intellij-community,kdwink/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,signed/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,petteyg/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,jexp/idea2,xfournet/intellij-community,semonte/intellij-community,vladmm/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,izonder/intellij-community,consulo/consulo,holmes/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,izonder/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,jexp/idea2,wreckJ/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,kool79/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,holmes/intellij-community,kool79/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,slisson/intellij-community,caot/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,diorcety/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,gnuhub/intellij-community,slisson/intellij-community,asedunov/intellij-community,ibinti/intellij-community,retomerz/intellij-community,fitermay/intellij-community,jagguli/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,apixandru/intellij-community,allotria/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,ernestp/consulo,holmes/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,izonder/intellij-community,kdwink/intellij-community,jagguli/intellij-community,petteyg/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,robovm/robovm-studio,supersven/intellij-community,kool79/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,kool79/intellij-community,slisson/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,holmes/intellij-community,vladmm/intellij-community,allotria/intellij-community,caot/intellij-community,ryano144/intellij-community,jexp/idea2,adedayo/intellij-community,supersven/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,asedunov/intellij-community,jexp/idea2,SerCeMan/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,adedayo/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,ernestp/consulo,xfournet/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,da1z/intellij-community,gnuhub/intellij-community,signed/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,signed/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,samthor/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,amith01994/intellij-community
package com.intellij.codeInsight.completion; import com.intellij.codeInsight.TailType; import com.intellij.codeInsight.lookup.LookupItem; import com.intellij.psi.*; import com.intellij.psi.filters.*; import com.intellij.psi.filters.classes.*; import com.intellij.psi.filters.element.ExcludeDeclaredFilter; import com.intellij.psi.filters.element.ModifierFilter; import com.intellij.psi.filters.element.ReferenceOnFilter; import com.intellij.psi.filters.getters.UpWalkGetter; import com.intellij.psi.filters.position.*; import com.intellij.psi.filters.types.TypeCodeFragmentIsVoidEnabledFilter; import com.intellij.psi.impl.source.jsp.jspJava.JspClass; import com.intellij.psi.jsp.JspElementType; public class JavaCompletionData extends CompletionData{ protected static final String[] MODIFIERS_LIST = { "public", "protected", "private", "static", "final", "native", "abstract", "synchronized", "volatile", "transient" }; private static final String[] ourBlockFinalizers = {"{", "}", ";", ":", "else"}; public JavaCompletionData(){ declareCompletionSpaces(); final CompletionVariant variant = new CompletionVariant(PsiMethod.class, TrueFilter.INSTANCE); variant.includeScopeClass(PsiVariable.class); variant.includeScopeClass(PsiClass.class); variant.includeScopeClass(PsiFile.class); variant.addCompletion(new ModifierChooser()); registerVariant(variant); initVariantsInFileScope(); initVariantsInClassScope(); initVariantsInMethodScope(); initVariantsInFieldScope(); defineScopeEquivalence(PsiMethod.class, PsiClassInitializer.class); defineScopeEquivalence(PsiMethod.class, PsiCodeFragment.class); } private void declareCompletionSpaces() { declareFinalScope(PsiFile.class); { // Class body final CompletionVariant variant = new CompletionVariant(CLASS_BODY); variant.includeScopeClass(PsiClass.class, true); this.registerVariant(variant); } { // Method body final CompletionVariant variant = new CompletionVariant(new InsideElementFilter(new ClassFilter(PsiCodeBlock.class))); variant.includeScopeClass(PsiMethod.class, true); variant.includeScopeClass(PsiClassInitializer.class, true); this.registerVariant(variant); } { // Field initializer final CompletionVariant variant = new CompletionVariant(new AfterElementFilter(new TextFilter("="))); variant.includeScopeClass(PsiField.class, true); this.registerVariant(variant); } declareFinalScope(PsiLiteralExpression.class); declareFinalScope(PsiComment.class); } protected void initVariantsInFileScope(){ // package keyword completion { final CompletionVariant variant = new CompletionVariant(PsiJavaFile.class, new StartElementFilter()); variant.addCompletion(PsiKeyword.PACKAGE); this.registerVariant(variant); } // import keyword completion { final CompletionVariant variant = new CompletionVariant(PsiJavaFile.class, new OrFilter( new StartElementFilter(), END_OF_BLOCK )); variant.addCompletion(PsiKeyword.IMPORT); this.registerVariant(variant); } // other in file scope { final ElementFilter position = new OrFilter(new ElementFilter[]{ END_OF_BLOCK, new LeftNeighbour(new OrFilter(new SuperParentFilter(new ClassFilter(PsiAnnotation.class)), new TextFilter(MODIFIERS_LIST))), new StartElementFilter() }); final CompletionVariant variant = new CompletionVariant(PsiJavaFile.class, position); variant.includeScopeClass(PsiClass.class); variant.addCompletion(PsiKeyword.CLASS); variant.addCompletion(PsiKeyword.INTERFACE); registerVariant(variant); } { final CompletionVariant variant = new CompletionVariant(PsiTypeCodeFragment.class, new StartElementFilter()); addPrimitiveTypes(variant, TailType.NONE); final CompletionVariant variant1 = new CompletionVariant(PsiTypeCodeFragment.class, new AndFilter( new StartElementFilter(), new TypeCodeFragmentIsVoidEnabledFilter() ) ); variant1.addCompletion(PsiKeyword.VOID, TailType.NONE); registerVariant(variant); registerVariant(variant1); } } /** * aClass == null for JspDeclaration scope */ protected void initVariantsInClassScope() { // Completion for extends keyword // position { final ElementFilter position = new AndFilter(new ElementFilter[]{ new NotFilter(CLASS_BODY), new NotFilter(new AfterElementFilter(new ContentFilter(new TextFilter(PsiKeyword.EXTENDS)))), new NotFilter(new AfterElementFilter(new ContentFilter(new TextFilter(PsiKeyword.IMPLEMENTS)))), new NotFilter(new LeftNeighbour(new LeftNeighbour(new TextFilter("<", ",")))), new NotFilter(new ScopeFilter(new EnumFilter())), new LeftNeighbour(new OrFilter( new ClassFilter(PsiIdentifier.class), new TextFilter(">"))), }); // completion final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiClass.class, true); variant.addCompletion(PsiKeyword.EXTENDS); variant.excludeScopeClass(PsiAnonymousClass.class); variant.excludeScopeClass(PsiTypeParameter.class); this.registerVariant(variant); } // Completion for implements keyword // position { final ElementFilter position = new AndFilter(new ElementFilter[]{ new NotFilter(CLASS_BODY), new NotFilter(new BeforeElementFilter(new ContentFilter(new TextFilter(PsiKeyword.EXTENDS)))), new NotFilter(new AfterElementFilter(new ContentFilter(new TextFilter(PsiKeyword.IMPLEMENTS)))), new NotFilter(new LeftNeighbour(new LeftNeighbour(new TextFilter("<", ",")))), new LeftNeighbour(new OrFilter( new ClassFilter(PsiIdentifier.class), new TextFilter(">"))), new NotFilter(new ScopeFilter(new InterfaceFilter())) }); // completion final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiClass.class, true); variant.addCompletion(PsiKeyword.IMPLEMENTS); variant.excludeScopeClass(PsiAnonymousClass.class); this.registerVariant(variant); } // Completion after extends in interface, type parameter and implements in class // position { final ElementFilter position = new AndFilter( new NotFilter(CLASS_BODY), new OrFilter( new ElementFilter [] { new AndFilter( new LeftNeighbour(new TextFilter(PsiKeyword.EXTENDS, ",")), new ScopeFilter(new InterfaceFilter()) ), new AndFilter( new LeftNeighbour(new TextFilter(PsiKeyword.EXTENDS, "&")), new ScopeFilter(new ClassFilter(PsiTypeParameter.class)) ), new LeftNeighbour(new TextFilter(PsiKeyword.IMPLEMENTS, ",")) } ) ); // completion final OrFilter flags = new OrFilter(); flags.addFilter(new ThisOrAnyInnerFilter( new AndFilter(new ElementFilter[]{ new ClassFilter(PsiClass.class), new NotFilter(new AssignableFromContextFilter()), new InterfaceFilter() }) )); flags.addFilter(new ClassFilter(PsiPackage.class)); CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiClass.class, true); variant.excludeScopeClass(PsiAnonymousClass.class); variant.addCompletionFilterOnElement(flags); this.registerVariant(variant); } // Completion for classes in class extends // position { final ElementFilter position = new AndFilter( new NotFilter(CLASS_BODY), new AndFilter(new ElementFilter[]{ new LeftNeighbour(new TextFilter(PsiKeyword.EXTENDS)), new ScopeFilter(new NotFilter(new InterfaceFilter())) }) ); // completion final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiClass.class, true); variant.excludeScopeClass(PsiAnonymousClass.class); variant.addCompletionFilterOnElement(new ThisOrAnyInnerFilter( new AndFilter(new ElementFilter[]{ new ClassFilter(PsiClass.class), new NotFilter(new AssignableFromContextFilter()), new NotFilter(new InterfaceFilter()), new ModifierFilter(PsiModifier.FINAL, false) }) )); variant.addCompletionFilterOnElement(new ClassFilter(PsiPackage.class)); this.registerVariant(variant); } { // declaration start // position final CompletionVariant variant = new CompletionVariant(PsiClass.class, new AndFilter( CLASS_BODY, new OrFilter( END_OF_BLOCK, new LeftNeighbour(new OrFilter( new TextFilter(MODIFIERS_LIST), new SuperParentFilter(new ClassFilter(PsiAnnotation.class)), new TokenTypeFilter(JavaTokenType.GT))) ))); // completion addPrimitiveTypes(variant); variant.addCompletion(PsiKeyword.VOID); variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class)); variant.addCompletionFilterOnElement(new ClassFilter(PsiPackage.class)); this.registerVariant(variant); } { final CompletionVariant variant = new CompletionVariant(new LeftNeighbour(new LeftNeighbour(new TextFilter("<", ",")))); variant.includeScopeClass(PsiClass.class, true); variant.addCompletion(PsiKeyword.EXTENDS, TailType.SPACE); this.registerVariant(variant); } } private void initVariantsInMethodScope() { { // parameters list completion final CompletionVariant variant = new CompletionVariant( new LeftNeighbour(new OrFilter(new TextFilter(new String[]{"(", ",", "final"}), new SuperParentFilter(new ClassFilter(PsiAnnotation.class))))); variant.includeScopeClass(PsiParameterList.class, true); addPrimitiveTypes(variant); variant.addCompletion(PsiKeyword.FINAL); variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class)); this.registerVariant(variant); } // Completion for classes in method throws section // position { final ElementFilter position = new LeftNeighbour(new AndFilter( new TextFilter(")"), new ParentElementFilter(new ClassFilter(PsiParameterList.class)))); // completion CompletionVariant variant = new CompletionVariant(PsiMethod.class, position); variant.addCompletion(PsiKeyword.THROWS); this.registerVariant(variant); //in annotation methods variant = new CompletionVariant(PsiAnnotationMethod.class, position); variant.addCompletion(PsiKeyword.DEFAULT); this.registerVariant(variant); } { // Completion for classes in method throws section // position final ElementFilter position = new AndFilter( new LeftNeighbour(new TextFilter(PsiKeyword.THROWS, ",")), new InsideElementFilter(new ClassFilter(PsiReferenceList.class)) ); // completion final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiMethod.class, true); variant.addCompletionFilterOnElement(new ThisOrAnyInnerFilter(new InheritorFilter("java.lang.Throwable"))); variant.addCompletionFilterOnElement(new ClassFilter(PsiPackage.class)); this.registerVariant(variant); } { // completion for declarations final CompletionVariant variant = new CompletionVariant(PsiMethod.class, new OrFilter(END_OF_BLOCK, new LeftNeighbour(new TextFilter("final")))); addPrimitiveTypes(variant); variant.addCompletion(PsiKeyword.CLASS); this.registerVariant(variant); } // Completion in cast expressions { final CompletionVariant variant = new CompletionVariant(PsiMethod.class, new LeftNeighbour(new AndFilter( new TextFilter("("), new ParentElementFilter(new OrFilter( new ClassFilter(PsiParenthesizedExpression.class), new ClassFilter(PsiTypeCastExpression.class)))))); addPrimitiveTypes(variant); this.registerVariant(variant); } { // instanceof keyword final ElementFilter position = new LeftNeighbour(new OrFilter(new ElementFilter[]{ new ReferenceOnFilter(new ClassFilter(PsiVariable.class)), new TextFilter("this"), new AndFilter(new TextFilter(")"), new ParentElementFilter(new AndFilter( new ClassFilter(PsiTypeCastExpression.class, false), new OrFilter( new ParentElementFilter(new ClassFilter(PsiExpression.class)), new ClassFilter(PsiExpression.class))))), new AndFilter(new TextFilter("]"), new ParentElementFilter(new ClassFilter(PsiArrayAccessExpression.class))) })); final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiExpression.class, true); variant.includeScopeClass(PsiMethod.class); variant.addCompletionFilter(new FalseFilter()); variant.addCompletion(PsiKeyword.INSTANCEOF); this.registerVariant(variant); } { // after instanceof keyword final ElementFilter position = new PreviousElementFilter(new TextFilter(PsiKeyword.INSTANCEOF)); final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiExpression.class, true); variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class)); this.registerVariant(variant); } { // after final keyword final ElementFilter position = new AndFilter(new SuperParentFilter(new ClassFilter(PsiCodeBlock.class)), new LeftNeighbour(new TextFilter(PsiKeyword.FINAL))); final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiDeclarationStatement.class, true); variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class)); addPrimitiveTypes(variant); this.registerVariant(variant); } { // Keyword completion in start of declaration final CompletionVariant variant = new CompletionVariant(PsiMethod.class, END_OF_BLOCK); variant.addCompletion(PsiKeyword.THIS, TailType.NONE); variant.addCompletion(PsiKeyword.SUPER, TailType.NONE); addKeywords(variant); this.registerVariant(variant); } { // Keyword completion in returns final CompletionVariant variant = new CompletionVariant(PsiMethod.class, new LeftNeighbour(new TextFilter("return"))); variant.addCompletion(PsiKeyword.THIS, TailType.NONE); variant.addCompletion(PsiKeyword.SUPER, TailType.NONE); this.registerVariant(variant); } // Catch/Finnaly completion { final ElementFilter position = new LeftNeighbour(new AndFilter( new TextFilter("}"), new ParentElementFilter(new AndFilter( new LeftNeighbour(new TextFilter("try")), new ParentElementFilter(new ClassFilter(PsiTryStatement.class)))))); final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiCodeBlock.class, true); variant.addCompletion(PsiKeyword.CATCH, TailType.LPARENTH); variant.addCompletion(PsiKeyword.FINALLY, '{'); variant.addCompletionFilter(new FalseFilter()); this.registerVariant(variant); } // Catch/Finnaly completion { final ElementFilter position = new LeftNeighbour(new AndFilter( new TextFilter("}"), new ParentElementFilter(new AndFilter( new LeftNeighbour(new NotFilter(new TextFilter("try"))), new OrFilter( new ParentElementFilter(new ClassFilter(PsiTryStatement.class)), new ParentElementFilter(new ClassFilter(PsiCatchSection.class))) )))); final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiCodeBlock.class, false); variant.addCompletion(PsiKeyword.CATCH, TailType.LPARENTH); variant.addCompletion(PsiKeyword.FINALLY, '{'); //variant.addCompletionFilter(new FalseFilter()); this.registerVariant(variant); } { // Completion for catches final CompletionVariant variant = new CompletionVariant(PsiTryStatement.class, new PreviousElementFilter(new AndFilter( new ParentElementFilter(new ClassFilter(PsiTryStatement.class)), new TextFilter("(") ))); variant.includeScopeClass(PsiParameter.class); variant.addCompletionFilterOnElement(new ThisOrAnyInnerFilter(new InheritorFilter("java.lang.Throwable"))); variant.addCompletionFilterOnElement(new ClassFilter(PsiPackage.class)); this.registerVariant(variant); } // Completion for else expression // completion { final ElementFilter position = new LeftNeighbour( new OrFilter( new AndFilter(new TextFilter("}"),new ParentElementFilter(new ClassFilter(PsiIfStatement.class), 3)), new AndFilter(new TextFilter(";"),new ParentElementFilter(new ClassFilter(PsiIfStatement.class), 2)) )); final CompletionVariant variant = new CompletionVariant(PsiMethod.class, position); variant.addCompletion(PsiKeyword.ELSE); this.registerVariant(variant); } { // Super/This keyword completion final ElementFilter position = new LeftNeighbour( new AndFilter( new TextFilter("."), new LeftNeighbour( new ReferenceOnFilter(new GeneratorFilter(EqualsFilter.class, new UpWalkGetter(new ClassFilter(PsiClass.class)))) ))); final CompletionVariant variant = new CompletionVariant(PsiMethod.class, position); variant.includeScopeClass(PsiVariable.class); variant.addCompletion(PsiKeyword.SUPER, TailType.DOT); variant.addCompletion(PsiKeyword.THIS, TailType.DOT); this.registerVariant(variant); } { // Class field completion final CompletionVariant variant = new CompletionVariant(PsiMethod.class, new LeftNeighbour( new AndFilter(new TextFilter("."), new LeftNeighbour(new OrFilter(new ElementFilter[]{ new ReferenceOnFilter(new ClassFilter(PsiClass.class)), new TextFilter(PRIMITIVE_TYPES), new TextFilter("]") }))))); variant.includeScopeClass(PsiVariable.class); variant.addCompletion(PsiKeyword.CLASS, TailType.NONE); this.registerVariant(variant); } { // break completion final CompletionVariant variant = new CompletionVariant(new AndFilter(END_OF_BLOCK, new OrFilter( new ScopeFilter(new ClassFilter(PsiSwitchStatement.class)), new InsideElementFilter(new ClassFilter(PsiBlockStatement.class))))); variant.includeScopeClass(PsiForStatement.class, false); variant.includeScopeClass(PsiForeachStatement.class, false); variant.includeScopeClass(PsiWhileStatement.class, false); variant.includeScopeClass(PsiDoWhileStatement.class, false); variant.includeScopeClass(PsiSwitchStatement.class, false); variant.addCompletion(PsiKeyword.BREAK); this.registerVariant(variant); } { // continue completion final CompletionVariant variant = new CompletionVariant(new AndFilter(END_OF_BLOCK, new InsideElementFilter(new ClassFilter(PsiBlockStatement.class)))); variant.includeScopeClass(PsiForeachStatement.class, false); variant.includeScopeClass(PsiForStatement.class, false); variant.includeScopeClass(PsiWhileStatement.class, false); variant.includeScopeClass(PsiDoWhileStatement.class, false); variant.addCompletion(PsiKeyword.CONTINUE); this.registerVariant(variant); } { final CompletionVariant variant = new CompletionVariant( new AndFilter( END_OF_BLOCK, new OrFilter( new ParentElementFilter(new ClassFilter(PsiSwitchLabelStatement.class)), new LeftNeighbour(new OrFilter( new ParentElementFilter(new ClassFilter(PsiSwitchStatement.class), 2), new AndFilter(new TextFilter(";", "}"),new ParentElementFilter(new ClassFilter(PsiSwitchStatement.class), 3) )))))); variant.includeScopeClass(PsiSwitchStatement.class, true); variant.addCompletion(PsiKeyword.CASE, TailType.SPACE); variant.addCompletion(PsiKeyword.DEFAULT, ':'); this.registerVariant(variant); } { // primitive arrays after new final CompletionVariant variant = new CompletionVariant(PsiExpression.class, new LeftNeighbour( new AndFilter(new TextFilter("new"), new LeftNeighbour(new NotFilter(new TextFilter(".", "throw"))))) ); variant.includeScopeClass(PsiNewExpression.class, true); addPrimitiveTypes(variant); variant.setItemProperty(LookupItem.BRACKETS_COUNT_ATTR, new Integer(1)); this.registerVariant(variant); } { // after new final CompletionVariant variant = new CompletionVariant(new LeftNeighbour(new TextFilter("new"))); variant.includeScopeClass(PsiNewExpression.class, true); variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class)); this.registerVariant(variant); } { final CompletionVariant variant = new CompletionVariant(new AndFilter( new ScopeFilter(new ParentElementFilter(new ClassFilter(PsiThrowStatement.class))), new ParentElementFilter(new ClassFilter(PsiNewExpression.class))) ); variant.includeScopeClass(PsiNewExpression.class, false); variant.addCompletionFilterOnElement(new ThisOrAnyInnerFilter(new InheritorFilter("java.lang.Throwable"))); this.registerVariant(variant); } { // completion in reference parameters final CompletionVariant variant = new CompletionVariant(TrueFilter.INSTANCE); variant.includeScopeClass(PsiReferenceParameterList.class, true); variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class)); this.registerVariant(variant); } { // null completion final CompletionVariant variant = new CompletionVariant(new NotFilter(new LeftNeighbour(new TextFilter(".")))); variant.addCompletion("null",TailType.NONE); variant.includeScopeClass(PsiExpressionList.class); this.registerVariant(variant); } } private void initVariantsInFieldScope() { { // completion in initializer final CompletionVariant variant = new CompletionVariant(new AfterElementFilter(new TextFilter("="))); variant.includeScopeClass(PsiVariable.class, false); variant.addCompletionFilterOnElement(new OrFilter( new ClassFilter(PsiVariable.class, false), new ExcludeDeclaredFilter(new ClassFilter(PsiVariable.class)) )); this.registerVariant(variant); } } private static void addPrimitiveTypes(CompletionVariant variant){ addPrimitiveTypes(variant, CompletionVariant.DEFAULT_TAIL_TYPE); } private static void addPrimitiveTypes(CompletionVariant variant, int tailType){ variant.addCompletion(new String[]{ PsiKeyword.SHORT, PsiKeyword.BOOLEAN, PsiKeyword.DOUBLE, PsiKeyword.LONG, PsiKeyword.INT, PsiKeyword.FLOAT, PsiKeyword.CHAR }, tailType); } private static void addKeywords(CompletionVariant variant){ variant.addCompletion(PsiKeyword.SWITCH, TailType.LPARENTH); variant.addCompletion(PsiKeyword.WHILE, TailType.LPARENTH); variant.addCompletion(PsiKeyword.FOR, TailType.LPARENTH); variant.addCompletion(PsiKeyword.TRY, '{'); variant.addCompletion(PsiKeyword.THROW, TailType.SPACE); variant.addCompletion(PsiKeyword.RETURN, TailType.SPACE); variant.addCompletion(PsiKeyword.NEW, TailType.SPACE); variant.addCompletion(PsiKeyword.ASSERT, TailType.SPACE); } static final AndFilter START_OF_CODE_FRAGMENT = new AndFilter( new ScopeFilter(new AndFilter( new ClassFilter(PsiCodeFragment.class), new ClassFilter(PsiExpressionCodeFragment.class, false) )), new StartElementFilter() ); static final ElementFilter END_OF_BLOCK = new OrFilter( new AndFilter( new LeftNeighbour(new OrFilter(new ElementFilter[]{ new TextFilter(ourBlockFinalizers), new TextFilter("*/"), new TokenTypeFilter(JspElementType.HOLDER_TEMPLATE_DATA), new AndFilter( new TextFilter(")"), new NotFilter( new OrFilter( new ParentElementFilter(new ClassFilter(PsiExpressionList.class)), new ParentElementFilter(new ClassFilter(PsiParameterList.class)) ) ) ), })), new NotFilter(new TextFilter(".")) ), START_OF_CODE_FRAGMENT ); private static final String[] PRIMITIVE_TYPES = new String[]{ PsiKeyword.SHORT, PsiKeyword.BOOLEAN, PsiKeyword.DOUBLE, PsiKeyword.LONG, PsiKeyword.INT, PsiKeyword.FLOAT, PsiKeyword.VOID, PsiKeyword.CHAR, PsiKeyword.BYTE }; private final static ElementFilter CLASS_BODY = new OrFilter( new AfterElementFilter(new TextFilter("{")), new ScopeFilter(new ClassFilter(JspClass.class))); }
source/com/intellij/codeInsight/completion/JavaCompletionData.java
package com.intellij.codeInsight.completion; import com.intellij.codeInsight.TailType; import com.intellij.codeInsight.lookup.LookupItem; import com.intellij.psi.*; import com.intellij.psi.filters.*; import com.intellij.psi.filters.classes.*; import com.intellij.psi.filters.element.ExcludeDeclaredFilter; import com.intellij.psi.filters.element.ModifierFilter; import com.intellij.psi.filters.element.ReferenceOnFilter; import com.intellij.psi.filters.getters.UpWalkGetter; import com.intellij.psi.filters.position.*; import com.intellij.psi.filters.types.TypeCodeFragmentIsVoidEnabledFilter; import com.intellij.psi.impl.source.jsp.jspJava.JspClass; import com.intellij.psi.jsp.JspElementType; public class JavaCompletionData extends CompletionData{ protected static final String[] MODIFIERS_LIST = { "public", "protected", "private", "static", "final", "native", "abstract", "synchronized", "volatile", "transient" }; private static final String[] ourBlockFinalizers = {"{", "}", ";", ":", "else"}; public JavaCompletionData(){ declareCompletionSpaces(); final CompletionVariant variant = new CompletionVariant(PsiMethod.class, TrueFilter.INSTANCE); variant.includeScopeClass(PsiVariable.class); variant.includeScopeClass(PsiClass.class); variant.includeScopeClass(PsiFile.class); variant.addCompletion(new ModifierChooser()); registerVariant(variant); initVariantsInFileScope(); initVariantsInClassScope(); initVariantsInMethodScope(); initVariantsInFieldScope(); defineScopeEquivalence(PsiMethod.class, PsiClassInitializer.class); defineScopeEquivalence(PsiMethod.class, PsiCodeFragment.class); } private void declareCompletionSpaces() { declareFinalScope(PsiFile.class); { // Class body final CompletionVariant variant = new CompletionVariant(CLASS_BODY); variant.includeScopeClass(PsiClass.class, true); this.registerVariant(variant); } { // Method body final CompletionVariant variant = new CompletionVariant(new InsideElementFilter(new ClassFilter(PsiCodeBlock.class))); variant.includeScopeClass(PsiMethod.class, true); variant.includeScopeClass(PsiClassInitializer.class, true); this.registerVariant(variant); } { // Field initializer final CompletionVariant variant = new CompletionVariant(new AfterElementFilter(new TextFilter("="))); variant.includeScopeClass(PsiField.class, true); this.registerVariant(variant); } declareFinalScope(PsiLiteralExpression.class); declareFinalScope(PsiComment.class); } protected void initVariantsInFileScope(){ // package keyword completion { final CompletionVariant variant = new CompletionVariant(PsiJavaFile.class, new StartElementFilter()); variant.addCompletion(PsiKeyword.PACKAGE); this.registerVariant(variant); } // import keyword completion { final CompletionVariant variant = new CompletionVariant(PsiJavaFile.class, new OrFilter( new StartElementFilter(), END_OF_BLOCK )); variant.addCompletion(PsiKeyword.IMPORT); this.registerVariant(variant); } // other in file scope { final ElementFilter position = new OrFilter(new ElementFilter[]{ END_OF_BLOCK, new LeftNeighbour(new OrFilter(new SuperParentFilter(new ClassFilter(PsiAnnotation.class)), new TextFilter(MODIFIERS_LIST))), new StartElementFilter() }); final CompletionVariant variant = new CompletionVariant(PsiJavaFile.class, position); variant.includeScopeClass(PsiClass.class); variant.addCompletion(PsiKeyword.CLASS); variant.addCompletion(PsiKeyword.INTERFACE); registerVariant(variant); } { final CompletionVariant variant = new CompletionVariant(PsiTypeCodeFragment.class, new StartElementFilter()); addPrimitiveTypes(variant, TailType.NONE); final CompletionVariant variant1 = new CompletionVariant(PsiTypeCodeFragment.class, new AndFilter( new StartElementFilter(), new TypeCodeFragmentIsVoidEnabledFilter() ) ); variant1.addCompletion(PsiKeyword.VOID, TailType.NONE); registerVariant(variant); registerVariant(variant1); } } /** * aClass == null for JspDeclaration scope */ protected void initVariantsInClassScope() { // Completion for extends keyword // position { final ElementFilter position = new AndFilter(new ElementFilter[]{ new NotFilter(CLASS_BODY), new NotFilter(new AfterElementFilter(new ContentFilter(new TextFilter(PsiKeyword.EXTENDS)))), new NotFilter(new AfterElementFilter(new ContentFilter(new TextFilter(PsiKeyword.IMPLEMENTS)))), new NotFilter(new LeftNeighbour(new LeftNeighbour(new TextFilter("<", ",")))), new NotFilter(new ScopeFilter(new EnumFilter())), new LeftNeighbour(new OrFilter( new ClassFilter(PsiIdentifier.class), new TextFilter(">"))), }); // completion final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiClass.class, true); variant.addCompletion(PsiKeyword.EXTENDS); variant.excludeScopeClass(PsiAnonymousClass.class); variant.excludeScopeClass(PsiTypeParameter.class); this.registerVariant(variant); } // Completion for implements keyword // position { final ElementFilter position = new AndFilter(new ElementFilter[]{ new NotFilter(CLASS_BODY), new NotFilter(new BeforeElementFilter(new ContentFilter(new TextFilter(PsiKeyword.EXTENDS)))), new NotFilter(new AfterElementFilter(new ContentFilter(new TextFilter(PsiKeyword.IMPLEMENTS)))), new NotFilter(new LeftNeighbour(new LeftNeighbour(new TextFilter("<", ",")))), new LeftNeighbour(new OrFilter( new ClassFilter(PsiIdentifier.class), new TextFilter(">"))), new NotFilter(new ScopeFilter(new InterfaceFilter())) }); // completion final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiClass.class, true); variant.addCompletion(PsiKeyword.IMPLEMENTS); variant.excludeScopeClass(PsiAnonymousClass.class); this.registerVariant(variant); } // Completion after extends in interface, type parameter and implements in class // position { final ElementFilter position = new AndFilter( new NotFilter(CLASS_BODY), new OrFilter( new ElementFilter [] { new AndFilter( new LeftNeighbour(new TextFilter(PsiKeyword.EXTENDS, ",")), new ScopeFilter(new InterfaceFilter()) ), new AndFilter( new LeftNeighbour(new TextFilter(PsiKeyword.EXTENDS, "&")), new ScopeFilter(new ClassFilter(PsiTypeParameter.class)) ), new LeftNeighbour(new TextFilter(PsiKeyword.IMPLEMENTS, ",")) } ) ); // completion final OrFilter flags = new OrFilter(); flags.addFilter(new ThisOrAnyInnerFilter( new AndFilter(new ElementFilter[]{ new ClassFilter(PsiClass.class), new NotFilter(new AssignableFromContextFilter()), new InterfaceFilter() }) )); flags.addFilter(new ClassFilter(PsiPackage.class)); CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiClass.class, true); variant.excludeScopeClass(PsiAnonymousClass.class); variant.addCompletionFilterOnElement(flags); this.registerVariant(variant); } // Completion for classes in class extends // position { final ElementFilter position = new AndFilter( new NotFilter(CLASS_BODY), new AndFilter(new ElementFilter[]{ new LeftNeighbour(new TextFilter(PsiKeyword.EXTENDS)), new ScopeFilter(new NotFilter(new InterfaceFilter())) }) ); // completion final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiClass.class, true); variant.excludeScopeClass(PsiAnonymousClass.class); variant.addCompletionFilterOnElement(new ThisOrAnyInnerFilter( new AndFilter(new ElementFilter[]{ new ClassFilter(PsiClass.class), new NotFilter(new AssignableFromContextFilter()), new NotFilter(new InterfaceFilter()), new ModifierFilter(PsiModifier.FINAL, false) }) )); variant.addCompletionFilterOnElement(new ClassFilter(PsiPackage.class)); this.registerVariant(variant); } { // declaration start // position final CompletionVariant variant = new CompletionVariant(PsiClass.class, new AndFilter( CLASS_BODY, new OrFilter( END_OF_BLOCK, new LeftNeighbour(new OrFilter( new TextFilter(MODIFIERS_LIST), new TokenTypeFilter(JavaTokenType.GT))) ))); // completion addPrimitiveTypes(variant); variant.addCompletion(PsiKeyword.VOID); variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class)); variant.addCompletionFilterOnElement(new ClassFilter(PsiPackage.class)); this.registerVariant(variant); } { final CompletionVariant variant = new CompletionVariant(new LeftNeighbour(new LeftNeighbour(new TextFilter("<", ",")))); variant.includeScopeClass(PsiClass.class, true); variant.addCompletion(PsiKeyword.EXTENDS, TailType.SPACE); this.registerVariant(variant); } } private void initVariantsInMethodScope() { { // parameters list completion final CompletionVariant variant = new CompletionVariant(new LeftNeighbour(new TextFilter(new String[]{"(", ",", "final"}))); variant.includeScopeClass(PsiParameterList.class, true); addPrimitiveTypes(variant); variant.addCompletion(PsiKeyword.FINAL); variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class)); this.registerVariant(variant); } // Completion for classes in method throws section // position { final ElementFilter position = new LeftNeighbour(new AndFilter( new TextFilter(")"), new ParentElementFilter(new ClassFilter(PsiParameterList.class)))); // completion CompletionVariant variant = new CompletionVariant(PsiMethod.class, position); variant.addCompletion(PsiKeyword.THROWS); this.registerVariant(variant); //in annotation methods variant = new CompletionVariant(PsiAnnotationMethod.class, position); variant.addCompletion(PsiKeyword.DEFAULT); this.registerVariant(variant); } { // Completion for classes in method throws section // position final ElementFilter position = new AndFilter( new LeftNeighbour(new TextFilter(PsiKeyword.THROWS, ",")), new InsideElementFilter(new ClassFilter(PsiReferenceList.class)) ); // completion final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiMethod.class, true); variant.addCompletionFilterOnElement(new ThisOrAnyInnerFilter(new InheritorFilter("java.lang.Throwable"))); variant.addCompletionFilterOnElement(new ClassFilter(PsiPackage.class)); this.registerVariant(variant); } { // completion for declarations final CompletionVariant variant = new CompletionVariant(PsiMethod.class, new OrFilter(END_OF_BLOCK, new LeftNeighbour(new TextFilter("final")))); addPrimitiveTypes(variant); variant.addCompletion(PsiKeyword.CLASS); this.registerVariant(variant); } // Completion in cast expressions { final CompletionVariant variant = new CompletionVariant(PsiMethod.class, new LeftNeighbour(new AndFilter( new TextFilter("("), new ParentElementFilter(new OrFilter( new ClassFilter(PsiParenthesizedExpression.class), new ClassFilter(PsiTypeCastExpression.class)))))); addPrimitiveTypes(variant); this.registerVariant(variant); } { // instanceof keyword final ElementFilter position = new LeftNeighbour(new OrFilter(new ElementFilter[]{ new ReferenceOnFilter(new ClassFilter(PsiVariable.class)), new TextFilter("this"), new AndFilter(new TextFilter(")"), new ParentElementFilter(new AndFilter( new ClassFilter(PsiTypeCastExpression.class, false), new OrFilter( new ParentElementFilter(new ClassFilter(PsiExpression.class)), new ClassFilter(PsiExpression.class))))), new AndFilter(new TextFilter("]"), new ParentElementFilter(new ClassFilter(PsiArrayAccessExpression.class))) })); final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiExpression.class, true); variant.includeScopeClass(PsiMethod.class); variant.addCompletionFilter(new FalseFilter()); variant.addCompletion(PsiKeyword.INSTANCEOF); this.registerVariant(variant); } { // after instanceof keyword final ElementFilter position = new PreviousElementFilter(new TextFilter(PsiKeyword.INSTANCEOF)); final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiExpression.class, true); variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class)); this.registerVariant(variant); } { // after final keyword final ElementFilter position = new AndFilter(new SuperParentFilter(new ClassFilter(PsiCodeBlock.class)), new LeftNeighbour(new TextFilter(PsiKeyword.FINAL))); final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiDeclarationStatement.class, true); variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class)); addPrimitiveTypes(variant); this.registerVariant(variant); } { // Keyword completion in start of declaration final CompletionVariant variant = new CompletionVariant(PsiMethod.class, END_OF_BLOCK); variant.addCompletion(PsiKeyword.THIS, TailType.NONE); variant.addCompletion(PsiKeyword.SUPER, TailType.NONE); addKeywords(variant); this.registerVariant(variant); } { // Keyword completion in returns final CompletionVariant variant = new CompletionVariant(PsiMethod.class, new LeftNeighbour(new TextFilter("return"))); variant.addCompletion(PsiKeyword.THIS, TailType.NONE); variant.addCompletion(PsiKeyword.SUPER, TailType.NONE); this.registerVariant(variant); } // Catch/Finnaly completion { final ElementFilter position = new LeftNeighbour(new AndFilter( new TextFilter("}"), new ParentElementFilter(new AndFilter( new LeftNeighbour(new TextFilter("try")), new ParentElementFilter(new ClassFilter(PsiTryStatement.class)))))); final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiCodeBlock.class, true); variant.addCompletion(PsiKeyword.CATCH, TailType.LPARENTH); variant.addCompletion(PsiKeyword.FINALLY, '{'); variant.addCompletionFilter(new FalseFilter()); this.registerVariant(variant); } // Catch/Finnaly completion { final ElementFilter position = new LeftNeighbour(new AndFilter( new TextFilter("}"), new ParentElementFilter(new AndFilter( new LeftNeighbour(new NotFilter(new TextFilter("try"))), new OrFilter( new ParentElementFilter(new ClassFilter(PsiTryStatement.class)), new ParentElementFilter(new ClassFilter(PsiCatchSection.class))) )))); final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiCodeBlock.class, false); variant.addCompletion(PsiKeyword.CATCH, TailType.LPARENTH); variant.addCompletion(PsiKeyword.FINALLY, '{'); //variant.addCompletionFilter(new FalseFilter()); this.registerVariant(variant); } { // Completion for catches final CompletionVariant variant = new CompletionVariant(PsiTryStatement.class, new PreviousElementFilter(new AndFilter( new ParentElementFilter(new ClassFilter(PsiTryStatement.class)), new TextFilter("(") ))); variant.includeScopeClass(PsiParameter.class); variant.addCompletionFilterOnElement(new ThisOrAnyInnerFilter(new InheritorFilter("java.lang.Throwable"))); variant.addCompletionFilterOnElement(new ClassFilter(PsiPackage.class)); this.registerVariant(variant); } // Completion for else expression // completion { final ElementFilter position = new LeftNeighbour( new OrFilter( new AndFilter(new TextFilter("}"),new ParentElementFilter(new ClassFilter(PsiIfStatement.class), 3)), new AndFilter(new TextFilter(";"),new ParentElementFilter(new ClassFilter(PsiIfStatement.class), 2)) )); final CompletionVariant variant = new CompletionVariant(PsiMethod.class, position); variant.addCompletion(PsiKeyword.ELSE); this.registerVariant(variant); } { // Super/This keyword completion final ElementFilter position = new LeftNeighbour( new AndFilter( new TextFilter("."), new LeftNeighbour( new ReferenceOnFilter(new GeneratorFilter(EqualsFilter.class, new UpWalkGetter(new ClassFilter(PsiClass.class)))) ))); final CompletionVariant variant = new CompletionVariant(PsiMethod.class, position); variant.includeScopeClass(PsiVariable.class); variant.addCompletion(PsiKeyword.SUPER, TailType.DOT); variant.addCompletion(PsiKeyword.THIS, TailType.DOT); this.registerVariant(variant); } { // Class field completion final CompletionVariant variant = new CompletionVariant(PsiMethod.class, new LeftNeighbour( new AndFilter(new TextFilter("."), new LeftNeighbour(new OrFilter(new ElementFilter[]{ new ReferenceOnFilter(new ClassFilter(PsiClass.class)), new TextFilter(PRIMITIVE_TYPES), new TextFilter("]") }))))); variant.includeScopeClass(PsiVariable.class); variant.addCompletion(PsiKeyword.CLASS, TailType.NONE); this.registerVariant(variant); } { // break completion final CompletionVariant variant = new CompletionVariant(new AndFilter(END_OF_BLOCK, new OrFilter( new ScopeFilter(new ClassFilter(PsiSwitchStatement.class)), new InsideElementFilter(new ClassFilter(PsiBlockStatement.class))))); variant.includeScopeClass(PsiForStatement.class, false); variant.includeScopeClass(PsiForeachStatement.class, false); variant.includeScopeClass(PsiWhileStatement.class, false); variant.includeScopeClass(PsiDoWhileStatement.class, false); variant.includeScopeClass(PsiSwitchStatement.class, false); variant.addCompletion(PsiKeyword.BREAK); this.registerVariant(variant); } { // continue completion final CompletionVariant variant = new CompletionVariant(new AndFilter(END_OF_BLOCK, new InsideElementFilter(new ClassFilter(PsiBlockStatement.class)))); variant.includeScopeClass(PsiForeachStatement.class, false); variant.includeScopeClass(PsiForStatement.class, false); variant.includeScopeClass(PsiWhileStatement.class, false); variant.includeScopeClass(PsiDoWhileStatement.class, false); variant.addCompletion(PsiKeyword.CONTINUE); this.registerVariant(variant); } { final CompletionVariant variant = new CompletionVariant( new AndFilter( END_OF_BLOCK, new OrFilter( new ParentElementFilter(new ClassFilter(PsiSwitchLabelStatement.class)), new LeftNeighbour(new OrFilter( new ParentElementFilter(new ClassFilter(PsiSwitchStatement.class), 2), new AndFilter(new TextFilter(";", "}"),new ParentElementFilter(new ClassFilter(PsiSwitchStatement.class), 3) )))))); variant.includeScopeClass(PsiSwitchStatement.class, true); variant.addCompletion(PsiKeyword.CASE, TailType.SPACE); variant.addCompletion(PsiKeyword.DEFAULT, ':'); this.registerVariant(variant); } { // primitive arrays after new final CompletionVariant variant = new CompletionVariant(PsiExpression.class, new LeftNeighbour( new AndFilter(new TextFilter("new"), new LeftNeighbour(new NotFilter(new TextFilter(".", "throw"))))) ); variant.includeScopeClass(PsiNewExpression.class, true); addPrimitiveTypes(variant); variant.setItemProperty(LookupItem.BRACKETS_COUNT_ATTR, new Integer(1)); this.registerVariant(variant); } { // after new final CompletionVariant variant = new CompletionVariant(new LeftNeighbour(new TextFilter("new"))); variant.includeScopeClass(PsiNewExpression.class, true); variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class)); this.registerVariant(variant); } { final CompletionVariant variant = new CompletionVariant(new AndFilter( new ScopeFilter(new ParentElementFilter(new ClassFilter(PsiThrowStatement.class))), new ParentElementFilter(new ClassFilter(PsiNewExpression.class))) ); variant.includeScopeClass(PsiNewExpression.class, false); variant.addCompletionFilterOnElement(new ThisOrAnyInnerFilter(new InheritorFilter("java.lang.Throwable"))); this.registerVariant(variant); } { // completion in reference parameters final CompletionVariant variant = new CompletionVariant(TrueFilter.INSTANCE); variant.includeScopeClass(PsiReferenceParameterList.class, true); variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class)); this.registerVariant(variant); } { // null completion final CompletionVariant variant = new CompletionVariant(new NotFilter(new LeftNeighbour(new TextFilter(".")))); variant.addCompletion("null",TailType.NONE); variant.includeScopeClass(PsiExpressionList.class); this.registerVariant(variant); } } private void initVariantsInFieldScope() { { // completion in initializer final CompletionVariant variant = new CompletionVariant(new AfterElementFilter(new TextFilter("="))); variant.includeScopeClass(PsiVariable.class, false); variant.addCompletionFilterOnElement(new OrFilter( new ClassFilter(PsiVariable.class, false), new ExcludeDeclaredFilter(new ClassFilter(PsiVariable.class)) )); this.registerVariant(variant); } } private static void addPrimitiveTypes(CompletionVariant variant){ addPrimitiveTypes(variant, CompletionVariant.DEFAULT_TAIL_TYPE); } private static void addPrimitiveTypes(CompletionVariant variant, int tailType){ variant.addCompletion(new String[]{ PsiKeyword.SHORT, PsiKeyword.BOOLEAN, PsiKeyword.DOUBLE, PsiKeyword.LONG, PsiKeyword.INT, PsiKeyword.FLOAT, PsiKeyword.CHAR }, tailType); } private static void addKeywords(CompletionVariant variant){ variant.addCompletion(PsiKeyword.SWITCH, TailType.LPARENTH); variant.addCompletion(PsiKeyword.WHILE, TailType.LPARENTH); variant.addCompletion(PsiKeyword.FOR, TailType.LPARENTH); variant.addCompletion(PsiKeyword.TRY, '{'); variant.addCompletion(PsiKeyword.THROW, TailType.SPACE); variant.addCompletion(PsiKeyword.RETURN, TailType.SPACE); variant.addCompletion(PsiKeyword.NEW, TailType.SPACE); variant.addCompletion(PsiKeyword.ASSERT, TailType.SPACE); } static final AndFilter START_OF_CODE_FRAGMENT = new AndFilter( new ScopeFilter(new AndFilter( new ClassFilter(PsiCodeFragment.class), new ClassFilter(PsiExpressionCodeFragment.class, false) )), new StartElementFilter() ); static final ElementFilter END_OF_BLOCK = new OrFilter( new AndFilter( new LeftNeighbour(new OrFilter(new ElementFilter[]{ new TextFilter(ourBlockFinalizers), new TextFilter("*/"), new TokenTypeFilter(JspElementType.HOLDER_TEMPLATE_DATA), new AndFilter( new TextFilter(")"), new NotFilter( new OrFilter( new ParentElementFilter(new ClassFilter(PsiExpressionList.class)), new ParentElementFilter(new ClassFilter(PsiParameterList.class)) ) ) ), })), new NotFilter(new TextFilter(".")) ), START_OF_CODE_FRAGMENT ); private static final String[] PRIMITIVE_TYPES = new String[]{ PsiKeyword.SHORT, PsiKeyword.BOOLEAN, PsiKeyword.DOUBLE, PsiKeyword.LONG, PsiKeyword.INT, PsiKeyword.FLOAT, PsiKeyword.VOID, PsiKeyword.CHAR, PsiKeyword.BYTE }; private final static ElementFilter CLASS_BODY = new OrFilter( new AfterElementFilter(new TextFilter("{")), new ScopeFilter(new ClassFilter(JspClass.class))); }
Completion after annotations
source/com/intellij/codeInsight/completion/JavaCompletionData.java
Completion after annotations
<ide><path>ource/com/intellij/codeInsight/completion/JavaCompletionData.java <ide> END_OF_BLOCK, <ide> new LeftNeighbour(new OrFilter( <ide> new TextFilter(MODIFIERS_LIST), <add> new SuperParentFilter(new ClassFilter(PsiAnnotation.class)), <ide> new TokenTypeFilter(JavaTokenType.GT))) <ide> ))); <ide> <ide> private void initVariantsInMethodScope() { <ide> { <ide> // parameters list completion <del> final CompletionVariant variant = new CompletionVariant(new LeftNeighbour(new TextFilter(new String[]{"(", ",", "final"}))); <add> final CompletionVariant variant = new CompletionVariant( <add> new LeftNeighbour(new OrFilter(new TextFilter(new String[]{"(", ",", "final"}), <add> new SuperParentFilter(new ClassFilter(PsiAnnotation.class))))); <ide> variant.includeScopeClass(PsiParameterList.class, true); <ide> addPrimitiveTypes(variant); <ide> variant.addCompletion(PsiKeyword.FINAL);
Java
apache-2.0
0f991bd565679adb310a1e0718a18882523f2ac5
0
quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus
package io.quarkus.kubernetes.deployment; import static io.quarkus.kubernetes.deployment.Constants.DEFAULT_S2I_IMAGE_NAME; import static io.quarkus.kubernetes.deployment.Constants.DEPLOY; import static io.quarkus.kubernetes.deployment.Constants.DEPLOYMENT; import static io.quarkus.kubernetes.deployment.Constants.DEPLOYMENT_CONFIG; import static io.quarkus.kubernetes.deployment.Constants.KNATIVE; import static io.quarkus.kubernetes.deployment.Constants.KUBERNETES; import static io.quarkus.kubernetes.deployment.Constants.OPENSHIFT; import static io.quarkus.kubernetes.deployment.Constants.OPENSHIFT_APP_RUNTIME; import static io.quarkus.kubernetes.deployment.Constants.QUARKUS; import static io.quarkus.kubernetes.deployment.Constants.QUARKUS_ANNOTATIONS_BUILD_TIMESTAMP; import static io.quarkus.kubernetes.deployment.Constants.QUARKUS_ANNOTATIONS_COMMIT_ID; import static io.quarkus.kubernetes.deployment.Constants.QUARKUS_ANNOTATIONS_VCS_URL; import static io.quarkus.kubernetes.deployment.Constants.SERVICE; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.jboss.logging.Logger; import io.dekorate.Session; import io.dekorate.SessionWriter; import io.dekorate.kubernetes.config.Annotation; import io.dekorate.kubernetes.config.Label; import io.dekorate.kubernetes.config.PortBuilder; import io.dekorate.kubernetes.config.ProbeBuilder; import io.dekorate.kubernetes.configurator.AddPort; import io.dekorate.kubernetes.decorator.AddAnnotationDecorator; import io.dekorate.kubernetes.decorator.AddAwsElasticBlockStoreVolumeDecorator; import io.dekorate.kubernetes.decorator.AddAzureDiskVolumeDecorator; import io.dekorate.kubernetes.decorator.AddAzureFileVolumeDecorator; import io.dekorate.kubernetes.decorator.AddConfigMapVolumeDecorator; import io.dekorate.kubernetes.decorator.AddEnvVarDecorator; import io.dekorate.kubernetes.decorator.AddImagePullSecretDecorator; import io.dekorate.kubernetes.decorator.AddInitContainerDecorator; import io.dekorate.kubernetes.decorator.AddLabelDecorator; import io.dekorate.kubernetes.decorator.AddLivenessProbeDecorator; import io.dekorate.kubernetes.decorator.AddMountDecorator; import io.dekorate.kubernetes.decorator.AddPvcVolumeDecorator; import io.dekorate.kubernetes.decorator.AddReadinessProbeDecorator; import io.dekorate.kubernetes.decorator.AddRoleBindingResourceDecorator; import io.dekorate.kubernetes.decorator.AddSecretVolumeDecorator; import io.dekorate.kubernetes.decorator.AddServiceAccountResourceDecorator; import io.dekorate.kubernetes.decorator.AddSidecarDecorator; import io.dekorate.kubernetes.decorator.ApplyArgsDecorator; import io.dekorate.kubernetes.decorator.ApplyCommandDecorator; import io.dekorate.kubernetes.decorator.ApplyImagePullPolicyDecorator; import io.dekorate.kubernetes.decorator.ApplyServiceAccountNamedDecorator; import io.dekorate.kubernetes.decorator.ApplyWorkingDirDecorator; import io.dekorate.kubernetes.decorator.RemoveAnnotationDecorator; import io.dekorate.processor.SimpleFileWriter; import io.dekorate.project.BuildInfo; import io.dekorate.project.FileProjectFactory; import io.dekorate.project.Project; import io.dekorate.project.ScmInfo; import io.dekorate.s2i.config.S2iBuildConfig; import io.dekorate.s2i.config.S2iBuildConfigBuilder; import io.dekorate.s2i.decorator.AddBuilderImageStreamResourceDecorator; import io.dekorate.utils.Annotations; import io.dekorate.utils.Maps; import io.quarkus.container.image.deployment.util.ImageUtil; import io.quarkus.container.spi.BaseImageInfoBuildItem; import io.quarkus.container.spi.ContainerImageInfoBuildItem; import io.quarkus.deployment.IsNormal; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.builditem.ApplicationInfoBuildItem; import io.quarkus.deployment.builditem.ArchiveRootBuildItem; import io.quarkus.deployment.builditem.FeatureBuildItem; import io.quarkus.deployment.builditem.GeneratedFileSystemResourceBuildItem; import io.quarkus.deployment.pkg.PackageConfig; import io.quarkus.deployment.pkg.builditem.OutputTargetBuildItem; import io.quarkus.deployment.util.FileUtil; import io.quarkus.kubernetes.spi.KubernetesCommandBuildItem; import io.quarkus.kubernetes.spi.KubernetesDeploymentTargetBuildItem; import io.quarkus.kubernetes.spi.KubernetesHealthLivenessPathBuildItem; import io.quarkus.kubernetes.spi.KubernetesHealthReadinessPathBuildItem; import io.quarkus.kubernetes.spi.KubernetesPortBuildItem; import io.quarkus.kubernetes.spi.KubernetesRoleBuildItem; class KubernetesProcessor { private static final Logger log = Logger.getLogger(KubernetesDeployer.class); private static final String OUTPUT_ARTIFACT_FORMAT = "%s%s.jar"; @BuildStep public void checkKubernetes(BuildProducer<KubernetesDeploymentTargetBuildItem> deploymentTargets) { if (KubernetesConfigUtil.getDeploymentTargets().contains(KUBERNETES)) { deploymentTargets.produce(new KubernetesDeploymentTargetBuildItem(KUBERNETES, DEPLOYMENT)); } } @BuildStep public void checkOpenshift(BuildProducer<KubernetesDeploymentTargetBuildItem> deploymentTargets) { if (KubernetesConfigUtil.getDeploymentTargets().contains(OPENSHIFT)) { deploymentTargets.produce(new KubernetesDeploymentTargetBuildItem(OPENSHIFT, DEPLOYMENT_CONFIG)); } } @BuildStep public void checkKnative(BuildProducer<KubernetesDeploymentTargetBuildItem> deploymentTargets) { if (KubernetesConfigUtil.getDeploymentTargets().contains(KNATIVE)) { deploymentTargets.produce(new KubernetesDeploymentTargetBuildItem(KNATIVE, SERVICE)); } } @BuildStep(onlyIf = IsNormal.class) public void build(ApplicationInfoBuildItem applicationInfo, ArchiveRootBuildItem archiveRootBuildItem, OutputTargetBuildItem outputTargetBuildItem, PackageConfig packageConfig, KubernetesConfig kubernetesConfig, OpenshiftConfig openshiftConfig, KnativeConfig knativeConfig, List<KubernetesRoleBuildItem> kubernetesRoleBuildItems, List<KubernetesPortBuildItem> kubernetesPortBuildItems, List<KubernetesDeploymentTargetBuildItem> kubernetesDeploymentTargetBuildItems, Optional<BaseImageInfoBuildItem> baseImageBuildItem, Optional<ContainerImageInfoBuildItem> containerImageBuildItem, Optional<KubernetesCommandBuildItem> commandBuildItem, Optional<KubernetesHealthLivenessPathBuildItem> kubernetesHealthLivenessPathBuildItem, Optional<KubernetesHealthReadinessPathBuildItem> kubernetesHealthReadinessPathBuildItem, BuildProducer<GeneratedFileSystemResourceBuildItem> generatedResourceProducer) { if (kubernetesPortBuildItems.isEmpty()) { log.debug("The service is not an HTTP service so no Kubernetes manifests will be generated"); return; } final Path root; try { root = Files.createTempDirectory("quarkus-kubernetes"); } catch (IOException e) { throw new RuntimeException("Unable to setup environment for generating Kubernetes resources", e); } Map<String, Object> config = KubernetesConfigUtil.toMap(kubernetesConfig, openshiftConfig, knativeConfig); Set<String> deploymentTargets = kubernetesDeploymentTargetBuildItems.stream() .map(KubernetesDeploymentTargetBuildItem::getName) .collect(Collectors.toSet()); Path artifactPath = archiveRootBuildItem.getArchiveRoot().resolve( String.format(OUTPUT_ARTIFACT_FORMAT, outputTargetBuildItem.getBaseName(), packageConfig.runnerSuffix)); final Map<String, String> generatedResourcesMap; // by passing false to SimpleFileWriter, we ensure that no files are actually written during this phase final SessionWriter sessionWriter = new SimpleFileWriter(root, false); Project project = createProject(applicationInfo, artifactPath); sessionWriter.setProject(project); final Session session = Session.getSession(); session.setWriter(sessionWriter); session.feed(Maps.fromProperties(config)); //Apply configuration applyGlobalConfig(session, kubernetesConfig); ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); applyConfig(session, project, KUBERNETES, kubernetesConfig.name.orElse(applicationInfo.getName()), kubernetesConfig, now); applyConfig(session, project, OPENSHIFT, openshiftConfig.name.orElse(applicationInfo.getName()), openshiftConfig, now); applyConfig(session, project, KNATIVE, knativeConfig.name.orElse(applicationInfo.getName()), knativeConfig, now); //apply build item configurations to the dekorate session. applyBuildItems(session, applicationInfo.getName(), kubernetesConfig, openshiftConfig, knativeConfig, deploymentTargets, kubernetesRoleBuildItems, kubernetesPortBuildItems, baseImageBuildItem, containerImageBuildItem, commandBuildItem, kubernetesHealthLivenessPathBuildItem, kubernetesHealthReadinessPathBuildItem); // write the generated resources to the filesystem generatedResourcesMap = session.close(); for (Map.Entry<String, String> resourceEntry : generatedResourcesMap.entrySet()) { String fileName = resourceEntry.getKey().replace(root.toAbsolutePath().toString(), ""); String relativePath = resourceEntry.getKey().replace(root.toAbsolutePath().toString(), KUBERNETES); if (fileName.endsWith(".yml") || fileName.endsWith(".json")) { String target = fileName.substring(0, fileName.lastIndexOf(".")); if (target.startsWith(File.separator)) { target = target.substring(1); } if (!deploymentTargets.contains(target)) { continue; } } generatedResourceProducer.produce( new GeneratedFileSystemResourceBuildItem( // we need to make sure we are only passing the relative path to the build item relativePath, resourceEntry.getValue().getBytes(StandardCharsets.UTF_8))); } try { if (root != null && root.toFile().exists()) { FileUtil.deleteDirectory(root); } } catch (IOException e) { log.debug("Unable to delete temporary directory " + root, e); } } @BuildStep FeatureBuildItem produceFeature() { return new FeatureBuildItem(FeatureBuildItem.KUBERNETES); } /** * Apply global changes * * @param session The session to apply the changes * @param config The {@link KubernetesConfig} instance */ private void applyGlobalConfig(Session session, KubernetesConfig config) { //Ports config.ports.entrySet().forEach(e -> session.configurators().add(new AddPort(PortConverter.convert(e)))); } /** * Apply changes to the target resource group * * @param session The session to apply the changes * @param target The deployment target (e.g. kubernetes, openshift, knative) * @param name The name of the resource to accept the configuration * @param config The {@link PlatformConfiguration} instance * @param now */ private void applyConfig(Session session, Project project, String target, String name, PlatformConfiguration config, ZonedDateTime now) { //Labels config.getLabels().forEach((key, value) -> { session.resources().decorate(target, new AddLabelDecorator(new Label(key, value))); }); if (OPENSHIFT.equals(target)) { session.resources().decorate(OPENSHIFT, new AddLabelDecorator(new Label(OPENSHIFT_APP_RUNTIME, QUARKUS))); } //Annotations config.getAnnotations().forEach((key, value) -> { session.resources().decorate(target, new AddAnnotationDecorator(new Annotation(key, value))); }); ScmInfo scm = project.getScmInfo(); String vcsUrl = scm != null ? scm.getUrl() : Annotations.UNKNOWN; String commitId = scm != null ? scm.getCommit() : Annotations.UNKNOWN; //Dekorate uses its own annotations. Let's replace them with the quarkus ones. session.resources().decorate(target, new RemoveAnnotationDecorator(Annotations.VCS_URL)); session.resources().decorate(target, new RemoveAnnotationDecorator(Annotations.COMMIT_ID)); //Add quarkus vcs annotations session.resources().decorate(target, new AddAnnotationDecorator(new Annotation(QUARKUS_ANNOTATIONS_COMMIT_ID, commitId))); session.resources().decorate(target, new AddAnnotationDecorator(new Annotation(QUARKUS_ANNOTATIONS_VCS_URL, vcsUrl))); if (config.isAddBuildTimestamp()) { session.resources().decorate(target, new AddAnnotationDecorator(new Annotation(QUARKUS_ANNOTATIONS_BUILD_TIMESTAMP, now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd - HH:mm:ss Z"))))); } //EnvVars config.getEnvVars().entrySet().forEach(e -> { session.resources().decorate(target, new AddEnvVarDecorator(EnvConverter.convert(e))); }); config.getWorkingDir().ifPresent(w -> { session.resources().decorate(target, new ApplyWorkingDirDecorator(name, w)); }); config.getCommand().ifPresent(c -> { session.resources().decorate(target, new ApplyCommandDecorator(name, c.toArray(new String[c.size()]))); }); config.getArguments().ifPresent(a -> { session.resources().decorate(target, new ApplyArgsDecorator(name, a.toArray(new String[a.size()]))); }); config.getServiceAccount().ifPresent(s -> { session.resources().decorate(target, new ApplyServiceAccountNamedDecorator(name, s)); }); //Image Pull session.resources().decorate(new ApplyImagePullPolicyDecorator(config.getImagePullPolicy())); config.getImagePullSecrets().ifPresent(l -> { l.forEach(s -> session.resources().decorate(target, new AddImagePullSecretDecorator(name, s))); }); //Probes config.getLivenessProbe().ifPresent(p -> { session.resources().decorate(target, new AddLivenessProbeDecorator(name, ProbeConverter.convert(p))); }); config.getReadinessProbe().ifPresent(p -> { session.resources().decorate(target, new AddReadinessProbeDecorator(name, ProbeConverter.convert(p))); }); // Mounts and Volumes config.getMounts().entrySet().forEach(e -> { session.resources().decorate(target, new AddMountDecorator(MountConverter.convert(e))); }); config.getSecretVolumes().entrySet().forEach(e -> { session.resources().decorate(target, new AddSecretVolumeDecorator(SecretVolumeConverter.convert(e))); }); config.getConfigMapVolumes().entrySet().forEach(e -> { session.resources().decorate(target, new AddConfigMapVolumeDecorator(ConfigMapVolumeConverter.convert(e))); }); config.getPvcVolumes().entrySet().forEach(e -> { session.resources().decorate(target, new AddPvcVolumeDecorator(PvcVolumeConverter.convert(e))); }); config.getAwsElasticBlockStoreVolumes().entrySet().forEach(e -> { session.resources().decorate(target, new AddAwsElasticBlockStoreVolumeDecorator(AwsElasticBlockStoreVolumeConverter.convert(e))); }); config.getAzureFileVolumes().entrySet().forEach(e -> { session.resources().decorate(target, new AddAzureFileVolumeDecorator(AzureFileVolumeConverter.convert(e))); }); config.getAzureDiskVolumes().entrySet().forEach(e -> { session.resources().decorate(target, new AddAzureDiskVolumeDecorator(AzureDiskVolumeConverter.convert(e))); }); config.getInitContainers().entrySet().forEach(e -> { session.resources().decorate(target, new AddInitContainerDecorator(name, ContainerConverter.convert(e))); }); config.getContainers().entrySet().forEach(e -> { session.resources().decorate(target, new AddSidecarDecorator(name, ContainerConverter.convert(e))); }); } private void applyBuildItems(Session session, String name, KubernetesConfig kubernetesConfig, OpenshiftConfig openshiftConfig, KnativeConfig knativeConfig, Set<String> deploymentTargets, List<KubernetesRoleBuildItem> kubernetesRoleBuildItems, List<KubernetesPortBuildItem> kubernetesPortBuildItems, Optional<BaseImageInfoBuildItem> baseImageBuildItem, Optional<ContainerImageInfoBuildItem> containerImageBuildItem, Optional<KubernetesCommandBuildItem> commandBuildItem, Optional<KubernetesHealthLivenessPathBuildItem> kubernetesHealthLivenessPathBuildItem, Optional<KubernetesHealthReadinessPathBuildItem> kubernetesHealthReadinessPathBuildItem) { String kubernetesName = kubernetesConfig.name.orElse(name); String openshiftName = openshiftConfig.name.orElse(name); String knativeName = knativeConfig.name.orElse(name); session.resources().decorate(KNATIVE, new AddMissingContainerNameDecorator(knativeName, knativeName)); containerImageBuildItem.ifPresent(c -> { session.resources().decorate(OPENSHIFT, new ApplyContainerImageDecorator(openshiftName, c.getImage())); session.resources().decorate(KUBERNETES, new ApplyContainerImageDecorator(kubernetesName, c.getImage())); session.resources().decorate(KNATIVE, new ApplyContainerImageDecorator(knativeName, c.getImage())); }); //Handle Command and arguments commandBuildItem.ifPresent(c -> { session.resources() .decorate(new ApplyCommandDecorator(kubernetesName, new String[] { c.getCommand() })); session.resources().decorate(KUBERNETES, new ApplyArgsDecorator(kubernetesName, c.getArgs())); session.resources() .decorate(new ApplyCommandDecorator(openshiftName, new String[] { c.getCommand() })); session.resources().decorate(OPENSHIFT, new ApplyArgsDecorator(openshiftName, c.getArgs())); session.resources() .decorate(new ApplyCommandDecorator(knativeName, new String[] { c.getCommand() })); session.resources().decorate(KNATIVE, new ApplyArgsDecorator(knativeName, c.getArgs())); }); //Handle ports final Map<String, Integer> ports = verifyPorts(kubernetesPortBuildItems); ports.entrySet().stream() .map(e -> new PortBuilder().withName(e.getKey()).withContainerPort(e.getValue()).build()) .forEach(p -> session.configurators().add(new AddPort(p))); //Handle RBAC if (!kubernetesPortBuildItems.isEmpty()) { session.resources().decorate(new ApplyServiceAccountNamedDecorator()); session.resources().decorate(new AddServiceAccountResourceDecorator()); kubernetesRoleBuildItems .forEach(r -> session.resources().decorate(new AddRoleBindingResourceDecorator(r.getRole()))); } //Handle custom s2i builder images if (deploymentTargets.contains(OPENSHIFT)) { baseImageBuildItem.map(BaseImageInfoBuildItem::getImage).ifPresent(builderImage -> { String builderImageName = ImageUtil.getName(builderImage); S2iBuildConfig s2iBuildConfig = new S2iBuildConfigBuilder().withBuilderImage(builderImage).build(); if (!DEFAULT_S2I_IMAGE_NAME.equals(builderImageName)) { session.resources().decorate(OPENSHIFT, new RemoveBuilderImageResourceDecorator(DEFAULT_S2I_IMAGE_NAME)); } session.resources().decorate(OPENSHIFT, new AddBuilderImageStreamResourceDecorator(s2iBuildConfig)); session.resources().decorate(OPENSHIFT, new ApplyBuilderImageDecorator(openshiftName, builderImage)); }); } //Handle probes kubernetesHealthLivenessPathBuildItem .ifPresent(l -> session.resources() .decorate(new AddLivenessProbeDecorator(name, new ProbeBuilder() .withHttpActionPath(l.getPath()) .build()))); kubernetesHealthReadinessPathBuildItem .ifPresent(r -> session.resources() .decorate(new AddReadinessProbeDecorator(name, new ProbeBuilder() .withHttpActionPath(r.getPath()) .build()))); } private Map<String, Integer> verifyPorts(List<KubernetesPortBuildItem> kubernetesPortBuildItems) { final Map<String, Integer> result = new HashMap<>(); final Set<Integer> usedPorts = new HashSet<>(); for (KubernetesPortBuildItem entry : kubernetesPortBuildItems) { final String name = entry.getName(); if (result.containsKey(name)) { throw new IllegalArgumentException( "All Kubernetes ports must have unique names - " + name + "has been used multiple times"); } final Integer port = entry.getPort(); if (usedPorts.contains(port)) { throw new IllegalArgumentException( "All Kubernetes ports must be unique - " + port + "has been used multiple times"); } result.put(name, port); usedPorts.add(port); } return result; } private Project createProject(ApplicationInfoBuildItem app, Path artifactPath) { //Let dekorate create a Project instance and then override with what is found in ApplicationInfoBuildItem. Project project = FileProjectFactory.create(artifactPath.toFile()); BuildInfo buildInfo = new BuildInfo(app.getName(), app.getVersion(), "jar", project.getBuildInfo().getBuildTool(), artifactPath, project.getBuildInfo().getOutputFile(), project.getBuildInfo().getClassOutputDir()); return new Project(project.getRoot(), buildInfo, project.getScmInfo()); } }
extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/KubernetesProcessor.java
package io.quarkus.kubernetes.deployment; import static io.quarkus.kubernetes.deployment.Constants.DEFAULT_S2I_IMAGE_NAME; import static io.quarkus.kubernetes.deployment.Constants.DEPLOY; import static io.quarkus.kubernetes.deployment.Constants.DEPLOYMENT; import static io.quarkus.kubernetes.deployment.Constants.DEPLOYMENT_CONFIG; import static io.quarkus.kubernetes.deployment.Constants.KNATIVE; import static io.quarkus.kubernetes.deployment.Constants.KUBERNETES; import static io.quarkus.kubernetes.deployment.Constants.OPENSHIFT; import static io.quarkus.kubernetes.deployment.Constants.OPENSHIFT_APP_RUNTIME; import static io.quarkus.kubernetes.deployment.Constants.QUARKUS; import static io.quarkus.kubernetes.deployment.Constants.QUARKUS_ANNOTATIONS_BUILD_TIMESTAMP; import static io.quarkus.kubernetes.deployment.Constants.QUARKUS_ANNOTATIONS_COMMIT_ID; import static io.quarkus.kubernetes.deployment.Constants.QUARKUS_ANNOTATIONS_VCS_URL; import static io.quarkus.kubernetes.deployment.Constants.SERVICE; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.jboss.logging.Logger; import io.dekorate.Session; import io.dekorate.SessionWriter; import io.dekorate.kubernetes.config.Annotation; import io.dekorate.kubernetes.config.Label; import io.dekorate.kubernetes.config.PortBuilder; import io.dekorate.kubernetes.config.ProbeBuilder; import io.dekorate.kubernetes.configurator.AddPort; import io.dekorate.kubernetes.decorator.AddAnnotationDecorator; import io.dekorate.kubernetes.decorator.AddAwsElasticBlockStoreVolumeDecorator; import io.dekorate.kubernetes.decorator.AddAzureDiskVolumeDecorator; import io.dekorate.kubernetes.decorator.AddAzureFileVolumeDecorator; import io.dekorate.kubernetes.decorator.AddConfigMapVolumeDecorator; import io.dekorate.kubernetes.decorator.AddEnvVarDecorator; import io.dekorate.kubernetes.decorator.AddImagePullSecretDecorator; import io.dekorate.kubernetes.decorator.AddInitContainerDecorator; import io.dekorate.kubernetes.decorator.AddLabelDecorator; import io.dekorate.kubernetes.decorator.AddLivenessProbeDecorator; import io.dekorate.kubernetes.decorator.AddMountDecorator; import io.dekorate.kubernetes.decorator.AddPvcVolumeDecorator; import io.dekorate.kubernetes.decorator.AddReadinessProbeDecorator; import io.dekorate.kubernetes.decorator.AddRoleBindingResourceDecorator; import io.dekorate.kubernetes.decorator.AddSecretVolumeDecorator; import io.dekorate.kubernetes.decorator.AddServiceAccountResourceDecorator; import io.dekorate.kubernetes.decorator.AddSidecarDecorator; import io.dekorate.kubernetes.decorator.ApplyArgsDecorator; import io.dekorate.kubernetes.decorator.ApplyCommandDecorator; import io.dekorate.kubernetes.decorator.ApplyImagePullPolicyDecorator; import io.dekorate.kubernetes.decorator.ApplyServiceAccountNamedDecorator; import io.dekorate.kubernetes.decorator.ApplyWorkingDirDecorator; import io.dekorate.kubernetes.decorator.RemoveAnnotationDecorator; import io.dekorate.processor.SimpleFileWriter; import io.dekorate.project.BuildInfo; import io.dekorate.project.FileProjectFactory; import io.dekorate.project.Project; import io.dekorate.project.ScmInfo; import io.dekorate.s2i.config.S2iBuildConfig; import io.dekorate.s2i.config.S2iBuildConfigBuilder; import io.dekorate.s2i.decorator.AddBuilderImageStreamResourceDecorator; import io.dekorate.utils.Annotations; import io.dekorate.utils.Maps; import io.quarkus.container.image.deployment.util.ImageUtil; import io.quarkus.container.spi.BaseImageInfoBuildItem; import io.quarkus.container.spi.ContainerImageInfoBuildItem; import io.quarkus.deployment.IsNormal; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.builditem.ApplicationInfoBuildItem; import io.quarkus.deployment.builditem.ArchiveRootBuildItem; import io.quarkus.deployment.builditem.FeatureBuildItem; import io.quarkus.deployment.builditem.GeneratedFileSystemResourceBuildItem; import io.quarkus.deployment.pkg.PackageConfig; import io.quarkus.deployment.pkg.builditem.OutputTargetBuildItem; import io.quarkus.deployment.util.FileUtil; import io.quarkus.kubernetes.spi.KubernetesCommandBuildItem; import io.quarkus.kubernetes.spi.KubernetesDeploymentTargetBuildItem; import io.quarkus.kubernetes.spi.KubernetesHealthLivenessPathBuildItem; import io.quarkus.kubernetes.spi.KubernetesHealthReadinessPathBuildItem; import io.quarkus.kubernetes.spi.KubernetesPortBuildItem; import io.quarkus.kubernetes.spi.KubernetesRoleBuildItem; class KubernetesProcessor { private static final Logger log = Logger.getLogger(KubernetesDeployer.class); private static final String OUTPUT_ARTIFACT_FORMAT = "%s%s.jar"; @BuildStep public void checkKubernetes(BuildProducer<KubernetesDeploymentTargetBuildItem> deploymentTargets) { if (KubernetesConfigUtil.getDeploymentTargets().contains(KUBERNETES)) { deploymentTargets.produce(new KubernetesDeploymentTargetBuildItem(KUBERNETES, DEPLOYMENT)); } } @BuildStep public void checkOpenshift(BuildProducer<KubernetesDeploymentTargetBuildItem> deploymentTargets) { if (KubernetesConfigUtil.getDeploymentTargets().contains(OPENSHIFT)) { deploymentTargets.produce(new KubernetesDeploymentTargetBuildItem(OPENSHIFT, DEPLOYMENT_CONFIG)); } } @BuildStep public void checkKnative(BuildProducer<KubernetesDeploymentTargetBuildItem> deploymentTargets) { if (KubernetesConfigUtil.getDeploymentTargets().contains(KNATIVE)) { deploymentTargets.produce(new KubernetesDeploymentTargetBuildItem(KNATIVE, SERVICE)); } } @BuildStep(onlyIf = IsNormal.class) public void build(ApplicationInfoBuildItem applicationInfo, ArchiveRootBuildItem archiveRootBuildItem, OutputTargetBuildItem outputTargetBuildItem, PackageConfig packageConfig, KubernetesConfig kubernetesConfig, OpenshiftConfig openshiftConfig, KnativeConfig knativeConfig, List<KubernetesRoleBuildItem> kubernetesRoleBuildItems, List<KubernetesPortBuildItem> kubernetesPortBuildItems, List<KubernetesDeploymentTargetBuildItem> kubernetesDeploymentTargetBuildItems, Optional<BaseImageInfoBuildItem> baseImageBuildItem, Optional<ContainerImageInfoBuildItem> containerImageBuildItem, Optional<KubernetesCommandBuildItem> commandBuildItem, Optional<KubernetesHealthLivenessPathBuildItem> kubernetesHealthLivenessPathBuildItem, Optional<KubernetesHealthReadinessPathBuildItem> kubernetesHealthReadinessPathBuildItem, BuildProducer<GeneratedFileSystemResourceBuildItem> generatedResourceProducer) { if (kubernetesPortBuildItems.isEmpty()) { log.debug("The service is not an HTTP service so no Kubernetes manifests will be generated"); return; } final Path root; try { root = Files.createTempDirectory("quarkus-kubernetes"); } catch (IOException e) { throw new RuntimeException("Unable to setup environment for generating Kubernetes resources", e); } Map<String, Object> config = KubernetesConfigUtil.toMap(kubernetesConfig, openshiftConfig, knativeConfig); Set<String> deploymentTargets = kubernetesDeploymentTargetBuildItems.stream() .map(KubernetesDeploymentTargetBuildItem::getName) .collect(Collectors.toSet()); Path artifactPath = archiveRootBuildItem.getArchiveRoot().resolve( String.format(OUTPUT_ARTIFACT_FORMAT, outputTargetBuildItem.getBaseName(), packageConfig.runnerSuffix)); final Map<String, String> generatedResourcesMap; // by passing false to SimpleFileWriter, we ensure that no files are actually written during this phase final SessionWriter sessionWriter = new SimpleFileWriter(root, false); Project project = createProject(applicationInfo, artifactPath); sessionWriter.setProject(project); final Session session = Session.getSession(); session.setWriter(sessionWriter); session.feed(Maps.fromProperties(config)); //Apply configuration applyGlobalConfig(session, kubernetesConfig); ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); applyConfig(session, project, KUBERNETES, kubernetesConfig.name.orElse(applicationInfo.getName()), kubernetesConfig, now); applyConfig(session, project, OPENSHIFT, openshiftConfig.name.orElse(applicationInfo.getName()), openshiftConfig, now); applyConfig(session, project, KNATIVE, knativeConfig.name.orElse(applicationInfo.getName()), knativeConfig, now); //apply build item configurations to the dekorate session. applyBuildItems(session, applicationInfo.getName(), kubernetesConfig, openshiftConfig, knativeConfig, deploymentTargets, kubernetesRoleBuildItems, kubernetesPortBuildItems, baseImageBuildItem, containerImageBuildItem, commandBuildItem, kubernetesHealthLivenessPathBuildItem, kubernetesHealthReadinessPathBuildItem); // write the generated resources to the filesystem generatedResourcesMap = session.close(); for (Map.Entry<String, String> resourceEntry : generatedResourcesMap.entrySet()) { String fileName = resourceEntry.getKey().replace(root.toAbsolutePath().toString(), ""); String relativePath = resourceEntry.getKey().replace(root.toAbsolutePath().toString(), KUBERNETES); if (fileName.endsWith(".yml") || fileName.endsWith(".json")) { String target = fileName.substring(0, fileName.lastIndexOf(".")); if (target.startsWith(File.separator)) { target = target.substring(1); } if (!deploymentTargets.contains(target)) { continue; } } generatedResourceProducer.produce( new GeneratedFileSystemResourceBuildItem( // we need to make sure we are only passing the relative path to the build item relativePath, resourceEntry.getValue().getBytes(StandardCharsets.UTF_8))); } try { if (root != null && root.toFile().exists()) { FileUtil.deleteDirectory(root); } } catch (IOException e) { log.debug("Unable to delete temporary directory " + root, e); } } @BuildStep FeatureBuildItem produceFeature() { return new FeatureBuildItem(FeatureBuildItem.KUBERNETES); } /** * Apply global changes * * @param session The session to apply the changes * @param config The {@link KubernetesConfig} instance */ private void applyGlobalConfig(Session session, KubernetesConfig config) { //Ports config.ports.entrySet().forEach(e -> session.configurators().add(new AddPort(PortConverter.convert(e)))); } /** * Apply changes to the target resource group * * @param session The session to apply the changes * @param target The deployment target (e.g. kubernetes, openshift, knative) * @param name The name of the resource to accept the configuration * @param config The {@link PlatformConfiguration} instance * @param now */ private void applyConfig(Session session, Project project, String target, String name, PlatformConfiguration config, ZonedDateTime now) { //Labels config.getLabels().forEach((key, value) -> { session.resources().decorate(target, new AddLabelDecorator(new Label(key, value))); }); if (OPENSHIFT.equals(target)) { session.resources().decorate(OPENSHIFT, new AddLabelDecorator(new Label(OPENSHIFT_APP_RUNTIME, QUARKUS))); } //Annotations config.getAnnotations().forEach((key, value) -> { session.resources().decorate(target, new AddAnnotationDecorator(new Annotation(key, value))); }); ScmInfo scm = project.getScmInfo(); String vcsUrl = scm != null ? scm.getUrl() : Annotations.UNKNOWN; String commitId = scm != null ? scm.getCommit() : Annotations.UNKNOWN; //Dekorate uses its own annotations. Let's replace them with the quarkus ones. session.resources().decorate(target, new RemoveAnnotationDecorator(Annotations.VCS_URL)); session.resources().decorate(target, new RemoveAnnotationDecorator(Annotations.COMMIT_ID)); //Add quarkus vcs annotations session.resources().decorate(target, new AddAnnotationDecorator(new Annotation(QUARKUS_ANNOTATIONS_COMMIT_ID, commitId))); session.resources().decorate(target, new AddAnnotationDecorator(new Annotation(QUARKUS_ANNOTATIONS_VCS_URL, vcsUrl))); if (config.isAddBuildTimestamp()) { session.resources().decorate(target, new AddAnnotationDecorator(new Annotation(QUARKUS_ANNOTATIONS_BUILD_TIMESTAMP, now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd - HH:mm:ss Z"))))); } //EnvVars config.getEnvVars().entrySet().forEach(e -> { session.resources().decorate(target, new AddEnvVarDecorator(EnvConverter.convert(e))); }); config.getWorkingDir().ifPresent(w -> { session.resources().decorate(target, new ApplyWorkingDirDecorator(name, DEPLOY)); }); config.getCommand().ifPresent(c -> { session.resources().decorate(target, new ApplyCommandDecorator(name, c.toArray(new String[c.size()]))); }); config.getArguments().ifPresent(a -> { session.resources().decorate(target, new ApplyArgsDecorator(name, a.toArray(new String[a.size()]))); }); config.getServiceAccount().ifPresent(s -> { session.resources().decorate(target, new ApplyServiceAccountNamedDecorator(name, s)); }); //Image Pull session.resources().decorate(new ApplyImagePullPolicyDecorator(config.getImagePullPolicy())); config.getImagePullSecrets().ifPresent(l -> { l.forEach(s -> session.resources().decorate(target, new AddImagePullSecretDecorator(name, s))); }); //Probes config.getLivenessProbe().ifPresent(p -> { session.resources().decorate(target, new AddLivenessProbeDecorator(name, ProbeConverter.convert(p))); }); config.getReadinessProbe().ifPresent(p -> { session.resources().decorate(target, new AddReadinessProbeDecorator(name, ProbeConverter.convert(p))); }); // Mounts and Volumes config.getMounts().entrySet().forEach(e -> { session.resources().decorate(target, new AddMountDecorator(MountConverter.convert(e))); }); config.getSecretVolumes().entrySet().forEach(e -> { session.resources().decorate(target, new AddSecretVolumeDecorator(SecretVolumeConverter.convert(e))); }); config.getConfigMapVolumes().entrySet().forEach(e -> { session.resources().decorate(target, new AddConfigMapVolumeDecorator(ConfigMapVolumeConverter.convert(e))); }); config.getPvcVolumes().entrySet().forEach(e -> { session.resources().decorate(target, new AddPvcVolumeDecorator(PvcVolumeConverter.convert(e))); }); config.getAwsElasticBlockStoreVolumes().entrySet().forEach(e -> { session.resources().decorate(target, new AddAwsElasticBlockStoreVolumeDecorator(AwsElasticBlockStoreVolumeConverter.convert(e))); }); config.getAzureFileVolumes().entrySet().forEach(e -> { session.resources().decorate(target, new AddAzureFileVolumeDecorator(AzureFileVolumeConverter.convert(e))); }); config.getAzureDiskVolumes().entrySet().forEach(e -> { session.resources().decorate(target, new AddAzureDiskVolumeDecorator(AzureDiskVolumeConverter.convert(e))); }); config.getInitContainers().entrySet().forEach(e -> { session.resources().decorate(target, new AddInitContainerDecorator(name, ContainerConverter.convert(e))); }); config.getContainers().entrySet().forEach(e -> { session.resources().decorate(target, new AddSidecarDecorator(name, ContainerConverter.convert(e))); }); } private void applyBuildItems(Session session, String name, KubernetesConfig kubernetesConfig, OpenshiftConfig openshiftConfig, KnativeConfig knativeConfig, Set<String> deploymentTargets, List<KubernetesRoleBuildItem> kubernetesRoleBuildItems, List<KubernetesPortBuildItem> kubernetesPortBuildItems, Optional<BaseImageInfoBuildItem> baseImageBuildItem, Optional<ContainerImageInfoBuildItem> containerImageBuildItem, Optional<KubernetesCommandBuildItem> commandBuildItem, Optional<KubernetesHealthLivenessPathBuildItem> kubernetesHealthLivenessPathBuildItem, Optional<KubernetesHealthReadinessPathBuildItem> kubernetesHealthReadinessPathBuildItem) { String kubernetesName = kubernetesConfig.name.orElse(name); String openshiftName = openshiftConfig.name.orElse(name); String knativeName = knativeConfig.name.orElse(name); session.resources().decorate(KNATIVE, new AddMissingContainerNameDecorator(knativeName, knativeName)); containerImageBuildItem.ifPresent(c -> { session.resources().decorate(OPENSHIFT, new ApplyContainerImageDecorator(openshiftName, c.getImage())); session.resources().decorate(KUBERNETES, new ApplyContainerImageDecorator(kubernetesName, c.getImage())); session.resources().decorate(KNATIVE, new ApplyContainerImageDecorator(knativeName, c.getImage())); }); //Handle Command and arguments commandBuildItem.ifPresent(c -> { session.resources() .decorate(new ApplyCommandDecorator(kubernetesName, new String[] { c.getCommand() })); session.resources().decorate(KUBERNETES, new ApplyArgsDecorator(kubernetesName, c.getArgs())); session.resources() .decorate(new ApplyCommandDecorator(openshiftName, new String[] { c.getCommand() })); session.resources().decorate(OPENSHIFT, new ApplyArgsDecorator(openshiftName, c.getArgs())); session.resources() .decorate(new ApplyCommandDecorator(knativeName, new String[] { c.getCommand() })); session.resources().decorate(KNATIVE, new ApplyArgsDecorator(knativeName, c.getArgs())); }); //Handle ports final Map<String, Integer> ports = verifyPorts(kubernetesPortBuildItems); ports.entrySet().stream() .map(e -> new PortBuilder().withName(e.getKey()).withContainerPort(e.getValue()).build()) .forEach(p -> session.configurators().add(new AddPort(p))); //Handle RBAC if (!kubernetesPortBuildItems.isEmpty()) { session.resources().decorate(new ApplyServiceAccountNamedDecorator()); session.resources().decorate(new AddServiceAccountResourceDecorator()); kubernetesRoleBuildItems .forEach(r -> session.resources().decorate(new AddRoleBindingResourceDecorator(r.getRole()))); } //Handle custom s2i builder images if (deploymentTargets.contains(OPENSHIFT)) { baseImageBuildItem.map(BaseImageInfoBuildItem::getImage).ifPresent(builderImage -> { String builderImageName = ImageUtil.getName(builderImage); S2iBuildConfig s2iBuildConfig = new S2iBuildConfigBuilder().withBuilderImage(builderImage).build(); if (!DEFAULT_S2I_IMAGE_NAME.equals(builderImageName)) { session.resources().decorate(OPENSHIFT, new RemoveBuilderImageResourceDecorator(DEFAULT_S2I_IMAGE_NAME)); } session.resources().decorate(OPENSHIFT, new AddBuilderImageStreamResourceDecorator(s2iBuildConfig)); session.resources().decorate(OPENSHIFT, new ApplyBuilderImageDecorator(openshiftName, builderImage)); }); } //Handle probes kubernetesHealthLivenessPathBuildItem .ifPresent(l -> session.resources() .decorate(new AddLivenessProbeDecorator(name, new ProbeBuilder() .withHttpActionPath(l.getPath()) .build()))); kubernetesHealthReadinessPathBuildItem .ifPresent(r -> session.resources() .decorate(new AddReadinessProbeDecorator(name, new ProbeBuilder() .withHttpActionPath(r.getPath()) .build()))); } private Map<String, Integer> verifyPorts(List<KubernetesPortBuildItem> kubernetesPortBuildItems) { final Map<String, Integer> result = new HashMap<>(); final Set<Integer> usedPorts = new HashSet<>(); for (KubernetesPortBuildItem entry : kubernetesPortBuildItems) { final String name = entry.getName(); if (result.containsKey(name)) { throw new IllegalArgumentException( "All Kubernetes ports must have unique names - " + name + "has been used multiple times"); } final Integer port = entry.getPort(); if (usedPorts.contains(port)) { throw new IllegalArgumentException( "All Kubernetes ports must be unique - " + port + "has been used multiple times"); } result.put(name, port); usedPorts.add(port); } return result; } private Project createProject(ApplicationInfoBuildItem app, Path artifactPath) { //Let dekorate create a Project instance and then override with what is found in ApplicationInfoBuildItem. Project project = FileProjectFactory.create(artifactPath.toFile()); BuildInfo buildInfo = new BuildInfo(app.getName(), app.getVersion(), "jar", project.getBuildInfo().getBuildTool(), artifactPath, project.getBuildInfo().getOutputFile(), project.getBuildInfo().getClassOutputDir()); return new Project(project.getRoot(), buildInfo, project.getScmInfo()); } }
fix: wrong value passed to working dir decorator
extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/KubernetesProcessor.java
fix: wrong value passed to working dir decorator
<ide><path>xtensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/KubernetesProcessor.java <ide> }); <ide> <ide> config.getWorkingDir().ifPresent(w -> { <del> session.resources().decorate(target, new ApplyWorkingDirDecorator(name, DEPLOY)); <add> session.resources().decorate(target, new ApplyWorkingDirDecorator(name, w)); <ide> }); <ide> <ide> config.getCommand().ifPresent(c -> {
Java
apache-2.0
50b124f6fdb2cfa496501781fa905b200bcb59c5
0
yuyijq/dubbo,yuyijq/dubbo,lovepoem/dubbo,aglne/dubbo,lovepoem/dubbo,fengyie007/dubbo,fengyie007/dubbo,JasonHZXie/dubbo,bpzhang/dubbo,alibaba/dubbo,aglne/dubbo,JasonHZXie/dubbo,qtvbwfn/dubbo,alibaba/dubbo,bpzhang/dubbo,qtvbwfn/dubbo,wuwen5/dubbo,wuwen5/dubbo,lovepoem/dubbo,aglne/dubbo,qtvbwfn/dubbo,fengyie007/dubbo,bpzhang/dubbo,wuwen5/dubbo,qtvbwfn/dubbo
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.dubbo; import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.protocol.dubbo.support.ProtocolUtils; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import java.lang.reflect.Field; import static org.junit.Assert.fail; /** * Check available status for dubboInvoker */ public class DubboInvokerAvilableTest { private static DubboProtocol protocol = DubboProtocol.getDubboProtocol(); private static ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); @BeforeClass public static void setUpBeforeClass() throws Exception { } @Before public void setUp() throws Exception { } @Test public void test_Normal_available() { URL url = URL.valueOf("dubbo://127.0.0.1:20883/org.apache.dubbo.rpc.protocol.dubbo.IDemoService"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); DubboInvoker<?> invoker = (DubboInvoker<?>) protocol.refer(IDemoService.class, url); Assert.assertEquals(true, invoker.isAvailable()); invoker.destroy(); Assert.assertEquals(false, invoker.isAvailable()); } @Test public void test_Normal_ChannelReadOnly() throws Exception { URL url = URL.valueOf("dubbo://127.0.0.1:20883/org.apache.dubbo.rpc.protocol.dubbo.IDemoService"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); DubboInvoker<?> invoker = (DubboInvoker<?>) protocol.refer(IDemoService.class, url); Assert.assertEquals(true, invoker.isAvailable()); getClients(invoker)[0].setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); Assert.assertEquals(false, invoker.isAvailable()); // reset status since connection is shared among invokers getClients(invoker)[0].removeAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY); } @Ignore public void test_normal_channel_close_wait_gracefully() throws Exception { int testPort = NetUtils.getAvailablePort(); URL url = URL.valueOf("dubbo://127.0.0.1:" + testPort + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?scope=true&lazy=false"); Exporter<IDemoService> exporter = ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); Exporter<IDemoService> exporter0 = ProtocolUtils.export(new DemoServiceImpl0(), IDemoService.class, url); DubboInvoker<?> invoker = (DubboInvoker<?>) protocol.refer(IDemoService.class, url); long start = System.currentTimeMillis(); try{ System.setProperty(Constants.SHUTDOWN_WAIT_KEY, "2000"); System.out.println("------------ConfigUtils.getServerShutdownTimeout(): " + ConfigUtils.getServerShutdownTimeout()); protocol.destroy(); }finally { System.getProperties().remove(Constants.SHUTDOWN_WAIT_KEY); } long waitTime = System.currentTimeMillis() - start; Assert.assertTrue(waitTime >= 2000); Assert.assertEquals(false, invoker.isAvailable()); } @Test public void test_NoInvokers() throws Exception { URL url = URL.valueOf("dubbo://127.0.0.1:20883/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?connections=1"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); DubboInvoker<?> invoker = (DubboInvoker<?>) protocol.refer(IDemoService.class, url); ExchangeClient[] clients = getClients(invoker); clients[0].close(); Assert.assertEquals(false, invoker.isAvailable()); } @Test public void test_Lazy_ChannelReadOnly() throws Exception { URL url = URL.valueOf("dubbo://127.0.0.1:20883/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?lazy=true&connections=1&timeout=10000"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); DubboInvoker<?> invoker = (DubboInvoker<?>) protocol.refer(IDemoService.class, url); Assert.assertEquals(true, invoker.isAvailable()); try { getClients(invoker)[0].setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); fail(); } catch (IllegalStateException e) { } //invoke method --> init client IDemoService service = (IDemoService) proxy.getProxy(invoker); Assert.assertEquals("ok", service.get()); Assert.assertEquals(true, invoker.isAvailable()); getClients(invoker)[0].setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); Assert.assertEquals(false, invoker.isAvailable()); } private ExchangeClient[] getClients(DubboInvoker<?> invoker) throws Exception { Field field = DubboInvoker.class.getDeclaredField("clients"); field.setAccessible(true); ExchangeClient[] clients = (ExchangeClient[]) field.get(invoker); Assert.assertEquals(1, clients.length); return clients; } public class DemoServiceImpl implements IDemoService { public String get() { return "ok"; } } public class DemoServiceImpl0 implements IDemoService { public String get() { return "ok"; } } }
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.dubbo; import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.protocol.dubbo.support.ProtocolUtils; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.lang.reflect.Field; import static org.junit.Assert.fail; /** * Check available status for dubboInvoker */ public class DubboInvokerAvilableTest { private static DubboProtocol protocol = DubboProtocol.getDubboProtocol(); private static ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); @BeforeClass public static void setUpBeforeClass() throws Exception { } @Before public void setUp() throws Exception { } @Test public void test_Normal_available() { URL url = URL.valueOf("dubbo://127.0.0.1:20883/org.apache.dubbo.rpc.protocol.dubbo.IDemoService"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); DubboInvoker<?> invoker = (DubboInvoker<?>) protocol.refer(IDemoService.class, url); Assert.assertEquals(true, invoker.isAvailable()); invoker.destroy(); Assert.assertEquals(false, invoker.isAvailable()); } @Test public void test_Normal_ChannelReadOnly() throws Exception { URL url = URL.valueOf("dubbo://127.0.0.1:20883/org.apache.dubbo.rpc.protocol.dubbo.IDemoService"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); DubboInvoker<?> invoker = (DubboInvoker<?>) protocol.refer(IDemoService.class, url); Assert.assertEquals(true, invoker.isAvailable()); getClients(invoker)[0].setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); Assert.assertEquals(false, invoker.isAvailable()); // reset status since connection is shared among invokers getClients(invoker)[0].removeAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY); } @Test public void test_normal_channel_close_wait_gracefully() throws Exception { int testPort = NetUtils.getAvailablePort(); URL url = URL.valueOf("dubbo://127.0.0.1:" + testPort + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?scope=true&lazy=false"); Exporter<IDemoService> exporter = ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); Exporter<IDemoService> exporter0 = ProtocolUtils.export(new DemoServiceImpl0(), IDemoService.class, url); DubboInvoker<?> invoker = (DubboInvoker<?>) protocol.refer(IDemoService.class, url); long start = System.currentTimeMillis(); try{ System.setProperty(Constants.SHUTDOWN_WAIT_KEY, "2000"); System.out.println("------------ConfigUtils.getServerShutdownTimeout(): " + ConfigUtils.getServerShutdownTimeout()); protocol.destroy(); }finally { System.getProperties().remove(Constants.SHUTDOWN_WAIT_KEY); } long waitTime = System.currentTimeMillis() - start; Assert.assertTrue(waitTime >= 2000); Assert.assertEquals(false, invoker.isAvailable()); } @Test public void test_NoInvokers() throws Exception { URL url = URL.valueOf("dubbo://127.0.0.1:20883/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?connections=1"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); DubboInvoker<?> invoker = (DubboInvoker<?>) protocol.refer(IDemoService.class, url); ExchangeClient[] clients = getClients(invoker); clients[0].close(); Assert.assertEquals(false, invoker.isAvailable()); } @Test public void test_Lazy_ChannelReadOnly() throws Exception { URL url = URL.valueOf("dubbo://127.0.0.1:20883/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?lazy=true&connections=1&timeout=10000"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); DubboInvoker<?> invoker = (DubboInvoker<?>) protocol.refer(IDemoService.class, url); Assert.assertEquals(true, invoker.isAvailable()); try { getClients(invoker)[0].setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); fail(); } catch (IllegalStateException e) { } //invoke method --> init client IDemoService service = (IDemoService) proxy.getProxy(invoker); Assert.assertEquals("ok", service.get()); Assert.assertEquals(true, invoker.isAvailable()); getClients(invoker)[0].setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); Assert.assertEquals(false, invoker.isAvailable()); } private ExchangeClient[] getClients(DubboInvoker<?> invoker) throws Exception { Field field = DubboInvoker.class.getDeclaredField("clients"); field.setAccessible(true); ExchangeClient[] clients = (ExchangeClient[]) field.get(invoker); Assert.assertEquals(1, clients.length); return clients; } public class DemoServiceImpl implements IDemoService { public String get() { return "ok"; } } public class DemoServiceImpl0 implements IDemoService { public String get() { return "ok"; } } }
ignore unstable test test_normal_channel_close_wait_gracefully
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java
ignore unstable test test_normal_channel_close_wait_gracefully
<ide><path>ubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvilableTest.java <ide> import org.junit.Assert; <ide> import org.junit.Before; <ide> import org.junit.BeforeClass; <add>import org.junit.Ignore; <ide> import org.junit.Test; <ide> <ide> import java.lang.reflect.Field; <ide> getClients(invoker)[0].removeAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY); <ide> } <ide> <del> @Test <add> @Ignore <ide> public void test_normal_channel_close_wait_gracefully() throws Exception { <ide> int testPort = NetUtils.getAvailablePort(); <ide> URL url = URL.valueOf("dubbo://127.0.0.1:" + testPort + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?scope=true&lazy=false");
Java
bsd-2-clause
d4f2753e0577142400abbfae6265970dd6ed39de
0
l2-/runelite,l2-/runelite,Sethtroll/runelite,runelite/runelite,runelite/runelite,runelite/runelite,Sethtroll/runelite
/* * Copyright (c) 2018, Tomas Slusny <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.client.plugins.playerindicators; import com.google.inject.Provides; import java.awt.Color; import javax.inject.Inject; import lombok.Value; import net.runelite.api.ClanMemberRank; import static net.runelite.api.ClanMemberRank.UNRANKED; import net.runelite.api.Client; import static net.runelite.api.MenuAction.*; import net.runelite.api.MenuEntry; import net.runelite.api.Player; import net.runelite.api.events.ClientTick; import net.runelite.client.config.ConfigManager; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.game.ClanManager; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.ui.overlay.OverlayManager; import net.runelite.client.util.ColorUtil; @PluginDescriptor( name = "Player Indicators", description = "Highlight players on-screen and/or on the minimap", tags = {"highlight", "minimap", "overlay", "players"} ) public class PlayerIndicatorsPlugin extends Plugin { @Inject private OverlayManager overlayManager; @Inject private PlayerIndicatorsConfig config; @Inject private PlayerIndicatorsOverlay playerIndicatorsOverlay; @Inject private PlayerIndicatorsTileOverlay playerIndicatorsTileOverlay; @Inject private PlayerIndicatorsMinimapOverlay playerIndicatorsMinimapOverlay; @Inject private Client client; @Inject private ClanManager clanManager; @Provides PlayerIndicatorsConfig provideConfig(ConfigManager configManager) { return configManager.getConfig(PlayerIndicatorsConfig.class); } @Override protected void startUp() throws Exception { overlayManager.add(playerIndicatorsOverlay); overlayManager.add(playerIndicatorsTileOverlay); overlayManager.add(playerIndicatorsMinimapOverlay); } @Override protected void shutDown() throws Exception { overlayManager.remove(playerIndicatorsOverlay); overlayManager.remove(playerIndicatorsTileOverlay); overlayManager.remove(playerIndicatorsMinimapOverlay); } @Subscribe public void onClientTick(ClientTick clientTick) { MenuEntry[] menuEntries = client.getMenuEntries(); boolean modified = false; for (MenuEntry entry : menuEntries) { int type = entry.getType(); if (type >= MENU_ACTION_DEPRIORITIZE_OFFSET) { type -= MENU_ACTION_DEPRIORITIZE_OFFSET; } int identifier = entry.getIdentifier(); if (type == SPELL_CAST_ON_PLAYER.getId() || type == ITEM_USE_ON_PLAYER.getId() || type == PLAYER_FIRST_OPTION.getId() || type == PLAYER_SECOND_OPTION.getId() || type == PLAYER_THIRD_OPTION.getId() || type == PLAYER_FOURTH_OPTION.getId() || type == PLAYER_FIFTH_OPTION.getId() || type == PLAYER_SIXTH_OPTION.getId() || type == PLAYER_SEVENTH_OPTION.getId() || type == PLAYER_EIGTH_OPTION.getId() || type == RUNELITE.getId()) { Player[] players = client.getCachedPlayers(); Player player = null; if (identifier >= 0 && identifier < players.length) { player = players[identifier]; } if (player == null) { continue; } Decorations decorations = getDecorations(player); if (decorations == null) { continue; } String oldTarget = entry.getTarget(); String newTarget = decorateTarget(oldTarget, decorations); entry.setTarget(newTarget); modified = true; } } if (modified) { client.setMenuEntries(menuEntries); } } private Decorations getDecorations(Player player) { int image = -1; Color color = null; if (config.highlightFriends() && player.isFriend()) { color = config.getFriendColor(); } else if (config.drawClanMemberNames() && player.isClanMember()) { color = config.getClanMemberColor(); ClanMemberRank rank = clanManager.getRank(player.getName()); if (rank != UNRANKED) { image = clanManager.getIconNumber(rank); } } else if (config.highlightTeamMembers() && player.getTeam() > 0 && client.getLocalPlayer().getTeam() == player.getTeam()) { color = config.getTeamMemberColor(); } else if (config.highlightNonClanMembers() && !player.isClanMember()) { color = config.getNonClanMemberColor(); } if (image == -1 && color == null) { return null; } return new Decorations(image, color); } private String decorateTarget(String oldTarget, Decorations decorations) { String newTarget = oldTarget; if (decorations.getColor() != null && config.colorPlayerMenu()) { // strip out existing <col... int idx = oldTarget.indexOf('>'); if (idx != -1) { newTarget = oldTarget.substring(idx + 1); } newTarget = ColorUtil.prependColorTag(newTarget, decorations.getColor()); } if (decorations.getImage() != -1 && config.showClanRanks()) { newTarget = "<img=" + decorations.getImage() + ">" + newTarget; } return newTarget; } @Value private static class Decorations { private final int image; private final Color color; } }
runelite-client/src/main/java/net/runelite/client/plugins/playerindicators/PlayerIndicatorsPlugin.java
/* * Copyright (c) 2018, Tomas Slusny <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.client.plugins.playerindicators; import com.google.inject.Provides; import java.awt.Color; import javax.inject.Inject; import lombok.Value; import net.runelite.api.ClanMemberRank; import static net.runelite.api.ClanMemberRank.UNRANKED; import net.runelite.api.Client; import static net.runelite.api.MenuAction.*; import net.runelite.api.MenuEntry; import net.runelite.api.Player; import net.runelite.api.events.MenuEntryAdded; import net.runelite.client.config.ConfigManager; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.game.ClanManager; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.ui.overlay.OverlayManager; import net.runelite.client.util.ColorUtil; @PluginDescriptor( name = "Player Indicators", description = "Highlight players on-screen and/or on the minimap", tags = {"highlight", "minimap", "overlay", "players"} ) public class PlayerIndicatorsPlugin extends Plugin { @Inject private OverlayManager overlayManager; @Inject private PlayerIndicatorsConfig config; @Inject private PlayerIndicatorsOverlay playerIndicatorsOverlay; @Inject private PlayerIndicatorsTileOverlay playerIndicatorsTileOverlay; @Inject private PlayerIndicatorsMinimapOverlay playerIndicatorsMinimapOverlay; @Inject private Client client; @Inject private ClanManager clanManager; @Provides PlayerIndicatorsConfig provideConfig(ConfigManager configManager) { return configManager.getConfig(PlayerIndicatorsConfig.class); } @Override protected void startUp() throws Exception { overlayManager.add(playerIndicatorsOverlay); overlayManager.add(playerIndicatorsTileOverlay); overlayManager.add(playerIndicatorsMinimapOverlay); } @Override protected void shutDown() throws Exception { overlayManager.remove(playerIndicatorsOverlay); overlayManager.remove(playerIndicatorsTileOverlay); overlayManager.remove(playerIndicatorsMinimapOverlay); } @Subscribe public void onMenuEntryAdded(MenuEntryAdded menuEntryAdded) { int type = menuEntryAdded.getType(); if (type >= 2000) { type -= 2000; } int identifier = menuEntryAdded.getIdentifier(); if (type == SPELL_CAST_ON_PLAYER.getId() || type == ITEM_USE_ON_PLAYER.getId() || type == PLAYER_FIRST_OPTION.getId() || type == PLAYER_SECOND_OPTION.getId() || type == PLAYER_THIRD_OPTION.getId() || type == PLAYER_FOURTH_OPTION.getId() || type == PLAYER_FIFTH_OPTION.getId() || type == PLAYER_SIXTH_OPTION.getId() || type == PLAYER_SEVENTH_OPTION.getId() || type == PLAYER_EIGTH_OPTION.getId() || type == RUNELITE.getId()) { Player[] players = client.getCachedPlayers(); Player player = null; if (identifier >= 0 && identifier < players.length) { player = players[identifier]; } if (player == null) { return; } Decorations decorations = getDecorations(player); if (decorations == null) { return; } MenuEntry[] menuEntries = client.getMenuEntries(); MenuEntry entry = menuEntries[menuEntries.length - 1]; String oldTarget = entry.getTarget(); String newTarget = decorateTarget(oldTarget, decorations); entry.setTarget(newTarget); client.setMenuEntries(menuEntries); } } private Decorations getDecorations(Player player) { int image = -1; Color color = null; if (config.highlightFriends() && player.isFriend()) { color = config.getFriendColor(); } else if (config.drawClanMemberNames() && player.isClanMember()) { color = config.getClanMemberColor(); ClanMemberRank rank = clanManager.getRank(player.getName()); if (rank != UNRANKED) { image = clanManager.getIconNumber(rank); } } else if (config.highlightTeamMembers() && player.getTeam() > 0 && client.getLocalPlayer().getTeam() == player.getTeam()) { color = config.getTeamMemberColor(); } else if (config.highlightNonClanMembers() && !player.isClanMember()) { color = config.getNonClanMemberColor(); } if (image == -1 && color == null) { return null; } return new Decorations(image, color); } private String decorateTarget(String oldTarget, Decorations decorations) { String newTarget = oldTarget; if (decorations.getColor() != null && config.colorPlayerMenu()) { // strip out existing <col... int idx = oldTarget.indexOf('>'); if (idx != -1) { newTarget = oldTarget.substring(idx + 1); } newTarget = ColorUtil.prependColorTag(newTarget, decorations.getColor()); } if (decorations.getImage() != -1 && config.showClanRanks()) { newTarget = "<img=" + decorations.getImage() + ">" + newTarget; } return newTarget; } @Value private static class Decorations { private final int image; private final Color color; } }
player-indicators: move menu logic to ClientTick
runelite-client/src/main/java/net/runelite/client/plugins/playerindicators/PlayerIndicatorsPlugin.java
player-indicators: move menu logic to ClientTick
<ide><path>unelite-client/src/main/java/net/runelite/client/plugins/playerindicators/PlayerIndicatorsPlugin.java <ide> import static net.runelite.api.MenuAction.*; <ide> import net.runelite.api.MenuEntry; <ide> import net.runelite.api.Player; <del>import net.runelite.api.events.MenuEntryAdded; <add>import net.runelite.api.events.ClientTick; <ide> import net.runelite.client.config.ConfigManager; <ide> import net.runelite.client.eventbus.Subscribe; <ide> import net.runelite.client.game.ClanManager; <ide> } <ide> <ide> @Subscribe <del> public void onMenuEntryAdded(MenuEntryAdded menuEntryAdded) <del> { <del> int type = menuEntryAdded.getType(); <del> <del> if (type >= 2000) <del> { <del> type -= 2000; <del> } <del> <del> int identifier = menuEntryAdded.getIdentifier(); <del> if (type == SPELL_CAST_ON_PLAYER.getId() <del> || type == ITEM_USE_ON_PLAYER.getId() <del> || type == PLAYER_FIRST_OPTION.getId() <del> || type == PLAYER_SECOND_OPTION.getId() <del> || type == PLAYER_THIRD_OPTION.getId() <del> || type == PLAYER_FOURTH_OPTION.getId() <del> || type == PLAYER_FIFTH_OPTION.getId() <del> || type == PLAYER_SIXTH_OPTION.getId() <del> || type == PLAYER_SEVENTH_OPTION.getId() <del> || type == PLAYER_EIGTH_OPTION.getId() <del> || type == RUNELITE.getId()) <del> { <del> Player[] players = client.getCachedPlayers(); <del> Player player = null; <del> <del> if (identifier >= 0 && identifier < players.length) <del> { <del> player = players[identifier]; <del> } <del> <del> if (player == null) <del> { <del> return; <del> } <del> <del> Decorations decorations = getDecorations(player); <del> <del> if (decorations == null) <del> { <del> return; <del> } <del> <del> MenuEntry[] menuEntries = client.getMenuEntries(); <del> MenuEntry entry = menuEntries[menuEntries.length - 1]; <del> <del> String oldTarget = entry.getTarget(); <del> String newTarget = decorateTarget(oldTarget, decorations); <del> <del> entry.setTarget(newTarget); <del> <add> public void onClientTick(ClientTick clientTick) <add> { <add> MenuEntry[] menuEntries = client.getMenuEntries(); <add> boolean modified = false; <add> <add> for (MenuEntry entry : menuEntries) <add> { <add> int type = entry.getType(); <add> <add> if (type >= MENU_ACTION_DEPRIORITIZE_OFFSET) <add> { <add> type -= MENU_ACTION_DEPRIORITIZE_OFFSET; <add> } <add> <add> int identifier = entry.getIdentifier(); <add> if (type == SPELL_CAST_ON_PLAYER.getId() <add> || type == ITEM_USE_ON_PLAYER.getId() <add> || type == PLAYER_FIRST_OPTION.getId() <add> || type == PLAYER_SECOND_OPTION.getId() <add> || type == PLAYER_THIRD_OPTION.getId() <add> || type == PLAYER_FOURTH_OPTION.getId() <add> || type == PLAYER_FIFTH_OPTION.getId() <add> || type == PLAYER_SIXTH_OPTION.getId() <add> || type == PLAYER_SEVENTH_OPTION.getId() <add> || type == PLAYER_EIGTH_OPTION.getId() <add> || type == RUNELITE.getId()) <add> { <add> Player[] players = client.getCachedPlayers(); <add> Player player = null; <add> <add> if (identifier >= 0 && identifier < players.length) <add> { <add> player = players[identifier]; <add> } <add> <add> if (player == null) <add> { <add> continue; <add> } <add> <add> Decorations decorations = getDecorations(player); <add> <add> if (decorations == null) <add> { <add> continue; <add> } <add> <add> String oldTarget = entry.getTarget(); <add> String newTarget = decorateTarget(oldTarget, decorations); <add> <add> entry.setTarget(newTarget); <add> modified = true; <add> } <add> } <add> <add> if (modified) <add> { <ide> client.setMenuEntries(menuEntries); <ide> } <ide> }
Java
mit
b2fb149b00ccabd73e0386fc257c14c7f9a777f2
0
erfgoed-en-locatie/artsholland-platform,erfgoed-en-locatie/artsholland-platform,erfgoed-en-locatie/artsholland-platform,erfgoed-en-locatie/artsholland-platform,erfgoed-en-locatie/artsholland-platform
package org.waag.ah.rest.model; import java.util.ArrayList; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.lang.ArrayUtils; import org.waag.ah.rest.RestParameters; public class SPARQLQuery { private static final String PAGING_PLACEMARK = "[[paging]]"; private static final String STATEMENTS_PLACEMARK = "[[statements]]"; private static final String FILTER_PLACEMARK = "[[filter]]"; private static final String LANGUAGE_PLACEMARK = "[[language]]"; private static final long MAXIMUM_PER_PAGE = 250; /* * SPARQL */ // TODO: load SPARQL from file? private static final String SPARQL_CONSTRUCT = "CONSTRUCT { ?object ?p ?o . }" + "WHERE {" + " OPTIONAL { ?object ?p ?o . }" + " {" + " SELECT DISTINCT ?object WHERE" + " {" + " [[statements]]" + " [[filter]]" + " } [[paging]]" //ORDER BY ?object + " } [[language]]" + "} ORDER BY ?object ?p"; private static final String SPARQL_COUNT = "SELECT (COUNT(?o) AS ?count)" + "WHERE {" + " OPTIONAL { ?object a ?o . }" + " {" + " SELECT DISTINCT ?object WHERE" + " {" + " [[statements]]" + " [[filter]]" + " }" // ORDER BY ?object + " }" + "} GROUP BY ?o"; private static final String SPARQL_SINGLE_SELF = "CONSTRUCT { ?object ?p ?o . }" + "WHERE {" + " { [[statements]] [[language]] [[filter]] }" + "} ORDER BY ?p"; /* * private fields */ private String[] statements; private boolean singleSelf = false; public SPARQLQuery(String... statements) { this.statements = statements; } public SPARQLQuery(boolean singleSelf, String... statements) { this.statements = statements; this.singleSelf = singleSelf; } public String generateContruct(RestRelation relation, RestParameters params, Map<String, String> bindings, boolean includePrefix) { String query = singleSelf ? SPARQL_SINGLE_SELF : SPARQL_CONSTRUCT; query = addPaging(query, params.getPerPage(), params.getPage()); query = addLanguageFilter(query, params); query = addFilters(query, generateFilters(relation, params)); query = addStatements(query, (String[]) ArrayUtils.addAll(statements, relation.getStatements(params).toArray())); query = addBindings(bindings, query); return includePrefix ? AHRDFNamespaces.getSPARQLPrefix() + query : query; } public String generateCount(RestRelation relation, RestParameters params, Map<String, String> bindings, boolean includePrefix) { String query = SPARQL_COUNT; query = query.replace(PAGING_PLACEMARK, ""); query = query.replace(LANGUAGE_PLACEMARK, ""); query = addFilters(query, generateFilters(relation, params)); query = addStatements(query, (String[]) ArrayUtils.addAll(statements, relation.getStatements(params).toArray())); query = addBindings(bindings, query); return includePrefix ? AHRDFNamespaces.getSPARQLPrefix() + query : query; } /* private String generateSPARQLBody(RestRelation relation, RestParameters params, Map<String, String> bindings, String query) { query = addPaging(query, params.getResultLimit(), params.getPage()); query = addLanguageFilter(query, params); query = addFilters(query, generateFilters(relation, params)); query = addStatements(query, (String[]) ArrayUtils.addAll(statements, relation.getStatements(params).toArray())); query = addBindings(bindings, query); return query; } */ private String addBindings(Map<String, String> bindings, String query) { Map<String, String> namespaces = AHRDFNamespaces.getNamespaces(); for (Map.Entry<String, String> entry : bindings.entrySet()) { String value = entry.getValue(); boolean addBrackets = true; if (value.contains(":")) { for (Entry<String, String> namespace : namespaces.entrySet()) { if (value.startsWith(namespace.getKey())) { addBrackets = false; break; } } } if (addBrackets) { value = "<" + value + ">"; } query = query.replace("?" + entry.getKey(), value); } return query; } public String[] getStatements() { return statements; } public void setStatements(String[] statements) { this.statements = statements; } private ArrayList<String> generateFilters(RestRelation relation, RestParameters params) { return relation.getFilters(params); } private String addStatements(String query, String... statements) { StringBuilder statementsString = new StringBuilder(); if (statements != null && statements.length > 0) { statementsString.append(statements[0]); for (int i = 1; i < statements.length; i++) { statementsString.append(" "); statementsString.append(statements[i]); } } return query.replace(STATEMENTS_PLACEMARK, statementsString); } private String addLanguageFilter(String query, RestParameters params) { ArrayList<String> filters = new ArrayList<String>(); String languageFilter = "!isLiteral(?o) || datatype(?o) != \"xsd:string\" || langMatches(lang(?o), ?lang ) || langMatches(lang(?o), \"\")"; languageFilter = languageFilter.replace("?lang", "\"" + params.getLanguageTag() + "\""); filters.add(languageFilter); return addFilters(query, LANGUAGE_PLACEMARK, filters); } private String addPaging(String query, long perPage, long page) { // TODO: check if count & page are valid long oldPerPage = perPage; if (perPage > MAXIMUM_PER_PAGE) { perPage = MAXIMUM_PER_PAGE; } if (page < 1) { page = 1; } return query.replace(PAGING_PLACEMARK, "LIMIT " + perPage + " OFFSET " + oldPerPage * (page - 1)); } private String addFilters(String query, ArrayList<String> filters) { return addFilters(query, FILTER_PLACEMARK, filters); } private String addFilters(String query, String placemark, ArrayList<String> filters) { StringBuilder filter = new StringBuilder(); if (filters != null && filters.size() > 0) { filter.append("FILTER("); filter.append("(" + filters.get(0) + ")"); for (int i = 1; i < filters.size(); i++) { filter.append(" && "); filter.append("(" + filters.get(i) + ")"); } filter.append(")"); } return query.replace(placemark, filter); } }
artsholland-core/src/main/java/org/waag/ah/rest/model/SPARQLQuery.java
package org.waag.ah.rest.model; import java.util.ArrayList; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.lang.ArrayUtils; import org.waag.ah.rest.RestParameters; public class SPARQLQuery { private static final String PAGING_PLACEMARK = "[[paging]]"; private static final String STATEMENTS_PLACEMARK = "[[statements]]"; private static final String FILTER_PLACEMARK = "[[filter]]"; private static final String LANGUAGE_PLACEMARK = "[[language]]"; private static final long MAXIMUM_PER_PAGE = 250; /* * SPARQL */ // TODO: load SPARQL from file? private static final String SPARQL_CONSTRUCT = "CONSTRUCT { ?object ?p ?o . }" + "WHERE {" + " OPTIONAL { ?object ?p ?o . }" + " {" + " SELECT DISTINCT ?object WHERE" + " {" + " [[statements]]" + " [[filter]]" + " } [[paging]]" //ORDER BY ?object + " } [[language]]" + "}"; // ORDER BY ?object ?p private static final String SPARQL_COUNT = "SELECT (COUNT(?o) AS ?count)" + "WHERE {" + " OPTIONAL { ?object a ?o . }" + " {" + " SELECT DISTINCT ?object WHERE" + " {" + " [[statements]]" + " [[filter]]" + " }" // ORDER BY ?object + " }" + "} GROUP BY ?o"; private static final String SPARQL_SINGLE_SELF = "CONSTRUCT { ?object ?p ?o . }" + "WHERE {" + " { [[statements]] [[language]] [[filter]] }" + "} ORDER BY ?p"; /* * private fields */ private String[] statements; private boolean singleSelf = false; public SPARQLQuery(String... statements) { this.statements = statements; } public SPARQLQuery(boolean singleSelf, String... statements) { this.statements = statements; this.singleSelf = singleSelf; } public String generateContruct(RestRelation relation, RestParameters params, Map<String, String> bindings, boolean includePrefix) { String query = singleSelf ? SPARQL_SINGLE_SELF : SPARQL_CONSTRUCT; query = addPaging(query, params.getPerPage(), params.getPage()); query = addLanguageFilter(query, params); query = addFilters(query, generateFilters(relation, params)); query = addStatements(query, (String[]) ArrayUtils.addAll(statements, relation.getStatements(params).toArray())); query = addBindings(bindings, query); return includePrefix ? AHRDFNamespaces.getSPARQLPrefix() + query : query; } public String generateCount(RestRelation relation, RestParameters params, Map<String, String> bindings, boolean includePrefix) { String query = SPARQL_COUNT; query = query.replace(PAGING_PLACEMARK, ""); query = query.replace(LANGUAGE_PLACEMARK, ""); query = addFilters(query, generateFilters(relation, params)); query = addStatements(query, (String[]) ArrayUtils.addAll(statements, relation.getStatements(params).toArray())); query = addBindings(bindings, query); return includePrefix ? AHRDFNamespaces.getSPARQLPrefix() + query : query; } /* private String generateSPARQLBody(RestRelation relation, RestParameters params, Map<String, String> bindings, String query) { query = addPaging(query, params.getResultLimit(), params.getPage()); query = addLanguageFilter(query, params); query = addFilters(query, generateFilters(relation, params)); query = addStatements(query, (String[]) ArrayUtils.addAll(statements, relation.getStatements(params).toArray())); query = addBindings(bindings, query); return query; } */ private String addBindings(Map<String, String> bindings, String query) { Map<String, String> namespaces = AHRDFNamespaces.getNamespaces(); for (Map.Entry<String, String> entry : bindings.entrySet()) { String value = entry.getValue(); boolean addBrackets = true; if (value.contains(":")) { for (Entry<String, String> namespace : namespaces.entrySet()) { if (value.startsWith(namespace.getKey())) { addBrackets = false; break; } } } if (addBrackets) { value = "<" + value + ">"; } query = query.replace("?" + entry.getKey(), value); } return query; } public String[] getStatements() { return statements; } public void setStatements(String[] statements) { this.statements = statements; } private ArrayList<String> generateFilters(RestRelation relation, RestParameters params) { return relation.getFilters(params); } private String addStatements(String query, String... statements) { StringBuilder statementsString = new StringBuilder(); if (statements != null && statements.length > 0) { statementsString.append(statements[0]); for (int i = 1; i < statements.length; i++) { statementsString.append(" "); statementsString.append(statements[i]); } } return query.replace(STATEMENTS_PLACEMARK, statementsString); } private String addLanguageFilter(String query, RestParameters params) { ArrayList<String> filters = new ArrayList<String>(); String languageFilter = "!isLiteral(?o) || datatype(?o) != \"xsd:string\" || langMatches(lang(?o), ?lang ) || langMatches(lang(?o), \"\")"; languageFilter = languageFilter.replace("?lang", "\"" + params.getLanguageTag() + "\""); filters.add(languageFilter); return addFilters(query, LANGUAGE_PLACEMARK, filters); } private String addPaging(String query, long perPage, long page) { // TODO: check if count & page are valid long oldPerPage = perPage; if (perPage > MAXIMUM_PER_PAGE) { perPage = MAXIMUM_PER_PAGE; } if (page < 1) { page = 1; } return query.replace(PAGING_PLACEMARK, "LIMIT " + perPage + " OFFSET " + oldPerPage * (page - 1)); } private String addFilters(String query, ArrayList<String> filters) { return addFilters(query, FILTER_PLACEMARK, filters); } private String addFilters(String query, String placemark, ArrayList<String> filters) { StringBuilder filter = new StringBuilder(); if (filters != null && filters.size() > 0) { filter.append("FILTER("); filter.append("(" + filters.get(0) + ")"); for (int i = 1; i < filters.size(); i++) { filter.append(" && "); filter.append("(" + filters.get(i) + ")"); } filter.append(")"); } return query.replace(placemark, filter); } }
ORDER BY is needed to group objects together for REST API JSON results.
artsholland-core/src/main/java/org/waag/ah/rest/model/SPARQLQuery.java
ORDER BY is needed to group objects together for REST API JSON results.
<ide><path>rtsholland-core/src/main/java/org/waag/ah/rest/model/SPARQLQuery.java <ide> + " [[filter]]" <ide> + " } [[paging]]" //ORDER BY ?object <ide> + " } [[language]]" <del> + "}"; // ORDER BY ?object ?p <add> + "} ORDER BY ?object ?p"; <ide> <ide> private static final String SPARQL_COUNT = <ide> "SELECT (COUNT(?o) AS ?count)"
Java
apache-2.0
error: pathspec 'simulator/src/test/java/com/hazelcast/simulator/utils/ClassUtilsTest.java' did not match any file(s) known to git
cb171697a1e670e4236309529a4d4057b7a0cac0
1
jerrinot/hazelcast-stabilizer,hazelcast/hazelcast-simulator,hazelcast/hazelcast-simulator,pveentjer/hazelcast-simulator,jerrinot/hazelcast-stabilizer,hazelcast/hazelcast-simulator,pveentjer/hazelcast-simulator,Donnerbart/hazelcast-simulator,Donnerbart/hazelcast-simulator
package com.hazelcast.simulator.utils; import org.junit.Test; import static com.hazelcast.simulator.utils.ReflectionUtils.invokePrivateConstructor; public class ClassUtilsTest { @Test public void testConstructor() throws Exception { invokePrivateConstructor(ClassUtils.class); } }
simulator/src/test/java/com/hazelcast/simulator/utils/ClassUtilsTest.java
Fixed missing coverage of ClassUtils.
simulator/src/test/java/com/hazelcast/simulator/utils/ClassUtilsTest.java
Fixed missing coverage of ClassUtils.
<ide><path>imulator/src/test/java/com/hazelcast/simulator/utils/ClassUtilsTest.java <add>package com.hazelcast.simulator.utils; <add> <add>import org.junit.Test; <add> <add>import static com.hazelcast.simulator.utils.ReflectionUtils.invokePrivateConstructor; <add> <add>public class ClassUtilsTest { <add> <add> @Test <add> public void testConstructor() throws Exception { <add> invokePrivateConstructor(ClassUtils.class); <add> } <add>}
Java
apache-2.0
38e17bfa6b97b5c751694caab572f02fd0c7224b
0
amidst/code-examples
package eu.amidst.core.examples.huginlink; import junit.framework.TestCase; import org.junit.Test; public class HuginConversionExampleTest extends TestCase { @Test public void test() throws Exception { try { HuginConversionExample.main(null); }catch (UnsatisfiedLinkError err) { }catch (NoClassDefFoundError ex) { } } }
src/test/java/eu/amidst/core/examples/huginlink/HuginConversionExampleTest.java
package eu.amidst.core.examples.huginlink; import junit.framework.TestCase; import org.junit.Test; public class HuginConversionExampleTest extends TestCase { @Test public void test() throws Exception { try { HuginConversionExample.main(null); }catch (UnsatisfiedLinkError err) { } } }
Fixed NoClassDefFoundError in HuginConversionExample
src/test/java/eu/amidst/core/examples/huginlink/HuginConversionExampleTest.java
Fixed NoClassDefFoundError in HuginConversionExample
<ide><path>rc/test/java/eu/amidst/core/examples/huginlink/HuginConversionExampleTest.java <ide> HuginConversionExample.main(null); <ide> }catch (UnsatisfiedLinkError err) { <ide> <add> }catch (NoClassDefFoundError ex) { <add> <ide> } <ide> } <ide> }
Java
agpl-3.0
283999c87d2b5f28db933428eb28be0566bfa8be
0
scionaltera/emergentmud,scionaltera/emergentmud
/* * EmergentMUD - A modern MUD with a procedurally generated world. * Copyright (C) 2016-2017 Peter Keeler * * This file is part of EmergentMUD. * * EmergentMUD is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * EmergentMUD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.emergentmud.core.resource; import com.emergentmud.core.command.Command; import com.emergentmud.core.command.Emote; import com.emergentmud.core.exception.NoAccountException; import com.emergentmud.core.model.Account; import com.emergentmud.core.model.CommandMetadata; import com.emergentmud.core.model.EmoteMetadata; import com.emergentmud.core.model.Entity; import com.emergentmud.core.model.Essence; import com.emergentmud.core.model.Room; import com.emergentmud.core.model.SocialNetwork; import com.emergentmud.core.model.stomp.GameOutput; import com.emergentmud.core.repository.AccountRepository; import com.emergentmud.core.repository.CommandMetadataRepository; import com.emergentmud.core.repository.EmoteMetadataRepository; import com.emergentmud.core.repository.EntityRepository; import com.emergentmud.core.repository.EssenceRepository; import com.emergentmud.core.repository.RoomBuilder; import com.emergentmud.core.repository.WorldManager; import com.emergentmud.core.resource.model.PlayRequest; import com.emergentmud.core.util.EntityUtil; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.context.ApplicationContext; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; import org.springframework.ui.Model; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import static org.mockito.Mockito.*; import static org.junit.Assert.*; public class MainResourceTest { private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static final String NETWORK_NAME = "AlteraNet"; private static final String NETWORK_ID = "alteranet"; private static final String NETWORK_USER = "007"; private static final String ACCOUNT_ID = "1234567890"; @Mock private ApplicationContext applicationContext; @Mock private SecurityContextLogoutHandler securityContextLogoutHandler; @Mock private AccountRepository accountRepository; @Mock private EssenceRepository essenceRepository; @Mock private EntityRepository entityRepository; @Mock private CommandMetadataRepository commandMetadataRepository; @Mock private EmoteMetadataRepository emoteMetadataRepository; @Mock private RoomBuilder roomBuilder; @Mock private WorldManager worldManager; @Mock private EntityUtil entityUtil; @Mock private Emote emote; @Mock private HttpSession httpSession; @Mock private HttpServletRequest httpServletRequest; @Mock private OAuth2Authentication principal; @Mock private Model model; @Mock private PlayRequest playRequest; @Captor private ArgumentCaptor<Map<String, String>> mapCaptor; @Captor private ArgumentCaptor<GameOutput> outputCaptor; @Captor private ArgumentCaptor<Entity> entityCaptor; private Account account; private Essence essence; private List<SocialNetwork> socialNetworks = new ArrayList<>(); private List<Essence> essences = new ArrayList<>(); private List<EmoteMetadata> emoteMetadata = new ArrayList<>(); private MainResource mainResource; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); generateSocialNetworks(); account = generateAccount(); generateEssences(); essence = essences.get(0); generateEmoteMetadata(); when(worldManager.test(eq(0L), eq(0L), eq(0L))).thenReturn(true); when(httpSession.getAttribute(eq("social"))).thenReturn(NETWORK_ID); when(principal.getName()).thenReturn(NETWORK_USER); when(accountRepository.save(any(Account.class))).thenAnswer(invocation -> { Account account = (Account)invocation.getArguments()[0]; account.setId(UUID.randomUUID().toString()); return account; }); when(essenceRepository.save(any(Essence.class))).thenAnswer(invocation -> { Essence essence = (Essence)invocation.getArguments()[0]; essence.setId(UUID.randomUUID().toString()); return essence; }); when(entityRepository.save(any(Entity.class))).thenAnswer(invocation -> { Entity entity = (Entity)invocation.getArguments()[0]; entity.setId(UUID.randomUUID().toString()); return entity; }); when(accountRepository.findBySocialNetworkAndSocialNetworkId(eq(NETWORK_ID), eq(NETWORK_USER))).thenReturn(account); when(essenceRepository.findByAccountId(anyString())).thenReturn(essences); when(playRequest.getEssenceId()).thenReturn("essence0"); mainResource = new MainResource( applicationContext, socialNetworks, securityContextLogoutHandler, accountRepository, essenceRepository, entityRepository, commandMetadataRepository, emoteMetadataRepository, roomBuilder, worldManager, entityUtil, emote ); } @Test public void testIndexNotAuthenticated() throws Exception { String view = mainResource.index(httpSession, null, model); verify(model).addAttribute(eq("networks"), eq(socialNetworks)); verifyZeroInteractions(accountRepository); verifyZeroInteractions(essenceRepository); assertEquals("index", view); } @Test public void testIndexNewAccount() throws Exception { ArgumentCaptor<Account> accountCaptor = ArgumentCaptor.forClass(Account.class); when(accountRepository.findBySocialNetworkAndSocialNetworkId(eq(NETWORK_ID), eq(NETWORK_USER))).thenReturn(null); String view = mainResource.index(httpSession, principal, model); verify(model).addAttribute(eq("networks"), eq(socialNetworks)); verify(accountRepository).save(accountCaptor.capture()); verify(model).addAttribute(eq("account"), any(Account.class)); verify(model).addAttribute(eq("essences"), eq(essences)); assertEquals("essence", view); Account generated = accountCaptor.getValue(); assertEquals(NETWORK_ID, generated.getSocialNetwork()); assertEquals(NETWORK_USER, generated.getSocialNetworkId()); } @Test public void testIndexExistingAccount() throws Exception { String view = mainResource.index(httpSession, principal, model); verify(model).addAttribute(eq("networks"), eq(socialNetworks)); verify(accountRepository, never()).save(any(Account.class)); verify(account, never()).setSocialNetwork(anyString()); verify(account, never()).setSocialNetworkId(anyString()); verify(model).addAttribute(eq("account"), eq(account)); verify(model).addAttribute(eq("essences"), eq(essences)); assertEquals("essence", view); } @Test public void testSocial() throws Exception { String view = mainResource.social(NETWORK_ID, httpSession); verify(httpSession).setAttribute(eq("social"), eq(NETWORK_ID)); assertEquals("redirect:/login/" + NETWORK_ID, view); } @Test public void testNewEssence() throws Exception { String view = mainResource.newEssence(); assertEquals("new-essence", view); } @Test public void testSaveFirstNewEssence() throws Exception { when(essenceRepository.count()).thenReturn(0L); String view = mainResource.saveNewEssence(httpSession, principal, essence, model); verify(essence).setAccountId(eq(ACCOUNT_ID)); verify(essence).setAdmin(eq(true)); verify(essence).setCreationDate(anyLong()); assertEquals("redirect:/", view); } @Test public void testSaveNewEssence() throws Exception { when(essenceRepository.count()).thenReturn(100L); String view = mainResource.saveNewEssence(httpSession, principal, essence, model); verify(essence).setAccountId(eq(ACCOUNT_ID)); verify(essence, never()).setAdmin(anyBoolean()); verify(essence).setCreationDate(anyLong()); assertEquals("redirect:/", view); } @Test public void testSaveNewEssenceNameTooShort() throws Exception { when(essenceRepository.count()).thenReturn(100L); when(essence.getName()).thenReturn("A"); String view = mainResource.saveNewEssence(httpSession, principal, essence, model); verify(essence, never()).setAccountId(eq(ACCOUNT_ID)); verify(essence, never()).setAdmin(anyBoolean()); verify(model).addAttribute(eq("essenceName"), eq("A")); verify(model).addAttribute(eq("errorName"), anyString()); assertEquals("new-essence", view); } @Test public void testSaveNewEssenceNameTooLong() throws Exception { when(essenceRepository.count()).thenReturn(100L); when(essence.getName()).thenReturn("Supercalifragilisticexpealadocious"); String view = mainResource.saveNewEssence(httpSession, principal, essence, model); verify(essence, never()).setAccountId(eq(ACCOUNT_ID)); verify(essence, never()).setAdmin(anyBoolean()); verify(model).addAttribute(eq("essenceName"), eq("Supercalifragilisticexpealadocious")); verify(model).addAttribute(eq("errorName"), anyString()); assertEquals("new-essence", view); } @Test public void testSaveNewEssenceNameNotCapitalized() throws Exception { when(essenceRepository.count()).thenReturn(100L); when(essence.getName()).thenReturn("abraham"); String view = mainResource.saveNewEssence(httpSession, principal, essence, model); verify(essence, never()).setAccountId(eq(ACCOUNT_ID)); verify(essence, never()).setAdmin(anyBoolean()); verify(model).addAttribute(eq("essenceName"), eq("abraham")); verify(model).addAttribute(eq("errorName"), anyString()); assertEquals("new-essence", view); } @Test public void testSaveNewEssenceNameInvalidCharacters() throws Exception { when(essenceRepository.count()).thenReturn(100L); when(essence.getName()).thenReturn("Abra!ham"); String view = mainResource.saveNewEssence(httpSession, principal, essence, model); verify(essence, never()).setAccountId(eq(ACCOUNT_ID)); verify(essence, never()).setAdmin(anyBoolean()); verify(model).addAttribute(eq("essenceName"), eq("Abra!ham")); verify(model).addAttribute(eq("errorName"), anyString()); assertEquals("new-essence", view); } @Test public void testSaveNewEssenceNameStartsWithHyphen() throws Exception { when(essenceRepository.count()).thenReturn(100L); when(essence.getName()).thenReturn("-Abraham"); String view = mainResource.saveNewEssence(httpSession, principal, essence, model); verify(essence, never()).setAccountId(eq(ACCOUNT_ID)); verify(essence, never()).setAdmin(anyBoolean()); verify(model).addAttribute(eq("essenceName"), eq("-Abraham")); verify(model).addAttribute(eq("errorName"), anyString()); assertEquals("new-essence", view); } @Test public void testSaveNewEssenceNameStartsWithApostrophe() throws Exception { when(essenceRepository.count()).thenReturn(100L); when(essence.getName()).thenReturn("'Abraham"); String view = mainResource.saveNewEssence(httpSession, principal, essence, model); verify(essence, never()).setAccountId(eq(ACCOUNT_ID)); verify(essence, never()).setAdmin(anyBoolean()); verify(model).addAttribute(eq("essenceName"), eq("'Abraham")); verify(model).addAttribute(eq("errorName"), anyString()); assertEquals("new-essence", view); } @Test public void testSaveNewEssenceNameEndsWithHyphen() throws Exception { when(essenceRepository.count()).thenReturn(100L); when(essence.getName()).thenReturn("Abraham-"); String view = mainResource.saveNewEssence(httpSession, principal, essence, model); verify(essence, never()).setAccountId(eq(ACCOUNT_ID)); verify(essence, never()).setAdmin(anyBoolean()); verify(model).addAttribute(eq("essenceName"), eq("Abraham-")); verify(model).addAttribute(eq("errorName"), anyString()); assertEquals("new-essence", view); } @Test public void testSaveNewEssenceNameEndsWithApostrophe() throws Exception { when(essenceRepository.count()).thenReturn(100L); when(essence.getName()).thenReturn("Abraham'"); String view = mainResource.saveNewEssence(httpSession, principal, essence, model); verify(essence, never()).setAccountId(eq(ACCOUNT_ID)); verify(essence, never()).setAdmin(anyBoolean()); verify(model).addAttribute(eq("essenceName"), eq("Abraham'")); verify(model).addAttribute(eq("errorName"), anyString()); assertEquals("new-essence", view); } @Test public void testSaveNewEssenceNameMultipleSymbols1() throws Exception { when(essenceRepository.count()).thenReturn(100L); when(essence.getName()).thenReturn("Abra--ham"); String view = mainResource.saveNewEssence(httpSession, principal, essence, model); verify(essence, never()).setAccountId(eq(ACCOUNT_ID)); verify(essence, never()).setAdmin(anyBoolean()); verify(model).addAttribute(eq("essenceName"), eq("Abra--ham")); verify(model).addAttribute(eq("errorName"), anyString()); assertEquals("new-essence", view); } @Test public void testSaveNewEssenceNameMultipleSymbols2() throws Exception { when(essenceRepository.count()).thenReturn(100L); when(essence.getName()).thenReturn("Ab-ra-ham"); String view = mainResource.saveNewEssence(httpSession, principal, essence, model); verify(essence, never()).setAccountId(eq(ACCOUNT_ID)); verify(essence, never()).setAdmin(anyBoolean()); verify(model).addAttribute(eq("essenceName"), eq("Ab-ra-ham")); verify(model).addAttribute(eq("errorName"), anyString()); assertEquals("new-essence", view); } @Test(expected = NoAccountException.class) public void testSaveNewEssenceMissingAccount() throws Exception { when(accountRepository.findBySocialNetworkAndSocialNetworkId(eq(NETWORK_ID), eq(NETWORK_USER))).thenReturn(null); mainResource.saveNewEssence(httpSession, principal, essence, model); } @Test public void testPlayExisting() throws Exception { String view = mainResource.play(playRequest, httpSession, httpServletRequest, principal, model); Entity entity = essence.getEntity(); verify(roomBuilder, never()).generateRoom(eq(0L), eq(0L), eq(0L)); verify(entityUtil).sendMessageToRoom(any(Room.class), any(Entity.class), outputCaptor.capture()); verify(worldManager).put(eq(entity), eq(0L), eq(0L), eq(0L)); verify(httpSession).setAttribute(anyString(), mapCaptor.capture()); verify(model).addAttribute(eq("breadcrumb"), anyString()); verify(model).addAttribute(eq("account"), eq(account)); verify(model).addAttribute(eq("essence"), eq(essence)); assertEquals("play", view); GameOutput output = outputCaptor.getValue(); assertTrue(output.getOutput().get(0).startsWith("[yellow]")); Map<String, String> sessionMap = mapCaptor.getValue(); assertEquals(account.getId(), sessionMap.get("account")); assertEquals(essence.getId(), sessionMap.get("essence")); assertEquals(entity.getId(), sessionMap.get("entity")); } @Test public void testPlayNoWorld() throws Exception { when(worldManager.test(eq(0L), eq(0L), eq(0L))).thenReturn(false); String view = mainResource.play(playRequest, httpSession, httpServletRequest, principal, model); Entity entity = essence.getEntity(); verify(roomBuilder).generateRoom(eq(0L), eq(0L), eq(0L)); verify(entityUtil).sendMessageToRoom(any(Room.class), any(Entity.class), outputCaptor.capture()); verify(worldManager).put(eq(entity), eq(0L), eq(0L), eq(0L)); verify(httpSession).setAttribute(anyString(), mapCaptor.capture()); verify(model).addAttribute(eq("breadcrumb"), anyString()); verify(model).addAttribute(eq("account"), eq(account)); verify(model).addAttribute(eq("essence"), eq(essence)); assertEquals("play", view); Map<String, String> sessionMap = mapCaptor.getValue(); assertEquals(account.getId(), sessionMap.get("account")); assertEquals(essence.getId(), sessionMap.get("essence")); assertEquals(entity.getId(), sessionMap.get("entity")); } @Test public void testPlayNoId() throws Exception { when(playRequest.getEssenceId()).thenReturn(null); String view = mainResource.play(playRequest, httpSession, httpServletRequest, principal, model); verifyZeroInteractions(model); verifyZeroInteractions(httpSession); assertEquals("redirect:/", view); } @Test public void testPlayNoAccount() throws Exception { when(accountRepository.findBySocialNetworkAndSocialNetworkId(eq(NETWORK_ID), eq(NETWORK_USER))).thenReturn(null); String view = mainResource.play(playRequest, httpSession, httpServletRequest, principal, model); verify(httpSession).getAttribute(eq("social")); verifyNoMoreInteractions(httpSession); verifyZeroInteractions(model); assertEquals("redirect:/", view); } @Test public void testPlayNoEssence() throws Exception { when(essenceRepository.findByAccountId(anyString())).thenReturn(new ArrayList<>()); String view = mainResource.play(playRequest, httpSession, httpServletRequest, principal, model); verify(httpSession).getAttribute(eq("social")); verifyNoMoreInteractions(httpSession); verifyZeroInteractions(model); assertEquals("redirect:/", view); } @Test public void testPlayNoEntity() throws Exception { Essence essence1 = essences.get(1); when(essence1.getEntity()).thenReturn(null); when(playRequest.getEssenceId()).thenReturn("essence1"); String view = mainResource.play(playRequest, httpSession, httpServletRequest, principal, model); verify(entityUtil).sendMessageToRoom(any(Room.class), any(Entity.class), outputCaptor.capture()); verify(entityRepository).save(any(Entity.class)); verify(essence1).setEntity(any(Entity.class)); verify(essenceRepository).save(eq(essence1)); verify(worldManager).put(any(Entity.class), eq(0L), eq(0L), eq(0L)); verify(httpSession).setAttribute(anyString(), mapCaptor.capture()); verify(model).addAttribute(eq("breadcrumb"), anyString()); verify(model).addAttribute(eq("account"), eq(account)); verify(model).addAttribute(eq("essence"), eq(essence1)); assertEquals("play", view); GameOutput output = outputCaptor.getValue(); assertTrue(output.getOutput().get(0).startsWith("[yellow]")); Map<String, String> sessionMap = mapCaptor.getValue(); assertEquals(account.getId(), sessionMap.get("account")); assertEquals(essence1.getId(), sessionMap.get("essence")); assertTrue(sessionMap.containsKey("entity")); } @Test public void testPlayReconnect() throws Exception { Room room = mock(Room.class); Essence essence0 = essences.get(0); Entity entity0 = essence0.getEntity(); when(entity0.getRoom()).thenReturn(room); when(entity0.getStompSessionId()).thenReturn("stompSessionId"); when(entity0.getStompUsername()).thenReturn("stompUsername"); String view = mainResource.play(playRequest, httpSession, httpServletRequest, principal, model); verify(entityUtil).sendMessageToEntity(any(Entity.class), outputCaptor.capture()); verify(worldManager).put(any(Entity.class), eq(0L), eq(0L), eq(0L)); verify(httpSession).setAttribute(anyString(), mapCaptor.capture()); verify(model).addAttribute(eq("breadcrumb"), anyString()); verify(model).addAttribute(eq("account"), eq(account)); verify(model).addAttribute(eq("essence"), eq(essence)); assertEquals("play", view); GameOutput output = outputCaptor.getValue(); assertTrue(output.getOutput().get(0).startsWith("[red]")); } @Test public void testCommandsNotAuthenticated() throws Exception { List<CommandMetadata> metadata = generateCommandMetadata(false); when(commandMetadataRepository.findByAdmin(eq(false))).thenReturn(metadata); String view = mainResource.commands(model, null, httpSession); verifyZeroInteractions(httpSession); verify(commandMetadataRepository).findByAdmin(eq(false)); verify(applicationContext, times(5)).getBean(startsWith("command")); verify(model).addAttribute(eq("metadataList"), anyListOf(CommandMetadata.class)); verify(model).addAttribute(eq("commandMap"), anyMapOf(String.class, Command.class)); assertEquals("commands", view); } @Test public void testCommandsAuthenticatedNoAdmins() throws Exception { List<CommandMetadata> metadata = generateCommandMetadata(false); when(commandMetadataRepository.findByAdmin(eq(false))).thenReturn(metadata); when(httpSession.getAttribute(eq("social"))).thenReturn("alteraBook"); when(principal.getName()).thenReturn("2928749020"); when(accountRepository.findBySocialNetworkAndSocialNetworkId(eq("alteraBook"), eq("2928749020"))).thenReturn(account); when(account.getId()).thenReturn("accountId"); when(essenceRepository.findByAccountId(eq("accountId"))).thenReturn(essences); String view = mainResource.commands(model, principal, httpSession); verify(httpSession).getAttribute(eq("social")); verify(commandMetadataRepository).findByAdmin(eq(false)); verify(applicationContext, times(5)).getBean(startsWith("command")); verify(model).addAttribute(eq("metadataList"), anyListOf(CommandMetadata.class)); verify(model).addAttribute(eq("commandMap"), anyMapOf(String.class, Command.class)); assertEquals("commands", view); } @Test public void testCommandsAuthenticatedWithAdmins() throws Exception { List<CommandMetadata> metadata = generateCommandMetadata(true); when(commandMetadataRepository.findAll()).thenReturn(metadata); when(httpSession.getAttribute(eq("social"))).thenReturn("alteraBook"); when(principal.getName()).thenReturn("2928749020"); when(accountRepository.findBySocialNetworkAndSocialNetworkId(eq("alteraBook"), eq("2928749020"))).thenReturn(account); when(account.getId()).thenReturn("accountId"); when(essences.get(2).isAdmin()).thenReturn(true); when(essenceRepository.findByAccountId(eq("accountId"))).thenReturn(essences); String view = mainResource.commands(model, principal, httpSession); verify(httpSession).getAttribute(eq("social")); verify(commandMetadataRepository).findAll(); verify(applicationContext, times(5)).getBean(startsWith("command")); verify(model).addAttribute(eq("metadataList"), anyListOf(CommandMetadata.class)); verify(model).addAttribute(eq("commandMap"), anyMapOf(String.class, Command.class)); assertEquals("commands", view); } @Test public void testEmotesNotAuthenticated() throws Exception { when(emoteMetadataRepository.findAll()).thenReturn(emoteMetadata); String view = mainResource.emotes(model, null, httpSession); verify(emoteMetadataRepository).findAll(); verifyZeroInteractions(httpSession); verify(model).addAttribute(eq("self"), entityCaptor.capture()); verify(model).addAttribute(eq("target"), entityCaptor.capture()); verify(model).addAttribute(eq("metadataList"), anyListOf(EmoteMetadata.class)); verify(model).addAttribute(eq("emoteMap"), anyMapOf(String.class, EmoteMetadata.class)); verifyAllEmoteMetadata(emoteMetadata); List<Entity> captures = entityCaptor.getAllValues(); assertEquals("emotes", view); assertEquals("Alice", captures.get(0).getName()); assertEquals("Bob", captures.get(1).getName()); } @Test public void testEmotesAuthenticatedNoEssences() throws Exception { when(emoteMetadataRepository.findAll()).thenReturn(emoteMetadata); when(httpSession.getAttribute(eq("social"))).thenReturn("social"); when(principal.getName()).thenReturn("principal"); when(accountRepository.findBySocialNetworkAndSocialNetworkId(eq("social"), eq("principal"))).thenReturn(account); when(account.getId()).thenReturn("accountId"); when(essenceRepository.findByAccountId(eq("accountId"))).thenReturn(new ArrayList<>()); String view = mainResource.emotes(model, principal, httpSession); verify(emoteMetadataRepository).findAll(); verify(httpSession).getAttribute(eq("social")); verify(model).addAttribute(eq("self"), entityCaptor.capture()); verify(model).addAttribute(eq("target"), entityCaptor.capture()); verify(model).addAttribute(eq("metadataList"), anyListOf(EmoteMetadata.class)); verify(model).addAttribute(eq("emoteMap"), anyMapOf(String.class, EmoteMetadata.class)); verifyAllEmoteMetadata(emoteMetadata); List<Entity> captures = entityCaptor.getAllValues(); assertEquals("emotes", view); assertEquals("Alice", captures.get(0).getName()); assertEquals("Bob", captures.get(1).getName()); } @Test public void testEmotesAuthenticatedOneEssence() throws Exception { ArrayList<Essence> oneEssence = new ArrayList<>(); oneEssence.add(essences.get(0)); when(emoteMetadataRepository.findAll()).thenReturn(emoteMetadata); when(httpSession.getAttribute(eq("social"))).thenReturn("social"); when(principal.getName()).thenReturn("principal"); when(accountRepository.findBySocialNetworkAndSocialNetworkId(eq("social"), eq("principal"))).thenReturn(account); when(account.getId()).thenReturn("accountId"); when(essenceRepository.findByAccountId(eq("accountId"))).thenReturn(oneEssence); String view = mainResource.emotes(model, principal, httpSession); verify(emoteMetadataRepository).findAll(); verify(httpSession).getAttribute(eq("social")); verify(model).addAttribute(eq("self"), entityCaptor.capture()); verify(model).addAttribute(eq("target"), entityCaptor.capture()); verify(model).addAttribute(eq("metadataList"), anyListOf(EmoteMetadata.class)); verify(model).addAttribute(eq("emoteMap"), anyMapOf(String.class, EmoteMetadata.class)); verifyAllEmoteMetadata(emoteMetadata); List<Entity> captures = entityCaptor.getAllValues(); assertEquals("emotes", view); assertEquals("EssenceA", captures.get(0).getName()); assertEquals("Bob", captures.get(1).getName()); } @Test public void testEmotesAuthenticatedTwoEssences() throws Exception { ArrayList<Essence> twoEssences = new ArrayList<>(); twoEssences.add(essences.get(0)); twoEssences.add(essences.get(1)); when(emoteMetadataRepository.findAll()).thenReturn(emoteMetadata); when(httpSession.getAttribute(eq("social"))).thenReturn("social"); when(principal.getName()).thenReturn("principal"); when(accountRepository.findBySocialNetworkAndSocialNetworkId(eq("social"), eq("principal"))).thenReturn(account); when(account.getId()).thenReturn("accountId"); when(essenceRepository.findByAccountId(eq("accountId"))).thenReturn(twoEssences); String view = mainResource.emotes(model, principal, httpSession); verify(emoteMetadataRepository).findAll(); verify(httpSession).getAttribute(eq("social")); verify(model).addAttribute(eq("self"), entityCaptor.capture()); verify(model).addAttribute(eq("target"), entityCaptor.capture()); verify(model).addAttribute(eq("metadataList"), anyListOf(EmoteMetadata.class)); verify(model).addAttribute(eq("emoteMap"), anyMapOf(String.class, EmoteMetadata.class)); verifyAllEmoteMetadata(emoteMetadata); List<Entity> captures = entityCaptor.getAllValues(); assertEquals("emotes", view); assertEquals("EssenceA", captures.get(0).getName()); assertEquals("EssenceB", captures.get(1).getName()); } @Test public void testLogout() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); String view = mainResource.logout(request, response, httpSession, principal); verify(securityContextLogoutHandler).logout(eq(request), eq(response), any(Authentication.class)); assertEquals("redirect:/", view); } private void generateSocialNetworks() { socialNetworks.add(new SocialNetwork(NETWORK_ID, NETWORK_NAME)); } private Account generateAccount() { Account account = mock(Account.class); when(account.getId()).thenReturn(ACCOUNT_ID); when(account.getSocialNetwork()).thenReturn(NETWORK_ID); when(account.getSocialNetworkId()).thenReturn(NETWORK_USER); return account; } private void generateEssences() { for (int i = 0; i < 3; i++) { Essence essence = mock(Essence.class); Entity entity = mock(Entity.class); when(essence.getId()).thenReturn("essence" + i); when(essence.getName()).thenReturn("Essence" + ALPHABET.charAt(i)); when(essence.getAccountId()).thenReturn(ACCOUNT_ID); when(essence.getEntity()).thenReturn(entity); when(entity.getId()).thenReturn("entity" + i); when(entity.getName()).thenReturn("Entity" + ALPHABET.charAt(i)); essences.add(essence); } } private List<CommandMetadata> generateCommandMetadata(boolean admin) { List<CommandMetadata> commandMetadata = new ArrayList<>(); for (int i = 0; i < 5; i++) { CommandMetadata metadata = mock(CommandMetadata.class); Command command = mock(Command.class); when(metadata.getBeanName()).thenReturn("command" + ALPHABET.charAt(i)); when(metadata.getName()).thenReturn("command" + ALPHABET.charAt(i)); if (admin) { when(metadata.isAdmin()).thenReturn(i % 2 == 0); } else { when(metadata.isAdmin()).thenReturn(false); } when(applicationContext.getBean(eq(metadata.getBeanName()))).thenReturn(command); commandMetadata.add(metadata); } return commandMetadata; } private void generateEmoteMetadata() { for (int i = 0; i < 5; i++) { EmoteMetadata metadata = mock(EmoteMetadata.class); emoteMetadata.add(metadata); } } private void verifyAllEmoteMetadata(List<EmoteMetadata> metadata) { metadata.forEach(m -> { verify(m).setToSelfUntargeted(anyString()); verify(m).setToRoomUntargeted(anyString()); verify(m).setToSelfWithTarget(anyString()); verify(m).setToTarget(anyString()); verify(m).setToRoomWithTarget(anyString()); verify(m).setToSelfAsTarget(anyString()); verify(m).setToRoomTargetingSelf(anyString()); }); } }
src/test/java/com/emergentmud/core/resource/MainResourceTest.java
/* * EmergentMUD - A modern MUD with a procedurally generated world. * Copyright (C) 2016-2017 Peter Keeler * * This file is part of EmergentMUD. * * EmergentMUD is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * EmergentMUD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.emergentmud.core.resource; import com.emergentmud.core.command.Command; import com.emergentmud.core.command.Emote; import com.emergentmud.core.exception.NoAccountException; import com.emergentmud.core.model.Account; import com.emergentmud.core.model.CommandMetadata; import com.emergentmud.core.model.EmoteMetadata; import com.emergentmud.core.model.Entity; import com.emergentmud.core.model.Essence; import com.emergentmud.core.model.Room; import com.emergentmud.core.model.SocialNetwork; import com.emergentmud.core.model.stomp.GameOutput; import com.emergentmud.core.repository.AccountRepository; import com.emergentmud.core.repository.CommandMetadataRepository; import com.emergentmud.core.repository.EmoteMetadataRepository; import com.emergentmud.core.repository.EntityRepository; import com.emergentmud.core.repository.EssenceRepository; import com.emergentmud.core.repository.RoomBuilder; import com.emergentmud.core.repository.WorldManager; import com.emergentmud.core.resource.model.PlayRequest; import com.emergentmud.core.util.EntityUtil; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.context.ApplicationContext; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; import org.springframework.ui.Model; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import static org.mockito.Mockito.*; import static org.junit.Assert.*; public class MainResourceTest { private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static final String NETWORK_NAME = "AlteraNet"; private static final String NETWORK_ID = "alteranet"; private static final String NETWORK_USER = "007"; private static final String ACCOUNT_ID = "1234567890"; @Mock private ApplicationContext applicationContext; @Mock private SecurityContextLogoutHandler securityContextLogoutHandler; @Mock private AccountRepository accountRepository; @Mock private EssenceRepository essenceRepository; @Mock private EntityRepository entityRepository; @Mock private CommandMetadataRepository commandMetadataRepository; @Mock private EmoteMetadataRepository emoteMetadataRepository; @Mock private RoomBuilder roomBuilder; @Mock private WorldManager worldManager; @Mock private EntityUtil entityUtil; @Mock private Emote emote; @Mock private HttpSession httpSession; @Mock private OAuth2Authentication principal; @Mock private Model model; @Mock private PlayRequest playRequest; @Captor private ArgumentCaptor<Map<String, String>> mapCaptor; @Captor private ArgumentCaptor<GameOutput> outputCaptor; @Captor private ArgumentCaptor<Entity> entityCaptor; private Account account; private Essence essence; private List<SocialNetwork> socialNetworks = new ArrayList<>(); private List<Essence> essences = new ArrayList<>(); private List<EmoteMetadata> emoteMetadata = new ArrayList<>(); private MainResource mainResource; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); generateSocialNetworks(); account = generateAccount(); generateEssences(); essence = essences.get(0); generateEmoteMetadata(); when(worldManager.test(eq(0L), eq(0L), eq(0L))).thenReturn(true); when(httpSession.getAttribute(eq("social"))).thenReturn(NETWORK_ID); when(principal.getName()).thenReturn(NETWORK_USER); when(accountRepository.save(any(Account.class))).thenAnswer(invocation -> { Account account = (Account)invocation.getArguments()[0]; account.setId(UUID.randomUUID().toString()); return account; }); when(essenceRepository.save(any(Essence.class))).thenAnswer(invocation -> { Essence essence = (Essence)invocation.getArguments()[0]; essence.setId(UUID.randomUUID().toString()); return essence; }); when(entityRepository.save(any(Entity.class))).thenAnswer(invocation -> { Entity entity = (Entity)invocation.getArguments()[0]; entity.setId(UUID.randomUUID().toString()); return entity; }); when(accountRepository.findBySocialNetworkAndSocialNetworkId(eq(NETWORK_ID), eq(NETWORK_USER))).thenReturn(account); when(essenceRepository.findByAccountId(anyString())).thenReturn(essences); when(playRequest.getEssenceId()).thenReturn("essence0"); mainResource = new MainResource( applicationContext, socialNetworks, securityContextLogoutHandler, accountRepository, essenceRepository, entityRepository, commandMetadataRepository, emoteMetadataRepository, roomBuilder, worldManager, entityUtil, emote ); } @Test public void testIndexNotAuthenticated() throws Exception { String view = mainResource.index(httpSession, null, model); verify(model).addAttribute(eq("networks"), eq(socialNetworks)); verifyZeroInteractions(accountRepository); verifyZeroInteractions(essenceRepository); assertEquals("index", view); } @Test public void testIndexNewAccount() throws Exception { ArgumentCaptor<Account> accountCaptor = ArgumentCaptor.forClass(Account.class); when(accountRepository.findBySocialNetworkAndSocialNetworkId(eq(NETWORK_ID), eq(NETWORK_USER))).thenReturn(null); String view = mainResource.index(httpSession, principal, model); verify(model).addAttribute(eq("networks"), eq(socialNetworks)); verify(accountRepository).save(accountCaptor.capture()); verify(model).addAttribute(eq("account"), any(Account.class)); verify(model).addAttribute(eq("essences"), eq(essences)); assertEquals("essence", view); Account generated = accountCaptor.getValue(); assertEquals(NETWORK_ID, generated.getSocialNetwork()); assertEquals(NETWORK_USER, generated.getSocialNetworkId()); } @Test public void testIndexExistingAccount() throws Exception { String view = mainResource.index(httpSession, principal, model); verify(model).addAttribute(eq("networks"), eq(socialNetworks)); verify(accountRepository, never()).save(any(Account.class)); verify(account, never()).setSocialNetwork(anyString()); verify(account, never()).setSocialNetworkId(anyString()); verify(model).addAttribute(eq("account"), eq(account)); verify(model).addAttribute(eq("essences"), eq(essences)); assertEquals("essence", view); } @Test public void testSocial() throws Exception { String view = mainResource.social(NETWORK_ID, httpSession); verify(httpSession).setAttribute(eq("social"), eq(NETWORK_ID)); assertEquals("redirect:/login/" + NETWORK_ID, view); } @Test public void testNewEssence() throws Exception { String view = mainResource.newEssence(); assertEquals("new-essence", view); } @Test public void testSaveFirstNewEssence() throws Exception { when(essenceRepository.count()).thenReturn(0L); String view = mainResource.saveNewEssence(httpSession, principal, essence, model); verify(essence).setAccountId(eq(ACCOUNT_ID)); verify(essence).setAdmin(eq(true)); verify(essence).setCreationDate(anyLong()); assertEquals("redirect:/", view); } @Test public void testSaveNewEssence() throws Exception { when(essenceRepository.count()).thenReturn(100L); String view = mainResource.saveNewEssence(httpSession, principal, essence, model); verify(essence).setAccountId(eq(ACCOUNT_ID)); verify(essence, never()).setAdmin(anyBoolean()); verify(essence).setCreationDate(anyLong()); assertEquals("redirect:/", view); } @Test public void testSaveNewEssenceNameTooShort() throws Exception { when(essenceRepository.count()).thenReturn(100L); when(essence.getName()).thenReturn("A"); String view = mainResource.saveNewEssence(httpSession, principal, essence, model); verify(essence, never()).setAccountId(eq(ACCOUNT_ID)); verify(essence, never()).setAdmin(anyBoolean()); verify(model).addAttribute(eq("essenceName"), eq("A")); verify(model).addAttribute(eq("errorName"), anyString()); assertEquals("new-essence", view); } @Test public void testSaveNewEssenceNameTooLong() throws Exception { when(essenceRepository.count()).thenReturn(100L); when(essence.getName()).thenReturn("Supercalifragilisticexpealadocious"); String view = mainResource.saveNewEssence(httpSession, principal, essence, model); verify(essence, never()).setAccountId(eq(ACCOUNT_ID)); verify(essence, never()).setAdmin(anyBoolean()); verify(model).addAttribute(eq("essenceName"), eq("Supercalifragilisticexpealadocious")); verify(model).addAttribute(eq("errorName"), anyString()); assertEquals("new-essence", view); } @Test public void testSaveNewEssenceNameNotCapitalized() throws Exception { when(essenceRepository.count()).thenReturn(100L); when(essence.getName()).thenReturn("abraham"); String view = mainResource.saveNewEssence(httpSession, principal, essence, model); verify(essence, never()).setAccountId(eq(ACCOUNT_ID)); verify(essence, never()).setAdmin(anyBoolean()); verify(model).addAttribute(eq("essenceName"), eq("abraham")); verify(model).addAttribute(eq("errorName"), anyString()); assertEquals("new-essence", view); } @Test public void testSaveNewEssenceNameInvalidCharacters() throws Exception { when(essenceRepository.count()).thenReturn(100L); when(essence.getName()).thenReturn("Abra!ham"); String view = mainResource.saveNewEssence(httpSession, principal, essence, model); verify(essence, never()).setAccountId(eq(ACCOUNT_ID)); verify(essence, never()).setAdmin(anyBoolean()); verify(model).addAttribute(eq("essenceName"), eq("Abra!ham")); verify(model).addAttribute(eq("errorName"), anyString()); assertEquals("new-essence", view); } @Test public void testSaveNewEssenceNameStartsWithHyphen() throws Exception { when(essenceRepository.count()).thenReturn(100L); when(essence.getName()).thenReturn("-Abraham"); String view = mainResource.saveNewEssence(httpSession, principal, essence, model); verify(essence, never()).setAccountId(eq(ACCOUNT_ID)); verify(essence, never()).setAdmin(anyBoolean()); verify(model).addAttribute(eq("essenceName"), eq("-Abraham")); verify(model).addAttribute(eq("errorName"), anyString()); assertEquals("new-essence", view); } @Test public void testSaveNewEssenceNameStartsWithApostrophe() throws Exception { when(essenceRepository.count()).thenReturn(100L); when(essence.getName()).thenReturn("'Abraham"); String view = mainResource.saveNewEssence(httpSession, principal, essence, model); verify(essence, never()).setAccountId(eq(ACCOUNT_ID)); verify(essence, never()).setAdmin(anyBoolean()); verify(model).addAttribute(eq("essenceName"), eq("'Abraham")); verify(model).addAttribute(eq("errorName"), anyString()); assertEquals("new-essence", view); } @Test public void testSaveNewEssenceNameEndsWithHyphen() throws Exception { when(essenceRepository.count()).thenReturn(100L); when(essence.getName()).thenReturn("Abraham-"); String view = mainResource.saveNewEssence(httpSession, principal, essence, model); verify(essence, never()).setAccountId(eq(ACCOUNT_ID)); verify(essence, never()).setAdmin(anyBoolean()); verify(model).addAttribute(eq("essenceName"), eq("Abraham-")); verify(model).addAttribute(eq("errorName"), anyString()); assertEquals("new-essence", view); } @Test public void testSaveNewEssenceNameEndsWithApostrophe() throws Exception { when(essenceRepository.count()).thenReturn(100L); when(essence.getName()).thenReturn("Abraham'"); String view = mainResource.saveNewEssence(httpSession, principal, essence, model); verify(essence, never()).setAccountId(eq(ACCOUNT_ID)); verify(essence, never()).setAdmin(anyBoolean()); verify(model).addAttribute(eq("essenceName"), eq("Abraham'")); verify(model).addAttribute(eq("errorName"), anyString()); assertEquals("new-essence", view); } @Test public void testSaveNewEssenceNameMultipleSymbols1() throws Exception { when(essenceRepository.count()).thenReturn(100L); when(essence.getName()).thenReturn("Abra--ham"); String view = mainResource.saveNewEssence(httpSession, principal, essence, model); verify(essence, never()).setAccountId(eq(ACCOUNT_ID)); verify(essence, never()).setAdmin(anyBoolean()); verify(model).addAttribute(eq("essenceName"), eq("Abra--ham")); verify(model).addAttribute(eq("errorName"), anyString()); assertEquals("new-essence", view); } @Test public void testSaveNewEssenceNameMultipleSymbols2() throws Exception { when(essenceRepository.count()).thenReturn(100L); when(essence.getName()).thenReturn("Ab-ra-ham"); String view = mainResource.saveNewEssence(httpSession, principal, essence, model); verify(essence, never()).setAccountId(eq(ACCOUNT_ID)); verify(essence, never()).setAdmin(anyBoolean()); verify(model).addAttribute(eq("essenceName"), eq("Ab-ra-ham")); verify(model).addAttribute(eq("errorName"), anyString()); assertEquals("new-essence", view); } @Test(expected = NoAccountException.class) public void testSaveNewEssenceMissingAccount() throws Exception { when(accountRepository.findBySocialNetworkAndSocialNetworkId(eq(NETWORK_ID), eq(NETWORK_USER))).thenReturn(null); mainResource.saveNewEssence(httpSession, principal, essence, model); } @Test public void testPlayExisting() throws Exception { String view = mainResource.play(playRequest, httpSession, principal, model); Entity entity = essence.getEntity(); verify(roomBuilder, never()).generateRoom(eq(0L), eq(0L), eq(0L)); verify(entityUtil).sendMessageToRoom(any(Room.class), any(Entity.class), outputCaptor.capture()); verify(worldManager).put(eq(entity), eq(0L), eq(0L), eq(0L)); verify(httpSession).setAttribute(anyString(), mapCaptor.capture()); verify(model).addAttribute(eq("breadcrumb"), anyString()); verify(model).addAttribute(eq("account"), eq(account)); verify(model).addAttribute(eq("essence"), eq(essence)); assertEquals("play", view); GameOutput output = outputCaptor.getValue(); assertTrue(output.getOutput().get(0).startsWith("[yellow]")); Map<String, String> sessionMap = mapCaptor.getValue(); assertEquals(account.getId(), sessionMap.get("account")); assertEquals(essence.getId(), sessionMap.get("essence")); assertEquals(entity.getId(), sessionMap.get("entity")); } @Test public void testPlayNoWorld() throws Exception { when(worldManager.test(eq(0L), eq(0L), eq(0L))).thenReturn(false); String view = mainResource.play(playRequest, httpSession, principal, model); Entity entity = essence.getEntity(); verify(roomBuilder).generateRoom(eq(0L), eq(0L), eq(0L)); verify(entityUtil).sendMessageToRoom(any(Room.class), any(Entity.class), outputCaptor.capture()); verify(worldManager).put(eq(entity), eq(0L), eq(0L), eq(0L)); verify(httpSession).setAttribute(anyString(), mapCaptor.capture()); verify(model).addAttribute(eq("breadcrumb"), anyString()); verify(model).addAttribute(eq("account"), eq(account)); verify(model).addAttribute(eq("essence"), eq(essence)); assertEquals("play", view); Map<String, String> sessionMap = mapCaptor.getValue(); assertEquals(account.getId(), sessionMap.get("account")); assertEquals(essence.getId(), sessionMap.get("essence")); assertEquals(entity.getId(), sessionMap.get("entity")); } @Test public void testPlayNoId() throws Exception { when(playRequest.getEssenceId()).thenReturn(null); String view = mainResource.play(playRequest, httpSession, principal, model); verifyZeroInteractions(model); verifyZeroInteractions(httpSession); assertEquals("redirect:/", view); } @Test public void testPlayNoAccount() throws Exception { when(accountRepository.findBySocialNetworkAndSocialNetworkId(eq(NETWORK_ID), eq(NETWORK_USER))).thenReturn(null); String view = mainResource.play(playRequest, httpSession, principal, model); verify(httpSession).getAttribute(eq("social")); verifyNoMoreInteractions(httpSession); verifyZeroInteractions(model); assertEquals("redirect:/", view); } @Test public void testPlayNoEssence() throws Exception { when(essenceRepository.findByAccountId(anyString())).thenReturn(new ArrayList<>()); String view = mainResource.play(playRequest, httpSession, principal, model); verify(httpSession).getAttribute(eq("social")); verifyNoMoreInteractions(httpSession); verifyZeroInteractions(model); assertEquals("redirect:/", view); } @Test public void testPlayNoEntity() throws Exception { Essence essence1 = essences.get(1); when(essence1.getEntity()).thenReturn(null); when(playRequest.getEssenceId()).thenReturn("essence1"); String view = mainResource.play(playRequest, httpSession, principal, model); verify(entityUtil).sendMessageToRoom(any(Room.class), any(Entity.class), outputCaptor.capture()); verify(entityRepository).save(any(Entity.class)); verify(essence1).setEntity(any(Entity.class)); verify(essenceRepository).save(eq(essence1)); verify(worldManager).put(any(Entity.class), eq(0L), eq(0L), eq(0L)); verify(httpSession).setAttribute(anyString(), mapCaptor.capture()); verify(model).addAttribute(eq("breadcrumb"), anyString()); verify(model).addAttribute(eq("account"), eq(account)); verify(model).addAttribute(eq("essence"), eq(essence1)); assertEquals("play", view); GameOutput output = outputCaptor.getValue(); assertTrue(output.getOutput().get(0).startsWith("[yellow]")); Map<String, String> sessionMap = mapCaptor.getValue(); assertEquals(account.getId(), sessionMap.get("account")); assertEquals(essence1.getId(), sessionMap.get("essence")); assertTrue(sessionMap.containsKey("entity")); } @Test public void testPlayReconnect() throws Exception { Room room = mock(Room.class); Essence essence0 = essences.get(0); Entity entity0 = essence0.getEntity(); when(entity0.getRoom()).thenReturn(room); when(entity0.getStompSessionId()).thenReturn("stompSessionId"); when(entity0.getStompUsername()).thenReturn("stompUsername"); String view = mainResource.play(playRequest, httpSession, principal, model); verify(entityUtil).sendMessageToEntity(any(Entity.class), outputCaptor.capture()); verify(worldManager).put(any(Entity.class), eq(0L), eq(0L), eq(0L)); verify(httpSession).setAttribute(anyString(), mapCaptor.capture()); verify(model).addAttribute(eq("breadcrumb"), anyString()); verify(model).addAttribute(eq("account"), eq(account)); verify(model).addAttribute(eq("essence"), eq(essence)); assertEquals("play", view); GameOutput output = outputCaptor.getValue(); assertTrue(output.getOutput().get(0).startsWith("[red]")); } @Test public void testCommandsNotAuthenticated() throws Exception { List<CommandMetadata> metadata = generateCommandMetadata(false); when(commandMetadataRepository.findByAdmin(eq(false))).thenReturn(metadata); String view = mainResource.commands(model, null, httpSession); verifyZeroInteractions(httpSession); verify(commandMetadataRepository).findByAdmin(eq(false)); verify(applicationContext, times(5)).getBean(startsWith("command")); verify(model).addAttribute(eq("metadataList"), anyListOf(CommandMetadata.class)); verify(model).addAttribute(eq("commandMap"), anyMapOf(String.class, Command.class)); assertEquals("commands", view); } @Test public void testCommandsAuthenticatedNoAdmins() throws Exception { List<CommandMetadata> metadata = generateCommandMetadata(false); when(commandMetadataRepository.findByAdmin(eq(false))).thenReturn(metadata); when(httpSession.getAttribute(eq("social"))).thenReturn("alteraBook"); when(principal.getName()).thenReturn("2928749020"); when(accountRepository.findBySocialNetworkAndSocialNetworkId(eq("alteraBook"), eq("2928749020"))).thenReturn(account); when(account.getId()).thenReturn("accountId"); when(essenceRepository.findByAccountId(eq("accountId"))).thenReturn(essences); String view = mainResource.commands(model, principal, httpSession); verify(httpSession).getAttribute(eq("social")); verify(commandMetadataRepository).findByAdmin(eq(false)); verify(applicationContext, times(5)).getBean(startsWith("command")); verify(model).addAttribute(eq("metadataList"), anyListOf(CommandMetadata.class)); verify(model).addAttribute(eq("commandMap"), anyMapOf(String.class, Command.class)); assertEquals("commands", view); } @Test public void testCommandsAuthenticatedWithAdmins() throws Exception { List<CommandMetadata> metadata = generateCommandMetadata(true); when(commandMetadataRepository.findAll()).thenReturn(metadata); when(httpSession.getAttribute(eq("social"))).thenReturn("alteraBook"); when(principal.getName()).thenReturn("2928749020"); when(accountRepository.findBySocialNetworkAndSocialNetworkId(eq("alteraBook"), eq("2928749020"))).thenReturn(account); when(account.getId()).thenReturn("accountId"); when(essences.get(2).isAdmin()).thenReturn(true); when(essenceRepository.findByAccountId(eq("accountId"))).thenReturn(essences); String view = mainResource.commands(model, principal, httpSession); verify(httpSession).getAttribute(eq("social")); verify(commandMetadataRepository).findAll(); verify(applicationContext, times(5)).getBean(startsWith("command")); verify(model).addAttribute(eq("metadataList"), anyListOf(CommandMetadata.class)); verify(model).addAttribute(eq("commandMap"), anyMapOf(String.class, Command.class)); assertEquals("commands", view); } @Test public void testEmotesNotAuthenticated() throws Exception { when(emoteMetadataRepository.findAll()).thenReturn(emoteMetadata); String view = mainResource.emotes(model, null, httpSession); verify(emoteMetadataRepository).findAll(); verifyZeroInteractions(httpSession); verify(model).addAttribute(eq("self"), entityCaptor.capture()); verify(model).addAttribute(eq("target"), entityCaptor.capture()); verify(model).addAttribute(eq("metadataList"), anyListOf(EmoteMetadata.class)); verify(model).addAttribute(eq("emoteMap"), anyMapOf(String.class, EmoteMetadata.class)); verifyAllEmoteMetadata(emoteMetadata); List<Entity> captures = entityCaptor.getAllValues(); assertEquals("emotes", view); assertEquals("Alice", captures.get(0).getName()); assertEquals("Bob", captures.get(1).getName()); } @Test public void testEmotesAuthenticatedNoEssences() throws Exception { when(emoteMetadataRepository.findAll()).thenReturn(emoteMetadata); when(httpSession.getAttribute(eq("social"))).thenReturn("social"); when(principal.getName()).thenReturn("principal"); when(accountRepository.findBySocialNetworkAndSocialNetworkId(eq("social"), eq("principal"))).thenReturn(account); when(account.getId()).thenReturn("accountId"); when(essenceRepository.findByAccountId(eq("accountId"))).thenReturn(new ArrayList<>()); String view = mainResource.emotes(model, principal, httpSession); verify(emoteMetadataRepository).findAll(); verify(httpSession).getAttribute(eq("social")); verify(model).addAttribute(eq("self"), entityCaptor.capture()); verify(model).addAttribute(eq("target"), entityCaptor.capture()); verify(model).addAttribute(eq("metadataList"), anyListOf(EmoteMetadata.class)); verify(model).addAttribute(eq("emoteMap"), anyMapOf(String.class, EmoteMetadata.class)); verifyAllEmoteMetadata(emoteMetadata); List<Entity> captures = entityCaptor.getAllValues(); assertEquals("emotes", view); assertEquals("Alice", captures.get(0).getName()); assertEquals("Bob", captures.get(1).getName()); } @Test public void testEmotesAuthenticatedOneEssence() throws Exception { ArrayList<Essence> oneEssence = new ArrayList<>(); oneEssence.add(essences.get(0)); when(emoteMetadataRepository.findAll()).thenReturn(emoteMetadata); when(httpSession.getAttribute(eq("social"))).thenReturn("social"); when(principal.getName()).thenReturn("principal"); when(accountRepository.findBySocialNetworkAndSocialNetworkId(eq("social"), eq("principal"))).thenReturn(account); when(account.getId()).thenReturn("accountId"); when(essenceRepository.findByAccountId(eq("accountId"))).thenReturn(oneEssence); String view = mainResource.emotes(model, principal, httpSession); verify(emoteMetadataRepository).findAll(); verify(httpSession).getAttribute(eq("social")); verify(model).addAttribute(eq("self"), entityCaptor.capture()); verify(model).addAttribute(eq("target"), entityCaptor.capture()); verify(model).addAttribute(eq("metadataList"), anyListOf(EmoteMetadata.class)); verify(model).addAttribute(eq("emoteMap"), anyMapOf(String.class, EmoteMetadata.class)); verifyAllEmoteMetadata(emoteMetadata); List<Entity> captures = entityCaptor.getAllValues(); assertEquals("emotes", view); assertEquals("EssenceA", captures.get(0).getName()); assertEquals("Bob", captures.get(1).getName()); } @Test public void testEmotesAuthenticatedTwoEssences() throws Exception { ArrayList<Essence> twoEssences = new ArrayList<>(); twoEssences.add(essences.get(0)); twoEssences.add(essences.get(1)); when(emoteMetadataRepository.findAll()).thenReturn(emoteMetadata); when(httpSession.getAttribute(eq("social"))).thenReturn("social"); when(principal.getName()).thenReturn("principal"); when(accountRepository.findBySocialNetworkAndSocialNetworkId(eq("social"), eq("principal"))).thenReturn(account); when(account.getId()).thenReturn("accountId"); when(essenceRepository.findByAccountId(eq("accountId"))).thenReturn(twoEssences); String view = mainResource.emotes(model, principal, httpSession); verify(emoteMetadataRepository).findAll(); verify(httpSession).getAttribute(eq("social")); verify(model).addAttribute(eq("self"), entityCaptor.capture()); verify(model).addAttribute(eq("target"), entityCaptor.capture()); verify(model).addAttribute(eq("metadataList"), anyListOf(EmoteMetadata.class)); verify(model).addAttribute(eq("emoteMap"), anyMapOf(String.class, EmoteMetadata.class)); verifyAllEmoteMetadata(emoteMetadata); List<Entity> captures = entityCaptor.getAllValues(); assertEquals("emotes", view); assertEquals("EssenceA", captures.get(0).getName()); assertEquals("EssenceB", captures.get(1).getName()); } @Test public void testLogout() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); String view = mainResource.logout(request, response, httpSession, principal); verify(securityContextLogoutHandler).logout(eq(request), eq(response), any(Authentication.class)); assertEquals("redirect:/", view); } private void generateSocialNetworks() { socialNetworks.add(new SocialNetwork(NETWORK_ID, NETWORK_NAME)); } private Account generateAccount() { Account account = mock(Account.class); when(account.getId()).thenReturn(ACCOUNT_ID); when(account.getSocialNetwork()).thenReturn(NETWORK_ID); when(account.getSocialNetworkId()).thenReturn(NETWORK_USER); return account; } private void generateEssences() { for (int i = 0; i < 3; i++) { Essence essence = mock(Essence.class); Entity entity = mock(Entity.class); when(essence.getId()).thenReturn("essence" + i); when(essence.getName()).thenReturn("Essence" + ALPHABET.charAt(i)); when(essence.getAccountId()).thenReturn(ACCOUNT_ID); when(essence.getEntity()).thenReturn(entity); when(entity.getId()).thenReturn("entity" + i); when(entity.getName()).thenReturn("Entity" + ALPHABET.charAt(i)); essences.add(essence); } } private List<CommandMetadata> generateCommandMetadata(boolean admin) { List<CommandMetadata> commandMetadata = new ArrayList<>(); for (int i = 0; i < 5; i++) { CommandMetadata metadata = mock(CommandMetadata.class); Command command = mock(Command.class); when(metadata.getBeanName()).thenReturn("command" + ALPHABET.charAt(i)); when(metadata.getName()).thenReturn("command" + ALPHABET.charAt(i)); if (admin) { when(metadata.isAdmin()).thenReturn(i % 2 == 0); } else { when(metadata.isAdmin()).thenReturn(false); } when(applicationContext.getBean(eq(metadata.getBeanName()))).thenReturn(command); commandMetadata.add(metadata); } return commandMetadata; } private void generateEmoteMetadata() { for (int i = 0; i < 5; i++) { EmoteMetadata metadata = mock(EmoteMetadata.class); emoteMetadata.add(metadata); } } private void verifyAllEmoteMetadata(List<EmoteMetadata> metadata) { metadata.forEach(m -> { verify(m).setToSelfUntargeted(anyString()); verify(m).setToRoomUntargeted(anyString()); verify(m).setToSelfWithTarget(anyString()); verify(m).setToTarget(anyString()); verify(m).setToRoomWithTarget(anyString()); verify(m).setToSelfAsTarget(anyString()); verify(m).setToRoomTargetingSelf(anyString()); }); } }
Fix up the tests.
src/test/java/com/emergentmud/core/resource/MainResourceTest.java
Fix up the tests.
<ide><path>rc/test/java/com/emergentmud/core/resource/MainResourceTest.java <ide> private HttpSession httpSession; <ide> <ide> @Mock <add> private HttpServletRequest httpServletRequest; <add> <add> @Mock <ide> private OAuth2Authentication principal; <ide> <ide> @Mock <ide> <ide> @Test <ide> public void testPlayExisting() throws Exception { <del> String view = mainResource.play(playRequest, httpSession, principal, model); <add> String view = mainResource.play(playRequest, httpSession, httpServletRequest, principal, model); <ide> Entity entity = essence.getEntity(); <ide> <ide> verify(roomBuilder, never()).generateRoom(eq(0L), eq(0L), eq(0L)); <ide> public void testPlayNoWorld() throws Exception { <ide> when(worldManager.test(eq(0L), eq(0L), eq(0L))).thenReturn(false); <ide> <del> String view = mainResource.play(playRequest, httpSession, principal, model); <add> String view = mainResource.play(playRequest, httpSession, httpServletRequest, principal, model); <ide> Entity entity = essence.getEntity(); <ide> <ide> verify(roomBuilder).generateRoom(eq(0L), eq(0L), eq(0L)); <ide> public void testPlayNoId() throws Exception { <ide> when(playRequest.getEssenceId()).thenReturn(null); <ide> <del> String view = mainResource.play(playRequest, httpSession, principal, model); <add> String view = mainResource.play(playRequest, httpSession, httpServletRequest, principal, model); <ide> <ide> verifyZeroInteractions(model); <ide> verifyZeroInteractions(httpSession); <ide> public void testPlayNoAccount() throws Exception { <ide> when(accountRepository.findBySocialNetworkAndSocialNetworkId(eq(NETWORK_ID), eq(NETWORK_USER))).thenReturn(null); <ide> <del> String view = mainResource.play(playRequest, httpSession, principal, model); <add> String view = mainResource.play(playRequest, httpSession, httpServletRequest, principal, model); <ide> <ide> verify(httpSession).getAttribute(eq("social")); <ide> verifyNoMoreInteractions(httpSession); <ide> public void testPlayNoEssence() throws Exception { <ide> when(essenceRepository.findByAccountId(anyString())).thenReturn(new ArrayList<>()); <ide> <del> String view = mainResource.play(playRequest, httpSession, principal, model); <add> String view = mainResource.play(playRequest, httpSession, httpServletRequest, principal, model); <ide> <ide> verify(httpSession).getAttribute(eq("social")); <ide> verifyNoMoreInteractions(httpSession); <ide> when(essence1.getEntity()).thenReturn(null); <ide> when(playRequest.getEssenceId()).thenReturn("essence1"); <ide> <del> String view = mainResource.play(playRequest, httpSession, principal, model); <add> String view = mainResource.play(playRequest, httpSession, httpServletRequest, principal, model); <ide> <ide> verify(entityUtil).sendMessageToRoom(any(Room.class), any(Entity.class), outputCaptor.capture()); <ide> verify(entityRepository).save(any(Entity.class)); <ide> when(entity0.getStompSessionId()).thenReturn("stompSessionId"); <ide> when(entity0.getStompUsername()).thenReturn("stompUsername"); <ide> <del> String view = mainResource.play(playRequest, httpSession, principal, model); <add> String view = mainResource.play(playRequest, httpSession, httpServletRequest, principal, model); <ide> <ide> verify(entityUtil).sendMessageToEntity(any(Entity.class), outputCaptor.capture()); <ide> verify(worldManager).put(any(Entity.class), eq(0L), eq(0L), eq(0L));
Java
bsd-2-clause
5247e33e132f3e58c8b5fa94b229b6e667239807
0
keeguon/activerecord-jdbc-adapter,keeguon/activerecord-jdbc-adapter,bruceadams/activerecord-jdbc-adapter,kares/activerecord-jdbc-adapter,jruby/activerecord-jdbc-adapter,bruceadams/activerecord-jdbc-adapter,kares/activerecord-jdbc-adapter,jruby/activerecord-jdbc-adapter,keeguon/activerecord-jdbc-adapter,jruby/activerecord-jdbc-adapter,bruceadams/activerecord-jdbc-adapter,kares/activerecord-jdbc-adapter
/* **** BEGIN LICENSE BLOCK ***** * Copyright (c) 2006-2011 Nick Sieger <[email protected]> * Copyright (c) 2006-2007 Ola Bini <[email protected]> * Copyright (c) 2008-2009 Thomas E Enebo <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ***** END LICENSE BLOCK *****/ package arjdbc.jdbc; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Array; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.SQLXML; import java.sql.Statement; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import org.jruby.Ruby; import org.jruby.RubyArray; import org.jruby.RubyBignum; import org.jruby.RubyBoolean; import org.jruby.RubyClass; import org.jruby.RubyFixnum; import org.jruby.RubyHash; import org.jruby.RubyIO; import org.jruby.RubyInteger; import org.jruby.RubyModule; import org.jruby.RubyNumeric; import org.jruby.RubyObject; import org.jruby.RubyString; import org.jruby.RubySymbol; import org.jruby.RubyTime; import org.jruby.anno.JRubyMethod; import org.jruby.exceptions.RaiseException; import org.jruby.javasupport.JavaEmbedUtils; import org.jruby.javasupport.JavaUtil; import org.jruby.javasupport.util.RuntimeHelpers; import org.jruby.runtime.Arity; import org.jruby.runtime.Block; import org.jruby.runtime.ObjectAllocator; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.backtrace.RubyStackTraceElement; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.util.ByteList; /** * Part of our ActiveRecord::ConnectionAdapters::Connection impl. */ public class RubyJdbcConnection extends RubyObject { private static final String[] TABLE_TYPE = new String[] { "TABLE" }; private static final String[] TABLE_TYPES = new String[] { "TABLE", "VIEW", "SYNONYM" }; protected RubyJdbcConnection(Ruby runtime, RubyClass metaClass) { super(runtime, metaClass); } private static ObjectAllocator JDBCCONNECTION_ALLOCATOR = new ObjectAllocator() { public IRubyObject allocate(Ruby runtime, RubyClass klass) { return new RubyJdbcConnection(runtime, klass); } }; public static RubyClass createJdbcConnectionClass(final Ruby runtime) { RubyClass jdbcConnection = getConnectionAdapters(runtime). defineClassUnder("JdbcConnection", runtime.getObject(), JDBCCONNECTION_ALLOCATOR); jdbcConnection.defineAnnotatedMethods(RubyJdbcConnection.class); return jdbcConnection; } public static RubyClass getJdbcConnectionClass(final Ruby runtime) { return getConnectionAdapters(runtime).getClass("JdbcConnection"); } /** * @param runtime * @return <code>ActiveRecord::ConnectionAdapters</code> */ protected static RubyModule getConnectionAdapters(final Ruby runtime) { return (RubyModule) runtime.getModule("ActiveRecord").getConstant("ConnectionAdapters"); } /** * @param runtime * @return <code>ActiveRecord::Result</code> */ static RubyClass getResult(final Ruby runtime) { return runtime.getModule("ActiveRecord").getClass("Result"); } /** * @param runtime * @return <code>ActiveRecord::ConnectionAdapters::IndexDefinition</code> */ protected static RubyClass getIndexDefinition(final Ruby runtime) { return getConnectionAdapters(runtime).getClass("IndexDefinition"); } /** * @param runtime * @return <code>ActiveRecord::JDBCError</code> */ protected static RubyClass getJDBCError(final Ruby runtime) { return runtime.getModule("ActiveRecord").getClass("JDBCError"); } /** * @param runtime * @return <code>ActiveRecord::ConnectionNotEstablished</code> */ protected static RubyClass getConnectionNotEstablished(final Ruby runtime) { return runtime.getModule("ActiveRecord").getClass("ConnectionNotEstablished"); } /** * NOTE: Only available since AR-4.0 * @param runtime * @return <code>ActiveRecord::TransactionIsolationError</code> */ protected static RubyClass getTransactionIsolationError(final Ruby runtime) { return (RubyClass) runtime.getModule("ActiveRecord").getConstant("TransactionIsolationError"); } /** * @param runtime * @return <code>ActiveRecord::ConnectionAdapters::JdbcTypeConverter</code> */ private static RubyClass getJdbcTypeConverter(final Ruby runtime) { return getConnectionAdapters(runtime).getClass("JdbcTypeConverter"); } /* def transaction_isolation_levels { read_uncommitted: "READ UNCOMMITTED", read_committed: "READ COMMITTED", repeatable_read: "REPEATABLE READ", serializable: "SERIALIZABLE" } end */ public static int mapTransactionIsolationLevel(IRubyObject isolation) { if ( ! ( isolation instanceof RubySymbol ) ) { isolation = isolation.convertToString().callMethod("intern"); } final Object isolationString = isolation.toString(); // RubySymbol.toString if ( isolationString == "read_uncommitted" ) return Connection.TRANSACTION_READ_UNCOMMITTED; // 1 if ( isolationString == "read_committed" ) return Connection.TRANSACTION_READ_COMMITTED; // 2 if ( isolationString == "repeatable_read" ) return Connection.TRANSACTION_REPEATABLE_READ; // 4 if ( isolationString == "serializable" ) return Connection.TRANSACTION_SERIALIZABLE; // 8 throw new IllegalArgumentException( "unexpected isolation level: " + isolation + " (" + isolationString + ")" ); } @JRubyMethod(name = "supports_transaction_isolation?", optional = 1) public IRubyObject supports_transaction_isolation_p(final ThreadContext context, final IRubyObject[] args) throws SQLException { final IRubyObject isolation = args.length > 0 ? args[0] : null; return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { final DatabaseMetaData metaData = connection.getMetaData(); final boolean supported; if ( isolation != null && ! isolation.isNil() ) { final int level = mapTransactionIsolationLevel(isolation); supported = metaData.supportsTransactionIsolationLevel(level); } else { final int level = metaData.getDefaultTransactionIsolation(); supported = level > Connection.TRANSACTION_NONE; // > 0 } return context.getRuntime().newBoolean(supported); } }); } @JRubyMethod(name = "begin", optional = 1) // optional isolation argument for AR-4.0 public IRubyObject begin(final ThreadContext context, final IRubyObject[] args) { final IRubyObject isolation = args.length > 0 ? args[0] : null; try { // handleException == false so we can handle setTXIsolation return withConnection(context, false, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { connection.setAutoCommit(false); if ( isolation != null && ! isolation.isNil() ) { final int level = mapTransactionIsolationLevel(isolation); try { connection.setTransactionIsolation(level); } catch (SQLException e) { RubyClass txError = getTransactionIsolationError(context.getRuntime()); if ( txError != null ) throw wrapException(context, txError, e); throw e; // let it roll - will be wrapped into a JDBCError (non 4.0) } } return context.getRuntime().getNil(); } }); } catch (SQLException e) { return handleException(context, e); } } @JRubyMethod(name = "commit") public IRubyObject commit(final ThreadContext context) { final Connection connection = getConnection(true); try { if ( ! connection.getAutoCommit() ) { try { connection.commit(); return context.getRuntime().newBoolean(true); } finally { connection.setAutoCommit(true); } } return context.getRuntime().getNil(); } catch (SQLException e) { return handleException(context, e); } } @JRubyMethod(name = "rollback") public IRubyObject rollback(final ThreadContext context) { final Connection connection = getConnection(true); try { if ( ! connection.getAutoCommit() ) { try { connection.rollback(); return context.getRuntime().newBoolean(true); } finally { connection.setAutoCommit(true); } } return context.getRuntime().getNil(); } catch (SQLException e) { return handleException(context, e); } } @JRubyMethod(name = "connection") public IRubyObject connection(final ThreadContext context) { if ( getConnection(false) == null ) { synchronized (this) { if ( getConnection(false) == null ) { reconnect(context); } } } return getInstanceVariable("@connection"); } @JRubyMethod(name = "disconnect!") public IRubyObject disconnect(final ThreadContext context) { // TODO: only here to try resolving multi-thread issues : // https://github.com/jruby/activerecord-jdbc-adapter/issues/197 // https://github.com/jruby/activerecord-jdbc-adapter/issues/198 if ( Boolean.getBoolean("arjdbc.disconnect.debug") ) { final List<?> backtrace = createCallerBacktrace(context); final Ruby runtime = context.getRuntime(); runtime.getOut().println(this + " connection.disconnect! occured: "); for ( Object element : backtrace ) { runtime.getOut().println(element); } runtime.getOut().flush(); } return setConnection(null); } @JRubyMethod(name = "reconnect!") public IRubyObject reconnect(final ThreadContext context) { try { return setConnection( getConnectionFactory().newConnection() ); } catch (SQLException e) { return handleException(context, e); } } @JRubyMethod(name = "database_name") public IRubyObject database_name(ThreadContext context) throws SQLException { Connection connection = getConnection(true); String name = connection.getCatalog(); if (null == name) { name = connection.getMetaData().getUserName(); if (null == name) name = "db1"; } return context.getRuntime().newString(name); } @JRubyMethod(name = "execute", required = 1) public IRubyObject execute(final ThreadContext context, final IRubyObject sql) { return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { Statement statement = null; final String query = sql.convertToString().getUnicodeValue(); try { statement = createStatement(context, connection); if ( doExecute(statement, query) ) { return unmarshalResults(context, connection.getMetaData(), statement, false); } else { return unmarshalKeysOrUpdateCount(context, connection, statement); } } catch (final SQLException e) { debugErrorSQL(context, query); throw e; } finally { close(statement); } } }); } protected Statement createStatement(final ThreadContext context, final Connection connection) throws SQLException { final Statement statement = connection.createStatement(); IRubyObject statementEscapeProcessing = getConfigValue(context, "statement_escape_processing"); // NOTE: disable (driver) escape processing by default, it's not really // needed for AR statements ... if users need it they might configure : if ( statementEscapeProcessing.isNil() ) { statement.setEscapeProcessing(false); } else { statement.setEscapeProcessing(statementEscapeProcessing.isTrue()); } return statement; } /** * Execute a query using the given statement. * @param statement * @param query * @return true if the first result is a <code>ResultSet</code>; * false if it is an update count or there are no results * @throws SQLException */ protected boolean doExecute(final Statement statement, final String query) throws SQLException { return genericExecute(statement, query); } /** * @deprecated renamed to {@link #doExecute(Statement, String)} */ @Deprecated protected boolean genericExecute(final Statement statement, final String query) throws SQLException { return statement.execute(query); } protected IRubyObject unmarshalKeysOrUpdateCount(final ThreadContext context, final Connection connection, final Statement statement) throws SQLException { final Ruby runtime = context.getRuntime(); final IRubyObject key; if ( connection.getMetaData().supportsGetGeneratedKeys() ) { key = unmarshalIdResult(runtime, statement); } else { key = runtime.getNil(); } return key.isNil() ? runtime.newFixnum( statement.getUpdateCount() ) : key; } @JRubyMethod(name = "execute_insert", required = 1) public IRubyObject execute_insert(final ThreadContext context, final IRubyObject sql) throws SQLException { return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { Statement statement = null; final String insertSQL = sql.convertToString().getUnicodeValue(); try { statement = createStatement(context, connection); statement.executeUpdate(insertSQL, Statement.RETURN_GENERATED_KEYS); return unmarshalIdResult(context.getRuntime(), statement); } catch (final SQLException e) { debugErrorSQL(context, insertSQL); throw e; } finally { close(statement); } } }); } @JRubyMethod(name = {"execute_update", "execute_delete"}, required = 1) public IRubyObject execute_update(final ThreadContext context, final IRubyObject sql) throws SQLException { return withConnection(context, new Callable<RubyInteger>() { public RubyInteger call(final Connection connection) throws SQLException { Statement statement = null; final String updateSQL = sql.convertToString().getUnicodeValue(); try { statement = createStatement(context, connection); final int rowCount = statement.executeUpdate(updateSQL); return context.getRuntime().newFixnum(rowCount); } catch (final SQLException e) { debugErrorSQL(context, updateSQL); throw e; } finally { close(statement); } } }); } /** * NOTE: since 1.3 this behaves like <code>execute_query</code> in AR-JDBC 1.2 * @param context * @param sql * @param block (optional) block to yield row values * @return raw query result as a name => value Hash (unless block given) * @throws SQLException * @see #execute_query_raw(ThreadContext, IRubyObject[], Block) */ @JRubyMethod(name = "execute_query_raw", required = 1) // optional block public IRubyObject execute_query_raw(final ThreadContext context, final IRubyObject sql, final Block block) throws SQLException { final String query = sql.convertToString().getUnicodeValue(); return executeQueryRaw(context, query, 0, block); } /** * NOTE: since 1.3 this behaves like <code>execute_query</code> in AR-JDBC 1.2 * @param context * @param args * @param block (optional) block to yield row values * @return raw query result as a name => value Hash (unless block given) * @throws SQLException */ @JRubyMethod(name = "execute_query_raw", required = 2, optional = 1) // @JRubyMethod(name = "execute_query_raw", required = 1, optional = 2) public IRubyObject execute_query_raw(final ThreadContext context, final IRubyObject[] args, final Block block) throws SQLException { // args: (sql), (sql, max_rows), (sql, binds), (sql, max_rows, binds) final String query = args[0].convertToString().getUnicodeValue(); // sql IRubyObject max_rows = args.length > 1 ? args[1] : null; IRubyObject binds = args.length > 2 ? args[2] : null; final int maxRows; if ( max_rows == null || max_rows.isNil() ) maxRows = 0; else { if ( binds instanceof RubyNumeric ) { // (sql, max_rows) maxRows = RubyNumeric.fix2int(binds); binds = null; } else { if ( max_rows instanceof RubyNumeric ) { maxRows = RubyNumeric.fix2int(max_rows); } else { if ( binds == null ) binds = max_rows; // (sql, binds) maxRows = 0; } } } if ( binds == null || binds.isNil() ) { // no prepared statements return executeQueryRaw(context, query, maxRows, block); } else { // we allow prepared statements with empty binds parameters return executePreparedQueryRaw(context, query, (List) binds, maxRows, block); } } /** * @param context * @param query * @param maxRows * @param block * @return raw query result (in case no block was given) * * @see #execute_query_raw(ThreadContext, IRubyObject[], Block) */ protected IRubyObject executeQueryRaw(final ThreadContext context, final String query, final int maxRows, final Block block) { return doExecuteQueryRaw(context, query, maxRows, block, null); // binds == null } protected IRubyObject executePreparedQueryRaw(final ThreadContext context, final String query, final List<?> binds, final int maxRows, final Block block) { return doExecuteQueryRaw(context, query, maxRows, block, binds); } private IRubyObject doExecuteQueryRaw(final ThreadContext context, final String query, final int maxRows, final Block block, final List<?> binds) { return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { final Ruby runtime = context.getRuntime(); final DatabaseMetaData metaData = connection.getMetaData(); Statement statement = null; ResultSet resultSet = null; try { if ( binds == null ) { // plain statement statement = createStatement(context, connection); statement.setMaxRows(maxRows); // zero means there is no limit resultSet = statement.executeQuery(query); } else { final PreparedStatement prepStatement; statement = prepStatement = connection.prepareStatement(query); statement.setMaxRows(maxRows); // zero means there is no limit setStatementParameters(context, connection, prepStatement, binds); resultSet = prepStatement.executeQuery(); } if ( block != null && block.isGiven() ) { // yield(id1, name1) ... row 1 result data // yield(id2, name2) ... row 2 result data return yieldResultRows(context, runtime, metaData, resultSet, block); } return mapToRawResult(context, runtime, metaData, resultSet, false); } catch (final SQLException e) { debugErrorSQL(context, query); throw e; } finally { close(resultSet); close(statement); } } }); } /** * Executes a query and returns the (AR) result. * @param context * @param sql * @return raw query result as a name => value Hash (unless block given) * @throws SQLException * @see #execute_query(ThreadContext, IRubyObject[], Block) */ @JRubyMethod(name = "execute_query", required = 1) public IRubyObject execute_query(final ThreadContext context, final IRubyObject sql) throws SQLException { final String query = sql.convertToString().getUnicodeValue(); return executeQuery(context, query, 0); } /** * Executes a query and returns the (AR) result. * @param context * @param args * @return and <code>ActiveRecord::Result</code> * @throws SQLException * * @see #execute_query(ThreadContext, IRubyObject, IRubyObject, Block) */ @JRubyMethod(name = "execute_query", required = 2, optional = 1) // @JRubyMethod(name = "execute_query", required = 1, optional = 2) public IRubyObject execute_query(final ThreadContext context, final IRubyObject[] args) throws SQLException { // args: (sql), (sql, max_rows), (sql, binds), (sql, max_rows, binds) final String query = args[0].convertToString().getUnicodeValue(); // sql IRubyObject max_rows = args.length > 1 ? args[1] : null; IRubyObject binds = args.length > 2 ? args[2] : null; final int maxRows; if ( max_rows == null || max_rows.isNil() ) maxRows = 0; else { if ( binds instanceof RubyNumeric ) { // (sql, max_rows) maxRows = RubyNumeric.fix2int(binds); binds = null; } else { if ( max_rows instanceof RubyNumeric ) { maxRows = RubyNumeric.fix2int(max_rows); } else { if ( binds == null ) binds = max_rows; // (sql, binds) maxRows = 0; } } } if ( binds == null || binds.isNil() ) { // no prepared statements return executeQuery(context, query, maxRows); } else { // we allow prepared statements with empty binds parameters return executePreparedQuery(context, query, (List) binds, maxRows); } } /** * NOTE: This methods behavior changed in AR-JDBC 1.3 the old behavior is * achievable using {@link #executeQueryRaw(ThreadContext, String, int, Block)}. * * @param context * @param query * @param maxRows * @return AR (mapped) query result * * @see #execute_query(ThreadContext, IRubyObject) * @see #execute_query(ThreadContext, IRubyObject, IRubyObject) * @see #mapToResult(ThreadContext, Ruby, DatabaseMetaData, ResultSet, RubyJdbcConnection.ColumnData[]) */ protected IRubyObject executeQuery(final ThreadContext context, final String query, final int maxRows) { return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { Statement statement = null; ResultSet resultSet = null; try { statement = createStatement(context, connection); statement.setMaxRows(maxRows); // zero means there is no limit resultSet = statement.executeQuery(query); return mapQueryResult(context, connection, resultSet); } catch (final SQLException e) { debugErrorSQL(context, query); throw e; } finally { close(resultSet); close(statement); } } }); } protected IRubyObject executePreparedQuery(final ThreadContext context, final String query, final List<?> binds, final int maxRows) { return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { PreparedStatement statement = null; ResultSet resultSet = null; try { statement = connection.prepareStatement(query); statement.setMaxRows(maxRows); // zero means there is no limit setStatementParameters(context, connection, statement, binds); resultSet = statement.executeQuery(); return mapQueryResult(context, connection, resultSet); } catch (final SQLException e) { debugErrorSQL(context, query); throw e; } finally { close(resultSet); close(statement); } } }); } private IRubyObject mapQueryResult(final ThreadContext context, final Connection connection, final ResultSet resultSet) throws SQLException { final Ruby runtime = context.getRuntime(); final DatabaseMetaData metaData = connection.getMetaData(); final ColumnData[] columns = setupColumns(runtime, metaData, resultSet.getMetaData(), false); return mapToResult(context, runtime, metaData, resultSet, columns); } @JRubyMethod(name = "execute_id_insert", required = 2) public IRubyObject execute_id_insert(final ThreadContext context, final IRubyObject sql, final IRubyObject id) throws SQLException { return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { PreparedStatement statement = null; final String insertSQL = sql.convertToString().getUnicodeValue(); try { statement = connection.prepareStatement(insertSQL); statement.setLong(1, RubyNumeric.fix2long(id)); statement.executeUpdate(); } catch (final SQLException e) { debugErrorSQL(context, insertSQL); throw e; } finally { close(statement); } return id; } }); } @JRubyMethod(name = "native_database_types", frame = false) public IRubyObject native_database_types() { return getInstanceVariable("@native_database_types"); } @JRubyMethod(name = "primary_keys", required = 1) public IRubyObject primary_keys(ThreadContext context, IRubyObject tableName) throws SQLException { @SuppressWarnings("unchecked") List<IRubyObject> primaryKeys = (List) primaryKeys(context, tableName.toString()); return context.getRuntime().newArray(primaryKeys); } private static final int PRIMARY_KEYS_COLUMN_NAME = 4; protected List<RubyString> primaryKeys(final ThreadContext context, final String tableName) { return withConnection(context, new Callable<List<RubyString>>() { public List<RubyString> call(final Connection connection) throws SQLException { final Ruby runtime = context.getRuntime(); final DatabaseMetaData metaData = connection.getMetaData(); final String _tableName = caseConvertIdentifierForJdbc(metaData, tableName); ResultSet resultSet = null; final List<RubyString> keyNames = new ArrayList<RubyString>(); try { TableName components = extractTableName(connection, null, _tableName); resultSet = metaData.getPrimaryKeys(components.catalog, components.schema, components.name); while (resultSet.next()) { String columnName = resultSet.getString(PRIMARY_KEYS_COLUMN_NAME); columnName = caseConvertIdentifierForRails(metaData, columnName); keyNames.add( RubyString.newUnicodeString(runtime, columnName) ); } } finally { close(resultSet); } return keyNames; } }); } @JRubyMethod(name = "set_native_database_types") public IRubyObject set_native_database_types(final ThreadContext context) throws SQLException { final Ruby runtime = context.getRuntime(); final DatabaseMetaData metaData = getConnection(true).getMetaData(); final IRubyObject types; final ResultSet typeDesc = metaData.getTypeInfo(); try { types = mapToRawResult(context, runtime, metaData, typeDesc, true); } finally { close(typeDesc); } final IRubyObject typeConverter = getJdbcTypeConverter(runtime).callMethod("new", types); setInstanceVariable("@native_types", typeConverter.callMethod(context, "choose_best_types")); return runtime.getNil(); } @JRubyMethod(name = "tables") public IRubyObject tables(ThreadContext context) { return tables(context, null, null, null, TABLE_TYPE); } @JRubyMethod(name = "tables") public IRubyObject tables(ThreadContext context, IRubyObject catalog) { return tables(context, toStringOrNull(catalog), null, null, TABLE_TYPE); } @JRubyMethod(name = "tables") public IRubyObject tables(ThreadContext context, IRubyObject catalog, IRubyObject schemaPattern) { return tables(context, toStringOrNull(catalog), toStringOrNull(schemaPattern), null, TABLE_TYPE); } @JRubyMethod(name = "tables") public IRubyObject tables(ThreadContext context, IRubyObject catalog, IRubyObject schemaPattern, IRubyObject tablePattern) { return tables(context, toStringOrNull(catalog), toStringOrNull(schemaPattern), toStringOrNull(tablePattern), TABLE_TYPE); } @JRubyMethod(name = "tables", required = 4, rest = true) public IRubyObject tables(ThreadContext context, IRubyObject[] args) { return tables(context, toStringOrNull(args[0]), toStringOrNull(args[1]), toStringOrNull(args[2]), getTypes(args[3])); } protected IRubyObject tables(final ThreadContext context, final String catalog, final String schemaPattern, final String tablePattern, final String[] types) { return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { return matchTables(context.getRuntime(), connection, catalog, schemaPattern, tablePattern, types, false); } }); } protected String[] getTableTypes() { return TABLE_TYPES; } @JRubyMethod(name = "table_exists?", required = 1, optional = 1) public IRubyObject table_exists_p(final ThreadContext context, final IRubyObject[] args) { IRubyObject name = args[0], schema_name = args.length > 1 ? args[1] : null; if ( ! ( name instanceof RubyString ) ) { name = name.callMethod(context, "to_s"); } final String tableName = ((RubyString) name).getUnicodeValue(); final String tableSchema = schema_name == null ? null : schema_name.convertToString().getUnicodeValue(); final Ruby runtime = context.getRuntime(); return withConnection(context, new Callable<RubyBoolean>() { public RubyBoolean call(final Connection connection) throws SQLException { final TableName components = extractTableName(connection, tableSchema, tableName); return runtime.newBoolean( tableExists(runtime, connection, components) ); } }); } @JRubyMethod(name = {"columns", "columns_internal"}, required = 1, optional = 2) public IRubyObject columns_internal(final ThreadContext context, final IRubyObject[] args) throws SQLException { return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { ResultSet columns = null, primaryKeys = null; try { final String tableName = args[0].convertToString().getUnicodeValue(); // optionals (NOTE: catalog argumnet was never used before 1.3.0) : final String catalog = args.length > 1 ? toStringOrNull(args[1]) : null; final String defaultSchema = args.length > 2 ? toStringOrNull(args[2]) : null; final TableName components; if ( catalog == null ) { // backwards-compatibility with < 1.3.0 components = extractTableName(connection, defaultSchema, tableName); } else { components = extractTableName(connection, catalog, defaultSchema, tableName); } if ( ! tableExists(context.getRuntime(), connection, components) ) { throw new SQLException("table: " + tableName + " does not exist"); } final DatabaseMetaData metaData = connection.getMetaData(); columns = metaData.getColumns(components.catalog, components.schema, components.name, null); primaryKeys = metaData.getPrimaryKeys(components.catalog, components.schema, components.name); return unmarshalColumns(context, metaData, columns, primaryKeys); } finally { close(columns); close(primaryKeys); } } }); } @JRubyMethod(name = "indexes") public IRubyObject indexes(ThreadContext context, IRubyObject tableName, IRubyObject name, IRubyObject schemaName) { return indexes(context, toStringOrNull(tableName), toStringOrNull(name), toStringOrNull(schemaName)); } // NOTE: metaData.getIndexInfo row mappings : private static final int INDEX_INFO_TABLE_NAME = 3; private static final int INDEX_INFO_NON_UNIQUE = 4; private static final int INDEX_INFO_NAME = 6; private static final int INDEX_INFO_COLUMN_NAME = 9; /** * Default JDBC introspection for index metadata on the JdbcConnection. * * JDBC index metadata is denormalized (multiple rows may be returned for * one index, one row per column in the index), so a simple block-based * filter like that used for tables doesn't really work here. Callers * should filter the return from this method instead. */ protected IRubyObject indexes(final ThreadContext context, final String tableName, final String name, final String schemaName) { return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { final Ruby runtime = context.getRuntime(); final RubyClass indexDefinition = getIndexDefinition(runtime); final DatabaseMetaData metaData = connection.getMetaData(); String _tableName = caseConvertIdentifierForJdbc(metaData, tableName); String _schemaName = caseConvertIdentifierForJdbc(metaData, schemaName); final List<RubyString> primaryKeys = primaryKeys(context, _tableName); ResultSet indexInfoSet = null; final List<IRubyObject> indexes = new ArrayList<IRubyObject>(); try { indexInfoSet = metaData.getIndexInfo(null, _schemaName, _tableName, false, true); String currentIndex = null; while ( indexInfoSet.next() ) { String indexName = indexInfoSet.getString(INDEX_INFO_NAME); if ( indexName == null ) continue; indexName = caseConvertIdentifierForRails(metaData, indexName); final String columnName = indexInfoSet.getString(INDEX_INFO_COLUMN_NAME); final RubyString rubyColumnName = RubyString.newUnicodeString( runtime, caseConvertIdentifierForRails(metaData, columnName) ); if ( primaryKeys.contains(rubyColumnName) ) continue; // We are working on a new index if ( ! indexName.equals(currentIndex) ) { currentIndex = indexName; String indexTableName = indexInfoSet.getString(INDEX_INFO_TABLE_NAME); indexTableName = caseConvertIdentifierForRails(metaData, indexTableName); final boolean nonUnique = indexInfoSet.getBoolean(INDEX_INFO_NON_UNIQUE); IRubyObject[] args = new IRubyObject[] { RubyString.newUnicodeString(runtime, indexTableName), // table_name RubyString.newUnicodeString(runtime, indexName), // index_name runtime.newBoolean( ! nonUnique ), // unique runtime.newArray() // [] for column names, we'll add to that in just a bit // orders, (since AR 3.2) where, type, using (AR 4.0) }; indexes.add( indexDefinition.callMethod(context, "new", args) ); // IndexDefinition.new } // One or more columns can be associated with an index IRubyObject lastIndexDef = indexes.isEmpty() ? null : indexes.get(indexes.size() - 1); if (lastIndexDef != null) { lastIndexDef.callMethod(context, "columns").callMethod(context, "<<", rubyColumnName); } } return runtime.newArray(indexes); } finally { close(indexInfoSet); } } }); } // NOTE: this seems to be not used ... at all ?! /* * sql, values (array), types (column.type array), name = nil, pk = nil, id_value = nil, sequence_name = nil */ @Deprecated @JRubyMethod(name = "insert_bind", required = 3, rest = true) public IRubyObject insert_bind(final ThreadContext context, final IRubyObject[] args) throws SQLException { final Ruby runtime = context.getRuntime(); return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { final String sql = args[0].convertToString().toString(); PreparedStatement statement = null; try { statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); setPreparedStatementValues(context, connection, statement, args[1], args[2]); statement.executeUpdate(); return unmarshalIdResult(runtime, statement); } finally { close(statement); } } }); } // NOTE: this seems to be not used ... at all ?! /* * sql, values (array), types (column.type array), name = nil */ @Deprecated @JRubyMethod(name = "update_bind", required = 3, rest = true) public IRubyObject update_bind(final ThreadContext context, final IRubyObject[] args) throws SQLException { final Ruby runtime = context.getRuntime(); Arity.checkArgumentCount(runtime, args, 3, 4); return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { final String sql = args[0].convertToString().toString(); PreparedStatement statement = null; try { statement = connection.prepareStatement(sql); setPreparedStatementValues(context, connection, statement, args[1], args[2]); statement.executeUpdate(); } finally { close(statement); } return runtime.getNil(); } }); } @JRubyMethod(name = "with_connection_retry_guard", frame = true) public IRubyObject with_connection_retry_guard(final ThreadContext context, final Block block) { return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { return block.call(context, new IRubyObject[] { convertJavaToRuby(connection) }); } }); } /* * (is binary?, colname, tablename, primary_key, id, lob_value) */ @JRubyMethod(name = "write_large_object", required = 6) public IRubyObject write_large_object(final ThreadContext context, final IRubyObject[] args) throws SQLException { final boolean isBinary = args[0].isTrue(); final RubyString columnName = args[1].convertToString(); final RubyString tableName = args[2].convertToString(); final RubyString idKey = args[3].convertToString(); final RubyString idVal = args[4].convertToString(); final IRubyObject lobValue = args[5]; final Ruby runtime = context.getRuntime(); return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { final String sql = "UPDATE "+ tableName + " SET "+ columnName +" = ? WHERE "+ idKey +" = "+ idVal; PreparedStatement statement = null; try { statement = connection.prepareStatement(sql); if ( isBinary ) { // binary final ByteList blob = lobValue.convertToString().getByteList(); final int realSize = blob.getRealSize(); statement.setBinaryStream(1, new ByteArrayInputStream(blob.unsafeBytes(), blob.getBegin(), realSize), realSize ); } else { // clob String clob = lobValue.convertToString().getUnicodeValue(); statement.setCharacterStream(1, new StringReader(clob), clob.length()); } statement.executeUpdate(); } finally { close(statement); } return runtime.getNil(); } }); } /** * Convert an identifier coming back from the database to a case which Rails is expecting. * * Assumption: Rails identifiers will be quoted for mixed or will stay mixed * as identifier names in Rails itself. Otherwise, they expect identifiers to * be lower-case. Databases which store identifiers uppercase should be made * lower-case. * * Assumption 2: It is always safe to convert all upper case names since it appears that * some adapters do not report StoresUpper/Lower/Mixed correctly (am I right postgres/mysql?). */ protected static String caseConvertIdentifierForRails(final DatabaseMetaData metaData, final String value) throws SQLException { if ( value == null ) return null; return metaData.storesUpperCaseIdentifiers() ? value.toLowerCase() : value; } /** * Convert an identifier destined for a method which cares about the databases internal * storage case. Methods like DatabaseMetaData.getPrimaryKeys() needs the table name to match * the internal storage name. Arbtrary queries and the like DO NOT need to do this. */ protected String caseConvertIdentifierForJdbc(final DatabaseMetaData metaData, final String value) throws SQLException { if ( value == null ) return null; if ( metaData.storesUpperCaseIdentifiers() ) { return value.toUpperCase(); } else if ( metaData.storesLowerCaseIdentifiers() ) { return value.toLowerCase(); } return value; } protected IRubyObject getConfigValue(final ThreadContext context, final String key) { final IRubyObject config = getInstanceVariable("@config"); return config.callMethod(context, "[]", context.getRuntime().newSymbol(key)); } /** * @deprecated renamed to {@link #getConfigValue(ThreadContext, String)} */ @Deprecated protected IRubyObject config_value(ThreadContext context, String key) { return getConfigValue(context, key); } private static String toStringOrNull(IRubyObject arg) { return arg.isNil() ? null : arg.toString(); } protected IRubyObject getAdapter(ThreadContext context) { return callMethod(context, "adapter"); } protected IRubyObject getJdbcColumnClass(ThreadContext context) { return getAdapter(context).callMethod(context, "jdbc_column_class"); } protected JdbcConnectionFactory getConnectionFactory() throws RaiseException { IRubyObject connection_factory = getInstanceVariable("@connection_factory"); if ( connection_factory == null ) { throw getRuntime().newRuntimeError("@connection_factory not set"); } JdbcConnectionFactory connectionFactory; try { connectionFactory = (JdbcConnectionFactory) connection_factory.toJava(JdbcConnectionFactory.class); } catch (Exception e) { throw getRuntime().newRuntimeError("@connection_factory not set properly: " + e); } return connectionFactory; } private static String[] getTypes(final IRubyObject typeArg) { if ( typeArg instanceof RubyArray ) { IRubyObject[] rubyTypes = ((RubyArray) typeArg).toJavaArray(); final String[] types = new String[rubyTypes.length]; for ( int i = 0; i < types.length; i++ ) { types[i] = rubyTypes[i].toString(); } return types; } return new String[] { typeArg.toString() }; // expect a RubyString } /** * @deprecated this method is no longer used, instead consider overriding * {@link #mapToResult(ThreadContext, Ruby, DatabaseMetaData, ResultSet, RubyJdbcConnection.ColumnData[])} */ @Deprecated protected void populateFromResultSet( final ThreadContext context, final Ruby runtime, final List<IRubyObject> results, final ResultSet resultSet, final ColumnData[] columns) throws SQLException { final ResultHandler resultHandler = ResultHandler.getInstance(context); while ( resultSet.next() ) { results.add( resultHandler.mapRawRow(context, runtime, columns, resultSet, this) ); } } /** * Maps a query result into a <code>ActiveRecord</code> result. * @param context * @param runtime * @param metaData * @param resultSet * @param columns * @return since 3.1 expected to return a <code>ActiveRecord::Result</code> * @throws SQLException */ protected IRubyObject mapToResult(final ThreadContext context, final Ruby runtime, final DatabaseMetaData metaData, final ResultSet resultSet, final ColumnData[] columns) throws SQLException { final ResultHandler resultHandler = ResultHandler.getInstance(context); final RubyArray resultRows = runtime.newArray(); while ( resultSet.next() ) { resultRows.add( resultHandler.mapRow(context, runtime, columns, resultSet, this) ); } return resultHandler.newResult(context, runtime, columns, resultRows); } protected IRubyObject jdbcToRuby(final Ruby runtime, final int column, final int type, final ResultSet resultSet) throws SQLException { try { switch (type) { case Types.BLOB: case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: return streamToRuby(runtime, resultSet, column); case Types.CLOB: case Types.NCLOB: // JDBC 4.0 return readerToRuby(runtime, resultSet, column); case Types.LONGVARCHAR: case Types.LONGNVARCHAR: // JDBC 4.0 if ( runtime.is1_9() ) { return readerToRuby(runtime, resultSet, column); } else { return streamToRuby(runtime, resultSet, column); } case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: return integerToRuby(runtime, resultSet, column); case Types.REAL: case Types.FLOAT: case Types.DOUBLE: return doubleToRuby(runtime, resultSet, column); case Types.BIGINT: return bigIntegerToRuby(runtime, resultSet, column); case Types.NUMERIC: case Types.DECIMAL: return decimalToRuby(runtime, resultSet, column); case Types.DATE: return dateToRuby(runtime, resultSet, column); case Types.TIME: return timeToRuby(runtime, resultSet, column); case Types.TIMESTAMP: return timestampToRuby(runtime, resultSet, column); case Types.BIT: case Types.BOOLEAN: return booleanToRuby(runtime, resultSet, column); case Types.SQLXML: // JDBC 4.0 return xmlToRuby(runtime, resultSet, column); case Types.ARRAY: // we handle JDBC Array into (Ruby) [] return arrayToRuby(runtime, resultSet, column); case Types.NULL: return runtime.getNil(); // NOTE: (JDBC) exotic stuff just cause it's so easy with JRuby :) case Types.JAVA_OBJECT: case Types.OTHER: return objectToRuby(runtime, resultSet, column); // (default) String case Types.CHAR: case Types.VARCHAR: case Types.NCHAR: // JDBC 4.0 case Types.NVARCHAR: // JDBC 4.0 default: return stringToRuby(runtime, resultSet, column); } // NOTE: not mapped types : //case Types.DISTINCT: //case Types.STRUCT: //case Types.REF: //case Types.DATALINK: } catch (IOException e) { throw new SQLException(e.getMessage(), e); } } protected IRubyObject integerToRuby( final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException { final long value = resultSet.getLong(column); if ( value == 0 && resultSet.wasNull() ) return runtime.getNil(); return integerToRuby(runtime, resultSet, value); } @Deprecated protected IRubyObject integerToRuby( final Ruby runtime, final ResultSet resultSet, final long longValue) throws SQLException { if ( longValue == 0 && resultSet.wasNull() ) return runtime.getNil(); return runtime.newFixnum(longValue); } protected IRubyObject doubleToRuby(Ruby runtime, ResultSet resultSet, final int column) throws SQLException { final double value = resultSet.getDouble(column); if ( value == 0 && resultSet.wasNull() ) return runtime.getNil(); return doubleToRuby(runtime, resultSet, value); } @Deprecated protected IRubyObject doubleToRuby(Ruby runtime, ResultSet resultSet, double doubleValue) throws SQLException { if ( doubleValue == 0 && resultSet.wasNull() ) return runtime.getNil(); return runtime.newFloat(doubleValue); } protected IRubyObject stringToRuby( final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException { final String value = resultSet.getString(column); if ( value == null && resultSet.wasNull() ) return runtime.getNil(); return stringToRuby(runtime, resultSet, value); } @Deprecated protected IRubyObject stringToRuby( final Ruby runtime, final ResultSet resultSet, final String string) throws SQLException { if ( string == null && resultSet.wasNull() ) return runtime.getNil(); return RubyString.newUnicodeString(runtime, string); } protected IRubyObject bigIntegerToRuby( final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException { final String value = resultSet.getString(column); if ( value == null && resultSet.wasNull() ) return runtime.getNil(); return bigIntegerToRuby(runtime, resultSet, value); } @Deprecated protected IRubyObject bigIntegerToRuby( final Ruby runtime, final ResultSet resultSet, final String intValue) throws SQLException { if ( intValue == null && resultSet.wasNull() ) return runtime.getNil(); return RubyBignum.bignorm(runtime, new BigInteger(intValue)); } protected IRubyObject decimalToRuby( final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException { final String value = resultSet.getString(column); if ( value == null && resultSet.wasNull() ) return runtime.getNil(); // NOTE: JRuby 1.6 -> 1.7 API change : moved org.jruby.RubyBigDecimal return runtime.getKernel().callMethod("BigDecimal", runtime.newString(value)); } private static boolean parseDateTime = false; // TODO protected IRubyObject dateToRuby( // TODO final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException { final Date value = resultSet.getDate(column); if ( value == null && resultSet.wasNull() ) return runtime.getNil(); return RubyString.newUnicodeString(runtime, value.toString()); } protected IRubyObject timeToRuby( // TODO final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException { final Time value = resultSet.getTime(column); if ( value == null && resultSet.wasNull() ) return runtime.getNil(); return RubyString.newUnicodeString(runtime, value.toString()); } protected IRubyObject timestampToRuby( final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException { final Timestamp value = resultSet.getTimestamp(column); if ( value == null && resultSet.wasNull() ) return runtime.getNil(); return timestampToRuby(runtime, resultSet, value); } @Deprecated protected IRubyObject timestampToRuby( final Ruby runtime, final ResultSet resultSet, final Timestamp value) throws SQLException { if ( value == null && resultSet.wasNull() ) return runtime.getNil(); String format = value.toString(); // yyyy-mm-dd hh:mm:ss.fffffffff if ( format.endsWith(" 00:00:00.0") ) { format = format.substring(0, format.length() - (" 00:00:00.0".length())); } if ( format.endsWith(".0") ) { format = format.substring(0, format.length() - (".0".length())); } return RubyString.newUnicodeString(runtime, format); } protected IRubyObject booleanToRuby( final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException { final boolean value = resultSet.getBoolean(column); if ( resultSet.wasNull() ) return runtime.getNil(); return booleanToRuby(runtime, resultSet, value); } @Deprecated protected IRubyObject booleanToRuby( final Ruby runtime, final ResultSet resultSet, final boolean value) throws SQLException { if ( value == false && resultSet.wasNull() ) return runtime.getNil(); return runtime.newBoolean(value); } protected static int streamBufferSize = 2048; protected IRubyObject streamToRuby( final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException, IOException { final InputStream stream = resultSet.getBinaryStream(column); try { if ( resultSet.wasNull() ) return runtime.getNil(); return streamToRuby(runtime, resultSet, stream); } finally { if ( stream != null ) stream.close(); } } @Deprecated protected IRubyObject streamToRuby( final Ruby runtime, final ResultSet resultSet, final InputStream stream) throws SQLException, IOException { if ( stream == null && resultSet.wasNull() ) return runtime.getNil(); final int bufSize = streamBufferSize; final ByteList string = new ByteList(bufSize); final byte[] buf = new byte[bufSize]; for (int len = stream.read(buf); len != -1; len = stream.read(buf)) { string.append(buf, 0, len); } return runtime.newString(string); } protected IRubyObject readerToRuby( final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException, IOException { final Reader reader = resultSet.getCharacterStream(column); try { if ( resultSet.wasNull() ) return runtime.getNil(); return readerToRuby(runtime, resultSet, reader); } finally { if ( reader != null ) reader.close(); } } @Deprecated protected IRubyObject readerToRuby( final Ruby runtime, final ResultSet resultSet, final Reader reader) throws SQLException, IOException { if ( reader == null && resultSet.wasNull() ) return runtime.getNil(); final int bufSize = streamBufferSize; final StringBuilder string = new StringBuilder(bufSize); final char[] buf = new char[bufSize]; for (int len = reader.read(buf); len != -1; len = reader.read(buf)) { string.append(buf, 0, len); } return RubyString.newUnicodeString(runtime, string.toString()); } protected IRubyObject objectToRuby( final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException { final Object value = resultSet.getObject(column); if ( value == null && resultSet.wasNull() ) return runtime.getNil(); return JavaUtil.convertJavaToRuby(runtime, value); } protected IRubyObject arrayToRuby( final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException { final Array value = resultSet.getArray(column); try { if ( value == null && resultSet.wasNull() ) return runtime.getNil(); final RubyArray array = runtime.newArray(); final ResultSet arrayResult = value.getResultSet(); // 1: index, 2: value final int baseType = value.getBaseType(); while ( arrayResult.next() ) { IRubyObject element = jdbcToRuby(runtime, 2, baseType, arrayResult); array.append(element); } return array; } finally { value.free(); } } protected IRubyObject xmlToRuby( final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException { final SQLXML xml = resultSet.getSQLXML(column); try { return RubyString.newUnicodeString(runtime, xml.getString()); } finally { xml.free(); } } /* protected */ void setStatementParameters(final ThreadContext context, final Connection connection, final PreparedStatement statement, final List<?> binds) throws SQLException { final Ruby runtime = context.getRuntime(); for ( int i = 0; i < binds.size(); i++ ) { // [ [ column1, param1 ], [ column2, param2 ], ... ] Object param = binds.get(i); IRubyObject column = null; if ( param.getClass() == RubyArray.class ) { final RubyArray _param = (RubyArray) param; column = _param.eltInternal(0); param = _param.eltInternal(1); } else if ( param instanceof List ) { final List<?> _param = (List<?>) param; column = (IRubyObject) _param.get(0); param = _param.get(1); } else if ( param instanceof Object[] ) { final Object[] _param = (Object[]) param; column = (IRubyObject) _param[0]; param = _param[1]; } final IRubyObject type; if ( column != null && ! column.isNil() ) { type = column.callMethod(context, "type"); } else { type = null; } setStatementParameter(context, runtime, connection, statement, i + 1, param, type); } } /* protected */ void setStatementParameter(final ThreadContext context, final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final Object value, final IRubyObject column) throws SQLException { final RubySymbol columnType = resolveColumnType(context, runtime, column); final int type = jdbcTypeFor(runtime, column, columnType, value); // TODO pass column with (JDBC) type to methods : switch (type) { case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: if ( value instanceof RubyBignum ) { setBigIntegerParameter(runtime, connection, statement, index, type, (RubyBignum) value); } setIntegerParameter(runtime, connection, statement, index, type, value); break; case Types.BIGINT: setBigIntegerParameter(runtime, connection, statement, index, type, value); break; case Types.REAL: case Types.FLOAT: case Types.DOUBLE: setDoubleParameter(runtime, connection, statement, index, type, value); break; case Types.NUMERIC: case Types.DECIMAL: setDecimalParameter(runtime, connection, statement, index, type, value); break; case Types.DATE: setDateParameter(runtime, connection, statement, index, type, value); break; case Types.TIME: setTimeParameter(runtime, connection, statement, index, type, value); break; case Types.TIMESTAMP: setTimestampParameter(runtime, connection, statement, index, type, value); break; case Types.BIT: case Types.BOOLEAN: setBooleanParameter(runtime, connection, statement, index, type, value); break; case Types.SQLXML: setXmlParameter(runtime, connection, statement, index, type, value); break; case Types.ARRAY: setArrayParameter(runtime, connection, statement, index, type, value); break; case Types.JAVA_OBJECT: case Types.OTHER: setObjectParameter(runtime, connection, statement, index, type, value); break; case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: case Types.BLOB: setBlobParameter(runtime, connection, statement, index, type, value); break; case Types.CLOB: case Types.NCLOB: // JDBC 4.0 setClobParameter(runtime, connection, statement, index, type, value); break; case Types.CHAR: case Types.VARCHAR: case Types.NCHAR: // JDBC 4.0 case Types.NVARCHAR: // JDBC 4.0 default: setStringParameter(runtime, connection, statement, index, type, value); } } @Deprecated private void setPreparedStatementValues(final ThreadContext context, final Connection connection, final PreparedStatement statement, final IRubyObject valuesArg, final IRubyObject typesArg) throws SQLException { final Ruby runtime = context.getRuntime(); final RubyArray values = (RubyArray) valuesArg; final RubyArray types = (RubyArray) typesArg; // column types for( int i = 0, j = values.getLength(); i < j; i++ ) { setStatementParameter( context, runtime, connection, statement, i + 1, values.eltInternal(i), types.eltInternal(i) ); } } private RubySymbol resolveColumnType(final ThreadContext context, final Ruby runtime, final IRubyObject column) { if ( column instanceof RubySymbol ) { // deprecated behavior return (RubySymbol) column; } if ( column instanceof RubyString) { // deprecated behavior if ( runtime.is1_9() ) { return ( (RubyString) column ).intern19(); } else { return ( (RubyString) column ).intern(); } } if ( column == null || column.isNil() ) { throw runtime.newArgumentError("nil column passed"); } return (RubySymbol) column.callMethod(context, "type"); } /* protected */ int jdbcTypeFor(final Ruby runtime, final IRubyObject column, final RubySymbol columnType, final Object value) throws SQLException { final String internedType = columnType.asJavaString(); if ( internedType == (Object) "string" ) return Types.VARCHAR; else if ( internedType == (Object) "text" ) return Types.CLOB; else if ( internedType == (Object) "integer" ) return Types.INTEGER; else if ( internedType == (Object) "decimal" ) return Types.DECIMAL; else if ( internedType == (Object) "float" ) return Types.FLOAT; else if ( internedType == (Object) "date" ) return Types.DATE; else if ( internedType == (Object) "time" ) return Types.TIME; else if ( internedType == (Object) "datetime") return Types.TIMESTAMP; else if ( internedType == (Object) "timestamp" ) return Types.TIMESTAMP; else if ( internedType == (Object) "binary" ) return Types.BLOB; else if ( internedType == (Object) "boolean" ) return Types.BOOLEAN; else if ( internedType == (Object) "xml" ) return Types.SQLXML; else if ( internedType == (Object) "array" ) return Types.ARRAY; else return Types.OTHER; // -1 as well as 0 are used in Types } /* protected */ void setIntegerParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setIntegerParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.INTEGER); else { statement.setLong(index, ((Number) value).longValue()); } } } /* protected */ void setIntegerParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.INTEGER); else { if ( value instanceof RubyFixnum ) { statement.setLong(index, ((RubyFixnum) value).getLongValue()); } else { statement.setInt(index, RubyNumeric.fix2int(value)); } } } /* protected */ void setBigIntegerParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setBigIntegerParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.BIGINT); else { if ( value instanceof BigDecimal ) { statement.setBigDecimal(index, (BigDecimal) value); } else if ( value instanceof BigInteger ) { setLongOrDecimalParameter(statement, index, (BigInteger) value); } else { statement.setLong(index, ((Number) value).longValue()); } } } } /* protected */ void setBigIntegerParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.INTEGER); else { if ( value instanceof RubyBignum ) { setLongOrDecimalParameter(statement, index, ((RubyBignum) value).getValue()); } else { statement.setLong(index, ((RubyInteger) value).getLongValue()); } } } private static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE); private static final BigInteger MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE); /* protected */ static void setLongOrDecimalParameter(final PreparedStatement statement, final int index, final BigInteger value) throws SQLException { if ( value.compareTo(MAX_LONG) <= 0 // -1 intValue < MAX_VALUE && value.compareTo(MIN_LONG) >= 0 ) { statement.setLong(index, value.longValue()); } else { statement.setBigDecimal(index, new BigDecimal(value)); } } /* protected */ void setDoubleParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setDoubleParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.DOUBLE); else { statement.setDouble(index, ((Number) value).doubleValue()); } } } /* protected */ void setDoubleParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.DOUBLE); else { statement.setDouble(index, ((RubyNumeric) value).getDoubleValue()); } } /* protected */ void setDecimalParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setDecimalParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.DECIMAL); else { if ( value instanceof BigDecimal ) { statement.setBigDecimal(index, (BigDecimal) value); } else if ( value instanceof BigInteger ) { setLongOrDecimalParameter(statement, index, (BigInteger) value); } else { statement.setDouble(index, ((Number) value).doubleValue()); } } } } /* protected */ void setDecimalParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.DECIMAL); else { // NOTE: RubyBigDecimal moved into org.jruby.ext.bigdecimal (1.6 -> 1.7) if ( value.getMetaClass().getName().indexOf("BigDecimal") != -1 ) { try { // reflect ((RubyBigDecimal) value).getValue() : BigDecimal decValue = (BigDecimal) value.getClass(). getMethod("getValue", (Class<?>[]) null). invoke(value, (Object[]) null); statement.setBigDecimal(index, decValue); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e.getCause() != null ? e.getCause() : e); } } else { statement.setDouble(index, ((RubyNumeric) value).getDoubleValue()); } } } /* protected */ void setTimestampParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setTimestampParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.TIMESTAMP); else { if ( value instanceof Timestamp ) { statement.setTimestamp(index, (Timestamp) value); } else if ( value instanceof java.util.Date ) { statement.setTimestamp(index, new Timestamp(((java.util.Date) value).getTime())); } else { statement.setTimestamp(index, Timestamp.valueOf(value.toString())); } } } } /* protected */ void setTimestampParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.TIMESTAMP); else { if ( value instanceof RubyTime ) { final RubyTime timeValue = (RubyTime) value; final java.util.Date dateValue = timeValue.getJavaDate(); long millis = dateValue.getTime(); Timestamp timestamp = new Timestamp(millis); Calendar calendar = Calendar.getInstance(); calendar.setTime(dateValue); if ( type != Types.DATE ) { int micros = (int) timeValue.microseconds(); timestamp.setNanos( micros * 1000 ); // time.nsec ~ time.usec * 1000 } statement.setTimestamp( index, timestamp, calendar ); } else { final String stringValue = value.convertToString().toString(); // yyyy-[m]m-[d]d hh:mm:ss[.f...] final Timestamp timestamp = Timestamp.valueOf( stringValue ); statement.setTimestamp( index, timestamp, Calendar.getInstance() ); } } } /* protected */ void setTimeParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setTimeParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.TIME); else { if ( value instanceof Time ) { statement.setTime(index, (Time) value); } else if ( value instanceof java.util.Date ) { statement.setTime(index, new Time(((java.util.Date) value).getTime())); } else { // hh:mm:ss statement.setTime(index, Time.valueOf(value.toString())); // statement.setString(index, value.toString()); } } } } /* protected */ void setTimeParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.TIME); else { // setTimestampParameter(runtime, connection, statement, index, type, value); if ( value instanceof RubyTime ) { final RubyTime timeValue = (RubyTime) value; final java.util.Date dateValue = timeValue.getJavaDate(); Time time = new Time(dateValue.getTime()); Calendar calendar = Calendar.getInstance(); calendar.setTime(dateValue); statement.setTime( index, time, calendar ); } else { final String stringValue = value.convertToString().toString(); final Time time = Time.valueOf( stringValue ); statement.setTime( index, time, Calendar.getInstance() ); } } } /* protected */ void setDateParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setDateParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.DATE); else { if ( value instanceof Date ) { statement.setDate(index, (Date) value); } else if ( value instanceof java.util.Date ) { statement.setDate(index, new Date(((java.util.Date) value).getTime())); } else { // yyyy-[m]m-[d]d statement.setDate(index, Date.valueOf(value.toString())); // statement.setString(index, value.toString()); } } } } /* protected */ void setDateParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.DATE); else { // setTimestampParameter(runtime, connection, statement, index, type, value); if ( value instanceof RubyTime ) { final RubyTime timeValue = (RubyTime) value; final java.util.Date dateValue = timeValue.getJavaDate(); Date date = new Date(dateValue.getTime()); Calendar calendar = Calendar.getInstance(); calendar.setTime(dateValue); statement.setDate( index, date, calendar ); } else { final String stringValue = value.convertToString().toString(); final Date date = Date.valueOf( stringValue ); statement.setDate( index, date, Calendar.getInstance() ); } } } /* protected */ void setBooleanParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setBooleanParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.BOOLEAN); else { statement.setBoolean(index, ((Boolean) value).booleanValue()); } } } /* protected */ void setBooleanParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.BOOLEAN); else { statement.setBoolean(index, value.isTrue()); } } /* protected */ void setStringParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setStringParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.VARCHAR); else { statement.setString(index, value.toString()); } } } /* protected */ void setStringParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.VARCHAR); else { statement.setString(index, value.convertToString().toString()); } } /* protected */ void setArrayParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setArrayParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.ARRAY); else { // TODO get array element type name ?! Array array = connection.createArrayOf(null, (Object[]) value); statement.setArray(index, array); } } } /* protected */ void setArrayParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.ARRAY); else { // TODO get array element type name ?! Array array = connection.createArrayOf(null, ((RubyArray) value).toArray()); statement.setArray(index, array); } } /* protected */ void setXmlParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setXmlParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.SQLXML); else { SQLXML xml = connection.createSQLXML(); xml.setString(value.toString()); statement.setSQLXML(index, xml); } } } /* protected */ void setXmlParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.SQLXML); else { SQLXML xml = connection.createSQLXML(); xml.setString(value.convertToString().toString()); statement.setSQLXML(index, xml); } } /* protected */ void setBlobParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setBlobParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.BLOB); else { statement.setBlob(index, (InputStream) value); } } } /* protected */ void setBlobParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.BLOB); else { if ( value instanceof RubyString ) { statement.setBlob(index, new ByteArrayInputStream(((RubyString) value).getBytes())); } else { // assume IO/File statement.setBlob(index, ((RubyIO) value).getInStream()); } } } /* protected */ void setClobParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setClobParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.CLOB); else { statement.setClob(index, (Reader) value); } } } /* protected */ void setClobParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.CLOB); else { if ( value instanceof RubyString ) { statement.setClob(index, new StringReader(((RubyString) value).decodeString())); } else { // assume IO/File statement.setClob(index, new InputStreamReader(((RubyIO) value).getInStream())); } } } /* protected */ void setObjectParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, Object value) throws SQLException { if (value instanceof IRubyObject) { value = ((IRubyObject) value).toJava(Object.class); } if ( value == null ) statement.setNull(index, Types.JAVA_OBJECT); statement.setObject(index, value); } protected final Connection getConnection() { return getConnection(false); } protected Connection getConnection(boolean error) { final Connection connection = (Connection) dataGetStruct(); if ( connection == null && error ) { final RubyClass errorClass = getConnectionNotEstablished( getRuntime() ); throw new RaiseException(getRuntime(), errorClass, "no connection available", false); } return connection; } private synchronized RubyJdbcConnection setConnection(final Connection connection) { close( getConnection(false) ); // close previously open connection if there is one final IRubyObject rubyConnectionObject = connection != null ? convertJavaToRuby(connection) : getRuntime().getNil(); setInstanceVariable( "@connection", rubyConnectionObject ); dataWrapStruct(connection); return this; } private boolean isConnectionBroken(final ThreadContext context, final Connection connection) { Statement statement = null; try { final RubyString aliveSQL = getConfigValue(context, "connection_alive_sql").convertToString(); if ( isSelect(aliveSQL) ) { // expect a SELECT/CALL SQL statement statement = createStatement(context, connection); statement.execute( aliveSQL.toString() ); return false; // connection ain't broken } else { // alive_sql nil (or not a statement we can execute) return ! connection.isClosed(); // if closed than broken } } catch (Exception e) { debugMessage(context, "connection considered broken due: " + e.toString()); return true; } finally { close(statement); } } private boolean tableExists(final Ruby runtime, final Connection connection, final TableName tableName) throws SQLException { final IRubyObject matchedTables = matchTables(runtime, connection, tableName.catalog, tableName.schema, tableName.name, getTableTypes(), true); // NOTE: allow implementers to ignore checkExistsOnly paramater - empty array means does not exists return matchedTables != null && ! matchedTables.isNil() && ( ! (matchedTables instanceof RubyArray) || ! ((RubyArray) matchedTables).isEmpty() ); } /** * Match table names for given table name (pattern). * @param runtime * @param connection * @param catalog * @param schemaPattern * @param tablePattern * @param types table types * @param checkExistsOnly an optimization flag (that might be ignored by sub-classes) * whether the result really matters if true no need to map table names and a truth-y * value is sufficient (except for an empty array which is considered that the table * did not exists). * @return matched (and Ruby mapped) table names * @see #mapTables(Ruby, DatabaseMetaData, String, String, String, ResultSet) * @throws SQLException */ protected IRubyObject matchTables(final Ruby runtime, final Connection connection, final String catalog, final String schemaPattern, final String tablePattern, final String[] types, final boolean checkExistsOnly) throws SQLException { final DatabaseMetaData metaData = connection.getMetaData(); final String _tablePattern = caseConvertIdentifierForJdbc(metaData, tablePattern); final String _schemaPattern = caseConvertIdentifierForJdbc(metaData, schemaPattern); ResultSet tablesSet = null; try { tablesSet = metaData.getTables(catalog, _schemaPattern, _tablePattern, types); if ( checkExistsOnly ) { // only check if given table exists return tablesSet.next() ? runtime.getTrue() : null; } else { return mapTables(runtime, metaData, catalog, _schemaPattern, _tablePattern, tablesSet); } } finally { close(tablesSet); } } // NOTE java.sql.DatabaseMetaData.getTables : protected final static int TABLES_TABLE_CAT = 1; protected final static int TABLES_TABLE_SCHEM = 2; protected final static int TABLES_TABLE_NAME = 3; protected final static int TABLES_TABLE_TYPE = 4; /** * @param runtime * @param metaData * @param catalog * @param schemaPattern * @param tablePattern * @param tablesSet * @return List<RubyString> * @throws SQLException */ protected RubyArray mapTables(final Ruby runtime, final DatabaseMetaData metaData, final String catalog, final String schemaPattern, final String tablePattern, final ResultSet tablesSet) throws SQLException { final RubyArray tables = runtime.newArray(); while ( tablesSet.next() ) { String name = tablesSet.getString(TABLES_TABLE_NAME); name = caseConvertIdentifierForRails(metaData, name); tables.add(RubyString.newUnicodeString(runtime, name)); } return tables; } /** * NOTE: since 1.3.0 only present for binary compatibility (with extensions). * * @depreacated no longer used - replaced with * {@link #matchTables(Ruby, Connection, String, String, String, String[], boolean)} * please update your sub-class esp. if you're overriding this method ! */ @Deprecated protected SQLBlock tableLookupBlock(final Ruby runtime, final String catalog, final String schemaPattern, final String tablePattern, final String[] types) { return new SQLBlock() { public IRubyObject call(final Connection connection) throws SQLException { return matchTables(runtime, connection, catalog, schemaPattern, tablePattern, types, false); } }; } protected static final int COLUMN_NAME = 4; protected static final int DATA_TYPE = 5; protected static final int TYPE_NAME = 6; protected static final int COLUMN_SIZE = 7; protected static final int DECIMAL_DIGITS = 9; protected static final int COLUMN_DEF = 13; protected static final int IS_NULLABLE = 18; /** * Create a string which represents a SQL type usable by Rails from the * resultSet column meta-data * @param resultSet. */ protected String typeFromResultSet(final ResultSet resultSet) throws SQLException { final int precision = intFromResultSet(resultSet, COLUMN_SIZE); final int scale = intFromResultSet(resultSet, DECIMAL_DIGITS); final String type = resultSet.getString(TYPE_NAME); return formatTypeWithPrecisionAndScale(type, precision, scale); } protected static int intFromResultSet( final ResultSet resultSet, final int column) throws SQLException { final int precision = resultSet.getInt(column); return precision == 0 && resultSet.wasNull() ? -1 : precision; } protected static String formatTypeWithPrecisionAndScale( final String type, final int precision, final int scale) { if ( precision <= 0 ) return type; final StringBuilder typeStr = new StringBuilder().append(type); typeStr.append('(').append(precision); // type += "(" + precision; if ( scale > 0 ) typeStr.append(',').append(scale); // type += "," + scale; return typeStr.append(')').toString(); // type += ")"; } private static IRubyObject defaultValueFromResultSet(final Ruby runtime, final ResultSet resultSet) throws SQLException { final String defaultValue = resultSet.getString(COLUMN_DEF); return defaultValue == null ? runtime.getNil() : RubyString.newUnicodeString(runtime, defaultValue); } private IRubyObject unmarshalColumns(final ThreadContext context, final DatabaseMetaData metaData, final ResultSet results, final ResultSet primaryKeys) throws SQLException { final Ruby runtime = context.getRuntime(); // RubyHash types = (RubyHash) native_database_types(); final IRubyObject jdbcColumn = getJdbcColumnClass(context); final List<String> primarykeyNames = new ArrayList<String>(); while ( primaryKeys.next() ) { primarykeyNames.add( primaryKeys.getString(COLUMN_NAME) ); } final List<IRubyObject> columns = new ArrayList<IRubyObject>(); while ( results.next() ) { final String colName = results.getString(COLUMN_NAME); IRubyObject column = jdbcColumn.callMethod(context, "new", new IRubyObject[] { getInstanceVariable("@config"), RubyString.newUnicodeString( runtime, caseConvertIdentifierForRails(metaData, colName) ), defaultValueFromResultSet( runtime, results ), RubyString.newUnicodeString( runtime, typeFromResultSet(results) ), runtime.newBoolean( ! results.getString(IS_NULLABLE).trim().equals("NO") ) }); columns.add(column); if ( primarykeyNames.contains(colName) ) { column.callMethod(context, "primary=", runtime.getTrue()); } } return runtime.newArray(columns); } protected static IRubyObject unmarshalIdResult( final Ruby runtime, final Statement statement) throws SQLException { final ResultSet genKeys = statement.getGeneratedKeys(); try { if (genKeys.next() && genKeys.getMetaData().getColumnCount() > 0) { return runtime.newFixnum( genKeys.getLong(1) ); } return runtime.getNil(); } finally { close(genKeys); } } /** * @deprecated no longer used - kept for binary compatibility, this method * is confusing since it closes the result set it receives and thus was * replaced with {@link #unmarshalIdResult(Ruby, Statement)} */ @Deprecated public static IRubyObject unmarshal_id_result( final Ruby runtime, final ResultSet genKeys) throws SQLException { try { if (genKeys.next() && genKeys.getMetaData().getColumnCount() > 0) { return runtime.newFixnum( genKeys.getLong(1) ); } return runtime.getNil(); } finally { close(genKeys); } } protected IRubyObject unmarshalResults(final ThreadContext context, final DatabaseMetaData metaData, final Statement statement, final boolean downCase) throws SQLException { final Ruby runtime = context.getRuntime(); IRubyObject result; ResultSet resultSet = statement.getResultSet(); try { result = mapToRawResult(context, runtime, metaData, resultSet, downCase); } finally { close(resultSet); } if ( ! statement.getMoreResults() ) return result; final List<IRubyObject> results = new ArrayList<IRubyObject>(); results.add(result); do { resultSet = statement.getResultSet(); try { result = mapToRawResult(context, runtime, metaData, resultSet, downCase); } finally { close(resultSet); } results.add(result); } while ( statement.getMoreResults() ); return runtime.newArray(results); } /** * @deprecated no longer used but kept for binary compatibility */ @Deprecated protected IRubyObject unmarshalResult(final ThreadContext context, final DatabaseMetaData metaData, final ResultSet resultSet, final boolean downCase) throws SQLException { return mapToRawResult(context, context.getRuntime(), metaData, resultSet, downCase); } /** * Converts a JDBC result set into an array (rows) of hashes (row). * * @param downCase should column names only be in lower case? */ @SuppressWarnings("unchecked") private IRubyObject mapToRawResult(final ThreadContext context, final Ruby runtime, final DatabaseMetaData metaData, final ResultSet resultSet, final boolean downCase) throws SQLException { final ColumnData[] columns = extractColumns(runtime, metaData, resultSet, downCase); final RubyArray results = runtime.newArray(); // [ { 'col1': 1, 'col2': 2 }, { 'col1': 3, 'col2': 4 } ] populateFromResultSet(context, runtime, (List<IRubyObject>) results, resultSet, columns); return results; } private IRubyObject yieldResultRows(final ThreadContext context, final Ruby runtime, final DatabaseMetaData metaData, final ResultSet resultSet, final Block block) throws SQLException { final ColumnData[] columns = extractColumns(runtime, metaData, resultSet, false); final IRubyObject[] blockArgs = new IRubyObject[columns.length]; while ( resultSet.next() ) { for ( int i = 0; i < columns.length; i++ ) { final ColumnData column = columns[i]; blockArgs[i] = jdbcToRuby(runtime, column.index, column.type, resultSet); } block.call( context, blockArgs ); } return runtime.getNil(); // yielded result rows } /** * Extract columns from result set. * @param runtime * @param metaData * @param resultSet * @param downCase * @return columns data * @throws SQLException */ protected ColumnData[] extractColumns(final Ruby runtime, final DatabaseMetaData metaData, final ResultSet resultSet, final boolean downCase) throws SQLException { return setupColumns(runtime, metaData, resultSet.getMetaData(), downCase); } /** * @deprecated renamed and parameterized to {@link #withConnection(ThreadContext, SQLBlock)} */ @Deprecated @SuppressWarnings("unchecked") protected Object withConnectionAndRetry(final ThreadContext context, final SQLBlock block) throws RaiseException { return withConnection(context, block); } protected <T> T withConnection(final ThreadContext context, final Callable<T> block) throws RaiseException { try { return withConnection(context, true, block); } catch (final SQLException e) { return handleException(context, e); // should never happen } } private <T> T withConnection(final ThreadContext context, final boolean handleException, final Callable<T> block) throws RaiseException, RuntimeException, SQLException { Throwable exception = null; int tries = 1; int i = 0; while ( i++ < tries ) { final Connection connection = getConnection(true); boolean autoCommit = true; // retry in-case getAutoCommit throws try { autoCommit = connection.getAutoCommit(); return block.call(connection); } catch (final Exception e) { // SQLException or RuntimeException exception = e; if ( autoCommit ) { // do not retry if (inside) transactions if ( i == 1 ) { IRubyObject retryCount = getConfigValue(context, "retry_count"); tries = (int) retryCount.convertToInteger().getLongValue(); if ( tries <= 0 ) tries = 1; } if ( isConnectionBroken(context, connection) ) { reconnect(context); continue; // retry connection (block) again } break; // connection not broken yet failed } } } // (retry) loop ended and we did not return ... exception != null if ( handleException ) { return handleException(context, getCause(exception)); // throws } else { if ( exception instanceof SQLException ) { throw (SQLException) exception; } if ( exception instanceof RuntimeException ) { throw (RuntimeException) exception; } // won't happen - our try block only throws SQL or Runtime exceptions throw new RuntimeException(exception); } } private static Throwable getCause(Throwable exception) { Throwable cause = exception.getCause(); while (cause != null && cause != exception) { // SQLException's cause might be DB specific (checked/unchecked) : if ( exception instanceof SQLException ) break; exception = cause; cause = exception.getCause(); } return exception; } protected <T> T handleException(final ThreadContext context, Throwable exception) throws RaiseException { // NOTE: we shall not wrap unchecked (runtime) exceptions into AR::Error // if it's really a misbehavior of the driver throwing a RuntimeExcepion // instead of SQLException than this should be overriden for the adapter if ( exception instanceof RuntimeException ) { throw (RuntimeException) exception; } debugStackTrace(context, exception); throw wrapException(context, exception); } /** * @deprecated use {@link #wrapException(ThreadContext, Throwable)} instead * for overriding how exceptions are handled use {@link #handleException(ThreadContext, Throwable)} */ @Deprecated protected RuntimeException wrap(final ThreadContext context, final Throwable exception) { return wrapException(context, exception); } protected RaiseException wrapException(final ThreadContext context, final Throwable exception) { final Ruby runtime = context.getRuntime(); if ( exception instanceof SQLException ) { final String message = SQLException.class == exception.getClass() ? exception.getMessage() : exception.toString(); // useful to easily see type on Ruby side final RaiseException error = wrapException(context, getJDBCError(runtime), exception, message); final int errorCode = ((SQLException) exception).getErrorCode(); RuntimeHelpers.invoke( context, error.getException(), "errno=", runtime.newFixnum(errorCode) ); RuntimeHelpers.invoke( context, error.getException(), "sql_exception=", JavaEmbedUtils.javaToRuby(runtime, exception) ); return error; } return wrapException(context, getJDBCError(runtime), exception); } protected static RaiseException wrapException(final ThreadContext context, final RubyClass errorClass, final Throwable exception) { return wrapException(context, errorClass, exception, exception.toString()); } protected static RaiseException wrapException(final ThreadContext context, final RubyClass errorClass, final Throwable exception, final String message) { final RaiseException error = new RaiseException(context.getRuntime(), errorClass, message, true); error.initCause(exception); return error; } private IRubyObject convertJavaToRuby(final Connection connection) { return JavaUtil.convertJavaToRuby( getRuntime(), connection ); } /** * Some databases support schemas and others do not. * For ones which do this method should return true, aiding in decisions regarding schema vs database determination. */ protected boolean databaseSupportsSchemas() { return false; } private static final byte[] SELECT = new byte[] { 's','e','l','e','c','t' }; private static final byte[] WITH = new byte[] { 'w','i','t','h' }; private static final byte[] SHOW = new byte[] { 's','h','o','w' }; private static final byte[] CALL = new byte[]{ 'c','a','l','l' }; @JRubyMethod(name = "select?", required = 1, meta = true, frame = false) public static IRubyObject select_p(final ThreadContext context, final IRubyObject self, final IRubyObject sql) { return context.getRuntime().newBoolean( isSelect(sql.convertToString()) ); } private static boolean isSelect(final RubyString sql) { final ByteList sqlBytes = sql.getByteList(); return startsWithIgnoreCase(sqlBytes, SELECT) || startsWithIgnoreCase(sqlBytes, WITH) || startsWithIgnoreCase(sqlBytes, SHOW) || startsWithIgnoreCase(sqlBytes, CALL); } private static final byte[] INSERT = new byte[] { 'i','n','s','e','r','t' }; @JRubyMethod(name = "insert?", required = 1, meta = true, frame = false) public static IRubyObject insert_p(final ThreadContext context, final IRubyObject self, final IRubyObject sql) { final ByteList sqlBytes = sql.convertToString().getByteList(); return context.getRuntime().newBoolean(startsWithIgnoreCase(sqlBytes, INSERT)); } protected static boolean startsWithIgnoreCase(final ByteList string, final byte[] start) { int p = skipWhitespace(string, string.getBegin()); final byte[] stringBytes = string.unsafeBytes(); if ( stringBytes[p] == '(' ) p = skipWhitespace(string, p + 1); for ( int i = 0; i < string.getRealSize() && i < start.length; i++ ) { if ( Character.toLowerCase(stringBytes[p + i]) != start[i] ) return false; } return true; } private static int skipWhitespace(final ByteList string, final int from) { final int end = string.getBegin() + string.getRealSize(); final byte[] stringBytes = string.unsafeBytes(); for ( int i = from; i < end; i++ ) { if ( ! Character.isWhitespace( stringBytes[i] ) ) return i; } return end; } /** * JDBC connection helper that handles mapping results to * <code>ActiveRecord::Result</code> (available since AR-3.1). * * @see #populateFromResultSet(ThreadContext, Ruby, List, ResultSet, RubyJdbcConnection.ColumnData[]) * @author kares */ protected static class ResultHandler { protected static Boolean USE_RESULT; // AR-3.2 : initialize(columns, rows) // AR-4.0 : initialize(columns, rows, column_types = {}) protected static Boolean INIT_COLUMN_TYPES = Boolean.FALSE; protected static Boolean FORCE_HASH_ROWS = Boolean.FALSE; private static volatile ResultHandler instance; public static ResultHandler getInstance(final ThreadContext context) { if ( instance == null ) { synchronized(ResultHandler.class) { if ( instance == null ) { // fine to initialize twice setInstance( new ResultHandler(context) ); } } } return instance; } protected static synchronized void setInstance(final ResultHandler instance) { ResultHandler.instance = instance; } protected ResultHandler(final ThreadContext context) { final Ruby runtime = context.getRuntime(); final RubyClass result = getResult(runtime); USE_RESULT = result != null && result != runtime.getNilClass(); } public IRubyObject mapRow(final ThreadContext context, final Ruby runtime, final ColumnData[] columns, final ResultSet resultSet, final RubyJdbcConnection connection) throws SQLException { if ( USE_RESULT ) { // maps a AR::Result row final RubyArray row = runtime.newArray(columns.length); for ( int i = 0; i < columns.length; i++ ) { final ColumnData column = columns[i]; row.append( connection.jdbcToRuby(runtime, column.index, column.type, resultSet) ); } return row; } else { return mapRawRow(context, runtime, columns, resultSet, connection); } } IRubyObject mapRawRow(final ThreadContext context, final Ruby runtime, final ColumnData[] columns, final ResultSet resultSet, final RubyJdbcConnection connection) throws SQLException { final RubyHash row = RubyHash.newHash(runtime); for ( int i = 0; i < columns.length; i++ ) { final ColumnData column = columns[i]; row.op_aset( context, column.name, connection.jdbcToRuby(runtime, column.index, column.type, resultSet) ); } return row; } public IRubyObject newResult(final ThreadContext context, final Ruby runtime, final ColumnData[] columns, final IRubyObject rows) { // rows array if ( USE_RESULT ) { // ActiveRecord::Result.new(columns, rows) final RubyClass result = getResult(runtime); return result.callMethod( context, "new", initArgs(runtime, columns, rows), Block.NULL_BLOCK ); } return rows; // contains { 'col1' => 1, ... } Hash-es } private IRubyObject[] initArgs(final Ruby runtime, final ColumnData[] columns, final IRubyObject rows) { final IRubyObject[] args; final RubyArray cols = runtime.newArray(columns.length); if ( INIT_COLUMN_TYPES ) { // NOTE: NOT IMPLEMENTED for ( int i=0; i<columns.length; i++ ) { cols.add( columns[i].name ); } args = new IRubyObject[] { cols, rows }; } else { for ( int i=0; i<columns.length; i++ ) { cols.add( columns[i].name ); } args = new IRubyObject[] { cols, rows }; } return args; } } protected static final class TableName { public final String catalog, schema, name; public TableName(String catalog, String schema, String table) { this.catalog = catalog; this.schema = schema; this.name = table; } } /** * Extract the table name components for the given name e.g. "mycat.sys.entries" * * @param connection * @param catalog (optional) catalog to use if table name does not contain * the catalog prefix * @param schema (optional) schema to use if table name does not have one * @param tableName the table name * @return (parsed) table name * * @throws IllegalArgumentException for invalid table name format * @throws SQLException */ protected TableName extractTableName( final Connection connection, String catalog, String schema, final String tableName) throws IllegalArgumentException, SQLException { final String[] nameParts = tableName.split("\\."); if ( nameParts.length > 3 ) { throw new IllegalArgumentException("table name: " + tableName + " should not contain more than 2 '.'"); } String name = tableName; if ( nameParts.length == 2 ) { schema = nameParts[0]; name = nameParts[1]; } else if ( nameParts.length == 3 ) { catalog = nameParts[0]; schema = nameParts[1]; name = nameParts[2]; } final DatabaseMetaData metaData = connection.getMetaData(); if (schema != null) { schema = caseConvertIdentifierForJdbc(metaData, schema); } name = caseConvertIdentifierForJdbc(metaData, name); if (schema != null && ! databaseSupportsSchemas()) { catalog = schema; } if (catalog == null) catalog = connection.getCatalog(); return new TableName(catalog, schema, name); } /** * @deprecated use {@link #extractTableName(Connection, String, String, String)} */ @Deprecated protected TableName extractTableName( final Connection connection, final String schema, final String tableName) throws IllegalArgumentException, SQLException { return extractTableName(connection, null, schema, tableName); } protected static final class ColumnData { public final RubyString name; public final int index; public final int type; public ColumnData(RubyString name, int type, int idx) { this.name = name; this.type = type; this.index = idx; } } private static ColumnData[] setupColumns( final Ruby runtime, final DatabaseMetaData metaData, final ResultSetMetaData resultMetaData, final boolean downCase) throws SQLException { final int columnCount = resultMetaData.getColumnCount(); final ColumnData[] columns = new ColumnData[columnCount]; for ( int i = 1; i <= columnCount; i++ ) { // metadata is one-based final String name; if (downCase) { name = resultMetaData.getColumnLabel(i).toLowerCase(); } else { name = caseConvertIdentifierForRails(metaData, resultMetaData.getColumnLabel(i)); } final int columnType = resultMetaData.getColumnType(i); final RubyString columnName = RubyString.newUnicodeString(runtime, name); columns[i - 1] = new ColumnData(columnName, columnType, i); } return columns; } // JDBC API Helpers : protected static void close(final Connection connection) { if ( connection != null ) { try { connection.close(); } catch (final Exception e) { /* NOOP */ } } } public static void close(final ResultSet resultSet) { if (resultSet != null) { try { resultSet.close(); } catch (final Exception e) { /* NOOP */ } } } public static void close(final Statement statement) { if (statement != null) { try { statement.close(); } catch (final Exception e) { /* NOOP */ } } } // DEBUG-ing helpers : private static boolean debug = Boolean.getBoolean("arjdbc.debug"); public static boolean isDebug() { return debug; } public static void setDebug(boolean debug) { RubyJdbcConnection.debug = debug; } public static void debugMessage(final ThreadContext context, final String msg) { if ( debug || context.runtime.isDebug() ) { context.runtime.getOut().println(msg); } } protected static void debugErrorSQL(final ThreadContext context, final String sql) { if ( debug || context.runtime.isDebug() ) { context.runtime.getOut().println("Error SQL: " + sql); } } public static void debugStackTrace(final ThreadContext context, final Throwable e) { if ( debug || context.runtime.isDebug() ) { e.printStackTrace(context.runtime.getOut()); } } private static RubyArray createCallerBacktrace(final ThreadContext context) { final Ruby runtime = context.getRuntime(); runtime.incrementCallerCount(); Method gatherCallerBacktrace; RubyStackTraceElement[] trace; try { gatherCallerBacktrace = context.getClass().getMethod("gatherCallerBacktrace"); trace = (RubyStackTraceElement[]) gatherCallerBacktrace.invoke(context); // 1.6.8 } catch (NoSuchMethodException ignore) { try { gatherCallerBacktrace = context.getClass().getMethod("gatherCallerBacktrace", Integer.TYPE); trace = (RubyStackTraceElement[]) gatherCallerBacktrace.invoke(context, 0); // 1.7.4 } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e.getTargetException()); } } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e.getTargetException()); } // RubyStackTraceElement[] trace = context.gatherCallerBacktrace(level); final RubyArray backtrace = runtime.newArray(trace.length); for (int i = 0; i < trace.length; i++) { RubyStackTraceElement element = trace[i]; backtrace.append( RubyString.newString(runtime, element.getFileName() + ":" + element.getLineNumber() + ":in `" + element.getMethodName() + "'" ) ); } return backtrace; } }
src/java/arjdbc/jdbc/RubyJdbcConnection.java
/* **** BEGIN LICENSE BLOCK ***** * Copyright (c) 2006-2011 Nick Sieger <[email protected]> * Copyright (c) 2006-2007 Ola Bini <[email protected]> * Copyright (c) 2008-2009 Thomas E Enebo <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ***** END LICENSE BLOCK *****/ package arjdbc.jdbc; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.lang.reflect.InvocationTargetException; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Array; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.SQLXML; import java.sql.Statement; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import org.jruby.Ruby; import org.jruby.RubyArray; import org.jruby.RubyBignum; import org.jruby.RubyBoolean; import org.jruby.RubyClass; import org.jruby.RubyFixnum; import org.jruby.RubyHash; import org.jruby.RubyIO; import org.jruby.RubyInteger; import org.jruby.RubyModule; import org.jruby.RubyNumeric; import org.jruby.RubyObject; import org.jruby.RubyString; import org.jruby.RubySymbol; import org.jruby.RubyTime; import org.jruby.anno.JRubyMethod; import org.jruby.exceptions.RaiseException; import org.jruby.javasupport.JavaEmbedUtils; import org.jruby.javasupport.JavaUtil; import org.jruby.javasupport.util.RuntimeHelpers; import org.jruby.runtime.Arity; import org.jruby.runtime.Block; import org.jruby.runtime.ObjectAllocator; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.util.ByteList; /** * Part of our ActiveRecord::ConnectionAdapters::Connection impl. */ public class RubyJdbcConnection extends RubyObject { private static final String[] TABLE_TYPE = new String[] { "TABLE" }; private static final String[] TABLE_TYPES = new String[] { "TABLE", "VIEW", "SYNONYM" }; protected RubyJdbcConnection(Ruby runtime, RubyClass metaClass) { super(runtime, metaClass); } private static ObjectAllocator JDBCCONNECTION_ALLOCATOR = new ObjectAllocator() { public IRubyObject allocate(Ruby runtime, RubyClass klass) { return new RubyJdbcConnection(runtime, klass); } }; public static RubyClass createJdbcConnectionClass(final Ruby runtime) { RubyClass jdbcConnection = getConnectionAdapters(runtime). defineClassUnder("JdbcConnection", runtime.getObject(), JDBCCONNECTION_ALLOCATOR); jdbcConnection.defineAnnotatedMethods(RubyJdbcConnection.class); return jdbcConnection; } public static RubyClass getJdbcConnectionClass(final Ruby runtime) { return getConnectionAdapters(runtime).getClass("JdbcConnection"); } /** * @param runtime * @return <code>ActiveRecord::ConnectionAdapters</code> */ protected static RubyModule getConnectionAdapters(final Ruby runtime) { return (RubyModule) runtime.getModule("ActiveRecord").getConstant("ConnectionAdapters"); } /** * @param runtime * @return <code>ActiveRecord::Result</code> */ static RubyClass getResult(final Ruby runtime) { return runtime.getModule("ActiveRecord").getClass("Result"); } /** * @param runtime * @return <code>ActiveRecord::ConnectionAdapters::IndexDefinition</code> */ protected static RubyClass getIndexDefinition(final Ruby runtime) { return getConnectionAdapters(runtime).getClass("IndexDefinition"); } /** * @param runtime * @return <code>ActiveRecord::JDBCError</code> */ protected static RubyClass getJDBCError(final Ruby runtime) { return runtime.getModule("ActiveRecord").getClass("JDBCError"); } /** * @param runtime * @return <code>ActiveRecord::ConnectionNotEstablished</code> */ protected static RubyClass getConnectionNotEstablished(final Ruby runtime) { return runtime.getModule("ActiveRecord").getClass("ConnectionNotEstablished"); } /** * NOTE: Only available since AR-4.0 * @param runtime * @return <code>ActiveRecord::TransactionIsolationError</code> */ protected static RubyClass getTransactionIsolationError(final Ruby runtime) { return (RubyClass) runtime.getModule("ActiveRecord").getConstant("TransactionIsolationError"); } /** * @param runtime * @return <code>ActiveRecord::ConnectionAdapters::JdbcTypeConverter</code> */ private static RubyClass getJdbcTypeConverter(final Ruby runtime) { return getConnectionAdapters(runtime).getClass("JdbcTypeConverter"); } /* def transaction_isolation_levels { read_uncommitted: "READ UNCOMMITTED", read_committed: "READ COMMITTED", repeatable_read: "REPEATABLE READ", serializable: "SERIALIZABLE" } end */ public static int mapTransactionIsolationLevel(IRubyObject isolation) { if ( ! ( isolation instanceof RubySymbol ) ) { isolation = isolation.convertToString().callMethod("intern"); } final Object isolationString = isolation.toString(); // RubySymbol.toString if ( isolationString == "read_uncommitted" ) return Connection.TRANSACTION_READ_UNCOMMITTED; // 1 if ( isolationString == "read_committed" ) return Connection.TRANSACTION_READ_COMMITTED; // 2 if ( isolationString == "repeatable_read" ) return Connection.TRANSACTION_REPEATABLE_READ; // 4 if ( isolationString == "serializable" ) return Connection.TRANSACTION_SERIALIZABLE; // 8 throw new IllegalArgumentException( "unexpected isolation level: " + isolation + " (" + isolationString + ")" ); } @JRubyMethod(name = "supports_transaction_isolation?", optional = 1) public IRubyObject supports_transaction_isolation_p(final ThreadContext context, final IRubyObject[] args) throws SQLException { final IRubyObject isolation = args.length > 0 ? args[0] : null; return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { final DatabaseMetaData metaData = connection.getMetaData(); final boolean supported; if ( isolation != null && ! isolation.isNil() ) { final int level = mapTransactionIsolationLevel(isolation); supported = metaData.supportsTransactionIsolationLevel(level); } else { final int level = metaData.getDefaultTransactionIsolation(); supported = level > Connection.TRANSACTION_NONE; // > 0 } return context.getRuntime().newBoolean(supported); } }); } @JRubyMethod(name = "begin", optional = 1) // optional isolation argument for AR-4.0 public IRubyObject begin(final ThreadContext context, final IRubyObject[] args) { final IRubyObject isolation = args.length > 0 ? args[0] : null; try { // handleException == false so we can handle setTXIsolation return withConnection(context, false, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { connection.setAutoCommit(false); if ( isolation != null && ! isolation.isNil() ) { final int level = mapTransactionIsolationLevel(isolation); try { connection.setTransactionIsolation(level); } catch (SQLException e) { RubyClass txError = getTransactionIsolationError(context.getRuntime()); if ( txError != null ) throw wrapException(context, txError, e); throw e; // let it roll - will be wrapped into a JDBCError (non 4.0) } } return context.getRuntime().getNil(); } }); } catch (SQLException e) { return handleException(context, e); } } @JRubyMethod(name = "commit") public IRubyObject commit(final ThreadContext context) { final Connection connection = getConnection(true); try { if ( ! connection.getAutoCommit() ) { try { connection.commit(); return context.getRuntime().newBoolean(true); } finally { connection.setAutoCommit(true); } } return context.getRuntime().getNil(); } catch (SQLException e) { return handleException(context, e); } } @JRubyMethod(name = "rollback") public IRubyObject rollback(final ThreadContext context) { final Connection connection = getConnection(true); try { if ( ! connection.getAutoCommit() ) { try { connection.rollback(); return context.getRuntime().newBoolean(true); } finally { connection.setAutoCommit(true); } } return context.getRuntime().getNil(); } catch (SQLException e) { return handleException(context, e); } } @JRubyMethod(name = "connection") public IRubyObject connection(final ThreadContext context) { if ( getConnection(false) == null ) { synchronized (this) { if ( getConnection(false) == null ) { reconnect(context); } } } return getInstanceVariable("@connection"); } @JRubyMethod(name = "disconnect!") public IRubyObject disconnect(final ThreadContext context) { // TODO: only here to try resolving multi-thread issues : // https://github.com/jruby/activerecord-jdbc-adapter/issues/197 // https://github.com/jruby/activerecord-jdbc-adapter/issues/198 if ( Boolean.getBoolean("arjdbc.disconnect.debug") ) { final Ruby runtime = context.getRuntime(); List backtrace = (List) context.createCallerBacktrace(runtime, 0); runtime.getOut().println(this + " connection.disconnect! occured: "); for ( Object element : backtrace ) { runtime.getOut().println(element); } runtime.getOut().flush(); } return setConnection(null); } @JRubyMethod(name = "reconnect!") public IRubyObject reconnect(final ThreadContext context) { try { return setConnection( getConnectionFactory().newConnection() ); } catch (SQLException e) { return handleException(context, e); } } @JRubyMethod(name = "database_name") public IRubyObject database_name(ThreadContext context) throws SQLException { Connection connection = getConnection(true); String name = connection.getCatalog(); if (null == name) { name = connection.getMetaData().getUserName(); if (null == name) name = "db1"; } return context.getRuntime().newString(name); } @JRubyMethod(name = "execute", required = 1) public IRubyObject execute(final ThreadContext context, final IRubyObject sql) { return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { Statement statement = null; final String query = sql.convertToString().getUnicodeValue(); try { statement = createStatement(context, connection); if ( doExecute(statement, query) ) { return unmarshalResults(context, connection.getMetaData(), statement, false); } else { return unmarshalKeysOrUpdateCount(context, connection, statement); } } catch (final SQLException e) { debugErrorSQL(context, query); throw e; } finally { close(statement); } } }); } protected Statement createStatement(final ThreadContext context, final Connection connection) throws SQLException { final Statement statement = connection.createStatement(); IRubyObject statementEscapeProcessing = getConfigValue(context, "statement_escape_processing"); // NOTE: disable (driver) escape processing by default, it's not really // needed for AR statements ... if users need it they might configure : if ( statementEscapeProcessing.isNil() ) { statement.setEscapeProcessing(false); } else { statement.setEscapeProcessing(statementEscapeProcessing.isTrue()); } return statement; } /** * Execute a query using the given statement. * @param statement * @param query * @return true if the first result is a <code>ResultSet</code>; * false if it is an update count or there are no results * @throws SQLException */ protected boolean doExecute(final Statement statement, final String query) throws SQLException { return genericExecute(statement, query); } /** * @deprecated renamed to {@link #doExecute(Statement, String)} */ @Deprecated protected boolean genericExecute(final Statement statement, final String query) throws SQLException { return statement.execute(query); } protected IRubyObject unmarshalKeysOrUpdateCount(final ThreadContext context, final Connection connection, final Statement statement) throws SQLException { final Ruby runtime = context.getRuntime(); final IRubyObject key; if ( connection.getMetaData().supportsGetGeneratedKeys() ) { key = unmarshalIdResult(runtime, statement); } else { key = runtime.getNil(); } return key.isNil() ? runtime.newFixnum( statement.getUpdateCount() ) : key; } @JRubyMethod(name = "execute_insert", required = 1) public IRubyObject execute_insert(final ThreadContext context, final IRubyObject sql) throws SQLException { return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { Statement statement = null; final String insertSQL = sql.convertToString().getUnicodeValue(); try { statement = createStatement(context, connection); statement.executeUpdate(insertSQL, Statement.RETURN_GENERATED_KEYS); return unmarshalIdResult(context.getRuntime(), statement); } catch (final SQLException e) { debugErrorSQL(context, insertSQL); throw e; } finally { close(statement); } } }); } @JRubyMethod(name = {"execute_update", "execute_delete"}, required = 1) public IRubyObject execute_update(final ThreadContext context, final IRubyObject sql) throws SQLException { return withConnection(context, new Callable<RubyInteger>() { public RubyInteger call(final Connection connection) throws SQLException { Statement statement = null; final String updateSQL = sql.convertToString().getUnicodeValue(); try { statement = createStatement(context, connection); final int rowCount = statement.executeUpdate(updateSQL); return context.getRuntime().newFixnum(rowCount); } catch (final SQLException e) { debugErrorSQL(context, updateSQL); throw e; } finally { close(statement); } } }); } /** * NOTE: since 1.3 this behaves like <code>execute_query</code> in AR-JDBC 1.2 * @param context * @param sql * @param block (optional) block to yield row values * @return raw query result as a name => value Hash (unless block given) * @throws SQLException * @see #execute_query_raw(ThreadContext, IRubyObject[], Block) */ @JRubyMethod(name = "execute_query_raw", required = 1) // optional block public IRubyObject execute_query_raw(final ThreadContext context, final IRubyObject sql, final Block block) throws SQLException { final String query = sql.convertToString().getUnicodeValue(); return executeQueryRaw(context, query, 0, block); } /** * NOTE: since 1.3 this behaves like <code>execute_query</code> in AR-JDBC 1.2 * @param context * @param args * @param block (optional) block to yield row values * @return raw query result as a name => value Hash (unless block given) * @throws SQLException */ @JRubyMethod(name = "execute_query_raw", required = 2, optional = 1) // @JRubyMethod(name = "execute_query_raw", required = 1, optional = 2) public IRubyObject execute_query_raw(final ThreadContext context, final IRubyObject[] args, final Block block) throws SQLException { // args: (sql), (sql, max_rows), (sql, binds), (sql, max_rows, binds) final String query = args[0].convertToString().getUnicodeValue(); // sql IRubyObject max_rows = args.length > 1 ? args[1] : null; IRubyObject binds = args.length > 2 ? args[2] : null; final int maxRows; if ( max_rows == null || max_rows.isNil() ) maxRows = 0; else { if ( binds instanceof RubyNumeric ) { // (sql, max_rows) maxRows = RubyNumeric.fix2int(binds); binds = null; } else { if ( max_rows instanceof RubyNumeric ) { maxRows = RubyNumeric.fix2int(max_rows); } else { if ( binds == null ) binds = max_rows; // (sql, binds) maxRows = 0; } } } if ( binds == null || binds.isNil() ) { // no prepared statements return executeQueryRaw(context, query, maxRows, block); } else { // we allow prepared statements with empty binds parameters return executePreparedQueryRaw(context, query, (List) binds, maxRows, block); } } /** * @param context * @param query * @param maxRows * @param block * @return raw query result (in case no block was given) * * @see #execute_query_raw(ThreadContext, IRubyObject[], Block) */ protected IRubyObject executeQueryRaw(final ThreadContext context, final String query, final int maxRows, final Block block) { return doExecuteQueryRaw(context, query, maxRows, block, null); // binds == null } protected IRubyObject executePreparedQueryRaw(final ThreadContext context, final String query, final List<?> binds, final int maxRows, final Block block) { return doExecuteQueryRaw(context, query, maxRows, block, binds); } private IRubyObject doExecuteQueryRaw(final ThreadContext context, final String query, final int maxRows, final Block block, final List<?> binds) { return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { final Ruby runtime = context.getRuntime(); final DatabaseMetaData metaData = connection.getMetaData(); Statement statement = null; ResultSet resultSet = null; try { if ( binds == null ) { // plain statement statement = createStatement(context, connection); statement.setMaxRows(maxRows); // zero means there is no limit resultSet = statement.executeQuery(query); } else { final PreparedStatement prepStatement; statement = prepStatement = connection.prepareStatement(query); statement.setMaxRows(maxRows); // zero means there is no limit setStatementParameters(context, connection, prepStatement, binds); resultSet = prepStatement.executeQuery(); } if ( block != null && block.isGiven() ) { // yield(id1, name1) ... row 1 result data // yield(id2, name2) ... row 2 result data return yieldResultRows(context, runtime, metaData, resultSet, block); } return mapToRawResult(context, runtime, metaData, resultSet, false); } catch (final SQLException e) { debugErrorSQL(context, query); throw e; } finally { close(resultSet); close(statement); } } }); } /** * Executes a query and returns the (AR) result. * @param context * @param sql * @return raw query result as a name => value Hash (unless block given) * @throws SQLException * @see #execute_query(ThreadContext, IRubyObject[], Block) */ @JRubyMethod(name = "execute_query", required = 1) public IRubyObject execute_query(final ThreadContext context, final IRubyObject sql) throws SQLException { final String query = sql.convertToString().getUnicodeValue(); return executeQuery(context, query, 0); } /** * Executes a query and returns the (AR) result. * @param context * @param args * @return and <code>ActiveRecord::Result</code> * @throws SQLException * * @see #execute_query(ThreadContext, IRubyObject, IRubyObject, Block) */ @JRubyMethod(name = "execute_query", required = 2, optional = 1) // @JRubyMethod(name = "execute_query", required = 1, optional = 2) public IRubyObject execute_query(final ThreadContext context, final IRubyObject[] args) throws SQLException { // args: (sql), (sql, max_rows), (sql, binds), (sql, max_rows, binds) final String query = args[0].convertToString().getUnicodeValue(); // sql IRubyObject max_rows = args.length > 1 ? args[1] : null; IRubyObject binds = args.length > 2 ? args[2] : null; final int maxRows; if ( max_rows == null || max_rows.isNil() ) maxRows = 0; else { if ( binds instanceof RubyNumeric ) { // (sql, max_rows) maxRows = RubyNumeric.fix2int(binds); binds = null; } else { if ( max_rows instanceof RubyNumeric ) { maxRows = RubyNumeric.fix2int(max_rows); } else { if ( binds == null ) binds = max_rows; // (sql, binds) maxRows = 0; } } } if ( binds == null || binds.isNil() ) { // no prepared statements return executeQuery(context, query, maxRows); } else { // we allow prepared statements with empty binds parameters return executePreparedQuery(context, query, (List) binds, maxRows); } } /** * NOTE: This methods behavior changed in AR-JDBC 1.3 the old behavior is * achievable using {@link #executeQueryRaw(ThreadContext, String, int, Block)}. * * @param context * @param query * @param maxRows * @return AR (mapped) query result * * @see #execute_query(ThreadContext, IRubyObject) * @see #execute_query(ThreadContext, IRubyObject, IRubyObject) * @see #mapToResult(ThreadContext, Ruby, DatabaseMetaData, ResultSet, RubyJdbcConnection.ColumnData[]) */ protected IRubyObject executeQuery(final ThreadContext context, final String query, final int maxRows) { return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { Statement statement = null; ResultSet resultSet = null; try { statement = createStatement(context, connection); statement.setMaxRows(maxRows); // zero means there is no limit resultSet = statement.executeQuery(query); return mapQueryResult(context, connection, resultSet); } catch (final SQLException e) { debugErrorSQL(context, query); throw e; } finally { close(resultSet); close(statement); } } }); } protected IRubyObject executePreparedQuery(final ThreadContext context, final String query, final List<?> binds, final int maxRows) { return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { PreparedStatement statement = null; ResultSet resultSet = null; try { statement = connection.prepareStatement(query); statement.setMaxRows(maxRows); // zero means there is no limit setStatementParameters(context, connection, statement, binds); resultSet = statement.executeQuery(); return mapQueryResult(context, connection, resultSet); } catch (final SQLException e) { debugErrorSQL(context, query); throw e; } finally { close(resultSet); close(statement); } } }); } private IRubyObject mapQueryResult(final ThreadContext context, final Connection connection, final ResultSet resultSet) throws SQLException { final Ruby runtime = context.getRuntime(); final DatabaseMetaData metaData = connection.getMetaData(); final ColumnData[] columns = setupColumns(runtime, metaData, resultSet.getMetaData(), false); return mapToResult(context, runtime, metaData, resultSet, columns); } @JRubyMethod(name = "execute_id_insert", required = 2) public IRubyObject execute_id_insert(final ThreadContext context, final IRubyObject sql, final IRubyObject id) throws SQLException { return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { PreparedStatement statement = null; final String insertSQL = sql.convertToString().getUnicodeValue(); try { statement = connection.prepareStatement(insertSQL); statement.setLong(1, RubyNumeric.fix2long(id)); statement.executeUpdate(); } catch (final SQLException e) { debugErrorSQL(context, insertSQL); throw e; } finally { close(statement); } return id; } }); } @JRubyMethod(name = "native_database_types", frame = false) public IRubyObject native_database_types() { return getInstanceVariable("@native_database_types"); } @JRubyMethod(name = "primary_keys", required = 1) public IRubyObject primary_keys(ThreadContext context, IRubyObject tableName) throws SQLException { @SuppressWarnings("unchecked") List<IRubyObject> primaryKeys = (List) primaryKeys(context, tableName.toString()); return context.getRuntime().newArray(primaryKeys); } private static final int PRIMARY_KEYS_COLUMN_NAME = 4; protected List<RubyString> primaryKeys(final ThreadContext context, final String tableName) { return withConnection(context, new Callable<List<RubyString>>() { public List<RubyString> call(final Connection connection) throws SQLException { final Ruby runtime = context.getRuntime(); final DatabaseMetaData metaData = connection.getMetaData(); final String _tableName = caseConvertIdentifierForJdbc(metaData, tableName); ResultSet resultSet = null; final List<RubyString> keyNames = new ArrayList<RubyString>(); try { TableName components = extractTableName(connection, null, _tableName); resultSet = metaData.getPrimaryKeys(components.catalog, components.schema, components.name); while (resultSet.next()) { String columnName = resultSet.getString(PRIMARY_KEYS_COLUMN_NAME); columnName = caseConvertIdentifierForRails(metaData, columnName); keyNames.add( RubyString.newUnicodeString(runtime, columnName) ); } } finally { close(resultSet); } return keyNames; } }); } @JRubyMethod(name = "set_native_database_types") public IRubyObject set_native_database_types(final ThreadContext context) throws SQLException { final Ruby runtime = context.getRuntime(); final DatabaseMetaData metaData = getConnection(true).getMetaData(); final IRubyObject types; final ResultSet typeDesc = metaData.getTypeInfo(); try { types = mapToRawResult(context, runtime, metaData, typeDesc, true); } finally { close(typeDesc); } final IRubyObject typeConverter = getJdbcTypeConverter(runtime).callMethod("new", types); setInstanceVariable("@native_types", typeConverter.callMethod(context, "choose_best_types")); return runtime.getNil(); } @JRubyMethod(name = "tables") public IRubyObject tables(ThreadContext context) { return tables(context, null, null, null, TABLE_TYPE); } @JRubyMethod(name = "tables") public IRubyObject tables(ThreadContext context, IRubyObject catalog) { return tables(context, toStringOrNull(catalog), null, null, TABLE_TYPE); } @JRubyMethod(name = "tables") public IRubyObject tables(ThreadContext context, IRubyObject catalog, IRubyObject schemaPattern) { return tables(context, toStringOrNull(catalog), toStringOrNull(schemaPattern), null, TABLE_TYPE); } @JRubyMethod(name = "tables") public IRubyObject tables(ThreadContext context, IRubyObject catalog, IRubyObject schemaPattern, IRubyObject tablePattern) { return tables(context, toStringOrNull(catalog), toStringOrNull(schemaPattern), toStringOrNull(tablePattern), TABLE_TYPE); } @JRubyMethod(name = "tables", required = 4, rest = true) public IRubyObject tables(ThreadContext context, IRubyObject[] args) { return tables(context, toStringOrNull(args[0]), toStringOrNull(args[1]), toStringOrNull(args[2]), getTypes(args[3])); } protected IRubyObject tables(final ThreadContext context, final String catalog, final String schemaPattern, final String tablePattern, final String[] types) { return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { return matchTables(context.getRuntime(), connection, catalog, schemaPattern, tablePattern, types, false); } }); } protected String[] getTableTypes() { return TABLE_TYPES; } @JRubyMethod(name = "table_exists?", required = 1, optional = 1) public IRubyObject table_exists_p(final ThreadContext context, final IRubyObject[] args) { IRubyObject name = args[0], schema_name = args.length > 1 ? args[1] : null; if ( ! ( name instanceof RubyString ) ) { name = name.callMethod(context, "to_s"); } final String tableName = ((RubyString) name).getUnicodeValue(); final String tableSchema = schema_name == null ? null : schema_name.convertToString().getUnicodeValue(); final Ruby runtime = context.getRuntime(); return withConnection(context, new Callable<RubyBoolean>() { public RubyBoolean call(final Connection connection) throws SQLException { final TableName components = extractTableName(connection, tableSchema, tableName); return runtime.newBoolean( tableExists(runtime, connection, components) ); } }); } @JRubyMethod(name = {"columns", "columns_internal"}, required = 1, optional = 2) public IRubyObject columns_internal(final ThreadContext context, final IRubyObject[] args) throws SQLException { return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { ResultSet columns = null, primaryKeys = null; try { final String tableName = args[0].convertToString().getUnicodeValue(); // optionals (NOTE: catalog argumnet was never used before 1.3.0) : final String catalog = args.length > 1 ? toStringOrNull(args[1]) : null; final String defaultSchema = args.length > 2 ? toStringOrNull(args[2]) : null; final TableName components; if ( catalog == null ) { // backwards-compatibility with < 1.3.0 components = extractTableName(connection, defaultSchema, tableName); } else { components = extractTableName(connection, catalog, defaultSchema, tableName); } if ( ! tableExists(context.getRuntime(), connection, components) ) { throw new SQLException("table: " + tableName + " does not exist"); } final DatabaseMetaData metaData = connection.getMetaData(); columns = metaData.getColumns(components.catalog, components.schema, components.name, null); primaryKeys = metaData.getPrimaryKeys(components.catalog, components.schema, components.name); return unmarshalColumns(context, metaData, columns, primaryKeys); } finally { close(columns); close(primaryKeys); } } }); } @JRubyMethod(name = "indexes") public IRubyObject indexes(ThreadContext context, IRubyObject tableName, IRubyObject name, IRubyObject schemaName) { return indexes(context, toStringOrNull(tableName), toStringOrNull(name), toStringOrNull(schemaName)); } // NOTE: metaData.getIndexInfo row mappings : private static final int INDEX_INFO_TABLE_NAME = 3; private static final int INDEX_INFO_NON_UNIQUE = 4; private static final int INDEX_INFO_NAME = 6; private static final int INDEX_INFO_COLUMN_NAME = 9; /** * Default JDBC introspection for index metadata on the JdbcConnection. * * JDBC index metadata is denormalized (multiple rows may be returned for * one index, one row per column in the index), so a simple block-based * filter like that used for tables doesn't really work here. Callers * should filter the return from this method instead. */ protected IRubyObject indexes(final ThreadContext context, final String tableName, final String name, final String schemaName) { return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { final Ruby runtime = context.getRuntime(); final RubyClass indexDefinition = getIndexDefinition(runtime); final DatabaseMetaData metaData = connection.getMetaData(); String _tableName = caseConvertIdentifierForJdbc(metaData, tableName); String _schemaName = caseConvertIdentifierForJdbc(metaData, schemaName); final List<RubyString> primaryKeys = primaryKeys(context, _tableName); ResultSet indexInfoSet = null; final List<IRubyObject> indexes = new ArrayList<IRubyObject>(); try { indexInfoSet = metaData.getIndexInfo(null, _schemaName, _tableName, false, true); String currentIndex = null; while ( indexInfoSet.next() ) { String indexName = indexInfoSet.getString(INDEX_INFO_NAME); if ( indexName == null ) continue; indexName = caseConvertIdentifierForRails(metaData, indexName); final String columnName = indexInfoSet.getString(INDEX_INFO_COLUMN_NAME); final RubyString rubyColumnName = RubyString.newUnicodeString( runtime, caseConvertIdentifierForRails(metaData, columnName) ); if ( primaryKeys.contains(rubyColumnName) ) continue; // We are working on a new index if ( ! indexName.equals(currentIndex) ) { currentIndex = indexName; String indexTableName = indexInfoSet.getString(INDEX_INFO_TABLE_NAME); indexTableName = caseConvertIdentifierForRails(metaData, indexTableName); final boolean nonUnique = indexInfoSet.getBoolean(INDEX_INFO_NON_UNIQUE); IRubyObject[] args = new IRubyObject[] { RubyString.newUnicodeString(runtime, indexTableName), // table_name RubyString.newUnicodeString(runtime, indexName), // index_name runtime.newBoolean( ! nonUnique ), // unique runtime.newArray() // [] for column names, we'll add to that in just a bit // orders, (since AR 3.2) where, type, using (AR 4.0) }; indexes.add( indexDefinition.callMethod(context, "new", args) ); // IndexDefinition.new } // One or more columns can be associated with an index IRubyObject lastIndexDef = indexes.isEmpty() ? null : indexes.get(indexes.size() - 1); if (lastIndexDef != null) { lastIndexDef.callMethod(context, "columns").callMethod(context, "<<", rubyColumnName); } } return runtime.newArray(indexes); } finally { close(indexInfoSet); } } }); } // NOTE: this seems to be not used ... at all ?! /* * sql, values (array), types (column.type array), name = nil, pk = nil, id_value = nil, sequence_name = nil */ @Deprecated @JRubyMethod(name = "insert_bind", required = 3, rest = true) public IRubyObject insert_bind(final ThreadContext context, final IRubyObject[] args) throws SQLException { final Ruby runtime = context.getRuntime(); return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { final String sql = args[0].convertToString().toString(); PreparedStatement statement = null; try { statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); setPreparedStatementValues(context, connection, statement, args[1], args[2]); statement.executeUpdate(); return unmarshalIdResult(runtime, statement); } finally { close(statement); } } }); } // NOTE: this seems to be not used ... at all ?! /* * sql, values (array), types (column.type array), name = nil */ @Deprecated @JRubyMethod(name = "update_bind", required = 3, rest = true) public IRubyObject update_bind(final ThreadContext context, final IRubyObject[] args) throws SQLException { final Ruby runtime = context.getRuntime(); Arity.checkArgumentCount(runtime, args, 3, 4); return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { final String sql = args[0].convertToString().toString(); PreparedStatement statement = null; try { statement = connection.prepareStatement(sql); setPreparedStatementValues(context, connection, statement, args[1], args[2]); statement.executeUpdate(); } finally { close(statement); } return runtime.getNil(); } }); } @JRubyMethod(name = "with_connection_retry_guard", frame = true) public IRubyObject with_connection_retry_guard(final ThreadContext context, final Block block) { return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { return block.call(context, new IRubyObject[] { convertJavaToRuby(connection) }); } }); } /* * (is binary?, colname, tablename, primary_key, id, lob_value) */ @JRubyMethod(name = "write_large_object", required = 6) public IRubyObject write_large_object(final ThreadContext context, final IRubyObject[] args) throws SQLException { final boolean isBinary = args[0].isTrue(); final RubyString columnName = args[1].convertToString(); final RubyString tableName = args[2].convertToString(); final RubyString idKey = args[3].convertToString(); final RubyString idVal = args[4].convertToString(); final IRubyObject lobValue = args[5]; final Ruby runtime = context.getRuntime(); return withConnection(context, new Callable<IRubyObject>() { public IRubyObject call(final Connection connection) throws SQLException { final String sql = "UPDATE "+ tableName + " SET "+ columnName +" = ? WHERE "+ idKey +" = "+ idVal; PreparedStatement statement = null; try { statement = connection.prepareStatement(sql); if ( isBinary ) { // binary final ByteList blob = lobValue.convertToString().getByteList(); final int realSize = blob.getRealSize(); statement.setBinaryStream(1, new ByteArrayInputStream(blob.unsafeBytes(), blob.getBegin(), realSize), realSize ); } else { // clob String clob = lobValue.convertToString().getUnicodeValue(); statement.setCharacterStream(1, new StringReader(clob), clob.length()); } statement.executeUpdate(); } finally { close(statement); } return runtime.getNil(); } }); } /** * Convert an identifier coming back from the database to a case which Rails is expecting. * * Assumption: Rails identifiers will be quoted for mixed or will stay mixed * as identifier names in Rails itself. Otherwise, they expect identifiers to * be lower-case. Databases which store identifiers uppercase should be made * lower-case. * * Assumption 2: It is always safe to convert all upper case names since it appears that * some adapters do not report StoresUpper/Lower/Mixed correctly (am I right postgres/mysql?). */ protected static String caseConvertIdentifierForRails(final DatabaseMetaData metaData, final String value) throws SQLException { if ( value == null ) return null; return metaData.storesUpperCaseIdentifiers() ? value.toLowerCase() : value; } /** * Convert an identifier destined for a method which cares about the databases internal * storage case. Methods like DatabaseMetaData.getPrimaryKeys() needs the table name to match * the internal storage name. Arbtrary queries and the like DO NOT need to do this. */ protected String caseConvertIdentifierForJdbc(final DatabaseMetaData metaData, final String value) throws SQLException { if ( value == null ) return null; if ( metaData.storesUpperCaseIdentifiers() ) { return value.toUpperCase(); } else if ( metaData.storesLowerCaseIdentifiers() ) { return value.toLowerCase(); } return value; } protected IRubyObject getConfigValue(final ThreadContext context, final String key) { final IRubyObject config = getInstanceVariable("@config"); return config.callMethod(context, "[]", context.getRuntime().newSymbol(key)); } /** * @deprecated renamed to {@link #getConfigValue(ThreadContext, String)} */ @Deprecated protected IRubyObject config_value(ThreadContext context, String key) { return getConfigValue(context, key); } private static String toStringOrNull(IRubyObject arg) { return arg.isNil() ? null : arg.toString(); } protected IRubyObject getAdapter(ThreadContext context) { return callMethod(context, "adapter"); } protected IRubyObject getJdbcColumnClass(ThreadContext context) { return getAdapter(context).callMethod(context, "jdbc_column_class"); } protected JdbcConnectionFactory getConnectionFactory() throws RaiseException { IRubyObject connection_factory = getInstanceVariable("@connection_factory"); if ( connection_factory == null ) { throw getRuntime().newRuntimeError("@connection_factory not set"); } JdbcConnectionFactory connectionFactory; try { connectionFactory = (JdbcConnectionFactory) connection_factory.toJava(JdbcConnectionFactory.class); } catch (Exception e) { throw getRuntime().newRuntimeError("@connection_factory not set properly: " + e); } return connectionFactory; } private static String[] getTypes(final IRubyObject typeArg) { if ( typeArg instanceof RubyArray ) { IRubyObject[] rubyTypes = ((RubyArray) typeArg).toJavaArray(); final String[] types = new String[rubyTypes.length]; for ( int i = 0; i < types.length; i++ ) { types[i] = rubyTypes[i].toString(); } return types; } return new String[] { typeArg.toString() }; // expect a RubyString } /** * @deprecated this method is no longer used, instead consider overriding * {@link #mapToResult(ThreadContext, Ruby, DatabaseMetaData, ResultSet, RubyJdbcConnection.ColumnData[])} */ @Deprecated protected void populateFromResultSet( final ThreadContext context, final Ruby runtime, final List<IRubyObject> results, final ResultSet resultSet, final ColumnData[] columns) throws SQLException { final ResultHandler resultHandler = ResultHandler.getInstance(context); while ( resultSet.next() ) { results.add( resultHandler.mapRawRow(context, runtime, columns, resultSet, this) ); } } /** * Maps a query result into a <code>ActiveRecord</code> result. * @param context * @param runtime * @param metaData * @param resultSet * @param columns * @return since 3.1 expected to return a <code>ActiveRecord::Result</code> * @throws SQLException */ protected IRubyObject mapToResult(final ThreadContext context, final Ruby runtime, final DatabaseMetaData metaData, final ResultSet resultSet, final ColumnData[] columns) throws SQLException { final ResultHandler resultHandler = ResultHandler.getInstance(context); final RubyArray resultRows = runtime.newArray(); while ( resultSet.next() ) { resultRows.add( resultHandler.mapRow(context, runtime, columns, resultSet, this) ); } return resultHandler.newResult(context, runtime, columns, resultRows); } protected IRubyObject jdbcToRuby(final Ruby runtime, final int column, final int type, final ResultSet resultSet) throws SQLException { try { switch (type) { case Types.BLOB: case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: return streamToRuby(runtime, resultSet, column); case Types.CLOB: case Types.NCLOB: // JDBC 4.0 return readerToRuby(runtime, resultSet, column); case Types.LONGVARCHAR: case Types.LONGNVARCHAR: // JDBC 4.0 if ( runtime.is1_9() ) { return readerToRuby(runtime, resultSet, column); } else { return streamToRuby(runtime, resultSet, column); } case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: return integerToRuby(runtime, resultSet, column); case Types.REAL: case Types.FLOAT: case Types.DOUBLE: return doubleToRuby(runtime, resultSet, column); case Types.BIGINT: return bigIntegerToRuby(runtime, resultSet, column); case Types.NUMERIC: case Types.DECIMAL: return decimalToRuby(runtime, resultSet, column); case Types.DATE: return dateToRuby(runtime, resultSet, column); case Types.TIME: return timeToRuby(runtime, resultSet, column); case Types.TIMESTAMP: return timestampToRuby(runtime, resultSet, column); case Types.BIT: case Types.BOOLEAN: return booleanToRuby(runtime, resultSet, column); case Types.SQLXML: // JDBC 4.0 return xmlToRuby(runtime, resultSet, column); case Types.ARRAY: // we handle JDBC Array into (Ruby) [] return arrayToRuby(runtime, resultSet, column); case Types.NULL: return runtime.getNil(); // NOTE: (JDBC) exotic stuff just cause it's so easy with JRuby :) case Types.JAVA_OBJECT: case Types.OTHER: return objectToRuby(runtime, resultSet, column); // (default) String case Types.CHAR: case Types.VARCHAR: case Types.NCHAR: // JDBC 4.0 case Types.NVARCHAR: // JDBC 4.0 default: return stringToRuby(runtime, resultSet, column); } // NOTE: not mapped types : //case Types.DISTINCT: //case Types.STRUCT: //case Types.REF: //case Types.DATALINK: } catch (IOException e) { throw new SQLException(e.getMessage(), e); } } protected IRubyObject integerToRuby( final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException { final long value = resultSet.getLong(column); if ( value == 0 && resultSet.wasNull() ) return runtime.getNil(); return integerToRuby(runtime, resultSet, value); } @Deprecated protected IRubyObject integerToRuby( final Ruby runtime, final ResultSet resultSet, final long longValue) throws SQLException { if ( longValue == 0 && resultSet.wasNull() ) return runtime.getNil(); return runtime.newFixnum(longValue); } protected IRubyObject doubleToRuby(Ruby runtime, ResultSet resultSet, final int column) throws SQLException { final double value = resultSet.getDouble(column); if ( value == 0 && resultSet.wasNull() ) return runtime.getNil(); return doubleToRuby(runtime, resultSet, value); } @Deprecated protected IRubyObject doubleToRuby(Ruby runtime, ResultSet resultSet, double doubleValue) throws SQLException { if ( doubleValue == 0 && resultSet.wasNull() ) return runtime.getNil(); return runtime.newFloat(doubleValue); } protected IRubyObject stringToRuby( final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException { final String value = resultSet.getString(column); if ( value == null && resultSet.wasNull() ) return runtime.getNil(); return stringToRuby(runtime, resultSet, value); } @Deprecated protected IRubyObject stringToRuby( final Ruby runtime, final ResultSet resultSet, final String string) throws SQLException { if ( string == null && resultSet.wasNull() ) return runtime.getNil(); return RubyString.newUnicodeString(runtime, string); } protected IRubyObject bigIntegerToRuby( final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException { final String value = resultSet.getString(column); if ( value == null && resultSet.wasNull() ) return runtime.getNil(); return bigIntegerToRuby(runtime, resultSet, value); } @Deprecated protected IRubyObject bigIntegerToRuby( final Ruby runtime, final ResultSet resultSet, final String intValue) throws SQLException { if ( intValue == null && resultSet.wasNull() ) return runtime.getNil(); return RubyBignum.bignorm(runtime, new BigInteger(intValue)); } protected IRubyObject decimalToRuby( final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException { final String value = resultSet.getString(column); if ( value == null && resultSet.wasNull() ) return runtime.getNil(); // NOTE: JRuby 1.6 -> 1.7 API change : moved org.jruby.RubyBigDecimal return runtime.getKernel().callMethod("BigDecimal", runtime.newString(value)); } private static boolean parseDateTime = false; // TODO protected IRubyObject dateToRuby( // TODO final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException { final Date value = resultSet.getDate(column); if ( value == null && resultSet.wasNull() ) return runtime.getNil(); return RubyString.newUnicodeString(runtime, value.toString()); } protected IRubyObject timeToRuby( // TODO final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException { final Time value = resultSet.getTime(column); if ( value == null && resultSet.wasNull() ) return runtime.getNil(); return RubyString.newUnicodeString(runtime, value.toString()); } protected IRubyObject timestampToRuby( final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException { final Timestamp value = resultSet.getTimestamp(column); if ( value == null && resultSet.wasNull() ) return runtime.getNil(); return timestampToRuby(runtime, resultSet, value); } @Deprecated protected IRubyObject timestampToRuby( final Ruby runtime, final ResultSet resultSet, final Timestamp value) throws SQLException { if ( value == null && resultSet.wasNull() ) return runtime.getNil(); String format = value.toString(); // yyyy-mm-dd hh:mm:ss.fffffffff if ( format.endsWith(" 00:00:00.0") ) { format = format.substring(0, format.length() - (" 00:00:00.0".length())); } if ( format.endsWith(".0") ) { format = format.substring(0, format.length() - (".0".length())); } return RubyString.newUnicodeString(runtime, format); } protected IRubyObject booleanToRuby( final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException { final boolean value = resultSet.getBoolean(column); if ( resultSet.wasNull() ) return runtime.getNil(); return booleanToRuby(runtime, resultSet, value); } @Deprecated protected IRubyObject booleanToRuby( final Ruby runtime, final ResultSet resultSet, final boolean value) throws SQLException { if ( value == false && resultSet.wasNull() ) return runtime.getNil(); return runtime.newBoolean(value); } protected static int streamBufferSize = 2048; protected IRubyObject streamToRuby( final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException, IOException { final InputStream stream = resultSet.getBinaryStream(column); try { if ( resultSet.wasNull() ) return runtime.getNil(); return streamToRuby(runtime, resultSet, stream); } finally { if ( stream != null ) stream.close(); } } @Deprecated protected IRubyObject streamToRuby( final Ruby runtime, final ResultSet resultSet, final InputStream stream) throws SQLException, IOException { if ( stream == null && resultSet.wasNull() ) return runtime.getNil(); final int bufSize = streamBufferSize; final ByteList string = new ByteList(bufSize); final byte[] buf = new byte[bufSize]; for (int len = stream.read(buf); len != -1; len = stream.read(buf)) { string.append(buf, 0, len); } return runtime.newString(string); } protected IRubyObject readerToRuby( final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException, IOException { final Reader reader = resultSet.getCharacterStream(column); try { if ( resultSet.wasNull() ) return runtime.getNil(); return readerToRuby(runtime, resultSet, reader); } finally { if ( reader != null ) reader.close(); } } @Deprecated protected IRubyObject readerToRuby( final Ruby runtime, final ResultSet resultSet, final Reader reader) throws SQLException, IOException { if ( reader == null && resultSet.wasNull() ) return runtime.getNil(); final int bufSize = streamBufferSize; final StringBuilder string = new StringBuilder(bufSize); final char[] buf = new char[bufSize]; for (int len = reader.read(buf); len != -1; len = reader.read(buf)) { string.append(buf, 0, len); } return RubyString.newUnicodeString(runtime, string.toString()); } protected IRubyObject objectToRuby( final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException { final Object value = resultSet.getObject(column); if ( value == null && resultSet.wasNull() ) return runtime.getNil(); return JavaUtil.convertJavaToRuby(runtime, value); } protected IRubyObject arrayToRuby( final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException { final Array value = resultSet.getArray(column); try { if ( value == null && resultSet.wasNull() ) return runtime.getNil(); final RubyArray array = runtime.newArray(); final ResultSet arrayResult = value.getResultSet(); // 1: index, 2: value final int baseType = value.getBaseType(); while ( arrayResult.next() ) { IRubyObject element = jdbcToRuby(runtime, 2, baseType, arrayResult); array.append(element); } return array; } finally { value.free(); } } protected IRubyObject xmlToRuby( final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException { final SQLXML xml = resultSet.getSQLXML(column); try { return RubyString.newUnicodeString(runtime, xml.getString()); } finally { xml.free(); } } /* protected */ void setStatementParameters(final ThreadContext context, final Connection connection, final PreparedStatement statement, final List<?> binds) throws SQLException { final Ruby runtime = context.getRuntime(); for ( int i = 0; i < binds.size(); i++ ) { // [ [ column1, param1 ], [ column2, param2 ], ... ] Object param = binds.get(i); IRubyObject column = null; if ( param.getClass() == RubyArray.class ) { final RubyArray _param = (RubyArray) param; column = _param.eltInternal(0); param = _param.eltInternal(1); } else if ( param instanceof List ) { final List<?> _param = (List<?>) param; column = (IRubyObject) _param.get(0); param = _param.get(1); } else if ( param instanceof Object[] ) { final Object[] _param = (Object[]) param; column = (IRubyObject) _param[0]; param = _param[1]; } final IRubyObject type; if ( column != null && ! column.isNil() ) { type = column.callMethod(context, "type"); } else { type = null; } setStatementParameter(context, runtime, connection, statement, i + 1, param, type); } } /* protected */ void setStatementParameter(final ThreadContext context, final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final Object value, final IRubyObject column) throws SQLException { final RubySymbol columnType = resolveColumnType(context, runtime, column); final int type = jdbcTypeFor(runtime, column, columnType, value); // TODO pass column with (JDBC) type to methods : switch (type) { case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: if ( value instanceof RubyBignum ) { setBigIntegerParameter(runtime, connection, statement, index, type, (RubyBignum) value); } setIntegerParameter(runtime, connection, statement, index, type, value); break; case Types.BIGINT: setBigIntegerParameter(runtime, connection, statement, index, type, value); break; case Types.REAL: case Types.FLOAT: case Types.DOUBLE: setDoubleParameter(runtime, connection, statement, index, type, value); break; case Types.NUMERIC: case Types.DECIMAL: setDecimalParameter(runtime, connection, statement, index, type, value); break; case Types.DATE: setDateParameter(runtime, connection, statement, index, type, value); break; case Types.TIME: setTimeParameter(runtime, connection, statement, index, type, value); break; case Types.TIMESTAMP: setTimestampParameter(runtime, connection, statement, index, type, value); break; case Types.BIT: case Types.BOOLEAN: setBooleanParameter(runtime, connection, statement, index, type, value); break; case Types.SQLXML: setXmlParameter(runtime, connection, statement, index, type, value); break; case Types.ARRAY: setArrayParameter(runtime, connection, statement, index, type, value); break; case Types.JAVA_OBJECT: case Types.OTHER: setObjectParameter(runtime, connection, statement, index, type, value); break; case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: case Types.BLOB: setBlobParameter(runtime, connection, statement, index, type, value); break; case Types.CLOB: case Types.NCLOB: // JDBC 4.0 setClobParameter(runtime, connection, statement, index, type, value); break; case Types.CHAR: case Types.VARCHAR: case Types.NCHAR: // JDBC 4.0 case Types.NVARCHAR: // JDBC 4.0 default: setStringParameter(runtime, connection, statement, index, type, value); } } @Deprecated private void setPreparedStatementValues(final ThreadContext context, final Connection connection, final PreparedStatement statement, final IRubyObject valuesArg, final IRubyObject typesArg) throws SQLException { final Ruby runtime = context.getRuntime(); final RubyArray values = (RubyArray) valuesArg; final RubyArray types = (RubyArray) typesArg; // column types for( int i = 0, j = values.getLength(); i < j; i++ ) { setStatementParameter( context, runtime, connection, statement, i + 1, values.eltInternal(i), types.eltInternal(i) ); } } private RubySymbol resolveColumnType(final ThreadContext context, final Ruby runtime, final IRubyObject column) { if ( column instanceof RubySymbol ) { // deprecated behavior return (RubySymbol) column; } if ( column instanceof RubyString) { // deprecated behavior if ( runtime.is1_9() ) { return ( (RubyString) column ).intern19(); } else { return ( (RubyString) column ).intern(); } } if ( column == null || column.isNil() ) { throw runtime.newArgumentError("nil column passed"); } return (RubySymbol) column.callMethod(context, "type"); } /* protected */ int jdbcTypeFor(final Ruby runtime, final IRubyObject column, final RubySymbol columnType, final Object value) throws SQLException { final String internedType = columnType.asJavaString(); if ( internedType == (Object) "string" ) return Types.VARCHAR; else if ( internedType == (Object) "text" ) return Types.CLOB; else if ( internedType == (Object) "integer" ) return Types.INTEGER; else if ( internedType == (Object) "decimal" ) return Types.DECIMAL; else if ( internedType == (Object) "float" ) return Types.FLOAT; else if ( internedType == (Object) "date" ) return Types.DATE; else if ( internedType == (Object) "time" ) return Types.TIME; else if ( internedType == (Object) "datetime") return Types.TIMESTAMP; else if ( internedType == (Object) "timestamp" ) return Types.TIMESTAMP; else if ( internedType == (Object) "binary" ) return Types.BLOB; else if ( internedType == (Object) "boolean" ) return Types.BOOLEAN; else if ( internedType == (Object) "xml" ) return Types.SQLXML; else if ( internedType == (Object) "array" ) return Types.ARRAY; else return Types.OTHER; // -1 as well as 0 are used in Types } /* protected */ void setIntegerParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setIntegerParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.INTEGER); else { statement.setLong(index, ((Number) value).longValue()); } } } /* protected */ void setIntegerParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.INTEGER); else { if ( value instanceof RubyFixnum ) { statement.setLong(index, ((RubyFixnum) value).getLongValue()); } else { statement.setInt(index, RubyNumeric.fix2int(value)); } } } /* protected */ void setBigIntegerParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setBigIntegerParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.BIGINT); else { if ( value instanceof BigDecimal ) { statement.setBigDecimal(index, (BigDecimal) value); } else if ( value instanceof BigInteger ) { setLongOrDecimalParameter(statement, index, (BigInteger) value); } else { statement.setLong(index, ((Number) value).longValue()); } } } } /* protected */ void setBigIntegerParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.INTEGER); else { if ( value instanceof RubyBignum ) { setLongOrDecimalParameter(statement, index, ((RubyBignum) value).getValue()); } else { statement.setLong(index, ((RubyInteger) value).getLongValue()); } } } private static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE); private static final BigInteger MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE); /* protected */ static void setLongOrDecimalParameter(final PreparedStatement statement, final int index, final BigInteger value) throws SQLException { if ( value.compareTo(MAX_LONG) <= 0 // -1 intValue < MAX_VALUE && value.compareTo(MIN_LONG) >= 0 ) { statement.setLong(index, value.longValue()); } else { statement.setBigDecimal(index, new BigDecimal(value)); } } /* protected */ void setDoubleParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setDoubleParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.DOUBLE); else { statement.setDouble(index, ((Number) value).doubleValue()); } } } /* protected */ void setDoubleParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.DOUBLE); else { statement.setDouble(index, ((RubyNumeric) value).getDoubleValue()); } } /* protected */ void setDecimalParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setDecimalParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.DECIMAL); else { if ( value instanceof BigDecimal ) { statement.setBigDecimal(index, (BigDecimal) value); } else if ( value instanceof BigInteger ) { setLongOrDecimalParameter(statement, index, (BigInteger) value); } else { statement.setDouble(index, ((Number) value).doubleValue()); } } } } /* protected */ void setDecimalParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.DECIMAL); else { // NOTE: RubyBigDecimal moved into org.jruby.ext.bigdecimal (1.6 -> 1.7) if ( value.getMetaClass().getName().indexOf("BigDecimal") != -1 ) { try { // reflect ((RubyBigDecimal) value).getValue() : BigDecimal decValue = (BigDecimal) value.getClass(). getMethod("getValue", (Class<?>[]) null). invoke(value, (Object[]) null); statement.setBigDecimal(index, decValue); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e.getCause() != null ? e.getCause() : e); } } else { statement.setDouble(index, ((RubyNumeric) value).getDoubleValue()); } } } /* protected */ void setTimestampParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setTimestampParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.TIMESTAMP); else { if ( value instanceof Timestamp ) { statement.setTimestamp(index, (Timestamp) value); } else if ( value instanceof java.util.Date ) { statement.setTimestamp(index, new Timestamp(((java.util.Date) value).getTime())); } else { statement.setTimestamp(index, Timestamp.valueOf(value.toString())); } } } } /* protected */ void setTimestampParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.TIMESTAMP); else { if ( value instanceof RubyTime ) { final RubyTime timeValue = (RubyTime) value; final java.util.Date dateValue = timeValue.getJavaDate(); long millis = dateValue.getTime(); Timestamp timestamp = new Timestamp(millis); Calendar calendar = Calendar.getInstance(); calendar.setTime(dateValue); if ( type != Types.DATE ) { int micros = (int) timeValue.microseconds(); timestamp.setNanos( micros * 1000 ); // time.nsec ~ time.usec * 1000 } statement.setTimestamp( index, timestamp, calendar ); } else { final String stringValue = value.convertToString().toString(); // yyyy-[m]m-[d]d hh:mm:ss[.f...] final Timestamp timestamp = Timestamp.valueOf( stringValue ); statement.setTimestamp( index, timestamp, Calendar.getInstance() ); } } } /* protected */ void setTimeParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setTimeParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.TIME); else { if ( value instanceof Time ) { statement.setTime(index, (Time) value); } else if ( value instanceof java.util.Date ) { statement.setTime(index, new Time(((java.util.Date) value).getTime())); } else { // hh:mm:ss statement.setTime(index, Time.valueOf(value.toString())); // statement.setString(index, value.toString()); } } } } /* protected */ void setTimeParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.TIME); else { // setTimestampParameter(runtime, connection, statement, index, type, value); if ( value instanceof RubyTime ) { final RubyTime timeValue = (RubyTime) value; final java.util.Date dateValue = timeValue.getJavaDate(); Time time = new Time(dateValue.getTime()); Calendar calendar = Calendar.getInstance(); calendar.setTime(dateValue); statement.setTime( index, time, calendar ); } else { final String stringValue = value.convertToString().toString(); final Time time = Time.valueOf( stringValue ); statement.setTime( index, time, Calendar.getInstance() ); } } } /* protected */ void setDateParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setDateParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.DATE); else { if ( value instanceof Date ) { statement.setDate(index, (Date) value); } else if ( value instanceof java.util.Date ) { statement.setDate(index, new Date(((java.util.Date) value).getTime())); } else { // yyyy-[m]m-[d]d statement.setDate(index, Date.valueOf(value.toString())); // statement.setString(index, value.toString()); } } } } /* protected */ void setDateParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.DATE); else { // setTimestampParameter(runtime, connection, statement, index, type, value); if ( value instanceof RubyTime ) { final RubyTime timeValue = (RubyTime) value; final java.util.Date dateValue = timeValue.getJavaDate(); Date date = new Date(dateValue.getTime()); Calendar calendar = Calendar.getInstance(); calendar.setTime(dateValue); statement.setDate( index, date, calendar ); } else { final String stringValue = value.convertToString().toString(); final Date date = Date.valueOf( stringValue ); statement.setDate( index, date, Calendar.getInstance() ); } } } /* protected */ void setBooleanParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setBooleanParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.BOOLEAN); else { statement.setBoolean(index, ((Boolean) value).booleanValue()); } } } /* protected */ void setBooleanParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.BOOLEAN); else { statement.setBoolean(index, value.isTrue()); } } /* protected */ void setStringParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setStringParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.VARCHAR); else { statement.setString(index, value.toString()); } } } /* protected */ void setStringParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.VARCHAR); else { statement.setString(index, value.convertToString().toString()); } } /* protected */ void setArrayParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setArrayParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.ARRAY); else { // TODO get array element type name ?! Array array = connection.createArrayOf(null, (Object[]) value); statement.setArray(index, array); } } } /* protected */ void setArrayParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.ARRAY); else { // TODO get array element type name ?! Array array = connection.createArrayOf(null, ((RubyArray) value).toArray()); statement.setArray(index, array); } } /* protected */ void setXmlParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setXmlParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.SQLXML); else { SQLXML xml = connection.createSQLXML(); xml.setString(value.toString()); statement.setSQLXML(index, xml); } } } /* protected */ void setXmlParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.SQLXML); else { SQLXML xml = connection.createSQLXML(); xml.setString(value.convertToString().toString()); statement.setSQLXML(index, xml); } } /* protected */ void setBlobParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setBlobParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.BLOB); else { statement.setBlob(index, (InputStream) value); } } } /* protected */ void setBlobParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.BLOB); else { if ( value instanceof RubyString ) { statement.setBlob(index, new ByteArrayInputStream(((RubyString) value).getBytes())); } else { // assume IO/File statement.setBlob(index, ((RubyIO) value).getInStream()); } } } /* protected */ void setClobParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final Object value) throws SQLException { if ( value instanceof IRubyObject ) { setClobParameter(runtime, connection, statement, index, type, (IRubyObject) value); } else { if ( value == null ) statement.setNull(index, Types.CLOB); else { statement.setClob(index, (Reader) value); } } } /* protected */ void setClobParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, final IRubyObject value) throws SQLException { if ( value.isNil() ) statement.setNull(index, Types.CLOB); else { if ( value instanceof RubyString ) { statement.setClob(index, new StringReader(((RubyString) value).decodeString())); } else { // assume IO/File statement.setClob(index, new InputStreamReader(((RubyIO) value).getInStream())); } } } /* protected */ void setObjectParameter(final Ruby runtime, final Connection connection, final PreparedStatement statement, final int index, final int type, Object value) throws SQLException { if (value instanceof IRubyObject) { value = ((IRubyObject) value).toJava(Object.class); } if ( value == null ) statement.setNull(index, Types.JAVA_OBJECT); statement.setObject(index, value); } protected final Connection getConnection() { return getConnection(false); } protected Connection getConnection(boolean error) { final Connection connection = (Connection) dataGetStruct(); if ( connection == null && error ) { final RubyClass errorClass = getConnectionNotEstablished( getRuntime() ); throw new RaiseException(getRuntime(), errorClass, "no connection available", false); } return connection; } private synchronized RubyJdbcConnection setConnection(final Connection connection) { close( getConnection(false) ); // close previously open connection if there is one final IRubyObject rubyConnectionObject = connection != null ? convertJavaToRuby(connection) : getRuntime().getNil(); setInstanceVariable( "@connection", rubyConnectionObject ); dataWrapStruct(connection); return this; } private boolean isConnectionBroken(final ThreadContext context, final Connection connection) { Statement statement = null; try { final RubyString aliveSQL = getConfigValue(context, "connection_alive_sql").convertToString(); if ( isSelect(aliveSQL) ) { // expect a SELECT/CALL SQL statement statement = createStatement(context, connection); statement.execute( aliveSQL.toString() ); return false; // connection ain't broken } else { // alive_sql nil (or not a statement we can execute) return ! connection.isClosed(); // if closed than broken } } catch (Exception e) { debugMessage(context, "connection considered broken due: " + e.toString()); return true; } finally { close(statement); } } private boolean tableExists(final Ruby runtime, final Connection connection, final TableName tableName) throws SQLException { final IRubyObject matchedTables = matchTables(runtime, connection, tableName.catalog, tableName.schema, tableName.name, getTableTypes(), true); // NOTE: allow implementers to ignore checkExistsOnly paramater - empty array means does not exists return matchedTables != null && ! matchedTables.isNil() && ( ! (matchedTables instanceof RubyArray) || ! ((RubyArray) matchedTables).isEmpty() ); } /** * Match table names for given table name (pattern). * @param runtime * @param connection * @param catalog * @param schemaPattern * @param tablePattern * @param types table types * @param checkExistsOnly an optimization flag (that might be ignored by sub-classes) * whether the result really matters if true no need to map table names and a truth-y * value is sufficient (except for an empty array which is considered that the table * did not exists). * @return matched (and Ruby mapped) table names * @see #mapTables(Ruby, DatabaseMetaData, String, String, String, ResultSet) * @throws SQLException */ protected IRubyObject matchTables(final Ruby runtime, final Connection connection, final String catalog, final String schemaPattern, final String tablePattern, final String[] types, final boolean checkExistsOnly) throws SQLException { final DatabaseMetaData metaData = connection.getMetaData(); final String _tablePattern = caseConvertIdentifierForJdbc(metaData, tablePattern); final String _schemaPattern = caseConvertIdentifierForJdbc(metaData, schemaPattern); ResultSet tablesSet = null; try { tablesSet = metaData.getTables(catalog, _schemaPattern, _tablePattern, types); if ( checkExistsOnly ) { // only check if given table exists return tablesSet.next() ? runtime.getTrue() : null; } else { return mapTables(runtime, metaData, catalog, _schemaPattern, _tablePattern, tablesSet); } } finally { close(tablesSet); } } // NOTE java.sql.DatabaseMetaData.getTables : protected final static int TABLES_TABLE_CAT = 1; protected final static int TABLES_TABLE_SCHEM = 2; protected final static int TABLES_TABLE_NAME = 3; protected final static int TABLES_TABLE_TYPE = 4; /** * @param runtime * @param metaData * @param catalog * @param schemaPattern * @param tablePattern * @param tablesSet * @return List<RubyString> * @throws SQLException */ protected RubyArray mapTables(final Ruby runtime, final DatabaseMetaData metaData, final String catalog, final String schemaPattern, final String tablePattern, final ResultSet tablesSet) throws SQLException { final RubyArray tables = runtime.newArray(); while ( tablesSet.next() ) { String name = tablesSet.getString(TABLES_TABLE_NAME); name = caseConvertIdentifierForRails(metaData, name); tables.add(RubyString.newUnicodeString(runtime, name)); } return tables; } /** * NOTE: since 1.3.0 only present for binary compatibility (with extensions). * * @depreacated no longer used - replaced with * {@link #matchTables(Ruby, Connection, String, String, String, String[], boolean)} * please update your sub-class esp. if you're overriding this method ! */ @Deprecated protected SQLBlock tableLookupBlock(final Ruby runtime, final String catalog, final String schemaPattern, final String tablePattern, final String[] types) { return new SQLBlock() { public IRubyObject call(final Connection connection) throws SQLException { return matchTables(runtime, connection, catalog, schemaPattern, tablePattern, types, false); } }; } protected static final int COLUMN_NAME = 4; protected static final int DATA_TYPE = 5; protected static final int TYPE_NAME = 6; protected static final int COLUMN_SIZE = 7; protected static final int DECIMAL_DIGITS = 9; protected static final int COLUMN_DEF = 13; protected static final int IS_NULLABLE = 18; /** * Create a string which represents a SQL type usable by Rails from the * resultSet column meta-data * @param resultSet. */ protected String typeFromResultSet(final ResultSet resultSet) throws SQLException { final int precision = intFromResultSet(resultSet, COLUMN_SIZE); final int scale = intFromResultSet(resultSet, DECIMAL_DIGITS); final String type = resultSet.getString(TYPE_NAME); return formatTypeWithPrecisionAndScale(type, precision, scale); } protected static int intFromResultSet( final ResultSet resultSet, final int column) throws SQLException { final int precision = resultSet.getInt(column); return precision == 0 && resultSet.wasNull() ? -1 : precision; } protected static String formatTypeWithPrecisionAndScale( final String type, final int precision, final int scale) { if ( precision <= 0 ) return type; final StringBuilder typeStr = new StringBuilder().append(type); typeStr.append('(').append(precision); // type += "(" + precision; if ( scale > 0 ) typeStr.append(',').append(scale); // type += "," + scale; return typeStr.append(')').toString(); // type += ")"; } private static IRubyObject defaultValueFromResultSet(final Ruby runtime, final ResultSet resultSet) throws SQLException { final String defaultValue = resultSet.getString(COLUMN_DEF); return defaultValue == null ? runtime.getNil() : RubyString.newUnicodeString(runtime, defaultValue); } private IRubyObject unmarshalColumns(final ThreadContext context, final DatabaseMetaData metaData, final ResultSet results, final ResultSet primaryKeys) throws SQLException { final Ruby runtime = context.getRuntime(); // RubyHash types = (RubyHash) native_database_types(); final IRubyObject jdbcColumn = getJdbcColumnClass(context); final List<String> primarykeyNames = new ArrayList<String>(); while ( primaryKeys.next() ) { primarykeyNames.add( primaryKeys.getString(COLUMN_NAME) ); } final List<IRubyObject> columns = new ArrayList<IRubyObject>(); while ( results.next() ) { final String colName = results.getString(COLUMN_NAME); IRubyObject column = jdbcColumn.callMethod(context, "new", new IRubyObject[] { getInstanceVariable("@config"), RubyString.newUnicodeString( runtime, caseConvertIdentifierForRails(metaData, colName) ), defaultValueFromResultSet( runtime, results ), RubyString.newUnicodeString( runtime, typeFromResultSet(results) ), runtime.newBoolean( ! results.getString(IS_NULLABLE).trim().equals("NO") ) }); columns.add(column); if ( primarykeyNames.contains(colName) ) { column.callMethod(context, "primary=", runtime.getTrue()); } } return runtime.newArray(columns); } protected static IRubyObject unmarshalIdResult( final Ruby runtime, final Statement statement) throws SQLException { final ResultSet genKeys = statement.getGeneratedKeys(); try { if (genKeys.next() && genKeys.getMetaData().getColumnCount() > 0) { return runtime.newFixnum( genKeys.getLong(1) ); } return runtime.getNil(); } finally { close(genKeys); } } /** * @deprecated no longer used - kept for binary compatibility, this method * is confusing since it closes the result set it receives and thus was * replaced with {@link #unmarshalIdResult(Ruby, Statement)} */ @Deprecated public static IRubyObject unmarshal_id_result( final Ruby runtime, final ResultSet genKeys) throws SQLException { try { if (genKeys.next() && genKeys.getMetaData().getColumnCount() > 0) { return runtime.newFixnum( genKeys.getLong(1) ); } return runtime.getNil(); } finally { close(genKeys); } } protected IRubyObject unmarshalResults(final ThreadContext context, final DatabaseMetaData metaData, final Statement statement, final boolean downCase) throws SQLException { final Ruby runtime = context.getRuntime(); IRubyObject result; ResultSet resultSet = statement.getResultSet(); try { result = mapToRawResult(context, runtime, metaData, resultSet, downCase); } finally { close(resultSet); } if ( ! statement.getMoreResults() ) return result; final List<IRubyObject> results = new ArrayList<IRubyObject>(); results.add(result); do { resultSet = statement.getResultSet(); try { result = mapToRawResult(context, runtime, metaData, resultSet, downCase); } finally { close(resultSet); } results.add(result); } while ( statement.getMoreResults() ); return runtime.newArray(results); } /** * @deprecated no longer used but kept for binary compatibility */ @Deprecated protected IRubyObject unmarshalResult(final ThreadContext context, final DatabaseMetaData metaData, final ResultSet resultSet, final boolean downCase) throws SQLException { return mapToRawResult(context, context.getRuntime(), metaData, resultSet, downCase); } /** * Converts a JDBC result set into an array (rows) of hashes (row). * * @param downCase should column names only be in lower case? */ @SuppressWarnings("unchecked") private IRubyObject mapToRawResult(final ThreadContext context, final Ruby runtime, final DatabaseMetaData metaData, final ResultSet resultSet, final boolean downCase) throws SQLException { final ColumnData[] columns = extractColumns(runtime, metaData, resultSet, downCase); final RubyArray results = runtime.newArray(); // [ { 'col1': 1, 'col2': 2 }, { 'col1': 3, 'col2': 4 } ] populateFromResultSet(context, runtime, (List<IRubyObject>) results, resultSet, columns); return results; } private IRubyObject yieldResultRows(final ThreadContext context, final Ruby runtime, final DatabaseMetaData metaData, final ResultSet resultSet, final Block block) throws SQLException { final ColumnData[] columns = extractColumns(runtime, metaData, resultSet, false); final IRubyObject[] blockArgs = new IRubyObject[columns.length]; while ( resultSet.next() ) { for ( int i = 0; i < columns.length; i++ ) { final ColumnData column = columns[i]; blockArgs[i] = jdbcToRuby(runtime, column.index, column.type, resultSet); } block.call( context, blockArgs ); } return runtime.getNil(); // yielded result rows } /** * Extract columns from result set. * @param runtime * @param metaData * @param resultSet * @param downCase * @return columns data * @throws SQLException */ protected ColumnData[] extractColumns(final Ruby runtime, final DatabaseMetaData metaData, final ResultSet resultSet, final boolean downCase) throws SQLException { return setupColumns(runtime, metaData, resultSet.getMetaData(), downCase); } /** * @deprecated renamed and parameterized to {@link #withConnection(ThreadContext, SQLBlock)} */ @Deprecated @SuppressWarnings("unchecked") protected Object withConnectionAndRetry(final ThreadContext context, final SQLBlock block) throws RaiseException { return withConnection(context, block); } protected <T> T withConnection(final ThreadContext context, final Callable<T> block) throws RaiseException { try { return withConnection(context, true, block); } catch (final SQLException e) { return handleException(context, e); // should never happen } } private <T> T withConnection(final ThreadContext context, final boolean handleException, final Callable<T> block) throws RaiseException, RuntimeException, SQLException { Throwable exception = null; int tries = 1; int i = 0; while ( i++ < tries ) { final Connection connection = getConnection(true); boolean autoCommit = true; // retry in-case getAutoCommit throws try { autoCommit = connection.getAutoCommit(); return block.call(connection); } catch (final Exception e) { // SQLException or RuntimeException exception = e; if ( autoCommit ) { // do not retry if (inside) transactions if ( i == 1 ) { IRubyObject retryCount = getConfigValue(context, "retry_count"); tries = (int) retryCount.convertToInteger().getLongValue(); if ( tries <= 0 ) tries = 1; } if ( isConnectionBroken(context, connection) ) { reconnect(context); continue; // retry connection (block) again } break; // connection not broken yet failed } } } // (retry) loop ended and we did not return ... exception != null if ( handleException ) { return handleException(context, getCause(exception)); // throws } else { if ( exception instanceof SQLException ) { throw (SQLException) exception; } if ( exception instanceof RuntimeException ) { throw (RuntimeException) exception; } // won't happen - our try block only throws SQL or Runtime exceptions throw new RuntimeException(exception); } } private static Throwable getCause(Throwable exception) { Throwable cause = exception.getCause(); while (cause != null && cause != exception) { // SQLException's cause might be DB specific (checked/unchecked) : if ( exception instanceof SQLException ) break; exception = cause; cause = exception.getCause(); } return exception; } protected <T> T handleException(final ThreadContext context, Throwable exception) throws RaiseException { // NOTE: we shall not wrap unchecked (runtime) exceptions into AR::Error // if it's really a misbehavior of the driver throwing a RuntimeExcepion // instead of SQLException than this should be overriden for the adapter if ( exception instanceof RuntimeException ) { throw (RuntimeException) exception; } debugStackTrace(context, exception); throw wrapException(context, exception); } /** * @deprecated use {@link #wrapException(ThreadContext, Throwable)} instead * for overriding how exceptions are handled use {@link #handleException(ThreadContext, Throwable)} */ @Deprecated protected RuntimeException wrap(final ThreadContext context, final Throwable exception) { return wrapException(context, exception); } protected RaiseException wrapException(final ThreadContext context, final Throwable exception) { final Ruby runtime = context.getRuntime(); if ( exception instanceof SQLException ) { final String message = SQLException.class == exception.getClass() ? exception.getMessage() : exception.toString(); // useful to easily see type on Ruby side final RaiseException error = wrapException(context, getJDBCError(runtime), exception, message); final int errorCode = ((SQLException) exception).getErrorCode(); RuntimeHelpers.invoke( context, error.getException(), "errno=", runtime.newFixnum(errorCode) ); RuntimeHelpers.invoke( context, error.getException(), "sql_exception=", JavaEmbedUtils.javaToRuby(runtime, exception) ); return error; } return wrapException(context, getJDBCError(runtime), exception); } protected static RaiseException wrapException(final ThreadContext context, final RubyClass errorClass, final Throwable exception) { return wrapException(context, errorClass, exception, exception.toString()); } protected static RaiseException wrapException(final ThreadContext context, final RubyClass errorClass, final Throwable exception, final String message) { final RaiseException error = new RaiseException(context.getRuntime(), errorClass, message, true); error.initCause(exception); return error; } private IRubyObject convertJavaToRuby(final Connection connection) { return JavaUtil.convertJavaToRuby( getRuntime(), connection ); } /** * Some databases support schemas and others do not. * For ones which do this method should return true, aiding in decisions regarding schema vs database determination. */ protected boolean databaseSupportsSchemas() { return false; } private static final byte[] SELECT = new byte[] { 's','e','l','e','c','t' }; private static final byte[] WITH = new byte[] { 'w','i','t','h' }; private static final byte[] SHOW = new byte[] { 's','h','o','w' }; private static final byte[] CALL = new byte[]{ 'c','a','l','l' }; @JRubyMethod(name = "select?", required = 1, meta = true, frame = false) public static IRubyObject select_p(final ThreadContext context, final IRubyObject self, final IRubyObject sql) { return context.getRuntime().newBoolean( isSelect(sql.convertToString()) ); } private static boolean isSelect(final RubyString sql) { final ByteList sqlBytes = sql.getByteList(); return startsWithIgnoreCase(sqlBytes, SELECT) || startsWithIgnoreCase(sqlBytes, WITH) || startsWithIgnoreCase(sqlBytes, SHOW) || startsWithIgnoreCase(sqlBytes, CALL); } private static final byte[] INSERT = new byte[] { 'i','n','s','e','r','t' }; @JRubyMethod(name = "insert?", required = 1, meta = true, frame = false) public static IRubyObject insert_p(final ThreadContext context, final IRubyObject self, final IRubyObject sql) { final ByteList sqlBytes = sql.convertToString().getByteList(); return context.getRuntime().newBoolean(startsWithIgnoreCase(sqlBytes, INSERT)); } protected static boolean startsWithIgnoreCase(final ByteList string, final byte[] start) { int p = skipWhitespace(string, string.getBegin()); final byte[] stringBytes = string.unsafeBytes(); if ( stringBytes[p] == '(' ) p = skipWhitespace(string, p + 1); for ( int i = 0; i < string.getRealSize() && i < start.length; i++ ) { if ( Character.toLowerCase(stringBytes[p + i]) != start[i] ) return false; } return true; } private static int skipWhitespace(final ByteList string, final int from) { final int end = string.getBegin() + string.getRealSize(); final byte[] stringBytes = string.unsafeBytes(); for ( int i = from; i < end; i++ ) { if ( ! Character.isWhitespace( stringBytes[i] ) ) return i; } return end; } /** * JDBC connection helper that handles mapping results to * <code>ActiveRecord::Result</code> (available since AR-3.1). * * @see #populateFromResultSet(ThreadContext, Ruby, List, ResultSet, RubyJdbcConnection.ColumnData[]) * @author kares */ protected static class ResultHandler { protected static Boolean USE_RESULT; // AR-3.2 : initialize(columns, rows) // AR-4.0 : initialize(columns, rows, column_types = {}) protected static Boolean INIT_COLUMN_TYPES = Boolean.FALSE; protected static Boolean FORCE_HASH_ROWS = Boolean.FALSE; private static volatile ResultHandler instance; public static ResultHandler getInstance(final ThreadContext context) { if ( instance == null ) { synchronized(ResultHandler.class) { if ( instance == null ) { // fine to initialize twice setInstance( new ResultHandler(context) ); } } } return instance; } protected static synchronized void setInstance(final ResultHandler instance) { ResultHandler.instance = instance; } protected ResultHandler(final ThreadContext context) { final Ruby runtime = context.getRuntime(); final RubyClass result = getResult(runtime); USE_RESULT = result != null && result != runtime.getNilClass(); } public IRubyObject mapRow(final ThreadContext context, final Ruby runtime, final ColumnData[] columns, final ResultSet resultSet, final RubyJdbcConnection connection) throws SQLException { if ( USE_RESULT ) { // maps a AR::Result row final RubyArray row = runtime.newArray(columns.length); for ( int i = 0; i < columns.length; i++ ) { final ColumnData column = columns[i]; row.append( connection.jdbcToRuby(runtime, column.index, column.type, resultSet) ); } return row; } else { return mapRawRow(context, runtime, columns, resultSet, connection); } } IRubyObject mapRawRow(final ThreadContext context, final Ruby runtime, final ColumnData[] columns, final ResultSet resultSet, final RubyJdbcConnection connection) throws SQLException { final RubyHash row = RubyHash.newHash(runtime); for ( int i = 0; i < columns.length; i++ ) { final ColumnData column = columns[i]; row.op_aset( context, column.name, connection.jdbcToRuby(runtime, column.index, column.type, resultSet) ); } return row; } public IRubyObject newResult(final ThreadContext context, final Ruby runtime, final ColumnData[] columns, final IRubyObject rows) { // rows array if ( USE_RESULT ) { // ActiveRecord::Result.new(columns, rows) final RubyClass result = getResult(runtime); return result.callMethod( context, "new", initArgs(runtime, columns, rows), Block.NULL_BLOCK ); } return rows; // contains { 'col1' => 1, ... } Hash-es } private IRubyObject[] initArgs(final Ruby runtime, final ColumnData[] columns, final IRubyObject rows) { final IRubyObject[] args; final RubyArray cols = runtime.newArray(columns.length); if ( INIT_COLUMN_TYPES ) { // NOTE: NOT IMPLEMENTED for ( int i=0; i<columns.length; i++ ) { cols.add( columns[i].name ); } args = new IRubyObject[] { cols, rows }; } else { for ( int i=0; i<columns.length; i++ ) { cols.add( columns[i].name ); } args = new IRubyObject[] { cols, rows }; } return args; } } protected static final class TableName { public final String catalog, schema, name; public TableName(String catalog, String schema, String table) { this.catalog = catalog; this.schema = schema; this.name = table; } } /** * Extract the table name components for the given name e.g. "mycat.sys.entries" * * @param connection * @param catalog (optional) catalog to use if table name does not contain * the catalog prefix * @param schema (optional) schema to use if table name does not have one * @param tableName the table name * @return (parsed) table name * * @throws IllegalArgumentException for invalid table name format * @throws SQLException */ protected TableName extractTableName( final Connection connection, String catalog, String schema, final String tableName) throws IllegalArgumentException, SQLException { final String[] nameParts = tableName.split("\\."); if ( nameParts.length > 3 ) { throw new IllegalArgumentException("table name: " + tableName + " should not contain more than 2 '.'"); } String name = tableName; if ( nameParts.length == 2 ) { schema = nameParts[0]; name = nameParts[1]; } else if ( nameParts.length == 3 ) { catalog = nameParts[0]; schema = nameParts[1]; name = nameParts[2]; } final DatabaseMetaData metaData = connection.getMetaData(); if (schema != null) { schema = caseConvertIdentifierForJdbc(metaData, schema); } name = caseConvertIdentifierForJdbc(metaData, name); if (schema != null && ! databaseSupportsSchemas()) { catalog = schema; } if (catalog == null) catalog = connection.getCatalog(); return new TableName(catalog, schema, name); } /** * @deprecated use {@link #extractTableName(Connection, String, String, String)} */ @Deprecated protected TableName extractTableName( final Connection connection, final String schema, final String tableName) throws IllegalArgumentException, SQLException { return extractTableName(connection, null, schema, tableName); } protected static final class ColumnData { public final RubyString name; public final int index; public final int type; public ColumnData(RubyString name, int type, int idx) { this.name = name; this.type = type; this.index = idx; } } private static ColumnData[] setupColumns( final Ruby runtime, final DatabaseMetaData metaData, final ResultSetMetaData resultMetaData, final boolean downCase) throws SQLException { final int columnCount = resultMetaData.getColumnCount(); final ColumnData[] columns = new ColumnData[columnCount]; for ( int i = 1; i <= columnCount; i++ ) { // metadata is one-based final String name; if (downCase) { name = resultMetaData.getColumnLabel(i).toLowerCase(); } else { name = caseConvertIdentifierForRails(metaData, resultMetaData.getColumnLabel(i)); } final int columnType = resultMetaData.getColumnType(i); final RubyString columnName = RubyString.newUnicodeString(runtime, name); columns[i - 1] = new ColumnData(columnName, columnType, i); } return columns; } // JDBC API Helpers : protected static void close(final Connection connection) { if ( connection != null ) { try { connection.close(); } catch (final Exception e) { /* NOOP */ } } } public static void close(final ResultSet resultSet) { if (resultSet != null) { try { resultSet.close(); } catch (final Exception e) { /* NOOP */ } } } public static void close(final Statement statement) { if (statement != null) { try { statement.close(); } catch (final Exception e) { /* NOOP */ } } } // DEBUG-ing helpers : private static boolean debug = Boolean.getBoolean("arjdbc.debug"); public static boolean isDebug() { return debug; } public static void setDebug(boolean debug) { RubyJdbcConnection.debug = debug; } public static void debugMessage(final ThreadContext context, final String msg) { if ( debug || context.runtime.isDebug() ) { context.runtime.getOut().println(msg); } } protected static void debugErrorSQL(final ThreadContext context, final String sql) { if ( debug || context.runtime.isDebug() ) { context.runtime.getOut().println("Error SQL: " + sql); } } public static void debugStackTrace(final ThreadContext context, final Throwable e) { if ( debug || context.runtime.isDebug() ) { e.printStackTrace(context.runtime.getOut()); } } }
due removed ThreadContext.createCallerBacktrace we need to re-invent it using reflection - provides us and maintains JRuby 1.6.8 - 1.7.4 compatibility
src/java/arjdbc/jdbc/RubyJdbcConnection.java
due removed ThreadContext.createCallerBacktrace we need to re-invent it using reflection - provides us and maintains JRuby 1.6.8 - 1.7.4 compatibility
<ide><path>rc/java/arjdbc/jdbc/RubyJdbcConnection.java <ide> import java.io.Reader; <ide> import java.io.StringReader; <ide> import java.lang.reflect.InvocationTargetException; <add>import java.lang.reflect.Method; <ide> import java.math.BigDecimal; <ide> import java.math.BigInteger; <ide> import java.sql.Array; <ide> import org.jruby.runtime.Block; <ide> import org.jruby.runtime.ObjectAllocator; <ide> import org.jruby.runtime.ThreadContext; <add>import org.jruby.runtime.backtrace.RubyStackTraceElement; <ide> import org.jruby.runtime.builtin.IRubyObject; <ide> import org.jruby.util.ByteList; <ide> <ide> // https://github.com/jruby/activerecord-jdbc-adapter/issues/197 <ide> // https://github.com/jruby/activerecord-jdbc-adapter/issues/198 <ide> if ( Boolean.getBoolean("arjdbc.disconnect.debug") ) { <add> final List<?> backtrace = createCallerBacktrace(context); <ide> final Ruby runtime = context.getRuntime(); <del> List backtrace = (List) context.createCallerBacktrace(runtime, 0); <ide> runtime.getOut().println(this + " connection.disconnect! occured: "); <ide> for ( Object element : backtrace ) { <ide> runtime.getOut().println(element); <ide> } <ide> return setConnection(null); <ide> } <del> <add> <ide> @JRubyMethod(name = "reconnect!") <ide> public IRubyObject reconnect(final ThreadContext context) { <ide> try { <ide> } <ide> } <ide> <add> private static RubyArray createCallerBacktrace(final ThreadContext context) { <add> final Ruby runtime = context.getRuntime(); <add> runtime.incrementCallerCount(); <add> <add> Method gatherCallerBacktrace; RubyStackTraceElement[] trace; <add> try { <add> gatherCallerBacktrace = context.getClass().getMethod("gatherCallerBacktrace"); <add> trace = (RubyStackTraceElement[]) gatherCallerBacktrace.invoke(context); // 1.6.8 <add> } <add> catch (NoSuchMethodException ignore) { <add> try { <add> gatherCallerBacktrace = context.getClass().getMethod("gatherCallerBacktrace", Integer.TYPE); <add> trace = (RubyStackTraceElement[]) gatherCallerBacktrace.invoke(context, 0); // 1.7.4 <add> } <add> catch (NoSuchMethodException e) { throw new RuntimeException(e); } <add> catch (IllegalAccessException e) { throw new RuntimeException(e); } <add> catch (InvocationTargetException e) { throw new RuntimeException(e.getTargetException()); } <add> } <add> catch (IllegalAccessException e) { throw new RuntimeException(e); } <add> catch (InvocationTargetException e) { throw new RuntimeException(e.getTargetException()); } <add> // RubyStackTraceElement[] trace = context.gatherCallerBacktrace(level); <add> <add> final RubyArray backtrace = runtime.newArray(trace.length); <add> for (int i = 0; i < trace.length; i++) { <add> RubyStackTraceElement element = trace[i]; <add> backtrace.append( RubyString.newString(runtime, <add> element.getFileName() + ":" + element.getLineNumber() + ":in `" + element.getMethodName() + "'" <add> ) ); <add> } <add> return backtrace; <add> } <add> <ide> }
JavaScript
apache-2.0
1fa739607c6964fab2c04c7382d63d78d20dbd49
0
dollars0427/SQLwatcher
//Require Module var log4js = require('log4js'); var logger = log4js.getLogger('Logging'); var mysql = require('mysql'); var mailer = require('emailjs'); var promise = require('promised-io'); var when = promise.when; var fs = require('fs'); var settingPath = process.argv[2]; var queryListPath = process.argv[3]; if(!settingPath || !queryListPath){ printUsage(); process.exit(1); } function printUsage(){ var out = "Usage: " + process.argv[1] + " [Setting file] [Query list file]" console.log(out); } var settingFile = JSON.parse(fs.readFileSync(settingPath)); var queryListFile = JSON.parse(fs.readFileSync(queryListPath)); var dbConfig = settingFile['database'] var queryConfig = queryListFile['query'] var timerConfig = settingFile['repeatTimer']; var mailConfig = settingFile['mail']; var database = require('./database'); var email = require('./email'); var mysqlOpt = { host:dbConfig.host, port:dbConfig.port, user:dbConfig.username, password:dbConfig.password, database:dbConfig.dbName } var aliveMailOpt = { text: mailConfig.alive.text, from: mailConfig.alive.from, to: mailConfig.alive.to, subject: mailConfig.alive.subject }; var warningMailOpt = { text: mailConfig.dead.text, from: mailConfig.dead.from, to: mailConfig.dead.to, subject: mailConfig.dead.subject } var workerFree = true; var lastExecute = 0; var lastSuccess = 0; var times = timerConfig.ms; setInterval(runSQL,500); function getLock(){ if(!workerFree){ return false; } workerFree = false; return true; } function release(reset){ if(reset){ lastExecute = new Date().getTime(); } workerFree = true; } function runSQL(){ if(!getLock()){ return; } var now = new Date().getTime(); if (now - lastExecute < times){ release(); return; } var dbConnection = mysql.createConnection(mysqlOpt); function connectDatabase(){ var p = new promise.defer(); dbConnection.connect(function(err){ if(err){ logger.error('Cannot Connect To Database!',err); process.exit(1); } logger.info('Connected to database.'); p.resolve(); }); return p; } function _runSQL(opt){ var p = new promise.defer(); var query = queryConfig[opt["idx"]]; if(!query){ p.resolve(); return p; } database.excuteMySQLQuery(dbConnection,query,function(err,result){ if(err){ logger.error('Detected Error! ', err); p.reject({ time:new Date(), err: new Error(err), sql: query }); return; } logger.info('SQL success:', query); p.resolve({ idx: opt["idx"] + 1}); }); return p; } function complete(){ var p = new promise.defer(); dbConnection.end(function(err){ if(err){ logger.error(err); connection.end(); } logger.info('Complete!'); release(true); p.resolve(); }); return p; } function runQueries(){ var p = new promise.defer(); function runSucess(){ logger.warn('Run Sucess!'); var opt = { time: new Date(), }; p.resolve(opt); } function runFailed(opt){ logger.warn('Run Failed:'); logger.warn(opt.err); logger.warn(opt.sql); p.resolve(opt); } var funList = []; for(var i = 0; i< queryConfig.length; i++){ funList.push(_runSQL); } var pSQL = promise.seq(funList, {idx: 0}); when(pSQL,runSucess,runFailed); return p; } function sendNotification(result){ var p = new promise.defer(); var mailConnection = mailer.server.connect({ user:mailConfig.server.user, password:mailConfig.server.password, host:mailConfig.server.host, port:mailConfig.server.port, ssl:mailConfig.server.ssl, tls:mailConfig.server.tls }); if(result['err']){ var text = mailConfig.dead.text + ' \n' + ' \n' +'Result Time: ' + result['time'] +' \n Error Message: ' + result['err'] +' \n' +' \n Excuted Query:' + result['sql']; var opt = { text: text, from: mailConfig.dead.from, to: mailConfig.dead.to, subject: mailConfig.dead.subject }; email.sendWarningMail(mailConnection,opt,function(err,email){ if(err){ logger.error(err); } }); } } var chain = new promise.defer(); chain .then(connectDatabase) .then(runQueries) .then(sendNotification) .then(complete) chain.resolve(); } function sendMail(err,email){ if(err){ logger.error(err); return; } logger.debug('Sended Messages: ',email); }
index.js
//Require Module var log4js = require('log4js'); var logger = log4js.getLogger('Logging'); var mysql = require('mysql'); var mailer = require('emailjs'); var promise = require('promised-io'); var when = promise.when; var fs = require('fs'); var settingPath = process.argv[2]; var queryListPath = process.argv[3]; if(!settingPath || !queryListPath){ printUsage(); process.exit(1); } function printUsage(){ var out = "Usage: " + process.argv[1] + " [Setting file] [Query list file]" console.log(out); } var settingFile = JSON.parse(fs.readFileSync(settingPath)); var queryListFile = JSON.parse(fs.readFileSync(queryListPath)); var dbConfig = settingFile['database'] var queryConfig = queryListFile['query'] var timerConfig = settingFile['repeatTimer']; var mailConfig = settingFile['mail']; var database = require('./database'); var email = require('./email'); var mysqlOpt = { host:dbConfig.host, port:dbConfig.port, user:dbConfig.username, password:dbConfig.password, database:dbConfig.dbName } var aliveMailOpt = { text: mailConfig.alive.text, from: mailConfig.alive.from, to: mailConfig.alive.to, subject: mailConfig.alive.subject }; var warningMailOpt = { text: mailConfig.dead.text, from: mailConfig.dead.from, to: mailConfig.dead.to, subject: mailConfig.dead.subject } var mailConnection = mailer.server.connect({ user:mailConfig.server.user, password:mailConfig.server.password, host:mailConfig.server.host, port:mailConfig.server.port, ssl:mailConfig.server.ssl, tls:mailConfig.server.tls }); var workerFree = true; var lastExecute = 0; var times = timerConfig.ms; setInterval(runSQL,500); function getLock(){ if(!workerFree){ return false; } workerFree = false; return true; } function release(reset){ if(reset){ lastExecute = new Date().getTime(); } workerFree = true; } function runSQL(){ if(!getLock()){ return; } var now = new Date().getTime(); if (now - lastExecute < times){ release(); return; } var dbConnection = mysql.createConnection(mysqlOpt); function connectDatabase(){ var p = new promise.defer(); dbConnection.connect(function(err){ if(err){ logger.error('Cannot Connect To Database!',err); process.exit(1); } logger.info('Connected to database.'); p.resolve(); }); return p; } function _runSQL(opt){ var p = new promise.defer(); var query = queryConfig[opt["idx"]]; if(!query){ p.resolve(); return p; } database.excuteMySQLQuery(dbConnection,query,function(err,result){ if(err){ logger.error('Detected Error! ', err); p.reject({ err: new Error(err), sql: query }); return; } logger.info('SQL success:', query); p.resolve({ idx: opt["idx"] + 1}); }); return p; } function complete(){ var p = new promise.defer(); dbConnection.end(function(err){ if(err){ logger.error(err); connection.end(); } logger.info('Complete!'); release(true); p.resolve(); }); return p; } function runQueries(){ var p = new promise.defer(); function runSucess(opt){ logger.warn('Run Sucess!'); p.resolve(); } function runFailed(opt){ logger.warn('Run Failed:'); logger.warn(opt.err); logger.warn(opt.sql); p.resolve(); } var funList = []; for(var i = 0; i< queryConfig.length; i++){ funList.push(_runSQL); } var pSQL = promise.seq(funList, {idx: 0}); when(pSQL,runSucess,runFailed); return p; } var chain = new promise.defer(); chain .then(connectDatabase) .then(runQueries) .then(sendNotification) .then(complete) chain.resolve(); } function sendMail(err,email){ if(err){ logger.error(err); return; } logger.debug('Sended Messages: ',email); }
Can send warning email
index.js
Can send warning email
<ide><path>ndex.js <ide> subject: mailConfig.dead.subject <ide> } <ide> <del>var mailConnection = mailer.server.connect({ <del> user:mailConfig.server.user, <del> password:mailConfig.server.password, <del> host:mailConfig.server.host, <del> port:mailConfig.server.port, <del> ssl:mailConfig.server.ssl, <del> tls:mailConfig.server.tls <del>}); <ide> <ide> var workerFree = true; <ide> var lastExecute = 0; <add>var lastSuccess = 0; <ide> <ide> var times = timerConfig.ms; <ide> <ide> } <ide> <ide> var dbConnection = mysql.createConnection(mysqlOpt); <del> <add> <ide> function connectDatabase(){ <ide> <ide> var p = new promise.defer(); <ide> logger.error('Detected Error! ', err); <ide> <ide> p.reject({ <add> time:new Date(), <ide> err: new Error(err), <ide> sql: query <ide> }); <ide> function runQueries(){ <ide> <ide> var p = new promise.defer(); <del> <del> function runSucess(opt){ <add> <add> function runSucess(){ <ide> <ide> logger.warn('Run Sucess!'); <ide> <del> p.resolve(); <add> var opt = { <add> time: new Date(), <add> }; <add> <add> p.resolve(opt); <ide> <ide> } <ide> <ide> logger.warn(opt.err); <ide> logger.warn(opt.sql); <ide> <del> p.resolve(); <add> p.resolve(opt); <ide> <ide> } <ide> <ide> <ide> return p; <ide> } <del> <add> <add> function sendNotification(result){ <add> <add> var p = new promise.defer(); <add> <add> var mailConnection = mailer.server.connect({ <add> user:mailConfig.server.user, <add> password:mailConfig.server.password, <add> host:mailConfig.server.host, <add> port:mailConfig.server.port, <add> ssl:mailConfig.server.ssl, <add> tls:mailConfig.server.tls <add> }); <add> <add> if(result['err']){ <add> <add> var text = mailConfig.dead.text <add> + ' \n' <add> + ' \n' <add> +'Result Time: ' <add> + result['time'] <add> +' \n Error Message: ' <add> + result['err'] <add> +' \n' <add> +' \n Excuted Query:' <add> + result['sql']; <add> <add> var opt = { <add> text: text, <add> from: mailConfig.dead.from, <add> to: mailConfig.dead.to, <add> subject: mailConfig.dead.subject <add> }; <add> <add> email.sendWarningMail(mailConnection,opt,function(err,email){ <add> <add> if(err){ <add> logger.error(err); <add> } <add> <add> }); <add> } <add> <add> } <add> <ide> var chain = new promise.defer(); <ide> chain <ide> .then(connectDatabase) <ide> <ide> <ide> function sendMail(err,email){ <del> <add> <ide> if(err){ <ide> logger.error(err); <ide> return;
Java
bsd-3-clause
c0c22f9815acd496dc52ecb63917919f52600cb1
0
naixx/threetenbp,pepyakin/threetenbp,pepyakin/threetenbp,naixx/threetenbp,ThreeTen/threetenbp,ThreeTen/threetenbp,jnehlmeier/threetenbp,jnehlmeier/threetenbp
/* * Copyright (c) 2007, 2008, Stephen Colebourne & Michael Nascimento Santos * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of JSR-310 nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package javax.time; /** * Provides access to an instant on the time-line. * <p> * InstantProvider is a simple interface that provides uniform access to any * object that can provide access to an <code>Instant</code>. * <p> * The implementation of <code>InstantProvider</code> may be mutable. * For example, {@link java.util.Date Date} is a mutable implementation of * this interface. * The result of {@link #toInstant()}, however, is immutable. * <p> * When implementing an API that accepts an InstantProvider as a parameter, it is * important to convert the input to a <code>Instant</code> once and once only. * It is recommended that this is done at the top of the method before other processing. * This is necessary to handle the case where the implementation of the provider is * mutable and changes in value between two calls to <code>toInstant()</code>. * <p> * The recommended way to convert an InstantProvider to a Instant is using * {@link Instant#instant(InstantProvider)} as this method provides additional null checking. * <p> * It is recommended that this interface should only be implemented by classes * that provide time information to at least minute precision. * <p> * The implementation of <code>InstantProvider</code> may provide more * information than just an instant. For example, * {@link javax.time.calendar.ZonedDateTime ZonedDateTime}, implements this * interface and also provides full date, time and time zone information. * <p> * InstantProvider makes no guarantees about the thread-safety or immutability * of implementations. * * @author Michael Nascimento Santos * @author Stephen Colebourne */ public interface InstantProvider { /** * Returns an instance of <code>Instant</code> initialised from the * state of this object. * <p> * This method will take the instant represented by this object and return * an {@link Instant}. If this object is already a <code>Instant</code> * then it is simply returned. * <p> * If this object does not support nanosecond precision, then all fields * below the precision it does support must be set to zero. For example, * if this instance only stores millisecond precision, then the * nanoseconds part of the <code>Instant</code> will be set to zero. * * @return the <code>Instant</code> equivalent to this object, never null * @throws CalendricalException if the time cannot be converted */ Instant toInstant(); }
src/main/java/javax/time/InstantProvider.java
/* * Copyright (c) 2007, 2008, Stephen Colebourne & Michael Nascimento Santos * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of JSR-310 nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package javax.time; import javax.time.calendar.LocalTime; import javax.time.calendar.TimeProvider; /** * Provides access to an instant on the time-line. * <p> * InstantProvider is a simple interface that provides uniform access to any * object that can provide access to an <code>Instant</code>. * <p> * The implementation of <code>InstantProvider</code> may be mutable. * For example, {@link java.util.Date Date} is a mutable implementation of * this interface. * The result of {@link #toInstant()}, however, is immutable. * <p> * When implementing an API that accepts an InstantProvider as a parameter, it is * important to convert the input to a <code>Instant</code> once and once only. * It is recommended that this is done at the top of the method before other processing. * This is necessary to handle the case where the implementation of the provider is * mutable and changes in value between two calls to <code>toInstant()</code>. * <p> * The recommended way to convert a TimeProvider to a LocalTime is using * {@link LocalTime#dateTime(TimeProvider)} as this method provides additional null checking. * <p> * It is recommended that this interface should only be implemented by classes * that provide time information to at least minute precision. * <p> * The implementation of <code>InstantProvider</code> may provide more * information than just an instant. For example, * {@link javax.time.calendar.ZonedDateTime ZonedDateTime}, implements this * interface and also provides full date, time and time zone information. * <p> * InstantProvider makes no guarantees about the thread-safety or immutability * of implementations. * * @author Michael Nascimento Santos * @author Stephen Colebourne */ public interface InstantProvider { /** * Returns an instance of <code>Instant</code> initialised from the * state of this object. * <p> * This method will take the instant represented by this object and return * an {@link Instant}. If this object is already a <code>Instant</code> * then it is simply returned. * <p> * If this object does not support nanosecond precision, then all fields * below the precision it does support must be set to zero. For example, * if this instance only stores millisecond precision, then the * nanoseconds part of the <code>Instant</code> will be set to zero. * * @return the <code>Instant</code> equivalent to this object, never null * @throws CalendricalException if the time cannot be converted */ Instant toInstant(); }
Tidy provider definition and implementation git-svn-id: 17e42e1b38baac66ab68ec9830049dead5ccbb9b@651 291d795c-afe8-5c46-8ee5-bf9dd72e1864
src/main/java/javax/time/InstantProvider.java
Tidy provider definition and implementation
<ide><path>rc/main/java/javax/time/InstantProvider.java <ide> */ <ide> package javax.time; <ide> <del>import javax.time.calendar.LocalTime; <del>import javax.time.calendar.TimeProvider; <ide> <ide> /** <ide> * Provides access to an instant on the time-line. <ide> * This is necessary to handle the case where the implementation of the provider is <ide> * mutable and changes in value between two calls to <code>toInstant()</code>. <ide> * <p> <del> * The recommended way to convert a TimeProvider to a LocalTime is using <del> * {@link LocalTime#dateTime(TimeProvider)} as this method provides additional null checking. <add> * The recommended way to convert an InstantProvider to a Instant is using <add> * {@link Instant#instant(InstantProvider)} as this method provides additional null checking. <ide> * <p> <ide> * It is recommended that this interface should only be implemented by classes <ide> * that provide time information to at least minute precision.
Java
apache-2.0
4b5e60d8948051dac95a112f2ad0cb0f26c657ca
0
3dcitydb/importer-exporter,3dcitydb/importer-exporter,3dcitydb/importer-exporter
/* * 3D City Database - The Open Source CityGML Database * https://www.3dcitydb.org/ * * Copyright 2013 - 2021 * Chair of Geoinformatics * Technical University of Munich, Germany * https://www.lrg.tum.de/gis/ * * The 3D City Database is jointly developed with the following * cooperation partners: * * Virtual City Systems, Berlin <https://vc.systems/> * M.O.S.S. Computer Grafik Systeme GmbH, Taufkirchen <http://www.moss.de/> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.citydb.core.database.version; import org.citydb.config.i18n.Language; import org.citydb.config.project.database.DatabaseConfig; import org.citydb.core.database.adapter.AbstractDatabaseAdapter; import org.citydb.core.database.connection.DatabaseConnectionWarning; import org.citydb.core.database.connection.DatabaseConnectionWarning.ConnectionWarningType; import org.citydb.core.util.Util; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class DefaultDatabaseVersionChecker implements DatabaseVersionChecker { private final DatabaseVersionSupport[] supportedVersions = new DatabaseVersionSupport[]{ DatabaseVersionSupport.targetVersion(4, 3, 0).withBackwardsCompatibility(4, 0, 0).withRevisionForwardCompatibility(true), DatabaseVersionSupport.targetVersion(3, 3, 1).withBackwardsCompatibility(3, 0, 0).withRevisionForwardCompatibility(true) }; @Override public List<DatabaseConnectionWarning> checkVersionSupport(AbstractDatabaseAdapter databaseAdapter) throws DatabaseVersionException { DatabaseVersion version = databaseAdapter.getConnectionMetaData().getCityDBVersion(); List<DatabaseConnectionWarning> warnings = new ArrayList<DatabaseConnectionWarning>(); // check for unsupported version if (!version.isSupportedBy(supportedVersions)) { String message = "The version " + version + " of the " + DatabaseConfig.CITYDB_PRODUCT_NAME + " is not supported."; String text = Language.I18N.getString("db.dialog.error.version.error"); Object[] args = new Object[]{ version, DatabaseConfig.CITYDB_PRODUCT_NAME, Util.collection2string(Arrays.asList(supportedVersions), ", ") }; String formattedMessage = MessageFormat.format(text, args); throw new DatabaseVersionException(message, formattedMessage, DatabaseConfig.CITYDB_PRODUCT_NAME, Arrays.asList(supportedVersions)); } // check for outdated version for (DatabaseVersionSupport supportedVersion : supportedVersions) { if (supportedVersion.getTargetVersion().compareTo(version) > 0) { String message = "The version " + version + " of the " + DatabaseConfig.CITYDB_PRODUCT_NAME + " is out of date. Consider upgrading."; String text = Language.I18N.getString("db.dialog.warn.version.outofdate"); Object[] args = new Object[]{ version, DatabaseConfig.CITYDB_PRODUCT_NAME }; String formattedMessage = MessageFormat.format(text, args); warnings.add(new DatabaseConnectionWarning(message, formattedMessage, DatabaseConfig.CITYDB_PRODUCT_NAME, ConnectionWarningType.OUTDATED_DATABASE_VERSION)); break; } } return warnings; } @Override public List<DatabaseVersionSupport> getSupportedVersions(String productName) { return DatabaseConfig.CITYDB_PRODUCT_NAME.equals(productName) ? Arrays.asList(supportedVersions) : Collections.<DatabaseVersionSupport>emptyList(); } }
impexp-core/src/main/java/org/citydb/core/database/version/DefaultDatabaseVersionChecker.java
/* * 3D City Database - The Open Source CityGML Database * https://www.3dcitydb.org/ * * Copyright 2013 - 2021 * Chair of Geoinformatics * Technical University of Munich, Germany * https://www.lrg.tum.de/gis/ * * The 3D City Database is jointly developed with the following * cooperation partners: * * Virtual City Systems, Berlin <https://vc.systems/> * M.O.S.S. Computer Grafik Systeme GmbH, Taufkirchen <http://www.moss.de/> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.citydb.core.database.version; import org.citydb.config.i18n.Language; import org.citydb.config.project.database.DatabaseConfig; import org.citydb.core.database.adapter.AbstractDatabaseAdapter; import org.citydb.core.database.connection.DatabaseConnectionWarning; import org.citydb.core.database.connection.DatabaseConnectionWarning.ConnectionWarningType; import org.citydb.core.util.Util; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class DefaultDatabaseVersionChecker implements DatabaseVersionChecker { private final DatabaseVersionSupport[] supportedVersions = new DatabaseVersionSupport[]{ DatabaseVersionSupport.targetVersion(4, 2, 0).withBackwardsCompatibility(4, 0, 0).withRevisionForwardCompatibility(true), DatabaseVersionSupport.targetVersion(3, 3, 1).withBackwardsCompatibility(3, 0, 0).withRevisionForwardCompatibility(true) }; @Override public List<DatabaseConnectionWarning> checkVersionSupport(AbstractDatabaseAdapter databaseAdapter) throws DatabaseVersionException { DatabaseVersion version = databaseAdapter.getConnectionMetaData().getCityDBVersion(); List<DatabaseConnectionWarning> warnings = new ArrayList<DatabaseConnectionWarning>(); // check for unsupported version if (!version.isSupportedBy(supportedVersions)) { String message = "The version " + version + " of the " + DatabaseConfig.CITYDB_PRODUCT_NAME + " is not supported."; String text = Language.I18N.getString("db.dialog.error.version.error"); Object[] args = new Object[]{ version, DatabaseConfig.CITYDB_PRODUCT_NAME, Util.collection2string(Arrays.asList(supportedVersions), ", ") }; String formattedMessage = MessageFormat.format(text, args); throw new DatabaseVersionException(message, formattedMessage, DatabaseConfig.CITYDB_PRODUCT_NAME, Arrays.asList(supportedVersions)); } // check for outdated version for (DatabaseVersionSupport supportedVersion : supportedVersions) { if (supportedVersion.getTargetVersion().compareTo(version) > 0) { String message = "The version " + version + " of the " + DatabaseConfig.CITYDB_PRODUCT_NAME + " is out of date. Consider upgrading."; String text = Language.I18N.getString("db.dialog.warn.version.outofdate"); Object[] args = new Object[]{ version, DatabaseConfig.CITYDB_PRODUCT_NAME }; String formattedMessage = MessageFormat.format(text, args); warnings.add(new DatabaseConnectionWarning(message, formattedMessage, DatabaseConfig.CITYDB_PRODUCT_NAME, ConnectionWarningType.OUTDATED_DATABASE_VERSION)); break; } } return warnings; } @Override public List<DatabaseVersionSupport> getSupportedVersions(String productName) { return DatabaseConfig.CITYDB_PRODUCT_NAME.equals(productName) ? Arrays.asList(supportedVersions) : Collections.<DatabaseVersionSupport>emptyList(); } }
added support for connecting to 3DCityDB v4.3.0
impexp-core/src/main/java/org/citydb/core/database/version/DefaultDatabaseVersionChecker.java
added support for connecting to 3DCityDB v4.3.0
<ide><path>mpexp-core/src/main/java/org/citydb/core/database/version/DefaultDatabaseVersionChecker.java <ide> <ide> public class DefaultDatabaseVersionChecker implements DatabaseVersionChecker { <ide> private final DatabaseVersionSupport[] supportedVersions = new DatabaseVersionSupport[]{ <del> DatabaseVersionSupport.targetVersion(4, 2, 0).withBackwardsCompatibility(4, 0, 0).withRevisionForwardCompatibility(true), <add> DatabaseVersionSupport.targetVersion(4, 3, 0).withBackwardsCompatibility(4, 0, 0).withRevisionForwardCompatibility(true), <ide> DatabaseVersionSupport.targetVersion(3, 3, 1).withBackwardsCompatibility(3, 0, 0).withRevisionForwardCompatibility(true) <ide> }; <ide>
Java
mpl-2.0
2d4d3159861d658cbc00dda1a5f64d4cee9d0aaa
0
PawelGutkowski/openmrs-module-webservices.rest,PawelGutkowski/openmrs-module-webservices.rest,PawelGutkowski/openmrs-module-webservices.rest
/** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.module.webservices.rest.web.v1_0.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.openmrs.api.APIAuthenticationException; import org.openmrs.api.context.Context; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.module.webservices.rest.SimpleObject; import org.openmrs.module.webservices.rest.web.RestConstants; import org.openmrs.module.webservices.rest.web.RestUtil; import org.openmrs.module.webservices.validation.ValidationException; import org.springframework.stereotype.Controller; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; /** * Resource controllers should extend this base class to have standard exception handling done * automatically. (This is necessary to send error messages as HTTP statuses rather than just as * html content, as the core web application does.) */ @Controller @RequestMapping(value = "/rest/**") public class BaseRestController { private final int DEFAULT_ERROR_CODE = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; private static final String DISABLE_WWW_AUTH_HEADER_NAME = "Disable-WWW-Authenticate"; private final String DEFAULT_ERROR_DETAIL = ""; private final Log log = LogFactory.getLog(getClass()); /** * @should return unauthorized if not logged in * @should return forbidden if logged in */ @ExceptionHandler(APIAuthenticationException.class) @ResponseBody public SimpleObject apiAuthenticationExceptionHandler(Exception ex, HttpServletRequest request, HttpServletResponse response) throws Exception { int errorCode; String errorDetail; if (Context.isAuthenticated()) { // user is logged in but doesn't have the relevant privilege -> 403 FORBIDDEN errorCode = HttpServletResponse.SC_FORBIDDEN; errorDetail = "User is logged in but doesn't have the relevant privilege"; } else { // user is not logged in -> 401 UNAUTHORIZED errorCode = HttpServletResponse.SC_UNAUTHORIZED; errorDetail = "User is not logged in"; if (shouldAddWWWAuthHeader(request)) { response.addHeader("WWW-Authenticate", "Basic realm=\"OpenMRS at " + RestConstants.URI_PREFIX + "\""); } } response.setStatus(errorCode); return RestUtil.wrapErrorResponse(ex, errorDetail); } @ExceptionHandler(ValidationException.class) @ResponseBody public SimpleObject validationExceptionHandler(ValidationException validationException, HttpServletRequest request, HttpServletResponse response) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return RestUtil.wrapValidationErrorResponse(validationException); } @ExceptionHandler(Exception.class) @ResponseBody public SimpleObject handleException(Exception ex, HttpServletRequest request, HttpServletResponse response) throws Exception { log.error(ex.getMessage(), ex); int errorCode = DEFAULT_ERROR_CODE; String errorDetail = DEFAULT_ERROR_DETAIL; ResponseStatus ann = ex.getClass().getAnnotation(ResponseStatus.class); if (ann != null) { errorCode = ann.value().value(); if (StringUtils.isNotEmpty(ann.reason())) { errorDetail = ann.reason(); } } else if (RestUtil.hasCause(ex, APIAuthenticationException.class)) { return apiAuthenticationExceptionHandler(ex, request, response); } else if (ex.getClass() == HttpRequestMethodNotSupportedException.class) { errorCode = HttpServletResponse.SC_METHOD_NOT_ALLOWED; } response.setStatus(errorCode); return RestUtil.wrapErrorResponse(ex, errorDetail); } private boolean shouldAddWWWAuthHeader(HttpServletRequest request) { return request.getHeader(DISABLE_WWW_AUTH_HEADER_NAME) == null || !request.getHeader(DISABLE_WWW_AUTH_HEADER_NAME).equals("true"); } /** * It should be overridden if you want to expose resources under a different URL than /rest/v1. * * @return the namespace */ public String getNamespace() { return RestConstants.VERSION_1; } public String buildResourceName(String resource) { String namespace = getNamespace(); if (StringUtils.isBlank(namespace)) { return resource; } else { if (namespace.startsWith("/")) { namespace = namespace.substring(1); } if (!namespace.endsWith("/")) { namespace += "/"; } return namespace + resource; } } }
omod-common/src/main/java/org/openmrs/module/webservices/rest/web/v1_0/controller/BaseRestController.java
/** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.module.webservices.rest.web.v1_0.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.openmrs.api.APIAuthenticationException; import org.openmrs.api.context.Context; import org.openmrs.module.webservices.rest.SimpleObject; import org.openmrs.module.webservices.rest.web.RestConstants; import org.openmrs.module.webservices.rest.web.RestUtil; import org.openmrs.module.webservices.validation.ValidationException; import org.springframework.stereotype.Controller; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; /** * Resource controllers should extend this base class to have standard exception handling done * automatically. (This is necessary to send error messages as HTTP statuses rather than just as * html content, as the core web application does.) */ @Controller @RequestMapping(value = "/rest/**") public class BaseRestController { private final int DEFAULT_ERROR_CODE = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; private static final String DISABLE_WWW_AUTH_HEADER_NAME = "Disable-WWW-Authenticate"; private final String DEFAULT_ERROR_DETAIL = ""; /** * @should return unauthorized if not logged in * @should return forbidden if logged in */ @ExceptionHandler(APIAuthenticationException.class) @ResponseBody public SimpleObject apiAuthenticationExceptionHandler(Exception ex, HttpServletRequest request, HttpServletResponse response) throws Exception { int errorCode; String errorDetail; if (Context.isAuthenticated()) { // user is logged in but doesn't have the relevant privilege -> 403 FORBIDDEN errorCode = HttpServletResponse.SC_FORBIDDEN; errorDetail = "User is logged in but doesn't have the relevant privilege"; } else { // user is not logged in -> 401 UNAUTHORIZED errorCode = HttpServletResponse.SC_UNAUTHORIZED; errorDetail = "User is not logged in"; if (shouldAddWWWAuthHeader(request)) { response.addHeader("WWW-Authenticate", "Basic realm=\"OpenMRS at " + RestConstants.URI_PREFIX + "\""); } } response.setStatus(errorCode); return RestUtil.wrapErrorResponse(ex, errorDetail); } @ExceptionHandler(ValidationException.class) @ResponseBody public SimpleObject validationExceptionHandler(ValidationException validationException, HttpServletRequest request, HttpServletResponse response) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return RestUtil.wrapValidationErrorResponse(validationException); } @ExceptionHandler(Exception.class) @ResponseBody public SimpleObject handleException(Exception ex, HttpServletRequest request, HttpServletResponse response) throws Exception { int errorCode = DEFAULT_ERROR_CODE; String errorDetail = DEFAULT_ERROR_DETAIL; ResponseStatus ann = ex.getClass().getAnnotation(ResponseStatus.class); if (ann != null) { errorCode = ann.value().value(); if (StringUtils.isNotEmpty(ann.reason())) { errorDetail = ann.reason(); } } else if (RestUtil.hasCause(ex, APIAuthenticationException.class)) { return apiAuthenticationExceptionHandler(ex, request, response); } else if (ex.getClass() == HttpRequestMethodNotSupportedException.class) { errorCode = HttpServletResponse.SC_METHOD_NOT_ALLOWED; } response.setStatus(errorCode); return RestUtil.wrapErrorResponse(ex, errorDetail); } private boolean shouldAddWWWAuthHeader(HttpServletRequest request) { return request.getHeader(DISABLE_WWW_AUTH_HEADER_NAME) == null || !request.getHeader(DISABLE_WWW_AUTH_HEADER_NAME).equals("true"); } /** * It should be overridden if you want to expose resources under a different URL than /rest/v1. * * @return the namespace */ public String getNamespace() { return RestConstants.VERSION_1; } public String buildResourceName(String resource) { String namespace = getNamespace(); if (StringUtils.isBlank(namespace)) { return resource; } else { if (namespace.startsWith("/")) { namespace = namespace.substring(1); } if (!namespace.endsWith("/")) { namespace += "/"; } return namespace + resource; } } }
[RESTTWS-484] : Logging error for un-handled exception only for handleException() method in BaseRestController.class
omod-common/src/main/java/org/openmrs/module/webservices/rest/web/v1_0/controller/BaseRestController.java
[RESTTWS-484] : Logging error for un-handled exception only for handleException() method in BaseRestController.class
<ide><path>mod-common/src/main/java/org/openmrs/module/webservices/rest/web/v1_0/controller/BaseRestController.java <ide> import org.apache.commons.lang.StringUtils; <ide> import org.openmrs.api.APIAuthenticationException; <ide> import org.openmrs.api.context.Context; <add>import org.apache.commons.logging.Log; <add>import org.apache.commons.logging.LogFactory; <ide> import org.openmrs.module.webservices.rest.SimpleObject; <ide> import org.openmrs.module.webservices.rest.web.RestConstants; <ide> import org.openmrs.module.webservices.rest.web.RestUtil; <ide> private static final String DISABLE_WWW_AUTH_HEADER_NAME = "Disable-WWW-Authenticate"; <ide> <ide> private final String DEFAULT_ERROR_DETAIL = ""; <add> <add> private final Log log = LogFactory.getLog(getClass()); <ide> <ide> /** <ide> * @should return unauthorized if not logged in <ide> @ResponseBody <ide> public SimpleObject handleException(Exception ex, HttpServletRequest request, HttpServletResponse response) <ide> throws Exception { <add> log.error(ex.getMessage(), ex); <ide> int errorCode = DEFAULT_ERROR_CODE; <ide> String errorDetail = DEFAULT_ERROR_DETAIL; <ide> ResponseStatus ann = ex.getClass().getAnnotation(ResponseStatus.class);
Java
bsd-3-clause
a617fd8e029f6ebbd1a331ce8aa8025b00f43c50
0
Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java
/* * Copyright 1997-2007 Unidata Program Center/University Corporation for * Atmospheric Research, P.O. Box 3000, Boulder, CO 80307, * [email protected]. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at * your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package ucar.nc2.iosp.nexrad2; import ucar.unidata.io.RandomAccessFile; import ucar.nc2.util.CancelTask; import ucar.nc2.util.DiskCache; import ucar.nc2.NetcdfFile; import java.io.*; import java.util.*; import ucar.unidata.io.bzip2.CBZip2InputStream; import ucar.unidata.io.bzip2.BZip2ReadException; /** * This class reads a NEXRAD level II data file. * It can handle NCDC archives (ARCHIVE2), as well as CRAFT/IDD compressed files (AR2V0001). * <p/> * Adapted with permission from the Java Iras software developed by David Priegnitz at NSSL.<p> * <p/> * Documentation on Archive Level II data format can be found at: * <a href="http://www.ncdc.noaa.gov/oa/radar/leveliidoc.html"> * http://www.ncdc.noaa.gov/oa/radar/leveliidoc.html</a> * * @author caron * @author David Priegnitz */ public class Level2VolumeScan { // data formats static public final String ARCHIVE2 = "ARCHIVE2"; static public final String AR2V0001 = "AR2V0001"; static public final String AR2V0003 = "AR2V0003"; static private org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(Level2VolumeScan.class); //////////////////////////////////////////////////////////////////////////////////// // Data file RandomAccessFile raf; private String dataFormat = null; // ARCHIVE2 or AR2V0001 private int title_julianDay; // days since 1/1/70 private int title_msecs; // milliseconds since midnight private String stationId; // 4 letter station assigned by ICAO private NexradStationDB.Station station; // from lookup table, may be null private Level2Record first, last; private int vcp = 0; // Volume coverage pattern private int max_radials = 0; private int min_radials = Integer.MAX_VALUE; private int max_radials_hr = 0; private int min_radials_hr = Integer.MAX_VALUE; private int dopplarResolution; private boolean hasDifferentDopplarResolutions; private boolean hasHighResolutionData; private boolean hasHighResolutionREF; private boolean hasHighResolutionVEL; private boolean hasHighResolutionSW; private boolean hasHighResolutionZDR; private boolean hasHighResolutionPHI; private boolean hasHighResolutionRHO; // List of List of Level2Record private List<List<Level2Record>> reflectivityGroups, dopplerGroups; //private ArrayList reflectivityGroups, dopplerGroups; private List<List<Level2Record>> reflectivityHighResGroups; private List<List<Level2Record>> velocityHighResGroups; private List<List<Level2Record>> spectrumHighResGroups; private ArrayList diffReflectHighResGroups; private ArrayList diffPhaseHighResGroups; private ArrayList coefficientHighResGroups; private boolean showMessages = false, showData = false, debugScans = false, debugGroups2 = false, debugRadials = false, debugStats = false; Level2VolumeScan(RandomAccessFile orgRaf, CancelTask cancelTask) throws IOException { this.raf = orgRaf; if (log.isDebugEnabled()) log.debug("Level2VolumeScan on " + raf.getLocation()); raf.seek(0); raf.order(RandomAccessFile.BIG_ENDIAN); // volume scan header dataFormat = raf.readString(8); raf.skipBytes(1); String volumeNo = raf.readString(3); title_julianDay = raf.readInt(); // since 1/1/70 title_msecs = raf.readInt(); stationId = raf.readString(4).trim(); // only in AR2V0001 if (log.isDebugEnabled()) log.debug(" dataFormat= " + dataFormat + " stationId= " + stationId); if (stationId.length() == 0) { // try to get it from the filename LOOK stationId = null; } // try to find the station if (stationId != null) { if( !stationId.startsWith("K") && stationId.length()==4) { String _stationId = "K" + stationId; station = NexradStationDB.get(_stationId); } else station = NexradStationDB.get(stationId); } //see if we have to uncompress if (dataFormat.equals(AR2V0001) || dataFormat.equals(AR2V0003)) { raf.skipBytes(4); String BZ = raf.readString(2); if (BZ.equals("BZ")) { RandomAccessFile uraf; File uncompressedFile = DiskCache.getFileStandardPolicy(raf.getLocation() + ".uncompress"); if (uncompressedFile.exists()) { uraf = new ucar.unidata.io.RandomAccessFile(uncompressedFile.getPath(), "r"); } else { // nope, gotta uncompress it uraf = uncompress(raf, uncompressedFile.getPath()); uraf.flush(); if (log.isDebugEnabled()) log.debug("flushed uncompressed file= " + uncompressedFile.getPath()); } // switch to uncompressed file raf.close(); raf = uraf; raf.order(RandomAccessFile.BIG_ENDIAN); } raf.seek(Level2Record.FILE_HEADER_SIZE); } List<Level2Record> reflectivity = new ArrayList<Level2Record>(); List<Level2Record> doppler = new ArrayList<Level2Record>(); List<Level2Record> highReflectivity = new ArrayList<Level2Record>(); List<Level2Record> highVelocity = new ArrayList<Level2Record>(); List<Level2Record> highSpectrum = new ArrayList<Level2Record>(); List<Level2Record> highDiffReflectivity = new ArrayList<Level2Record>(); List<Level2Record> highDiffPhase = new ArrayList<Level2Record>(); List<Level2Record> highCorreCoefficient = new ArrayList<Level2Record>(); long message_offset31 = 0; int recno = 0; while (true) { Level2Record r = Level2Record.factory(raf, recno++, message_offset31); if (r == null) break; if (showData) r.dump2(System.out); // skip non-data messages if (r.message_type == 31) { message_offset31 = message_offset31 + (r.message_size*2 + 12 - 2432); } if (r.message_type != 1 && r.message_type != 31) { if (showMessages) r.dumpMessage(System.out); continue; } // if (showData) r.dump2(System.out); /* skip bad if (!r.checkOk()) { r.dump(System.out); continue; } */ // some global params if (vcp == 0) vcp = r.vcp; if (first == null) first = r; last = r; if (!r.checkOk()) { continue; } if (r.hasReflectData) reflectivity.add(r); if (r.hasDopplerData) doppler.add(r); if(r.message_type == 31) { if (r.hasHighResREFData) highReflectivity.add(r); if (r.hasHighResVELData) highVelocity.add(r); if (r.hasHighResSWData) highSpectrum.add(r); if (r.hasHighResZDRData) highDiffReflectivity.add(r); if (r.hasHighResPHIData) highDiffPhase.add(r); if (r.hasHighResRHOData) highCorreCoefficient.add(r); } if ((cancelTask != null) && cancelTask.isCancel()) return; } if (debugRadials) System.out.println(" reflect ok= " + reflectivity.size() + " doppler ok= " + doppler.size()); if(highReflectivity.size() == 0) { reflectivityGroups = sortScans("reflect", reflectivity, 600); dopplerGroups = sortScans("doppler", doppler, 600); } if(highReflectivity.size() > 0) reflectivityHighResGroups = sortScans("reflect_HR", highReflectivity, 720); if(highVelocity.size() > 0) velocityHighResGroups = sortScans("velocity_HR", highVelocity, 720); if(highSpectrum.size() > 0) spectrumHighResGroups = sortScans("spectrum_HR", highSpectrum, 720); if(highDiffReflectivity.size() > 0) diffReflectHighResGroups = sortScans("diffReflect_HR", highDiffReflectivity, 720); if(highDiffPhase.size() > 0) diffPhaseHighResGroups = sortScans("diffPhase_HR", highDiffPhase, 720); if(highCorreCoefficient.size() > 0) coefficientHighResGroups = sortScans("coefficient_HR", highCorreCoefficient, 720); } private ArrayList sortScans(String name, List<Level2Record> scans, int siz) { // now group by elevation_num Map<Short,List<Level2Record>> groupHash = new HashMap<Short,List<Level2Record>>(siz); for (Level2Record record : scans) { List<Level2Record> group = groupHash.get(record.elevation_num); if (null == group) { group = new ArrayList<Level2Record>(); groupHash.put(record.elevation_num, group); } group.add(record); } // sort the groups by elevation_num ArrayList groups = new ArrayList(groupHash.values()); Collections.sort(groups, new GroupComparator()); // use the maximum radials for (int i = 0; i < groups.size(); i++) { ArrayList group = (ArrayList) groups.get(i); int size = group.size(); testScan(name, group); if(size < 600) { max_radials = Math.max(max_radials, group.size()); min_radials = Math.min(min_radials, group.size()); } else { max_radials_hr = Math.max(max_radials_hr, group.size()); min_radials_hr = Math.min(min_radials_hr, group.size()); } } if (debugRadials) { System.out.println(name + " min_radials= " + min_radials + " max_radials= " + max_radials); for (int i = 0; i < groups.size(); i++) { ArrayList group = (ArrayList) groups.get(i); Level2Record lastr = (Level2Record) group.get(0); for (int j = 1; j < group.size(); j++) { Level2Record r = (Level2Record) group.get(j); if (r.data_msecs < lastr.data_msecs) System.out.println(" out of order " + j); lastr = r; } } } testVariable(name, groups); if (debugScans) System.out.println("-----------------------------"); return groups; } public int getMaxRadials(int r) { if(r == 0) return max_radials; else if (r== 1) return max_radials_hr; else return 0; } public int getMinRadials(int r) { if(r == 0) return min_radials; else if (r== 1) return min_radials_hr; else return 0; } public int getDopplarResolution() { return dopplarResolution; } public boolean hasDifferentDopplarResolutions() { return hasDifferentDopplarResolutions; } public boolean hasHighResolutions(int dt) { if(dt == 0) return hasHighResolutionData; else if(dt == 1) return hasHighResolutionREF; else if(dt == 2) return hasHighResolutionVEL; else if(dt == 3) return hasHighResolutionSW; else if(dt == 4) return hasHighResolutionZDR; else if(dt == 5) return hasHighResolutionPHI; else if(dt == 6) return hasHighResolutionRHO; else return false; } // do we have same characteristics for all records in a scan? private int MAX_RADIAL = 721; private int[] radial = new int[MAX_RADIAL]; private boolean testScan(String name, ArrayList group) { int datatype = name.equals("reflect") ? Level2Record.REFLECTIVITY : Level2Record.VELOCITY_HI; Level2Record first = (Level2Record) group.get(0); int n = group.size(); if (debugScans) { boolean hasBoth = first.hasDopplerData && first.hasReflectData; System.out.println(name + " " + first + " has " + n + " radials resolution= " + first.resolution + " has both = " + hasBoth); } boolean ok = true; double sum = 0.0; double sum2 = 0.0; for (int i = 0; i < MAX_RADIAL; i++) radial[i] = 0; for (int i = 0; i < group.size(); i++) { Level2Record r = (Level2Record) group.get(i); /* this appears to be common - seems to be ok, we put missing values in if (r.getGateCount(datatype) != first.getGateCount(datatype)) { log.error(raf.getLocation()+" different number of gates ("+r.getGateCount(datatype)+ "!="+first.getGateCount(datatype)+") in record "+name+ " "+r); ok = false; } */ if (r.getGateSize(datatype) != first.getGateSize(datatype)) { log.warn(raf.getLocation() + " different gate size (" + r.getGateSize(datatype) + ") in record " + name + " " + r); ok = false; } if (r.getGateStart(datatype) != first.getGateStart(datatype)) { log.warn(raf.getLocation() + " different gate start (" + r.getGateStart(datatype) + ") in record " + name + " " + r); ok = false; } if (r.resolution != first.resolution) { log.warn(raf.getLocation() + " different resolution (" + r.resolution + ") in record " + name + " " + r); ok = false; } if ((r.radial_num < 0) || (r.radial_num >= MAX_RADIAL)) { log.info(raf.getLocation() + " radial out of range= " + r.radial_num + " in record " + name + " " + r); continue; } if (radial[r.radial_num] > 0) { log.warn(raf.getLocation() + " duplicate radial = " + r.radial_num + " in record " + name + " " + r); ok = false; } radial[r.radial_num] = r.recno + 1; sum += r.getElevation(); sum2 += r.getElevation() * r.getElevation(); // System.out.println(" elev="+r.getElevation()+" azi="+r.getAzimuth()); } for (int i = 1; i < radial.length; i++) { if (0 == radial[i]) { if (n != (i - 1)) { log.warn(" missing radial(s)"); ok = false; } break; } } double avg = sum / n; double sd = Math.sqrt((n * sum2 - sum * sum) / (n * (n - 1))); // System.out.println(" avg elev="+avg+" std.dev="+sd); return ok; } // do we have same characteristics for all groups in a variable? private boolean testVariable(String name, List scans) { int datatype = name.equals("reflect") ? Level2Record.REFLECTIVITY : Level2Record.VELOCITY_HI; if (scans.size() == 0) { log.warn(" No data for = " + name); return false; } boolean ok = true; List firstScan = (List) scans.get(0); Level2Record firstRecord = (Level2Record) firstScan.get(0); dopplarResolution = firstRecord.resolution; if (debugGroups2) System.out.println("Group " + Level2Record.getDatatypeName(datatype) + " ngates = " + firstRecord.getGateCount(datatype) + " start = " + firstRecord.getGateStart(datatype) + " size = " + firstRecord.getGateSize(datatype)); for (int i = 1; i < scans.size(); i++) { List scan = (List) scans.get(i); Level2Record record = (Level2Record) scan.get(0); if ((datatype == Level2Record.VELOCITY_HI) && (record.resolution != firstRecord.resolution)) { // do all velocity resolutions match ?? log.warn(name + " scan " + i + " diff resolutions = " + record.resolution + ", " + firstRecord.resolution + " elev= " + record.elevation_num + " " + record.getElevation()); ok = false; hasDifferentDopplarResolutions = true; } if (record.getGateSize(datatype) != firstRecord.getGateSize(datatype)) { log.warn(name + " scan " + i + " diff gates size = " + record.getGateSize(datatype) + " " + firstRecord.getGateSize(datatype) + " elev= " + record.elevation_num + " " + record.getElevation()); ok = false; } else if (debugGroups2) System.out.println(" ok gates size elev= " + record.elevation_num + " " + record.getElevation()); if (record.getGateStart(datatype) != firstRecord.getGateStart(datatype)) { log.warn(name + " scan " + i + " diff gates start = " + record.getGateStart(datatype) + " " + firstRecord.getGateStart(datatype) + " elev= " + record.elevation_num + " " + record.getElevation()); ok = false; } else if (debugGroups2) System.out.println(" ok gates start elev= " + record.elevation_num + " " + record.getElevation()); if (record.message_type == 31 ) { hasHighResolutionData = true; //each data type if(record.hasHighResREFData) hasHighResolutionREF = true; if(record.hasHighResVELData) hasHighResolutionVEL = true; if(record.hasHighResSWData) hasHighResolutionSW = true; if(record.hasHighResZDRData) hasHighResolutionZDR = true; if(record.hasHighResPHIData) hasHighResolutionPHI = true; if(record.hasHighResRHOData) hasHighResolutionRHO = true; } } return ok; } /** * Get Reflectivity Groups * Groups are all the records for a variable and elevation_num; * * @return List of type List of type Level2Record */ public List getReflectivityGroups() { return reflectivityGroups; } /** * Get Velocity Groups * Groups are all the records for a variable and elevation_num; * * @return List of type List of type Level2Record */ public List getVelocityGroups() { return dopplerGroups; } public List getHighResVelocityGroups() { return velocityHighResGroups; } public List getHighResReflectivityGroups() { return reflectivityHighResGroups; } public List getHighResSpectrumGroups() { return spectrumHighResGroups; } private class GroupComparator implements Comparator<List<Level2Record>> { public int compare(List<Level2Record> group1, List<Level2Record> group2) { Level2Record record1 = group1.get(0); Level2Record record2 = group2.get(0); //if (record1.elevation_num != record2.elevation_num) return record1.elevation_num - record2.elevation_num; //return record1.cut - record2.cut; } } /** * Get data format (ARCHIVE2, AR2V0001) for this file. * @return data format (ARCHIVE2, AR2V0001) for this file. */ public String getDataFormat() { return dataFormat; } /** * Get the starting Julian day for this volume * * @return days since 1/1/70. */ public int getTitleJulianDays() { return title_julianDay; } /** * Get the starting time in seconds since midnight. * * @return Generation time of data in milliseconds of day past midnight (UTC). */ public int getTitleMsecs() { return title_msecs; } /** * Get the Volume Coverage Pattern number for this data. * * @return VCP * @see Level2Record#getVolumeCoveragePatternName */ public int getVCP() { return vcp; } /** * Get the 4-char station ID for this data * * @return station ID (may be null) */ public String getStationId() { return stationId; } public String getStationName() { return station == null ? "unknown" : station.name; } public double getStationLatitude() { return station == null ? 0.0 : station.lat; } public double getStationLongitude() { return station == null ? 0.0 : station.lon; } public double getStationElevation() { return station == null ? 0.0 : station.elev; } public Date getStartDate() { return first.getDate(); } public Date getEndDate() { return last.getDate(); } /** * Write equivilent uncompressed version of the file. * * @param raf2 file to uncompress * @param ufilename write to this file * @return raf of uncompressed file * @throws IOException on read error */ private RandomAccessFile uncompress(RandomAccessFile raf2, String ufilename) throws IOException { raf2.seek(0); byte[] header = new byte[Level2Record.FILE_HEADER_SIZE]; raf2.read(header); RandomAccessFile dout2 = new RandomAccessFile(ufilename, "rw"); dout2.write(header); boolean eof = false; int numCompBytes; byte[] ubuff = new byte[40000]; byte[] obuff = new byte[40000]; try { CBZip2InputStream cbzip2 = new CBZip2InputStream(); while (!eof) { try { numCompBytes = raf2.readInt(); if (numCompBytes == -1) { if (log.isDebugEnabled()) log.debug(" done: numCompBytes=-1 "); break; } } catch (EOFException ee) { log.warn(" got EOFException "); break; // assume this is ok } if (log.isDebugEnabled()) { log.debug("reading compressed bytes " + numCompBytes + " input starts at " + raf2.getFilePointer() + "; output starts at " + dout2.getFilePointer()); } /* * For some stupid reason, the last block seems to * have the number of bytes negated. So, we just * assume that any negative number (other than -1) * is the last block and go on our merry little way. */ if (numCompBytes < 0) { if (log.isDebugEnabled()) log.debug("last block?" + numCompBytes); numCompBytes = -numCompBytes; eof = true; } byte[] buf = new byte[numCompBytes]; raf2.readFully(buf); ByteArrayInputStream bis = new ByteArrayInputStream(buf, 2, numCompBytes - 2); //CBZip2InputStream cbzip2 = new CBZip2InputStream(bis); cbzip2.setStream(bis); int total = 0; int nread; /* while ((nread = cbzip2.read(ubuff)) != -1) { dout2.write(ubuff, 0, nread); total += nread; } */ try { while ((nread = cbzip2.read(ubuff)) != -1) { if (total + nread > obuff.length) { byte[] temp = obuff; obuff = new byte[temp.length * 2]; System.arraycopy(temp, 0, obuff, 0, temp.length); } System.arraycopy(ubuff, 0, obuff, total, nread); total += nread; } if (obuff.length >= 0) dout2.write(obuff, 0, total); } catch (BZip2ReadException ioe) { log.warn("Nexrad2IOSP.uncompress ", ioe); } float nrecords = (float) (total / 2432.0); if (log.isDebugEnabled()) log.debug(" unpacked " + total + " num bytes " + nrecords + " records; ouput ends at " + dout2.getFilePointer()); } } catch (EOFException e) { e.printStackTrace(); } dout2.flush(); return dout2; } // debugging static void bdiff(String filename) throws IOException { InputStream in1 = new FileInputStream(filename + ".tmp"); InputStream in2 = new FileInputStream(filename + ".tmp2"); int count = 0; int bad = 0; while (true) { int b1 = in1.read(); int b2 = in2.read(); if (b1 < 0) break; if (b2 < 0) break; if (b1 != b2) { System.out.println(count + " in1=" + b1 + " in2= " + b2); bad++; if (bad > 130) break; } count++; } System.out.println("total read = " + count); } // check if compressed file seems ok static public long testValid(String ufilename) throws IOException { boolean lookForHeader = false; // gotta make it RandomAccessFile raf = new RandomAccessFile(ufilename, "r"); raf.order(RandomAccessFile.BIG_ENDIAN); raf.seek(0); byte[] b = new byte[8]; raf.read(b); String test = new String(b); if (test.equals(Level2VolumeScan.ARCHIVE2) || test.equals(Level2VolumeScan.AR2V0001)) { System.out.println("--Good header= " + test); raf.seek(24); } else { System.out.println("--No header "); lookForHeader = true; raf.seek(0); } boolean eof = false; int numCompBytes; try { while (!eof) { if (lookForHeader) { raf.read(b); test = new String(b); if (test.equals(Level2VolumeScan.ARCHIVE2) || test.equals(Level2VolumeScan.AR2V0001)) { System.out.println(" found header= " + test); raf.skipBytes(16); lookForHeader = false; } else { raf.skipBytes(-8); } } try { numCompBytes = raf.readInt(); if (numCompBytes == -1) { System.out.println("\n--done: numCompBytes=-1 "); break; } } catch (EOFException ee) { System.out.println("\n--got EOFException "); break; // assume this is ok } System.out.print(" " + numCompBytes + ","); if (numCompBytes < 0) { System.out.println("\n--last block " + numCompBytes); numCompBytes = -numCompBytes; if (!lookForHeader) eof = true; } raf.skipBytes(numCompBytes); } } catch (EOFException e) { e.printStackTrace(); } return raf.getFilePointer(); } /** * test */ public static void main2(String[] args) throws IOException { File testDir = new File("C:/data/bad/radar2/"); File[] files = testDir.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; if (!file.getPath().endsWith(".ar2v")) continue; System.out.println(file.getPath() + " " + file.length()); long pos = testValid(file.getPath()); if (pos == file.length()) { System.out.println("OK"); try { NetcdfFile.open(file.getPath()); } catch (Throwable t) { System.out.println("ERROR= " + t); } } else System.out.println("NOT pos=" + pos); System.out.println(); } } public static void main(String args[]) throws IOException { NexradStationDB.init(); RandomAccessFile raf = new RandomAccessFile("/upc/share/testdata/radar/nexrad/level2/Level2_KFTG_20060818_1814.ar2v.uncompress.missingradials", "r"); // RandomAccessFile raf = new RandomAccessFile("R:/testdata/radar/nexrad/level2/problem/KCCX_20060627_1701", "r"); new Level2VolumeScan(raf, null); } }
cdm/src/main/java/ucar/nc2/iosp/nexrad2/Level2VolumeScan.java
/* * Copyright 1997-2007 Unidata Program Center/University Corporation for * Atmospheric Research, P.O. Box 3000, Boulder, CO 80307, * [email protected]. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at * your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package ucar.nc2.iosp.nexrad2; import ucar.unidata.io.RandomAccessFile; import ucar.nc2.util.CancelTask; import ucar.nc2.util.DiskCache; import ucar.nc2.NetcdfFile; import java.io.*; import java.util.*; import ucar.unidata.io.bzip2.CBZip2InputStream; import ucar.unidata.io.bzip2.BZip2ReadException; /** * This class reads a NEXRAD level II data file. * It can handle NCDC archives (ARCHIVE2), as well as CRAFT/IDD compressed files (AR2V0001). * <p/> * Adapted with permission from the Java Iras software developed by David Priegnitz at NSSL.<p> * <p/> * Documentation on Archive Level II data format can be found at: * <a href="http://www.ncdc.noaa.gov/oa/radar/leveliidoc.html"> * http://www.ncdc.noaa.gov/oa/radar/leveliidoc.html</a> * * @author caron * @author David Priegnitz */ public class Level2VolumeScan { // data formats static public final String ARCHIVE2 = "ARCHIVE2"; static public final String AR2V0001 = "AR2V0001"; static private org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(Level2VolumeScan.class); //////////////////////////////////////////////////////////////////////////////////// // Data file RandomAccessFile raf; private String dataFormat = null; // ARCHIVE2 or AR2V0001 private int title_julianDay; // days since 1/1/70 private int title_msecs; // milliseconds since midnight private String stationId; // 4 letter station assigned by ICAO private NexradStationDB.Station station; // from lookup table, may be null private Level2Record first, last; private int vcp = 0; // Volume coverage pattern private int max_radials = 0; private int min_radials = Integer.MAX_VALUE; private int max_radials_hr = 0; private int min_radials_hr = Integer.MAX_VALUE; private int dopplarResolution; private boolean hasDifferentDopplarResolutions; private boolean hasHighResolutionData; private boolean hasHighResolutionREF; private boolean hasHighResolutionVEL; private boolean hasHighResolutionSW; private boolean hasHighResolutionZDR; private boolean hasHighResolutionPHI; private boolean hasHighResolutionRHO; // List of List of Level2Record private List<List<Level2Record>> reflectivityGroups, dopplerGroups; //private ArrayList reflectivityGroups, dopplerGroups; private List<List<Level2Record>> reflectivityHighResGroups; private List<List<Level2Record>> velocityHighResGroups; private List<List<Level2Record>> spectrumHighResGroups; private ArrayList diffReflectHighResGroups; private ArrayList diffPhaseHighResGroups; private ArrayList coefficientHighResGroups; private boolean showMessages = false, showData = false, debugScans = false, debugGroups2 = false, debugRadials = false, debugStats = false; Level2VolumeScan(RandomAccessFile orgRaf, CancelTask cancelTask) throws IOException { this.raf = orgRaf; if (log.isDebugEnabled()) log.debug("Level2VolumeScan on " + raf.getLocation()); raf.seek(0); raf.order(RandomAccessFile.BIG_ENDIAN); // volume scan header dataFormat = raf.readString(8); raf.skipBytes(1); String volumeNo = raf.readString(3); title_julianDay = raf.readInt(); // since 1/1/70 title_msecs = raf.readInt(); stationId = raf.readString(4).trim(); // only in AR2V0001 if (log.isDebugEnabled()) log.debug(" dataFormat= " + dataFormat + " stationId= " + stationId); if (stationId.length() == 0) { // try to get it from the filename LOOK stationId = null; } // try to find the station if (stationId != null) { station = NexradStationDB.get(stationId); } //see if we have to uncompress if (dataFormat.equals(AR2V0001)) { raf.skipBytes(4); String BZ = raf.readString(2); if (BZ.equals("BZ")) { RandomAccessFile uraf; File uncompressedFile = DiskCache.getFileStandardPolicy(raf.getLocation() + ".uncompress"); if (uncompressedFile.exists()) { uraf = new ucar.unidata.io.RandomAccessFile(uncompressedFile.getPath(), "r"); } else { // nope, gotta uncompress it uraf = uncompress(raf, uncompressedFile.getPath()); uraf.flush(); if (log.isDebugEnabled()) log.debug("flushed uncompressed file= " + uncompressedFile.getPath()); } // switch to uncompressed file raf.close(); raf = uraf; raf.order(RandomAccessFile.BIG_ENDIAN); } raf.seek(Level2Record.FILE_HEADER_SIZE); } List<Level2Record> reflectivity = new ArrayList<Level2Record>(); List<Level2Record> doppler = new ArrayList<Level2Record>(); List<Level2Record> highReflectivity = new ArrayList<Level2Record>(); List<Level2Record> highVelocity = new ArrayList<Level2Record>(); List<Level2Record> highSpectrum = new ArrayList<Level2Record>(); List<Level2Record> highDiffReflectivity = new ArrayList<Level2Record>(); List<Level2Record> highDiffPhase = new ArrayList<Level2Record>(); List<Level2Record> highCorreCoefficient = new ArrayList<Level2Record>(); long message_offset31 = 0; int recno = 0; while (true) { Level2Record r = Level2Record.factory(raf, recno++, message_offset31); if (r == null) break; if (showData) r.dump2(System.out); // skip non-data messages if (r.message_type == 31) { message_offset31 = message_offset31 + (r.message_size*2 + 12 - 2432); } if (r.message_type != 1 && r.message_type != 31) { if (showMessages) r.dumpMessage(System.out); continue; } // if (showData) r.dump2(System.out); /* skip bad if (!r.checkOk()) { r.dump(System.out); continue; } */ // some global params if (vcp == 0) vcp = r.vcp; if (first == null) first = r; last = r; if (!r.checkOk()) { continue; } if (r.hasReflectData) reflectivity.add(r); if (r.hasDopplerData) doppler.add(r); if(r.message_type == 31) { if (r.hasHighResREFData) highReflectivity.add(r); if (r.hasHighResVELData) highVelocity.add(r); if (r.hasHighResSWData) highSpectrum.add(r); if (r.hasHighResZDRData) highDiffReflectivity.add(r); if (r.hasHighResPHIData) highDiffPhase.add(r); if (r.hasHighResRHOData) highCorreCoefficient.add(r); } if ((cancelTask != null) && cancelTask.isCancel()) return; } if (debugRadials) System.out.println(" reflect ok= " + reflectivity.size() + " doppler ok= " + doppler.size()); reflectivityGroups = sortScans("reflect", reflectivity, 600); dopplerGroups = sortScans("doppler", doppler, 600); if(highReflectivity.size() > 0) reflectivityHighResGroups = sortScans("reflect_HR", highReflectivity, 720); if(highVelocity.size() > 0) velocityHighResGroups = sortScans("velocity_HR", highVelocity, 720); if(highSpectrum.size() > 0) spectrumHighResGroups = sortScans("spectrum_HR", highSpectrum, 720); if(highDiffReflectivity.size() > 0) diffReflectHighResGroups = sortScans("diffReflect_HR", highDiffReflectivity, 720); if(highDiffPhase.size() > 0) diffPhaseHighResGroups = sortScans("diffPhase_HR", highDiffPhase, 720); if(highCorreCoefficient.size() > 0) coefficientHighResGroups = sortScans("coefficient_HR", highCorreCoefficient, 720); } private ArrayList sortScans(String name, List<Level2Record> scans, int siz) { // now group by elevation_num Map<Short,List<Level2Record>> groupHash = new HashMap<Short,List<Level2Record>>(siz); for (Level2Record record : scans) { List<Level2Record> group = groupHash.get(record.elevation_num); if (null == group) { group = new ArrayList<Level2Record>(); groupHash.put(record.elevation_num, group); } group.add(record); } // sort the groups by elevation_num ArrayList groups = new ArrayList(groupHash.values()); Collections.sort(groups, new GroupComparator()); // use the maximum radials for (int i = 0; i < groups.size(); i++) { ArrayList group = (ArrayList) groups.get(i); int size = group.size(); testScan(name, group); if(size < 600) { max_radials = Math.max(max_radials, group.size()); min_radials = Math.min(min_radials, group.size()); } else { max_radials_hr = Math.max(max_radials_hr, group.size()); min_radials_hr = Math.min(min_radials_hr, group.size()); } } if (debugRadials) { System.out.println(name + " min_radials= " + min_radials + " max_radials= " + max_radials); for (int i = 0; i < groups.size(); i++) { ArrayList group = (ArrayList) groups.get(i); Level2Record lastr = (Level2Record) group.get(0); for (int j = 1; j < group.size(); j++) { Level2Record r = (Level2Record) group.get(j); if (r.data_msecs < lastr.data_msecs) System.out.println(" out of order " + j); lastr = r; } } } testVariable(name, groups); if (debugScans) System.out.println("-----------------------------"); return groups; } public int getMaxRadials(int r) { if(r == 0) return max_radials; else if (r== 1) return max_radials_hr; else return 0; } public int getMinRadials(int r) { if(r == 0) return min_radials; else if (r== 1) return min_radials_hr; else return 0; } public int getDopplarResolution() { return dopplarResolution; } public boolean hasDifferentDopplarResolutions() { return hasDifferentDopplarResolutions; } public boolean hasHighResolutions(int dt) { if(dt == 0) return hasHighResolutionData; else if(dt == 1) return hasHighResolutionREF; else if(dt == 2) return hasHighResolutionVEL; else if(dt == 3) return hasHighResolutionSW; else if(dt == 4) return hasHighResolutionZDR; else if(dt == 5) return hasHighResolutionPHI; else if(dt == 6) return hasHighResolutionRHO; else return false; } // do we have same characteristics for all records in a scan? private int MAX_RADIAL = 720; private int[] radial = new int[MAX_RADIAL]; private boolean testScan(String name, ArrayList group) { int datatype = name.equals("reflect") ? Level2Record.REFLECTIVITY : Level2Record.VELOCITY_HI; Level2Record first = (Level2Record) group.get(0); int n = group.size(); if (debugScans) { boolean hasBoth = first.hasDopplerData && first.hasReflectData; System.out.println(name + " " + first + " has " + n + " radials resolution= " + first.resolution + " has both = " + hasBoth); } boolean ok = true; double sum = 0.0; double sum2 = 0.0; for (int i = 0; i < MAX_RADIAL; i++) radial[i] = 0; for (int i = 0; i < group.size(); i++) { Level2Record r = (Level2Record) group.get(i); /* this appears to be common - seems to be ok, we put missing values in if (r.getGateCount(datatype) != first.getGateCount(datatype)) { log.error(raf.getLocation()+" different number of gates ("+r.getGateCount(datatype)+ "!="+first.getGateCount(datatype)+") in record "+name+ " "+r); ok = false; } */ if (r.getGateSize(datatype) != first.getGateSize(datatype)) { log.warn(raf.getLocation() + " different gate size (" + r.getGateSize(datatype) + ") in record " + name + " " + r); ok = false; } if (r.getGateStart(datatype) != first.getGateStart(datatype)) { log.warn(raf.getLocation() + " different gate start (" + r.getGateStart(datatype) + ") in record " + name + " " + r); ok = false; } if (r.resolution != first.resolution) { log.warn(raf.getLocation() + " different resolution (" + r.resolution + ") in record " + name + " " + r); ok = false; } if ((r.radial_num < 0) || (r.radial_num >= MAX_RADIAL)) { log.info(raf.getLocation() + " radial out of range= " + r.radial_num + " in record " + name + " " + r); continue; } if (radial[r.radial_num] > 0) { log.warn(raf.getLocation() + " duplicate radial = " + r.radial_num + " in record " + name + " " + r); ok = false; } radial[r.radial_num] = r.recno + 1; sum += r.getElevation(); sum2 += r.getElevation() * r.getElevation(); // System.out.println(" elev="+r.getElevation()+" azi="+r.getAzimuth()); } for (int i = 1; i < radial.length; i++) { if (0 == radial[i]) { if (n != (i - 1)) { log.warn(" missing radial(s)"); ok = false; } break; } } double avg = sum / n; double sd = Math.sqrt((n * sum2 - sum * sum) / (n * (n - 1))); // System.out.println(" avg elev="+avg+" std.dev="+sd); return ok; } // do we have same characteristics for all groups in a variable? private boolean testVariable(String name, List scans) { int datatype = name.equals("reflect") ? Level2Record.REFLECTIVITY : Level2Record.VELOCITY_HI; if (scans.size() == 0) { log.warn(" No data for = " + name); return false; } boolean ok = true; List firstScan = (List) scans.get(0); Level2Record firstRecord = (Level2Record) firstScan.get(0); dopplarResolution = firstRecord.resolution; if (debugGroups2) System.out.println("Group " + Level2Record.getDatatypeName(datatype) + " ngates = " + firstRecord.getGateCount(datatype) + " start = " + firstRecord.getGateStart(datatype) + " size = " + firstRecord.getGateSize(datatype)); for (int i = 1; i < scans.size(); i++) { List scan = (List) scans.get(i); Level2Record record = (Level2Record) scan.get(0); if ((datatype == Level2Record.VELOCITY_HI) && (record.resolution != firstRecord.resolution)) { // do all velocity resolutions match ?? log.warn(name + " scan " + i + " diff resolutions = " + record.resolution + ", " + firstRecord.resolution + " elev= " + record.elevation_num + " " + record.getElevation()); ok = false; hasDifferentDopplarResolutions = true; } if (record.getGateSize(datatype) != firstRecord.getGateSize(datatype)) { log.warn(name + " scan " + i + " diff gates size = " + record.getGateSize(datatype) + " " + firstRecord.getGateSize(datatype) + " elev= " + record.elevation_num + " " + record.getElevation()); ok = false; } else if (debugGroups2) System.out.println(" ok gates size elev= " + record.elevation_num + " " + record.getElevation()); if (record.getGateStart(datatype) != firstRecord.getGateStart(datatype)) { log.warn(name + " scan " + i + " diff gates start = " + record.getGateStart(datatype) + " " + firstRecord.getGateStart(datatype) + " elev= " + record.elevation_num + " " + record.getElevation()); ok = false; } else if (debugGroups2) System.out.println(" ok gates start elev= " + record.elevation_num + " " + record.getElevation()); if (record.message_type == 31 ) { hasHighResolutionData = true; //each data type if(record.hasHighResREFData) hasHighResolutionREF = true; if(record.hasHighResVELData) hasHighResolutionVEL = true; if(record.hasHighResSWData) hasHighResolutionSW = true; if(record.hasHighResZDRData) hasHighResolutionZDR = true; if(record.hasHighResPHIData) hasHighResolutionPHI = true; if(record.hasHighResRHOData) hasHighResolutionRHO = true; } } return ok; } /** * Get Reflectivity Groups * Groups are all the records for a variable and elevation_num; * * @return List of type List of type Level2Record */ public List getReflectivityGroups() { return reflectivityGroups; } /** * Get Velocity Groups * Groups are all the records for a variable and elevation_num; * * @return List of type List of type Level2Record */ public List getVelocityGroups() { return dopplerGroups; } public List getHighResVelocityGroups() { return velocityHighResGroups; } public List getHighResReflectivityGroups() { return reflectivityHighResGroups; } public List getHighResSpectrumGroups() { return spectrumHighResGroups; } private class GroupComparator implements Comparator<List<Level2Record>> { public int compare(List<Level2Record> group1, List<Level2Record> group2) { Level2Record record1 = group1.get(0); Level2Record record2 = group2.get(0); //if (record1.elevation_num != record2.elevation_num) return record1.elevation_num - record2.elevation_num; //return record1.cut - record2.cut; } } /** * Get data format (ARCHIVE2, AR2V0001) for this file. * @return data format (ARCHIVE2, AR2V0001) for this file. */ public String getDataFormat() { return dataFormat; } /** * Get the starting Julian day for this volume * * @return days since 1/1/70. */ public int getTitleJulianDays() { return title_julianDay; } /** * Get the starting time in seconds since midnight. * * @return Generation time of data in milliseconds of day past midnight (UTC). */ public int getTitleMsecs() { return title_msecs; } /** * Get the Volume Coverage Pattern number for this data. * * @return VCP * @see Level2Record#getVolumeCoveragePatternName */ public int getVCP() { return vcp; } /** * Get the 4-char station ID for this data * * @return station ID (may be null) */ public String getStationId() { return stationId; } public String getStationName() { return station == null ? "unknown" : station.name; } public double getStationLatitude() { return station == null ? 0.0 : station.lat; } public double getStationLongitude() { return station == null ? 0.0 : station.lon; } public double getStationElevation() { return station == null ? 0.0 : station.elev; } public Date getStartDate() { return first.getDate(); } public Date getEndDate() { return last.getDate(); } /** * Write equivilent uncompressed version of the file. * * @param raf2 file to uncompress * @param ufilename write to this file * @return raf of uncompressed file * @throws IOException on read error */ private RandomAccessFile uncompress(RandomAccessFile raf2, String ufilename) throws IOException { raf2.seek(0); byte[] header = new byte[Level2Record.FILE_HEADER_SIZE]; raf2.read(header); RandomAccessFile dout2 = new RandomAccessFile(ufilename, "rw"); dout2.write(header); boolean eof = false; int numCompBytes; byte[] ubuff = new byte[40000]; byte[] obuff = new byte[40000]; try { CBZip2InputStream cbzip2 = new CBZip2InputStream(); while (!eof) { try { numCompBytes = raf2.readInt(); if (numCompBytes == -1) { if (log.isDebugEnabled()) log.debug(" done: numCompBytes=-1 "); break; } } catch (EOFException ee) { log.warn(" got EOFException "); break; // assume this is ok } if (log.isDebugEnabled()) { log.debug("reading compressed bytes " + numCompBytes + " input starts at " + raf2.getFilePointer() + "; output starts at " + dout2.getFilePointer()); } /* * For some stupid reason, the last block seems to * have the number of bytes negated. So, we just * assume that any negative number (other than -1) * is the last block and go on our merry little way. */ if (numCompBytes < 0) { if (log.isDebugEnabled()) log.debug("last block?" + numCompBytes); numCompBytes = -numCompBytes; eof = true; } byte[] buf = new byte[numCompBytes]; raf2.readFully(buf); ByteArrayInputStream bis = new ByteArrayInputStream(buf, 2, numCompBytes - 2); //CBZip2InputStream cbzip2 = new CBZip2InputStream(bis); cbzip2.setStream(bis); int total = 0; int nread; /* while ((nread = cbzip2.read(ubuff)) != -1) { dout2.write(ubuff, 0, nread); total += nread; } */ try { while ((nread = cbzip2.read(ubuff)) != -1) { if (total + nread > obuff.length) { byte[] temp = obuff; obuff = new byte[temp.length * 2]; System.arraycopy(temp, 0, obuff, 0, temp.length); } System.arraycopy(ubuff, 0, obuff, total, nread); total += nread; } if (obuff.length >= 0) dout2.write(obuff, 0, total); } catch (BZip2ReadException ioe) { log.warn("Nexrad2IOSP.uncompress ", ioe); } float nrecords = (float) (total / 2432.0); if (log.isDebugEnabled()) log.debug(" unpacked " + total + " num bytes " + nrecords + " records; ouput ends at " + dout2.getFilePointer()); } } catch (EOFException e) { e.printStackTrace(); } dout2.flush(); return dout2; } // debugging static void bdiff(String filename) throws IOException { InputStream in1 = new FileInputStream(filename + ".tmp"); InputStream in2 = new FileInputStream(filename + ".tmp2"); int count = 0; int bad = 0; while (true) { int b1 = in1.read(); int b2 = in2.read(); if (b1 < 0) break; if (b2 < 0) break; if (b1 != b2) { System.out.println(count + " in1=" + b1 + " in2= " + b2); bad++; if (bad > 130) break; } count++; } System.out.println("total read = " + count); } // check if compressed file seems ok static public long testValid(String ufilename) throws IOException { boolean lookForHeader = false; // gotta make it RandomAccessFile raf = new RandomAccessFile(ufilename, "r"); raf.order(RandomAccessFile.BIG_ENDIAN); raf.seek(0); byte[] b = new byte[8]; raf.read(b); String test = new String(b); if (test.equals(Level2VolumeScan.ARCHIVE2) || test.equals(Level2VolumeScan.AR2V0001)) { System.out.println("--Good header= " + test); raf.seek(24); } else { System.out.println("--No header "); lookForHeader = true; raf.seek(0); } boolean eof = false; int numCompBytes; try { while (!eof) { if (lookForHeader) { raf.read(b); test = new String(b); if (test.equals(Level2VolumeScan.ARCHIVE2) || test.equals(Level2VolumeScan.AR2V0001)) { System.out.println(" found header= " + test); raf.skipBytes(16); lookForHeader = false; } else { raf.skipBytes(-8); } } try { numCompBytes = raf.readInt(); if (numCompBytes == -1) { System.out.println("\n--done: numCompBytes=-1 "); break; } } catch (EOFException ee) { System.out.println("\n--got EOFException "); break; // assume this is ok } System.out.print(" " + numCompBytes + ","); if (numCompBytes < 0) { System.out.println("\n--last block " + numCompBytes); numCompBytes = -numCompBytes; if (!lookForHeader) eof = true; } raf.skipBytes(numCompBytes); } } catch (EOFException e) { e.printStackTrace(); } return raf.getFilePointer(); } /** * test */ public static void main2(String[] args) throws IOException { File testDir = new File("C:/data/bad/radar2/"); File[] files = testDir.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; if (!file.getPath().endsWith(".ar2v")) continue; System.out.println(file.getPath() + " " + file.length()); long pos = testValid(file.getPath()); if (pos == file.length()) { System.out.println("OK"); try { NetcdfFile.open(file.getPath()); } catch (Throwable t) { System.out.println("ERROR= " + t); } } else System.out.println("NOT pos=" + pos); System.out.println(); } } public static void main(String args[]) throws IOException { NexradStationDB.init(); RandomAccessFile raf = new RandomAccessFile("/upc/share/testdata/radar/nexrad/level2/Level2_KFTG_20060818_1814.ar2v.uncompress.missingradials", "r"); // RandomAccessFile raf = new RandomAccessFile("R:/testdata/radar/nexrad/level2/problem/KCCX_20060627_1701", "r"); new Level2VolumeScan(raf, null); } }
level2 high res. variable offset and scale
cdm/src/main/java/ucar/nc2/iosp/nexrad2/Level2VolumeScan.java
level2 high res. variable offset and scale
<ide><path>dm/src/main/java/ucar/nc2/iosp/nexrad2/Level2VolumeScan.java <ide> // data formats <ide> static public final String ARCHIVE2 = "ARCHIVE2"; <ide> static public final String AR2V0001 = "AR2V0001"; <add> static public final String AR2V0003 = "AR2V0003"; <ide> <ide> static private org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(Level2VolumeScan.class); <ide> //////////////////////////////////////////////////////////////////////////////////// <ide> <ide> // try to find the station <ide> if (stationId != null) { <del> station = NexradStationDB.get(stationId); <add> if( !stationId.startsWith("K") && stationId.length()==4) { <add> String _stationId = "K" + stationId; <add> station = NexradStationDB.get(_stationId); <add> } <add> else <add> station = NexradStationDB.get(stationId); <ide> } <ide> <ide> //see if we have to uncompress <del> if (dataFormat.equals(AR2V0001)) { <add> if (dataFormat.equals(AR2V0001) || dataFormat.equals(AR2V0003)) { <ide> raf.skipBytes(4); <ide> String BZ = raf.readString(2); <ide> if (BZ.equals("BZ")) { <ide> if ((cancelTask != null) && cancelTask.isCancel()) return; <ide> } <ide> if (debugRadials) System.out.println(" reflect ok= " + reflectivity.size() + " doppler ok= " + doppler.size()); <del> <del> reflectivityGroups = sortScans("reflect", reflectivity, 600); <del> dopplerGroups = sortScans("doppler", doppler, 600); <add> if(highReflectivity.size() == 0) { <add> reflectivityGroups = sortScans("reflect", reflectivity, 600); <add> dopplerGroups = sortScans("doppler", doppler, 600); <add> } <ide> if(highReflectivity.size() > 0) <ide> reflectivityHighResGroups = sortScans("reflect_HR", highReflectivity, 720); <ide> if(highVelocity.size() > 0) <ide> } <ide> <ide> // do we have same characteristics for all records in a scan? <del> private int MAX_RADIAL = 720; <add> private int MAX_RADIAL = 721; <ide> private int[] radial = new int[MAX_RADIAL]; <ide> <ide> private boolean testScan(String name, ArrayList group) {
Java
apache-2.0
510e2247ec13ff2946610236a3407b6d7290ae16
0
aneznamova/java_pft
package ru.stqa.pft.addressbook.tests; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.model.ContactData; import java.util.Arrays; import java.util.stream.Collectors; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; /** * Created by neznaa on 4/9/2016. */ public class ContactInfoTest extends TestBase { @BeforeMethod public void ensurePrecondition() { if (app.contact().list().size() == 0) app.contact().create(new ContactData() .withFirstname("Semen").withLastname("Efimov").withAddress("Spb Test street 23 kv.76") .withMobilephone("9213000000").withHomephone("34-323-55").withWorkphone("43 23 212") .withEmail("[email protected]").withEmail2("[email protected]").withEmail3("[email protected]").withGroup("test1")); } @Test public void testContactInfo() { app.goTo().goToHomePage(); ContactData contact = app.contact().all().iterator().next(); ContactData contactInfoFromEditForm = app.contact().infoFromEditForm(contact); assertThat(contact.getAllPhones(), equalTo(mergePhones(contactInfoFromEditForm))); assertThat(contact.getAllEmails(), equalTo(mergeEmails(contactInfoFromEditForm))); assertThat(contact.getAddress(), equalTo(contactInfoFromEditForm.getAddress())); } private String mergeEmails(ContactData contact) { return Arrays.asList(contact.getEmail(), contact.getEmail2(), contact.getEmail3()) .stream().filter((s) -> !s.equals("")) .collect(Collectors.joining("\n")); } private String mergePhones(ContactData contact) { return Arrays.asList(contact.getHomephone(), contact.getMobilephone(), contact.getWorkphone()) .stream().filter((s) -> !s.equals("")) .map(ContactInfoTest::cleaned) .collect(Collectors.joining("\n")); } public static String cleaned(String phone) { return phone.replaceAll("\\s", "").replaceAll("[-()]",""); } }
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactInfoTest.java
package ru.stqa.pft.addressbook.tests; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.model.ContactData; import java.util.Arrays; import java.util.stream.Collectors; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; /** * Created by neznaa on 4/9/2016. */ public class ContactInfoTest extends TestBase { @Test public void testContactInfo() { app.goTo().goToHomePage(); ContactData contact = app.contact().all().iterator().next(); ContactData contactInfoFromEditForm = app.contact().infoFromEditForm(contact); assertThat(contact.getAllPhones(), equalTo(mergePhones(contactInfoFromEditForm))); assertThat(contact.getAllEmails(), equalTo(mergeEmails(contactInfoFromEditForm))); assertThat(contact.getAddress(), equalTo(contactInfoFromEditForm.getAddress())); } private String mergeEmails(ContactData contact) { return Arrays.asList(contact.getEmail(), contact.getEmail2(), contact.getEmail3()) .stream().filter((s) -> !s.equals("")) .collect(Collectors.joining("\n")); } private String mergePhones(ContactData contact) { return Arrays.asList(contact.getHomephone(), contact.getMobilephone(), contact.getWorkphone()) .stream().filter((s) -> !s.equals("")) .map(ContactInfoTest::cleaned) .collect(Collectors.joining("\n")); } public static String cleaned(String phone) { return phone.replaceAll("\\s", "").replaceAll("[-()]",""); } }
Добавлено предусловие для теста проверяющего корректность адреса, телефонов и почты
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactInfoTest.java
Добавлено предусловие для теста проверяющего корректность адреса, телефонов и почты
<ide><path>ddressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactInfoTest.java <ide> package ru.stqa.pft.addressbook.tests; <ide> <add>import org.testng.annotations.BeforeMethod; <ide> import org.testng.annotations.Test; <ide> import ru.stqa.pft.addressbook.model.ContactData; <ide> <ide> * Created by neznaa on 4/9/2016. <ide> */ <ide> public class ContactInfoTest extends TestBase { <add> @BeforeMethod <add> public void ensurePrecondition() { <add> if (app.contact().list().size() == 0) app.contact().create(new ContactData() <add> .withFirstname("Semen").withLastname("Efimov").withAddress("Spb Test street 23 kv.76") <add> .withMobilephone("9213000000").withHomephone("34-323-55").withWorkphone("43 23 212") <add> .withEmail("[email protected]").withEmail2("[email protected]").withEmail3("[email protected]").withGroup("test1")); <add> } <ide> <add> <ide> @Test <ide> public void testContactInfo() { <ide> app.goTo().goToHomePage();
Java
apache-2.0
bcefc15aacc5c2353b949570bdaad6311ddc5a84
0
neilellis/dollar,sillelien/dollar,sillelien/dollar,neilellis/dollar,neilellis/dollar,sillelien/dollar
/* * Copyright (c) 2014-2017 Neil Ellis * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dollar.internal.runtime.script; import com.google.common.io.CharStreams; import dollar.api.DollarStatic; import dollar.internal.runtime.script.api.ParserOptions; import dollar.internal.runtime.script.parser.Symbols; import dollar.test.CircleCiParallelRule; import org.jetbrains.annotations.NotNull; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Ignore; import org.junit.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.fail; @SuppressWarnings("ALL") public class ParserSlowTest { @ClassRule public static final CircleCiParallelRule className = new CircleCiParallelRule(); @NotNull private static final String[] files = { }; @NotNull private final ParserOptions options = new ParserOptions(); private boolean parallel; public static Stream<String> fileNames() { return Stream.of(files); } public static List<String> operatorList() { return Symbols.OPERATORS.stream().map(i -> { String file = "/examples/op/" + i.name() + ".ds"; InputStream resourceAsStream = ParserSlowTest.class.getResourceAsStream(file); if (resourceAsStream != null) { try { if (CharStreams.toString(new InputStreamReader(resourceAsStream)).matches("\\s*")) { return null; } else { return file; } } catch (IOException e) { e.printStackTrace(System.err); return null; } } else { return null; } }).filter(Objects::nonNull).collect(Collectors.toList()); } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @ParameterizedTest @ValueSource( // "bulletin.ds", // "example.ds", strings = {"slow/air_quality.ds", "slow/test_redis.ds", "slow/test_uris.ds", "slow/test_concurrency.ds", "slow/test_modules.ds"}) public void testScript(@NotNull String filename) throws Exception { System.out.println("Testing " + filename); new DollarParserImpl(options).parse(getClass().getResourceAsStream("/" + filename), filename, parallel); } @ParameterizedTest @MethodSource("operatorList") public void operators(@NotNull String file) { InputStream resourceAsStream = getClass().getResourceAsStream(file); try { new DollarParserImpl(new ParserOptions()).parse(resourceAsStream, file, false); resourceAsStream.close(); } catch (Exception e) { fail(e); } } @Test public void testMarkdown1() throws IOException { new DollarParserImpl(options).parseMarkdown( CharStreams.toString(new InputStreamReader(getClass().getResourceAsStream("/test1.md")))); } @Test @Ignore("Regression test") public void testOperators() throws Exception { DollarStatic.getConfig().failFast(false); final List<String> operatorTestFiles = Arrays.asList(); for (String operatorTestFile : operatorTestFiles) { System.out.println(operatorTestFile); new DollarParserImpl(options).parse( getClass().getResourceAsStream("/regression/operators/" + operatorTestFile), operatorTestFile, parallel); } } }
dollar-examples/src/test/java/dollar/internal/runtime/script/ParserSlowTest.java
/* * Copyright (c) 2014-2017 Neil Ellis * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dollar.internal.runtime.script; import com.google.common.io.CharStreams; import dollar.api.DollarStatic; import dollar.internal.runtime.script.api.ParserOptions; import dollar.internal.runtime.script.parser.Symbols; import dollar.test.CircleCiParallelRule; import org.jetbrains.annotations.NotNull; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Ignore; import org.junit.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.fail; @SuppressWarnings("ALL") public class ParserSlowTest { @ClassRule public static final CircleCiParallelRule className = new CircleCiParallelRule(); @NotNull private static final String[] files = { }; @NotNull private final ParserOptions options = new ParserOptions(); private boolean parallel; public static Stream<String> fileNames() { return Stream.of(files); } public static List<String> operatorList() { return Symbols.OPERATORS.stream().map(i -> { String file = "/examples/op/" + i.name() + ".ds"; InputStream resourceAsStream = ParserSlowTest.class.getResourceAsStream(file); if (resourceAsStream != null) { try { if (CharStreams.toString(new InputStreamReader(resourceAsStream)).matches("\\s*")) { return null; } else { return file; } } catch (IOException e) { e.printStackTrace(System.err); return null; } } else { return null; } }).filter(Objects::nonNull).collect(Collectors.toList()); } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @ParameterizedTest @ValueSource( // "bulletin.ds", // "example.ds", strings = {"slow/crime.ds", "slow/air_quality.ds", "slow/test_redis.ds", "slow/test_uris.ds", "slow/test_concurrency.ds", "slow/test_modules.ds"}) public void testScript(@NotNull String filename) throws Exception { System.out.println("Testing " + filename); new DollarParserImpl(options).parse(getClass().getResourceAsStream("/" + filename), filename, parallel); } @ParameterizedTest @MethodSource("operatorList") public void operators(@NotNull String file) { InputStream resourceAsStream = getClass().getResourceAsStream(file); try { new DollarParserImpl(new ParserOptions()).parse(resourceAsStream, file, false); resourceAsStream.close(); } catch (Exception e) { fail(e); } } @Test public void testMarkdown1() throws IOException { new DollarParserImpl(options).parseMarkdown( CharStreams.toString(new InputStreamReader(getClass().getResourceAsStream("/test1.md")))); } @Test @Ignore("Regression test") public void testOperators() throws Exception { DollarStatic.getConfig().failFast(false); final List<String> operatorTestFiles = Arrays.asList(); for (String operatorTestFile : operatorTestFiles) { System.out.println(operatorTestFile); new DollarParserImpl(options).parse( getClass().getResourceAsStream("/regression/operators/" + operatorTestFile), operatorTestFile, parallel); } } }
Better doc testing and adding air quality example
dollar-examples/src/test/java/dollar/internal/runtime/script/ParserSlowTest.java
Better doc testing and adding air quality example
<ide><path>ollar-examples/src/test/java/dollar/internal/runtime/script/ParserSlowTest.java <ide> @ValueSource( <ide> // "bulletin.ds", <ide> // "example.ds", <del> strings = {"slow/crime.ds", "slow/air_quality.ds", "slow/test_redis.ds", <add> strings = {"slow/air_quality.ds", "slow/test_redis.ds", <ide> "slow/test_uris.ds", "slow/test_concurrency.ds", <ide> "slow/test_modules.ds"}) <ide>
Java
apache-2.0
1be3b8bf83c88abea93f6246643ddec21960ab32
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.gradle.frameworkSupport; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import org.gradle.util.GradleVersion; import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Set; /** * @author Vladislav.Soroka * @since 4/24/2015 */ public class BuildScriptDataBuilder { @NotNull private final VirtualFile myBuildScriptFile; protected final Set<String> imports = ContainerUtil.newTreeSet(); protected final Set<String> plugins = ContainerUtil.newTreeSet(); protected final Set<String> pluginsInGroup = ContainerUtil.newTreeSet(); protected final Set<String> repositories = ContainerUtil.newTreeSet(); protected final Set<String> dependencies = ContainerUtil.newTreeSet(); protected final Set<String> properties = ContainerUtil.newTreeSet(); protected final Set<String> buildScriptProperties = ContainerUtil.newTreeSet(); protected final Set<String> buildScriptRepositories = ContainerUtil.newTreeSet(); protected final Set<String> buildScriptDependencies = ContainerUtil.newTreeSet(); protected final Set<String> other = ContainerUtil.newTreeSet(); protected final GradleVersion myGradleVersion; public BuildScriptDataBuilder(@NotNull VirtualFile buildScriptFile) { this(buildScriptFile, GradleVersion.current()); } public BuildScriptDataBuilder(@NotNull VirtualFile buildScriptFile, @NotNull GradleVersion gradleVersion) { myBuildScriptFile = buildScriptFile; myGradleVersion = gradleVersion; } @NotNull public VirtualFile getBuildScriptFile() { return myBuildScriptFile; } @NotNull public GradleVersion getGradleVersion() { return myGradleVersion; } /** * @deprecated use {@link #buildMainPart()} and {@link #buildConfigurationPart()} instead */ public String build() { return buildMainPart(); } public String buildImports() { if (!imports.isEmpty()) { return StringUtil.join(imports, "\n") + "\n"; } return ""; } public String buildConfigurationPart() { List<String> lines = ContainerUtil.newArrayList(); addBuildscriptLines(lines, BuildScriptDataBuilder::padding); if (!pluginsInGroup.isEmpty()) { lines.add("plugins {"); lines.addAll(ContainerUtil.map(pluginsInGroup, BuildScriptDataBuilder::padding)); lines.add("}"); lines.add(""); } return StringUtil.join(lines, "\n"); } public String buildMainPart() { List<String> lines = ContainerUtil.newArrayList(); addPluginsLines(lines, BuildScriptDataBuilder::padding); if (!properties.isEmpty()) { lines.addAll(properties); lines.add(""); } if (!repositories.isEmpty()) { lines.add("repositories {"); lines.addAll(ContainerUtil.map(repositories, BuildScriptDataBuilder::padding)); lines.add("}"); lines.add(""); } if (!dependencies.isEmpty()) { lines.add("dependencies {"); lines.addAll(ContainerUtil.map(dependencies, BuildScriptDataBuilder::padding)); lines.add("}"); lines.add(""); } if (!other.isEmpty()) { lines.addAll(other); } return StringUtil.join(lines, "\n"); } protected void addPluginsLines(@NotNull List<String> lines, @NotNull Function<String, String> padding) { if (!plugins.isEmpty()) { lines.addAll(plugins); lines.add(""); } } private void addBuildscriptLines(@NotNull List<String> lines, @NotNull Function<String, String> padding) { if (!buildScriptRepositories.isEmpty() || !buildScriptDependencies.isEmpty() || !buildScriptProperties.isEmpty()) { lines.add("buildscript {"); final List<String> buildScriptLines = ContainerUtil.newSmartList(); if (!buildScriptProperties.isEmpty()) { buildScriptLines.addAll(buildScriptProperties); buildScriptLines.add(""); } if (!buildScriptRepositories.isEmpty()) { buildScriptLines.add("repositories {"); buildScriptLines.addAll(ContainerUtil.map(buildScriptRepositories, padding)); buildScriptLines.add("}"); } if (!buildScriptDependencies.isEmpty()) { buildScriptLines.add("dependencies {"); buildScriptLines.addAll(ContainerUtil.map(buildScriptDependencies, padding)); buildScriptLines.add("}"); } lines.addAll(ContainerUtil.map(buildScriptLines, padding)); lines.add("}"); lines.add(""); } } public BuildScriptDataBuilder addImport(@NotNull String importString) { imports.add(importString); return this; } public BuildScriptDataBuilder addBuildscriptPropertyDefinition(@NotNull String definition) { buildScriptProperties.add(definition.trim()); return this; } public BuildScriptDataBuilder addBuildscriptRepositoriesDefinition(@NotNull String definition) { buildScriptRepositories.add(definition.trim()); return this; } public BuildScriptDataBuilder addBuildscriptDependencyNotation(@NotNull String notation) { buildScriptDependencies.add(notation.trim()); return this; } public BuildScriptDataBuilder addPluginDefinitionInPluginsGroup(@NotNull String definition) { pluginsInGroup.add(definition.trim()); return this; } public BuildScriptDataBuilder addPluginDefinition(@NotNull String definition) { plugins.add(definition.trim()); return this; } public BuildScriptDataBuilder addRepositoriesDefinition(@NotNull String definition) { repositories.add(definition.trim()); return this; } public BuildScriptDataBuilder addDependencyNotation(@NotNull String notation) { dependencies.add(notation.trim()); return this; } public BuildScriptDataBuilder addPropertyDefinition(@NotNull String definition) { properties.add(definition.trim()); return this; } public BuildScriptDataBuilder addOther(@NotNull String definition) { other.add(definition.trim()); return this; } private static String padding(String s) {return StringUtil.isNotEmpty(s) ? " " + s : "";} }
plugins/gradle/src/org/jetbrains/plugins/gradle/frameworkSupport/BuildScriptDataBuilder.java
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.gradle.frameworkSupport; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import org.gradle.util.GradleVersion; import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Set; /** * @author Vladislav.Soroka * @since 4/24/2015 */ public class BuildScriptDataBuilder { @NotNull private final VirtualFile myBuildScriptFile; protected final Set<String> imports = ContainerUtil.newTreeSet(); protected final Set<String> plugins = ContainerUtil.newTreeSet(); protected final Set<String> pluginsInGroup = ContainerUtil.newTreeSet(); protected final Set<String> repositories = ContainerUtil.newTreeSet(); protected final Set<String> dependencies = ContainerUtil.newTreeSet(); protected final Set<String> properties = ContainerUtil.newTreeSet(); protected final Set<String> buildScriptProperties = ContainerUtil.newTreeSet(); protected final Set<String> buildScriptRepositories = ContainerUtil.newTreeSet(); protected final Set<String> buildScriptDependencies = ContainerUtil.newTreeSet(); protected final Set<String> other = ContainerUtil.newTreeSet(); protected final GradleVersion myGradleVersion; public BuildScriptDataBuilder(@NotNull VirtualFile buildScriptFile) { this(buildScriptFile, GradleVersion.current()); } public BuildScriptDataBuilder(@NotNull VirtualFile buildScriptFile, @NotNull GradleVersion gradleVersion) { myBuildScriptFile = buildScriptFile; myGradleVersion = gradleVersion; } @NotNull public VirtualFile getBuildScriptFile() { return myBuildScriptFile; } /** * @deprecated use {@link #buildMainPart()} and {@link #buildConfigurationPart()} instead */ public String build() { return buildMainPart(); } public String buildImports() { if (!imports.isEmpty()) { return StringUtil.join(imports, "\n") + "\n"; } return ""; } public String buildConfigurationPart() { List<String> lines = ContainerUtil.newArrayList(); addBuildscriptLines(lines, BuildScriptDataBuilder::padding); if (!pluginsInGroup.isEmpty()) { lines.add("plugins {"); lines.addAll(ContainerUtil.map(pluginsInGroup, BuildScriptDataBuilder::padding)); lines.add("}"); lines.add(""); } return StringUtil.join(lines, "\n"); } public String buildMainPart() { List<String> lines = ContainerUtil.newArrayList(); addPluginsLines(lines, BuildScriptDataBuilder::padding); if (!properties.isEmpty()) { lines.addAll(properties); lines.add(""); } if (!repositories.isEmpty()) { lines.add("repositories {"); lines.addAll(ContainerUtil.map(repositories, BuildScriptDataBuilder::padding)); lines.add("}"); lines.add(""); } if (!dependencies.isEmpty()) { lines.add("dependencies {"); lines.addAll(ContainerUtil.map(dependencies, BuildScriptDataBuilder::padding)); lines.add("}"); lines.add(""); } if (!other.isEmpty()) { lines.addAll(other); } return StringUtil.join(lines, "\n"); } protected void addPluginsLines(@NotNull List<String> lines, @NotNull Function<String, String> padding) { if (!plugins.isEmpty()) { lines.addAll(plugins); lines.add(""); } } private void addBuildscriptLines(@NotNull List<String> lines, @NotNull Function<String, String> padding) { if (!buildScriptRepositories.isEmpty() || !buildScriptDependencies.isEmpty() || !buildScriptProperties.isEmpty()) { lines.add("buildscript {"); final List<String> buildScriptLines = ContainerUtil.newSmartList(); if (!buildScriptProperties.isEmpty()) { buildScriptLines.addAll(buildScriptProperties); buildScriptLines.add(""); } if (!buildScriptRepositories.isEmpty()) { buildScriptLines.add("repositories {"); buildScriptLines.addAll(ContainerUtil.map(buildScriptRepositories, padding)); buildScriptLines.add("}"); } if (!buildScriptDependencies.isEmpty()) { buildScriptLines.add("dependencies {"); buildScriptLines.addAll(ContainerUtil.map(buildScriptDependencies, padding)); buildScriptLines.add("}"); } lines.addAll(ContainerUtil.map(buildScriptLines, padding)); lines.add("}"); lines.add(""); } } public BuildScriptDataBuilder addImport(@NotNull String importString) { imports.add(importString); return this; } public BuildScriptDataBuilder addBuildscriptPropertyDefinition(@NotNull String definition) { buildScriptProperties.add(definition.trim()); return this; } public BuildScriptDataBuilder addBuildscriptRepositoriesDefinition(@NotNull String definition) { buildScriptRepositories.add(definition.trim()); return this; } public BuildScriptDataBuilder addBuildscriptDependencyNotation(@NotNull String notation) { buildScriptDependencies.add(notation.trim()); return this; } public BuildScriptDataBuilder addPluginDefinitionInPluginsGroup(@NotNull String definition) { pluginsInGroup.add(definition.trim()); return this; } public BuildScriptDataBuilder addPluginDefinition(@NotNull String definition) { plugins.add(definition.trim()); return this; } public BuildScriptDataBuilder addRepositoriesDefinition(@NotNull String definition) { repositories.add(definition.trim()); return this; } public BuildScriptDataBuilder addDependencyNotation(@NotNull String notation) { dependencies.add(notation.trim()); return this; } public BuildScriptDataBuilder addPropertyDefinition(@NotNull String definition) { properties.add(definition.trim()); return this; } public BuildScriptDataBuilder addOther(@NotNull String definition) { other.add(definition.trim()); return this; } private static String padding(String s) {return StringUtil.isNotEmpty(s) ? " " + s : "";} }
Gradle: expose build script data builder gradle version (IDEA-188057)
plugins/gradle/src/org/jetbrains/plugins/gradle/frameworkSupport/BuildScriptDataBuilder.java
Gradle: expose build script data builder gradle version (IDEA-188057)
<ide><path>lugins/gradle/src/org/jetbrains/plugins/gradle/frameworkSupport/BuildScriptDataBuilder.java <ide> @NotNull <ide> public VirtualFile getBuildScriptFile() { <ide> return myBuildScriptFile; <add> } <add> <add> @NotNull <add> public GradleVersion getGradleVersion() { <add> return myGradleVersion; <ide> } <ide> <ide> /**
JavaScript
apache-2.0
01826faf515650907f6b1c65891f6ef7e6a713fb
0
icfantv/deck,HaishiBai/deck,sgarlick987/deck,duftler/deck,ajordens/deck,icfantv/deck,spinnaker/deck,duftler/deck,spinnaker/deck,spinnaker/deck,sgarlick987/deck,zanthrash/deck-old,icfantv/deck,HaishiBai/deck,sgarlick987/deck,zanthrash/deck-1,spinnaker/deck,HaishiBai/deck,kenzanlabs/deck,zanthrash/deck-1,icfantv/deck,sgarlick987/deck,duftler/deck,kenzanlabs/deck,ajordens/deck,zanthrash/deck-1,ajordens/deck,ajordens/deck,zanthrash/deck-old,duftler/deck,kenzanlabs/deck
'use strict'; angular.module('deckApp.gce') .controller('gceCloneServerGroupCtrl', function($scope, $modalInstance, _, $q, $exceptionHandler, $state, accountService, orcaService, mortService, oortService, instanceTypeService, modalWizardService, securityGroupService, taskMonitorService, imageService, serverGroupCommand, application, title) { $scope.title = title; $scope.healthCheckTypes = ['EC2', 'ELB']; $scope.terminationPolicies = ['OldestInstance', 'NewestInstance', 'OldestLaunchConfiguration', 'ClosestToNextInstanceHour', 'Default']; $scope.applicationName = application.name; $scope.state = { loaded: false, imagesLoaded: false }; $scope.taskMonitor = taskMonitorService.buildTaskMonitor({ application: application, title: 'Creating your server group', forceRefreshMessage: 'Getting your new server group from Google...', modalInstance: $modalInstance, forceRefreshEnabled: true }); var accountLoader = accountService.getRegionsKeyedByAccount().then(function(regionsKeyedByAccount) { $scope.accounts = _.keys(regionsKeyedByAccount); $scope.regionsKeyedByAccount = regionsKeyedByAccount; }); var securityGroupLoader = securityGroupService.getAllSecurityGroups().then(function(securityGroups) { $scope.securityGroups = securityGroups; }); var loadBalancerLoader = oortService.listGCELoadBalancers().then(function(loadBalancers) { $scope.loadBalancers = loadBalancers; }); var subnetLoader = mortService.listSubnets().then(function(subnets) { $scope.subnets = subnets; }); $scope.command = serverGroupCommand; var imageLoader = imageService.findImages({ provider: $scope.command.selectedProvider, account: serverGroupCommand.credentials }) .then(function(images) { $scope.gceImages = collectImageNames(images); $scope.lastImageAccount = serverGroupCommand.credentials; } ); var instanceTypeLoader = instanceTypeService.getAllTypesByRegion($scope.command.selectedProvider).then(function(instanceTypes) { $scope.instanceTypesByRegion = instanceTypes; }); $q.all([accountLoader, securityGroupLoader, loadBalancerLoader, subnetLoader, imageLoader, instanceTypeLoader]).then(function() { $scope.state.loaded = true; initializeCommand(); initializeWizardState(); initializeSelectOptions(); initializeWatches(); }); function initializeWizardState() { if (serverGroupCommand.viewState.mode === 'clone') { if ($scope.command.image) { modalWizardService.getWizard().markComplete('location'); } modalWizardService.getWizard().markComplete('load-balancers'); //modalWizardService.getWizard().markComplete('security-groups'); modalWizardService.getWizard().markComplete('instance-profile'); modalWizardService.getWizard().markComplete('instance-type'); modalWizardService.getWizard().markComplete('capacity'); modalWizardService.getWizard().markComplete('advanced'); } } function initializeWatches() { $scope.$watch('command.credentials', credentialsChanged); $scope.$watch('command.region', regionChanged); $scope.$watch('command.subnetType', subnetChanged); } function initializeSelectOptions() { credentialsChanged(); regionChanged(); configureSubnetPurposes(); configureSecurityGroupOptions(); } function credentialsChanged() { if ($scope.command.credentials) { $scope.regionToZonesMap = $scope.regionsKeyedByAccount[$scope.command.credentials].regions; if (!$scope.regionToZonesMap) { // TODO(duftler): Move these default values to settings.js and/or accountService.js. $scope.regionToZonesMap = { 'us-central1': ['us-central1-a', 'us-central1-b', 'us-central1-f'], 'europe-west1': ['europe-west1-a', 'europe-west1-b', 'europe-west1-c'], 'asia-east1': ['asia-east1-a', 'asia-east1-b', 'asia-east1-c'] }; } $scope.regions = _.keys($scope.regionToZonesMap); if ($scope.regions.indexOf($scope.command.region) === -1) { $scope.command.region = null; } } else { $scope.command.region = null; } configureImages(); } function regionChanged() { if ($scope.regionToZonesMap) { $scope.zones = $scope.regionToZonesMap[$scope.command.region]; if (!$scope.command.region || $scope.zones.indexOf($scope.command.zone) === -1) { $scope.command.zone = null; } } else { $scope.zones = null; $scope.command.zone = null; } configureLoadBalancerOptions(); } function subnetChanged() { if (true) { return; } var subnet = _($scope.subnets) .find({purpose: $scope.command.subnetType, account: $scope.command.credentials, region: $scope.command.region}); $scope.command.vpcId = subnet ? subnet.vpcId : null; configureSecurityGroupOptions(); configureLoadBalancerOptions(); } function configureSubnetPurposes() { if (true) { return; } if ($scope.command.region === null) { $scope.regionSubnetPurposes = null; } $scope.regionSubnetPurposes = _($scope.subnets) .filter({account: $scope.command.credentials, region: $scope.command.region, target: 'ec2'}) .pluck('purpose') .uniq() .map(function(purpose) { return { purpose: purpose, label: purpose };}) .valueOf(); } function configureSecurityGroupOptions() { if (true) { return; } var newRegionalSecurityGroups = _($scope.securityGroups[$scope.command.credentials].aws[$scope.command.region]) .filter({vpcId: $scope.command.vpcId || null}) .valueOf(); if ($scope.regionalSecurityGroups && $scope.command.securityGroups) { var previousCount = $scope.command.securityGroups.length; // not initializing - we are actually changing groups var matchedGroupNames = $scope.command.securityGroups.map(function(groupId) { return _($scope.regionalSecurityGroups).find({id: groupId}).name; }).map(function(groupName) { return _(newRegionalSecurityGroups).find({name: groupName}); }).filter(function(group) { return group; }).map(function(group) { return group.id; }); $scope.command.securityGroups = matchedGroupNames; if (matchedGroupNames.length !== previousCount) { modalWizardService.getWizard().markDirty('security-groups'); } } $scope.regionalSecurityGroups = newRegionalSecurityGroups; } function configureLoadBalancerOptions() { var newLoadBalancers = _($scope.loadBalancers) .filter({account: $scope.command.credentials}) .pluck('regions') .flatten(true) .filter({name: $scope.command.region}) .pluck('loadBalancers') .flatten(true) .pluck('name') .unique() .valueOf(); if ($scope.regionalLoadBalancers && $scope.command.loadBalancers) { var previousCount = $scope.command.loadBalancers.length; $scope.command.loadBalancers = _.intersection(newLoadBalancers, $scope.command.loadBalancers); if ($scope.command.loadBalancers.length !== previousCount) { modalWizardService.getWizard().markDirty('load-balancers'); } } $scope.regionalLoadBalancers = newLoadBalancers; } function configureImages() { if ($scope.command.credentials !== $scope.lastImageAccount) { imageService.findImages({ provider: $scope.command.selectedProvider, account: $scope.command.credentials}) .then(function(images) { $scope.gceImages = collectImageNames(images); if ($scope.gceImages.indexOf($scope.command.image) === -1) { $scope.command.image = null; } } ); $scope.lastImageAccount = $scope.command.credentials; } } function collectImageNames(images) { return _(images) .pluck('imageName') .flatten(true) .unique() .valueOf(); } // function configureInstanceTypes() { // if ($scope.command.region) { // $scope.regionalInstanceTypes = instanceTypeService.getAvailableTypesForRegions($scope.command.selectedProvider, $scope.instanceTypesByRegion, [$scope.command.region]); // if ($scope.command.instanceType && $scope.regionalInstanceTypes.indexOf($scope.command.instanceType) === -1) { // $scope.regionalInstanceTypes.push($scope.command.instanceType); // } // } // } function initializeCommand() { if (serverGroupCommand.viewState.imageId && $scope.gceImages.indexOf(serverGroupCommand.viewState.imageId) > -1) { $scope.command.image = serverGroupCommand.viewState.imageId; } } function transformInstanceMetadata() { var transformedInstanceMetadata = {}; // The instanceMetadata is stored using 'key' and 'value' attributes to enable the Add/Remove behavior in the wizard. $scope.command.instanceMetadata.forEach(function(metadataPair) { transformedInstanceMetadata[metadataPair.key] = metadataPair.value; }); // We use this list of load balancer names when 'Enabling' a server group. if ($scope.command.loadBalancers.length > 0) { transformedInstanceMetadata['load-balancer-names'] = $scope.command.loadBalancers.toString(); } $scope.command.instanceMetadata = transformedInstanceMetadata; } // TODO(duftler): Update this to reflect current fields defined on dialog. this.isValid = function () { return $scope.command && ($scope.command.amiName !== null) && ($scope.command.application !== null) && ($scope.command.credentials !== null) && ($scope.command.instanceType !== null) && ($scope.command.region !== null) && ($scope.command.availabilityZones !== null) && ($scope.command.capacity.min !== null) && ($scope.command.capacity.max !== null) && ($scope.command.capacity.desired !== null) && modalWizardService.getWizard().isComplete(); }; this.showSubmitButton = function () { return modalWizardService.getWizard().allPagesVisited(); }; $scope.taskMonitor.onApplicationRefresh = function handleApplicationRefreshComplete() { $scope.taskMonitor.task.getCompletedKatoTask().then(function(katoTask) { if (katoTask.resultObjects && katoTask.resultObjects.length && katoTask.resultObjects[0].serverGroupNames) { var newStateParams = { serverGroup: katoTask.resultObjects[0].serverGroupNames[0].split(':')[1], accountId: $scope.command.credentials, region: $scope.command.region }; if (!$state.includes('**.clusters.**')) { $state.go('^.^.^.clusters.serverGroup', newStateParams); } else { if ($state.includes('**.serverGroup')) { $state.go('^.^.serverGroup', newStateParams); } else { if ($state.includes('**.clusters.*')) { $state.go('^.serverGroup', newStateParams); } else { $state.go('.serverGroup', newStateParams); } } } } }); }; this.clone = function () { $scope.taskMonitor.submit( function() { transformInstanceMetadata(); return orcaService.cloneServerGroup($scope.command, application.name); } ); }; this.cancel = function () { $modalInstance.dismiss(); }; });
app/scripts/controllers/modal/gceCloneServerGroupCtrl.js
'use strict'; angular.module('deckApp.gce') .controller('gceCloneServerGroupCtrl', function($scope, $modalInstance, _, $q, $exceptionHandler, $state, accountService, orcaService, mortService, oortService, instanceTypeService, modalWizardService, securityGroupService, taskMonitorService, imageService, serverGroupCommand, application, title) { $scope.title = title; $scope.healthCheckTypes = ['EC2', 'ELB']; $scope.terminationPolicies = ['OldestInstance', 'NewestInstance', 'OldestLaunchConfiguration', 'ClosestToNextInstanceHour', 'Default']; $scope.applicationName = application.name; $scope.state = { loaded: false, imagesLoaded: false }; $scope.taskMonitor = taskMonitorService.buildTaskMonitor({ application: application, title: 'Creating your server group', forceRefreshMessage: 'Getting your new server group from Google...', modalInstance: $modalInstance, forceRefreshEnabled: true }); var accountLoader = accountService.getRegionsKeyedByAccount().then(function(regionsKeyedByAccount) { $scope.accounts = _.keys(regionsKeyedByAccount); $scope.regionsKeyedByAccount = regionsKeyedByAccount; }); var securityGroupLoader = securityGroupService.getAllSecurityGroups().then(function(securityGroups) { $scope.securityGroups = securityGroups; }); var loadBalancerLoader = oortService.listGCELoadBalancers().then(function(loadBalancers) { $scope.loadBalancers = loadBalancers; }); var subnetLoader = mortService.listSubnets().then(function(subnets) { $scope.subnets = subnets; }); $scope.command = serverGroupCommand; var imageLoader = imageService.findImages({ provider: $scope.command.selectedProvider, account: serverGroupCommand.credentials }) .then(function(images) { $scope.gceImages = images; $scope.lastImageAccount = serverGroupCommand.credentials; } ); var instanceTypeLoader = instanceTypeService.getAllTypesByRegion($scope.command.selectedProvider).then(function(instanceTypes) { $scope.instanceTypesByRegion = instanceTypes; }); $q.all([accountLoader, securityGroupLoader, loadBalancerLoader, subnetLoader, imageLoader, instanceTypeLoader]).then(function() { $scope.state.loaded = true; initializeCommand(); initializeWizardState(); initializeSelectOptions(); initializeWatches(); }); function initializeWizardState() { if (serverGroupCommand.viewState.mode === 'clone') { if ($scope.command.image) { modalWizardService.getWizard().markComplete('location'); } modalWizardService.getWizard().markComplete('load-balancers'); //modalWizardService.getWizard().markComplete('security-groups'); modalWizardService.getWizard().markComplete('instance-profile'); modalWizardService.getWizard().markComplete('instance-type'); modalWizardService.getWizard().markComplete('capacity'); modalWizardService.getWizard().markComplete('advanced'); } } function initializeWatches() { $scope.$watch('command.credentials', credentialsChanged); $scope.$watch('command.region', regionChanged); $scope.$watch('command.subnetType', subnetChanged); } function initializeSelectOptions() { credentialsChanged(); regionChanged(); configureSubnetPurposes(); configureSecurityGroupOptions(); } function credentialsChanged() { if ($scope.command.credentials) { $scope.regionToZonesMap = $scope.regionsKeyedByAccount[$scope.command.credentials].regions; if (!$scope.regionToZonesMap) { // TODO(duftler): Move these default values to settings.js and/or accountService.js. $scope.regionToZonesMap = { 'us-central1': ['us-central1-a', 'us-central1-b', 'us-central1-f'], 'europe-west1': ['europe-west1-a', 'europe-west1-b', 'europe-west1-c'], 'asia-east1': ['asia-east1-a', 'asia-east1-b', 'asia-east1-c'] }; } $scope.regions = _.keys($scope.regionToZonesMap); if ($scope.regions.indexOf($scope.command.region) === -1) { $scope.command.region = null; } } else { $scope.command.region = null; } configureImages(); } function regionChanged() { if ($scope.regionToZonesMap) { $scope.zones = $scope.regionToZonesMap[$scope.command.region]; if (!$scope.command.region || $scope.zones.indexOf($scope.command.zone) === -1) { $scope.command.zone = null; } } else { $scope.zones = null; $scope.command.zone = null; } configureLoadBalancerOptions(); } function subnetChanged() { if (true) { return; } var subnet = _($scope.subnets) .find({purpose: $scope.command.subnetType, account: $scope.command.credentials, region: $scope.command.region}); $scope.command.vpcId = subnet ? subnet.vpcId : null; configureSecurityGroupOptions(); configureLoadBalancerOptions(); } function configureSubnetPurposes() { if (true) { return; } if ($scope.command.region === null) { $scope.regionSubnetPurposes = null; } $scope.regionSubnetPurposes = _($scope.subnets) .filter({account: $scope.command.credentials, region: $scope.command.region, target: 'ec2'}) .pluck('purpose') .uniq() .map(function(purpose) { return { purpose: purpose, label: purpose };}) .valueOf(); } function configureSecurityGroupOptions() { if (true) { return; } var newRegionalSecurityGroups = _($scope.securityGroups[$scope.command.credentials].aws[$scope.command.region]) .filter({vpcId: $scope.command.vpcId || null}) .valueOf(); if ($scope.regionalSecurityGroups && $scope.command.securityGroups) { var previousCount = $scope.command.securityGroups.length; // not initializing - we are actually changing groups var matchedGroupNames = $scope.command.securityGroups.map(function(groupId) { return _($scope.regionalSecurityGroups).find({id: groupId}).name; }).map(function(groupName) { return _(newRegionalSecurityGroups).find({name: groupName}); }).filter(function(group) { return group; }).map(function(group) { return group.id; }); $scope.command.securityGroups = matchedGroupNames; if (matchedGroupNames.length !== previousCount) { modalWizardService.getWizard().markDirty('security-groups'); } } $scope.regionalSecurityGroups = newRegionalSecurityGroups; } function configureLoadBalancerOptions() { var newLoadBalancers = _($scope.loadBalancers) .filter({account: $scope.command.credentials}) .pluck('regions') .flatten(true) .filter({name: $scope.command.region}) .pluck('loadBalancers') .flatten(true) .pluck('name') .unique() .valueOf(); if ($scope.regionalLoadBalancers && $scope.command.loadBalancers) { var previousCount = $scope.command.loadBalancers.length; $scope.command.loadBalancers = _.intersection(newLoadBalancers, $scope.command.loadBalancers); if ($scope.command.loadBalancers.length !== previousCount) { modalWizardService.getWizard().markDirty('load-balancers'); } } $scope.regionalLoadBalancers = newLoadBalancers; } function configureImages() { if ($scope.command.credentials !== $scope.lastImageAccount) { imageService.findImages({ provider: $scope.command.selectedProvider, account: $scope.command.credentials}) .then(function(images) { $scope.gceImages = images; if ($scope.gceImages.indexOf($scope.command.image) === -1) { $scope.command.image = null; } } ); $scope.lastImageAccount = $scope.command.credentials; } } // function configureInstanceTypes() { // if ($scope.command.region) { // $scope.regionalInstanceTypes = instanceTypeService.getAvailableTypesForRegions($scope.command.selectedProvider, $scope.instanceTypesByRegion, [$scope.command.region]); // if ($scope.command.instanceType && $scope.regionalInstanceTypes.indexOf($scope.command.instanceType) === -1) { // $scope.regionalInstanceTypes.push($scope.command.instanceType); // } // } // } function initializeCommand() { if (serverGroupCommand.viewState.imageId && $scope.gceImages.indexOf(serverGroupCommand.viewState.imageId) > -1) { $scope.command.image = serverGroupCommand.viewState.imageId; } } function transformInstanceMetadata() { var transformedInstanceMetadata = {}; // The instanceMetadata is stored using 'key' and 'value' attributes to enable the Add/Remove behavior in the wizard. $scope.command.instanceMetadata.forEach(function(metadataPair) { transformedInstanceMetadata[metadataPair.key] = metadataPair.value; }); // We use this list of load balancer names when 'Enabling' a server group. if ($scope.command.loadBalancers.length > 0) { transformedInstanceMetadata['load-balancer-names'] = $scope.command.loadBalancers.toString(); } $scope.command.instanceMetadata = transformedInstanceMetadata; } // TODO(duftler): Update this to reflect current fields defined on dialog. this.isValid = function () { return $scope.command && ($scope.command.amiName !== null) && ($scope.command.application !== null) && ($scope.command.credentials !== null) && ($scope.command.instanceType !== null) && ($scope.command.region !== null) && ($scope.command.availabilityZones !== null) && ($scope.command.capacity.min !== null) && ($scope.command.capacity.max !== null) && ($scope.command.capacity.desired !== null) && modalWizardService.getWizard().isComplete(); }; this.showSubmitButton = function () { return modalWizardService.getWizard().allPagesVisited(); }; $scope.taskMonitor.onApplicationRefresh = function handleApplicationRefreshComplete() { $scope.taskMonitor.task.getCompletedKatoTask().then(function(katoTask) { if (katoTask.resultObjects && katoTask.resultObjects.length && katoTask.resultObjects[0].serverGroupNames) { var newStateParams = { serverGroup: katoTask.resultObjects[0].serverGroupNames[0].split(':')[1], accountId: $scope.command.credentials, region: $scope.command.region }; if (!$state.includes('**.clusters.**')) { $state.go('^.^.^.clusters.serverGroup', newStateParams); } else { if ($state.includes('**.serverGroup')) { $state.go('^.^.serverGroup', newStateParams); } else { if ($state.includes('**.clusters.*')) { $state.go('^.serverGroup', newStateParams); } else { $state.go('.serverGroup', newStateParams); } } } } }); }; this.clone = function () { $scope.taskMonitor.submit( function() { transformInstanceMetadata(); return orcaService.cloneServerGroup($scope.command, application.name); } ); }; this.cancel = function () { $modalInstance.dismiss(); }; });
Now that we get back a list of image maps, instead of a list of simple strings, we need to collect the imageNames.
app/scripts/controllers/modal/gceCloneServerGroupCtrl.js
Now that we get back a list of image maps, instead of a list of simple strings, we need to collect the imageNames.
<ide><path>pp/scripts/controllers/modal/gceCloneServerGroupCtrl.js <ide> provider: $scope.command.selectedProvider, <ide> account: serverGroupCommand.credentials }) <ide> .then(function(images) { <del> $scope.gceImages = images; <add> $scope.gceImages = collectImageNames(images); <ide> $scope.lastImageAccount = serverGroupCommand.credentials; <ide> } <ide> ); <ide> provider: $scope.command.selectedProvider, <ide> account: $scope.command.credentials}) <ide> .then(function(images) { <del> $scope.gceImages = images; <add> $scope.gceImages = collectImageNames(images); <ide> if ($scope.gceImages.indexOf($scope.command.image) === -1) { <ide> $scope.command.image = null; <ide> } <ide> <ide> $scope.lastImageAccount = $scope.command.credentials; <ide> } <add> } <add> <add> function collectImageNames(images) { <add> return _(images) <add> .pluck('imageName') <add> .flatten(true) <add> .unique() <add> .valueOf(); <ide> } <ide> <ide> // function configureInstanceTypes() {
Java
apache-2.0
1bb59de542385b09393aa4e80b21b4fe5fd63299
0
jonvestal/open-kilda,carmine/open-kilda,carmine/open-kilda,jonvestal/open-kilda,nikitamarchenko/open-kilda,telstra/open-kilda,carmine/open-kilda,carmine/open-kilda,jonvestal/open-kilda,jonvestal/open-kilda,carmine/open-kilda,nikitamarchenko/open-kilda,nikitamarchenko/open-kilda,nikitamarchenko/open-kilda,telstra/open-kilda,telstra/open-kilda,telstra/open-kilda,jonvestal/open-kilda,nikitamarchenko/open-kilda,telstra/open-kilda,nikitamarchenko/open-kilda,carmine/open-kilda,telstra/open-kilda,telstra/open-kilda
/* Copyright 2017 Telstra Open Source * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openkilda.wfm.topology.flow; import org.apache.storm.Config; import org.openkilda.messaging.ServiceType; import org.openkilda.messaging.Utils; import org.openkilda.pce.provider.Auth; import org.openkilda.pce.provider.AuthNeo4j; import org.openkilda.wfm.ConfigurationException; import org.openkilda.wfm.CtrlBoltRef; import org.openkilda.wfm.LaunchEnvironment; import org.openkilda.wfm.StreamNameCollisionException; import org.openkilda.wfm.topology.AbstractTopology; import org.openkilda.wfm.topology.flow.bolts.CrudBolt; import org.openkilda.wfm.topology.flow.bolts.ErrorBolt; import org.openkilda.wfm.topology.flow.bolts.LcmFlowCacheSyncBolt; import org.openkilda.wfm.topology.flow.bolts.NorthboundReplyBolt; import org.openkilda.wfm.topology.flow.bolts.SpeakerBolt; import org.openkilda.wfm.topology.flow.bolts.SplitterBolt; import org.openkilda.wfm.topology.flow.bolts.TopologyEngineBolt; import org.openkilda.wfm.topology.flow.bolts.TransactionBolt; import org.openkilda.wfm.topology.utils.LcmKafkaSpout; import org.apache.storm.generated.ComponentObject; import org.apache.storm.generated.StormTopology; import org.apache.storm.kafka.bolt.KafkaBolt; import org.apache.storm.kafka.spout.KafkaSpout; import org.apache.storm.kafka.spout.KafkaSpoutConfig; import org.apache.storm.topology.BoltDeclarer; import org.apache.storm.topology.TopologyBuilder; import org.apache.storm.tuple.Fields; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; /** * Flow topology. */ public class FlowTopology extends AbstractTopology { public static final String SWITCH_ID_FIELD = "switch-id"; public static final String STATUS_FIELD = "status"; public static final String ERROR_TYPE_FIELD = "error-type"; public static final Fields fieldFlowId = new Fields(Utils.FLOW_ID); public static final Fields fieldSwitchId = new Fields(SWITCH_ID_FIELD); public static final Fields fieldsFlowIdStatus = new Fields(Utils.FLOW_ID, STATUS_FIELD); public static final Fields fieldsMessageFlowId = new Fields(MESSAGE_FIELD, Utils.FLOW_ID); public static final Fields fieldsMessageErrorType = new Fields(MESSAGE_FIELD, ERROR_TYPE_FIELD); public static final Fields fieldsMessageSwitchIdFlowIdTransactionId = new Fields(MESSAGE_FIELD, SWITCH_ID_FIELD, Utils.FLOW_ID, Utils.TRANSACTION_ID); private static final Logger logger = LoggerFactory.getLogger(FlowTopology.class); private final Auth pathComputerAuth; public FlowTopology(LaunchEnvironment env) throws ConfigurationException { super(env); pathComputerAuth = new AuthNeo4j(config.getNeo4jHost(), config.getNeo4jLogin(), config.getNeo4jPassword()); logger.debug("Topology built {}: zookeeper={}, kafka={}, parallelism={}, workers={}" + ", neo4j_url{}, neo4j_user{}, neo4j_pswd{}", getTopologyName(), config.getZookeeperHosts(), config.getKafkaHosts(), config.getParallelism(), config.getWorkers(), config.getNeo4jHost(), config.getNeo4jLogin(), config.getNeo4jPassword()); } public FlowTopology(LaunchEnvironment env, Auth pathComputerAuth) throws ConfigurationException { super(env); this.pathComputerAuth = pathComputerAuth; logger.debug("Topology built {}: zookeeper={}, kafka={}, parallelism={}, workers={}", getTopologyName(), config.getZookeeperHosts(), config.getKafkaHosts(), config.getParallelism(), config.getWorkers()); } @Override public StormTopology createTopology() throws StreamNameCollisionException { logger.info("Creating Topology: {}", topologyName); TopologyBuilder builder = new TopologyBuilder(); List<CtrlBoltRef> ctrlTargets = new ArrayList<>(); BoltDeclarer boltSetup; Integer parallelism = config.getParallelism(); KafkaSpoutConfig<String, String> kafkaSpoutConfig; KafkaSpout<String, String> kafkaSpout; // builder.setSpout( // ComponentType.LCM_SPOUT.toString(), // createKafkaSpout(config.getKafkaFlowTopic(), ComponentType.LCM_SPOUT.toString()), 1); // builder.setBolt( // ComponentType.LCM_FLOW_SYNC_BOLT.toString(), // new LcmFlowCacheSyncBolt(ComponentType.NORTHBOUND_KAFKA_SPOUT.toString()), // 1) // .shuffleGrouping(ComponentType.NORTHBOUND_KAFKA_SPOUT.toString(), LcmKafkaSpout.STREAM_ID_LCM) // .shuffleGrouping(ComponentType.LCM_SPOUT.toString()); /* * Spout receives all Northbound requests. */ kafkaSpoutConfig = makeKafkaSpoutConfigBuilder( ComponentType.NORTHBOUND_KAFKA_SPOUT.toString(), config.getKafkaFlowTopic()).build(); // (crimi) - commenting out LcmKafkaSpout here due to dying worker //kafkaSpout = new LcmKafkaSpout<>(kafkaSpoutConfig); kafkaSpout = new KafkaSpout<>(kafkaSpoutConfig); builder.setSpout(ComponentType.NORTHBOUND_KAFKA_SPOUT.toString(), kafkaSpout, parallelism); /* * Bolt splits requests on streams. * It groups requests by flow-id. */ SplitterBolt splitterBolt = new SplitterBolt(); builder.setBolt(ComponentType.SPLITTER_BOLT.toString(), splitterBolt, parallelism) .shuffleGrouping(ComponentType.NORTHBOUND_KAFKA_SPOUT.toString()); /* * Bolt handles flow CRUD operations. * It groups requests by flow-id. */ CrudBolt crudBolt = new CrudBolt(pathComputerAuth); ComponentObject.serialized_java(org.apache.storm.utils.Utils.javaSerialize(pathComputerAuth)); boltSetup = builder.setBolt(ComponentType.CRUD_BOLT.toString(), crudBolt, parallelism) .fieldsGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.CREATE.toString(), fieldFlowId) // TODO: this READ is used for single and for all flows. But all flows shouldn't be fieldsGrouping. .fieldsGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.READ.toString(), fieldFlowId) .fieldsGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.UPDATE.toString(), fieldFlowId) .fieldsGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.DELETE.toString(), fieldFlowId) .fieldsGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.PUSH.toString(), fieldFlowId) .fieldsGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.UNPUSH.toString(), fieldFlowId) .fieldsGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.PATH.toString(), fieldFlowId) .fieldsGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.RESTORE.toString(), fieldFlowId) .fieldsGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.REROUTE.toString(), fieldFlowId) .fieldsGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.STATUS.toString(), fieldFlowId) // TODO: this CACHE_SYNC shouldn't be fields-grouping - there is no field - it should be all - but tackle during multi instance testing .fieldsGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.CACHE_SYNC.toString(), fieldFlowId) .fieldsGrouping(ComponentType.TRANSACTION_BOLT.toString(), StreamType.STATUS.toString(), fieldFlowId) .fieldsGrouping(ComponentType.SPEAKER_BOLT.toString(), StreamType.STATUS.toString(), fieldFlowId) .fieldsGrouping(ComponentType.TOPOLOGY_ENGINE_BOLT.toString(), StreamType.STATUS.toString(), fieldFlowId); // .shuffleGrouping( // ComponentType.LCM_FLOW_SYNC_BOLT.toString(), LcmFlowCacheSyncBolt.STREAM_ID_SYNC_FLOW_CACHE); ctrlTargets.add(new CtrlBoltRef(ComponentType.CRUD_BOLT.toString(), crudBolt, boltSetup)); /* * Bolt sends cache updates. */ KafkaBolt cacheKafkaBolt = createKafkaBolt(config.getKafkaTopoCacheTopic()); builder.setBolt(ComponentType.CACHE_KAFKA_BOLT.toString(), cacheKafkaBolt, parallelism) .shuffleGrouping(ComponentType.CRUD_BOLT.toString(), StreamType.CREATE.toString()) .shuffleGrouping(ComponentType.CRUD_BOLT.toString(), StreamType.UPDATE.toString()) .shuffleGrouping(ComponentType.CRUD_BOLT.toString(), StreamType.DELETE.toString()) .shuffleGrouping(ComponentType.CRUD_BOLT.toString(), StreamType.STATUS.toString()); /* * Spout receives Topology Engine response */ KafkaSpout topologyKafkaSpout = createKafkaSpout( config.getKafkaFlowTopic(), ComponentType.TOPOLOGY_ENGINE_KAFKA_SPOUT.toString()); builder.setSpout(ComponentType.TOPOLOGY_ENGINE_KAFKA_SPOUT.toString(), topologyKafkaSpout, parallelism); /* * Bolt processes Topology Engine responses, groups by flow-id field */ TopologyEngineBolt topologyEngineBolt = new TopologyEngineBolt(); builder.setBolt(ComponentType.TOPOLOGY_ENGINE_BOLT.toString(), topologyEngineBolt, parallelism) .shuffleGrouping(ComponentType.TOPOLOGY_ENGINE_KAFKA_SPOUT.toString()); /* * Bolt sends Speaker requests */ KafkaBolt speakerKafkaBolt = createKafkaBolt(config.getKafkaSpeakerTopic()); builder.setBolt(ComponentType.SPEAKER_KAFKA_BOLT.toString(), speakerKafkaBolt, parallelism) .shuffleGrouping(ComponentType.TRANSACTION_BOLT.toString(), StreamType.CREATE.toString()) .shuffleGrouping(ComponentType.TRANSACTION_BOLT.toString(), StreamType.DELETE.toString()); /* * Spout receives Speaker responses */ KafkaSpout speakerKafkaSpout = createKafkaSpout( config.getKafkaFlowTopic(), ComponentType.SPEAKER_KAFKA_SPOUT.toString()); builder.setSpout(ComponentType.SPEAKER_KAFKA_SPOUT.toString(), speakerKafkaSpout, parallelism); /* * Bolt processes Speaker responses, groups by flow-id field */ SpeakerBolt speakerBolt = new SpeakerBolt(); builder.setBolt(ComponentType.SPEAKER_BOLT.toString(), speakerBolt, parallelism) .shuffleGrouping(ComponentType.SPEAKER_KAFKA_SPOUT.toString()); /* * Transaction bolt. */ TransactionBolt transactionBolt = new TransactionBolt(); boltSetup = builder.setBolt(ComponentType.TRANSACTION_BOLT.toString(), transactionBolt, parallelism) .fieldsGrouping(ComponentType.TOPOLOGY_ENGINE_BOLT.toString(), StreamType.CREATE.toString(), fieldSwitchId) .fieldsGrouping(ComponentType.TOPOLOGY_ENGINE_BOLT.toString(), StreamType.DELETE.toString(), fieldSwitchId) // (crimi) - whereas this doesn't belong here per se (Response from TE), it looks as though // nobody receives this message // .fieldsGrouping(ComponentType.TOPOLOGY_ENGINE_BOLT.toString(), StreamType.RESPONSE.toString(), fieldSwitchId) // .fieldsGrouping(ComponentType.SPEAKER_BOLT.toString(), StreamType.CREATE.toString(), fieldSwitchId) .fieldsGrouping(ComponentType.SPEAKER_BOLT.toString(), StreamType.DELETE.toString(), fieldSwitchId); ctrlTargets.add(new CtrlBoltRef(ComponentType.TRANSACTION_BOLT.toString(), transactionBolt, boltSetup)); /* * Error processing bolt */ ErrorBolt errorProcessingBolt = new ErrorBolt(); builder.setBolt(ComponentType.ERROR_BOLT.toString(), errorProcessingBolt, parallelism) .shuffleGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.ERROR.toString()) .shuffleGrouping(ComponentType.CRUD_BOLT.toString(), StreamType.ERROR.toString()); /* * Bolt forms Northbound responses */ NorthboundReplyBolt northboundReplyBolt = new NorthboundReplyBolt(); builder.setBolt(ComponentType.NORTHBOUND_REPLY_BOLT.toString(), northboundReplyBolt, parallelism) .shuffleGrouping(ComponentType.CRUD_BOLT.toString(), StreamType.RESPONSE.toString()) .shuffleGrouping(ComponentType.ERROR_BOLT.toString(), StreamType.RESPONSE.toString()); /* * Bolt sends Northbound responses */ KafkaBolt northboundKafkaBolt = createKafkaBolt(config.getKafkaNorthboundTopic()); builder.setBolt(ComponentType.NORTHBOUND_KAFKA_BOLT.toString(), northboundKafkaBolt, parallelism) .shuffleGrouping(ComponentType.NORTHBOUND_REPLY_BOLT.toString(), StreamType.RESPONSE.toString()); createCtrlBranch(builder, ctrlTargets); createHealthCheckHandler(builder, ServiceType.FLOW_TOPOLOGY.getId()); // builder.setBolt( // ComponentType.TOPOLOGY_ENGINE_OUTPUT.toString(), createKafkaBolt(config.getKafkaTopoEngTopic()), 1) // .shuffleGrouping(ComponentType.LCM_FLOW_SYNC_BOLT.toString(), LcmFlowCacheSyncBolt.STREAM_ID_TPE); return builder.createTopology(); } public static void main(String[] args) { try { LaunchEnvironment env = new LaunchEnvironment(args); (new FlowTopology(env)).setup(); } catch (Exception e) { System.exit(handleLaunchException(e)); } } }
services/wfm/src/main/java/org/openkilda/wfm/topology/flow/FlowTopology.java
/* Copyright 2017 Telstra Open Source * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openkilda.wfm.topology.flow; import org.apache.storm.Config; import org.openkilda.messaging.ServiceType; import org.openkilda.messaging.Utils; import org.openkilda.pce.provider.Auth; import org.openkilda.pce.provider.AuthNeo4j; import org.openkilda.wfm.ConfigurationException; import org.openkilda.wfm.CtrlBoltRef; import org.openkilda.wfm.LaunchEnvironment; import org.openkilda.wfm.StreamNameCollisionException; import org.openkilda.wfm.topology.AbstractTopology; import org.openkilda.wfm.topology.flow.bolts.CrudBolt; import org.openkilda.wfm.topology.flow.bolts.ErrorBolt; import org.openkilda.wfm.topology.flow.bolts.LcmFlowCacheSyncBolt; import org.openkilda.wfm.topology.flow.bolts.NorthboundReplyBolt; import org.openkilda.wfm.topology.flow.bolts.SpeakerBolt; import org.openkilda.wfm.topology.flow.bolts.SplitterBolt; import org.openkilda.wfm.topology.flow.bolts.TopologyEngineBolt; import org.openkilda.wfm.topology.flow.bolts.TransactionBolt; import org.openkilda.wfm.topology.utils.LcmKafkaSpout; import org.apache.storm.generated.ComponentObject; import org.apache.storm.generated.StormTopology; import org.apache.storm.kafka.bolt.KafkaBolt; import org.apache.storm.kafka.spout.KafkaSpout; import org.apache.storm.kafka.spout.KafkaSpoutConfig; import org.apache.storm.topology.BoltDeclarer; import org.apache.storm.topology.TopologyBuilder; import org.apache.storm.tuple.Fields; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; /** * Flow topology. */ public class FlowTopology extends AbstractTopology { public static final String SWITCH_ID_FIELD = "switch-id"; public static final String STATUS_FIELD = "status"; public static final String ERROR_TYPE_FIELD = "error-type"; public static final Fields fieldFlowId = new Fields(Utils.FLOW_ID); public static final Fields fieldSwitchId = new Fields(SWITCH_ID_FIELD); public static final Fields fieldsFlowIdStatus = new Fields(Utils.FLOW_ID, STATUS_FIELD); public static final Fields fieldsMessageFlowId = new Fields(MESSAGE_FIELD, Utils.FLOW_ID); public static final Fields fieldsMessageErrorType = new Fields(MESSAGE_FIELD, ERROR_TYPE_FIELD); public static final Fields fieldsMessageSwitchIdFlowIdTransactionId = new Fields(MESSAGE_FIELD, SWITCH_ID_FIELD, Utils.FLOW_ID, Utils.TRANSACTION_ID); private static final Logger logger = LoggerFactory.getLogger(FlowTopology.class); private final Auth pathComputerAuth; public FlowTopology(LaunchEnvironment env) throws ConfigurationException { super(env); pathComputerAuth = new AuthNeo4j(config.getNeo4jHost(), config.getNeo4jLogin(), config.getNeo4jPassword()); logger.debug("Topology built {}: zookeeper={}, kafka={}, parallelism={}, workers={}" + ", neo4j_url{}, neo4j_user{}, neo4j_pswd{}", getTopologyName(), config.getZookeeperHosts(), config.getKafkaHosts(), config.getParallelism(), config.getWorkers(), config.getNeo4jHost(), config.getNeo4jLogin(), config.getNeo4jPassword()); } public FlowTopology(LaunchEnvironment env, Auth pathComputerAuth) throws ConfigurationException { super(env); this.pathComputerAuth = pathComputerAuth; logger.debug("Topology built {}: zookeeper={}, kafka={}, parallelism={}, workers={}", getTopologyName(), config.getZookeeperHosts(), config.getKafkaHosts(), config.getParallelism(), config.getWorkers()); } @Override public StormTopology createTopology() throws StreamNameCollisionException { logger.info("Creating Topology: {}", topologyName); TopologyBuilder builder = new TopologyBuilder(); List<CtrlBoltRef> ctrlTargets = new ArrayList<>(); BoltDeclarer boltSetup; Integer parallelism = config.getParallelism(); KafkaSpoutConfig<String, String> kafkaSpoutConfig; KafkaSpout<String, String> kafkaSpout; // builder.setSpout( // ComponentType.LCM_SPOUT.toString(), // createKafkaSpout(config.getKafkaFlowTopic(), ComponentType.LCM_SPOUT.toString()), 1); // builder.setBolt( // ComponentType.LCM_FLOW_SYNC_BOLT.toString(), // new LcmFlowCacheSyncBolt(ComponentType.NORTHBOUND_KAFKA_SPOUT.toString()), // 1) // .shuffleGrouping(ComponentType.NORTHBOUND_KAFKA_SPOUT.toString(), LcmKafkaSpout.STREAM_ID_LCM) // .shuffleGrouping(ComponentType.LCM_SPOUT.toString()); /* * Spout receives all Northbound requests. */ kafkaSpoutConfig = makeKafkaSpoutConfigBuilder( ComponentType.NORTHBOUND_KAFKA_SPOUT.toString(), config.getKafkaFlowTopic()).build(); // (crimi) - commenting out LcmKafkaSpout here due to dying worker //kafkaSpout = new LcmKafkaSpout<>(kafkaSpoutConfig); kafkaSpout = new KafkaSpout<>(kafkaSpoutConfig); builder.setSpout(ComponentType.NORTHBOUND_KAFKA_SPOUT.toString(), kafkaSpout, parallelism); /* * Bolt splits requests on streams. * It groups requests by flow-id. */ SplitterBolt splitterBolt = new SplitterBolt(); builder.setBolt(ComponentType.SPLITTER_BOLT.toString(), splitterBolt, parallelism) .shuffleGrouping(ComponentType.NORTHBOUND_KAFKA_SPOUT.toString()); /* * Bolt handles flow CRUD operations. * It groups requests by flow-id. */ CrudBolt crudBolt = new CrudBolt(pathComputerAuth); ComponentObject.serialized_java(org.apache.storm.utils.Utils.javaSerialize(pathComputerAuth)); boltSetup = builder.setBolt(ComponentType.CRUD_BOLT.toString(), crudBolt, parallelism) .fieldsGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.CREATE.toString(), fieldFlowId) // TODO: this READ is used for single and for all flows. But all flows shouldn't be fieldsGrouping. .fieldsGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.READ.toString(), fieldFlowId) .fieldsGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.UPDATE.toString(), fieldFlowId) .fieldsGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.DELETE.toString(), fieldFlowId) .fieldsGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.PUSH.toString(), fieldFlowId) .fieldsGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.UNPUSH.toString(), fieldFlowId) .fieldsGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.PATH.toString(), fieldFlowId) .fieldsGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.RESTORE.toString(), fieldFlowId) .fieldsGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.REROUTE.toString(), fieldFlowId) .fieldsGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.STATUS.toString(), fieldFlowId) // TODO: this CACHE_SYNC shouldn't be fields-grouping - there is no field - it should be all - but tackle during multi instance testing .fieldsGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.CACHE_SYNC.toString(), fieldFlowId) .fieldsGrouping(ComponentType.TRANSACTION_BOLT.toString(), StreamType.STATUS.toString(), fieldFlowId) .fieldsGrouping(ComponentType.SPEAKER_BOLT.toString(), StreamType.STATUS.toString(), fieldFlowId) .fieldsGrouping(ComponentType.TOPOLOGY_ENGINE_BOLT.toString(), StreamType.STATUS.toString(), fieldFlowId) // .shuffleGrouping( // ComponentType.LCM_FLOW_SYNC_BOLT.toString(), LcmFlowCacheSyncBolt.STREAM_ID_SYNC_FLOW_CACHE); ctrlTargets.add(new CtrlBoltRef(ComponentType.CRUD_BOLT.toString(), crudBolt, boltSetup)); /* * Bolt sends cache updates. */ KafkaBolt cacheKafkaBolt = createKafkaBolt(config.getKafkaTopoCacheTopic()); builder.setBolt(ComponentType.CACHE_KAFKA_BOLT.toString(), cacheKafkaBolt, parallelism) .shuffleGrouping(ComponentType.CRUD_BOLT.toString(), StreamType.CREATE.toString()) .shuffleGrouping(ComponentType.CRUD_BOLT.toString(), StreamType.UPDATE.toString()) .shuffleGrouping(ComponentType.CRUD_BOLT.toString(), StreamType.DELETE.toString()) .shuffleGrouping(ComponentType.CRUD_BOLT.toString(), StreamType.STATUS.toString()); /* * Spout receives Topology Engine response */ KafkaSpout topologyKafkaSpout = createKafkaSpout( config.getKafkaFlowTopic(), ComponentType.TOPOLOGY_ENGINE_KAFKA_SPOUT.toString()); builder.setSpout(ComponentType.TOPOLOGY_ENGINE_KAFKA_SPOUT.toString(), topologyKafkaSpout, parallelism); /* * Bolt processes Topology Engine responses, groups by flow-id field */ TopologyEngineBolt topologyEngineBolt = new TopologyEngineBolt(); builder.setBolt(ComponentType.TOPOLOGY_ENGINE_BOLT.toString(), topologyEngineBolt, parallelism) .shuffleGrouping(ComponentType.TOPOLOGY_ENGINE_KAFKA_SPOUT.toString()); /* * Bolt sends Speaker requests */ KafkaBolt speakerKafkaBolt = createKafkaBolt(config.getKafkaSpeakerTopic()); builder.setBolt(ComponentType.SPEAKER_KAFKA_BOLT.toString(), speakerKafkaBolt, parallelism) .shuffleGrouping(ComponentType.TRANSACTION_BOLT.toString(), StreamType.CREATE.toString()) .shuffleGrouping(ComponentType.TRANSACTION_BOLT.toString(), StreamType.DELETE.toString()); /* * Spout receives Speaker responses */ KafkaSpout speakerKafkaSpout = createKafkaSpout( config.getKafkaFlowTopic(), ComponentType.SPEAKER_KAFKA_SPOUT.toString()); builder.setSpout(ComponentType.SPEAKER_KAFKA_SPOUT.toString(), speakerKafkaSpout, parallelism); /* * Bolt processes Speaker responses, groups by flow-id field */ SpeakerBolt speakerBolt = new SpeakerBolt(); builder.setBolt(ComponentType.SPEAKER_BOLT.toString(), speakerBolt, parallelism) .shuffleGrouping(ComponentType.SPEAKER_KAFKA_SPOUT.toString()); /* * Transaction bolt. */ TransactionBolt transactionBolt = new TransactionBolt(); boltSetup = builder.setBolt(ComponentType.TRANSACTION_BOLT.toString(), transactionBolt, parallelism) .fieldsGrouping(ComponentType.TOPOLOGY_ENGINE_BOLT.toString(), StreamType.CREATE.toString(), fieldSwitchId) .fieldsGrouping(ComponentType.TOPOLOGY_ENGINE_BOLT.toString(), StreamType.DELETE.toString(), fieldSwitchId) // (crimi) - whereas this doesn't belong here per se (Response from TE), it looks as though // nobody receives this message // .fieldsGrouping(ComponentType.TOPOLOGY_ENGINE_BOLT.toString(), StreamType.RESPONSE.toString(), fieldSwitchId) // .fieldsGrouping(ComponentType.SPEAKER_BOLT.toString(), StreamType.CREATE.toString(), fieldSwitchId) .fieldsGrouping(ComponentType.SPEAKER_BOLT.toString(), StreamType.DELETE.toString(), fieldSwitchId); ctrlTargets.add(new CtrlBoltRef(ComponentType.TRANSACTION_BOLT.toString(), transactionBolt, boltSetup)); /* * Error processing bolt */ ErrorBolt errorProcessingBolt = new ErrorBolt(); builder.setBolt(ComponentType.ERROR_BOLT.toString(), errorProcessingBolt, parallelism) .shuffleGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.ERROR.toString()) .shuffleGrouping(ComponentType.CRUD_BOLT.toString(), StreamType.ERROR.toString()); /* * Bolt forms Northbound responses */ NorthboundReplyBolt northboundReplyBolt = new NorthboundReplyBolt(); builder.setBolt(ComponentType.NORTHBOUND_REPLY_BOLT.toString(), northboundReplyBolt, parallelism) .shuffleGrouping(ComponentType.CRUD_BOLT.toString(), StreamType.RESPONSE.toString()) .shuffleGrouping(ComponentType.ERROR_BOLT.toString(), StreamType.RESPONSE.toString()); /* * Bolt sends Northbound responses */ KafkaBolt northboundKafkaBolt = createKafkaBolt(config.getKafkaNorthboundTopic()); builder.setBolt(ComponentType.NORTHBOUND_KAFKA_BOLT.toString(), northboundKafkaBolt, parallelism) .shuffleGrouping(ComponentType.NORTHBOUND_REPLY_BOLT.toString(), StreamType.RESPONSE.toString()); createCtrlBranch(builder, ctrlTargets); createHealthCheckHandler(builder, ServiceType.FLOW_TOPOLOGY.getId()); // builder.setBolt( // ComponentType.TOPOLOGY_ENGINE_OUTPUT.toString(), createKafkaBolt(config.getKafkaTopoEngTopic()), 1) // .shuffleGrouping(ComponentType.LCM_FLOW_SYNC_BOLT.toString(), LcmFlowCacheSyncBolt.STREAM_ID_TPE); return builder.createTopology(); } public static void main(String[] args) { try { LaunchEnvironment env = new LaunchEnvironment(args); (new FlowTopology(env)).setup(); } catch (Exception e) { System.exit(handleLaunchException(e)); } } }
Add missing ;
services/wfm/src/main/java/org/openkilda/wfm/topology/flow/FlowTopology.java
Add missing ;
<ide><path>ervices/wfm/src/main/java/org/openkilda/wfm/topology/flow/FlowTopology.java <ide> .fieldsGrouping(ComponentType.SPLITTER_BOLT.toString(), StreamType.CACHE_SYNC.toString(), fieldFlowId) <ide> .fieldsGrouping(ComponentType.TRANSACTION_BOLT.toString(), StreamType.STATUS.toString(), fieldFlowId) <ide> .fieldsGrouping(ComponentType.SPEAKER_BOLT.toString(), StreamType.STATUS.toString(), fieldFlowId) <del> .fieldsGrouping(ComponentType.TOPOLOGY_ENGINE_BOLT.toString(), StreamType.STATUS.toString(), fieldFlowId) <add> .fieldsGrouping(ComponentType.TOPOLOGY_ENGINE_BOLT.toString(), StreamType.STATUS.toString(), fieldFlowId); <ide> // .shuffleGrouping( <ide> // ComponentType.LCM_FLOW_SYNC_BOLT.toString(), LcmFlowCacheSyncBolt.STREAM_ID_SYNC_FLOW_CACHE); <ide> ctrlTargets.add(new CtrlBoltRef(ComponentType.CRUD_BOLT.toString(), crudBolt, boltSetup));
Java
apache-2.0
eb292a8384dfacdc21b5fe758ef629a5cf111f9f
0
internetisalie/lua-for-idea,internetisalie/lua-for-idea,internetisalie/lua-for-idea,internetisalie/lua-for-idea
/* * Copyright 2010 Jon S Akhtar (Sylvanaar) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sylvanaar.idea.Lua.lang.parser.kahlua; import com.intellij.lang.ASTNode; import com.intellij.lang.PsiBuilder; import com.intellij.lang.PsiParser; import com.intellij.openapi.diagnostic.Logger; import com.intellij.psi.tree.IElementType; import com.sylvanaar.idea.Lua.lang.parser.LuaElementTypes; import com.sylvanaar.idea.Lua.lang.parser.LuaPsiBuilder; import org.jetbrains.annotations.NotNull; import se.krka.kahlua.vm.Prototype; import java.io.IOException; import java.io.Reader; public class KahluaParser implements PsiParser, LuaElementTypes { public int nCcalls = 0; static Logger log = Logger.getInstance("#Lua.parser.KahluaParser"); protected static final String RESERVED_LOCAL_VAR_FOR_CONTROL = "(for control)"; protected static final String RESERVED_LOCAL_VAR_FOR_STATE = "(for state)"; protected static final String RESERVED_LOCAL_VAR_FOR_GENERATOR = "(for generator)"; protected static final String RESERVED_LOCAL_VAR_FOR_STEP = "(for step)"; protected static final String RESERVED_LOCAL_VAR_FOR_LIMIT = "(for limit)"; protected static final String RESERVED_LOCAL_VAR_FOR_INDEX = "(for index)"; // // keywords array // protected static final String[] RESERVED_LOCAL_VAR_KEYWORDS = new String[]{ // RESERVED_LOCAL_VAR_FOR_CONTROL, // RESERVED_LOCAL_VAR_FOR_GENERATOR, // RESERVED_LOCAL_VAR_FOR_INDEX, // RESERVED_LOCAL_VAR_FOR_LIMIT, // RESERVED_LOCAL_VAR_FOR_STATE, // RESERVED_LOCAL_VAR_FOR_STEP // }; // private static final Hashtable<String, Boolean> RESERVED_LOCAL_VAR_KEYWORDS_TABLE = // new Hashtable<String, Boolean>(); // // static { // int i = 0; // while (i < RESERVED_LOCAL_VAR_KEYWORDS.length) { // String RESERVED_LOCAL_VAR_KEYWORD = RESERVED_LOCAL_VAR_KEYWORDS[i]; // RESERVED_LOCAL_VAR_KEYWORDS_TABLE.put(RESERVED_LOCAL_VAR_KEYWORD, Boolean.TRUE); // i++; // } // } private static final int EOZ = (-1); //private static final int MAXSRC = 80; private static final int MAX_INT = Integer.MAX_VALUE - 2; //private static final int UCHAR_MAX = 255; // TO DO, convert to unicode CHAR_MAX? private static final int LUAI_MAXCCALLS = 200; private LuaPsiBuilder builder = null; // public KahluaParser(Project project) { // } private static String LUA_QS(String s) { return "'" + s + "'"; } private static String LUA_QL(Object o) { return LUA_QS(String.valueOf(o)); } // public static boolean isReservedKeyword(String varName) { // return RESERVED_LOCAL_VAR_KEYWORDS_TABLE.containsKey(varName); // } /* ** Marks the end of a patch list. It is an invalid value both as an absolute ** address, and as a list link (would link an element to itself). */ static final int NO_JUMP = (-1); /* ** grep "ORDER OPR" if you change these enums */ static final int OPR_ADD = 0, OPR_SUB = 1, OPR_MUL = 2, OPR_DIV = 3, OPR_MOD = 4, OPR_POW = 5, OPR_CONCAT = 6, OPR_NE = 7, OPR_EQ = 8, OPR_LT = 9, OPR_LE = 10, OPR_GT = 11, OPR_GE = 12, OPR_AND = 13, OPR_OR = 14, OPR_NOBINOPR = 15; static final int OPR_MINUS = 0, OPR_NOT = 1, OPR_LEN = 2, OPR_NOUNOPR = 3; /* exp kind */ static final int VVOID = 0, /* no value */ VNIL = 1, VTRUE = 2, VFALSE = 3, VK = 4, /* info = index of constant in `k' */ VKNUM = 5, /* nval = numerical value */ VLOCAL = 6, /* info = local register */ VUPVAL = 7, /* info = index of upvalue in `upvalues' */ VGLOBAL = 8, /* info = index of table, aux = index of global name in `k' */ VINDEXED = 9, /* info = table register, aux = index register (or `k') */ VJMP = 10, /* info = instruction pc */ VRELOCABLE = 11, /* info = instruction pc */ VNONRELOC = 12, /* info = result register */ VCALL = 13, /* info = instruction pc */ VVARARG = 14; /* info = instruction pc */ int current = 0; /* current character (charint) */ int linenumber = 0; /* input line counter */ int lastline = 0; /* line of last token `consumed' */ IElementType t = null; /* current token */ IElementType lookahead = null; /* look ahead token */ FuncState fs = null; /* `FuncState' is private to the parser */ Reader z = null; /* input stream */ byte[] buff = null; /* buffer for tokens */ int nbuff = 0; /* length of buffer */ String source = null; /* current source name */ public KahluaParser(Reader stream, int firstByte, String source) { this.z = stream; this.buff = new byte[32]; this.lookahead = null; /* no look-ahead token */ this.fs = null; this.linenumber = 1; this.lastline = 1; this.source = source; this.nbuff = 0; /* initialize buffer */ this.current = firstByte; /* read first char */ this.skipShebang(); } public KahluaParser() {}; void nextChar() { try { current = z.read(); } catch (IOException e) { e.printStackTrace(); current = EOZ; } } boolean currIsNewline() { return current == '\n' || current == '\r'; } void lexerror(String msg, IElementType token) { String cid = source; String errorMessage; if (token != null) { errorMessage = /*cid + ":" + linenumber + ": " +*/ msg + " near `" + token + "`"; } else { errorMessage = /*cid + ":" + linenumber + ": " +*/ msg; } builder.error(errorMessage); //throw new KahluaException(errorMessage); } // private static String trim(String s, int max) { // if (s.length() > max) { // return s.substring(0, max - 3) + "..."; // } // return s; // } void syntaxerror(String msg) { lexerror(msg, t); } private void skipShebang() { if (current == '#') while (!currIsNewline() && current != EOZ) nextChar(); } /* ** ======================================================= ** LEXICAL ANALYZER ** ======================================================= */ void next() { lastline = linenumber; builder.advanceLexer(); t = builder.getTokenType(); // /* // if (lookahead != TK_EOS) { /* is there a look-ahead token? */ // t.set( lookahead ); /* use this one */ // lookahead = TK_EOS; /* and discharge it */ // } else // t = llex(t); /* read next token */ // */ } void lookahead() { // FuncState._assert (lookahead == TK_EOS); PsiBuilder.Marker current = builder.mark(); builder.advanceLexer(); lookahead = builder.getTokenType(); current.rollbackTo(); } // ============================================================= // from lcode.h // ============================================================= // ============================================================= // from lparser.c // ============================================================= boolean hasmultret(int k) { return ((k) == VCALL || (k) == VVARARG); } /*---------------------------------------------------------------------- name args description ------------------------------------------------------------------------*/ /* * * prototypes for recursive non-terminal functions */ void error_expected(IElementType token) { syntaxerror(token.toString() + " expected"); } boolean testnext(IElementType c) { if (t == c) { next(); return true; } return false; } void check(IElementType c) { if (t != c) error_expected(c); } void checknext(IElementType c) { check(c); next(); } void check_condition(boolean c, String msg) { if (!(c)) syntaxerror(msg); } void check_match(IElementType what, IElementType who, int where) { if (!testnext(what)) { if (where == linenumber) error_expected(what); else { syntaxerror(what + " expected " + "(to close " + who.toString() + " at line " + where + ")"); } } } String str_checkname() { String ts; check(NAME); ts = builder.text(); next(); return ts; } void codestring(ExpDesc e, String s) { e.init(VK, fs.stringK(s)); } void checkname(ExpDesc e) { codestring(e, str_checkname()); } int registerlocalvar(String varname) { FuncState fs = this.fs; if (fs.locvars == null || fs.nlocvars + 1 > fs.locvars.length) fs.locvars = FuncState.realloc(fs.locvars, fs.nlocvars * 2 + 1); fs.locvars[fs.nlocvars] = varname; return fs.nlocvars++; } // // #define new_localvarliteral(ls,v,n) \ // this.new_localvar(luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char))-1), n) // void new_localvarliteral(String v, int n) { new_localvar(v, n); } void new_localvar(String name, int n) { FuncState fs = this.fs; fs.checklimit(fs.nactvar + n + 1, FuncState.LUAI_MAXVARS, "local variables"); fs.actvar[fs.nactvar + n] = (short) registerlocalvar(name); } void adjustlocalvars(int nvars) { FuncState fs = this.fs; fs.nactvar = (fs.nactvar + nvars); } void removevars(int tolevel) { FuncState fs = this.fs; fs.nactvar = tolevel; } void singlevar(ExpDesc var) { PsiBuilder.Marker ref = builder.mark(); PsiBuilder.Marker mark = builder.mark(); String varname = this.str_checkname(); FuncState fs = this.fs; if (fs.singlevaraux(varname, var, 1) == VGLOBAL) { var.info = fs.stringK(varname); /* info points to global name */ mark.done(GLOBAL_NAME); } else { mark.done(LOCAL_NAME); } ref.done(REFERENCE); } void adjust_assign(int nvars, int nexps, ExpDesc e) { FuncState fs = this.fs; int extra = nvars - nexps; if (hasmultret(e.k)) { /* includes call itself */ extra++; if (extra < 0) extra = 0; /* last exp. provides the difference */ fs.setreturns(e, extra); if (extra > 1) fs.reserveregs(extra - 1); } else { /* close last expression */ if (e.k != VVOID) fs.exp2nextreg(e); if (extra > 0) { int reg = fs.freereg; fs.reserveregs(extra); fs.nil(reg, extra); } } } void enterlevel() { if (++nCcalls > LUAI_MAXCCALLS) lexerror("chunk has too many syntax levels", EMPTY_INPUT); } void leavelevel() { nCcalls--; } void pushclosure(FuncState func, ExpDesc v) { FuncState fs = this.fs; Prototype f = fs.f; if (f.prototypes == null || fs.np + 1 > f.prototypes.length) f.prototypes = FuncState.realloc(f.prototypes, fs.np * 2 + 1); f.prototypes[fs.np++] = func.f; v.init(VRELOCABLE, fs.codeABx(FuncState.OP_CLOSURE, 0, fs.np - 1)); for (int i = 0; i < func.f.numUpvalues; i++) { int o = (func.upvalues_k[i] == VLOCAL) ? FuncState.OP_MOVE : FuncState.OP_GETUPVAL; fs.codeABC(o, 0, func.upvalues_info[i], 0); } } void close_func() { FuncState fs = this.fs; Prototype f = fs.f; f.isVararg = fs.isVararg != 0; this.removevars(0); fs.ret(0, 0); /* final return */ f.code = FuncState.realloc(f.code, fs.pc); f.lines = FuncState.realloc(f.lines, fs.pc); // f.sizelineinfo = fs.pc; f.constants = FuncState.realloc(f.constants, fs.nk); f.prototypes = FuncState.realloc(f.prototypes, fs.np); fs.locvars = FuncState.realloc(fs.locvars, fs.nlocvars); // f.sizelocvars = fs.nlocvars; fs.upvalues = FuncState.realloc(fs.upvalues, f.numUpvalues); // FuncState._assert (CheckCode.checkcode(f)); FuncState._assert(fs.bl == null); this.fs = fs.prev; // L.top -= 2; /* remove table and prototype from the stack */ // /* last token read was anchored in defunct function; must reanchor it // */ // if (fs!=null) ls.anchor_token(); } /*============================================================*/ /* GRAMMAR RULES */ /*============================================================*/ void field(ExpDesc v, PsiBuilder.Marker ref) { /* field -> ['.' | ':'] NAME */ FuncState fs = this.fs; ExpDesc key = new ExpDesc(); fs.exp2anyreg(v); this.next(); /* skip the dot or colon */ PsiBuilder.Marker mark = builder.mark(); this.checkname(key); mark.done(FIELD_NAME); fs.indexed(v, key); } void yindex(ExpDesc v) { /* index -> '[' expr ']' */ this.next(); /* skip the '[' */ PsiBuilder.Marker mark = builder.mark(); this.expr(v); mark.done(TABLE_INDEX); this.fs.exp2val(v); this.checknext(RBRACK); } /* ** {====================================================================== ** Rules for Constructors ** ======================================================================= */ void recfield(ConsControl cc) { /* recfield -> (NAME | `['exp1`]') = exp1 */ FuncState fs = this.fs; int reg = this.fs.freereg; ExpDesc key = new ExpDesc(); ExpDesc val = new ExpDesc(); int rkkey; if (this.t == NAME) { fs.checklimit(cc.nh, MAX_INT, "items in a constructor"); this.checkname(key); } else /* this.t == '[' */ this.yindex(key); cc.nh++; this.checknext(ASSIGN); rkkey = fs.exp2RK(key); this.expr(val); fs.codeABC(FuncState.OP_SETTABLE, cc.t.info, rkkey, fs.exp2RK(val)); fs.freereg = reg; /* free registers */ } void listfield(ConsControl cc) { this.expr(cc.v); fs.checklimit(cc.na, MAX_INT, "items in a constructor"); cc.na++; cc.tostore++; } void constructor(ExpDesc t) { PsiBuilder.Marker mark = builder.mark(); /* constructor -> ?? */ FuncState fs = this.fs; int line = this.linenumber; int pc = fs.codeABC(FuncState.OP_NEWTABLE, 0, 0, 0); ConsControl cc = new ConsControl(); cc.na = cc.nh = cc.tostore = 0; cc.t = t; t.init(VRELOCABLE, pc); cc.v.init(VVOID, 0); /* no value (yet) */ fs.exp2nextreg(t); /* fix it at stack top (for gc) */ this.checknext(LCURLY); do { FuncState._assert(cc.v.k == VVOID || cc.tostore > 0); if (this.t == RCURLY) break; fs.closelistfield(cc); if (this.t == NAME) { /* may be listfields or recfields */ this.lookahead(); if (this.lookahead != ASSIGN) /* expression? */ this.listfield(cc); else this.recfield(cc); // break; } else if (this.t == LBRACK) { /* constructor_item -> recfield */ this.recfield(cc); // break; } else { /* constructor_part -> listfield */ this.listfield(cc); // break; } } while (this.testnext(COMMA) || this.testnext(SEMI)); this.check_match(RCURLY, LCURLY, line); fs.lastlistfield(cc); InstructionPtr i = new InstructionPtr(fs.f.code, pc); FuncState.SETARG_B(i, luaO_int2fb(cc.na)); /* set initial array size */ FuncState.SETARG_C(i, luaO_int2fb(cc.nh)); /* set initial table size */ mark.done(TABLE_CONSTUCTOR); } /* ** converts an integer to a "floating point byte", represented as ** (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if ** eeeee != 0 and (xxx) otherwise. */ static int luaO_int2fb(int x) { int e = 0; /* expoent */ while (x >= 16) { x = (x + 1) >> 1; e++; } if (x < 8) return x; else return ((e + 1) << 3) | (x - 8); } /* }====================================================================== */ void parlist() { //log.info(">>> parlist"); /* parlist -> [ param { `,' param } ] */ FuncState fs = this.fs; Prototype f = fs.f; int nparams = 0; fs.isVararg = 0; if (this.t != RPAREN) { /* is `parlist' not empty? */ do { PsiBuilder.Marker parm = builder.mark(); if (this.t == NAME) { /* param . NAME */ PsiBuilder.Marker mark = builder.mark(); String name = this.str_checkname(); mark.done(LOCAL_NAME); this.new_localvar(name, nparams++); parm.done(PARAMETER); // break; } else if (this.t == ELLIPSIS) { /* param . `...' */ this.next(); parm.done(PARAMETER); fs.isVararg |= FuncState.VARARG_ISVARARG; // break; } else { parm.drop(); this.syntaxerror("<name> or " + LUA_QL("...") + " expected"); } } while ((fs.isVararg == 0) && this.testnext(COMMA)); } this.adjustlocalvars(nparams); f.numParams = (fs.nactvar - (fs.isVararg & FuncState.VARARG_HASARG)); fs.reserveregs(fs.nactvar); /* reserve register for parameters */ //log.info("<<< parlist"); } void body(ExpDesc e, boolean needself, int line) { /* body -> `(' parlist `)' chunk END */ FuncState new_fs = new FuncState(this); new_fs.linedefined = line; this.checknext(LPAREN); if (needself) { new_localvarliteral("self", 0); adjustlocalvars(1); } PsiBuilder.Marker mark = builder.mark(); this.parlist(); mark.done(LuaElementTypes.PARAMETER_LIST); this.checknext(RPAREN); mark = builder.mark(); this.chunk(); mark.done(BLOCK); new_fs.lastlinedefined = this.linenumber; this.check_match(END, FUNCTION, line); this.close_func(); this.pushclosure(new_fs, e); } int explist1(ExpDesc v) { PsiBuilder.Marker mark = builder.mark(); /* explist1 -> expr { `,' expr } */ int n = 1; /* at least one expression */ this.expr(v); while (this.testnext(COMMA)) { fs.exp2nextreg(v); this.expr(v); n++; } mark.done(EXPR_LIST); return n; } void funcargs(ExpDesc f) { PsiBuilder.Marker mark = builder.mark(); FuncState fs = this.fs; ExpDesc args = new ExpDesc(); int base, nparams; int line = this.linenumber; if (this.t == LPAREN) { /* funcargs -> `(' [ explist1 ] `)' */ if (line != this.lastline) this.syntaxerror("ambiguous syntax (function call x new statement)"); this.next(); if (this.t == RPAREN) /* arg list is empty? */ args.k = VVOID; else { this.explist1(args); fs.setmultret(args); } this.check_match(RPAREN, LPAREN, line); // break; } else if (this.t == LCURLY) { /* funcargs -> constructor */ this.constructor(args); } else if (this.t == STRING || this.t == LONGSTRING) { /* funcargs -> STRING */ this.codestring(args, builder.text()); this.next(); /* must use `seminfo' before `next' */ } else { this.syntaxerror("function arguments expected"); } FuncState._assert(f.k == VNONRELOC); base = f.info; /* base register for call */ if (hasmultret(args.k)) nparams = FuncState.LUA_MULTRET; /* open call */ else { if (args.k != VVOID) fs.exp2nextreg(args); /* close last argument */ nparams = fs.freereg - (base + 1); } f.init(VCALL, fs.codeABC(FuncState.OP_CALL, base, nparams + 1, 2)); fs.fixline(line); fs.freereg = base + 1; /* call remove function and arguments and leaves * (unless changed) one result */ mark.done(FUNCTION_CALL_ARGS); } /* ** {====================================================================== ** Expression parsing ** ======================================================================= */ void prefixexp(ExpDesc v) { /* prefixexp -> NAME | '(' expr ')' */ if (this.t == LPAREN) { int line = this.linenumber; this.next(); this.expr(v); this.check_match(RPAREN, LPAREN, line); fs.dischargevars(v); return; } else if (this.t == NAME) { this.singlevar(v); return; } this.syntaxerror("unexpected symbol in prefix expression"); } void primaryexp(ExpDesc v) { /* * primaryexp -> prefixexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | * funcargs } */ PsiBuilder.Marker mark = builder.mark(); // PsiBuilder.Marker ref = builder.mark(); // PsiBuilder.Marker tmp = ref; FuncState fs = this.fs; this.prefixexp(v); for (; ;) { if (this.t == DOT) { /* field */ this.field(v, mark); // if (tmp != null) { // ref = ref.precede(); // tmp.done(REFERENCE); // tmp = ref; // } // break; } else if (this.t == LBRACK) { /* `[' exp1 `]' */ ExpDesc key = new ExpDesc(); fs.exp2anyreg(v); this.yindex(key); // if (tmp != null) { // ref = ref.precede(); // tmp.done(REFERENCE); // tmp = ref; // } fs.indexed(v, key); // break; } else if (this.t == COLON) { /* `:' NAME funcargs */ ExpDesc key = new ExpDesc(); this.next(); this.checkname(key); // // ref = ref.precede(); // if (tmp != null) // tmp.done(REFERENCE); // tmp = null; PsiBuilder.Marker call = null; if (mark != null) { call = mark.precede(); mark.done(FUNCTION_IDENTIFIER_NEEDSELF); mark = null; } fs.self(v, key); this.funcargs(v); if (call != null) call.done(FUNCTION_CALL_EXPR); // break; } else if (this.t == LPAREN || this.t == STRING || this.t == LONGSTRING || this.t == LCURLY) { /* funcargs */ fs.exp2nextreg(v); // if (tmp != null) { // tmp.drop(); tmp = null; // } PsiBuilder.Marker call = null; if (mark != null) { call = mark.precede(); mark.done(FUNCTION_IDENTIFIER); mark = null; } this.funcargs(v); if (call != null) call.done(FUNCTION_CALL_EXPR); // break; } else { // if (tmp != null) // tmp.drop(); if (mark != null) mark.done(VARIABLE); return; } } } void simpleexp(ExpDesc v) { /* * simpleexp -> NUMBER | STRING | NIL | true | false | ... | constructor | * FUNCTION body | primaryexp */ PsiBuilder.Marker mark = builder.mark(); try { if (this.t == NUMBER) { v.init(VKNUM, 0); v.setNval(0); // TODO } else if (this.t == STRING || this.t == LONGSTRING) { this.codestring(v, builder.text()); //TODO } else if (this.t == NIL) { v.init(VNIL, 0); } else if (this.t == TRUE) { v.init(VTRUE, 0); } else if (this.t == FALSE) { v.init(VFALSE, 0); } else if (this.t == ELLIPSIS) { /* vararg */ FuncState fs = this.fs; this.check_condition(fs.isVararg != 0, "cannot use " + LUA_QL("...") + " outside a vararg function"); fs.isVararg &= ~FuncState.VARARG_NEEDSARG; /* don't need 'arg' */ v.init(VVARARG, fs.codeABC(FuncState.OP_VARARG, 0, 1, 0)); } else if (this.t == LCURLY) { /* constructor */ this.constructor(v); return; } else if (this.t == FUNCTION) { this.next(); PsiBuilder.Marker funcStmt = builder.mark(); this.body(v, false, this.linenumber); funcStmt.done(ANONYMOUS_FUNCTION_EXPRESSION); return; } else { this.primaryexp(v); return; } this.next(); mark.done(LITERAL_EXPRESSION); mark = null; } finally { if (mark != null) mark.drop(); } } int getunopr(IElementType op) { if (op == NOT) return OPR_NOT; if (op == MINUS) return OPR_MINUS; if (op == GETN) return OPR_LEN; return OPR_NOUNOPR; } int getbinopr(IElementType op) { if (op == PLUS) return OPR_ADD; if (op == MINUS) return OPR_SUB; if (op == MULT) return OPR_MUL; if (op == DIV) return OPR_DIV; if (op == MOD) return OPR_MOD; if (op == EXP) return OPR_POW; if (op == CONCAT) return OPR_CONCAT; if (op == NE) return OPR_NE; if (op == EQ) return OPR_EQ; if (op == LT) return OPR_LT; if (op == LE) return OPR_LE; if (op == GT) return OPR_GT; if (op == GE) return OPR_GE; if (op == AND) return OPR_AND; if (op == OR) return OPR_OR; return OPR_NOBINOPR; } static final int[] priorityLeft = { 6, 6, 7, 7, 7, /* `+' `-' `/' `%' */ 10, 5, /* power and concat (right associative) */ 3, 3, /* equality and inequality */ 3, 3, 3, 3, /* order */ 2, 1, /* logical (and/or) */ }; static final int[] priorityRight = { /* ORDER OPR */ 6, 6, 7, 7, 7, /* `+' `-' `/' `%' */ 9, 4, /* power and concat (right associative) */ 3, 3, /* equality and inequality */ 3, 3, 3, 3, /* order */ 2, 1 /* logical (and/or) */ }; static final int UNARY_PRIORITY = 8; /* priority for unary operators */ /* ** subexpr -> (simpleexp | unop subexpr) { binop subexpr } ** where `binop' is any binary operator with a priority higher than `limit' */ int subexpr(ExpDesc v, int limit) { int op; int uop; PsiBuilder.Marker mark = builder.mark(); PsiBuilder.Marker oper; this.enterlevel(); uop = getunopr(this.t); if (uop != OPR_NOUNOPR) { PsiBuilder.Marker mark2 = builder.mark(); oper = builder.mark(); this.next(); oper.done(UNARY_OP); this.subexpr(v, UNARY_PRIORITY); mark2.done(UNARY_EXP); fs.prefix(uop, v); } else { this.simpleexp(v); } /* expand while operators have priorities higher than `limit' */ op = getbinopr(this.t); while (op != OPR_NOBINOPR && priorityLeft[op] > limit) { ExpDesc v2 = new ExpDesc(); int nextop; oper = builder.mark(); this.next(); oper.done(BINARY_OP); fs.infix(op, v); /* read sub-expression with higher priority */ nextop = this.subexpr(v2, priorityRight[op]); fs.posfix(op, v, v2); op = nextop; mark.done(BINARY_EXP); mark = mark.precede(); } mark.drop(); this.leavelevel(); return op; /* return first untreated operator */ } void expr(ExpDesc v) { PsiBuilder.Marker mark = builder.mark(); this.subexpr(v, 0); mark.done(EXPR); // next(); } /* }==================================================================== */ /* ** {====================================================================== ** Rules for Statements ** ======================================================================= */ boolean block_follow(IElementType token) { return token == ELSE || token == ELSEIF || token == END || token == UNTIL || token == null; } void block() { PsiBuilder.Marker mark = builder.mark(); /* block -> chunk */ FuncState fs = this.fs; BlockCnt bl = new BlockCnt(); fs.enterblock(bl, false); this.chunk(); FuncState._assert(bl.breaklist == NO_JUMP); fs.leaveblock(); mark.done(BLOCK); } /* ** check whether, in an assignment to a local variable, the local variable ** is needed in a previous assignment (to a table). If so, save original ** local value in a safe place and use this safe copy in the previous ** assignment. */ void check_conflict(LHS_assign lh, ExpDesc v) { FuncState fs = this.fs; int extra = fs.freereg; /* eventual position to save local variable */ boolean conflict = false; for (; lh != null; lh = lh.prev) { if (lh.v.k == VINDEXED) { if (lh.v.info == v.info) { /* conflict? */ conflict = true; lh.v.info = extra; /* previous assignment will use safe copy */ } if (lh.v.aux == v.info) { /* conflict? */ conflict = true; lh.v.aux = extra; /* previous assignment will use safe copy */ } } } if (conflict) { fs.codeABC(FuncState.OP_MOVE, fs.freereg, v.info, 0); /* make copy */ fs.reserveregs(1); } } void assignment(LHS_assign lh, int nvars, PsiBuilder.Marker expr) { // PsiBuilder.Marker mark = builder.mark(); ExpDesc e = new ExpDesc(); this.check_condition(VLOCAL <= lh.v.k && lh.v.k <= VINDEXED, "syntax error"); if (this.testnext(COMMA)) { /* assignment -> `,' primaryexp assignment */ LHS_assign nv = new LHS_assign(); nv.prev = lh; this.primaryexp(nv.v); if (nv.v.k == VLOCAL) this.check_conflict(lh, nv.v); this.assignment(nv, nvars + 1, expr); } else { /* assignment . `=' explist1 */ int nexps; expr.done(IDENTIFIER_LIST); this.checknext(ASSIGN); nexps = this.explist1(e); if (nexps != nvars) { this.adjust_assign(nvars, nexps, e); if (nexps > nvars) this.fs.freereg -= nexps - nvars; /* remove extra values */ } else { fs.setoneret(e); /* close last expression */ fs.storevar(lh.v, e); // mark.done(ASSIGN_STMT); return; /* avoid default */ } } e.init(VNONRELOC, this.fs.freereg - 1); /* default assignment */ fs.storevar(lh.v, e); // mark.done(ASSIGN_STMT); } int cond() { PsiBuilder.Marker mark = builder.mark(); /* cond -> exp */ ExpDesc v = new ExpDesc(); /* read condition */ this.expr(v); /* `falses' are all equal here */ if (v.k == VNIL) v.k = VFALSE; fs.goiftrue(v); mark.done(CONDITIONAL_EXPR); return v.f; } void breakstat() { FuncState fs = this.fs; BlockCnt bl = fs.bl; boolean upval = false; while (bl != null && !bl.isbreakable) { upval |= bl.upval; bl = bl.previous; } if (bl == null) { this.syntaxerror("no loop to break"); } else { if (upval) fs.codeABC(FuncState.OP_CLOSE, bl.nactvar, 0, 0); bl.breaklist = fs.concat(bl.breaklist, fs.jump()); } } void whilestat(int line) { PsiBuilder.Marker mark = builder.mark(); /* whilestat -> WHILE cond DO block END */ FuncState fs = this.fs; int whileinit; int condexit; BlockCnt bl = new BlockCnt(); this.next(); /* skip WHILE */ whileinit = fs.getlabel(); condexit = this.cond(); fs.enterblock(bl, true); this.checknext(DO); this.block(); fs.patchlist(fs.jump(), whileinit); this.check_match(END, WHILE, line); fs.leaveblock(); fs.patchtohere(condexit); /* false conditions finish the loop */ mark.done(WHILE_BLOCK); } void repeatstat(int line) { PsiBuilder.Marker mark = builder.mark(); /* repeatstat -> REPEAT block UNTIL cond */ int condexit; FuncState fs = this.fs; int repeat_init = fs.getlabel(); BlockCnt bl1 = new BlockCnt(); BlockCnt bl2 = new BlockCnt(); fs.enterblock(bl1, true); /* loop block */ fs.enterblock(bl2, false); /* scope block */ this.next(); /* skip REPEAT */ this.chunk(); this.check_match(UNTIL, REPEAT, line); condexit = this.cond(); /* read condition (inside scope block) */ if (!bl2.upval) { /* no upvalues? */ fs.leaveblock(); /* finish scope */ fs.patchlist(condexit, repeat_init); /* close the loop */ } else { /* complete semantics when there are upvalues */ this.breakstat(); /* if condition then break */ fs.patchtohere(condexit); /* else... */ fs.leaveblock(); /* finish scope... */ fs.patchlist(fs.jump(), repeat_init); /* and repeat */ } fs.leaveblock(); /* finish loop */ mark.done(BLOCK); } int exp1() { ExpDesc e = new ExpDesc(); int k; this.expr(e); k = e.k; fs.exp2nextreg(e); return k; } void forbody(int base, int line, int nvars, boolean isnum) { /* forbody -> DO block */ BlockCnt bl = new BlockCnt(); FuncState fs = this.fs; int prep, endfor; this.adjustlocalvars(3); /* control variables */ this.checknext(DO); prep = isnum ? fs.codeAsBx(FuncState.OP_FORPREP, base, NO_JUMP) : fs.jump(); fs.enterblock(bl, false); /* scope for declared variables */ this.adjustlocalvars(nvars); fs.reserveregs(nvars); this.block(); fs.leaveblock(); /* end of scope for declared variables */ fs.patchtohere(prep); endfor = (isnum) ? fs.codeAsBx(FuncState.OP_FORLOOP, base, NO_JUMP) : fs .codeABC(FuncState.OP_TFORLOOP, base, 0, nvars); fs.fixline(line); /* pretend that `Lua.OP_FOR' starts the loop */ fs.patchlist((isnum ? endfor : fs.jump()), prep + 1); } void fornum(String varname, int line) { /* fornum -> NAME = exp1,exp1[,exp1] forbody */ FuncState fs = this.fs; int base = fs.freereg; this.new_localvarliteral(RESERVED_LOCAL_VAR_FOR_INDEX, 0); this.new_localvarliteral(RESERVED_LOCAL_VAR_FOR_LIMIT, 1); this.new_localvarliteral(RESERVED_LOCAL_VAR_FOR_STEP, 2); this.new_localvar(varname, 3); this.checknext(ASSIGN); this.exp1(); /* initial value */ this.checknext(COMMA); this.exp1(); /* limit */ if (this.testnext(COMMA)) this.exp1(); /* optional step */ else { /* default step = 1 */ fs.codeABx(FuncState.OP_LOADK, fs.freereg, fs.numberK(1)); fs.reserveregs(1); } this.forbody(base, line, 1, true); } void forlist(String indexname) { /* forlist -> NAME {,NAME} IN explist1 forbody */ FuncState fs = this.fs; ExpDesc e = new ExpDesc(); int nvars = 0; int line; int base = fs.freereg; /* create control variables */ this.new_localvarliteral(RESERVED_LOCAL_VAR_FOR_GENERATOR, nvars++); this.new_localvarliteral(RESERVED_LOCAL_VAR_FOR_STATE, nvars++); this.new_localvarliteral(RESERVED_LOCAL_VAR_FOR_CONTROL, nvars++); /* create declared variables */ this.new_localvar(indexname, nvars++); // next(); while (this.testnext(COMMA)) { PsiBuilder.Marker mark = builder.mark(); String name = this.str_checkname(); mark.done(LOCAL_NAME); this.new_localvar(name, nvars++); } this.checknext(IN); line = this.linenumber; this.adjust_assign(3, this.explist1(e), e); fs.checkstack(3); /* extra space to call generator */ this.forbody(base, line, nvars - 3, false); } void forstat(int line) { /* forstat -> FOR (fornum | forlist) END */ FuncState fs = this.fs; String varname; BlockCnt bl = new BlockCnt(); fs.enterblock(bl, true); /* scope for loop and control variables */ PsiBuilder.Marker mark = builder.mark(); boolean numeric = false; this.checknext(FOR); /* skip `for' */ PsiBuilder.Marker var_mark = builder.mark(); varname = this.str_checkname(); /* first variable name */ var_mark.done(LOCAL_NAME); if (this.t == ASSIGN) { numeric = true; this.fornum(varname, line); } else if (this.t == COMMA || this.t == IN) { this.forlist(varname); } else { this.syntaxerror(LUA_QL("=") + " or " + LUA_QL("in") + " expected"); } this.check_match(END, FOR, line); mark.done(numeric ? NUMERIC_FOR_BLOCK : GENERIC_FOR_BLOCK); fs.leaveblock(); /* loop scope (`break' jumps to this point) */ } int test_then_block() { /* test_then_block -> [IF | ELSEIF] cond THEN block */ int condexit; this.next(); /* skip IF or ELSEIF */ condexit = this.cond(); this.checknext(THEN); this.block(); /* `then' part */ return condexit; } void ifstat(int line) { PsiBuilder.Marker mark = builder.mark(); /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] * END */ FuncState fs = this.fs; int flist; int escapelist = NO_JUMP; flist = test_then_block(); /* IF cond THEN block */ while (this.t == ELSEIF) { escapelist = fs.concat(escapelist, fs.jump()); fs.patchtohere(flist); flist = test_then_block(); /* ELSEIF cond THEN block */ } if (this.t == ELSE) { escapelist = fs.concat(escapelist, fs.jump()); fs.patchtohere(flist); this.next(); /* skip ELSE (after patch, for correct line info) */ this.block(); /* `else' part */ } else escapelist = fs.concat(escapelist, flist); fs.patchtohere(escapelist); this.check_match(END, IF, line); mark.done(IF_THEN_BLOCK); } void localfunc(PsiBuilder.Marker stat) { ExpDesc v = new ExpDesc(); ExpDesc b = new ExpDesc(); FuncState fs = this.fs; PsiBuilder.Marker funcStmt = stat; next(); PsiBuilder.Marker funcName = builder.mark(); PsiBuilder.Marker mark = builder.mark(); String name = this.str_checkname(); mark.done(LOCAL_NAME); funcName.done(FUNCTION_IDENTIFIER); this.new_localvar(name, 0); v.init(VLOCAL, fs.freereg); fs.reserveregs(1); this.adjustlocalvars(1); this.body(b, false, this.linenumber); funcStmt.done(LOCAL_FUNCTION); fs.storevar(v, b); /* debug information will only see the variable after this point! */ } void localstat(PsiBuilder.Marker stat) { // PsiBuilder.Marker mark = stat; PsiBuilder.Marker names = builder.mark(); /* stat -> LOCAL NAME {`,' NAME} [`=' explist1] */ int nvars = 0; int nexps; ExpDesc e = new ExpDesc(); do { PsiBuilder.Marker mark = builder.mark(); String name = this.str_checkname(); mark.done(LOCAL_NAME_DECL); this.new_localvar(name, nvars++); } while (this.testnext(COMMA)); names.done(IDENTIFIER_LIST); if (this.testnext(ASSIGN)) { nexps = this.explist1(e); stat.done(LOCAL_DECL_WITH_ASSIGNMENT); } else { e.k = VVOID; nexps = 0; stat.done(LOCAL_DECL); } this.adjust_assign(nvars, nexps, e); this.adjustlocalvars(nvars); } boolean funcname(ExpDesc v) { //log.info(">>> funcname"); /* funcname -> NAME {field} [`:' NAME] */ boolean needself = false; PsiBuilder.Marker ref = builder.mark(); PsiBuilder.Marker tmp = ref; this.singlevar(v); int lastPos = builder.getCurrentOffset(); while (this.t == DOT) { this.field(v, ref); ref = ref.precede(); tmp.done(REFERENCE); tmp = ref; } if (this.t == COLON) { needself = true; this.field(v, ref); // ref = ref.precede(); tmp.done(REFERENCE); tmp = null; } if (tmp != null) // ref.done(REFERENCE); // else tmp.drop(); //log.info("<<< funcname"); return needself; } void funcstat(int line) { //log.info(">>> funcstat"); PsiBuilder.Marker funcStmt = builder.mark(); /* funcstat -> FUNCTION funcname body */ boolean needself; ExpDesc v = new ExpDesc(); ExpDesc b = new ExpDesc(); this.next(); /* skip FUNCTION */ PsiBuilder.Marker funcName = builder.mark(); needself = this.funcname(v); if (needself) funcName.done(FUNCTION_IDENTIFIER_NEEDSELF); else funcName.done(FUNCTION_IDENTIFIER); this.body(b, needself, line); funcStmt.done(FUNCTION_DEFINITION); fs.storevar(v, b); fs.fixline(line); /* definition `happens' in the first line */ ///log.info("<<< funcstat"); } void exprstat() { /* stat -> func | assignment */ FuncState fs = this.fs; LHS_assign v = new LHS_assign(); PsiBuilder.Marker mark = builder.mark(); this.primaryexp(v.v); if (v.v.k == VCALL) /* stat -> func */ { mark.done(FUNCTION_CALL); FuncState.SETARG_C(fs.getcodePtr(v.v), 1); /* call statement uses no results */ } else { /* stat -> assignment */ PsiBuilder.Marker expr = mark; mark = expr.precede(); v.prev = null; this.assignment(v, 1, expr); mark.done(ASSIGN_STMT); } } void retstat() { PsiBuilder.Marker mark = builder.mark(); boolean tailCall = false; /* stat -> RETURN explist */ FuncState fs = this.fs; ExpDesc e = new ExpDesc(); int first, nret; /* registers with returned values */ this.next(); /* skip RETURN */ if (block_follow(this.t) || this.t == SEMI) first = nret = 0; /* return no values */ else { nret = this.explist1(e); /* optional return values */ if (hasmultret(e.k)) { fs.setmultret(e); if (e.k == VCALL && nret == 1) { /* tail call? */ tailCall = true; FuncState.SET_OPCODE(fs.getcodePtr(e), FuncState.OP_TAILCALL); FuncState._assert(FuncState.GETARG_A(fs.getcode(e)) == fs.nactvar); } first = fs.nactvar; nret = FuncState.LUA_MULTRET; /* return all values */ } else { if (nret == 1) /* only one single value? */ first = fs.exp2anyreg(e); else { fs.exp2nextreg(e); /* values must go to the `stack' */ first = fs.nactvar; /* return all `active' values */ FuncState._assert(nret == fs.freereg - first); } } } mark.done(tailCall?RETURN_STATEMENT_WITH_TAIL_CALL:RETURN_STATEMENT); fs.ret(first, nret); } boolean statement() { try { //log.info(">>> statement"); int line = this.linenumber; /* may be needed for error messages */ if (this.t == IF) { /* stat -> ifstat */ this.ifstat(line); return false; } if (this.t == WHILE) { /* stat -> whilestat */ this.whilestat(line); return false; } if (this.t == DO) { /* stat -> DO block END */ PsiBuilder.Marker mark = builder.mark(); this.next(); /* skip DO */ this.block(); this.check_match(END, DO, line); mark.done(DO_BLOCK); return false; } if (this.t == FOR) { /* stat -> forstat */ this.forstat(line); return false; } if (this.t == REPEAT) { /* stat -> repeatstat */ this.repeatstat(line); return false; } if (this.t == FUNCTION) { this.funcstat(line); /* stat -> funcstat */ return false; } if (this.t == LOCAL) { /* stat -> localstat */ PsiBuilder.Marker stat = builder.mark(); this.next(); /* skip LOCAL */ if (this.t == FUNCTION) /* local function? */ this.localfunc(stat); else this.localstat(stat); return false; } if (this.t == RETURN) { /* stat -> retstat */ this.retstat(); return true; /* must be last statement */ } if (this.t == BREAK) { /* stat -> breakstat */ this.next(); /* skip BREAK */ this.breakstat(); return true; /* must be last statement */ } this.exprstat(); return false; /* to avoid warnings */ } finally { //log.info("<<< statement"); } } void chunk() { //log.info(">>> chunk"); /* chunk -> { stat [`;'] } */ boolean islast = false; this.enterlevel(); while (!islast && !block_follow(this.t)) { islast = this.statement(); this.testnext(SEMI); FuncState._assert(this.fs.f.maxStacksize >= this.fs.freereg && this.fs.freereg >= this.fs.nactvar); this.fs.freereg = this.fs.nactvar; /* free registers */ } this.leavelevel(); //log.info("<<< chunk"); } /* }====================================================================== */ @NotNull @Override public ASTNode parse(IElementType root, PsiBuilder builder) { final LuaPsiBuilder psiBuilder = new LuaPsiBuilder(builder); final PsiBuilder.Marker rootMarker = psiBuilder.mark(); String name = "todo:name"; source = name; KahluaParser lexstate = new KahluaParser(z, 0, source); FuncState funcstate = new FuncState(lexstate); // lexstate.buff = buff; /* main func. is always vararg */ funcstate.isVararg = FuncState.VARARG_ISVARARG; funcstate.f.name = name; lexstate.builder = psiBuilder; lexstate.t = psiBuilder.getTokenType(); if (lexstate.t == null) // Try to kludge in handling of partial parses lexstate.next(); /* read first token */ lexstate.chunk(); // lexstate.check(EMPTY_INPUT); lexstate.close_func(); FuncState._assert(funcstate.prev == null); FuncState._assert(funcstate.f.numUpvalues == 0); FuncState._assert(lexstate.fs == null); // return funcstate.f; if (root != null) rootMarker.done(root); return builder.getTreeBuilt(); } }
src/lang/parser/kahlua/KahluaParser.java
/* * Copyright 2010 Jon S Akhtar (Sylvanaar) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sylvanaar.idea.Lua.lang.parser.kahlua; import com.intellij.lang.ASTNode; import com.intellij.lang.PsiBuilder; import com.intellij.lang.PsiParser; import com.intellij.openapi.diagnostic.Logger; import com.intellij.psi.tree.IElementType; import com.sylvanaar.idea.Lua.lang.parser.LuaElementTypes; import com.sylvanaar.idea.Lua.lang.parser.LuaPsiBuilder; import org.jetbrains.annotations.NotNull; import se.krka.kahlua.vm.Prototype; import java.io.IOException; import java.io.Reader; public class KahluaParser implements PsiParser, LuaElementTypes { public int nCcalls = 0; static Logger log = Logger.getInstance("#Lua.parser.KahluaParser"); protected static final String RESERVED_LOCAL_VAR_FOR_CONTROL = "(for control)"; protected static final String RESERVED_LOCAL_VAR_FOR_STATE = "(for state)"; protected static final String RESERVED_LOCAL_VAR_FOR_GENERATOR = "(for generator)"; protected static final String RESERVED_LOCAL_VAR_FOR_STEP = "(for step)"; protected static final String RESERVED_LOCAL_VAR_FOR_LIMIT = "(for limit)"; protected static final String RESERVED_LOCAL_VAR_FOR_INDEX = "(for index)"; // // keywords array // protected static final String[] RESERVED_LOCAL_VAR_KEYWORDS = new String[]{ // RESERVED_LOCAL_VAR_FOR_CONTROL, // RESERVED_LOCAL_VAR_FOR_GENERATOR, // RESERVED_LOCAL_VAR_FOR_INDEX, // RESERVED_LOCAL_VAR_FOR_LIMIT, // RESERVED_LOCAL_VAR_FOR_STATE, // RESERVED_LOCAL_VAR_FOR_STEP // }; // private static final Hashtable<String, Boolean> RESERVED_LOCAL_VAR_KEYWORDS_TABLE = // new Hashtable<String, Boolean>(); // // static { // int i = 0; // while (i < RESERVED_LOCAL_VAR_KEYWORDS.length) { // String RESERVED_LOCAL_VAR_KEYWORD = RESERVED_LOCAL_VAR_KEYWORDS[i]; // RESERVED_LOCAL_VAR_KEYWORDS_TABLE.put(RESERVED_LOCAL_VAR_KEYWORD, Boolean.TRUE); // i++; // } // } private static final int EOZ = (-1); //private static final int MAXSRC = 80; private static final int MAX_INT = Integer.MAX_VALUE - 2; //private static final int UCHAR_MAX = 255; // TO DO, convert to unicode CHAR_MAX? private static final int LUAI_MAXCCALLS = 200; private LuaPsiBuilder builder = null; // public KahluaParser(Project project) { // } private static String LUA_QS(String s) { return "'" + s + "'"; } private static String LUA_QL(Object o) { return LUA_QS(String.valueOf(o)); } // public static boolean isReservedKeyword(String varName) { // return RESERVED_LOCAL_VAR_KEYWORDS_TABLE.containsKey(varName); // } /* ** Marks the end of a patch list. It is an invalid value both as an absolute ** address, and as a list link (would link an element to itself). */ static final int NO_JUMP = (-1); /* ** grep "ORDER OPR" if you change these enums */ static final int OPR_ADD = 0, OPR_SUB = 1, OPR_MUL = 2, OPR_DIV = 3, OPR_MOD = 4, OPR_POW = 5, OPR_CONCAT = 6, OPR_NE = 7, OPR_EQ = 8, OPR_LT = 9, OPR_LE = 10, OPR_GT = 11, OPR_GE = 12, OPR_AND = 13, OPR_OR = 14, OPR_NOBINOPR = 15; static final int OPR_MINUS = 0, OPR_NOT = 1, OPR_LEN = 2, OPR_NOUNOPR = 3; /* exp kind */ static final int VVOID = 0, /* no value */ VNIL = 1, VTRUE = 2, VFALSE = 3, VK = 4, /* info = index of constant in `k' */ VKNUM = 5, /* nval = numerical value */ VLOCAL = 6, /* info = local register */ VUPVAL = 7, /* info = index of upvalue in `upvalues' */ VGLOBAL = 8, /* info = index of table, aux = index of global name in `k' */ VINDEXED = 9, /* info = table register, aux = index register (or `k') */ VJMP = 10, /* info = instruction pc */ VRELOCABLE = 11, /* info = instruction pc */ VNONRELOC = 12, /* info = result register */ VCALL = 13, /* info = instruction pc */ VVARARG = 14; /* info = instruction pc */ int current = 0; /* current character (charint) */ int linenumber = 0; /* input line counter */ int lastline = 0; /* line of last token `consumed' */ IElementType t = null; /* current token */ IElementType lookahead = null; /* look ahead token */ FuncState fs = null; /* `FuncState' is private to the parser */ Reader z = null; /* input stream */ byte[] buff = null; /* buffer for tokens */ int nbuff = 0; /* length of buffer */ String source = null; /* current source name */ public KahluaParser(Reader stream, int firstByte, String source) { this.z = stream; this.buff = new byte[32]; this.lookahead = null; /* no look-ahead token */ this.fs = null; this.linenumber = 1; this.lastline = 1; this.source = source; this.nbuff = 0; /* initialize buffer */ this.current = firstByte; /* read first char */ this.skipShebang(); } public KahluaParser() {}; void nextChar() { try { current = z.read(); } catch (IOException e) { e.printStackTrace(); current = EOZ; } } boolean currIsNewline() { return current == '\n' || current == '\r'; } void lexerror(String msg, IElementType token) { String cid = source; String errorMessage; if (token != null) { errorMessage = /*cid + ":" + linenumber + ": " +*/ msg + " near `" + token + "`"; } else { errorMessage = /*cid + ":" + linenumber + ": " +*/ msg; } builder.error(errorMessage); //throw new KahluaException(errorMessage); } // private static String trim(String s, int max) { // if (s.length() > max) { // return s.substring(0, max - 3) + "..."; // } // return s; // } void syntaxerror(String msg) { lexerror(msg, t); } private void skipShebang() { if (current == '#') while (!currIsNewline() && current != EOZ) nextChar(); } /* ** ======================================================= ** LEXICAL ANALYZER ** ======================================================= */ void next() { lastline = linenumber; builder.advanceLexer(); t = builder.getTokenType(); // /* // if (lookahead != TK_EOS) { /* is there a look-ahead token? */ // t.set( lookahead ); /* use this one */ // lookahead = TK_EOS; /* and discharge it */ // } else // t = llex(t); /* read next token */ // */ } void lookahead() { // FuncState._assert (lookahead == TK_EOS); PsiBuilder.Marker current = builder.mark(); builder.advanceLexer(); lookahead = builder.getTokenType(); current.rollbackTo(); } // ============================================================= // from lcode.h // ============================================================= // ============================================================= // from lparser.c // ============================================================= boolean hasmultret(int k) { return ((k) == VCALL || (k) == VVARARG); } /*---------------------------------------------------------------------- name args description ------------------------------------------------------------------------*/ /* * * prototypes for recursive non-terminal functions */ void error_expected(IElementType token) { syntaxerror(token.toString() + " expected"); } boolean testnext(IElementType c) { if (t == c) { next(); return true; } return false; } void check(IElementType c) { if (t != c) error_expected(c); } void checknext(IElementType c) { check(c); next(); } void check_condition(boolean c, String msg) { if (!(c)) syntaxerror(msg); } void check_match(IElementType what, IElementType who, int where) { if (!testnext(what)) { if (where == linenumber) error_expected(what); else { syntaxerror(what + " expected " + "(to close " + who.toString() + " at line " + where + ")"); } } } String str_checkname() { String ts; check(NAME); ts = builder.text(); next(); return ts; } void codestring(ExpDesc e, String s) { e.init(VK, fs.stringK(s)); } void checkname(ExpDesc e) { codestring(e, str_checkname()); } int registerlocalvar(String varname) { FuncState fs = this.fs; if (fs.locvars == null || fs.nlocvars + 1 > fs.locvars.length) fs.locvars = FuncState.realloc(fs.locvars, fs.nlocvars * 2 + 1); fs.locvars[fs.nlocvars] = varname; return fs.nlocvars++; } // // #define new_localvarliteral(ls,v,n) \ // this.new_localvar(luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char))-1), n) // void new_localvarliteral(String v, int n) { new_localvar(v, n); } void new_localvar(String name, int n) { FuncState fs = this.fs; fs.checklimit(fs.nactvar + n + 1, FuncState.LUAI_MAXVARS, "local variables"); fs.actvar[fs.nactvar + n] = (short) registerlocalvar(name); } void adjustlocalvars(int nvars) { FuncState fs = this.fs; fs.nactvar = (fs.nactvar + nvars); } void removevars(int tolevel) { FuncState fs = this.fs; fs.nactvar = tolevel; } void singlevar(ExpDesc var) { PsiBuilder.Marker mark = builder.mark(); String varname = this.str_checkname(); FuncState fs = this.fs; if (fs.singlevaraux(varname, var, 1) == VGLOBAL) { var.info = fs.stringK(varname); /* info points to global name */ mark.done(GLOBAL_NAME); } else { mark.done(LOCAL_NAME); } } void adjust_assign(int nvars, int nexps, ExpDesc e) { FuncState fs = this.fs; int extra = nvars - nexps; if (hasmultret(e.k)) { /* includes call itself */ extra++; if (extra < 0) extra = 0; /* last exp. provides the difference */ fs.setreturns(e, extra); if (extra > 1) fs.reserveregs(extra - 1); } else { /* close last expression */ if (e.k != VVOID) fs.exp2nextreg(e); if (extra > 0) { int reg = fs.freereg; fs.reserveregs(extra); fs.nil(reg, extra); } } } void enterlevel() { if (++nCcalls > LUAI_MAXCCALLS) lexerror("chunk has too many syntax levels", EMPTY_INPUT); } void leavelevel() { nCcalls--; } void pushclosure(FuncState func, ExpDesc v) { FuncState fs = this.fs; Prototype f = fs.f; if (f.prototypes == null || fs.np + 1 > f.prototypes.length) f.prototypes = FuncState.realloc(f.prototypes, fs.np * 2 + 1); f.prototypes[fs.np++] = func.f; v.init(VRELOCABLE, fs.codeABx(FuncState.OP_CLOSURE, 0, fs.np - 1)); for (int i = 0; i < func.f.numUpvalues; i++) { int o = (func.upvalues_k[i] == VLOCAL) ? FuncState.OP_MOVE : FuncState.OP_GETUPVAL; fs.codeABC(o, 0, func.upvalues_info[i], 0); } } void close_func() { FuncState fs = this.fs; Prototype f = fs.f; f.isVararg = fs.isVararg != 0; this.removevars(0); fs.ret(0, 0); /* final return */ f.code = FuncState.realloc(f.code, fs.pc); f.lines = FuncState.realloc(f.lines, fs.pc); // f.sizelineinfo = fs.pc; f.constants = FuncState.realloc(f.constants, fs.nk); f.prototypes = FuncState.realloc(f.prototypes, fs.np); fs.locvars = FuncState.realloc(fs.locvars, fs.nlocvars); // f.sizelocvars = fs.nlocvars; fs.upvalues = FuncState.realloc(fs.upvalues, f.numUpvalues); // FuncState._assert (CheckCode.checkcode(f)); FuncState._assert(fs.bl == null); this.fs = fs.prev; // L.top -= 2; /* remove table and prototype from the stack */ // /* last token read was anchored in defunct function; must reanchor it // */ // if (fs!=null) ls.anchor_token(); } /*============================================================*/ /* GRAMMAR RULES */ /*============================================================*/ void field(ExpDesc v, PsiBuilder.Marker ref) { /* field -> ['.' | ':'] NAME */ FuncState fs = this.fs; ExpDesc key = new ExpDesc(); fs.exp2anyreg(v); this.next(); /* skip the dot or colon */ PsiBuilder.Marker mark = builder.mark(); this.checkname(key); mark.done(FIELD_NAME); fs.indexed(v, key); } void yindex(ExpDesc v) { /* index -> '[' expr ']' */ this.next(); /* skip the '[' */ PsiBuilder.Marker mark = builder.mark(); this.expr(v); mark.done(TABLE_INDEX); this.fs.exp2val(v); this.checknext(RBRACK); } /* ** {====================================================================== ** Rules for Constructors ** ======================================================================= */ void recfield(ConsControl cc) { /* recfield -> (NAME | `['exp1`]') = exp1 */ FuncState fs = this.fs; int reg = this.fs.freereg; ExpDesc key = new ExpDesc(); ExpDesc val = new ExpDesc(); int rkkey; if (this.t == NAME) { fs.checklimit(cc.nh, MAX_INT, "items in a constructor"); this.checkname(key); } else /* this.t == '[' */ this.yindex(key); cc.nh++; this.checknext(ASSIGN); rkkey = fs.exp2RK(key); this.expr(val); fs.codeABC(FuncState.OP_SETTABLE, cc.t.info, rkkey, fs.exp2RK(val)); fs.freereg = reg; /* free registers */ } void listfield(ConsControl cc) { this.expr(cc.v); fs.checklimit(cc.na, MAX_INT, "items in a constructor"); cc.na++; cc.tostore++; } void constructor(ExpDesc t) { PsiBuilder.Marker mark = builder.mark(); /* constructor -> ?? */ FuncState fs = this.fs; int line = this.linenumber; int pc = fs.codeABC(FuncState.OP_NEWTABLE, 0, 0, 0); ConsControl cc = new ConsControl(); cc.na = cc.nh = cc.tostore = 0; cc.t = t; t.init(VRELOCABLE, pc); cc.v.init(VVOID, 0); /* no value (yet) */ fs.exp2nextreg(t); /* fix it at stack top (for gc) */ this.checknext(LCURLY); do { FuncState._assert(cc.v.k == VVOID || cc.tostore > 0); if (this.t == RCURLY) break; fs.closelistfield(cc); if (this.t == NAME) { /* may be listfields or recfields */ this.lookahead(); if (this.lookahead != ASSIGN) /* expression? */ this.listfield(cc); else this.recfield(cc); // break; } else if (this.t == LBRACK) { /* constructor_item -> recfield */ this.recfield(cc); // break; } else { /* constructor_part -> listfield */ this.listfield(cc); // break; } } while (this.testnext(COMMA) || this.testnext(SEMI)); this.check_match(RCURLY, LCURLY, line); fs.lastlistfield(cc); InstructionPtr i = new InstructionPtr(fs.f.code, pc); FuncState.SETARG_B(i, luaO_int2fb(cc.na)); /* set initial array size */ FuncState.SETARG_C(i, luaO_int2fb(cc.nh)); /* set initial table size */ mark.done(TABLE_CONSTUCTOR); } /* ** converts an integer to a "floating point byte", represented as ** (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if ** eeeee != 0 and (xxx) otherwise. */ static int luaO_int2fb(int x) { int e = 0; /* expoent */ while (x >= 16) { x = (x + 1) >> 1; e++; } if (x < 8) return x; else return ((e + 1) << 3) | (x - 8); } /* }====================================================================== */ void parlist() { //log.info(">>> parlist"); /* parlist -> [ param { `,' param } ] */ FuncState fs = this.fs; Prototype f = fs.f; int nparams = 0; fs.isVararg = 0; if (this.t != RPAREN) { /* is `parlist' not empty? */ do { PsiBuilder.Marker parm = builder.mark(); if (this.t == NAME) { /* param . NAME */ PsiBuilder.Marker mark = builder.mark(); String name = this.str_checkname(); mark.done(LOCAL_NAME); this.new_localvar(name, nparams++); parm.done(PARAMETER); // break; } else if (this.t == ELLIPSIS) { /* param . `...' */ this.next(); parm.done(PARAMETER); fs.isVararg |= FuncState.VARARG_ISVARARG; // break; } else { parm.drop(); this.syntaxerror("<name> or " + LUA_QL("...") + " expected"); } } while ((fs.isVararg == 0) && this.testnext(COMMA)); } this.adjustlocalvars(nparams); f.numParams = (fs.nactvar - (fs.isVararg & FuncState.VARARG_HASARG)); fs.reserveregs(fs.nactvar); /* reserve register for parameters */ //log.info("<<< parlist"); } void body(ExpDesc e, boolean needself, int line) { /* body -> `(' parlist `)' chunk END */ FuncState new_fs = new FuncState(this); new_fs.linedefined = line; this.checknext(LPAREN); if (needself) { new_localvarliteral("self", 0); adjustlocalvars(1); } PsiBuilder.Marker mark = builder.mark(); this.parlist(); mark.done(LuaElementTypes.PARAMETER_LIST); this.checknext(RPAREN); mark = builder.mark(); this.chunk(); mark.done(BLOCK); new_fs.lastlinedefined = this.linenumber; this.check_match(END, FUNCTION, line); this.close_func(); this.pushclosure(new_fs, e); } int explist1(ExpDesc v) { PsiBuilder.Marker mark = builder.mark(); /* explist1 -> expr { `,' expr } */ int n = 1; /* at least one expression */ this.expr(v); while (this.testnext(COMMA)) { fs.exp2nextreg(v); this.expr(v); n++; } mark.done(EXPR_LIST); return n; } void funcargs(ExpDesc f) { PsiBuilder.Marker mark = builder.mark(); FuncState fs = this.fs; ExpDesc args = new ExpDesc(); int base, nparams; int line = this.linenumber; if (this.t == LPAREN) { /* funcargs -> `(' [ explist1 ] `)' */ if (line != this.lastline) this.syntaxerror("ambiguous syntax (function call x new statement)"); this.next(); if (this.t == RPAREN) /* arg list is empty? */ args.k = VVOID; else { this.explist1(args); fs.setmultret(args); } this.check_match(RPAREN, LPAREN, line); // break; } else if (this.t == LCURLY) { /* funcargs -> constructor */ this.constructor(args); } else if (this.t == STRING || this.t == LONGSTRING) { /* funcargs -> STRING */ this.codestring(args, builder.text()); this.next(); /* must use `seminfo' before `next' */ } else { this.syntaxerror("function arguments expected"); } FuncState._assert(f.k == VNONRELOC); base = f.info; /* base register for call */ if (hasmultret(args.k)) nparams = FuncState.LUA_MULTRET; /* open call */ else { if (args.k != VVOID) fs.exp2nextreg(args); /* close last argument */ nparams = fs.freereg - (base + 1); } f.init(VCALL, fs.codeABC(FuncState.OP_CALL, base, nparams + 1, 2)); fs.fixline(line); fs.freereg = base + 1; /* call remove function and arguments and leaves * (unless changed) one result */ mark.done(FUNCTION_CALL_ARGS); } /* ** {====================================================================== ** Expression parsing ** ======================================================================= */ void prefixexp(ExpDesc v) { /* prefixexp -> NAME | '(' expr ')' */ if (this.t == LPAREN) { int line = this.linenumber; this.next(); this.expr(v); this.check_match(RPAREN, LPAREN, line); fs.dischargevars(v); return; } else if (this.t == NAME) { this.singlevar(v); return; } this.syntaxerror("unexpected symbol in prefix expression"); } void primaryexp(ExpDesc v) { /* * primaryexp -> prefixexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | * funcargs } */ PsiBuilder.Marker mark = builder.mark(); PsiBuilder.Marker ref = builder.mark(); PsiBuilder.Marker tmp = ref; FuncState fs = this.fs; this.prefixexp(v); for (; ;) { if (this.t == DOT) { /* field */ this.field(v, mark); if (tmp != null) { ref = ref.precede(); tmp.done(REFERENCE); tmp = ref; } // break; } else if (this.t == LBRACK) { /* `[' exp1 `]' */ ExpDesc key = new ExpDesc(); fs.exp2anyreg(v); this.yindex(key); if (tmp != null) { ref = ref.precede(); tmp.done(REFERENCE); tmp = ref; } fs.indexed(v, key); // break; } else if (this.t == COLON) { /* `:' NAME funcargs */ ExpDesc key = new ExpDesc(); this.next(); this.checkname(key); // ref = ref.precede(); if (tmp != null) tmp.done(REFERENCE); tmp = null; PsiBuilder.Marker call = null; if (mark != null) { call = mark.precede(); mark.done(FUNCTION_IDENTIFIER_NEEDSELF); mark = null; } fs.self(v, key); this.funcargs(v); if (call != null) call.done(FUNCTION_CALL_EXPR); // break; } else if (this.t == LPAREN || this.t == STRING || this.t == LONGSTRING || this.t == LCURLY) { /* funcargs */ fs.exp2nextreg(v); if (tmp != null) { tmp.drop(); tmp = null; } PsiBuilder.Marker call = null; if (mark != null) { call = mark.precede(); mark.done(FUNCTION_IDENTIFIER); mark = null; } this.funcargs(v); if (call != null) call.done(FUNCTION_CALL_EXPR); // break; } else { if (tmp != null) tmp.drop(); if (mark != null) mark.done(VARIABLE); return; } } } void simpleexp(ExpDesc v) { /* * simpleexp -> NUMBER | STRING | NIL | true | false | ... | constructor | * FUNCTION body | primaryexp */ PsiBuilder.Marker mark = builder.mark(); try { if (this.t == NUMBER) { v.init(VKNUM, 0); v.setNval(0); // TODO } else if (this.t == STRING || this.t == LONGSTRING) { this.codestring(v, builder.text()); //TODO } else if (this.t == NIL) { v.init(VNIL, 0); } else if (this.t == TRUE) { v.init(VTRUE, 0); } else if (this.t == FALSE) { v.init(VFALSE, 0); } else if (this.t == ELLIPSIS) { /* vararg */ FuncState fs = this.fs; this.check_condition(fs.isVararg != 0, "cannot use " + LUA_QL("...") + " outside a vararg function"); fs.isVararg &= ~FuncState.VARARG_NEEDSARG; /* don't need 'arg' */ v.init(VVARARG, fs.codeABC(FuncState.OP_VARARG, 0, 1, 0)); } else if (this.t == LCURLY) { /* constructor */ this.constructor(v); return; } else if (this.t == FUNCTION) { this.next(); PsiBuilder.Marker funcStmt = builder.mark(); this.body(v, false, this.linenumber); funcStmt.done(ANONYMOUS_FUNCTION_EXPRESSION); return; } else { this.primaryexp(v); return; } this.next(); mark.done(LITERAL_EXPRESSION); mark = null; } finally { if (mark != null) mark.drop(); } } int getunopr(IElementType op) { if (op == NOT) return OPR_NOT; if (op == MINUS) return OPR_MINUS; if (op == GETN) return OPR_LEN; return OPR_NOUNOPR; } int getbinopr(IElementType op) { if (op == PLUS) return OPR_ADD; if (op == MINUS) return OPR_SUB; if (op == MULT) return OPR_MUL; if (op == DIV) return OPR_DIV; if (op == MOD) return OPR_MOD; if (op == EXP) return OPR_POW; if (op == CONCAT) return OPR_CONCAT; if (op == NE) return OPR_NE; if (op == EQ) return OPR_EQ; if (op == LT) return OPR_LT; if (op == LE) return OPR_LE; if (op == GT) return OPR_GT; if (op == GE) return OPR_GE; if (op == AND) return OPR_AND; if (op == OR) return OPR_OR; return OPR_NOBINOPR; } static final int[] priorityLeft = { 6, 6, 7, 7, 7, /* `+' `-' `/' `%' */ 10, 5, /* power and concat (right associative) */ 3, 3, /* equality and inequality */ 3, 3, 3, 3, /* order */ 2, 1, /* logical (and/or) */ }; static final int[] priorityRight = { /* ORDER OPR */ 6, 6, 7, 7, 7, /* `+' `-' `/' `%' */ 9, 4, /* power and concat (right associative) */ 3, 3, /* equality and inequality */ 3, 3, 3, 3, /* order */ 2, 1 /* logical (and/or) */ }; static final int UNARY_PRIORITY = 8; /* priority for unary operators */ /* ** subexpr -> (simpleexp | unop subexpr) { binop subexpr } ** where `binop' is any binary operator with a priority higher than `limit' */ int subexpr(ExpDesc v, int limit) { int op; int uop; PsiBuilder.Marker mark = builder.mark(); PsiBuilder.Marker oper; this.enterlevel(); uop = getunopr(this.t); if (uop != OPR_NOUNOPR) { PsiBuilder.Marker mark2 = builder.mark(); oper = builder.mark(); this.next(); oper.done(UNARY_OP); this.subexpr(v, UNARY_PRIORITY); mark2.done(UNARY_EXP); fs.prefix(uop, v); } else { this.simpleexp(v); } /* expand while operators have priorities higher than `limit' */ op = getbinopr(this.t); while (op != OPR_NOBINOPR && priorityLeft[op] > limit) { ExpDesc v2 = new ExpDesc(); int nextop; oper = builder.mark(); this.next(); oper.done(BINARY_OP); fs.infix(op, v); /* read sub-expression with higher priority */ nextop = this.subexpr(v2, priorityRight[op]); fs.posfix(op, v, v2); op = nextop; mark.done(BINARY_EXP); mark = mark.precede(); } mark.drop(); this.leavelevel(); return op; /* return first untreated operator */ } void expr(ExpDesc v) { PsiBuilder.Marker mark = builder.mark(); this.subexpr(v, 0); mark.done(EXPR); // next(); } /* }==================================================================== */ /* ** {====================================================================== ** Rules for Statements ** ======================================================================= */ boolean block_follow(IElementType token) { return token == ELSE || token == ELSEIF || token == END || token == UNTIL || token == null; } void block() { PsiBuilder.Marker mark = builder.mark(); /* block -> chunk */ FuncState fs = this.fs; BlockCnt bl = new BlockCnt(); fs.enterblock(bl, false); this.chunk(); FuncState._assert(bl.breaklist == NO_JUMP); fs.leaveblock(); mark.done(BLOCK); } /* ** check whether, in an assignment to a local variable, the local variable ** is needed in a previous assignment (to a table). If so, save original ** local value in a safe place and use this safe copy in the previous ** assignment. */ void check_conflict(LHS_assign lh, ExpDesc v) { FuncState fs = this.fs; int extra = fs.freereg; /* eventual position to save local variable */ boolean conflict = false; for (; lh != null; lh = lh.prev) { if (lh.v.k == VINDEXED) { if (lh.v.info == v.info) { /* conflict? */ conflict = true; lh.v.info = extra; /* previous assignment will use safe copy */ } if (lh.v.aux == v.info) { /* conflict? */ conflict = true; lh.v.aux = extra; /* previous assignment will use safe copy */ } } } if (conflict) { fs.codeABC(FuncState.OP_MOVE, fs.freereg, v.info, 0); /* make copy */ fs.reserveregs(1); } } void assignment(LHS_assign lh, int nvars, PsiBuilder.Marker expr) { // PsiBuilder.Marker mark = builder.mark(); ExpDesc e = new ExpDesc(); this.check_condition(VLOCAL <= lh.v.k && lh.v.k <= VINDEXED, "syntax error"); if (this.testnext(COMMA)) { /* assignment -> `,' primaryexp assignment */ LHS_assign nv = new LHS_assign(); nv.prev = lh; this.primaryexp(nv.v); if (nv.v.k == VLOCAL) this.check_conflict(lh, nv.v); this.assignment(nv, nvars + 1, expr); } else { /* assignment . `=' explist1 */ int nexps; expr.done(IDENTIFIER_LIST); this.checknext(ASSIGN); nexps = this.explist1(e); if (nexps != nvars) { this.adjust_assign(nvars, nexps, e); if (nexps > nvars) this.fs.freereg -= nexps - nvars; /* remove extra values */ } else { fs.setoneret(e); /* close last expression */ fs.storevar(lh.v, e); // mark.done(ASSIGN_STMT); return; /* avoid default */ } } e.init(VNONRELOC, this.fs.freereg - 1); /* default assignment */ fs.storevar(lh.v, e); // mark.done(ASSIGN_STMT); } int cond() { PsiBuilder.Marker mark = builder.mark(); /* cond -> exp */ ExpDesc v = new ExpDesc(); /* read condition */ this.expr(v); /* `falses' are all equal here */ if (v.k == VNIL) v.k = VFALSE; fs.goiftrue(v); mark.done(CONDITIONAL_EXPR); return v.f; } void breakstat() { FuncState fs = this.fs; BlockCnt bl = fs.bl; boolean upval = false; while (bl != null && !bl.isbreakable) { upval |= bl.upval; bl = bl.previous; } if (bl == null) { this.syntaxerror("no loop to break"); } else { if (upval) fs.codeABC(FuncState.OP_CLOSE, bl.nactvar, 0, 0); bl.breaklist = fs.concat(bl.breaklist, fs.jump()); } } void whilestat(int line) { PsiBuilder.Marker mark = builder.mark(); /* whilestat -> WHILE cond DO block END */ FuncState fs = this.fs; int whileinit; int condexit; BlockCnt bl = new BlockCnt(); this.next(); /* skip WHILE */ whileinit = fs.getlabel(); condexit = this.cond(); fs.enterblock(bl, true); this.checknext(DO); this.block(); fs.patchlist(fs.jump(), whileinit); this.check_match(END, WHILE, line); fs.leaveblock(); fs.patchtohere(condexit); /* false conditions finish the loop */ mark.done(WHILE_BLOCK); } void repeatstat(int line) { PsiBuilder.Marker mark = builder.mark(); /* repeatstat -> REPEAT block UNTIL cond */ int condexit; FuncState fs = this.fs; int repeat_init = fs.getlabel(); BlockCnt bl1 = new BlockCnt(); BlockCnt bl2 = new BlockCnt(); fs.enterblock(bl1, true); /* loop block */ fs.enterblock(bl2, false); /* scope block */ this.next(); /* skip REPEAT */ this.chunk(); this.check_match(UNTIL, REPEAT, line); condexit = this.cond(); /* read condition (inside scope block) */ if (!bl2.upval) { /* no upvalues? */ fs.leaveblock(); /* finish scope */ fs.patchlist(condexit, repeat_init); /* close the loop */ } else { /* complete semantics when there are upvalues */ this.breakstat(); /* if condition then break */ fs.patchtohere(condexit); /* else... */ fs.leaveblock(); /* finish scope... */ fs.patchlist(fs.jump(), repeat_init); /* and repeat */ } fs.leaveblock(); /* finish loop */ mark.done(BLOCK); } int exp1() { ExpDesc e = new ExpDesc(); int k; this.expr(e); k = e.k; fs.exp2nextreg(e); return k; } void forbody(int base, int line, int nvars, boolean isnum) { /* forbody -> DO block */ BlockCnt bl = new BlockCnt(); FuncState fs = this.fs; int prep, endfor; this.adjustlocalvars(3); /* control variables */ this.checknext(DO); prep = isnum ? fs.codeAsBx(FuncState.OP_FORPREP, base, NO_JUMP) : fs.jump(); fs.enterblock(bl, false); /* scope for declared variables */ this.adjustlocalvars(nvars); fs.reserveregs(nvars); this.block(); fs.leaveblock(); /* end of scope for declared variables */ fs.patchtohere(prep); endfor = (isnum) ? fs.codeAsBx(FuncState.OP_FORLOOP, base, NO_JUMP) : fs .codeABC(FuncState.OP_TFORLOOP, base, 0, nvars); fs.fixline(line); /* pretend that `Lua.OP_FOR' starts the loop */ fs.patchlist((isnum ? endfor : fs.jump()), prep + 1); } void fornum(String varname, int line) { /* fornum -> NAME = exp1,exp1[,exp1] forbody */ FuncState fs = this.fs; int base = fs.freereg; this.new_localvarliteral(RESERVED_LOCAL_VAR_FOR_INDEX, 0); this.new_localvarliteral(RESERVED_LOCAL_VAR_FOR_LIMIT, 1); this.new_localvarliteral(RESERVED_LOCAL_VAR_FOR_STEP, 2); this.new_localvar(varname, 3); this.checknext(ASSIGN); this.exp1(); /* initial value */ this.checknext(COMMA); this.exp1(); /* limit */ if (this.testnext(COMMA)) this.exp1(); /* optional step */ else { /* default step = 1 */ fs.codeABx(FuncState.OP_LOADK, fs.freereg, fs.numberK(1)); fs.reserveregs(1); } this.forbody(base, line, 1, true); } void forlist(String indexname) { /* forlist -> NAME {,NAME} IN explist1 forbody */ FuncState fs = this.fs; ExpDesc e = new ExpDesc(); int nvars = 0; int line; int base = fs.freereg; /* create control variables */ this.new_localvarliteral(RESERVED_LOCAL_VAR_FOR_GENERATOR, nvars++); this.new_localvarliteral(RESERVED_LOCAL_VAR_FOR_STATE, nvars++); this.new_localvarliteral(RESERVED_LOCAL_VAR_FOR_CONTROL, nvars++); /* create declared variables */ this.new_localvar(indexname, nvars++); // next(); while (this.testnext(COMMA)) { PsiBuilder.Marker mark = builder.mark(); String name = this.str_checkname(); mark.done(LOCAL_NAME); this.new_localvar(name, nvars++); } this.checknext(IN); line = this.linenumber; this.adjust_assign(3, this.explist1(e), e); fs.checkstack(3); /* extra space to call generator */ this.forbody(base, line, nvars - 3, false); } void forstat(int line) { /* forstat -> FOR (fornum | forlist) END */ FuncState fs = this.fs; String varname; BlockCnt bl = new BlockCnt(); fs.enterblock(bl, true); /* scope for loop and control variables */ PsiBuilder.Marker mark = builder.mark(); boolean numeric = false; this.checknext(FOR); /* skip `for' */ PsiBuilder.Marker var_mark = builder.mark(); varname = this.str_checkname(); /* first variable name */ var_mark.done(LOCAL_NAME); if (this.t == ASSIGN) { numeric = true; this.fornum(varname, line); } else if (this.t == COMMA || this.t == IN) { this.forlist(varname); } else { this.syntaxerror(LUA_QL("=") + " or " + LUA_QL("in") + " expected"); } this.check_match(END, FOR, line); mark.done(numeric ? NUMERIC_FOR_BLOCK : GENERIC_FOR_BLOCK); fs.leaveblock(); /* loop scope (`break' jumps to this point) */ } int test_then_block() { /* test_then_block -> [IF | ELSEIF] cond THEN block */ int condexit; this.next(); /* skip IF or ELSEIF */ condexit = this.cond(); this.checknext(THEN); this.block(); /* `then' part */ return condexit; } void ifstat(int line) { PsiBuilder.Marker mark = builder.mark(); /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] * END */ FuncState fs = this.fs; int flist; int escapelist = NO_JUMP; flist = test_then_block(); /* IF cond THEN block */ while (this.t == ELSEIF) { escapelist = fs.concat(escapelist, fs.jump()); fs.patchtohere(flist); flist = test_then_block(); /* ELSEIF cond THEN block */ } if (this.t == ELSE) { escapelist = fs.concat(escapelist, fs.jump()); fs.patchtohere(flist); this.next(); /* skip ELSE (after patch, for correct line info) */ this.block(); /* `else' part */ } else escapelist = fs.concat(escapelist, flist); fs.patchtohere(escapelist); this.check_match(END, IF, line); mark.done(IF_THEN_BLOCK); } void localfunc(PsiBuilder.Marker stat) { ExpDesc v = new ExpDesc(); ExpDesc b = new ExpDesc(); FuncState fs = this.fs; PsiBuilder.Marker funcStmt = stat; next(); PsiBuilder.Marker funcName = builder.mark(); PsiBuilder.Marker mark = builder.mark(); String name = this.str_checkname(); mark.done(LOCAL_NAME); funcName.done(FUNCTION_IDENTIFIER); this.new_localvar(name, 0); v.init(VLOCAL, fs.freereg); fs.reserveregs(1); this.adjustlocalvars(1); this.body(b, false, this.linenumber); funcStmt.done(LOCAL_FUNCTION); fs.storevar(v, b); /* debug information will only see the variable after this point! */ } void localstat(PsiBuilder.Marker stat) { // PsiBuilder.Marker mark = stat; PsiBuilder.Marker names = builder.mark(); /* stat -> LOCAL NAME {`,' NAME} [`=' explist1] */ int nvars = 0; int nexps; ExpDesc e = new ExpDesc(); do { PsiBuilder.Marker mark = builder.mark(); String name = this.str_checkname(); mark.done(LOCAL_NAME_DECL); this.new_localvar(name, nvars++); } while (this.testnext(COMMA)); names.done(IDENTIFIER_LIST); if (this.testnext(ASSIGN)) { nexps = this.explist1(e); stat.done(LOCAL_DECL_WITH_ASSIGNMENT); } else { e.k = VVOID; nexps = 0; stat.done(LOCAL_DECL); } this.adjust_assign(nvars, nexps, e); this.adjustlocalvars(nvars); } boolean funcname(ExpDesc v) { //log.info(">>> funcname"); /* funcname -> NAME {field} [`:' NAME] */ boolean needself = false; PsiBuilder.Marker ref = builder.mark(); PsiBuilder.Marker tmp = ref; this.singlevar(v); int lastPos = builder.getCurrentOffset(); while (this.t == DOT) { this.field(v, ref); ref = ref.precede(); tmp.done(REFERENCE); tmp = ref; } if (this.t == COLON) { needself = true; this.field(v, ref); // ref = ref.precede(); tmp.done(REFERENCE); tmp = null; } if (tmp != null) // ref.done(REFERENCE); // else tmp.drop(); //log.info("<<< funcname"); return needself; } void funcstat(int line) { //log.info(">>> funcstat"); PsiBuilder.Marker funcStmt = builder.mark(); /* funcstat -> FUNCTION funcname body */ boolean needself; ExpDesc v = new ExpDesc(); ExpDesc b = new ExpDesc(); this.next(); /* skip FUNCTION */ PsiBuilder.Marker funcName = builder.mark(); needself = this.funcname(v); if (needself) funcName.done(FUNCTION_IDENTIFIER_NEEDSELF); else funcName.done(FUNCTION_IDENTIFIER); this.body(b, needself, line); funcStmt.done(FUNCTION_DEFINITION); fs.storevar(v, b); fs.fixline(line); /* definition `happens' in the first line */ ///log.info("<<< funcstat"); } void exprstat() { /* stat -> func | assignment */ FuncState fs = this.fs; LHS_assign v = new LHS_assign(); PsiBuilder.Marker mark = builder.mark(); this.primaryexp(v.v); if (v.v.k == VCALL) /* stat -> func */ { mark.done(FUNCTION_CALL); FuncState.SETARG_C(fs.getcodePtr(v.v), 1); /* call statement uses no results */ } else { /* stat -> assignment */ PsiBuilder.Marker expr = mark; mark = expr.precede(); v.prev = null; this.assignment(v, 1, expr); mark.done(ASSIGN_STMT); } } void retstat() { PsiBuilder.Marker mark = builder.mark(); boolean tailCall = false; /* stat -> RETURN explist */ FuncState fs = this.fs; ExpDesc e = new ExpDesc(); int first, nret; /* registers with returned values */ this.next(); /* skip RETURN */ if (block_follow(this.t) || this.t == SEMI) first = nret = 0; /* return no values */ else { nret = this.explist1(e); /* optional return values */ if (hasmultret(e.k)) { fs.setmultret(e); if (e.k == VCALL && nret == 1) { /* tail call? */ tailCall = true; FuncState.SET_OPCODE(fs.getcodePtr(e), FuncState.OP_TAILCALL); FuncState._assert(FuncState.GETARG_A(fs.getcode(e)) == fs.nactvar); } first = fs.nactvar; nret = FuncState.LUA_MULTRET; /* return all values */ } else { if (nret == 1) /* only one single value? */ first = fs.exp2anyreg(e); else { fs.exp2nextreg(e); /* values must go to the `stack' */ first = fs.nactvar; /* return all `active' values */ FuncState._assert(nret == fs.freereg - first); } } } mark.done(tailCall?RETURN_STATEMENT_WITH_TAIL_CALL:RETURN_STATEMENT); fs.ret(first, nret); } boolean statement() { try { //log.info(">>> statement"); int line = this.linenumber; /* may be needed for error messages */ if (this.t == IF) { /* stat -> ifstat */ this.ifstat(line); return false; } if (this.t == WHILE) { /* stat -> whilestat */ this.whilestat(line); return false; } if (this.t == DO) { /* stat -> DO block END */ PsiBuilder.Marker mark = builder.mark(); this.next(); /* skip DO */ this.block(); this.check_match(END, DO, line); mark.done(DO_BLOCK); return false; } if (this.t == FOR) { /* stat -> forstat */ this.forstat(line); return false; } if (this.t == REPEAT) { /* stat -> repeatstat */ this.repeatstat(line); return false; } if (this.t == FUNCTION) { this.funcstat(line); /* stat -> funcstat */ return false; } if (this.t == LOCAL) { /* stat -> localstat */ PsiBuilder.Marker stat = builder.mark(); this.next(); /* skip LOCAL */ if (this.t == FUNCTION) /* local function? */ this.localfunc(stat); else this.localstat(stat); return false; } if (this.t == RETURN) { /* stat -> retstat */ this.retstat(); return true; /* must be last statement */ } if (this.t == BREAK) { /* stat -> breakstat */ this.next(); /* skip BREAK */ this.breakstat(); return true; /* must be last statement */ } this.exprstat(); return false; /* to avoid warnings */ } finally { //log.info("<<< statement"); } } void chunk() { //log.info(">>> chunk"); /* chunk -> { stat [`;'] } */ boolean islast = false; this.enterlevel(); while (!islast && !block_follow(this.t)) { islast = this.statement(); this.testnext(SEMI); FuncState._assert(this.fs.f.maxStacksize >= this.fs.freereg && this.fs.freereg >= this.fs.nactvar); this.fs.freereg = this.fs.nactvar; /* free registers */ } this.leavelevel(); //log.info("<<< chunk"); } /* }====================================================================== */ @NotNull @Override public ASTNode parse(IElementType root, PsiBuilder builder) { final LuaPsiBuilder psiBuilder = new LuaPsiBuilder(builder); final PsiBuilder.Marker rootMarker = psiBuilder.mark(); String name = "todo:name"; source = name; KahluaParser lexstate = new KahluaParser(z, 0, source); FuncState funcstate = new FuncState(lexstate); // lexstate.buff = buff; /* main func. is always vararg */ funcstate.isVararg = FuncState.VARARG_ISVARARG; funcstate.f.name = name; lexstate.builder = psiBuilder; lexstate.t = psiBuilder.getTokenType(); if (lexstate.t == null) // Try to kludge in handling of partial parses lexstate.next(); /* read first token */ lexstate.chunk(); // lexstate.check(EMPTY_INPUT); lexstate.close_func(); FuncState._assert(funcstate.prev == null); FuncState._assert(funcstate.f.numUpvalues == 0); FuncState._assert(lexstate.fs == null); // return funcstate.f; if (root != null) rootMarker.done(root); return builder.getTreeBuilt(); } }
rework parsing of references. now all global and local names are references, individual fields are not
src/lang/parser/kahlua/KahluaParser.java
rework parsing of references. now all global and local names are references, individual fields are not
<ide><path>rc/lang/parser/kahlua/KahluaParser.java <ide> } <ide> <ide> void singlevar(ExpDesc var) { <add> <add> PsiBuilder.Marker ref = builder.mark(); <ide> PsiBuilder.Marker mark = builder.mark(); <ide> String varname = this.str_checkname(); <ide> <ide> } else { <ide> mark.done(LOCAL_NAME); <ide> } <add> <add> ref.done(REFERENCE); <ide> } <ide> <ide> void adjust_assign(int nvars, int nexps, ExpDesc e) { <ide> <ide> <ide> PsiBuilder.Marker mark = builder.mark(); <del> PsiBuilder.Marker ref = builder.mark(); <del> PsiBuilder.Marker tmp = ref; <add> // PsiBuilder.Marker ref = builder.mark(); <add> // PsiBuilder.Marker tmp = ref; <ide> <ide> FuncState fs = this.fs; <ide> this.prefixexp(v); <ide> <ide> if (this.t == DOT) { /* field */ <ide> this.field(v, mark); <del> if (tmp != null) { <del> ref = ref.precede(); <del> tmp.done(REFERENCE); <del> tmp = ref; <del> } <add>// if (tmp != null) { <add>// ref = ref.precede(); <add>// tmp.done(REFERENCE); <add>// tmp = ref; <add>// } <ide> // break; <ide> } else if (this.t == LBRACK) { /* `[' exp1 `]' */ <ide> ExpDesc key = new ExpDesc(); <ide> fs.exp2anyreg(v); <ide> this.yindex(key); <del> if (tmp != null) { <del> ref = ref.precede(); <del> tmp.done(REFERENCE); <del> tmp = ref; <del> } <add>// if (tmp != null) { <add>// ref = ref.precede(); <add>// tmp.done(REFERENCE); <add>// tmp = ref; <add>// } <ide> fs.indexed(v, key); <ide> // break; <ide> } else if (this.t == COLON) { /* `:' NAME funcargs */ <ide> this.next(); <ide> this.checkname(key); <ide> <del> // ref = ref.precede(); <del> if (tmp != null) <del> tmp.done(REFERENCE); <del> tmp = null; <add>// // ref = ref.precede(); <add>// if (tmp != null) <add>// tmp.done(REFERENCE); <add>// tmp = null; <ide> <ide> PsiBuilder.Marker call = null; <ide> <ide> || this.t == LCURLY) { /* funcargs */ <ide> fs.exp2nextreg(v); <ide> <del> if (tmp != null) { <del> tmp.drop(); tmp = null; <del> } <add>// if (tmp != null) { <add>// tmp.drop(); tmp = null; <add>// } <ide> <ide> PsiBuilder.Marker call = null; <ide> <ide> <ide> // break; <ide> } else { <del> if (tmp != null) <del> tmp.drop(); <add>// if (tmp != null) <add>// tmp.drop(); <ide> if (mark != null) <ide> mark.done(VARIABLE); <ide> return;
Java
mit
8de48db7c5d178520179d1f853d0c1943fae09aa
0
ohtuprojekti/OKKoPa,ohtuprojekti/OKKoPa
package fi.helsinki.cs.okkopa; import com.unboundid.ldap.sdk.LDAPException; import fi.helsinki.cs.okkopa.database.FailedEmailDatabase; import fi.helsinki.cs.okkopa.database.QRCodeDatabase; import fi.helsinki.cs.okkopa.delete.ErrorPDFRemover; import fi.helsinki.cs.okkopa.delete.Remover; import fi.helsinki.cs.okkopa.mail.read.EmailRead; import fi.helsinki.cs.okkopa.mail.send.ExamPaperSender; import fi.helsinki.cs.okkopa.exception.DocumentException; import fi.helsinki.cs.okkopa.exception.NotFoundException; import fi.helsinki.cs.okkopa.model.ExamPaper; import fi.helsinki.cs.okkopa.ldap.LdapConnector; import fi.helsinki.cs.okkopa.mail.writeToDisk.Saver; import fi.helsinki.cs.okkopa.model.FailedEmail; import fi.helsinki.cs.okkopa.model.Student; import fi.helsinki.cs.okkopa.pdfprocessor.PDFProcessor; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.nio.file.FileAlreadyExistsException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import org.apache.log4j.Logger; import javax.mail.MessagingException; import org.apache.commons.io.IOUtils; import org.jpedal.exception.PdfException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class OkkopaRunner implements Runnable { private PDFProcessor pDFProcessor; private EmailRead server; private ExamPaperSender sender; private static Logger LOGGER = Logger.getLogger(OkkopaRunner.class.getName()); private QRCodeDatabase qrCodeDatabase; private LdapConnector ldapConnector; private boolean saveToTikli; private boolean saveOnExamPaperPDFError; private boolean logCompleteExceptionStack; private final String saveErrorFolder; private Saver saver; private final String saveRetryFolder; // Used with email retry private int retryExpirationMinutes; private Remover errorPDFRemover; private FailedEmailDatabase failedEmailDatabase; @Autowired public OkkopaRunner(EmailRead server, ExamPaperSender sender, PDFProcessor pDFProcessor, Settings settings, QRCodeDatabase okkopaDatabase, LdapConnector ldapConnector, Saver saver, FailedEmailDatabase failedEmailDatabase) { this.server = server; this.sender = sender; this.pDFProcessor = pDFProcessor; this.qrCodeDatabase = okkopaDatabase; this.ldapConnector = ldapConnector; this.saver = saver; saveErrorFolder = settings.getSettings().getProperty("exampaper.saveunreadablefolder"); saveRetryFolder = settings.getSettings().getProperty("mail.send.retrysavefolder"); saveToTikli = Boolean.parseBoolean(settings.getSettings().getProperty("tikli.enable")); saveOnExamPaperPDFError = Boolean.parseBoolean(settings.getSettings().getProperty("exampaper.saveunreadable")); logCompleteExceptionStack = Boolean.parseBoolean(settings.getSettings().getProperty("logger.logcompletestack")); retryExpirationMinutes = Integer.parseInt(settings.getSettings().getProperty("mail.send.retryexpirationminutes")); this.errorPDFRemover = new ErrorPDFRemover(settings); this.failedEmailDatabase = failedEmailDatabase; } @Override public void run() { LOGGER.debug("Poistetaan vanhoja epäonnistuneita viestejä"); errorPDFRemover.deleteOldMessages(); retryFailedEmails(); try { server.connect(); LOGGER.debug("Kirjauduttu sisään."); while (true) { ArrayList<InputStream> attachments = server.getNextMessagesAttachments(); LOGGER.debug("Vanhimman viestin liitteet haettu"); if (attachments == null) { LOGGER.debug("Ei uusia viestejä."); break; } for (InputStream attachment : attachments) { LOGGER.debug("Käsitellään liitettä."); processAttachment(attachment); IOUtils.closeQuietly(attachment); } } } catch (MessagingException | IOException ex) { logException(ex); } finally { server.close(); } } private void processAttachment(InputStream inputStream) { List<ExamPaper> examPapers; // Split PDF to ExamPapers (2 pages per each). try { examPapers = pDFProcessor.splitPDF(inputStream); IOUtils.closeQuietly(inputStream); } catch (DocumentException ex) { // Errors: bad PDF-file, odd number of pages. logException(ex); // nothing to process, return return; } ExamPaper courseInfoPage = examPapers.get(0); String courseInfo = null; try { courseInfo = getCourseInfo(courseInfoPage); // Remove if succesful so that the page won't be processed as // a normal exam paper. examPapers.remove(courseInfoPage); } catch (NotFoundException ex) { logException(ex); } // Process all examPapers while (!examPapers.isEmpty()) { ExamPaper examPaper = examPapers.remove(0); processExamPaper(examPaper, courseInfo); } } private void processExamPaper(ExamPaper examPaper, String courseInfo) { try { examPaper.setPageImages(pDFProcessor.getPageImages(examPaper)); examPaper.setQRCodeString(pDFProcessor.readQRCode(examPaper)); } catch (PdfException | NotFoundException ex) { logException(ex); if (saveOnExamPaperPDFError) { try { LOGGER.debug("Tallennetaan virheellistä pdf tiedostoa kansioon " + saveErrorFolder); saver.saveInputStream(examPaper.getPdf(), saveErrorFolder, "" + System.currentTimeMillis() + ".pdf"); } catch (FileAlreadyExistsException ex1) { java.util.logging.Logger.getLogger(OkkopaRunner.class.getName()).log(Level.SEVERE, "File already exists", ex1); } } return; } String currentUserId; try { currentUserId = fetchUserId(examPaper.getQRCodeString()); } catch (SQLException | NotFoundException ex) { logException(ex); // QR code isn't an user id and doesn't match any database entries. return; } // Get email and student number from LDAP: try { examPaper.setStudent(ldapConnector.fetchStudent(currentUserId)); } catch (NotFoundException | LDAPException | GeneralSecurityException ex) { logException(ex); } // TODO remove when ldap has been implemented. //examPaper.setStudent(new Student(currentUserId, "[email protected]", "dummystudentnumber")); sendEmail(examPaper, true); LOGGER.debug("Koepaperi lähetetty sähköpostilla."); if (courseInfo != null && saveToTikli) { saveToTikli(examPaper); LOGGER.debug("Koepaperi tallennettu Tikliin."); } } public String getCourseInfo(ExamPaper examPaper) throws NotFoundException { // TODO unimplemented throw new NotFoundException("Course ID not found."); } private void saveToTikli(ExamPaper examPaper) { LOGGER.info("Tässä vaiheessa tallennettaisiin paperit Tikliin"); } private void sendEmail(ExamPaper examPaper, boolean saveOnError) { try { sender.send(examPaper); } catch (MessagingException ex) { LOGGER.debug("Sähköpostin lähetys epäonnistui. Tallennetaan PDF-liite levylle."); if (saveOnError) { saveFailedEmail(examPaper); } logException(ex); } } private void logException(Exception ex) { //Currently just logging exceptions. Should exception handling be in its own class? if (logCompleteExceptionStack) { LOGGER.error(ex.toString(), ex); } else { LOGGER.error(ex.toString()); } } private String fetchUserId(String qrcode) throws SQLException, NotFoundException { if (Character.isDigit(qrcode.charAt(0))) { return qrCodeDatabase.getUserID(qrcode); } return qrcode; } private void saveFailedEmail(ExamPaper examPaper) { try { String filename = "" + System.currentTimeMillis() + ".pdf"; saver.saveInputStream(examPaper.getPdf(), saveRetryFolder, filename); failedEmailDatabase.addFailedEmail(examPaper.getStudent().getEmail(), filename); } catch (FileAlreadyExistsException | SQLException ex1) { logException(ex1); // TODO if one fails what then? } } private void retryFailedEmails() { // Get failed email send attachments (PDF-files) LOGGER.debug("Yritetään lähettää sähköposteja uudelleen."); ArrayList<File> fileList = saver.list(saveRetryFolder); if (fileList == null) { LOGGER.debug("Ei uudelleenlähetettävää."); return; }; List<FailedEmail> failedEmails; try { failedEmails = failedEmailDatabase.listAll(); } catch (SQLException ex) { logException(ex); return; } for (FailedEmail failedEmail : failedEmails) { for (File pdf : fileList) { if (failedEmail.getFilename().equals(pdf.getName())) { try { FileInputStream fis = new FileInputStream(pdf); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(fis, bos); ExamPaper examPaper = new ExamPaper(); examPaper.setPdf(bos.toByteArray()); examPaper.setStudent(new Student()); examPaper.getStudent().setEmail(failedEmail.getReceiverEmail()); sendEmail(examPaper, false); IOUtils.closeQuietly(fis); // TODO expiration time and so on } catch (Exception ex) { logException(ex); continue; } } } } } }
src/main/java/fi/helsinki/cs/okkopa/OkkopaRunner.java
package fi.helsinki.cs.okkopa; import com.unboundid.ldap.sdk.LDAPException; import fi.helsinki.cs.okkopa.database.QRCodeDatabase; import fi.helsinki.cs.okkopa.delete.ErrorPDFRemover; import fi.helsinki.cs.okkopa.delete.Remover; import fi.helsinki.cs.okkopa.mail.read.EmailRead; import fi.helsinki.cs.okkopa.mail.send.ExamPaperSender; import fi.helsinki.cs.okkopa.exception.DocumentException; import fi.helsinki.cs.okkopa.exception.NotFoundException; import fi.helsinki.cs.okkopa.model.ExamPaper; import fi.helsinki.cs.okkopa.ldap.LdapConnector; import fi.helsinki.cs.okkopa.mail.writeToDisk.Saver; import fi.helsinki.cs.okkopa.model.Student; import fi.helsinki.cs.okkopa.pdfprocessor.PDFProcessor; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.nio.file.FileAlreadyExistsException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import org.apache.log4j.Logger; import javax.mail.MessagingException; import org.apache.commons.io.IOUtils; import org.jpedal.exception.PdfException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class OkkopaRunner implements Runnable { private PDFProcessor pDFProcessor; private EmailRead server; private ExamPaperSender sender; private static Logger LOGGER = Logger.getLogger(OkkopaRunner.class.getName()); private QRCodeDatabase qrCodeDatabase; private LdapConnector ldapConnector; private boolean saveToTikli; private boolean saveOnExamPaperPDFError; private boolean logCompleteExceptionStack; private final String saveErrorFolder; private Saver saver; private final String saveRetryFolder; // Used with email retry private boolean retrying; private boolean sent; private int retryExpirationMinutes; private Remover errorPDFRemover; @Autowired public OkkopaRunner(EmailRead server, ExamPaperSender sender, PDFProcessor pDFProcessor, Settings settings, QRCodeDatabase okkopaDatabase, LdapConnector ldapConnector, Saver saver) { this.server = server; this.sender = sender; this.pDFProcessor = pDFProcessor; this.qrCodeDatabase = okkopaDatabase; this.ldapConnector = ldapConnector; this.saver = saver; saveErrorFolder = settings.getSettings().getProperty("exampaper.saveunreadablefolder"); saveRetryFolder = settings.getSettings().getProperty("mail.send.retrysavefolder"); saveToTikli = Boolean.parseBoolean(settings.getSettings().getProperty("tikli.enable")); saveOnExamPaperPDFError = Boolean.parseBoolean(settings.getSettings().getProperty("exampaper.saveunreadable")); logCompleteExceptionStack = Boolean.parseBoolean(settings.getSettings().getProperty("logger.logcompletestack")); retryExpirationMinutes = Integer.parseInt(settings.getSettings().getProperty("mail.send.retryexpirationminutes")); retrying = false; sent = true; this.errorPDFRemover = new ErrorPDFRemover(settings); } @Override public void run() { LOGGER.debug("Poistetaan vanhoja epäonnistuneita viestejä"); errorPDFRemover.deleteOldMessages(); retrying = true; retryFailedEmails(); retrying = false; try { server.connect(); LOGGER.debug("Kirjauduttu sisään."); while (true) { ArrayList<InputStream> attachments = server.getNextMessagesAttachments(); LOGGER.debug("Vanhimman viestin liitteet haettu"); if (attachments == null) { LOGGER.debug("Ei uusia viestejä."); break; } for (InputStream attachment : attachments) { LOGGER.debug("Käsitellään liitettä."); processAttachment(attachment); IOUtils.closeQuietly(attachment); } } } catch (MessagingException | IOException ex) { logException(ex); } finally { server.close(); } } private void processAttachment(InputStream inputStream) { List<ExamPaper> examPapers; // Split PDF to ExamPapers (2 pages per each). try { examPapers = pDFProcessor.splitPDF(inputStream); IOUtils.closeQuietly(inputStream); } catch (DocumentException ex) { // Errors: bad PDF-file, odd number of pages. logException(ex); // nothing to process, return return; } ExamPaper courseInfoPage = examPapers.get(0); String courseInfo = null; try { courseInfo = getCourseInfo(courseInfoPage); // Remove if succesful so that the page won't be processed as // a normal exam paper. examPapers.remove(courseInfoPage); } catch (NotFoundException ex) { logException(ex); } // Process all examPapers while (!examPapers.isEmpty()) { ExamPaper examPaper = examPapers.remove(0); processExamPaper(examPaper, courseInfo); } } private void processExamPaper(ExamPaper examPaper, String courseInfo) { try { examPaper.setPageImages(pDFProcessor.getPageImages(examPaper)); examPaper.setQRCodeString(pDFProcessor.readQRCode(examPaper)); } catch (PdfException | NotFoundException ex) { logException(ex); if (saveOnExamPaperPDFError) { try { LOGGER.debug("Tallennetaan virheellistä pdf tiedostoa kansioon "+saveErrorFolder); saver.saveInputStream(examPaper.getPdf(), saveErrorFolder, "" + System.currentTimeMillis() + ".pdf"); } catch (FileAlreadyExistsException ex1) { java.util.logging.Logger.getLogger(OkkopaRunner.class.getName()).log(Level.SEVERE, "File already exists", ex1); } } return; } String currentUserId; try { currentUserId = fetchUserId(examPaper.getQRCodeString()); } catch (SQLException | NotFoundException ex) { logException(ex); // QR code isn't an user id and doesn't match any database entries. return; } // Get email and student number from LDAP: try { examPaper.setStudent(ldapConnector.fetchStudent(currentUserId)); } catch (NotFoundException | LDAPException | GeneralSecurityException ex) { logException(ex); } // TODO remove when ldap has been implemented. //examPaper.setStudent(new Student(currentUserId, "[email protected]", "dummystudentnumber")); sendEmail(examPaper); LOGGER.debug("Koepaperi lähetetty sähköpostilla."); if (courseInfo != null && saveToTikli) { saveToTikli(examPaper); LOGGER.debug("Koepaperi tallennettu Tikliin."); } } public String getCourseInfo(ExamPaper examPaper) throws NotFoundException { // TODO unimplemented throw new NotFoundException("Course ID not found."); } private void saveToTikli(ExamPaper examPaper) { LOGGER.info("Tässä vaiheessa tallennettaisiin paperit Tikliin"); } private void sendEmail(ExamPaper examPaper) { try { sender.send(examPaper); sent = true; } catch (MessagingException ex) { if (!retrying) { LOGGER.debug("Sähköpostin lähetys epäonnistui. Tallennetaan PDF-liite levylle."); try { saver.saveInputStream(examPaper.getPdf(), saveRetryFolder, "" + System.currentTimeMillis() + ".pdf"); } catch (FileAlreadyExistsException ex1) { logException(ex1); } } logException(ex); sent = false; } } private void logException(Exception ex) { //Currently just logging exceptions. Should exception handling be in its own class? if (logCompleteExceptionStack) { LOGGER.error(ex.toString(), ex); } else { LOGGER.error(ex.toString()); } } private String fetchUserId(String qrcode) throws SQLException, NotFoundException { if (Character.isDigit(qrcode.charAt(0))) { return qrCodeDatabase.getUserID(qrcode); } return qrcode; } private void retryFailedEmails() { // Get failed email send attachments (PDF-files) LOGGER.debug("Yritetään lähettää sähköposteja uudelleen."); ArrayList<File> fileList = saver.list(saveRetryFolder); if (fileList == null) { LOGGER.debug("Ei uudelleenlähetettävää."); return; }; LOGGER.debug(fileList.size() + " uudelleenlähetettävää säilössä."); for (File pdf : fileList) { FileInputStream fis; try { fis = new FileInputStream(pdf); } catch (FileNotFoundException ex) { logException(ex); continue; } // Send each single PDF through the whole process. processAttachment(fis); IOUtils.closeQuietly(fis); long fileAge = (System.currentTimeMillis() - pdf.lastModified()) / 60000; if (sent || fileAge > retryExpirationMinutes) { pdf.delete(); } } } }
email retry to db
src/main/java/fi/helsinki/cs/okkopa/OkkopaRunner.java
email retry to db
<ide><path>rc/main/java/fi/helsinki/cs/okkopa/OkkopaRunner.java <ide> package fi.helsinki.cs.okkopa; <ide> <ide> import com.unboundid.ldap.sdk.LDAPException; <add>import fi.helsinki.cs.okkopa.database.FailedEmailDatabase; <ide> import fi.helsinki.cs.okkopa.database.QRCodeDatabase; <ide> import fi.helsinki.cs.okkopa.delete.ErrorPDFRemover; <ide> import fi.helsinki.cs.okkopa.delete.Remover; <ide> import fi.helsinki.cs.okkopa.model.ExamPaper; <ide> import fi.helsinki.cs.okkopa.ldap.LdapConnector; <ide> import fi.helsinki.cs.okkopa.mail.writeToDisk.Saver; <add>import fi.helsinki.cs.okkopa.model.FailedEmail; <ide> import fi.helsinki.cs.okkopa.model.Student; <ide> import fi.helsinki.cs.okkopa.pdfprocessor.PDFProcessor; <add>import java.io.ByteArrayOutputStream; <ide> import java.io.File; <ide> import java.io.FileInputStream; <del>import java.io.FileNotFoundException; <ide> import java.io.IOException; <ide> import java.io.InputStream; <ide> import java.security.GeneralSecurityException; <ide> private Saver saver; <ide> private final String saveRetryFolder; <ide> // Used with email retry <del> private boolean retrying; <del> private boolean sent; <ide> private int retryExpirationMinutes; <ide> private Remover errorPDFRemover; <add> private FailedEmailDatabase failedEmailDatabase; <ide> <ide> @Autowired <ide> public OkkopaRunner(EmailRead server, ExamPaperSender sender, <ide> PDFProcessor pDFProcessor, Settings settings, <del> QRCodeDatabase okkopaDatabase, LdapConnector ldapConnector, Saver saver) { <add> QRCodeDatabase okkopaDatabase, LdapConnector ldapConnector, Saver saver, <add> FailedEmailDatabase failedEmailDatabase) { <ide> this.server = server; <ide> this.sender = sender; <ide> this.pDFProcessor = pDFProcessor; <ide> saveOnExamPaperPDFError = Boolean.parseBoolean(settings.getSettings().getProperty("exampaper.saveunreadable")); <ide> logCompleteExceptionStack = Boolean.parseBoolean(settings.getSettings().getProperty("logger.logcompletestack")); <ide> retryExpirationMinutes = Integer.parseInt(settings.getSettings().getProperty("mail.send.retryexpirationminutes")); <del> retrying = false; <del> sent = true; <ide> this.errorPDFRemover = new ErrorPDFRemover(settings); <add> this.failedEmailDatabase = failedEmailDatabase; <ide> } <ide> <ide> @Override <ide> public void run() { <ide> LOGGER.debug("Poistetaan vanhoja epäonnistuneita viestejä"); <ide> errorPDFRemover.deleteOldMessages(); <del> retrying = true; <ide> retryFailedEmails(); <del> retrying = false; <ide> try { <ide> server.connect(); <ide> LOGGER.debug("Kirjauduttu sisään."); <ide> logException(ex); <ide> if (saveOnExamPaperPDFError) { <ide> try { <del> LOGGER.debug("Tallennetaan virheellistä pdf tiedostoa kansioon "+saveErrorFolder); <add> LOGGER.debug("Tallennetaan virheellistä pdf tiedostoa kansioon " + saveErrorFolder); <ide> saver.saveInputStream(examPaper.getPdf(), saveErrorFolder, "" + System.currentTimeMillis() + ".pdf"); <ide> } catch (FileAlreadyExistsException ex1) { <ide> java.util.logging.Logger.getLogger(OkkopaRunner.class.getName()).log(Level.SEVERE, "File already exists", ex1); <ide> // TODO remove when ldap has been implemented. <ide> //examPaper.setStudent(new Student(currentUserId, "[email protected]", "dummystudentnumber")); <ide> <del> sendEmail(examPaper); <add> sendEmail(examPaper, true); <ide> LOGGER.debug("Koepaperi lähetetty sähköpostilla."); <ide> if (courseInfo != null && saveToTikli) { <ide> saveToTikli(examPaper); <ide> LOGGER.info("Tässä vaiheessa tallennettaisiin paperit Tikliin"); <ide> } <ide> <del> private void sendEmail(ExamPaper examPaper) { <add> private void sendEmail(ExamPaper examPaper, boolean saveOnError) { <ide> try { <ide> sender.send(examPaper); <del> sent = true; <ide> } catch (MessagingException ex) { <del> if (!retrying) { <del> LOGGER.debug("Sähköpostin lähetys epäonnistui. Tallennetaan PDF-liite levylle."); <del> try { <del> saver.saveInputStream(examPaper.getPdf(), saveRetryFolder, "" + System.currentTimeMillis() + ".pdf"); <del> } catch (FileAlreadyExistsException ex1) { <del> logException(ex1); <del> } <del> } <del> logException(ex); <del> sent = false; <add> LOGGER.debug("Sähköpostin lähetys epäonnistui. Tallennetaan PDF-liite levylle."); <add> if (saveOnError) { <add> saveFailedEmail(examPaper); <add> } <add> logException(ex); <ide> } <ide> } <ide> <ide> return qrcode; <ide> } <ide> <add> private void saveFailedEmail(ExamPaper examPaper) { <add> try { <add> String filename = "" + System.currentTimeMillis() + ".pdf"; <add> saver.saveInputStream(examPaper.getPdf(), saveRetryFolder, filename); <add> failedEmailDatabase.addFailedEmail(examPaper.getStudent().getEmail(), filename); <add> } catch (FileAlreadyExistsException | SQLException ex1) { <add> logException(ex1); <add> // TODO if one fails what then? <add> } <add> } <add> <ide> private void retryFailedEmails() { <ide> // Get failed email send attachments (PDF-files) <ide> LOGGER.debug("Yritetään lähettää sähköposteja uudelleen."); <ide> LOGGER.debug("Ei uudelleenlähetettävää."); <ide> return; <ide> }; <del> LOGGER.debug(fileList.size() + " uudelleenlähetettävää säilössä."); <del> for (File pdf : fileList) { <del> FileInputStream fis; <del> try { <del> fis = new FileInputStream(pdf); <del> } catch (FileNotFoundException ex) { <del> logException(ex); <del> continue; <del> } <del> // Send each single PDF through the whole process. <del> processAttachment(fis); <del> IOUtils.closeQuietly(fis); <del> <del> long fileAge = (System.currentTimeMillis() - pdf.lastModified()) / 60000; <del> if (sent || fileAge > retryExpirationMinutes) { <del> pdf.delete(); <add> List<FailedEmail> failedEmails; <add> try { <add> failedEmails = failedEmailDatabase.listAll(); <add> } catch (SQLException ex) { <add> logException(ex); <add> return; <add> } <add> for (FailedEmail failedEmail : failedEmails) { <add> for (File pdf : fileList) { <add> if (failedEmail.getFilename().equals(pdf.getName())) { <add> try { <add> FileInputStream fis = new FileInputStream(pdf); <add> ByteArrayOutputStream bos = new ByteArrayOutputStream(); <add> IOUtils.copy(fis, bos); <add> ExamPaper examPaper = new ExamPaper(); <add> examPaper.setPdf(bos.toByteArray()); <add> examPaper.setStudent(new Student()); <add> examPaper.getStudent().setEmail(failedEmail.getReceiverEmail()); <add> sendEmail(examPaper, false); <add> IOUtils.closeQuietly(fis); <add> // TODO expiration time and so on <add> } catch (Exception ex) { <add> logException(ex); <add> continue; <add> } <add> } <ide> } <ide> } <ide> }
Java
agpl-3.0
c0b5d28a01b4c008d2e9c006aa075d557e88876a
0
duncte123/SkyBot,duncte123/SkyBot,duncte123/SkyBot,duncte123/SkyBot
/* * Skybot, a multipurpose discord bot * Copyright (C) 2017 - 2020 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan & Maurice R S "Sanduhr32" * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ml.duncte123.skybot.commands.guild.mod; import io.sentry.Sentry; import ml.duncte123.skybot.Author; import ml.duncte123.skybot.objects.command.CommandContext; import ml.duncte123.skybot.objects.command.Flag; import ml.duncte123.skybot.utils.AirUtils; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.exceptions.ErrorResponseException; import net.dv8tion.jda.api.requests.ErrorResponse; import net.dv8tion.jda.api.requests.Request; import net.dv8tion.jda.api.requests.RestFuture; import javax.annotation.Nonnull; import java.lang.reflect.Field; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; import static me.duncte123.botcommons.messaging.MessageUtils.*; import static ml.duncte123.skybot.utils.ModerationUtils.modLog; @Author(nickname = "Sanduhr32", author = "Maurice R S") public class CleanupCommand extends ModBaseCommand { public CleanupCommand() { this.name = "cleanup"; this.aliases = new String[]{ "clear", "purge", "wipe", }; this.help = "Performs a purge in the channel where the command is run.\n" + "To clear an entire channel it's better to use `{prefix}purgechannel`"; this.usage = "[amount] [--keep-pinned] [--bots-only]"; this.userPermissions = new Permission[]{ Permission.MESSAGE_MANAGE, Permission.MESSAGE_HISTORY, }; this.botPermissions = new Permission[]{ Permission.MESSAGE_MANAGE, Permission.MESSAGE_HISTORY, }; this.flags = new Flag[]{ new Flag( "keep-pinned", "If this flag is set the messages that are pinned in the channel will be skipped" ), new Flag( "bots-only", "If this flag is set only messages that are from bots will be deleted" ), }; } @Override public void execute(@Nonnull CommandContext ctx) { final List<String> args = ctx.getArgs(); int total = 5; if (args.size() > 3) { sendErrorWithMessage(ctx.getMessage(), "Usage: " + this.getUsageInstructions(ctx.getPrefix(), ctx.getInvoke())); return; } final var flags = ctx.getParsedFlags(this); final boolean keepPinned = flags.containsKey("keep-pinned"); final boolean clearBots = flags.containsKey("bots-only"); // if size == 0 then this will just be skipped for (final String arg : args) { if (AirUtils.isInt(arg)) { try { total = Integer.parseInt(args.get(0)); } catch (NumberFormatException e) { sendError(ctx.getMessage()); sendMsg(ctx, "Error: Amount to clear is not a valid number"); return; } if (total < 1 || total > 1000) { sendMsgAndDeleteAfter(ctx.getEvent(), 5, TimeUnit.SECONDS, "Error: count must be minimal 2 and maximal 1000\n" + "To clear an entire channel it's better to use `" + ctx.getPrefix() + "purgechannel`"); return; } } } final TextChannel channel = ctx.getChannel(); // Start of the annotation channel.getIterableHistory().takeAsync(total).thenApplyAsync((msgs) -> { Stream<Message> msgStream = msgs.stream(); if (keepPinned) { msgStream = msgStream.filter((msg) -> !msg.isPinned()); } if (clearBots) { msgStream = msgStream.filter((msg) -> msg.getAuthor().isBot()); } final List<Message> msgList = msgStream //TODO: Still needed? // .filter((msg) -> msg.getCreationTime().isBefore(OffsetDateTime.now().plus(2, ChronoUnit.WEEKS))) .collect(Collectors.toList()); final CompletableFuture<Message> hack = new CompletableFuture<>(); sendMsg(ctx, "Deleting messages, please wait this might take a long time (message will be deleted once complete)", hack::complete); try { final CompletableFuture<?>[] futures = channel.purgeMessages(msgList) .stream() .map(this::hackTimeout) .toArray(CompletableFuture[]::new); CompletableFuture.allOf(futures).get(); } catch (ErrorResponseException e) { if (e.getErrorResponse() == ErrorResponse.UNKNOWN_CHANNEL) { modLog(String.format("Failed to delete messages in %s, channel was deleted during progress", channel), ctx.getGuild()); return -100; } Sentry.capture(e); } catch (InterruptedException | ExecutionException e) { Sentry.capture(e); } finally { removeMessage(channel, hack); } return msgList.size(); }).exceptionally((thr) -> { String cause = ""; if (thr.getCause() != null) { cause = " caused by: " + thr.getCause().getMessage(); } sendMsg(ctx, "ERROR: " + thr.getMessage() + cause); return -100; }).whenCompleteAsync((count, thr) -> { if (count == -100) { return; } sendMsgFormatAndDeleteAfter(ctx.getEvent(), 5, TimeUnit.SECONDS, "Removed %d messages! (this message will auto delete in 5 seconds)", count); modLog(String.format("%d messages removed in %s by %s", count, channel, ctx.getAuthor().getAsTag()), ctx.getGuild()); }); // End of the annotation } /** * This method sets the timeout on a RestAction to -1 to make it not time out * * @param future the RestFuture to change the timeout of * @return the future with a different timeout */ @SuppressWarnings("rawtypes") private CompletableFuture<Void> hackTimeout(CompletableFuture<Void> future) { if (!(future instanceof RestFuture)) { // Ignore stuff that is not a rest future return future; } final Class<? extends RestFuture> futureClass = ((RestFuture<Void>) future).getClass(); try { final Field requestField = futureClass.getDeclaredField("request"); requestField.setAccessible(true); //noinspection unchecked final Request<Void> request = (Request<Void>) requestField.get(future); final Class<? extends Request> requestClass = request.getClass(); final Field deadlineField = requestClass.getDeclaredField("deadline"); deadlineField.setAccessible(true); // Set the deadline to -1 so this rest action cannot time out deadlineField.set(request, -1L); } catch (NoSuchFieldException | IllegalAccessException ignored) { // Ignore this stuff } return future; } private void removeMessage(TextChannel channel, CompletableFuture<Message> hack) { try { final Message hacked = hack.get(); if (hacked != null) { channel.deleteMessageById(hacked.getIdLong()).queue(); } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } }
src/main/java/ml/duncte123/skybot/commands/guild/mod/CleanupCommand.java
/* * Skybot, a multipurpose discord bot * Copyright (C) 2017 - 2020 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan & Maurice R S "Sanduhr32" * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ml.duncte123.skybot.commands.guild.mod; import io.sentry.Sentry; import ml.duncte123.skybot.Author; import ml.duncte123.skybot.objects.command.CommandContext; import ml.duncte123.skybot.objects.command.Flag; import ml.duncte123.skybot.utils.AirUtils; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.exceptions.ErrorResponseException; import net.dv8tion.jda.api.requests.ErrorResponse; import javax.annotation.Nonnull; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; import static me.duncte123.botcommons.messaging.MessageUtils.*; import static ml.duncte123.skybot.utils.ModerationUtils.modLog; @Author(nickname = "Sanduhr32", author = "Maurice R S") public class CleanupCommand extends ModBaseCommand { public CleanupCommand() { this.name = "cleanup"; this.aliases = new String[]{ "clear", "purge", "wipe", }; this.help = "Performs a purge in the channel where the command is run.\n" + "To clear an entire channel it's better to use `{prefix}purgechannel`"; this.usage = "[amount] [--keep-pinned] [--bots-only]"; this.userPermissions = new Permission[]{ Permission.MESSAGE_MANAGE, Permission.MESSAGE_HISTORY, }; this.botPermissions = new Permission[]{ Permission.MESSAGE_MANAGE, Permission.MESSAGE_HISTORY, }; this.flags = new Flag[]{ new Flag( "keep-pinned", "If this flag is set the messages that are pinned in the channel will be skipped" ), new Flag( "bots-only", "If this flag is set only messages that are from bots will be deleted" ), }; } @Override public void execute(@Nonnull CommandContext ctx) { final List<String> args = ctx.getArgs(); int total = 5; if (args.size() > 3) { sendErrorWithMessage(ctx.getMessage(), "Usage: " + this.getUsageInstructions(ctx.getPrefix(), ctx.getInvoke())); return; } final var flags = ctx.getParsedFlags(this); final boolean keepPinned = flags.containsKey("keep-pinned"); final boolean clearBots = flags.containsKey("bots-only"); // if size == 0 then this will just be skipped for (final String arg : args) { if (AirUtils.isInt(arg)) { try { total = Integer.parseInt(args.get(0)); } catch (NumberFormatException e) { sendError(ctx.getMessage()); sendMsg(ctx, "Error: Amount to clear is not a valid number"); return; } if (total < 1 || total > 1000) { sendMsgAndDeleteAfter(ctx.getEvent(), 5, TimeUnit.SECONDS, "Error: count must be minimal 2 and maximal 1000\n" + "To clear an entire channel it's better to use `" + ctx.getPrefix() + "purgechannel`"); return; } } } final TextChannel channel = ctx.getChannel(); // Start of the annotation channel.getIterableHistory().takeAsync(total).thenApplyAsync((msgs) -> { Stream<Message> msgStream = msgs.stream(); if (keepPinned) { msgStream = msgStream.filter((msg) -> !msg.isPinned()); } if (clearBots) { msgStream = msgStream.filter((msg) -> msg.getAuthor().isBot()); } final List<Message> msgList = msgStream //TODO: Still needed? // .filter((msg) -> msg.getCreationTime().isBefore(OffsetDateTime.now().plus(2, ChronoUnit.WEEKS))) .collect(Collectors.toList()); final CompletableFuture<Message> hack = new CompletableFuture<>(); sendMsg(ctx, "Deleting messages, please wait this might take a while (message will be deleted once complete)", hack::complete); try { final List<CompletableFuture<Void>> futures = channel.purgeMessages(msgList); CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get(); } catch (ErrorResponseException e) { if (e.getErrorResponse() == ErrorResponse.UNKNOWN_CHANNEL) { modLog(String.format("Failed to delete messages in %s, channel was deleted during progress", channel), ctx.getGuild()); return -100; } Sentry.capture(e); } catch (InterruptedException | ExecutionException e) { Sentry.capture(e); } finally { removeMessage(channel, hack); } return msgList.size(); }).exceptionally((thr) -> { String cause = ""; if (thr.getCause() != null) { cause = " caused by: " + thr.getCause().getMessage(); } sendMsg(ctx, "ERROR: " + thr.getMessage() + cause); return -100; }).whenCompleteAsync((count, thr) -> { if (count == -100) { return; } sendMsgFormatAndDeleteAfter(ctx.getEvent(), 5, TimeUnit.SECONDS, "Removed %d messages! (this message will auto delete in 5 seconds)", count); modLog(String.format("%d messages removed in %s by %s", count, channel, ctx.getAuthor().getAsTag()), ctx.getGuild()); }); // End of the annotation } private void removeMessage(TextChannel channel, CompletableFuture<Message> hack) { try { final Message hacked = hack.get(); if (hacked != null) { channel.deleteMessageById(hacked.getIdLong()).queue(); } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } }
Force cleanup timeouts to -1, fixes DUNCTEBOT-G5
src/main/java/ml/duncte123/skybot/commands/guild/mod/CleanupCommand.java
Force cleanup timeouts to -1, fixes DUNCTEBOT-G5
<ide><path>rc/main/java/ml/duncte123/skybot/commands/guild/mod/CleanupCommand.java <ide> import net.dv8tion.jda.api.entities.TextChannel; <ide> import net.dv8tion.jda.api.exceptions.ErrorResponseException; <ide> import net.dv8tion.jda.api.requests.ErrorResponse; <add>import net.dv8tion.jda.api.requests.Request; <add>import net.dv8tion.jda.api.requests.RestFuture; <ide> <ide> import javax.annotation.Nonnull; <add>import java.lang.reflect.Field; <ide> import java.util.List; <ide> import java.util.concurrent.CompletableFuture; <ide> import java.util.concurrent.ExecutionException; <ide> .collect(Collectors.toList()); <ide> <ide> final CompletableFuture<Message> hack = new CompletableFuture<>(); <del> sendMsg(ctx, "Deleting messages, please wait this might take a while (message will be deleted once complete)", hack::complete); <add> sendMsg(ctx, "Deleting messages, please wait this might take a long time (message will be deleted once complete)", hack::complete); <ide> <ide> try { <del> final List<CompletableFuture<Void>> futures = channel.purgeMessages(msgList); <del> <del> CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get(); <add> final CompletableFuture<?>[] futures = channel.purgeMessages(msgList) <add> .stream() <add> .map(this::hackTimeout) <add> .toArray(CompletableFuture[]::new); <add> <add> CompletableFuture.allOf(futures).get(); <ide> } catch (ErrorResponseException e) { <ide> if (e.getErrorResponse() == ErrorResponse.UNKNOWN_CHANNEL) { <ide> modLog(String.format("Failed to delete messages in %s, channel was deleted during progress", channel), ctx.getGuild()); <ide> // End of the annotation <ide> } <ide> <add> /** <add> * This method sets the timeout on a RestAction to -1 to make it not time out <add> * <add> * @param future the RestFuture to change the timeout of <add> * @return the future with a different timeout <add> */ <add> @SuppressWarnings("rawtypes") <add> private CompletableFuture<Void> hackTimeout(CompletableFuture<Void> future) { <add> if (!(future instanceof RestFuture)) { <add> // Ignore stuff that is not a rest future <add> return future; <add> } <add> <add> final Class<? extends RestFuture> futureClass = ((RestFuture<Void>) future).getClass(); <add> <add> try { <add> final Field requestField = futureClass.getDeclaredField("request"); <add> <add> requestField.setAccessible(true); <add> <add> //noinspection unchecked <add> final Request<Void> request = (Request<Void>) requestField.get(future); <add> final Class<? extends Request> requestClass = request.getClass(); <add> <add> final Field deadlineField = requestClass.getDeclaredField("deadline"); <add> <add> deadlineField.setAccessible(true); <add> <add> // Set the deadline to -1 so this rest action cannot time out <add> deadlineField.set(request, -1L); <add> } <add> catch (NoSuchFieldException | IllegalAccessException ignored) { <add> // Ignore this stuff <add> } <add> <add> return future; <add> } <add> <ide> private void removeMessage(TextChannel channel, CompletableFuture<Message> hack) { <ide> try { <ide> final Message hacked = hack.get();
Java
mit
2e7d9ecd3f13befa879eb9025dd3c054a6bbb616
0
Skaito/NppUDLThemeSwitcher
package lt.realmdev.nppudlthemeswitcher; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * * @author Marius Tomas <[email protected]> */ public class UDLItem { private final File path; private final String name; public UDLItem(File path, String name) { this.path = path; this.name = name; } public void applyTheme(ThemeItem theme) { if (path != null && path.isFile()) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; try { db = dbf.newDocumentBuilder(); Document doc = db.parse(path); NodeList nodes = null; for (int i = 0, c = doc.getChildNodes().getLength(); i < c; i++) { if (doc.getChildNodes().item(i).getNodeName().equals("NotepadPlus")) { nodes = doc.getChildNodes().item(i).getChildNodes(); break; } } if (nodes == null) return; for (int i = 0, c = nodes.getLength(); i < c; i++) { if (nodes.item(i).getNodeName().equals("UserLang")) { String uName = nodes.item(i).getAttributes().getNamedItem("name").getNodeValue(); if (!uName.equals(name)) continue; theme.loadData(); ThemeStyle defaultStyle = theme.styles.containsKey(ThemeItem.STYLE_DEFAULT) ? theme.styles.get(ThemeItem.STYLE_DEFAULT) : null; if (defaultStyle == null) Logger.getLogger(UDLItem.class.getName()).log(Level.WARNING, "Default theme style not found."); for (int n = 0, cn = nodes.item(i).getChildNodes().getLength(); n < cn; n++) { Node nBlock = nodes.item(i).getChildNodes().item(n); if (nBlock.getNodeName().equals("KeywordLists")) { for (int t = 0, ct = nBlock.getChildNodes().getLength(); t < ct; t++) { Node nKeywords = nBlock.getChildNodes().item(t); if (nKeywords.getNodeName().equals("Keywords")) { String sName = nKeywords.getAttributes().getNamedItem("name").getNodeValue(); if (sName.matches("^Keywords[0-9]+$")) { Node cNode = nKeywords.getFirstChild(); if (cNode != null && cNode.getNodeType() == Node.TEXT_NODE) { cNode.setNodeValue(cNode.getNodeValue().replaceAll("[\r\n ]+", " ")); } } } } } else if (nBlock.getNodeName().equals("Styles")) { for (int t = 0, ct = nBlock.getChildNodes().getLength(); t < ct; t++) { Node nStyle = nBlock.getChildNodes().item(t); if (nStyle.getNodeName().equals("WordsStyle")) { String sName = nStyle.getAttributes().getNamedItem("name").getNodeValue(); if (sName.equals("DEFAULT")) { applyStyleToNode(nStyle, defaultStyle); } else if (sName.equals("COMMENTS")) { lookupAndApplyStyleToNode(nStyle, theme.styles, ThemeItem.STYLE_COMMENT, defaultStyle); } else if (sName.equals("LINE COMMENTS")) { lookupAndApplyStyleToNode(nStyle, theme.styles, ThemeItem.STYLE_COMMENT_LINE, defaultStyle); } else if (sName.equals("NUMBERS")) { lookupAndApplyStyleToNode(nStyle, theme.styles, ThemeItem.STYLE_NUMBER, defaultStyle); } else if (sName.matches("^KEYWORDS[0-9]+$")) { lookupAndApplyStyleToNode(nStyle, theme.styles, ThemeItem.STYLE_INSTRUCTION_WORD, defaultStyle); } else if (sName.equals("OPERATORS")) { lookupAndApplyStyleToNode(nStyle, theme.styles, ThemeItem.STYLE_OPERATOR, defaultStyle); } else if (sName.matches("^FOLDER IN CODE[0-9]+$")) { applyStyleToNode(nStyle, defaultStyle); } else if (sName.equals("FOLDER IN COMMENT")) { applyStyleToNode(nStyle, defaultStyle); } else if (sName.matches("^DELIMITERS[0-9]+$")) { lookupAndApplyStyleToNode(nStyle, theme.styles, ThemeItem.STYLE_STRING, defaultStyle); } else { applyStyleToNode(nStyle, defaultStyle); } } } } } } } if (!path.isFile()) path.createNewFile(); try (FileOutputStream fos = new FileOutputStream(path)) { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(fos); transformer.transform(source, result); } catch (TransformerException ex) { Logger.getLogger(UDLItem.class.getName()).log(Level.SEVERE, null, ex); } } catch (ParserConfigurationException | SAXException | IOException ex) { Logger.getLogger(UDLItem.class.getName()).log(Level.SEVERE, null, ex); } } } private void lookupAndApplyStyleToNode(Node styleNode, Map<String, ThemeStyle> styles, String name, ThemeStyle defaultStyle) { ThemeStyle style = styles.containsKey(name) ? styles.get(name) : null; if (style == null) { style = defaultStyle; Logger.getLogger(UDLItem.class.getName()).log(Level.WARNING, "Theme style ''{0}'' not found, using default style.", name); } applyStyleToNode(styleNode, style); } private void applyStyleToNode(Node styleNode, ThemeStyle style) { if (style == null) return; styleNode.getAttributes().getNamedItem("fgColor").setNodeValue(style.getFgColor()); styleNode.getAttributes().getNamedItem("bgColor").setNodeValue(style.getBgColor()); styleNode.getAttributes().getNamedItem("fontName").setNodeValue(style.getFontName()); styleNode.getAttributes().getNamedItem("fontStyle").setNodeValue(String.valueOf(style.getFontStyle())); } public File getPath() { return path; } public String getName() { return name; } @Override public String toString() { return name; } }
src/main/java/lt/realmdev/nppudlthemeswitcher/UDLItem.java
package lt.realmdev.nppudlthemeswitcher; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * * @author Marius Tomas <[email protected]> */ public class UDLItem { private final File path; private final String name; public UDLItem(File path, String name) { this.path = path; this.name = name; } public void applyTheme(ThemeItem theme) { if (path != null && path.isFile()) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; try { db = dbf.newDocumentBuilder(); Document doc = db.parse(path); NodeList nodes = null; for (int i = 0, c = doc.getChildNodes().getLength(); i < c; i++) { if (doc.getChildNodes().item(i).getNodeName().equals("NotepadPlus")) { nodes = doc.getChildNodes().item(i).getChildNodes(); break; } } if (nodes == null) return; for (int i = 0, c = nodes.getLength(); i < c; i++) { if (nodes.item(i).getNodeName().equals("UserLang")) { String uName = nodes.item(i).getAttributes().getNamedItem("name").getNodeValue(); if (!uName.equals(name)) continue; theme.loadData(); ThemeStyle defaultStyle = theme.styles.containsKey(ThemeItem.STYLE_DEFAULT) ? theme.styles.get(ThemeItem.STYLE_DEFAULT) : null; if (defaultStyle == null) Logger.getLogger(UDLItem.class.getName()).log(Level.WARNING, "Default theme style not found."); for (int n = 0, cn = nodes.item(i).getChildNodes().getLength(); n < cn; n++) { Node nBlock = nodes.item(i).getChildNodes().item(n); if (nBlock.getNodeName().equals("KeywordLists")) { for (int t = 0, ct = nBlock.getChildNodes().getLength(); t < ct; t++) { Node nKeywords = nBlock.getChildNodes().item(t); if (nKeywords.getNodeName().equals("Keywords")) { String sName = nKeywords.getAttributes().getNamedItem("name").getNodeValue(); if (sName.matches("^Keywords[0-9]+$")) { Node cNode = nKeywords.getFirstChild(); if (cNode != null && cNode.getNodeType() == Node.TEXT_NODE) { cNode.setNodeValue(cNode.getNodeValue().replaceAll("[\r\n ]+", " ")); } } } } } else if (nBlock.getNodeName().equals("Styles")) { for (int t = 0, ct = nBlock.getChildNodes().getLength(); t < ct; t++) { Node nStyle = nBlock.getChildNodes().item(t); if (nStyle.getNodeName().equals("WordsStyle")) { String sName = nStyle.getAttributes().getNamedItem("name").getNodeValue(); if (sName.equals("DEFAULT")) { applyStyleToNode(nStyle, defaultStyle); } else if (sName.equals("COMMENTS")) { lookupAndApplyStyleToNode(nStyle, theme.styles, ThemeItem.STYLE_COMMENT, defaultStyle); } else if (sName.equals("LINE COMMENTS")) { lookupAndApplyStyleToNode(nStyle, theme.styles, ThemeItem.STYLE_COMMENT_LINE, defaultStyle); } else if (sName.equals("NUMBERS")) { lookupAndApplyStyleToNode(nStyle, theme.styles, ThemeItem.STYLE_NUMBER, defaultStyle); } else if (sName.matches("^KEYWORDS[0-9]+$")) { lookupAndApplyStyleToNode(nStyle, theme.styles, ThemeItem.STYLE_INSTRUCTION_WORD, defaultStyle); } else if (sName.equals("OPERATORS")) { lookupAndApplyStyleToNode(nStyle, theme.styles, ThemeItem.STYLE_OPERATOR, defaultStyle); } else if (sName.matches("^FOLDER IN CODE[0-9]+$")) { applyStyleToNode(nStyle, defaultStyle); } else if (sName.equals("FOLDER IN COMMENT")) { applyStyleToNode(nStyle, defaultStyle); } else if (sName.matches("^DELIMITERS[0-9]+$")) { lookupAndApplyStyleToNode(nStyle, theme.styles, ThemeItem.STYLE_STRING, defaultStyle); } else { applyStyleToNode(nStyle, defaultStyle); } } } } } } } if (!path.isFile()) path.createNewFile(); try (FileOutputStream fos = new FileOutputStream(path)) { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(fos); transformer.transform(source, result); } catch (TransformerException ex) { Logger.getLogger(UDLItem.class.getName()).log(Level.SEVERE, null, ex); } } catch (ParserConfigurationException | SAXException | IOException ex) { Logger.getLogger(UDLItem.class.getName()).log(Level.SEVERE, null, ex); } } } private void lookupAndApplyStyleToNode(Node styleNode, Map<String, ThemeStyle> styles, String name, ThemeStyle defaultStyle) { ThemeStyle style = styles.containsKey(name) ? styles.get(name) : null; if (style == null) { style = defaultStyle; Logger.getLogger(UDLItem.class.getName()).log(Level.WARNING, "Theme style ''{0}'' not found, using default style.", name); } applyStyleToNode(styleNode, style); } private void applyStyleToNode(Node styleNode, ThemeStyle style) { if (style == null) return; styleNode.getAttributes().getNamedItem("fgColor").setNodeValue(style.getFgColor()); styleNode.getAttributes().getNamedItem("bgColor").setNodeValue(style.getBgColor()); styleNode.getAttributes().getNamedItem("fontName").setNodeValue(style.getFontName()); styleNode.getAttributes().getNamedItem("fontStyle").setNodeValue(String.valueOf(style.getFontStyle())); } public File getPath() { return path; } public String getName() { return name; } @Override public String toString() { return name; } }
Remove unused imports
src/main/java/lt/realmdev/nppudlthemeswitcher/UDLItem.java
Remove unused imports
<ide><path>rc/main/java/lt/realmdev/nppudlthemeswitcher/UDLItem.java <ide> import java.util.Map; <ide> import java.util.logging.Level; <ide> import java.util.logging.Logger; <del>import javax.xml.XMLConstants; <ide> import javax.xml.parsers.DocumentBuilder; <ide> import javax.xml.parsers.DocumentBuilderFactory; <ide> import javax.xml.parsers.ParserConfigurationException; <del>import javax.xml.transform.OutputKeys; <ide> import javax.xml.transform.Transformer; <ide> import javax.xml.transform.TransformerException; <ide> import javax.xml.transform.TransformerFactory; <ide> import org.w3c.dom.Document; <ide> import org.w3c.dom.Node; <ide> import org.w3c.dom.NodeList; <del>import org.xml.sax.EntityResolver; <del>import org.xml.sax.InputSource; <ide> import org.xml.sax.SAXException; <ide> <ide> /**
Java
bsd-2-clause
8a06d5c11d1b1209f91aa387282e13afed31d5b0
0
imagej/imagej-common
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2016 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package net.imagej.table; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import org.junit.Test; /** * Tests {@link DefaultResultsTable}. * * @author Curtis Rueden * @author Alison Walter */ public class DefaultResultsTableTest { private static final String[] HEADERS = {"Year", "Age", "BA"}; // Paul Molitor private static final double[][] DATA = { {1978, 21, .273}, {1979, 22, .322}, {1980, 23, .304}, {1981, 24, .267}, {1982, 25, .302}, {1983, 26, .270}, {1984, 27, .217}, {1985, 28, .297}, {1986, 29, .281}, {1987, 30, .353}, {1988, 31, .312}, {1989, 32, .315}, {1990, 33, .285}, {1991, 34, .325}, {1992, 35, .320}, {1993, 36, .332}, {1994, 37, .341}, {1995, 38, .270}, {1996, 39, .341}, {1997, 40, .305}, {1998, 41, .281}, }; @Test public void testStructure() { final ResultsTable table = createTable(); assertEquals(3, table.getColumnCount()); assertEquals(21, table.getRowCount()); for (DoubleColumn column : table) { assertEquals(21, column.size()); } assertEquals("Year", table.getColumnHeader(0)); assertEquals("Age", table.getColumnHeader(1)); assertEquals("BA", table.getColumnHeader(2)); for (int c = 0; c < table.getColumnCount(); c++) { final DoubleColumn columnByHeader = table.get(HEADERS[c]); final DoubleColumn columnByIndex = table.get(c); assertSame(columnByHeader, columnByIndex); assertEquals(DATA.length, columnByHeader.size()); for (int r = 0; r < table.getRowCount(); r++) { assertEquals(DATA[r][c], table.getValue(c, r), 0); assertEquals(DATA[r][c], columnByHeader.getValue(r), 0); } } } @Test public void testGetColumnType() { final ResultsTable table = createTable(); final DoubleColumn col = table.get(0); assertEquals(col.getType(), Double.class); } @Test public void testAppendColumn() { final ResultsTable table = createTable(); final Double[] values = { -0.25, 0.5, 0.625, -1.25, 0.0, 0.0325, 100.5, 13.25, 110.5, -2.25, 4.625, -3.0, 100.0, 1209.25, -10.5, 16.25, -200.0, -0.0325, 940385034958.5, -301284390284.25, 17.25 }; final DoubleColumn col = table.appendColumn("Header4"); col.fill(values); // Test appending a column assertEquals(table.getColumnCount(), 4); assertEquals(table.get(3).getHeader(), "Header4"); checkTableModifiedColumn(table, values, 3); } @Test public void testRemoveColumn() { final ResultsTable table = createTable(); final DoubleColumn col = table.removeColumn(0); // Test removing a column for (int i = 0; i < col.size(); i++) { assertEquals(col.getValue(i), DATA[i][0], 0); } assertEquals(table.getColumnCount(), 2); checkTableModifiedColumn(table, null, 0); } @Test public void testInsertColumn() { final ResultsTable table = createTable(); final Double[] values = { -0.25, 0.5, 0.625, -1.25, 0.0, 0.0325, 100.5, 13.25, 110.5, -2.25, 4.625, -3.0, 100.0, 1209.25, -10.5, 16.25, -200.0, -0.0325, 940385034958.5, -301284390284.25, 17.25 }; final DoubleColumn col = table.insertColumn(1, "Header4"); col.fill(values); assertEquals(table.getColumnCount(), 4); assertEquals(table.get(1).getHeader(), "Header4"); checkTableModifiedColumn(table, values, 1); } @Test public void testAppendRow() { final ResultsTable table = createTable(); final double[] values = { 1999, 42, 0.0 }; // Test appending a row table.appendRow(); assertEquals(table.getRowCount(), 22); for (int i = 0; i < values.length; i++) { table.setValue(i, 21, values[i]); assertEquals(table.getValue(i, 21), values[i], 0); } checkTableModifiedRow(table, values, 21); } @Test public void testRemoveRow() { final ResultsTable table = createTable(); table.removeRow(4); assertEquals(table.getRowCount(), 20); for (int i = 0; i < table.getColumnCount(); i++) { assertEquals(table.getValue(i, 4), DATA[5][i], 0); } checkTableModifiedRow(table, null, 4); } @Test public void testRowInsert() { final ResultsTable table = createTable(); final double[] values = { 1999, 42, 0.0 }; table.insertRow(6); assertEquals(table.getRowCount(), 22); for (int i = 0; i < table.getColumnCount(); i++) { table.setValue(i, 6, values[i]); } checkTableModifiedRow(table, values, 6); } //TODO - Add more tests. // -- Helper methods -- private ResultsTable createTable() { final ResultsTable table = new DefaultResultsTable(DATA[0].length, DATA.length); for (int c=0; c<HEADERS.length; c++) { table.setColumnHeader(c, HEADERS[c]); } for (int r = 0; r < DATA.length; r++) { for (int c = 0; c < DATA[r].length; c++) { table.setValue(c, r, DATA[r][c]); } } return table; } private void checkTableModifiedColumn(final ResultsTable table, final Double[] values, final int mod) { for (int r = 0; r < table.getRowCount(); r++) { for (int c = 0; c < table.getColumnCount(); c++) { if ( c == mod && values != null ) { assertEquals(table.getValue(c, r), values[r], 0); } else if ( c > mod && values != null ) { assertEquals(table.getValue(c, r), DATA[r][c - 1], 0); } else if ( c >= mod && values == null ) { assertEquals(table.getValue(c, r), DATA[r][c + 1], 0); } else { assertEquals(table.getValue(c, r), DATA[r][c], 0); } } } } private void checkTableModifiedRow(final ResultsTable table, final double[] values, final int mod) { for (int r = 0; r < table.getRowCount(); r++) { for (int c = 0; c < table.getColumnCount(); c++) { if ( r == mod && values != null ) { assertEquals(table.getValue(c, r), values[c], 0); } else if ( r > mod && values != null) { assertEquals(table.getValue(c, r), DATA[r-1][c], 0); } else if ( r >= mod && values == null ) { assertEquals(table.getValue(c, r), DATA[r+1][c], 0); } else { assertEquals(table.getValue(c, r), DATA[r][c], 0); } } } } }
src/test/java/net/imagej/table/DefaultResultsTableTest.java
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2016 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package net.imagej.table; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import org.junit.Test; /** * Tests {@link DefaultResultsTable}. * * @author Curtis Rueden * @author Alison Walter */ public class DefaultResultsTableTest { private static final String[] HEADERS = {"Year", "Age", "BA"}; // Paul Molitor private static final double[][] DATA = { {1978, 21, .273}, {1979, 22, .322}, {1980, 23, .304}, {1981, 24, .267}, {1982, 25, .302}, {1983, 26, .270}, {1984, 27, .217}, {1985, 28, .297}, {1986, 29, .281}, {1987, 30, .353}, {1988, 31, .312}, {1989, 32, .315}, {1990, 33, .285}, {1991, 34, .325}, {1992, 35, .320}, {1993, 36, .332}, {1994, 37, .341}, {1995, 38, .270}, {1996, 39, .341}, {1997, 40, .305}, {1998, 41, .281}, }; @Test public void testStructure() { final ResultsTable table = createTable(); assertEquals(3, table.getColumnCount()); assertEquals(21, table.getRowCount()); for (DoubleColumn column : table) { assertEquals(21, column.size()); } assertEquals("Year", table.getColumnHeader(0)); assertEquals("Age", table.getColumnHeader(1)); assertEquals("BA", table.getColumnHeader(2)); for (int c = 0; c < table.getColumnCount(); c++) { final DoubleColumn columnByHeader = table.get(HEADERS[c]); final DoubleColumn columnByIndex = table.get(c); assertSame(columnByHeader, columnByIndex); assertEquals(DATA.length, columnByHeader.size()); for (int r = 0; r < table.getRowCount(); r++) { assertEquals(DATA[r][c], table.getValue(c, r), 0); assertEquals(DATA[r][c], columnByHeader.getValue(r), 0); } } } @Test public void testGetColumnType() { final ResultsTable table = createTable(); final DoubleColumn col = table.get(0); assertEquals(col.getType(), Double.class); } @Test public void testAppendColumn() { final ResultsTable table = createTable(); final Double[] values = { -0.25, 0.5, 0.625, -1.25, 0.0, 0.0325, 100.5, 13.25, 110.5, -2.25, 4.625, -3.0, 100.0, 1209.25, -10.5, 16.25, -200.0, -0.0325, 940385034958.5, -301284390284.25, 17.25 }; final DoubleColumn col = table.appendColumn("Header4"); col.fill(values); // Test appending a column assertEquals(table.getColumnCount(), 4); assertEquals(table.get(3).getHeader(), "Header4"); checkTableModifiedColumn(table, values, 3); } @Test public void testRemoveColumn() { final ResultsTable table = createTable(); final DoubleColumn col = table.removeColumn(0); // Test removing a column for (int i = 0; i < col.size(); i++) { assertEquals(col.getValue(i), DATA[i][0], 0); } assertEquals(table.getColumnCount(), 2); checkTableModifiedColumn(table, null, 0); } @Test public void testAppendRow() { final ResultsTable table = createTable(); final double[] values = { 1999, 42, 0.0 }; // Test appending a row table.appendRow(); assertEquals(table.getRowCount(), 22); for (int i = 0; i < values.length; i++) { table.setValue(i, 21, values[i]); assertEquals(table.getValue(i, 21), values[i], 0); } checkTableModifiedRow(table, values, 21); } @Test public void testRemoveRow() { final ResultsTable table = createTable(); table.removeRow(4); assertEquals(table.getRowCount(), 20); for (int i = 0; i < table.getColumnCount(); i++) { assertEquals(table.getValue(i, 4), DATA[5][i], 0); } checkTableModifiedRow(table, null, 4); } //TODO - Add more tests. // -- Helper methods -- private ResultsTable createTable() { final ResultsTable table = new DefaultResultsTable(DATA[0].length, DATA.length); for (int c=0; c<HEADERS.length; c++) { table.setColumnHeader(c, HEADERS[c]); } for (int r = 0; r < DATA.length; r++) { for (int c = 0; c < DATA[r].length; c++) { table.setValue(c, r, DATA[r][c]); } } return table; } private void checkTableModifiedColumn(final ResultsTable table, final Double[] values, final int mod) { for (int r = 0; r < table.getRowCount(); r++) { for (int c = 0; c < table.getColumnCount(); c++) { if ( c == mod && values != null ) { assertEquals(table.getValue(c, r), values[r], 0); } else if ( c > mod && values != null ) { assertEquals(table.getValue(c, r), DATA[r][c - 1], 0); } else if ( c >= mod && values == null ) { assertEquals(table.getValue(c, r), DATA[r][c + 1], 0); } else { assertEquals(table.getValue(c, r), DATA[r][c], 0); } } } } private void checkTableModifiedRow(final ResultsTable table, final double[] values, final int mod) { for (int r = 0; r < table.getRowCount(); r++) { for (int c = 0; c < table.getColumnCount(); c++) { if ( r == mod && values != null ) { assertEquals(table.getValue(c, r), values[c], 0); } else if ( r > mod && values != null) { assertEquals(table.getValue(c, r), DATA[r-1][c], 0); } else if ( r >= mod && values == null ) { assertEquals(table.getValue(c, r), DATA[r+1][c], 0); } else { assertEquals(table.getValue(c, r), DATA[r][c], 0); } } } } }
Add tests for inserting a row/column to ResultsTable
src/test/java/net/imagej/table/DefaultResultsTableTest.java
Add tests for inserting a row/column to ResultsTable
<ide><path>rc/test/java/net/imagej/table/DefaultResultsTableTest.java <ide> } <ide> <ide> @Test <add> public void testInsertColumn() { <add> final ResultsTable table = createTable(); <add> final Double[] values = { -0.25, 0.5, 0.625, -1.25, 0.0, 0.0325, 100.5, <add> 13.25, 110.5, -2.25, 4.625, -3.0, 100.0, 1209.25, -10.5, 16.25, -200.0, <add> -0.0325, 940385034958.5, -301284390284.25, 17.25 }; <add> <add> final DoubleColumn col = table.insertColumn(1, "Header4"); <add> col.fill(values); <add> <add> assertEquals(table.getColumnCount(), 4); <add> assertEquals(table.get(1).getHeader(), "Header4"); <add> <add> checkTableModifiedColumn(table, values, 1); <add> } <add> <add> @Test <ide> public void testAppendRow() { <ide> final ResultsTable table = createTable(); <ide> final double[] values = { 1999, 42, 0.0 }; <ide> } <ide> <ide> checkTableModifiedRow(table, null, 4); <add> } <add> <add> @Test <add> public void testRowInsert() { <add> final ResultsTable table = createTable(); <add> final double[] values = { 1999, 42, 0.0 }; <add> <add> table.insertRow(6); <add> <add> assertEquals(table.getRowCount(), 22); <add> for (int i = 0; i < table.getColumnCount(); i++) { <add> table.setValue(i, 6, values[i]); <add> } <add> <add> checkTableModifiedRow(table, values, 6); <ide> } <ide> <ide> //TODO - Add more tests.
Java
apache-2.0
ed01fad0c463afd2978553d3706840e4e89b635a
0
lalaji/carbon-apimgt,rswijesena/carbon-apimgt,chamindias/carbon-apimgt,chamindias/carbon-apimgt,laki88/carbon-apimgt,thilinicooray/carbon-apimgt,Niranjan-K/carbon-apimgt,sineth-neranjana/carbon-apimgt,tharikaGitHub/carbon-apimgt,sambaheerathan/carbon-apimgt,tharindu1st/carbon-apimgt,susinda/carbon-apimgt,pradeepmurugesan/carbon-apimgt,uvindra/carbon-apimgt,madusankapremaratne/carbon-apimgt,isharac/carbon-apimgt,charithag/carbon-apimgt,tharikaGitHub/carbon-apimgt,abimarank/carbon-apimgt,dhanuka84/carbon-apimgt,dongwh/carbon-apimgt,malinthaprasan/carbon-apimgt,lalaji/carbon-apimgt,malinthaprasan/carbon-apimgt,lakmali/carbon-apimgt,ruks/carbon-apimgt,isharac/carbon-apimgt,thusithak/carbon-apimgt,jaadds/carbon-apimgt,wso2/carbon-apimgt,wso2/carbon-apimgt,dhanuka84/carbon-apimgt,Arshardh/carbon-apimgt,pradeepmurugesan/carbon-apimgt,pradeepmurugesan/carbon-apimgt,ruks/carbon-apimgt,dhanuka84/carbon-apimgt,Arshardh/carbon-apimgt,praminda/carbon-apimgt,ayyoob/carbon-apimgt,fazlan-nazeem/carbon-apimgt,prasa7/carbon-apimgt,wso2/carbon-apimgt,laki88/carbon-apimgt,susinda/carbon-apimgt,ayyoob/carbon-apimgt,tharindu1st/carbon-apimgt,charithag/carbon-apimgt,tharikaGitHub/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,Rajith90/carbon-apimgt,pradeepmurugesan/carbon-apimgt,nuwand/carbon-apimgt,thilinicooray/carbon-apimgt,uvindra/carbon-apimgt,knPerera/carbon-apimgt,thilinicooray/carbon-apimgt,thusithak/carbon-apimgt,chamilaadhi/carbon-apimgt,Minoli/carbon-apimgt,ayyoob/carbon-apimgt,ayyoob/carbon-apimgt,chamilaadhi/carbon-apimgt,pubudu538/carbon-apimgt,Niranjan-K/carbon-apimgt,dewmini/carbon-apimgt,knPerera/carbon-apimgt,harsha89/carbon-apimgt,harsha89/carbon-apimgt,praminda/carbon-apimgt,hevayo/carbon-apimgt,uvindra/carbon-apimgt,Niranjan-K/carbon-apimgt,ruks/carbon-apimgt,madusankapremaratne/carbon-apimgt,lakmali/carbon-apimgt,bhathiya/carbon-apimgt,chamindias/carbon-apimgt,knPerera/carbon-apimgt,thilinicooray/carbon-apimgt,charithag/carbon-apimgt,fazlan-nazeem/carbon-apimgt,sineth-neranjana/carbon-apimgt,jaadds/carbon-apimgt,susinda/carbon-apimgt,ChamNDeSilva/carbon-apimgt,pubudu538/carbon-apimgt,praminda/carbon-apimgt,tharikaGitHub/carbon-apimgt,Arshardh/carbon-apimgt,madusankapremaratne/carbon-apimgt,fazlan-nazeem/carbon-apimgt,tharindu1st/carbon-apimgt,sineth-neranjana/carbon-apimgt,wso2/carbon-apimgt,jaadds/carbon-apimgt,nuwand/carbon-apimgt,dewmini/carbon-apimgt,hevayo/carbon-apimgt,dhanuka84/carbon-apimgt,uvindra/carbon-apimgt,charithag/carbon-apimgt,jaadds/carbon-apimgt,madusankapremaratne/carbon-apimgt,chamilaadhi/carbon-apimgt,hevayo/carbon-apimgt,Niranjan-K/carbon-apimgt,dongwh/carbon-apimgt,harsha89/carbon-apimgt,Minoli/carbon-apimgt,Minoli/carbon-apimgt,pubudu538/carbon-apimgt,nuwand/carbon-apimgt,knPerera/carbon-apimgt,lakmali/carbon-apimgt,dongwh/carbon-apimgt,dewmini/carbon-apimgt,laki88/carbon-apimgt,dongwh/carbon-apimgt,ChamNDeSilva/carbon-apimgt,harsha89/carbon-apimgt,laki88/carbon-apimgt,isharac/carbon-apimgt,lalaji/carbon-apimgt,ruks/carbon-apimgt,fazlan-nazeem/carbon-apimgt,abimarank/carbon-apimgt,isharac/carbon-apimgt,pubudu538/carbon-apimgt,rswijesena/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,Rajith90/carbon-apimgt,bhathiya/carbon-apimgt,malinthaprasan/carbon-apimgt,susinda/carbon-apimgt,prasa7/carbon-apimgt,malinthaprasan/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,Arshardh/carbon-apimgt,prasa7/carbon-apimgt,bhathiya/carbon-apimgt,rswijesena/carbon-apimgt,Rajith90/carbon-apimgt,bhathiya/carbon-apimgt,sambaheerathan/carbon-apimgt,prasa7/carbon-apimgt,abimarank/carbon-apimgt,Rajith90/carbon-apimgt,hevayo/carbon-apimgt,sineth-neranjana/carbon-apimgt,thusithak/carbon-apimgt,chamilaadhi/carbon-apimgt,sambaheerathan/carbon-apimgt,nuwand/carbon-apimgt,chamindias/carbon-apimgt,ChamNDeSilva/carbon-apimgt,tharindu1st/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt
/* * Copyright WSO2 Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.apimgt.keymgt.handlers; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.tools.ant.util.regexp.RegexpUtil; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.model.Scope; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO; import org.wso2.carbon.identity.base.IdentityException; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.oauth.internal.OAuthComponentServiceHolder; import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import sun.misc.Regexp; import javax.cache.Cache; import javax.cache.Caching; import java.util.*; import java.util.regex.Pattern; public class ScopesIssuer { private static Log log = LogFactory.getLog(ScopesIssuer.class); private static final String DEFAULT_SCOPE_NAME = "default"; private List<String> scopeSkipList = new ArrayList<String>(); /** Singleton of ScopeIssuer.**/ private static ScopesIssuer scopesIssuer; public static void loadInstance(List<String> whitelist){ scopesIssuer = new ScopesIssuer(); if(whitelist != null && !whitelist.isEmpty()){ scopesIssuer.scopeSkipList.addAll(whitelist); } } private ScopesIssuer(){} public static ScopesIssuer getInstance(){ return scopesIssuer; } public boolean setScopes(OAuthTokenReqMessageContext tokReqMsgCtx){ String[] requestedScopes = tokReqMsgCtx.getScope(); String[] defaultScope = new String[]{DEFAULT_SCOPE_NAME}; //If no scopes were requested. if(requestedScopes == null || requestedScopes.length == 0){ tokReqMsgCtx.setScope(defaultScope); return true; } String consumerKey = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId(); String username = tokReqMsgCtx.getAuthorizedUser(); List<String> reqScopeList = Arrays.asList(requestedScopes); try { Map<String, String> appScopes = null; ApiMgtDAO apiMgtDAO = new ApiMgtDAO(); //Get all the scopes and roles against the scopes defined for the APIs subscribed to the application. appScopes = apiMgtDAO.getScopeRolesOfApplication(consumerKey); //If no scopes can be found in the context of the application if(appScopes.isEmpty()){ if(log.isDebugEnabled()){ log.debug("No scopes defined for the Application " + tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId()); } String[] allowedScopes = getAllowedScopes(reqScopeList); tokReqMsgCtx.setScope(allowedScopes); return true; } int tenantId; RealmService realmService = OAuthComponentServiceHolder.getRealmService(); UserStoreManager userStoreManager = null; String[] userRoles = null; try { tenantId = IdentityUtil.getTenantIdOFUser(username); userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager(); userRoles = userStoreManager.getRoleListOfUser(MultitenantUtils.getTenantAwareUsername(username)); } catch (IdentityException e) { //Log and return since we do not want to stop issuing the token in case of scope validation failures. log.error("Error when obtaining tenant Id of user " + username, e); return false; } catch (UserStoreException e) { //Log and return since we do not want to stop issuing the token in case of scope validation failures. log.error("Error when getting the tenant's UserStoreManager or when getting roles of user ", e); return false; } if(userRoles == null || userRoles.length == 0){ if(log.isDebugEnabled()){ log.debug("Could not find roles of the user."); } tokReqMsgCtx.setScope(defaultScope); return true; } List<String> authorizedScopes = new ArrayList<String>(); List<String> userRoleList = new ArrayList<String>(Arrays.asList(userRoles)); //Iterate the requested scopes list. for (String scope : reqScopeList) { //Get the set of roles associated with the requested scope. String roles = appScopes.get(scope); //If the scope has been defined in the context of the App and if roles have been defined for the scope if (roles != null && roles.length() != 0) { List<String> roleList = new ArrayList<String>(Arrays.asList(roles.replaceAll(" ", "").split(","))); //Check if user has at least one of the roles associated with the scope roleList.retainAll(userRoleList); if(!roleList.isEmpty()){ authorizedScopes.add(scope); } } //The requested scope is defined for the context of the App but no roles have been associated with the scope //OR //The scope string starts with 'device_'. else if (appScopes.containsKey(scope) || isWhiteListedScope(scope)) { authorizedScopes.add(scope); } } if(!authorizedScopes.isEmpty()){ String[] authScopesArr = authorizedScopes.toArray(new String[authorizedScopes.size()]); tokReqMsgCtx.setScope(authScopesArr); } else{ tokReqMsgCtx.setScope(defaultScope); } } catch (APIManagementException e) { log.error("Error while getting scopes of application " + e.getMessage()); return false; } return true; } /** * Determines if the scope is specified in the whitelist. * @param scope * @return */ private boolean isWhiteListedScope(String scope){ for(String scopeTobeSkipped : scopeSkipList){ if(scope.matches(scopeTobeSkipped)){ return true; } } return false; } /** * Get the set of default scopes. If a requested scope is matches with the patterns specified in the whitelist, * then such scopes will be issued without further validation. If the scope list is empty, * token will be issued for default scope. * @param requestedScopes - The set of requested scopes * @return */ private String[] getAllowedScopes(List<String> requestedScopes){ List<String> authorizedScopes = new ArrayList<String>(); //Iterate the requested scopes list. for (String scope : requestedScopes) { if(isWhiteListedScope(scope)){ authorizedScopes.add(scope); } } if(authorizedScopes.isEmpty()){ authorizedScopes.add(DEFAULT_SCOPE_NAME); } return authorizedScopes.toArray(new String[authorizedScopes.size()]); } }
components/apimgt/org.wso2.carbon.apimgt.keymgt/src/main/java/org/wso2/carbon/apimgt/keymgt/handlers/ScopesIssuer.java
/* * Copyright WSO2 Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.apimgt.keymgt.handlers; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.tools.ant.util.regexp.RegexpUtil; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.model.Scope; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO; import org.wso2.carbon.identity.base.IdentityException; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.oauth.internal.OAuthComponentServiceHolder; import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import sun.misc.Regexp; import javax.cache.Cache; import javax.cache.Caching; import java.util.*; import java.util.regex.Pattern; public class ScopesIssuer { private static Log log = LogFactory.getLog(ScopesIssuer.class); private static final String DEFAULT_SCOPE_NAME = "default"; private List<String> scopeSkipList = new ArrayList<String>(); /** Singleton of ScopeIssuer.**/ private static ScopesIssuer scopesIssuer; public static void loadInstance(List<String> whitelist){ scopesIssuer = new ScopesIssuer(); if(whitelist != null && !whitelist.isEmpty()){ scopesIssuer.scopeSkipList.addAll(whitelist); } } private ScopesIssuer(){} public static ScopesIssuer getInstance(){ return scopesIssuer; } public boolean setScopes(OAuthTokenReqMessageContext tokReqMsgCtx){ String[] requestedScopes = tokReqMsgCtx.getScope(); String[] defaultScope = new String[]{DEFAULT_SCOPE_NAME}; //If no scopes were requested. if(requestedScopes == null || requestedScopes.length == 0){ tokReqMsgCtx.setScope(defaultScope); return true; } String consumerKey = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId(); String username = tokReqMsgCtx.getAuthorizedUser(); String cacheKey = getAppUserScopeCacheKey(consumerKey, username, requestedScopes); Cache cache = Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER). getCache(APIConstants.APP_USER_SCOPE_CACHE); List<String> reqScopeList = Arrays.asList(requestedScopes); try { Map<String, String> appScopes = null; Cache appCache = Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER). getCache(APIConstants.APP_SCOPE_CACHE); //Cache hit if(appCache.containsKey(consumerKey)){ appScopes = (Map<String, String>)appCache.get(consumerKey); // checking the user cache only if app cache is available (since we only update app cache) if(cache.containsKey(cacheKey)){ tokReqMsgCtx.setScope((String [])cache.get(cacheKey)); return true; } } //Cache miss else{ ApiMgtDAO apiMgtDAO = new ApiMgtDAO(); //Get all the scopes and roles against the scopes defined for the APIs subscribed to the application. appScopes = apiMgtDAO.getScopeRolesOfApplication(consumerKey); //If scopes is null, set empty hashmap to scopes so that we avoid adding a null entry to the cache. if(appScopes == null){ appScopes = new HashMap<String, String>(); } appCache.put(consumerKey, appScopes); } //If no scopes can be found in the context of the application if(appScopes.isEmpty()){ if(log.isDebugEnabled()){ log.debug("No scopes defined for the Application " + tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId()); } String[] allowedScopes = getAllowedScopes(reqScopeList); tokReqMsgCtx.setScope(allowedScopes); cache.put(cacheKey, allowedScopes); return true; } int tenantId; RealmService realmService = OAuthComponentServiceHolder.getRealmService(); UserStoreManager userStoreManager = null; String[] userRoles = null; try { tenantId = IdentityUtil.getTenantIdOFUser(username); userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager(); userRoles = userStoreManager.getRoleListOfUser(MultitenantUtils.getTenantAwareUsername(username)); } catch (IdentityException e) { //Log and return since we do not want to stop issuing the token in case of scope validation failures. log.error("Error when obtaining tenant Id of user " + username, e); return false; } catch (UserStoreException e) { //Log and return since we do not want to stop issuing the token in case of scope validation failures. log.error("Error when getting the tenant's UserStoreManager or when getting roles of user ", e); return false; } if(userRoles == null || userRoles.length == 0){ if(log.isDebugEnabled()){ log.debug("Could not find roles of the user."); } tokReqMsgCtx.setScope(defaultScope); cache.put(cacheKey, defaultScope); return true; } List<String> authorizedScopes = new ArrayList<String>(); List<String> userRoleList = new ArrayList<String>(Arrays.asList(userRoles)); //Iterate the requested scopes list. for (String scope : reqScopeList) { //Get the set of roles associated with the requested scope. String roles = appScopes.get(scope); //If the scope has been defined in the context of the App and if roles have been defined for the scope if (roles != null && roles.length() != 0) { List<String> roleList = new ArrayList<String>(Arrays.asList(roles.replaceAll(" ", "").split(","))); //Check if user has at least one of the roles associated with the scope roleList.retainAll(userRoleList); if(!roleList.isEmpty()){ authorizedScopes.add(scope); } } //The requested scope is defined for the context of the App but no roles have been associated with the scope //OR //The scope string starts with 'device_'. else if (appScopes.containsKey(scope) || isWhiteListedScope(scope)) { authorizedScopes.add(scope); } } if(!authorizedScopes.isEmpty()){ String[] authScopesArr = authorizedScopes.toArray(new String[authorizedScopes.size()]); cache.put(cacheKey, authScopesArr); tokReqMsgCtx.setScope(authScopesArr); } else{ cache.put(cacheKey, defaultScope); tokReqMsgCtx.setScope(defaultScope); } } catch (APIManagementException e) { log.error("Error while getting scopes of application " + e.getMessage()); return false; } return true; } /** * Determines if the scope is specified in the whitelist. * @param scope * @return */ private boolean isWhiteListedScope(String scope){ for(String scopeTobeSkipped : scopeSkipList){ if(scope.matches(scopeTobeSkipped)){ return true; } } return false; } private String getAppUserScopeCacheKey(String consumerKey, String username, String[] requestedScopes){ StringBuilder reqScopesBuilder = new StringBuilder(""); for(int i=0; i<requestedScopes.length; i++){ reqScopesBuilder.append(requestedScopes[i]); } int reqScopesHash = reqScopesBuilder.toString().hashCode(); StringBuilder cacheKey = new StringBuilder(""); cacheKey.append(consumerKey); cacheKey.append(":"); cacheKey.append(username); cacheKey.append(":"); cacheKey.append(reqScopesHash); return cacheKey.toString(); } /** * Get the set of default scopes. If a requested scope is matches with the patterns specified in the whitelist, * then such scopes will be issued without further validation. If the scope list is empty, * token will be issued for default scope. * @param requestedScopes - The set of requested scopes * @return */ private String[] getAllowedScopes(List<String> requestedScopes){ List<String> authorizedScopes = new ArrayList<String>(); //Iterate the requested scopes list. for (String scope : requestedScopes) { if(isWhiteListedScope(scope)){ authorizedScopes.add(scope); } } if(authorizedScopes.isEmpty()){ authorizedScopes.add(DEFAULT_SCOPE_NAME); } return authorizedScopes.toArray(new String[authorizedScopes.size()]); } }
removed scopes caching
components/apimgt/org.wso2.carbon.apimgt.keymgt/src/main/java/org/wso2/carbon/apimgt/keymgt/handlers/ScopesIssuer.java
removed scopes caching
<ide><path>omponents/apimgt/org.wso2.carbon.apimgt.keymgt/src/main/java/org/wso2/carbon/apimgt/keymgt/handlers/ScopesIssuer.java <ide> <ide> String consumerKey = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId(); <ide> String username = tokReqMsgCtx.getAuthorizedUser(); <del> <del> String cacheKey = getAppUserScopeCacheKey(consumerKey, username, requestedScopes); <del> Cache cache = Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER). <del> getCache(APIConstants.APP_USER_SCOPE_CACHE); <del> <ide> List<String> reqScopeList = Arrays.asList(requestedScopes); <ide> <ide> try { <ide> Map<String, String> appScopes = null; <del> Cache appCache = Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER). <del> getCache(APIConstants.APP_SCOPE_CACHE); <del> <del> //Cache hit <del> if(appCache.containsKey(consumerKey)){ <del> appScopes = (Map<String, String>)appCache.get(consumerKey); <del> <del> // checking the user cache only if app cache is available (since we only update app cache) <del> if(cache.containsKey(cacheKey)){ <del> tokReqMsgCtx.setScope((String [])cache.get(cacheKey)); <del> return true; <del> } <del> } <del> //Cache miss <del> else{ <del> ApiMgtDAO apiMgtDAO = new ApiMgtDAO(); <del> //Get all the scopes and roles against the scopes defined for the APIs subscribed to the application. <del> appScopes = apiMgtDAO.getScopeRolesOfApplication(consumerKey); <del> //If scopes is null, set empty hashmap to scopes so that we avoid adding a null entry to the cache. <del> if(appScopes == null){ <del> appScopes = new HashMap<String, String>(); <del> } <del> appCache.put(consumerKey, appScopes); <del> } <add> ApiMgtDAO apiMgtDAO = new ApiMgtDAO(); <add> //Get all the scopes and roles against the scopes defined for the APIs subscribed to the application. <add> appScopes = apiMgtDAO.getScopeRolesOfApplication(consumerKey); <ide> <ide> //If no scopes can be found in the context of the application <ide> if(appScopes.isEmpty()){ <ide> <ide> String[] allowedScopes = getAllowedScopes(reqScopeList); <ide> tokReqMsgCtx.setScope(allowedScopes); <del> cache.put(cacheKey, allowedScopes); <ide> return true; <ide> } <ide> <ide> log.debug("Could not find roles of the user."); <ide> } <ide> tokReqMsgCtx.setScope(defaultScope); <del> cache.put(cacheKey, defaultScope); <ide> return true; <ide> } <ide> <ide> } <ide> if(!authorizedScopes.isEmpty()){ <ide> String[] authScopesArr = authorizedScopes.toArray(new String[authorizedScopes.size()]); <del> cache.put(cacheKey, authScopesArr); <ide> tokReqMsgCtx.setScope(authScopesArr); <ide> } <ide> else{ <del> cache.put(cacheKey, defaultScope); <ide> tokReqMsgCtx.setScope(defaultScope); <ide> } <ide> } catch (APIManagementException e) { <ide> return false; <ide> } <ide> <del> private String getAppUserScopeCacheKey(String consumerKey, String username, String[] requestedScopes){ <del> StringBuilder reqScopesBuilder = new StringBuilder(""); <del> for(int i=0; i<requestedScopes.length; i++){ <del> reqScopesBuilder.append(requestedScopes[i]); <del> } <del> <del> int reqScopesHash = reqScopesBuilder.toString().hashCode(); <del> <del> StringBuilder cacheKey = new StringBuilder(""); <del> cacheKey.append(consumerKey); <del> cacheKey.append(":"); <del> cacheKey.append(username); <del> cacheKey.append(":"); <del> cacheKey.append(reqScopesHash); <del> <del> return cacheKey.toString(); <del> } <del> <ide> /** <ide> * Get the set of default scopes. If a requested scope is matches with the patterns specified in the whitelist, <ide> * then such scopes will be issued without further validation. If the scope list is empty,
JavaScript
mit
8eb5c0241251334bb0f226195b53d56640f2aaf2
0
Sawtaytoes/Ghadyani-Framework-Webpack-React-Redux,Sawtaytoes/Ghadyani-Framework-Webpack-React-Redux
export default (reducer, initialState) => ( (state = initialState, action) => ( reducer[action.type] ? reducer[action.type](state, action) : state ) )
src/utils/createReducer.js
export default (reducer, initialState) => (state = initialState, action) => ( reducer[action.type] ? reducer[action.type](state, action) : state )
Minor formatting change in createReducer
src/utils/createReducer.js
Minor formatting change in createReducer
<ide><path>rc/utils/createReducer.js <del>export default (reducer, initialState) => (state = initialState, action) => ( <del> reducer[action.type] <del> ? reducer[action.type](state, action) <del> : state <add>export default (reducer, initialState) => ( <add> (state = initialState, action) => ( <add> reducer[action.type] <add> ? reducer[action.type](state, action) <add> : state <add> ) <ide> )
JavaScript
mit
a88d0335003d117d1e37335170562207fa73d44c
0
mahonrig/glry,mahonrig/glry,mahonrig/glry
/* ToDo: -Implement photo gallery -About me page */ /* Create the ember application registered to a global variable */ window.Photoworks = Ember.Application.create(); /* Using local storage fixture adapter for now, change to RESTful */ Photoworks.PhotosAdapter = DS.FixtureAdapter.extend(); Photoworks.OptionsAdapter = DS.FixtureAdapter.extend(); Photoworks.CartItemSerializer = DS.LSSerializer.extend(); Photoworks.CartItemAdapter = DS.LSAdapter.extend({ namespace: 'photoworks' }); /* Map our routes, resource used for noun, route used for verb */ Photoworks.Router.map(function() { this.resource('prints'); /* Thumbnails page */ this.resource('order', { path: '/order/:photo_id' }); /* Print large view and ordering */ this.resource('printDetails'); /* Product details */ }); /* Route for large display of selected print and ordering options */ Photoworks.OrderRoute = Ember.Route.extend({ model: function(params) { return this.store.find('photos', params.photo_id); } }); /* Route for the available prints thumbnail gallery */ Photoworks.PrintsRoute = Ember.Route.extend({ model: function() { return this.store.find('photos'); } }); /* Currently only using this for the shopping cart, need to convert to a view / more specific controller I think */ Photoworks.ApplicationRoute = Ember.Route.extend({ model: function() { return this.store.find('cartItem'); } }); /* Application controller*/ Photoworks.ApplicationController = Ember.ArrayController.extend({ /* Return total number of items in cart */ totalItems: function(){ return this.get('length'); }.property('@each'), /* Return total price in cart */ totalPrice: function(){ var cartItems = this.get('model'); return cartItems.reduce(function(prevValue, item){ console.log(item.get('price')); return prevValue + item.get('price'); }, 0); }.property('@each.cartItem.price'), /* Used for the paypal form, index the cart items */ assignIndex: function(){ this.map(function(item, index){ Ember.set(item, 'index', index+1); }); }.observes('cartItem.[]', 'firstObject', 'lastObject'), /* Actions hash */ actions: { /* Clear all items from the cart */ clearCart: function(){ var cartItems = this.get('model'); cartItems.forEach(function(item){ item.deleteRecord(); item.save(); }); }, toggleCart: function(){ $('.cart').fadeToggle(); }, hideCart: function(){ $('.cart').fadeOut(); } } }); /* Controller for individual items in the cart */ Photoworks.CartItemController = Ember.ObjectController.extend({ actions: { removeFromCart: function(id){ this.store.find('cartItem', id).then(function(item){ item.deleteRecord(); item.save(); }); } }, /* For paypal checkout form */ paypalFormItem: function() { var index = this.get('index'); return 'item_name_' + index; }.property('index'), paypalFormAmount: function() { var index = this.get('index'); return 'amount_' + index; }.property('index'), paypalFormTitle: function() { var title = this.get('title'); var type = this.get('type'); var size = this.get('size'); return title + ' ' + size + ' ' + type; }.property('title', 'type', 'size') }); /* Controller for individual thumbnails on the prints page */ Photoworks.ThumbController = Ember.ObjectController.extend({ /* Return thumbnail, probably don't want this hardcoded */ url: function(){ var img = this.get('img'); return "http://mgibsonphotoworks.com/uploads/thumbs/" + img ; }.property('img') }); /* Controller for the large view ordering page */ Photoworks.OrderController = Ember.ObjectController.extend({ actions: { addToCart: function() { var title = this.get('title'); var type = this.get('type'); var size = this.get('size'); var price = this.get('price'); if (price){ var record = this.store.createRecord('cartItem', { title: title, type: type, size: size, price: price }); record.save(); $('.added').fadeIn().delay(500).fadeOut(); console.log('Added item: ' + title); } else { console.log('Please select a size'); $('.errorSelect').fadeIn().delay(500).fadeOut(); } } }, /* Available print types, maybe should convert to model instead of hardcoding */ types: [ {type: "Print Only", id: 1}, {type: "Matted Print", id: 2}, {type: "Framed Print", id: 3}, {type: "Metal Print", id: 4} ], /* Store id of current print type selected */ currentType: { id: 1 }, /* Store id of current size selected */ currentSize: { id: 1 }, /* Return large image, need to not hardcode this */ url: function(){ var img = this.get('img'); return "http://mgibsonphotoworks.com/uploads/large/" + img ; }.property('img'), /* The following are needed to keep logic out of the template, annoying */ printSelected: function(){ if (this.get('currentType.id') == 1) return true; else return false; }.property('currentType.id'), mattSelected: function(){ if (this.get('currentType.id') == 2) return true; else return false; }.property('currentType.id'), frameSelected: function(){ if (this.get('currentType.id') == 3) return true; else return false; }.property('currentType.id'), metalSelected: function(){ if (this.get('currentType.id') == 4) return true; else return false; }.property('currentType.id'), /* End annoying replacements for a simple switch statement */ /* Store current price for selected item */ price: 0, /* Store current type for selected item. This is separate from types above and comes from the options model */ type: '', /* Store currently selected print size */ size: '', /* Updates price, type, and size from option model observes for changes in the currently selected size */ itemUpdate: function() { that = this; /* Keep hold of our context */ id = this.get('currentSize.id'); /* If id is set, an option is selected */ if (id){ /* Store returns a promise, use then() to wait for it to resolve */ this.store.find('options', id).then(function(option){ console.log(option.get('price')); console.log(option.get('type')); console.log(option.get('size')); that.set('price', option.get('price')); that.set('type', option.get('type')); that.set('size', option.get('size')); }); } else { /* Size option not set, clear everything */ that.set('price', 0); that.set('type', ''); } that.set('size', ''); }.observes('currentSize.id') }); /* Model for our photos */ Photoworks.Photos = DS.Model.extend({ title: DS.attr('string'), img: DS.attr('string'), printSizes: DS.hasMany('options', { async: true }), mattSizes: DS.hasMany('options', { async: true }), frameSizes: DS.hasMany('options', { async: true }), metalSizes: DS.hasMany('options', { async: true }) }); /* Model for available print, matt, frame, and metal options */ Photoworks.Options = DS.Model.extend({ type: DS.attr('string'), size: DS.attr('string'), price: DS.attr('number'), /* To show price in select drop-down */ display: function(){ var displayed = this.get('size') + ': $' + this.get('price'); return displayed; }.property('size', 'price') }); /* Model for our shopping cart items */ Photoworks.CartItem = DS.Model.extend({ title: DS.attr('string'), type: DS.attr('string'), size: DS.attr('string'), price: DS.attr('number') }); /* Temp fixtures for testing */ /*Photoworks.CartItem.FIXTURES = [ { id: 1, title: "Pacific Northwest Rainforest", type: "Framed", size: "8x10 in 11x14", price: 50 }, { id: 2, title: "Mount Shuksan at Sunset", type: "Matt", size: "11x14 on 16x20", price: 100 } ];*/ /* Available options */ Photoworks.Options.FIXTURES = [ { id: 1, type: 'Print', size: '8x12', price: 50 }, { id: 2, type: 'Print', size: '12x18', price: 75 }, { id: 3, type: 'Print', size: '16x24', price: 100 }, { id: 4, type: 'Print', size: '20x30', price: 125 }, { id: 5, type: 'Print', size: '8"x10"', price: 50 }, { id: 6, type: 'Print', size: '11x14', price: 75 }, { id: 7, type: 'Print', size: '16x20', price: 100 }, { id: 8, type: 'Print', size: '20x24', price: 125 }, { id: 9, type: 'Matted', size: '8x12 on 11x14', price: 75 }, { id: 10, type: 'Matted', size: '11x16 on 16x20', price: 100 }, { id: 11, type: 'Matted', size: '12x18 on 24x30', price: 125 }, { id: 12, type: 'Matted', size: '8x10 on 11x14', price: 75 }, { id: 13, type: 'Matted', size: '11x14 on 16x20', price: 100 }, { id: 14, type: 'Matted', size: '16x20 on 20x24', price: 125 }, { id: 15, type: 'Framed', size: '8x12 in 11x14', price: 125 }, { id: 16, type: 'Framed', size: '11x16 in 16x20', price: 175 }, { id: 17, type: 'Framed', size: '14x20 in 24x30', price: 225 }, { id: 18, type: 'Metal', size: '8x12', price: 100 }, { id: 19, type: 'Metal', size: '12x18', price: 150 }, { id: 20, type: 'Metal', size: '16x24', price: 200 }, { id: 21, type: 'Metal', size: '20x30', price: 250 }, { id: 22, type: 'Print', size: '10x10', price: 50 }, { id: 23, type: 'Print', size: '16x16', price: 75 }, { id: 24, type: 'Print', size: '20x20', price: 100 }, { id: 25, type: 'Matted', size: '10x10 on 12x12', price: 75 }, { id: 26, type: 'Framed', size: '10x10 in 12x12', price: 125 }, { id: 27, type: 'Framed', size: '16x16 in 20x20', price: 200 }, { id: 28, type: 'Metal', size: '10x10', price: 100 }, { id: 29, type: 'Metal', size: '16x16', price: 150 }, { id: 30, type: 'Metal', size: '24x24', price: 250 }, { id: 31, type: 'Metal', size: '12x36', price: 250 }, { id: 32, type: 'Metal', size: '20x60', price: 500 }, { id: 33, type: 'Framed', size: '12x36', price: 200 }, { id: 34, type: 'Print', size: '12x36', price: 100 }, { id: 35, type: 'Print', size: '16x48', price: 150 }, { id: 36, type: 'Print', size: '20x60', price: 200 }, ]; /* Current photos in gallery */ Photoworks.Photos.FIXTURES = [ { id: 1, title: 'Pacific Northwest Rainforest', img: 'IMG_1124%20-%20IMG_1125.jpg', printSizes: [22, 23, 24], mattSizes: [25], frameSizes: [26, 27], metalSizes: [28, 29, 30] }, { id: 2, title: 'Mt Shuksan', img: 'IMG_0908%20-%20IMG_0910-Edit.jpg', printSizes: [34, 35, 36], mattSizes: [], frameSizes: [33], metalSizes: [31, 32] }, { id: 3, title: 'Above the snowline', img: 'IMG_1106%20-%20IMG_1111.jpg', printSizes: [1, 3], mattSizes: [1,2], frameSizes: [2,3], metalSizes: [3] }, { id: 4, title: 'Mt Index and Lake Serene', img: 'IMG_1082%20-%20IMG_1093-Edit.jpg', printSizes: [1, 3], mattSizes: [1,2], frameSizes: [2,3], metalSizes: [3] }, { id: 5, title: 'Nooksack Falls', img: 'IMG_0994%20-%20IMG_0997.jpg', printSizes: [1, 3], mattSizes: [1,2], frameSizes: [2,3], metalSizes: [3] }, { id: 6, title: 'Snowfields at Mount Baker', img: 'IMG_0926.jpg', printSizes: [1, 3], mattSizes: [1,2], frameSizes: [2,3], metalSizes: [3] } ];
js/application.js
/* ToDo: */ /* Create the ember application registered to a global variable */ window.Photoworks = Ember.Application.create(); /* Using local storage fixture adapter for now, change to RESTful */ Photoworks.PhotosAdapter = DS.FixtureAdapter.extend(); Photoworks.OptionsAdapter = DS.FixtureAdapter.extend(); Photoworks.CartItemSerializer = DS.LSSerializer.extend(); Photoworks.CartItemAdapter = DS.LSAdapter.extend({ namespace: 'photoworks' }); /* Map our routes, resource used for noun, route used for verb */ Photoworks.Router.map(function() { this.resource('prints'); /* Thumbnails page */ this.resource('order', { path: '/order/:photo_id' }); /* Print large view and ordering */ this.resource('printDetails'); /* Product details */ }); /* Route for large display of selected print and ordering options */ Photoworks.OrderRoute = Ember.Route.extend({ model: function(params) { return this.store.find('photos', params.photo_id); } }); /* Route for the available prints thumbnail gallery */ Photoworks.PrintsRoute = Ember.Route.extend({ model: function() { return this.store.find('photos'); } }); /* Currently only using this for the shopping cart, need to convert to a view / more specific controller I think */ Photoworks.ApplicationRoute = Ember.Route.extend({ model: function() { return this.store.find('cartItem'); } }); /* Application controller*/ Photoworks.ApplicationController = Ember.ArrayController.extend({ /* Return total number of items in cart */ totalItems: function(){ return this.get('length'); }.property('@each'), /* Return total price in cart */ totalPrice: function(){ var cartItems = this.get('model'); return cartItems.reduce(function(prevValue, item){ console.log(item.get('price')); return prevValue + item.get('price'); }, 0); }.property('@each.cartItem.price'), /* Used for the paypal form, index the cart items */ assignIndex: function(){ this.map(function(item, index){ Ember.set(item, 'index', index+1); }); }.observes('cartItem.[]', 'firstObject', 'lastObject'), /* Actions hash */ actions: { /* Clear all items from the cart */ clearCart: function(){ var cartItems = this.get('model'); cartItems.forEach(function(item){ item.deleteRecord(); item.save(); }); }, toggleCart: function(){ $('.cart').fadeToggle(); }, hideCart: function(){ $('.cart').fadeOut(); } } }); /* Controller for individual items in the cart */ Photoworks.CartItemController = Ember.ObjectController.extend({ actions: { removeFromCart: function(id){ this.store.find('cartItem', id).then(function(item){ item.deleteRecord(); item.save(); }); } }, /* For paypal checkout form */ paypalFormItem: function() { var index = this.get('index'); return 'item_name_' + index; }.property('index'), paypalFormAmount: function() { var index = this.get('index'); return 'amount_' + index; }.property('index'), paypalFormTitle: function() { var title = this.get('title'); var type = this.get('type'); var size = this.get('size'); return title + ' ' + size + ' ' + type; }.property('title', 'type', 'size') }); /* Controller for individual thumbnails on the prints page */ Photoworks.ThumbController = Ember.ObjectController.extend({ /* Return thumbnail, probably don't want this hardcoded */ url: function(){ var img = this.get('img'); return "http://mgibsonphotoworks.com/uploads/thumbs/" + img ; }.property('img') }); /* Controller for the large view ordering page */ Photoworks.OrderController = Ember.ObjectController.extend({ actions: { addToCart: function() { var title = this.get('title'); var type = this.get('type'); var size = this.get('size'); var price = this.get('price'); if (price){ var record = this.store.createRecord('cartItem', { title: title, type: type, size: size, price: price }); record.save(); $('.added').fadeIn().delay(500).fadeOut(); console.log('Added item: ' + title); } else { console.log('Please select a size'); $('.errorSelect').fadeIn().delay(500).fadeOut(); } } }, /* Available print types, maybe should convert to model instead of hardcoding */ types: [ {type: "Print Only", id: 1}, {type: "Matted Print", id: 2}, {type: "Framed Print", id: 3}, {type: "Metal Print", id: 4} ], /* Store id of current print type selected */ currentType: { id: 1 }, /* Store id of current size selected */ currentSize: { id: 1 }, /* Return large image, need to not hardcode this */ url: function(){ var img = this.get('img'); return "http://mgibsonphotoworks.com/uploads/large/" + img ; }.property('img'), /* The following are needed to keep logic out of the template, annoying */ printSelected: function(){ if (this.get('currentType.id') == 1) return true; else return false; }.property('currentType.id'), mattSelected: function(){ if (this.get('currentType.id') == 2) return true; else return false; }.property('currentType.id'), frameSelected: function(){ if (this.get('currentType.id') == 3) return true; else return false; }.property('currentType.id'), metalSelected: function(){ if (this.get('currentType.id') == 4) return true; else return false; }.property('currentType.id'), /* End annoying replacements for a simple switch statement */ /* Store current price for selected item */ price: 0, /* Store current type for selected item. This is separate from types above and comes from the options model */ type: '', /* Store currently selected print size */ size: '', /* Updates price, type, and size from option model observes for changes in the currently selected size */ itemUpdate: function() { that = this; /* Keep hold of our context */ id = this.get('currentSize.id'); /* If id is set, an option is selected */ if (id){ /* Store returns a promise, use then() to wait for it to resolve */ this.store.find('options', id).then(function(option){ console.log(option.get('price')); console.log(option.get('type')); console.log(option.get('size')); that.set('price', option.get('price')); that.set('type', option.get('type')); that.set('size', option.get('size')); }); } else { /* Size option not set, clear everything */ that.set('price', 0); that.set('type', ''); } that.set('size', ''); }.observes('currentSize.id') }); /* Model for our photos */ Photoworks.Photos = DS.Model.extend({ title: DS.attr('string'), img: DS.attr('string'), printSizes: DS.hasMany('options', { async: true }), mattSizes: DS.hasMany('options', { async: true }), frameSizes: DS.hasMany('options', { async: true }), metalSizes: DS.hasMany('options', { async: true }) }); /* Model for available print, matt, frame, and metal options */ Photoworks.Options = DS.Model.extend({ type: DS.attr('string'), size: DS.attr('string'), price: DS.attr('number'), /* To show price in select drop-down */ display: function(){ var displayed = this.get('size') + ': $' + this.get('price'); return displayed; }.property('size', 'price') }); /* Model for our shopping cart items */ Photoworks.CartItem = DS.Model.extend({ title: DS.attr('string'), type: DS.attr('string'), size: DS.attr('string'), price: DS.attr('number') }); /* Temp fixtures for testing */ /*Photoworks.CartItem.FIXTURES = [ { id: 1, title: "Pacific Northwest Rainforest", type: "Framed", size: "8x10 in 11x14", price: 50 }, { id: 2, title: "Mount Shuksan at Sunset", type: "Matt", size: "11x14 on 16x20", price: 100 } ];*/ /* Available options */ Photoworks.Options.FIXTURES = [ { id: 1, type: 'Print', size: '8"x10"', price: 50 }, { id: 2, type: 'Print', size: '8x12', price: 50 }, { id: 3, type: 'Print', size: '11x14', price: 75 }, { id: 4, type: 'Print', size: '12x18', price: 90 }, { id: 5, type: 'Print', size: '16x20', price: 100 }, { id: 6, type: 'Print', size: '10x10', price: 50 }, { id: 7, type: 'Print', size: '20x20', price: 50 }, { id: 8, type: 'Matted', size: '8x10 in 11x14', price: 50 }, { id: 9, type: 'Matted', size: '11x14 in 16x20', price: 50 }, { id: 10, type: 'Matted', size: '16x20 in 20x24', price: 50 }, ]; /* Current photos in gallery */ Photoworks.Photos.FIXTURES = [ { id: 1, title: 'Pacific Northwest Rainforest', img: 'IMG_1124%20-%20IMG_1125.jpg', printSizes: [1, 3], mattSizes: [8,9,10], frameSizes: [2,3], metalSizes: [3] }, { id: 2, title: 'Mt Shuksan', img: 'IMG_0908%20-%20IMG_0910-Edit.jpg', printSizes: [1, 3], mattSizes: [1,2], frameSizes: [2,3], metalSizes: [3] }, { id: 3, title: 'Above the snowline', img: 'IMG_1106%20-%20IMG_1111.jpg', printSizes: [1, 3], mattSizes: [1,2], frameSizes: [2,3], metalSizes: [3] }, { id: 4, title: 'Mt Index and Lake Serene', img: 'IMG_1082%20-%20IMG_1093-Edit.jpg', printSizes: [1, 3], mattSizes: [1,2], frameSizes: [2,3], metalSizes: [3] }, { id: 5, title: 'Nooksack Falls', img: 'IMG_0994%20-%20IMG_0997.jpg', printSizes: [1, 3], mattSizes: [1,2], frameSizes: [2,3], metalSizes: [3] }, { id: 6, title: 'Snowfields at Mount Baker', img: 'IMG_0926.jpg', printSizes: [1, 3], mattSizes: [1,2], frameSizes: [2,3], metalSizes: [3] } ];
Updating Photo data.
js/application.js
Updating Photo data.
<ide><path>s/application.js <ide> /* <ide> ToDo: <del> <add> -Implement photo gallery <add> -About me page <ide> <ide> */ <ide> /* Create the ember application registered to a global variable */ <ide> { <ide> id: 1, <ide> type: 'Print', <add> size: '8x12', <add> price: 50 <add> }, <add> { <add> id: 2, <add> type: 'Print', <add> size: '12x18', <add> price: 75 <add> }, <add> { <add> id: 3, <add> type: 'Print', <add> size: '16x24', <add> price: 100 <add> }, <add> { <add> id: 4, <add> type: 'Print', <add> size: '20x30', <add> price: 125 <add> }, <add> { <add> id: 5, <add> type: 'Print', <ide> size: '8"x10"', <ide> price: 50 <ide> }, <ide> { <del> id: 2, <del> type: 'Print', <del> size: '8x12', <del> price: 50 <del> }, <del> { <del> id: 3, <add> id: 6, <ide> type: 'Print', <ide> size: '11x14', <ide> price: 75 <ide> }, <ide> { <del> id: 4, <del> type: 'Print', <add> id: 7, <add> type: 'Print', <add> size: '16x20', <add> price: 100 <add> }, <add> { <add> id: 8, <add> type: 'Print', <add> size: '20x24', <add> price: 125 <add> }, <add> { <add> id: 9, <add> type: 'Matted', <add> size: '8x12 on 11x14', <add> price: 75 <add> }, <add> { <add> id: 10, <add> type: 'Matted', <add> size: '11x16 on 16x20', <add> price: 100 <add> }, <add> { <add> id: 11, <add> type: 'Matted', <add> size: '12x18 on 24x30', <add> price: 125 <add> }, <add> { <add> id: 12, <add> type: 'Matted', <add> size: '8x10 on 11x14', <add> price: 75 <add> }, <add> { <add> id: 13, <add> type: 'Matted', <add> size: '11x14 on 16x20', <add> price: 100 <add> }, <add> { <add> id: 14, <add> type: 'Matted', <add> size: '16x20 on 20x24', <add> price: 125 <add> }, <add> { <add> id: 15, <add> type: 'Framed', <add> size: '8x12 in 11x14', <add> price: 125 <add> }, <add> { <add> id: 16, <add> type: 'Framed', <add> size: '11x16 in 16x20', <add> price: 175 <add> }, <add> { <add> id: 17, <add> type: 'Framed', <add> size: '14x20 in 24x30', <add> price: 225 <add> }, <add> { <add> id: 18, <add> type: 'Metal', <add> size: '8x12', <add> price: 100 <add> }, <add> { <add> id: 19, <add> type: 'Metal', <ide> size: '12x18', <del> price: 90 <del> }, <del> { <del> id: 5, <del> type: 'Print', <del> size: '16x20', <del> price: 100 <del> }, <del> { <del> id: 6, <add> price: 150 <add> }, <add> { <add> id: 20, <add> type: 'Metal', <add> size: '16x24', <add> price: 200 <add> }, <add> { <add> id: 21, <add> type: 'Metal', <add> size: '20x30', <add> price: 250 <add> }, <add> { <add> id: 22, <ide> type: 'Print', <ide> size: '10x10', <ide> price: 50 <ide> }, <ide> { <del> id: 7, <add> id: 23, <add> type: 'Print', <add> size: '16x16', <add> price: 75 <add> }, <add> { <add> id: 24, <ide> type: 'Print', <ide> size: '20x20', <del> price: 50 <del> }, <del> { <del> id: 8, <del> type: 'Matted', <del> size: '8x10 in 11x14', <del> price: 50 <del> }, <del> { <del> id: 9, <del> type: 'Matted', <del> size: '11x14 in 16x20', <del> price: 50 <del> }, <del> { <del> id: 10, <del> type: 'Matted', <del> size: '16x20 in 20x24', <del> price: 50 <add> price: 100 <add> }, <add> { <add> id: 25, <add> type: 'Matted', <add> size: '10x10 on 12x12', <add> price: 75 <add> }, <add> { <add> id: 26, <add> type: 'Framed', <add> size: '10x10 in 12x12', <add> price: 125 <add> }, <add> { <add> id: 27, <add> type: 'Framed', <add> size: '16x16 in 20x20', <add> price: 200 <add> }, <add> { <add> id: 28, <add> type: 'Metal', <add> size: '10x10', <add> price: 100 <add> }, <add> { <add> id: 29, <add> type: 'Metal', <add> size: '16x16', <add> price: 150 <add> }, <add> { <add> id: 30, <add> type: 'Metal', <add> size: '24x24', <add> price: 250 <add> }, <add> { <add> id: 31, <add> type: 'Metal', <add> size: '12x36', <add> price: 250 <add> }, <add> { <add> id: 32, <add> type: 'Metal', <add> size: '20x60', <add> price: 500 <add> }, <add> { <add> id: 33, <add> type: 'Framed', <add> size: '12x36', <add> price: 200 <add> }, <add> { <add> id: 34, <add> type: 'Print', <add> size: '12x36', <add> price: 100 <add> }, <add> { <add> id: 35, <add> type: 'Print', <add> size: '16x48', <add> price: 150 <add> }, <add> { <add> id: 36, <add> type: 'Print', <add> size: '20x60', <add> price: 200 <ide> }, <ide> ]; <ide> <ide> id: 1, <ide> title: 'Pacific Northwest Rainforest', <ide> img: 'IMG_1124%20-%20IMG_1125.jpg', <del> printSizes: [1, 3], <del> mattSizes: [8,9,10], <del> frameSizes: [2,3], <del> metalSizes: [3] <add> printSizes: [22, 23, 24], <add> mattSizes: [25], <add> frameSizes: [26, 27], <add> metalSizes: [28, 29, 30] <ide> }, <ide> { <ide> id: 2, <ide> title: 'Mt Shuksan', <ide> img: 'IMG_0908%20-%20IMG_0910-Edit.jpg', <del> printSizes: [1, 3], <del> mattSizes: [1,2], <del> frameSizes: [2,3], <del> metalSizes: [3] <add> printSizes: [34, 35, 36], <add> mattSizes: [], <add> frameSizes: [33], <add> metalSizes: [31, 32] <ide> }, <ide> { <ide> id: 3,
Java
apache-2.0
7af38385c5d069bcec9bdfe3b8b1babaf65a6b59
0
apache/incubator-taverna-engine,apache/incubator-taverna-engine
/******************************************************************************* * Copyright (C) 2007 The University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 ******************************************************************************/ package net.sf.taverna.t2.security.credentialmanager; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.math.BigInteger; import java.net.URLDecoder; import java.net.URLEncoder; import java.security.Key; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.PrivateKey; import java.security.Provider; import java.security.Security; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.TreeMap; import javax.crypto.spec.SecretKeySpec; import javax.security.auth.x500.X500Principal; import net.sf.taverna.t2.lang.observer.MultiCaster; import net.sf.taverna.t2.lang.observer.Observable; import net.sf.taverna.t2.lang.observer.Observer; import net.sf.taverna.t2.spi.SPIRegistry; import org.apache.log4j.Logger; /** * Provides a wrapper for the user's Keystore and Truststore and implements * methods for managing user's credentials (passwords, private key pairs and * proxies) and trusted services' public key certificates. * * @author Alex Nenadic */ public class CredentialManager implements Observable<KeystoreChangedEvent>{ private static final String T2TRUSTSTORE_FILE = "t2truststore.jks"; private static final String SERVICE_URLS_FILE = "t2serviceURLs.txt"; private static final String T2KEYSTORE_FILE = "t2keystore.ubr"; // Log4J Logger private static Logger logger = Logger.getLogger(CredentialManager.class); // Multicaster of KeystoreChangedEventS private MultiCaster<KeystoreChangedEvent> multiCaster = new MultiCaster<KeystoreChangedEvent>( this); // Security config directory private static File secConfigDirectory = CMUtil.getSecurityConfigurationDirectory(); // Keystore file. private static File keystoreFile = new File(secConfigDirectory,T2KEYSTORE_FILE); // Truststore file. private static File truststoreFile = new File(secConfigDirectory,T2TRUSTSTORE_FILE); // Service URLs file containing lists of service URLs associated with private key aliases. // The alias points to the key pair entry to be used for a particular service. private static File serviceURLsFile = new File(secConfigDirectory,SERVICE_URLS_FILE); // Master password the Keystore and Truststore are created/accessed with. private static String masterPassword; // Keystore containing user's passwords, private keys and public key certificate chains. private static KeyStore keystore; // Truststore containing trusted certificates of CA authorities and services. private static KeyStore truststore; // A map of service URLs associated with private key aliases, i.e. aliases // are keys in the hashmap and lists of URLs are hashmap values. private static HashMap<String,ArrayList<String>> serviceURLsForKeyPairs; // Constants denoting which of the two keystores we are currently // performing operations on. public static final String KEYSTORE = "Keystore"; public static final String TRUSTSTORE = "Truststore"; // Default password for Truststore - needed as the Truststore needs to be populated // sometimes before the Workbench starts up - e.g. in case of caGrid when trusted CAs // need to be inserted there at startup. private static final String TRUSTSTORE_PASSWORD = "raehiekooshe0eghiPhi"; // Credential Manager singleton private static CredentialManager INSTANCE; // Bouncy Castle provider private static Provider bcProvider; /** * Returns a CredentialManager singleton. */ public static CredentialManager getInstance() throws CMException { synchronized (CredentialManager.class) { if (INSTANCE == null) INSTANCE = new CredentialManager(); } return INSTANCE; } /** * Overrides the Objects clone method to prevent the singleton object to be * cloned. */ @Override public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } /** * Credential Manager constructor. The constructor is private * to suppress unauthorized calls to it. */ private CredentialManager() throws CMException { SPIRegistry<MasterPasswordProviderSPI> masterPasswordManager = new SPIRegistry<MasterPasswordProviderSPI>(MasterPasswordProviderSPI.class); TreeMap<Integer, MasterPasswordProviderSPI> sortedProviders = new TreeMap<Integer, MasterPasswordProviderSPI>(); for (MasterPasswordProviderSPI spi : masterPasswordManager.getInstances()) { int priority = spi.canProvidePassword(); if (priority >= 0){ sortedProviders.put(new Integer(priority), spi); } } if (!sortedProviders.isEmpty()){ // we have found at least one password provider while (!sortedProviders.isEmpty()){ MasterPasswordProviderSPI provider = sortedProviders.get(sortedProviders.lastKey()); String password = provider.getPassword(); if (password!= null){ masterPassword = password; break; } sortedProviders.remove(sortedProviders.lastKey()); } } else{ // We are in big trouble - we do not have the master password String exMessage = "Failed to obtain master password."; logger.error(exMessage); throw new CMException(exMessage); } // We do not want anyone to call Security.addProvider() and // Security.removeProvider() synchronized methods until we // execute this block to prevent someone interfering with // our adding and removing of BC security provider synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); // Get the new Bouncy Castle provider try { ClassLoader ourCL = getClass().getClassLoader(); Class<?> bcProvClass = ourCL.loadClass("org.bouncycastle.jce.provider.BouncyCastleProvider"); bcProvider = (Provider) bcProvClass.newInstance(); // Add our BC provider as a security provider // while doing the crypto operations Security.addProvider(bcProvider); logger.info("Credential Manager: Adding Bouncy Castle security provider version " + bcProvider.getVersion()); } catch (Exception ex) { // No sign of the provider String exMessage = "Failed to load the Bouncy Castle cryptographic provider"; ex.printStackTrace(); logger.error(ex); // Return the old BC providers and remove the one we have added restoreOldBCProviders(oldBCProviders); throw new CMException(exMessage); } init(masterPassword); // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } private static void restoreOldBCProviders(ArrayList<Provider> oldBCProviders) { Security.removeProvider("BC"); for (Provider prov : oldBCProviders){ Security.addProvider(prov); } } private static ArrayList<Provider> unregisterOldBCProviders() { ArrayList<Provider> oldBCProviders = new ArrayList<Provider>(); // Different versions of Bouncy Castle provider may be lurking around. // E.g. an old 1.25 version of Bouncy Castle provider // is added by caGrid package and others may be as well by // third party providers for (int i=0; i<Security.getProviders().length; i++){ if(Security.getProviders()[i].getName().equals("BC")){ oldBCProviders.add(Security.getProviders()[i]); } } // Remove (hopefully) all registered BC providers Security.removeProvider("BC"); return oldBCProviders; } /** * Initialises Credential Manager - loads the Keystore, Truststore and serviceURLsFile. */ public void init(String mPassword) throws CMException { // Load the Keystore try { keystore = loadKeystore(mPassword); logger.info("Credential Manager: Loaded the Keystore."); } catch (CMException cme) { logger.error(cme.getMessage(), cme); throw cme; } // Load service URLs associated with private key aliases from a file try { loadServiceURLsForKeyPairs(); logger.info("Credential Manager: Loaded the Service URLs for private key pairs."); } catch (CMException cme) { logger.error(cme.getMessage(), cme); throw cme; } // Load the Truststore try { truststore = loadTruststore(TRUSTSTORE_PASSWORD); logger.info("Credential Manager: Loaded the Truststore."); } catch (CMException cme) { logger.error(cme.getMessage(), cme); throw cme; } } /** * Loads Taverna's Bouncy Castle "UBER"-type keystore from a file on the disk and * returns it. */ public static KeyStore loadKeystore(String masterPassword) throws CMException { KeyStore keystore = null; try { keystore = KeyStore.getInstance("UBER", "BC"); } catch (Exception ex) { // The requested keystore type is not available from the provider String exMessage = "Failed to instantiate a Bouncy Castle 'UBER'-type keystore."; logger.error(exMessage, ex); ex.printStackTrace(); throw new CMException(exMessage); } if (keystoreFile.exists()) { // If the file exists, open it // Try to load the keystore as Bouncy Castle "UBER"-type // keystore FileInputStream fis = null; try { // Get the file fis = new FileInputStream(keystoreFile); // Load the keystore from the file keystore.load(fis, masterPassword.toCharArray()); } catch (Exception ex) { String exMessage = "Failed to load the keystore. Possible reason: incorrect password or corrupted file."; logger.error(exMessage, ex); ex.printStackTrace(); throw new CMException(exMessage); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { // ignore } } } } else { // Otherwise create a new empty keystore FileOutputStream fos = null; try { keystore.load(null, null); // Immediately save the new (empty) keystore to the file fos = new FileOutputStream(keystoreFile); keystore.store(fos, masterPassword.toCharArray()); } catch (Exception ex) { String exMessage = "Failed to generate a new empty keystore."; logger.error(exMessage, ex); ex.printStackTrace(); throw new CMException(exMessage); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { // ignore } } } } return keystore; } /** * Load Taverna's truststore from a file on a disk. If the truststore * does not already exist, a new empty one will be created and contents * of Java's truststore located in <JAVA_HOME>/lib/security/cacerts will * be copied over to this truststore. */ private static KeyStore loadTruststore(String masterPassword) throws CMException{ KeyStore truststore = null; // Try to create the Taverna's Truststore - has to be "JKS"-type keystore // because we use it to set the system property "javax.net.ssl.trustStore" try { truststore = KeyStore.getInstance("JKS"); } catch (Exception ex) { // The requested keystore type is not available from the provider String exMessage = "Failed to instantiate a 'JKS'-type keystore."; logger.error(exMessage, ex); ex.printStackTrace(); throw new CMException(exMessage); } if (truststoreFile.exists()) { // If the Truststore file already exists, open it and load the Truststore FileInputStream fis = null; try { // Get the file fis = new FileInputStream(truststoreFile); // Load the Truststore from the file truststore.load(fis, masterPassword.toCharArray()); } catch (Exception ex) { String exMessage = "Failed to load the truststore. Possible reason: incorrect password or corrupted file."; logger.error(exMessage, ex); ex.printStackTrace(); throw new CMException(exMessage); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { // ignore } } } } else { // Otherwise create a new empty truststore and load it with certs from Java's truststore File javaTruststoreFile = new File(System.getProperty("java.home") + "/lib/security/cacerts"); KeyStore javaTruststore = null; // Java's truststore is of type "JKS" - try to load it try { javaTruststore = KeyStore.getInstance("JKS"); } catch (Exception ex) { // The requested keystore type is not available from the provider String exMessage = "Failed to instantiate a 'JKS'-type keystore."; logger.error(exMessage, ex); ex.printStackTrace(); throw new CMException(exMessage); } FileInputStream fis = null; boolean loadedJavaTruststore = false; try { // Get the file fis = new FileInputStream(javaTruststoreFile); // Load the Java keystore from the file javaTruststore.load(fis, "changeit".toCharArray()); // try with the default Java truststore password first loadedJavaTruststore = true; } catch(IOException ioex){ // If there is an I/O or format problem with the keystore data, // or if the given password was incorrect logger.error("Failed to load the Java truststore to copy over certificates using default password 'changeit'. Trying with user-provided password."); // Close the input stream and reopen it to rewind it (resetting it did not work for some reason) if (fis != null) { try { fis.close(); fis = new FileInputStream(javaTruststoreFile); } catch (IOException e) { // ignore } } // Hopefully it was the password problem - ask user to provide // their password for the Java truststore GetMasterPasswordDialog getPasswordDialog = new GetMasterPasswordDialog("Credential Manager needs to copy certificates from Java truststore. Please enter your password."); getPasswordDialog.setLocationRelativeTo(null); getPasswordDialog.setVisible(true); String javaTruststorePassword = getPasswordDialog.getPassword(); if (javaTruststorePassword == null){ // user cancelled - do not try to load Java truststore loadedJavaTruststore = false; } else{ try { javaTruststore.load(fis, javaTruststorePassword.toCharArray()); loadedJavaTruststore = true; } catch (Exception ex) { String exMessage = "Failed to load the Java truststore to copy over certificates using user-provided password. Creating a new empty truststore for Taverna."; logger.error(exMessage, ex); ex.printStackTrace(); loadedJavaTruststore = false; } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { // ignore } } } } } catch (Exception ex) { String exMessage = "Failed to load the Java truststore to copy over certificates. Creating a new empty truststore for Taverna."; logger.error(exMessage, ex); ex.printStackTrace(); loadedJavaTruststore = false; } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { // ignore } } } FileOutputStream fos = null; // Create a new empty truststore for Taverna try { truststore.load(null, null); if (loadedJavaTruststore){ // Copy certificates into Taverna's truststore from Java truststore Enumeration<String> aliases = javaTruststore.aliases(); while (aliases.hasMoreElements()){ String alias = aliases.nextElement(); Certificate certificate = javaTruststore.getCertificate(alias); if (certificate instanceof X509Certificate){ String trustedCertAlias = createX509CertificateAlias((X509Certificate)certificate); truststore.setCertificateEntry(trustedCertAlias, certificate); } } } // Immediately save the new truststore to the file fos = new FileOutputStream(truststoreFile); truststore.store(fos, masterPassword.toCharArray()); } catch (Exception ex) { String exMessage = "Failed to generate a new truststore."; logger.error(exMessage, ex); ex.printStackTrace(); throw new CMException(exMessage); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { // ignore } } } } // Set the system property "javax.net.ssl.Truststore" to use Taverna's truststore System.setProperty("javax.net.ssl.trustStore", truststoreFile.getAbsolutePath()); System.setProperty("javax.net.ssl.trustStorePassword", masterPassword); // Taverna distro for MAC contains info.plist file with some Java system properties set to // use the Keychain which clashes with what we are setting here so we need to clear them System.clearProperty("javax.net.ssl.trustStoreType"); System.clearProperty("javax.net.ssl.trustStoreProvider"); return truststore; } /** * Load lists of service URLs associated with private key aliases from a * file and populate the serviceURLs hashmap. */ public void loadServiceURLsForKeyPairs() throws CMException { serviceURLsForKeyPairs = new HashMap<String, ArrayList<String>>(); synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); try { // Create an empty map with aliases as keys for (Enumeration<String> e = keystore.aliases(); e .hasMoreElements();) { String element = (String) e.nextElement(); // We want only key pair entry aliases (and not password entry aliases) if (element.startsWith("keypair#")) serviceURLsForKeyPairs.put(element, new ArrayList<String>()); } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to get private key aliases when loading service URLs."; logger.error(exMessage, ex); ex.printStackTrace(); throw (new CMException(exMessage)); } // If Service URLs file exists - load the URL lists from the file if (serviceURLsFile.exists()) { BufferedReader serviceURLsReader = null; try { serviceURLsReader = new BufferedReader(new FileReader(serviceURLsFile)); String line = serviceURLsReader.readLine(); while (line != null) { // Line consists of an URL-encoded URL and alias // separated by a blank character, // i.e. line=<ENCODED_URL>" "<ALIAS> // One alias can have more than one URL associated with it // (i.e. more // than one line in the file can exist for the same alias). String alias = line.substring(line.indexOf(' ') + 1); String url = line.substring(0, line.indexOf(' ')); // URLs were encoded before storing them in a file url = URLDecoder.decode(url, "UTF-8"); ArrayList<String> urlsList = (ArrayList<String>) serviceURLsForKeyPairs .get(alias); // get URL list for the current alias (it can be empty) if (urlsList == null) { urlsList = new ArrayList<String>(); } urlsList.add(url); // add the new URL to the list of URLs for this alias serviceURLsForKeyPairs.put(alias, urlsList); // put the updated list back to the map line = serviceURLsReader.readLine(); } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to read the service URLs file."; logger.error(exMessage, ex); ex.printStackTrace(); throw (new CMException(exMessage)); } finally { if (serviceURLsReader != null) { try { serviceURLsReader.close(); } catch (IOException e) { // ignore } } // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } } /** * Add the service URLs list associated with a private key entry to the serviceURLs * hashmap and save/update the service URLs file. */ public void saveServiceURLsForKeyPair(String alias, ArrayList<String> serviceURLsList) throws CMException { // Add service url list to the serviceURLs hashmap (overwrites previous // value, if any) serviceURLsForKeyPairs.put(alias, serviceURLsList); // Save the updated hashmap to the file saveServiceURLsForKeyPairs(); } /** * Get the service URLs list associated with a private key entry. */ public ArrayList<String> getServiceURLsForKeyPair(String alias){ return serviceURLsForKeyPairs.get(alias); } /** * Get a map of service URL lists for each of the private key entries in the Keystore. */ public HashMap<String, ArrayList<String>> getServiceURLsforKeyPairs() { return serviceURLsForKeyPairs; } /** * Delete the service URLs list associated with a private key entry. */ public void deleteServiceURLsForKeyPair(String alias) throws CMException { // Remove service URL list from the serviceURLs hashmap serviceURLsForKeyPairs.remove(alias); // Save the updated serviceURLs hashmap to the file saveServiceURLsForKeyPairs(); } /** * Saves the content of serviceURLs map to a file. Overwrites previous * content of the file. */ public void saveServiceURLsForKeyPairs() throws CMException { synchronized (serviceURLsFile) { // If file already exists if (serviceURLsFile.exists()) { // Delete the previous contents of the file serviceURLsFile.delete(); } // Create a new empty file try { serviceURLsFile.createNewFile(); } catch (IOException ex) { String exMessage = "Credential Manager: Failed to create a new service URLs' file."; logger.error(exMessage, ex); ex.printStackTrace(); throw (new CMException(exMessage)); } BufferedWriter serviceURLsWriter = null; try { // Open the file for writing serviceURLsWriter = new BufferedWriter((new FileWriter( serviceURLsFile, false))); // Write the serviceURLs hashmap to the file for (String alias : serviceURLsForKeyPairs.keySet()) { // for all aliases // For all urls associated with the alias ArrayList<String> serviceURLsForKeyPair = (ArrayList<String>) serviceURLsForKeyPairs .get(alias); for (String serviceURL : serviceURLsForKeyPair) { // Each line of the file contains an encoded service URL // with its associated alias appended and separated from // the URL by a blank character ' ', // i.e. line=<ENCODED_URL>" "<ALIAS> // Service URLs are encoded before saving to make sure // they do not contain blank characters // that are used as delimiters. String encodedURL = URLEncoder.encode((String) serviceURL, "UTF-8"); StringBuffer line = new StringBuffer(encodedURL + " " + alias); serviceURLsWriter.append(line); serviceURLsWriter.newLine(); } } } catch (FileNotFoundException ex) { // Should not happen } catch (IOException ex) { String exMessage = "Credential Manager: Failed to save the service URLs to the file."; logger.error(exMessage, ex); ex.printStackTrace(); throw (new CMException(exMessage)); } finally { if (serviceURLsWriter != null) { try { serviceURLsWriter.close(); } catch (IOException e) { // ignore } } } } } /** * Get a username and password pair for the given service, or null if it * does not exit. */ public String getUsernameAndPasswordForService(String serviceURL) throws CMException { synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); // Alias for the username and password entry String alias = "password#" + serviceURL; SecretKeySpec passwordKey = null; try { synchronized (keystore) { passwordKey = (((SecretKeySpec) keystore .getKey(alias, null))); } if (passwordKey != null){ String unpasspair = new String(passwordKey.getEncoded()); // the decoded key contains string <USERNAME>" "<PASSWORD> return unpasspair; } else{ return null; } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to get the username and password pair for service " + serviceURL + " from the Keystore."; ex.printStackTrace(); logger.error(exMessage, ex); throw (new CMException(exMessage)); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Get service URLs associated with all username/password pairs currently in the Keystore. */ public ArrayList<String> getServiceURLsforUsernameAndPasswords() throws CMException{ ArrayList<String> serviceURLs = new ArrayList<String>(); ArrayList<String> aliases; try{ aliases = getAliases(KEYSTORE); } catch(CMException cme){ String exMessage = "Credential Manager: Failed to access the Keystore to get the service URLs for passwords."; logger.error(exMessage); throw new CMException(exMessage); } for (String alias: aliases){ if (alias.startsWith("password#")){ serviceURLs.add(alias.substring(alias.indexOf('#')+1)); } } return serviceURLs; } /** * Insert a new username and password pair in the keystore for the given service URL. * * Effectively, this method inserts a new secret key entry in the keystore, where * key contains <USERNAME>" "<PASSWORD> string, i.e. password is prepended with the * username and separated by a blank character (which hopefully will not appear in * the username). * * Username and password string is saved in the Keystore as byte array using * SecretKeySpec (which constructs a secret key from the given byte array but * does not check if the given bytes indeed specify a secret key of the * specified algorithm). * * An alias used to identify the username and password entry is constructed as * "password#"<SERVICE_URL> using the service URL * this username/password pair is to be used for. */ public void saveUsernameAndPasswordForService(String username, String password, String serviceURL) throws CMException { synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); // Alias for the username and password entry String alias = "password#" + serviceURL; /* * Password (together with its related username) is wrapped as a * SecretKeySpec that implements SecretKey and constructs a secret * key from the given password as a byte array. The reason for this * is that we can only save instances of Key objects in the * Keystore, and SecretKeySpec class is useful for raw secret keys * (i.e. username and passwords concats) that can be represented as * a byte array and have no key or algorithm parameters associated * with them, e.g., DES or Triple DES. That is why we create it with * the name "DUMMY" for algorithm name, as this is not checked for * anyway. * * Blank character is a good separator as it (most probably) will * not appear in the username. */ String keyToSave = username + " " + password; SecretKeySpec passwordKey = new SecretKeySpec(keyToSave.getBytes(), "DUMMY"); try { synchronized (keystore) { keystore.setKeyEntry(alias, passwordKey, null, null); saveKeystore(KEYSTORE); multiCaster.notify(new KeystoreChangedEvent(CredentialManager.KEYSTORE)); } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to insert username and password pair for service "+ serviceURL+ " in the Keystore."; logger.error(exMessage, ex); ex.printStackTrace(); throw (new CMException(exMessage)); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Delete username and password pair for the given service URL from the Keystore. */ public void deleteUsernameAndPasswordForService(String serviceURL) throws CMException{ deleteEntry(KEYSTORE, "password#"+serviceURL); saveKeystore(KEYSTORE); multiCaster.notify(new KeystoreChangedEvent(CredentialManager.KEYSTORE)); } /** * Get key pair entry's private key for the given service URL. */ public PrivateKey getPrivateKey(String serviceURL){ //TODO return null; } /** * Get key pair entry's public key certificate chain for the given service URL. */ public Certificate[] getPublicKeyCertificateChain(String serviceURL){ //TODO return null; } /** * Insert a new key entry containing private key and public key certificate * (chain) in the Keystore and save the list of service URLs this key pair * is associated to. * * An alias used to identify the keypair entry is constructed as: * "keypair#"<CERT_SUBJECT_COMMON_NAME>"#"<CERT_ISSUER_COMMON_NAME>"#"<CERT_SERIAL_NUMBER> */ public void saveKeyPair(Key privateKey, Certificate[] certs, ArrayList<String> serviceURLs) throws CMException { synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); // Create an alias for the new key pair entry in the Keystore // as "keypair#"<CERT_SUBJECT_COMMON_NAME>"#"<CERT_ISSUER_COMMON_NAME>"#"<CERT_SERIAL_NUMBER> String ownerDN = ((X509Certificate) certs[0]).getSubjectX500Principal() .getName(X500Principal.RFC2253); CMX509Util util = new CMX509Util(); util.parseDN(ownerDN); String ownerCN = util.getCN(); // owner's common name // Get the hexadecimal representation of the certificate's serial number String serialNumber = new BigInteger(1, ((X509Certificate) certs[0]) .getSerialNumber().toByteArray()).toString(16) .toUpperCase(); String issuerDN = ((X509Certificate) certs[0]).getIssuerX500Principal() .getName(X500Principal.RFC2253); util.parseDN(issuerDN); String issuerCN = util.getCN(); // issuer's common name String alias = "keypair#" + ownerCN + "#" + issuerCN + "#" + serialNumber; try { synchronized (keystore) { keystore.setKeyEntry(alias, privateKey, null, certs); saveKeystore(KEYSTORE); // Add service url list to the serviceURLs hashmap (overwrites previous // value, if any) if (serviceURLs == null) serviceURLs = new ArrayList<String>(); serviceURLsForKeyPairs.put(alias, serviceURLs); // Save the updated hashmap to the file saveServiceURLsForKeyPairs(); multiCaster.notify(new KeystoreChangedEvent(CredentialManager.KEYSTORE)); } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to insert the key pair entry in the Keystore."; logger.error(exMessage, ex); ex.printStackTrace(); throw (new CMException(exMessage)); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Check if the Keystore contains the key pair entry. */ public boolean containsKeyPair(Key privateKey, Certificate[] certs) throws CMException { synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); // Create an alias for the new key pair entry in the Keystore // as "keypair#"<CERT_SUBJECT_COMMON_NAME>"#"<CERT_ISSUER_COMMON_NAME>"#"<CERT_SERIAL_NUMBER> String ownerDN = ((X509Certificate) certs[0]).getSubjectX500Principal() .getName(X500Principal.RFC2253); CMX509Util util = new CMX509Util(); util.parseDN(ownerDN); String ownerCN = util.getCN(); // owner's common name // Get the hexadecimal representation of the certificate's serial number String serialNumber = new BigInteger(1, ((X509Certificate) certs[0]) .getSerialNumber().toByteArray()).toString(16) .toUpperCase(); String issuerDN = ((X509Certificate) certs[0]).getIssuerX500Principal() .getName(X500Principal.RFC2253); util.parseDN(issuerDN); String issuerCN = util.getCN(); // issuer's common name String alias = "keypair#" + ownerCN + "#" + issuerCN + "#" + serialNumber; synchronized (keystore) { try { return keystore.containsAlias(alias); } catch (KeyStoreException ex) { String exMessage = "Credential Manager: Failed to get aliases from the Keystore ti check if it contains the given key pair."; logger.error(exMessage, ex); ex.printStackTrace(); throw (new CMException(exMessage)); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } } /** * Delete key pair entry from the Keystore. */ public void deleteKeyPair(String alias) throws CMException{ // TODO: We are passing alias for now but we want to be passing // the private key and its public key certificate // // Create an alias for the new key pair entry in the Keystore // // as "keypair#"<CERT_SUBJECT_COMMON_NAME>"#"<CERT_ISSUER_COMMON_NAME>"#"<CERT_SERIAL_NUMBER> // String ownerDN = ((X509Certificate) certs[0]).getSubjectX500Principal() // .getName(X500Principal.RFC2253); // CMX509Util util = new CMX509Util(); // util.parseDN(ownerDN); // String ownerCN = util.getCN(); // owner's common name // // // Get the hexadecimal representation of the certificate's serial number // String serialNumber = new BigInteger(1, ((X509Certificate) certs[0]) // .getSerialNumber().toByteArray()).toString(16) // .toUpperCase(); // // String issuerDN = ((X509Certificate) certs[0]).getIssuerX500Principal() // .getName(X500Principal.RFC2253); // util.parseDN(issuerDN); // String issuerCN = util.getCN(); // issuer's common name // // String alias = "keypair#" + ownerCN + "#" + issuerCN + "#" + serialNumber; deleteEntry(KEYSTORE, alias); saveKeystore(KEYSTORE); deleteServiceURLsForKeyPair(alias); multiCaster.notify(new KeystoreChangedEvent(CredentialManager.KEYSTORE)); } /** * Exports a key entry containing private key and public key certificate * (chain) from the Keystore to a PKCS #12 file. */ public void exportKeyPair(String alias, File exportFile, String pkcs12Password) throws CMException { FileOutputStream fos = null; synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); // Export the key pair try { // Get the private key for the alias PrivateKey privateKey = (PrivateKey) keystore.getKey(alias, null); // Get the related public key's certificate chain Certificate[] certChain = getCertificateChain(alias); // Create a new PKCS #12 keystore KeyStore newPkcs12 = KeyStore.getInstance("PKCS12", "BC"); newPkcs12.load(null, null); // Place the private key and certificate chain into the PKCS #12 // keystore. // Construct a new alias as "<SUBJECT_COMMON_NAME>'s <ISSUER_ORGANISATION> ID" String sDN = ((X509Certificate) certChain[0]) .getSubjectX500Principal().getName(X500Principal.RFC2253); CMX509Util util = new CMX509Util(); util.parseDN(sDN); String sCN = util.getCN(); String iDN = ((X509Certificate) certChain[0]) .getIssuerX500Principal().getName(X500Principal.RFC2253); util.parseDN(iDN); String iCN = util.getCN(); String pkcs12Alias = sCN + "'s " + iCN + " ID"; newPkcs12.setKeyEntry(pkcs12Alias, privateKey, new char[0], certChain); // Store the new PKCS #12 keystore on the disk fos = new FileOutputStream(exportFile); newPkcs12.store(fos, pkcs12Password.toCharArray()); fos.close(); } catch (Exception ex) { String exMessage = "Credential Manager: Failed to export the key pair from the Keystore."; logger.error(exMessage, ex); throw (new CMException(exMessage)); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { // ignore } } // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Returns caGrid proxy's private key entry for the given Authentication and Dorian services. * * Since caGrid v1.3, caGrid proxies are just normal key pairs where the * validity of the key is 12 hours by default. * Before v1.3 these were actual proxies. Still we differentiate between * these and normal 'key pair' entries and form their keystore aliases as: * * "cagridproxy#"<AuthNServiceURL>" "<DorianServiceURL> * * This basically means that AuthN Service URL and Dorian Service URL define * a single caGrid proxy entry in the keystore. * */ public synchronized PrivateKey getCaGridProxyPrivateKey(String authNServiceURL, String dorianServiceURL) throws CMException{ synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); String proxyAlias = "cagridproxy#" + authNServiceURL + " " + dorianServiceURL; PrivateKey privateKey = null; try { privateKey = (PrivateKey) keystore.getKey(proxyAlias, null); } catch (Exception ex) { String exMessage = "Credential Manager: Failed to get the private key of the proxy key pair entry"; logger.error(exMessage); ex.printStackTrace(); throw new CMException(exMessage); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } return privateKey; } } /** * Returns caGrid proxy's cerificate chain for the given Authentication and Dorian services. * The alias used to get the chain is constructed as: * * "cagridproxy#"<AuthNServiceURL>" "<DorianServiceURL> */ public synchronized Certificate[] getCaGridProxyCertificateChain(String authNServiceURL, String dorianServiceURL) throws CMException{ synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); String proxyAlias = "cagridproxy#" + authNServiceURL + " " + dorianServiceURL; // Get the proxy key pair entry's certificate chain Certificate[] certChain = null; try { certChain = getCertificateChain(proxyAlias); } catch (Exception ex) { String exMessage = "Credential Manager: Failed to get the certificate chain for the proxy entry"; logger.error(exMessage); ex.printStackTrace(); throw new CMException(exMessage); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } return certChain; } } /** * Insert a proxy key entry in the Keystore with an alias constructed as: * * "cagridproxy#"<AuthNServiceURL>" "<DorianServiceURL> */ public synchronized void saveCaGridProxy(PrivateKey privateKey, X509Certificate[] x509CertChain, String authNServiceURL, String dorianServiceURL) throws CMException { synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); String proxyAlias = "cagridproxy#" + authNServiceURL + " " + dorianServiceURL; try { synchronized (keystore) { keystore.setKeyEntry(proxyAlias, privateKey, null, x509CertChain); saveKeystore(KEYSTORE); multiCaster.notify(new KeystoreChangedEvent(CredentialManager.KEYSTORE)); } } catch (KeyStoreException ex) { String exMessage = "Credential Manager: Failed to insert the proxy key pair in the keystore."; logger.error(exMessage); ex.printStackTrace(); throw (new CMException(exMessage)); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Delete caGrid proxy entry from the Keystore. */ public void deleteCaGridProxy(String alias) throws CMException{ deleteEntry(KEYSTORE, alias); saveKeystore(KEYSTORE); multiCaster.notify(new KeystoreChangedEvent(CredentialManager.KEYSTORE)); } /** * Get certificate entry from the Keystore or Truststore. * If the given alias name identifies a trusted certificate entry, the * certificate associated with that entry is returned from the Truststore. * If the given alias name identifies a key pair entry, the first element of * the certificate chain of that entry is returned from the Keystore. */ public Certificate getCertificate(String ksType, String alias) throws CMException { synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); try { if (ksType.equals(KEYSTORE)) { synchronized (keystore) { return keystore.getCertificate(alias); } } else if (ksType.equals(TRUSTSTORE)) { synchronized (truststore) { return truststore.getCertificate(alias); } } else{ return null; } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to fetch certificate from the " + ksType + "."; logger.error(exMessage, ex); throw (new CMException(exMessage)); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Gets certificate chain for the key pair entry from the Keystore. This * method works for Keystore only as Truststore does not contain key pair * entries, but trusted certificate entries only. */ public Certificate[] getCertificateChain(String alias) throws CMException{ synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); try { synchronized (keystore) { return keystore.getCertificateChain(alias); } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to fetch certificate chain for the keypair from the Keystore"; logger.error(exMessage, ex); throw (new CMException(exMessage)); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Insert a trusted certificate entry in the Truststore with an * alias constructed as: * * "trustedcert#<CERT_SUBJECT_COMMON_NAME>"#"<CERT_ISSUER_COMMON_NAME>"#"<CERT_SERIAL_NUMBER> */ public void saveTrustedCertificate(X509Certificate cert) throws CMException { synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); // Create an alias for the new trusted certificate entry in the Truststore // as "trustedcert#"<CERT_SUBJECT_COMMON_NAME>"#"<CERT_ISSUER_COMMON_NAME>"#"<CERT_SERIAL_NUMBER> String alias = createX509CertificateAlias(cert); try { synchronized (truststore) { truststore.setCertificateEntry(alias, cert); saveKeystore(TRUSTSTORE); multiCaster.notify(new KeystoreChangedEvent(CredentialManager.TRUSTSTORE)); } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to insert trusted certificate entry in the Truststore."; logger.error(exMessage, ex); throw (new CMException(exMessage)); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Create a Truststore alias for the trusted certificate as * * "trustedcert#"<CERT_SUBJECT_COMMON_NAME>"#"<CERT_ISSUER_COMMON_NAME>"#"<CERT_SERIAL_NUMBER> */ private static String createX509CertificateAlias(X509Certificate cert) { String ownerDN = cert.getSubjectX500Principal() .getName(X500Principal.RFC2253); CMX509Util util = new CMX509Util(); util.parseDN(ownerDN); String owner; String ownerCN = util.getCN(); // owner's common name String ownerOU = util.getOU(); String ownerO = util.getO(); if (!ownerCN.equals("none")){ // try owner's CN first owner = ownerCN; } // try owner's OU else if (!ownerOU.equals("none")){ owner = ownerOU; } else if (!ownerO.equals("none")){ // finally use owner's Organisation owner= ownerO; } else{ owner = "<Not Part of Certificate>"; } // Get the hexadecimal representation of the certificate's serial number String serialNumber = new BigInteger(1, cert.getSerialNumber() .toByteArray()).toString(16).toUpperCase(); String issuerDN = cert.getIssuerX500Principal() .getName(X500Principal.RFC2253); util.parseDN(issuerDN); String issuer; String issuerCN = util.getCN(); // issuer's common name String issuerOU = util.getOU(); String issuerO = util.getO(); if (!issuerCN.equals("none")){ // try issuer's CN first issuer = issuerCN; } // try issuer's OU else if (!issuerOU.equals("none")){ issuer = issuerOU; } else if (!issuerO.equals("none")){ // finally use issuer's Organisation issuer= issuerO; } else{ issuer = "<Not Part of Certificate>"; } String alias = "trustedcert#" + owner + "#" + issuer + "#" + serialNumber; return alias; } /** * Delete trusted certificate entry from the Truststore. */ public void deleteTrustedCertificate(String alias) throws CMException{ deleteEntry(TRUSTSTORE, alias); saveKeystore(TRUSTSTORE); multiCaster.notify(new KeystoreChangedEvent(CredentialManager.TRUSTSTORE)); } /** * Checks if the given entry is a key entry in the Keystore. */ public boolean isKeyEntry(String alias) throws CMException { try { synchronized (keystore) { return keystore.isKeyEntry(alias); } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to access the key entry in the Keystore."; logger.error(exMessage, ex); throw (new CMException(exMessage)); } } /** * Deletes an entry from a keystore. */ private void deleteEntry(String ksType, String alias) throws CMException { synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); try { if (ksType.equals(KEYSTORE)) { synchronized (keystore) { keystore.deleteEntry(alias); } // If this was key pair rather than password entry - remove the // associated URLs from the serviceURLsFile as well if (alias.startsWith("keypair#")) deleteServiceURLsForKeyPair(alias); } else if (ksType.equals(TRUSTSTORE)) { synchronized (truststore) { truststore.deleteEntry(alias); } } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to delete the entry with alias "+alias+"from the " + ksType + "."; logger.error(exMessage, ex); ex.printStackTrace(); throw (new CMException(exMessage)); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Check if a keystore contains an entry with the given alias. */ public boolean containsAlias(String ksType, String alias) throws CMException { synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); try { if (ksType.equals(KEYSTORE)) synchronized (keystore) { return keystore.containsAlias(alias); } else if (ksType.equals(TRUSTSTORE)) synchronized (truststore) { return truststore.containsAlias(alias); } else{ return false; } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to access the " + ksType + " to check if an alias exists."; logger.error(exMessage, ex); throw (new CMException(exMessage)); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Gets all the aliases from a keystore or null if there was some error * while accessing the keystore. */ public ArrayList<String> getAliases(String ksType) throws CMException { synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); try { if (ksType.equals(KEYSTORE)){ synchronized (keystore) { return Collections.list(keystore.aliases()); } } else if (ksType.equals(TRUSTSTORE)) { synchronized (truststore) { return Collections.list(truststore.aliases()); } } else{ return null; } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to access the " + ksType + " to get the aliases."; logger.error(exMessage, ex); ex.printStackTrace(); throw new CMException(exMessage); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Gets the creation date of an entry in the specified keystore. * * Note that not all keystores support 'creation date' property, but Bouncy * Castle 'UBER'-type keystores do. */ public Date getEntryCreationDate(String ksType, String alias) throws CMException{ synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); try { if (ksType.equals(KEYSTORE)){ synchronized (keystore) { return keystore.getCreationDate(alias); } } else if (ksType.equals(TRUSTSTORE)){ synchronized (truststore) { return truststore.getCreationDate(alias); } } else{ return null; } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to get the creation date for the entry from the " + ksType + "."; logger.error(exMessage); ex.printStackTrace(); throw new CMException(exMessage); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Check if Keystore/Truststore file already exists on disk. */ public boolean exists(String ksType) { if (ksType.equals(KEYSTORE)) return keystoreFile.exists(); else if (ksType.equals(TRUSTSTORE)) { return truststoreFile.exists(); } else return false; } /** * Save the Keystore back to the file it was originally loaded from. */ public void saveKeystore(String ksType) throws CMException { FileOutputStream fos = null; synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); try { if (ksType.equals(KEYSTORE)) { synchronized (keystore) { fos = new FileOutputStream(keystoreFile); keystore.store(fos, masterPassword.toCharArray()); } } else if (ksType.equals(TRUSTSTORE)) { synchronized (truststore) { fos = new FileOutputStream(truststoreFile); // Hard-coded trust store password truststore.store(fos, TRUSTSTORE_PASSWORD.toCharArray()); } } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to save the " + ksType + "."; ex.printStackTrace(); logger.error(exMessage, ex); throw (new CMException(exMessage)); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { // ignore } } // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Load PKCS12 keystore from the given file using the suppied password. */ public KeyStore loadPKCS12Keystore(File importFile, String pkcs12Password) throws CMException{ synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); // Load the PKCS #12 keystore from the file using BC provider KeyStore pkcs12; try { pkcs12 = KeyStore.getInstance("PKCS12", "BC"); pkcs12.load(new FileInputStream(importFile), pkcs12Password .toCharArray()); return pkcs12; } catch (Exception ex) { String exMessage = "Credential Manager: Failed to open PKCS12 keystore"; ex.printStackTrace(); logger.error(exMessage, ex); throw (new CMException(exMessage)); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } public void addObserver(Observer<KeystoreChangedEvent> observer) { multiCaster.addObserver(observer); } public List<Observer<KeystoreChangedEvent>> getObservers() { return multiCaster.getObservers(); } public void removeObserver(Observer<KeystoreChangedEvent> observer) { multiCaster.removeObserver(observer); } /** * Change the Keystore master password. Truststore is using a different * pre-set password. */ public void changeMasterPassword(String newPassword) throws CMException{ masterPassword = newPassword; saveKeystore(KEYSTORE); // We are using a different pre-set password for Truststore because // we need to initialise it earlier (for setting SSL system properties) // when we still do not know user's master password. //saveKeystore(TRUSTSTORE); } public static void initialiseSSL() throws CMException { loadTruststore(TRUSTSTORE_PASSWORD); } /** * Gets a Security Agent Manager instance. */ // public SecurityAgentManager getSecurityAgentManager() throws CMNotInitialisedException{ // // if (!isInitialised) { // throw new CMNotInitialisedException( // "Credential Manager not initialised."); // } // // return new SecurityAgentManager(keystore, serviceURLs, truststore); // } }
credential-manager/src/main/java/net/sf/taverna/t2/security/credentialmanager/CredentialManager.java
/******************************************************************************* * Copyright (C) 2007 The University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 ******************************************************************************/ package net.sf.taverna.t2.security.credentialmanager; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.math.BigInteger; import java.net.URLDecoder; import java.net.URLEncoder; import java.security.Key; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.PrivateKey; import java.security.Provider; import java.security.Security; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.TreeMap; import javax.crypto.spec.SecretKeySpec; import javax.security.auth.x500.X500Principal; import net.sf.taverna.t2.lang.observer.MultiCaster; import net.sf.taverna.t2.lang.observer.Observable; import net.sf.taverna.t2.lang.observer.Observer; import net.sf.taverna.t2.spi.SPIRegistry; import org.apache.log4j.Logger; /** * Provides a wrapper for the user's Keystore and Truststore and implements * methods for managing user's credentials (passwords, private key pairs and * proxies) and trusted services' public key certificates. * * @author Alex Nenadic */ public class CredentialManager implements Observable<KeystoreChangedEvent>{ private static final String T2TRUSTSTORE_FILE = "t2truststore.jks"; private static final String SERVICE_URLS_FILE = "t2serviceURLs.txt"; private static final String T2KEYSTORE_FILE = "t2keystore.ubr"; // Log4J Logger private static Logger logger = Logger.getLogger(CredentialManager.class); // Multicaster of KeystoreChangedEventS private MultiCaster<KeystoreChangedEvent> multiCaster = new MultiCaster<KeystoreChangedEvent>( this); // Security config directory private static File secConfigDirectory = CMUtil.getSecurityConfigurationDirectory(); // Keystore file. private static File keystoreFile = new File(secConfigDirectory,T2KEYSTORE_FILE); // Truststore file. private static File truststoreFile = new File(secConfigDirectory,T2TRUSTSTORE_FILE); // Service URLs file containing lists of service URLs associated with private key aliases. // The alias points to the key pair entry to be used for a particular service. private static File serviceURLsFile = new File(secConfigDirectory,SERVICE_URLS_FILE); // Master password the Keystore and Truststore are created/accessed with. private static String masterPassword; // Keystore containing user's passwords, private keys and public key certificate chains. private static KeyStore keystore; // Truststore containing trusted certificates of CA authorities and services. private static KeyStore truststore; // A map of service URLs associated with private key aliases, i.e. aliases // are keys in the hashmap and lists of URLs are hashmap values. private static HashMap<String,ArrayList<String>> serviceURLsForKeyPairs; // Constants denoting which of the two keystores we are currently // performing operations on. public static final String KEYSTORE = "Keystore"; public static final String TRUSTSTORE = "Truststore"; // Default password for Truststore - needed as the Truststore needs to be populated // sometimes before the Workbench starts up - e.g. in case of caGrid when trusted CAs // need to be inserted there at startup. private static final String TRUSTSTORE_PASSWORD = "raehiekooshe0eghiPhi"; // Credential Manager singleton private static CredentialManager INSTANCE; // Bouncy Castle provider private static Provider bcProvider; /** * Returns a CredentialManager singleton. */ public static CredentialManager getInstance() throws CMException { synchronized (CredentialManager.class) { if (INSTANCE == null) INSTANCE = new CredentialManager(); } return INSTANCE; } /** * Overrides the Objects clone method to prevent the singleton object to be * cloned. */ @Override public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } /** * Credential Manager constructor. The constructor is private * to suppress unauthorized calls to it. */ private CredentialManager() throws CMException { SPIRegistry<MasterPasswordProviderSPI> masterPasswordManager = new SPIRegistry<MasterPasswordProviderSPI>(MasterPasswordProviderSPI.class); TreeMap<Integer, MasterPasswordProviderSPI> sortedProviders = new TreeMap<Integer, MasterPasswordProviderSPI>(); for (MasterPasswordProviderSPI spi : masterPasswordManager.getInstances()) { int priority = spi.canProvidePassword(); if (priority >= 0){ sortedProviders.put(new Integer(priority), spi); } } if (!sortedProviders.isEmpty()){ // we have found at least one password provider while (!sortedProviders.isEmpty()){ MasterPasswordProviderSPI provider = sortedProviders.get(sortedProviders.lastKey()); String password = provider.getPassword(); if (password!= null){ masterPassword = password; break; } sortedProviders.remove(sortedProviders.lastKey()); } } else{ // We are in big trouble - we do not have the master password String exMessage = "Failed to obtain master password."; logger.error(exMessage); throw new CMException(exMessage); } // We do not want anyone to call Security.addProvider() and // Security.removeProvider() synchronized methods until we // execute this block to prevent someone interfering with // our adding and removing of BC security provider synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); // Get the new Bouncy Castle provider try { ClassLoader ourCL = getClass().getClassLoader(); Class<?> bcProvClass = ourCL.loadClass("org.bouncycastle.jce.provider.BouncyCastleProvider"); bcProvider = (Provider) bcProvClass.newInstance(); // Add our BC provider as a security provider // while doing the crypto operations Security.addProvider(bcProvider); logger.info("Credential Manager: Adding Bouncy Castle security provider version " + bcProvider.getVersion()); } catch (Exception ex) { // No sign of the provider String exMessage = "Failed to load the Bouncy Castle cryptographic provider"; ex.printStackTrace(); logger.error(ex); // Return the old BC providers and remove the one we have added restoreOldBCProviders(oldBCProviders); throw new CMException(exMessage); } init(masterPassword); // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } private static void restoreOldBCProviders(ArrayList<Provider> oldBCProviders) { Security.removeProvider("BC"); for (Provider prov : oldBCProviders){ Security.addProvider(prov); } } private static ArrayList<Provider> unregisterOldBCProviders() { ArrayList<Provider> oldBCProviders = new ArrayList<Provider>(); // Different versions of Bouncy Castle provider may be lurking around. // E.g. an old 1.25 version of Bouncy Castle provider // is added by caGrid package and others may be as well by // third party providers for (int i=0; i<Security.getProviders().length; i++){ if(Security.getProviders()[i].getName().equals("BC")){ oldBCProviders.add(Security.getProviders()[i]); } } // Remove (hopefully) all registered BC providers Security.removeProvider("BC"); return oldBCProviders; } /** * Initialises Credential Manager - loads the Keystore, Truststore and serviceURLsFile. */ public void init(String mPassword) throws CMException { // Load the Keystore try { keystore = loadKeystore(mPassword); logger.info("Credential Manager: Loaded the Keystore."); } catch (CMException cme) { logger.error(cme.getMessage(), cme); throw cme; } // Load service URLs associated with private key aliases from a file try { loadServiceURLsForKeyPairs(); logger.info("Credential Manager: Loaded the Service URLs for private key pairs."); } catch (CMException cme) { logger.error(cme.getMessage(), cme); throw cme; } // Load the Truststore try { truststore = loadTruststore(TRUSTSTORE_PASSWORD); logger.info("Credential Manager: Loaded the Truststore."); } catch (CMException cme) { logger.error(cme.getMessage(), cme); throw cme; } } /** * Loads Taverna's Bouncy Castle "UBER"-type keystore from a file on the disk and * returns it. */ public static KeyStore loadKeystore(String masterPassword) throws CMException { KeyStore keystore = null; try { keystore = KeyStore.getInstance("UBER", "BC"); } catch (Exception ex) { // The requested keystore type is not available from the provider String exMessage = "Failed to instantiate a Bouncy Castle 'UBER'-type keystore."; logger.error(exMessage, ex); ex.printStackTrace(); throw new CMException(exMessage); } if (keystoreFile.exists()) { // If the file exists, open it // Try to load the keystore as Bouncy Castle "UBER"-type // keystore FileInputStream fis = null; try { // Get the file fis = new FileInputStream(keystoreFile); // Load the keystore from the file keystore.load(fis, masterPassword.toCharArray()); } catch (Exception ex) { String exMessage = "Failed to load the keystore. Possible reason: incorrect password or corrupted file."; logger.error(exMessage, ex); ex.printStackTrace(); throw new CMException(exMessage); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { // ignore } } } } else { // Otherwise create a new empty keystore FileOutputStream fos = null; try { keystore.load(null, null); // Immediately save the new (empty) keystore to the file fos = new FileOutputStream(keystoreFile); keystore.store(fos, masterPassword.toCharArray()); } catch (Exception ex) { String exMessage = "Failed to generate a new empty keystore."; logger.error(exMessage, ex); ex.printStackTrace(); throw new CMException(exMessage); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { // ignore } } } } return keystore; } /** * Load Taverna's truststore from a file on a disk. If the truststore * does not already exist, a new empty one will be created and contents * of Java's truststore located in <JAVA_HOME>/lib/security/cacerts will * be copied over to this truststore. */ private static KeyStore loadTruststore(String masterPassword) throws CMException{ KeyStore truststore = null; // Try to create the Taverna's Truststore - has to be "JKS"-type keystore // because we use it to set the system property "javax.net.ssl.trustStore" try { truststore = KeyStore.getInstance("JKS"); } catch (Exception ex) { // The requested keystore type is not available from the provider String exMessage = "Failed to instantiate a 'JKS'-type keystore."; logger.error(exMessage, ex); ex.printStackTrace(); throw new CMException(exMessage); } if (truststoreFile.exists()) { // If the Truststore file already exists, open it and load the Truststore FileInputStream fis = null; try { // Get the file fis = new FileInputStream(truststoreFile); // Load the Truststore from the file truststore.load(fis, masterPassword.toCharArray()); } catch (Exception ex) { String exMessage = "Failed to load the truststore. Possible reason: incorrect password or corrupted file."; logger.error(exMessage, ex); ex.printStackTrace(); throw new CMException(exMessage); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { // ignore } } } } else { // Otherwise create a new empty truststore and load it with certs from Java's truststore File javaTruststoreFile = new File(System.getProperty("java.home") + "/lib/security/cacerts"); KeyStore javaTruststore = null; // Java's truststore is of type "JKS" - try to load it try { javaTruststore = KeyStore.getInstance("JKS"); } catch (Exception ex) { // The requested keystore type is not available from the provider String exMessage = "Failed to instantiate a 'JKS'-type keystore."; logger.error(exMessage, ex); ex.printStackTrace(); throw new CMException(exMessage); } FileInputStream fis = null; boolean loadedJavaTruststore = false; try { // Get the file fis = new FileInputStream(javaTruststoreFile); // Load the Java keystore from the file javaTruststore.load(fis, "changeit".toCharArray()); // try with the default Java truststore password first loadedJavaTruststore = true; } catch(IOException ioex){ // If there is an I/O or format problem with the keystore data, // or if the given password was incorrect logger.error("Failed to load the Java truststore to copy over certificates using default password 'changeit'. Trying with user-provided password."); // Close the input stream and reopen it to rewind it (resetting it did not work for some reason) if (fis != null) { try { fis.close(); fis = new FileInputStream(javaTruststoreFile); } catch (IOException e) { // ignore } } // Hopefully it was the password problem - ask user to provide // their password for the Java truststore GetMasterPasswordDialog getPasswordDialog = new GetMasterPasswordDialog("Credential Manager needs to copy certificates from Java truststore. Please enter your password."); getPasswordDialog.setLocationRelativeTo(null); getPasswordDialog.setVisible(true); String javaTruststorePassword = getPasswordDialog.getPassword(); if (javaTruststorePassword == null){ // user cancelled - do not try to load Java truststore loadedJavaTruststore = false; } else{ try { javaTruststore.load(fis, javaTruststorePassword.toCharArray()); loadedJavaTruststore = true; } catch (Exception ex) { String exMessage = "Failed to load the Java truststore to copy over certificates using user-provided password. Creating a new empty truststore for Taverna."; logger.error(exMessage, ex); ex.printStackTrace(); loadedJavaTruststore = false; } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { // ignore } } } } } catch (Exception ex) { String exMessage = "Failed to load the Java truststore to copy over certificates. Creating a new empty truststore for Taverna."; logger.error(exMessage, ex); ex.printStackTrace(); loadedJavaTruststore = false; } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { // ignore } } } FileOutputStream fos = null; // Create a new empty truststore for Taverna try { truststore.load(null, null); if (loadedJavaTruststore){ // Copy certificates into Taverna's truststore from Java truststore Enumeration<String> aliases = javaTruststore.aliases(); while (aliases.hasMoreElements()){ String alias = aliases.nextElement(); Certificate certificate = javaTruststore.getCertificate(alias); if (certificate instanceof X509Certificate){ String trustedCertAlias = createX509CertificateAlias((X509Certificate)certificate); truststore.setCertificateEntry(trustedCertAlias, certificate); } } } // Immediately save the new truststore to the file fos = new FileOutputStream(truststoreFile); truststore.store(fos, masterPassword.toCharArray()); } catch (Exception ex) { String exMessage = "Failed to generate a new truststore."; logger.error(exMessage, ex); ex.printStackTrace(); throw new CMException(exMessage); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { // ignore } } } } // Set the system property "javax.net.ssl.Truststore" to use Taverna's truststore System.setProperty("javax.net.ssl.trustStore", truststoreFile.getAbsolutePath()); System.setProperty("javax.net.ssl.trustStorePassword", masterPassword); // Taverna distro for MAC contains info.plist file with some Java system properties set to // use the Keychain which clashes with what we are setting here so wee need to clear them System.clearProperty("javax.net.ssl.trustStoreType"); System.clearProperty("javax.net.ssl.trustStoreProvider"); return truststore; } /** * Load lists of service URLs associated with private key aliases from a * file and populate the serviceURLs hashmap. */ public void loadServiceURLsForKeyPairs() throws CMException { serviceURLsForKeyPairs = new HashMap<String, ArrayList<String>>(); synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); try { // Create an empty map with aliases as keys for (Enumeration<String> e = keystore.aliases(); e .hasMoreElements();) { String element = (String) e.nextElement(); // We want only key pair entry aliases (and not password entry aliases) if (element.startsWith("keypair#")) serviceURLsForKeyPairs.put(element, new ArrayList<String>()); } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to get private key aliases when loading service URLs."; logger.error(exMessage, ex); ex.printStackTrace(); throw (new CMException(exMessage)); } // If Service URLs file exists - load the URL lists from the file if (serviceURLsFile.exists()) { BufferedReader serviceURLsReader = null; try { serviceURLsReader = new BufferedReader(new FileReader(serviceURLsFile)); String line = serviceURLsReader.readLine(); while (line != null) { // Line consists of an URL-encoded URL and alias // separated by a blank character, // i.e. line=<ENCODED_URL>" "<ALIAS> // One alias can have more than one URL associated with it // (i.e. more // than one line in the file can exist for the same alias). String alias = line.substring(line.indexOf(' ') + 1); String url = line.substring(0, line.indexOf(' ')); // URLs were encoded before storing them in a file url = URLDecoder.decode(url, "UTF-8"); ArrayList<String> urlsList = (ArrayList<String>) serviceURLsForKeyPairs .get(alias); // get URL list for the current alias (it can be empty) if (urlsList == null) { urlsList = new ArrayList<String>(); } urlsList.add(url); // add the new URL to the list of URLs for this alias serviceURLsForKeyPairs.put(alias, urlsList); // put the updated list back to the map line = serviceURLsReader.readLine(); } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to read the service URLs file."; logger.error(exMessage, ex); ex.printStackTrace(); throw (new CMException(exMessage)); } finally { if (serviceURLsReader != null) { try { serviceURLsReader.close(); } catch (IOException e) { // ignore } } // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } } /** * Add the service URLs list associated with a private key entry to the serviceURLs * hashmap and save/update the service URLs file. */ public void saveServiceURLsForKeyPair(String alias, ArrayList<String> serviceURLsList) throws CMException { // Add service url list to the serviceURLs hashmap (overwrites previous // value, if any) serviceURLsForKeyPairs.put(alias, serviceURLsList); // Save the updated hashmap to the file saveServiceURLsForKeyPairs(); } /** * Get the service URLs list associated with a private key entry. */ public ArrayList<String> getServiceURLsForKeyPair(String alias){ return serviceURLsForKeyPairs.get(alias); } /** * Get a map of service URL lists for each of the private key entries in the Keystore. */ public HashMap<String, ArrayList<String>> getServiceURLsforKeyPairs() { return serviceURLsForKeyPairs; } /** * Delete the service URLs list associated with a private key entry. */ public void deleteServiceURLsForKeyPair(String alias) throws CMException { // Remove service URL list from the serviceURLs hashmap serviceURLsForKeyPairs.remove(alias); // Save the updated serviceURLs hashmap to the file saveServiceURLsForKeyPairs(); } /** * Saves the content of serviceURLs map to a file. Overwrites previous * content of the file. */ public void saveServiceURLsForKeyPairs() throws CMException { synchronized (serviceURLsFile) { // If file already exists if (serviceURLsFile.exists()) { // Delete the previous contents of the file serviceURLsFile.delete(); } // Create a new empty file try { serviceURLsFile.createNewFile(); } catch (IOException ex) { String exMessage = "Credential Manager: Failed to create a new service URLs' file."; logger.error(exMessage, ex); ex.printStackTrace(); throw (new CMException(exMessage)); } BufferedWriter serviceURLsWriter = null; try { // Open the file for writing serviceURLsWriter = new BufferedWriter((new FileWriter( serviceURLsFile, false))); // Write the serviceURLs hashmap to the file for (String alias : serviceURLsForKeyPairs.keySet()) { // for all aliases // For all urls associated with the alias ArrayList<String> serviceURLsForKeyPair = (ArrayList<String>) serviceURLsForKeyPairs .get(alias); for (String serviceURL : serviceURLsForKeyPair) { // Each line of the file contains an encoded service URL // with its associated alias appended and separated from // the URL by a blank character ' ', // i.e. line=<ENCODED_URL>" "<ALIAS> // Service URLs are encoded before saving to make sure // they do not contain blank characters // that are used as delimiters. String encodedURL = URLEncoder.encode((String) serviceURL, "UTF-8"); StringBuffer line = new StringBuffer(encodedURL + " " + alias); serviceURLsWriter.append(line); serviceURLsWriter.newLine(); } } } catch (FileNotFoundException ex) { // Should not happen } catch (IOException ex) { String exMessage = "Credential Manager: Failed to save the service URLs to the file."; logger.error(exMessage, ex); ex.printStackTrace(); throw (new CMException(exMessage)); } finally { if (serviceURLsWriter != null) { try { serviceURLsWriter.close(); } catch (IOException e) { // ignore } } } } } /** * Get a username and password pair for the given service, or null if it * does not exit. */ public String getUsernameAndPasswordForService(String serviceURL) throws CMException { synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); // Alias for the username and password entry String alias = "password#" + serviceURL; SecretKeySpec passwordKey = null; try { synchronized (keystore) { passwordKey = (((SecretKeySpec) keystore .getKey(alias, null))); } if (passwordKey != null){ String unpasspair = new String(passwordKey.getEncoded()); // the decoded key contains string <USERNAME>" "<PASSWORD> return unpasspair; } else{ return null; } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to get the username and password pair for service " + serviceURL + " from the Keystore."; ex.printStackTrace(); logger.error(exMessage, ex); throw (new CMException(exMessage)); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Get service URLs associated with all username/password pairs currently in the Keystore. */ public ArrayList<String> getServiceURLsforUsernameAndPasswords() throws CMException{ ArrayList<String> serviceURLs = new ArrayList<String>(); ArrayList<String> aliases; try{ aliases = getAliases(KEYSTORE); } catch(CMException cme){ String exMessage = "Credential Manager: Failed to access the Keystore to get the service URLs for passwords."; logger.error(exMessage); throw new CMException(exMessage); } for (String alias: aliases){ if (alias.startsWith("password#")){ serviceURLs.add(alias.substring(alias.indexOf('#')+1)); } } return serviceURLs; } /** * Insert a new username and password pair in the keystore for the given service URL. * * Effectively, this method inserts a new secret key entry in the keystore, where * key contains <USERNAME>" "<PASSWORD> string, i.e. password is prepended with the * username and separated by a blank character (which hopefully will not appear in * the username). * * Username and password string is saved in the Keystore as byte array using * SecretKeySpec (which constructs a secret key from the given byte array but * does not check if the given bytes indeed specify a secret key of the * specified algorithm). * * An alias used to identify the username and password entry is constructed as * "password#"<SERVICE_URL> using the service URL * this username/password pair is to be used for. */ public void saveUsernameAndPasswordForService(String username, String password, String serviceURL) throws CMException { synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); // Alias for the username and password entry String alias = "password#" + serviceURL; /* * Password (together with its related username) is wrapped as a * SecretKeySpec that implements SecretKey and constructs a secret * key from the given password as a byte array. The reason for this * is that we can only save instances of Key objects in the * Keystore, and SecretKeySpec class is useful for raw secret keys * (i.e. username and passwords concats) that can be represented as * a byte array and have no key or algorithm parameters associated * with them, e.g., DES or Triple DES. That is why we create it with * the name "DUMMY" for algorithm name, as this is not checked for * anyway. * * Blank character is a good separator as it (most probably) will * not appear in the username. */ String keyToSave = username + " " + password; SecretKeySpec passwordKey = new SecretKeySpec(keyToSave.getBytes(), "DUMMY"); try { synchronized (keystore) { keystore.setKeyEntry(alias, passwordKey, null, null); saveKeystore(KEYSTORE); multiCaster.notify(new KeystoreChangedEvent(CredentialManager.KEYSTORE)); } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to insert username and password pair for service "+ serviceURL+ " in the Keystore."; logger.error(exMessage, ex); ex.printStackTrace(); throw (new CMException(exMessage)); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Delete username and password pair for the given service URL from the Keystore. */ public void deleteUsernameAndPasswordForService(String serviceURL) throws CMException{ deleteEntry(KEYSTORE, "password#"+serviceURL); saveKeystore(KEYSTORE); multiCaster.notify(new KeystoreChangedEvent(CredentialManager.KEYSTORE)); } /** * Get key pair entry's private key for the given service URL. */ public PrivateKey getPrivateKey(String serviceURL){ //TODO return null; } /** * Get key pair entry's public key certificate chain for the given service URL. */ public Certificate[] getPublicKeyCertificateChain(String serviceURL){ //TODO return null; } /** * Insert a new key entry containing private key and public key certificate * (chain) in the Keystore and save the list of service URLs this key pair * is associated to. * * An alias used to identify the keypair entry is constructed as: * "keypair#"<CERT_SUBJECT_COMMON_NAME>"#"<CERT_ISSUER_COMMON_NAME>"#"<CERT_SERIAL_NUMBER> */ public void saveKeyPair(Key privateKey, Certificate[] certs, ArrayList<String> serviceURLs) throws CMException { synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); // Create an alias for the new key pair entry in the Keystore // as "keypair#"<CERT_SUBJECT_COMMON_NAME>"#"<CERT_ISSUER_COMMON_NAME>"#"<CERT_SERIAL_NUMBER> String ownerDN = ((X509Certificate) certs[0]).getSubjectX500Principal() .getName(X500Principal.RFC2253); CMX509Util util = new CMX509Util(); util.parseDN(ownerDN); String ownerCN = util.getCN(); // owner's common name // Get the hexadecimal representation of the certificate's serial number String serialNumber = new BigInteger(1, ((X509Certificate) certs[0]) .getSerialNumber().toByteArray()).toString(16) .toUpperCase(); String issuerDN = ((X509Certificate) certs[0]).getIssuerX500Principal() .getName(X500Principal.RFC2253); util.parseDN(issuerDN); String issuerCN = util.getCN(); // issuer's common name String alias = "keypair#" + ownerCN + "#" + issuerCN + "#" + serialNumber; try { synchronized (keystore) { keystore.setKeyEntry(alias, privateKey, null, certs); saveKeystore(KEYSTORE); // Add service url list to the serviceURLs hashmap (overwrites previous // value, if any) if (serviceURLs == null) serviceURLs = new ArrayList<String>(); serviceURLsForKeyPairs.put(alias, serviceURLs); // Save the updated hashmap to the file saveServiceURLsForKeyPairs(); multiCaster.notify(new KeystoreChangedEvent(CredentialManager.KEYSTORE)); } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to insert the key pair entry in the Keystore."; logger.error(exMessage, ex); ex.printStackTrace(); throw (new CMException(exMessage)); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Check if the Keystore contains the key pair entry. */ public boolean containsKeyPair(Key privateKey, Certificate[] certs) throws CMException { synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); // Create an alias for the new key pair entry in the Keystore // as "keypair#"<CERT_SUBJECT_COMMON_NAME>"#"<CERT_ISSUER_COMMON_NAME>"#"<CERT_SERIAL_NUMBER> String ownerDN = ((X509Certificate) certs[0]).getSubjectX500Principal() .getName(X500Principal.RFC2253); CMX509Util util = new CMX509Util(); util.parseDN(ownerDN); String ownerCN = util.getCN(); // owner's common name // Get the hexadecimal representation of the certificate's serial number String serialNumber = new BigInteger(1, ((X509Certificate) certs[0]) .getSerialNumber().toByteArray()).toString(16) .toUpperCase(); String issuerDN = ((X509Certificate) certs[0]).getIssuerX500Principal() .getName(X500Principal.RFC2253); util.parseDN(issuerDN); String issuerCN = util.getCN(); // issuer's common name String alias = "keypair#" + ownerCN + "#" + issuerCN + "#" + serialNumber; synchronized (keystore) { try { return keystore.containsAlias(alias); } catch (KeyStoreException ex) { String exMessage = "Credential Manager: Failed to get aliases from the Keystore ti check if it contains the given key pair."; logger.error(exMessage, ex); ex.printStackTrace(); throw (new CMException(exMessage)); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } } /** * Delete key pair entry from the Keystore. */ public void deleteKeyPair(String alias) throws CMException{ // TODO: We are passing alias for now but we want to be passing // the private key and its public key certificate // // Create an alias for the new key pair entry in the Keystore // // as "keypair#"<CERT_SUBJECT_COMMON_NAME>"#"<CERT_ISSUER_COMMON_NAME>"#"<CERT_SERIAL_NUMBER> // String ownerDN = ((X509Certificate) certs[0]).getSubjectX500Principal() // .getName(X500Principal.RFC2253); // CMX509Util util = new CMX509Util(); // util.parseDN(ownerDN); // String ownerCN = util.getCN(); // owner's common name // // // Get the hexadecimal representation of the certificate's serial number // String serialNumber = new BigInteger(1, ((X509Certificate) certs[0]) // .getSerialNumber().toByteArray()).toString(16) // .toUpperCase(); // // String issuerDN = ((X509Certificate) certs[0]).getIssuerX500Principal() // .getName(X500Principal.RFC2253); // util.parseDN(issuerDN); // String issuerCN = util.getCN(); // issuer's common name // // String alias = "keypair#" + ownerCN + "#" + issuerCN + "#" + serialNumber; deleteEntry(KEYSTORE, alias); saveKeystore(KEYSTORE); deleteServiceURLsForKeyPair(alias); multiCaster.notify(new KeystoreChangedEvent(CredentialManager.KEYSTORE)); } /** * Exports a key entry containing private key and public key certificate * (chain) from the Keystore to a PKCS #12 file. */ public void exportKeyPair(String alias, File exportFile, String pkcs12Password) throws CMException { FileOutputStream fos = null; synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); // Export the key pair try { // Get the private key for the alias PrivateKey privateKey = (PrivateKey) keystore.getKey(alias, null); // Get the related public key's certificate chain Certificate[] certChain = getCertificateChain(alias); // Create a new PKCS #12 keystore KeyStore newPkcs12 = KeyStore.getInstance("PKCS12", "BC"); newPkcs12.load(null, null); // Place the private key and certificate chain into the PKCS #12 // keystore. // Construct a new alias as "<SUBJECT_COMMON_NAME>'s <ISSUER_ORGANISATION> ID" String sDN = ((X509Certificate) certChain[0]) .getSubjectX500Principal().getName(X500Principal.RFC2253); CMX509Util util = new CMX509Util(); util.parseDN(sDN); String sCN = util.getCN(); String iDN = ((X509Certificate) certChain[0]) .getIssuerX500Principal().getName(X500Principal.RFC2253); util.parseDN(iDN); String iCN = util.getCN(); String pkcs12Alias = sCN + "'s " + iCN + " ID"; newPkcs12.setKeyEntry(pkcs12Alias, privateKey, new char[0], certChain); // Store the new PKCS #12 keystore on the disk fos = new FileOutputStream(exportFile); newPkcs12.store(fos, pkcs12Password.toCharArray()); fos.close(); } catch (Exception ex) { String exMessage = "Credential Manager: Failed to export the key pair from the Keystore."; logger.error(exMessage, ex); throw (new CMException(exMessage)); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { // ignore } } // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Returns caGrid proxy's private key entry for the given Authentication and Dorian services. * * Since caGrid v1.3, caGrid proxies are just normal key pairs where the * validity of the key is 12 hours by default. * Before v1.3 these were actual proxies. Still we differentiate between * these and normal 'key pair' entries and form their keystore aliases as: * * "cagridproxy#"<AuthNServiceURL>" "<DorianServiceURL> * * This basically means that AuthN Service URL and Dorian Service URL define * a single caGrid proxy entry in the keystore. * */ public synchronized PrivateKey getCaGridProxyPrivateKey(String authNServiceURL, String dorianServiceURL) throws CMException{ synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); String proxyAlias = "cagridproxy#" + authNServiceURL + " " + dorianServiceURL; PrivateKey privateKey = null; try { privateKey = (PrivateKey) keystore.getKey(proxyAlias, null); } catch (Exception ex) { String exMessage = "Credential Manager: Failed to get the private key of the proxy key pair entry"; logger.error(exMessage); ex.printStackTrace(); throw new CMException(exMessage); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } return privateKey; } } /** * Returns caGrid proxy's cerificate chain for the given Authentication and Dorian services. * The alias used to get the chain is constructed as: * * "cagridproxy#"<AuthNServiceURL>" "<DorianServiceURL> */ public synchronized Certificate[] getCaGridProxyCertificateChain(String authNServiceURL, String dorianServiceURL) throws CMException{ synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); String proxyAlias = "cagridproxy#" + authNServiceURL + " " + dorianServiceURL; // Get the proxy key pair entry's certificate chain Certificate[] certChain = null; try { certChain = getCertificateChain(proxyAlias); } catch (Exception ex) { String exMessage = "Credential Manager: Failed to get the certificate chain for the proxy entry"; logger.error(exMessage); ex.printStackTrace(); throw new CMException(exMessage); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } return certChain; } } /** * Insert a proxy key entry in the Keystore with an alias constructed as: * * "cagridproxy#"<AuthNServiceURL>" "<DorianServiceURL> */ public synchronized void saveCaGridProxy(PrivateKey privateKey, X509Certificate[] x509CertChain, String authNServiceURL, String dorianServiceURL) throws CMException { synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); String proxyAlias = "cagridproxy#" + authNServiceURL + " " + dorianServiceURL; try { synchronized (keystore) { keystore.setKeyEntry(proxyAlias, privateKey, null, x509CertChain); saveKeystore(KEYSTORE); multiCaster.notify(new KeystoreChangedEvent(CredentialManager.KEYSTORE)); } } catch (KeyStoreException ex) { String exMessage = "Credential Manager: Failed to insert the proxy key pair in the keystore."; logger.error(exMessage); ex.printStackTrace(); throw (new CMException(exMessage)); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Delete caGrid proxy entry from the Keystore. */ public void deleteCaGridProxy(String alias) throws CMException{ deleteEntry(KEYSTORE, alias); saveKeystore(KEYSTORE); multiCaster.notify(new KeystoreChangedEvent(CredentialManager.KEYSTORE)); } /** * Get certificate entry from the Keystore or Truststore. * If the given alias name identifies a trusted certificate entry, the * certificate associated with that entry is returned from the Truststore. * If the given alias name identifies a key pair entry, the first element of * the certificate chain of that entry is returned from the Keystore. */ public Certificate getCertificate(String ksType, String alias) throws CMException { synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); try { if (ksType.equals(KEYSTORE)) { synchronized (keystore) { return keystore.getCertificate(alias); } } else if (ksType.equals(TRUSTSTORE)) { synchronized (truststore) { return truststore.getCertificate(alias); } } else{ return null; } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to fetch certificate from the " + ksType + "."; logger.error(exMessage, ex); throw (new CMException(exMessage)); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Gets certificate chain for the key pair entry from the Keystore. This * method works for Keystore only as Truststore does not contain key pair * entries, but trusted certificate entries only. */ public Certificate[] getCertificateChain(String alias) throws CMException{ synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); try { synchronized (keystore) { return keystore.getCertificateChain(alias); } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to fetch certificate chain for the keypair from the Keystore"; logger.error(exMessage, ex); throw (new CMException(exMessage)); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Insert a trusted certificate entry in the Truststore with an * alias constructed as: * * "trustedcert#<CERT_SUBJECT_COMMON_NAME>"#"<CERT_ISSUER_COMMON_NAME>"#"<CERT_SERIAL_NUMBER> */ public void saveTrustedCertificate(X509Certificate cert) throws CMException { synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); // Create an alias for the new trusted certificate entry in the Truststore // as "trustedcert#"<CERT_SUBJECT_COMMON_NAME>"#"<CERT_ISSUER_COMMON_NAME>"#"<CERT_SERIAL_NUMBER> String alias = createX509CertificateAlias(cert); try { synchronized (truststore) { truststore.setCertificateEntry(alias, cert); saveKeystore(TRUSTSTORE); multiCaster.notify(new KeystoreChangedEvent(CredentialManager.TRUSTSTORE)); } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to insert trusted certificate entry in the Truststore."; logger.error(exMessage, ex); throw (new CMException(exMessage)); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Create a Truststore alias for the trusted certificate as * * "trustedcert#"<CERT_SUBJECT_COMMON_NAME>"#"<CERT_ISSUER_COMMON_NAME>"#"<CERT_SERIAL_NUMBER> */ private static String createX509CertificateAlias(X509Certificate cert) { String ownerDN = cert.getSubjectX500Principal() .getName(X500Principal.RFC2253); CMX509Util util = new CMX509Util(); util.parseDN(ownerDN); String owner; String ownerCN = util.getCN(); // owner's common name String ownerOU = util.getOU(); String ownerO = util.getO(); if (!ownerCN.equals("none")){ // try owner's CN first owner = ownerCN; } // try owner's OU else if (!ownerOU.equals("none")){ owner = ownerOU; } else if (!ownerO.equals("none")){ // finally use owner's Organisation owner= ownerO; } else{ owner = "<Not Part of Certificate>"; } // Get the hexadecimal representation of the certificate's serial number String serialNumber = new BigInteger(1, cert.getSerialNumber() .toByteArray()).toString(16).toUpperCase(); String issuerDN = cert.getIssuerX500Principal() .getName(X500Principal.RFC2253); util.parseDN(issuerDN); String issuer; String issuerCN = util.getCN(); // issuer's common name String issuerOU = util.getOU(); String issuerO = util.getO(); if (!issuerCN.equals("none")){ // try issuer's CN first issuer = issuerCN; } // try issuer's OU else if (!issuerOU.equals("none")){ issuer = issuerOU; } else if (!issuerO.equals("none")){ // finally use issuer's Organisation issuer= issuerO; } else{ issuer = "<Not Part of Certificate>"; } String alias = "trustedcert#" + owner + "#" + issuer + "#" + serialNumber; return alias; } /** * Delete trusted certificate entry from the Truststore. */ public void deleteTrustedCertificate(String alias) throws CMException{ deleteEntry(TRUSTSTORE, alias); saveKeystore(TRUSTSTORE); multiCaster.notify(new KeystoreChangedEvent(CredentialManager.TRUSTSTORE)); } /** * Checks if the given entry is a key entry in the Keystore. */ public boolean isKeyEntry(String alias) throws CMException { try { synchronized (keystore) { return keystore.isKeyEntry(alias); } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to access the key entry in the Keystore."; logger.error(exMessage, ex); throw (new CMException(exMessage)); } } /** * Deletes an entry from a keystore. */ private void deleteEntry(String ksType, String alias) throws CMException { synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); try { if (ksType.equals(KEYSTORE)) { synchronized (keystore) { keystore.deleteEntry(alias); } // If this was key pair rather than password entry - remove the // associated URLs from the serviceURLsFile as well if (alias.startsWith("keypair#")) deleteServiceURLsForKeyPair(alias); } else if (ksType.equals(TRUSTSTORE)) { synchronized (truststore) { truststore.deleteEntry(alias); } } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to delete the entry with alias "+alias+"from the " + ksType + "."; logger.error(exMessage, ex); ex.printStackTrace(); throw (new CMException(exMessage)); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Check if a keystore contains an entry with the given alias. */ public boolean containsAlias(String ksType, String alias) throws CMException { synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); try { if (ksType.equals(KEYSTORE)) synchronized (keystore) { return keystore.containsAlias(alias); } else if (ksType.equals(TRUSTSTORE)) synchronized (truststore) { return truststore.containsAlias(alias); } else{ return false; } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to access the " + ksType + " to check if an alias exists."; logger.error(exMessage, ex); throw (new CMException(exMessage)); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Gets all the aliases from a keystore or null if there was some error * while accessing the keystore. */ public ArrayList<String> getAliases(String ksType) throws CMException { synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); try { if (ksType.equals(KEYSTORE)){ synchronized (keystore) { return Collections.list(keystore.aliases()); } } else if (ksType.equals(TRUSTSTORE)) { synchronized (truststore) { return Collections.list(truststore.aliases()); } } else{ return null; } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to access the " + ksType + " to get the aliases."; logger.error(exMessage, ex); ex.printStackTrace(); throw new CMException(exMessage); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Gets the creation date of an entry in the specified keystore. * * Note that not all keystores support 'creation date' property, but Bouncy * Castle 'UBER'-type keystores do. */ public Date getEntryCreationDate(String ksType, String alias) throws CMException{ synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); try { if (ksType.equals(KEYSTORE)){ synchronized (keystore) { return keystore.getCreationDate(alias); } } else if (ksType.equals(TRUSTSTORE)){ synchronized (truststore) { return truststore.getCreationDate(alias); } } else{ return null; } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to get the creation date for the entry from the " + ksType + "."; logger.error(exMessage); ex.printStackTrace(); throw new CMException(exMessage); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Check if Keystore/Truststore file already exists on disk. */ public boolean exists(String ksType) { if (ksType.equals(KEYSTORE)) return keystoreFile.exists(); else if (ksType.equals(TRUSTSTORE)) { return truststoreFile.exists(); } else return false; } /** * Save the Keystore back to the file it was originally loaded from. */ public void saveKeystore(String ksType) throws CMException { FileOutputStream fos = null; synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); try { if (ksType.equals(KEYSTORE)) { synchronized (keystore) { fos = new FileOutputStream(keystoreFile); keystore.store(fos, masterPassword.toCharArray()); } } else if (ksType.equals(TRUSTSTORE)) { synchronized (truststore) { fos = new FileOutputStream(truststoreFile); // Hard-coded trust store password truststore.store(fos, TRUSTSTORE_PASSWORD.toCharArray()); } } } catch (Exception ex) { String exMessage = "Credential Manager: Failed to save the " + ksType + "."; ex.printStackTrace(); logger.error(exMessage, ex); throw (new CMException(exMessage)); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { // ignore } } // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } /** * Load PKCS12 keystore from the given file using the suppied password. */ public KeyStore loadPKCS12Keystore(File importFile, String pkcs12Password) throws CMException{ synchronized (Security.class) { ArrayList<Provider> oldBCProviders = unregisterOldBCProviders(); Security.addProvider(bcProvider); // Load the PKCS #12 keystore from the file using BC provider KeyStore pkcs12; try { pkcs12 = KeyStore.getInstance("PKCS12", "BC"); pkcs12.load(new FileInputStream(importFile), pkcs12Password .toCharArray()); return pkcs12; } catch (Exception ex) { String exMessage = "Credential Manager: Failed to open PKCS12 keystore"; ex.printStackTrace(); logger.error(exMessage, ex); throw (new CMException(exMessage)); } finally{ // Add the old BC providers back and remove the one we have added restoreOldBCProviders(oldBCProviders); } } } public void addObserver(Observer<KeystoreChangedEvent> observer) { multiCaster.addObserver(observer); } public List<Observer<KeystoreChangedEvent>> getObservers() { return multiCaster.getObservers(); } public void removeObserver(Observer<KeystoreChangedEvent> observer) { multiCaster.removeObserver(observer); } /** * Change the Keystore master password. Truststore is using a different * pre-set password. */ public void changeMasterPassword(String newPassword) throws CMException{ masterPassword = newPassword; saveKeystore(KEYSTORE); // We are using a different pre-set password for Truststore because // we need to initialise it earlier (for setting SSL system properties) // when we still do not know user's master password. //saveKeystore(TRUSTSTORE); } public static void initialiseSSL() throws CMException { loadTruststore(TRUSTSTORE_PASSWORD); } /** * Gets a Security Agent Manager instance. */ // public SecurityAgentManager getSecurityAgentManager() throws CMNotInitialisedException{ // // if (!isInitialised) { // throw new CMNotInitialisedException( // "Credential Manager not initialised."); // } // // return new SecurityAgentManager(keystore, serviceURLs, truststore); // } }
corrected a typo in a comment git-svn-id: 43cdacd7b689315367422a18859344a18d686e0c@8606 bf327186-88b3-11dd-a302-d386e5130c1c
credential-manager/src/main/java/net/sf/taverna/t2/security/credentialmanager/CredentialManager.java
corrected a typo in a comment
<ide><path>redential-manager/src/main/java/net/sf/taverna/t2/security/credentialmanager/CredentialManager.java <ide> System.setProperty("javax.net.ssl.trustStore", truststoreFile.getAbsolutePath()); <ide> System.setProperty("javax.net.ssl.trustStorePassword", masterPassword); <ide> // Taverna distro for MAC contains info.plist file with some Java system properties set to <del> // use the Keychain which clashes with what we are setting here so wee need to clear them <add> // use the Keychain which clashes with what we are setting here so we need to clear them <ide> System.clearProperty("javax.net.ssl.trustStoreType"); <ide> System.clearProperty("javax.net.ssl.trustStoreProvider"); <ide> return truststore;
Java
agpl-3.0
c97b6b7a392203764fe5e57f19dedfcdda64c4a0
0
Peergos/Peergos,Peergos/Peergos,Peergos/Peergos,ianopolous/Peergos,ianopolous/Peergos,ianopolous/Peergos
package peergos.server.tests; import org.junit.Assert; import peergos.server.*; import peergos.server.storage.ResetableFileInputStream; import peergos.shared.Crypto; import peergos.shared.NetworkAccess; import peergos.shared.crypto.symmetric.SymmetricKey; import peergos.shared.social.*; import peergos.shared.user.*; import peergos.shared.user.fs.*; import peergos.shared.user.fs.FileWrapper; import peergos.shared.user.fs.cryptree.*; import peergos.shared.util.ArrayOps; import peergos.shared.util.Serialize; import java.io.File; import java.io.IOException; import java.nio.file.*; import java.util.*; import java.util.concurrent.*; import java.util.stream.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class PeergosNetworkUtils { public static String generateUsername(Random random) { return "username_" + Math.abs(random.nextInt() % 1_000_000_000); } public static String generatePassword() { return ArrayOps.bytesToHex(crypto.random.randomBytes(32)); } public static final Crypto crypto = Main.initCrypto(); public static String randomString() { return UUID.randomUUID().toString(); } public static byte[] randomData(Random random, int length) { byte[] data = new byte[length]; random.nextBytes(data); return data; } public static String randomUsername(String prefix, Random rnd) { byte[] suffix = new byte[(30 - prefix.length()) / 2]; rnd.nextBytes(suffix); return prefix + ArrayOps.bytesToHex(suffix); } public static void checkFileContents(byte[] expected, FileWrapper f, UserContext context) { long size = f.getFileProperties().size; byte[] retrievedData = Serialize.readFully(f.getInputStream(context.network, context.crypto, size, l -> {}).join(), f.getSize()).join(); assertEquals(expected.length, size); assertTrue("Correct contents", Arrays.equals(retrievedData, expected)); } public static List<UserContext> getUserContextsForNode(NetworkAccess network, Random random, int size, List<String> passwords) { return IntStream.range(0, size) .mapToObj(e -> { String username = generateUsername(random); String password = passwords.get(e); try { return ensureSignedUp(username, password, network.clear(), crypto); } catch (Exception ioe) { throw new IllegalStateException(ioe); } }).collect(Collectors.toList()); } public static void grantAndRevokeFileReadAccess(NetworkAccess sharerNode, NetworkAccess shareeNode, int shareeCount, Random random) throws Exception { Assert.assertTrue(0 < shareeCount); //sign up a user on sharerNode String sharerUsername = generateUsername(random); String sharerPassword = generatePassword(); UserContext sharerUser = ensureSignedUp(sharerUsername, sharerPassword, sharerNode.clear(), crypto); //sign up some users on shareeNode List<String> shareePasswords = IntStream.range(0, shareeCount) .mapToObj(i -> generatePassword()) .collect(Collectors.toList()); List<UserContext> shareeUsers = getUserContextsForNode(shareeNode, random, shareeCount, shareePasswords); // friend sharer with others friendBetweenGroups(Arrays.asList(sharerUser), shareeUsers); // upload a file to "a"'s space FileWrapper u1Root = sharerUser.getUserRoot().get(); String filename = "somefile.txt"; File f = File.createTempFile("peergos", ""); byte[] originalFileContents = sharerUser.crypto.random.randomBytes(10*1024*1024); Files.write(f.toPath(), originalFileContents); ResetableFileInputStream resetableFileInputStream = new ResetableFileInputStream(f); FileWrapper uploaded = u1Root.uploadOrReplaceFile(filename, resetableFileInputStream, f.length(), sharerUser.network, crypto, l -> {}, crypto.random.randomBytes(32)).get(); // share the file from sharer to each of the sharees Set<String> shareeNames = shareeUsers.stream() .map(u -> u.username) .collect(Collectors.toSet()); sharerUser.shareReadAccessWith(Paths.get(sharerUser.username, filename), shareeNames).join(); // check other users can read the file for (UserContext userContext : shareeUsers) { Optional<FileWrapper> sharedFile = userContext.getByPath(sharerUser.username + "/" + filename).get(); Assert.assertTrue("shared file present", sharedFile.isPresent()); Assert.assertTrue("File is read only", ! sharedFile.get().isWritable()); checkFileContents(originalFileContents, sharedFile.get(), userContext); } // check other users can browser to the friend's root for (UserContext userContext : shareeUsers) { Optional<FileWrapper> friendRoot = userContext.getByPath(sharerUser.username).get(); assertTrue("friend root present", friendRoot.isPresent()); Set<FileWrapper> children = friendRoot.get().getChildren(crypto.hasher, userContext.network).get(); Optional<FileWrapper> sharedFile = children.stream() .filter(file -> file.getName().equals(filename)) .findAny(); assertTrue("Shared file present via root.getChildren()", sharedFile.isPresent()); } UserContext userToUnshareWith = shareeUsers.stream().findFirst().get(); // unshare with a single user sharerUser.unShareReadAccess(Paths.get(sharerUser.username, filename), userToUnshareWith.username).get(); List<UserContext> updatedShareeUsers = shareeUsers.stream() .map(e -> { try { return ensureSignedUp(e.username, shareePasswords.get(shareeUsers.indexOf(e)), shareeNode, crypto); } catch (Exception ex) { throw new IllegalStateException(ex.getMessage(), ex); } }).collect(Collectors.toList()); //test that the other user cannot access it from scratch Optional<FileWrapper> otherUserView = updatedShareeUsers.get(0).getByPath(sharerUser.username + "/" + filename).get(); Assert.assertTrue(!otherUserView.isPresent()); List<UserContext> remainingUsers = updatedShareeUsers.stream() .skip(1) .collect(Collectors.toList()); UserContext updatedSharerUser = ensureSignedUp(sharerUsername, sharerPassword, sharerNode.clear(), crypto); // check remaining users can still read it for (UserContext userContext : remainingUsers) { String path = sharerUser.username + "/" + filename; Optional<FileWrapper> sharedFile = userContext.getByPath(path).get(); Assert.assertTrue("path '" + path + "' is still available", sharedFile.isPresent()); checkFileContents(originalFileContents, sharedFile.get(), userContext); } // test that u1 can still access the original file Optional<FileWrapper> fileWithNewBaseKey = updatedSharerUser.getByPath(sharerUser.username + "/" + filename).get(); Assert.assertTrue(fileWithNewBaseKey.isPresent()); // Now modify the file byte[] suffix = "Some new data at the end".getBytes(); AsyncReader suffixStream = new AsyncReader.ArrayBacked(suffix); FileWrapper parent = updatedSharerUser.getByPath(updatedSharerUser.username).get().get(); parent.uploadFileSection(filename, suffixStream, false, originalFileContents.length, originalFileContents.length + suffix.length, Optional.empty(), true, updatedSharerUser.network, crypto, l -> {}, null).get(); AsyncReader extendedContents = updatedSharerUser.getByPath(sharerUser.username + "/" + filename).get().get() .getInputStream(updatedSharerUser.network, crypto, l -> {}).get(); byte[] newFileContents = Serialize.readFully(extendedContents, originalFileContents.length + suffix.length).get(); Assert.assertTrue(Arrays.equals(newFileContents, ArrayOps.concat(originalFileContents, suffix))); } public static void grantAndRevokeFileWriteAccess(NetworkAccess sharerNode, NetworkAccess shareeNode, int shareeCount, Random random) throws Exception { Assert.assertTrue(0 < shareeCount); //sign up a user on sharerNode String sharerUsername = generateUsername(random); String sharerPassword = generatePassword(); UserContext sharerUser = ensureSignedUp(sharerUsername, sharerPassword, sharerNode.clear(), crypto); //sign up some users on shareeNode List<String> shareePasswords = IntStream.range(0, shareeCount) .mapToObj(i -> generatePassword()) .collect(Collectors.toList()); List<UserContext> shareeUsers = getUserContextsForNode(shareeNode, random, shareeCount, shareePasswords); // friend sharer with others friendBetweenGroups(Arrays.asList(sharerUser), shareeUsers); // upload a file to "a"'s space FileWrapper u1Root = sharerUser.getUserRoot().get(); String filename = "somefile.txt"; byte[] originalFileContents = sharerUser.crypto.random.randomBytes(10*1024*1024); AsyncReader resetableFileInputStream = AsyncReader.build(originalFileContents); FileWrapper uploaded = u1Root.uploadOrReplaceFile(filename, resetableFileInputStream, originalFileContents.length, sharerUser.network, crypto, l -> {}, crypto.random.randomBytes(32)).get(); // share the file from sharer to each of the sharees String filePath = sharerUser.username + "/" + filename; FileWrapper u1File = sharerUser.getByPath(filePath).get().get(); byte[] originalStreamSecret = u1File.getFileProperties().streamSecret.get(); sharerUser.shareWriteAccessWith(Paths.get(sharerUser.username, filename), shareeUsers.stream().map(u -> u.username).collect(Collectors.toSet())).get(); // check other users can read the file for (UserContext userContext : shareeUsers) { Optional<FileWrapper> sharedFile = userContext.getByPath(filePath).get(); Assert.assertTrue("shared file present", sharedFile.isPresent()); Assert.assertTrue("File is writable", sharedFile.get().isWritable()); checkFileContents(originalFileContents, sharedFile.get(), userContext); // check the other user can't rename the file FileWrapper parent = userContext.getByPath(sharerUser.username).get().get(); CompletableFuture<FileWrapper> rename = sharedFile.get() .rename("Somenew name.dat", parent, Paths.get(filePath), userContext); assertTrue("Cannot rename", rename.isCompletedExceptionally()); } // check other users can browser to the friend's root for (UserContext userContext : shareeUsers) { Optional<FileWrapper> friendRoot = userContext.getByPath(sharerUser.username).get(); assertTrue("friend root present", friendRoot.isPresent()); Set<FileWrapper> children = friendRoot.get().getChildren(crypto.hasher, userContext.network).get(); Optional<FileWrapper> sharedFile = children.stream() .filter(file -> file.getName().equals(filename)) .findAny(); assertTrue("Shared file present via root.getChildren()", sharedFile.isPresent()); } MultiUserTests.checkUserValidity(sharerNode, sharerUsername); UserContext userToUnshareWith = shareeUsers.stream().findFirst().get(); // unshare with a single user sharerUser.unShareWriteAccess(Paths.get(sharerUser.username, filename), userToUnshareWith.username).join(); List<UserContext> updatedShareeUsers = shareeUsers.stream() .map(e -> ensureSignedUp(e.username, shareePasswords.get(shareeUsers.indexOf(e)), shareeNode, crypto)) .collect(Collectors.toList()); //test that the other user cannot access it from scratch Optional<FileWrapper> otherUserView = updatedShareeUsers.get(0).getByPath(filePath).get(); Assert.assertTrue(!otherUserView.isPresent()); List<UserContext> remainingUsers = updatedShareeUsers.stream() .skip(1) .collect(Collectors.toList()); UserContext updatedSharerUser = ensureSignedUp(sharerUsername, sharerPassword, sharerNode.clear(), crypto); FileWrapper theFile = updatedSharerUser.getByPath(filePath).join().get(); byte[] newStreamSecret = theFile.getFileProperties().streamSecret.get(); boolean sameStreams = Arrays.equals(originalStreamSecret, newStreamSecret); Assert.assertTrue("Stream secret should change on revocation", ! sameStreams); String retrievedPath = theFile.getPath(sharerNode).join(); Assert.assertTrue("File has correct path", retrievedPath.equals("/" + filePath)); // check remaining users can still read it for (UserContext userContext : remainingUsers) { String path = filePath; Optional<FileWrapper> sharedFile = userContext.getByPath(path).get(); Assert.assertTrue("path '" + path + "' is still available", sharedFile.isPresent()); checkFileContents(originalFileContents, sharedFile.get(), userContext); } // test that u1 can still access the original file Optional<FileWrapper> fileWithNewBaseKey = updatedSharerUser.getByPath(filePath).get(); Assert.assertTrue(fileWithNewBaseKey.isPresent()); // Now modify the file from the sharer byte[] suffix = "Some new data at the end".getBytes(); AsyncReader suffixStream = new AsyncReader.ArrayBacked(suffix); FileWrapper parent = updatedSharerUser.getByPath(updatedSharerUser.username).get().get(); parent.uploadFileSection(filename, suffixStream, false, originalFileContents.length, originalFileContents.length + suffix.length, Optional.empty(), true, updatedSharerUser.network, crypto, l -> {}, null).get(); AsyncReader extendedContents = updatedSharerUser.getByPath(filePath).get().get().getInputStream(updatedSharerUser.network, updatedSharerUser.crypto, l -> {}).get(); byte[] newFileContents = Serialize.readFully(extendedContents, originalFileContents.length + suffix.length).get(); Assert.assertTrue(Arrays.equals(newFileContents, ArrayOps.concat(originalFileContents, suffix))); // Now modify the file from the sharee byte[] suffix2 = "Some more data".getBytes(); AsyncReader suffixStream2 = new AsyncReader.ArrayBacked(suffix2); UserContext sharee = remainingUsers.get(0); FileWrapper parent2 = sharee.getByPath(updatedSharerUser.username).get().get(); parent2.uploadFileSection(filename, suffixStream2, false, originalFileContents.length + suffix.length, originalFileContents.length + suffix.length + suffix2.length, Optional.empty(), true, shareeNode, crypto, l -> {}, null).get(); AsyncReader extendedContents2 = sharee.getByPath(filePath).get().get() .getInputStream(updatedSharerUser.network, updatedSharerUser.crypto, l -> {}).get(); byte[] newFileContents2 = Serialize.readFully(extendedContents2, originalFileContents.length + suffix.length + suffix2.length).get(); byte[] expected = ArrayOps.concat(ArrayOps.concat(originalFileContents, suffix), suffix2); equalArrays(newFileContents2, expected); MultiUserTests.checkUserValidity(sharerNode, sharerUsername); } public static void equalArrays(byte[] a, byte[] b) { if (a.length != b.length) throw new IllegalStateException("Different length arrays!"); for (int i=0; i < a.length; i++) if (a[i] != b[i]) throw new IllegalStateException("Different at index " + i); } public static void shareFileWithDifferentSigner(NetworkAccess sharerNode, NetworkAccess shareeNode, Random random) { // sign up the sharer String sharerUsername = generateUsername(random); String sharerPassword = generatePassword(); UserContext sharer = ensureSignedUp(sharerUsername, sharerPassword, sharerNode.clear(), crypto); // sign up the sharee String shareeUsername = generateUsername(random); String shareePassword = generatePassword(); UserContext sharee = ensureSignedUp(shareeUsername, shareePassword, shareeNode.clear(), crypto); // friend users friendBetweenGroups(Arrays.asList(sharer), Arrays.asList(sharee)); // make directory /sharer/dir and grant write access to it to a friend String dirName = "dir"; sharer.getUserRoot().join().mkdir(dirName, sharer.network, false, crypto).join(); Path dirPath = Paths.get(sharerUsername, dirName); sharer.shareWriteAccessWith(dirPath, Collections.singleton(sharee.username)).join(); // no revoke write access to dir sharer.unShareWriteAccess(dirPath, Collections.singleton(sharee.username)).join(); // check sharee can't read the dir Optional<FileWrapper> sharedDir = sharee.getByPath(dirPath).join(); Assert.assertTrue("unshared dir not present", ! sharedDir.isPresent()); // upload a file to the dir FileWrapper dir = sharer.getByPath(dirPath).join().get(); String filename = "somefile.txt"; byte[] originalFileContents = sharer.crypto.random.randomBytes(10*1024*1024); AsyncReader resetableFileInputStream = AsyncReader.build(originalFileContents); FileWrapper uploaded = dir.uploadOrReplaceFile(filename, resetableFileInputStream, originalFileContents.length, sharer.network, crypto, l -> {}, crypto.random.randomBytes(32)).join(); // share the file read only with the sharee Path filePath = dirPath.resolve(filename); FileWrapper u1File = sharer.getByPath(filePath).join().get(); sharer.shareWriteAccessWith(filePath, Collections.singleton(sharee.username)).join(); // check other user can read the file directly Optional<FileWrapper> sharedFile = sharee.getByPath(filePath).join(); Assert.assertTrue("shared file present", sharedFile.isPresent()); checkFileContents(originalFileContents, sharedFile.get(), sharee); // check other user can read the file via its parent Optional<FileWrapper> sharedDirViaFile = sharee.getByPath(dirPath.toString()).join(); Set<FileWrapper> children = sharedDirViaFile.get().getChildren(crypto.hasher, sharee.network).join(); Assert.assertTrue("shared file present via parent", children.size() == 1); FileWrapper friend = sharee.getByPath(Paths.get(sharer.username)).join().get(); Set<FileWrapper> friendChildren = friend.getChildren(crypto.hasher, sharee.network).join(); Assert.assertEquals(friendChildren.size(), 1); } public static void sharedwithPermutations(NetworkAccess sharerNode, Random rnd) throws Exception { String sharerUsername = randomUsername("sharer-", rnd); String password = "terriblepassword"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(sharerUsername, password, sharerNode, crypto); String shareeUsername = randomUsername("sharee-", rnd); UserContext sharee = PeergosNetworkUtils.ensureSignedUp(shareeUsername, password, sharerNode, crypto); String shareeUsername2 = randomUsername("sharee2-", rnd); UserContext sharee2 = PeergosNetworkUtils.ensureSignedUp(shareeUsername2, password, sharerNode, crypto); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), Arrays.asList(sharee)); friendBetweenGroups(Arrays.asList(sharer), Arrays.asList(sharee2)); // friends are now connected // share a file from u1 to the others FileWrapper u1Root = sharer.getUserRoot().get(); String folderName = "afolder"; u1Root.mkdir(folderName, sharer.network, SymmetricKey.random(), false, crypto).get(); Path p = Paths.get(sharerUsername, folderName); FileSharedWithState result = sharer.sharedWith(p).join(); Assert.assertTrue(result.readAccess.size() == 0 && result.writeAccess.size() == 0); sharer.shareReadAccessWith(p, Collections.singleton(sharee.username)).join(); result = sharer.sharedWith(p).join(); Assert.assertTrue(result.readAccess.size() == 1); sharer.shareWriteAccessWith(p, Collections.singleton(sharee2.username)).join(); result = sharer.sharedWith(p).join(); Assert.assertTrue(result.readAccess.size() == 1 && result.writeAccess.size() == 1); sharer.unShareReadAccess(p, Set.of(sharee.username)).join(); result = sharer.sharedWith(p).join(); Assert.assertTrue(result.readAccess.size() == 0 && result.writeAccess.size() == 1); sharer.unShareWriteAccess(p, Set.of(sharee2.username)).join(); result = sharer.sharedWith(p).join(); Assert.assertTrue(result.readAccess.size() == 0 && result.writeAccess.size() == 0); // now try again, but after adding read, write sharees, remove the write sharee sharer.shareReadAccessWith(p, Collections.singleton(sharee.username)).join(); result = sharer.sharedWith(p).join(); Assert.assertTrue(result.readAccess.size() == 1); sharer.shareWriteAccessWith(p, Collections.singleton(sharee2.username)).join(); result = sharer.sharedWith(p).join(); Assert.assertTrue(result.readAccess.size() == 1 && result.writeAccess.size() == 1); sharer.unShareWriteAccess(p, Set.of(sharee2.username)).join(); result = sharer.sharedWith(p).join(); Assert.assertTrue(result.readAccess.size() == 1 && result.writeAccess.size() == 0); } public static void sharedWriteableAndTruncate(NetworkAccess sharerNode, Random rnd) throws Exception { String sharerUsername = randomUsername("sharer", rnd); String sharerPassword = "sharer1"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(sharerUsername, sharerPassword, sharerNode, crypto); String shareeUsername = randomUsername("sharee", rnd); String shareePassword = "sharee1"; UserContext sharee = PeergosNetworkUtils.ensureSignedUp(shareeUsername, shareePassword, sharerNode, crypto); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), Arrays.asList(sharee)); // friends are now connected // share a file from u1 to the others FileWrapper u1Root = sharer.getUserRoot().get(); String dirName = "afolder"; u1Root.mkdir(dirName, sharer.network, SymmetricKey.random(), false, crypto).get(); Path dirPath = Paths.get(sharerUsername, dirName); FileWrapper dir = sharer.getByPath(dirPath).join().get(); String filename = "somefile.txt"; byte[] originalFileContents = sharer.crypto.random.randomBytes(409); AsyncReader resetableFileInputStream = AsyncReader.build(originalFileContents); FileWrapper uploaded = dir.uploadOrReplaceFile(filename, resetableFileInputStream, originalFileContents.length, sharer.network, crypto, l -> {}, crypto.random.randomBytes(32)).join(); Path filePath = Paths.get(sharerUsername, dirName, filename); FileWrapper file = sharer.getByPath(filePath).join().get(); long originalfileSize = file.getFileProperties().size; System.out.println("filesize=" + originalfileSize); FileWrapper parent = sharer.getByPath(dirPath).join().get(); sharer.shareWriteAccessWith(file, filePath.toString(), parent, Collections.singletonList(sharee.username).toArray(new String[1])).join(); dir = sharer.getByPath(dirPath).join().get(); byte[] updatedFileContents = sharer.crypto.random.randomBytes(255); resetableFileInputStream = AsyncReader.build(updatedFileContents); uploaded = dir.uploadOrReplaceFile(filename, resetableFileInputStream, updatedFileContents.length, sharer.network, crypto, l -> {}, crypto.random.randomBytes(32)).join(); file = sharer.getByPath(filePath).join().get(); long newFileSize = file.getFileProperties().size; System.out.println("filesize=" + newFileSize); Assert.assertTrue(newFileSize == 255); //sharee now attempts to modify file FileWrapper sharedFile = sharee.getByPath(filePath).join().get(); byte[] modifiedFileContents = sharer.crypto.random.randomBytes(255); sharedFile.overwriteFileJS(AsyncReader.build(modifiedFileContents), 0, modifiedFileContents.length, sharee.network, sharee.crypto, len -> {}).join(); FileWrapper sharedFileUpdated = sharee.getByPath(filePath).join().get(); checkFileContents(modifiedFileContents, sharedFileUpdated, sharee); } public static void renameSharedwithFolder(NetworkAccess sharerNode, Random rnd) throws Exception { String sharerUsername = randomUsername("sharer-", rnd); String password = "terriblepassword"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(sharerUsername, password, sharerNode, crypto); String shareeUsername = randomUsername("sharee-", rnd); UserContext sharee = PeergosNetworkUtils.ensureSignedUp(shareeUsername, password, sharerNode, crypto); friendBetweenGroups(Arrays.asList(sharer), Arrays.asList(sharee)); FileWrapper u1Root = sharer.getUserRoot().get(); String folderName = "afolder"; u1Root.mkdir(folderName, sharer.network, SymmetricKey.random(), false, crypto).get(); Path p = Paths.get(sharerUsername, folderName); sharer.shareReadAccessWith(p, Set.of(shareeUsername)).join(); FileSharedWithState result = sharer.sharedWith(p).join(); Assert.assertTrue(result.readAccess.size() == 1); u1Root = sharer.getUserRoot().get(); FileWrapper file = sharer.getByPath(p).join().get(); String renamedFolderName= "renamed"; file.rename(renamedFolderName, u1Root, p, sharer).join(); p = Paths.get(sharerUsername, renamedFolderName); sharer.unShareReadAccess(p, Set.of(sharee.username)).join(); result = sharer.sharedWith(p).join(); Assert.assertTrue(result.readAccess.size() == 0 && result.writeAccess.size() == 0); } public static void grantAndRevokeDirReadAccess(NetworkAccess sharerNode, NetworkAccess shareeNode, int shareeCount, Random random) throws Exception { Assert.assertTrue(0 < shareeCount); CryptreeNode.setMaxChildLinkPerBlob(10); String sharerUsername = generateUsername(random); String sharerPassword = generatePassword(); UserContext sharer = PeergosNetworkUtils.ensureSignedUp(sharerUsername, sharerPassword, sharerNode, crypto); List<String> shareePasswords = IntStream.range(0, shareeCount) .mapToObj(i -> generatePassword()) .collect(Collectors.toList()); List<UserContext> shareeUsers = getUserContextsForNode(shareeNode, random, shareeCount, shareePasswords); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); // friends are now connected // share a file from u1 to the others FileWrapper u1Root = sharer.getUserRoot().get(); String folderName = "afolder"; u1Root.mkdir(folderName, sharer.network, SymmetricKey.random(), false, crypto).get(); String path = Paths.get(sharerUsername, folderName).toString(); System.out.println("PATH "+ path); FileWrapper folder = sharer.getByPath(path).get().get(); String filename = "somefile.txt"; byte[] originalFileContents = "Hello Peergos friend!".getBytes(); AsyncReader resetableFileInputStream = new AsyncReader.ArrayBacked(originalFileContents); FileWrapper updatedFolder = folder.uploadOrReplaceFile(filename, resetableFileInputStream, originalFileContents.length, sharer.network, crypto, l -> {},crypto.random.randomBytes(32)).get(); String originalFilePath = sharer.username + "/" + folderName + "/" + filename; for (int i=0; i< 20; i++) { sharer.getByPath(path).join().get() .mkdir("subdir"+i, sharer.network, false, crypto).join(); } Set<String> childNames = sharer.getByPath(path).join().get().getChildren(crypto.hasher, sharer.network).join() .stream() .map(f -> f.getName()) .collect(Collectors.toSet()); // file is uploaded, do the actual sharing boolean finished = sharer.shareReadAccessWithAll(updatedFolder, Paths.get(path), shareeUsers.stream() .map(c -> c.username) .collect(Collectors.toSet())).get(); // check each user can see the shared folder and directory for (UserContext sharee : shareeUsers) { // test retrieval via getChildren() which is used by the web-ui Set<FileWrapper> children = sharee.getByPath(sharer.username).join().get() .getChildren(crypto.hasher, sharee.network).join(); Assert.assertTrue(children.stream() .filter(f -> f.getName().equals(folderName)) .findAny() .isPresent()); FileWrapper sharedFolder = sharee.getByPath(sharer.username + "/" + folderName).get().orElseThrow(() -> new AssertionError("shared folder is present after sharing")); Assert.assertEquals(sharedFolder.getFileProperties().name, folderName); FileWrapper sharedFile = sharee.getByPath(sharer.username + "/" + folderName + "/" + filename).get().get(); checkFileContents(originalFileContents, sharedFile, sharee); } UserContext updatedSharer = PeergosNetworkUtils.ensureSignedUp(sharerUsername, sharerPassword, sharerNode.clear(), crypto); List<UserContext> updatedSharees = shareeUsers.stream() .map(e -> { try { return ensureSignedUp(e.username, shareePasswords.get(shareeUsers.indexOf(e)), e.network, crypto); } catch (Exception ex) { throw new IllegalStateException(ex.getMessage(), ex); } }).collect(Collectors.toList()); for (int i = 0; i < updatedSharees.size(); i++) { UserContext user = updatedSharees.get(i); updatedSharer.unShareReadAccess(Paths.get(updatedSharer.username, folderName), user.username).get(); Optional<FileWrapper> updatedSharedFolder = user.getByPath(updatedSharer.username + "/" + folderName).get(); // test that u1 can still access the original file, and user cannot Optional<FileWrapper> fileWithNewBaseKey = updatedSharer.getByPath(updatedSharer.username + "/" + folderName + "/" + filename).get(); Assert.assertTrue(!updatedSharedFolder.isPresent()); Assert.assertTrue(fileWithNewBaseKey.isPresent()); // Now modify the file byte[] suffix = "Some new data at the end".getBytes(); AsyncReader suffixStream = new AsyncReader.ArrayBacked(suffix); FileWrapper parent = updatedSharer.getByPath(updatedSharer.username + "/" + folderName).get().get(); parent.uploadFileSection(filename, suffixStream, false, originalFileContents.length, originalFileContents.length + suffix.length, Optional.empty(), true, updatedSharer.network, crypto, l -> {}, null).get(); FileWrapper extendedFile = updatedSharer.getByPath(originalFilePath).get().get(); AsyncReader extendedContents = extendedFile.getInputStream(updatedSharer.network, crypto, l -> {}).get(); byte[] newFileContents = Serialize.readFully(extendedContents, extendedFile.getSize()).get(); Assert.assertTrue(Arrays.equals(newFileContents, ArrayOps.concat(originalFileContents, suffix))); // test remaining users can still see shared file and folder for (int j = i + 1; j < updatedSharees.size(); j++) { UserContext otherUser = updatedSharees.get(j); Optional<FileWrapper> sharedFolder = otherUser.getByPath(updatedSharer.username + "/" + folderName).get(); Assert.assertTrue("Shared folder present via direct path", sharedFolder.isPresent() && sharedFolder.get().getName().equals(folderName)); FileWrapper sharedFile = otherUser.getByPath(updatedSharer.username + "/" + folderName + "/" + filename).get().get(); checkFileContents(newFileContents, sharedFile, otherUser); Set<String> sharedChildNames = sharedFolder.get().getChildren(crypto.hasher, otherUser.network).join() .stream() .map(f -> f.getName()) .collect(Collectors.toSet()); Assert.assertTrue("Correct children", sharedChildNames.equals(childNames)); } } } public static void grantAndRevokeDirWriteAccess(NetworkAccess sharerNode, NetworkAccess shareeNode, int shareeCount, Random random) throws Exception { Assert.assertTrue(0 < shareeCount); CryptreeNode.setMaxChildLinkPerBlob(10); String sharerUsername = generateUsername(random); String sharerPassword = generatePassword(); UserContext sharer = PeergosNetworkUtils.ensureSignedUp(sharerUsername, sharerPassword, sharerNode, crypto); List<String> shareePasswords = IntStream.range(0, shareeCount) .mapToObj(i -> generatePassword()) .collect(Collectors.toList()); List<UserContext> shareeUsers = getUserContextsForNode(shareeNode, random, shareeCount, shareePasswords); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); // friends are now connected // share a file from u1 to the others FileWrapper u1Root = sharer.getUserRoot().join(); String folderName = "afolder"; u1Root.mkdir(folderName, sharer.network, SymmetricKey.random(), false, crypto).get(); String path = Paths.get(sharerUsername, folderName).toString(); System.out.println("PATH "+ path); FileWrapper folder = sharer.getByPath(path).join().get(); String filename = "somefile.txt"; byte[] originalFileContents = "Hello Peergos friend!".getBytes(); AsyncReader resetableFileInputStream = new AsyncReader.ArrayBacked(originalFileContents); folder.uploadOrReplaceFile(filename, resetableFileInputStream, originalFileContents.length, sharer.network, crypto, l -> {}, crypto.random.randomBytes(32)).join(); String originalFilePath = sharer.username + "/" + folderName + "/" + filename; for (int i=0; i< 20; i++) { sharer.getByPath(path).join().get() .mkdir("subdir"+i, sharer.network, false, crypto).join(); } // file is uploaded, do the actual sharing boolean finished = sharer.shareWriteAccessWithAll(sharer.getByPath(path).join().get(), Paths.get(path), sharer.getUserRoot().join(), shareeUsers.stream() .map(c -> c.username) .collect(Collectors.toSet())).get(); // upload a image String imagename = "small.png"; byte[] data = Files.readAllBytes(Paths.get("assets", "logo.png")); FileWrapper sharedFolderv0 = sharer.getByPath(path).join().get(); sharedFolderv0.uploadOrReplaceFile(imagename, AsyncReader.build(data), data.length, sharer.network, crypto, x -> {}, crypto.random.randomBytes(32)).join(); // create a directory FileWrapper sharedFolderv1 = sharer.getByPath(path).join().get(); sharedFolderv1.mkdir("asubdir", sharer.network, false, crypto).join(); UserContext shareeUploader = shareeUsers.get(0); // check sharee can see folder via getChildren() which is used by the web-ui Set<FileWrapper> children = shareeUploader.getByPath(sharer.username).join().get() .getChildren(crypto.hasher, shareeUploader.network).join(); Assert.assertTrue(children.stream() .filter(f -> f.getName().equals(folderName)) .findAny() .isPresent()); // check a sharee can upload a file FileWrapper sharedDir = shareeUploader.getByPath(path).join().get(); sharedDir.uploadFileJS("a-new-file.png", AsyncReader.build(data), 0, data.length, false, false, shareeUploader.network, crypto, x -> {}, shareeUploader.getTransactionService()).join(); Set<String> childNames = sharer.getByPath(path).join().get().getChildren(crypto.hasher, sharer.network).join() .stream() .map(f -> f.getName()) .collect(Collectors.toSet()); // check each user can see the shared folder and directory for (UserContext sharee : shareeUsers) { FileWrapper sharedFolder = sharee.getByPath(sharer.username + "/" + folderName).get().orElseThrow(() -> new AssertionError("shared folder is present after sharing")); Assert.assertEquals(sharedFolder.getFileProperties().name, folderName); FileWrapper sharedFile = sharee.getByPath(sharer.username + "/" + folderName + "/" + filename).get().get(); checkFileContents(originalFileContents, sharedFile, sharee); Set<String> sharedChildNames = sharedFolder.getChildren(crypto.hasher, sharee.network).join() .stream() .map(f -> f.getName()) .collect(Collectors.toSet()); Assert.assertTrue("Correct children", sharedChildNames.equals(childNames)); } MultiUserTests.checkUserValidity(sharerNode, sharerUsername); UserContext updatedSharer = PeergosNetworkUtils.ensureSignedUp(sharerUsername, sharerPassword, sharerNode.clear(), crypto); List<UserContext> updatedSharees = shareeUsers.stream() .map(e -> { try { return ensureSignedUp(e.username, shareePasswords.get(shareeUsers.indexOf(e)), e.network, crypto); } catch (Exception ex) { throw new IllegalStateException(ex.getMessage(), ex); } }).collect(Collectors.toList()); for (int i = 0; i < updatedSharees.size(); i++) { UserContext user = updatedSharees.get(i); updatedSharer.unShareWriteAccess(Paths.get(updatedSharer.username, folderName), user.username).get(); Optional<FileWrapper> updatedSharedFolder = user.getByPath(updatedSharer.username + "/" + folderName).get(); // test that u1 can still access the original file, and user cannot Optional<FileWrapper> fileWithNewBaseKey = updatedSharer.getByPath(updatedSharer.username + "/" + folderName + "/" + filename).get(); Assert.assertTrue(!updatedSharedFolder.isPresent()); Assert.assertTrue(fileWithNewBaseKey.isPresent()); // Now modify the file byte[] suffix = "Some new data at the end".getBytes(); AsyncReader suffixStream = new AsyncReader.ArrayBacked(suffix); FileWrapper parent = updatedSharer.getByPath(updatedSharer.username + "/" + folderName).get().get(); parent.uploadFileSection(filename, suffixStream, false, originalFileContents.length, originalFileContents.length + suffix.length, Optional.empty(), true, updatedSharer.network, crypto, l -> {}, null).get(); FileWrapper extendedFile = updatedSharer.getByPath(originalFilePath).get().get(); AsyncReader extendedContents = extendedFile.getInputStream(updatedSharer.network, updatedSharer.crypto, l -> { }).get(); byte[] newFileContents = Serialize.readFully(extendedContents, extendedFile.getSize()).get(); Assert.assertTrue(Arrays.equals(newFileContents, ArrayOps.concat(originalFileContents, suffix))); // test remaining users can still see shared file and folder for (int j = i + 1; j < updatedSharees.size(); j++) { UserContext otherUser = updatedSharees.get(j); Optional<FileWrapper> sharedFolder = otherUser.getByPath(updatedSharer.username + "/" + folderName).get(); Assert.assertTrue("Shared folder present via direct path", sharedFolder.isPresent() && sharedFolder.get().getName().equals(folderName)); FileWrapper sharedFile = otherUser.getByPath(updatedSharer.username + "/" + folderName + "/" + filename).get().get(); checkFileContents(newFileContents, sharedFile, otherUser); Set<String> sharedChildNames = sharedFolder.get().getChildren(crypto.hasher, otherUser.network).join() .stream() .map(f -> f.getName()) .collect(Collectors.toSet()); Assert.assertTrue("Correct children", sharedChildNames.equals(childNames)); } } MultiUserTests.checkUserValidity(sharerNode, sharerUsername); } public static void grantAndRevokeNestedDirWriteAccess(NetworkAccess network, Random random) { CryptreeNode.setMaxChildLinkPerBlob(10); String password = "notagoodone"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(generateUsername(random), password, network, crypto); List<UserContext> shareeUsers = getUserContextsForNode(network, random, 2, Arrays.asList(password, password)); UserContext a = shareeUsers.get(0); UserContext b = shareeUsers.get(1); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); // friends are now connected // share a directory from u1 to u2 FileWrapper u1Root = sharer.getUserRoot().join(); String folderName = "folder"; u1Root.mkdir(folderName, sharer.network, SymmetricKey.random(), false, crypto).join(); Path dirPath = Paths.get(sharer.username, folderName); FileWrapper folder = sharer.getByPath(dirPath).join().get(); String filename = "somefile.txt"; byte[] data = "Hello Peergos friend!".getBytes(); AsyncReader resetableFileInputStream = new AsyncReader.ArrayBacked(data); folder.uploadOrReplaceFile(filename, resetableFileInputStream, data.length, sharer.network, crypto, l -> {}, crypto.random.randomBytes(32)).join(); String originalFilePath = sharer.username + "/" + folderName + "/" + filename; for (int i=0; i< 20; i++) { sharer.getByPath(dirPath).join().get() .mkdir("subdir"+i, sharer.network, false, crypto).join(); } // share /u1/folder with 'a' sharer.shareWriteAccessWithAll(sharer.getByPath(dirPath).join().get(), dirPath, sharer.getUserRoot().join(), Collections.singleton(a.username)).join(); // create a directory FileWrapper sharedFolderv1 = sharer.getByPath(dirPath).join().get(); String subdirName = "subdir"; sharedFolderv1.mkdir(subdirName, sharer.network, false, crypto).join(); // share /u1/folder with 'b' Path subdirPath = Paths.get(sharer.username, folderName, subdirName); sharer.shareWriteAccessWithAll(sharer.getByPath(subdirPath).join().get(), subdirPath, sharer.getByPath(dirPath).join().get(), Collections.singleton(b.username)).join(); // check 'b' can upload a file UserContext shareeUploader = shareeUsers.get(0); FileWrapper sharedDir = shareeUploader.getByPath(subdirPath).join().get(); sharedDir.uploadFileJS("a-new-file.png", AsyncReader.build(data), 0, data.length, false, false, shareeUploader.network, crypto, x -> {}, shareeUploader.getTransactionService()).join(); Set<String> childNames = sharer.getByPath(dirPath).join().get().getChildren(crypto.hasher, sharer.network).join() .stream() .map(f -> f.getName()) .collect(Collectors.toSet()); // check 'a' can see the shared directory FileWrapper sharedFolder = a.getByPath(sharer.username + "/" + folderName).join() .orElseThrow(() -> new AssertionError("shared folder is present after sharing")); Assert.assertEquals(sharedFolder.getFileProperties().name, folderName); FileWrapper sharedFile = a.getByPath(sharer.username + "/" + folderName + "/" + filename).join().get(); checkFileContents(data, sharedFile, a); Set<String> sharedChildNames = sharedFolder.getChildren(crypto.hasher, a.network).join() .stream() .map(f -> f.getName()) .collect(Collectors.toSet()); Assert.assertTrue("Correct children", sharedChildNames.equals(childNames)); MultiUserTests.checkUserValidity(network, sharer.username); UserContext updatedSharer = PeergosNetworkUtils.ensureSignedUp(sharer.username, password, network.clear(), crypto); List<UserContext> updatedSharees = shareeUsers.stream() .map(e -> { try { return ensureSignedUp(e.username, password, e.network, crypto); } catch (Exception ex) { throw new IllegalStateException(ex.getMessage(), ex); } }).collect(Collectors.toList()); // unshare subdir from 'b' UserContext user = updatedSharees.get(1); updatedSharer.unShareWriteAccess(subdirPath, b.username).join(); Optional<FileWrapper> updatedSharedFolder = user.getByPath(updatedSharer.username + "/" + folderName).join(); // test that u1 can still access the original file, and user cannot Optional<FileWrapper> fileWithNewBaseKey = updatedSharer.getByPath(updatedSharer.username + "/" + folderName + "/" + filename).join(); Assert.assertTrue(!updatedSharedFolder.isPresent()); Assert.assertTrue(fileWithNewBaseKey.isPresent()); // Now modify the file byte[] suffix = "Some new data at the end".getBytes(); AsyncReader suffixStream = new AsyncReader.ArrayBacked(suffix); FileWrapper parent = updatedSharer.getByPath(updatedSharer.username + "/" + folderName).join().get(); parent.uploadFileSection(filename, suffixStream, false, data.length, data.length + suffix.length, Optional.empty(), true, updatedSharer.network, crypto, l -> {}, null).join(); FileWrapper extendedFile = updatedSharer.getByPath(originalFilePath).join().get(); AsyncReader extendedContents = extendedFile.getInputStream(updatedSharer.network, updatedSharer.crypto, l -> {}).join(); byte[] newFileContents = Serialize.readFully(extendedContents, extendedFile.getSize()).join(); Assert.assertTrue(Arrays.equals(newFileContents, ArrayOps.concat(data, suffix))); // test 'a' can still see shared file and folder UserContext otherUser = updatedSharees.get(0); Optional<FileWrapper> folderAgain = otherUser.getByPath(updatedSharer.username + "/" + folderName).join(); Assert.assertTrue("Shared folder present via direct path", folderAgain.isPresent() && folderAgain.get().getName().equals(folderName)); FileWrapper sharedFileAgain = otherUser.getByPath(updatedSharer.username + "/" + folderName + "/" + filename).join().get(); checkFileContents(newFileContents, sharedFileAgain, otherUser); Set<String> childNamesAgain = folderAgain.get().getChildren(crypto.hasher, otherUser.network).join() .stream() .map(f -> f.getName()) .collect(Collectors.toSet()); Assert.assertTrue("Correct children", childNamesAgain.equals(childNames)); MultiUserTests.checkUserValidity(network, sharer.username); } public static void grantAndRevokeParentNestedWriteAccess(NetworkAccess network, Random random) { CryptreeNode.setMaxChildLinkPerBlob(10); String password = "notagoodone"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(generateUsername(random), password, network, crypto); List<UserContext> shareeUsers = getUserContextsForNode(network, random, 2, Arrays.asList(password, password)); UserContext a = shareeUsers.get(0); UserContext b = shareeUsers.get(1); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); // friends are now connected // share a directory from u1 to u2 FileWrapper u1Root = sharer.getUserRoot().join(); String folderName = "folder"; u1Root.mkdir(folderName, sharer.network, SymmetricKey.random(), false, crypto).join(); Path dirPath = Paths.get(sharer.username, folderName); // create a directory String subdirName = "subdir"; sharer.getByPath(dirPath).join().get() .mkdir(subdirName, sharer.network, false, crypto).join(); // share /u1/folder/subdir with 'b' Path subdirPath = Paths.get(sharer.username, folderName, subdirName); sharer.shareWriteAccessWithAll(sharer.getByPath(subdirPath).join().get(), subdirPath, sharer.getByPath(dirPath).join().get(), Collections.singleton(b.username)).join(); // share /u1/folder with 'a' sharer.shareWriteAccessWithAll(sharer.getByPath(dirPath).join().get(), dirPath, sharer.getUserRoot().join(), Collections.singleton(a.username)).join(); // check sharer can still see /u1/folder/subdir Assert.assertTrue("subdir still present", sharer.getByPath(subdirPath).join().isPresent()); // check 'a' can see the shared directory FileWrapper sharedFolder = a.getByPath(sharer.username + "/" + folderName).join() .orElseThrow(() -> new AssertionError("shared folder is present after sharing")); Assert.assertEquals(sharedFolder.getFileProperties().name, folderName); // revoke access to /u1/folder from 'a' sharer.unShareWriteAccess(dirPath, a.username).join(); // check 'a' can't see the shared directory Optional<FileWrapper> unsharedFolder = a.getByPath(sharer.username + "/" + folderName).join(); Assert.assertTrue("a can't see unshared folder", ! unsharedFolder.isPresent()); } public static void grantAndRevokeReadAccessToFileInFolder(NetworkAccess network, Random random) throws IOException { CryptreeNode.setMaxChildLinkPerBlob(10); String password = "notagoodone"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(generateUsername(random), password, network, crypto); List<UserContext> shareeUsers = getUserContextsForNode(network, random, 1, Arrays.asList(password, password)); UserContext a = shareeUsers.get(0); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); // friends are now connected // share a directory from u1 to u2 FileWrapper u1Root = sharer.getUserRoot().join(); String folderName = "folder"; u1Root.mkdir(folderName, sharer.network, SymmetricKey.random(), false, crypto).join(); Path dirPath = Paths.get(sharer.username, folderName); String filename = "somefile.txt"; File f = File.createTempFile("peergos", ""); byte[] originalFileContents = sharer.crypto.random.randomBytes(1*1024*1024); Files.write(f.toPath(), originalFileContents); ResetableFileInputStream resetableFileInputStream = new ResetableFileInputStream(f); FileWrapper dir = sharer.getByPath(dirPath).join().get(); FileWrapper uploaded = dir.uploadOrReplaceFile(filename, resetableFileInputStream, f.length(), sharer.network, crypto, l -> {}, crypto.random.randomBytes(32)).join(); Path fileToShare = Paths.get(sharer.username, folderName, filename); sharer.shareReadAccessWithAll(sharer.getByPath(fileToShare).join().get(), fileToShare , Collections.singleton(a.username)).join(); // check 'a' can see the shared file FileWrapper sharedFolder = a.getByPath(sharer.username + "/" + folderName + "/" + filename).join() .orElseThrow(() -> new AssertionError("shared folder is present after sharing")); Assert.assertEquals(sharedFolder.getFileProperties().name, filename); sharer.unShareReadAccess(fileToShare, a.username).join(); // check 'a' can't see the shared directory FileWrapper unsharedLocation = a.getByPath(sharer.username).join().get(); Set<FileWrapper> children = unsharedLocation.getChildren(crypto.hasher, sharer.network).join(); Assert.assertTrue("a can't see unshared folder", children.isEmpty()); } public static void grantAndRevokeWriteThenReadAccessToFolder(NetworkAccess network, Random random) throws IOException { CryptreeNode.setMaxChildLinkPerBlob(10); String password = "notagoodone"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(generateUsername(random), password, network, crypto); List<UserContext> shareeUsers = getUserContextsForNode(network, random, 1, Arrays.asList(password, password)); UserContext a = shareeUsers.get(0); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); // friends are now connected // share a directory from u1 to u2 FileWrapper u1Root = sharer.getUserRoot().join(); String folderName = "folder"; u1Root.mkdir(folderName, sharer.network, SymmetricKey.random(), false, crypto).join(); Path dirPath = Paths.get(sharer.username, folderName); // share /u1/folder with 'a' sharer.shareWriteAccessWithAll(sharer.getByPath(dirPath).join().get(), dirPath, sharer.getUserRoot().join(), Collections.singleton(a.username)).join(); // check 'a' can see the shared file FileWrapper sharedFolder = a.getByPath(sharer.username + "/" + folderName).join() .orElseThrow(() -> new AssertionError("shared folder is present after sharing")); Assert.assertEquals(sharedFolder.getFileProperties().name, folderName); sharer.unShareWriteAccess(dirPath, a.username).join(); // check 'a' can't see the shared directory FileWrapper unsharedLocation = a.getByPath(sharer.username).join().get(); Set<FileWrapper> children = unsharedLocation.getChildren(crypto.hasher, sharer.network).join(); Assert.assertTrue("a can't see unshared folder", children.isEmpty()); sharer.shareReadAccessWithAll(sharer.getByPath(dirPath).join().get(), dirPath , Collections.singleton(a.username)).join(); // check 'a' can see the shared file sharedFolder = a.getByPath(sharer.username + "/" + folderName).join() .orElseThrow(() -> new AssertionError("shared folder is present after sharing")); Assert.assertEquals(sharedFolder.getFileProperties().name, folderName); sharer.unShareReadAccess(dirPath, a.username).join(); // check 'a' can't see the shared directory unsharedLocation = a.getByPath(sharer.username).join().get(); children = unsharedLocation.getChildren(crypto.hasher, sharer.network).join(); Assert.assertTrue("a can't see unshared folder", children.isEmpty()); } public static void grantAndRevokeDirWriteAccessWithNestedWriteAccess(NetworkAccess network, Random random) { CryptreeNode.setMaxChildLinkPerBlob(10); String password = "notagoodone"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(generateUsername(random), password, network, crypto); List<UserContext> shareeUsers = getUserContextsForNode(network, random, 2, Arrays.asList(password, password)); UserContext a = shareeUsers.get(0); UserContext b = shareeUsers.get(1); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); // friends are now connected FileWrapper u1Root = sharer.getUserRoot().join(); String folderName = "folder"; u1Root.mkdir(folderName, sharer.network, SymmetricKey.random(), false, crypto).join(); Path dirPath = Paths.get(sharer.username, folderName); // put a file and some sub-dirs into the dir FileWrapper folder = sharer.getByPath(dirPath).join().get(); String filename = "somefile.txt"; byte[] data = "Hello Peergos friend!".getBytes(); AsyncReader resetableFileInputStream = new AsyncReader.ArrayBacked(data); folder.uploadOrReplaceFile(filename, resetableFileInputStream, data.length, sharer.network, crypto, l -> {}, crypto.random.randomBytes(32)).join(); for (int i=0; i< 20; i++) { sharer.getByPath(dirPath).join().get() .mkdir("subdir"+i, sharer.network, false, crypto).join(); } // grant write access to a directory to user 'a' sharer.shareWriteAccessWithAll(sharer.getByPath(dirPath).join().get(), dirPath, sharer.getUserRoot().join(), Collections.singleton(a.username)).join(); // create another sub-directory FileWrapper sharedFolderv1 = sharer.getByPath(dirPath).join().get(); String subdirName = "subdir"; sharedFolderv1.mkdir(subdirName, sharer.network, false, crypto).join(); // grant write access to a sub-directory to user 'b' Path subdirPath = Paths.get(sharer.username, folderName, subdirName); sharer.shareWriteAccessWithAll(sharer.getByPath(subdirPath).join().get(), subdirPath, sharer.getByPath(dirPath).join().get(), Collections.singleton(b.username)).join(); List<Set<AbsoluteCapability>> childCapsByChunk0 = getAllChildCapsByChunk(sharer.getByPath(dirPath).join().get(), network); Assert.assertTrue("Correct links per chunk, without duplicates", childCapsByChunk0.stream().map(x -> x.size()).collect(Collectors.toList()) .equals(Arrays.asList(10, 10, 2))); // check 'b' can upload a file UserContext shareeUploader = shareeUsers.get(0); FileWrapper sharedDir = shareeUploader.getByPath(subdirPath).join().get(); sharedDir.uploadFileJS("a-new-file.png", AsyncReader.build(data), 0, data.length, false, false, shareeUploader.network, crypto, x -> {}, shareeUploader.getTransactionService()).join(); // check 'a' can see the shared directory FileWrapper sharedFolder = a.getByPath(sharer.username + "/" + folderName).join() .orElseThrow(() -> new AssertionError("shared folder is present after sharing")); Assert.assertEquals(sharedFolder.getFileProperties().name, folderName); FileWrapper sharedFile = a.getByPath(sharer.username + "/" + folderName + "/" + filename).join().get(); checkFileContents(data, sharedFile, a); Set<String> sharedChildNames = sharedFolder.getChildren(crypto.hasher, a.network).join() .stream() .map(f -> f.getName()) .collect(Collectors.toSet()); Set<String> childNames = sharer.getByPath(dirPath).join().get().getChildren(crypto.hasher, sharer.network).join() .stream() .map(f -> f.getName()) .collect(Collectors.toSet()); Assert.assertTrue("Correct children", sharedChildNames.equals(childNames)); MultiUserTests.checkUserValidity(network, sharer.username); Set<AbsoluteCapability> childCaps = getAllChildCaps(sharer.getByPath(dirPath).join().get(), network); Assert.assertTrue("Correct number of child caps on dir", childCaps.size() == 22); UserContext updatedSharer = PeergosNetworkUtils.ensureSignedUp(sharer.username, password, network.clear(), crypto); List<UserContext> updatedSharees = shareeUsers.stream() .map(e -> { try { return ensureSignedUp(e.username, password, e.network, crypto); } catch (Exception ex) { throw new IllegalStateException(ex.getMessage(), ex); } }).collect(Collectors.toList()); // revoke write access to top level dir from 'a' UserContext user = updatedSharees.get(0); List<Set<AbsoluteCapability>> childCapsByChunk1 = getAllChildCapsByChunk(updatedSharer.getByPath(dirPath).join().get(), network); Assert.assertTrue("Correct links per chunk, without duplicates", childCapsByChunk1.stream().map(x -> x.size()).collect(Collectors.toList()) .equals(Arrays.asList(10, 10, 2))); updatedSharer.unShareWriteAccess(dirPath, a.username).join(); List<Set<AbsoluteCapability>> childCapsByChunk2 = getAllChildCapsByChunk(sharer.getByPath(dirPath).join().get(), network); Assert.assertTrue("Correct links per chunk, without duplicates", childCapsByChunk2.stream().map(x -> x.size()).collect(Collectors.toList()) .equals(Arrays.asList(10, 10, 2))); Optional<FileWrapper> updatedSharedFolder = user.getByPath(dirPath).join(); // test that sharer can still access the sub-dir, and 'a' cannot access the top level dir Optional<FileWrapper> updatedSubdir = updatedSharer.getByPath(subdirPath).join(); Assert.assertTrue(! updatedSharedFolder.isPresent()); Assert.assertTrue(updatedSubdir.isPresent()); // test 'b' can still see shared sub-dir UserContext otherUser = updatedSharees.get(1); Optional<FileWrapper> subdirAgain = otherUser.getByPath(subdirPath).join(); Assert.assertTrue("Shared folder present via direct path", subdirAgain.isPresent()); MultiUserTests.checkUserValidity(network, sharer.username); } public static void socialFeed(NetworkAccess network, Random random) { CryptreeNode.setMaxChildLinkPerBlob(10); String password = "notagoodone"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(generateUsername(random), password, network, crypto); List<UserContext> shareeUsers = getUserContextsForNode(network, random, 1, Arrays.asList(password, password)); UserContext a = shareeUsers.get(0); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); // friends are now connected // share a file from u1 to u2 FileWrapper u1Root = sharer.getUserRoot().join(); String filename = "somefile.txt"; byte[] fileData = sharer.crypto.random.randomBytes(1*1024*1024); Path file1 = Paths.get(sharer.username, "first-file.txt"); uploadAndShare(fileData, file1, sharer, a.username); // check 'a' can see the shared file in their social feed SocialFeed feed = a.getSocialFeed().join(); int feedSize = 3; List<SharedItem> items = feed.getShared(feedSize, feedSize + 1, a.crypto, a.network).join(); Assert.assertTrue(items.size() > 0); SharedItem item = items.get(0); Assert.assertTrue(item.owner.equals(sharer.username)); Assert.assertTrue(item.sharer.equals(sharer.username)); AbsoluteCapability readCap = sharer.getByPath(file1).join().get().getPointer().capability.readOnly(); Assert.assertTrue(item.cap.equals(readCap)); Assert.assertTrue(item.path.equals("/" + file1.toString())); // Test the feed after a fresh login UserContext freshA = PeergosNetworkUtils.ensureSignedUp(a.username, password, network, crypto); SocialFeed freshFeed = freshA.getSocialFeed().join(); List<SharedItem> freshItems = freshFeed.getShared(feedSize, feedSize + 1, a.crypto, a.network).join(); Assert.assertTrue(freshItems.size() > 0); SharedItem freshItem = freshItems.get(0); Assert.assertTrue(freshItem.equals(item)); // Test sharing a new item after construction Path file2 = Paths.get(sharer.username, "second-file.txt"); uploadAndShare(fileData, file2, sharer, a.username); SocialFeed updatedFeed = freshFeed.update().join(); List<SharedItem> items2 = updatedFeed.getShared(feedSize + 1, feedSize + 2, a.crypto, a.network).join(); Assert.assertTrue(items2.size() > 0); SharedItem item2 = items2.get(0); Assert.assertTrue(item2.owner.equals(sharer.username)); Assert.assertTrue(item2.sharer.equals(sharer.username)); AbsoluteCapability readCap2 = sharer.getByPath(file2).join().get().getPointer().capability.readOnly(); Assert.assertTrue(item2.cap.equals(readCap2)); // check accessing the files normally UserContext fresherA = PeergosNetworkUtils.ensureSignedUp(a.username, password, network, crypto); Optional<FileWrapper> directFile1 = fresherA.getByPath(file1).join(); Assert.assertTrue(directFile1.isPresent()); Optional<FileWrapper> directFile2 = fresherA.getByPath(file2).join(); Assert.assertTrue(directFile2.isPresent()); // check feed after browsing to the senders home Path file3 = Paths.get(sharer.username, "third-file.txt"); uploadAndShare(fileData, file3, sharer, a.username); // browse to sender home freshA.getByPath(Paths.get(sharer.username)).join(); Path file4 = Paths.get(sharer.username, "fourth-file.txt"); uploadAndShare(fileData, file4, sharer, a.username); // now check feed SocialFeed updatedFeed3 = freshFeed.update().join(); List<SharedItem> items3 = updatedFeed3.getShared(feedSize + 2, feedSize + 3, a.crypto, a.network).join(); Assert.assertTrue(items3.size() > 0); SharedItem item3 = items3.get(0); Assert.assertTrue(item3.owner.equals(sharer.username)); Assert.assertTrue(item3.sharer.equals(sharer.username)); AbsoluteCapability readCap3 = sharer.getByPath(file3).join().get().getPointer().capability.readOnly(); Assert.assertTrue(item3.cap.equals(readCap3)); } private static void uploadAndShare(byte[] data, Path file, UserContext sharer, String sharee) { String filename = file.getFileName().toString(); sharer.getByPath(file.getParent()).join().get() .uploadOrReplaceFile(filename, AsyncReader.build(data), data.length, sharer.network, crypto, l -> {}, crypto.random.randomBytes(32)).join(); sharer.shareReadAccessWithAll(sharer.getByPath(file).join().get(), file, Set.of(sharee)).join(); } public static void socialFeedVariations2(NetworkAccess network, Random random) { CryptreeNode.setMaxChildLinkPerBlob(10); String password = "notagoodone"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(generateUsername(random), password, network, crypto); List<UserContext> shareeUsers = getUserContextsForNode(network, random, 1, Arrays.asList(password, password)); UserContext sharee = shareeUsers.get(0); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); String dir1 = "one"; String dir2 = "two"; sharer.getUserRoot().join().mkdir(dir1, sharer.network, false, sharer.crypto).join(); sharer.getUserRoot().join().mkdir(dir2, sharer.network, false, sharer.crypto).join(); Path dirToShare1 = Paths.get(sharer.username, dir1); Path dirToShare2 = Paths.get(sharer.username, dir2); sharer.shareReadAccessWithAll(sharer.getByPath(dirToShare1).join().get(), dirToShare1, Set.of(sharee.username)).join(); sharer.shareReadAccessWithAll(sharer.getByPath(dirToShare2).join().get(), dirToShare2, Set.of(sharee.username)).join(); SocialFeed feed = sharee.getSocialFeed().join(); List<SharedItem> items = feed.getShared(0, 1000, sharee.crypto, sharee.network).join(); Assert.assertTrue(items.size() == 3 + 2); sharee.getUserRoot().join().mkdir("mine", sharee.network, false, sharer.crypto).join(); } public static void socialFeedFailsInUI(NetworkAccess network, Random random) { CryptreeNode.setMaxChildLinkPerBlob(10); String password = "notagoodone"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(generateUsername(random), password, network, crypto); List<UserContext> shareeUsers = getUserContextsForNode(network, random, 1, Arrays.asList(password, password)); UserContext sharee = shareeUsers.get(0); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); String dir1 = "one"; String dir2 = "two"; sharer.getUserRoot().join().mkdir(dir1, sharer.network, false, sharer.crypto).join(); sharer.getUserRoot().join().mkdir(dir2, sharer.network, false, sharer.crypto).join(); Path dirToShare1 = Paths.get(sharer.username, dir1); Path dirToShare2 = Paths.get(sharer.username, dir2); sharer.shareReadAccessWithAll(sharer.getByPath(dirToShare1).join().get(), dirToShare1, Set.of(sharee.username)).join(); sharer.shareReadAccessWithAll(sharer.getByPath(dirToShare2).join().get(), dirToShare2, Set.of(sharee.username)).join(); SocialFeed feed = sharee.getSocialFeed().join(); List<SharedItem> items = feed.getShared(0, 1000, sharee.crypto, sharee.network).join(); Assert.assertTrue(items.size() == 3 + 2); sharee = PeergosNetworkUtils.ensureSignedUp(sharee.username, password, network, crypto); sharee.getUserRoot().join().mkdir("mine", sharer.network, false, sharer.crypto).join(); feed = sharee.getSocialFeed().join(); items = feed.getShared(0, 1000, sharee.crypto, sharee.network).join(); Assert.assertTrue(items.size() == 3 + 2); //When attempting this in the web-ui the below call results in a failure when loading timeline entry //Cannot seek to position 680 in file of length 340 feed = sharee.getSocialFeed().join(); items = feed.getShared(0, 1000, sharee.crypto, sharee.network).join(); Assert.assertTrue(items.size() == 3 + 2); } public static void socialFeedEmpty(NetworkAccess network, Random random) { CryptreeNode.setMaxChildLinkPerBlob(10); String password = "notagoodone"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(generateUsername(random), password, network, crypto); SocialFeed feed = sharer.getSocialFeed().join(); List<SharedItem> items = feed.getShared(0, 1, sharer.crypto, sharer.network).join(); Assert.assertTrue(items.size() == 0); } public static void socialFeedVariations(NetworkAccess network, Random random) { CryptreeNode.setMaxChildLinkPerBlob(10); String password = "notagoodone"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(generateUsername(random), password, network, crypto); List<UserContext> shareeUsers = getUserContextsForNode(network, random, 1, Arrays.asList(password, password)); UserContext a = shareeUsers.get(0); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); String dir1 = "one"; String dir2 = "two"; sharer.getUserRoot().join().mkdir(dir1, sharer.network, false, sharer.crypto).join(); sharer.getUserRoot().join().mkdir(dir2, sharer.network, false, sharer.crypto).join(); Path dirToShare1 = Paths.get(sharer.username, dir1); Path dirToShare2 = Paths.get(sharer.username, dir2); sharer.shareReadAccessWithAll(sharer.getByPath(dirToShare1).join().get(), dirToShare1, Set.of(a.username)).join(); sharer.shareReadAccessWithAll(sharer.getByPath(dirToShare2).join().get(), dirToShare2, Set.of(a.username)).join(); SocialFeed feed = a.getSocialFeed().join(); List<SharedItem> items = feed.getShared(0, 1000, a.crypto, a.network).join(); Assert.assertTrue(items.size() == 2); //Add another file and share String dir3 = "three"; sharer.getUserRoot().join().mkdir(dir3, sharer.network, false, sharer.crypto).join(); Path dirToShare3 = Paths.get(sharer.username, dir3); sharer.shareReadAccessWithAll(sharer.getByPath(dirToShare3).join().get(), dirToShare3, Set.of(a.username)).join(); feed = a.getSocialFeed().join().update().join(); items = feed.getShared(0, 1000, a.crypto, a.network).join(); Assert.assertTrue(items.size() == 3); } public static void groupSharing(NetworkAccess network, Random random) { CryptreeNode.setMaxChildLinkPerBlob(10); String password = "notagoodone"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(generateUsername(random), password, network, crypto); List<UserContext> shareeUsers = getUserContextsForNode(network.clear(), random, 2, Arrays.asList(password, password)); UserContext friend = shareeUsers.get(0); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); String dirName = "one"; sharer.getUserRoot().join().mkdir(dirName, sharer.network, false, sharer.crypto).join(); Path dirToShare1 = Paths.get(sharer.username, dirName); SocialState social = sharer.getSocialState().join(); String friends = social.getFriendsGroupUid(); sharer.shareReadAccessWithAll(sharer.getByPath(dirToShare1).join().get(), dirToShare1, Set.of(friends)).join(); FileSharedWithState fileSharedWithState = sharer.sharedWith(dirToShare1).join(); Assert.assertTrue(fileSharedWithState.readAccess.size() == 1); Assert.assertTrue(fileSharedWithState.readAccess.contains(friends)); Optional<FileWrapper> dir = friend.getByPath(dirToShare1).join(); Assert.assertTrue(dir.isPresent()); Optional<FileWrapper> home = friend.getByPath(Paths.get(sharer.username)).join(); Assert.assertTrue(home.isPresent()); Optional<FileWrapper> dirViaGetChild = home.get().getChild(dirName, sharer.crypto.hasher, sharer.network).join(); Assert.assertTrue(dirViaGetChild.isPresent()); Set<FileWrapper> children = home.get().getChildren(sharer.crypto.hasher, sharer.network).join(); Assert.assertTrue(children.size() > 1); // remove friend, which should rotate all keys of things shared with the friends group sharer.removeFollower(friend.username).join(); Optional<FileWrapper> dir2 = friend.getByPath(dirToShare1).join(); Assert.assertTrue(dir2.isEmpty()); // new friends List<UserContext> newFriends = getUserContextsForNode(network.clear(), random, 1, Arrays.asList(password, password)); UserContext newFriend = newFriends.get(0); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), newFriends); Optional<FileWrapper> dirForNewFriend = newFriend.getByPath(dirToShare1).join(); Assert.assertTrue(dirForNewFriend.isPresent()); } public static void groupSharingToFollowers(NetworkAccess network, Random random) { CryptreeNode.setMaxChildLinkPerBlob(10); String password = "notagoodone"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(generateUsername(random), password, network, crypto); List<UserContext> shareeUsers = getUserContextsForNode(network.clear(), random, 2, Arrays.asList(password, password)); UserContext friend = shareeUsers.get(0); // make others follow sharer followBetweenGroups(Arrays.asList(sharer), shareeUsers); String dir1 = "one"; sharer.getUserRoot().join().mkdir(dir1, sharer.network, false, sharer.crypto).join(); Path dirToShare1 = Paths.get(sharer.username, dir1); SocialState social = sharer.getSocialState().join(); String followers = social.getFollowersGroupUid(); sharer.shareReadAccessWithAll(sharer.getByPath(dirToShare1).join().get(), dirToShare1, Set.of(followers)).join(); FileSharedWithState fileSharedWithState = sharer.sharedWith(dirToShare1).join(); Assert.assertTrue(fileSharedWithState.readAccess.size() == 1); Assert.assertTrue(fileSharedWithState.readAccess.contains(followers)); Optional<FileWrapper> dir = friend.getByPath(dirToShare1).join(); Assert.assertTrue(dir.isPresent()); // remove friend, which should rotate all keys of things shared with the friends group sharer.removeFollower(friend.username).join(); Optional<FileWrapper> dir2 = friend.getByPath(dirToShare1).join(); Assert.assertTrue(dir2.isEmpty()); } public static List<Set<AbsoluteCapability>> getAllChildCapsByChunk(FileWrapper dir, NetworkAccess network) { return getAllChildCapsByChunk(dir.getPointer().capability, dir.getPointer().fileAccess, dir.version, network); } public static List<Set<AbsoluteCapability>> getAllChildCapsByChunk(AbsoluteCapability cap, CryptreeNode dir, Snapshot inVersion, NetworkAccess network) { Set<NamedAbsoluteCapability> direct = dir.getDirectChildrenCapabilities(cap, inVersion, network).join(); AbsoluteCapability nextChunkCap = cap.withMapKey(dir.getNextChunkLocation(cap.rBaseKey, Optional.empty(), cap.getMapKey(), null).join()); Snapshot version = new Snapshot(cap.writer, WriterData.getWriterData(network.mutable.getPointerTarget(cap.owner, cap.writer, network.dhtClient).join().get(), network.dhtClient).join()); Optional<CryptreeNode> next = network.getMetadata(version.get(nextChunkCap.writer).props, nextChunkCap).join(); Set<AbsoluteCapability> directUnnamed = direct.stream().map(n -> n.cap).collect(Collectors.toSet()); if (! next.isPresent()) return Arrays.asList(directUnnamed); return Stream.concat(Stream.of(directUnnamed), getAllChildCapsByChunk(nextChunkCap, next.get(), inVersion, network).stream()) .collect(Collectors.toList()); } public static Set<AbsoluteCapability> getAllChildCaps(FileWrapper dir, NetworkAccess network) { RetrievedCapability p = dir.getPointer(); AbsoluteCapability cap = p.capability; return getAllChildCaps(cap, p.fileAccess, network); } public static Set<AbsoluteCapability> getAllChildCaps(AbsoluteCapability cap, CryptreeNode dir, NetworkAccess network) { return dir.getAllChildrenCapabilities(new Snapshot(cap.writer, WriterData.getWriterData(network.mutable.getPointerTarget(cap.owner, cap.writer, network.dhtClient).join().get(), network.dhtClient).join()), cap, crypto.hasher, network).join() .stream().map(n -> n.cap).collect(Collectors.toSet()); } public static void shareFolderForWriteAccess(NetworkAccess sharerNode, NetworkAccess shareeNode, int shareeCount, Random random) throws Exception { Assert.assertTrue(0 < shareeCount); String sharerUsername = generateUsername(random); String sharerPassword = generatePassword(); UserContext sharer = PeergosNetworkUtils.ensureSignedUp(sharerUsername, sharerPassword, sharerNode, crypto); List<String> shareePasswords = IntStream.range(0, shareeCount) .mapToObj(i -> generatePassword()) .collect(Collectors.toList()); List<UserContext> shareeUsers = getUserContextsForNode(shareeNode, random, shareeCount, shareePasswords); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); // friends are now connected // share a directory from u1 to the others FileWrapper u1Root = sharer.getUserRoot().get(); String folderName = "awritefolder"; u1Root.mkdir(folderName, sharer.network, SymmetricKey.random(), false, crypto).get(); String path = Paths.get(sharerUsername, folderName).toString(); System.out.println("PATH "+ path); FileWrapper folder = sharer.getByPath(path).get().get(); // file is uploaded, do the actual sharing boolean finished = sharer.shareWriteAccessWithAll(folder, Paths.get(path), sharer.getUserRoot().join(), shareeUsers.stream() .map(c -> c.username) .collect(Collectors.toSet())).get(); // check each user can see the shared folder, and write to it for (UserContext sharee : shareeUsers) { FileWrapper sharedFolder = sharee.getByPath(sharer.username + "/" + folderName).get().orElseThrow(() -> new AssertionError("shared folder is present after sharing")); Assert.assertEquals(sharedFolder.getFileProperties().name, folderName); sharedFolder.mkdir(sharee.username, shareeNode, false, crypto).get(); } Set<FileWrapper> children = sharer.getByPath(path).get().get().getChildren(crypto.hasher, sharerNode).get(); Assert.assertTrue(children.size() == shareeCount); } public static void publicLinkToFile(Random random, NetworkAccess writerNode, NetworkAccess readerNode) throws Exception { String username = generateUsername(random); String password = "test01"; UserContext context = PeergosNetworkUtils.ensureSignedUp(username, password, writerNode, crypto); FileWrapper userRoot = context.getUserRoot().get(); String filename = "mediumfile.bin"; byte[] data = new byte[128*1024]; random.nextBytes(data); long t1 = System.currentTimeMillis(); userRoot.uploadFileSection(filename, new AsyncReader.ArrayBacked(data), false, 0, data.length, Optional.empty(), true, context.network, crypto, l -> {}, crypto.random.randomBytes(32)).get(); long t2 = System.currentTimeMillis(); String path = "/" + username + "/" + filename; FileWrapper file = context.getByPath(path).get().get(); String link = file.toLink(); UserContext linkContext = UserContext.fromSecretLink(link, readerNode, crypto).get(); String entryPath = linkContext.getEntryPath().join(); Assert.assertTrue("Correct entry path", entryPath.equals("/" + username)); Optional<FileWrapper> fileThroughLink = linkContext.getByPath(path).get(); Assert.assertTrue("File present through link", fileThroughLink.isPresent()); } public static void friendBetweenGroups(List<UserContext> a, List<UserContext> b) { for (UserContext userA : a) { for (UserContext userB : b) { // send intial request userA.sendFollowRequest(userB.username, SymmetricKey.random()).join(); // make sharer reciprocate all the follow requests List<FollowRequestWithCipherText> sharerRequests = userB.processFollowRequests().join(); for (FollowRequestWithCipherText u1Request : sharerRequests) { AbsoluteCapability pointer = u1Request.req.entry.get().pointer; Assert.assertTrue("Read only capabilities are shared", ! pointer.wBaseKey.isPresent()); boolean accept = true; boolean reciprocate = true; userB.sendReplyFollowRequest(u1Request, accept, reciprocate).join(); } // complete the friendship connection userA.processFollowRequests().join(); } } } public static void followBetweenGroups(List<UserContext> sharers, List<UserContext> followers) { for (UserContext userA : sharers) { for (UserContext userB : followers) { // send intial request userB.sendFollowRequest(userA.username, SymmetricKey.random()).join(); // make sharer reciprocate all the follow requests List<FollowRequestWithCipherText> sharerRequests = userA.processFollowRequests().join(); for (FollowRequestWithCipherText u1Request : sharerRequests) { AbsoluteCapability pointer = u1Request.req.entry.get().pointer; Assert.assertTrue("Read only capabilities are shared", ! pointer.wBaseKey.isPresent()); boolean accept = true; boolean reciprocate = false; userA.sendReplyFollowRequest(u1Request, accept, reciprocate).join(); } // complete the friendship connection userB.processFollowRequests().join(); } } } public static UserContext ensureSignedUp(String username, String password, NetworkAccess network, Crypto crypto) { boolean isRegistered = network.isUsernameRegistered(username).join(); if (isRegistered) return UserContext.signIn(username, password, network, crypto).join(); return UserContext.signUp(username, password, "", network, crypto).join(); } }
src/peergos/server/tests/PeergosNetworkUtils.java
package peergos.server.tests; import org.junit.Assert; import peergos.server.*; import peergos.server.storage.ResetableFileInputStream; import peergos.shared.Crypto; import peergos.shared.NetworkAccess; import peergos.shared.crypto.symmetric.SymmetricKey; import peergos.shared.social.*; import peergos.shared.user.*; import peergos.shared.user.fs.*; import peergos.shared.user.fs.FileWrapper; import peergos.shared.user.fs.cryptree.*; import peergos.shared.util.ArrayOps; import peergos.shared.util.Serialize; import java.io.File; import java.io.IOException; import java.nio.file.*; import java.util.*; import java.util.concurrent.*; import java.util.stream.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class PeergosNetworkUtils { public static String generateUsername(Random random) { return "username_" + Math.abs(random.nextInt() % 1_000_000_000); } public static String generatePassword() { return ArrayOps.bytesToHex(crypto.random.randomBytes(32)); } public static final Crypto crypto = Main.initCrypto(); public static String randomString() { return UUID.randomUUID().toString(); } public static byte[] randomData(Random random, int length) { byte[] data = new byte[length]; random.nextBytes(data); return data; } public static String randomUsername(String prefix, Random rnd) { byte[] suffix = new byte[(30 - prefix.length()) / 2]; rnd.nextBytes(suffix); return prefix + ArrayOps.bytesToHex(suffix); } public static void checkFileContents(byte[] expected, FileWrapper f, UserContext context) { long size = f.getFileProperties().size; byte[] retrievedData = Serialize.readFully(f.getInputStream(context.network, context.crypto, size, l -> {}).join(), f.getSize()).join(); assertEquals(expected.length, size); assertTrue("Correct contents", Arrays.equals(retrievedData, expected)); } public static List<UserContext> getUserContextsForNode(NetworkAccess network, Random random, int size, List<String> passwords) { return IntStream.range(0, size) .mapToObj(e -> { String username = generateUsername(random); String password = passwords.get(e); try { return ensureSignedUp(username, password, network.clear(), crypto); } catch (Exception ioe) { throw new IllegalStateException(ioe); } }).collect(Collectors.toList()); } public static void grantAndRevokeFileReadAccess(NetworkAccess sharerNode, NetworkAccess shareeNode, int shareeCount, Random random) throws Exception { Assert.assertTrue(0 < shareeCount); //sign up a user on sharerNode String sharerUsername = generateUsername(random); String sharerPassword = generatePassword(); UserContext sharerUser = ensureSignedUp(sharerUsername, sharerPassword, sharerNode.clear(), crypto); //sign up some users on shareeNode List<String> shareePasswords = IntStream.range(0, shareeCount) .mapToObj(i -> generatePassword()) .collect(Collectors.toList()); List<UserContext> shareeUsers = getUserContextsForNode(shareeNode, random, shareeCount, shareePasswords); // friend sharer with others friendBetweenGroups(Arrays.asList(sharerUser), shareeUsers); // upload a file to "a"'s space FileWrapper u1Root = sharerUser.getUserRoot().get(); String filename = "somefile.txt"; File f = File.createTempFile("peergos", ""); byte[] originalFileContents = sharerUser.crypto.random.randomBytes(10*1024*1024); Files.write(f.toPath(), originalFileContents); ResetableFileInputStream resetableFileInputStream = new ResetableFileInputStream(f); FileWrapper uploaded = u1Root.uploadOrReplaceFile(filename, resetableFileInputStream, f.length(), sharerUser.network, crypto, l -> {}, crypto.random.randomBytes(32)).get(); // share the file from sharer to each of the sharees Set<String> shareeNames = shareeUsers.stream() .map(u -> u.username) .collect(Collectors.toSet()); sharerUser.shareReadAccessWith(Paths.get(sharerUser.username, filename), shareeNames).join(); // check other users can read the file for (UserContext userContext : shareeUsers) { Optional<FileWrapper> sharedFile = userContext.getByPath(sharerUser.username + "/" + filename).get(); Assert.assertTrue("shared file present", sharedFile.isPresent()); Assert.assertTrue("File is read only", ! sharedFile.get().isWritable()); checkFileContents(originalFileContents, sharedFile.get(), userContext); } // check other users can browser to the friend's root for (UserContext userContext : shareeUsers) { Optional<FileWrapper> friendRoot = userContext.getByPath(sharerUser.username).get(); assertTrue("friend root present", friendRoot.isPresent()); Set<FileWrapper> children = friendRoot.get().getChildren(crypto.hasher, userContext.network).get(); Optional<FileWrapper> sharedFile = children.stream() .filter(file -> file.getName().equals(filename)) .findAny(); assertTrue("Shared file present via root.getChildren()", sharedFile.isPresent()); } UserContext userToUnshareWith = shareeUsers.stream().findFirst().get(); // unshare with a single user sharerUser.unShareReadAccess(Paths.get(sharerUser.username, filename), userToUnshareWith.username).get(); List<UserContext> updatedShareeUsers = shareeUsers.stream() .map(e -> { try { return ensureSignedUp(e.username, shareePasswords.get(shareeUsers.indexOf(e)), shareeNode, crypto); } catch (Exception ex) { throw new IllegalStateException(ex.getMessage(), ex); } }).collect(Collectors.toList()); //test that the other user cannot access it from scratch Optional<FileWrapper> otherUserView = updatedShareeUsers.get(0).getByPath(sharerUser.username + "/" + filename).get(); Assert.assertTrue(!otherUserView.isPresent()); List<UserContext> remainingUsers = updatedShareeUsers.stream() .skip(1) .collect(Collectors.toList()); UserContext updatedSharerUser = ensureSignedUp(sharerUsername, sharerPassword, sharerNode.clear(), crypto); // check remaining users can still read it for (UserContext userContext : remainingUsers) { String path = sharerUser.username + "/" + filename; Optional<FileWrapper> sharedFile = userContext.getByPath(path).get(); Assert.assertTrue("path '" + path + "' is still available", sharedFile.isPresent()); checkFileContents(originalFileContents, sharedFile.get(), userContext); } // test that u1 can still access the original file Optional<FileWrapper> fileWithNewBaseKey = updatedSharerUser.getByPath(sharerUser.username + "/" + filename).get(); Assert.assertTrue(fileWithNewBaseKey.isPresent()); // Now modify the file byte[] suffix = "Some new data at the end".getBytes(); AsyncReader suffixStream = new AsyncReader.ArrayBacked(suffix); FileWrapper parent = updatedSharerUser.getByPath(updatedSharerUser.username).get().get(); parent.uploadFileSection(filename, suffixStream, false, originalFileContents.length, originalFileContents.length + suffix.length, Optional.empty(), true, updatedSharerUser.network, crypto, l -> {}, null).get(); AsyncReader extendedContents = updatedSharerUser.getByPath(sharerUser.username + "/" + filename).get().get() .getInputStream(updatedSharerUser.network, crypto, l -> {}).get(); byte[] newFileContents = Serialize.readFully(extendedContents, originalFileContents.length + suffix.length).get(); Assert.assertTrue(Arrays.equals(newFileContents, ArrayOps.concat(originalFileContents, suffix))); } public static void grantAndRevokeFileWriteAccess(NetworkAccess sharerNode, NetworkAccess shareeNode, int shareeCount, Random random) throws Exception { Assert.assertTrue(0 < shareeCount); //sign up a user on sharerNode String sharerUsername = generateUsername(random); String sharerPassword = generatePassword(); UserContext sharerUser = ensureSignedUp(sharerUsername, sharerPassword, sharerNode.clear(), crypto); //sign up some users on shareeNode List<String> shareePasswords = IntStream.range(0, shareeCount) .mapToObj(i -> generatePassword()) .collect(Collectors.toList()); List<UserContext> shareeUsers = getUserContextsForNode(shareeNode, random, shareeCount, shareePasswords); // friend sharer with others friendBetweenGroups(Arrays.asList(sharerUser), shareeUsers); // upload a file to "a"'s space FileWrapper u1Root = sharerUser.getUserRoot().get(); String filename = "somefile.txt"; byte[] originalFileContents = sharerUser.crypto.random.randomBytes(10*1024*1024); AsyncReader resetableFileInputStream = AsyncReader.build(originalFileContents); FileWrapper uploaded = u1Root.uploadOrReplaceFile(filename, resetableFileInputStream, originalFileContents.length, sharerUser.network, crypto, l -> {}, crypto.random.randomBytes(32)).get(); // share the file from sharer to each of the sharees String filePath = sharerUser.username + "/" + filename; FileWrapper u1File = sharerUser.getByPath(filePath).get().get(); byte[] originalStreamSecret = u1File.getFileProperties().streamSecret.get(); sharerUser.shareWriteAccessWith(Paths.get(sharerUser.username, filename), shareeUsers.stream().map(u -> u.username).collect(Collectors.toSet())).get(); // check other users can read the file for (UserContext userContext : shareeUsers) { Optional<FileWrapper> sharedFile = userContext.getByPath(filePath).get(); Assert.assertTrue("shared file present", sharedFile.isPresent()); Assert.assertTrue("File is writable", sharedFile.get().isWritable()); checkFileContents(originalFileContents, sharedFile.get(), userContext); // check the other user can't rename the file FileWrapper parent = userContext.getByPath(sharerUser.username).get().get(); CompletableFuture<FileWrapper> rename = sharedFile.get() .rename("Somenew name.dat", parent, Paths.get(filePath), userContext); assertTrue("Cannot rename", rename.isCompletedExceptionally()); } // check other users can browser to the friend's root for (UserContext userContext : shareeUsers) { Optional<FileWrapper> friendRoot = userContext.getByPath(sharerUser.username).get(); assertTrue("friend root present", friendRoot.isPresent()); Set<FileWrapper> children = friendRoot.get().getChildren(crypto.hasher, userContext.network).get(); Optional<FileWrapper> sharedFile = children.stream() .filter(file -> file.getName().equals(filename)) .findAny(); assertTrue("Shared file present via root.getChildren()", sharedFile.isPresent()); } MultiUserTests.checkUserValidity(sharerNode, sharerUsername); UserContext userToUnshareWith = shareeUsers.stream().findFirst().get(); // unshare with a single user sharerUser.unShareWriteAccess(Paths.get(sharerUser.username, filename), userToUnshareWith.username).join(); List<UserContext> updatedShareeUsers = shareeUsers.stream() .map(e -> ensureSignedUp(e.username, shareePasswords.get(shareeUsers.indexOf(e)), shareeNode, crypto)) .collect(Collectors.toList()); //test that the other user cannot access it from scratch Optional<FileWrapper> otherUserView = updatedShareeUsers.get(0).getByPath(filePath).get(); Assert.assertTrue(!otherUserView.isPresent()); List<UserContext> remainingUsers = updatedShareeUsers.stream() .skip(1) .collect(Collectors.toList()); UserContext updatedSharerUser = ensureSignedUp(sharerUsername, sharerPassword, sharerNode.clear(), crypto); FileWrapper theFile = updatedSharerUser.getByPath(filePath).join().get(); byte[] newStreamSecret = theFile.getFileProperties().streamSecret.get(); boolean sameStreams = Arrays.equals(originalStreamSecret, newStreamSecret); Assert.assertTrue("Stream secret should change on revocation", ! sameStreams); String retrievedPath = theFile.getPath(sharerNode).join(); Assert.assertTrue("File has correct path", retrievedPath.equals("/" + filePath)); // check remaining users can still read it for (UserContext userContext : remainingUsers) { String path = filePath; Optional<FileWrapper> sharedFile = userContext.getByPath(path).get(); Assert.assertTrue("path '" + path + "' is still available", sharedFile.isPresent()); checkFileContents(originalFileContents, sharedFile.get(), userContext); } // test that u1 can still access the original file Optional<FileWrapper> fileWithNewBaseKey = updatedSharerUser.getByPath(filePath).get(); Assert.assertTrue(fileWithNewBaseKey.isPresent()); // Now modify the file from the sharer byte[] suffix = "Some new data at the end".getBytes(); AsyncReader suffixStream = new AsyncReader.ArrayBacked(suffix); FileWrapper parent = updatedSharerUser.getByPath(updatedSharerUser.username).get().get(); parent.uploadFileSection(filename, suffixStream, false, originalFileContents.length, originalFileContents.length + suffix.length, Optional.empty(), true, updatedSharerUser.network, crypto, l -> {}, null).get(); AsyncReader extendedContents = updatedSharerUser.getByPath(filePath).get().get().getInputStream(updatedSharerUser.network, updatedSharerUser.crypto, l -> {}).get(); byte[] newFileContents = Serialize.readFully(extendedContents, originalFileContents.length + suffix.length).get(); Assert.assertTrue(Arrays.equals(newFileContents, ArrayOps.concat(originalFileContents, suffix))); // Now modify the file from the sharee byte[] suffix2 = "Some more data".getBytes(); AsyncReader suffixStream2 = new AsyncReader.ArrayBacked(suffix2); UserContext sharee = remainingUsers.get(0); FileWrapper parent2 = sharee.getByPath(updatedSharerUser.username).get().get(); parent2.uploadFileSection(filename, suffixStream2, false, originalFileContents.length + suffix.length, originalFileContents.length + suffix.length + suffix2.length, Optional.empty(), true, shareeNode, crypto, l -> {}, null).get(); AsyncReader extendedContents2 = sharee.getByPath(filePath).get().get() .getInputStream(updatedSharerUser.network, updatedSharerUser.crypto, l -> {}).get(); byte[] newFileContents2 = Serialize.readFully(extendedContents2, originalFileContents.length + suffix.length + suffix2.length).get(); byte[] expected = ArrayOps.concat(ArrayOps.concat(originalFileContents, suffix), suffix2); equalArrays(newFileContents2, expected); MultiUserTests.checkUserValidity(sharerNode, sharerUsername); } public static void equalArrays(byte[] a, byte[] b) { if (a.length != b.length) throw new IllegalStateException("Different length arrays!"); for (int i=0; i < a.length; i++) if (a[i] != b[i]) throw new IllegalStateException("Different at index " + i); } public static void shareFileWithDifferentSigner(NetworkAccess sharerNode, NetworkAccess shareeNode, Random random) { // sign up the sharer String sharerUsername = generateUsername(random); String sharerPassword = generatePassword(); UserContext sharer = ensureSignedUp(sharerUsername, sharerPassword, sharerNode.clear(), crypto); // sign up the sharee String shareeUsername = generateUsername(random); String shareePassword = generatePassword(); UserContext sharee = ensureSignedUp(shareeUsername, shareePassword, shareeNode.clear(), crypto); // friend users friendBetweenGroups(Arrays.asList(sharer), Arrays.asList(sharee)); // make directory /sharer/dir and grant write access to it to a friend String dirName = "dir"; sharer.getUserRoot().join().mkdir(dirName, sharer.network, false, crypto).join(); Path dirPath = Paths.get(sharerUsername, dirName); sharer.shareWriteAccessWith(dirPath, Collections.singleton(sharee.username)).join(); // no revoke write access to dir sharer.unShareWriteAccess(dirPath, Collections.singleton(sharee.username)).join(); // check sharee can't read the dir Optional<FileWrapper> sharedDir = sharee.getByPath(dirPath).join(); Assert.assertTrue("unshared dir not present", ! sharedDir.isPresent()); // upload a file to the dir FileWrapper dir = sharer.getByPath(dirPath).join().get(); String filename = "somefile.txt"; byte[] originalFileContents = sharer.crypto.random.randomBytes(10*1024*1024); AsyncReader resetableFileInputStream = AsyncReader.build(originalFileContents); FileWrapper uploaded = dir.uploadOrReplaceFile(filename, resetableFileInputStream, originalFileContents.length, sharer.network, crypto, l -> {}, crypto.random.randomBytes(32)).join(); // share the file read only with the sharee Path filePath = dirPath.resolve(filename); FileWrapper u1File = sharer.getByPath(filePath).join().get(); sharer.shareWriteAccessWith(filePath, Collections.singleton(sharee.username)).join(); // check other user can read the file directly Optional<FileWrapper> sharedFile = sharee.getByPath(filePath).join(); Assert.assertTrue("shared file present", sharedFile.isPresent()); checkFileContents(originalFileContents, sharedFile.get(), sharee); // check other user can read the file via its parent Optional<FileWrapper> sharedDirViaFile = sharee.getByPath(dirPath.toString()).join(); Set<FileWrapper> children = sharedDirViaFile.get().getChildren(crypto.hasher, sharee.network).join(); Assert.assertTrue("shared file present via parent", children.size() == 1); FileWrapper friend = sharee.getByPath(Paths.get(sharer.username)).join().get(); Set<FileWrapper> friendChildren = friend.getChildren(crypto.hasher, sharee.network).join(); Assert.assertEquals(friendChildren.size(), 1); } public static void sharedwithPermutations(NetworkAccess sharerNode, Random rnd) throws Exception { String sharerUsername = randomUsername("sharer-", rnd); String password = "terriblepassword"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(sharerUsername, password, sharerNode, crypto); String shareeUsername = randomUsername("sharee-", rnd); UserContext sharee = PeergosNetworkUtils.ensureSignedUp(shareeUsername, password, sharerNode, crypto); String shareeUsername2 = randomUsername("sharee2-", rnd); UserContext sharee2 = PeergosNetworkUtils.ensureSignedUp(shareeUsername2, password, sharerNode, crypto); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), Arrays.asList(sharee)); friendBetweenGroups(Arrays.asList(sharer), Arrays.asList(sharee2)); // friends are now connected // share a file from u1 to the others FileWrapper u1Root = sharer.getUserRoot().get(); String folderName = "afolder"; u1Root.mkdir(folderName, sharer.network, SymmetricKey.random(), false, crypto).get(); Path p = Paths.get(sharerUsername, folderName); FileSharedWithState result = sharer.sharedWith(p).join(); Assert.assertTrue(result.readAccess.size() == 0 && result.writeAccess.size() == 0); sharer.shareReadAccessWith(p, Collections.singleton(sharee.username)).join(); result = sharer.sharedWith(p).join(); Assert.assertTrue(result.readAccess.size() == 1); sharer.shareWriteAccessWith(p, Collections.singleton(sharee2.username)).join(); result = sharer.sharedWith(p).join(); Assert.assertTrue(result.readAccess.size() == 1 && result.writeAccess.size() == 1); sharer.unShareReadAccess(p, Set.of(sharee.username)).join(); result = sharer.sharedWith(p).join(); Assert.assertTrue(result.readAccess.size() == 0 && result.writeAccess.size() == 1); sharer.unShareWriteAccess(p, Set.of(sharee2.username)).join(); result = sharer.sharedWith(p).join(); Assert.assertTrue(result.readAccess.size() == 0 && result.writeAccess.size() == 0); // now try again, but after adding read, write sharees, remove the write sharee sharer.shareReadAccessWith(p, Collections.singleton(sharee.username)).join(); result = sharer.sharedWith(p).join(); Assert.assertTrue(result.readAccess.size() == 1); sharer.shareWriteAccessWith(p, Collections.singleton(sharee2.username)).join(); result = sharer.sharedWith(p).join(); Assert.assertTrue(result.readAccess.size() == 1 && result.writeAccess.size() == 1); sharer.unShareWriteAccess(p, Set.of(sharee2.username)).join(); result = sharer.sharedWith(p).join(); Assert.assertTrue(result.readAccess.size() == 1 && result.writeAccess.size() == 0); } public static void sharedWriteableAndTruncate(NetworkAccess sharerNode, Random rnd) throws Exception { String sharerUsername = randomUsername("sharer", rnd); String sharerPassword = "sharer1"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(sharerUsername, sharerPassword, sharerNode, crypto); String shareeUsername = randomUsername("sharee", rnd); String shareePassword = "sharee1"; UserContext sharee = PeergosNetworkUtils.ensureSignedUp(shareeUsername, shareePassword, sharerNode, crypto); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), Arrays.asList(sharee)); // friends are now connected // share a file from u1 to the others FileWrapper u1Root = sharer.getUserRoot().get(); String dirName = "afolder"; u1Root.mkdir(dirName, sharer.network, SymmetricKey.random(), false, crypto).get(); Path dirPath = Paths.get(sharerUsername, dirName); FileWrapper dir = sharer.getByPath(dirPath).join().get(); String filename = "somefile.txt"; byte[] originalFileContents = sharer.crypto.random.randomBytes(409); AsyncReader resetableFileInputStream = AsyncReader.build(originalFileContents); FileWrapper uploaded = dir.uploadOrReplaceFile(filename, resetableFileInputStream, originalFileContents.length, sharer.network, crypto, l -> {}, crypto.random.randomBytes(32)).join(); Path filePath = Paths.get(sharerUsername, dirName, filename); FileWrapper file = sharer.getByPath(filePath).join().get(); long originalfileSize = file.getFileProperties().size; System.out.println("filesize=" + originalfileSize); FileWrapper parent = sharer.getByPath(dirPath).join().get(); sharer.shareWriteAccessWith(file, filePath.toString(), parent, Collections.singletonList(sharee.username).toArray(new String[1])).join(); dir = sharer.getByPath(dirPath).join().get(); byte[] updatedFileContents = sharer.crypto.random.randomBytes(255); resetableFileInputStream = AsyncReader.build(updatedFileContents); uploaded = dir.uploadOrReplaceFile(filename, resetableFileInputStream, updatedFileContents.length, sharer.network, crypto, l -> {}, crypto.random.randomBytes(32)).join(); file = sharer.getByPath(filePath).join().get(); long newFileSize = file.getFileProperties().size; System.out.println("filesize=" + newFileSize); Assert.assertTrue(newFileSize == 255); //sharee now attempts to modify file FileWrapper sharedFile = sharee.getByPath(filePath).join().get(); byte[] modifiedFileContents = sharer.crypto.random.randomBytes(255); sharedFile.overwriteFileJS(AsyncReader.build(modifiedFileContents), 0, modifiedFileContents.length, sharee.network, sharee.crypto, len -> {}).join(); FileWrapper sharedFileUpdated = sharee.getByPath(filePath).join().get(); checkFileContents(modifiedFileContents, sharedFileUpdated, sharee); } public static void renameSharedwithFolder(NetworkAccess sharerNode, Random rnd) throws Exception { String sharerUsername = randomUsername("sharer-", rnd); String password = "terriblepassword"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(sharerUsername, password, sharerNode, crypto); String shareeUsername = randomUsername("sharee-", rnd); UserContext sharee = PeergosNetworkUtils.ensureSignedUp(shareeUsername, password, sharerNode, crypto); friendBetweenGroups(Arrays.asList(sharer), Arrays.asList(sharee)); FileWrapper u1Root = sharer.getUserRoot().get(); String folderName = "afolder"; u1Root.mkdir(folderName, sharer.network, SymmetricKey.random(), false, crypto).get(); Path p = Paths.get(sharerUsername, folderName); sharer.shareReadAccessWith(p, Set.of(shareeUsername)).join(); FileSharedWithState result = sharer.sharedWith(p).join(); Assert.assertTrue(result.readAccess.size() == 1); u1Root = sharer.getUserRoot().get(); FileWrapper file = sharer.getByPath(p).join().get(); String renamedFolderName= "renamed"; file.rename(renamedFolderName, u1Root, p, sharer).join(); p = Paths.get(sharerUsername, renamedFolderName); sharer.unShareReadAccess(p, Set.of(sharee.username)).join(); result = sharer.sharedWith(p).join(); Assert.assertTrue(result.readAccess.size() == 0 && result.writeAccess.size() == 0); } public static void grantAndRevokeDirReadAccess(NetworkAccess sharerNode, NetworkAccess shareeNode, int shareeCount, Random random) throws Exception { Assert.assertTrue(0 < shareeCount); CryptreeNode.setMaxChildLinkPerBlob(10); String sharerUsername = generateUsername(random); String sharerPassword = generatePassword(); UserContext sharer = PeergosNetworkUtils.ensureSignedUp(sharerUsername, sharerPassword, sharerNode, crypto); List<String> shareePasswords = IntStream.range(0, shareeCount) .mapToObj(i -> generatePassword()) .collect(Collectors.toList()); List<UserContext> shareeUsers = getUserContextsForNode(shareeNode, random, shareeCount, shareePasswords); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); // friends are now connected // share a file from u1 to the others FileWrapper u1Root = sharer.getUserRoot().get(); String folderName = "afolder"; u1Root.mkdir(folderName, sharer.network, SymmetricKey.random(), false, crypto).get(); String path = Paths.get(sharerUsername, folderName).toString(); System.out.println("PATH "+ path); FileWrapper folder = sharer.getByPath(path).get().get(); String filename = "somefile.txt"; byte[] originalFileContents = "Hello Peergos friend!".getBytes(); AsyncReader resetableFileInputStream = new AsyncReader.ArrayBacked(originalFileContents); FileWrapper updatedFolder = folder.uploadOrReplaceFile(filename, resetableFileInputStream, originalFileContents.length, sharer.network, crypto, l -> {},crypto.random.randomBytes(32)).get(); String originalFilePath = sharer.username + "/" + folderName + "/" + filename; for (int i=0; i< 20; i++) { sharer.getByPath(path).join().get() .mkdir("subdir"+i, sharer.network, false, crypto).join(); } Set<String> childNames = sharer.getByPath(path).join().get().getChildren(crypto.hasher, sharer.network).join() .stream() .map(f -> f.getName()) .collect(Collectors.toSet()); // file is uploaded, do the actual sharing boolean finished = sharer.shareReadAccessWithAll(updatedFolder, Paths.get(path), shareeUsers.stream() .map(c -> c.username) .collect(Collectors.toSet())).get(); // check each user can see the shared folder and directory for (UserContext sharee : shareeUsers) { // test retrieval via getChildren() which is used by the web-ui Set<FileWrapper> children = sharee.getByPath(sharer.username).join().get() .getChildren(crypto.hasher, sharee.network).join(); Assert.assertTrue(children.stream() .filter(f -> f.getName().equals(folderName)) .findAny() .isPresent()); FileWrapper sharedFolder = sharee.getByPath(sharer.username + "/" + folderName).get().orElseThrow(() -> new AssertionError("shared folder is present after sharing")); Assert.assertEquals(sharedFolder.getFileProperties().name, folderName); FileWrapper sharedFile = sharee.getByPath(sharer.username + "/" + folderName + "/" + filename).get().get(); checkFileContents(originalFileContents, sharedFile, sharee); } UserContext updatedSharer = PeergosNetworkUtils.ensureSignedUp(sharerUsername, sharerPassword, sharerNode.clear(), crypto); List<UserContext> updatedSharees = shareeUsers.stream() .map(e -> { try { return ensureSignedUp(e.username, shareePasswords.get(shareeUsers.indexOf(e)), e.network, crypto); } catch (Exception ex) { throw new IllegalStateException(ex.getMessage(), ex); } }).collect(Collectors.toList()); for (int i = 0; i < updatedSharees.size(); i++) { UserContext user = updatedSharees.get(i); updatedSharer.unShareReadAccess(Paths.get(updatedSharer.username, folderName), user.username).get(); Optional<FileWrapper> updatedSharedFolder = user.getByPath(updatedSharer.username + "/" + folderName).get(); // test that u1 can still access the original file, and user cannot Optional<FileWrapper> fileWithNewBaseKey = updatedSharer.getByPath(updatedSharer.username + "/" + folderName + "/" + filename).get(); Assert.assertTrue(!updatedSharedFolder.isPresent()); Assert.assertTrue(fileWithNewBaseKey.isPresent()); // Now modify the file byte[] suffix = "Some new data at the end".getBytes(); AsyncReader suffixStream = new AsyncReader.ArrayBacked(suffix); FileWrapper parent = updatedSharer.getByPath(updatedSharer.username + "/" + folderName).get().get(); parent.uploadFileSection(filename, suffixStream, false, originalFileContents.length, originalFileContents.length + suffix.length, Optional.empty(), true, updatedSharer.network, crypto, l -> {}, null).get(); FileWrapper extendedFile = updatedSharer.getByPath(originalFilePath).get().get(); AsyncReader extendedContents = extendedFile.getInputStream(updatedSharer.network, crypto, l -> {}).get(); byte[] newFileContents = Serialize.readFully(extendedContents, extendedFile.getSize()).get(); Assert.assertTrue(Arrays.equals(newFileContents, ArrayOps.concat(originalFileContents, suffix))); // test remaining users can still see shared file and folder for (int j = i + 1; j < updatedSharees.size(); j++) { UserContext otherUser = updatedSharees.get(j); Optional<FileWrapper> sharedFolder = otherUser.getByPath(updatedSharer.username + "/" + folderName).get(); Assert.assertTrue("Shared folder present via direct path", sharedFolder.isPresent() && sharedFolder.get().getName().equals(folderName)); FileWrapper sharedFile = otherUser.getByPath(updatedSharer.username + "/" + folderName + "/" + filename).get().get(); checkFileContents(newFileContents, sharedFile, otherUser); Set<String> sharedChildNames = sharedFolder.get().getChildren(crypto.hasher, otherUser.network).join() .stream() .map(f -> f.getName()) .collect(Collectors.toSet()); Assert.assertTrue("Correct children", sharedChildNames.equals(childNames)); } } } public static void grantAndRevokeDirWriteAccess(NetworkAccess sharerNode, NetworkAccess shareeNode, int shareeCount, Random random) throws Exception { Assert.assertTrue(0 < shareeCount); CryptreeNode.setMaxChildLinkPerBlob(10); String sharerUsername = generateUsername(random); String sharerPassword = generatePassword(); UserContext sharer = PeergosNetworkUtils.ensureSignedUp(sharerUsername, sharerPassword, sharerNode, crypto); List<String> shareePasswords = IntStream.range(0, shareeCount) .mapToObj(i -> generatePassword()) .collect(Collectors.toList()); List<UserContext> shareeUsers = getUserContextsForNode(shareeNode, random, shareeCount, shareePasswords); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); // friends are now connected // share a file from u1 to the others FileWrapper u1Root = sharer.getUserRoot().join(); String folderName = "afolder"; u1Root.mkdir(folderName, sharer.network, SymmetricKey.random(), false, crypto).get(); String path = Paths.get(sharerUsername, folderName).toString(); System.out.println("PATH "+ path); FileWrapper folder = sharer.getByPath(path).join().get(); String filename = "somefile.txt"; byte[] originalFileContents = "Hello Peergos friend!".getBytes(); AsyncReader resetableFileInputStream = new AsyncReader.ArrayBacked(originalFileContents); folder.uploadOrReplaceFile(filename, resetableFileInputStream, originalFileContents.length, sharer.network, crypto, l -> {}, crypto.random.randomBytes(32)).join(); String originalFilePath = sharer.username + "/" + folderName + "/" + filename; for (int i=0; i< 20; i++) { sharer.getByPath(path).join().get() .mkdir("subdir"+i, sharer.network, false, crypto).join(); } // file is uploaded, do the actual sharing boolean finished = sharer.shareWriteAccessWithAll(sharer.getByPath(path).join().get(), Paths.get(path), sharer.getUserRoot().join(), shareeUsers.stream() .map(c -> c.username) .collect(Collectors.toSet())).get(); // upload a image String imagename = "small.png"; byte[] data = Files.readAllBytes(Paths.get("assets", "logo.png")); FileWrapper sharedFolderv0 = sharer.getByPath(path).join().get(); sharedFolderv0.uploadOrReplaceFile(imagename, AsyncReader.build(data), data.length, sharer.network, crypto, x -> {}, crypto.random.randomBytes(32)).join(); // create a directory FileWrapper sharedFolderv1 = sharer.getByPath(path).join().get(); sharedFolderv1.mkdir("asubdir", sharer.network, false, crypto).join(); UserContext shareeUploader = shareeUsers.get(0); // check sharee can see folder via getChildren() which is used by the web-ui Set<FileWrapper> children = shareeUploader.getByPath(sharer.username).join().get() .getChildren(crypto.hasher, shareeUploader.network).join(); Assert.assertTrue(children.stream() .filter(f -> f.getName().equals(folderName)) .findAny() .isPresent()); // check a sharee can upload a file FileWrapper sharedDir = shareeUploader.getByPath(path).join().get(); sharedDir.uploadFileJS("a-new-file.png", AsyncReader.build(data), 0, data.length, false, false, shareeUploader.network, crypto, x -> {}, shareeUploader.getTransactionService()).join(); Set<String> childNames = sharer.getByPath(path).join().get().getChildren(crypto.hasher, sharer.network).join() .stream() .map(f -> f.getName()) .collect(Collectors.toSet()); // check each user can see the shared folder and directory for (UserContext sharee : shareeUsers) { FileWrapper sharedFolder = sharee.getByPath(sharer.username + "/" + folderName).get().orElseThrow(() -> new AssertionError("shared folder is present after sharing")); Assert.assertEquals(sharedFolder.getFileProperties().name, folderName); FileWrapper sharedFile = sharee.getByPath(sharer.username + "/" + folderName + "/" + filename).get().get(); checkFileContents(originalFileContents, sharedFile, sharee); Set<String> sharedChildNames = sharedFolder.getChildren(crypto.hasher, sharee.network).join() .stream() .map(f -> f.getName()) .collect(Collectors.toSet()); Assert.assertTrue("Correct children", sharedChildNames.equals(childNames)); } MultiUserTests.checkUserValidity(sharerNode, sharerUsername); UserContext updatedSharer = PeergosNetworkUtils.ensureSignedUp(sharerUsername, sharerPassword, sharerNode.clear(), crypto); List<UserContext> updatedSharees = shareeUsers.stream() .map(e -> { try { return ensureSignedUp(e.username, shareePasswords.get(shareeUsers.indexOf(e)), e.network, crypto); } catch (Exception ex) { throw new IllegalStateException(ex.getMessage(), ex); } }).collect(Collectors.toList()); for (int i = 0; i < updatedSharees.size(); i++) { UserContext user = updatedSharees.get(i); updatedSharer.unShareWriteAccess(Paths.get(updatedSharer.username, folderName), user.username).get(); Optional<FileWrapper> updatedSharedFolder = user.getByPath(updatedSharer.username + "/" + folderName).get(); // test that u1 can still access the original file, and user cannot Optional<FileWrapper> fileWithNewBaseKey = updatedSharer.getByPath(updatedSharer.username + "/" + folderName + "/" + filename).get(); Assert.assertTrue(!updatedSharedFolder.isPresent()); Assert.assertTrue(fileWithNewBaseKey.isPresent()); // Now modify the file byte[] suffix = "Some new data at the end".getBytes(); AsyncReader suffixStream = new AsyncReader.ArrayBacked(suffix); FileWrapper parent = updatedSharer.getByPath(updatedSharer.username + "/" + folderName).get().get(); parent.uploadFileSection(filename, suffixStream, false, originalFileContents.length, originalFileContents.length + suffix.length, Optional.empty(), true, updatedSharer.network, crypto, l -> {}, null).get(); FileWrapper extendedFile = updatedSharer.getByPath(originalFilePath).get().get(); AsyncReader extendedContents = extendedFile.getInputStream(updatedSharer.network, updatedSharer.crypto, l -> { }).get(); byte[] newFileContents = Serialize.readFully(extendedContents, extendedFile.getSize()).get(); Assert.assertTrue(Arrays.equals(newFileContents, ArrayOps.concat(originalFileContents, suffix))); // test remaining users can still see shared file and folder for (int j = i + 1; j < updatedSharees.size(); j++) { UserContext otherUser = updatedSharees.get(j); Optional<FileWrapper> sharedFolder = otherUser.getByPath(updatedSharer.username + "/" + folderName).get(); Assert.assertTrue("Shared folder present via direct path", sharedFolder.isPresent() && sharedFolder.get().getName().equals(folderName)); FileWrapper sharedFile = otherUser.getByPath(updatedSharer.username + "/" + folderName + "/" + filename).get().get(); checkFileContents(newFileContents, sharedFile, otherUser); Set<String> sharedChildNames = sharedFolder.get().getChildren(crypto.hasher, otherUser.network).join() .stream() .map(f -> f.getName()) .collect(Collectors.toSet()); Assert.assertTrue("Correct children", sharedChildNames.equals(childNames)); } } MultiUserTests.checkUserValidity(sharerNode, sharerUsername); } public static void grantAndRevokeNestedDirWriteAccess(NetworkAccess network, Random random) { CryptreeNode.setMaxChildLinkPerBlob(10); String password = "notagoodone"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(generateUsername(random), password, network, crypto); List<UserContext> shareeUsers = getUserContextsForNode(network, random, 2, Arrays.asList(password, password)); UserContext a = shareeUsers.get(0); UserContext b = shareeUsers.get(1); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); // friends are now connected // share a directory from u1 to u2 FileWrapper u1Root = sharer.getUserRoot().join(); String folderName = "folder"; u1Root.mkdir(folderName, sharer.network, SymmetricKey.random(), false, crypto).join(); Path dirPath = Paths.get(sharer.username, folderName); FileWrapper folder = sharer.getByPath(dirPath).join().get(); String filename = "somefile.txt"; byte[] data = "Hello Peergos friend!".getBytes(); AsyncReader resetableFileInputStream = new AsyncReader.ArrayBacked(data); folder.uploadOrReplaceFile(filename, resetableFileInputStream, data.length, sharer.network, crypto, l -> {}, crypto.random.randomBytes(32)).join(); String originalFilePath = sharer.username + "/" + folderName + "/" + filename; for (int i=0; i< 20; i++) { sharer.getByPath(dirPath).join().get() .mkdir("subdir"+i, sharer.network, false, crypto).join(); } // share /u1/folder with 'a' sharer.shareWriteAccessWithAll(sharer.getByPath(dirPath).join().get(), dirPath, sharer.getUserRoot().join(), Collections.singleton(a.username)).join(); // create a directory FileWrapper sharedFolderv1 = sharer.getByPath(dirPath).join().get(); String subdirName = "subdir"; sharedFolderv1.mkdir(subdirName, sharer.network, false, crypto).join(); // share /u1/folder with 'b' Path subdirPath = Paths.get(sharer.username, folderName, subdirName); sharer.shareWriteAccessWithAll(sharer.getByPath(subdirPath).join().get(), subdirPath, sharer.getByPath(dirPath).join().get(), Collections.singleton(b.username)).join(); // check 'b' can upload a file UserContext shareeUploader = shareeUsers.get(0); FileWrapper sharedDir = shareeUploader.getByPath(subdirPath).join().get(); sharedDir.uploadFileJS("a-new-file.png", AsyncReader.build(data), 0, data.length, false, false, shareeUploader.network, crypto, x -> {}, shareeUploader.getTransactionService()).join(); Set<String> childNames = sharer.getByPath(dirPath).join().get().getChildren(crypto.hasher, sharer.network).join() .stream() .map(f -> f.getName()) .collect(Collectors.toSet()); // check 'a' can see the shared directory FileWrapper sharedFolder = a.getByPath(sharer.username + "/" + folderName).join() .orElseThrow(() -> new AssertionError("shared folder is present after sharing")); Assert.assertEquals(sharedFolder.getFileProperties().name, folderName); FileWrapper sharedFile = a.getByPath(sharer.username + "/" + folderName + "/" + filename).join().get(); checkFileContents(data, sharedFile, a); Set<String> sharedChildNames = sharedFolder.getChildren(crypto.hasher, a.network).join() .stream() .map(f -> f.getName()) .collect(Collectors.toSet()); Assert.assertTrue("Correct children", sharedChildNames.equals(childNames)); MultiUserTests.checkUserValidity(network, sharer.username); UserContext updatedSharer = PeergosNetworkUtils.ensureSignedUp(sharer.username, password, network.clear(), crypto); List<UserContext> updatedSharees = shareeUsers.stream() .map(e -> { try { return ensureSignedUp(e.username, password, e.network, crypto); } catch (Exception ex) { throw new IllegalStateException(ex.getMessage(), ex); } }).collect(Collectors.toList()); // unshare subdir from 'b' UserContext user = updatedSharees.get(1); updatedSharer.unShareWriteAccess(subdirPath, b.username).join(); Optional<FileWrapper> updatedSharedFolder = user.getByPath(updatedSharer.username + "/" + folderName).join(); // test that u1 can still access the original file, and user cannot Optional<FileWrapper> fileWithNewBaseKey = updatedSharer.getByPath(updatedSharer.username + "/" + folderName + "/" + filename).join(); Assert.assertTrue(!updatedSharedFolder.isPresent()); Assert.assertTrue(fileWithNewBaseKey.isPresent()); // Now modify the file byte[] suffix = "Some new data at the end".getBytes(); AsyncReader suffixStream = new AsyncReader.ArrayBacked(suffix); FileWrapper parent = updatedSharer.getByPath(updatedSharer.username + "/" + folderName).join().get(); parent.uploadFileSection(filename, suffixStream, false, data.length, data.length + suffix.length, Optional.empty(), true, updatedSharer.network, crypto, l -> {}, null).join(); FileWrapper extendedFile = updatedSharer.getByPath(originalFilePath).join().get(); AsyncReader extendedContents = extendedFile.getInputStream(updatedSharer.network, updatedSharer.crypto, l -> {}).join(); byte[] newFileContents = Serialize.readFully(extendedContents, extendedFile.getSize()).join(); Assert.assertTrue(Arrays.equals(newFileContents, ArrayOps.concat(data, suffix))); // test 'a' can still see shared file and folder UserContext otherUser = updatedSharees.get(0); Optional<FileWrapper> folderAgain = otherUser.getByPath(updatedSharer.username + "/" + folderName).join(); Assert.assertTrue("Shared folder present via direct path", folderAgain.isPresent() && folderAgain.get().getName().equals(folderName)); FileWrapper sharedFileAgain = otherUser.getByPath(updatedSharer.username + "/" + folderName + "/" + filename).join().get(); checkFileContents(newFileContents, sharedFileAgain, otherUser); Set<String> childNamesAgain = folderAgain.get().getChildren(crypto.hasher, otherUser.network).join() .stream() .map(f -> f.getName()) .collect(Collectors.toSet()); Assert.assertTrue("Correct children", childNamesAgain.equals(childNames)); MultiUserTests.checkUserValidity(network, sharer.username); } public static void grantAndRevokeParentNestedWriteAccess(NetworkAccess network, Random random) { CryptreeNode.setMaxChildLinkPerBlob(10); String password = "notagoodone"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(generateUsername(random), password, network, crypto); List<UserContext> shareeUsers = getUserContextsForNode(network, random, 2, Arrays.asList(password, password)); UserContext a = shareeUsers.get(0); UserContext b = shareeUsers.get(1); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); // friends are now connected // share a directory from u1 to u2 FileWrapper u1Root = sharer.getUserRoot().join(); String folderName = "folder"; u1Root.mkdir(folderName, sharer.network, SymmetricKey.random(), false, crypto).join(); Path dirPath = Paths.get(sharer.username, folderName); // create a directory String subdirName = "subdir"; sharer.getByPath(dirPath).join().get() .mkdir(subdirName, sharer.network, false, crypto).join(); // share /u1/folder/subdir with 'b' Path subdirPath = Paths.get(sharer.username, folderName, subdirName); sharer.shareWriteAccessWithAll(sharer.getByPath(subdirPath).join().get(), subdirPath, sharer.getByPath(dirPath).join().get(), Collections.singleton(b.username)).join(); // share /u1/folder with 'a' sharer.shareWriteAccessWithAll(sharer.getByPath(dirPath).join().get(), dirPath, sharer.getUserRoot().join(), Collections.singleton(a.username)).join(); // check sharer can still see /u1/folder/subdir Assert.assertTrue("subdir still present", sharer.getByPath(subdirPath).join().isPresent()); // check 'a' can see the shared directory FileWrapper sharedFolder = a.getByPath(sharer.username + "/" + folderName).join() .orElseThrow(() -> new AssertionError("shared folder is present after sharing")); Assert.assertEquals(sharedFolder.getFileProperties().name, folderName); // revoke access to /u1/folder from 'a' sharer.unShareWriteAccess(dirPath, a.username).join(); // check 'a' can't see the shared directory Optional<FileWrapper> unsharedFolder = a.getByPath(sharer.username + "/" + folderName).join(); Assert.assertTrue("a can't see unshared folder", ! unsharedFolder.isPresent()); } public static void grantAndRevokeReadAccessToFileInFolder(NetworkAccess network, Random random) throws IOException { CryptreeNode.setMaxChildLinkPerBlob(10); String password = "notagoodone"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(generateUsername(random), password, network, crypto); List<UserContext> shareeUsers = getUserContextsForNode(network, random, 1, Arrays.asList(password, password)); UserContext a = shareeUsers.get(0); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); // friends are now connected // share a directory from u1 to u2 FileWrapper u1Root = sharer.getUserRoot().join(); String folderName = "folder"; u1Root.mkdir(folderName, sharer.network, SymmetricKey.random(), false, crypto).join(); Path dirPath = Paths.get(sharer.username, folderName); String filename = "somefile.txt"; File f = File.createTempFile("peergos", ""); byte[] originalFileContents = sharer.crypto.random.randomBytes(1*1024*1024); Files.write(f.toPath(), originalFileContents); ResetableFileInputStream resetableFileInputStream = new ResetableFileInputStream(f); FileWrapper dir = sharer.getByPath(dirPath).join().get(); FileWrapper uploaded = dir.uploadOrReplaceFile(filename, resetableFileInputStream, f.length(), sharer.network, crypto, l -> {}, crypto.random.randomBytes(32)).join(); Path fileToShare = Paths.get(sharer.username, folderName, filename); sharer.shareReadAccessWithAll(sharer.getByPath(fileToShare).join().get(), fileToShare , Collections.singleton(a.username)).join(); // check 'a' can see the shared file FileWrapper sharedFolder = a.getByPath(sharer.username + "/" + folderName + "/" + filename).join() .orElseThrow(() -> new AssertionError("shared folder is present after sharing")); Assert.assertEquals(sharedFolder.getFileProperties().name, filename); sharer.unShareReadAccess(fileToShare, a.username).join(); // check 'a' can't see the shared directory FileWrapper unsharedLocation = a.getByPath(sharer.username).join().get(); Set<FileWrapper> children = unsharedLocation.getChildren(crypto.hasher, sharer.network).join(); Assert.assertTrue("a can't see unshared folder", children.isEmpty()); } public static void grantAndRevokeWriteThenReadAccessToFolder(NetworkAccess network, Random random) throws IOException { CryptreeNode.setMaxChildLinkPerBlob(10); String password = "notagoodone"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(generateUsername(random), password, network, crypto); List<UserContext> shareeUsers = getUserContextsForNode(network, random, 1, Arrays.asList(password, password)); UserContext a = shareeUsers.get(0); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); // friends are now connected // share a directory from u1 to u2 FileWrapper u1Root = sharer.getUserRoot().join(); String folderName = "folder"; u1Root.mkdir(folderName, sharer.network, SymmetricKey.random(), false, crypto).join(); Path dirPath = Paths.get(sharer.username, folderName); // share /u1/folder with 'a' sharer.shareWriteAccessWithAll(sharer.getByPath(dirPath).join().get(), dirPath, sharer.getUserRoot().join(), Collections.singleton(a.username)).join(); // check 'a' can see the shared file FileWrapper sharedFolder = a.getByPath(sharer.username + "/" + folderName).join() .orElseThrow(() -> new AssertionError("shared folder is present after sharing")); Assert.assertEquals(sharedFolder.getFileProperties().name, folderName); sharer.unShareWriteAccess(dirPath, a.username).join(); // check 'a' can't see the shared directory FileWrapper unsharedLocation = a.getByPath(sharer.username).join().get(); Set<FileWrapper> children = unsharedLocation.getChildren(crypto.hasher, sharer.network).join(); Assert.assertTrue("a can't see unshared folder", children.isEmpty()); sharer.shareReadAccessWithAll(sharer.getByPath(dirPath).join().get(), dirPath , Collections.singleton(a.username)).join(); // check 'a' can see the shared file sharedFolder = a.getByPath(sharer.username + "/" + folderName).join() .orElseThrow(() -> new AssertionError("shared folder is present after sharing")); Assert.assertEquals(sharedFolder.getFileProperties().name, folderName); sharer.unShareReadAccess(dirPath, a.username).join(); // check 'a' can't see the shared directory unsharedLocation = a.getByPath(sharer.username).join().get(); children = unsharedLocation.getChildren(crypto.hasher, sharer.network).join(); Assert.assertTrue("a can't see unshared folder", children.isEmpty()); } public static void grantAndRevokeDirWriteAccessWithNestedWriteAccess(NetworkAccess network, Random random) { CryptreeNode.setMaxChildLinkPerBlob(10); String password = "notagoodone"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(generateUsername(random), password, network, crypto); List<UserContext> shareeUsers = getUserContextsForNode(network, random, 2, Arrays.asList(password, password)); UserContext a = shareeUsers.get(0); UserContext b = shareeUsers.get(1); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); // friends are now connected FileWrapper u1Root = sharer.getUserRoot().join(); String folderName = "folder"; u1Root.mkdir(folderName, sharer.network, SymmetricKey.random(), false, crypto).join(); Path dirPath = Paths.get(sharer.username, folderName); // put a file and some sub-dirs into the dir FileWrapper folder = sharer.getByPath(dirPath).join().get(); String filename = "somefile.txt"; byte[] data = "Hello Peergos friend!".getBytes(); AsyncReader resetableFileInputStream = new AsyncReader.ArrayBacked(data); folder.uploadOrReplaceFile(filename, resetableFileInputStream, data.length, sharer.network, crypto, l -> {}, crypto.random.randomBytes(32)).join(); for (int i=0; i< 20; i++) { sharer.getByPath(dirPath).join().get() .mkdir("subdir"+i, sharer.network, false, crypto).join(); } // grant write access to a directory to user 'a' sharer.shareWriteAccessWithAll(sharer.getByPath(dirPath).join().get(), dirPath, sharer.getUserRoot().join(), Collections.singleton(a.username)).join(); // create another sub-directory FileWrapper sharedFolderv1 = sharer.getByPath(dirPath).join().get(); String subdirName = "subdir"; sharedFolderv1.mkdir(subdirName, sharer.network, false, crypto).join(); // grant write access to a sub-directory to user 'b' Path subdirPath = Paths.get(sharer.username, folderName, subdirName); sharer.shareWriteAccessWithAll(sharer.getByPath(subdirPath).join().get(), subdirPath, sharer.getByPath(dirPath).join().get(), Collections.singleton(b.username)).join(); List<Set<AbsoluteCapability>> childCapsByChunk0 = getAllChildCapsByChunk(sharer.getByPath(dirPath).join().get(), network); Assert.assertTrue("Correct links per chunk, without duplicates", childCapsByChunk0.stream().map(x -> x.size()).collect(Collectors.toList()) .equals(Arrays.asList(10, 10, 2))); // check 'b' can upload a file UserContext shareeUploader = shareeUsers.get(0); FileWrapper sharedDir = shareeUploader.getByPath(subdirPath).join().get(); sharedDir.uploadFileJS("a-new-file.png", AsyncReader.build(data), 0, data.length, false, false, shareeUploader.network, crypto, x -> {}, shareeUploader.getTransactionService()).join(); // check 'a' can see the shared directory FileWrapper sharedFolder = a.getByPath(sharer.username + "/" + folderName).join() .orElseThrow(() -> new AssertionError("shared folder is present after sharing")); Assert.assertEquals(sharedFolder.getFileProperties().name, folderName); FileWrapper sharedFile = a.getByPath(sharer.username + "/" + folderName + "/" + filename).join().get(); checkFileContents(data, sharedFile, a); Set<String> sharedChildNames = sharedFolder.getChildren(crypto.hasher, a.network).join() .stream() .map(f -> f.getName()) .collect(Collectors.toSet()); Set<String> childNames = sharer.getByPath(dirPath).join().get().getChildren(crypto.hasher, sharer.network).join() .stream() .map(f -> f.getName()) .collect(Collectors.toSet()); Assert.assertTrue("Correct children", sharedChildNames.equals(childNames)); MultiUserTests.checkUserValidity(network, sharer.username); Set<AbsoluteCapability> childCaps = getAllChildCaps(sharer.getByPath(dirPath).join().get(), network); Assert.assertTrue("Correct number of child caps on dir", childCaps.size() == 22); UserContext updatedSharer = PeergosNetworkUtils.ensureSignedUp(sharer.username, password, network.clear(), crypto); List<UserContext> updatedSharees = shareeUsers.stream() .map(e -> { try { return ensureSignedUp(e.username, password, e.network, crypto); } catch (Exception ex) { throw new IllegalStateException(ex.getMessage(), ex); } }).collect(Collectors.toList()); // revoke write access to top level dir from 'a' UserContext user = updatedSharees.get(0); List<Set<AbsoluteCapability>> childCapsByChunk1 = getAllChildCapsByChunk(updatedSharer.getByPath(dirPath).join().get(), network); Assert.assertTrue("Correct links per chunk, without duplicates", childCapsByChunk1.stream().map(x -> x.size()).collect(Collectors.toList()) .equals(Arrays.asList(10, 10, 2))); updatedSharer.unShareWriteAccess(dirPath, a.username).join(); List<Set<AbsoluteCapability>> childCapsByChunk2 = getAllChildCapsByChunk(sharer.getByPath(dirPath).join().get(), network); Assert.assertTrue("Correct links per chunk, without duplicates", childCapsByChunk2.stream().map(x -> x.size()).collect(Collectors.toList()) .equals(Arrays.asList(10, 10, 2))); Optional<FileWrapper> updatedSharedFolder = user.getByPath(dirPath).join(); // test that sharer can still access the sub-dir, and 'a' cannot access the top level dir Optional<FileWrapper> updatedSubdir = updatedSharer.getByPath(subdirPath).join(); Assert.assertTrue(! updatedSharedFolder.isPresent()); Assert.assertTrue(updatedSubdir.isPresent()); // test 'b' can still see shared sub-dir UserContext otherUser = updatedSharees.get(1); Optional<FileWrapper> subdirAgain = otherUser.getByPath(subdirPath).join(); Assert.assertTrue("Shared folder present via direct path", subdirAgain.isPresent()); MultiUserTests.checkUserValidity(network, sharer.username); } public static void socialFeed(NetworkAccess network, Random random) { CryptreeNode.setMaxChildLinkPerBlob(10); String password = "notagoodone"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(generateUsername(random), password, network, crypto); List<UserContext> shareeUsers = getUserContextsForNode(network, random, 1, Arrays.asList(password, password)); UserContext a = shareeUsers.get(0); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); // friends are now connected // share a file from u1 to u2 FileWrapper u1Root = sharer.getUserRoot().join(); String filename = "somefile.txt"; byte[] fileData = sharer.crypto.random.randomBytes(1*1024*1024); Path file1 = Paths.get(sharer.username, "first-file.txt"); uploadAndShare(fileData, file1, sharer, a.username); // check 'a' can see the shared file in their social feed SocialFeed feed = a.getSocialFeed().join(); List<SharedItem> items = feed.getShared(0, 1, a.crypto, a.network).join(); Assert.assertTrue(items.size() > 0); SharedItem item = items.get(0); Assert.assertTrue(item.owner.equals(sharer.username)); Assert.assertTrue(item.sharer.equals(sharer.username)); AbsoluteCapability readCap = sharer.getByPath(file1).join().get().getPointer().capability.readOnly(); Assert.assertTrue(item.cap.equals(readCap)); Assert.assertTrue(item.path.equals("/" + file1.toString())); // Test the feed after a fresh login UserContext freshA = PeergosNetworkUtils.ensureSignedUp(a.username, password, network, crypto); SocialFeed freshFeed = freshA.getSocialFeed().join(); List<SharedItem> freshItems = freshFeed.getShared(0, 1, a.crypto, a.network).join(); Assert.assertTrue(freshItems.size() > 0); SharedItem freshItem = freshItems.get(0); Assert.assertTrue(freshItem.equals(item)); // Test sharing a new item after construction Path file2 = Paths.get(sharer.username, "second-file.txt"); uploadAndShare(fileData, file2, sharer, a.username); SocialFeed updatedFeed = freshFeed.update().join(); List<SharedItem> items2 = updatedFeed.getShared(1, 2, a.crypto, a.network).join(); Assert.assertTrue(items2.size() > 0); SharedItem item2 = items2.get(0); Assert.assertTrue(item2.owner.equals(sharer.username)); Assert.assertTrue(item2.sharer.equals(sharer.username)); AbsoluteCapability readCap2 = sharer.getByPath(file2).join().get().getPointer().capability.readOnly(); Assert.assertTrue(item2.cap.equals(readCap2)); // check accessing the files normally UserContext fresherA = PeergosNetworkUtils.ensureSignedUp(a.username, password, network, crypto); Optional<FileWrapper> directFile1 = fresherA.getByPath(file1).join(); Assert.assertTrue(directFile1.isPresent()); Optional<FileWrapper> directFile2 = fresherA.getByPath(file2).join(); Assert.assertTrue(directFile2.isPresent()); // check feed after browsing to the senders home Path file3 = Paths.get(sharer.username, "third-file.txt"); uploadAndShare(fileData, file3, sharer, a.username); // browse to sender home freshA.getByPath(Paths.get(sharer.username)).join(); Path file4 = Paths.get(sharer.username, "fourth-file.txt"); uploadAndShare(fileData, file4, sharer, a.username); // now check feed SocialFeed updatedFeed3 = freshFeed.update().join(); List<SharedItem> items3 = updatedFeed3.getShared(2, 3, a.crypto, a.network).join(); Assert.assertTrue(items3.size() > 0); SharedItem item3 = items3.get(0); Assert.assertTrue(item3.owner.equals(sharer.username)); Assert.assertTrue(item3.sharer.equals(sharer.username)); AbsoluteCapability readCap3 = sharer.getByPath(file3).join().get().getPointer().capability.readOnly(); Assert.assertTrue(item3.cap.equals(readCap3)); } private static void uploadAndShare(byte[] data, Path file, UserContext sharer, String sharee) { String filename = file.getFileName().toString(); sharer.getByPath(file.getParent()).join().get() .uploadOrReplaceFile(filename, AsyncReader.build(data), data.length, sharer.network, crypto, l -> {}, crypto.random.randomBytes(32)).join(); sharer.shareReadAccessWithAll(sharer.getByPath(file).join().get(), file, Set.of(sharee)).join(); } public static void socialFeedVariations2(NetworkAccess network, Random random) { CryptreeNode.setMaxChildLinkPerBlob(10); String password = "notagoodone"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(generateUsername(random), password, network, crypto); List<UserContext> shareeUsers = getUserContextsForNode(network, random, 1, Arrays.asList(password, password)); UserContext sharee = shareeUsers.get(0); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); String dir1 = "one"; String dir2 = "two"; sharer.getUserRoot().join().mkdir(dir1, sharer.network, false, sharer.crypto).join(); sharer.getUserRoot().join().mkdir(dir2, sharer.network, false, sharer.crypto).join(); Path dirToShare1 = Paths.get(sharer.username, dir1); Path dirToShare2 = Paths.get(sharer.username, dir2); sharer.shareReadAccessWithAll(sharer.getByPath(dirToShare1).join().get(), dirToShare1, Set.of(sharee.username)).join(); sharer.shareReadAccessWithAll(sharer.getByPath(dirToShare2).join().get(), dirToShare2, Set.of(sharee.username)).join(); SocialFeed feed = sharee.getSocialFeed().join(); List<SharedItem> items = feed.getShared(0, 1000, sharee.crypto, sharee.network).join(); Assert.assertTrue(items.size() == 2); sharee.getUserRoot().join().mkdir("mine", sharee.network, false, sharer.crypto).join(); } public static void socialFeedFailsInUI(NetworkAccess network, Random random) { CryptreeNode.setMaxChildLinkPerBlob(10); String password = "notagoodone"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(generateUsername(random), password, network, crypto); List<UserContext> shareeUsers = getUserContextsForNode(network, random, 1, Arrays.asList(password, password)); UserContext sharee = shareeUsers.get(0); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); String dir1 = "one"; String dir2 = "two"; sharer.getUserRoot().join().mkdir(dir1, sharer.network, false, sharer.crypto).join(); sharer.getUserRoot().join().mkdir(dir2, sharer.network, false, sharer.crypto).join(); Path dirToShare1 = Paths.get(sharer.username, dir1); Path dirToShare2 = Paths.get(sharer.username, dir2); sharer.shareReadAccessWithAll(sharer.getByPath(dirToShare1).join().get(), dirToShare1, Set.of(sharee.username)).join(); sharer.shareReadAccessWithAll(sharer.getByPath(dirToShare2).join().get(), dirToShare2, Set.of(sharee.username)).join(); SocialFeed feed = sharee.getSocialFeed().join(); List<SharedItem> items = feed.getShared(0, 1000, sharee.crypto, sharee.network).join(); Assert.assertTrue(items.size() == 2); sharee = PeergosNetworkUtils.ensureSignedUp(sharee.username, password, network, crypto); sharee.getUserRoot().join().mkdir("mine", sharer.network, false, sharer.crypto).join(); feed = sharee.getSocialFeed().join(); items = feed.getShared(0, 1000, sharee.crypto, sharee.network).join(); Assert.assertTrue(items.size() == 2); //When attempting this in the web-ui the below call results in a failure when loading timeline entry //Cannot seek to position 680 in file of length 340 feed = sharee.getSocialFeed().join(); items = feed.getShared(0, 1000, sharee.crypto, sharee.network).join(); Assert.assertTrue(items.size() == 2); } public static void socialFeedEmpty(NetworkAccess network, Random random) { CryptreeNode.setMaxChildLinkPerBlob(10); String password = "notagoodone"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(generateUsername(random), password, network, crypto); SocialFeed feed = sharer.getSocialFeed().join(); List<SharedItem> items = feed.getShared(0, 1, sharer.crypto, sharer.network).join(); Assert.assertTrue(items.size() == 0); } public static void socialFeedVariations(NetworkAccess network, Random random) { CryptreeNode.setMaxChildLinkPerBlob(10); String password = "notagoodone"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(generateUsername(random), password, network, crypto); List<UserContext> shareeUsers = getUserContextsForNode(network, random, 1, Arrays.asList(password, password)); UserContext a = shareeUsers.get(0); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); String dir1 = "one"; String dir2 = "two"; sharer.getUserRoot().join().mkdir(dir1, sharer.network, false, sharer.crypto).join(); sharer.getUserRoot().join().mkdir(dir2, sharer.network, false, sharer.crypto).join(); Path dirToShare1 = Paths.get(sharer.username, dir1); Path dirToShare2 = Paths.get(sharer.username, dir2); sharer.shareReadAccessWithAll(sharer.getByPath(dirToShare1).join().get(), dirToShare1, Set.of(a.username)).join(); sharer.shareReadAccessWithAll(sharer.getByPath(dirToShare2).join().get(), dirToShare2, Set.of(a.username)).join(); SocialFeed feed = a.getSocialFeed().join(); List<SharedItem> items = feed.getShared(0, 1000, a.crypto, a.network).join(); Assert.assertTrue(items.size() == 2); //Add another file and share String dir3 = "three"; sharer.getUserRoot().join().mkdir(dir3, sharer.network, false, sharer.crypto).join(); Path dirToShare3 = Paths.get(sharer.username, dir3); sharer.shareReadAccessWithAll(sharer.getByPath(dirToShare3).join().get(), dirToShare3, Set.of(a.username)).join(); feed = a.getSocialFeed().join().update().join(); items = feed.getShared(0, 1000, a.crypto, a.network).join(); Assert.assertTrue(items.size() == 3); } public static void groupSharing(NetworkAccess network, Random random) { CryptreeNode.setMaxChildLinkPerBlob(10); String password = "notagoodone"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(generateUsername(random), password, network, crypto); List<UserContext> shareeUsers = getUserContextsForNode(network.clear(), random, 2, Arrays.asList(password, password)); UserContext friend = shareeUsers.get(0); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); String dirName = "one"; sharer.getUserRoot().join().mkdir(dirName, sharer.network, false, sharer.crypto).join(); Path dirToShare1 = Paths.get(sharer.username, dirName); SocialState social = sharer.getSocialState().join(); String friends = social.getFriendsGroupUid(); sharer.shareReadAccessWithAll(sharer.getByPath(dirToShare1).join().get(), dirToShare1, Set.of(friends)).join(); FileSharedWithState fileSharedWithState = sharer.sharedWith(dirToShare1).join(); Assert.assertTrue(fileSharedWithState.readAccess.size() == 1); Assert.assertTrue(fileSharedWithState.readAccess.contains(friends)); Optional<FileWrapper> dir = friend.getByPath(dirToShare1).join(); Assert.assertTrue(dir.isPresent()); Optional<FileWrapper> home = friend.getByPath(Paths.get(sharer.username)).join(); Assert.assertTrue(home.isPresent()); Optional<FileWrapper> dirViaGetChild = home.get().getChild(dirName, sharer.crypto.hasher, sharer.network).join(); Assert.assertTrue(dirViaGetChild.isPresent()); Set<FileWrapper> children = home.get().getChildren(sharer.crypto.hasher, sharer.network).join(); Assert.assertTrue(children.size() > 1); // remove friend, which should rotate all keys of things shared with the friends group sharer.removeFollower(friend.username).join(); Optional<FileWrapper> dir2 = friend.getByPath(dirToShare1).join(); Assert.assertTrue(dir2.isEmpty()); // new friends List<UserContext> newFriends = getUserContextsForNode(network.clear(), random, 1, Arrays.asList(password, password)); UserContext newFriend = newFriends.get(0); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), newFriends); Optional<FileWrapper> dirForNewFriend = newFriend.getByPath(dirToShare1).join(); Assert.assertTrue(dirForNewFriend.isPresent()); } public static void groupSharingToFollowers(NetworkAccess network, Random random) { CryptreeNode.setMaxChildLinkPerBlob(10); String password = "notagoodone"; UserContext sharer = PeergosNetworkUtils.ensureSignedUp(generateUsername(random), password, network, crypto); List<UserContext> shareeUsers = getUserContextsForNode(network.clear(), random, 2, Arrays.asList(password, password)); UserContext friend = shareeUsers.get(0); // make others follow sharer followBetweenGroups(Arrays.asList(sharer), shareeUsers); String dir1 = "one"; sharer.getUserRoot().join().mkdir(dir1, sharer.network, false, sharer.crypto).join(); Path dirToShare1 = Paths.get(sharer.username, dir1); SocialState social = sharer.getSocialState().join(); String followers = social.getFollowersGroupUid(); sharer.shareReadAccessWithAll(sharer.getByPath(dirToShare1).join().get(), dirToShare1, Set.of(followers)).join(); FileSharedWithState fileSharedWithState = sharer.sharedWith(dirToShare1).join(); Assert.assertTrue(fileSharedWithState.readAccess.size() == 1); Assert.assertTrue(fileSharedWithState.readAccess.contains(followers)); Optional<FileWrapper> dir = friend.getByPath(dirToShare1).join(); Assert.assertTrue(dir.isPresent()); // remove friend, which should rotate all keys of things shared with the friends group sharer.removeFollower(friend.username).join(); Optional<FileWrapper> dir2 = friend.getByPath(dirToShare1).join(); Assert.assertTrue(dir2.isEmpty()); } public static List<Set<AbsoluteCapability>> getAllChildCapsByChunk(FileWrapper dir, NetworkAccess network) { return getAllChildCapsByChunk(dir.getPointer().capability, dir.getPointer().fileAccess, dir.version, network); } public static List<Set<AbsoluteCapability>> getAllChildCapsByChunk(AbsoluteCapability cap, CryptreeNode dir, Snapshot inVersion, NetworkAccess network) { Set<NamedAbsoluteCapability> direct = dir.getDirectChildrenCapabilities(cap, inVersion, network).join(); AbsoluteCapability nextChunkCap = cap.withMapKey(dir.getNextChunkLocation(cap.rBaseKey, Optional.empty(), cap.getMapKey(), null).join()); Snapshot version = new Snapshot(cap.writer, WriterData.getWriterData(network.mutable.getPointerTarget(cap.owner, cap.writer, network.dhtClient).join().get(), network.dhtClient).join()); Optional<CryptreeNode> next = network.getMetadata(version.get(nextChunkCap.writer).props, nextChunkCap).join(); Set<AbsoluteCapability> directUnnamed = direct.stream().map(n -> n.cap).collect(Collectors.toSet()); if (! next.isPresent()) return Arrays.asList(directUnnamed); return Stream.concat(Stream.of(directUnnamed), getAllChildCapsByChunk(nextChunkCap, next.get(), inVersion, network).stream()) .collect(Collectors.toList()); } public static Set<AbsoluteCapability> getAllChildCaps(FileWrapper dir, NetworkAccess network) { RetrievedCapability p = dir.getPointer(); AbsoluteCapability cap = p.capability; return getAllChildCaps(cap, p.fileAccess, network); } public static Set<AbsoluteCapability> getAllChildCaps(AbsoluteCapability cap, CryptreeNode dir, NetworkAccess network) { return dir.getAllChildrenCapabilities(new Snapshot(cap.writer, WriterData.getWriterData(network.mutable.getPointerTarget(cap.owner, cap.writer, network.dhtClient).join().get(), network.dhtClient).join()), cap, crypto.hasher, network).join() .stream().map(n -> n.cap).collect(Collectors.toSet()); } public static void shareFolderForWriteAccess(NetworkAccess sharerNode, NetworkAccess shareeNode, int shareeCount, Random random) throws Exception { Assert.assertTrue(0 < shareeCount); String sharerUsername = generateUsername(random); String sharerPassword = generatePassword(); UserContext sharer = PeergosNetworkUtils.ensureSignedUp(sharerUsername, sharerPassword, sharerNode, crypto); List<String> shareePasswords = IntStream.range(0, shareeCount) .mapToObj(i -> generatePassword()) .collect(Collectors.toList()); List<UserContext> shareeUsers = getUserContextsForNode(shareeNode, random, shareeCount, shareePasswords); // friend sharer with others friendBetweenGroups(Arrays.asList(sharer), shareeUsers); // friends are now connected // share a directory from u1 to the others FileWrapper u1Root = sharer.getUserRoot().get(); String folderName = "awritefolder"; u1Root.mkdir(folderName, sharer.network, SymmetricKey.random(), false, crypto).get(); String path = Paths.get(sharerUsername, folderName).toString(); System.out.println("PATH "+ path); FileWrapper folder = sharer.getByPath(path).get().get(); // file is uploaded, do the actual sharing boolean finished = sharer.shareWriteAccessWithAll(folder, Paths.get(path), sharer.getUserRoot().join(), shareeUsers.stream() .map(c -> c.username) .collect(Collectors.toSet())).get(); // check each user can see the shared folder, and write to it for (UserContext sharee : shareeUsers) { FileWrapper sharedFolder = sharee.getByPath(sharer.username + "/" + folderName).get().orElseThrow(() -> new AssertionError("shared folder is present after sharing")); Assert.assertEquals(sharedFolder.getFileProperties().name, folderName); sharedFolder.mkdir(sharee.username, shareeNode, false, crypto).get(); } Set<FileWrapper> children = sharer.getByPath(path).get().get().getChildren(crypto.hasher, sharerNode).get(); Assert.assertTrue(children.size() == shareeCount); } public static void publicLinkToFile(Random random, NetworkAccess writerNode, NetworkAccess readerNode) throws Exception { String username = generateUsername(random); String password = "test01"; UserContext context = PeergosNetworkUtils.ensureSignedUp(username, password, writerNode, crypto); FileWrapper userRoot = context.getUserRoot().get(); String filename = "mediumfile.bin"; byte[] data = new byte[128*1024]; random.nextBytes(data); long t1 = System.currentTimeMillis(); userRoot.uploadFileSection(filename, new AsyncReader.ArrayBacked(data), false, 0, data.length, Optional.empty(), true, context.network, crypto, l -> {}, crypto.random.randomBytes(32)).get(); long t2 = System.currentTimeMillis(); String path = "/" + username + "/" + filename; FileWrapper file = context.getByPath(path).get().get(); String link = file.toLink(); UserContext linkContext = UserContext.fromSecretLink(link, readerNode, crypto).get(); String entryPath = linkContext.getEntryPath().join(); Assert.assertTrue("Correct entry path", entryPath.equals("/" + username)); Optional<FileWrapper> fileThroughLink = linkContext.getByPath(path).get(); Assert.assertTrue("File present through link", fileThroughLink.isPresent()); } public static void friendBetweenGroups(List<UserContext> a, List<UserContext> b) { for (UserContext userA : a) { for (UserContext userB : b) { // send intial request userA.sendFollowRequest(userB.username, SymmetricKey.random()).join(); // make sharer reciprocate all the follow requests List<FollowRequestWithCipherText> sharerRequests = userB.processFollowRequests().join(); for (FollowRequestWithCipherText u1Request : sharerRequests) { AbsoluteCapability pointer = u1Request.req.entry.get().pointer; Assert.assertTrue("Read only capabilities are shared", ! pointer.wBaseKey.isPresent()); boolean accept = true; boolean reciprocate = true; userB.sendReplyFollowRequest(u1Request, accept, reciprocate).join(); } // complete the friendship connection userA.processFollowRequests().join(); } } } public static void followBetweenGroups(List<UserContext> sharers, List<UserContext> followers) { for (UserContext userA : sharers) { for (UserContext userB : followers) { // send intial request userB.sendFollowRequest(userA.username, SymmetricKey.random()).join(); // make sharer reciprocate all the follow requests List<FollowRequestWithCipherText> sharerRequests = userA.processFollowRequests().join(); for (FollowRequestWithCipherText u1Request : sharerRequests) { AbsoluteCapability pointer = u1Request.req.entry.get().pointer; Assert.assertTrue("Read only capabilities are shared", ! pointer.wBaseKey.isPresent()); boolean accept = true; boolean reciprocate = false; userA.sendReplyFollowRequest(u1Request, accept, reciprocate).join(); } // complete the friendship connection userB.processFollowRequests().join(); } } } public static UserContext ensureSignedUp(String username, String password, NetworkAccess network, Crypto crypto) { boolean isRegistered = network.isUsernameRegistered(username).join(); if (isRegistered) return UserContext.signIn(username, password, network, crypto).join(); return UserContext.signUp(username, password, "", network, crypto).join(); } }
Fix some timeline tests
src/peergos/server/tests/PeergosNetworkUtils.java
Fix some timeline tests
<ide><path>rc/peergos/server/tests/PeergosNetworkUtils.java <ide> <ide> // check 'a' can see the shared file in their social feed <ide> SocialFeed feed = a.getSocialFeed().join(); <del> List<SharedItem> items = feed.getShared(0, 1, a.crypto, a.network).join(); <add> int feedSize = 3; <add> List<SharedItem> items = feed.getShared(feedSize, feedSize + 1, a.crypto, a.network).join(); <ide> Assert.assertTrue(items.size() > 0); <ide> SharedItem item = items.get(0); <ide> Assert.assertTrue(item.owner.equals(sharer.username)); <ide> // Test the feed after a fresh login <ide> UserContext freshA = PeergosNetworkUtils.ensureSignedUp(a.username, password, network, crypto); <ide> SocialFeed freshFeed = freshA.getSocialFeed().join(); <del> List<SharedItem> freshItems = freshFeed.getShared(0, 1, a.crypto, a.network).join(); <add> List<SharedItem> freshItems = freshFeed.getShared(feedSize, feedSize + 1, a.crypto, a.network).join(); <ide> Assert.assertTrue(freshItems.size() > 0); <ide> SharedItem freshItem = freshItems.get(0); <ide> Assert.assertTrue(freshItem.equals(item)); <ide> uploadAndShare(fileData, file2, sharer, a.username); <ide> <ide> SocialFeed updatedFeed = freshFeed.update().join(); <del> List<SharedItem> items2 = updatedFeed.getShared(1, 2, a.crypto, a.network).join(); <add> List<SharedItem> items2 = updatedFeed.getShared(feedSize + 1, feedSize + 2, a.crypto, a.network).join(); <ide> Assert.assertTrue(items2.size() > 0); <ide> SharedItem item2 = items2.get(0); <ide> Assert.assertTrue(item2.owner.equals(sharer.username)); <ide> <ide> // now check feed <ide> SocialFeed updatedFeed3 = freshFeed.update().join(); <del> List<SharedItem> items3 = updatedFeed3.getShared(2, 3, a.crypto, a.network).join(); <add> List<SharedItem> items3 = updatedFeed3.getShared(feedSize + 2, feedSize + 3, a.crypto, a.network).join(); <ide> Assert.assertTrue(items3.size() > 0); <ide> SharedItem item3 = items3.get(0); <ide> Assert.assertTrue(item3.owner.equals(sharer.username)); <ide> <ide> SocialFeed feed = sharee.getSocialFeed().join(); <ide> List<SharedItem> items = feed.getShared(0, 1000, sharee.crypto, sharee.network).join(); <del> Assert.assertTrue(items.size() == 2); <add> Assert.assertTrue(items.size() == 3 + 2); <ide> <ide> sharee.getUserRoot().join().mkdir("mine", sharee.network, false, sharer.crypto).join(); <ide> } <ide> <ide> SocialFeed feed = sharee.getSocialFeed().join(); <ide> List<SharedItem> items = feed.getShared(0, 1000, sharee.crypto, sharee.network).join(); <del> Assert.assertTrue(items.size() == 2); <add> Assert.assertTrue(items.size() == 3 + 2); <ide> <ide> sharee = PeergosNetworkUtils.ensureSignedUp(sharee.username, password, network, crypto); <ide> sharee.getUserRoot().join().mkdir("mine", sharer.network, false, sharer.crypto).join(); <ide> <ide> feed = sharee.getSocialFeed().join(); <ide> items = feed.getShared(0, 1000, sharee.crypto, sharee.network).join(); <del> Assert.assertTrue(items.size() == 2); <add> Assert.assertTrue(items.size() == 3 + 2); <ide> <ide> //When attempting this in the web-ui the below call results in a failure when loading timeline entry <ide> //Cannot seek to position 680 in file of length 340 <ide> feed = sharee.getSocialFeed().join(); <ide> items = feed.getShared(0, 1000, sharee.crypto, sharee.network).join(); <del> Assert.assertTrue(items.size() == 2); <add> Assert.assertTrue(items.size() == 3 + 2); <ide> } <ide> <ide> public static void socialFeedEmpty(NetworkAccess network, Random random) {
Java
apache-2.0
c3bd54045425930901062df9fe3da0a8b96fcd74
0
openfurther/further-open-core,openfurther/further-open-core
/** * Copyright (C) [2013] [The FURTHeR Project] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.utah.further.fqe.ds.model.further.export; import static org.slf4j.LoggerFactory.getLogger; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Resource; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.google.common.base.Joiner; import edu.utah.further.core.api.collections.CollectionUtil; import edu.utah.further.core.api.exception.ApplicationException; import edu.utah.further.dts.api.domain.concept.DtsConcept; import edu.utah.further.dts.api.domain.namespace.DtsNamespace; import edu.utah.further.dts.api.service.DtsOperationService; import edu.utah.further.fqe.ds.api.domain.AbstractQueryContext; import edu.utah.further.fqe.ds.api.domain.ExportContext; import edu.utah.further.fqe.ds.api.domain.Exporter; import edu.utah.further.ds.further.model.impl.domain.Observation; import edu.utah.further.ds.further.model.impl.domain.Person; /** * A comma separated value implementation of an {@link Exporter} * <p> * -----------------------------------------------------------------------------------<br> * (c) 2008-2012 FURTHeR Project, Health Sciences IT, University of Utah<br> * Contact: {@code <[email protected]>}<br> * Biomedical Informatics, 26 South 2000 East<br> * Room 5775 HSEB, Salt Lake City, UT 84112<br> * Day Phone: 1-801-581-4080<br> * ----------------------------------------------------------------------------------- * * @author Rich Hansen {@code <[email protected]>} * @version Jul 31, 2014 */ @Service("csvExporter") @Transactional public final class CsvExporterImpl implements Exporter { /** * A logger that helps identify this class' printouts. */ private static final Logger log = getLogger(AbstractQueryContext.class); /** * String used to designate that a particular code was not found in DTS */ private static final String NOT_FOUND = "NOT_FOUND"; /** * Strings used to find Demographic map entries */ public static final String GENDER_PERSON_SOURCE_CD = "gender"; public static final String BIRTH_DATE_PERSON_SOURCE_CD = "birthdate"; public static final String BIRTH_YEAR_PERSON_SOURCE_CD = "birthyear"; public static final String BIRTH_MONTH_PERSON_SOURCE_CD = "birthmonth"; public static final String BIRTH_DAY_PERSON_SOURCE_CD = "birthday"; public static final String EDUCATION_PERSON_SOURCE_CD = "education"; public static final String MULTI_BIRTH_IND_PERSON_SOURCE_CD = "multibirthind"; public static final String MULTI_BIRTH_NUM_PERSON_SOURCE_CD = "multibirthnum"; public static final String DEATH_DATE_PERSON_SOURCE_CD = "deathdate"; public static final String DEATH_YEAR_PERSON_SOURCE_CD = "deathyear"; public static final String PEDIGREE_PERSON_SOURCE_CD = "pedigree"; public static final String ETHNICITY_PERSON_SOURCE_CD = "ethnicity"; public static final String RACE_PERSON_SOURCE_CD = "race"; public static final String RELIGION_PERSON_SOURCE_CD = "religion"; public static final String PRIMARYLANGUAGE_PERSON_SOURCE_CD = "primarylanguage"; public static final String MARITAL_PERSON_SOURCE_CD = "marital"; public static final String CAUSEOFDEATH_PERSON_SOURCE_CD = "causeofdeath"; public static final String VITALSTATUS_PERSON_SOURCE_CD = "vitalstatus"; // ========================= DEPENDENCIES ============================== /** * Terminology services */ @Autowired private DtsOperationService dos; /** * A prefix to namespace mapper. Prefixes that do not require a namespace -1. */ @Resource(name = "prefixMapper") private Map<String, Integer> prefixMapper; // ========================= IMPLEMENTATION: Exporter ======= /* * (non-Javadoc) * * @see edu.utah.further.fqe.ds.api.domain.Exporter#format(java.util.List, * edu.utah.further.fqe.ds.api.domain.ExportContext) */ @Override @SuppressWarnings("unchecked") public <F> F format(final List<?> results, final ExportContext exportContext) { if (results == null || results.size() == 0) { throw new ApplicationException( "No results found. Your query may have returned zero results. " + "If you think this is an error, ensure that you are " + "running not running a count only query."); } final Class<?> resultClazz = results.get(0).getClass(); // Handle Person results if (resultClazz.equals(Person.class)) { // We've already checked the type final List<Person> persons = (List<Person>) results; final Map<String, String> nameMapper = getCodeToNameMap(persons); // Build the CSV header final StringBuilder sb = new StringBuilder(); sb.append(Joiner.on(",").join(createPersonHeaderList()) + System.getProperty("line.separator")); // Build the CSV data for (final Person person : persons) { sb.append(new PersonStringAdapter(person, nameMapper) + System.getProperty("line.separator")); } log.debug("Header is: " + sb.toString()); return (F) sb.toString(); } // handle other result types here // blow up otherwise throw new ApplicationException("Unsupported result type: " + resultClazz.getCanonicalName()); } // ========================= GET/SET METHODS =========================== /** * Return the prefixMapper property. * * @return the prefixMapper */ public Map<String, Integer> getPrefixMapper() { return prefixMapper; } /** * Set a new value for the prefixMapper property. * * @param prefixMapper * the prefixMapper to set */ public void setPrefixMapper(final Map<String, Integer> prefixMapper) { this.prefixMapper = prefixMapper; } /** * Return the dos property. * * @return the dos */ public DtsOperationService getDos() { return dos; } /** * Set a new value for the dos property. * * @param dos * the dos to set */ public void setDos(final DtsOperationService dos) { this.dos = dos; } // ========================= PRIVATE METHODS/CLASSES =========================== /** * Returns a map of the concept_cd to it's named value. * * E.g. SNOMED:248152002 -> Female * * @param persons * @return */ private Map<String, String> getCodeToNameMap( final List<Person> persons) { final Map<String, String> terminologyNameMap = CollectionUtil.newMap(); Map<DtsNamespace, Set<String>> translationErrors = null; DtsNamespace dtsNamespace = null; String code = null; for (final Person person : persons) { log.debug("Processing person: " + person.getId()); // Lookup the Gender name if(person.getAdministrativeGenderNamespaceId() != null) { dtsNamespace = dos.findNamespaceById(person.getAdministrativeGenderNamespaceId().intValue()); code = person.getAdministrativeGender(); codeToNameLookup(terminologyNameMap, translationErrors, dtsNamespace, person.getAdministrativeGenderNamespaceId().toString(), code); } // Lookup the Ethnicity name if(person.getEthnicityNamespaceId() != null) { dtsNamespace = dos.findNamespaceById(person.getEthnicityNamespaceId().intValue()); code = person.getEthnicity(); codeToNameLookup(terminologyNameMap, translationErrors, dtsNamespace, person.getEthnicityNamespaceId().toString(), code); } // Lookup the Race name if(person.getRaceNamespaceId() != null) { dtsNamespace = dos.findNamespaceById(person.getRaceNamespaceId().intValue()); code = person.getRace(); codeToNameLookup(terminologyNameMap, translationErrors, dtsNamespace, person.getRaceNamespaceId().toString(), code); } // Lookup the Religion name if(person.getReligionNamespaceId() != null) { dtsNamespace = dos.findNamespaceById(person.getReligionNamespaceId().intValue()); code = person.getReligion(); codeToNameLookup(terminologyNameMap, translationErrors, dtsNamespace, person.getReligionNamespaceId().toString(), code); } // Lookup the PrimaryLanguage name if(person.getPrimaryLanguageNamespaceId() != null) { dtsNamespace = dos.findNamespaceById(person.getPrimaryLanguageNamespaceId().intValue()); code = person.getPrimaryLanguage(); codeToNameLookup(terminologyNameMap, translationErrors, dtsNamespace, person.getPrimaryLanguageNamespaceId().toString(), code); } // Lookup the MaritalStatus name if(person.getMaritalStatusNamespaceId() != null) { dtsNamespace = dos.findNamespaceById(person.getMaritalStatusNamespaceId().intValue()); code = person.getMaritalStatus(); codeToNameLookup(terminologyNameMap, translationErrors, dtsNamespace, person.getMaritalStatusNamespaceId().toString(), code); } // Lookup the CauseOfDeath name if(person.getCauseOfDeathNamespaceId() != null) { dtsNamespace = dos.findNamespaceById(person.getCauseOfDeathNamespaceId().intValue()); code = person.getCauseOfDeath(); codeToNameLookup(terminologyNameMap, translationErrors, dtsNamespace, person.getCauseOfDeathNamespaceId().toString(), code); } // Lookup the VitalStatus name if(person.getVitalStatusNamespaceId() != null) { dtsNamespace = dos.findNamespaceById(person.getVitalStatusNamespaceId().intValue()); code = person.getVitalStatus(); codeToNameLookup(terminologyNameMap, translationErrors, dtsNamespace, person.getVitalStatusNamespaceId().toString(), code); } } return terminologyNameMap; } /** * Lookup logic supporting creation of map of the concept_cd to it's named value. * * * @param terminologyNameMap * @param translationErrors * @param dtsNamespace * @param code * @return */ private void codeToNameLookup( final Map<String, String> terminologyNameMap, Map<DtsNamespace, Set<String>> translationErrors, final DtsNamespace dtsNamespace, final String namespaceId, final String code) { final DtsConcept dtsConcept = dtsNamespace.isLocal() ? dos .findConceptByLocalCode(dtsNamespace, code) : dos .findConceptByCodeInSource(dtsNamespace, code); String name = (dtsConcept == null) ? "" : dtsConcept.getName(); // Replace all commas in names. name = name.replace(",", ";"); // Keep track of all untranslated codes if (dtsConcept == null) { if (translationErrors == null) { translationErrors = CollectionUtil.newMap(); } Set<String> untranslatedCodes = translationErrors .get(dtsNamespace); if (untranslatedCodes == null) { untranslatedCodes = CollectionUtil.newSet(); } untranslatedCodes.add(code); translationErrors.put(dtsNamespace, untranslatedCodes); } // Put the <namespace id + concept_cd,name> into the terminologyNameMap terminologyNameMap.put(namespaceId + ":" + code, name); } /** * Creates the list of headers (attribute names) to put at the top of the CSV * * @return */ private List<String> createPersonHeaderList() { // Create the header final List<String> headerValues = CollectionUtil.newList(); headerValues.add("PERSON NUM"); for (final DemographicExportAttribute attribute : DemographicExportAttribute .values()) { if (attribute.isIgnored()) { continue; } headerValues.add(attribute.getDisplayName()); if (attribute.isValueCoded()) { headerValues.add(attribute.getDisplayName() + " CODE"); } } return headerValues; } /** * This class maps observations to person attributes and provides a toString in a * comma separated value format. In the i2b2 model, we chose to store all demographic * data as observations, therefore the observations need to be mapped back to person * attributes. * <p> * ----------------------------------------------------------------------------------- * <br> * (c) 2008-2012 FURTHeR Project, Health Sciences IT, University of Utah<br> * Contact: {@code <[email protected]>}<br> * Biomedical Informatics, 26 South 2000 East<br> * Room 5775 HSEB, Salt Lake City, UT 84112<br> * Day Phone: 1-801-581-4080<br> * ----------------------------------------------------------------------------------- * * @author N. Dustin Schultz {@code <[email protected]>} * @version Oct 8, 2012 */ private static final class PersonStringAdapter { /** * The person to adapt */ private final Person person; /** * Holds the mapping between the code of the value and the attribute */ private final Map<DemographicExportAttribute, AttributeValue> attributeValueMapper = CollectionUtil .newMap(); /** * Constructor * * @param person */ public PersonStringAdapter(final Person person, final Map<String, String> nameMapper) { this.person = person; log.debug("Adapting person: " + person.getId()); // Adapt the Gender String source = GENDER_PERSON_SOURCE_CD; DemographicExportAttribute attribute = DemographicExportAttribute .getAttributeBySourceCode(source); String concept = (person.getAdministrativeGenderNamespaceId() == null ? "" : person.getAdministrativeGenderNamespaceId()) + ":" + (person.getAdministrativeGender() == null ? "" : person.getAdministrativeGender()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); // Adapt the Ethnicity source = ETHNICITY_PERSON_SOURCE_CD; attribute = DemographicExportAttribute .getAttributeBySourceCode(source); concept = (person.getEthnicityNamespaceId() == null ? "" : person.getEthnicityNamespaceId()) + ":" + (person.getEthnicity() == null ? "" : person.getEthnicity()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); // Adapt the DateOfBirth source = BIRTH_DATE_PERSON_SOURCE_CD; attribute = DemographicExportAttribute .getAttributeBySourceCode(source); concept = source + ":" + (person.getDateOfBirth() == null ? "" : person.getDateOfBirth()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); // Adapt the BirthYear source = BIRTH_YEAR_PERSON_SOURCE_CD; attribute = DemographicExportAttribute .getAttributeBySourceCode(source); concept = source + ":" + (person.getBirthYear() == null ? "" : person.getBirthYear()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); // Adapt the BirthMonth source = BIRTH_MONTH_PERSON_SOURCE_CD; attribute = DemographicExportAttribute .getAttributeBySourceCode(source); concept = source + ":" + (person.getBirthMonth() == null ? "" : person.getBirthMonth()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); // Adapt the BirthDay source = BIRTH_DAY_PERSON_SOURCE_CD; attribute = DemographicExportAttribute .getAttributeBySourceCode(source); concept = source + ":" + (person.getBirthDay() == null ? "" : person.getBirthDay()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); // Adapt the EducationLevel source = EDUCATION_PERSON_SOURCE_CD; attribute = DemographicExportAttribute .getAttributeBySourceCode(source); concept = source + ":" + (person.getEducationLevel() == null ? "" : person.getEducationLevel()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); // Adapt the MultipleBirthIndicator source = MULTI_BIRTH_IND_PERSON_SOURCE_CD; attribute = DemographicExportAttribute .getAttributeBySourceCode(source); concept = source + ":" + (person.getMultipleBirthIndicator() == null ? "" : person.getMultipleBirthIndicator()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); // Adapt the MultipleBirthIndicatorOrderNumber source = MULTI_BIRTH_NUM_PERSON_SOURCE_CD; attribute = DemographicExportAttribute .getAttributeBySourceCode(source); concept = source + ":" + (person.getMultipleBirthIndicatorOrderNumber() == null ? "" : person.getMultipleBirthIndicatorOrderNumber()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); // Adapt the DateOfDeath source = DEATH_DATE_PERSON_SOURCE_CD; attribute = DemographicExportAttribute .getAttributeBySourceCode(source); concept = source + ":" + (person.getDateOfDeath() == null ? "" : person.getDateOfDeath()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); // Adapt the DeathYear source = DEATH_YEAR_PERSON_SOURCE_CD; attribute = DemographicExportAttribute .getAttributeBySourceCode(source); concept = source + ":" + (person.getDeathYear() == null ? "" : person.getDeathYear()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); // Adapt the PedigreeQuality source = PEDIGREE_PERSON_SOURCE_CD; attribute = DemographicExportAttribute .getAttributeBySourceCode(source); concept = source + ":" + (person.getPedigreeQuality() == null ? "" : person.getPedigreeQuality()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); // Adapt the Race source = RACE_PERSON_SOURCE_CD; attribute = DemographicExportAttribute .getAttributeBySourceCode(source); concept = (person.getRaceNamespaceId() == null ? "" : person.getRaceNamespaceId()) + ":" + (person.getRace() == null ? "" : person.getRace()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); // Adapt the Religion source = RELIGION_PERSON_SOURCE_CD; attribute = DemographicExportAttribute .getAttributeBySourceCode(source); concept = (person.getReligionNamespaceId() == null ? "" : person.getReligionNamespaceId()) + ":" + (person.getReligion() == null ? "" : person.getReligion()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); // Adapt the PrimaryLanguage source = PRIMARYLANGUAGE_PERSON_SOURCE_CD; attribute = DemographicExportAttribute .getAttributeBySourceCode(source); concept = (person.getPrimaryLanguageNamespaceId() == null ? "" : person.getPrimaryLanguageNamespaceId()) + ":" + (person.getPrimaryLanguage() == null ? "" : person.getPrimaryLanguage()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); // Adapt the MaritalStatus source = MARITAL_PERSON_SOURCE_CD; attribute = DemographicExportAttribute .getAttributeBySourceCode(source); concept = (person.getMaritalStatusNamespaceId() == null ? "" : person.getMaritalStatusNamespaceId()) + ":" + (person.getMaritalStatus() == null ? "" : person.getMaritalStatus()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); // Adapt the CauseOfDeath source = CAUSEOFDEATH_PERSON_SOURCE_CD; attribute = DemographicExportAttribute .getAttributeBySourceCode(source); concept = (person.getCauseOfDeathNamespaceId() == null ? "" : person.getCauseOfDeathNamespaceId()) + ":" + (person.getCauseOfDeath() == null ? "" : person.getCauseOfDeath()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); // Adapt the VitalStatus source = VITALSTATUS_PERSON_SOURCE_CD; attribute = DemographicExportAttribute .getAttributeBySourceCode(source); concept = (person.getVitalStatusNamespaceId() == null ? "" : person.getVitalStatusNamespaceId()) + ":" + (person.getVitalStatus() == null ? "" : person.getVitalStatus()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { final List<String> values = CollectionUtil.newList(); // Always add the person id as the first value values.add(person.getId().getId().toString()); for (final DemographicExportAttribute exportAttribute : DemographicExportAttribute .values()) { if (exportAttribute.isIgnored()) { continue; } final AttributeValue value = attributeValueMapper.get(exportAttribute); if (value == null) { // they don't have this export attribute values.add(""); if (exportAttribute.isValueCoded()) { values.add(""); } } else { if(value.getName() != null) { values.add(value.getName()); } else { values.add(""); } if (exportAttribute.isValueCoded()) { if ("".equals(value.getName())) { // FUR-2482 - replace codes that aren't in DTS with NOT_FOUND values.add(NOT_FOUND); } else { // FUR-2481 - replace colons with underscore if(value.getCode() != null) { String newValue = value.getCode().replace(":", "_"); values.add(newValue); } else { values.add(""); } } } } } return Joiner.on(",").join(values); } } /** * Holds a given codes attribute key, name, and code * <p> * ----------------------------------------------------------------------------------- * <br> * (c) 2008-2012 FURTHeR Project, Health Sciences IT, University of Utah<br> * Contact: {@code <[email protected]>}<br> * Biomedical Informatics, 26 South 2000 East<br> * Room 5775 HSEB, Salt Lake City, UT 84112<br> * Day Phone: 1-801-581-4080<br> * ----------------------------------------------------------------------------------- * * @author N. Dustin Schultz {@code <[email protected]>} * @version Oct 9, 2012 */ private static final class AttributeValue { /** * The name of this attribute */ private final String name; /** * The code of this attribute */ private final String code; /** * @param key * @param name */ public AttributeValue(final String code, final String name) { super(); this.code = code; this.name = name; } /** * Return the code property. * * @return the code */ public String getCode() { return code; } /** * Return the name property. * * @return the name */ public String getName() { return name; } } }
fqe/fqe-ds-model/fqe-ds-further-model/src/main/java/edu/utah/further/fqe/ds/model/further/export/CsvExporterImpl.java
/** * Copyright (C) [2013] [The FURTHeR Project] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.utah.further.fqe.ds.model.further.export; import static org.slf4j.LoggerFactory.getLogger; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Resource; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.google.common.base.Joiner; import edu.utah.further.core.api.collections.CollectionUtil; import edu.utah.further.core.api.exception.ApplicationException; import edu.utah.further.dts.api.domain.concept.DtsConcept; import edu.utah.further.dts.api.domain.namespace.DtsNamespace; import edu.utah.further.dts.api.service.DtsOperationService; import edu.utah.further.fqe.ds.api.domain.AbstractQueryContext; import edu.utah.further.fqe.ds.api.domain.ExportContext; import edu.utah.further.fqe.ds.api.domain.Exporter; import edu.utah.further.ds.further.model.impl.domain.Observation; import edu.utah.further.ds.further.model.impl.domain.Person; /** * A comma separated value implementation of an {@link Exporter} * <p> * -----------------------------------------------------------------------------------<br> * (c) 2008-2012 FURTHeR Project, Health Sciences IT, University of Utah<br> * Contact: {@code <[email protected]>}<br> * Biomedical Informatics, 26 South 2000 East<br> * Room 5775 HSEB, Salt Lake City, UT 84112<br> * Day Phone: 1-801-581-4080<br> * ----------------------------------------------------------------------------------- * * @author Rich Hansen {@code <[email protected]>} * @version Jul 31, 2014 */ @Service("csvExporter") @Transactional public final class CsvExporterImpl implements Exporter { /** * A logger that helps identify this class' printouts. */ private static final Logger log = getLogger(AbstractQueryContext.class); /** * String used to designate that a particular code was not found in DTS */ private static final String NOT_FOUND = "NOT_FOUND"; // ========================= DEPENDENCIES ============================== /** * Terminology services */ @Autowired private DtsOperationService dos; /** * A prefix to namespace mapper. Prefixes that do not require a namespace -1. */ @Resource(name = "prefixMapper") private Map<String, Integer> prefixMapper; // ========================= IMPLEMENTATION: Exporter ======= /* * (non-Javadoc) * * @see edu.utah.further.fqe.ds.api.domain.Exporter#format(java.util.List, * edu.utah.further.fqe.ds.api.domain.ExportContext) */ @Override @SuppressWarnings("unchecked") public <F> F format(final List<?> results, final ExportContext exportContext) { if (results == null || results.size() == 0) { throw new ApplicationException( "No results found. Your query may have returned zero results. " + "If you think this is an error, ensure that you are " + "running not running a count only query."); } final Class<?> resultClazz = results.get(0).getClass(); // Handle Person results if (resultClazz.equals(Person.class)) { // We've already checked the type final List<Person> persons = (List<Person>) results; final Map<String, String> nameMapper = getCodeToNameMap(persons); // Build the CSV header final StringBuilder sb = new StringBuilder(); sb.append(Joiner.on(",").join(createPersonHeaderList()) + System.getProperty("line.separator")); // Build the CSV data for (final Person person : persons) { sb.append(new PersonStringAdapter(person, nameMapper) + System.getProperty("line.separator")); } log.debug("Header is: " + sb.toString()); return (F) sb.toString(); } // handle other result types here // blow up otherwise throw new ApplicationException("Unsupported result type: " + resultClazz.getCanonicalName()); } // ========================= GET/SET METHODS =========================== /** * Return the prefixMapper property. * * @return the prefixMapper */ public Map<String, Integer> getPrefixMapper() { return prefixMapper; } /** * Set a new value for the prefixMapper property. * * @param prefixMapper * the prefixMapper to set */ public void setPrefixMapper(final Map<String, Integer> prefixMapper) { this.prefixMapper = prefixMapper; } /** * Return the dos property. * * @return the dos */ public DtsOperationService getDos() { return dos; } /** * Set a new value for the dos property. * * @param dos * the dos to set */ public void setDos(final DtsOperationService dos) { this.dos = dos; } // ========================= PRIVATE METHODS/CLASSES =========================== /** * Returns a map of the concept_cd to it's named value. * * E.g. SNOMED:248152002 -> Female * * @param persons * @return */ private Map<String, String> getCodeToNameMap( final List<Person> persons) { final Map<String, String> terminologyNameMap = CollectionUtil.newMap(); Map<DtsNamespace, Set<String>> translationErrors = null; DtsNamespace dtsNamespace = null; String code = null; for (final Person person : persons) { log.debug("Processing person: " + person.getId()); // Lookup the Gender name if(person.getAdministrativeGenderNamespaceId() != null) { dtsNamespace = dos.findNamespaceById(person.getAdministrativeGenderNamespaceId().intValue()); code = person.getAdministrativeGender(); codeToNameLookup(terminologyNameMap, translationErrors, dtsNamespace, person.getAdministrativeGenderNamespaceId().toString(), code); } // Lookup the Ethnicity name if(person.getEthnicityNamespaceId() != null) { dtsNamespace = dos.findNamespaceById(person.getEthnicityNamespaceId().intValue()); code = person.getEthnicity(); codeToNameLookup(terminologyNameMap, translationErrors, dtsNamespace, person.getEthnicityNamespaceId().toString(), code); } // Lookup the Race name if(person.getRaceNamespaceId() != null) { dtsNamespace = dos.findNamespaceById(person.getRaceNamespaceId().intValue()); code = person.getRace(); codeToNameLookup(terminologyNameMap, translationErrors, dtsNamespace, person.getRaceNamespaceId().toString(), code); } // Lookup the Religion name if(person.getReligionNamespaceId() != null) { dtsNamespace = dos.findNamespaceById(person.getReligionNamespaceId().intValue()); code = person.getReligion(); codeToNameLookup(terminologyNameMap, translationErrors, dtsNamespace, person.getReligionNamespaceId().toString(), code); } // Lookup the PrimaryLanguage name if(person.getPrimaryLanguageNamespaceId() != null) { dtsNamespace = dos.findNamespaceById(person.getPrimaryLanguageNamespaceId().intValue()); code = person.getPrimaryLanguage(); codeToNameLookup(terminologyNameMap, translationErrors, dtsNamespace, person.getPrimaryLanguageNamespaceId().toString(), code); } // Lookup the MaritalStatus name if(person.getMaritalStatusNamespaceId() != null) { dtsNamespace = dos.findNamespaceById(person.getMaritalStatusNamespaceId().intValue()); code = person.getMaritalStatus(); codeToNameLookup(terminologyNameMap, translationErrors, dtsNamespace, person.getMaritalStatusNamespaceId().toString(), code); } // Lookup the CauseOfDeath name if(person.getCauseOfDeathNamespaceId() != null) { dtsNamespace = dos.findNamespaceById(person.getCauseOfDeathNamespaceId().intValue()); code = person.getCauseOfDeath(); codeToNameLookup(terminologyNameMap, translationErrors, dtsNamespace, person.getCauseOfDeathNamespaceId().toString(), code); } // Lookup the VitalStatus name if(person.getVitalStatusNamespaceId() != null) { dtsNamespace = dos.findNamespaceById(person.getVitalStatusNamespaceId().intValue()); code = person.getVitalStatus(); codeToNameLookup(terminologyNameMap, translationErrors, dtsNamespace, person.getVitalStatusNamespaceId().toString(), code); } } return terminologyNameMap; } /** * Lookup logic supporting creation of map of the concept_cd to it's named value. * * * @param terminologyNameMap * @param translationErrors * @param dtsNamespace * @param code * @return */ private void codeToNameLookup( final Map<String, String> terminologyNameMap, Map<DtsNamespace, Set<String>> translationErrors, final DtsNamespace dtsNamespace, final String namespaceId, final String code) { final DtsConcept dtsConcept = dtsNamespace.isLocal() ? dos .findConceptByLocalCode(dtsNamespace, code) : dos .findConceptByCodeInSource(dtsNamespace, code); String name = (dtsConcept == null) ? "" : dtsConcept.getName(); // Replace all commas in names. name = name.replace(",", ";"); // Keep track of all untranslated codes if (dtsConcept == null) { if (translationErrors == null) { translationErrors = CollectionUtil.newMap(); } Set<String> untranslatedCodes = translationErrors .get(dtsNamespace); if (untranslatedCodes == null) { untranslatedCodes = CollectionUtil.newSet(); } untranslatedCodes.add(code); translationErrors.put(dtsNamespace, untranslatedCodes); } // Put the <namespace id + concept_cd,name> into the terminologyNameMap terminologyNameMap.put(namespaceId + ":" + code, name); } /** * Creates the list of headers (attribute names) to put at the top of the CSV * * @return */ private List<String> createPersonHeaderList() { // Create the header final List<String> headerValues = CollectionUtil.newList(); headerValues.add("PERSON NUM"); for (final DemographicExportAttribute attribute : DemographicExportAttribute .values()) { if (attribute.isIgnored()) { continue; } headerValues.add(attribute.getDisplayName()); if (attribute.isValueCoded()) { headerValues.add(attribute.getDisplayName() + " CODE"); } } return headerValues; } /** * This class maps observations to person attributes and provides a toString in a * comma separated value format. In the i2b2 model, we chose to store all demographic * data as observations, therefore the observations need to be mapped back to person * attributes. * <p> * ----------------------------------------------------------------------------------- * <br> * (c) 2008-2012 FURTHeR Project, Health Sciences IT, University of Utah<br> * Contact: {@code <[email protected]>}<br> * Biomedical Informatics, 26 South 2000 East<br> * Room 5775 HSEB, Salt Lake City, UT 84112<br> * Day Phone: 1-801-581-4080<br> * ----------------------------------------------------------------------------------- * * @author N. Dustin Schultz {@code <[email protected]>} * @version Oct 8, 2012 */ private static final class PersonStringAdapter { /** * The person to adapt */ private final Person person; /** * Holds the mapping between the code of the value and the attribute */ private final Map<DemographicExportAttribute, AttributeValue> attributeValueMapper = CollectionUtil .newMap(); /** * Constructor * * @param person */ public PersonStringAdapter(final Person person, final Map<String, String> nameMapper) { this.person = person; log.debug("Adapting person: " + person.getId()); // Adapt the Gender String source = "gender"; DemographicExportAttribute attribute = DemographicExportAttribute .getAttributeBySourceCode(source); String concept = (person.getAdministrativeGenderNamespaceId() == null ? "" : person.getAdministrativeGenderNamespaceId()) + ":" + (person.getAdministrativeGender() == null ? "" : person.getAdministrativeGender()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); // Adapt the Ethnicity source = "ethnicity"; attribute = DemographicExportAttribute .getAttributeBySourceCode(source); concept = (person.getEthnicityNamespaceId() == null ? "" : person.getEthnicityNamespaceId()) + ":" + (person.getEthnicity() == null ? "" : person.getEthnicity()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); // Adapt the Race source = "race"; attribute = DemographicExportAttribute .getAttributeBySourceCode(source); concept = (person.getRaceNamespaceId() == null ? "" : person.getRaceNamespaceId()) + ":" + (person.getRace() == null ? "" : person.getRace()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); // Adapt the Religion source = "religion"; attribute = DemographicExportAttribute .getAttributeBySourceCode(source); concept = (person.getReligionNamespaceId() == null ? "" : person.getReligionNamespaceId()) + ":" + (person.getReligion() == null ? "" : person.getReligion()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); // Adapt the PrimaryLanguage source = "primarylanguage"; attribute = DemographicExportAttribute .getAttributeBySourceCode(source); concept = (person.getPrimaryLanguageNamespaceId() == null ? "" : person.getPrimaryLanguageNamespaceId()) + ":" + (person.getPrimaryLanguage() == null ? "" : person.getPrimaryLanguage()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); // Adapt the MaritalStatus source = "marital"; attribute = DemographicExportAttribute .getAttributeBySourceCode(source); concept = (person.getMaritalStatusNamespaceId() == null ? "" : person.getMaritalStatusNamespaceId()) + ":" + (person.getMaritalStatus() == null ? "" : person.getMaritalStatus()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); // Adapt the CauseOfDeath source = "causeofdeath"; attribute = DemographicExportAttribute .getAttributeBySourceCode(source); concept = (person.getCauseOfDeathNamespaceId() == null ? "" : person.getCauseOfDeathNamespaceId()) + ":" + (person.getCauseOfDeath() == null ? "" : person.getCauseOfDeath()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); // Adapt the VitalStatus source = "vitalstatus"; attribute = DemographicExportAttribute .getAttributeBySourceCode(source); concept = (person.getVitalStatusNamespaceId() == null ? "" : person.getVitalStatusNamespaceId()) + ":" + (person.getVitalStatus() == null ? "" : person.getVitalStatus()); attributeValueMapper.put(attribute, new AttributeValue(concept, nameMapper.get(concept))); } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { final List<String> values = CollectionUtil.newList(); // Always add the person id as the first value values.add(person.getId().getId().toString()); for (final DemographicExportAttribute exportAttribute : DemographicExportAttribute .values()) { if (exportAttribute.isIgnored()) { continue; } final AttributeValue value = attributeValueMapper.get(exportAttribute); if (value == null) { // they don't have this export attribute values.add(""); if (exportAttribute.isValueCoded()) { values.add(""); } } else { if(value.getName() != null) { values.add(value.getName()); } else { values.add(""); } if (exportAttribute.isValueCoded()) { if ("".equals(value.getName())) { // FUR-2482 - replace codes that aren't in DTS with NOT_FOUND values.add(NOT_FOUND); } else { // FUR-2481 - replace colons with underscore if(value.getCode() != null) { String newValue = value.getCode().replace(":", "_"); values.add(newValue); } else { values.add(""); } } } } } return Joiner.on(",").join(values); } } /** * Holds a given codes attribute key, name, and code * <p> * ----------------------------------------------------------------------------------- * <br> * (c) 2008-2012 FURTHeR Project, Health Sciences IT, University of Utah<br> * Contact: {@code <[email protected]>}<br> * Biomedical Informatics, 26 South 2000 East<br> * Room 5775 HSEB, Salt Lake City, UT 84112<br> * Day Phone: 1-801-581-4080<br> * ----------------------------------------------------------------------------------- * * @author N. Dustin Schultz {@code <[email protected]>} * @version Oct 9, 2012 */ private static final class AttributeValue { /** * The name of this attribute */ private final String name; /** * The code of this attribute */ private final String code; /** * @param key * @param name */ public AttributeValue(final String code, final String name) { super(); this.code = code; this.name = name; } /** * Return the code property. * * @return the code */ public String getCode() { return code; } /** * Return the name property. * * @return the name */ public String getName() { return name; } } }
CSV Export, Person refactor: add no-code columns to export
fqe/fqe-ds-model/fqe-ds-further-model/src/main/java/edu/utah/further/fqe/ds/model/further/export/CsvExporterImpl.java
CSV Export, Person refactor: add no-code columns to export
<ide><path>qe/fqe-ds-model/fqe-ds-further-model/src/main/java/edu/utah/further/fqe/ds/model/further/export/CsvExporterImpl.java <ide> */ <ide> private static final String NOT_FOUND = "NOT_FOUND"; <ide> <add> /** <add> * Strings used to find Demographic map entries <add> */ <add> public static final String GENDER_PERSON_SOURCE_CD = "gender"; <add> public static final String BIRTH_DATE_PERSON_SOURCE_CD = "birthdate"; <add> public static final String BIRTH_YEAR_PERSON_SOURCE_CD = "birthyear"; <add> public static final String BIRTH_MONTH_PERSON_SOURCE_CD = "birthmonth"; <add> public static final String BIRTH_DAY_PERSON_SOURCE_CD = "birthday"; <add> public static final String EDUCATION_PERSON_SOURCE_CD = "education"; <add> public static final String MULTI_BIRTH_IND_PERSON_SOURCE_CD = "multibirthind"; <add> public static final String MULTI_BIRTH_NUM_PERSON_SOURCE_CD = "multibirthnum"; <add> public static final String DEATH_DATE_PERSON_SOURCE_CD = "deathdate"; <add> public static final String DEATH_YEAR_PERSON_SOURCE_CD = "deathyear"; <add> public static final String PEDIGREE_PERSON_SOURCE_CD = "pedigree"; <add> public static final String ETHNICITY_PERSON_SOURCE_CD = "ethnicity"; <add> public static final String RACE_PERSON_SOURCE_CD = "race"; <add> public static final String RELIGION_PERSON_SOURCE_CD = "religion"; <add> public static final String PRIMARYLANGUAGE_PERSON_SOURCE_CD = "primarylanguage"; <add> public static final String MARITAL_PERSON_SOURCE_CD = "marital"; <add> public static final String CAUSEOFDEATH_PERSON_SOURCE_CD = "causeofdeath"; <add> public static final String VITALSTATUS_PERSON_SOURCE_CD = "vitalstatus"; <add> <ide> // ========================= DEPENDENCIES ============================== <ide> <ide> /** <ide> log.debug("Adapting person: " + person.getId()); <ide> <ide> // Adapt the Gender <del> String source = "gender"; <add> String source = GENDER_PERSON_SOURCE_CD; <ide> DemographicExportAttribute attribute = DemographicExportAttribute <ide> .getAttributeBySourceCode(source); <ide> <ide> nameMapper.get(concept))); <ide> <ide> // Adapt the Ethnicity <del> source = "ethnicity"; <add> source = ETHNICITY_PERSON_SOURCE_CD; <ide> attribute = DemographicExportAttribute <ide> .getAttributeBySourceCode(source); <ide> <ide> attributeValueMapper.put(attribute, new AttributeValue(concept, <ide> nameMapper.get(concept))); <ide> <add> // Adapt the DateOfBirth <add> source = BIRTH_DATE_PERSON_SOURCE_CD; <add> attribute = DemographicExportAttribute <add> .getAttributeBySourceCode(source); <add> <add> concept = <add> source <add> + ":" <add> + (person.getDateOfBirth() == null ? "" : person.getDateOfBirth()); <add> attributeValueMapper.put(attribute, new AttributeValue(concept, <add> nameMapper.get(concept))); <add> <add> // Adapt the BirthYear <add> source = BIRTH_YEAR_PERSON_SOURCE_CD; <add> attribute = DemographicExportAttribute <add> .getAttributeBySourceCode(source); <add> <add> concept = <add> source <add> + ":" <add> + (person.getBirthYear() == null ? "" : person.getBirthYear()); <add> attributeValueMapper.put(attribute, new AttributeValue(concept, <add> nameMapper.get(concept))); <add> <add> // Adapt the BirthMonth <add> source = BIRTH_MONTH_PERSON_SOURCE_CD; <add> attribute = DemographicExportAttribute <add> .getAttributeBySourceCode(source); <add> <add> concept = <add> source <add> + ":" <add> + (person.getBirthMonth() == null ? "" : person.getBirthMonth()); <add> attributeValueMapper.put(attribute, new AttributeValue(concept, <add> nameMapper.get(concept))); <add> <add> // Adapt the BirthDay <add> source = BIRTH_DAY_PERSON_SOURCE_CD; <add> attribute = DemographicExportAttribute <add> .getAttributeBySourceCode(source); <add> <add> concept = <add> source <add> + ":" <add> + (person.getBirthDay() == null ? "" : person.getBirthDay()); <add> attributeValueMapper.put(attribute, new AttributeValue(concept, <add> nameMapper.get(concept))); <add> <add> // Adapt the EducationLevel <add> source = EDUCATION_PERSON_SOURCE_CD; <add> attribute = DemographicExportAttribute <add> .getAttributeBySourceCode(source); <add> <add> concept = <add> source <add> + ":" <add> + (person.getEducationLevel() == null ? "" : person.getEducationLevel()); <add> attributeValueMapper.put(attribute, new AttributeValue(concept, <add> nameMapper.get(concept))); <add> <add> // Adapt the MultipleBirthIndicator <add> source = MULTI_BIRTH_IND_PERSON_SOURCE_CD; <add> attribute = DemographicExportAttribute <add> .getAttributeBySourceCode(source); <add> <add> concept = <add> source <add> + ":" <add> + (person.getMultipleBirthIndicator() == null ? "" : person.getMultipleBirthIndicator()); <add> attributeValueMapper.put(attribute, new AttributeValue(concept, <add> nameMapper.get(concept))); <add> <add> // Adapt the MultipleBirthIndicatorOrderNumber <add> source = MULTI_BIRTH_NUM_PERSON_SOURCE_CD; <add> attribute = DemographicExportAttribute <add> .getAttributeBySourceCode(source); <add> <add> concept = <add> source <add> + ":" <add> + (person.getMultipleBirthIndicatorOrderNumber() == null ? "" : person.getMultipleBirthIndicatorOrderNumber()); <add> attributeValueMapper.put(attribute, new AttributeValue(concept, <add> nameMapper.get(concept))); <add> <add> // Adapt the DateOfDeath <add> source = DEATH_DATE_PERSON_SOURCE_CD; <add> attribute = DemographicExportAttribute <add> .getAttributeBySourceCode(source); <add> <add> concept = <add> source <add> + ":" <add> + (person.getDateOfDeath() == null ? "" : person.getDateOfDeath()); <add> attributeValueMapper.put(attribute, new AttributeValue(concept, <add> nameMapper.get(concept))); <add> <add> // Adapt the DeathYear <add> source = DEATH_YEAR_PERSON_SOURCE_CD; <add> attribute = DemographicExportAttribute <add> .getAttributeBySourceCode(source); <add> <add> concept = <add> source <add> + ":" <add> + (person.getDeathYear() == null ? "" : person.getDeathYear()); <add> attributeValueMapper.put(attribute, new AttributeValue(concept, <add> nameMapper.get(concept))); <add> <add> // Adapt the PedigreeQuality <add> source = PEDIGREE_PERSON_SOURCE_CD; <add> attribute = DemographicExportAttribute <add> .getAttributeBySourceCode(source); <add> <add> concept = <add> source <add> + ":" <add> + (person.getPedigreeQuality() == null ? "" : person.getPedigreeQuality()); <add> attributeValueMapper.put(attribute, new AttributeValue(concept, <add> nameMapper.get(concept))); <add> <ide> // Adapt the Race <del> source = "race"; <add> source = RACE_PERSON_SOURCE_CD; <ide> attribute = DemographicExportAttribute <ide> .getAttributeBySourceCode(source); <ide> <ide> nameMapper.get(concept))); <ide> <ide> // Adapt the Religion <del> source = "religion"; <add> source = RELIGION_PERSON_SOURCE_CD; <ide> attribute = DemographicExportAttribute <ide> .getAttributeBySourceCode(source); <ide> <ide> nameMapper.get(concept))); <ide> <ide> // Adapt the PrimaryLanguage <del> source = "primarylanguage"; <add> source = PRIMARYLANGUAGE_PERSON_SOURCE_CD; <ide> attribute = DemographicExportAttribute <ide> .getAttributeBySourceCode(source); <ide> <ide> nameMapper.get(concept))); <ide> <ide> // Adapt the MaritalStatus <del> source = "marital"; <add> source = MARITAL_PERSON_SOURCE_CD; <ide> attribute = DemographicExportAttribute <ide> .getAttributeBySourceCode(source); <ide> <ide> nameMapper.get(concept))); <ide> <ide> // Adapt the CauseOfDeath <del> source = "causeofdeath"; <add> source = CAUSEOFDEATH_PERSON_SOURCE_CD; <ide> attribute = DemographicExportAttribute <ide> .getAttributeBySourceCode(source); <ide> <ide> nameMapper.get(concept))); <ide> <ide> // Adapt the VitalStatus <del> source = "vitalstatus"; <add> source = VITALSTATUS_PERSON_SOURCE_CD; <ide> attribute = DemographicExportAttribute <ide> .getAttributeBySourceCode(source); <ide>
Java
apache-2.0
dd3c0ffadb4aedfacb6f7f435ea3d07ec0db1c58
0
IHTSDO/snow-owl,IHTSDO/snow-owl,b2ihealthcare/snow-owl,IHTSDO/snow-owl,b2ihealthcare/snow-owl,b2ihealthcare/snow-owl,IHTSDO/snow-owl,b2ihealthcare/snow-owl
/* * Copyright 2011-2015 B2i Healthcare Pte Ltd, http://b2i.sg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.b2international.snowowl.snomed.api.impl.traceability; import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.Sets.newHashSetWithExpectedSize; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.TimeZone; import org.apache.lucene.document.Document; import org.apache.lucene.search.Filter; import org.apache.lucene.search.FilteredQuery; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.Sort; import org.apache.lucene.search.TopDocs; import org.eclipse.emf.cdo.CDOObject; import org.eclipse.emf.cdo.common.id.CDOID; import org.eclipse.emf.cdo.common.id.CDOIDUtil; import org.eclipse.emf.cdo.common.revision.delta.CDOFeatureDelta; import org.eclipse.emf.cdo.common.revision.delta.CDORevisionDelta; import org.eclipse.emf.cdo.common.revision.delta.CDOSetFeatureDelta; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EStructuralFeature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.b2international.snowowl.core.ApplicationContext; import com.b2international.snowowl.core.CoreTerminologyBroker; import com.b2international.snowowl.core.ServiceProvider; import com.b2international.snowowl.core.api.IBranchPath; import com.b2international.snowowl.core.api.SnowowlRuntimeException; import com.b2international.snowowl.core.api.SnowowlServiceException; import com.b2international.snowowl.core.api.index.IIndexUpdater; import com.b2international.snowowl.core.events.Request; import com.b2international.snowowl.datastore.ICDOCommitChangeSet; import com.b2international.snowowl.datastore.index.IndexRead; import com.b2international.snowowl.datastore.index.IndexUtils; import com.b2international.snowowl.datastore.index.mapping.Mappings; import com.b2international.snowowl.datastore.server.AbstractCDOChangeProcessor; import com.b2international.snowowl.datastore.server.index.IndexServerService; import com.b2international.snowowl.eventbus.IEventBus; import com.b2international.snowowl.snomed.Component; import com.b2international.snowowl.snomed.Concept; import com.b2international.snowowl.snomed.Description; import com.b2international.snowowl.snomed.Relationship; import com.b2international.snowowl.snomed.SnomedConstants.Concepts; import com.b2international.snowowl.snomed.SnomedPackage; import com.b2international.snowowl.snomed.api.domain.browser.ISnomedBrowserDescription; import com.b2international.snowowl.snomed.api.domain.browser.ISnomedBrowserRelationship; import com.b2international.snowowl.snomed.api.domain.browser.SnomedBrowserDescriptionType; import com.b2international.snowowl.snomed.api.impl.domain.browser.SnomedBrowserConcept; import com.b2international.snowowl.snomed.api.impl.domain.browser.SnomedBrowserDescription; import com.b2international.snowowl.snomed.api.impl.domain.browser.SnomedBrowserRelationship; import com.b2international.snowowl.snomed.api.impl.domain.browser.SnomedBrowserRelationshipTarget; import com.b2international.snowowl.snomed.api.impl.domain.browser.SnomedBrowserRelationshipType; import com.b2international.snowowl.snomed.core.domain.ISnomedConcept; import com.b2international.snowowl.snomed.core.domain.ISnomedDescription; import com.b2international.snowowl.snomed.core.domain.ISnomedRelationship; import com.b2international.snowowl.snomed.core.domain.SnomedConcepts; import com.b2international.snowowl.snomed.core.domain.SnomedDescriptions; import com.b2international.snowowl.snomed.core.domain.SnomedRelationships; import com.b2international.snowowl.snomed.datastore.SnomedDescriptionLookupService; import com.b2international.snowowl.snomed.datastore.index.entry.SnomedIndexEntry; import com.b2international.snowowl.snomed.datastore.index.mapping.SnomedMappings; import com.b2international.snowowl.snomed.datastore.server.request.SnomedRequests; import com.b2international.snowowl.snomed.snomedrefset.SnomedLanguageRefSetMember; import com.b2international.snowowl.snomed.snomedrefset.SnomedRefSetMember; import com.b2international.snowowl.snomed.snomedrefset.SnomedRefSetPackage; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.util.ISO8601DateFormat; import com.google.common.base.Function; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableSet; /** * Change processor implementation that produces a log entry for committed transactions. */ public class SnomedTraceabilityChangeProcessor extends AbstractCDOChangeProcessor<SnomedIndexEntry, CDOObject> { private static final Logger LOGGER = LoggerFactory.getLogger("traceability"); // Track primary terminology components and reference set members relevant to acceptability and inactivation private static final Collection<EClass> TRACKED_ECLASSES = ImmutableSet.of(SnomedPackage.Literals.CONCEPT, SnomedPackage.Literals.DESCRIPTION, SnomedPackage.Literals.RELATIONSHIP, SnomedRefSetPackage.Literals.SNOMED_LANGUAGE_REF_SET_MEMBER, SnomedRefSetPackage.Literals.SNOMED_ASSOCIATION_REF_SET_MEMBER, SnomedRefSetPackage.Literals.SNOMED_ATTRIBUTE_VALUE_REF_SET_MEMBER); private static final Set<String> TRACKED_REFERENCE_SET_IDS = ImmutableSet.of(Concepts.REFSET_CONCEPT_INACTIVITY_INDICATOR, Concepts.REFSET_DESCRIPTION_INACTIVITY_INDICATOR, Concepts.REFSET_ALTERNATIVE_ASSOCIATION, Concepts.REFSET_MOVED_FROM_ASSOCIATION, Concepts.REFSET_MOVED_TO_ASSOCIATION, Concepts.REFSET_POSSIBLY_EQUIVALENT_TO_ASSOCIATION, Concepts.REFSET_REFERS_TO_ASSOCIATION, Concepts.REFSET_REPLACED_BY_ASSOCIATION, Concepts.REFSET_SAME_AS_ASSOCIATION, Concepts.REFSET_SIMILAR_TO_ASSOCIATION, Concepts.REFSET_WAS_A_ASSOCIATION); private static final Set<String> FIELDS_TO_LOAD = SnomedMappings.fieldsToLoad() .id() .descriptionConcept() .relationshipSource() .build(); private static final ObjectWriter WRITER; private static final Set<EStructuralFeature> IGNORED_FEATURES = ImmutableSet.<EStructuralFeature>of(SnomedPackage.Literals.CONCEPT__DESCRIPTIONS, SnomedPackage.Literals.CONCEPT__INBOUND_RELATIONSHIPS, SnomedPackage.Literals.CONCEPT__OUTBOUND_RELATIONSHIPS); static { final ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(Include.NON_EMPTY); final ISO8601DateFormat df = new ISO8601DateFormat(); df.setTimeZone(TimeZone.getTimeZone("UTC")); objectMapper.setDateFormat(df); objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); WRITER = objectMapper.writer(); } private TraceabilityEntry entry; public SnomedTraceabilityChangeProcessor(final IIndexUpdater<SnomedIndexEntry> indexUpdater, final IBranchPath branchPath) { super(indexUpdater, branchPath, TRACKED_ECLASSES); } @Override public void process(ICDOCommitChangeSet commitChangeSet) throws SnowowlServiceException { this.entry = new TraceabilityEntry(commitChangeSet); super.process(commitChangeSet); if (detachedComponents.isEmpty()) { return; } final Set<Long> detachedStorageKeys = newHashSetWithExpectedSize(detachedComponents.size()); for (Entry<CDOID, EClass> entry : detachedComponents) { final long storageKey = CDOIDUtil.getLong(entry.getKey()); final EClass eClass = entry.getValue(); if (SnomedPackage.Literals.CONCEPT.equals(eClass) || SnomedPackage.Literals.DESCRIPTION.equals(eClass) || SnomedPackage.Literals.RELATIONSHIP.equals(eClass)) { detachedStorageKeys.add(storageKey); } } if (detachedStorageKeys.isEmpty()) { return; } ((IndexServerService<?>) indexService).executeReadTransaction(branchPath, new IndexRead<Void>() { @Override public Void execute(IndexSearcher index) throws IOException { final Query componentTypeQuery = SnomedMappings.newQuery() .concept() .description() .relationship() .matchAny(); final Filter storageKeyFilter = Mappings.storageKey().createTermsFilter(detachedStorageKeys); // XXX: wrapping into FilteredQuery because we don't want to retrieve all components if detachedStorageKeys is null for some reason final TopDocs topDocs = index.search(new FilteredQuery(componentTypeQuery, storageKeyFilter), null, detachedComponents.size(), Sort.INDEXORDER, false, false); if (IndexUtils.isEmpty(topDocs)) { return null; } for (int i = 0; i < topDocs.scoreDocs.length; i++) { final Document document = index.doc(topDocs.scoreDocs[i].doc, FIELDS_TO_LOAD); final String detachedComponentId = SnomedMappings.id().getValueAsString(document); String conceptId = document.get(SnomedMappings.relationshipSource().fieldName()); if (conceptId != null) { entry.registerChange(conceptId, new TraceabilityChange(SnomedPackage.Literals.RELATIONSHIP, detachedComponentId, ChangeType.DELETE)); continue; } conceptId = document.get(SnomedMappings.descriptionConcept().fieldName()); if (conceptId != null) { entry.registerChange(conceptId, new TraceabilityChange(SnomedPackage.Literals.DESCRIPTION, detachedComponentId, ChangeType.DELETE)); continue; } entry.registerChange(detachedComponentId, new TraceabilityChange(SnomedPackage.Literals.CONCEPT, detachedComponentId, ChangeType.DELETE)); } return null; } }); } @Override protected void processAddition(CDOObject newComponent) { final EClass eClass = newComponent.eClass(); if (SnomedPackage.Literals.CONCEPT.equals(eClass)) { final Concept newConcept = (Concept) newComponent; entry.registerChange(newConcept.getId(), new TraceabilityChange(eClass, newConcept.getId(), ChangeType.CREATE)); } else if (SnomedPackage.Literals.DESCRIPTION.equals(eClass)) { final Description newDescription = (Description) newComponent; entry.registerChange(newDescription.getConcept().getId(), new TraceabilityChange(eClass, newDescription.getId(), ChangeType.CREATE)); } else if (SnomedPackage.Literals.RELATIONSHIP.equals(eClass)) { final Relationship newRelationship = (Relationship) newComponent; entry.registerChange(newRelationship.getSource().getId(), new TraceabilityChange(eClass, newRelationship.getId(), ChangeType.CREATE)); } // Reference set members are logged through their container core component change } @Override protected void processUpdate(CDOObject dirtyComponent) { final EClass eClass = dirtyComponent.eClass(); final CDORevisionDelta revisionDelta = commitChangeSet.getRevisionDeltas().get(dirtyComponent.cdoID()); if (SnomedPackage.Literals.CONCEPT.equals(eClass)) { final Concept dirtyConcept = (Concept) dirtyComponent; registerInactivationOrUpdate(eClass, dirtyConcept.getId(), dirtyConcept.getId(), revisionDelta); } else if (SnomedPackage.Literals.DESCRIPTION.equals(eClass)) { final Description dirtyDescription = (Description) dirtyComponent; registerInactivationOrUpdate(eClass, dirtyDescription.getConcept().getId(), dirtyDescription.getId(), revisionDelta); } else if (SnomedPackage.Literals.RELATIONSHIP.equals(eClass)) { final Relationship dirtyRelationship = (Relationship) dirtyComponent; registerInactivationOrUpdate(eClass, dirtyRelationship.getSource().getId(), dirtyRelationship.getId(), revisionDelta); } else if (SnomedRefSetPackage.Literals.SNOMED_LANGUAGE_REF_SET_MEMBER.equals(eClass)) { // An updated language reference set member is recorded as an update on the description final SnomedLanguageRefSetMember newMember = (SnomedLanguageRefSetMember) dirtyComponent; final Description description = new SnomedDescriptionLookupService().getComponent(newMember.getReferencedComponentId(), commitChangeSet.getView()); entry.registerChange(description.getConcept().getId(), new TraceabilityChange(description.eClass(), description.getId(), ChangeType.UPDATE)); } else if (SnomedRefSetPackage.Literals.SNOMED_ASSOCIATION_REF_SET_MEMBER.equals(eClass) || SnomedRefSetPackage.Literals.SNOMED_ATTRIBUTE_VALUE_REF_SET_MEMBER.equals(eClass)) { // An updated inactivation reason or association reference set member is recorded as an update on the referenced component final SnomedRefSetMember newMember = (SnomedRefSetMember) dirtyComponent; if (TRACKED_REFERENCE_SET_IDS.contains(newMember.getRefSetIdentifierId())) { final short referencedComponentType = newMember.getReferencedComponentType(); final String referencedTerminologyComponentId = CoreTerminologyBroker.getInstance().getTerminologyComponentId(referencedComponentType); final Component referencedComponent = (Component) CoreTerminologyBroker.getInstance() .getLookupService(referencedTerminologyComponentId) .getComponent(newMember.getReferencedComponentId(), commitChangeSet.getView()); final String conceptId = referencedComponent instanceof Description ? ((Description) referencedComponent).getConcept().getId() : referencedComponent.getId(); entry.registerChange(conceptId, new TraceabilityChange(referencedComponent.eClass(), referencedComponent.getId(), ChangeType.UPDATE)); } } } private void registerInactivationOrUpdate(final EClass eClass, final String conceptId, final String componentId, CDORevisionDelta revisionDelta) { CDOSetFeatureDelta activeDelta = (CDOSetFeatureDelta) revisionDelta.getFeatureDelta(SnomedPackage.Literals.COMPONENT__ACTIVE); if (activeDelta != null && Boolean.FALSE.equals(activeDelta.getValue())) { entry.registerChange(conceptId, new TraceabilityChange(eClass, componentId, ChangeType.INACTIVATE)); } else { for (CDOFeatureDelta featureDelta : revisionDelta.getFeatureDeltas()) { if (!IGNORED_FEATURES.contains(featureDelta.getFeature())) { entry.registerChange(conceptId, new TraceabilityChange(eClass, componentId, ChangeType.UPDATE)); } } } } @Override public void afterCommit() { final Set<String> conceptIds = entry.getChanges().keySet(); final String branch = commitChangeSet.getView().getBranch().getPathName(); final IEventBus bus = ApplicationContext.getServiceForClass(IEventBus.class); final Request<ServiceProvider, SnomedConcepts> conceptSearchRequest = SnomedRequests.prepareSearchConcept() .setComponentIds(conceptIds) .setOffset(0) .setLimit(entry.getChanges().size()) .setExpand("descriptions(),relationships(expand(destination()))") .build(branch); final SnomedConcepts concepts = conceptSearchRequest.executeSync(bus); final Set<String> hasChildrenStated = collectNonLeafs(conceptIds, branch, bus, Concepts.STATED_RELATIONSHIP); final Set<String> hasChildrenInferred = collectNonLeafs(conceptIds, branch, bus, Concepts.INFERRED_RELATIONSHIP); for (ISnomedConcept concept : concepts) { SnomedBrowserConcept convertedConcept = new SnomedBrowserConcept(); convertedConcept.setActive(concept.isActive()); convertedConcept.setConceptId(concept.getId()); convertedConcept.setDefinitionStatus(concept.getDefinitionStatus()); convertedConcept.setDescriptions(convertDescriptions(concept.getDescriptions())); convertedConcept.setEffectiveTime(concept.getEffectiveTime()); convertedConcept.setModuleId(concept.getModuleId()); convertedConcept.setRelationships(convertRelationships(concept.getRelationships())); convertedConcept.setIsLeafStated(!hasChildrenStated.contains(concept.getId())); convertedConcept.setIsLeafInferred(!hasChildrenInferred.contains(concept.getId())); convertedConcept.setFsn(concept.getId()); // PT and SYN labels are not populated entry.setConcept(convertedConcept.getId(), convertedConcept); } try { LOGGER.info(WRITER.writeValueAsString(entry)); } catch (IOException e) { throw SnowowlRuntimeException.wrap(e); } super.afterCommit(); } private Set<String> collectNonLeafs(final Set<String> conceptIds, final String branch, final IEventBus bus, String characteristicTypeId) { final Set<String> hasChildren = newHashSet(); final Request<ServiceProvider, SnomedRelationships> hasChildrenSearchRequest = SnomedRequests.prepareSearchRelationship() .filterByDestination(conceptIds) .filterByActive(true) .filterByCharacteristicType(characteristicTypeId) .all() .build(branch); final SnomedRelationships relationships = hasChildrenSearchRequest.executeSync(bus); for (ISnomedRelationship relationship : relationships) { hasChildren.add(relationship.getDestinationId()); } return hasChildren; } private List<ISnomedBrowserDescription> convertDescriptions(SnomedDescriptions descriptions) { return FluentIterable.from(descriptions).transform(new Function<ISnomedDescription, ISnomedBrowserDescription>() { @Override public ISnomedBrowserDescription apply(ISnomedDescription input) { final SnomedBrowserDescription convertedDescription = new SnomedBrowserDescription(); convertedDescription.setAcceptabilityMap(input.getAcceptabilityMap()); convertedDescription.setActive(input.isActive()); convertedDescription.setCaseSignificance(input.getCaseSignificance()); convertedDescription.setConceptId(input.getConceptId()); convertedDescription.setDescriptionId(input.getId()); convertedDescription.setEffectiveTime(input.getEffectiveTime()); convertedDescription.setLang(input.getLanguageCode()); convertedDescription.setModuleId(input.getModuleId()); convertedDescription.setTerm(input.getTerm()); convertedDescription.setType(SnomedBrowserDescriptionType.getByConceptId(input.getTypeId())); return convertedDescription; } }).toList(); } private List<ISnomedBrowserRelationship> convertRelationships(SnomedRelationships relationships) { return FluentIterable.from(relationships).transform(new Function<ISnomedRelationship, ISnomedBrowserRelationship>() { @Override public ISnomedBrowserRelationship apply(ISnomedRelationship input) { final SnomedBrowserRelationship convertedRelationship = new SnomedBrowserRelationship(); convertedRelationship.setActive(input.isActive()); convertedRelationship.setCharacteristicType(input.getCharacteristicType()); convertedRelationship.setEffectiveTime(input.getEffectiveTime()); convertedRelationship.setGroupId(input.getGroup()); convertedRelationship.setModifier(input.getModifier()); convertedRelationship.setModuleId(input.getModuleId()); convertedRelationship.setRelationshipId(input.getId()); convertedRelationship.setSourceId(input.getSourceId()); final SnomedBrowserRelationshipType type = new SnomedBrowserRelationshipType(input.getTypeId()); type.setFsn(input.getTypeId()); convertedRelationship.setType(type); final SnomedBrowserRelationshipTarget target = new SnomedBrowserRelationshipTarget(); target.setActive(input.getDestinationConcept().isActive()); target.setConceptId(input.getDestinationId()); target.setDefinitionStatus(input.getDestinationConcept().getDefinitionStatus()); target.setEffectiveTime(input.getDestinationConcept().getEffectiveTime()); target.setFsn(input.getDestinationId()); target.setModuleId(input.getDestinationConcept().getModuleId()); convertedRelationship.setTarget(target); return convertedRelationship; } }).toList(); } @Override protected void processDeletion(Entry<CDOID, EClass> detachedComponent) { // Handled separately } @Override public void reset() { entry = null; super.reset(); } @Override public String getChangeDescription() { return String.format("Traceability logged for %d concept(s).", entry.getChanges().size()); } @Override public String getName() { return "SNOMED CT Traceability"; } }
snomed/com.b2international.snowowl.snomed.api.impl/src/com/b2international/snowowl/snomed/api/impl/traceability/SnomedTraceabilityChangeProcessor.java
/* * Copyright 2011-2015 B2i Healthcare Pte Ltd, http://b2i.sg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.b2international.snowowl.snomed.api.impl.traceability; import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.Sets.newHashSetWithExpectedSize; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.TimeZone; import org.apache.lucene.document.Document; import org.apache.lucene.search.FilteredQuery; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.Sort; import org.apache.lucene.search.TopDocs; import org.eclipse.emf.cdo.CDOObject; import org.eclipse.emf.cdo.common.id.CDOID; import org.eclipse.emf.cdo.common.id.CDOIDUtil; import org.eclipse.emf.cdo.common.revision.delta.CDOFeatureDelta; import org.eclipse.emf.cdo.common.revision.delta.CDORevisionDelta; import org.eclipse.emf.cdo.common.revision.delta.CDOSetFeatureDelta; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EStructuralFeature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.b2international.snowowl.core.ApplicationContext; import com.b2international.snowowl.core.CoreTerminologyBroker; import com.b2international.snowowl.core.ServiceProvider; import com.b2international.snowowl.core.api.IBranchPath; import com.b2international.snowowl.core.api.SnowowlRuntimeException; import com.b2international.snowowl.core.api.SnowowlServiceException; import com.b2international.snowowl.core.api.index.IIndexUpdater; import com.b2international.snowowl.core.events.Request; import com.b2international.snowowl.datastore.ICDOCommitChangeSet; import com.b2international.snowowl.datastore.index.IndexRead; import com.b2international.snowowl.datastore.index.IndexUtils; import com.b2international.snowowl.datastore.index.mapping.Mappings; import com.b2international.snowowl.datastore.server.AbstractCDOChangeProcessor; import com.b2international.snowowl.datastore.server.index.IndexServerService; import com.b2international.snowowl.eventbus.IEventBus; import com.b2international.snowowl.snomed.Component; import com.b2international.snowowl.snomed.Concept; import com.b2international.snowowl.snomed.Description; import com.b2international.snowowl.snomed.Relationship; import com.b2international.snowowl.snomed.SnomedConstants.Concepts; import com.b2international.snowowl.snomed.SnomedPackage; import com.b2international.snowowl.snomed.api.domain.browser.ISnomedBrowserDescription; import com.b2international.snowowl.snomed.api.domain.browser.ISnomedBrowserRelationship; import com.b2international.snowowl.snomed.api.domain.browser.SnomedBrowserDescriptionType; import com.b2international.snowowl.snomed.api.impl.domain.browser.SnomedBrowserConcept; import com.b2international.snowowl.snomed.api.impl.domain.browser.SnomedBrowserDescription; import com.b2international.snowowl.snomed.api.impl.domain.browser.SnomedBrowserRelationship; import com.b2international.snowowl.snomed.api.impl.domain.browser.SnomedBrowserRelationshipTarget; import com.b2international.snowowl.snomed.api.impl.domain.browser.SnomedBrowserRelationshipType; import com.b2international.snowowl.snomed.core.domain.ISnomedConcept; import com.b2international.snowowl.snomed.core.domain.ISnomedDescription; import com.b2international.snowowl.snomed.core.domain.ISnomedRelationship; import com.b2international.snowowl.snomed.core.domain.SnomedConcepts; import com.b2international.snowowl.snomed.core.domain.SnomedDescriptions; import com.b2international.snowowl.snomed.core.domain.SnomedRelationships; import com.b2international.snowowl.snomed.datastore.SnomedDescriptionLookupService; import com.b2international.snowowl.snomed.datastore.index.entry.SnomedIndexEntry; import com.b2international.snowowl.snomed.datastore.index.mapping.SnomedMappings; import com.b2international.snowowl.snomed.datastore.server.request.SnomedRequests; import com.b2international.snowowl.snomed.snomedrefset.SnomedLanguageRefSetMember; import com.b2international.snowowl.snomed.snomedrefset.SnomedRefSetMember; import com.b2international.snowowl.snomed.snomedrefset.SnomedRefSetPackage; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.util.ISO8601DateFormat; import com.google.common.base.Function; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableSet; /** * Change processor implementation that produces a log entry for committed transactions. */ public class SnomedTraceabilityChangeProcessor extends AbstractCDOChangeProcessor<SnomedIndexEntry, CDOObject> { private static final Logger LOGGER = LoggerFactory.getLogger("traceability"); // Track primary terminology components and reference set members relevant to acceptability and inactivation private static final Collection<EClass> TRACKED_ECLASSES = ImmutableSet.of(SnomedPackage.Literals.CONCEPT, SnomedPackage.Literals.DESCRIPTION, SnomedPackage.Literals.RELATIONSHIP, SnomedRefSetPackage.Literals.SNOMED_LANGUAGE_REF_SET_MEMBER, SnomedRefSetPackage.Literals.SNOMED_ASSOCIATION_REF_SET_MEMBER, SnomedRefSetPackage.Literals.SNOMED_ATTRIBUTE_VALUE_REF_SET_MEMBER); private static final Set<String> TRACKED_REFERENCE_SET_IDS = ImmutableSet.of(Concepts.REFSET_CONCEPT_INACTIVITY_INDICATOR, Concepts.REFSET_DESCRIPTION_INACTIVITY_INDICATOR, Concepts.REFSET_ALTERNATIVE_ASSOCIATION, Concepts.REFSET_MOVED_FROM_ASSOCIATION, Concepts.REFSET_MOVED_TO_ASSOCIATION, Concepts.REFSET_POSSIBLY_EQUIVALENT_TO_ASSOCIATION, Concepts.REFSET_REFERS_TO_ASSOCIATION, Concepts.REFSET_REPLACED_BY_ASSOCIATION, Concepts.REFSET_SAME_AS_ASSOCIATION, Concepts.REFSET_SIMILAR_TO_ASSOCIATION, Concepts.REFSET_WAS_A_ASSOCIATION); private static final Set<String> FIELDS_TO_LOAD = SnomedMappings.fieldsToLoad() .id() .descriptionConcept() .relationshipSource() .build(); private static final ObjectWriter WRITER; private static final Set<EStructuralFeature> IGNORED_FEATURES = ImmutableSet.<EStructuralFeature>of(SnomedPackage.Literals.CONCEPT__DESCRIPTIONS, SnomedPackage.Literals.CONCEPT__INBOUND_RELATIONSHIPS, SnomedPackage.Literals.CONCEPT__OUTBOUND_RELATIONSHIPS); static { final ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(Include.NON_EMPTY); final ISO8601DateFormat df = new ISO8601DateFormat(); df.setTimeZone(TimeZone.getTimeZone("UTC")); objectMapper.setDateFormat(df); objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); WRITER = objectMapper.writer(); } private TraceabilityEntry entry; public SnomedTraceabilityChangeProcessor(final IIndexUpdater<SnomedIndexEntry> indexUpdater, final IBranchPath branchPath) { super(indexUpdater, branchPath, TRACKED_ECLASSES); } @Override public void process(ICDOCommitChangeSet commitChangeSet) throws SnowowlServiceException { this.entry = new TraceabilityEntry(commitChangeSet); super.process(commitChangeSet); if (detachedComponents.isEmpty()) { return; } final Set<Long> detachedStorageKeys = newHashSetWithExpectedSize(detachedComponents.size()); for (Entry<CDOID, EClass> entry : detachedComponents) { final long storageKey = CDOIDUtil.getLong(entry.getKey()); final EClass eClass = entry.getValue(); if (SnomedPackage.Literals.CONCEPT.equals(eClass) || SnomedPackage.Literals.DESCRIPTION.equals(eClass) || SnomedPackage.Literals.RELATIONSHIP.equals(eClass)) { detachedStorageKeys.add(storageKey); } } ((IndexServerService<?>) indexService).executeReadTransaction(branchPath, new IndexRead<Void>() { @Override public Void execute(IndexSearcher index) throws IOException { final Query storageKeyQuery = SnomedMappings.newQuery() .and(SnomedMappings.newQuery().concept().description().relationship().matchAny()) .and(new FilteredQuery(new MatchAllDocsQuery(), Mappings.storageKey().createTermsFilter(detachedStorageKeys))) .matchAll(); final TopDocs topDocs = index.search(storageKeyQuery, null, detachedComponents.size(), Sort.INDEXORDER, false, false); if (IndexUtils.isEmpty(topDocs)) { return null; } for (int i = 0; i < topDocs.scoreDocs.length; i++) { final Document document = index.doc(topDocs.scoreDocs[i].doc, FIELDS_TO_LOAD); final String detachedComponentId = SnomedMappings.id().getValueAsString(document); String conceptId = document.get(SnomedMappings.relationshipSource().fieldName()); if (conceptId != null) { entry.registerChange(conceptId, new TraceabilityChange(SnomedPackage.Literals.RELATIONSHIP, detachedComponentId, ChangeType.DELETE)); continue; } conceptId = document.get(SnomedMappings.descriptionConcept().fieldName()); if (conceptId != null) { entry.registerChange(conceptId, new TraceabilityChange(SnomedPackage.Literals.DESCRIPTION, detachedComponentId, ChangeType.DELETE)); continue; } entry.registerChange(detachedComponentId, new TraceabilityChange(SnomedPackage.Literals.CONCEPT, detachedComponentId, ChangeType.DELETE)); } return null; } }); } @Override protected void processAddition(CDOObject newComponent) { final EClass eClass = newComponent.eClass(); if (SnomedPackage.Literals.CONCEPT.equals(eClass)) { final Concept newConcept = (Concept) newComponent; entry.registerChange(newConcept.getId(), new TraceabilityChange(eClass, newConcept.getId(), ChangeType.CREATE)); } else if (SnomedPackage.Literals.DESCRIPTION.equals(eClass)) { final Description newDescription = (Description) newComponent; entry.registerChange(newDescription.getConcept().getId(), new TraceabilityChange(eClass, newDescription.getId(), ChangeType.CREATE)); } else if (SnomedPackage.Literals.RELATIONSHIP.equals(eClass)) { final Relationship newRelationship = (Relationship) newComponent; entry.registerChange(newRelationship.getSource().getId(), new TraceabilityChange(eClass, newRelationship.getId(), ChangeType.CREATE)); } // Reference set members are logged through their container core component change } @Override protected void processUpdate(CDOObject dirtyComponent) { final EClass eClass = dirtyComponent.eClass(); final CDORevisionDelta revisionDelta = commitChangeSet.getRevisionDeltas().get(dirtyComponent.cdoID()); if (SnomedPackage.Literals.CONCEPT.equals(eClass)) { final Concept dirtyConcept = (Concept) dirtyComponent; registerInactivationOrUpdate(eClass, dirtyConcept.getId(), dirtyConcept.getId(), revisionDelta); } else if (SnomedPackage.Literals.DESCRIPTION.equals(eClass)) { final Description dirtyDescription = (Description) dirtyComponent; registerInactivationOrUpdate(eClass, dirtyDescription.getConcept().getId(), dirtyDescription.getId(), revisionDelta); } else if (SnomedPackage.Literals.RELATIONSHIP.equals(eClass)) { final Relationship dirtyRelationship = (Relationship) dirtyComponent; registerInactivationOrUpdate(eClass, dirtyRelationship.getSource().getId(), dirtyRelationship.getId(), revisionDelta); } else if (SnomedRefSetPackage.Literals.SNOMED_LANGUAGE_REF_SET_MEMBER.equals(eClass)) { // An updated language reference set member is recorded as an update on the description final SnomedLanguageRefSetMember newMember = (SnomedLanguageRefSetMember) dirtyComponent; final Description description = new SnomedDescriptionLookupService().getComponent(newMember.getReferencedComponentId(), commitChangeSet.getView()); entry.registerChange(description.getConcept().getId(), new TraceabilityChange(description.eClass(), description.getId(), ChangeType.UPDATE)); } else if (SnomedRefSetPackage.Literals.SNOMED_ASSOCIATION_REF_SET_MEMBER.equals(eClass) || SnomedRefSetPackage.Literals.SNOMED_ATTRIBUTE_VALUE_REF_SET_MEMBER.equals(eClass)) { // An updated inactivation reason or association reference set member is recorded as an update on the referenced component final SnomedRefSetMember newMember = (SnomedRefSetMember) dirtyComponent; if (TRACKED_REFERENCE_SET_IDS.contains(newMember.getRefSetIdentifierId())) { final short referencedComponentType = newMember.getReferencedComponentType(); final String referencedTerminologyComponentId = CoreTerminologyBroker.getInstance().getTerminologyComponentId(referencedComponentType); final Component referencedComponent = (Component) CoreTerminologyBroker.getInstance() .getLookupService(referencedTerminologyComponentId) .getComponent(newMember.getReferencedComponentId(), commitChangeSet.getView()); final String conceptId = referencedComponent instanceof Description ? ((Description) referencedComponent).getConcept().getId() : referencedComponent.getId(); entry.registerChange(conceptId, new TraceabilityChange(referencedComponent.eClass(), referencedComponent.getId(), ChangeType.UPDATE)); } } } private void registerInactivationOrUpdate(final EClass eClass, final String conceptId, final String componentId, CDORevisionDelta revisionDelta) { CDOSetFeatureDelta activeDelta = (CDOSetFeatureDelta) revisionDelta.getFeatureDelta(SnomedPackage.Literals.COMPONENT__ACTIVE); if (activeDelta != null && Boolean.FALSE.equals(activeDelta.getValue())) { entry.registerChange(conceptId, new TraceabilityChange(eClass, componentId, ChangeType.INACTIVATE)); } else { for (CDOFeatureDelta featureDelta : revisionDelta.getFeatureDeltas()) { if (!IGNORED_FEATURES.contains(featureDelta.getFeature())) { entry.registerChange(conceptId, new TraceabilityChange(eClass, componentId, ChangeType.UPDATE)); } } } } @Override public void afterCommit() { final Set<String> conceptIds = entry.getChanges().keySet(); final String branch = commitChangeSet.getView().getBranch().getPathName(); final IEventBus bus = ApplicationContext.getServiceForClass(IEventBus.class); final Request<ServiceProvider, SnomedConcepts> conceptSearchRequest = SnomedRequests.prepareSearchConcept() .setComponentIds(conceptIds) .setOffset(0) .setLimit(entry.getChanges().size()) .setExpand("descriptions(),relationships(expand(destination()))") .build(branch); final SnomedConcepts concepts = conceptSearchRequest.executeSync(bus); final Set<String> hasChildrenStated = collectNonLeafs(conceptIds, branch, bus, Concepts.STATED_RELATIONSHIP); final Set<String> hasChildrenInferred = collectNonLeafs(conceptIds, branch, bus, Concepts.INFERRED_RELATIONSHIP); for (ISnomedConcept concept : concepts) { SnomedBrowserConcept convertedConcept = new SnomedBrowserConcept(); convertedConcept.setActive(concept.isActive()); convertedConcept.setConceptId(concept.getId()); convertedConcept.setDefinitionStatus(concept.getDefinitionStatus()); convertedConcept.setDescriptions(convertDescriptions(concept.getDescriptions())); convertedConcept.setEffectiveTime(concept.getEffectiveTime()); convertedConcept.setModuleId(concept.getModuleId()); convertedConcept.setRelationships(convertRelationships(concept.getRelationships())); convertedConcept.setIsLeafStated(!hasChildrenStated.contains(concept.getId())); convertedConcept.setIsLeafInferred(!hasChildrenInferred.contains(concept.getId())); convertedConcept.setFsn(concept.getId()); // PT and SYN labels are not populated entry.setConcept(convertedConcept.getId(), convertedConcept); } try { LOGGER.info(WRITER.writeValueAsString(entry)); } catch (IOException e) { throw SnowowlRuntimeException.wrap(e); } super.afterCommit(); } private Set<String> collectNonLeafs(final Set<String> conceptIds, final String branch, final IEventBus bus, String characteristicTypeId) { final Set<String> hasChildren = newHashSet(); final Request<ServiceProvider, SnomedRelationships> hasChildrenSearchRequest = SnomedRequests.prepareSearchRelationship() .filterByDestination(conceptIds) .filterByActive(true) .filterByCharacteristicType(characteristicTypeId) .all() .build(branch); final SnomedRelationships relationships = hasChildrenSearchRequest.executeSync(bus); for (ISnomedRelationship relationship : relationships) { hasChildren.add(relationship.getDestinationId()); } return hasChildren; } private List<ISnomedBrowserDescription> convertDescriptions(SnomedDescriptions descriptions) { return FluentIterable.from(descriptions).transform(new Function<ISnomedDescription, ISnomedBrowserDescription>() { @Override public ISnomedBrowserDescription apply(ISnomedDescription input) { final SnomedBrowserDescription convertedDescription = new SnomedBrowserDescription(); convertedDescription.setAcceptabilityMap(input.getAcceptabilityMap()); convertedDescription.setActive(input.isActive()); convertedDescription.setCaseSignificance(input.getCaseSignificance()); convertedDescription.setConceptId(input.getConceptId()); convertedDescription.setDescriptionId(input.getId()); convertedDescription.setEffectiveTime(input.getEffectiveTime()); convertedDescription.setLang(input.getLanguageCode()); convertedDescription.setModuleId(input.getModuleId()); convertedDescription.setTerm(input.getTerm()); convertedDescription.setType(SnomedBrowserDescriptionType.getByConceptId(input.getTypeId())); return convertedDescription; } }).toList(); } private List<ISnomedBrowserRelationship> convertRelationships(SnomedRelationships relationships) { return FluentIterable.from(relationships).transform(new Function<ISnomedRelationship, ISnomedBrowserRelationship>() { @Override public ISnomedBrowserRelationship apply(ISnomedRelationship input) { final SnomedBrowserRelationship convertedRelationship = new SnomedBrowserRelationship(); convertedRelationship.setActive(input.isActive()); convertedRelationship.setCharacteristicType(input.getCharacteristicType()); convertedRelationship.setEffectiveTime(input.getEffectiveTime()); convertedRelationship.setGroupId(input.getGroup()); convertedRelationship.setModifier(input.getModifier()); convertedRelationship.setModuleId(input.getModuleId()); convertedRelationship.setRelationshipId(input.getId()); convertedRelationship.setSourceId(input.getSourceId()); final SnomedBrowserRelationshipType type = new SnomedBrowserRelationshipType(input.getTypeId()); type.setFsn(input.getTypeId()); convertedRelationship.setType(type); final SnomedBrowserRelationshipTarget target = new SnomedBrowserRelationshipTarget(); target.setActive(input.getDestinationConcept().isActive()); target.setConceptId(input.getDestinationId()); target.setDefinitionStatus(input.getDestinationConcept().getDefinitionStatus()); target.setEffectiveTime(input.getDestinationConcept().getEffectiveTime()); target.setFsn(input.getDestinationId()); target.setModuleId(input.getDestinationConcept().getModuleId()); convertedRelationship.setTarget(target); return convertedRelationship; } }).toList(); } @Override protected void processDeletion(Entry<CDOID, EClass> detachedComponent) { // Handled separately } @Override public void reset() { entry = null; super.reset(); } @Override public String getChangeDescription() { return String.format("Traceability logged for %d concept(s).", entry.getChanges().size()); } @Override public String getName() { return "SNOMED CT Traceability"; } }
[snomed] Also check if detached components included at least one item... ...of relevance in SnomedTraceabilityChangeProcessor
snomed/com.b2international.snowowl.snomed.api.impl/src/com/b2international/snowowl/snomed/api/impl/traceability/SnomedTraceabilityChangeProcessor.java
[snomed] Also check if detached components included at least one item...
<ide><path>nomed/com.b2international.snowowl.snomed.api.impl/src/com/b2international/snowowl/snomed/api/impl/traceability/SnomedTraceabilityChangeProcessor.java <ide> import java.util.TimeZone; <ide> <ide> import org.apache.lucene.document.Document; <add>import org.apache.lucene.search.Filter; <ide> import org.apache.lucene.search.FilteredQuery; <ide> import org.apache.lucene.search.IndexSearcher; <del>import org.apache.lucene.search.MatchAllDocsQuery; <ide> import org.apache.lucene.search.Query; <ide> import org.apache.lucene.search.Sort; <ide> import org.apache.lucene.search.TopDocs; <ide> } <ide> } <ide> <add> if (detachedStorageKeys.isEmpty()) { <add> return; <add> } <add> <ide> ((IndexServerService<?>) indexService).executeReadTransaction(branchPath, new IndexRead<Void>() { <ide> @Override <ide> public Void execute(IndexSearcher index) throws IOException { <ide> <del> final Query storageKeyQuery = SnomedMappings.newQuery() <del> .and(SnomedMappings.newQuery().concept().description().relationship().matchAny()) <del> .and(new FilteredQuery(new MatchAllDocsQuery(), Mappings.storageKey().createTermsFilter(detachedStorageKeys))) <del> .matchAll(); <del> <del> final TopDocs topDocs = index.search(storageKeyQuery, null, detachedComponents.size(), Sort.INDEXORDER, false, false); <add> final Query componentTypeQuery = SnomedMappings.newQuery() <add> .concept() <add> .description() <add> .relationship() <add> .matchAny(); <add> <add> final Filter storageKeyFilter = Mappings.storageKey().createTermsFilter(detachedStorageKeys); <add> <add> // XXX: wrapping into FilteredQuery because we don't want to retrieve all components if detachedStorageKeys is null for some reason <add> final TopDocs topDocs = index.search(new FilteredQuery(componentTypeQuery, storageKeyFilter), null, detachedComponents.size(), Sort.INDEXORDER, false, false); <ide> if (IndexUtils.isEmpty(topDocs)) { <ide> return null; <ide> }
JavaScript
mit
d23d8ea288e4bb440d51ff3ecf32b271b3d698a5
0
wibron/helg
'use strict'; var assert = require('assert'), timeKeeper = require('timekeeper'), helg = require('./'); var wednesday = new Date(1414580400000), saturday = new Date(1414839600000), friday = new Date(1414771500000), sunday = new Date(1414926000000); describe('Helg', function () { describe('When passing an erroneous date object', function () { it('should throw an error', function () { var invalid = function () { return helg.ere('Sunday 11th 2014'); }; assert.throws(invalid, Error); }); }) describe('When setting the date manually', function () { it('should return false when the day is wednesday', function () { assert.equal(helg.ere(wednesday), false); }); it('should return true when the day is saturday', function () { assert.equal(helg.ere(saturday), true); }); it('should return true when the day is sunday', function () { assert.equal(helg.ere(sunday), true); }); it('should return true when the day is friday and after 5pm', function () { assert.equal(helg.ere(friday), true); }); }); describe('When getting the date from the computers local time', function () { it('should return true when the day is saturday', function () { timeKeeper.travel(saturday); assert.equal(helg.ere(), true); }); it('should return false when the day is wednesday', function () { timeKeeper.travel(wednesday); assert.equal(helg.ere(), false); }); it('should return true when the day is friday and after 5pm', function () { timeKeeper.travel(friday); assert.equal(helg.ere(), true); }); it('should return true when the day is sunday', function () { timeKeeper.travel(sunday); assert.equal(helg.ere(), true); }); }); });
test.js
'use strict'; var assert = require('assert'), timeKeeper = require('timekeeper'), helg = require('./'); var wednesday = new Date(1414580400000), saturday = new Date(1414839600000), sunday = new Date(1414926000000), friday = new Date(1414771500000); describe('Helg', function () { describe('When passing an erroneous date object', function () { it('should throw an error', function () { var invalid = function () { return helg.ere('Sunday 11th 2014'); }; assert.throws(invalid, Error); }); }) describe('When setting the date manually', function () { it('should return false when the day is wednesday', function () { assert.equal(helg.ere(wednesday), false); }); it('should return true when the day is saturday', function () { assert.equal(helg.ere(saturday), true); }); it('should return true when the day is sunday', function () { assert.equal(helg.ere(sunday), true); }); it('should return true when the day is friday and after 5pm', function () { assert.equal(helg.ere(friday), true); }); }); describe('When getting the date from the computers local time', function () { it('should return true when the day is saturday', function () { timeKeeper.travel(saturday); assert.equal(helg.ere(), true); }); it('should return false when the day is wednesday', function () { timeKeeper.travel(wednesday); assert.equal(helg.ere(), false); }); it('should return true when the day is friday and after 5pm', function () { timeKeeper.travel(friday); assert.equal(helg.ere(), true); }); it('should return true when the day is sunday', function () { timeKeeper.travel(sunday); assert.equal(helg.ere(), true); }); }); });
Swap lines
test.js
Swap lines
<ide><path>est.js <ide> <ide> var wednesday = new Date(1414580400000), <ide> saturday = new Date(1414839600000), <del> sunday = new Date(1414926000000), <del> friday = new Date(1414771500000); <add> friday = new Date(1414771500000), <add> sunday = new Date(1414926000000); <ide> <ide> describe('Helg', function () { <ide>
Java
lgpl-2.1
ef7d5d5be7c4ea13d4353e2747b97f50d0505271
0
mediaworx/opencms-core,alkacon/opencms-core,sbonoc/opencms-core,MenZil/opencms-core,sbonoc/opencms-core,mediaworx/opencms-core,ggiudetti/opencms-core,it-tavis/opencms-core,it-tavis/opencms-core,serrapos/opencms-core,MenZil/opencms-core,alkacon/opencms-core,sbonoc/opencms-core,mediaworx/opencms-core,gallardo/opencms-core,serrapos/opencms-core,it-tavis/opencms-core,MenZil/opencms-core,ggiudetti/opencms-core,serrapos/opencms-core,it-tavis/opencms-core,ggiudetti/opencms-core,serrapos/opencms-core,mediaworx/opencms-core,ggiudetti/opencms-core,serrapos/opencms-core,MenZil/opencms-core,victos/opencms-core,victos/opencms-core,serrapos/opencms-core,victos/opencms-core,sbonoc/opencms-core,alkacon/opencms-core,alkacon/opencms-core,gallardo/opencms-core,serrapos/opencms-core,victos/opencms-core,gallardo/opencms-core,gallardo/opencms-core
/* * File : $Source: /alkacon/cvs/opencms/src-modules/org/opencms/gwt/client/util/Attic/CmsDomUtil.java,v $ * Date : $Date: 2010/04/01 13:45:32 $ * Version: $Revision: 1.9 $ * * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (C) 2002 - 2009 Alkacon Software (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.gwt.client.util; import org.opencms.gwt.client.util.impl.DocumentStyleImpl; import java.util.ArrayList; import java.util.List; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.NodeList; /** * Utility class to access the HTML DOM.<p> * * @author Tobias Herrmann * * @version $Revision: 1.9 $ * * @since 8.0.0 */ public final class CmsDomUtil { /** * CSS Colors.<p> */ public static enum Color { /** CSS Color. */ red, } /** * CSS Properties.<p> */ public static enum Style { /** CSS Property. */ backgroundColor, /** CSS Property. */ backgroundImage, /** CSS Property. */ borderStyle, /** CSS Property. */ display, /** CSS Property. */ floatCss { /** * @see java.lang.Enum#toString() */ @Override public String toString() { return "float"; } }, /** CSS Property. */ fontFamily, /** CSS Property. */ fontSize, /** CSS Property. */ fontSizeAdjust, /** CSS Property. */ fontStretch, /** CSS Property. */ fontStyle, /** CSS Property. */ fontVariant, /** CSS Property. */ fontWeight, /** CSS Property. */ height, /** CSS Property. */ left, /** CSS Property. */ letterSpacing, /** CSS Property. */ lineHeight, /** CSS Property. */ marginBottom, /** CSS Property. */ opacity, /** CSS Property. */ padding, /** CSS Property. */ position, /** CSS Property. */ textAlign, /** CSS Property. */ textDecoration, /** CSS Property. */ textIndent, /** CSS Property. */ textShadow, /** CSS Property. */ textTransform, /** CSS Property. */ top, /** CSS Property. */ visibility, /** CSS Property. */ whiteSpace, /** CSS Property. */ width, /** CSS Property. */ wordSpacing, /** CSS Property. */ wordWrap } /** * CSS Property values.<p> */ public static enum StyleValue { /** CSS Property value. */ absolute, /** CSS Property value. */ auto, /** CSS Property value. */ hidden, /** CSS Property value. */ none, /** CSS Property value. */ normal, /** CSS Property value. */ nowrap, /** CSS Property value. */ transparent; } /** * HTML Tags.<p> */ public static enum Tag { /** HTML Tag. */ ALL { /** * @see java.lang.Enum#toString() */ @Override public String toString() { return "*"; } }, /** HTML Tag. */ b, /** HTML Tag. */ div, /** HTML Tag. */ li, /** HTML Tag. */ ul; } /** Browser dependent implementation. */ private static DocumentStyleImpl styleImpl; /** * Hidden constructor.<p> */ private CmsDomUtil() { // doing nothing } /** * Generates a closing tag.<p> * * @param tag the tag to use * * @return HTML code */ public static String close(Tag tag) { return "</" + tag.name() + ">"; } /** * Encloses the given text with the given tag.<p> * * @param tag the tag to use * @param text the text to enclose * * @return HTML code */ public static String enclose(Tag tag, String text) { return open(tag) + text + close(tag); } /** * Returns the computed style of the given element.<p> * * @param element the element * @param style the CSS property * * @return the currently computed style */ public static String getCurrentStyle(Element element, Style style) { if (styleImpl == null) { styleImpl = GWT.create(DocumentStyleImpl.class); } return styleImpl.getCurrentStyle(element, style.toString()); } /** * Returns the computed style of the given element as number.<p> * * @param element the element * @param style the CSS property * * @return the currently computed style */ public static int getCurrentStyleInt(Element element, Style style) { String currentStyle = getCurrentStyle(element, style); return CmsStringUtil.parseInt(currentStyle); } /** * Returns all elements from the DOM with the given CSS class and tag name.<p> * * @param className the class name to look for * @param tag the tag * * @return the matching elements */ public static List<Element> getElementByClass(String className, Tag tag) { return getElementsByClass(className, tag, Document.get().getBody()); } /** * Returns all elements from the DOM with the given CSS class.<p> * * @param className the class name to look for * * @return the matching elements */ public static List<Element> getElementsByClass(String className) { return getElementsByClass(className, Tag.ALL, Document.get().getBody()); } /** * Returns all elements with the given CSS class including the root element.<p> * * @param className the class name to look for * @param rootElement the root element of the search * * @return the matching elements */ public static List<Element> getElementsByClass(String className, Element rootElement) { return getElementsByClass(className, Tag.ALL, rootElement); } /** * Returns all elements with the given CSS class and tag name including the root element.<p> * * @param className the class name to look for * @param tag the tag * @param rootElement the root element of the search * * @return the matching elements */ public static List<Element> getElementsByClass(String className, Tag tag, Element rootElement) { if ((rootElement == null) || (className == null) || (className.trim().length() == 0) || (tag == null)) { return null; } className = className.trim(); List<Element> result = new ArrayList<Element>(); if (internalHasClass(className, rootElement)) { result.add(rootElement); } NodeList<Element> elements = rootElement.getElementsByTagName(tag.toString()); for (int i = 0; i < elements.getLength(); i++) { if (internalHasClass(className, elements.getItem(i))) { result.add(elements.getItem(i)); } } return result; } /** * Utility method to determine if the given element has a set background.<p> * * @param element the element * * @return <code>true</code> if the element has a background set */ public static boolean hasBackground(Element element) { String backgroundColor = CmsDomUtil.getCurrentStyle(element, Style.backgroundColor); String backgroundImage = CmsDomUtil.getCurrentStyle(element, Style.backgroundImage); if ((backgroundColor.equals(StyleValue.transparent.toString())) && ((backgroundImage == null) || (backgroundImage.trim().length() == 0) || backgroundImage.equals(StyleValue.none.toString()))) { return false; } return true; } /** * Utility method to determine if the given element has a set border.<p> * * @param element the element * * @return <code>true</code> if the element has a border */ public static boolean hasBorder(Element element) { String borderStyle = CmsDomUtil.getCurrentStyle(element, Style.borderStyle); if ((borderStyle == null) || borderStyle.equals(StyleValue.none.toString()) || (borderStyle.length() == 0)) { return false; } return true; } /** * Indicates if the given element has a CSS class.<p> * * @param className the class name to look for * @param element the element * * @return <code>true</code> if the element has the given CSS class */ public static boolean hasClass(String className, Element element) { return internalHasClass(className.trim(), element); } /** * Generates an opening tag.<p> * * @param tag the tag to use * * @return HTML code */ public static String open(Tag tag) { return "<" + tag.name() + ">"; } /** * Internal method to indicate if the given element has a CSS class.<p> * * @param className the class name to look for * @param element the element * * @return <code>true</code> if the element has the given CSS class */ private static boolean internalHasClass(String className, Element element) { String elementClass = element.getClassName().trim(); boolean hasClass = elementClass.equals(className); hasClass |= elementClass.contains(" " + className + " "); hasClass |= elementClass.startsWith(className + " "); hasClass |= elementClass.endsWith(" " + className); return hasClass; } }
src-modules/org/opencms/gwt/client/util/CmsDomUtil.java
/* * File : $Source: /alkacon/cvs/opencms/src-modules/org/opencms/gwt/client/util/Attic/CmsDomUtil.java,v $ * Date : $Date: 2010/04/01 09:25:36 $ * Version: $Revision: 1.8 $ * * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (C) 2002 - 2009 Alkacon Software (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.gwt.client.util; import org.opencms.gwt.client.util.impl.DocumentStyleImpl; import java.util.ArrayList; import java.util.List; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.NodeList; /** * Utility class to access the HTML DOM.<p> * * @author Tobias Herrmann * * @version $Revision: 1.8 $ * * @since 8.0.0 */ public final class CmsDomUtil { /** * CSS Colors.<p> */ public static enum Color { /** CSS Color. */ red, } /** * CSS Properties.<p> */ public static enum Style { /** CSS Property. */ backgroundColor, /** CSS Property. */ backgroundImage, /** CSS Property. */ borderStyle, /** CSS Property. */ display, /** CSS Property. */ floatCss { /** * @see java.lang.Enum#toString() */ @Override public String toString() { return "float"; } }, /** CSS Property. */ fontFamily, /** CSS Property. */ fontSize, /** CSS Property. */ fontSizeAdjust, /** CSS Property. */ fontStretch, /** CSS Property. */ fontStyle, /** CSS Property. */ fontVariant, /** CSS Property. */ fontWeight, /** CSS Property. */ height, /** CSS Property. */ left, /** CSS Property. */ letterSpacing, /** CSS Property. */ lineHeight, /** CSS Property. */ marginBottom, /** CSS Property. */ opacity, /** CSS Property. */ padding, /** CSS Property. */ position, /** CSS Property. */ textAlign, /** CSS Property. */ textDecoration, /** CSS Property. */ textIndent, /** CSS Property. */ textShadow, /** CSS Property. */ textTransform, /** CSS Property. */ top, /** CSS Property. */ visibility, /** CSS Property. */ whiteSpace, /** CSS Property. */ width, /** CSS Property. */ wordSpacing, /** CSS Property. */ wordWrap } /** * CSS Property values.<p> */ public static enum StyleValue { /** CSS Property value. */ absolute, /** CSS Property value. */ auto, /** CSS Property value. */ hidden, /** CSS Property value. */ none, /** CSS Property value. */ transparent; } /** * HTML Tags.<p> */ public static enum Tag { /** HTML Tag. */ ALL { /** * @see java.lang.Enum#toString() */ @Override public String toString() { return "*"; } }, /** HTML Tag. */ b, /** HTML Tag. */ div, /** HTML Tag. */ li, /** HTML Tag. */ ul; } /** Browser dependent implementation. */ private static DocumentStyleImpl styleImpl; /** * Hidden constructor.<p> */ private CmsDomUtil() { // doing nothing } /** * Generates a closing tag.<p> * * @param tag the tag to use * * @return HTML code */ public static String close(Tag tag) { return "</" + tag.name() + ">"; } /** * Encloses the given text with the given tag.<p> * * @param tag the tag to use * @param text the text to enclose * * @return HTML code */ public static String enclose(Tag tag, String text) { return open(tag) + text + close(tag); } /** * Returns the computed style of the given element.<p> * * @param element the element * @param style the CSS property * * @return the currently computed style */ public static String getCurrentStyle(Element element, Style style) { if (styleImpl == null) { styleImpl = GWT.create(DocumentStyleImpl.class); } return styleImpl.getCurrentStyle(element, style.toString()); } /** * Returns the computed style of the given element as number.<p> * * @param element the element * @param style the CSS property * * @return the currently computed style */ public static int getCurrentStyleInt(Element element, Style style) { String currentStyle = getCurrentStyle(element, style); return CmsStringUtil.parseInt(currentStyle); } /** * Returns all elements from the DOM with the given CSS class and tag name.<p> * * @param className the class name to look for * @param tag the tag * * @return the matching elements */ public static List<Element> getElementByClass(String className, Tag tag) { return getElementsByClass(className, tag, Document.get().getBody()); } /** * Returns all elements from the DOM with the given CSS class.<p> * * @param className the class name to look for * * @return the matching elements */ public static List<Element> getElementsByClass(String className) { return getElementsByClass(className, Tag.ALL, Document.get().getBody()); } /** * Returns all elements with the given CSS class including the root element.<p> * * @param className the class name to look for * @param rootElement the root element of the search * * @return the matching elements */ public static List<Element> getElementsByClass(String className, Element rootElement) { return getElementsByClass(className, Tag.ALL, rootElement); } /** * Returns all elements with the given CSS class and tag name including the root element.<p> * * @param className the class name to look for * @param tag the tag * @param rootElement the root element of the search * * @return the matching elements */ public static List<Element> getElementsByClass(String className, Tag tag, Element rootElement) { if ((rootElement == null) || (className == null) || (className.trim().length() == 0) || (tag == null)) { return null; } className = className.trim(); List<Element> result = new ArrayList<Element>(); if (internalHasClass(className, rootElement)) { result.add(rootElement); } NodeList<Element> elements = rootElement.getElementsByTagName(tag.toString()); for (int i = 0; i < elements.getLength(); i++) { if (internalHasClass(className, elements.getItem(i))) { result.add(elements.getItem(i)); } } return result; } /** * Utility method to determine if the given element has a set background.<p> * * @param element the element * * @return <code>true</code> if the element has a background set */ public static boolean hasBackground(Element element) { String backgroundColor = CmsDomUtil.getCurrentStyle(element, Style.backgroundColor); String backgroundImage = CmsDomUtil.getCurrentStyle(element, Style.backgroundImage); if ((backgroundColor.equals(StyleValue.transparent.toString())) && ((backgroundImage == null) || (backgroundImage.trim().length() == 0) || backgroundImage.equals(StyleValue.none.toString()))) { return false; } return true; } /** * Utility method to determine if the given element has a set border.<p> * * @param element the element * * @return <code>true</code> if the element has a border */ public static boolean hasBorder(Element element) { String borderStyle = CmsDomUtil.getCurrentStyle(element, Style.borderStyle); if ((borderStyle == null) || borderStyle.equals(StyleValue.none.toString()) || (borderStyle.length() == 0)) { return false; } return true; } /** * Indicates if the given element has a CSS class.<p> * * @param className the class name to look for * @param element the element * * @return <code>true</code> if the element has the given CSS class */ public static boolean hasClass(String className, Element element) { return internalHasClass(className.trim(), element); } /** * Generates an opening tag.<p> * * @param tag the tag to use * * @return HTML code */ public static String open(Tag tag) { return "<" + tag.name() + ">"; } /** * Internal method to indicate if the given element has a CSS class.<p> * * @param className the class name to look for * @param element the element * * @return <code>true</code> if the element has the given CSS class */ private static boolean internalHasClass(String className, Element element) { String elementClass = element.getClassName().trim(); boolean hasClass = elementClass.equals(className); hasClass |= elementClass.contains(" " + className + " "); hasClass |= elementClass.startsWith(className + " "); hasClass |= elementClass.endsWith(" " + className); return hasClass; } }
new style values added
src-modules/org/opencms/gwt/client/util/CmsDomUtil.java
new style values added
<ide><path>rc-modules/org/opencms/gwt/client/util/CmsDomUtil.java <ide> /* <ide> * File : $Source: /alkacon/cvs/opencms/src-modules/org/opencms/gwt/client/util/Attic/CmsDomUtil.java,v $ <del> * Date : $Date: 2010/04/01 09:25:36 $ <del> * Version: $Revision: 1.8 $ <add> * Date : $Date: 2010/04/01 13:45:32 $ <add> * Version: $Revision: 1.9 $ <ide> * <ide> * This library is part of OpenCms - <ide> * the Open Source Content Management System <ide> * <ide> * @author Tobias Herrmann <ide> * <del> * @version $Revision: 1.8 $ <add> * @version $Revision: 1.9 $ <ide> * <ide> * @since 8.0.0 <ide> */ <ide> none, <ide> <ide> /** CSS Property value. */ <add> normal, <add> <add> /** CSS Property value. */ <add> nowrap, <add> <add> /** CSS Property value. */ <ide> transparent; <ide> } <ide>
Java
apache-2.0
error: pathspec 'src/projet_poo2/Calcul.java' did not match any file(s) known to git
5093ddb43b089189aaa789da3a7f7659a91eaa4c
1
jeje22/projet_poo2
package projet_poo2; public class Calcul { public static boolean correlation() { boolean res=false; int N=IHM.pictures[0].width/2-1; int P=IHM.pictures[0].height/2-1; int K=(2*N+1)*(2*P+1); if(IHM.reference.get(0).size()==IHM.reference.get(1).size()) { for(int k=0;k<IHM.reference.get(0).size();k++) { int reste=0; int c=(1/K)+0; int val1_x=IHM.reference.get(0).get(k).x; int val1_y=IHM.reference.get(0).get(k).y; int val2_x=IHM.reference.get(1).get(k).x; int val2_y=IHM.reference.get(1).get(k).y; for(int i=-N;i<=N;i++) { for(int j=P;j<=P;j++) { reste+=val_1_x-N+i; } } } } else { System.out.println("erreur : le nombre de point n'est pas le mme sur les 2 images"); } return res; } }
src/projet_poo2/Calcul.java
ajout de calcul non fonctionnel
src/projet_poo2/Calcul.java
ajout de calcul non fonctionnel
<ide><path>rc/projet_poo2/Calcul.java <add>package projet_poo2; <add> <add>public class Calcul <add>{ <add> public static boolean correlation() <add> { <add> boolean res=false; <add> int N=IHM.pictures[0].width/2-1; <add> int P=IHM.pictures[0].height/2-1; <add> <add> int K=(2*N+1)*(2*P+1); <add> <add> <add> if(IHM.reference.get(0).size()==IHM.reference.get(1).size()) <add> { <add> for(int k=0;k<IHM.reference.get(0).size();k++) <add> { <add> int reste=0; <add> int c=(1/K)+0; <add> <add> int val1_x=IHM.reference.get(0).get(k).x; <add> int val1_y=IHM.reference.get(0).get(k).y; <add> <add> int val2_x=IHM.reference.get(1).get(k).x; <add> int val2_y=IHM.reference.get(1).get(k).y; <add> <add> for(int i=-N;i<=N;i++) <add> { <add> for(int j=P;j<=P;j++) <add> { <add> reste+=val_1_x-N+i; <add> } <add> } <add> } <add> } <add> else <add> { <add> System.out.println("erreur : le nombre de point n'est pas le mme sur les 2 images"); <add> } <add> <add> <add> return res; <add> } <add>}
JavaScript
mit
ac51da47deee0b55c93c15bd4ce93803df52c396
0
juco/tinker,foreachlt/tinker
var express = require('express') , app = express(); // Config app.set('port', process.env.PORT || 3000); app.set('secret', process.env.SECRET || 'tinker'); app.set('github_token', process.env.TOKEN || 'token'); // Routes app.get('/', function(req, res) { res.status(200).end(); }); app.post('/tinker', function(req, res) { res.status(200).end(); }); // Start the server app.listen(app.get('port')); console.log('Started the server on port', app.get('port'));
index.js
var express = require('express') , app = express(); // Config app.set('port', process.env.PORT || 3000); app.set('secret', process.env.SECRET || 'tinker'); app.set('github_token', process.env.TOKEN || 'token'); // Routes app.get('/', function(req, res) { res.status(200).end(); }); app.get('/payload', function(req, res) { res.status(200).end(); }); app.get('/ping', function(req, res) { res.status(200).end(); }); // Start the server app.listen(app.get('port')); console.log('Started the server on port', app.get('port'));
Minor
index.js
Minor
<ide><path>ndex.js <ide> res.status(200).end(); <ide> }); <ide> <del>app.get('/payload', function(req, res) { <del> res.status(200).end(); <del>}); <del> <del>app.get('/ping', function(req, res) { <add>app.post('/tinker', function(req, res) { <ide> res.status(200).end(); <ide> }); <ide>
Java
apache-2.0
dbe52b471c55af380860f1d473d2fa229fd4013f
0
eskatos/swing-on-steroids
package org.codeartisans.java.sos.threading; import com.google.inject.Inject; import com.google.inject.name.Named; import java.util.LinkedList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.codeartisans.java.toolbox.exceptions.NullArgumentException; public class DefaultWorkQueue implements WorkQueue { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultWorkQueue.class); private final PooledWorker[] threads; private final LinkedList<Runnable> queue; private final ThreadGroup threadGroup; @Inject public DefaultWorkQueue(@Named(NAME) String name, @Named(SIZE) Integer size) { NullArgumentException.ensureNotEmpty(NAME, true, name); NullArgumentException.ensureNotZero(SIZE, size); name = name.trim(); queue = new LinkedList<Runnable>(); threads = new PooledWorker[size]; threadGroup = new ThreadGroup(name + "WorkQueue"); for (int i = 0; i < size; i++) { threads[i] = new PooledWorker(threadGroup, name + "Worker-" + i); threads[i].start(); } } @Override public void execute(Runnable r) { synchronized (queue) { queue.addLast(r); queue.notify(); } } private class PooledWorker extends Thread { private PooledWorker(ThreadGroup threadGroup, String threadName) { super(threadGroup, threadName); } @Override public void run() { Runnable r; while (true) { synchronized (queue) { while (queue.isEmpty()) { try { queue.wait(); } catch (InterruptedException ignored) { } } r = queue.removeFirst(); } // If we don't catch RuntimeException, the pool could leak threads try { r.run(); } catch (RuntimeException ex) { LOGGER.warn(ex.getMessage(), ex); } } } } }
src/main/java/org/codeartisans/java/sos/threading/DefaultWorkQueue.java
package org.codeartisans.java.sos.threading; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import java.util.LinkedList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.codeartisans.java.toolbox.exceptions.NullArgumentException; @Singleton public class DefaultWorkQueue implements WorkQueue { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultWorkQueue.class); private final PooledWorker[] threads; private final LinkedList<Runnable> queue; private final ThreadGroup threadGroup; @Inject public DefaultWorkQueue(@Named(NAME) String name, @Named(SIZE) Integer size) { NullArgumentException.ensureNotEmpty(NAME, true, name); NullArgumentException.ensureNotZero(SIZE, size); name = name.trim(); queue = new LinkedList<Runnable>(); threads = new PooledWorker[size]; threadGroup = new ThreadGroup(name + "WorkQueue"); for (int i = 0; i < size; i++) { threads[i] = new PooledWorker(threadGroup, name + "Worker-" + i); threads[i].start(); } } @Override public void execute(Runnable r) { synchronized (queue) { queue.addLast(r); queue.notify(); } } private class PooledWorker extends Thread { private PooledWorker(ThreadGroup threadGroup, String threadName) { super(threadGroup, threadName); } @Override public void run() { Runnable r; while (true) { synchronized (queue) { while (queue.isEmpty()) { try { queue.wait(); } catch (InterruptedException ignored) { } } r = queue.removeFirst(); } // If we don't catch RuntimeException, the pool could leak threads try { r.run(); } catch (RuntimeException ex) { LOGGER.warn(ex.getMessage(), ex); } } } } }
removed a @Singleton annotation from DefaultWorkQueue
src/main/java/org/codeartisans/java/sos/threading/DefaultWorkQueue.java
removed a @Singleton annotation from DefaultWorkQueue
<ide><path>rc/main/java/org/codeartisans/java/sos/threading/DefaultWorkQueue.java <ide> package org.codeartisans.java.sos.threading; <ide> <ide> import com.google.inject.Inject; <del>import com.google.inject.Singleton; <ide> import com.google.inject.name.Named; <ide> import java.util.LinkedList; <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> import org.codeartisans.java.toolbox.exceptions.NullArgumentException; <ide> <del>@Singleton <ide> public class DefaultWorkQueue <ide> implements WorkQueue <ide> {
Java
apache-2.0
90e5f442e0ae827f959d07b3fa191cecd98334a6
0
orientechnologies/orientdb,orientechnologies/orientdb,orientechnologies/orientdb,orientechnologies/orientdb
/* * * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * * For more information: http://orientdb.com * */ package com.orientechnologies.orient.core.config; import com.orientechnologies.common.io.OFileUtils; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.common.profiler.OProfiler; import com.orientechnologies.common.util.OApi; import com.orientechnologies.orient.core.OConstants; import com.orientechnologies.orient.core.Orient; import com.orientechnologies.orient.core.cache.ORecordCacheWeakRefs; import com.orientechnologies.orient.core.engine.local.OEngineLocalPaginated; import com.orientechnologies.orient.core.index.OIndexDefinition; import com.orientechnologies.orient.core.metadata.OMetadataDefault; import com.orientechnologies.orient.core.serialization.serializer.record.binary.ORecordSerializerBinary; import com.orientechnologies.orient.core.storage.OChecksumMode; import com.orientechnologies.orient.core.storage.cluster.OPaginatedCluster; import java.io.PrintStream; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.logging.ConsoleHandler; import java.util.logging.FileHandler; import java.util.logging.Level; /** * Keeps all configuration settings. At startup assigns the configuration values by reading system * properties. * * @author Luca Garulli (l.garulli--(at)--orientdb.com) */ public enum OGlobalConfiguration { // ENVIRONMENT ENVIRONMENT_DUMP_CFG_AT_STARTUP( "environment.dumpCfgAtStartup", "Dumps the configuration during application startup", Boolean.class, Boolean.FALSE), @Deprecated ENVIRONMENT_CONCURRENT( "environment.concurrent", "Specifies if running in multi-thread environment. Setting this to false turns off the internal lock management", Boolean.class, Boolean.TRUE), ENVIRONMENT_LOCK_MANAGER_CONCURRENCY_LEVEL( "environment.lock.concurrency.level", "Concurrency level of lock manager", Integer.class, Runtime.getRuntime().availableProcessors() << 3, false), @Deprecated ENVIRONMENT_ALLOW_JVM_SHUTDOWN( "environment.allowJVMShutdown", "Allows the shutdown of the JVM, if needed/requested", Boolean.class, true, true), // SCRIPT SCRIPT_POOL( "script.pool.maxSize", "Maximum number of instances in the pool of script engines", Integer.class, 20), SCRIPT_POLYGLOT_USE_GRAAL( "script.polyglot.useGraal", "Use GraalVM as polyglot engine", Boolean.class, true), // MEMORY MEMORY_USE_UNSAFE( "memory.useUnsafe", "Indicates whether Unsafe will be used, if it is present", Boolean.class, true), MEMORY_PROFILING( "memory.profiling", "Switches on profiling of allocations of direct memory inside of OrientDB.", Boolean.class, false), MEMORY_PROFILING_REPORT_INTERVAL( "memory.profiling.reportInterval", "Interval of printing of memory profiling results in minutes", Integer.class, 15), @Deprecated MEMORY_CHUNK_SIZE( "memory.chunk.size", "Size of single memory chunk (in bytes) which will be preallocated by OrientDB", Integer.class, Integer.MAX_VALUE), MEMORY_LEFT_TO_OS( "memory.leftToOS", "Amount of free memory which should be left unallocated in case of OrientDB is started outside of container. " + "Value can be set as % of total memory provided to OrientDB or as absolute value in bytes, kilobytes, megabytes or gigabytes. " + "If you set value as 10% it means that 10% of memory will not be allocated by OrientDB and will be left to use by the rest of " + "applications, if 2g value is provided it means that 2 gigabytes of memory will be left to use by the rest of applications. " + "Default value is 2g", String.class, "2g"), MEMORY_LEFT_TO_CONTAINER( "memory.leftToContainer", "Amount of free memory which should be left unallocated in case of OrientDB is started inside of container. " + "Value can be set as % of total memory provided to OrientDB or as absolute value in bytes, kilobytes, megabytes or gigabytes. " + "If you set value as 10% it means that 10% of memory will not be allocated by OrientDB and will be left to use by the rest of " + "applications, if 2g value is provided it means that 2 gigabytes of memory will be left to use by the rest of applications. " + "Default value is 256m", String.class, "256m"), DIRECT_MEMORY_SAFE_MODE( "memory.directMemory.safeMode", "Indicates whether to perform a range check before each direct memory update. It is true by default, " + "but usually it can be safely set to false. It should only be to true after dramatic changes have been made in the storage structures", Boolean.class, true), DIRECT_MEMORY_POOL_LIMIT( "memory.pool.limit", "Limit of the pages cached inside of direct memory pool to avoid frequent reallocation of memory in OS", Integer.class, Integer.MAX_VALUE), DIRECT_MEMORY_PREALLOCATE( "memory.directMemory.preallocate", "Preallocate amount of direct memory which is needed for the disk cache", Boolean.class, false), DIRECT_MEMORY_TRACK_MODE( "memory.directMemory.trackMode", "Activates the direct memory pool [leak detector](Leak-Detector.md). This detector causes a large overhead and should be used for debugging " + "purposes only. It's also a good idea to pass the " + "-Djava.util.logging.manager=com.orientechnologies.common.log.ShutdownLogManager switch to the JVM, " + "if you use this mode, this will enable the logging from JVM shutdown hooks.", Boolean.class, false), DIRECT_MEMORY_ONLY_ALIGNED_ACCESS( "memory.directMemory.onlyAlignedMemoryAccess", "Some architectures do not allow unaligned memory access or may suffer from speed degradation. For such platforms, this flag should be set to true", Boolean.class, true), @Deprecated JVM_GC_DELAY_FOR_OPTIMIZE( "jvm.gc.delayForOptimize", "Minimal amount of time (in seconds), since the last System.gc(), when called after tree optimization", Long.class, 600), // STORAGE /** Limit of amount of files which may be open simultaneously */ OPEN_FILES_LIMIT( "storage.openFiles.limit", "Limit of amount of files which may be open simultaneously, -1 (default) means automatic detection", Integer.class, -1), /** * Amount of cached locks is used for component lock in atomic operation to avoid constant * creation of new lock instances, default value is 10000. */ COMPONENTS_LOCK_CACHE( "storage.componentsLock.cache", "Amount of cached locks is used for component lock to avoid constant creation of new lock instances", Integer.class, 10000), DISK_CACHE_PINNED_PAGES( "storage.diskCache.pinnedPages", "Maximum amount of pinned pages which may be contained in cache," + " if this percent is reached next pages will be left in unpinned state. You can not set value more than 50", Integer.class, 20, false), DISK_CACHE_SIZE( "storage.diskCache.bufferSize", "Size of disk buffer in megabytes, disk size may be changed at runtime, " + "but if does not enough to contain all pinned pages exception will be thrown", Integer.class, 4 * 1024, new OCacheSizeChangeCallback()), DISK_WRITE_CACHE_PART( "storage.diskCache.writeCachePart", "Percentage of disk cache, which is used as write cache", Integer.class, 5), @Deprecated DISK_WRITE_CACHE_USE_ASYNC_IO( "storage.diskCache.useAsyncIO", "Use asynchronous IO API to facilitate abilities of SSD to parallelize IO requests", Boolean.class, true), @Deprecated DISK_USE_NATIVE_OS_API( "storage.disk.useNativeOsAPI", "Allows to call native OS methods if possible", Boolean.class, true), DISK_WRITE_CACHE_SHUTDOWN_TIMEOUT( "storage.diskCache.writeCacheShutdownTimeout", "Timeout of shutdown of write cache for single task in min.", Integer.class, 30), DISK_WRITE_CACHE_PAGE_TTL( "storage.diskCache.writeCachePageTTL", "Max time until a page will be flushed from write cache (in seconds)", Long.class, 24 * 60 * 60), DISK_WRITE_CACHE_PAGE_FLUSH_INTERVAL( "storage.diskCache.writeCachePageFlushInterval", "Interval between flushing of pages from write cache (in ms)", Integer.class, 25), DISK_WRITE_CACHE_FLUSH_WRITE_INACTIVITY_INTERVAL( "storage.diskCache.writeCacheFlushInactivityInterval", "Interval between 2 writes to the disk cache," + " if writes are done with an interval more than provided, all files will be fsynced before the next write," + " which allows a data restore after a server crash (in ms)", Long.class, 60 * 1000), DISK_WRITE_CACHE_FLUSH_LOCK_TIMEOUT( "storage.diskCache.writeCacheFlushLockTimeout", "Maximum amount of time the write cache will wait before a page flushes (in ms, -1 to disable)", Integer.class, -1), @Deprecated DISC_CACHE_FREE_SPACE_CHECK_INTERVAL( "storage.diskCache.diskFreeSpaceCheckInterval", "The interval (in seconds), after which the storage periodically " + "checks whether the amount of free disk space is enough to work in write mode", Integer.class, 5), /** * The interval (how many new pages should be added before free space will be checked), after * which the storage periodically checks whether the amount of free disk space is enough to work * in write mode. */ DISC_CACHE_FREE_SPACE_CHECK_INTERVAL_IN_PAGES( "storage.diskCache.diskFreeSpaceCheckIntervalInPages", "The interval (how many new pages should be added before free space will be checked), after which the storage periodically " + "checks whether the amount of free disk space is enough to work in write mode", Integer.class, 2048), /** * Keep disk cache state between moment when storage is closed and moment when it is opened again. * <code>true</code> by default. */ STORAGE_KEEP_DISK_CACHE_STATE( "storage.diskCache.keepState", "Keep disk cache state between moment when storage is closed and moment when it is opened again. true by default", Boolean.class, false), STORAGE_CHECKSUM_MODE( "storage.diskCache.checksumMode", "Controls the per-page checksum storage and verification done by " + "the file cache. Possible modes: 'off' – checksums are completely off; 'store' – checksums are calculated and stored " + "on page flushes, no verification is done on page loads, stored checksums are verified only during user-initiated health " + "checks; 'storeAndVerify' – checksums are calculated and stored on page flushes, verification is performed on " + "each page load, errors are reported in the log; 'storeAndThrow' – same as `storeAndVerify` with addition of exceptions " + "thrown on errors, this mode is useful for debugging and testing, but should be avoided in a production environment;" + " 'storeAndSwitchReadOnlyMode' (default) - Same as 'storeAndVerify' with addition that storage will be switched in read only mode " + "till it will not be repaired.", OChecksumMode.class, OChecksumMode.StoreAndSwitchReadOnlyMode, false), STORAGE_CHECK_LATEST_OPERATION_ID( "storage.checkLatestOperationId", "Indicates wether storage should be checked for latest operation id, " + "to ensure that all the records are needed to restore database are stored into the WAL (true by default)", Boolean.class, true), STORAGE_EXCLUSIVE_FILE_ACCESS( "storage.exclusiveFileAccess", "Limit access to the datafiles to the single API user, set to " + "true to prevent concurrent modification files by different instances of storage", Boolean.class, true), STORAGE_TRACK_FILE_ACCESS( "storage.trackFileAccess", "Works only if storage.exclusiveFileAccess is set to true. " + "Tracks stack trace of thread which initially opened a file", Boolean.class, true), @Deprecated STORAGE_CONFIGURATION_SYNC_ON_UPDATE( "storage.configuration.syncOnUpdate", "Indicates a force sync should be performed for each update on the storage configuration", Boolean.class, true), STORAGE_COMPRESSION_METHOD( "storage.compressionMethod", "Record compression method used in storage" + " Possible values : gzip, nothing. Default is 'nothing' that means no compression", String.class, "nothing"), @Deprecated STORAGE_ENCRYPTION_METHOD( "storage.encryptionMethod", "Record encryption method used in storage" + " Possible values : 'aes' and 'des'. Default is 'nothing' for no encryption", String.class, "nothing"), STORAGE_ENCRYPTION_KEY( "storage.encryptionKey", "Contains the storage encryption key. This setting is hidden", String.class, null, false, true), STORAGE_MAKE_FULL_CHECKPOINT_AFTER_CREATE( "storage.makeFullCheckpointAfterCreate", "Indicates whether a full checkpoint should be performed, if storage was created", Boolean.class, false), /** * @deprecated because it was used as workaround for the case when storage is already opened but * there are no checkpoints and as result data restore after crash may work incorrectly, this * bug is fixed under https://github.com/orientechnologies/orientdb/issues/7562 in so this * functionality is not needed any more. */ @Deprecated STORAGE_MAKE_FULL_CHECKPOINT_AFTER_OPEN( "storage.makeFullCheckpointAfterOpen", "Indicates whether a full checkpoint should be performed, if storage was opened. It is needed so fuzzy checkpoints can work properly", Boolean.class, true), STORAGE_ATOMIC_OPERATIONS_TABLE_COMPACTION_LIMIT( "storage.atomicOperationsTable.compactionLimit", "Limit of size of atomic operations table after which compaction will be triggered on", Integer.class, 10_000), STORAGE_MAKE_FULL_CHECKPOINT_AFTER_CLUSTER_CREATE( "storage.makeFullCheckpointAfterClusterCreate", "Indicates whether a full checkpoint should be performed, if storage was opened", Boolean.class, true), STORAGE_CALL_FSYNC( "storage.callFsync", "Call fsync during fuzzy checkpoints or WAL writes, true by default", Boolean.class, true), STORAGE_USE_DOUBLE_WRITE_LOG( "storage.useDoubleWriteLog", "Allows usage of double write log in storage. " + "This log prevents pages to be teared apart so it is not recommended to switch it off.", Boolean.class, true), STORAGE_DOUBLE_WRITE_LOG_MAX_SEG_SIZE( "storage.doubleWriteLog.maxSegSize", "Maximum size of double write log segment in megabytes, -1 means that size will be calculated automatically", Integer.class, -1), STORAGE_DOUBLE_WRITE_LOG_MAX_SEG_SIZE_PERCENT( "storage.doubleWriteLog.maxSegSizePercent", "Maximum size of segment of double write log in percents, should be set to value bigger than 0", Integer.class, 5), STORAGE_DOUBLE_WRITE_LOG_MIN_SEG_SIZE( "storage.doubleWriteLog.minSegSize", "Minimum size of segment of double write log in megabytes, should be set to value bigger than 0. " + "If both set maximum and minimum size of segments. Minimum size always will have priority over maximum size.", Integer.class, 256), @Deprecated STORAGE_TRACK_PAGE_OPERATIONS_IN_TX( "storage.trackOperationsInTx", "If this flag switched on, transaction features will be implemented " + "not by tracking of binary changes, but by tracking of operations on page level.", Boolean.class, false), STORAGE_PAGE_OPERATIONS_CACHE_SIZE( "storage.pageOperationsCacheSize", "Size of page operations cache in MB per transaction. " + "If operations are cached, they are not read from WAL during rollback.", Integer.class, 16), STORAGE_CLUSTER_VERSION( "storage.cluster.version", "Binary version of cluster which will be used inside of storage", Integer.class, OPaginatedCluster.getLatestBinaryVersion()), STORAGE_PRINT_WAL_PERFORMANCE_STATISTICS( "storage.printWALPerformanceStatistics", "Periodically prints statistics about WAL performance", Boolean.class, false), STORAGE_PRINT_WAL_PERFORMANCE_INTERVAL( "storage.walPerformanceStatisticsInterval", "Interval in seconds between consequent reports of WAL performance statistics", Integer.class, 10), @Deprecated STORAGE_TRACK_CHANGED_RECORDS_IN_WAL( "storage.trackChangedRecordsInWAL", "If this flag is set metadata which contains rids of changed records is added at the end of each atomic operation", Boolean.class, false), STORAGE_INTERNAL_JOURNALED_TX_STREAMING_PORT( "storage.internal.journaled.tx.streaming.port", "Activates journaled tx streaming " + "on the given TCP/IP port. Used for internal testing purposes only. Never touch it if you don't know what you doing.", Integer.class, null), STORAGE_PESSIMISTIC_LOCKING( "storage.pessimisticLock", "Set the approach of the pessimistic locking, valid options: none, modification, readwrite", String.class, "none"), /** * @deprecated WAL can not be disabled because that is very unsafe for consistency and durability */ @Deprecated USE_WAL("storage.useWAL", "Whether WAL should be used in paginated storage", Boolean.class, true), @Deprecated USE_CHM_CACHE( "storage.useCHMCache", "Whether to use new disk cache implementation based on CHM or old one based on cuncurrent queues", Boolean.class, true), WAL_SYNC_ON_PAGE_FLUSH( "storage.wal.syncOnPageFlush", "Indicates whether a force sync should be performed during WAL page flush", Boolean.class, true), WAL_CACHE_SIZE( "storage.wal.cacheSize", "Maximum size of WAL cache (in amount of WAL pages, each page is 4k) If set to 0, caching will be disabled", Integer.class, 65536), WAL_BUFFER_SIZE( "storage.wal.bufferSize", "Size of the direct memory WAL buffer which is used inside of " + "the background write thread (in MB)", Integer.class, 64), WAL_SEGMENTS_INTERVAL( "storage.wal.segmentsInterval", "Maximum interval in time in min. after which new WAL segment will be added", Integer.class, 10), WAL_FILE_AUTOCLOSE_INTERVAL( "storage.wal.fileAutoCloseInterval", "Interval in seconds after which WAL file will be closed if there is no " + "any IO operations on this file (in seconds), default value is 10", Integer.class, 10, false), WAL_SEGMENT_BUFFER_SIZE( "storage.wal.segmentBufferSize", "Size of the buffer which contains WAL records in serialized format " + "in megabytes", Integer.class, 32), WAL_MAX_SEGMENT_SIZE( "storage.wal.maxSegmentSize", "Maximum size of single WAL segment (in megabytes)", Integer.class, -1), WAL_MAX_SEGMENT_SIZE_PERCENT( "storage.wal.maxSegmentSizePercent", "Maximum size of single WAL segment in percent of initial free space", Integer.class, 5), WAL_MIN_SEG_SIZE( "storage.wal.minSegSize", "Minimal value of maximum WAL segment size in MB", Integer.class, 6 * 1024), WAL_MIN_COMPRESSED_RECORD_SIZE( "storage.wal.minCompressedRecordSize", "Minimum size of record which is needed to be compressed before stored on disk", Integer.class, 8 * 1024), WAL_MAX_SIZE( "storage.wal.maxSize", "Maximum size of WAL on disk (in megabytes)", Integer.class, -1), WAL_KEEP_SINGLE_SEGMENT( "storage.wal.keepSingleSegment", "Database will provide the best efforts to keep only single WAL inside the storage", Boolean.class, true), @Deprecated WAL_ALLOW_DIRECT_IO( "storage.wal.allowDirectIO", "Allows usage of direct IO API on Linux OS to avoid keeping of WAL data in OS buffer", Boolean.class, false), WAL_COMMIT_TIMEOUT( "storage.wal.commitTimeout", "Maximum interval between WAL commits (in ms.)", Integer.class, 1000), WAL_SHUTDOWN_TIMEOUT( "storage.wal.shutdownTimeout", "Maximum wait interval between events, when the background flush thread" + "receives a shutdown command and when the background flush will be stopped (in ms.)", Integer.class, 10000), WAL_FUZZY_CHECKPOINT_INTERVAL( "storage.wal.fuzzyCheckpointInterval", "Interval between fuzzy checkpoints (in seconds)", Integer.class, 300), WAL_REPORT_AFTER_OPERATIONS_DURING_RESTORE( "storage.wal.reportAfterOperationsDuringRestore", "Amount of processed log operations, after which status of data restore procedure will be printed (0 or a negative value, disables the logging)", Integer.class, 10000), WAL_RESTORE_BATCH_SIZE( "storage.wal.restore.batchSize", "Amount of WAL records, which are read at once in a single batch during a restore procedure", Integer.class, 1000), @Deprecated WAL_READ_CACHE_SIZE( "storage.wal.readCacheSize", "Size of WAL read cache in amount of pages", Integer.class, 1000), WAL_FUZZY_CHECKPOINT_SHUTDOWN_TIMEOUT( "storage.wal.fuzzyCheckpointShutdownWait", "The amount of time the DB should wait until it shuts down (in seconds)", Integer.class, 60 * 10), WAL_FULL_CHECKPOINT_SHUTDOWN_TIMEOUT( "storage.wal.fullCheckpointShutdownTimeout", "The amount of time the DB will wait, until a checkpoint is finished, during a DB shutdown (in seconds)", Integer.class, 60 * 10), WAL_LOCATION( "storage.wal.path", "Path to the WAL file on the disk. By default, it is placed in the DB directory, but" + " it is highly recommended to use a separate disk to store log operations", String.class, null), DISK_CACHE_PAGE_SIZE( "storage.diskCache.pageSize", "Size of page of disk buffer (in kilobytes). !!! NEVER CHANGE THIS VALUE !!!", Integer.class, 64), DISK_CACHE_PRINT_FLUSH_TILL_SEGMENT_STATISTICS( "storage.diskCache.printFlushTillSegmentStatistics", "Print information about write cache state when it is requested to flush all data operations on which are logged " + "till provided WAL segment", Boolean.class, true), DISK_CACHE_PRINT_FLUSH_FILE_STATISTICS( "storage.diskCache.printFlushFileStatistics", "Print information about write cache state when it is requested to flush all data of file specified", Boolean.class, true), DISK_CACHE_PRINT_FILE_REMOVE_STATISTICS( "storage.diskCache.printFileRemoveStatistics", "Print information about write cache state when it is requested to clear all data of file specified", Boolean.class, true), DISK_CACHE_WAL_SIZE_TO_START_FLUSH( "storage.diskCache.walSizeToStartFlush", "WAL size after which pages in write cache will be started to flush", Long.class, 6 * 1024L * 1024 * 1024), DISK_CACHE_EXCLUSIVE_FLUSH_BOUNDARY( "storage.diskCache.exclusiveFlushBoundary", "If portion of exclusive pages into cache exceeds this value we start to flush only exclusive pages from disk cache", Float.class, 0.9), DISK_CACHE_CHUNK_SIZE( "storage.diskCache.chunkSize", "Maximum distance between two pages after which they are not treated as single continous chunk", Integer.class, 256), DISK_CACHE_EXCLUSIVE_PAGES_BOUNDARY( "storage.diskCache.exclusiveBoundary", "Portion of exclusive pages in write cache after which we will start to flush only exclusive pages", Float.class, 0.7), DISK_CACHE_WAL_SIZE_TO_STOP_FLUSH( "storage.diskCache.walSizeToStopFlush", "WAL size reaching which pages in write cache will be prevented from flush", Long.class, 2 * 1024L * 1024 * 1024), DISK_CACHE_FREE_SPACE_LIMIT( "storage.diskCache.diskFreeSpaceLimit", "Minimum amount of space on disk, which, when exceeded, " + "will cause the database to switch to read-only mode (in megabytes)", Long.class, 8 * WAL_MAX_SEGMENT_SIZE.getValueAsLong()), @Deprecated PAGINATED_STORAGE_LOWEST_FREELIST_BOUNDARY( "storage.lowestFreeListBound", "The least amount of free space (in kb) in a page, which is tracked in paginated storage", Integer.class, 16), STORAGE_LOCK_TIMEOUT( "storage.lockTimeout", "Maximum amount of time (in ms) to lock the storage", Integer.class, 0), STORAGE_RECORD_LOCK_TIMEOUT( "storage.record.lockTimeout", "Maximum of time (in ms) to lock a shared record", Integer.class, 2000), @Deprecated STORAGE_USE_TOMBSTONES( "storage.useTombstones", "When a record is deleted, the space in the cluster will not be freed, but rather tombstoned", Boolean.class, false), // RECORDS @Deprecated RECORD_DOWNSIZING_ENABLED( "record.downsizing.enabled", "On updates, if the record size is lower than before, this reduces the space taken accordingly. " + "If enabled this could increase defragmentation, but it reduces the used disk space", Boolean.class, true), // DATABASE OBJECT_SAVE_ONLY_DIRTY( "object.saveOnlyDirty", "Object Database only! It saves objects bound to dirty records", Boolean.class, false, true), DOCUMENT_BINARY_MAPPING( "document.binaryMapping", "Mapping approach for binary fields", Integer.class, 0), // DATABASE DB_POOL_MIN("db.pool.min", "Default database pool minimum size", Integer.class, 1), DB_POOL_MAX("db.pool.max", "Default database pool maximum size", Integer.class, 100), DB_CACHED_POOL_CAPACITY( "db.cached.pool.capacity", "Default database cached pools capacity", Integer.class, 100), DB_STRING_CAHCE_SIZE( "db.string.cache.size", "Number of common string to keep in memory cache", Integer.class, 5000), DB_CACHED_POOL_CLEAN_UP_TIMEOUT( "db.cached.pool.cleanUpTimeout", "Default timeout for clean up cache from unused or closed database pools, value in milliseconds", Long.class, 600_000), DB_POOL_ACQUIRE_TIMEOUT( "db.pool.acquireTimeout", "Default database pool timeout in milliseconds", Integer.class, 60000), @Deprecated DB_POOL_IDLE_TIMEOUT( "db.pool.idleTimeout", "Timeout for checking for free databases in the pool", Integer.class, 0), @Deprecated DB_POOL_IDLE_CHECK_DELAY( "db.pool.idleCheckDelay", "Delay time on checking for idle databases", Integer.class, 0), DB_MVCC_THROWFAST( "db.mvcc.throwfast", "Use fast-thrown exceptions for MVCC OConcurrentModificationExceptions. No context information will be available. " + "Set to true, when these exceptions are thrown, but the details are not necessary", Boolean.class, false, true), DB_VALIDATION( "db.validation", "Enables or disables validation of records", Boolean.class, true, true), DB_CUSTOM_SUPPORT( "db.custom.support", "Enables or disables use of custom types", Boolean.class, false, false), // SETTINGS OF NON-TRANSACTIONAL MODE @Deprecated NON_TX_RECORD_UPDATE_SYNCH( "nonTX.recordUpdate.synch", "Executes a sync against the file-system for every record operation. This slows down record updates, " + "but guarantees reliability on unreliable drives", Boolean.class, Boolean.FALSE), NON_TX_CLUSTERS_SYNC_IMMEDIATELY( "nonTX.clusters.sync.immediately", "List of clusters to sync immediately after update (separated by commas). Can be useful for a manual index", String.class, OMetadataDefault.CLUSTER_MANUAL_INDEX_NAME), // TRANSACTIONS @Deprecated TX_TRACK_ATOMIC_OPERATIONS( "tx.trackAtomicOperations", "This setting is used only for debug purposes. It creates a stack trace of methods, when an atomic operation is started", Boolean.class, false), TX_PAGE_CACHE_SIZE( "tx.pageCacheSize", "The size of a per-transaction page cache in pages, 12 by default, 0 to disable the cache.", Integer.class, 12), // INDEX INDEX_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD( "index.embeddedToSbtreeBonsaiThreshold", "Amount of values, after which the index implementation will use an sbtree as a values container. Set to -1, to disable and force using an sbtree", Integer.class, 40, true), INDEX_SBTREEBONSAI_TO_EMBEDDED_THRESHOLD( "index.sbtreeBonsaiToEmbeddedThreshold", "Amount of values, after which index implementation will use an embedded values container (disabled by default)", Integer.class, -1, true), HASH_TABLE_SPLIT_BUCKETS_BUFFER_LENGTH( "hashTable.slitBucketsBuffer.length", "Length of buffer (in pages), where buckets " + "that were split, but not flushed to the disk, are kept. This buffer is used to minimize random IO overhead", Integer.class, 1500), INDEX_SYNCHRONOUS_AUTO_REBUILD( "index.auto.synchronousAutoRebuild", "Synchronous execution of auto rebuilding of indexes, in case of a DB crash", Boolean.class, Boolean.TRUE), @Deprecated INDEX_AUTO_LAZY_UPDATES( "index.auto.lazyUpdates", "Configure the TreeMaps for automatic indexes, as buffered or not. -1 means buffered until tx.commit() or db.close() are called", Integer.class, 10000), INDEX_FLUSH_AFTER_CREATE( "index.flushAfterCreate", "Flush storage buffer after index creation", Boolean.class, true), @Deprecated INDEX_MANUAL_LAZY_UPDATES( "index.manual.lazyUpdates", "Configure the TreeMaps for manual indexes as buffered or not. -1 means buffered until tx.commit() or db.close() are called", Integer.class, 1), INDEX_DURABLE_IN_NON_TX_MODE( "index.durableInNonTxMode", "Indicates whether index implementation for plocal storage will be durable in non-Tx mode (true by default)", Boolean.class, true), INDEX_ALLOW_MANUAL_INDEXES( "index.allowManualIndexes", "Switch which allows usage of manual indexes inside OrientDB. " + "It is not recommended to switch it on, because manual indexes are deprecated, not supported and will be removed in next versions", Boolean.class, true), INDEX_ALLOW_MANUAL_INDEXES_WARNING( "index.allowManualIndexesWarning", "Switch which triggers printing of waring message any time when " + "manual indexes are used. It is not recommended to switch it off, because manual indexes are deprecated, " + "not supported and will be removed in next versions", Boolean.class, true), /** * @see OIndexDefinition#isNullValuesIgnored() * @since 2.2 */ INDEX_IGNORE_NULL_VALUES_DEFAULT( "index.ignoreNullValuesDefault", "Controls whether null values will be ignored by default " + "by newly created indexes or not (false by default)", Boolean.class, false), @Deprecated INDEX_TX_MODE( "index.txMode", "Indicates the index durability level in TX mode. Can be ROLLBACK_ONLY or FULL (ROLLBACK_ONLY by default)", String.class, "FULL"), INDEX_CURSOR_PREFETCH_SIZE( "index.stream.prefetchSize", "Default prefetch size of index stream", Integer.class, 10), // SBTREE SBTREE_MAX_DEPTH( "sbtree.maxDepth", "Maximum depth of sbtree, which will be traversed during key look up until it will be treated as broken (64 by default)", Integer.class, 64), SBTREE_MAX_KEY_SIZE( "sbtree.maxKeySize", "Maximum size of a key, which can be put in the SBTree in bytes (10240 by default)", Integer.class, 10240), SBTREE_MAX_EMBEDDED_VALUE_SIZE( "sbtree.maxEmbeddedValueSize", "Maximum size of value which can be put in an SBTree without creation link to a standalone page in bytes (40960 by default)", Integer.class, 40960), SBTREEBONSAI_BUCKET_SIZE( "sbtreebonsai.bucketSize", "Size of bucket in OSBTreeBonsai (in kB). Contract: bucketSize < storagePageSize, storagePageSize % bucketSize == 0", Integer.class, 2), SBTREEBONSAI_LINKBAG_CACHE_SIZE( "sbtreebonsai.linkBagCache.size", "Amount of LINKBAG collections to be cached, to avoid constant reloading of data", Integer.class, 100000), SBTREEBONSAI_LINKBAG_CACHE_EVICTION_SIZE( "sbtreebonsai.linkBagCache.evictionSize", "The number of cached LINKBAG collections, which will be removed, when the cache limit is reached", Integer.class, 1000), SBTREEBOSAI_FREE_SPACE_REUSE_TRIGGER( "sbtreebonsai.freeSpaceReuseTrigger", "How much free space should be in an sbtreebonsai file, before it will be reused during the next allocation", Float.class, 0.5), // RIDBAG RID_BAG_EMBEDDED_DEFAULT_SIZE( "ridBag.embeddedDefaultSize", "Size of embedded RidBag array, when created (empty)", Integer.class, 4), RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD( "ridBag.embeddedToSbtreeBonsaiThreshold", "Amount of values after which a LINKBAG implementation will use sbtree as values container. Set to -1 to always use an sbtree", Integer.class, 40, true), RID_BAG_SBTREEBONSAI_TO_EMBEDDED_THRESHOLD( "ridBag.sbtreeBonsaiToEmbeddedToThreshold", "Amount of values, after which a LINKBAG implementation will use an embedded values container (disabled by default)", Integer.class, -1, true), RID_BAG_SBTREEBONSAI_DELETE_DELAY( "ridBag.sbtreeBonsaiDeleteDelay", "How long should pass from last access before delete an already converted ridbag", Integer.class, 30000), // FILE @Deprecated TRACK_FILE_CLOSE( "file.trackFileClose", "Log all the cases when files are closed. This is needed only for internal debugging purposes", Boolean.class, false), FILE_LOCK("file.lock", "Locks files when used. Default is true", boolean.class, true), FILE_DELETE_DELAY( "file.deleteDelay", "Delay time (in ms) to wait for another attempt to delete a locked file", Integer.class, 10), FILE_DELETE_RETRY( "file.deleteRetry", "Number of retries to delete a locked file", Integer.class, 50), // SECURITY SECURITY_USER_PASSWORD_SALT_ITERATIONS( "security.userPasswordSaltIterations", "Number of iterations to generate the salt or user password. Changing this setting does not affect stored passwords", Integer.class, 65536), SECURITY_USER_PASSWORD_SALT_CACHE_SIZE( "security.userPasswordSaltCacheSize", "Cache size of hashed salt passwords. The cache works as LRU. Use 0 to disable the cache", Integer.class, 500), SECURITY_USER_PASSWORD_DEFAULT_ALGORITHM( "security.userPasswordDefaultAlgorithm", "Default encryption algorithm used for passwords hashing", String.class, "PBKDF2WithHmacSHA256"), // NETWORK NETWORK_MAX_CONCURRENT_SESSIONS( "network.maxConcurrentSessions", "Maximum number of concurrent sessions", Integer.class, 1000, true), NETWORK_SOCKET_BUFFER_SIZE( "network.socketBufferSize", "TCP/IP Socket buffer size, if 0 use the OS default", Integer.class, 0, true), NETWORK_LOCK_TIMEOUT( "network.lockTimeout", "Timeout (in ms) to acquire a lock against a channel", Integer.class, 15000, true), NETWORK_SOCKET_TIMEOUT( "network.socketTimeout", "TCP/IP Socket timeout (in ms)", Integer.class, 15000, true), NETWORK_REQUEST_TIMEOUT( "network.requestTimeout", "Request completion timeout (in ms)", Integer.class, 3600000 /* one hour */, true), NETWORK_SOCKET_RETRY_STRATEGY( "network.retry.strategy", "Select the retry server selection strategy, possible values are auto,same-dc ", String.class, "auto", true), NETWORK_SOCKET_RETRY( "network.retry", "Number of attempts to connect to the server on failure", Integer.class, 5, true), NETWORK_SOCKET_RETRY_DELAY( "network.retryDelay", "The time (in ms) the client must wait, before reconnecting to the server on failure", Integer.class, 500, true), NETWORK_BINARY_DNS_LOADBALANCING_ENABLED( "network.binary.loadBalancing.enabled", "Asks for DNS TXT record, to determine if load balancing is supported", Boolean.class, Boolean.FALSE, true), NETWORK_BINARY_DNS_LOADBALANCING_TIMEOUT( "network.binary.loadBalancing.timeout", "Maximum time (in ms) to wait for the answer from DNS about the TXT record for load balancing", Integer.class, 2000, true), NETWORK_BINARY_MAX_CONTENT_LENGTH( "network.binary.maxLength", "TCP/IP max content length (in KB) of BINARY requests", Integer.class, 16384, true), @Deprecated NETWORK_BINARY_READ_RESPONSE_MAX_TIMES( "network.binary.readResponse.maxTimes", "Maximum attempts, until a response can be read. Otherwise, the response will be dropped from the channel", Integer.class, 20, true), NETWORK_BINARY_MIN_PROTOCOL_VERSION( "network.binary.minProtocolVersion", "Set the minimum enabled binary protocol version and disable all backward compatible behaviour for version previous the one specified", Integer.class, 26, false), NETWORK_BINARY_DEBUG( "network.binary.debug", "Debug mode: print all data incoming on the binary channel", Boolean.class, false, true), NETWORK_BINARY_ALLOW_NO_TOKEN( "network.binary.allowNoToken", "Backward compatibility option to allow binary connections without tokens (STRONGLY DISCOURAGED, FOR SECURITY REASONS)", Boolean.class, Boolean.FALSE, true), // HTTP /** Since v2.2.8 */ NETWORK_HTTP_INSTALL_DEFAULT_COMMANDS( "network.http.installDefaultCommands", "Installs the default HTTP commands", Boolean.class, Boolean.TRUE, true), NETWORK_HTTP_SERVER_INFO( "network.http.serverInfo", "Server info to send in HTTP responses. Change the default if you want to hide it is a OrientDB Server", String.class, "OrientDB Server v." + OConstants.getVersion(), true), NETWORK_HTTP_MAX_CONTENT_LENGTH( "network.http.maxLength", "TCP/IP max content length (in bytes) for HTTP requests", Integer.class, 1000000, true), NETWORK_HTTP_STREAMING( "network.http.streaming", "Enable Http chunked streaming for json responses", Boolean.class, false, true), NETWORK_HTTP_CONTENT_CHARSET( "network.http.charset", "Http response charset", String.class, "utf-8", true), NETWORK_HTTP_JSON_RESPONSE_ERROR( "network.http.jsonResponseError", "Http response error in json", Boolean.class, true, true), NETWORK_HTTP_JSONP_ENABLED( "network.http.jsonp", "Enable the usage of JSONP, if requested by the client. The parameter name to use is 'callback'", Boolean.class, false, true), NETWORK_HTTP_SESSION_EXPIRE_TIMEOUT( "network.http.sessionExpireTimeout", "Timeout, after which an http session is considered to have expired (in seconds)", Integer.class, 900), NETWORK_HTTP_SESSION_COOKIE_SAME_SITE( "network.http.session.cookie.sameSite", "Activate the same site cookie session", Boolean.class, true), NETWORK_HTTP_USE_TOKEN( "network.http.useToken", "Enable Token based sessions for http", Boolean.class, false), NETWORK_TOKEN_SECRETKEY( "network.token.secretKey", "Network token sercret key", String.class, "", false, true), NETWORK_TOKEN_ENCRYPTION_ALGORITHM( "network.token.encryptionAlgorithm", "Network token algorithm", String.class, "HmacSHA256"), NETWORK_TOKEN_EXPIRE_TIMEOUT( "network.token.expireTimeout", "Timeout, after which a binary session is considered to have expired (in minutes)", Integer.class, 60), INIT_IN_SERVLET_CONTEXT_LISTENER( "orient.initInServletContextListener", "If this value set to ture (default) OrientDB engine " + "will be initialzed using embedded ServletContextListener", Boolean.class, true), // PROFILER PROFILER_ENABLED( "profiler.enabled", "Enables the recording of statistics and counters", Boolean.class, false, new OProfileEnabledChangeCallbac()), PROFILER_CONFIG( "profiler.config", "Configures the profiler as <seconds-for-snapshot>,<archive-snapshot-size>,<summary-size>", String.class, null, new OProfileConfigChangeCallback()), PROFILER_AUTODUMP_INTERVAL( "profiler.autoDump.interval", "Dumps the profiler values at regular intervals (in seconds)", Integer.class, 0, new OProfileDumpIntervalChangeCallback()), /** @Since 2.2.27 */ PROFILER_AUTODUMP_TYPE( "profiler.autoDump.type", "Type of profiler dump between 'full' or 'performance'", String.class, "full"), PROFILER_MAXVALUES( "profiler.maxValues", "Maximum values to store. Values are managed in a LRU", Integer.class, 200), PROFILER_MEMORYCHECK_INTERVAL( "profiler.memoryCheckInterval", "Checks the memory usage every configured milliseconds. Use 0 to disable it", Long.class, 120000), // SEQUENCES SEQUENCE_MAX_RETRY( "sequence.maxRetry", "Maximum number of retries between attempt to change a sequence in concurrent mode", Integer.class, 100), SEQUENCE_RETRY_DELAY( "sequence.retryDelay", "Maximum number of ms to wait between concurrent modification exceptions. The value is computed as random between 1 and this number", Integer.class, 200), /** Interval between snapshots of profiler state in milliseconds, default value is 100. */ STORAGE_PROFILER_SNAPSHOT_INTERVAL( "storageProfiler.intervalBetweenSnapshots", "Interval between snapshots of profiler state in milliseconds", Integer.class, 100), STORAGE_PROFILER_CLEANUP_INTERVAL( "storageProfiler.cleanUpInterval", "Interval between time series in milliseconds", Integer.class, 5000), // LOG LOG_CONSOLE_LEVEL( "log.console.level", "Console logging level", String.class, "info", new OConfigurationChangeCallback() { public void change(final Object iCurrentValue, final Object iNewValue) { OLogManager.instance().setLevel((String) iNewValue, ConsoleHandler.class); } }), LOG_FILE_LEVEL( "log.file.level", "File logging level", String.class, "info", new OConfigurationChangeCallback() { public void change(final Object iCurrentValue, final Object iNewValue) { OLogManager.instance().setLevel((String) iNewValue, FileHandler.class); } }), // CLASS CLASS_MINIMUM_CLUSTERS( "class.minimumClusters", "Minimum clusters to create when a new class is created. 0 means Automatic", Integer.class, 0), // LOG LOG_SUPPORTS_ANSI( "log.console.ansi", "ANSI Console support. 'auto' means automatic check if it is supported, 'true' to force using ANSI, 'false' to avoid using ANSI", String.class, "auto"), // CACHE CACHE_LOCAL_IMPL( "cache.local.impl", "Local Record cache implementation", String.class, ORecordCacheWeakRefs.class.getName()), // COMMAND COMMAND_TIMEOUT("command.timeout", "Default timeout for commands (in ms)", Long.class, 0, true), COMMAND_CACHE_ENABLED("command.cache.enabled", "Enable command cache", Boolean.class, false), COMMAND_CACHE_EVICT_STRATEGY( "command.cache.evictStrategy", "Command cache strategy between: [INVALIDATE_ALL,PER_CLUSTER]", String.class, "PER_CLUSTER"), COMMAND_CACHE_MIN_EXECUTION_TIME( "command.cache.minExecutionTime", "Minimum execution time to consider caching the result set", Integer.class, 10), COMMAND_CACHE_MAX_RESULSET_SIZE( "command.cache.maxResultsetSize", "Maximum resultset time to consider caching result set", Integer.class, 500), // QUERY QUERY_REMOTE_RESULTSET_PAGE_SIZE( "query.remoteResultSet.pageSize", "The size of a remote ResultSet page, ie. the number of records" + "that are fetched together during remote query execution. This has to be set on the client.", Integer.class, 1000), QUERY_REMOTE_SEND_EXECUTION_PLAN( "query.remoteResultSet.sendExecutionPlan", "Send the execution plan details or not. False by default", Boolean.class, false), QUERY_PARALLEL_AUTO( "query.parallelAuto", "Auto enable parallel query, if requirements are met", Boolean.class, false), QUERY_PARALLEL_MINIMUM_RECORDS( "query.parallelMinimumRecords", "Minimum number of records to activate parallel query automatically", Long.class, 300000), QUERY_PARALLEL_RESULT_QUEUE_SIZE( "query.parallelResultQueueSize", "Size of the queue that holds results on parallel execution. The queue is blocking, so in case the queue is full, the query threads will be in a wait state", Integer.class, 20000), QUERY_SCAN_PREFETCH_PAGES( "query.scanPrefetchPages", "Pages to prefetch during scan. Setting this value higher makes scans faster, because it reduces the number of I/O operations, though it consumes more memory. (Use 0 to disable)", Integer.class, 20), QUERY_SCAN_BATCH_SIZE( "query.scanBatchSize", "Scan clusters in blocks of records. This setting reduces the lock time on the cluster during scans." + " A high value mean a faster execution, but also a lower concurrency level. Set to 0 to disable batch scanning. Disabling batch scanning is suggested for read-only databases only", Long.class, 1000), QUERY_SCAN_THRESHOLD_TIP( "query.scanThresholdTip", "If the total number of records scanned in a query exceeds this setting, then a warning is given. (Use 0 to disable)", Long.class, 50000), QUERY_LIMIT_THRESHOLD_TIP( "query.limitThresholdTip", "If the total number of returned records exceeds this value, then a warning is given. (Use 0 to disable)", Long.class, 10000), QUERY_MAX_HEAP_ELEMENTS_ALLOWED_PER_OP( "query.maxHeapElementsAllowedPerOp", "Maximum number of elements (records) allowed in a single query for memory-intensive operations (eg. ORDER BY in heap). " + "If exceeded, the query fails with an OCommandExecutionException. Negative number means no limit." + "This setting is intended as a safety measure against excessive resource consumption from a single query (eg. prevent OutOfMemory)", Long.class, 500_000), QUERY_LIVE_SUPPORT( "query.live.support", "Enable/Disable the support of live query. (Use false to disable)", Boolean.class, true), STATEMENT_CACHE_SIZE( "statement.cacheSize", "Number of parsed SQL statements kept in cache. Zero means cache disabled", Integer.class, 100), // GRAPH SQL_GRAPH_CONSISTENCY_MODE( "sql.graphConsistencyMode", "Consistency mode for graphs. It can be 'tx' (default), 'notx_sync_repair' and 'notx_async_repair'. " + "'tx' uses transactions to maintain consistency. Instead both 'notx_sync_repair' and 'notx_async_repair' do not use transactions, " + "and the consistency, in case of JVM crash, is guaranteed by a database repair operation that run at startup. " + "With 'notx_sync_repair' the repair is synchronous, so the database comes online after the repair is ended, while " + "with 'notx_async_repair' the repair is a background process", String.class, "tx"), /** * Maximum size of pool of network channels between client and server. A channel is a TCP/IP * connection. */ CLIENT_CHANNEL_MAX_POOL( "client.channel.maxPool", "Maximum size of pool of network channels between client and server. A channel is a TCP/IP connection", Integer.class, 100), /** * Maximum time, where the client should wait for a connection from the pool, when all connections * busy. */ CLIENT_CONNECT_POOL_WAIT_TIMEOUT( "client.connectionPool.waitTimeout", "Maximum time, where the client should wait for a connection from the pool, when all connections busy", Integer.class, 5000, true), CLIENT_DB_RELEASE_WAIT_TIMEOUT( "client.channel.dbReleaseWaitTimeout", "Delay (in ms), after which a data modification command will be resent, if the DB was frozen", Integer.class, 10000, true), CLIENT_USE_SSL("client.ssl.enabled", "Use SSL for client connections", Boolean.class, false), CLIENT_SSL_KEYSTORE("client.ssl.keyStore", "Use SSL for client connections", String.class, null), CLIENT_SSL_KEYSTORE_PASSWORD( "client.ssl.keyStorePass", "Use SSL for client connections", String.class, null, false, true), CLIENT_SSL_TRUSTSTORE( "client.ssl.trustStore", "Use SSL for client connections", String.class, null), CLIENT_SSL_TRUSTSTORE_PASSWORD( "client.ssl.trustStorePass", "Use SSL for client connections", String.class, null, false, true), // SERVER SERVER_OPEN_ALL_DATABASES_AT_STARTUP( "server.openAllDatabasesAtStartup", "If true, the server opens all the available databases at startup. Available since 2.2", Boolean.class, false), SERVER_DATABASE_PATH( "server.database.path", "The path where are located the databases of a server", String.class, null), SERVER_CHANNEL_CLEAN_DELAY( "server.channel.cleanDelay", "Time in ms of delay to check pending closed connections", Integer.class, 5000), SERVER_CACHE_FILE_STATIC( "server.cache.staticFile", "Cache static resources upon loading", Boolean.class, false), SERVER_LOG_DUMP_CLIENT_EXCEPTION_LEVEL( "server.log.dumpClientExceptionLevel", "Logs client exceptions. Use any level supported by Java java.util.logging.Level class: OFF, FINE, CONFIG, INFO, WARNING, SEVERE", String.class, Level.FINE.getName()), SERVER_LOG_DUMP_CLIENT_EXCEPTION_FULLSTACKTRACE( "server.log.dumpClientExceptionFullStackTrace", "Dumps the full stack trace of the exception sent to the client", Boolean.class, Boolean.FALSE, true), SERVER_BACKWARD_COMPATIBILITY( "server.backwardCompatibility", "guarantee that the server use global context for search the database instance", Boolean.class, Boolean.FALSE, true, false), // DISTRIBUTED /** @Since 2.2.18 */ DISTRIBUTED_DUMP_STATS_EVERY( "distributed.dumpStatsEvery", "Time in ms to dump the cluster stats. Set to 0 to disable such dump", Long.class, 0l, true), DISTRIBUTED_CRUD_TASK_SYNCH_TIMEOUT( "distributed.crudTaskTimeout", "Maximum timeout (in ms) to wait for CRUD remote tasks", Long.class, 3000l, true), DISTRIBUTED_MAX_STARTUP_DELAY( "distributed.maxStartupDelay", "Maximum delay time (in ms) to wait for a server to start", Long.class, 10000l, true), DISTRIBUTED_COMMAND_TASK_SYNCH_TIMEOUT( "distributed.commandTaskTimeout", "Maximum timeout (in ms) to wait for command distributed tasks", Long.class, 2 * 60 * 1000l, true), DISTRIBUTED_COMMAND_QUICK_TASK_SYNCH_TIMEOUT( "distributed.commandQuickTaskTimeout", "Maximum timeout (in ms) to wait for quick command distributed tasks", Long.class, 5 * 1000l, true), DISTRIBUTED_COMMAND_LONG_TASK_SYNCH_TIMEOUT( "distributed.commandLongTaskTimeout", "Maximum timeout (in ms) to wait for Long-running distributed tasks", Long.class, 24 * 60 * 60 * 1000, true), DISTRIBUTED_DEPLOYDB_TASK_SYNCH_TIMEOUT( "distributed.deployDbTaskTimeout", "Maximum timeout (in ms) to wait for database deployment", Long.class, 1200000l, true), DISTRIBUTED_DEPLOYCHUNK_TASK_SYNCH_TIMEOUT( "distributed.deployChunkTaskTimeout", "Maximum timeout (in ms) to wait for database chunk deployment", Long.class, 60000l, true), DISTRIBUTED_DEPLOYDB_TASK_COMPRESSION( "distributed.deployDbTaskCompression", "Compression level (between 0 and 9) to use in backup for database deployment", Integer.class, 7, true), DISTRIBUTED_ASYNCH_QUEUE_SIZE( "distributed.asynchQueueSize", "Queue size to handle distributed asynchronous operations. The bigger is the queue, the more operation are buffered, but also more memory it's consumed. 0 = dynamic allocation, which means up to 2^31-1 entries", Integer.class, 0), DISTRIBUTED_ASYNCH_RESPONSES_TIMEOUT( "distributed.asynchResponsesTimeout", "Maximum timeout (in ms) to collect all the asynchronous responses from replication. After this time the operation is rolled back (through an UNDO)", Long.class, 15000l), DISTRIBUTED_PURGE_RESPONSES_TIMER_DELAY( "distributed.purgeResponsesTimerDelay", "Maximum timeout (in ms) to collect all the asynchronous responses from replication. This is the delay the purge thread uses to check asynchronous requests in timeout", Long.class, 15000l), /** @Since 2.2.7 */ DISTRIBUTED_CONFLICT_RESOLVER_REPAIRER_CHAIN( "distributed.conflictResolverRepairerChain", "Chain of conflict resolver implementation to use", String.class, "majority,content,version", false), /** @Since 2.2.7 */ DISTRIBUTED_CONFLICT_RESOLVER_REPAIRER_CHECK_EVERY( "distributed.conflictResolverRepairerCheckEvery", "Time (in ms) when the conflict resolver auto-repairer checks for records/cluster to repair", Long.class, 5000, true), /** @Since 2.2.7 */ DISTRIBUTED_CONFLICT_RESOLVER_REPAIRER_BATCH( "distributed.conflictResolverRepairerBatch", "Maximum number of records to repair in batch", Integer.class, 1000, true), /** @Since 2.2.7 */ DISTRIBUTED_TX_EXPIRE_TIMEOUT( "distributed.txAliveTimeout", "Maximum timeout (in ms) a distributed transaction can be alive. This timeout is to rollback pending transactions after a while", Long.class, 1800000l, true), /** @Since 2.2.6 */ DISTRIBUTED_REQUEST_CHANNELS( "distributed.requestChannels", "Number of network channels used to send requests", Integer.class, 1), /** @Since 2.2.6 */ DISTRIBUTED_RESPONSE_CHANNELS( "distributed.responseChannels", "Number of network channels used to send responses", Integer.class, 1), /** @Since 2.2.5 */ DISTRIBUTED_HEARTBEAT_TIMEOUT( "distributed.heartbeatTimeout", "Maximum time in ms to wait for the heartbeat. If the server does not respond in time, it is put offline", Long.class, 10000l), /** @Since 2.2.5 */ DISTRIBUTED_CHECK_HEALTH_CAN_OFFLINE_SERVER( "distributed.checkHealthCanOfflineServer", "In case a server does not respond to the heartbeat message, it is set offline", Boolean.class, false), /** @Since 2.2.5 */ DISTRIBUTED_CHECK_HEALTH_EVERY( "distributed.checkHealthEvery", "Time in ms to check the cluster health. Set to 0 to disable it", Long.class, 10000l), /** Since 2.2.4 */ DISTRIBUTED_AUTO_REMOVE_OFFLINE_SERVERS( "distributed.autoRemoveOfflineServers", "This is the amount of time (in ms) the server has to be OFFLINE, before it is automatically removed from the distributed configuration. -1 = never, 0 = immediately, >0 the actual time to wait", Long.class, 0, true), /** @Since 2.2.0 */ DISTRIBUTED_PUBLISH_NODE_STATUS_EVERY( "distributed.publishNodeStatusEvery", "Time in ms to publish the node status on distributed map. Set to 0 to disable such refresh of node configuration", Long.class, 10000l, true), /** @Since 2.2.0 */ DISTRIBUTED_REPLICATION_PROTOCOL_VERSION( "distributed.replicationProtocol.version", "1 for legacy replication model (v 3.0 and previous), 2 for coordinated replication (v 3.1 and next)", Integer.class, 1, true), /** @Since 2.2.0 */ @OApi(maturity = OApi.MATURITY.NEW) DISTRIBUTED_LOCAL_QUEUESIZE( "distributed.localQueueSize", "Size of the intra-thread queue for distributed messages", Integer.class, 10000), /** @Since 2.2.0 */ @OApi(maturity = OApi.MATURITY.NEW) DISTRIBUTED_DB_WORKERTHREADS( "distributed.dbWorkerThreads", "Number of parallel worker threads per database that process distributed messages. Use 0 for automatic", Integer.class, 0), /** @Since 2.1.3, Deprecated in 2.2.0 */ @Deprecated @OApi(maturity = OApi.MATURITY.NEW) DISTRIBUTED_QUEUE_MAXSIZE( "distributed.queueMaxSize", "Maximum queue size to mark a node as stalled. If the number of messages in queue are more than this values, the node is restarted with a remote command (0 = no maximum, which means up to 2^31-1 entries)", Integer.class, 10000), /** @Since 2.1.3 */ @OApi(maturity = OApi.MATURITY.NEW) DISTRIBUTED_BACKUP_DIRECTORY( "distributed.backupDirectory", "Directory where the copy of an existent database is saved, before it is downloaded from the cluster. Leave it empty to avoid the backup.", String.class, "../backup/databases"), /** @Since 2.2.15 */ @OApi(maturity = OApi.MATURITY.NEW) DISTRIBUTED_BACKUP_TRY_INCREMENTAL_FIRST( "distributed.backupTryIncrementalFirst", "Try to execute an incremental backup first.", Boolean.class, true), /** @Since 2.2.27 */ @OApi(maturity = OApi.MATURITY.NEW) DISTRIBUTED_CHECKINTEGRITY_LAST_TX( "distributed.checkIntegrityLastTxs", "Before asking for a delta sync, checks the integrity of the records touched by the last X transactions committed on local server.", Integer.class, 16), /** @Since 2.1 */ @OApi(maturity = OApi.MATURITY.NEW) DISTRIBUTED_CONCURRENT_TX_MAX_AUTORETRY( "distributed.concurrentTxMaxAutoRetry", "Maximum attempts the transaction coordinator should execute a transaction automatically, if records are locked. (Minimum is 1 = no attempts)", Integer.class, 15, true), /** @Since 2.2.7 */ @OApi(maturity = OApi.MATURITY.NEW) DISTRIBUTED_ATOMIC_LOCK_TIMEOUT( "distributed.atomicLockTimeout", "Timeout (in ms) to acquire a distributed lock on a record. (0=infinite)", Integer.class, 100, true), /** @Since 2.1 */ @OApi(maturity = OApi.MATURITY.NEW) DISTRIBUTED_CONCURRENT_TX_AUTORETRY_DELAY( "distributed.concurrentTxAutoRetryDelay", "Delay (in ms) between attempts on executing a distributed transaction, which had failed because of locked records. (0=no delay)", Integer.class, 1000, true), DISTRIBUTED_TRANSACTION_SEQUENCE_SET_SIZE( "distributed.transactionSequenceSetSize", "Size of the set of sequences used by distributed transactions, correspond to the amount of transactions commits that can be active at the same time", Integer.class, 1000, false), DB_DOCUMENT_SERIALIZER( "db.document.serializer", "The default record serializer used by the document database", String.class, ORecordSerializerBinary.NAME), /** @Since 2.2 */ @OApi(maturity = OApi.MATURITY.NEW) CLIENT_KRB5_CONFIG( "client.krb5.config", "Location of the Kerberos configuration file", String.class, null), /** @Since 2.2 */ @OApi(maturity = OApi.MATURITY.NEW) CLIENT_KRB5_CCNAME( "client.krb5.ccname", "Location of the Kerberos client ticketcache", String.class, null), /** @Since 2.2 */ @OApi(maturity = OApi.MATURITY.NEW) CLIENT_KRB5_KTNAME( "client.krb5.ktname", "Location of the Kerberos client keytab", String.class, null), @OApi(maturity = OApi.MATURITY.STABLE) CLIENT_CONNECTION_STRATEGY( "client.connection.strategy", "Strategy used for open connections from a client in case of multiple servers, possible options:STICKY, ROUND_ROBIN_CONNECT, ROUND_ROBIN_REQUEST", String.class, null), @OApi(maturity = OApi.MATURITY.NEW) CLIENT_CONNECTION_FETCH_HOST_LIST( "client.connection.fetchHostList", "If set true fetch the list of other possible hosts from the distributed environment ", Boolean.class, true), /** @Since 2.2 */ @OApi(maturity = OApi.MATURITY.NEW) CLIENT_CREDENTIAL_INTERCEPTOR( "client.credentialinterceptor", "The name of the CredentialInterceptor class", String.class, null), @OApi(maturity = OApi.MATURITY.NEW) CLIENT_CI_KEYALGORITHM( "client.ci.keyalgorithm", "The key algorithm used by the symmetric key credential interceptor", String.class, "AES"), @OApi(maturity = OApi.MATURITY.NEW) CLIENT_CI_CIPHERTRANSFORM( "client.ci.ciphertransform", "The cipher transformation used by the symmetric key credential interceptor", String.class, "AES/CBC/PKCS5Padding"), @OApi(maturity = OApi.MATURITY.NEW) CLIENT_CI_KEYSTORE_FILE( "client.ci.keystore.file", "The file path of the keystore used by the symmetric key credential interceptor", String.class, null), @OApi(maturity = OApi.MATURITY.NEW) CLIENT_CI_KEYSTORE_PASSWORD( "client.ci.keystore.password", "The password of the keystore used by the symmetric key credential interceptor", String.class, null, false, true), /** @Since 2.2 */ @OApi(maturity = OApi.MATURITY.NEW) CREATE_DEFAULT_USERS( "security.createDefaultUsers", "Indicates whether default database users should be created", Boolean.class, false), WARNING_DEFAULT_USERS( "security.warningDefaultUsers", "Indicates whether access with default users should show a warning", Boolean.class, true), /** @Since 2.2 */ @OApi(maturity = OApi.MATURITY.NEW) SERVER_SECURITY_FILE( "server.security.file", "Location of the OrientDB security.json configuration file", String.class, null), // CLOUD CLOUD_PROJECT_TOKEN( "cloud.project.token", "The token used to authenticate this project on the cloud platform", String.class, null), CLOUD_PROJECT_ID( "cloud.project.id", "The ID used to identify this project on the cloud platform", String.class, null), CLOUD_BASE_URL( "cloud.base.url", "The base URL of the cloud endpoint for requests", String.class, "cloud.orientdb.com"), SPATIAL_ENABLE_DIRECT_WKT_READER( "spatial.enableDirectWktReader", "Enable direct usage of WKTReader for additional dimention info", Boolean.class, false), /** Deprecated in v2.2.0 */ @Deprecated JNA_DISABLE_USE_SYSTEM_LIBRARY( "jna.disable.system.library", "This property disables using JNA, should it be installed on your system. (Default true) To use JNA bundled with database", boolean.class, true), @Deprecated DISTRIBUTED_QUEUE_TIMEOUT( "distributed.queueTimeout", "Maximum timeout (in ms) to wait for the response in replication", Long.class, 500000l, true), @Deprecated DB_MAKE_FULL_CHECKPOINT_ON_INDEX_CHANGE( "db.makeFullCheckpointOnIndexChange", "When index metadata is changed, a full checkpoint is performed", Boolean.class, true, true), @Deprecated DB_MAKE_FULL_CHECKPOINT_ON_SCHEMA_CHANGE( "db.makeFullCheckpointOnSchemaChange", "When index schema is changed, a full checkpoint is performed", Boolean.class, true, true), @Deprecated OAUTH2_SECRETKEY("oauth2.secretkey", "Http OAuth2 secret key", String.class, "", false, true), @Deprecated STORAGE_USE_CRC32_FOR_EACH_RECORD( "storage.cluster.usecrc32", "Indicates whether crc32 should be used for each record to check record integrity", Boolean.class, false), @Deprecated DB_USE_DISTRIBUTED_VERSION( "db.use.distributedVersion", "Deprecated, distributed version is not used anymore", Boolean.class, Boolean.FALSE), @Deprecated TX_COMMIT_SYNCH( "tx.commit.synch", "Synchronizes the storage after transaction commit", Boolean.class, false), @Deprecated TX_AUTO_RETRY( "tx.autoRetry", "Maximum number of automatic retry if some resource has been locked in the middle of the transaction (Timeout exception)", Integer.class, 1), @Deprecated TX_LOG_SYNCH( "tx.log.synch", "Executes a synch against the file-system at every log entry. This slows down transactions but guarantee transaction reliability on unreliable drives", Boolean.class, Boolean.FALSE), @Deprecated TX_USE_LOG( "tx.useLog", "Transactions use log file to store temporary data to be rolled back in case of crash", Boolean.class, true), @Deprecated INDEX_AUTO_REBUILD_AFTER_NOTSOFTCLOSE( "index.auto.rebuildAfterNotSoftClose", "Auto rebuild all automatic indexes after upon database open when wasn't closed properly", Boolean.class, true), @Deprecated CLIENT_CHANNEL_MIN_POOL("client.channel.minPool", "Minimum pool size", Integer.class, 1), AUTO_CLOSE_AFTER_DELAY( "storage.autoCloseAfterDelay", "Enable auto close of storage after a specified delay if no session are active", Boolean.class, false), AUTO_CLOSE_DELAY( "storage.autoCloseDelay", "Storage auto close delay time in minutes", Integer.class, 20), /** @Since 3.1 */ @OApi(maturity = OApi.MATURITY.NEW) DISTRIBUTED( "distributed", "Enable the clustering mode", Boolean.class, false, false, false, true), /** @Since 3.1 */ @OApi(maturity = OApi.MATURITY.NEW) DISTRIBUTED_NODE_NAME( "distributed.nodeName", "Name of the OrientDB node in the cluster", String.class, null, false, false, true), CLIENT_CHANNEL_IDLE_CLOSE( "client.channel.idleAutoClose", "Enable the automatic close of idle sockets after a specific timeout", Boolean.class, false), CLIENT_CHANNEL_IDLE_TIMEOUT( "client.channel.idleTimeout", "sockets maximum time idle in seconds", Integer.class, 900), DISTRIBUTED_AUTO_CREATE_CLUSTERS( "distributed.autoCreateClusters", "if true enable auto creation of cluster when a new node join", Boolean.class, true), ENTERPRISE_METRICS_MAX( "emterprise.metrics.max", "Top limit of number of metrics that the enterprise edition can keep in memory", Integer.class, 2500, false, false), ; static { readConfiguration(); } /** Place holder for the "undefined" value of setting. */ private final Object nullValue = new Object(); private final String key; private final Object defValue; private final Class<?> type; private final String description; private final OConfigurationChangeCallback changeCallback; private final Boolean canChangeAtRuntime; private final boolean hidden; private boolean env; private volatile Object value = nullValue; OGlobalConfiguration( final String iKey, final String iDescription, final Class<?> iType, final Object iDefValue, final OConfigurationChangeCallback iChangeAction) { key = iKey; description = iDescription; defValue = iDefValue; type = iType; canChangeAtRuntime = true; hidden = false; changeCallback = iChangeAction; } OGlobalConfiguration( final String iKey, final String iDescription, final Class<?> iType, final Object iDefValue) { this(iKey, iDescription, iType, iDefValue, false); } OGlobalConfiguration( final String iKey, final String iDescription, final Class<?> iType, final Object iDefValue, final Boolean iCanChange) { this(iKey, iDescription, iType, iDefValue, iCanChange, false); } OGlobalConfiguration( final String iKey, final String iDescription, final Class<?> iType, final Object iDefValue, final boolean iCanChange, final boolean iHidden) { this(iKey, iDescription, iType, iDefValue, iCanChange, iHidden, false); } OGlobalConfiguration( final String iKey, final String iDescription, final Class<?> iType, final Object iDefValue, final boolean iCanChange, final boolean iHidden, final boolean iEnv) { key = iKey; description = iDescription; defValue = iDefValue; type = iType; canChangeAtRuntime = iCanChange; hidden = iHidden; env = iEnv; changeCallback = null; } public static void dumpConfiguration(final PrintStream out) { out.print("OrientDB "); out.print(OConstants.getVersion()); out.println(" configuration dump:"); String lastSection = ""; for (OGlobalConfiguration value : values()) { final int index = value.key.indexOf('.'); String section = value.key; if (index >= 0) { section = value.key.substring(0, index); } if (!lastSection.equals(section)) { out.print("- "); out.println(section.toUpperCase(Locale.ENGLISH)); lastSection = section; } out.print(" + "); out.print(value.key); out.print(" = "); out.println(value.isHidden() ? "<hidden>" : String.valueOf((Object) value.getValue())); } } /** * Find the OGlobalConfiguration instance by the key. Key is case insensitive. * * @param iKey Key to find. It's case insensitive. * @return OGlobalConfiguration instance if found, otherwise null */ public static OGlobalConfiguration findByKey(final String iKey) { for (OGlobalConfiguration v : values()) { if (v.getKey().equalsIgnoreCase(iKey)) return v; } return null; } /** * Changes the configuration values in one shot by passing a Map of values. Keys can be the Java * ENUM names or the string representation of configuration values */ public static void setConfiguration(final Map<String, Object> iConfig) { for (Entry<String, Object> config : iConfig.entrySet()) { for (OGlobalConfiguration v : values()) { if (v.getKey().equals(config.getKey())) { v.setValue(config.getValue()); break; } else if (v.name().equals(config.getKey())) { v.setValue(config.getValue()); break; } } } } /** Assign configuration values by reading system properties. */ private static void readConfiguration() { String prop; for (OGlobalConfiguration config : values()) { prop = System.getProperty(config.key); if (prop != null) config.setValue(prop); } for (OGlobalConfiguration config : values()) { String key = getEnvKey(config); if (key != null) { prop = System.getenv(key); if (prop != null) { config.setValue(prop); } } } } public static String getEnvKey(OGlobalConfiguration config) { if (!config.env) return null; return "ORIENTDB_" + config.name(); } public <T> T getValue() { //noinspection unchecked return (T) (value != null && value != nullValue ? value : defValue); } /** * @return <code>true</code> if configuration was changed from default value and <code>false * </code> otherwise. */ public boolean isChanged() { return value != nullValue; } public void setValue(final Object iValue) { Object oldValue = value; if (iValue != null) if (type == Boolean.class) value = Boolean.parseBoolean(iValue.toString()); else if (type == Integer.class) value = Integer.parseInt(iValue.toString()); else if (type == Float.class) value = Float.parseFloat(iValue.toString()); else if (type == String.class) value = iValue.toString(); else if (type.isEnum()) { boolean accepted = false; if (type.isInstance(iValue)) { value = iValue; accepted = true; } else if (iValue instanceof String) { final String string = (String) iValue; for (Object constant : type.getEnumConstants()) { final Enum<?> enumConstant = (Enum<?>) constant; if (enumConstant.name().equalsIgnoreCase(string)) { value = enumConstant; accepted = true; break; } } } if (!accepted) throw new IllegalArgumentException("Invalid value of `" + key + "` option."); } else value = iValue; if (changeCallback != null) { try { changeCallback.change( oldValue == nullValue ? null : oldValue, value == nullValue ? null : value); } catch (Exception e) { OLogManager.instance().error(this, "Error during call of 'change callback'", e); } } } public boolean getValueAsBoolean() { final Object v = value != null && value != nullValue ? value : defValue; return v instanceof Boolean ? (Boolean) v : Boolean.parseBoolean(v.toString()); } public String getValueAsString() { return value != null && value != nullValue ? value.toString() : defValue != null ? defValue.toString() : null; } public int getValueAsInteger() { final Object v = value != null && value != nullValue ? value : defValue; return (int) (v instanceof Number ? ((Number) v).intValue() : OFileUtils.getSizeAsNumber(v.toString())); } public long getValueAsLong() { final Object v = value != null && value != nullValue ? value : defValue; return v instanceof Number ? ((Number) v).longValue() : OFileUtils.getSizeAsNumber(v.toString()); } public float getValueAsFloat() { final Object v = value != null && value != nullValue ? value : defValue; return v instanceof Float ? (Float) v : Float.parseFloat(v.toString()); } public String getKey() { return key; } public Boolean isChangeableAtRuntime() { return canChangeAtRuntime; } public boolean isHidden() { return hidden; } public Object getDefValue() { return defValue; } public Class<?> getType() { return type; } public String getDescription() { return description; } private static class OCacheSizeChangeCallback implements OConfigurationChangeCallback { @Override public void change(Object currentValue, Object newValue) { final Orient orient = Orient.instance(); if (orient != null) { final OEngineLocalPaginated engineLocalPaginated = (OEngineLocalPaginated) orient.getEngineIfRunning(OEngineLocalPaginated.NAME); if (engineLocalPaginated != null) engineLocalPaginated.changeCacheSize(((Integer) (newValue)) * 1024L * 1024L); } } } private static class OProfileEnabledChangeCallbac implements OConfigurationChangeCallback { public void change(final Object iCurrentValue, final Object iNewValue) { Orient instance = Orient.instance(); if (instance != null) { final OProfiler prof = instance.getProfiler(); if (prof != null) if ((Boolean) iNewValue) prof.startRecording(); else prof.stopRecording(); } } } private static class OProfileConfigChangeCallback implements OConfigurationChangeCallback { public void change(final Object iCurrentValue, final Object iNewValue) { Orient.instance().getProfiler().configure(iNewValue.toString()); } } private static class OProfileDumpIntervalChangeCallback implements OConfigurationChangeCallback { public void change(final Object iCurrentValue, final Object iNewValue) { Orient.instance().getProfiler().setAutoDump((Integer) iNewValue); } } }
core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java
/* * * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * * For more information: http://orientdb.com * */ package com.orientechnologies.orient.core.config; import com.orientechnologies.common.io.OFileUtils; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.common.profiler.OProfiler; import com.orientechnologies.common.util.OApi; import com.orientechnologies.orient.core.OConstants; import com.orientechnologies.orient.core.Orient; import com.orientechnologies.orient.core.cache.ORecordCacheWeakRefs; import com.orientechnologies.orient.core.engine.local.OEngineLocalPaginated; import com.orientechnologies.orient.core.index.OIndexDefinition; import com.orientechnologies.orient.core.metadata.OMetadataDefault; import com.orientechnologies.orient.core.serialization.serializer.record.binary.ORecordSerializerBinary; import com.orientechnologies.orient.core.storage.OChecksumMode; import com.orientechnologies.orient.core.storage.cluster.OPaginatedCluster; import java.io.PrintStream; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.logging.ConsoleHandler; import java.util.logging.FileHandler; import java.util.logging.Level; /** * Keeps all configuration settings. At startup assigns the configuration values by reading system * properties. * * @author Luca Garulli (l.garulli--(at)--orientdb.com) */ public enum OGlobalConfiguration { // ENVIRONMENT ENVIRONMENT_DUMP_CFG_AT_STARTUP( "environment.dumpCfgAtStartup", "Dumps the configuration during application startup", Boolean.class, Boolean.FALSE), @Deprecated ENVIRONMENT_CONCURRENT( "environment.concurrent", "Specifies if running in multi-thread environment. Setting this to false turns off the internal lock management", Boolean.class, Boolean.TRUE), ENVIRONMENT_LOCK_MANAGER_CONCURRENCY_LEVEL( "environment.lock.concurrency.level", "Concurrency level of lock manager", Integer.class, Runtime.getRuntime().availableProcessors() << 3, false), @Deprecated ENVIRONMENT_ALLOW_JVM_SHUTDOWN( "environment.allowJVMShutdown", "Allows the shutdown of the JVM, if needed/requested", Boolean.class, true, true), // SCRIPT SCRIPT_POOL( "script.pool.maxSize", "Maximum number of instances in the pool of script engines", Integer.class, 20), SCRIPT_POLYGLOT_USE_GRAAL( "script.polyglot.useGraal", "Use GraalVM as polyglot engine", Boolean.class, true), // MEMORY MEMORY_USE_UNSAFE( "memory.useUnsafe", "Indicates whether Unsafe will be used, if it is present", Boolean.class, true), MEMORY_PROFILING( "memory.profiling", "Switches on profiling of allocations of direct memory inside of OrientDB.", Boolean.class, false), MEMORY_PROFILING_REPORT_INTERVAL( "memory.profiling.reportInterval", "Interval of printing of memory profiling results in minutes", Integer.class, 15), @Deprecated MEMORY_CHUNK_SIZE( "memory.chunk.size", "Size of single memory chunk (in bytes) which will be preallocated by OrientDB", Integer.class, Integer.MAX_VALUE), MEMORY_LEFT_TO_OS( "memory.leftToOS", "Amount of free memory which should be left unallocated in case of OrientDB is started outside of container. " + "Value can be set as % of total memory provided to OrientDB or as absolute value in bytes, kilobytes, megabytes or gigabytes. " + "If you set value as 10% it means that 10% of memory will not be allocated by OrientDB and will be left to use by the rest of " + "applications, if 2g value is provided it means that 2 gigabytes of memory will be left to use by the rest of applications. " + "Default value is 2g", String.class, "2g"), MEMORY_LEFT_TO_CONTAINER( "memory.leftToContainer", "Amount of free memory which should be left unallocated in case of OrientDB is started inside of container. " + "Value can be set as % of total memory provided to OrientDB or as absolute value in bytes, kilobytes, megabytes or gigabytes. " + "If you set value as 10% it means that 10% of memory will not be allocated by OrientDB and will be left to use by the rest of " + "applications, if 2g value is provided it means that 2 gigabytes of memory will be left to use by the rest of applications. " + "Default value is 256m", String.class, "256m"), DIRECT_MEMORY_SAFE_MODE( "memory.directMemory.safeMode", "Indicates whether to perform a range check before each direct memory update. It is true by default, " + "but usually it can be safely set to false. It should only be to true after dramatic changes have been made in the storage structures", Boolean.class, true), DIRECT_MEMORY_POOL_LIMIT( "memory.pool.limit", "Limit of the pages cached inside of direct memory pool to avoid frequent reallocation of memory in OS", Integer.class, Integer.MAX_VALUE), DIRECT_MEMORY_PREALLOCATE( "memory.directMemory.preallocate", "Preallocate amount of direct memory which is needed for the disk cache", Boolean.class, false), DIRECT_MEMORY_TRACK_MODE( "memory.directMemory.trackMode", "Activates the direct memory pool [leak detector](Leak-Detector.md). This detector causes a large overhead and should be used for debugging " + "purposes only. It's also a good idea to pass the " + "-Djava.util.logging.manager=com.orientechnologies.common.log.ShutdownLogManager switch to the JVM, " + "if you use this mode, this will enable the logging from JVM shutdown hooks.", Boolean.class, false), DIRECT_MEMORY_ONLY_ALIGNED_ACCESS( "memory.directMemory.onlyAlignedMemoryAccess", "Some architectures do not allow unaligned memory access or may suffer from speed degradation. For such platforms, this flag should be set to true", Boolean.class, true), @Deprecated JVM_GC_DELAY_FOR_OPTIMIZE( "jvm.gc.delayForOptimize", "Minimal amount of time (in seconds), since the last System.gc(), when called after tree optimization", Long.class, 600), // STORAGE /** Limit of amount of files which may be open simultaneously */ OPEN_FILES_LIMIT( "storage.openFiles.limit", "Limit of amount of files which may be open simultaneously, -1 (default) means automatic detection", Integer.class, -1), /** * Amount of cached locks is used for component lock in atomic operation to avoid constant * creation of new lock instances, default value is 10000. */ COMPONENTS_LOCK_CACHE( "storage.componentsLock.cache", "Amount of cached locks is used for component lock to avoid constant creation of new lock instances", Integer.class, 10000), DISK_CACHE_PINNED_PAGES( "storage.diskCache.pinnedPages", "Maximum amount of pinned pages which may be contained in cache," + " if this percent is reached next pages will be left in unpinned state. You can not set value more than 50", Integer.class, 20, false), DISK_CACHE_SIZE( "storage.diskCache.bufferSize", "Size of disk buffer in megabytes, disk size may be changed at runtime, " + "but if does not enough to contain all pinned pages exception will be thrown", Integer.class, 4 * 1024, new OCacheSizeChangeCallback()), DISK_WRITE_CACHE_PART( "storage.diskCache.writeCachePart", "Percentage of disk cache, which is used as write cache", Integer.class, 5), @Deprecated DISK_WRITE_CACHE_USE_ASYNC_IO( "storage.diskCache.useAsyncIO", "Use asynchronous IO API to facilitate abilities of SSD to parallelize IO requests", Boolean.class, true), @Deprecated DISK_USE_NATIVE_OS_API( "storage.disk.useNativeOsAPI", "Allows to call native OS methods if possible", Boolean.class, true), DISK_WRITE_CACHE_SHUTDOWN_TIMEOUT( "storage.diskCache.writeCacheShutdownTimeout", "Timeout of shutdown of write cache for single task in min.", Integer.class, 30), DISK_WRITE_CACHE_PAGE_TTL( "storage.diskCache.writeCachePageTTL", "Max time until a page will be flushed from write cache (in seconds)", Long.class, 24 * 60 * 60), DISK_WRITE_CACHE_PAGE_FLUSH_INTERVAL( "storage.diskCache.writeCachePageFlushInterval", "Interval between flushing of pages from write cache (in ms)", Integer.class, 25), DISK_WRITE_CACHE_FLUSH_WRITE_INACTIVITY_INTERVAL( "storage.diskCache.writeCacheFlushInactivityInterval", "Interval between 2 writes to the disk cache," + " if writes are done with an interval more than provided, all files will be fsynced before the next write," + " which allows a data restore after a server crash (in ms)", Long.class, 60 * 1000), DISK_WRITE_CACHE_FLUSH_LOCK_TIMEOUT( "storage.diskCache.writeCacheFlushLockTimeout", "Maximum amount of time the write cache will wait before a page flushes (in ms, -1 to disable)", Integer.class, -1), @Deprecated DISC_CACHE_FREE_SPACE_CHECK_INTERVAL( "storage.diskCache.diskFreeSpaceCheckInterval", "The interval (in seconds), after which the storage periodically " + "checks whether the amount of free disk space is enough to work in write mode", Integer.class, 5), /** * The interval (how many new pages should be added before free space will be checked), after * which the storage periodically checks whether the amount of free disk space is enough to work * in write mode. */ DISC_CACHE_FREE_SPACE_CHECK_INTERVAL_IN_PAGES( "storage.diskCache.diskFreeSpaceCheckIntervalInPages", "The interval (how many new pages should be added before free space will be checked), after which the storage periodically " + "checks whether the amount of free disk space is enough to work in write mode", Integer.class, 2048), /** * Keep disk cache state between moment when storage is closed and moment when it is opened again. * <code>true</code> by default. */ STORAGE_KEEP_DISK_CACHE_STATE( "storage.diskCache.keepState", "Keep disk cache state between moment when storage is closed and moment when it is opened again. true by default", Boolean.class, false), STORAGE_CHECKSUM_MODE( "storage.diskCache.checksumMode", "Controls the per-page checksum storage and verification done by " + "the file cache. Possible modes: 'off' – checksums are completely off; 'store' – checksums are calculated and stored " + "on page flushes, no verification is done on page loads, stored checksums are verified only during user-initiated health " + "checks; 'storeAndVerify' – checksums are calculated and stored on page flushes, verification is performed on " + "each page load, errors are reported in the log; 'storeAndThrow' – same as `storeAndVerify` with addition of exceptions " + "thrown on errors, this mode is useful for debugging and testing, but should be avoided in a production environment;" + " 'storeAndSwitchReadOnlyMode' (default) - Same as 'storeAndVerify' with addition that storage will be switched in read only mode " + "till it will not be repaired.", OChecksumMode.class, OChecksumMode.StoreAndSwitchReadOnlyMode, false), STORAGE_CHECK_LATEST_OPERATION_ID( "storage.checkLatestOperationId", "Indicates wether storage should be checked for latest operation id, " + "to ensure that all the records are needed to restore database are stored into the WAL (true by default)", Boolean.class, true), STORAGE_EXCLUSIVE_FILE_ACCESS( "storage.exclusiveFileAccess", "Limit access to the datafiles to the single API user, set to " + "true to prevent concurrent modification files by different instances of storage", Boolean.class, true), STORAGE_TRACK_FILE_ACCESS( "storage.trackFileAccess", "Works only if storage.exclusiveFileAccess is set to true. " + "Tracks stack trace of thread which initially opened a file", Boolean.class, true), @Deprecated STORAGE_CONFIGURATION_SYNC_ON_UPDATE( "storage.configuration.syncOnUpdate", "Indicates a force sync should be performed for each update on the storage configuration", Boolean.class, true), STORAGE_COMPRESSION_METHOD( "storage.compressionMethod", "Record compression method used in storage" + " Possible values : gzip, nothing. Default is 'nothing' that means no compression", String.class, "nothing"), @Deprecated STORAGE_ENCRYPTION_METHOD( "storage.encryptionMethod", "Record encryption method used in storage" + " Possible values : 'aes' and 'des'. Default is 'nothing' for no encryption", String.class, "nothing"), STORAGE_ENCRYPTION_KEY( "storage.encryptionKey", "Contains the storage encryption key. This setting is hidden", String.class, null, false, true), STORAGE_MAKE_FULL_CHECKPOINT_AFTER_CREATE( "storage.makeFullCheckpointAfterCreate", "Indicates whether a full checkpoint should be performed, if storage was created", Boolean.class, false), /** * @deprecated because it was used as workaround for the case when storage is already opened but * there are no checkpoints and as result data restore after crash may work incorrectly, this * bug is fixed under https://github.com/orientechnologies/orientdb/issues/7562 in so this * functionality is not needed any more. */ @Deprecated STORAGE_MAKE_FULL_CHECKPOINT_AFTER_OPEN( "storage.makeFullCheckpointAfterOpen", "Indicates whether a full checkpoint should be performed, if storage was opened. It is needed so fuzzy checkpoints can work properly", Boolean.class, true), STORAGE_ATOMIC_OPERATIONS_TABLE_COMPACTION_LIMIT( "storage.atomicOperationsTable.compactionLimit", "Limit of size of atomic operations table after which compaction will be triggered on", Integer.class, 10_000), STORAGE_MAKE_FULL_CHECKPOINT_AFTER_CLUSTER_CREATE( "storage.makeFullCheckpointAfterClusterCreate", "Indicates whether a full checkpoint should be performed, if storage was opened", Boolean.class, true), STORAGE_CALL_FSYNC( "storage.callFsync", "Call fsync during fuzzy checkpoints or WAL writes, true by default", Boolean.class, true), STORAGE_USE_DOUBLE_WRITE_LOG( "storage.useDoubleWriteLog", "Allows usage of double write log in storage. " + "This log prevents pages to be teared apart so it is not recommended to switch it off.", Boolean.class, true), STORAGE_DOUBLE_WRITE_LOG_MAX_SEG_SIZE( "storage.doubleWriteLog.maxSegSize", "Maximum size of double write log segment in megabytes, -1 means that size will be calculated automatically", Integer.class, -1), STORAGE_DOUBLE_WRITE_LOG_MAX_SEG_SIZE_PERCENT( "storage.doubleWriteLog.maxSegSizePercent", "Maximum size of segment of double write log in percents, should be set to value bigger than 0", Integer.class, 5), STORAGE_DOUBLE_WRITE_LOG_MIN_SEG_SIZE( "storage.doubleWriteLog.minSegSize", "Minimum size of segment of double write log in megabytes, should be set to value bigger than 0. " + "If both set maximum and minimum size of segments. Minimum size always will have priority over maximum size.", Integer.class, 256), @Deprecated STORAGE_TRACK_PAGE_OPERATIONS_IN_TX( "storage.trackOperationsInTx", "If this flag switched on, transaction features will be implemented " + "not by tracking of binary changes, but by tracking of operations on page level.", Boolean.class, false), STORAGE_PAGE_OPERATIONS_CACHE_SIZE( "storage.pageOperationsCacheSize", "Size of page operations cache in MB per transaction. " + "If operations are cached, they are not read from WAL during rollback.", Integer.class, 16), STORAGE_CLUSTER_VERSION( "storage.cluster.version", "Binary version of cluster which will be used inside of storage", Integer.class, OPaginatedCluster.getLatestBinaryVersion()), STORAGE_PRINT_WAL_PERFORMANCE_STATISTICS( "storage.printWALPerformanceStatistics", "Periodically prints statistics about WAL performance", Boolean.class, false), STORAGE_PRINT_WAL_PERFORMANCE_INTERVAL( "storage.walPerformanceStatisticsInterval", "Interval in seconds between consequent reports of WAL performance statistics", Integer.class, 10), @Deprecated STORAGE_TRACK_CHANGED_RECORDS_IN_WAL( "storage.trackChangedRecordsInWAL", "If this flag is set metadata which contains rids of changed records is added at the end of each atomic operation", Boolean.class, false), STORAGE_INTERNAL_JOURNALED_TX_STREAMING_PORT( "storage.internal.journaled.tx.streaming.port", "Activates journaled tx streaming " + "on the given TCP/IP port. Used for internal testing purposes only. Never touch it if you don't know what you doing.", Integer.class, null), STORAGE_PESSIMISTIC_LOCKING( "storage.pessimisticLock", "Set the approach of the pessimistic locking, valid options: none, modification, readwrite", String.class, "none"), /** * @deprecated WAL can not be disabled because that is very unsafe for consistency and durability */ @Deprecated USE_WAL("storage.useWAL", "Whether WAL should be used in paginated storage", Boolean.class, true), @Deprecated USE_CHM_CACHE( "storage.useCHMCache", "Whether to use new disk cache implementation based on CHM or old one based on cuncurrent queues", Boolean.class, true), WAL_SYNC_ON_PAGE_FLUSH( "storage.wal.syncOnPageFlush", "Indicates whether a force sync should be performed during WAL page flush", Boolean.class, true), WAL_CACHE_SIZE( "storage.wal.cacheSize", "Maximum size of WAL cache (in amount of WAL pages, each page is 4k) If set to 0, caching will be disabled", Integer.class, 65536), WAL_BUFFER_SIZE( "storage.wal.bufferSize", "Size of the direct memory WAL buffer which is used inside of " + "the background write thread (in MB)", Integer.class, 64), WAL_SEGMENTS_INTERVAL( "storage.wal.segmentsInterval", "Maximum interval in time in min. after which new WAL segment will be added", Integer.class, 10), WAL_FILE_AUTOCLOSE_INTERVAL( "storage.wal.fileAutoCloseInterval", "Interval in seconds after which WAL file will be closed if there is no " + "any IO operations on this file (in seconds), default value is 10", Integer.class, 10, false), WAL_SEGMENT_BUFFER_SIZE( "storage.wal.segmentBufferSize", "Size of the buffer which contains WAL records in serialized format " + "in megabytes", Integer.class, 32), WAL_MAX_SEGMENT_SIZE( "storage.wal.maxSegmentSize", "Maximum size of single WAL segment (in megabytes)", Integer.class, -1), WAL_MAX_SEGMENT_SIZE_PERCENT( "storage.wal.maxSegmentSizePercent", "Maximum size of single WAL segment in percent of initial free space", Integer.class, 5), WAL_MIN_SEG_SIZE( "storage.wal.minSegSize", "Minimal value of maximum WAL segment size in MB", Integer.class, 6 * 1024), WAL_MIN_COMPRESSED_RECORD_SIZE( "storage.wal.minCompressedRecordSize", "Minimum size of record which is needed to be compressed before stored on disk", Integer.class, 8 * 1024), WAL_MAX_SIZE( "storage.wal.maxSize", "Maximum size of WAL on disk (in megabytes)", Integer.class, -1), WAL_KEEP_SINGLE_SEGMENT( "storage.wal.keepSingleSegment", "Database will provide the best efforts to keep only single WAL inside the storage", Boolean.class, true), @Deprecated WAL_ALLOW_DIRECT_IO( "storage.wal.allowDirectIO", "Allows usage of direct IO API on Linux OS to avoid keeping of WAL data in OS buffer", Boolean.class, false), WAL_COMMIT_TIMEOUT( "storage.wal.commitTimeout", "Maximum interval between WAL commits (in ms.)", Integer.class, 1000), WAL_SHUTDOWN_TIMEOUT( "storage.wal.shutdownTimeout", "Maximum wait interval between events, when the background flush thread" + "receives a shutdown command and when the background flush will be stopped (in ms.)", Integer.class, 10000), WAL_FUZZY_CHECKPOINT_INTERVAL( "storage.wal.fuzzyCheckpointInterval", "Interval between fuzzy checkpoints (in seconds)", Integer.class, 300), WAL_REPORT_AFTER_OPERATIONS_DURING_RESTORE( "storage.wal.reportAfterOperationsDuringRestore", "Amount of processed log operations, after which status of data restore procedure will be printed (0 or a negative value, disables the logging)", Integer.class, 10000), WAL_RESTORE_BATCH_SIZE( "storage.wal.restore.batchSize", "Amount of WAL records, which are read at once in a single batch during a restore procedure", Integer.class, 1000), @Deprecated WAL_READ_CACHE_SIZE( "storage.wal.readCacheSize", "Size of WAL read cache in amount of pages", Integer.class, 1000), WAL_FUZZY_CHECKPOINT_SHUTDOWN_TIMEOUT( "storage.wal.fuzzyCheckpointShutdownWait", "The amount of time the DB should wait until it shuts down (in seconds)", Integer.class, 60 * 10), WAL_FULL_CHECKPOINT_SHUTDOWN_TIMEOUT( "storage.wal.fullCheckpointShutdownTimeout", "The amount of time the DB will wait, until a checkpoint is finished, during a DB shutdown (in seconds)", Integer.class, 60 * 10), WAL_LOCATION( "storage.wal.path", "Path to the WAL file on the disk. By default, it is placed in the DB directory, but" + " it is highly recommended to use a separate disk to store log operations", String.class, null), DISK_CACHE_PAGE_SIZE( "storage.diskCache.pageSize", "Size of page of disk buffer (in kilobytes). !!! NEVER CHANGE THIS VALUE !!!", Integer.class, 64), DISK_CACHE_PRINT_FLUSH_TILL_SEGMENT_STATISTICS( "storage.diskCache.printFlushTillSegmentStatistics", "Print information about write cache state when it is requested to flush all data operations on which are logged " + "till provided WAL segment", Boolean.class, true), DISK_CACHE_PRINT_FLUSH_FILE_STATISTICS( "storage.diskCache.printFlushFileStatistics", "Print information about write cache state when it is requested to flush all data of file specified", Boolean.class, true), DISK_CACHE_PRINT_FILE_REMOVE_STATISTICS( "storage.diskCache.printFileRemoveStatistics", "Print information about write cache state when it is requested to clear all data of file specified", Boolean.class, true), DISK_CACHE_WAL_SIZE_TO_START_FLUSH( "storage.diskCache.walSizeToStartFlush", "WAL size after which pages in write cache will be started to flush", Long.class, 6 * 1024L * 1024 * 1024), DISK_CACHE_EXCLUSIVE_FLUSH_BOUNDARY( "storage.diskCache.exclusiveFlushBoundary", "If portion of exclusive pages into cache exceeds this value we start to flush only exclusive pages from disk cache", Float.class, 0.9), DISK_CACHE_CHUNK_SIZE( "storage.diskCache.chunkSize", "Maximum distance between two pages after which they are not treated as single continous chunk", Integer.class, 256), DISK_CACHE_EXCLUSIVE_PAGES_BOUNDARY( "storage.diskCache.exclusiveBoundary", "Portion of exclusive pages in write cache after which we will start to flush only exclusive pages", Float.class, 0.7), DISK_CACHE_WAL_SIZE_TO_STOP_FLUSH( "storage.diskCache.walSizeToStopFlush", "WAL size reaching which pages in write cache will be prevented from flush", Long.class, 2 * 1024L * 1024 * 1024), DISK_CACHE_FREE_SPACE_LIMIT( "storage.diskCache.diskFreeSpaceLimit", "Minimum amount of space on disk, which, when exceeded, " + "will cause the database to switch to read-only mode (in megabytes)", Long.class, 8 * WAL_MAX_SEGMENT_SIZE.getValueAsLong()), @Deprecated PAGINATED_STORAGE_LOWEST_FREELIST_BOUNDARY( "storage.lowestFreeListBound", "The least amount of free space (in kb) in a page, which is tracked in paginated storage", Integer.class, 16), STORAGE_LOCK_TIMEOUT( "storage.lockTimeout", "Maximum amount of time (in ms) to lock the storage", Integer.class, 0), STORAGE_RECORD_LOCK_TIMEOUT( "storage.record.lockTimeout", "Maximum of time (in ms) to lock a shared record", Integer.class, 2000), @Deprecated STORAGE_USE_TOMBSTONES( "storage.useTombstones", "When a record is deleted, the space in the cluster will not be freed, but rather tombstoned", Boolean.class, false), // RECORDS @Deprecated RECORD_DOWNSIZING_ENABLED( "record.downsizing.enabled", "On updates, if the record size is lower than before, this reduces the space taken accordingly. " + "If enabled this could increase defragmentation, but it reduces the used disk space", Boolean.class, true), // DATABASE OBJECT_SAVE_ONLY_DIRTY( "object.saveOnlyDirty", "Object Database only! It saves objects bound to dirty records", Boolean.class, false, true), DOCUMENT_BINARY_MAPPING( "document.binaryMapping", "Mapping approach for binary fields", Integer.class, 0), // DATABASE DB_POOL_MIN("db.pool.min", "Default database pool minimum size", Integer.class, 1), DB_POOL_MAX("db.pool.max", "Default database pool maximum size", Integer.class, 100), DB_CACHED_POOL_CAPACITY( "db.cached.pool.capacity", "Default database cached pools capacity", Integer.class, 100), DB_STRING_CAHCE_SIZE( "db.string.cache.size", "Number of common string to keep in memory cache", Integer.class, 5000), DB_CACHED_POOL_CLEAN_UP_TIMEOUT( "db.cached.pool.cleanUpTimeout", "Default timeout for clean up cache from unused or closed database pools, value in milliseconds", Long.class, 600_000), DB_POOL_ACQUIRE_TIMEOUT( "db.pool.acquireTimeout", "Default database pool timeout in milliseconds", Integer.class, 60000), @Deprecated DB_POOL_IDLE_TIMEOUT( "db.pool.idleTimeout", "Timeout for checking for free databases in the pool", Integer.class, 0), @Deprecated DB_POOL_IDLE_CHECK_DELAY( "db.pool.idleCheckDelay", "Delay time on checking for idle databases", Integer.class, 0), DB_MVCC_THROWFAST( "db.mvcc.throwfast", "Use fast-thrown exceptions for MVCC OConcurrentModificationExceptions. No context information will be available. " + "Set to true, when these exceptions are thrown, but the details are not necessary", Boolean.class, false, true), DB_VALIDATION( "db.validation", "Enables or disables validation of records", Boolean.class, true, true), DB_CUSTOM_SUPPORT( "db.custom.support", "Enables or disables use of custom types", Boolean.class, false, false), // SETTINGS OF NON-TRANSACTIONAL MODE @Deprecated NON_TX_RECORD_UPDATE_SYNCH( "nonTX.recordUpdate.synch", "Executes a sync against the file-system for every record operation. This slows down record updates, " + "but guarantees reliability on unreliable drives", Boolean.class, Boolean.FALSE), NON_TX_CLUSTERS_SYNC_IMMEDIATELY( "nonTX.clusters.sync.immediately", "List of clusters to sync immediately after update (separated by commas). Can be useful for a manual index", String.class, OMetadataDefault.CLUSTER_MANUAL_INDEX_NAME), // TRANSACTIONS @Deprecated TX_TRACK_ATOMIC_OPERATIONS( "tx.trackAtomicOperations", "This setting is used only for debug purposes. It creates a stack trace of methods, when an atomic operation is started", Boolean.class, false), TX_PAGE_CACHE_SIZE( "tx.pageCacheSize", "The size of a per-transaction page cache in pages, 12 by default, 0 to disable the cache.", Integer.class, 12), // INDEX INDEX_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD( "index.embeddedToSbtreeBonsaiThreshold", "Amount of values, after which the index implementation will use an sbtree as a values container. Set to -1, to disable and force using an sbtree", Integer.class, 40, true), INDEX_SBTREEBONSAI_TO_EMBEDDED_THRESHOLD( "index.sbtreeBonsaiToEmbeddedThreshold", "Amount of values, after which index implementation will use an embedded values container (disabled by default)", Integer.class, -1, true), HASH_TABLE_SPLIT_BUCKETS_BUFFER_LENGTH( "hashTable.slitBucketsBuffer.length", "Length of buffer (in pages), where buckets " + "that were split, but not flushed to the disk, are kept. This buffer is used to minimize random IO overhead", Integer.class, 1500), INDEX_SYNCHRONOUS_AUTO_REBUILD( "index.auto.synchronousAutoRebuild", "Synchronous execution of auto rebuilding of indexes, in case of a DB crash", Boolean.class, Boolean.TRUE), @Deprecated INDEX_AUTO_LAZY_UPDATES( "index.auto.lazyUpdates", "Configure the TreeMaps for automatic indexes, as buffered or not. -1 means buffered until tx.commit() or db.close() are called", Integer.class, 10000), INDEX_FLUSH_AFTER_CREATE( "index.flushAfterCreate", "Flush storage buffer after index creation", Boolean.class, true), @Deprecated INDEX_MANUAL_LAZY_UPDATES( "index.manual.lazyUpdates", "Configure the TreeMaps for manual indexes as buffered or not. -1 means buffered until tx.commit() or db.close() are called", Integer.class, 1), INDEX_DURABLE_IN_NON_TX_MODE( "index.durableInNonTxMode", "Indicates whether index implementation for plocal storage will be durable in non-Tx mode (true by default)", Boolean.class, true), INDEX_ALLOW_MANUAL_INDEXES( "index.allowManualIndexes", "Switch which allows usage of manual indexes inside OrientDB. " + "It is not recommended to switch it on, because manual indexes are deprecated, not supported and will be removed in next versions", Boolean.class, true), INDEX_ALLOW_MANUAL_INDEXES_WARNING( "index.allowManualIndexesWarning", "Switch which triggers printing of waring message any time when " + "manual indexes are used. It is not recommended to switch it off, because manual indexes are deprecated, " + "not supported and will be removed in next versions", Boolean.class, true), /** * @see OIndexDefinition#isNullValuesIgnored() * @since 2.2 */ INDEX_IGNORE_NULL_VALUES_DEFAULT( "index.ignoreNullValuesDefault", "Controls whether null values will be ignored by default " + "by newly created indexes or not (false by default)", Boolean.class, false), @Deprecated INDEX_TX_MODE( "index.txMode", "Indicates the index durability level in TX mode. Can be ROLLBACK_ONLY or FULL (ROLLBACK_ONLY by default)", String.class, "FULL"), INDEX_CURSOR_PREFETCH_SIZE( "index.stream.prefetchSize", "Default prefetch size of index stream", Integer.class, 10), // SBTREE SBTREE_MAX_DEPTH( "sbtree.maxDepth", "Maximum depth of sbtree, which will be traversed during key look up until it will be treated as broken (64 by default)", Integer.class, 64), SBTREE_MAX_KEY_SIZE( "sbtree.maxKeySize", "Maximum size of a key, which can be put in the SBTree in bytes (10240 by default)", Integer.class, 10240), SBTREE_MAX_EMBEDDED_VALUE_SIZE( "sbtree.maxEmbeddedValueSize", "Maximum size of value which can be put in an SBTree without creation link to a standalone page in bytes (40960 by default)", Integer.class, 40960), SBTREEBONSAI_BUCKET_SIZE( "sbtreebonsai.bucketSize", "Size of bucket in OSBTreeBonsai (in kB). Contract: bucketSize < storagePageSize, storagePageSize % bucketSize == 0", Integer.class, 2), SBTREEBONSAI_LINKBAG_CACHE_SIZE( "sbtreebonsai.linkBagCache.size", "Amount of LINKBAG collections to be cached, to avoid constant reloading of data", Integer.class, 100000), SBTREEBONSAI_LINKBAG_CACHE_EVICTION_SIZE( "sbtreebonsai.linkBagCache.evictionSize", "The number of cached LINKBAG collections, which will be removed, when the cache limit is reached", Integer.class, 1000), SBTREEBOSAI_FREE_SPACE_REUSE_TRIGGER( "sbtreebonsai.freeSpaceReuseTrigger", "How much free space should be in an sbtreebonsai file, before it will be reused during the next allocation", Float.class, 0.5), // RIDBAG RID_BAG_EMBEDDED_DEFAULT_SIZE( "ridBag.embeddedDefaultSize", "Size of embedded RidBag array, when created (empty)", Integer.class, 4), RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD( "ridBag.embeddedToSbtreeBonsaiThreshold", "Amount of values after which a LINKBAG implementation will use sbtree as values container. Set to -1 to always use an sbtree", Integer.class, 40, true), RID_BAG_SBTREEBONSAI_TO_EMBEDDED_THRESHOLD( "ridBag.sbtreeBonsaiToEmbeddedToThreshold", "Amount of values, after which a LINKBAG implementation will use an embedded values container (disabled by default)", Integer.class, -1, true), RID_BAG_SBTREEBONSAI_DELETE_DELAY( "ridBag.sbtreeBonsaiDeleteDelay", "How long should pass from last access before delete an already converted ridbag", Integer.class, 30000), // FILE @Deprecated TRACK_FILE_CLOSE( "file.trackFileClose", "Log all the cases when files are closed. This is needed only for internal debugging purposes", Boolean.class, false), FILE_LOCK("file.lock", "Locks files when used. Default is true", boolean.class, true), FILE_DELETE_DELAY( "file.deleteDelay", "Delay time (in ms) to wait for another attempt to delete a locked file", Integer.class, 10), FILE_DELETE_RETRY( "file.deleteRetry", "Number of retries to delete a locked file", Integer.class, 50), // SECURITY SECURITY_USER_PASSWORD_SALT_ITERATIONS( "security.userPasswordSaltIterations", "Number of iterations to generate the salt or user password. Changing this setting does not affect stored passwords", Integer.class, 65536), SECURITY_USER_PASSWORD_SALT_CACHE_SIZE( "security.userPasswordSaltCacheSize", "Cache size of hashed salt passwords. The cache works as LRU. Use 0 to disable the cache", Integer.class, 500), SECURITY_USER_PASSWORD_DEFAULT_ALGORITHM( "security.userPasswordDefaultAlgorithm", "Default encryption algorithm used for passwords hashing", String.class, "PBKDF2WithHmacSHA256"), // NETWORK NETWORK_MAX_CONCURRENT_SESSIONS( "network.maxConcurrentSessions", "Maximum number of concurrent sessions", Integer.class, 1000, true), NETWORK_SOCKET_BUFFER_SIZE( "network.socketBufferSize", "TCP/IP Socket buffer size, if 0 use the OS default", Integer.class, 0, true), NETWORK_LOCK_TIMEOUT( "network.lockTimeout", "Timeout (in ms) to acquire a lock against a channel", Integer.class, 15000, true), NETWORK_SOCKET_TIMEOUT( "network.socketTimeout", "TCP/IP Socket timeout (in ms)", Integer.class, 15000, true), NETWORK_REQUEST_TIMEOUT( "network.requestTimeout", "Request completion timeout (in ms)", Integer.class, 3600000 /* one hour */, true), NETWORK_SOCKET_RETRY_STRATEGY( "network.retry.strategy", "Select the retry server selection strategy, possible values are auto,same-dc ", String.class, "auto", true), NETWORK_SOCKET_RETRY( "network.retry", "Number of attempts to connect to the server on failure", Integer.class, 5, true), NETWORK_SOCKET_RETRY_DELAY( "network.retryDelay", "The time (in ms) the client must wait, before reconnecting to the server on failure", Integer.class, 500, true), NETWORK_BINARY_DNS_LOADBALANCING_ENABLED( "network.binary.loadBalancing.enabled", "Asks for DNS TXT record, to determine if load balancing is supported", Boolean.class, Boolean.FALSE, true), NETWORK_BINARY_DNS_LOADBALANCING_TIMEOUT( "network.binary.loadBalancing.timeout", "Maximum time (in ms) to wait for the answer from DNS about the TXT record for load balancing", Integer.class, 2000, true), NETWORK_BINARY_MAX_CONTENT_LENGTH( "network.binary.maxLength", "TCP/IP max content length (in KB) of BINARY requests", Integer.class, 16384, true), @Deprecated NETWORK_BINARY_READ_RESPONSE_MAX_TIMES( "network.binary.readResponse.maxTimes", "Maximum attempts, until a response can be read. Otherwise, the response will be dropped from the channel", Integer.class, 20, true), NETWORK_BINARY_MIN_PROTOCOL_VERSION( "network.binary.minProtocolVersion", "Set the minimum enabled binary protocol version and disable all backward compatible behaviour for version previous the one specified", Integer.class, 26, false), NETWORK_BINARY_DEBUG( "network.binary.debug", "Debug mode: print all data incoming on the binary channel", Boolean.class, false, true), NETWORK_BINARY_ALLOW_NO_TOKEN( "network.binary.allowNoToken", "Backward compatibility option to allow binary connections without tokens (STRONGLY DISCOURAGED, FOR SECURITY REASONS)", Boolean.class, Boolean.FALSE, true), // HTTP /** Since v2.2.8 */ NETWORK_HTTP_INSTALL_DEFAULT_COMMANDS( "network.http.installDefaultCommands", "Installs the default HTTP commands", Boolean.class, Boolean.TRUE, true), NETWORK_HTTP_SERVER_INFO( "network.http.serverInfo", "Server info to send in HTTP responses. Change the default if you want to hide it is a OrientDB Server", String.class, "OrientDB Server v." + OConstants.getVersion(), true), NETWORK_HTTP_MAX_CONTENT_LENGTH( "network.http.maxLength", "TCP/IP max content length (in bytes) for HTTP requests", Integer.class, 1000000, true), NETWORK_HTTP_STREAMING( "network.http.streaming", "Enable Http chunked streaming for json responses", Boolean.class, false, true), NETWORK_HTTP_CONTENT_CHARSET( "network.http.charset", "Http response charset", String.class, "utf-8", true), NETWORK_HTTP_JSON_RESPONSE_ERROR( "network.http.jsonResponseError", "Http response error in json", Boolean.class, true, true), NETWORK_HTTP_JSONP_ENABLED( "network.http.jsonp", "Enable the usage of JSONP, if requested by the client. The parameter name to use is 'callback'", Boolean.class, false, true), NETWORK_HTTP_SESSION_EXPIRE_TIMEOUT( "network.http.sessionExpireTimeout", "Timeout, after which an http session is considered to have expired (in seconds)", Integer.class, 900), NETWORK_HTTP_SESSION_COOKIE_SAME_SITE( "network.http.session.cookie.sameSite", "Activate the same site cookie session", Boolean.class, true), NETWORK_HTTP_USE_TOKEN( "network.http.useToken", "Enable Token based sessions for http", Boolean.class, false), NETWORK_TOKEN_SECRETKEY( "network.token.secretKey", "Network token sercret key", String.class, "", false, true), NETWORK_TOKEN_ENCRYPTION_ALGORITHM( "network.token.encryptionAlgorithm", "Network token algorithm", String.class, "HmacSHA256"), NETWORK_TOKEN_EXPIRE_TIMEOUT( "network.token.expireTimeout", "Timeout, after which a binary session is considered to have expired (in minutes)", Integer.class, 60), INIT_IN_SERVLET_CONTEXT_LISTENER( "orient.initInServletContextListener", "If this value set to ture (default) OrientDB engine " + "will be initialzed using embedded ServletContextListener", Boolean.class, true), // PROFILER PROFILER_ENABLED( "profiler.enabled", "Enables the recording of statistics and counters", Boolean.class, false, new OProfileEnabledChangeCallbac()), PROFILER_CONFIG( "profiler.config", "Configures the profiler as <seconds-for-snapshot>,<archive-snapshot-size>,<summary-size>", String.class, null, new OProfileConfigChangeCallback()), PROFILER_AUTODUMP_INTERVAL( "profiler.autoDump.interval", "Dumps the profiler values at regular intervals (in seconds)", Integer.class, 0, new OProfileDumpIntervalChangeCallback()), /** @Since 2.2.27 */ PROFILER_AUTODUMP_TYPE( "profiler.autoDump.type", "Type of profiler dump between 'full' or 'performance'", String.class, "full"), PROFILER_MAXVALUES( "profiler.maxValues", "Maximum values to store. Values are managed in a LRU", Integer.class, 200), PROFILER_MEMORYCHECK_INTERVAL( "profiler.memoryCheckInterval", "Checks the memory usage every configured milliseconds. Use 0 to disable it", Long.class, 120000), // SEQUENCES SEQUENCE_MAX_RETRY( "sequence.maxRetry", "Maximum number of retries between attempt to change a sequence in concurrent mode", Integer.class, 100), SEQUENCE_RETRY_DELAY( "sequence.retryDelay", "Maximum number of ms to wait between concurrent modification exceptions. The value is computed as random between 1 and this number", Integer.class, 200), /** Interval between snapshots of profiler state in milliseconds, default value is 100. */ STORAGE_PROFILER_SNAPSHOT_INTERVAL( "storageProfiler.intervalBetweenSnapshots", "Interval between snapshots of profiler state in milliseconds", Integer.class, 100), STORAGE_PROFILER_CLEANUP_INTERVAL( "storageProfiler.cleanUpInterval", "Interval between time series in milliseconds", Integer.class, 5000), // LOG LOG_CONSOLE_LEVEL( "log.console.level", "Console logging level", String.class, "info", new OConfigurationChangeCallback() { public void change(final Object iCurrentValue, final Object iNewValue) { OLogManager.instance().setLevel((String) iNewValue, ConsoleHandler.class); } }), LOG_FILE_LEVEL( "log.file.level", "File logging level", String.class, "info", new OConfigurationChangeCallback() { public void change(final Object iCurrentValue, final Object iNewValue) { OLogManager.instance().setLevel((String) iNewValue, FileHandler.class); } }), // CLASS CLASS_MINIMUM_CLUSTERS( "class.minimumClusters", "Minimum clusters to create when a new class is created. 0 means Automatic", Integer.class, 0), // LOG LOG_SUPPORTS_ANSI( "log.console.ansi", "ANSI Console support. 'auto' means automatic check if it is supported, 'true' to force using ANSI, 'false' to avoid using ANSI", String.class, "auto"), // CACHE CACHE_LOCAL_IMPL( "cache.local.impl", "Local Record cache implementation", String.class, ORecordCacheWeakRefs.class.getName()), // COMMAND COMMAND_TIMEOUT("command.timeout", "Default timeout for commands (in ms)", Long.class, 0, true), COMMAND_CACHE_ENABLED("command.cache.enabled", "Enable command cache", Boolean.class, false), COMMAND_CACHE_EVICT_STRATEGY( "command.cache.evictStrategy", "Command cache strategy between: [INVALIDATE_ALL,PER_CLUSTER]", String.class, "PER_CLUSTER"), COMMAND_CACHE_MIN_EXECUTION_TIME( "command.cache.minExecutionTime", "Minimum execution time to consider caching the result set", Integer.class, 10), COMMAND_CACHE_MAX_RESULSET_SIZE( "command.cache.maxResultsetSize", "Maximum resultset time to consider caching result set", Integer.class, 500), // QUERY QUERY_REMOTE_RESULTSET_PAGE_SIZE( "query.remoteResultSet.pageSize", "The size of a remote ResultSet page, ie. the number of records" + "that are fetched together during remote query execution. This has to be set on the client.", Integer.class, 1000), QUERY_REMOTE_SEND_EXECUTION_PLAN( "query.remoteResultSet.sendExecutionPlan", "Send the execution plan details or not. False by default", Boolean.class, false), QUERY_PARALLEL_AUTO( "query.parallelAuto", "Auto enable parallel query, if requirements are met", Boolean.class, false), QUERY_PARALLEL_MINIMUM_RECORDS( "query.parallelMinimumRecords", "Minimum number of records to activate parallel query automatically", Long.class, 300000), QUERY_PARALLEL_RESULT_QUEUE_SIZE( "query.parallelResultQueueSize", "Size of the queue that holds results on parallel execution. The queue is blocking, so in case the queue is full, the query threads will be in a wait state", Integer.class, 20000), QUERY_SCAN_PREFETCH_PAGES( "query.scanPrefetchPages", "Pages to prefetch during scan. Setting this value higher makes scans faster, because it reduces the number of I/O operations, though it consumes more memory. (Use 0 to disable)", Integer.class, 20), QUERY_SCAN_BATCH_SIZE( "query.scanBatchSize", "Scan clusters in blocks of records. This setting reduces the lock time on the cluster during scans." + " A high value mean a faster execution, but also a lower concurrency level. Set to 0 to disable batch scanning. Disabling batch scanning is suggested for read-only databases only", Long.class, 1000), QUERY_SCAN_THRESHOLD_TIP( "query.scanThresholdTip", "If the total number of records scanned in a query exceeds this setting, then a warning is given. (Use 0 to disable)", Long.class, 50000), QUERY_LIMIT_THRESHOLD_TIP( "query.limitThresholdTip", "If the total number of returned records exceeds this value, then a warning is given. (Use 0 to disable)", Long.class, 10000), QUERY_MAX_HEAP_ELEMENTS_ALLOWED_PER_OP( "query.maxHeapElementsAllowedPerOp", "Maximum number of elements (records) allowed in a single query for memory-intensive operations (eg. ORDER BY in heap). " + "If exceeded, the query fails with an OCommandExecutionException. Negative number means no limit." + "This setting is intended as a safety measure against excessive resource consumption from a single query (eg. prevent OutOfMemory)", Long.class, 500_000), QUERY_LIVE_SUPPORT( "query.live.support", "Enable/Disable the support of live query. (Use false to disable)", Boolean.class, true), STATEMENT_CACHE_SIZE( "statement.cacheSize", "Number of parsed SQL statements kept in cache. Zero means cache disabled", Integer.class, 100), // GRAPH SQL_GRAPH_CONSISTENCY_MODE( "sql.graphConsistencyMode", "Consistency mode for graphs. It can be 'tx' (default), 'notx_sync_repair' and 'notx_async_repair'. " + "'tx' uses transactions to maintain consistency. Instead both 'notx_sync_repair' and 'notx_async_repair' do not use transactions, " + "and the consistency, in case of JVM crash, is guaranteed by a database repair operation that run at startup. " + "With 'notx_sync_repair' the repair is synchronous, so the database comes online after the repair is ended, while " + "with 'notx_async_repair' the repair is a background process", String.class, "tx"), /** * Maximum size of pool of network channels between client and server. A channel is a TCP/IP * connection. */ CLIENT_CHANNEL_MAX_POOL( "client.channel.maxPool", "Maximum size of pool of network channels between client and server. A channel is a TCP/IP connection", Integer.class, 100), /** * Maximum time, where the client should wait for a connection from the pool, when all connections * busy. */ CLIENT_CONNECT_POOL_WAIT_TIMEOUT( "client.connectionPool.waitTimeout", "Maximum time, where the client should wait for a connection from the pool, when all connections busy", Integer.class, 5000, true), CLIENT_DB_RELEASE_WAIT_TIMEOUT( "client.channel.dbReleaseWaitTimeout", "Delay (in ms), after which a data modification command will be resent, if the DB was frozen", Integer.class, 10000, true), CLIENT_USE_SSL("client.ssl.enabled", "Use SSL for client connections", Boolean.class, false), CLIENT_SSL_KEYSTORE("client.ssl.keyStore", "Use SSL for client connections", String.class, null), CLIENT_SSL_KEYSTORE_PASSWORD( "client.ssl.keyStorePass", "Use SSL for client connections", String.class, null, false, true), CLIENT_SSL_TRUSTSTORE( "client.ssl.trustStore", "Use SSL for client connections", String.class, null), CLIENT_SSL_TRUSTSTORE_PASSWORD( "client.ssl.trustStorePass", "Use SSL for client connections", String.class, null, false, true), // SERVER SERVER_OPEN_ALL_DATABASES_AT_STARTUP( "server.openAllDatabasesAtStartup", "If true, the server opens all the available databases at startup. Available since 2.2", Boolean.class, false), SERVER_DATABASE_PATH( "server.database.path", "The path where are located the databases of a server", String.class, null), SERVER_CHANNEL_CLEAN_DELAY( "server.channel.cleanDelay", "Time in ms of delay to check pending closed connections", Integer.class, 5000), SERVER_CACHE_FILE_STATIC( "server.cache.staticFile", "Cache static resources upon loading", Boolean.class, false), SERVER_LOG_DUMP_CLIENT_EXCEPTION_LEVEL( "server.log.dumpClientExceptionLevel", "Logs client exceptions. Use any level supported by Java java.util.logging.Level class: OFF, FINE, CONFIG, INFO, WARNING, SEVERE", String.class, Level.FINE.getName()), SERVER_LOG_DUMP_CLIENT_EXCEPTION_FULLSTACKTRACE( "server.log.dumpClientExceptionFullStackTrace", "Dumps the full stack trace of the exception sent to the client", Boolean.class, Boolean.FALSE, true), SERVER_BACKWARD_COMPATIBILITY( "server.backwardCompatibility", "guarantee that the server use global context for search the database instance", Boolean.class, Boolean.FALSE, true, false), // DISTRIBUTED /** @Since 2.2.18 */ DISTRIBUTED_DUMP_STATS_EVERY( "distributed.dumpStatsEvery", "Time in ms to dump the cluster stats. Set to 0 to disable such dump", Long.class, 0l, true), DISTRIBUTED_CRUD_TASK_SYNCH_TIMEOUT( "distributed.crudTaskTimeout", "Maximum timeout (in ms) to wait for CRUD remote tasks", Long.class, 3000l, true), DISTRIBUTED_MAX_STARTUP_DELAY( "distributed.maxStartupDelay", "Maximum delay time (in ms) to wait for a server to start", Long.class, 10000l, true), DISTRIBUTED_COMMAND_TASK_SYNCH_TIMEOUT( "distributed.commandTaskTimeout", "Maximum timeout (in ms) to wait for command distributed tasks", Long.class, 2 * 60 * 1000l, true), DISTRIBUTED_COMMAND_QUICK_TASK_SYNCH_TIMEOUT( "distributed.commandQuickTaskTimeout", "Maximum timeout (in ms) to wait for quick command distributed tasks", Long.class, 5 * 1000l, true), DISTRIBUTED_COMMAND_LONG_TASK_SYNCH_TIMEOUT( "distributed.commandLongTaskTimeout", "Maximum timeout (in ms) to wait for Long-running distributed tasks", Long.class, 24 * 60 * 60 * 1000, true), DISTRIBUTED_DEPLOYDB_TASK_SYNCH_TIMEOUT( "distributed.deployDbTaskTimeout", "Maximum timeout (in ms) to wait for database deployment", Long.class, 1200000l, true), DISTRIBUTED_DEPLOYCHUNK_TASK_SYNCH_TIMEOUT( "distributed.deployChunkTaskTimeout", "Maximum timeout (in ms) to wait for database chunk deployment", Long.class, 60000l, true), DISTRIBUTED_DEPLOYDB_TASK_COMPRESSION( "distributed.deployDbTaskCompression", "Compression level (between 0 and 9) to use in backup for database deployment", Integer.class, 7, true), DISTRIBUTED_ASYNCH_QUEUE_SIZE( "distributed.asynchQueueSize", "Queue size to handle distributed asynchronous operations. The bigger is the queue, the more operation are buffered, but also more memory it's consumed. 0 = dynamic allocation, which means up to 2^31-1 entries", Integer.class, 0), DISTRIBUTED_ASYNCH_RESPONSES_TIMEOUT( "distributed.asynchResponsesTimeout", "Maximum timeout (in ms) to collect all the asynchronous responses from replication. After this time the operation is rolled back (through an UNDO)", Long.class, 15000l), DISTRIBUTED_PURGE_RESPONSES_TIMER_DELAY( "distributed.purgeResponsesTimerDelay", "Maximum timeout (in ms) to collect all the asynchronous responses from replication. This is the delay the purge thread uses to check asynchronous requests in timeout", Long.class, 15000l), /** @Since 2.2.7 */ DISTRIBUTED_CONFLICT_RESOLVER_REPAIRER_CHAIN( "distributed.conflictResolverRepairerChain", "Chain of conflict resolver implementation to use", String.class, "majority,content,version", false), /** @Since 2.2.7 */ DISTRIBUTED_CONFLICT_RESOLVER_REPAIRER_CHECK_EVERY( "distributed.conflictResolverRepairerCheckEvery", "Time (in ms) when the conflict resolver auto-repairer checks for records/cluster to repair", Long.class, 5000, true), /** @Since 2.2.7 */ DISTRIBUTED_CONFLICT_RESOLVER_REPAIRER_BATCH( "distributed.conflictResolverRepairerBatch", "Maximum number of records to repair in batch", Integer.class, 1000, true), /** @Since 2.2.7 */ DISTRIBUTED_TX_EXPIRE_TIMEOUT( "distributed.txAliveTimeout", "Maximum timeout (in ms) a distributed transaction can be alive. This timeout is to rollback pending transactions after a while", Long.class, 1800000l, true), /** @Since 2.2.6 */ DISTRIBUTED_REQUEST_CHANNELS( "distributed.requestChannels", "Number of network channels used to send requests", Integer.class, 1), /** @Since 2.2.6 */ DISTRIBUTED_RESPONSE_CHANNELS( "distributed.responseChannels", "Number of network channels used to send responses", Integer.class, 1), /** @Since 2.2.5 */ DISTRIBUTED_HEARTBEAT_TIMEOUT( "distributed.heartbeatTimeout", "Maximum time in ms to wait for the heartbeat. If the server does not respond in time, it is put offline", Long.class, 10000l), /** @Since 2.2.5 */ DISTRIBUTED_CHECK_HEALTH_CAN_OFFLINE_SERVER( "distributed.checkHealthCanOfflineServer", "In case a server does not respond to the heartbeat message, it is set offline", Boolean.class, false), /** @Since 2.2.5 */ DISTRIBUTED_CHECK_HEALTH_EVERY( "distributed.checkHealthEvery", "Time in ms to check the cluster health. Set to 0 to disable it", Long.class, 10000l), /** Since 2.2.4 */ DISTRIBUTED_AUTO_REMOVE_OFFLINE_SERVERS( "distributed.autoRemoveOfflineServers", "This is the amount of time (in ms) the server has to be OFFLINE, before it is automatically removed from the distributed configuration. -1 = never, 0 = immediately, >0 the actual time to wait", Long.class, 0, true), /** @Since 2.2.0 */ DISTRIBUTED_PUBLISH_NODE_STATUS_EVERY( "distributed.publishNodeStatusEvery", "Time in ms to publish the node status on distributed map. Set to 0 to disable such refresh of node configuration", Long.class, 10000l, true), /** @Since 2.2.0 */ DISTRIBUTED_REPLICATION_PROTOCOL_VERSION( "distributed.replicationProtocol.version", "1 for legacy replication model (v 3.0 and previous), 2 for coordinated replication (v 3.1 and next)", Integer.class, 1, true), /** @Since 2.2.0 */ @OApi(maturity = OApi.MATURITY.NEW) DISTRIBUTED_LOCAL_QUEUESIZE( "distributed.localQueueSize", "Size of the intra-thread queue for distributed messages", Integer.class, 10000), /** @Since 2.2.0 */ @OApi(maturity = OApi.MATURITY.NEW) DISTRIBUTED_DB_WORKERTHREADS( "distributed.dbWorkerThreads", "Number of parallel worker threads per database that process distributed messages. Use 0 for automatic", Integer.class, 0), /** @Since 2.1.3, Deprecated in 2.2.0 */ @Deprecated @OApi(maturity = OApi.MATURITY.NEW) DISTRIBUTED_QUEUE_MAXSIZE( "distributed.queueMaxSize", "Maximum queue size to mark a node as stalled. If the number of messages in queue are more than this values, the node is restarted with a remote command (0 = no maximum, which means up to 2^31-1 entries)", Integer.class, 10000), /** @Since 2.1.3 */ @OApi(maturity = OApi.MATURITY.NEW) DISTRIBUTED_BACKUP_DIRECTORY( "distributed.backupDirectory", "Directory where the copy of an existent database is saved, before it is downloaded from the cluster. Leave it empty to avoid the backup.", String.class, "../backup/databases"), /** @Since 2.2.15 */ @OApi(maturity = OApi.MATURITY.NEW) DISTRIBUTED_BACKUP_TRY_INCREMENTAL_FIRST( "distributed.backupTryIncrementalFirst", "Try to execute an incremental backup first.", Boolean.class, true), /** @Since 2.2.27 */ @OApi(maturity = OApi.MATURITY.NEW) DISTRIBUTED_CHECKINTEGRITY_LAST_TX( "distributed.checkIntegrityLastTxs", "Before asking for a delta sync, checks the integrity of the records touched by the last X transactions committed on local server.", Integer.class, 16), /** @Since 2.1 */ @OApi(maturity = OApi.MATURITY.NEW) DISTRIBUTED_CONCURRENT_TX_MAX_AUTORETRY( "distributed.concurrentTxMaxAutoRetry", "Maximum attempts the transaction coordinator should execute a transaction automatically, if records are locked. (Minimum is 1 = no attempts)", Integer.class, 15, true), /** @Since 2.2.7 */ @OApi(maturity = OApi.MATURITY.NEW) DISTRIBUTED_ATOMIC_LOCK_TIMEOUT( "distributed.atomicLockTimeout", "Timeout (in ms) to acquire a distributed lock on a record. (0=infinite)", Integer.class, 100, true), /** @Since 2.1 */ @OApi(maturity = OApi.MATURITY.NEW) DISTRIBUTED_CONCURRENT_TX_AUTORETRY_DELAY( "distributed.concurrentTxAutoRetryDelay", "Delay (in ms) between attempts on executing a distributed transaction, which had failed because of locked records. (0=no delay)", Integer.class, 1000, true), DISTRIBUTED_TRANSACTION_SEQUENCE_SET_SIZE( "distributed.transactionSequenceSetSize", "Size of the set of sequences used by distributed transactions, correspond to the amount of transactions commits that can be active at the same time", Integer.class, 1000, false), DB_DOCUMENT_SERIALIZER( "db.document.serializer", "The default record serializer used by the document database", String.class, ORecordSerializerBinary.NAME), /** @Since 2.2 */ @OApi(maturity = OApi.MATURITY.NEW) CLIENT_KRB5_CONFIG( "client.krb5.config", "Location of the Kerberos configuration file", String.class, null), /** @Since 2.2 */ @OApi(maturity = OApi.MATURITY.NEW) CLIENT_KRB5_CCNAME( "client.krb5.ccname", "Location of the Kerberos client ticketcache", String.class, null), /** @Since 2.2 */ @OApi(maturity = OApi.MATURITY.NEW) CLIENT_KRB5_KTNAME( "client.krb5.ktname", "Location of the Kerberos client keytab", String.class, null), @OApi(maturity = OApi.MATURITY.STABLE) CLIENT_CONNECTION_STRATEGY( "client.connection.strategy", "Strategy used for open connections from a client in case of multiple servers, possible options:STICKY, ROUND_ROBIN_CONNECT, ROUND_ROBIN_REQUEST", String.class, null), @OApi(maturity = OApi.MATURITY.NEW) CLIENT_CONNECTION_FETCH_HOST_LIST( "client.connection.fetchHostList", "If set true fetch the list of other possible hosts from the distributed environment ", Boolean.class, true), /** @Since 2.2 */ @OApi(maturity = OApi.MATURITY.NEW) CLIENT_CREDENTIAL_INTERCEPTOR( "client.credentialinterceptor", "The name of the CredentialInterceptor class", String.class, null), @OApi(maturity = OApi.MATURITY.NEW) CLIENT_CI_KEYALGORITHM( "client.ci.keyalgorithm", "The key algorithm used by the symmetric key credential interceptor", String.class, "AES"), @OApi(maturity = OApi.MATURITY.NEW) CLIENT_CI_CIPHERTRANSFORM( "client.ci.ciphertransform", "The cipher transformation used by the symmetric key credential interceptor", String.class, "AES/CBC/PKCS5Padding"), @OApi(maturity = OApi.MATURITY.NEW) CLIENT_CI_KEYSTORE_FILE( "client.ci.keystore.file", "The file path of the keystore used by the symmetric key credential interceptor", String.class, null), @OApi(maturity = OApi.MATURITY.NEW) CLIENT_CI_KEYSTORE_PASSWORD( "client.ci.keystore.password", "The password of the keystore used by the symmetric key credential interceptor", String.class, null, false, true), /** @Since 2.2 */ @OApi(maturity = OApi.MATURITY.NEW) CREATE_DEFAULT_USERS( "security.createDefaultUsers", "Indicates whether default database users should be created", Boolean.class, false), WARNING_DEFAULT_USERS( "security.warningDefaultUsers", "Indicates whether access with default users should show a warning", Boolean.class, true), /** @Since 2.2 */ @OApi(maturity = OApi.MATURITY.NEW) SERVER_SECURITY_FILE( "server.security.file", "Location of the OrientDB security.json configuration file", String.class, null), // CLOUD CLOUD_PROJECT_TOKEN( "cloud.project.token", "The token used to authenticate this project on the cloud platform", String.class, null), CLOUD_PROJECT_ID( "cloud.project.id", "The ID used to identify this project on the cloud platform", String.class, null), CLOUD_BASE_URL( "cloud.base.url", "The base URL of the cloud endpoint for requests", String.class, "cloud.orientdb.com"), SPATIAL_ENABLE_DIRECT_WKT_READER( "spatial.enableDirectWktReader", "Enable direct usage of WKTReader for additional dimention info", Boolean.class, false), /** Deprecated in v2.2.0 */ @Deprecated JNA_DISABLE_USE_SYSTEM_LIBRARY( "jna.disable.system.library", "This property disables using JNA, should it be installed on your system. (Default true) To use JNA bundled with database", boolean.class, true), @Deprecated DISTRIBUTED_QUEUE_TIMEOUT( "distributed.queueTimeout", "Maximum timeout (in ms) to wait for the response in replication", Long.class, 500000l, true), @Deprecated DB_MAKE_FULL_CHECKPOINT_ON_INDEX_CHANGE( "db.makeFullCheckpointOnIndexChange", "When index metadata is changed, a full checkpoint is performed", Boolean.class, true, true), @Deprecated DB_MAKE_FULL_CHECKPOINT_ON_SCHEMA_CHANGE( "db.makeFullCheckpointOnSchemaChange", "When index schema is changed, a full checkpoint is performed", Boolean.class, true, true), @Deprecated OAUTH2_SECRETKEY("oauth2.secretkey", "Http OAuth2 secret key", String.class, "", false, true), @Deprecated STORAGE_USE_CRC32_FOR_EACH_RECORD( "storage.cluster.usecrc32", "Indicates whether crc32 should be used for each record to check record integrity", Boolean.class, false), @Deprecated DB_USE_DISTRIBUTED_VERSION( "db.use.distributedVersion", "Deprecated, distributed version is not used anymore", Boolean.class, Boolean.FALSE), @Deprecated TX_COMMIT_SYNCH( "tx.commit.synch", "Synchronizes the storage after transaction commit", Boolean.class, false), @Deprecated TX_AUTO_RETRY( "tx.autoRetry", "Maximum number of automatic retry if some resource has been locked in the middle of the transaction (Timeout exception)", Integer.class, 1), @Deprecated TX_LOG_SYNCH( "tx.log.synch", "Executes a synch against the file-system at every log entry. This slows down transactions but guarantee transaction reliability on unreliable drives", Boolean.class, Boolean.FALSE), @Deprecated TX_USE_LOG( "tx.useLog", "Transactions use log file to store temporary data to be rolled back in case of crash", Boolean.class, true), @Deprecated INDEX_AUTO_REBUILD_AFTER_NOTSOFTCLOSE( "index.auto.rebuildAfterNotSoftClose", "Auto rebuild all automatic indexes after upon database open when wasn't closed properly", Boolean.class, true), @Deprecated CLIENT_CHANNEL_MIN_POOL("client.channel.minPool", "Minimum pool size", Integer.class, 1), AUTO_CLOSE_AFTER_DELAY( "storage.autoCloseAfterDelay", "Enable auto close of storage after a specified delay if no session are active", Boolean.class, false), AUTO_CLOSE_DELAY( "storage.autoCloseDelay", "Storage auto close delay time in minutes", Integer.class, 20), /** @Since 3.1 */ @OApi(maturity = OApi.MATURITY.NEW) DISTRIBUTED( "distributed", "Enable the clustering mode", Boolean.class, false, false, false, true), /** @Since 3.1 */ @OApi(maturity = OApi.MATURITY.NEW) DISTRIBUTED_NODE_NAME( "distributed.nodeName", "Name of the OrientDB node in the cluster", String.class, null, false, false, true), CLIENT_CHANNEL_IDLE_CLOSE( "client.channel.idleAutoClose", "Enable the automatic close of idle sockets after a specific timeout", Boolean.class, false), CLIENT_CHANNEL_IDLE_TIMEOUT( "client.channel.idleTimeout", "sockets maximum time idle in seconds", Integer.class, 900), DISTRIBUTED_AUTO_CREATE_CLUSTERS( "distributed.autoCreateClusters", "if true enable auto creation of cluster when a new node join", Boolean.class, true), ENTERPRISE_METRICS_MAX( "emterprise.metrics.max", "Top limit of number of metrics that the enterprise edition can keep in memory", Integer.class, 10000, false, false), ; static { readConfiguration(); } /** Place holder for the "undefined" value of setting. */ private final Object nullValue = new Object(); private final String key; private final Object defValue; private final Class<?> type; private final String description; private final OConfigurationChangeCallback changeCallback; private final Boolean canChangeAtRuntime; private final boolean hidden; private boolean env; private volatile Object value = nullValue; OGlobalConfiguration( final String iKey, final String iDescription, final Class<?> iType, final Object iDefValue, final OConfigurationChangeCallback iChangeAction) { key = iKey; description = iDescription; defValue = iDefValue; type = iType; canChangeAtRuntime = true; hidden = false; changeCallback = iChangeAction; } OGlobalConfiguration( final String iKey, final String iDescription, final Class<?> iType, final Object iDefValue) { this(iKey, iDescription, iType, iDefValue, false); } OGlobalConfiguration( final String iKey, final String iDescription, final Class<?> iType, final Object iDefValue, final Boolean iCanChange) { this(iKey, iDescription, iType, iDefValue, iCanChange, false); } OGlobalConfiguration( final String iKey, final String iDescription, final Class<?> iType, final Object iDefValue, final boolean iCanChange, final boolean iHidden) { this(iKey, iDescription, iType, iDefValue, iCanChange, iHidden, false); } OGlobalConfiguration( final String iKey, final String iDescription, final Class<?> iType, final Object iDefValue, final boolean iCanChange, final boolean iHidden, final boolean iEnv) { key = iKey; description = iDescription; defValue = iDefValue; type = iType; canChangeAtRuntime = iCanChange; hidden = iHidden; env = iEnv; changeCallback = null; } public static void dumpConfiguration(final PrintStream out) { out.print("OrientDB "); out.print(OConstants.getVersion()); out.println(" configuration dump:"); String lastSection = ""; for (OGlobalConfiguration value : values()) { final int index = value.key.indexOf('.'); String section = value.key; if (index >= 0) { section = value.key.substring(0, index); } if (!lastSection.equals(section)) { out.print("- "); out.println(section.toUpperCase(Locale.ENGLISH)); lastSection = section; } out.print(" + "); out.print(value.key); out.print(" = "); out.println(value.isHidden() ? "<hidden>" : String.valueOf((Object) value.getValue())); } } /** * Find the OGlobalConfiguration instance by the key. Key is case insensitive. * * @param iKey Key to find. It's case insensitive. * @return OGlobalConfiguration instance if found, otherwise null */ public static OGlobalConfiguration findByKey(final String iKey) { for (OGlobalConfiguration v : values()) { if (v.getKey().equalsIgnoreCase(iKey)) return v; } return null; } /** * Changes the configuration values in one shot by passing a Map of values. Keys can be the Java * ENUM names or the string representation of configuration values */ public static void setConfiguration(final Map<String, Object> iConfig) { for (Entry<String, Object> config : iConfig.entrySet()) { for (OGlobalConfiguration v : values()) { if (v.getKey().equals(config.getKey())) { v.setValue(config.getValue()); break; } else if (v.name().equals(config.getKey())) { v.setValue(config.getValue()); break; } } } } /** Assign configuration values by reading system properties. */ private static void readConfiguration() { String prop; for (OGlobalConfiguration config : values()) { prop = System.getProperty(config.key); if (prop != null) config.setValue(prop); } for (OGlobalConfiguration config : values()) { String key = getEnvKey(config); if (key != null) { prop = System.getenv(key); if (prop != null) { config.setValue(prop); } } } } public static String getEnvKey(OGlobalConfiguration config) { if (!config.env) return null; return "ORIENTDB_" + config.name(); } public <T> T getValue() { //noinspection unchecked return (T) (value != null && value != nullValue ? value : defValue); } /** * @return <code>true</code> if configuration was changed from default value and <code>false * </code> otherwise. */ public boolean isChanged() { return value != nullValue; } public void setValue(final Object iValue) { Object oldValue = value; if (iValue != null) if (type == Boolean.class) value = Boolean.parseBoolean(iValue.toString()); else if (type == Integer.class) value = Integer.parseInt(iValue.toString()); else if (type == Float.class) value = Float.parseFloat(iValue.toString()); else if (type == String.class) value = iValue.toString(); else if (type.isEnum()) { boolean accepted = false; if (type.isInstance(iValue)) { value = iValue; accepted = true; } else if (iValue instanceof String) { final String string = (String) iValue; for (Object constant : type.getEnumConstants()) { final Enum<?> enumConstant = (Enum<?>) constant; if (enumConstant.name().equalsIgnoreCase(string)) { value = enumConstant; accepted = true; break; } } } if (!accepted) throw new IllegalArgumentException("Invalid value of `" + key + "` option."); } else value = iValue; if (changeCallback != null) { try { changeCallback.change( oldValue == nullValue ? null : oldValue, value == nullValue ? null : value); } catch (Exception e) { OLogManager.instance().error(this, "Error during call of 'change callback'", e); } } } public boolean getValueAsBoolean() { final Object v = value != null && value != nullValue ? value : defValue; return v instanceof Boolean ? (Boolean) v : Boolean.parseBoolean(v.toString()); } public String getValueAsString() { return value != null && value != nullValue ? value.toString() : defValue != null ? defValue.toString() : null; } public int getValueAsInteger() { final Object v = value != null && value != nullValue ? value : defValue; return (int) (v instanceof Number ? ((Number) v).intValue() : OFileUtils.getSizeAsNumber(v.toString())); } public long getValueAsLong() { final Object v = value != null && value != nullValue ? value : defValue; return v instanceof Number ? ((Number) v).longValue() : OFileUtils.getSizeAsNumber(v.toString()); } public float getValueAsFloat() { final Object v = value != null && value != nullValue ? value : defValue; return v instanceof Float ? (Float) v : Float.parseFloat(v.toString()); } public String getKey() { return key; } public Boolean isChangeableAtRuntime() { return canChangeAtRuntime; } public boolean isHidden() { return hidden; } public Object getDefValue() { return defValue; } public Class<?> getType() { return type; } public String getDescription() { return description; } private static class OCacheSizeChangeCallback implements OConfigurationChangeCallback { @Override public void change(Object currentValue, Object newValue) { final Orient orient = Orient.instance(); if (orient != null) { final OEngineLocalPaginated engineLocalPaginated = (OEngineLocalPaginated) orient.getEngineIfRunning(OEngineLocalPaginated.NAME); if (engineLocalPaginated != null) engineLocalPaginated.changeCacheSize(((Integer) (newValue)) * 1024L * 1024L); } } } private static class OProfileEnabledChangeCallbac implements OConfigurationChangeCallback { public void change(final Object iCurrentValue, final Object iNewValue) { Orient instance = Orient.instance(); if (instance != null) { final OProfiler prof = instance.getProfiler(); if (prof != null) if ((Boolean) iNewValue) prof.startRecording(); else prof.stopRecording(); } } } private static class OProfileConfigChangeCallback implements OConfigurationChangeCallback { public void change(final Object iCurrentValue, final Object iNewValue) { Orient.instance().getProfiler().configure(iNewValue.toString()); } } private static class OProfileDumpIntervalChangeCallback implements OConfigurationChangeCallback { public void change(final Object iCurrentValue, final Object iNewValue) { Orient.instance().getProfiler().setAutoDump((Integer) iNewValue); } } }
set a lower threshold for enterprise metrics
core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java
set a lower threshold for enterprise metrics
<ide><path>ore/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java <ide> "emterprise.metrics.max", <ide> "Top limit of number of metrics that the enterprise edition can keep in memory", <ide> Integer.class, <del> 10000, <add> 2500, <ide> false, <ide> false), <ide> ;
JavaScript
mit
1d97976ec1072614358688e4b0b30968af4f40a1
0
hiulit/Phytoplankton,hiulit/Phytoplankton
Vue.component('menu-item', { props: ['menu'], template: '<li class="phytoplankton-menu__list__item">' + '<div class="phytoplankton-menu__list__item__header">' + '{{ menu.title }}' + '</div>' + '<ul class="phytoplankton-menu__list">' + '<li class="phytoplankton-menu__list__item" v-for="url in menu.url">' + '<a class="phytoplankton-menu__list__item__subheader" v-bind:data-url="url" @click="goToFile">{{ url }}</a>' + '</li>' + '</ul>' + '</li>', // data: { // }, methods: { goToFile: function(e) { if (page.url != e.target.dataset.url) { var submenu = document.querySelectorAll('[data-gumshoe]'); for (var i = 0, length = submenu.length; i < length; i++) { submenu[i].parentNode.removeChild(submenu[i]); } var menuArray = document.querySelectorAll('.js-phytoplankton-menu a'); for (var i = 0, length = menuArray.length; i < length; i++) { menuArray[i].classList.remove('is-active'); } e.target.classList.add('is-active'); page.url = e.target.dataset.url; page.loadFile(); } else { return; } } } }) // To add new items -> menu.menu.push({text: 'new item', url: 'new url'}) var menu = new Vue({ el: '.js-phytoplankton-menu', data: { items: config.menu } }) // var loader = new Vue({ // el: '.js-phytoplankton-page--loader', // data: { // message: 'Loading...', // seen: true // } // }); var page = new Vue({ el: '.js-phytoplankton-page', data: { url: '', docs: '', code: '', blocks: [], headings: [] }, beforeCreate: function () { console.log('beforeCreate'); }, created: function () { console.log('created'); $.ajax({ url: 'main.styl', async: false, cache: true, success: function(data){ allImports = findImports(data, 'http://localhost:8080/Phytoplankton/', 'styl'); } }); }, beforeMount: function () { console.log('beforeMount'); }, mounted: function () { console.log('mounted'); // // Set first menu link's state to "active". document.querySelectorAll('.js-phytoplankton-menu a')[0].classList.add('is-active'); // // Set page URL to first menu item. this.url = config.menu[0].url[0]; // // Load first file. this.loadFile(); }, // computed: { // computed: function () { // return console.log('computed'); // }, // compiledMarkdown: function () { // return this.docs // // return marked(this.docs, { // // sanitize: false, // // gfm: true, // // tables: true, // // langPrefix: 'language-' // // }) // } // }, beforeUpdate: function () { console.log('beforeUpdate'); }, updated: function () { // "onReady function" console.log('updated'); var pre = document.getElementsByTagName('pre'); for (var i = 0, length = pre.length; i < length; i++) { pre[i].classList.add('line-numbers'); } function createRepresentationFromHeadings(headings) { let i = 0; const tags = []; (function recurse(depth) { let unclosedLi = false; while (i < headings.length) { const [hashes, data] = headings[i].split("# "); if (hashes.length < depth) { break; } else if (hashes.length === depth) { if (unclosedLi) tags.push('</li>'); unclosedLi = true; tags.push('<li>', data); i++; } else { tags.push('<ul>'); recurse(depth+1); tags.push('</ul>'); } } if (unclosedLi) tags.push('</li>'); })(-1); return tags.join(''); } var hola = createRepresentationFromHeadings(page.headings); console.log(hola); $('[data-url="' + this.url + '"]').parent().append(hola); Prism.highlightAll(); Prism.fileHighlight(); fixie.init(); smoothScroll.init({ offset: 48 }); gumshoe.init({ offset: 49 }); }, // activated: function () { // console.log('activated'); // }, // deactivated: function () { // console.log('deactivated'); // }, // beforeDestroy: function () { // console.log('beforeDestroy'); // }, // destroyed: function () { // console.log('destroyed'); // }, methods: { loadFile: function() { // Resets this.blocks = []; // var cssArray = []; var styles = document.head.querySelectorAll('style'); if (styles.length) { for (var i = 0, lengthStyles = styles.length; i < lengthStyles; i++) { styles[i].parentNode.removeChild(styles[i]); } } var rq = new XMLHttpRequest(); rq.onreadystatechange = function(page) { if (this.readyState === XMLHttpRequest.DONE) { if (this.status === 200) { var blocks = separate(this.responseText); for (var i = 0, lengthBlocks = blocks.length; i < lengthBlocks; i++) { var tokens = marked.lexer(blocks[i].docs); var links = tokens.links || {}; var block = { docs: [], code: '' }; var match; var regex = /^(#{1,6}.*)/gm; while ((match = regex.exec(blocks[i].docs)) !== null) { page.headings.push(match[0]); } var cleanCode = removeComments(blocks[i].code); if (cleanCode !== '') { block.code = computeCss(cleanCode); } // var parsedCSS = gonzales.parse(block.code); // parsedCSS = parsedCSS.content; // for (var k = 0, lengthCss = parsedCSS.length; k < lengthCss; k++) { // if (parsedCSS[k].type === 'ruleset') { // var ruleset = parsedCSS[k].toString(); // cssArray.push('.code-render ' + ruleset); // } // } for (var j = 0, lengthTokens = tokens.length; j < lengthTokens; j++) { switch (tokens[j].type) { case 'code': if (!tokens[j].lang) { block.docs.push(tokens[j]); } else if (tokens[j].lang === 'markup') { block.docs.push({ type: 'html', lang: 'markup', text: '<ul class="phytoplankton-tabs">' + '<li class="phytoplankton-tabs__item is-active">HTML</li>' + '</ul>' + '<div class="code-render clearfix">' + tokens[j].text + '</div>' }); } break; default: block.docs.push(tokens[j]); break; } } block.docs.links = links; block.docs = marked.parser(block.docs); page.blocks.push(block); }; // if (cssArray.length) { // styles = document.createElement('style'); // for (var l = 0, lengthCssArray = cssArray.length; l < lengthCssArray; l++) { // styles.appendChild(document.createTextNode(cssArray[l])); // } // document.head.appendChild(styles); // } } else { return // loader.message = '**Request Failed!**\n\nEither the file the extension *(.css, .stylus, .styl, .less, .sass, .scss)* in `config.menu.url` is missing or the file just doesn\'t exist.'; // loader.message = marked(loader.message); } } }.bind(rq, this); rq.open("GET", this.url); rq.send(); } } })
scripts/main.js
Vue.component('menu-item', { props: ['menu'], template: '<li class="phytoplankton-menu__list__item">' + '<div class="phytoplankton-menu__list__item__header">' + '{{ menu.title }}' + '</div>' + '<ul class="phytoplankton-menu__list">' + '<li class="phytoplankton-menu__list__item" v-for="url in menu.url">' + '<a class="phytoplankton-menu__list__item__subheader" v-bind:data-url="url" @click="goToFile">{{ url }}</a>' + '</li>' + '</ul>' + '</li>', // data: { // }, methods: { goToFile: function(e) { if (page.url != e.target.dataset.url) { var submenu = document.querySelectorAll('[data-gumshoe]'); for (var i = 0, length = submenu.length; i < length; i++) { submenu[i].parentNode.removeChild(submenu[i]); } var menuArray = document.querySelectorAll('.js-phytoplankton-menu a'); for (var i = 0, length = menuArray.length; i < length; i++) { menuArray[i].classList.remove('is-active'); } e.target.classList.add('is-active'); page.url = e.target.dataset.url; page.loadFile(); } else { return; } } } }) // To add new items -> menu.menu.push({text: 'new item', url: 'new url'}) var menu = new Vue({ el: '.js-phytoplankton-menu', data: { items: config.menu } }) // var loader = new Vue({ // el: '.js-phytoplankton-page--loader', // data: { // message: 'Loading...', // seen: true // } // }); var page = new Vue({ el: '.js-phytoplankton-page', data: { url: '', docs: '', code: '', blocks: [] }, beforeCreate: function () { console.log('beforeCreate'); }, created: function () { console.log('created'); $.ajax({ url: 'main.styl', async: false, cache: true, success: function(data){ allImports = findImports(data, 'http://localhost:8080/Phytoplankton/', 'styl'); } }); }, beforeMount: function () { console.log('beforeMount'); }, mounted: function () { console.log('mounted'); // // Set first menu link's state to "active". document.querySelectorAll('.js-phytoplankton-menu a')[0].classList.add('is-active'); // // Set page URL to first menu item. this.url = config.menu[0].url[0]; // // Load first file. this.loadFile(); }, // computed: { // computed: function () { // return console.log('computed'); // }, // compiledMarkdown: function () { // return this.docs // // return marked(this.docs, { // // sanitize: false, // // gfm: true, // // tables: true, // // langPrefix: 'language-' // // }) // } // }, beforeUpdate: function () { console.log('beforeUpdate'); }, updated: function () { // "onReady function" console.log('updated'); var pre = document.getElementsByTagName('pre'); for (var i = 0, length = pre.length; i < length; i++) { pre[i].classList.add('line-numbers'); } // function createRepresentationFromHeadings(headings) { // let i = 0; // const tags = []; // (function recurse(depth) { // let unclosedLi = false; // while (i < headings.length) { // const [hashes, data] = headings[i].split("# "); // if (hashes.length < depth) { // break; // } else if (hashes.length === depth) { // if (unclosedLi) tags.push('</li>'); // unclosedLi = true; // tags.push('<li>', data); // i++; // } else { // tags.push('<ul>'); // recurse(depth+1); // tags.push('</ul>'); // } // } // if (unclosedLi) tags.push('</li>'); // })(-1); // return tags.join('\n'); // } // var headings = [ // "# Getting Started", // "# Heading 1", // "## SubHeading 1", // "## SubHeading 2", // "### SubSubHeading 1", // "### SubSubHeading 2", // "#### SubSubSubHeading 1", // "## SubHeading 3", // ]; // var hola = createRepresentationFromHeadings(headings); // console.log(hola); // var headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6'); // console.log(headings); // function createMenu() { // var i = 0; // var submenu = document.createElement('ul'); // submenu.setAttribute('data-gumshoe', ''); // (function recurse(depth) { // while(i < headings.length) { // var hash = headings[i]; // hash = hash.tagName.split('H'); // hash = Number(hash[1]); // var submenuItem = document.createElement('li'); // var submenuItemAnchor = document.createElement('a'); // submenuItem.appendChild(submenuItemAnchor); // submenuItemAnchor.setAttribute('href', '#' + headings[i].id); // submenuItemAnchor.setAttribute('data-scroll', ''); // submenuItemAnchor.appendChild(document.createTextNode(headings[i].textContent)); // if (hash > 1) { // if (hash !== depth) { // if (submenuList) { // console.log(submenuList); // var newSubmenuList = document.createElement('ul'); // newSubmenuList.appendChild(submenuItem); // submenuList.lastChild.appendChild(newSubmenuList); // } else { // var submenuList = document.createElement('ul'); // submenuList.appendChild(submenuItem); // submenu.lastChild.appendChild(submenuList); // depth = hash; // } // } else { // // console.log(submenuItem); // submenuList.lastChild.parentNode.appendChild(submenuItem); // } // } else { // depth = hash; // submenu.appendChild(submenuItem); // i++; // recurse(hash); // } // i++ // } // })(1); // return submenu; // } // var menuCreated = createMenu(headings); //Initialize the root UL var ul = $('<ul data-gumshoe>'); for(var i = 1; i < 8; i++){ var hs = $('h' + i); if(hs.length){ ul[0].childHeaders = hs ul[0].childHeaderLevel = i; break; } } var rootUl = ul; //main loop while(ul.length){ var nextUl = $(); //loop through each ul ul.each(function(){ var innerUl = this; var n = this.childHeaderLevel; //turn each childHeader into the corresponding ul innerUl.childHeaders.each(function(i,elem){ var childUl = $('<ul>').append('<li>' + $(elem).html() + '</li>') .appendTo(innerUl); childUl[0].childHeaders = $(this).nextUntil('h' + n) .filter('h' + (n+1)); childUl[0].childHeaderLevel = n + 1; nextUl = nextUl.add(childUl); }); }); ul = nextUl; } $('[data-url="' + this.url + '"]').parent().append(rootUl); Prism.highlightAll(); Prism.fileHighlight(); fixie.init(); smoothScroll.init({ offset: 48 }); gumshoe.init({ offset: 49 }); }, // activated: function () { // console.log('activated'); // }, // deactivated: function () { // console.log('deactivated'); // }, // beforeDestroy: function () { // console.log('beforeDestroy'); // }, // destroyed: function () { // console.log('destroyed'); // }, methods: { loadFile: function() { // Resets this.blocks = []; // var cssArray = []; var styles = document.head.querySelectorAll('style'); if (styles.length) { for (var i = 0, lengthStyles = styles.length; i < lengthStyles; i++) { styles[i].parentNode.removeChild(styles[i]); } } var rq = new XMLHttpRequest(); rq.onreadystatechange = function(page) { if (this.readyState === XMLHttpRequest.DONE) { if (this.status === 200) { var blocks = separate(this.responseText); for (var i = 0, lengthBlocks = blocks.length; i < lengthBlocks; i++) { var tokens = marked.lexer(blocks[i].docs); var links = tokens.links || {}; var block = { docs: [], code: '' }; var cleanCode = removeComments(blocks[i].code); if (cleanCode !== '') { block.code = computeCss(cleanCode); } // var parsedCSS = gonzales.parse(block.code); // parsedCSS = parsedCSS.content; // for (var k = 0, lengthCss = parsedCSS.length; k < lengthCss; k++) { // if (parsedCSS[k].type === 'ruleset') { // var ruleset = parsedCSS[k].toString(); // cssArray.push('.code-render ' + ruleset); // } // } for (var j = 0, lengthTokens = tokens.length; j < lengthTokens; j++) { switch (tokens[j].type) { case 'code': if (!tokens[j].lang) { block.docs.push(tokens[j]); } else if (tokens[j].lang === 'markup') { block.docs.push({ type: 'html', lang: 'markup', text: '<ul class="phytoplankton-tabs">' + '<li class="phytoplankton-tabs__item is-active">HTML</li>' + '</ul>' + '<div class="code-render clearfix">' + tokens[j].text + '</div>' }); } break; default: block.docs.push(tokens[j]); break; } } block.docs.links = links; block.docs = marked.parser(block.docs); page.blocks.push(block); }; // if (cssArray.length) { // styles = document.createElement('style'); // for (var l = 0, lengthCssArray = cssArray.length; l < lengthCssArray; l++) { // styles.appendChild(document.createTextNode(cssArray[l])); // } // document.head.appendChild(styles); // } } else { return // loader.message = '**Request Failed!**\n\nEither the file the extension *(.css, .stylus, .styl, .less, .sass, .scss)* in `config.menu.url` is missing or the file just doesn\'t exist.'; // loader.message = marked(loader.message); } } }.bind(rq, this); rq.open("GET", this.url); rq.send(); } } })
Finishing menu
scripts/main.js
Finishing menu
<ide><path>cripts/main.js <ide> url: '', <ide> docs: '', <ide> code: '', <del> blocks: [] <add> blocks: [], <add> headings: [] <ide> }, <ide> beforeCreate: function () { <ide> console.log('beforeCreate'); <ide> pre[i].classList.add('line-numbers'); <ide> } <ide> <del> // function createRepresentationFromHeadings(headings) { <del> // let i = 0; <del> // const tags = []; <del> <del> // (function recurse(depth) { <del> // let unclosedLi = false; <del> // while (i < headings.length) { <del> // const [hashes, data] = headings[i].split("# "); <del> // if (hashes.length < depth) { <del> // break; <del> // } else if (hashes.length === depth) { <del> // if (unclosedLi) tags.push('</li>'); <del> // unclosedLi = true; <del> // tags.push('<li>', data); <del> // i++; <del> // } else { <del> // tags.push('<ul>'); <del> // recurse(depth+1); <del> // tags.push('</ul>'); <del> // } <del> // } <del> // if (unclosedLi) tags.push('</li>'); <del> // })(-1); <del> // return tags.join('\n'); <del> // } <del> <del> // var headings = [ <del> // "# Getting Started", <del> // "# Heading 1", <del> // "## SubHeading 1", <del> // "## SubHeading 2", <del> // "### SubSubHeading 1", <del> // "### SubSubHeading 2", <del> // "#### SubSubSubHeading 1", <del> // "## SubHeading 3", <del> // ]; <del> <del> // var hola = createRepresentationFromHeadings(headings); <del> // console.log(hola); <del> <del> // var headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6'); <del> // console.log(headings); <del> // function createMenu() { <del> // var i = 0; <del> // var submenu = document.createElement('ul'); <del> // submenu.setAttribute('data-gumshoe', ''); <del> // (function recurse(depth) { <del> // while(i < headings.length) { <del> // var hash = headings[i]; <del> // hash = hash.tagName.split('H'); <del> // hash = Number(hash[1]); <del> // var submenuItem = document.createElement('li'); <del> // var submenuItemAnchor = document.createElement('a'); <del> // submenuItem.appendChild(submenuItemAnchor); <del> // submenuItemAnchor.setAttribute('href', '#' + headings[i].id); <del> // submenuItemAnchor.setAttribute('data-scroll', ''); <del> // submenuItemAnchor.appendChild(document.createTextNode(headings[i].textContent)); <del> // if (hash > 1) { <del> // if (hash !== depth) { <del> // if (submenuList) { <del> // console.log(submenuList); <del> // var newSubmenuList = document.createElement('ul'); <del> // newSubmenuList.appendChild(submenuItem); <del> // submenuList.lastChild.appendChild(newSubmenuList); <del> // } else { <del> // var submenuList = document.createElement('ul'); <del> // submenuList.appendChild(submenuItem); <del> // submenu.lastChild.appendChild(submenuList); <del> // depth = hash; <del> // } <del> // } else { <del> // // console.log(submenuItem); <del> // submenuList.lastChild.parentNode.appendChild(submenuItem); <del> // } <del> // } else { <del> // depth = hash; <del> // submenu.appendChild(submenuItem); <del> // i++; <del> // recurse(hash); <del> // } <del> // i++ <del> // } <del> // })(1); <del> // return submenu; <del> // } <del> // var menuCreated = createMenu(headings); <del> <del> //Initialize the root UL <del> var ul = $('<ul data-gumshoe>'); <del> for(var i = 1; i < 8; i++){ <del> var hs = $('h' + i); <del> if(hs.length){ <del> ul[0].childHeaders = hs <del> ul[0].childHeaderLevel = i; <del> break; <del> } <del> } <del> <del> var rootUl = ul; <del> //main loop <del> while(ul.length){ <del> var nextUl = $(); <del> //loop through each ul <del> ul.each(function(){ <del> var innerUl = this; <del> var n = this.childHeaderLevel; <del> //turn each childHeader into the corresponding ul <del> innerUl.childHeaders.each(function(i,elem){ <del> var childUl = $('<ul>').append('<li>' + $(elem).html() + '</li>') <del> .appendTo(innerUl); <del> childUl[0].childHeaders = $(this).nextUntil('h' + n) <del> .filter('h' + (n+1)); <del> childUl[0].childHeaderLevel = n + 1; <del> nextUl = nextUl.add(childUl); <del> }); <del> }); <del> ul = nextUl; <del> } <del> <del> $('[data-url="' + this.url + '"]').parent().append(rootUl); <add> function createRepresentationFromHeadings(headings) { <add> let i = 0; <add> const tags = []; <add> <add> (function recurse(depth) { <add> let unclosedLi = false; <add> while (i < headings.length) { <add> const [hashes, data] = headings[i].split("# "); <add> if (hashes.length < depth) { <add> break; <add> } else if (hashes.length === depth) { <add> if (unclosedLi) tags.push('</li>'); <add> unclosedLi = true; <add> tags.push('<li>', data); <add> i++; <add> } else { <add> tags.push('<ul>'); <add> recurse(depth+1); <add> tags.push('</ul>'); <add> } <add> } <add> if (unclosedLi) tags.push('</li>'); <add> })(-1); <add> return tags.join(''); <add> } <add> <add> var hola = createRepresentationFromHeadings(page.headings); <add> console.log(hola); <add> <add> $('[data-url="' + this.url + '"]').parent().append(hola); <ide> <ide> Prism.highlightAll(); <ide> Prism.fileHighlight(); <ide> docs: [], <ide> code: '' <ide> }; <add> <add> var match; <add> var regex = /^(#{1,6}.*)/gm; <add> while ((match = regex.exec(blocks[i].docs)) !== null) { <add> page.headings.push(match[0]); <add> } <ide> <ide> var cleanCode = removeComments(blocks[i].code); <ide> if (cleanCode !== '') {
Java
mit
cf4ec6c272ddc3fb49436d7c95d64cb9863b82a7
0
project-recoin/PybossaTwitterController,project-recoin/PybossaTwitterController
package sociam.pybossa; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.LinkedHashSet; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.bson.Document; import org.bson.types.ObjectId; import org.json.JSONArray; import org.json.JSONObject; import sociam.pybossa.config.Config; import com.mongodb.Block; import com.mongodb.MongoClient; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoDatabase; import com.mongodb.client.result.UpdateResult; public class TaskCreator { final static Logger logger = Logger.getLogger(TaskCreator.class); final static SimpleDateFormat MongoDBformatter = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); final static SimpleDateFormat PyBossaformatter = new SimpleDateFormat( "yyyy-mm-dd'T'hh:mm:ss.SSSSSS"); static MongoClient mongoClient = new MongoClient(Config.mongoHost, Config.mongoPort); static MongoDatabase database = mongoClient .getDatabase(Config.projectsDatabaseName); static MongoDatabase binsDatabase = mongoClient .getDatabase(Config.binsDatabaseName); static String url = Config.PyBossahost + Config.taskDir + Config.api_key; public static void main(String[] args) { PropertyConfigurator.configure("log4j.properties"); logger.info("TaskCreator will be repeated every " + Config.TaskCreatorTrigger + " ms"); try { while (true) { run(); logger.info("Sleeping for " + Config.TaskCreatorTrigger + " ms"); Thread.sleep(Integer.valueOf(Config.TaskCreatorTrigger)); } } catch (InterruptedException e) { logger.error("Error " , e); } } public static void run() { try { // Check for started projects HashSet<JSONObject> projectsAsJsons = getReadyProjects(); if (projectsAsJsons != null) { logger.info("There are " + projectsAsJsons.size() + " projects that have tasks ready to be inserted into PyBossa, then to MongoDB"); if (!projectsAsJsons.isEmpty()) { // Get project name and id for these started projects for (JSONObject jsonObject : projectsAsJsons) { JSONArray bin_id = jsonObject.getJSONArray("bin_ids"); int project_id = jsonObject.getInt("project_id"); int tasksPerProjectlimit = Integer .valueOf(Config.TasksPerProject); ArrayList<String> tasksTexts = getAllTasksTextsFromPyBossa(project_id); if (tasksTexts.size() > tasksPerProjectlimit) { if (updateProjectToInsertedInMongoDB(project_id)) { logger.debug("Project with id " + project_id + " has already got " + tasksPerProjectlimit + " tasks"); break; } } int tasksPerProjectCounter = 0; if (tasksPerProjectCounter > tasksPerProjectlimit) { logger.info("tasksPerProjectlimit was reached " + tasksPerProjectCounter); if (updateProjectToInsertedInMongoDB(project_id)) { logger.debug("changing to another project"); break; } } // TODO: don't retrieve ones which have already been // pushed // to // crowd and not completed by crowd, from Ramine for (Object object : bin_id) { String binItem = (String) object; // for each started project, get their bins HashSet<Document> tweets = getTweetsFromBinInMongoDB(binItem); HashSet<String> originalBinText = new HashSet<>(); logger.info("There are \"" + tweets.size() + "\" tweets for projectID " + project_id); for (Document tweet : tweets) { // for each bin, get the text/tweet String text = tweet.getString("text"); if (!originalBinText.contains(text)) { originalBinText.add(text); String text_encoded = tweet .getString("text_encoded"); ObjectId _id = tweet.getObjectId("_id"); if (tasksTexts != null) { if (!tasksTexts.contains(text_encoded)) { // Build the PyBossa json for // insertion // of a // task JSONObject PyBossaTaskJsonToBeInserted = BuildJsonTaskContent( text, "30", "0", "0", project_id, "0.0"); if (PyBossaTaskJsonToBeInserted != null) { // Insert the PyBossa json into // PyBossa JSONObject pybossaResponse = inserTaskIntoPyBossa( url, PyBossaTaskJsonToBeInserted); if (pybossaResponse != null) { JSONObject info = pybossaResponse .getJSONObject("info"); String task_text = info .getString("text"); tasksTexts.add(task_text); // Insert the resonse of // PyBossa // into // MongoDB if (insertTaskIntoMongoDB( pybossaResponse, false)) { logger.debug("task with pybossaResponse " + pybossaResponse .toString()); if (updateBinString( _id, task_text, binItem)) { logger.debug("Bin with _id " + _id + " was updated"); tasksPerProjectCounter++; } else { logger.error("Bin with _id " + _id + " was not updated "); } } else { logger.error("Task was not inserted Into MongoDB"); } } else { logger.error("pybossaResponse was null"); } } else { logger.error("PyBossaTaskJsonToBeInserted was null"); } } else { logger.error("task " + text + " in Project " + project_id + " is already in PyBossa!!"); } } } else { logger.error("Tweet is already processed " + tweet.toString()); } } } } } else { logger.debug("There are no ready projects' tasks to be inserted into PyBossa!"); } } } catch (Exception e) { logger.error("Erro " + e); } } private static Boolean updateProjectToInsertedInMongoDB(int project_id) { try { UpdateResult result = database.getCollection( Config.projectCollection).updateOne( new Document("project_id", project_id), new Document().append("$set", new Document( "project_status", "inserted"))); logger.debug(result.toString()); if (result.wasAcknowledged()) { if (result.getMatchedCount() > 0) { logger.debug(Config.projectCollection + " Collection was updated with project_status: inserted"); return true; } } return false; } catch (Exception e) { logger.error("Error " , e); return false; } } // For encoding issue that makes the text changed after inserting it into // PyBossa private static Boolean updateBinString(ObjectId _id, String text_encoded, String binItem) { try { UpdateResult result = binsDatabase.getCollection(binItem) .updateOne( new Document("_id", _id), new Document().append("$set", new Document( "text_encoded", text_encoded))); logger.debug(result.toString()); if (result.wasAcknowledged()) { if (result.getMatchedCount() > 0) { return true; } } return false; } catch (Exception e) { logger.error("Error " , e); return false; } } static HashSet<Document> tweetsjsons = new LinkedHashSet<Document>(); private static HashSet<Document> getTweetsFromBinInMongoDB( String collectionName) { tweetsjsons = new LinkedHashSet<Document>(); try { FindIterable<Document> iterable = binsDatabase.getCollection( collectionName).find().limit(200); if (iterable.first() != null) { iterable.forEach(new Block<Document>() { @Override public void apply(final Document document) { tweetsjsons.add(document); } }); return tweetsjsons; } return tweetsjsons; } catch (Exception e) { logger.error("Error " , e); return tweetsjsons; } } static HashSet<JSONObject> startedProjectsJsons = new LinkedHashSet<JSONObject>(); private static HashSet<JSONObject> getReadyProjects() { startedProjectsJsons = new LinkedHashSet<JSONObject>(); try { FindIterable<Document> iterable = database.getCollection( Config.projectCollection).find( new Document("project_status", "ready")); if (iterable.first() != null) { iterable.forEach(new Block<Document>() { @Override public void apply(final Document document) { JSONObject app2 = new JSONObject(document); startedProjectsJsons.add(app2); } }); return startedProjectsJsons; } return startedProjectsJsons; } catch (Exception e) { logger.error("Error " , e); return null; } } private static JSONObject inserTaskIntoPyBossa(String url, JSONObject jsonData) { JSONObject jsonResult = null; HttpClient httpClient = HttpClientBuilder.create().build(); try { HttpPost request = new HttpPost(url); StringEntity params = new StringEntity(jsonData.toString()); params.setContentType("application/json"); request.addHeader("content-type", "application/json"); request.addHeader("Accept", "*/*"); request.addHeader("Accept-Encoding", "gzip,deflate,sdch"); request.addHeader("Accept-Language", "en-US,en;q=0.8"); request.setEntity(params); HttpResponse response = httpClient.execute(request); if (response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 204) { BufferedReader br = new BufferedReader(new InputStreamReader( (response.getEntity().getContent()))); String output; logger.debug("Output from Server ...." + response.getStatusLine().getStatusCode() + "\n"); while ((output = br.readLine()) != null) { logger.debug(output); jsonResult = new JSONObject(output); } return jsonResult; } else { logger.error("PyBossa response failed : HTTP error code : " + response.getStatusLine().getStatusCode()); return null; } } catch (Exception ex) { logger.error(ex); return null; } } /** * It returns a json string for task creation from a given task details * * @param text * the task content * @param n_answers * @param quorum * @param calibration * @param project_id * The project ID * @param priority_0 * @return Json string */ private static JSONObject BuildJsonTaskContent(String text, String n_answers, String quorum, String calibration, int project_id, String priority_0) { try { JSONObject app = new JSONObject(); app.put("text", text); JSONObject app2 = new JSONObject(); app2.put("info", app); app2.put("n_answers", n_answers); app2.put("quorum", quorum); app2.put("calibration", calibration); app2.put("project_id", project_id); app2.put("priority_0", priority_0); return app2; } catch (Exception e) { logger.error("Error " , e); return null; } } private static Boolean insertTaskIntoMongoDB(JSONObject response, Boolean isPushedToTwitter) { try { Integer pybossa_task_id = response.getInt("id"); // String created_String = response.getString("created"); // Date publishedAt = PyBossaformatter.parse(created_String); Date date = new Date(); String publishedAt = MongoDBformatter.format(date); // String targettedFormat = MongoDBformatter.format(publishedAt); Integer project_id = response.getInt("project_id"); JSONObject info = response.getJSONObject("info"); String task_text = info.getString("text"); logger.debug("Inserting a task into MongoDB"); if (pushTaskToMongoDB(pybossa_task_id, publishedAt, project_id, isPushedToTwitter, task_text)) { return true; } else { return false; } } catch (Exception e) { logger.error("Error " , e); return false; } } private static boolean pushTaskToMongoDB(Integer pybossa_task_id, String publishedAt, Integer project_id, Boolean isPushedToTwitter, String task_text) { try { if (publishedAt != null && project_id != null && isPushedToTwitter != null && task_text != null) { FindIterable<Document> iterable = database.getCollection( Config.taskCollection).find( new Document("project_id", project_id).append( "task_text", task_text)); if (iterable.first() == null) { database.getCollection(Config.taskCollection).insertOne( new Document() .append("pybossa_task_id", pybossa_task_id) .append("publishedAt", publishedAt) .append("project_id", project_id) .append("isPushed", isPushedToTwitter) .append("task_text", task_text)); logger.debug("One task is inserted into MongoDB"); } else { logger.error("task is already in the collection!!"); } } return true; } catch (Exception e) { logger.error("Error with inserting the task " + "pybossa_task_id " + pybossa_task_id + "publishedAt " + publishedAt + "project_id " + project_id + "isPushed " + isPushedToTwitter + "task_text " + task_text + "\n" + e); return false; } } private static ArrayList<String> getAllTasksTextsFromPyBossa(int project_id) { String url = Config.PyBossahost + Config.taskDir + "?project_id=" + project_id; ArrayList<String> texts = new ArrayList<>(); HttpURLConnection con; try { URL obj = new URL(url); con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); // int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader( con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // print result JSONArray jsonData = new JSONArray(response.toString()); for (Object object : jsonData) { JSONObject json = new JSONObject(object.toString()); JSONObject info = json.getJSONObject("info"); String text = info.getString("text"); texts.add(text); } return texts; } catch (IOException e) { logger.error("Error " , e); return null; } } }
src/main/java/sociam/pybossa/TaskCreator.java
package sociam.pybossa; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.LinkedHashSet; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.bson.Document; import org.bson.types.ObjectId; import org.json.JSONArray; import org.json.JSONObject; import sociam.pybossa.config.Config; import com.mongodb.Block; import com.mongodb.MongoClient; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoDatabase; import com.mongodb.client.result.UpdateResult; public class TaskCreator { final static Logger logger = Logger.getLogger(TaskCreator.class); final static SimpleDateFormat MongoDBformatter = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); final static SimpleDateFormat PyBossaformatter = new SimpleDateFormat( "yyyy-mm-dd'T'hh:mm:ss.SSSSSS"); static MongoClient mongoClient = new MongoClient(Config.mongoHost, Config.mongoPort); static MongoDatabase database = mongoClient .getDatabase(Config.projectsDatabaseName); static MongoDatabase binsDatabase = mongoClient .getDatabase(Config.binsDatabaseName); static String url = Config.PyBossahost + Config.taskDir + Config.api_key; public static void main(String[] args) { PropertyConfigurator.configure("log4j.properties"); logger.info("TaskCreator will be repeated every " + Config.TaskCreatorTrigger + " ms"); try { while (true) { run(); logger.info("Sleeping for " + Config.TaskCreatorTrigger + " ms"); Thread.sleep(Integer.valueOf(Config.TaskCreatorTrigger)); } } catch (InterruptedException e) { logger.error("Error " , e); } } public static void run() { try { // Check for started projects HashSet<JSONObject> projectsAsJsons = getReadyProjects(); if (projectsAsJsons != null) { logger.info("There are " + projectsAsJsons.size() + " projects that have tasks ready to be inserted into PyBossa, then to MongoDB"); if (!projectsAsJsons.isEmpty()) { // Get project name and id for these started projects for (JSONObject jsonObject : projectsAsJsons) { JSONArray bin_id = jsonObject.getJSONArray("bin_ids"); int project_id = jsonObject.getInt("project_id"); int tasksPerProjectlimit = Integer .valueOf(Config.TasksPerProject); ArrayList<String> tasksTexts = getAllTasksTextsFromPyBossa(project_id); if (tasksTexts.size() > tasksPerProjectlimit) { if (updateProjectToInsertedInMongoDB(project_id)) { logger.debug("Project with id " + project_id + " has already got " + tasksPerProjectlimit + " tasks"); break; } } int tasksPerProjectCounter = 0; if (tasksPerProjectCounter > tasksPerProjectlimit) { logger.info("tasksPerProjectlimit was reached " + tasksPerProjectCounter); if (updateProjectToInsertedInMongoDB(project_id)) { logger.debug("changing to another project"); break; } } // TODO: don't retrieve ones which have already been // pushed // to // crowd and not completed by crowd, from Ramine for (Object object : bin_id) { String binItem = (String) object; // for each started project, get their bins HashSet<Document> tweets = getTweetsFromBinInMongoDB(binItem); HashSet<String> originalBinText = new HashSet<>(); logger.info("There are \"" + tweets.size() + "\" tweets for projectID " + project_id); for (Document tweet : tweets) { // for each bin, get the text/tweet String text = tweet.getString("text"); if (!originalBinText.contains(text)) { originalBinText.add(text); String text_encoded = tweet .getString("text_encoded"); ObjectId _id = tweet.getObjectId("_id"); if (tasksTexts != null) { if (!tasksTexts.contains(text_encoded)) { // Build the PyBossa json for // insertion // of a // task JSONObject PyBossaTaskJsonToBeInserted = BuildJsonTaskContent( text, "30", "0", "0", project_id, "0.0"); if (PyBossaTaskJsonToBeInserted != null) { // Insert the PyBossa json into // PyBossa JSONObject pybossaResponse = inserTaskIntoPyBossa( url, PyBossaTaskJsonToBeInserted); if (pybossaResponse != null) { JSONObject info = pybossaResponse .getJSONObject("info"); String task_text = info .getString("text"); tasksTexts.add(task_text); // Insert the resonse of // PyBossa // into // MongoDB if (insertTaskIntoMongoDB( pybossaResponse, false)) { logger.debug("task with pybossaResponse " + pybossaResponse .toString()); if (updateBinString( _id, task_text, binItem)) { logger.debug("Bin with _id " + _id + " was updated"); tasksPerProjectCounter++; } else { logger.error("Bin with _id " + _id + " was not updated "); } } else { logger.error("Task was not inserted Into MongoDB"); } } else { logger.error("pybossaResponse was null"); } } else { logger.error("PyBossaTaskJsonToBeInserted was null"); } } else { logger.error("task " + text + " in Project " + project_id + " is already in PyBossa!!"); } } } else { logger.error("Tweet is already processed " + tweet.toString()); } } } } } else { logger.debug("There are no ready projects' tasks to be inserted into PyBossa!"); } } } catch (Exception e) { logger.error("Erro " + e); } } private static Boolean updateProjectToInsertedInMongoDB(int project_id) { try { UpdateResult result = database.getCollection( Config.projectCollection).updateOne( new Document("project_id", project_id), new Document().append("$set", new Document( "project_status", "inserted"))); logger.debug(result.toString()); if (result.wasAcknowledged()) { if (result.getMatchedCount() > 0) { logger.debug(Config.projectCollection + " Collection was updated with project_status: inserted"); return true; } } return false; } catch (Exception e) { logger.error("Error " , e); return false; } } // For encoding issue that makes the text changed after inserting it into // PyBossa private static Boolean updateBinString(ObjectId _id, String text_encoded, String binItem) { try { UpdateResult result = binsDatabase.getCollection(binItem) .updateOne( new Document("_id", _id), new Document().append("$set", new Document( "text_encoded", text_encoded))); logger.debug(result.toString()); if (result.wasAcknowledged()) { if (result.getMatchedCount() > 0) { return true; } } return false; } catch (Exception e) { logger.error("Error " , e); return false; } } static HashSet<Document> tweetsjsons = new LinkedHashSet<Document>(); private static HashSet<Document> getTweetsFromBinInMongoDB( String collectionName) { tweetsjsons = new LinkedHashSet<Document>(); try { FindIterable<Document> iterable = binsDatabase.getCollection( collectionName).find(); if (iterable.first() != null) { iterable.forEach(new Block<Document>() { @Override public void apply(final Document document) { tweetsjsons.add(document); } }); return tweetsjsons; } return tweetsjsons; } catch (Exception e) { logger.error("Error " , e); return tweetsjsons; } } static HashSet<JSONObject> startedProjectsJsons = new LinkedHashSet<JSONObject>(); private static HashSet<JSONObject> getReadyProjects() { startedProjectsJsons = new LinkedHashSet<JSONObject>(); try { FindIterable<Document> iterable = database.getCollection( Config.projectCollection).find( new Document("project_status", "ready")); if (iterable.first() != null) { iterable.forEach(new Block<Document>() { @Override public void apply(final Document document) { JSONObject app2 = new JSONObject(document); startedProjectsJsons.add(app2); } }); return startedProjectsJsons; } return startedProjectsJsons; } catch (Exception e) { logger.error("Error " , e); return null; } } private static JSONObject inserTaskIntoPyBossa(String url, JSONObject jsonData) { JSONObject jsonResult = null; HttpClient httpClient = HttpClientBuilder.create().build(); try { HttpPost request = new HttpPost(url); StringEntity params = new StringEntity(jsonData.toString()); params.setContentType("application/json"); request.addHeader("content-type", "application/json"); request.addHeader("Accept", "*/*"); request.addHeader("Accept-Encoding", "gzip,deflate,sdch"); request.addHeader("Accept-Language", "en-US,en;q=0.8"); request.setEntity(params); HttpResponse response = httpClient.execute(request); if (response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 204) { BufferedReader br = new BufferedReader(new InputStreamReader( (response.getEntity().getContent()))); String output; logger.debug("Output from Server ...." + response.getStatusLine().getStatusCode() + "\n"); while ((output = br.readLine()) != null) { logger.debug(output); jsonResult = new JSONObject(output); } return jsonResult; } else { logger.error("PyBossa response failed : HTTP error code : " + response.getStatusLine().getStatusCode()); return null; } } catch (Exception ex) { logger.error(ex); return null; } } /** * It returns a json string for task creation from a given task details * * @param text * the task content * @param n_answers * @param quorum * @param calibration * @param project_id * The project ID * @param priority_0 * @return Json string */ private static JSONObject BuildJsonTaskContent(String text, String n_answers, String quorum, String calibration, int project_id, String priority_0) { try { JSONObject app = new JSONObject(); app.put("text", text); JSONObject app2 = new JSONObject(); app2.put("info", app); app2.put("n_answers", n_answers); app2.put("quorum", quorum); app2.put("calibration", calibration); app2.put("project_id", project_id); app2.put("priority_0", priority_0); return app2; } catch (Exception e) { logger.error("Error " , e); return null; } } private static Boolean insertTaskIntoMongoDB(JSONObject response, Boolean isPushedToTwitter) { try { Integer pybossa_task_id = response.getInt("id"); // String created_String = response.getString("created"); // Date publishedAt = PyBossaformatter.parse(created_String); Date date = new Date(); String publishedAt = MongoDBformatter.format(date); // String targettedFormat = MongoDBformatter.format(publishedAt); Integer project_id = response.getInt("project_id"); JSONObject info = response.getJSONObject("info"); String task_text = info.getString("text"); logger.debug("Inserting a task into MongoDB"); if (pushTaskToMongoDB(pybossa_task_id, publishedAt, project_id, isPushedToTwitter, task_text)) { return true; } else { return false; } } catch (Exception e) { logger.error("Error " , e); return false; } } private static boolean pushTaskToMongoDB(Integer pybossa_task_id, String publishedAt, Integer project_id, Boolean isPushedToTwitter, String task_text) { try { if (publishedAt != null && project_id != null && isPushedToTwitter != null && task_text != null) { FindIterable<Document> iterable = database.getCollection( Config.taskCollection).find( new Document("project_id", project_id).append( "task_text", task_text)); if (iterable.first() == null) { database.getCollection(Config.taskCollection).insertOne( new Document() .append("pybossa_task_id", pybossa_task_id) .append("publishedAt", publishedAt) .append("project_id", project_id) .append("isPushed", isPushedToTwitter) .append("task_text", task_text)); logger.debug("One task is inserted into MongoDB"); } else { logger.error("task is already in the collection!!"); } } return true; } catch (Exception e) { logger.error("Error with inserting the task " + "pybossa_task_id " + pybossa_task_id + "publishedAt " + publishedAt + "project_id " + project_id + "isPushed " + isPushedToTwitter + "task_text " + task_text + "\n" + e); return false; } } private static ArrayList<String> getAllTasksTextsFromPyBossa(int project_id) { String url = Config.PyBossahost + Config.taskDir + "?project_id=" + project_id; ArrayList<String> texts = new ArrayList<>(); HttpURLConnection con; try { URL obj = new URL(url); con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); // int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader( con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // print result JSONArray jsonData = new JSONArray(response.toString()); for (Object object : jsonData) { JSONObject json = new JSONObject(object.toString()); JSONObject info = json.getJSONObject("info"); String text = info.getString("text"); texts.add(text); } return texts; } catch (IOException e) { logger.error("Error " , e); return null; } } }
limit tasks retrieval to 200
src/main/java/sociam/pybossa/TaskCreator.java
limit tasks retrieval to 200
<ide><path>rc/main/java/sociam/pybossa/TaskCreator.java <ide> try { <ide> <ide> FindIterable<Document> iterable = binsDatabase.getCollection( <del> collectionName).find(); <add> collectionName).find().limit(200); <ide> if (iterable.first() != null) { <ide> iterable.forEach(new Block<Document>() { <ide> @Override
JavaScript
mit
84b87f6f9848dfa3bc7e85a6b850630283a89d12
0
JakeChampion/polyfill-service,JakeChampion/polyfill-service
/* eslint-env mocha */ "use strict"; const axios = require("axios"); const proclaim = require("proclaim"); const host = require("../helpers").host; describe("https://github.com/Financial-Times/polyfill-service/issues/1922", function() { this.timeout(30000); describe(`GET ${host}/v3/normalise_querystring_parameters_for_polyfill_bundle?callback=&compression=br&excludes=&features=IntersectionObserver%2Cdefault%2Cfetch&flags=&rum=0&ua=chrome%2F72.0.0&unknown=ignore&version=3.25.1`, function() { it("responds with same javascript when ua parameter is url encoded", async function() { const nonUrlEncodedUa = ( await axios.get( host + "/v3/normalise_querystring_parameters_for_polyfill_bundle?callback=&compression=br&excludes=&features=IntersectionObserver%2Cdefault%2Cfetch&flags=&rum=0&ua=chrome/72.0.0&unknown=ignore&version=3.25.1" ) ).data; const urlEncodedUa = ( await axios.get( host + "/v3/normalise_querystring_parameters_for_polyfill_bundle?callback=&compression=br&excludes=&features=IntersectionObserver%2Cdefault%2Cfetch&flags=&rum=0&ua=chrome%2F72.0.0&unknown=ignore&version=3.25.1" ) ).data; proclaim.deepStrictEqual(nonUrlEncodedUa, urlEncodedUa); }); }); });
test/integration/regression/gh-1922.test.js
/* eslint-env mocha */ "use strict"; const axios = require("axios"); const proclaim = require("proclaim"); const host = require("../helpers").host; describe("https://github.com/Financial-Times/polyfill-service/issues/1922", function() { this.timeout(30000); describe(`GET ${host}/v3/normalise_querystring_parameters_for_polyfill_bundle?callback=&compression=br&excludes=&features=IntersectionObserver%2Cdefault%2Cfetch&flags=&rum=0&ua=chrome%2F72.0.0&unknown=ignore&version=3.25.1`, function() { it("responds with same javascript when ua parameter is url encoded", async function() { const nonUrlEncodedUa = (await axios.get( host + "/v3/normalise_querystring_parameters_for_polyfill_bundle?callback=&compression=br&excludes=&features=IntersectionObserver%2Cdefault%2Cfetch&flags=&rum=0&ua=chrome/72.0.0&unknown=ignore&version=3.25.1" )).data; const urlEncodedUa = (await axios.get( host + "/v3/normalise_querystring_parameters_for_polyfill_bundle?callback=&compression=br&excludes=&features=IntersectionObserver%2Cdefault%2Cfetch&flags=&rum=0&ua=chrome%2F72.0.0&unknown=ignore&version=3.25.1" )).data; proclaim.deepStrictEqual(nonUrlEncodedUa, urlEncodedUa); }); }); });
fix linting
test/integration/regression/gh-1922.test.js
fix linting
<ide><path>est/integration/regression/gh-1922.test.js <ide> this.timeout(30000); <ide> describe(`GET ${host}/v3/normalise_querystring_parameters_for_polyfill_bundle?callback=&compression=br&excludes=&features=IntersectionObserver%2Cdefault%2Cfetch&flags=&rum=0&ua=chrome%2F72.0.0&unknown=ignore&version=3.25.1`, function() { <ide> it("responds with same javascript when ua parameter is url encoded", async function() { <del> const nonUrlEncodedUa = (await axios.get( <del> host + <del> "/v3/normalise_querystring_parameters_for_polyfill_bundle?callback=&compression=br&excludes=&features=IntersectionObserver%2Cdefault%2Cfetch&flags=&rum=0&ua=chrome/72.0.0&unknown=ignore&version=3.25.1" <del> )).data; <del> const urlEncodedUa = (await axios.get( <del> host + <del> "/v3/normalise_querystring_parameters_for_polyfill_bundle?callback=&compression=br&excludes=&features=IntersectionObserver%2Cdefault%2Cfetch&flags=&rum=0&ua=chrome%2F72.0.0&unknown=ignore&version=3.25.1" <del> )).data; <add> const nonUrlEncodedUa = ( <add> await axios.get( <add> host + <add> "/v3/normalise_querystring_parameters_for_polyfill_bundle?callback=&compression=br&excludes=&features=IntersectionObserver%2Cdefault%2Cfetch&flags=&rum=0&ua=chrome/72.0.0&unknown=ignore&version=3.25.1" <add> ) <add> ).data; <add> const urlEncodedUa = ( <add> await axios.get( <add> host + <add> "/v3/normalise_querystring_parameters_for_polyfill_bundle?callback=&compression=br&excludes=&features=IntersectionObserver%2Cdefault%2Cfetch&flags=&rum=0&ua=chrome%2F72.0.0&unknown=ignore&version=3.25.1" <add> ) <add> ).data; <ide> proclaim.deepStrictEqual(nonUrlEncodedUa, urlEncodedUa); <ide> }); <ide> });
Java
apache-2.0
b5b1f5960cca38ab82c3c3cefcf669de1dfe37b9
0
lucafavatella/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,apixandru/intellij-community,fnouama/intellij-community,dslomov/intellij-community,vladmm/intellij-community,semonte/intellij-community,xfournet/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,semonte/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,ernestp/consulo,blademainer/intellij-community,izonder/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,suncycheng/intellij-community,joewalnes/idea-community,ernestp/consulo,ivan-fedorov/intellij-community,akosyakov/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,signed/intellij-community,caot/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,izonder/intellij-community,consulo/consulo,clumsy/intellij-community,joewalnes/idea-community,fitermay/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,ernestp/consulo,Distrotech/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,holmes/intellij-community,fitermay/intellij-community,xfournet/intellij-community,blademainer/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,consulo/consulo,samthor/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,signed/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,allotria/intellij-community,kool79/intellij-community,kdwink/intellij-community,izonder/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,asedunov/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,allotria/intellij-community,diorcety/intellij-community,joewalnes/idea-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,fitermay/intellij-community,asedunov/intellij-community,supersven/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,slisson/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,signed/intellij-community,holmes/intellij-community,ibinti/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,signed/intellij-community,consulo/consulo,diorcety/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,supersven/intellij-community,vladmm/intellij-community,apixandru/intellij-community,hurricup/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,semonte/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,blademainer/intellij-community,samthor/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,slisson/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,slisson/intellij-community,blademainer/intellij-community,da1z/intellij-community,gnuhub/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,allotria/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,jexp/idea2,MER-GROUP/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,slisson/intellij-community,signed/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,holmes/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,clumsy/intellij-community,adedayo/intellij-community,caot/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,petteyg/intellij-community,caot/intellij-community,asedunov/intellij-community,FHannes/intellij-community,amith01994/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,da1z/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,kool79/intellij-community,allotria/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,holmes/intellij-community,retomerz/intellij-community,jexp/idea2,caot/intellij-community,fitermay/intellij-community,hurricup/intellij-community,jagguli/intellij-community,jagguli/intellij-community,diorcety/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,allotria/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,izonder/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,holmes/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,jexp/idea2,TangHao1987/intellij-community,semonte/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,fnouama/intellij-community,clumsy/intellij-community,signed/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,semonte/intellij-community,amith01994/intellij-community,retomerz/intellij-community,samthor/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,consulo/consulo,fnouama/intellij-community,hurricup/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,signed/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,joewalnes/idea-community,jexp/idea2,blademainer/intellij-community,ibinti/intellij-community,supersven/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,jagguli/intellij-community,diorcety/intellij-community,kool79/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,allotria/intellij-community,kool79/intellij-community,joewalnes/idea-community,FHannes/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,holmes/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,ibinti/intellij-community,slisson/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,kool79/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,retomerz/intellij-community,izonder/intellij-community,Lekanich/intellij-community,samthor/intellij-community,semonte/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,dslomov/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,joewalnes/idea-community,ol-loginov/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,FHannes/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,jexp/idea2,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,joewalnes/idea-community,xfournet/intellij-community,ol-loginov/intellij-community,caot/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,kool79/intellij-community,asedunov/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,joewalnes/idea-community,gnuhub/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,caot/intellij-community,da1z/intellij-community,vladmm/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,holmes/intellij-community,retomerz/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,caot/intellij-community,apixandru/intellij-community,clumsy/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,joewalnes/idea-community,lucafavatella/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,dslomov/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,supersven/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,slisson/intellij-community,retomerz/intellij-community,fitermay/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,hurricup/intellij-community,da1z/intellij-community,semonte/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,diorcety/intellij-community,diorcety/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,allotria/intellij-community,jexp/idea2,pwoodworth/intellij-community,kdwink/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,samthor/intellij-community,da1z/intellij-community,ernestp/consulo,da1z/intellij-community,hurricup/intellij-community,fnouama/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,izonder/intellij-community,hurricup/intellij-community,robovm/robovm-studio,izonder/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,ryano144/intellij-community,consulo/consulo,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,jexp/idea2,diorcety/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,jagguli/intellij-community,retomerz/intellij-community,semonte/intellij-community,Lekanich/intellij-community,signed/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,consulo/consulo,ibinti/intellij-community,petteyg/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,da1z/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,clumsy/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,supersven/intellij-community,petteyg/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,Lekanich/intellij-community,izonder/intellij-community,kool79/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,supersven/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,slisson/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,ryano144/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,FHannes/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,apixandru/intellij-community,jexp/idea2,da1z/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,caot/intellij-community,samthor/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,dslomov/intellij-community,signed/intellij-community,hurricup/intellij-community,retomerz/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,dslomov/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,semonte/intellij-community,ernestp/consulo,diorcety/intellij-community,fitermay/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,ernestp/consulo,ftomassetti/intellij-community,diorcety/intellij-community
package com.intellij.localvcs.integration; import com.intellij.localvcs.ILocalVcs; import com.intellij.openapi.vfs.VirtualFile; import java.io.IOException; // todo synchronization public abstract class ServiceState { protected ServiceStateHolder myHolder; protected ILocalVcs myVcs; protected IdeaGateway myGateway; public ServiceState(ServiceStateHolder h, ILocalVcs vcs, IdeaGateway gw) { myHolder = h; myGateway = gw; myVcs = vcs; afterEnteringState(); } public void startRefreshing() { illegalState(); } public void finishRefreshing() { illegalState(); } public void startCommand(String name) { illegalState(); } public void finishCommand() { illegalState(); } protected void goToState(ServiceState s) { beforeExitingFromState(); myHolder.setState(s); } public void create(VirtualFile f) { createRecursively(f); } private void createRecursively(VirtualFile f) { if (f.isDirectory()) { myVcs.createDirectory(f.getPath(), f.getTimeStamp()); for (VirtualFile child : f.getChildren()) createRecursively(child); } else { myVcs.createFile(f.getPath(), physicalContentOf(f), f.getTimeStamp()); } } public void changeFileContent(VirtualFile f) { myVcs.changeFileContent(f.getPath(), physicalContentOf(f), f.getTimeStamp()); } private byte[] physicalContentOf(VirtualFile f) { try { return myGateway.getPhysicalContent(f); } catch (IOException e) { throw new RuntimeException(e); } } public void rename(VirtualFile f, String newName) { myVcs.rename(f.getPath(), newName); } public void move(VirtualFile file, VirtualFile newParent) { myVcs.move(file.getPath(), newParent.getPath()); } public void delete(VirtualFile f) { myVcs.delete(f.getPath()); } protected void afterEnteringState() { } protected void beforeExitingFromState() { } private void illegalState() { // todo move to logging proxy... throw new IllegalStateException(getClass().getSimpleName()); } }
LocalVcs/src/com/intellij/localvcs/integration/ServiceState.java
package com.intellij.localvcs.integration; import com.intellij.localvcs.ILocalVcs; import com.intellij.openapi.vfs.VirtualFile; import java.io.IOException; // todo synchronization public abstract class ServiceState { protected ServiceStateHolder myHolder; protected ILocalVcs myVcs; protected IdeaGateway myGateway; public ServiceState(ServiceStateHolder h, ILocalVcs vcs, IdeaGateway gw) { myHolder = h; myGateway = gw; myVcs = vcs; afterEnteringState(); } public void startRefreshing() { throw new IllegalStateException(); } public void finishRefreshing() { throw new IllegalStateException(); } public void startCommand(String name) { throw new IllegalStateException(); } public void finishCommand() { throw new IllegalStateException(); } protected void goToState(ServiceState s) { beforeExitingFromState(); myHolder.setState(s); } public void create(VirtualFile f) { createRecursively(f); } private void createRecursively(VirtualFile f) { if (f.isDirectory()) { myVcs.createDirectory(f.getPath(), f.getTimeStamp()); for (VirtualFile child : f.getChildren()) createRecursively(child); } else { myVcs.createFile(f.getPath(), physicalContentOf(f), f.getTimeStamp()); } } public void changeFileContent(VirtualFile f) { myVcs.changeFileContent(f.getPath(), physicalContentOf(f), f.getTimeStamp()); } private byte[] physicalContentOf(VirtualFile f) { try { return myGateway.getPhysicalContent(f); } catch (IOException e) { throw new RuntimeException(e); } } public void rename(VirtualFile f, String newName) { myVcs.rename(f.getPath(), newName); } public void move(VirtualFile file, VirtualFile newParent) { myVcs.move(file.getPath(), newParent.getPath()); } public void delete(VirtualFile f) { myVcs.delete(f.getPath()); } protected void afterEnteringState() { } protected void beforeExitingFromState() { } }
-more verbose exception logging
LocalVcs/src/com/intellij/localvcs/integration/ServiceState.java
-more verbose exception logging
<ide><path>ocalVcs/src/com/intellij/localvcs/integration/ServiceState.java <ide> } <ide> <ide> public void startRefreshing() { <del> throw new IllegalStateException(); <add> illegalState(); <ide> } <ide> <ide> public void finishRefreshing() { <del> throw new IllegalStateException(); <add> illegalState(); <ide> } <ide> <ide> public void startCommand(String name) { <del> throw new IllegalStateException(); <add> illegalState(); <ide> } <ide> <ide> public void finishCommand() { <del> throw new IllegalStateException(); <add> illegalState(); <ide> } <ide> <ide> protected void goToState(ServiceState s) { <ide> <ide> protected void beforeExitingFromState() { <ide> } <add> <add> private void illegalState() { <add> // todo move to logging proxy... <add> throw new IllegalStateException(getClass().getSimpleName()); <add> } <ide> }
Java
apache-2.0
9cff3164ff568593c14e4e4906b93294251b3006
0
hbs/warp10-platform,hbs/warp10-platform,StevenLeRoux/warp10-platform,cityzendata/warp10-platform,StevenLeRoux/warp10-platform,hbs/warp10-platform,hbs/warp10-platform,cityzendata/warp10-platform,cityzendata/warp10-platform,cityzendata/warp10-platform,StevenLeRoux/warp10-platform,StevenLeRoux/warp10-platform
// // Copyright 2016 Cityzen Data // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package io.warp10.continuum.gts; import io.warp10.continuum.store.thrift.data.GTSWrapper; import io.warp10.continuum.store.thrift.data.Metadata; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; public class GTSWrapperHelper { /** * Default compression ratio threshold */ private static final double DEFAULT_COMP_RATIO_THRESHOLD = 100.0D; public static GTSDecoder fromGTSWrapperToGTSDecoder(GTSWrapper wrapper) { byte[] unwrapped = unwrapEncoded(wrapper); GTSDecoder decoder = new GTSDecoder(wrapper.getBase(), ByteBuffer.wrap(unwrapped).order(ByteOrder.BIG_ENDIAN)); decoder.setMetadata(wrapper.getMetadata()); decoder.setCount(wrapper.getCount()); return decoder; } /** * convert a GTSWrapper into GeoTimeSerie * @param wrapper * @return GeoTimeSerie */ public static GeoTimeSerie fromGTSWrapperToGTS(GTSWrapper wrapper) { Metadata metadata = wrapper.getMetadata(); GeoTimeSerie gts = null; if (null != wrapper.getEncoded()) { byte[] bytes = null; if (wrapper.isCompressed()) { bytes = unwrapEncoded(wrapper); } else { bytes = wrapper.getEncoded(); } ByteBuffer bb = ByteBuffer.wrap(bytes); GTSDecoder decoder = new GTSDecoder(wrapper.getBase(), bb); decoder.setCount(0 != wrapper.getCount() ? wrapper.getCount() : bytes.length / 10); gts = decoder.decode(); } else { gts = new GeoTimeSerie(); } if (null == metadata) { metadata = new Metadata(); } gts.setMetadata(metadata); return gts; } public static GTSWrapper fromGTSToGTSWrapper(GeoTimeSerie gts) { return fromGTSToGTSWrapper(gts, false); } public static GTSWrapper fromGTSEncoderToGTSWrapper(GTSEncoder encoder, boolean compress) { return fromGTSEncoderToGTSWrapper(encoder, compress, DEFAULT_COMP_RATIO_THRESHOLD); } public static GTSWrapper fromGTSEncoderToGTSWrapper(GTSEncoder encoder, boolean compress, double compratio) { if (compratio < 1.0D) { compratio = 1.0D; } GTSWrapper wrapper = new GTSWrapper(); try { if (!compress) { wrapper.setEncoded(encoder.getBytes()); } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] bytes = encoder.getBytes(); double ratio = 0.0D; int pass = 0; // // We compress the data once, if the compression ratio is greater // than 'compratio', we consider that the resulting compressed data will // probably still have lots of repetitions since we will have // overflowed the gzip sliding window several times, we therefore // enter a loop to compress the data until the compression ratio // falls below 'compratio' // We then store the number of compression passes in the GTSWrapper // so we can apply a matching number of decompression ops // // For ultimate compression, set 'compratio' to 1.0 // byte[] encoded = null; do { encoded = bytes; ratio = bytes.length; GZIPOutputStream gzos = new GZIPOutputStream(baos); gzos.write(bytes); gzos.close(); bytes = baos.toByteArray(); baos.reset(); ratio = ratio / bytes.length; pass++; } while (ratio > compratio); if (ratio > 1.0D) { // The last compression pass improved the footprint, so use the compressed data wrapper.setEncoded(bytes); } else { // The last pass added some overhead, ignore it pass = pass - 1; wrapper.setEncoded(encoded); } if (pass > 0) { wrapper.setCompressed(true); if (pass > 1) { // Only store number of passes if it is > 1 as 1 is the default value wrapper.setCompressionPasses(pass); } } else { wrapper.setCompressed(false); } } wrapper.setBase(encoder.getBaseTimestamp()); wrapper.setCount(encoder.getCount()); wrapper.setMetadata(encoder.getMetadata()); } catch (IOException e) { e.printStackTrace(); } return wrapper; } /** * convert a GeoTimeSerie into GTSWrapper * @param gts * @return GTSWrapper */ public static GTSWrapper fromGTSToGTSWrapper(GeoTimeSerie gts, boolean compress) { return fromGTSToGTSWrapper(gts, compress, DEFAULT_COMP_RATIO_THRESHOLD); } public static GTSWrapper fromGTSToGTSWrapper(GeoTimeSerie gts, boolean compress, double compratio) { GTSEncoder encoder = new GTSEncoder(0L); encoder.setMetadata(gts.getMetadata()); try { encoder.encode(gts); } catch (IOException ioe) { } GTSWrapper wrapper = fromGTSEncoderToGTSWrapper(encoder, compress, compratio); if (GTSHelper.isBucketized(gts)) { wrapper.setBucketcount(gts.bucketcount); wrapper.setBucketspan(gts.bucketspan); wrapper.setLastbucket(gts.lastbucket); } return wrapper; } /** * Produces a GTSWrapper whose values are those at ticks from the argument only clipped to [from,to]. * The bucketization parameters are not modified * * @param wrapper Source wrapper * @return A new wrapper */ public static GTSWrapper clip(GTSWrapper wrapper, long from, long to) { GTSDecoder decoder = new GTSDecoder(wrapper.getBase(), ByteBuffer.wrap(unwrapEncoded(wrapper))); GTSEncoder encoder = wrapper.isSetKey() ? new GTSEncoder(wrapper.getBase(), wrapper.getKey()) : new GTSEncoder(wrapper.getBase()); while(decoder.next()) { if (decoder.getTimestamp() >= from && decoder.getTimestamp() <= to) { try { encoder.addValue(decoder.getTimestamp(), decoder.getLocation(), decoder.getElevation(), decoder.getValue()); } catch (IOException ioe) { return null; } } } GTSWrapper clipped = new GTSWrapper(); clipped.setBase(wrapper.getBase()); clipped.setBucketcount(wrapper.getBucketcount()); clipped.setBucketspan(wrapper.getBucketspan()); clipped.setCount(encoder.getCount()); clipped.setEncoded(encoder.getBytes()); clipped.setLastbucket(wrapper.getLastbucket()); clipped.setMetadata(new Metadata(wrapper.getMetadata())); if (wrapper.isSetKey()) { clipped.setKey(wrapper.getKey()); } return clipped; } /** * Extract the encoded data, removing compression if needed * * @param wrapper from which to extract the encoded data * @return the raw encoded data */ private static byte[] unwrapEncoded(GTSWrapper wrapper) { if (!wrapper.isCompressed()) { return wrapper.getEncoded(); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] bytes = wrapper.getEncoded(); int pass = wrapper.getCompressionPasses(); while(pass > 0) { ByteArrayInputStream in = new ByteArrayInputStream(bytes); baos.reset(); try { GZIPInputStream gzis = new GZIPInputStream(in); byte[] buf = new byte[1024]; while(true) { int len = gzis.read(buf); if (len < 0) { break; } baos.write(buf, 0, len); } gzis.close(); } catch (IOException ioe) { throw new RuntimeException("Invalid compressed content."); } bytes = baos.toByteArray(); pass--; } return bytes; } public static boolean isBucketized(GTSWrapper gtsWrapper) { return 0 != gtsWrapper.getBucketcount() && 0L != gtsWrapper.getBucketspan() && 0L != gtsWrapper.getLastbucket(); } /** * Return an ID for a wrapper */ public static byte[] getId(GTSWrapper wrapper) { byte[] id = new byte[16]; long classId = wrapper.getMetadata().getClassId(); long labelsId = wrapper.getMetadata().getLabelsId(); for (int i = 7; i >= 0; i--) { id[i] = (byte) (classId & 0xFFL); classId >>>= 8; id[8 + i] = (byte) (labelsId & 0xFFL); labelsId >>>= 8; } return id; } /** * Method used to rewrap a GTSWrapper, typically to change the compression settings. * * @param wrapper * @param compress * @param compratio * @return */ public static GTSWrapper rewrap(GTSWrapper wrapper, boolean compress, double compratio) { byte[] unwrapped = unwrapEncoded(wrapper); GTSEncoder encoder = new GTSEncoder(wrapper.getBase(), null, unwrapped); GTSWrapper tmp = fromGTSEncoderToGTSWrapper(encoder, compress, compratio); GTSWrapper rewrapped = new GTSWrapper(wrapper); rewrapped.setCompressed(tmp.isCompressed()); rewrapped.setCompressionPasses(tmp.getCompressionPasses()); rewrapped.setEncoded(tmp.getEncoded()); return rewrapped; } }
warp10/src/main/java/io/warp10/continuum/gts/GTSWrapperHelper.java
// // Copyright 2016 Cityzen Data // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package io.warp10.continuum.gts; import io.warp10.continuum.store.thrift.data.GTSWrapper; import io.warp10.continuum.store.thrift.data.Metadata; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; public class GTSWrapperHelper { /** * Default compression ratio threshold */ private static final double DEFAULT_COMP_RATIO_THRESHOLD = 100.0D; public static GTSDecoder fromGTSWrapperToGTSDecoder(GTSWrapper wrapper) { byte[] unwrapped = unwrapEncoded(wrapper); GTSDecoder decoder = new GTSDecoder(wrapper.getBase(), ByteBuffer.wrap(unwrapped).order(ByteOrder.BIG_ENDIAN)); decoder.setMetadata(wrapper.getMetadata()); decoder.setCount(wrapper.getCount()); return decoder; } /** * convert a GTSWrapper into GeoTimeSerie * @param wrapper * @return GeoTimeSerie */ public static GeoTimeSerie fromGTSWrapperToGTS(GTSWrapper wrapper) { Metadata metadata = wrapper.getMetadata(); GeoTimeSerie gts = null; if (null != wrapper.getEncoded()) { byte[] bytes = null; if (wrapper.isCompressed()) { bytes = unwrapEncoded(wrapper); } else { bytes = wrapper.getEncoded(); } ByteBuffer bb = ByteBuffer.wrap(bytes); GTSDecoder decoder = new GTSDecoder(wrapper.getBase(), bb); decoder.setCount(0 != wrapper.getCount() ? wrapper.getCount() : bytes.length / 10); gts = decoder.decode(); } else { gts = new GeoTimeSerie(); } if (null == metadata) { metadata = new Metadata(); } gts.setMetadata(metadata); return gts; } public static GTSWrapper fromGTSToGTSWrapper(GeoTimeSerie gts) { return fromGTSToGTSWrapper(gts, false); } public static GTSWrapper fromGTSEncoderToGTSWrapper(GTSEncoder encoder, boolean compress) { return fromGTSEncoderToGTSWrapper(encoder, compress, DEFAULT_COMP_RATIO_THRESHOLD); } public static GTSWrapper fromGTSEncoderToGTSWrapper(GTSEncoder encoder, boolean compress, double compratio) { if (compratio < 1.0D) { compratio = 1.0D; } GTSWrapper wrapper = new GTSWrapper(); try { if (!compress) { wrapper.setEncoded(encoder.getBytes()); } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] bytes = encoder.getBytes(); double ratio = 0.0D; int pass = 0; // // We compress the data once, if the compression ratio is greater // than 'compratio', we consider that the resulting compressed data will // probably still have lots of repetitions since we will have // overflowed the gzip sliding window several times, we therefore // enter a loop to compress the data until the compression ratio // falls below 'compratio' // We then store the number of compression passes in the GTSWrapper // so we can apply a matching number of decompression ops // // For ultimate compression, set 'compratio' to 1.0 // byte[] encoded = null; do { encoded = bytes; ratio = bytes.length; GZIPOutputStream gzos = new GZIPOutputStream(baos); gzos.write(bytes); gzos.close(); bytes = baos.toByteArray(); baos.reset(); ratio = ratio / bytes.length; pass++; } while (ratio > compratio); if (ratio > 1.0D) { // The last compression pass improved the footprint, so use the compressed data wrapper.setEncoded(bytes); } else { // The last pass added some overhead, ignore it pass = pass - 1; wrapper.setEncoded(encoded); } if (pass > 0) { wrapper.setCompressed(true); if (pass > 1) { // Only store number of passes if it is > 1 as 1 is the default value wrapper.setCompressionPasses(pass); } } else { wrapper.setCompressed(false); } } wrapper.setBase(encoder.getBaseTimestamp()); wrapper.setCount(encoder.getCount()); wrapper.setMetadata(encoder.getMetadata()); } catch (IOException e) { e.printStackTrace(); } return wrapper; } /** * convert a GeoTimeSerie into GTSWrapper * @param gts * @return GTSWrapper */ public static GTSWrapper fromGTSToGTSWrapper(GeoTimeSerie gts, boolean compress) { return fromGTSToGTSWrapper(gts, compress, DEFAULT_COMP_RATIO_THRESHOLD); } public static GTSWrapper fromGTSToGTSWrapper(GeoTimeSerie gts, boolean compress, double compratio) { GTSEncoder encoder = new GTSEncoder(0L); encoder.setMetadata(gts.getMetadata()); try { encoder.encode(gts); } catch (IOException ioe) { } GTSWrapper wrapper = fromGTSEncoderToGTSWrapper(encoder, compress, compratio); if (GTSHelper.isBucketized(gts)) { wrapper.setBucketcount(gts.bucketcount); wrapper.setBucketspan(gts.bucketspan); wrapper.setLastbucket(gts.lastbucket); } return wrapper; } /** * Produces a GTSWrapper whose values are those at ticks from the argument only clipped to [from,to]. * The bucketization parameters are not modified * * @param wrapper Source wrapper * @return A new wrapper */ public static GTSWrapper clip(GTSWrapper wrapper, long from, long to) { GTSDecoder decoder = new GTSDecoder(wrapper.getBase(), ByteBuffer.wrap(unwrapEncoded(wrapper))); GTSEncoder encoder = wrapper.isSetKey() ? new GTSEncoder(wrapper.getBase(), wrapper.getKey()) : new GTSEncoder(wrapper.getBase()); while(decoder.next()) { if (decoder.getTimestamp() >= from && decoder.getTimestamp() <= to) { try { encoder.addValue(decoder.getTimestamp(), decoder.getLocation(), decoder.getElevation(), decoder.getValue()); } catch (IOException ioe) { return null; } } } GTSWrapper clipped = new GTSWrapper(); clipped.setBase(wrapper.getBase()); clipped.setBucketcount(wrapper.getBucketcount()); clipped.setBucketspan(wrapper.getBucketspan()); clipped.setCount(encoder.getCount()); clipped.setEncoded(encoder.getBytes()); clipped.setLastbucket(wrapper.getLastbucket()); clipped.setMetadata(new Metadata(wrapper.getMetadata())); if (wrapper.isSetKey()) { clipped.setKey(wrapper.getKey()); } return clipped; } /** * Extract the encoded data, removing compression if needed * * @param wrapper from which to extract the encoded data * @return the raw encoded data */ private static byte[] unwrapEncoded(GTSWrapper wrapper) { if (!wrapper.isCompressed()) { return wrapper.getEncoded(); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] bytes = wrapper.getEncoded(); int pass = wrapper.getCompressionPasses(); while(pass > 0) { ByteArrayInputStream in = new ByteArrayInputStream(bytes); baos.reset(); try { GZIPInputStream gzis = new GZIPInputStream(in); byte[] buf = new byte[1024]; while(true) { int len = gzis.read(buf); if (len < 0) { break; } baos.write(buf, 0, len); } gzis.close(); } catch (IOException ioe) { throw new RuntimeException("Invalid compressed content."); } bytes = baos.toByteArray(); pass--; } return bytes; } public static boolean isBucketized(GTSWrapper gtsWrapper) { return 0 != gtsWrapper.getBucketcount() && 0L != gtsWrapper.getBucketspan() && 0L != gtsWrapper.getLastbucket(); } /** * Return an ID for a wrapper */ public static byte[] getId(GTSWrapper wrapper) { byte[] id = new byte[16]; long classId = wrapper.getMetadata().getClassId(); long labelsId = wrapper.getMetadata().getLabelsId(); for (int i = 7; i >= 0; i--) { id[i] = (byte) (classId & 0xFFL); classId >>>= 8; id[8 + i] = (byte) (labelsId & 0xFFL); labelsId >>>= 8; } return id; } }
Added method rewrap
warp10/src/main/java/io/warp10/continuum/gts/GTSWrapperHelper.java
Added method rewrap
<ide><path>arp10/src/main/java/io/warp10/continuum/gts/GTSWrapperHelper.java <ide> <ide> return id; <ide> } <add> <add> /** <add> * Method used to rewrap a GTSWrapper, typically to change the compression settings. <add> * <add> * @param wrapper <add> * @param compress <add> * @param compratio <add> * @return <add> */ <add> public static GTSWrapper rewrap(GTSWrapper wrapper, boolean compress, double compratio) { <add> byte[] unwrapped = unwrapEncoded(wrapper); <add> <add> GTSEncoder encoder = new GTSEncoder(wrapper.getBase(), null, unwrapped); <add> <add> GTSWrapper tmp = fromGTSEncoderToGTSWrapper(encoder, compress, compratio); <add> <add> GTSWrapper rewrapped = new GTSWrapper(wrapper); <add> rewrapped.setCompressed(tmp.isCompressed()); <add> rewrapped.setCompressionPasses(tmp.getCompressionPasses()); <add> rewrapped.setEncoded(tmp.getEncoded()); <add> <add> return rewrapped; <add> } <ide> }
Java
apache-2.0
df126d73f88cf35680b8f9d5ee05bbf6e41da0ef
0
killjoy1221/HD-Font-Generator
package mnm.hdfontgen.pack; import mnm.hdfontgen.bitmap.BitmapFontGenerator; import mnm.hdfontgen.legacy.LegacyFontGenerator; public enum PackFormat { V1(1, "1.6.1", "1.8.9", LegacyFontGenerator::new), V2(2, "1.9", "1.10.2", LegacyFontGenerator::new), V3(3, "1.11", "1.12.2", LegacyFontGenerator::new), V4(4, "1.13", "1.14.4", BitmapFontGenerator::new), V5(5, "1.15", "1.16.1", BitmapFontGenerator::new), V6(6, "1.16.2", "1.16.5", BitmapFontGenerator::new), V7(7, "1.17", null, BitmapFontGenerator::new), ; public static final PackFormat LATEST = V7; private final int format; private final String minVersion; private final String maxVersion; private final PackGeneratorFactory factory; PackFormat(int format, String minVersion, String maxVersion, PackGeneratorFactory factory) { this.format = format; this.minVersion = minVersion; this.maxVersion = maxVersion; this.factory = factory; } public int getFormat() { return format; } public String getVersionRange() { if (maxVersion == null) { return String.format("%s+", minVersion); } return String.format("%s-%s", minVersion, maxVersion); } public PackGeneratorFactory getFactory() { return factory; } @Override public String toString() { if (maxVersion == null) { return String.format("MC %s+", minVersion); } return String.format("MC %s - %s", minVersion, maxVersion); } }
src/main/java/mnm/hdfontgen/pack/PackFormat.java
package mnm.hdfontgen.pack; import mnm.hdfontgen.bitmap.BitmapFontGenerator; import mnm.hdfontgen.legacy.LegacyFontGenerator; public enum PackFormat { V1(1, "1.6.1", "1.8.9", LegacyFontGenerator::new), V2(2, "1.9", "1.10.2", LegacyFontGenerator::new), V3(3, "1.11", "1.12.2", LegacyFontGenerator::new), V4(4, "1.13", "1.14.4", BitmapFontGenerator::new), V5(5, "1.15", "1.16.1", BitmapFontGenerator::new), V6(6, "1.16.2", "1.16.5", BitmapFontGenerator::new), V7(7, "1.17", "?", BitmapFontGenerator::new), ; public static final PackFormat LATEST = V7; private final int format; private final String minVersion; private final String maxVersion; private final PackGeneratorFactory factory; PackFormat(int format, String minVersion, String maxVersion, PackGeneratorFactory factory) { this.format = format; this.minVersion = minVersion; this.maxVersion = maxVersion; this.factory = factory; } public int getFormat() { return format; } public String getVersionRange() { return String.format("%s-%s", minVersion, maxVersion); } public PackGeneratorFactory getFactory() { return factory; } @Override public String toString() { return String.format("MC %s - %s", minVersion, maxVersion); } }
Fix error when generating fonts for 1.17+
src/main/java/mnm/hdfontgen/pack/PackFormat.java
Fix error when generating fonts for 1.17+
<ide><path>rc/main/java/mnm/hdfontgen/pack/PackFormat.java <ide> V4(4, "1.13", "1.14.4", BitmapFontGenerator::new), <ide> V5(5, "1.15", "1.16.1", BitmapFontGenerator::new), <ide> V6(6, "1.16.2", "1.16.5", BitmapFontGenerator::new), <del> V7(7, "1.17", "?", BitmapFontGenerator::new), <add> V7(7, "1.17", null, BitmapFontGenerator::new), <ide> ; <ide> <ide> public static final PackFormat LATEST = V7; <ide> } <ide> <ide> public String getVersionRange() { <add> if (maxVersion == null) { <add> return String.format("%s+", minVersion); <add> } <ide> return String.format("%s-%s", minVersion, maxVersion); <ide> } <ide> <ide> <ide> @Override <ide> public String toString() { <add> if (maxVersion == null) { <add> return String.format("MC %s+", minVersion); <add> } <ide> return String.format("MC %s - %s", minVersion, maxVersion); <ide> } <ide> }
Java
apache-2.0
403f22ac4e2b1ff1cd0ad6f0d465cedd08d8d3cf
0
googleinterns/step188-2020,googleinterns/step188-2020,googleinterns/step188-2020
package com.google.sps.data; import java.util.Set; public final class VolunteeringOpportunity { private String name; private Set<String> skillsRequired; private int numSpotsLeft; private Set<User> volunteers; public VolunteeringOpportunity( String name, Set<String> requiredSkills, int numSpotsLeft, Set<User> volunteers) { this.name = name; this.skillsRequired = skillsRequired; this.numSpotsLeft = numSpotsLeft; this.volunteers = new HashSet<User>(); } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Set<String> getRequiredSkills() { return this.skillsRequired; } public void setRequiredSkills(Set<String> requiredSkills) { this.skillsRequired = requiredSkills; } public void addRequiredSkill(String requiredSkill) { this.skillsRequired.add(requiredSkill); } public int getNumSpotsLeft() { return this.numSpotsLeft; } public void setNumSpotsLeft(int numSpotsLeft) { this.numSpotsLeft = numSpotsLeft; } public Set<User> getVolunteers() { return this.volunteers; } public void addVolunteer(User volunteer) { this.volunteers.add(volunteer); } }
project/src/main/java/com/google/sps/data/VolunteeringOpportunity.java
package com.google.sps.data; import java.util.Set; public final class VolunteeringOpportunity { private String name; private Set<String> skillsRequired; private int numSpotsLeft; private Set<User> volunteers; public VolunteeringOpportunity( String name, Set<String> requiredSkills, int numSpotsLeft, Set<User> volunteers) { this.name = name; this.skillsRequired = skillsRequired; this.numSpotsLeft = numSpotsLeft; this.volunteers = new HashSet<User>(); } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Set<String> getRequiredSkills() { return this.skillsRequired; } public void setRequiredSkills(Set<String> requiredSkills) { this.skillsRequired = requiredSkills; } public void addRequiredSkill(String requiredSkill) { this.skillsRequired.add(requiredSkill); } public int getNumSpotsLeft() { return this.numSpotsLeft; } public void setNumSpotsLeft(int numSpotsLeft) { this.numSpotsLeft = numSpotsLeft; } public Set<User> getVolunteers() { return this.volunteers; } public void addVolunteer(User volunteer) { this.volunteers.add(volunteer); } }
Fix style.
project/src/main/java/com/google/sps/data/VolunteeringOpportunity.java
Fix style.
<ide><path>roject/src/main/java/com/google/sps/data/VolunteeringOpportunity.java <ide> private Set<User> volunteers; <ide> <ide> public VolunteeringOpportunity( <del> String name, Set<String> requiredSkills, int numSpotsLeft, Set<User> volunteers) { <add> String name, Set<String> requiredSkills, int numSpotsLeft, Set<User> volunteers) { <ide> this.name = name; <ide> this.skillsRequired = skillsRequired; <ide> this.numSpotsLeft = numSpotsLeft;
JavaScript
apache-2.0
49a0765bd344e2aec32fda1b6512a7b2da863ce9
0
sumalla/speech-to-text-nodejs,cemoulto/speech-to-text-nodejs,olegka311/FirstKnApp,watson-developer-cloud/speech-to-text-nodejs,ReachingOut/speech-to-text-nodejs,ofer43211/speech-to-text-nodejs,shahnikita/speech-to-text-nodejs,abrichr/speech-to-text-nodejs,cemoulto/speech-to-text-nodejs,JeffreyTerry/butterfly,nothinkelse/sentiment-of-things,snehitgajjar/speechConversion,abrichr/speech-to-text-nodejs,tonybndt/BlueMix-Tutorials,alex-learn/speech-to-text-nodejs,sumalla/speech-to-text-nodejs,nothinkelse/sentiment-of-things,kasaby/speech-to-text-nodejs,patrickcho168/EmHacks,val314159/speech-to-text-nodejs,leonrch/speech-to-text-nodejs,olegka311/KnFirstapp,JeffreyTerry/butterfly,ofer43211/speech-to-text-nodejs,ManojitBallav/speech-to-text-nodejs,nothinkelse/sentiment-of-things,ManojitBallav/speech-to-text-nodejs,alex-learn/speech-to-text-nodejs,fmacias64/speech-to-text-nodejs,val314159/speech-to-text-nodejs,shahnikita/speech-to-text-nodejs,fmacias64/speech-to-text-nodejs,ReachingOut/speech-to-text-nodejs,snehitgajjar/speechConversion,watson-developer-cloud/speech-to-text-nodejs
/** * Copyright 2014 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*global $:false */ 'use strict'; $(document).ready(function() { // Only works on Chrome if (!$('body').hasClass('chrome')) { $('.unsupported-overlay').show(); } // UI var micButton = $('.micButton'), micText = $('.micText'), transcript = $('#text'), errorMsg = $('.errorMsg'); var speech = new SpeechRecognition({ ws: 'ws://127.0.0.1:8020/speech-to-text-beta/api/v1/recognize', model: 'WatsonModel' }); speech.onresult = function(result) { console.log('got a result: ', result); }; speech.onerror = function(err) { console.log('got a error: ', err); }; // Test out library var sampleUrl = 'audio/sample1.flac'; var sampleRequest = new XMLHttpRequest(); sampleRequest.open("GET", sampleUrl, true); sampleRequest.responseType = 'blob'; sampleRequest.onload = function(evt) { console.log('speech started...'); var blob = sampleRequest.response; var trimmedBlob = blob.slice(0, 4); var reader = new FileReader(); reader.addEventListener("loadend", function() { console.log('state', reader.readyState); console.log('bytes', reader.result); if (reader.result === 'fLaC') { speech._init('audio/flac'); } else { speech._init('audio/l16;rate=48000'); } speech.onstart = function(evt) { speech.recognize(sampleRequest.response); }; }); reader.readAsText(trimmedBlob); }; sampleRequest.send(); // Test out token var tokenUrl = '/token'; var tokenRequest = new XMLHttpRequest(); tokenRequest.open("GET", tokenUrl, true); tokenRequest.onload = function(evt) { // console.log('token ', tokenRequest.responseText); // console.log('response', request.responseText); // var xhr = new XMLHttpRequest(); // var url = 'https://stream-d.watsonplatform.net/text-to-speech-beta/api/v1/voices'; // xhr.open('GET', url, true); // xhr.setRequestHeader('X-Watson-Authorization-Token', request.responseText); // xhr.setRequestHeader('Authorization ', 'none'); // xhr.send(); // xhr.onload = function(evt) { // console.log('speech data', xhr.responseText); // alert('responsetext', xhr.responseText); // }; }; tokenRequest.send(); var modelsUrl = '/v1/models'; var modelsRequest = new XMLHttpRequest(); modelsRequest.open("GET", modelsUrl, true); // request.setRequestHeader('Authorization', 'Basic ' + creds); modelsRequest.onload = function(evt) { // console.log('token ', request.responseText); }; modelsRequest.send(); // Service // var recording = false, // speech = new SpeechRecognition({ // ws: 'ws://127.0.0.1:8020/speech-to-text-beta/api/v1/recognize', // model: 'WatsonModel' // }); // speech.onstart = function() { // console.log('demo.onstart()'); // recording = true; // micButton.addClass('recording'); // micText.text('Press again when finished'); // errorMsg.hide(); // transcript.show(); // // // Clean the paragraphs // transcript.empty(); // $('<p></p>').appendTo(transcript); // }; // // speech.onerror = function(error) { // // console.log('demo.onerror():', error); // // recording = false; // // micButton.removeClass('recording'); // displayError(error); // }; // // speech.onend = function() { // console.log('demo.onend()'); // recording = false; // micButton.removeClass('recording'); // micText.text('Press to start speaking'); // }; // // speech.onresult = function(data) { // console.log('demo.onresult()', data); // showResult(data); // }; // // micButton.click(function() { // if (!recording) { // speech.start(); // } else { // speech.stop(); // micButton.removeClass('recording'); // micText.text('Processing speech'); // } // }); function showResult(data) { //console.log(data); //if there are transcripts if (data.results && data.results.length > 0) { //if is a partial transcripts if (data.results.length === 1 ) { var paragraph = transcript.children().last(), text = data.results[0].alternatives[0].transcript || ''; console.log('text', text); //Capitalize first word text = text.charAt(0).toUpperCase() + text.substring(1); // if final results, append a new paragraph // if (data.results[0].final){ text = text.trim() + '.'; $('.loading').hide(); $('#text').append(text); // } // paragraph.text(text); } } // transcript.show(); } function displayError(error) { var message = error; try { var errorJson = JSON.parse(error); message = JSON.stringify(errorJson, null, 2); } catch (e) { message = error; } errorMsg.text(message); errorMsg.show(); transcript.hide(); } //Sample audios var audio1 = 'audio/sample1.wav', audio2 = 'audio/sample2.wav'; function _error(xhr) { $('.loading').hide(); displayError('Error processing the request, please try again.'); } function stopSounds() { $('.sample2').get(0).pause(); $('.sample2').get(0).currentTime = 0; $('.sample1').get(0).pause(); $('.sample1').get(0).currentTime = 0; } $('.audio1').click(function() { $('.audio-staged audio').attr('src', audio1); stopSounds(); $('.sample1').get(0).play(); }); $('.audio2').click(function() { $('.audio-staged audio').attr('src', audio2); stopSounds(); $('.sample2').get(0).play(); }); $('.send-api-audio1').click(function() { transcriptAudio(audio1); }); $('.send-api-audio2').click(function() { transcriptAudio(audio2); }); function showAudioResult(data){ $('.loading').hide(); transcript.empty(); $('<p></p>').appendTo(transcript); showResult(data); } // submit event function transcriptAudio(audio) { $('.loading').show(); $('.error').hide(); transcript.hide(); $('.url-input').val(audio); $('.upload-form').hide(); // Grab all form data $.ajax({ url: '/', type: 'POST', data: $('.upload-form').serialize(), success: showAudioResult, error: _error }); } // var ws = new WebSocket('ws://127.0.0.1:8020/speech-to-text-beta/api/v1/recognize'); // window.ws = ws; // ws.onopen = function(evt) { // console.log('loading'); // ws.send(JSON.stringify({'action': 'start', 'content-type': 'audio/l16;rate=48000'})); // }; // // ws.onmessage = function(evt) { // console.log('msg ', evt.data); // var data = JSON.parse(evt.data); // showResult(data); // }; // // ws.onerror = function(evt) { // console.log('error ', evt); // }; function sendDraggedFile(file) { $('.loading').show(); console.log('loading blob: '); // ws.send(file); // ws.send(JSON.stringify({'action': 'stop'})); } function handleFileUploadEvent(evt) { console.log('uploading file'); var file = evt.dataTransfer.files[0]; var objectUrl = URL.createObjectURL(file); sendDraggedFile(file); $('.custom.sample-title').text(file.name); $('.audio3').click(function() { console.log('evt', evt); $('.sample3').prop('src', objectUrl); stopSounds(); $('.sample3').get(0).play(); }); $('.send-api-audio3').click(function() { console.log('click! API'); sendDraggedFile(file); }); } var target = $("#fileUploadTarget"); target.on('dragenter', function (e) { e.stopPropagation(); e.preventDefault(); $(this).css('border', '2px solid #0B85A1'); }); target.on('dragover', function (e) { e.stopPropagation(); e.preventDefault(); }); target.on('drop', function (e) { $(this).css('border', '2px dotted #0B85A1'); e.preventDefault(); var evt = e.originalEvent; // Handle dragged file event handleFileUploadEvent(evt); }); });
public/js/demo.js
/** * Copyright 2014 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*global $:false */ 'use strict'; $(document).ready(function() { // Only works on Chrome if (!$('body').hasClass('chrome')) { $('.unsupported-overlay').show(); } // UI var micButton = $('.micButton'), micText = $('.micText'), transcript = $('#text'), errorMsg = $('.errorMsg'); // Test out CORS // var url = 'https://stream-d.watsonplatform.net/speech-to-text-beta/api/v1/models'; // var request = new XMLHttpRequest(); // request.open("GET", url, true); // request.onload = function(evt) { // console.log('response', request.responseText); // }; // request.send(); // Service var recording = false, speech = new SpeechRecognition({ ws: 'ws://127.0.0.1:8020/speech-to-text-beta/api/v1/recognize', model: 'WatsonModel' }); speech.onstart = function() { console.log('demo.onstart()'); recording = true; micButton.addClass('recording'); micText.text('Press again when finished'); errorMsg.hide(); transcript.show(); // Clean the paragraphs transcript.empty(); $('<p></p>').appendTo(transcript); }; speech.onerror = function(error) { // console.log('demo.onerror():', error); // recording = false; // micButton.removeClass('recording'); displayError(error); }; speech.onend = function() { console.log('demo.onend()'); recording = false; micButton.removeClass('recording'); micText.text('Press to start speaking'); }; speech.onresult = function(data) { console.log('demo.onresult()', data); showResult(data); }; micButton.click(function() { if (!recording) { speech.start(); } else { speech.stop(); micButton.removeClass('recording'); micText.text('Processing speech'); } }); function showResult(data) { //console.log(data); //if there are transcripts if (data.results && data.results.length > 0) { //if is a partial transcripts if (data.results.length === 1 ) { var paragraph = transcript.children().last(), text = data.results[0].alternatives[0].transcript || ''; console.log('text', text); //Capitalize first word text = text.charAt(0).toUpperCase() + text.substring(1); // if final results, append a new paragraph // if (data.results[0].final){ text = text.trim() + '.'; $('.loading').hide(); $('#text').append(text); // } // paragraph.text(text); } } // transcript.show(); } function displayError(error) { var message = error; try { var errorJson = JSON.parse(error); message = JSON.stringify(errorJson, null, 2); } catch (e) { message = error; } errorMsg.text(message); errorMsg.show(); transcript.hide(); } //Sample audios var audio1 = 'audio/sample1.wav', audio2 = 'audio/sample2.wav'; function _error(xhr) { $('.loading').hide(); displayError('Error processing the request, please try again.'); } function stopSounds() { $('.sample2').get(0).pause(); $('.sample2').get(0).currentTime = 0; $('.sample1').get(0).pause(); $('.sample1').get(0).currentTime = 0; } $('.audio1').click(function() { $('.audio-staged audio').attr('src', audio1); stopSounds(); $('.sample1').get(0).play(); }); $('.audio2').click(function() { $('.audio-staged audio').attr('src', audio2); stopSounds(); $('.sample2').get(0).play(); }); $('.send-api-audio1').click(function() { transcriptAudio(audio1); }); $('.send-api-audio2').click(function() { transcriptAudio(audio2); }); function showAudioResult(data){ $('.loading').hide(); transcript.empty(); $('<p></p>').appendTo(transcript); showResult(data); } // submit event function transcriptAudio(audio) { $('.loading').show(); $('.error').hide(); transcript.hide(); $('.url-input').val(audio); $('.upload-form').hide(); // Grab all form data $.ajax({ url: '/', type: 'POST', data: $('.upload-form').serialize(), success: showAudioResult, error: _error }); } var ws = new WebSocket('ws://127.0.0.1:8020/speech-to-text-beta/api/v1/recognize'); window.ws = ws; ws.onopen = function(evt) { console.log('loading'); ws.send(JSON.stringify({'action': 'start', 'content-type': 'audio/l16;rate=48000'})); }; ws.onmessage = function(evt) { console.log('msg ', evt.data); var data = JSON.parse(evt.data); showResult(data); }; ws.onerror = function(evt) { console.log('error ', evt); }; function sendDraggedFile(file) { $('.loading').show(); // var blob = new Blob(file, {type : 'audio/l16;rate=48000'}); console.log('loading blob: '); ws.send(file); ws.send(JSON.stringify({'action': 'stop'})); } function handleFileUploadEvent(evt) { console.log('uploading file'); var file = evt.dataTransfer.files[0]; var objectUrl = URL.createObjectURL(file); sendDraggedFile(file); $('.custom.sample-title').text(file.name); $('.audio3').click(function() { console.log('evt', evt); $('.sample3').prop('src', objectUrl); stopSounds(); $('.sample3').get(0).play(); }); $('.send-api-audio3').click(function() { console.log('click! API'); sendDraggedFile(file); }); } var target = $("#fileUploadTarget"); target.on('dragenter', function (e) { e.stopPropagation(); e.preventDefault(); $(this).css('border', '2px solid #0B85A1'); }); target.on('dragover', function (e) { e.stopPropagation(); e.preventDefault(); }); target.on('drop', function (e) { $(this).css('border', '2px dotted #0B85A1'); e.preventDefault(); var evt = e.originalEvent; // Handle dragged file event handleFileUploadEvent(evt); }); });
Checkpoint commit; change init method to accept content type
public/js/demo.js
Checkpoint commit; change init method to accept content type
<ide><path>ublic/js/demo.js <ide> transcript = $('#text'), <ide> errorMsg = $('.errorMsg'); <ide> <del> // Test out CORS <del> // var url = 'https://stream-d.watsonplatform.net/speech-to-text-beta/api/v1/models'; <del> // var request = new XMLHttpRequest(); <del> // request.open("GET", url, true); <del> // request.onload = function(evt) { <del> // console.log('response', request.responseText); <del> // }; <del> // request.send(); <del> <add> var speech = new SpeechRecognition({ <add> ws: 'ws://127.0.0.1:8020/speech-to-text-beta/api/v1/recognize', <add> model: 'WatsonModel' <add> }); <add> <add> speech.onresult = function(result) { <add> console.log('got a result: ', result); <add> }; <add> <add> speech.onerror = function(err) { <add> console.log('got a error: ', err); <add> }; <add> <add> // Test out library <add> var sampleUrl = 'audio/sample1.flac'; <add> var sampleRequest = new XMLHttpRequest(); <add> sampleRequest.open("GET", sampleUrl, true); <add> sampleRequest.responseType = 'blob'; <add> sampleRequest.onload = function(evt) { <add> console.log('speech started...'); <add> var blob = sampleRequest.response; <add> var trimmedBlob = blob.slice(0, 4); <add> var reader = new FileReader(); <add> reader.addEventListener("loadend", function() { <add> console.log('state', reader.readyState); <add> console.log('bytes', reader.result); <add> if (reader.result === 'fLaC') { <add> speech._init('audio/flac'); <add> } else { <add> speech._init('audio/l16;rate=48000'); <add> } <add> speech.onstart = function(evt) { <add> speech.recognize(sampleRequest.response); <add> }; <add> }); <add> reader.readAsText(trimmedBlob); <add> }; <add> sampleRequest.send(); <add> <add> // Test out token <add> var tokenUrl = '/token'; <add> var tokenRequest = new XMLHttpRequest(); <add> tokenRequest.open("GET", tokenUrl, true); <add> tokenRequest.onload = function(evt) { <add> // console.log('token ', tokenRequest.responseText); <add> // console.log('response', request.responseText); <add> // var xhr = new XMLHttpRequest(); <add> // var url = 'https://stream-d.watsonplatform.net/text-to-speech-beta/api/v1/voices'; <add> // xhr.open('GET', url, true); <add> // xhr.setRequestHeader('X-Watson-Authorization-Token', request.responseText); <add> // xhr.setRequestHeader('Authorization ', 'none'); <add> // xhr.send(); <add> // xhr.onload = function(evt) { <add> // console.log('speech data', xhr.responseText); <add> // alert('responsetext', xhr.responseText); <add> // }; <add> }; <add> tokenRequest.send(); <add> <add> var modelsUrl = '/v1/models'; <add> var modelsRequest = new XMLHttpRequest(); <add> modelsRequest.open("GET", modelsUrl, true); <add> // request.setRequestHeader('Authorization', 'Basic ' + creds); <add> modelsRequest.onload = function(evt) { <add> // console.log('token ', request.responseText); <add> }; <add> modelsRequest.send(); <ide> <ide> <ide> // Service <del> var recording = false, <del> speech = new SpeechRecognition({ <del> ws: 'ws://127.0.0.1:8020/speech-to-text-beta/api/v1/recognize', <del> model: 'WatsonModel' <del> }); <del> <del> speech.onstart = function() { <del> console.log('demo.onstart()'); <del> recording = true; <del> micButton.addClass('recording'); <del> micText.text('Press again when finished'); <del> errorMsg.hide(); <del> transcript.show(); <del> <del> // Clean the paragraphs <del> transcript.empty(); <del> $('<p></p>').appendTo(transcript); <del> }; <del> <del> speech.onerror = function(error) { <del> // console.log('demo.onerror():', error); <del> // recording = false; <del> // micButton.removeClass('recording'); <del> displayError(error); <del> }; <del> <del> speech.onend = function() { <del> console.log('demo.onend()'); <del> recording = false; <del> micButton.removeClass('recording'); <del> micText.text('Press to start speaking'); <del> }; <del> <del> speech.onresult = function(data) { <del> console.log('demo.onresult()', data); <del> showResult(data); <del> }; <del> <del> micButton.click(function() { <del> if (!recording) { <del> speech.start(); <del> } else { <del> speech.stop(); <del> micButton.removeClass('recording'); <del> micText.text('Processing speech'); <del> } <del> }); <add> // var recording = false, <add> // speech = new SpeechRecognition({ <add> // ws: 'ws://127.0.0.1:8020/speech-to-text-beta/api/v1/recognize', <add> // model: 'WatsonModel' <add> // }); <add> <add> // speech.onstart = function() { <add> // console.log('demo.onstart()'); <add> // recording = true; <add> // micButton.addClass('recording'); <add> // micText.text('Press again when finished'); <add> // errorMsg.hide(); <add> // transcript.show(); <add> // <add> // // Clean the paragraphs <add> // transcript.empty(); <add> // $('<p></p>').appendTo(transcript); <add> // }; <add> // <add> // speech.onerror = function(error) { <add> // // console.log('demo.onerror():', error); <add> // // recording = false; <add> // // micButton.removeClass('recording'); <add> // displayError(error); <add> // }; <add> // <add> // speech.onend = function() { <add> // console.log('demo.onend()'); <add> // recording = false; <add> // micButton.removeClass('recording'); <add> // micText.text('Press to start speaking'); <add> // }; <add> // <add> // speech.onresult = function(data) { <add> // console.log('demo.onresult()', data); <add> // showResult(data); <add> // }; <add> // <add> // micButton.click(function() { <add> // if (!recording) { <add> // speech.start(); <add> // } else { <add> // speech.stop(); <add> // micButton.removeClass('recording'); <add> // micText.text('Processing speech'); <add> // } <add> // }); <ide> <ide> function showResult(data) { <ide> //console.log(data); <ide> error: _error <ide> }); <ide> } <del> var ws = new WebSocket('ws://127.0.0.1:8020/speech-to-text-beta/api/v1/recognize'); <del> window.ws = ws; <del> ws.onopen = function(evt) { <del> console.log('loading'); <del> ws.send(JSON.stringify({'action': 'start', 'content-type': 'audio/l16;rate=48000'})); <del> }; <del> ws.onmessage = function(evt) { <del> console.log('msg ', evt.data); <del> var data = JSON.parse(evt.data); <del> showResult(data); <del> }; <del> <del> ws.onerror = function(evt) { <del> console.log('error ', evt); <del> }; <add> // var ws = new WebSocket('ws://127.0.0.1:8020/speech-to-text-beta/api/v1/recognize'); <add> // window.ws = ws; <add> // ws.onopen = function(evt) { <add> // console.log('loading'); <add> // ws.send(JSON.stringify({'action': 'start', 'content-type': 'audio/l16;rate=48000'})); <add> // }; <add> // <add> // ws.onmessage = function(evt) { <add> // console.log('msg ', evt.data); <add> // var data = JSON.parse(evt.data); <add> // showResult(data); <add> // }; <add> // <add> // ws.onerror = function(evt) { <add> // console.log('error ', evt); <add> // }; <ide> <ide> function sendDraggedFile(file) { <ide> $('.loading').show(); <del> // var blob = new Blob(file, {type : 'audio/l16;rate=48000'}); <ide> console.log('loading blob: '); <del> ws.send(file); <del> ws.send(JSON.stringify({'action': 'stop'})); <add> // ws.send(file); <add> // ws.send(JSON.stringify({'action': 'stop'})); <ide> } <ide> <ide> function handleFileUploadEvent(evt) { <ide> e.preventDefault(); <ide> $(this).css('border', '2px solid #0B85A1'); <ide> }); <add> <ide> target.on('dragover', function (e) { <ide> e.stopPropagation(); <ide> e.preventDefault(); <ide> }); <add> <ide> target.on('drop', function (e) { <ide> <ide> $(this).css('border', '2px dotted #0B85A1');
JavaScript
apache-2.0
7bd15a439002d8ec322d964f9446ef7763f04265
0
mobyourlife/mobv3,mobyourlife/mobv3,mobyourlife/mobv3
'use strict'; var FB = require('fb'); var moment = require('moment'); var unirest = require('unirest'); var URL = require('url-parse'); var ua = require('universal-analytics'); var Domain = require('../../models/domain'); var Fanpage = require('../../models/fanpage'); var Feed = require('../../models/feed'); var Ticket = require('../../models/ticket'); var TextPage = require('../../models/textpage'); var Album = require('../../models/album'); var Photo = require('../../models/photo'); var Video = require('../../models/video'); var Update = require('../../models/update'); var Email = require('../../models/email'); var User = require('../../models/user'); var email = require('../../lib/email')(); var sync = require('../../lib/sync')(); var pagamento = require('../../lib/pagamento'); var themes = require('../../lib/old-themes'); //var RTU = require('../../lib/realtime'); var AdminPerms = require('../../lib/admin-perms'); /* jobs to be run after new website creation */ var jobs = []; jobs.push(require('../../jobs/new-site-created')); jobs.push(require('../../jobs/update-page-info')); jobs.push(require('../../jobs/update-profile-picture')); jobs.push(require('../../jobs/sync-feeds')); jobs.push(require('../../jobs/sync-albums')); var runJobs = function () { for(i = 0; i < jobs.length; i += 1) { var cur = jobs[i]; if (cur) { console.log('Checking conditions for job "' + cur.jobName + '"...'); cur.checkConditions(function (job, status, model) { console.log(status ? ' [OK] Running job "' + job.jobName + '"...' : ' [NOPE] Job "' + job.jobName + '" will not run.'); job.doWork(model, function() { console.log(' [DONE] Finished job "' + job.jobName + '.'); }); }); } } } module.exports = function (router) { /* [retro ok] */ var validateSubdomain = function(uri, res, callbackTop, callbackSubdomain) { /* TODO: localizar para o idioma do site */ moment.locale('pt-br'); var parsed = uri ? new URL(uri) : null; var hostname = parsed ? parsed.hostname : null; console.log('hostname = ' + hostname); if (!hostname || hostname == 'www.mobyourlife.com.br') { callbackTop(); } else { Domain.findOne({ '_id': hostname }, function(err, found) { if (found) { Fanpage.findOne({'_id': found.ref}, function(err, found) { if (found) { var fanpage = found; callbackSubdomain(fanpage); } else { res.redirect('http://www.mobyourlife.com.br'); } }); } else { res.redirect('http://www.mobyourlife.com.br'); } }); } } /* [retro ok] */ var enableCors = function(req, res, next) { if (req.headers.origin) { validateSubdomain(req.headers.origin, res, function() { next(); }, function(fanpage) { req.fanpage = fanpage; res.header('Access-Control-Allow-Origin', req.headers.origin); res.header('Access-Control-Allow-Credentials', true); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); next(); }); } else { next(); } } /* api method to list all user created sites */ router.get('/my-sites', function (req, res) { if (req.isAuthenticated() && req.user && req.user.fanpages) { var list = Array(); for(var i = 0; i < req.user.fanpages.length; i++) { list.push(req.user.fanpages[i].id); } Fanpage.find({ _id: { $in: list } }).sort({ 'facebook.name': 1 }).exec(function(err, rows) { if (err) { console.log(err); } var model = { sites: rows }; res.send(model); }); } else { res.status(401).send(); } }); /* api method to list all user billing tickets */ router.get('/billing', function (req, res) { if (req.isAuthenticated() && req.user && req.user.fanpages) { var list = Array(); var names = Array(); for(var i = 0; i < req.user.fanpages.length; i++) { list.push(req.user.fanpages[i].id); names[req.user.fanpages[i].id] = req.user.fanpages[i].name; } Ticket.find({ ref: { $in: list } }).sort({ 'time': -1 }).exec(function(err, rows) { var ret = Array(); for (var j = 0; j < rows.length; j++) { ret.push({ fanpage: { id: rows[j].ref, name: names[rows[j].ref] }, ticket: rows[j] }); } res.status(200).send({ tickets: ret }); }); } }); /* api method to list all user fanpages without sites */ router.get('/remaining-fanpages', function (req, res) { if (req.isAuthenticated() && req.user && req.user.fanpages) { FB.setAccessToken(req.user.facebook.token); FB.api('/me/permissions', function(records) { var required = ['public_profile', 'email', 'manage_pages']; var pending = []; for (var i = 0; i < records.data.length; i++) { var perm = records.data[i]; if (required.indexOf(perm.permission) != -1) { if (perm.status != 'granted') { switch (perm.permission) { case 'public_profile': pending.push('Perfil público'); break; case 'email': pending.push('Endereço de email'); break; case 'manage_pages': pending.push('Gerenciar páginas'); break; default: break; } } } } if (pending.length != 0) { res.status(401).send({ pending: pending }); return; } FB.api('/me/accounts', { locale: 'pt_BR', fields: ['id', 'name', 'about', 'link', 'picture'] }, function(records) { if (records.data) { var pages_list = Array(); var ids_list = Array(); for (var r = 0; r < records.data.length; r++) { var item = { id: records.data[r].id, name: records.data[r].name, about: records.data[r].about, link: records.data[r].link, picture: records.data[r].picture.data.url }; pages_list.push(item); ids_list.push(records.data[r].id); } pages_list.sort(function(a, b) { var x = a.name.toLowerCase(), y = b.name.toLowerCase(); if (x < y) return -1; if (x > y) return 1; return 0; }); Fanpage.find({ _id: { $in: ids_list } }, function(err, records) { var built_list = Array(); if (records) { for (i = 0; i < pages_list.length; i++) { var existe = false; for (var j = 0; j < records.length; j++) { if (pages_list[i].id == records[j]._id) { existe = true; } } if (existe === false) { built_list.push(pages_list[i]); } } } else { built_list = pages_list; } res.status(200).send({ pages: built_list }); }); } }); }); } }); /* new website creation */ router.get('/create-new-website/:pageid', function (req, res) { if (req.isAuthenticated()) { FB.setAccessToken(req.user.facebook.token); FB.api('/' + req.params.pageid, { locale: 'pt_BR', fields: ['id', 'name', 'about', 'link', 'picture', 'access_token'] }, function(records) { if (records) { FB.setAccessToken(records.access_token); FB.api('/v2.2/' + records.id + '/subscribed_apps', 'post', function(ret) { Fanpage.findOne({ _id : records.id }, function(err, found) { var newFanpage = null; if (found) { newFanpage = found; } else { newFanpage = new Fanpage(); newFanpage.facebook.name = records.name; newFanpage.facebook.about = records.about; newFanpage.facebook.link = records.link; newFanpage.url = newFanpage.facebook.name.toLowerCase().replace(/[^a-zA-Z0-9]/g, '') + '.meusitemob.com.br'; if (records.picture && records.picture.data) { newFanpage.facebook.picture = records.picture.data.url; } /* creation info */ newFanpage.creation.time = Date.now(); newFanpage.creation.user = req.user; /* billing info */ var ticket = new Ticket(); ticket.ref = newFanpage._id; ticket.time = Date.now(); ticket.status = 'freebie'; ticket.validity.months = 0; ticket.validity.days = 15; newFanpage.billing.active = true; newFanpage.billing.evaluation = true; newFanpage.billing.expiration = moment() .add(ticket.validity.months, 'months') .add(ticket.validity.days, 'days'); ticket.save(function(err) { if (err) { console.log('Error creating ticket!'); console.log(ticket); throw err; } }); } // save the new fanpage to the database Fanpage.update({ _id: records.id }, newFanpage.toObject(), { upsert: true }, function(err) { if (err) { console.log('Error creating fanpage!'); console.log(newFanpage); throw err; } // create default subdomain var domain = new Domain(); domain.ref = records.id; domain.status = 'registered'; domain.creation.time = Date.now(); domain.creation.user = req.user; Domain.update({ _id: newFanpage.url }, domain.toObject(), { upsert: true }, function(err) { if (err) { console.log('Error creating domain!'); console.log(domain); throw err; } runJobs(); res.status(200).send({ url: domain._id }); }); }); }); }); } else { res.status(400).send(); } }); } }); /* api method to get details about a single user site */ router.get('/manage-site/:pageid', function (req, res) { if (req.isAuthenticated()) { Fanpage.findOne({ _id: req.params.pageid }, function(err, model) { if (err) { console.log(err); } res.send(model); }); } else { res.status(401).send(); } }); router.post('/customise-site', function (req, res) { if (req.isAuthenticated()) { Fanpage.update({ _id: req.body.pageid }, { 'custom.display_name': req.body.data.display_name, 'custom.about_page': req.body.data.about_page, 'theme.name': 'default', 'theme.colour': req.body.colour }, function (err) { if (err) { throw err; res.status(500).send(); return; } res.send(); }); } else { res.status(401).send(); } }); /* website creation wizard */ router.get('/wizard/website-created/:pageid', function (req, res) { if (req.isAuthenticated()) { Fanpage.update({ _id: req.params.pageid }, { 'wizard.current_step': 2, 'wizard.site_created': true }, function (err) { if (err) { console.log(err); } res.send(); }); } }); router.get('/wizard/personal-touch/:pageid/:colour', function (req, res) { if (req.isAuthenticated()) { Fanpage.update({ _id: req.params.pageid }, { 'wizard.current_step': 3, 'wizard.personal_touch': true, 'theme.name': 'default', 'theme.colour': req.params.colour }, function (err) { if (err) { console.log(err); } res.send(); }); } }); router.get('/wizard/website-shared/:pageid', function (req, res) { if (req.isAuthenticated()) { Fanpage.update({ _id: req.params.pageid }, { 'wizard.current_step': 4, 'wizard.share_it': true }, function (err) { if (err) { console.log(err); } res.send(); }); } }); router.get('/wizard/website-finished/:pageid', function (req, res) { if (req.isAuthenticated()) { Fanpage.update({ _id: req.params.pageid }, { 'wizard.current_step': 5, 'wizard.finished': true }, function (err) { if (err) { console.log(err); } res.send(); }); } }); /* api method to list all sites from all users */ router.get('/all-sites', function (req, res) { if (req.isAuthenticated() && req.user && req.user.id != 0) { Fanpage.find().sort({ 'facebook.name': 1 }).exec(function(err, rows) { if (err) { console.log(err); } var model = { sites: rows }; res.send(model); }); } else { res.status(401).send(); } }); /* api method to get all available stats */ router.get('/stats', function (req, res) { if (req.isAuthenticated() && req.user && req.user.id != 0) { var data = { fanpage_errors: 0, album_errors: 0 }; Fanpage.find({ 'error': { $exists: true } }).count().exec(function(err, result) { data.fanpage_errors = result; Album.find({ 'error': { $exists: true } }).count().exec(function(err, result) { data.album_errors = result; res.send(data); }); }); } else { res.status(401).send(); } }); /* api method to look for latest statistics about sites creation */ router.get('/latest-stats', function (req, res) { if (req.isAuthenticated()) { Fanpage.find().limit(1).sort({ 'creation.time': -1 }).exec(function(err, latest) { if (err) { console.log(err); } Fanpage.count().exec(function(err, count) { if (err) { console.log(err); } var model = { site: latest[0], count: count }; res.send(model); }); }); } else { res.status(401).send(); } }); /* whois method */ router.get('/whois/:domain', function (req, res) { if (req.isAuthenticated()) { unirest.get('https://whois.apitruck.com/' + req.params.domain) .headers({ 'Accept': 'application/json' }) .end(function (response) { if (response && response.body && response.body.response && response.body.response.registered == false) { res.status(200).send(); } else { res.status(500).send(); } } ); } else { res.status(401).send(); } }); /* send mail method */ router.post('/sendmail', function (req, res) { if (req.isAuthenticated()) { var subject = req.body.message.length > 20 ? req.body.message.substr(0, 20) : req.body.message; email.enviarEmail(req.body.name, req.body.email, subject, req.body.message, '[email protected]', function() { res.status(200).send(); }, function(err) { console.log(err); res.status(500).send({ responseCode: err.responseCode, response: err.response }); }); } }); /* register domain method */ router.post('/register-domain', function (req, res) { if (req.isAuthenticated()) { var find = { _id: req.body.domain, ref: req.body.pageid }; var item = { _id: req.body.domain, ref: req.body.pageid, status: 'waiting', 'creation.time': Date.now(), 'creation.user': req.user._id }; Domain.update(find, item, { upsert: true }, function(err) { if (err) { res.status(500).send(); } else { res.status(200).send(); } }); } }); /* api method to list all user websites registered domains */ router.get('/my-domains', function (req, res) { if (req.isAuthenticated() && req.user && req.user.fanpages) { var list = Array(); var names = Array(); for(var i = 0; i < req.user.fanpages.length; i++) { list.push(req.user.fanpages[i].id); names[req.user.fanpages[i].id] = req.user.fanpages[i].name; } Domain.find({ ref: { $in: list } }).sort({ '_id': 1 }).exec(function(err, rows) { var ret = Array(); for (var j = 0; j < rows.length; j++) { ret.push({ fanpage: { id: rows[j].ref, name: names[rows[j].ref] }, domain: rows[j] }); } res.status(200).send({ domains: ret }); }); } }); /* api to register in the newsletter */ router.post('/register-newsletter', function (req, res) { Email.update({ email: req.body.emailAddress }, { email: req.body.emailAddress }, { upsert: true }, function(err, records) { if (err) { console.log(err); res.status(500).send(); return; } res.status(200).send(); }); }); /* api method to call for payment */ router.post('/make-payment', function (req, res) { if (req.isAuthenticated()) { Fanpage.findOne({ _id: req.body.pageid }, function(err, fanpage) { if (err) { console.log(err); } pagamento(req.user, fanpage, 999.90, function(uri) { res.status(200).send({ uri: uri }); }, function() { res.status(500).send(); }); }); } }); /* OLD API BEGINNING */ // [should be retro ok] enviar foto de capa router.post('/upload-cover', enableCors, function(req, res) { var form = new formidable.IncomingForm(), height = 0, cover = null; //if (app.get('env') === 'development') { // form.uploadDir = './public/uploads'; //} else { form.uploadDir = '/var/www/mob/public/uploads'; //} form.keepExtensions = true; form .on('field', function(field, value) { if (field === 'height') { height = value; } }) .on('file', function(field, file) { if (field === 'cover') { cover = file; } }) .on('end', function() { var patharr = cover.path.indexOf('\\') != -1 ? cover.path.split('\\') : cover.path.split('/'); var path = patharr[patharr.length - 1]; Fanpage.update({ _id: req.fanpage._id }, { cover: height != 0 ? { path: path, height: height } : null }, { upsert: true}, function(err) { if (err) throw err; res.redirect(req.headers.referer); }); }); form.parse(req); }); // api para gerenciar álbuns router.post('/set-album', enableCors, function(req, res) { if (req.isAuthenticated()) { if (req.body.album_id && req.body.special_type) { Album.findOne({ _id: req.body.album_id }, function(err, one) { if (err) throw err; var proceed = false; for (var i = 0; i < req.user.fanpages.length; i++) { if (req.user.fanpages[i].id.toString().localeCompare(one.ref.toString()) === 0) { proceed = true; break; } } if (proceed) { var saveit = function() { Album.update({ _id: req.body.album_id }, { special: req.body.special_type }, function(err) { if (err) throw err; res.status(200).send(); }); }; if (req.body.special_type === 'banner') { Album.update({ ref: one.ref, special: 'banner' }, { special: 'default' }, function(err) { if (err) throw err; saveit(); }); } else { saveit(); } } else { res.status(403).send(); } }); } else { res.status(402).send(); } } }); /* [retro ok] api para sincronização de login */ router.get('/login', enableCors, function(req, res) { if (req.isAuthenticated() && req.headers.referer) { var parsed = new URL(req.headers.referer); if (AdminPerms.isAdmin(req.user)) { res.send({ auth: true, uid: req.user._id, name: req.user.facebook.name, email: req.user.facebook.email, picture: req.user.facebook.picture, csrf: res.locals._csrf }); return; } Domain.findOne({ '_id': parsed.hostname }, function(err, domain) { if (err) { throw err; } if (domain) { User.findOne({ _id: req.user._id, 'fanpages.id': domain.ref }, function (err, user) { if (err) { throw err; } if (user) { res.send({ auth: true, uid: req.user._id, name: req.user.facebook.name, email: req.user.facebook.email, picture: req.user.facebook.picture, csrf: res.locals._csrf }); return; } else { res.status(401).send({ auth: false }); } }); } else { res.status(401).send({ auth: false }); } }); } else { res.status(401).send({ auth: false }); } }); /* [retro ok] api para consulta do feed */ router.get('/feeds/:before?', enableCors, function(req, res) { var filter = { ref: req.fanpage._id }; if (req.params.before) { filter.time = { $lte: moment.unix(req.params.before).format() }; } Feed.find(filter).limit(5).sort('-time').exec(function(err, found) { for (var i = 0; i < found.length; i++) { found[i].unix = moment(found[i].time).unix(); found[i].fromNow = moment(found[i].time).fromNow(); found[i].timelineInverted = ((i % 2) == 0 ? '' : 'timeline-inverted'); found[i].isVideo = (found[i].type == 'video'); found[i].videoLink = null; found[i].imageLink = null; if (found[i].isVideo) { if (found[i].link.indexOf('youtube') != -1) { var link = found[i].link; link = link.replace('m.youtube.com/watch?v=', 'youtube.com/embed/'); link = link.replace('youtube.com/watch?v=', 'youtube.com/embed/'); found[i].videoLink = link; found[i].embedIframe = true; } else { found[i].videoLink = found[i].source; found[i].embedIframe = false; } } else { if (found[i].cdn) { found[i].imageLink = found[i].cdn; } else if (found[i].source) { found[i].imageLink = found[i].source; } else { found[i].imageLink = found[i].picture; } } found[i].textName = (found[i].name ? found[i].name : null); found[i].textMessage = (found[i].message ? found[i].message : found[i].description); found[i].hasHeader = (found[i].videoLink != null || found[i].imageLink != null); found[i].hasBody = (found[i].textName != null || found[i].textMessage); if (found[i].textMessage) { found[i].textMessage = found[i].textMessage.replace('\n', '<br/>'); } } res.render('api-feeds', { feeds: found }); }); }); /* [retro ok] api para consulta das fotos */ router.get('/fotos/:before?', enableCors, function(req, res) { var filter = { ref: req.fanpage._id }; if (req.params.before) { filter.time = { $lte: moment.unix(req.params.before).format() }; } Album.find({ ref: req.fanpage._id, special: { '$in': [null, 'default'] } }, function(err, list) { var albums = []; if (list) { for (var i = 0; i < list.length; i++) { albums.push(list[i]._id); } } filter.album_id = { '$in': albums }; Photo.find(filter).limit(15).sort('-time').exec(function(err, found) { res.status(200).send({ fotos: found }); }); }); }); /* [retro ok] */ router.get('/fotos-:album/:before?', enableCors, function(req, res) { var filter = { ref: req.fanpage._id }; if (req.params.before) { filter.time = { $lte: moment.unix(req.params.before).format() }; } Album.findOne({ ref: req.fanpage._id, path: req.params.album }, function(err, one) { if (one) { filter.album_id = one._id; Photo.find(filter).limit(15).sort('-time').exec(function(err, found) { res.send({ fotos: found }); }); } }); }); /* [retro ok] api para consulta dos vídeos */ router.get('/videos/:before?', enableCors, function(req, res) { var filter = { ref: req.fanpage._id }; if (req.params.before) { filter.time = { $lte: moment.unix(req.params.before).format() }; } Video.find(filter).limit(15).sort('-time').exec(function(err, found) { res.send({ videos: found }); }); }); /* [should be retro ok] atualizações em tempo real do Facebook * / router.get('/facebook/realtime', function(req, res) { console.log('Realtime updates verification request received.'); if (req.query['hub.mode'] === 'subscribe') { if (req.query['hub.verify_token'] === '123456') { console.log('Challenge answered.'); res.send(req.query['hub.challenge']); return; } } res.status(500).send(); }); /* [should be retro ok] * / router.post('/facebook/realtime', function(req, res) { var update = new Update(); update.time = Date.now(); update.data = req.body; update.save(function(err, data) { if (err) throw err; RTU.syncPending(); }); res.status(200).send(); }); */ router.get('/pagseguro/callback', function(req, res) { var visitor = ua('UA-52753958-4'); visitor.event('billing', 'finish-payment', '', 999.90).send(); res.redirect('/account/login'); }); /* OLD API END */ };
core/controllers/api/index.js
'use strict'; var FB = require('fb'); var moment = require('moment'); var unirest = require('unirest'); var URL = require('url-parse'); var ua = require('universal-analytics'); var Domain = require('../../models/domain'); var Fanpage = require('../../models/fanpage'); var Feed = require('../../models/feed'); var Ticket = require('../../models/ticket'); var TextPage = require('../../models/textpage'); var Album = require('../../models/album'); var Photo = require('../../models/photo'); var Video = require('../../models/video'); var Update = require('../../models/update'); var Email = require('../../models/email'); var User = require('../../models/user'); var email = require('../../lib/email')(); var sync = require('../../lib/sync')(); var pagamento = require('../../lib/pagamento'); var themes = require('../../lib/old-themes'); //var RTU = require('../../lib/realtime'); var AdminPerms = require('../../lib/admin-perms'); /* jobs to be run after new website creation */ var jobs = []; jobs.push(require('./jobs/new-site-created')); jobs.push(require('./jobs/update-page-info')); jobs.push(require('./jobs/update-profile-picture')); jobs.push(require('./jobs/sync-feeds')); jobs.push(require('./jobs/sync-albums')); var runJobs = function () { for(i = 0; i < jobs.length; i += 1) { var cur = jobs[i]; if (cur) { console.log('Checking conditions for job "' + cur.jobName + '"...'); cur.checkConditions(function (job, status, model) { console.log(status ? ' [OK] Running job "' + job.jobName + '"...' : ' [NOPE] Job "' + job.jobName + '" will not run.'); job.doWork(model, function() { console.log(' [DONE] Finished job "' + job.jobName + '.'); }); }); } } } module.exports = function (router) { /* [retro ok] */ var validateSubdomain = function(uri, res, callbackTop, callbackSubdomain) { /* TODO: localizar para o idioma do site */ moment.locale('pt-br'); var parsed = uri ? new URL(uri) : null; var hostname = parsed ? parsed.hostname : null; console.log('hostname = ' + hostname); if (!hostname || hostname == 'www.mobyourlife.com.br') { callbackTop(); } else { Domain.findOne({ '_id': hostname }, function(err, found) { if (found) { Fanpage.findOne({'_id': found.ref}, function(err, found) { if (found) { var fanpage = found; callbackSubdomain(fanpage); } else { res.redirect('http://www.mobyourlife.com.br'); } }); } else { res.redirect('http://www.mobyourlife.com.br'); } }); } } /* [retro ok] */ var enableCors = function(req, res, next) { if (req.headers.origin) { validateSubdomain(req.headers.origin, res, function() { next(); }, function(fanpage) { req.fanpage = fanpage; res.header('Access-Control-Allow-Origin', req.headers.origin); res.header('Access-Control-Allow-Credentials', true); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); next(); }); } else { next(); } } /* api method to list all user created sites */ router.get('/my-sites', function (req, res) { if (req.isAuthenticated() && req.user && req.user.fanpages) { var list = Array(); for(var i = 0; i < req.user.fanpages.length; i++) { list.push(req.user.fanpages[i].id); } Fanpage.find({ _id: { $in: list } }).sort({ 'facebook.name': 1 }).exec(function(err, rows) { if (err) { console.log(err); } var model = { sites: rows }; res.send(model); }); } else { res.status(401).send(); } }); /* api method to list all user billing tickets */ router.get('/billing', function (req, res) { if (req.isAuthenticated() && req.user && req.user.fanpages) { var list = Array(); var names = Array(); for(var i = 0; i < req.user.fanpages.length; i++) { list.push(req.user.fanpages[i].id); names[req.user.fanpages[i].id] = req.user.fanpages[i].name; } Ticket.find({ ref: { $in: list } }).sort({ 'time': -1 }).exec(function(err, rows) { var ret = Array(); for (var j = 0; j < rows.length; j++) { ret.push({ fanpage: { id: rows[j].ref, name: names[rows[j].ref] }, ticket: rows[j] }); } res.status(200).send({ tickets: ret }); }); } }); /* api method to list all user fanpages without sites */ router.get('/remaining-fanpages', function (req, res) { if (req.isAuthenticated() && req.user && req.user.fanpages) { FB.setAccessToken(req.user.facebook.token); FB.api('/me/permissions', function(records) { var required = ['public_profile', 'email', 'manage_pages']; var pending = []; for (var i = 0; i < records.data.length; i++) { var perm = records.data[i]; if (required.indexOf(perm.permission) != -1) { if (perm.status != 'granted') { switch (perm.permission) { case 'public_profile': pending.push('Perfil público'); break; case 'email': pending.push('Endereço de email'); break; case 'manage_pages': pending.push('Gerenciar páginas'); break; default: break; } } } } if (pending.length != 0) { res.status(401).send({ pending: pending }); return; } FB.api('/me/accounts', { locale: 'pt_BR', fields: ['id', 'name', 'about', 'link', 'picture'] }, function(records) { if (records.data) { var pages_list = Array(); var ids_list = Array(); for (var r = 0; r < records.data.length; r++) { var item = { id: records.data[r].id, name: records.data[r].name, about: records.data[r].about, link: records.data[r].link, picture: records.data[r].picture.data.url }; pages_list.push(item); ids_list.push(records.data[r].id); } pages_list.sort(function(a, b) { var x = a.name.toLowerCase(), y = b.name.toLowerCase(); if (x < y) return -1; if (x > y) return 1; return 0; }); Fanpage.find({ _id: { $in: ids_list } }, function(err, records) { var built_list = Array(); if (records) { for (i = 0; i < pages_list.length; i++) { var existe = false; for (var j = 0; j < records.length; j++) { if (pages_list[i].id == records[j]._id) { existe = true; } } if (existe === false) { built_list.push(pages_list[i]); } } } else { built_list = pages_list; } res.status(200).send({ pages: built_list }); }); } }); }); } }); /* new website creation */ router.get('/create-new-website/:pageid', function (req, res) { if (req.isAuthenticated()) { FB.setAccessToken(req.user.facebook.token); FB.api('/' + req.params.pageid, { locale: 'pt_BR', fields: ['id', 'name', 'about', 'link', 'picture', 'access_token'] }, function(records) { if (records) { FB.setAccessToken(records.access_token); FB.api('/v2.2/' + records.id + '/subscribed_apps', 'post', function(ret) { Fanpage.findOne({ _id : records.id }, function(err, found) { var newFanpage = null; if (found) { newFanpage = found; } else { newFanpage = new Fanpage(); newFanpage.facebook.name = records.name; newFanpage.facebook.about = records.about; newFanpage.facebook.link = records.link; newFanpage.url = newFanpage.facebook.name.toLowerCase().replace(/[^a-zA-Z0-9]/g, '') + '.meusitemob.com.br'; if (records.picture && records.picture.data) { newFanpage.facebook.picture = records.picture.data.url; } /* creation info */ newFanpage.creation.time = Date.now(); newFanpage.creation.user = req.user; /* billing info */ var ticket = new Ticket(); ticket.ref = newFanpage._id; ticket.time = Date.now(); ticket.status = 'freebie'; ticket.validity.months = 0; ticket.validity.days = 15; newFanpage.billing.active = true; newFanpage.billing.evaluation = true; newFanpage.billing.expiration = moment() .add(ticket.validity.months, 'months') .add(ticket.validity.days, 'days'); ticket.save(function(err) { if (err) { console.log('Error creating ticket!'); console.log(ticket); throw err; } }); } // save the new fanpage to the database Fanpage.update({ _id: records.id }, newFanpage.toObject(), { upsert: true }, function(err) { if (err) { console.log('Error creating fanpage!'); console.log(newFanpage); throw err; } // create default subdomain var domain = new Domain(); domain.ref = records.id; domain.status = 'registered'; domain.creation.time = Date.now(); domain.creation.user = req.user; Domain.update({ _id: newFanpage.url }, domain.toObject(), { upsert: true }, function(err) { if (err) { console.log('Error creating domain!'); console.log(domain); throw err; } runJobs(); res.status(200).send({ url: domain._id }); }); }); }); }); } else { res.status(400).send(); } }); } }); /* api method to get details about a single user site */ router.get('/manage-site/:pageid', function (req, res) { if (req.isAuthenticated()) { Fanpage.findOne({ _id: req.params.pageid }, function(err, model) { if (err) { console.log(err); } res.send(model); }); } else { res.status(401).send(); } }); router.post('/customise-site', function (req, res) { if (req.isAuthenticated()) { Fanpage.update({ _id: req.body.pageid }, { 'custom.display_name': req.body.data.display_name, 'custom.about_page': req.body.data.about_page, 'theme.name': 'default', 'theme.colour': req.body.colour }, function (err) { if (err) { throw err; res.status(500).send(); return; } res.send(); }); } else { res.status(401).send(); } }); /* website creation wizard */ router.get('/wizard/website-created/:pageid', function (req, res) { if (req.isAuthenticated()) { Fanpage.update({ _id: req.params.pageid }, { 'wizard.current_step': 2, 'wizard.site_created': true }, function (err) { if (err) { console.log(err); } res.send(); }); } }); router.get('/wizard/personal-touch/:pageid/:colour', function (req, res) { if (req.isAuthenticated()) { Fanpage.update({ _id: req.params.pageid }, { 'wizard.current_step': 3, 'wizard.personal_touch': true, 'theme.name': 'default', 'theme.colour': req.params.colour }, function (err) { if (err) { console.log(err); } res.send(); }); } }); router.get('/wizard/website-shared/:pageid', function (req, res) { if (req.isAuthenticated()) { Fanpage.update({ _id: req.params.pageid }, { 'wizard.current_step': 4, 'wizard.share_it': true }, function (err) { if (err) { console.log(err); } res.send(); }); } }); router.get('/wizard/website-finished/:pageid', function (req, res) { if (req.isAuthenticated()) { Fanpage.update({ _id: req.params.pageid }, { 'wizard.current_step': 5, 'wizard.finished': true }, function (err) { if (err) { console.log(err); } res.send(); }); } }); /* api method to list all sites from all users */ router.get('/all-sites', function (req, res) { if (req.isAuthenticated() && req.user && req.user.id != 0) { Fanpage.find().sort({ 'facebook.name': 1 }).exec(function(err, rows) { if (err) { console.log(err); } var model = { sites: rows }; res.send(model); }); } else { res.status(401).send(); } }); /* api method to get all available stats */ router.get('/stats', function (req, res) { if (req.isAuthenticated() && req.user && req.user.id != 0) { var data = { fanpage_errors: 0, album_errors: 0 }; Fanpage.find({ 'error': { $exists: true } }).count().exec(function(err, result) { data.fanpage_errors = result; Album.find({ 'error': { $exists: true } }).count().exec(function(err, result) { data.album_errors = result; res.send(data); }); }); } else { res.status(401).send(); } }); /* api method to look for latest statistics about sites creation */ router.get('/latest-stats', function (req, res) { if (req.isAuthenticated()) { Fanpage.find().limit(1).sort({ 'creation.time': -1 }).exec(function(err, latest) { if (err) { console.log(err); } Fanpage.count().exec(function(err, count) { if (err) { console.log(err); } var model = { site: latest[0], count: count }; res.send(model); }); }); } else { res.status(401).send(); } }); /* whois method */ router.get('/whois/:domain', function (req, res) { if (req.isAuthenticated()) { unirest.get('https://whois.apitruck.com/' + req.params.domain) .headers({ 'Accept': 'application/json' }) .end(function (response) { if (response && response.body && response.body.response && response.body.response.registered == false) { res.status(200).send(); } else { res.status(500).send(); } } ); } else { res.status(401).send(); } }); /* send mail method */ router.post('/sendmail', function (req, res) { if (req.isAuthenticated()) { var subject = req.body.message.length > 20 ? req.body.message.substr(0, 20) : req.body.message; email.enviarEmail(req.body.name, req.body.email, subject, req.body.message, '[email protected]', function() { res.status(200).send(); }, function(err) { console.log(err); res.status(500).send({ responseCode: err.responseCode, response: err.response }); }); } }); /* register domain method */ router.post('/register-domain', function (req, res) { if (req.isAuthenticated()) { var find = { _id: req.body.domain, ref: req.body.pageid }; var item = { _id: req.body.domain, ref: req.body.pageid, status: 'waiting', 'creation.time': Date.now(), 'creation.user': req.user._id }; Domain.update(find, item, { upsert: true }, function(err) { if (err) { res.status(500).send(); } else { res.status(200).send(); } }); } }); /* api method to list all user websites registered domains */ router.get('/my-domains', function (req, res) { if (req.isAuthenticated() && req.user && req.user.fanpages) { var list = Array(); var names = Array(); for(var i = 0; i < req.user.fanpages.length; i++) { list.push(req.user.fanpages[i].id); names[req.user.fanpages[i].id] = req.user.fanpages[i].name; } Domain.find({ ref: { $in: list } }).sort({ '_id': 1 }).exec(function(err, rows) { var ret = Array(); for (var j = 0; j < rows.length; j++) { ret.push({ fanpage: { id: rows[j].ref, name: names[rows[j].ref] }, domain: rows[j] }); } res.status(200).send({ domains: ret }); }); } }); /* api to register in the newsletter */ router.post('/register-newsletter', function (req, res) { Email.update({ email: req.body.emailAddress }, { email: req.body.emailAddress }, { upsert: true }, function(err, records) { if (err) { console.log(err); res.status(500).send(); return; } res.status(200).send(); }); }); /* api method to call for payment */ router.post('/make-payment', function (req, res) { if (req.isAuthenticated()) { Fanpage.findOne({ _id: req.body.pageid }, function(err, fanpage) { if (err) { console.log(err); } pagamento(req.user, fanpage, 999.90, function(uri) { res.status(200).send({ uri: uri }); }, function() { res.status(500).send(); }); }); } }); /* OLD API BEGINNING */ // [should be retro ok] enviar foto de capa router.post('/upload-cover', enableCors, function(req, res) { var form = new formidable.IncomingForm(), height = 0, cover = null; //if (app.get('env') === 'development') { // form.uploadDir = './public/uploads'; //} else { form.uploadDir = '/var/www/mob/public/uploads'; //} form.keepExtensions = true; form .on('field', function(field, value) { if (field === 'height') { height = value; } }) .on('file', function(field, file) { if (field === 'cover') { cover = file; } }) .on('end', function() { var patharr = cover.path.indexOf('\\') != -1 ? cover.path.split('\\') : cover.path.split('/'); var path = patharr[patharr.length - 1]; Fanpage.update({ _id: req.fanpage._id }, { cover: height != 0 ? { path: path, height: height } : null }, { upsert: true}, function(err) { if (err) throw err; res.redirect(req.headers.referer); }); }); form.parse(req); }); // api para gerenciar álbuns router.post('/set-album', enableCors, function(req, res) { if (req.isAuthenticated()) { if (req.body.album_id && req.body.special_type) { Album.findOne({ _id: req.body.album_id }, function(err, one) { if (err) throw err; var proceed = false; for (var i = 0; i < req.user.fanpages.length; i++) { if (req.user.fanpages[i].id.toString().localeCompare(one.ref.toString()) === 0) { proceed = true; break; } } if (proceed) { var saveit = function() { Album.update({ _id: req.body.album_id }, { special: req.body.special_type }, function(err) { if (err) throw err; res.status(200).send(); }); }; if (req.body.special_type === 'banner') { Album.update({ ref: one.ref, special: 'banner' }, { special: 'default' }, function(err) { if (err) throw err; saveit(); }); } else { saveit(); } } else { res.status(403).send(); } }); } else { res.status(402).send(); } } }); /* [retro ok] api para sincronização de login */ router.get('/login', enableCors, function(req, res) { if (req.isAuthenticated() && req.headers.referer) { var parsed = new URL(req.headers.referer); if (AdminPerms.isAdmin(req.user)) { res.send({ auth: true, uid: req.user._id, name: req.user.facebook.name, email: req.user.facebook.email, picture: req.user.facebook.picture, csrf: res.locals._csrf }); return; } Domain.findOne({ '_id': parsed.hostname }, function(err, domain) { if (err) { throw err; } if (domain) { User.findOne({ _id: req.user._id, 'fanpages.id': domain.ref }, function (err, user) { if (err) { throw err; } if (user) { res.send({ auth: true, uid: req.user._id, name: req.user.facebook.name, email: req.user.facebook.email, picture: req.user.facebook.picture, csrf: res.locals._csrf }); return; } else { res.status(401).send({ auth: false }); } }); } else { res.status(401).send({ auth: false }); } }); } else { res.status(401).send({ auth: false }); } }); /* [retro ok] api para consulta do feed */ router.get('/feeds/:before?', enableCors, function(req, res) { var filter = { ref: req.fanpage._id }; if (req.params.before) { filter.time = { $lte: moment.unix(req.params.before).format() }; } Feed.find(filter).limit(5).sort('-time').exec(function(err, found) { for (var i = 0; i < found.length; i++) { found[i].unix = moment(found[i].time).unix(); found[i].fromNow = moment(found[i].time).fromNow(); found[i].timelineInverted = ((i % 2) == 0 ? '' : 'timeline-inverted'); found[i].isVideo = (found[i].type == 'video'); found[i].videoLink = null; found[i].imageLink = null; if (found[i].isVideo) { if (found[i].link.indexOf('youtube') != -1) { var link = found[i].link; link = link.replace('m.youtube.com/watch?v=', 'youtube.com/embed/'); link = link.replace('youtube.com/watch?v=', 'youtube.com/embed/'); found[i].videoLink = link; found[i].embedIframe = true; } else { found[i].videoLink = found[i].source; found[i].embedIframe = false; } } else { if (found[i].cdn) { found[i].imageLink = found[i].cdn; } else if (found[i].source) { found[i].imageLink = found[i].source; } else { found[i].imageLink = found[i].picture; } } found[i].textName = (found[i].name ? found[i].name : null); found[i].textMessage = (found[i].message ? found[i].message : found[i].description); found[i].hasHeader = (found[i].videoLink != null || found[i].imageLink != null); found[i].hasBody = (found[i].textName != null || found[i].textMessage); if (found[i].textMessage) { found[i].textMessage = found[i].textMessage.replace('\n', '<br/>'); } } res.render('api-feeds', { feeds: found }); }); }); /* [retro ok] api para consulta das fotos */ router.get('/fotos/:before?', enableCors, function(req, res) { var filter = { ref: req.fanpage._id }; if (req.params.before) { filter.time = { $lte: moment.unix(req.params.before).format() }; } Album.find({ ref: req.fanpage._id, special: { '$in': [null, 'default'] } }, function(err, list) { var albums = []; if (list) { for (var i = 0; i < list.length; i++) { albums.push(list[i]._id); } } filter.album_id = { '$in': albums }; Photo.find(filter).limit(15).sort('-time').exec(function(err, found) { res.status(200).send({ fotos: found }); }); }); }); /* [retro ok] */ router.get('/fotos-:album/:before?', enableCors, function(req, res) { var filter = { ref: req.fanpage._id }; if (req.params.before) { filter.time = { $lte: moment.unix(req.params.before).format() }; } Album.findOne({ ref: req.fanpage._id, path: req.params.album }, function(err, one) { if (one) { filter.album_id = one._id; Photo.find(filter).limit(15).sort('-time').exec(function(err, found) { res.send({ fotos: found }); }); } }); }); /* [retro ok] api para consulta dos vídeos */ router.get('/videos/:before?', enableCors, function(req, res) { var filter = { ref: req.fanpage._id }; if (req.params.before) { filter.time = { $lte: moment.unix(req.params.before).format() }; } Video.find(filter).limit(15).sort('-time').exec(function(err, found) { res.send({ videos: found }); }); }); /* [should be retro ok] atualizações em tempo real do Facebook * / router.get('/facebook/realtime', function(req, res) { console.log('Realtime updates verification request received.'); if (req.query['hub.mode'] === 'subscribe') { if (req.query['hub.verify_token'] === '123456') { console.log('Challenge answered.'); res.send(req.query['hub.challenge']); return; } } res.status(500).send(); }); /* [should be retro ok] * / router.post('/facebook/realtime', function(req, res) { var update = new Update(); update.time = Date.now(); update.data = req.body; update.save(function(err, data) { if (err) throw err; RTU.syncPending(); }); res.status(200).send(); }); */ router.get('/pagseguro/callback', function(req, res) { var visitor = ua('UA-52753958-4'); visitor.event('billing', 'finish-payment', '', 999.90).send(); res.redirect('/account/login'); }); /* OLD API END */ };
Corrigindo caminho dos jobs.
core/controllers/api/index.js
Corrigindo caminho dos jobs.
<ide><path>ore/controllers/api/index.js <ide> <ide> /* jobs to be run after new website creation */ <ide> var jobs = []; <del>jobs.push(require('./jobs/new-site-created')); <del>jobs.push(require('./jobs/update-page-info')); <del>jobs.push(require('./jobs/update-profile-picture')); <del>jobs.push(require('./jobs/sync-feeds')); <del>jobs.push(require('./jobs/sync-albums')); <add>jobs.push(require('../../jobs/new-site-created')); <add>jobs.push(require('../../jobs/update-page-info')); <add>jobs.push(require('../../jobs/update-profile-picture')); <add>jobs.push(require('../../jobs/sync-feeds')); <add>jobs.push(require('../../jobs/sync-albums')); <ide> <ide> var runJobs = function () { <ide> for(i = 0; i < jobs.length; i += 1) {