repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
riccardove/easyjasub | easyjasub-lib/src/test/java/com/github/riccardove/easyjasub/FontListTest.java | 974 | package com.github.riccardove.easyjasub;
import org.junit.Ignore;
/*
* #%L
* easyjasub-lib
* %%
* Copyright (C) 2014 Riccardo Vestrini
* %%
* 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%
*/
@Ignore
public class FontListTest extends EasyJaSubTestCase {
public void testListAvailable() {
FontList list = new FontList();
assertTrue(list.iterator().hasNext());
// for (String name : list) {
// System.out.println(name);
// }
}
}
| apache-2.0 |
WxSmile/SmileDaily | app/src/main/java/io/gank/weixiao/business_ganhuo/GanHuosActivity.java | 1448 | package io.gank.weixiao.business_ganhuo;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import butterknife.BindView;
import io.gank.weixiao.R;
import io.gank.weixiao.component_core.contract.GanHuosContract;
import io.gank.weixiao.component_core.base.ToolBarActivity;
public class GanHuosActivity extends ToolBarActivity<GanHuosContract.Presenter> implements GanHuosContract.ActivityView {
@BindView(R.id.viewpager)
ViewPager viewPager;
@BindView(R.id.tablayout)
TabLayout tabLayout;
private GanHuosViewPagerAdapter ganHuosViewPagerAdapter;
@Override
public int setUpLayoutResId() {
return R.layout.activity_gan_huos1;
}
@Override
public GanHuosContract.Presenter setUpPresenterAndRepository() {
return null;
}
@Override
public void initView() {
ganHuosViewPagerAdapter = new GanHuosViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(ganHuosViewPagerAdapter);
viewPager.setOffscreenPageLimit(5);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
}
@Override
public void showLoadingIndicator(boolean b) {
}
@Override
protected void onDestroy() {
super.onDestroy();
// RefWatcher refWatcher = BaseApplication.getRefWatcher(this);
// refWatcher.watch(ganHuosViewPagerAdapter);
}
}
| apache-2.0 |
caihanling/web-demo | src/main/java/zx/soft/web/servlet/DemoServlet.java | 706 | package zx.soft.web.servlet;
import zx.soft.web.source.GetInterface;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class DemoServlet extends HttpServlet {
GetInterface getInterface = new GetInterface();
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setCharacterEncoding("UTF-8");
response.setHeader("Access-Control-Allow-Origin", "*");
PrintWriter writer = response.getWriter();
Object result = getInterface.getData("http://localhost:8080/rpc-api/");
writer.print(result);
}
}
| apache-2.0 |
AfricaRegex/SjcProduct | SjcProject/src/com/sjc/cc/pf/exception/UncheckedException.java | 1564 | package com.sjc.cc.pf.exception;
import java.io.PrintStream;
import java.io.PrintWriter;
/**
* 平台捕捉到的异常,用于将CheckedException转换为UncheckedException,以便不让代码捕捉一些不必要的异常,
* 并且使用此异常在堆栈信息打印时不会产生多余的堆栈信息。
*
* @author 龚林林
*/
public class UncheckedException extends BaseRuntimeException {
private static final long serialVersionUID = 1L;
public UncheckedException(Throwable cause) {
super("依赖第三方功能异常", cause, "ERR-UN-000", getCauseException(cause));
}
public UncheckedException(String message, Throwable cause) {
super(message, cause, "ERR-UN-000", getCauseException(cause));
}
/**
* 得到原始异常信息
*
* @param cause
* @return
*/
public static String getCauseException(Throwable cause) {
if (cause != null) {
cause = ExceptionSupportor.getRootCause(cause);
return cause.getClass().getName() + ":" + cause.getMessage();
}
else {
return "Cause Exception is null";
}
}
public void printStackTrace(PrintStream s) {
s.print(getMessage());
s.println(", The Exception is: ");
super.getCause().printStackTrace(s);
}
public void printStackTrace(PrintWriter s) {
s.print(getMessage());
s.println(", The Exception is: ");
super.getCause().printStackTrace(s);
}
}
| apache-2.0 |
arquillian/arquillian-extension-persistence | core/src/main/java/org/jboss/arquillian/persistence/core/lifecycle/PersistenceTestTrigger.java | 6255 | /*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.persistence.core.lifecycle;
import javax.sql.DataSource;
import org.jboss.arquillian.core.api.Event;
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.InstanceProducer;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.api.annotation.Observes;
import org.jboss.arquillian.core.spi.ServiceLoader;
import org.jboss.arquillian.persistence.core.configuration.PersistenceConfiguration;
import org.jboss.arquillian.persistence.core.datasource.JndiDataSourceProvider;
import org.jboss.arquillian.persistence.core.event.AfterPersistenceTest;
import org.jboss.arquillian.persistence.core.event.BeforePersistenceClass;
import org.jboss.arquillian.persistence.core.event.BeforePersistenceTest;
import org.jboss.arquillian.persistence.core.event.InitializeConfiguration;
import org.jboss.arquillian.persistence.core.metadata.MetadataExtractor;
import org.jboss.arquillian.persistence.core.metadata.PersistenceExtensionEnabler;
import org.jboss.arquillian.persistence.core.metadata.PersistenceExtensionFeatureResolver;
import org.jboss.arquillian.persistence.core.metadata.PersistenceExtensionScriptingFeatureResolver;
import org.jboss.arquillian.persistence.script.configuration.ScriptingConfiguration;
import org.jboss.arquillian.persistence.spi.datasource.DataSourceProvider;
import org.jboss.arquillian.test.spi.annotation.ClassScoped;
import org.jboss.arquillian.test.spi.annotation.TestScoped;
import org.jboss.arquillian.test.spi.event.suite.After;
import org.jboss.arquillian.test.spi.event.suite.Before;
import org.jboss.arquillian.test.spi.event.suite.BeforeClass;
/**
* Determines if persistence extension should be triggered for the given
* test class.
*
* @author <a href="mailto:bartosz.majsak@gmail.com">Bartosz Majsak</a>
*/
public class PersistenceTestTrigger {
@Inject
@ClassScoped
private InstanceProducer<MetadataExtractor> metadataExtractorProducer;
@Inject
@ClassScoped
private InstanceProducer<PersistenceExtensionEnabler> persistenceExtensionEnabler;
@Inject
@TestScoped
private InstanceProducer<PersistenceExtensionFeatureResolver> persistenceExtensionFeatureResolverProvider;
@Inject
@TestScoped
private InstanceProducer<PersistenceExtensionScriptingFeatureResolver>
persistenceExtensionScriptingFeatureResolverProvider;
@Inject
@TestScoped
private InstanceProducer<javax.sql.DataSource> dataSourceProducer;
@Inject
private Instance<PersistenceConfiguration> configurationInstance;
@Inject
private Instance<ScriptingConfiguration> scriptingConfigurationInstance;
@Inject
private Event<BeforePersistenceTest> beforePersistenceTestEvent;
@Inject
private Event<AfterPersistenceTest> afterPersistenceTestEvent;
@Inject
private Event<InitializeConfiguration> initializeConfigurationEvent;
@Inject
private Event<BeforePersistenceClass> beforePersistenceClassEvent;
@Inject
private Instance<ServiceLoader> serviceLoaderInstance;
public void beforeClass(@Observes BeforeClass beforeClass) {
metadataExtractorProducer.set(new MetadataExtractor(beforeClass.getTestClass()));
persistenceExtensionEnabler.set(new PersistenceExtensionEnabler(metadataExtractorProducer.get()));
if (persistenceExtensionEnabler.get().shouldPersistenceExtensionBeActivated()) {
initializeConfigurationEvent.fire(new InitializeConfiguration());
beforePersistenceClassEvent.fire(new BeforePersistenceClass(beforeClass.getTestClass()));
}
}
public void beforeTest(@Observes(precedence = 25) Before beforeTestEvent) {
PersistenceConfiguration persistenceConfiguration = configurationInstance.get();
persistenceExtensionFeatureResolverProvider.set(
new PersistenceExtensionFeatureResolver(beforeTestEvent.getTestMethod(), metadataExtractorProducer.get(),
persistenceConfiguration));
persistenceExtensionScriptingFeatureResolverProvider.set(
new PersistenceExtensionScriptingFeatureResolver(beforeTestEvent.getTestMethod(),
metadataExtractorProducer.get(), scriptingConfigurationInstance.get()));
if (persistenceExtensionEnabler.get().shouldPersistenceExtensionBeActivated()) {
createDataSource();
beforePersistenceTestEvent.fire(new BeforePersistenceTest(beforeTestEvent));
}
}
public void afterTest(@Observes(precedence = -2) After afterTestEvent) {
if (persistenceExtensionEnabler.get().shouldPersistenceExtensionBeActivated()) {
afterPersistenceTestEvent.fire(new AfterPersistenceTest(afterTestEvent));
}
}
// Private methods
private void createDataSource() {
String dataSourceName = persistenceExtensionFeatureResolverProvider.get().getDataSourceName();
dataSourceProducer.set(loadDataSource(dataSourceName));
}
/**
* @throws IllegalStateException
* when more than one data source provider exists on the classpath
*/
private DataSource loadDataSource(String dataSourceName) {
final DataSourceProvider dataSourceProvider = serviceLoaderInstance.get()
.onlyOne(DataSourceProvider.class, JndiDataSourceProvider.class);
return dataSourceProvider.lookupDataSource(dataSourceName);
}
}
| apache-2.0 |
jokeog/ProjectCalendae | library/src/main/java/com/mikephil/charting/interfaces/datasets/IBarLineScatterCandleBubbleDataSet.java | 374 | package com.mikephil.charting.interfaces.datasets;
import com.mikephil.charting.data.Entry;
/**
* Created by philipp on 21/10/15.
*/
public interface IBarLineScatterCandleBubbleDataSet<T extends Entry> extends IDataSet<T> {
/**
* Returns the color that is used for drawing the highlight indicators.
*
* @return
*/
int getHighLightColor();
}
| apache-2.0 |
jtransc/jtransc | jtransc-rt/src/java/io/NotSerializableException.java | 1851 | /*
* 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 java.io;
/**
* Signals that an object that is not serializable has been passed into the
* {@code ObjectOutput.writeObject()} method. This can happen if the object
* does not implement {@code Serializable} or {@code Externalizable}, or if it
* is serializable but it overrides {@code writeObject(ObjectOutputStream)} and
* explicitly prevents serialization by throwing this type of exception.
*
* @see ObjectOutput#writeObject(Object)
* @see ObjectOutputStream#writeObject(Object)
*/
public class NotSerializableException extends ObjectStreamException {
/**
* Constructs a new {@code NotSerializableException} with its stack trace
* filled in.
*/
public NotSerializableException() {
}
/**
* Constructs a new {@link NotSerializableException} with its stack trace
* and detail message filled in.
*
* @param detailMessage the detail message for this exception.
*/
public NotSerializableException(String detailMessage) {
super(detailMessage);
}
}
| apache-2.0 |
AleksanderMielczarek/ObservableCache | observable-cache-2-service-processor/src/main/java/com/github/aleksandermielczarek/observablecache2/service/processor/method/extend/CompletableExtendMethod.java | 796 | package com.github.aleksandermielczarek.observablecache2.service.processor.method.extend;
import com.github.aleksandermielczarek.observablecache.service.processor.api.method.extend.FromCacheMethod;
/**
* Created by Aleksander Mielczarek on 09.02.2017.
*/
public class CompletableExtendMethod implements FromCacheMethod {
@Override
public String additionalToken() {
return "cached";
}
@Override
public String returnedBaseType() {
return "com.github.aleksandermielczarek.observablecache2.CacheableCompletable";
}
@Override
public String returnedType() {
return "com.github.aleksandermielczarek.observablecache2.CompletableFromCache";
}
@Override
public String fromCacheMethod() {
return "getCompletable";
}
}
| apache-2.0 |
crate/crate | server/src/main/java/io/crate/planner/selectivity/SelectivityFunctions.java | 6888 | /*
* Licensed to Crate.io GmbH ("Crate") under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. Crate 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.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial agreement.
*/
package io.crate.planner.selectivity;
import io.crate.data.Row;
import io.crate.expression.operator.AndOperator;
import io.crate.expression.operator.EqOperator;
import io.crate.expression.operator.OrOperator;
import io.crate.expression.predicate.IsNullPredicate;
import io.crate.expression.predicate.NotPredicate;
import io.crate.expression.symbol.Function;
import io.crate.expression.symbol.Literal;
import io.crate.expression.symbol.ParameterSymbol;
import io.crate.expression.symbol.ScopedSymbol;
import io.crate.expression.symbol.Symbol;
import io.crate.expression.symbol.SymbolVisitor;
import io.crate.metadata.ColumnIdent;
import io.crate.metadata.Reference;
import io.crate.statistics.ColumnStats;
import io.crate.statistics.Stats;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.List;
/**
* Used to estimate the number of rows returned after applying a given query.
*
* The numbers, heuristic and logic here is heavily inspired by PostgreSQL.
* See `src/backend/optimizer/path/clausesel.c` `clause_selectivity`
*/
public class SelectivityFunctions {
private static final double DEFAULT_EQ_SEL = 0.005;
/**
* For all cases where we don't have a concrete selectivity logic we use this magic number.
* It seems to have worked for PostgreSQL quite well so far.
*/
private static final double MAGIC_SEL = 0.333;
public static long estimateNumRows(Stats stats, Symbol query, @Nullable Row params) {
var estimator = new SelectivityEstimator(stats, params);
return (long) (stats.numDocs() * query.accept(estimator, null));
}
static class SelectivityEstimator extends SymbolVisitor<Void, Double> {
private final Stats stats;
@Nullable
private final Row params;
SelectivityEstimator(Stats stats, @Nullable Row params) {
this.stats = stats;
this.params = params;
}
@Override
protected Double visitSymbol(Symbol symbol, Void context) {
return 1.0;
}
@Override
public Double visitLiteral(Literal literal, Void context) {
Object value = literal.value();
if (value instanceof Boolean) {
Boolean val = (Boolean) value;
return !val ? 0.0 : 1.0;
}
if (value == null) {
return 0.0;
}
return super.visitLiteral(literal, context);
}
@Override
public Double visitFunction(Function function, Void context) {
switch (function.name()) {
case AndOperator.NAME: {
double selectivity = 1.0;
for (Symbol argument : function.arguments()) {
selectivity *= argument.accept(this, context);
}
return selectivity;
}
case OrOperator.NAME: {
double sel1 = 1.0;
for (Symbol argument : function.arguments()) {
double sel2 = argument.accept(this, context);
sel1 = sel1 + sel2 - sel1 * sel2;
}
return sel1;
}
case EqOperator.NAME: {
List<Symbol> arguments = function.arguments();
return eqSelectivity(arguments.get(0), arguments.get(1), stats, params);
}
case NotPredicate.NAME: {
return 1.0 - function.arguments().get(0).accept(this, context);
}
case IsNullPredicate.NAME: {
var arguments = function.arguments();
return isNullSelectivity(arguments.get(0), stats);
}
default:
return MAGIC_SEL;
}
}
}
private static double isNullSelectivity(Symbol arg, Stats stats) {
ColumnIdent column = getColumn(arg);
if (column == null) {
return MAGIC_SEL;
}
var columnStats = stats.statsByColumn().get(column);
if (columnStats == null) {
return MAGIC_SEL;
}
return columnStats.nullFraction();
}
private static double eqSelectivity(Symbol leftArg, Symbol rightArg, Stats stats, @Nullable Row params) {
ColumnIdent column = getColumn(leftArg);
if (column == null) {
return DEFAULT_EQ_SEL;
}
var columnStats = stats.statsByColumn().get(column);
if (columnStats == null) {
return DEFAULT_EQ_SEL;
}
if (rightArg instanceof ParameterSymbol && params != null) {
var value = params.get(((ParameterSymbol) rightArg).index());
return eqSelectivityFromValueAndStats(value, columnStats);
}
if (rightArg instanceof Literal) {
return eqSelectivityFromValueAndStats(((Literal) rightArg).value(), columnStats);
}
return 1.0 / columnStats.approxDistinct();
}
private static double eqSelectivityFromValueAndStats(Object value, ColumnStats columnStats) {
if (value == null) {
// x = null -> is always false
return 0.0;
}
var mcv = columnStats.mostCommonValues();
int idx = Arrays.asList(mcv.values()).indexOf(value);
if (idx < 0) {
return 1.0 / columnStats.approxDistinct();
} else {
return mcv.frequencies()[idx];
}
}
@Nullable
private static ColumnIdent getColumn(Symbol symbol) {
if (symbol instanceof Reference) {
return ((Reference) symbol).column();
} else if (symbol instanceof ScopedSymbol) {
return ((ScopedSymbol) symbol).column();
} else {
return null;
}
}
}
| apache-2.0 |
Treydone/mandrel | mandrel-coordinator/src/main/java/io/mandrel/coordinator/CoordinatorContainer.java | 3887 | /*
* Licensed to Mandrel under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Mandrel 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 io.mandrel.coordinator;
import io.mandrel.blob.BlobStore;
import io.mandrel.blob.BlobStores;
import io.mandrel.common.container.AbstractContainer;
import io.mandrel.common.container.ContainerStatus;
import io.mandrel.common.data.Job;
import io.mandrel.common.service.TaskContext;
import io.mandrel.document.DocumentStore;
import io.mandrel.document.DocumentStores;
import io.mandrel.metadata.MetadataStore;
import io.mandrel.metadata.MetadataStores;
import io.mandrel.metrics.Accumulators;
import io.mandrel.transport.MandrelClient;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import com.google.common.util.concurrent.Monitor;
@Slf4j
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true, fluent = true)
public class CoordinatorContainer extends AbstractContainer {
private final Monitor monitor = new Monitor();
private final TaskContext context = new TaskContext();
public CoordinatorContainer(Job job, Accumulators accumulators, MandrelClient client) {
super(accumulators, job, client);
context.setDefinition(job);
// Init stores
MetadataStore metadatastore = job.getDefinition().getStores().getMetadataStore().build(context);
metadatastore.init();
MetadataStores.add(job.getId(), metadatastore);
BlobStore blobStore = job.getDefinition().getStores().getBlobStore().build(context);
blobStore.init();
BlobStores.add(job.getId(), blobStore);
job.getDefinition().getExtractors().getData().forEach(ex -> {
DocumentStore documentStore = ex.getDocumentStore().metadataExtractor(ex).build(context);
documentStore.init();
DocumentStores.add(job.getId(), ex.getName(), documentStore);
});
current.set(ContainerStatus.INITIATED);
}
@Override
public String type() {
return "coordinator";
}
@Override
public void start() {
if (monitor.tryEnter()) {
try {
if (!current.get().equals(ContainerStatus.STARTED)) {
current.set(ContainerStatus.STARTED);
}
} finally {
monitor.leave();
}
}
}
@Override
public void pause() {
if (monitor.tryEnter()) {
try {
if (!current.get().equals(ContainerStatus.PAUSED)) {
log.debug("Pausing the coordinator");
current.set(ContainerStatus.PAUSED);
}
} finally {
monitor.leave();
}
}
}
@Override
public void kill() {
if (monitor.tryEnter()) {
try {
if (!current.get().equals(ContainerStatus.KILLED)) {
try {
MetadataStores.remove(job.getId());
} catch (Exception e) {
log.debug(e.getMessage(), e);
}
try {
BlobStores.remove(job.getId());
} catch (Exception e) {
log.debug(e.getMessage(), e);
}
try {
DocumentStores.remove(job.getId());
} catch (Exception e) {
log.debug(e.getMessage(), e);
}
current.set(ContainerStatus.KILLED);
}
} finally {
monitor.leave();
}
}
}
@Override
public void register() {
CoordinatorContainers.add(job.getId(), this);
}
@Override
public void unregister() {
CoordinatorContainers.remove(job.getId());
}
}
| apache-2.0 |
PlanetWaves/clockworkengine | branches/3.0/engine/src/core/com/clockwork/effect/influencers/RadialParticleInfluencer.java | 3219 |
package com.clockwork.effect.influencers;
import com.clockwork.effect.Particle;
import com.clockwork.export.InputCapsule;
import com.clockwork.export.CWExporter;
import com.clockwork.export.CWImporter;
import com.clockwork.export.OutputCapsule;
import com.clockwork.math.FastMath;
import com.clockwork.math.Vector3f;
import java.io.IOException;
/**
* an influencer to make blasts expanding on the ground. can be used for various other things
*/
public class RadialParticleInfluencer extends DefaultParticleInfluencer {
private float radialVelocity = 0f;
private Vector3f origin = new Vector3f(0, 0, 0);
private boolean horizontal = false;
/**
* This method applies the variation to the particle with already set velocity.
* @param particle
* the particle to be affected
*/
@Override
protected void applyVelocityVariation(Particle particle) {
particle.velocity.set(initialVelocity);
temp.set(particle.position).subtractLocal(origin).normalizeLocal().multLocal(radialVelocity);
if (horizontal) {
temp.y = 0;
}
particle.velocity.addLocal(temp);
temp.set(FastMath.nextRandomFloat(), FastMath.nextRandomFloat(), FastMath.nextRandomFloat());
temp.multLocal(2f);
temp.subtractLocal(1f, 1f, 1f);
temp.multLocal(initialVelocity.length());
particle.velocity.interpolate(temp, velocityVariation);
}
/**
* the origin used for computing the radial velocity direction
* @return the origin
*/
public Vector3f getOrigin() {
return origin;
}
/**
* the origin used for computing the radial velocity direction
* @param origin
*/
public void setOrigin(Vector3f origin) {
this.origin = origin;
}
/**
* the radial velocity
* @return radialVelocity
*/
public float getRadialVelocity() {
return radialVelocity;
}
/**
* the radial velocity
* @param radialVelocity
*/
public void setRadialVelocity(float radialVelocity) {
this.radialVelocity = radialVelocity;
}
/**
* nullify y component of particle velocity to make the effect expand only on x and z axis
* @return
*/
public boolean isHorizontal() {
return horizontal;
}
/**
* nullify y component of particle velocity to make the effect expand only on x and z axis
* @param horizontal
*/
public void setHorizontal(boolean horizontal) {
this.horizontal = horizontal;
}
@Override
public void write(CWExporter ex) throws IOException {
super.write(ex);
OutputCapsule oc = ex.getCapsule(this);
oc.write(radialVelocity, "radialVelocity", 0f);
oc.write(origin, "origin", new Vector3f());
oc.write(horizontal, "horizontal", false);
}
@Override
public void read(CWImporter im) throws IOException {
super.read(im);
InputCapsule ic = im.getCapsule(this);
radialVelocity = ic.readFloat("radialVelocity", 0f);
origin = (Vector3f) ic.readSavable("origin", new Vector3f());
horizontal = ic.readBoolean("horizontal", false);
}
}
| apache-2.0 |
trejkaz/derby | java/client/org/apache/derby/client/net/NaiveTrustManager.java | 5300 | /*
Derby - Class org.apache.derby.client.net.NaiveTrustManager
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.derby.client.net;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyManagementException;
import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.net.ssl.KeyManagerFactory;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.UnrecoverableKeyException;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateException;
/**
* This is a naive trust manager we use when we don't want server
* authentication. Any certificate will be accepted.
**/
class NaiveTrustManager
implements X509TrustManager
{
/**
* We don't want more than one instence of this TrustManager
*/
private NaiveTrustManager()
{
}
static private TrustManager[] thisManager = null;
/**
* Generate a socket factory with this trust manager. Derby
* Utility routine which is not part of the X509TrustManager
* interface.
**/
static SocketFactory getSocketFactory()
throws NoSuchAlgorithmException,
KeyManagementException,
NoSuchProviderException,
KeyStoreException,
UnrecoverableKeyException,
CertificateException,
IOException
{
if (thisManager == null) {
thisManager = new TrustManager [] {new NaiveTrustManager()};
}
SSLContext ctx = SSLContext.getInstance("TLS");
if (ctx.getProvider().getName().equals("SunJSSE") &&
(System.getProperty("javax.net.ssl.keyStore") != null) &&
(System.getProperty("javax.net.ssl.keyStorePassword") != null)) {
// SunJSSE does not give you a working default keystore
// when using your own trust manager. Since a keystore is
// needed on the client when the server does
// peerAuthentication, we have to provide one working the
// same way as the default one.
String keyStore =
System.getProperty("javax.net.ssl.keyStore");
String keyStorePassword =
System.getProperty("javax.net.ssl.keyStorePassword");
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(keyStore),
keyStorePassword.toCharArray());
KeyManagerFactory kmf =
KeyManagerFactory.getInstance("SunX509", "SunJSSE");
kmf.init(ks, keyStorePassword.toCharArray());
ctx.init(kmf.getKeyManagers(),
thisManager,
null); // Use default random source
} else {
ctx.init(null, // Use default key manager
thisManager,
null); // Use default random source
}
return ctx.getSocketFactory();
}
/**
* Checks wether the we trust the client. Since this trust manager
* is just for the Derby clients, this routine is actually never
* called, but need to be here when we implement X509TrustManager.
* @param chain The client's certificate chain
* @param authType authorization type (e.g. "RSA" or "DHE_DSS")
**/
public void checkClientTrusted(X509Certificate[] chain,
String authType)
throws CertificateException
{
// Reject all attemtpts to trust a client. We should never end
// up here.
throw new CertificateException();
}
/**
* Checks wether the we trust the server, which we allways will.
* @param chain The server's certificate chain
* @param authType authorization type (e.g. "RSA" or "DHE_DSS")
**/
public void checkServerTrusted(X509Certificate[] chain,
String authType)
throws CertificateException
{
// Do nothing. We trust everyone.
}
/**
* Return an array of certificate authority certificates which are
* trusted for authenticating peers. Not relevant for this trust
* manager.
*/
public X509Certificate[] getAcceptedIssuers()
{
return new X509Certificate[0];
}
}
| apache-2.0 |
rcuvgd/Ivona---Text-to-speach | src/main/java/com/ivona/services/tts/model/Lexicon.java | 3279 | /*
* Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.ivona.services.tts.model;
/**
* Class representing a lexicon.
* <p>
* Please check the service documentation for more details.
*
* @see <a href="http://developer.ivona.com/en/speechcloud/speechcloud_developer_guide.html">Speech Cloud Developer Guide</a>
*/
public class Lexicon {
private String name;
private String contents;
/**
* Get the lexicon name.
*/
public String getName() {
return this.name;
}
/**
* Set the lexicon name.
*/
public void setName(String name) {
this.name = name;
}
/**
* Set the lexicon name.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*/
public Lexicon withName(String name) {
this.name = name;
return this;
}
/**
* Get the PLS contents of this lexicon.
*/
public String getContents() {
return this.contents;
}
/**
* Set the PLS contents of this lexicon.
*/
public void setContents(String contents) {
this.contents = contents;
}
/**
* Set the PLS contents of this lexicon.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*/
public Lexicon withContents(String contents) {
this.contents = contents;
return this;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Lexicon [name=");
builder.append(name);
builder.append(", contents=");
builder.append(contents);
builder.append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((contents == null) ? 0 : contents.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Lexicon other = (Lexicon) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (contents == null) {
if (other.contents != null) {
return false;
}
} else if (!contents.equals(other.contents)) {
return false;
}
return true;
}
}
| apache-2.0 |
andrei-viaryshka/pentaho-hadoop-shims | shims/mapr510/impl/src/main/java/org/pentaho/hadoop/shim/mapr510/authorization/ShimNoOpHadoopAuthorizationService.java | 1623 | /*******************************************************************************
*
* Pentaho Big Data
*
* Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.hadoop.shim.mapr510.authorization;
import org.pentaho.hadoop.shim.common.CommonHadoopShim;
import org.pentaho.hadoop.shim.common.CommonPigShim;
import org.pentaho.hadoop.shim.common.PigShimImpl;
import org.pentaho.hadoop.shim.common.authorization.NoOpHadoopAuthorizationService;
import org.pentaho.hadoop.shim.mapr510.HadoopShim;
public class ShimNoOpHadoopAuthorizationService extends NoOpHadoopAuthorizationService {
@Override protected CommonHadoopShim getHadoopShim() {
return new HadoopShim();
}
@Override protected CommonPigShim getPigShim() {
return new PigShimImpl() {
@Override public boolean isLocalExecutionSupported() {
return false;
}
};
}
}
| apache-2.0 |
fcopardo/EasyRest-Desktop | src/main/java/com/grizzly/rest/WebServiceFactory.java | 8081 | /*
* Copyright (c) 2014. Francisco Pardo Baeza
*
* 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.grizzly.rest;
import com.grizzly.rest.Model.RestResults;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.grizzly.rest.Model.sendRestData;
import org.springframework.http.HttpHeaders;
import rx.Subscriber;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import java.io.File;
import java.util.*;
/**
* Created on 24/03/14.
* Creates instances of parametrized AdvancedRestCall
*/
public class WebServiceFactory implements CacheProvider{
private HttpHeaders requestHeaders = new HttpHeaders();
private HttpHeaders responseHeaders = new HttpHeaders();
private long globalCacheTime = 899999;
private int timeOutValue = 60000;
private static HashMap<String, String> cachedRequests = new HashMap<>();
private String baseUrl = "";
private MappingJackson2HttpMessageConverter jacksonConverter;
private Map<String, List<Subscriber<RestResults>>> subscribers;
public HttpHeaders getRequestHeaders() {
return requestHeaders;
}
public void setRequestHeaders(HttpHeaders requestHeaders) {
this.requestHeaders = requestHeaders;
}
/*public HttpHeaders getResponseHeaders() {
return responseHeaders;
}*/
public void resetHeaders() {
requestHeaders = new HttpHeaders();
responseHeaders = new HttpHeaders();
}
/*public void setResponseHeaders(HttpHeaders responseHeaders) {
this.responseHeaders = responseHeaders;
}*/
public void setGlobalCacheTime(long time){
globalCacheTime = time;
}
public void setTimeOutValue(int miliseconds){
if(miliseconds>=0){
timeOutValue = miliseconds;
}
else{
throw new IllegalArgumentException("The timeout must be greater than zero");
}
}
public void setBaseUrl(String BaseUrl){
baseUrl = BaseUrl;
}
public WebServiceFactory() {
}
public <T extends sendRestData, X> EasyRestCall<T, X, Void> getRestCallInstance(Class<T> entityClass, Class<X> responseClass) {
return this.getRestCallInstance(entityClass, responseClass, Void.class, false);
}
public <T extends sendRestData, X> EasyRestCall<T, X, Void> getRestCallInstance(Class<T> entityClass, Class<X> responseClass, boolean isTest) {
return this.getRestCallInstance(entityClass, responseClass, Void.class, isTest);
}
public <T extends sendRestData, X, M> EasyRestCall<T, X, M> getRestCallInstance(Class<T> entityClass, Class<X> responseClass, Class<M> errorBodyClass) {
return this.getRestCallInstance(entityClass, responseClass, errorBodyClass, false);
}
public <T extends sendRestData, X, M> EasyRestCall<T, X, M> getRestCallInstance(Class<T> entityClass, Class<X> responseClass, Class<M> errorBodyClass, boolean isTest) {
EasyRestCall<T, X, M> myRestCall = null;
if(isTest) {
myRestCall = new EasyRestCall<>(entityClass, responseClass, errorBodyClass, 1);
}
else {
myRestCall = new EasyRestCall<>(entityClass, responseClass, errorBodyClass);
}
myRestCall.setCacheProvider(this);
myRestCall.setCacheTime(globalCacheTime);
if(requestHeaders!= null && !requestHeaders.isEmpty()){
myRestCall.setRequestHeaders(requestHeaders);
}
if(!baseUrl.isEmpty() && baseUrl.trim().equalsIgnoreCase("") && baseUrl != null){
myRestCall.setUrl(baseUrl);
}
if(jacksonConverter!=null){
//myRestCall.setJacksonMapper(jacksonConverter);
}
myRestCall.setTimeOut(timeOutValue);
return myRestCall;
}
public <T, X> GenericRestCall<T, X, Void> getGenericRestCallInstance(Class<T> entityClass, Class<X> responseClass, boolean isTest) {
return this.getGenericRestCallInstance(entityClass, responseClass, Void.class, isTest);
}
public <T, X> GenericRestCall<T, X, Void> getGenericRestCallInstance(Class<T> entityClass, Class<X> responseClass) {
return this.getGenericRestCallInstance(entityClass, responseClass, Void.class, false);
}
public <T, X, M> GenericRestCall<T, X, M> getGenericRestCallInstance(Class<T> entityClass, Class<X> responseClass, Class<M> errorBodyClass) {
return this.getGenericRestCallInstance(entityClass, responseClass, errorBodyClass, false);
}
public <T, X, M> GenericRestCall<T, X, M> getGenericRestCallInstance(Class<T> entityClass, Class<X> responseClass, Class<M> errorBodyClass, boolean isTest) {
GenericRestCall<T, X, M> myRestCall = null;
if(isTest) {
myRestCall = new GenericRestCall<>(entityClass, responseClass, errorBodyClass, 1);
}
else {
myRestCall = new GenericRestCall<>(entityClass, responseClass, errorBodyClass);
}
try{
myRestCall.setCacheProvider(this);
myRestCall.setCacheTime(globalCacheTime);
}
catch(NullPointerException e){
e.printStackTrace();
}
if(requestHeaders!= null && !requestHeaders.isEmpty()){
myRestCall.setRequestHeaders(requestHeaders);
}
if(!baseUrl.isEmpty() && baseUrl.trim().equalsIgnoreCase("") && baseUrl != null){
myRestCall.setUrl(baseUrl);
}
if(jacksonConverter!=null){
myRestCall.setJacksonMapper(jacksonConverter);
}
myRestCall.setTimeOut(timeOutValue);
return myRestCall;
}
@Override
public <T, X, M> boolean setCache(GenericRestCall<T, X, M> myRestCall, Class<X> responseClass, Class<T> entityClass, Class<M> errorBodyClass){
boolean bol = false;
if(!myRestCall.getUrl().trim().equalsIgnoreCase("") && myRestCall != null)
{
if(!responseClass.getCanonicalName().equalsIgnoreCase(Void.class.getCanonicalName()) ){
/*if(cachedRequests.containsKey(myRestCall.getUrl())){
myRestCall.setCachedFileName(cachedRequests.get(myRestCall.getUrl()));
return true;
}
else{
cachedRequests.put(myRestCall.getUrl(), myRestCall.getCachedFileName());
}*/
}
return false;
}
return bol;
}
/**
* Factory getter method. Returns either the current instance of the MappingJackson2HttpConverter,
* or a initialized one wih FAIL_ON_UNKNOW_PROPERTIES and FAIL_ON_INVALID_SUBTYPE set to false.
* @return the jacksonConverter to be used by all the rest calls created by this factory.
*/
public MappingJackson2HttpMessageConverter getJacksonConverter() {
if(jacksonConverter == null){
MappingJackson2HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter();
jacksonConverter.getObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
jacksonConverter.getObjectMapper().configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);
}
return jacksonConverter;
}
/**
* Allows setting a custom MappingJackson2HttpConverter
* @param jacksonConverter the converter to be set.
*/
public void setJacksonConverter(MappingJackson2HttpMessageConverter jacksonConverter) {
this.jacksonConverter = jacksonConverter;
}
}
| apache-2.0 |
Javer-com-ua/FlowerExpert | src/main/java/ua/com/javer/flowerexpert/dao/MessageDao.java | 368 | package ua.com.javer.flowerexpert.dao;
import ua.com.javer.flowerexpert.entity.Message;
import java.util.List;
public interface MessageDao {
List<Message> getAllMessages();
void addMessage(Message message);
void updateMessage(Message message);
void deleteMessage(Message message);
Message getMessageById(int id);
boolean existsMessage(String messageName);
}
| apache-2.0 |
oaqa/bioasq | src/main/java/edu/cmu/lti/oaqa/baseqa/answer/generate/generators/CoveringPhraseCavGenerator.java | 3211 | /*
* Open Advancement Question Answering (OAQA) Project Copyright 2016 Carnegie Mellon University
*
* 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.cmu.lti.oaqa.baseqa.answer.generate.generators;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import java.util.*;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.jcas.JCas;
import com.google.common.collect.SetMultimap;
import edu.cmu.lti.oaqa.baseqa.answer.CavUtil;
import edu.cmu.lti.oaqa.ecd.config.ConfigurableProvider;
import edu.cmu.lti.oaqa.type.answer.CandidateAnswerVariant;
import edu.cmu.lti.oaqa.type.nlp.Token;
import edu.cmu.lti.oaqa.util.TypeFactory;
import edu.cmu.lti.oaqa.util.TypeUtil;
/**
* This class tries to expand the answer spans of extracted {@link CandidateAnswerVariant}s by
* first identifying their head words in their parse trees, and including all the leaf nodes of the
* subtrees.
*
* @author <a href="mailto:ziy@cs.cmu.edu">Zi Yang</a> created on 4/15/15
*/
public class CoveringPhraseCavGenerator extends ConfigurableProvider implements CavGenerator {
// private static final String PUNCT_DEP_LABEL = "punct";
@Override
public boolean accept(JCas jcas) throws AnalysisEngineProcessException {
return TypeUtil.getQuestion(jcas).getQuestionType().equals("FACTOID")
|| TypeUtil.getQuestion(jcas).getQuestionType().equals("LIST");
}
@Override
public List<CandidateAnswerVariant> generate(JCas jcas) throws AnalysisEngineProcessException {
Set<Token> heads = TypeUtil.getCandidateAnswerVariants(jcas).stream()
.map(TypeUtil::getCandidateAnswerOccurrences).flatMap(Collection::stream)
.map(TypeUtil::getHeadTokenOfAnnotation).filter(Objects::nonNull).collect(toSet());
Set<Token> parents = heads.stream().map(Token::getHead).filter(Objects::nonNull)
.filter(t -> !heads.contains(t)).collect(toSet());
Map<JCas, List<Token>> view2parents = parents.stream().collect(groupingBy(CavUtil::getJCas));
return view2parents.entrySet().stream().flatMap(entry -> {
JCas view = entry.getKey();
List<Token> tokens = TypeUtil.getOrderedTokens(view);
SetMultimap<Token, Token> head2children = CavUtil.getHeadTokenMap(tokens);
return entry.getValue().stream()
.map(parent -> CavUtil.createCandidateAnswerOccurrenceFromDepBranch(view, parent,
head2children, null))
.map(cao -> TypeFactory.createCandidateAnswerVariant(jcas,
Collections.singletonList(cao)));
} ).collect(toList());
}
}
| apache-2.0 |
jpaw/bonaparte-java | bonaparte-jaxrs/src/main/java/de/jpaw/bonaparte/jaxrs/BonaparteJaxRsConverter.java | 1069 | package de.jpaw.bonaparte.jaxrs;
import javax.ws.rs.Produces;
import javax.ws.rs.ext.Provider;
import de.jpaw.bonaparte.core.BonaPortable;
import de.jpaw.bonaparte.core.BufferedMessageWriter;
import de.jpaw.bonaparte.core.ByteArrayComposer;
import de.jpaw.bonaparte.core.ByteArrayParser;
import de.jpaw.bonaparte.core.MessageParser;
import de.jpaw.bonaparte.core.MessageParserException;
import de.jpaw.bonaparte.core.MimeTypes;
@Provider
@Produces(MimeTypes.MIME_TYPE_BONAPARTE)
public class BonaparteJaxRsConverter extends AbstractBonaparteConverters<RuntimeException> {
public BonaparteJaxRsConverter() {
super(MimeTypes.MIME_TYPE_BONAPARTE);
}
@Override
protected MessageParser<MessageParserException> newParser(byte[] buffer, int offset, int len) {
return new ByteArrayParser(buffer, offset, len);
}
@Override
protected BufferedMessageWriter<RuntimeException> newComposerWithData(BonaPortable obj) {
ByteArrayComposer bac = new ByteArrayComposer();
bac.writeRecord(obj);
return bac;
}
}
| apache-2.0 |
evg08/MyJava | addressbook-web-tests/src/test/java/ru/stqa/pft/addreessbook/tests/TestBase.java | 604 | package ru.stqa.pft.addreessbook.tests;
import org.openqa.selenium.remote.BrowserType;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import ru.stqa.pft.addreessbook.appmanager.ApplicationManager;
/**
* Created by Евгения on 19.07.2017.
*/
public class TestBase {
protected ApplicationManager app = new ApplicationManager(BrowserType.FIREFOX);
@BeforeMethod
public void setUp() throws Exception {
app.init();
}
@AfterMethod
public void tearDown() {
app.stop();
}
public ApplicationManager getApp() {
return app;
}
}
| apache-2.0 |
tatyano/athenz | libs/java/server_common/src/test/java/com/yahoo/athenz/common/server/log/impl/AuditLogMsgBuilderTest.java | 4774 | /**
* Copyright 2016 Yahoo Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yahoo.athenz.common.server.log.impl;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.yahoo.athenz.common.server.log.AuditLogMsgBuilder;
import com.yahoo.athenz.common.server.log.AuditLogger;
import com.yahoo.athenz.common.server.log.AuditLoggerFactory;
import com.yahoo.athenz.common.server.log.impl.DefaultAuditLogMsgBuilder;
/**
* Test all API of AuditLogMsgBuilder.
* Test the getMsgBuilder() API of AuditLogFactory.
*/
public class AuditLogMsgBuilderTest {
private static final String ZMS_USER_DOMAIN = "athenz.user_domain";
private static final String USER_DOMAIN = System.getProperty(ZMS_USER_DOMAIN, "user");
static String TOKEN_STR = "v=U1;d=" + USER_DOMAIN + ";n=roger;h=somehost.somecompany.com;a=666;t=1492;e=2493;s=signature;";
DefaultAuditLogMsgBuilder starter(final String whatApi) {
AuditLoggerFactory auditLoggerFactory = new DefaultAuditLoggerFactory();
AuditLogger logger = auditLoggerFactory.create();
AuditLogMsgBuilder msgBldr = logger.getMsgBuilder();
msgBldr.who(TOKEN_STR).when("now-timestamp").clientIp("12.12.12.12").whatApi(whatApi);
return (DefaultAuditLogMsgBuilder)msgBldr;
}
@Test
public void testWho() {
DefaultAuditLogMsgBuilder msgBldr = starter("testWho");
String dataStr = "me?";
msgBldr.who(dataStr);
Assert.assertTrue(msgBldr.who().equals(dataStr), "who string=" + msgBldr.who());
}
@Test
public void testWhy() {
DefaultAuditLogMsgBuilder msgBldr = starter("testWhy");
String dataStr = "not?";
msgBldr.why(dataStr);
Assert.assertTrue(msgBldr.why().equals(dataStr), "why string=" + msgBldr.why());
}
@Test
public void testWhenString() {
DefaultAuditLogMsgBuilder msgBldr = starter("testWhenString");
String dataStr = "now?";
msgBldr.when(dataStr);
Assert.assertTrue(msgBldr.when().equals(dataStr), "when string=" + msgBldr.when());
}
@Test
public void testClientIp() {
DefaultAuditLogMsgBuilder msgBldr = starter("testClientIp");
String dataStr = "99.77.22.hup";
msgBldr.clientIp(dataStr);
Assert.assertTrue(msgBldr.clientIp().equals(dataStr), "clientIp string=" + msgBldr.clientIp());
}
@Test
public void testWhere() {
DefaultAuditLogMsgBuilder msgBldr = starter("testWhere");
String dataStr = "host1.athenz.com";
msgBldr.where(dataStr);
Assert.assertTrue(msgBldr.where().equals(dataStr), "where string=" + msgBldr.where());
}
@Test
public void testWhatMethod() {
DefaultAuditLogMsgBuilder msgBldr = starter("testWhatMethod");
String dataStr = "PUT";
msgBldr.whatMethod(dataStr);
Assert.assertTrue(msgBldr.whatMethod().equals(dataStr), "whatMethod string=" + msgBldr.whatMethod());
}
@Test
public void testWhatApi() {
DefaultAuditLogMsgBuilder msgBldr = starter("testWhatApi");
String dataStr = "putRole";
msgBldr.whatApi(dataStr);
Assert.assertTrue(msgBldr.whatApi().equals(dataStr), "whatApi string=" + msgBldr.whatApi());
}
@Test
public void testWhatDomain() {
DefaultAuditLogMsgBuilder msgBldr = starter("testWhatDomain");
String dataStr = "sys.auth";
msgBldr.whatDomain(dataStr);
Assert.assertTrue(msgBldr.whatDomain().equals(dataStr), "whatDomain string=" + msgBldr.whatDomain());
}
@Test
public void testWhatEntity() {
DefaultAuditLogMsgBuilder msgBldr = starter("testWhatEntity");
String dataStr = "readers";
msgBldr.whatEntity(dataStr);
Assert.assertTrue(msgBldr.whatEntity().equals(dataStr), "whatEntity string=" + msgBldr.whatEntity());
}
/**
* Test method for {@link com.yahoo.athenz.common.server.log.impl.DefaultAuditLogMsgBuilder#build()}.
*/
@Test
public void testBuild() {
AuditLogMsgBuilder msgBldr = starter("testBuild");
String msg = msgBldr.build();
Assert.assertTrue(msg.contains("WHAT-api=(testBuild)"), "Test string=" + msg);
}
}
| apache-2.0 |
dingjun84/mq-backup | rocketmq-client/src/main/java/com/alibaba/rocketmq/client/producer/SendStatus.java | 1415 | /**
* Copyright (C) 2010-2013 Alibaba Group Holding Limited
*
* 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.alibaba.rocketmq.client.producer;
/**
* 这4种状态都表示消息已经成功到达Master
*
* @author shijia.wxr<vintage.wang@gmail.com>
* @since 2013-7-25
*/
public enum SendStatus {
// 消息发送成功
SEND_OK,
// 消息发送成功,但是服务器刷盘超时,消息已经进入服务器队列,只有此时服务器宕机,消息才会丢失
FLUSH_DISK_TIMEOUT,
// 消息发送成功,但是服务器同步到Slave时超时,消息已经进入服务器队列,只有此时服务器宕机,消息才会丢失
FLUSH_SLAVE_TIMEOUT,
// 消息发送成功,但是此时slave不可用,消息已经进入服务器队列,只有此时服务器宕机,消息才会丢失
SLAVE_NOT_AVAILABLE
}
| apache-2.0 |
mibo/janos | janos-core/src/main/java/org/apache/olingo/odata2/janos/processor/core/data/store/InMemoryDataStore.java | 10377 | /*******************************************************************************
* 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.olingo.odata2.janos.processor.core.data.store;
import org.apache.olingo.odata2.api.annotation.edm.EdmKey;
import org.apache.olingo.odata2.janos.processor.api.data.ReadOptions;
import org.apache.olingo.odata2.janos.processor.api.data.ReadResult;
import org.apache.olingo.odata2.janos.processor.api.data.store.DataStore;
import org.apache.olingo.odata2.janos.processor.api.data.store.DataStoreException;
import org.apache.olingo.odata2.janos.processor.core.util.AnnotationHelper;
import org.apache.olingo.odata2.janos.processor.core.util.AnnotationRuntimeException;
import org.apache.olingo.odata2.janos.processor.core.util.ClassHelper;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
*
*/
public class InMemoryDataStore<T> implements DataStore<T> {
private static final AnnotationHelper ANNOTATION_HELPER = new AnnotationHelper();
private final Map<KeyElement, T> dataStore;
private final Class<T> dataTypeClass;
private final KeyAccess keyAccess;
private static class InMemoryDataStoreHolder {
private static final Map<Class<?>, InMemoryDataStore<?>> c2ds = new HashMap<>();
@SuppressWarnings("unchecked")
static synchronized InMemoryDataStore<?> getInstance(final Class<?> clz, final boolean createNewInstance)
throws DataStoreException {
InMemoryDataStore<?> ds = c2ds.get(clz);
if (createNewInstance || ds == null) {
ds = new InMemoryDataStore<>((Class<Object>) clz);
c2ds.put(clz, ds);
}
return ds;
}
}
@SuppressWarnings("unchecked")
public static <T> InMemoryDataStore<T> createInMemory(final Class<T> clazz) throws DataStoreException {
return (InMemoryDataStore<T>) InMemoryDataStoreHolder.getInstance(clazz, true);
}
@SuppressWarnings("unchecked")
public static <T> InMemoryDataStore<T> createInMemory(final Class<T> clazz, final boolean keepExisting)
throws DataStoreException {
return (InMemoryDataStore<T>) InMemoryDataStoreHolder.getInstance(clazz, !keepExisting);
}
private InMemoryDataStore(final Map<KeyElement, T> wrapStore, final Class<T> clz) throws DataStoreException {
dataStore = Collections.synchronizedMap(wrapStore);
dataTypeClass = clz;
keyAccess = new KeyAccess(clz);
}
private InMemoryDataStore(final Class<T> clz) throws DataStoreException {
this(new HashMap<>(), clz);
}
@Override
public Class<T> getDataTypeClass() {
return dataTypeClass;
}
@Override
public String getName() {
return ANNOTATION_HELPER.extractEntityTypeName(dataTypeClass);
}
@Override
public T createInstance() {
try {
return dataTypeClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new AnnotationRuntimeException("Unable to create instance of class '" + dataTypeClass + "'.", e);
}
}
@Override
public T read(final T object) {
KeyElement objKeys = getKeys(object);
return dataStore.get(objKeys);
}
@Override
public Collection<T> read() {
return Collections.unmodifiableCollection(dataStore.values());
}
@Override
public ReadResult<T> read(ReadOptions readOptions) {
return ReadResult.forResult(new ArrayList<>(dataStore.values())).build();
}
@Override
public T create(final T object) throws DataStoreException {
KeyElement keyElement = getKeys(object);
return create(object, keyElement);
}
private T create(final T object, final KeyElement keyElement) throws DataStoreException {
synchronized (dataStore) {
final boolean replaceKeys = dataStore.containsKey(keyElement);
if (keyElement.keyValuesMissing() || replaceKeys) {
KeyElement newKey = createSetAndGetKeys(object, replaceKeys);
return this.create(object, newKey);
}
dataStore.put(keyElement, object);
}
return object;
}
@Override
public T update(final T object) {
KeyElement keyElement = getKeys(object);
synchronized (dataStore) {
dataStore.remove(keyElement);
dataStore.put(keyElement, object);
}
return object;
}
@Override
public T delete(final T object) {
KeyElement keyElement = getKeys(object);
synchronized (dataStore) {
return dataStore.remove(keyElement);
}
}
/**
* Are the key values equal for both instances.
* If all compared key values are <code>null</code> this also means equal.
*
* @param first first instance to check for key equal
* @param second second instance to check for key equal
* @return <code>true</code> if object instance have equal keys set.
*/
private boolean isKeyEqual(final T first, final T second) {
KeyElement firstKeys = getKeys(first);
KeyElement secondKeys = getKeys(second);
return firstKeys.equals(secondKeys);
}
/**
* Are the key values equal for both instances.
* If all compared key values are <code>null</code> this also means equal.
* Before object (keys) are compared it is validated that both object instance are NOT null
* and that both are from the same class as this {@link InMemoryDataStore} (see {@link #dataTypeClass}).
* For the equal check on {@link #dataTypeClass} instances without validation see
* {@link #isKeyEqual(Object, Object)}.
*
* @param first first instance to check for key equal
* @param second second instance to check for key equal
* @return <code>true</code> if object instance have equal keys set.
*/
@SuppressWarnings("unchecked")
@Override
public boolean isKeyEqualChecked(Object first, Object second) throws DataStoreException {
if(first == null || second == null) {
throw new DataStoreException("Tried to compare null values which is not allowed.");
} else if(first.getClass() != dataTypeClass) {
throw new DataStoreException("First value is no instance from required class '" + dataTypeClass + "'.");
} else if(second.getClass() != dataTypeClass) {
throw new DataStoreException("Second value is no instance from required class '" + dataTypeClass + "'.");
}
return isKeyEqual((T) first, (T) second);
}
private class KeyElement {
private int cachedHashCode = 42;
private final List<Object> keyValues;
public KeyElement(final int size) {
keyValues = new ArrayList<>(size);
}
private void addValue(final Object keyValue) {
keyValues.add(keyValue);
cachedHashCode = 89 * cachedHashCode + (keyValue != null ? keyValue.hashCode() : 0);
}
boolean keyValuesMissing() {
return keyValues.contains(null);
}
@Override
public int hashCode() {
return cachedHashCode;
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
@SuppressWarnings("unchecked")
final KeyElement other = (KeyElement) obj;
if (this.keyValues != other.keyValues && (this.keyValues == null || !this.keyValues.equals(other.keyValues))) {
return false;
}
return true;
}
@Override
public String toString() {
return "KeyElement{" + "cachedHashCode=" + cachedHashCode + ", keyValues=" + keyValues + '}';
}
}
private class KeyAccess {
final List<Field> keyFields;
final AtomicInteger idCounter = new AtomicInteger(1);
KeyAccess(final Class<?> clazz) throws DataStoreException {
keyFields = ANNOTATION_HELPER.getAnnotatedFields(clazz, EdmKey.class);
if (keyFields.isEmpty()) {
throw new DataStoreException("No EdmKey annotated fields found for class " + clazz);
}
}
KeyElement getKeyValues(final T object) {
KeyElement keyElement = new KeyElement(keyFields.size());
for (Field field : keyFields) {
Object keyValue = ClassHelper.getFieldValue(object, field);
keyElement.addValue(keyValue);
}
return keyElement;
}
KeyElement createSetAndGetKeys(final T object, final boolean replaceKeys) {
KeyElement keyElement = new KeyElement(keyFields.size());
for (Field field : keyFields) {
Object key = ClassHelper.getFieldValue(object, field);
if (key == null || replaceKeys) {
key = createKey(field);
ClassHelper.setFieldValue(object, field, key);
}
keyElement.addValue(key);
}
return keyElement;
}
private Object createKey(final Field field) {
Class<?> type = field.getType();
if (type == String.class) {
return String.valueOf(idCounter.getAndIncrement());
} else if (type == Integer.class || type == int.class) {
return idCounter.getAndIncrement();
} else if (type == Long.class || type == long.class) {
return (long) idCounter.getAndIncrement();
} else if (type == UUID.class) {
return UUID.randomUUID();
}
throw new UnsupportedOperationException("Automated key generation for type '" + type
+ "' is not supported (caused on field '" + field + "').");
}
}
private KeyElement getKeys(final T object) {
return keyAccess.getKeyValues(object);
}
private KeyElement createSetAndGetKeys(final T object, final boolean replaceKeys) throws DataStoreException {
return keyAccess.createSetAndGetKeys(object, replaceKeys);
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-lambda/src/main/java/com/amazonaws/services/lambda/model/Concurrency.java | 5728 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.lambda.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/Concurrency" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class Concurrency implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The number of concurrent executions that are reserved for this function. For more information, see <a
* href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-concurrency.html">Managing Concurrency</a>.
* </p>
*/
private Integer reservedConcurrentExecutions;
/**
* <p>
* The number of concurrent executions that are reserved for this function. For more information, see <a
* href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-concurrency.html">Managing Concurrency</a>.
* </p>
*
* @param reservedConcurrentExecutions
* The number of concurrent executions that are reserved for this function. For more information, see <a
* href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-concurrency.html">Managing
* Concurrency</a>.
*/
public void setReservedConcurrentExecutions(Integer reservedConcurrentExecutions) {
this.reservedConcurrentExecutions = reservedConcurrentExecutions;
}
/**
* <p>
* The number of concurrent executions that are reserved for this function. For more information, see <a
* href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-concurrency.html">Managing Concurrency</a>.
* </p>
*
* @return The number of concurrent executions that are reserved for this function. For more information, see <a
* href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-concurrency.html">Managing
* Concurrency</a>.
*/
public Integer getReservedConcurrentExecutions() {
return this.reservedConcurrentExecutions;
}
/**
* <p>
* The number of concurrent executions that are reserved for this function. For more information, see <a
* href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-concurrency.html">Managing Concurrency</a>.
* </p>
*
* @param reservedConcurrentExecutions
* The number of concurrent executions that are reserved for this function. For more information, see <a
* href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-concurrency.html">Managing
* Concurrency</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Concurrency withReservedConcurrentExecutions(Integer reservedConcurrentExecutions) {
setReservedConcurrentExecutions(reservedConcurrentExecutions);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getReservedConcurrentExecutions() != null)
sb.append("ReservedConcurrentExecutions: ").append(getReservedConcurrentExecutions());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof Concurrency == false)
return false;
Concurrency other = (Concurrency) obj;
if (other.getReservedConcurrentExecutions() == null ^ this.getReservedConcurrentExecutions() == null)
return false;
if (other.getReservedConcurrentExecutions() != null && other.getReservedConcurrentExecutions().equals(this.getReservedConcurrentExecutions()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getReservedConcurrentExecutions() == null) ? 0 : getReservedConcurrentExecutions().hashCode());
return hashCode;
}
@Override
public Concurrency clone() {
try {
return (Concurrency) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.lambda.model.transform.ConcurrencyMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| apache-2.0 |
alistairrutherford/transportation-xml-glasgow | src/main/java/com/netthreads/transportation/parser/data/CarParkDataFactory.java | 1117 | /**
* -----------------------------------------------------------------------
* Copyright 2013 - Alistair Rutherford - www.netthreads.co.uk
* -----------------------------------------------------------------------
*
* 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.netthreads.transportation.parser.data;
import com.netthreads.transportation.parser.DataFactory;
/**
* RSS Data factory.
*
*/
public class CarParkDataFactory implements DataFactory<CarParkData>
{
@Override
public CarParkData createRecord()
{
return new CarParkData();
}
}
| apache-2.0 |
powerunit/powerunit-eclipse | powerunit-eclipse-plugin/src/main/java/ch/powerunit/poweruniteclipse/runner/package-info.java | 838 | /**
* Powerunit - A JDK1.8 test framework
* Copyright (C) 2014 Mathieu Boretti.
*
* This file is part of Powerunit
*
* Powerunit is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Powerunit is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Powerunit. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author borettim
*
*/
package ch.powerunit.poweruniteclipse.runner; | apache-2.0 |
multi-os-engine/moe-core | moe.apple/moe.platform.ios/src/main/java/apple/spritekit/enums/SKTransitionDirection.java | 1095 | /*
Copyright 2014-2016 Intel Corporation
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 apple.spritekit.enums;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.NInt;
@Generated
public final class SKTransitionDirection {
@Generated @NInt public static final long Up = 0x0000000000000000L;
@Generated @NInt public static final long Down = 0x0000000000000001L;
@Generated @NInt public static final long Right = 0x0000000000000002L;
@Generated @NInt public static final long Left = 0x0000000000000003L;
@Generated
private SKTransitionDirection() {
}
}
| apache-2.0 |
comcloud-build/test-for-maven-and-jenkins | src/main/java/org/apache/mahout/math/buffer/ObjectBufferConsumer.java | 964 | /*
Copyright 1999 CERN - European Organization for Nuclear Research.
Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose
is hereby granted without fee, provided that the above copyright notice appear in all copies and
that both that copyright notice and this permission notice appear in supporting documentation.
CERN makes no representations about the suitability of this software for any purpose.
It is provided "as is" without expressed or implied warranty.
*/
package org.apache.mahout.math.buffer;
import org.apache.mahout.math.list.ObjectArrayList;
/** @deprecated until unit tests are in place. Until this time, this class/interface is unsupported. */
@Deprecated
public interface ObjectBufferConsumer {
/**
* Adds all elements of the specified list to the receiver.
*
* @param list the list of which all elements shall be added.
*/
void addAllOf(ObjectArrayList<Object> list);
}
| apache-2.0 |
JavaSaBr/jME3-SpaceShift-Editor | src/main/java/com/ss/editor/ui/component/asset/tree/resource/ResourceElementFactory.java | 892 | package com.ss.editor.ui.component.asset.tree.resource;
import com.ss.editor.annotation.FromAnyThread;
import com.ss.editor.manager.JavaFxImageManager;
import org.jetbrains.annotations.NotNull;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* The factory to create resource elements.
*
* @author JavaSaBr
*/
public class ResourceElementFactory {
/**
* Create a resource element for the file.
*
* @param file the file.
* @return the created resource element.
*/
@FromAnyThread
public static @NotNull ResourceElement createFor(@NotNull final Path file) {
if (Files.isDirectory(file)) {
return new FolderResourceElement(file);
} else if (JavaFxImageManager.isImage(file)) {
return new ImageResourceElement(file);
} else {
return new FileResourceElement(file);
}
}
}
| apache-2.0 |
shadyeltobgy/wcm-io-caconfig | compat/src/main/java/io/wcm/config/core/management/ConfigurationFinder.java | 3081 | /*
* #%L
* wcm.io
* %%
* Copyright (C) 2016 wcm.io
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package io.wcm.config.core.management;
import java.util.Iterator;
import org.apache.sling.api.resource.Resource;
import org.osgi.annotation.versioning.ProviderType;
import io.wcm.config.api.Configuration;
/**
* Find matching configurations for a resource.
* @deprecated Use Sling Context-Aware Configuration Management API
*/
@Deprecated
@ProviderType
public interface ConfigurationFinder {
/**
* Tries to find the closed matching configuration for the given path.
* Tries to detect the application for the resource using {@link ApplicationFinder} to use the
* configuration finder strategy of this application.
* If no application is found, or it does not provide such a strategy, all configuration finder strategies are
* enquired, iterated in order of service ranking.
* @param resource Content resource
* @return Configuration or null if none was found
*/
Configuration find(Resource resource);
/**
* Tries to find the closed matching configuration for the given path.
* Only the configuration finding strategies of the given application are used.
* @param resource Content resource
* @param applicationId Application Id
* @return Configuration or null if none was found
*/
Configuration find(Resource resource, String applicationId);
/**
* Tries to find all enclosing configurations for the given path.
* Tries to detect the application for the resource using {@link ApplicationFinder} to use the
* configuration finder strategy of this application.
* If no application is found, or it does not provide such a strategy, all configuration finder strategies are
* enquired, iterated in order of service ranking.
* @param resource Content resource
* @return List of configurations that where found in the given path (in order of closest matching first).
* If none are found an empty iterator is returned.
*/
Iterator<Configuration> findAll(Resource resource);
/**
* Tries to find all enclosing configurations for the given path.
* Only the configuration finding strategies of the given application are used.
* @param resource Content resource
* @param applicationId Application Id
* @return List of configurations that where found in the given path (in order of closest matching first).
* If none are found an empty iterator is returned.
*/
Iterator<Configuration> findAll(Resource resource, String applicationId);
}
| apache-2.0 |
dongaihua/highlight-elasticsearch | src/main/java/org/elasticsearch/action/admin/indices/segments/IndicesSegmentResponse.java | 7726 | /*
* Licensed to ElasticSearch and Shay Banon 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.action.admin.indices.segments;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.elasticsearch.action.ShardOperationFailedException;
import org.elasticsearch.action.support.broadcast.BroadcastOperationResponse;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentBuilderString;
import org.elasticsearch.index.engine.Segment;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class IndicesSegmentResponse extends BroadcastOperationResponse implements ToXContent {
private ShardSegments[] shards;
private Map<String, IndexSegments> indicesSegments;
IndicesSegmentResponse() {
}
IndicesSegmentResponse(ShardSegments[] shards, ClusterState clusterState, int totalShards, int successfulShards, int failedShards, List<ShardOperationFailedException> shardFailures) {
super(totalShards, successfulShards, failedShards, shardFailures);
this.shards = shards;
}
public Map<String, IndexSegments> getIndices() {
if (indicesSegments != null) {
return indicesSegments;
}
Map<String, IndexSegments> indicesSegments = Maps.newHashMap();
Set<String> indices = Sets.newHashSet();
for (ShardSegments shard : shards) {
indices.add(shard.getIndex());
}
for (String index : indices) {
List<ShardSegments> shards = Lists.newArrayList();
for (ShardSegments shard : this.shards) {
if (shard.getShardRouting().index().equals(index)) {
shards.add(shard);
}
}
indicesSegments.put(index, new IndexSegments(index, shards.toArray(new ShardSegments[shards.size()])));
}
this.indicesSegments = indicesSegments;
return indicesSegments;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
shards = new ShardSegments[in.readVInt()];
for (int i = 0; i < shards.length; i++) {
shards[i] = ShardSegments.readShardSegments(in);
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeVInt(shards.length);
for (ShardSegments shard : shards) {
shard.writeTo(out);
}
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(Fields.INDICES);
for (IndexSegments indexSegments : getIndices().values()) {
builder.startObject(indexSegments.getIndex(), XContentBuilder.FieldCaseConversion.NONE);
builder.startObject(Fields.SHARDS);
for (IndexShardSegments indexSegment : indexSegments) {
builder.startArray(Integer.toString(indexSegment.getShardId().id()));
for (ShardSegments shardSegments : indexSegment) {
builder.startObject();
builder.startObject(Fields.ROUTING);
builder.field(Fields.STATE, shardSegments.getShardRouting().state());
builder.field(Fields.PRIMARY, shardSegments.getShardRouting().primary());
builder.field(Fields.NODE, shardSegments.getShardRouting().currentNodeId());
if (shardSegments.getShardRouting().relocatingNodeId() != null) {
builder.field(Fields.RELOCATING_NODE, shardSegments.getShardRouting().relocatingNodeId());
}
builder.endObject();
builder.field(Fields.NUM_COMMITTED_SEGMENTS, shardSegments.getNumberOfCommitted());
builder.field(Fields.NUM_SEARCH_SEGMENTS, shardSegments.getNumberOfSearch());
builder.startObject(Fields.SEGMENTS);
for (Segment segment : shardSegments) {
builder.startObject(segment.name());
builder.field(Fields.GENERATION, segment.generation());
builder.field(Fields.NUM_DOCS, segment.numDocs());
builder.field(Fields.DELETED_DOCS, segment.deletedDocs());
builder.field(Fields.SIZE, segment.size().toString());
builder.field(Fields.SIZE_IN_BYTES, segment.sizeInBytes());
builder.field(Fields.COMMITTED, segment.committed());
builder.field(Fields.SEARCH, segment.search());
builder.endObject();
}
builder.endObject();
builder.endObject();
}
builder.endArray();
}
builder.endObject();
builder.endObject();
}
builder.endObject();
return builder;
}
static final class Fields {
static final XContentBuilderString INDICES = new XContentBuilderString("indices");
static final XContentBuilderString SHARDS = new XContentBuilderString("shards");
static final XContentBuilderString ROUTING = new XContentBuilderString("routing");
static final XContentBuilderString STATE = new XContentBuilderString("state");
static final XContentBuilderString PRIMARY = new XContentBuilderString("primary");
static final XContentBuilderString NODE = new XContentBuilderString("node");
static final XContentBuilderString RELOCATING_NODE = new XContentBuilderString("relocating_node");
static final XContentBuilderString SEGMENTS = new XContentBuilderString("segments");
static final XContentBuilderString GENERATION = new XContentBuilderString("generation");
static final XContentBuilderString NUM_COMMITTED_SEGMENTS = new XContentBuilderString("num_committed_segments");
static final XContentBuilderString NUM_SEARCH_SEGMENTS = new XContentBuilderString("num_search_segments");
static final XContentBuilderString NUM_DOCS = new XContentBuilderString("num_docs");
static final XContentBuilderString DELETED_DOCS = new XContentBuilderString("deleted_docs");
static final XContentBuilderString SIZE = new XContentBuilderString("size");
static final XContentBuilderString SIZE_IN_BYTES = new XContentBuilderString("size_in_bytes");
static final XContentBuilderString COMMITTED = new XContentBuilderString("committed");
static final XContentBuilderString SEARCH = new XContentBuilderString("search");
}
} | apache-2.0 |
Mrsananabos/ashveytser | car_market_annot/src/main/java/ru/job4j/carMarket/controller/AuthenticController.java | 1884 | package ru.job4j.carMarket.controller;
import org.json.JSONObject;
import ru.job4j.carMarket.model.entity.User;
import ru.job4j.carMarket.model.service.impl.UserValidateImpl;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
public class AuthenticController extends HttpServlet {
static final String CONTENT_TYPE = "text/html; charset=windows-1251";
static final String LOGIN = "login";
static final String PASSWORD = "password";
static final String STATUS = "status";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType(CONTENT_TYPE);
String login = "null";
HttpSession session = req.getSession();
login = (String) session.getAttribute(LOGIN);
PrintWriter writer = new PrintWriter(resp.getOutputStream());
String answer = new JSONObject()
.put(LOGIN, login).toString();
writer.append(answer);
writer.flush();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
HttpSession session = req.getSession();
PrintWriter writer = new PrintWriter(resp.getOutputStream());
String login = req.getParameter(LOGIN);
String password = req.getParameter(PASSWORD);
String answer = "0";
User result = UserValidateImpl.getInstance().addUser(login, password);
if (result != null) {
session.setAttribute(LOGIN, login);
answer = "1";
}
String response = new JSONObject()
.put(STATUS, answer).toString();
writer.append(response);
writer.flush();
}
}
| apache-2.0 |
consulo/consulo | modules/base/core-impl/src/main/java/com/intellij/lang/impl/PsiBuilderImpl.java | 66797 | /*
* 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 com.intellij.lang.impl;
import com.intellij.lang.*;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.progress.EmptyProgressIndicator;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressIndicatorProvider;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiErrorElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.TokenType;
import com.intellij.psi.impl.BlockSupportImpl;
import com.intellij.psi.impl.DiffLog;
import com.intellij.psi.impl.source.CharTableImpl;
import com.intellij.psi.impl.source.resolve.FileContextUtil;
import com.intellij.psi.impl.source.tree.*;
import com.intellij.psi.text.BlockSupport;
import com.intellij.psi.tree.*;
import com.intellij.util.ArrayUtil;
import com.intellij.util.CharTable;
import com.intellij.util.ExceptionUtil;
import com.intellij.util.TripleFunction;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.Convertor;
import com.intellij.util.containers.LimitedPool;
import com.intellij.util.containers.Stack;
import com.intellij.util.diff.DiffTreeChangeBuilder;
import com.intellij.util.diff.FlyweightCapableTreeStructure;
import com.intellij.util.diff.ShallowNodeComparator;
import com.intellij.util.text.CharArrayUtil;
import consulo.lang.LanguageVersion;
import consulo.localize.LocalizeValue;
import consulo.logging.Logger;
import consulo.util.collection.primitive.ints.IntMaps;
import consulo.util.collection.primitive.ints.IntObjectMap;
import consulo.util.dataholder.Key;
import consulo.util.dataholder.UnprotectedUserDataHolder;
import consulo.util.lang.ThreeState;
import org.jetbrains.annotations.NonNls;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* @author max
*/
public class PsiBuilderImpl extends UnprotectedUserDataHolder implements PsiBuilder {
private static final Logger LOG = Logger.getInstance(PsiBuilderImpl.class);
// function stored in PsiBuilderImpl' user data which called during reparse when merge algorithm is not sure what to merge
public static final Key<TripleFunction<ASTNode, LighterASTNode, FlyweightCapableTreeStructure<LighterASTNode>, ThreeState>> CUSTOM_COMPARATOR =
Key.create("CUSTOM_COMPARATOR");
private static final Key<LazyParseableTokensCache> LAZY_PARSEABLE_TOKENS = Key.create("LAZY_PARSEABLE_TOKENS");
private static TokenSet ourAnyLanguageWhitespaceTokens = TokenSet.EMPTY;
private final Project myProject;
private final LanguageVersion myLanguageVersion;
private PsiFile myFile;
private int[] myLexStarts;
private IElementType[] myLexTypes;
private int myCurrentLexeme;
private final MyList myProduction = new MyList();
private final Lexer myLexer;
private final TokenSet myWhitespaces;
private TokenSet myComments;
private CharTable myCharTable;
private final CharSequence myText;
private final CharSequence myLastCommittedText;
private final char[] myTextArray;
private boolean myDebugMode;
private int myLexemeCount;
private boolean myTokenTypeChecked;
private ITokenTypeRemapper myRemapper;
private WhitespaceSkippedCallback myWhitespaceSkippedCallback;
private final ASTNode myOriginalTree;
private final MyTreeStructure myParentLightTree;
private final int myOffset;
private IElementType myCachedTokenType;
private final IntObjectMap<LazyParseableToken> myChameleonCache = IntMaps.newIntObjectHashMap();
private final LimitedPool<StartMarker> START_MARKERS = new LimitedPool<>(2000, new LimitedPool.ObjectFactory<StartMarker>() {
@Nonnull
@Override
public StartMarker create() {
return new StartMarker();
}
@Override
public void cleanup(@Nonnull final StartMarker startMarker) {
startMarker.clean();
}
});
private final LimitedPool<DoneMarker> DONE_MARKERS = new LimitedPool<>(2000, new LimitedPool.ObjectFactory<DoneMarker>() {
@Nonnull
@Override
public DoneMarker create() {
return new DoneMarker();
}
@Override
public void cleanup(@Nonnull final DoneMarker doneMarker) {
doneMarker.clean();
}
});
public static void registerWhitespaceToken(@Nonnull IElementType type) {
ourAnyLanguageWhitespaceTokens = TokenSet.orSet(ourAnyLanguageWhitespaceTokens, TokenSet.create(type));
}
public PsiBuilderImpl(@Nullable Project project,
@Nullable PsiFile containingFile,
@Nonnull ParserDefinition parserDefinition,
@Nonnull Lexer lexer,
@Nonnull LanguageVersion languageVersion,
@Nullable CharTable charTable,
@Nonnull final CharSequence text,
@Nullable ASTNode originalTree,
@Nullable MyTreeStructure parentLightTree) {
this(project, containingFile, languageVersion, parserDefinition, lexer, charTable, text, originalTree, originalTree == null ? null : originalTree.getText(),
parentLightTree, null);
}
public PsiBuilderImpl(@Nonnull Project project,
@Nonnull ParserDefinition parserDefinition,
@Nonnull LanguageVersion languageVersion,
@Nonnull Lexer lexer,
@Nonnull ASTNode chameleon,
@Nonnull CharSequence text) {
this(project, SharedImplUtil.getContainingFile(chameleon), languageVersion, parserDefinition, lexer, SharedImplUtil.findCharTableByTree(chameleon), text,
Pair.getFirst(chameleon.getUserData(BlockSupport.TREE_TO_BE_REPARSED)), Pair.getSecond(chameleon.getUserData(BlockSupport.TREE_TO_BE_REPARSED)), null,
chameleon);
}
public PsiBuilderImpl(@Nonnull Project project,
@Nonnull ParserDefinition parserDefinition,
@Nonnull LanguageVersion languageVersion,
@Nonnull Lexer lexer,
@Nonnull LighterLazyParseableNode chameleon,
@Nonnull CharSequence text) {
this(project, chameleon.getContainingFile(), languageVersion, parserDefinition, lexer, chameleon.getCharTable(), text, null, null,
((LazyParseableToken)chameleon).myParentStructure, chameleon);
}
private PsiBuilderImpl(@Nullable Project project,
@Nullable PsiFile containingFile,
@Nonnull LanguageVersion languageVersion,
@Nonnull ParserDefinition parserDefinition,
@Nonnull Lexer lexer,
@Nullable CharTable charTable,
@Nonnull CharSequence text,
@Nullable ASTNode originalTree,
@Nullable CharSequence lastCommittedText,
@Nullable MyTreeStructure parentLightTree,
@Nullable Object parentCachingNode) {
myProject = project;
myFile = containingFile;
myLanguageVersion = languageVersion;
myText = text;
myTextArray = CharArrayUtil.fromSequenceWithoutCopying(text);
myLexer = lexer;
myWhitespaces = parserDefinition.getWhitespaceTokens(languageVersion);
myComments = parserDefinition.getCommentTokens(languageVersion);
myCharTable = charTable;
myOriginalTree = originalTree;
myLastCommittedText = lastCommittedText;
if ((originalTree == null) != (lastCommittedText == null)) {
throw new IllegalArgumentException("originalTree and lastCommittedText must be null/notnull together but got: originalTree=" +
originalTree +
"; lastCommittedText=" +
(lastCommittedText == null ? null : "'" + StringUtil.first(lastCommittedText, 80, true) + "'"));
}
myParentLightTree = parentLightTree;
myOffset = parentCachingNode instanceof LazyParseableToken ? ((LazyParseableToken)parentCachingNode).getStartOffset() : 0;
cacheLexemes(parentCachingNode);
}
private void cacheLexemes(@Nullable Object parentCachingNode) {
int[] lexStarts = null;
IElementType[] lexTypes = null;
int lexemeCount = -1;
// set this to true to check that re-lexing of lazy parseables produces the same sequence as cached one
boolean doLexingOptimizationCorrectionCheck = false;
if (parentCachingNode instanceof LazyParseableToken) {
final LazyParseableToken parentToken = (LazyParseableToken)parentCachingNode;
// there are two types of lazy parseable tokens out there: collapsed out of individual tokens or single token that needs to be expanded
// in first case parent PsiBuilder has all our text lexed so no need to do it again
int tokenCount = parentToken.myEndIndex - parentToken.myStartIndex;
if (tokenCount != 1) { // not expand single lazy parseable token case
lexStarts = new int[tokenCount + 1];
System.arraycopy(parentToken.myBuilder.myLexStarts, parentToken.myStartIndex, lexStarts, 0, tokenCount);
int diff = parentToken.myBuilder.myLexStarts[parentToken.myStartIndex];
for (int i = 0; i < tokenCount; ++i) lexStarts[i] -= diff;
lexStarts[tokenCount] = myText.length();
lexTypes = new IElementType[tokenCount];
System.arraycopy(parentToken.myBuilder.myLexTypes, parentToken.myStartIndex, lexTypes, 0, tokenCount);
lexemeCount = tokenCount;
}
ProgressIndicatorProvider.checkCanceled();
//noinspection ConstantConditions
if (!doLexingOptimizationCorrectionCheck && lexemeCount != -1) {
myLexStarts = lexStarts;
myLexTypes = lexTypes;
myLexemeCount = lexemeCount;
return;
}
}
else if (parentCachingNode instanceof LazyParseableElement) {
final LazyParseableElement parentElement = (LazyParseableElement)parentCachingNode;
final LazyParseableTokensCache cachedTokens = parentElement.getUserData(LAZY_PARSEABLE_TOKENS);
parentElement.putUserData(LAZY_PARSEABLE_TOKENS, null);
//noinspection ConstantConditions
if (!doLexingOptimizationCorrectionCheck && cachedTokens != null) {
myLexStarts = cachedTokens.myLexStarts;
myLexTypes = cachedTokens.myLexTypes;
myLexemeCount = myLexTypes.length;
return;
}
}
int approxLexCount = Math.max(10, myText.length() / 5);
myLexStarts = new int[approxLexCount];
myLexTypes = new IElementType[approxLexCount];
myLexer.start(myText);
int i = 0;
int offset = 0;
while (true) {
IElementType type = myLexer.getTokenType();
if (type == null) break;
if (i % 20 == 0) ProgressIndicatorProvider.checkCanceled();
if (i >= myLexTypes.length - 1) {
resizeLexemes(i * 3 / 2);
}
int tokenStart = myLexer.getTokenStart();
if (tokenStart < offset) {
final StringBuilder sb = new StringBuilder();
final IElementType tokenType = myLexer.getTokenType();
sb.append("Token sequence broken").append("\n this: '").append(myLexer.getTokenText()).append("' (").append(tokenType).append(':')
.append(tokenType != null ? tokenType.getLanguage() : null).append(") ").append(tokenStart).append(":").append(myLexer.getTokenEnd());
if (i > 0) {
final int prevStart = myLexStarts[i - 1];
sb.append("\n prev: '").append(myText.subSequence(prevStart, offset)).append("' (").append(myLexTypes[i - 1]).append(':')
.append(myLexTypes[i - 1].getLanguage()).append(") ").append(prevStart).append(":").append(offset);
}
final int quoteStart = Math.max(tokenStart - 256, 0);
final int quoteEnd = Math.min(tokenStart + 256, myText.length());
sb.append("\n quote: [").append(quoteStart).append(':').append(quoteEnd).append("] '").append(myText.subSequence(quoteStart, quoteEnd)).append('\'');
LOG.error(sb);
}
myLexStarts[i] = offset = tokenStart;
myLexTypes[i] = type;
i++;
myLexer.advance();
}
myLexStarts[i] = myText.length();
myLexemeCount = i;
clearCachedTokenType();
//noinspection ConstantConditions
if (doLexingOptimizationCorrectionCheck && lexemeCount != -1) {
assert lexemeCount == myLexemeCount;
for (int j = 0; j < lexemeCount; ++j) {
if (myLexStarts[j] != lexStarts[j] || myLexTypes[j] != lexTypes[j]) {
assert false;
}
}
assert myLexStarts[lexemeCount] == lexStarts[lexemeCount];
}
}
@Override
public Project getProject() {
return myProject;
}
@Override
public void enforceCommentTokens(@Nonnull TokenSet tokens) {
myComments = tokens;
}
@Override
@Nullable
public LighterASTNode getLatestDoneMarker() {
int index = myProduction.size() - 1;
while (index >= 0) {
ProductionMarker marker = myProduction.get(index);
if (marker instanceof DoneMarker) return ((DoneMarker)marker).myStart;
--index;
}
return null;
}
private abstract static class Node implements LighterASTNode {
public abstract int hc();
}
public abstract static class ProductionMarker extends Node {
protected int myLexemeIndex;
protected WhitespacesAndCommentsBinder myEdgeTokenBinder;
protected ProductionMarker myParent;
protected ProductionMarker myNext;
public void clean() {
myLexemeIndex = 0;
myParent = myNext = null;
}
public void remapTokenType(@Nonnull IElementType type) {
throw new UnsupportedOperationException("Shall not be called on this kind of markers");
}
public int getStartIndex() {
return myLexemeIndex;
}
public int getEndIndex() {
throw new UnsupportedOperationException("Shall not be called on this kind of markers");
}
}
private static class StartMarker extends ProductionMarker implements Marker {
private PsiBuilderImpl myBuilder;
private IElementType myType;
private DoneMarker myDoneMarker;
private Throwable myDebugAllocationPosition;
private ProductionMarker myFirstChild;
private ProductionMarker myLastChild;
private int myHC = -1;
private StartMarker() {
myEdgeTokenBinder = WhitespacesBinders.DEFAULT_LEFT_BINDER;
}
@Override
public void clean() {
super.clean();
myBuilder = null;
myType = null;
myDoneMarker = null;
myDebugAllocationPosition = null;
myFirstChild = myLastChild = null;
myHC = -1;
myEdgeTokenBinder = WhitespacesBinders.DEFAULT_LEFT_BINDER;
}
@Override
public int hc() {
if (myHC == -1) {
PsiBuilderImpl builder = myBuilder;
int hc = 0;
final CharSequence buf = builder.myText;
final char[] bufArray = builder.myTextArray;
ProductionMarker child = myFirstChild;
int lexIdx = myLexemeIndex;
while (child != null) {
int lastLeaf = child.myLexemeIndex;
for (int i = builder.myLexStarts[lexIdx]; i < builder.myLexStarts[lastLeaf]; i++) {
hc += bufArray != null ? bufArray[i] : buf.charAt(i);
}
lexIdx = lastLeaf;
hc += child.hc();
if (child instanceof StartMarker) {
lexIdx = ((StartMarker)child).myDoneMarker.myLexemeIndex;
}
child = child.myNext;
}
for (int i = builder.myLexStarts[lexIdx]; i < builder.myLexStarts[myDoneMarker.myLexemeIndex]; i++) {
hc += bufArray != null ? bufArray[i] : buf.charAt(i);
}
myHC = hc;
}
return myHC;
}
@Override
public int getStartOffset() {
return myBuilder.myLexStarts[myLexemeIndex] + myBuilder.myOffset;
}
@Override
public int getEndOffset() {
return myBuilder.myLexStarts[myDoneMarker.myLexemeIndex] + myBuilder.myOffset;
}
@Override
public int getEndIndex() {
return myDoneMarker.myLexemeIndex;
}
public void addChild(@Nonnull ProductionMarker node) {
if (myFirstChild == null) {
myFirstChild = node;
myLastChild = node;
}
else {
myLastChild.myNext = node;
myLastChild = node;
}
}
@Nonnull
@Override
public Marker precede() {
return myBuilder.precede(this);
}
@Override
public void drop() {
myBuilder.drop(this);
}
@Override
public void rollbackTo() {
myBuilder.rollbackTo(this);
}
@Override
public void done(@Nonnull IElementType type) {
myType = type;
myBuilder.done(this);
}
@Override
public void collapse(@Nonnull IElementType type) {
myType = type;
myBuilder.collapse(this);
}
@Override
public void doneBefore(@Nonnull IElementType type, @Nonnull Marker before) {
myType = type;
myBuilder.doneBefore(this, before);
}
@Override
public void doneBefore(@Nonnull final IElementType type, @Nonnull final Marker before, @Nonnull final LocalizeValue errorMessage) {
StartMarker marker = (StartMarker)before;
myBuilder.myProduction.add(myBuilder.myProduction.lastIndexOf(marker), new ErrorItem(myBuilder, errorMessage, marker.myLexemeIndex));
doneBefore(type, before);
}
@Override
public void error(@Nonnull LocalizeValue message) {
myType = TokenType.ERROR_ELEMENT;
myBuilder.error(this, message);
}
@Override
public void errorBefore(@Nonnull final LocalizeValue message, @Nonnull final Marker before) {
myType = TokenType.ERROR_ELEMENT;
myBuilder.errorBefore(this, message, before);
}
@Override
public IElementType getTokenType() {
return myType;
}
@Override
public void remapTokenType(@Nonnull IElementType type) {
//assert myType != null && type != null;
myType = type;
}
@Override
public void setCustomEdgeTokenBinders(final WhitespacesAndCommentsBinder left, final WhitespacesAndCommentsBinder right) {
if (left != null) {
myEdgeTokenBinder = left;
}
if (right != null) {
if (myDoneMarker == null) throw new IllegalArgumentException("Cannot set right-edge processor for unclosed marker");
myDoneMarker.myEdgeTokenBinder = right;
}
}
@Override
public String toString() {
if (myBuilder == null) return "<dropped>";
boolean isDone = myDoneMarker != null;
CharSequence originalText = myBuilder.getOriginalText();
int startOffset = getStartOffset() - myBuilder.myOffset;
int endOffset = isDone ? getEndOffset() - myBuilder.myOffset : myBuilder.getCurrentOffset();
CharSequence text = originalText.subSequence(startOffset, endOffset);
return isDone ? text.toString() : text + "\u2026";
}
}
@Nonnull
private Marker precede(final StartMarker marker) {
int idx = myProduction.lastIndexOf(marker);
if (idx < 0) {
LOG.error("Cannot precede dropped or rolled-back marker");
}
StartMarker pre = createMarker(marker.myLexemeIndex);
myProduction.add(idx, pre);
return pre;
}
private abstract static class Token extends Node {
protected PsiBuilderImpl myBuilder;
private IElementType myTokenType;
private int myTokenStart;
private int myTokenEnd;
private int myHC = -1;
private StartMarker myParentNode;
public void clean() {
myBuilder = null;
myHC = -1;
myParentNode = null;
}
@Override
public int hc() {
if (myHC == -1) {
int hc = 0;
if (myTokenType instanceof TokenWrapper) {
final CharSequence value = ((TokenWrapper)myTokenType).getValue();
for (int i = 0; i < value.length(); i++) {
hc += value.charAt(i);
}
}
else {
final int start = myTokenStart;
final int end = myTokenEnd;
final CharSequence buf = myBuilder.myText;
final char[] bufArray = myBuilder.myTextArray;
for (int i = start; i < end; i++) {
hc += bufArray != null ? bufArray[i] : buf.charAt(i);
}
}
myHC = hc;
}
return myHC;
}
@Override
public int getEndOffset() {
return myTokenEnd + myBuilder.myOffset;
}
@Override
public int getStartOffset() {
return myTokenStart + myBuilder.myOffset;
}
@Nonnull
public CharSequence getText() {
if (myTokenType instanceof TokenWrapper) {
return ((TokenWrapper)myTokenType).getValue();
}
return myBuilder.myText.subSequence(myTokenStart, myTokenEnd);
}
@Nonnull
@Override
public IElementType getTokenType() {
return myTokenType;
}
void initToken(@Nonnull IElementType type, @Nonnull PsiBuilderImpl builder, StartMarker parent, int start, int end) {
myParentNode = parent;
myBuilder = builder;
myTokenType = type;
myTokenStart = start;
myTokenEnd = end;
}
}
private static class TokenNode extends Token implements LighterASTTokenNode {
@Override
public String toString() {
return getText().toString();
}
}
private static class LazyParseableToken extends Token implements LighterLazyParseableNode {
private MyTreeStructure myParentStructure;
private FlyweightCapableTreeStructure<LighterASTNode> myParsed;
private int myStartIndex;
private int myEndIndex;
@Override
public void clean() {
myBuilder.myChameleonCache.remove(getStartOffset());
super.clean();
myParentStructure = null;
myParsed = null;
}
@Override
public PsiFile getContainingFile() {
return myBuilder.myFile;
}
@Override
public CharTable getCharTable() {
return myBuilder.myCharTable;
}
public FlyweightCapableTreeStructure<LighterASTNode> parseContents() {
if (myParsed == null) {
myParsed = ((ILightLazyParseableElementType)getTokenType()).parseContents(this);
}
return myParsed;
}
@Override
public boolean accept(@Nonnull Visitor visitor) {
for (int i = myStartIndex; i < myEndIndex; i++) {
IElementType type = myBuilder.myLexTypes[i];
if (!visitor.visit(type)) {
return false;
}
}
return true;
}
}
private static class DoneMarker extends ProductionMarker {
private StartMarker myStart;
private boolean myCollapse;
DoneMarker() {
myEdgeTokenBinder = WhitespacesBinders.DEFAULT_RIGHT_BINDER;
}
DoneMarker(final StartMarker marker, final int currentLexeme) {
this();
myLexemeIndex = currentLexeme;
myStart = marker;
}
@Override
public void clean() {
super.clean();
myStart = null;
myEdgeTokenBinder = WhitespacesBinders.DEFAULT_RIGHT_BINDER;
}
@Override
public int hc() {
throw new UnsupportedOperationException("Shall not be called on this kind of markers");
}
@Nonnull
@Override
public IElementType getTokenType() {
throw new UnsupportedOperationException("Shall not be called on this kind of markers");
}
@Override
public int getEndOffset() {
throw new UnsupportedOperationException("Shall not be called on this kind of markers");
}
@Override
public int getStartOffset() {
throw new UnsupportedOperationException("Shall not be called on this kind of markers");
}
}
private static class DoneWithErrorMarker extends DoneMarker {
private final LocalizeValue myMessage;
private DoneWithErrorMarker(@Nonnull StartMarker marker, final int currentLexeme, @Nonnull LocalizeValue message) {
super(marker, currentLexeme);
myMessage = message;
}
}
private static class ErrorItem extends ProductionMarker {
private final PsiBuilderImpl myBuilder;
private final LocalizeValue myMessage;
ErrorItem(final PsiBuilderImpl builder, final LocalizeValue message, final int idx) {
myBuilder = builder;
myMessage = message;
myLexemeIndex = idx;
myEdgeTokenBinder = WhitespacesBinders.DEFAULT_RIGHT_BINDER;
}
@Override
public int hc() {
return 0;
}
@Override
public int getEndOffset() {
return myBuilder.myLexStarts[myLexemeIndex] + myBuilder.myOffset;
}
@Override
public int getStartOffset() {
return myBuilder.myLexStarts[myLexemeIndex] + myBuilder.myOffset;
}
@Nonnull
@Override
public IElementType getTokenType() {
return TokenType.ERROR_ELEMENT;
}
}
@Nonnull
@Override
public CharSequence getOriginalText() {
return myText;
}
@Override
@Nullable
public IElementType getTokenType() {
IElementType cached = myCachedTokenType;
if (cached == null) {
myCachedTokenType = cached = calcTokenType();
}
return cached;
}
private void clearCachedTokenType() {
myCachedTokenType = null;
}
private IElementType remapCurrentToken() {
if (myCachedTokenType != null) return myCachedTokenType;
if (myRemapper != null) {
remapCurrentToken(
myRemapper.filter(myLexTypes[myCurrentLexeme], myLexStarts[myCurrentLexeme], myLexStarts[myCurrentLexeme + 1], myLexer.getBufferSequence()));
}
return myLexTypes[myCurrentLexeme];
}
private IElementType calcTokenType() {
if (eof()) return null;
if (myRemapper != null) {
//remaps current token, and following, which remaps to spaces and comments
skipWhitespace();
}
return myLexTypes[myCurrentLexeme];
}
@Override
public void setTokenTypeRemapper(ITokenTypeRemapper remapper) {
myRemapper = remapper;
myTokenTypeChecked = false;
clearCachedTokenType();
}
@Override
public void remapCurrentToken(IElementType type) {
myLexTypes[myCurrentLexeme] = type;
clearCachedTokenType();
}
@Nullable
@Override
public IElementType lookAhead(int steps) {
if (eof()) { // ensure we skip over whitespace if it's needed
return null;
}
int cur = myCurrentLexeme;
while (steps > 0) {
++cur;
while (cur < myLexemeCount && whitespaceOrComment(myLexTypes[cur])) {
cur++;
}
steps--;
}
return cur < myLexemeCount ? myLexTypes[cur] : null;
}
@Override
public IElementType rawLookup(int steps) {
int cur = myCurrentLexeme + steps;
return cur < myLexemeCount && cur >= 0 ? myLexTypes[cur] : null;
}
@Override
public int rawTokenTypeStart(int steps) {
int cur = myCurrentLexeme + steps;
if (cur < 0) return -1;
if (cur >= myLexemeCount) return getOriginalText().length();
return myLexStarts[cur];
}
@Override
public int rawTokenIndex() {
return myCurrentLexeme;
}
@Override
public void setWhitespaceSkippedCallback(@Nullable final WhitespaceSkippedCallback callback) {
myWhitespaceSkippedCallback = callback;
}
@Override
public void advanceLexer() {
ProgressIndicatorProvider.checkCanceled();
if (eof()) return;
if (!myTokenTypeChecked) {
LOG.error("Probably a bug: eating token without its type checking");
}
myTokenTypeChecked = false;
myCurrentLexeme++;
clearCachedTokenType();
}
private void skipWhitespace() {
while (myCurrentLexeme < myLexemeCount && whitespaceOrComment(remapCurrentToken())) {
onSkip(myLexTypes[myCurrentLexeme], myLexStarts[myCurrentLexeme],
myCurrentLexeme + 1 < myLexemeCount ? myLexStarts[myCurrentLexeme + 1] : myText.length());
myCurrentLexeme++;
clearCachedTokenType();
}
}
private void onSkip(IElementType type, int start, int end) {
if (myWhitespaceSkippedCallback != null) {
myWhitespaceSkippedCallback.onSkip(type, start, end);
}
}
@Override
public int getCurrentOffset() {
if (eof()) return getOriginalText().length();
return myLexStarts[myCurrentLexeme];
}
@Override
@Nullable
public String getTokenText() {
CharSequence tokenSequence = getTokenSequence();
return tokenSequence == null ? null : tokenSequence.toString();
}
@Nullable
@Override
public CharSequence getTokenSequence() {
if (eof()) return null;
final IElementType type = getTokenType();
if (type instanceof TokenWrapper) {
return ((TokenWrapper)type).getValue();
}
return myText.subSequence(myLexStarts[myCurrentLexeme], myLexStarts[myCurrentLexeme + 1]);
}
private void resizeLexemes(final int newSize) {
myLexStarts = ArrayUtil.realloc(myLexStarts, newSize + 1);
myLexTypes = ArrayUtil.realloc(myLexTypes, newSize, IElementType.ARRAY_FACTORY);
clearCachedTokenType();
}
public boolean whitespaceOrComment(IElementType token) {
return myWhitespaces.contains(token) || myComments.contains(token);
}
@Nonnull
@Override
public Marker mark() {
if (!myProduction.isEmpty()) {
skipWhitespace();
}
StartMarker marker = createMarker(myCurrentLexeme);
myProduction.add(marker);
return marker;
}
@Nonnull
private StartMarker createMarker(final int lexemeIndex) {
StartMarker marker = START_MARKERS.alloc();
marker.myLexemeIndex = lexemeIndex;
marker.myBuilder = this;
if (myDebugMode) {
marker.myDebugAllocationPosition = new Throwable("Created at the following trace.");
}
return marker;
}
@Override
public final boolean eof() {
if (!myTokenTypeChecked) {
myTokenTypeChecked = true;
skipWhitespace();
}
return myCurrentLexeme >= myLexemeCount;
}
private void rollbackTo(@Nonnull Marker marker) {
myCurrentLexeme = ((StartMarker)marker).myLexemeIndex;
myTokenTypeChecked = true;
int idx = myProduction.lastIndexOf(marker);
if (idx < 0) {
LOG.error("The marker must be added before rolled back to.");
}
myProduction.removeRange(idx, myProduction.size());
START_MARKERS.recycle((StartMarker)marker);
clearCachedTokenType();
}
/**
* @return true if there are error elements created and not dropped after marker was created
*/
public boolean hasErrorsAfter(@Nonnull Marker marker) {
assert marker instanceof StartMarker;
int idx = myProduction.lastIndexOf(marker);
if (idx < 0) {
LOG.error("The marker must be added before checked for errors.");
}
for (int i = idx + 1; i < myProduction.size(); ++i) {
ProductionMarker m = myProduction.get(i);
if (m instanceof ErrorItem || m instanceof DoneWithErrorMarker) {
return true;
}
}
return false;
}
public void drop(@Nonnull Marker marker) {
final DoneMarker doneMarker = ((StartMarker)marker).myDoneMarker;
if (doneMarker != null) {
myProduction.remove(myProduction.lastIndexOf(doneMarker));
DONE_MARKERS.recycle(doneMarker);
}
final boolean removed = myProduction.remove(myProduction.lastIndexOf(marker)) == marker;
if (!removed) {
LOG.error("The marker must be added before it is dropped.");
}
START_MARKERS.recycle((StartMarker)marker);
}
public void error(@Nonnull Marker marker, LocalizeValue message) {
doValidityChecks(marker, null);
DoneWithErrorMarker doneMarker = new DoneWithErrorMarker((StartMarker)marker, myCurrentLexeme, message);
boolean tieToTheLeft = isEmpty(((StartMarker)marker).myLexemeIndex, myCurrentLexeme);
if (tieToTheLeft) ((StartMarker)marker).myEdgeTokenBinder = WhitespacesBinders.DEFAULT_RIGHT_BINDER;
((StartMarker)marker).myDoneMarker = doneMarker;
myProduction.add(doneMarker);
}
private void errorBefore(@Nonnull Marker marker, @Nonnull LocalizeValue message, @Nonnull Marker before) {
doValidityChecks(marker, before);
@SuppressWarnings("SuspiciousMethodCalls") int beforeIndex = myProduction.lastIndexOf(before);
DoneWithErrorMarker doneMarker = new DoneWithErrorMarker((StartMarker)marker, ((StartMarker)before).myLexemeIndex, message);
boolean tieToTheLeft = isEmpty(((StartMarker)marker).myLexemeIndex, ((StartMarker)before).myLexemeIndex);
if (tieToTheLeft) ((StartMarker)marker).myEdgeTokenBinder = WhitespacesBinders.DEFAULT_RIGHT_BINDER;
((StartMarker)marker).myDoneMarker = doneMarker;
myProduction.add(beforeIndex, doneMarker);
}
public void done(@Nonnull Marker marker) {
doValidityChecks(marker, null);
DoneMarker doneMarker = DONE_MARKERS.alloc();
doneMarker.myStart = (StartMarker)marker;
doneMarker.myLexemeIndex = myCurrentLexeme;
boolean tieToTheLeft = doneMarker.myStart.myType.isLeftBound() && isEmpty(((StartMarker)marker).myLexemeIndex, myCurrentLexeme);
if (tieToTheLeft) ((StartMarker)marker).myEdgeTokenBinder = WhitespacesBinders.DEFAULT_RIGHT_BINDER;
((StartMarker)marker).myDoneMarker = doneMarker;
myProduction.add(doneMarker);
}
public void doneBefore(@Nonnull Marker marker, @Nonnull Marker before) {
doValidityChecks(marker, before);
@SuppressWarnings("SuspiciousMethodCalls") int beforeIndex = myProduction.lastIndexOf(before);
DoneMarker doneMarker = DONE_MARKERS.alloc();
doneMarker.myLexemeIndex = ((StartMarker)before).myLexemeIndex;
doneMarker.myStart = (StartMarker)marker;
boolean tieToTheLeft = doneMarker.myStart.myType.isLeftBound() && isEmpty(((StartMarker)marker).myLexemeIndex, ((StartMarker)before).myLexemeIndex);
if (tieToTheLeft) ((StartMarker)marker).myEdgeTokenBinder = WhitespacesBinders.DEFAULT_RIGHT_BINDER;
((StartMarker)marker).myDoneMarker = doneMarker;
myProduction.add(beforeIndex, doneMarker);
}
private boolean isEmpty(final int startIdx, final int endIdx) {
for (int i = startIdx; i < endIdx; i++) {
final IElementType token = myLexTypes[i];
if (!whitespaceOrComment(token)) return false;
}
return true;
}
public void collapse(@Nonnull Marker marker) {
done(marker);
((StartMarker)marker).myDoneMarker.myCollapse = true;
}
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
private void doValidityChecks(@Nonnull Marker marker, @Nullable final Marker before) {
final DoneMarker doneMarker = ((StartMarker)marker).myDoneMarker;
if (doneMarker != null) {
LOG.error("Marker already done.");
}
if (!myDebugMode) return;
int idx = myProduction.lastIndexOf(marker);
if (idx < 0) {
LOG.error("Marker has never been added.");
}
int endIdx = myProduction.size();
if (before != null) {
//noinspection SuspiciousMethodCalls
endIdx = myProduction.lastIndexOf(before);
if (endIdx < 0) {
LOG.error("'Before' marker has never been added.");
}
if (idx > endIdx) {
LOG.error("'Before' marker precedes this one.");
}
}
for (int i = endIdx - 1; i > idx; i--) {
Object item = myProduction.get(i);
if (item instanceof StartMarker) {
StartMarker otherMarker = (StartMarker)item;
if (otherMarker.myDoneMarker == null) {
final Throwable debugAllocOther = otherMarker.myDebugAllocationPosition;
final Throwable debugAllocThis = ((StartMarker)marker).myDebugAllocationPosition;
if (debugAllocOther != null) {
Throwable currentTrace = new Throwable();
ExceptionUtil.makeStackTraceRelative(debugAllocThis, currentTrace).printStackTrace(System.err);
ExceptionUtil.makeStackTraceRelative(debugAllocOther, currentTrace).printStackTrace(System.err);
}
LOG.error("Another not done marker added after this one. Must be done before this.");
}
}
}
}
@Override
public void error(@Nonnull LocalizeValue messageText) {
final ProductionMarker lastMarker = myProduction.get(myProduction.size() - 1);
if (lastMarker instanceof ErrorItem && lastMarker.myLexemeIndex == myCurrentLexeme) {
return;
}
myProduction.add(new ErrorItem(this, messageText, myCurrentLexeme));
}
@Override
@Nonnull
public ASTNode getTreeBuilt() {
return buildTree();
}
@Nonnull
private ASTNode buildTree() {
final StartMarker rootMarker = prepareLightTree();
final boolean isTooDeep = myFile != null && BlockSupport.isTooDeep(myFile.getOriginalFile());
if (myOriginalTree != null && !isTooDeep) {
DiffLog diffLog = merge(myOriginalTree, rootMarker, myLastCommittedText);
throw new BlockSupport.ReparsedSuccessfullyException(diffLog);
}
final TreeElement rootNode = createRootAST(rootMarker);
bind(rootMarker, (CompositeElement)rootNode);
if (isTooDeep && !(rootNode instanceof FileElement)) {
final ASTNode childNode = rootNode.getFirstChildNode();
childNode.putUserData(BlockSupport.TREE_DEPTH_LIMIT_EXCEEDED, Boolean.TRUE);
}
assert rootNode.getTextLength() == myText.length() : rootNode.getElementType();
return rootNode;
}
@Override
@Nonnull
public FlyweightCapableTreeStructure<LighterASTNode> getLightTree() {
final StartMarker rootMarker = prepareLightTree();
return new MyTreeStructure(rootMarker, myParentLightTree);
}
@Nonnull
private TreeElement createRootAST(@Nonnull StartMarker rootMarker) {
final IElementType type = rootMarker.getTokenType();
@SuppressWarnings("NullableProblems") final TreeElement rootNode =
type instanceof ILazyParseableElementType ? ASTFactory.lazy((ILazyParseableElementType)type, null) : createComposite(rootMarker);
if (myCharTable == null) {
myCharTable = rootNode instanceof FileElement ? ((FileElement)rootNode).getCharTable() : new CharTableImpl();
}
if (!(rootNode instanceof FileElement)) {
rootNode.putUserData(CharTable.CHAR_TABLE_KEY, myCharTable);
}
return rootNode;
}
private static class ConvertFromTokensToASTBuilder implements DiffTreeChangeBuilder<ASTNode, LighterASTNode> {
private final DiffTreeChangeBuilder<ASTNode, ASTNode> myDelegate;
private final ASTConverter myConverter;
private ConvertFromTokensToASTBuilder(@Nonnull StartMarker rootNode, @Nonnull DiffTreeChangeBuilder<ASTNode, ASTNode> delegate) {
myDelegate = delegate;
myConverter = new ASTConverter(rootNode);
}
@Override
public void nodeDeleted(@Nonnull final ASTNode oldParent, @Nonnull final ASTNode oldNode) {
myDelegate.nodeDeleted(oldParent, oldNode);
}
@Override
public void nodeInserted(@Nonnull final ASTNode oldParent, @Nonnull final LighterASTNode newNode, final int pos) {
myDelegate.nodeInserted(oldParent, myConverter.convert((Node)newNode), pos);
}
@Override
public void nodeReplaced(@Nonnull final ASTNode oldChild, @Nonnull final LighterASTNode newChild) {
ASTNode converted = myConverter.convert((Node)newChild);
myDelegate.nodeReplaced(oldChild, converted);
}
}
@NonNls
private static final String UNBALANCED_MESSAGE = "Unbalanced tree. Most probably caused by unbalanced markers. " +
"Try calling setDebugMode(true) against PsiBuilder passed to identify exact location of the problem";
@Nonnull
private DiffLog merge(@Nonnull final ASTNode oldRoot, @Nonnull StartMarker newRoot, @Nonnull CharSequence lastCommittedText) {
DiffLog diffLog = new DiffLog();
DiffTreeChangeBuilder<ASTNode, LighterASTNode> builder = new ConvertFromTokensToASTBuilder(newRoot, diffLog);
MyTreeStructure treeStructure = new MyTreeStructure(newRoot, null);
ShallowNodeComparator<ASTNode, LighterASTNode> comparator = new MyComparator(getUserData(CUSTOM_COMPARATOR), treeStructure);
ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator();
BlockSupportImpl.diffTrees(oldRoot, builder, comparator, treeStructure, indicator == null ? new EmptyProgressIndicator() : indicator, lastCommittedText);
return diffLog;
}
@Nonnull
private StartMarker prepareLightTree() {
if (myProduction.isEmpty()) {
LOG.error("Parser produced no markers. Text:\n" + myText);
}
// build tree only once to avoid threading issues in read-only PSI
StartMarker rootMarker = (StartMarker)myProduction.get(0);
if (rootMarker.myFirstChild != null) return rootMarker;
myTokenTypeChecked = true;
balanceWhiteSpaces();
rootMarker.myParent = rootMarker.myFirstChild = rootMarker.myLastChild = rootMarker.myNext = null;
StartMarker curNode = rootMarker;
final Stack<StartMarker> nodes = ContainerUtil.newStack();
nodes.push(rootMarker);
int lastErrorIndex = -1;
int maxDepth = 0;
int curDepth = 0;
for (int i = 1; i < myProduction.size(); i++) {
final ProductionMarker item = myProduction.get(i);
if (curNode == null) LOG.error("Unexpected end of the production");
item.myParent = curNode;
if (item instanceof StartMarker) {
final StartMarker marker = (StartMarker)item;
marker.myFirstChild = marker.myLastChild = marker.myNext = null;
curNode.addChild(marker);
nodes.push(curNode);
curNode = marker;
curDepth++;
if (curDepth > maxDepth) maxDepth = curDepth;
}
else if (item instanceof DoneMarker) {
assertMarkersBalanced(((DoneMarker)item).myStart == curNode, item);
curNode = nodes.pop();
curDepth--;
}
else if (item instanceof ErrorItem) {
int curToken = item.myLexemeIndex;
if (curToken == lastErrorIndex) continue;
lastErrorIndex = curToken;
curNode.addChild(item);
}
}
if (myCurrentLexeme < myLexemeCount) {
final List<IElementType> missed = ContainerUtil.newArrayList(myLexTypes, myCurrentLexeme, myLexemeCount);
LOG.error("Tokens " + missed + " were not inserted into the tree. " + (myFile != null ? myFile.getLanguage() + ", " : "") + "Text:\n" + myText);
}
if (rootMarker.myDoneMarker.myLexemeIndex < myLexemeCount) {
final List<IElementType> missed = ContainerUtil.newArrayList(myLexTypes, rootMarker.myDoneMarker.myLexemeIndex, myLexemeCount);
LOG.error("Tokens " + missed + " are outside of root element \"" + rootMarker.myType + "\". Text:\n" + myText);
}
if (myLexStarts.length <= myCurrentLexeme + 1) {
resizeLexemes(myCurrentLexeme + 1);
}
myLexStarts[myCurrentLexeme] = myText.length(); // $ terminating token.;
myLexStarts[myCurrentLexeme + 1] = 0;
myLexTypes[myCurrentLexeme] = null;
assertMarkersBalanced(curNode == rootMarker, curNode);
checkTreeDepth(maxDepth, rootMarker.getTokenType() instanceof IFileElementType);
clearCachedTokenType();
return rootMarker;
}
private void assertMarkersBalanced(boolean condition, @Nullable ProductionMarker marker) {
if (condition) return;
int index = marker != null ? marker.getStartIndex() + 1 : myLexStarts.length;
CharSequence context = index < myLexStarts.length ? myText.subSequence(Math.max(0, myLexStarts[index] - 1000), myLexStarts[index]) : "<none>";
String language = myFile != null ? myFile.getLanguage() + ", " : "";
LOG.error(UNBALANCED_MESSAGE + "\n" + "language: " + language + "\n" + "context: '" + context + "'");
}
private void balanceWhiteSpaces() {
RelativeTokenTypesView wsTokens = new RelativeTokenTypesView();
RelativeTokenTextView tokenTextGetter = new RelativeTokenTextView();
int lastIndex = 0;
for (int i = 1, size = myProduction.size() - 1; i < size; i++) {
ProductionMarker item = myProduction.get(i);
if (item instanceof StartMarker) {
assertMarkersBalanced(((StartMarker)item).myDoneMarker != null, item);
}
boolean recursive = item.myEdgeTokenBinder instanceof WhitespacesAndCommentsBinder.RecursiveBinder;
int prevProductionLexIndex = recursive ? 0 : myProduction.get(i - 1).myLexemeIndex;
int wsStartIndex = Math.max(item.myLexemeIndex, lastIndex);
while (wsStartIndex > prevProductionLexIndex && whitespaceOrComment(myLexTypes[wsStartIndex - 1])) wsStartIndex--;
int wsEndIndex = item.myLexemeIndex;
while (wsEndIndex < myLexemeCount && whitespaceOrComment(myLexTypes[wsEndIndex])) wsEndIndex++;
if (wsStartIndex != wsEndIndex) {
wsTokens.configure(wsStartIndex, wsEndIndex);
tokenTextGetter.configure(wsStartIndex);
boolean atEnd = wsStartIndex == 0 || wsEndIndex == myLexemeCount;
item.myLexemeIndex = wsStartIndex + item.myEdgeTokenBinder.getEdgePosition(wsTokens, atEnd, tokenTextGetter);
if (recursive) {
for (int k = i - 1; k > 1; k--) {
ProductionMarker prev = myProduction.get(k);
if (prev.myLexemeIndex >= item.myLexemeIndex) {
prev.myLexemeIndex = item.myLexemeIndex;
}
else {
break;
}
}
}
}
else if (item.myLexemeIndex < wsStartIndex) {
item.myLexemeIndex = wsStartIndex;
}
lastIndex = item.myLexemeIndex;
}
}
private final class RelativeTokenTypesView extends AbstractList<IElementType> {
private int myStart;
private int mySize;
private void configure(int start, int end) {
myStart = start;
mySize = end - start;
}
@Override
public IElementType get(int index) {
return myLexTypes[myStart + index];
}
@Override
public int size() {
return mySize;
}
}
private final class RelativeTokenTextView implements WhitespacesAndCommentsBinder.TokenTextGetter {
private int myStart;
private void configure(int start) {
myStart = start;
}
@Override
@Nonnull
public CharSequence get(int i) {
return myText.subSequence(myLexStarts[myStart + i], myLexStarts[myStart + i + 1]);
}
}
private void checkTreeDepth(final int maxDepth, final boolean isFileRoot) {
if (myFile == null) return;
final PsiFile file = myFile.getOriginalFile();
final Boolean flag = file.getUserData(BlockSupport.TREE_DEPTH_LIMIT_EXCEEDED);
if (maxDepth > BlockSupport.INCREMENTAL_REPARSE_DEPTH_LIMIT) {
if (!Boolean.TRUE.equals(flag)) {
file.putUserData(BlockSupport.TREE_DEPTH_LIMIT_EXCEEDED, Boolean.TRUE);
}
}
else if (isFileRoot && flag != null) {
file.putUserData(BlockSupport.TREE_DEPTH_LIMIT_EXCEEDED, null);
}
}
private void bind(@Nonnull StartMarker rootMarker, @Nonnull CompositeElement rootNode) {
StartMarker curMarker = rootMarker;
CompositeElement curNode = rootNode;
int lexIndex = rootMarker.myLexemeIndex;
ProductionMarker item = rootMarker.myFirstChild != null ? rootMarker.myFirstChild : rootMarker.myDoneMarker;
while (true) {
lexIndex = insertLeaves(lexIndex, item.myLexemeIndex, curNode);
if (item == rootMarker.myDoneMarker) break;
if (item instanceof StartMarker) {
final StartMarker marker = (StartMarker)item;
if (!marker.myDoneMarker.myCollapse) {
curMarker = marker;
final CompositeElement childNode = createComposite(marker);
curNode.rawAddChildrenWithoutNotifications(childNode);
curNode = childNode;
item = marker.myFirstChild != null ? marker.myFirstChild : marker.myDoneMarker;
continue;
}
else {
lexIndex = collapseLeaves(curNode, marker);
}
}
else if (item instanceof ErrorItem) {
final CompositeElement errorElement = Factory.createErrorElement(((ErrorItem)item).myMessage);
curNode.rawAddChildrenWithoutNotifications(errorElement);
}
else if (item instanceof DoneMarker) {
curMarker = (StartMarker)((DoneMarker)item).myStart.myParent;
curNode = curNode.getTreeParent();
item = ((DoneMarker)item).myStart;
}
item = item.myNext != null ? item.myNext : curMarker.myDoneMarker;
}
}
private int insertLeaves(int curToken, int lastIdx, final CompositeElement curNode) {
lastIdx = Math.min(lastIdx, myLexemeCount);
while (curToken < lastIdx) {
ProgressIndicatorProvider.checkCanceled();
final int start = myLexStarts[curToken];
final int end = myLexStarts[curToken + 1];
if (start < end || myLexTypes[curToken] instanceof ILeafElementType) { // Empty token. Most probably a parser directive like indent/dedent in Python
final IElementType type = myLexTypes[curToken];
final TreeElement leaf = createLeaf(type, start, end);
curNode.rawAddChildrenWithoutNotifications(leaf);
}
curToken++;
}
return curToken;
}
private int collapseLeaves(@Nonnull CompositeElement ast, @Nonnull StartMarker startMarker) {
final int start = myLexStarts[startMarker.myLexemeIndex];
final int end = myLexStarts[startMarker.myDoneMarker.myLexemeIndex];
final IElementType markerType = startMarker.myType;
final TreeElement leaf = createLeaf(markerType, start, end);
if (markerType instanceof ILazyParseableElementType &&
((ILazyParseableElementType)markerType).reuseCollapsedTokens() &&
startMarker.myLexemeIndex < startMarker.myDoneMarker.myLexemeIndex) {
final int length = startMarker.myDoneMarker.myLexemeIndex - startMarker.myLexemeIndex;
final int[] relativeStarts = new int[length + 1];
final IElementType[] types = new IElementType[length];
for (int i = startMarker.myLexemeIndex; i < startMarker.myDoneMarker.myLexemeIndex; i++) {
relativeStarts[i - startMarker.myLexemeIndex] = myLexStarts[i] - start;
types[i - startMarker.myLexemeIndex] = myLexTypes[i];
}
relativeStarts[length] = end - start;
leaf.putUserData(LAZY_PARSEABLE_TOKENS, new LazyParseableTokensCache(relativeStarts, types));
}
ast.rawAddChildrenWithoutNotifications(leaf);
return startMarker.myDoneMarker.myLexemeIndex;
}
@Nonnull
private static CompositeElement createComposite(@Nonnull StartMarker marker) {
final IElementType type = marker.myType;
if (type == TokenType.ERROR_ELEMENT) {
LocalizeValue message = marker.myDoneMarker instanceof DoneWithErrorMarker ? ((DoneWithErrorMarker)marker.myDoneMarker).myMessage : null;
return Factory.createErrorElement(message == null ? LocalizeValue.empty() : message);
}
if (type == null) {
throw new RuntimeException(UNBALANCED_MESSAGE);
}
return ASTFactory.composite(type);
}
@Nonnull
public static LocalizeValue getErrorMessage(@Nonnull LighterASTNode node) {
if (node instanceof ErrorItem) return ((ErrorItem)node).myMessage;
if (node instanceof StartMarker) {
final StartMarker marker = (StartMarker)node;
if (marker.myType == TokenType.ERROR_ELEMENT && marker.myDoneMarker instanceof DoneWithErrorMarker) {
return ((DoneWithErrorMarker)marker.myDoneMarker).myMessage;
}
}
return LocalizeValue.empty();
}
private static class MyComparator implements ShallowNodeComparator<ASTNode, LighterASTNode> {
private final TripleFunction<ASTNode, LighterASTNode, FlyweightCapableTreeStructure<LighterASTNode>, ThreeState> custom;
private final MyTreeStructure myTreeStructure;
private MyComparator(TripleFunction<ASTNode, LighterASTNode, FlyweightCapableTreeStructure<LighterASTNode>, ThreeState> custom,
@Nonnull MyTreeStructure treeStructure) {
this.custom = custom;
myTreeStructure = treeStructure;
}
@Nonnull
@Override
public ThreeState deepEqual(@Nonnull final ASTNode oldNode, @Nonnull final LighterASTNode newNode) {
ProgressIndicatorProvider.checkCanceled();
boolean oldIsErrorElement = oldNode instanceof PsiErrorElement;
boolean newIsErrorElement = newNode.getTokenType() == TokenType.ERROR_ELEMENT;
if (oldIsErrorElement != newIsErrorElement) return ThreeState.NO;
if (oldIsErrorElement) {
final PsiErrorElement e1 = (PsiErrorElement)oldNode;
return Objects.equals(e1.getErrorDescriptionValue(), getErrorMessage(newNode)) ? ThreeState.UNSURE : ThreeState.NO;
}
if (custom != null) {
ThreeState customResult = custom.fun(oldNode, newNode, myTreeStructure);
if (customResult != ThreeState.UNSURE) {
return customResult;
}
}
if (newNode instanceof Token) {
final IElementType type = newNode.getTokenType();
final Token token = (Token)newNode;
if (oldNode instanceof ForeignLeafPsiElement) {
return type instanceof ForeignLeafType && StringUtil.equals(((ForeignLeafType)type).getValue(), oldNode.getText()) ? ThreeState.YES : ThreeState.NO;
}
if (oldNode instanceof LeafElement) {
if (type instanceof ForeignLeafType) return ThreeState.NO;
return ((LeafElement)oldNode).textMatches(token.getText()) ? ThreeState.YES : ThreeState.NO;
}
if (type instanceof ILightLazyParseableElementType) {
return ((TreeElement)oldNode).textMatches(token.getText())
? ThreeState.YES
: TreeUtil.isCollapsedChameleon(oldNode) ? ThreeState.NO // do not dive into collapsed nodes
: ThreeState.UNSURE;
}
if (oldNode.getElementType() instanceof ILazyParseableElementType && type instanceof ILazyParseableElementType ||
oldNode.getElementType() instanceof ICustomParsingType && type instanceof ICustomParsingType) {
return ((TreeElement)oldNode).textMatches(token.getText()) ? ThreeState.YES : ThreeState.NO;
}
}
return ThreeState.UNSURE;
}
@Override
public boolean typesEqual(@Nonnull final ASTNode n1, @Nonnull final LighterASTNode n2) {
if (n1 instanceof PsiWhiteSpaceImpl) {
return ourAnyLanguageWhitespaceTokens.contains(n2.getTokenType()) ||
n2 instanceof Token && ((Token)n2).myBuilder.myWhitespaces.contains(n2.getTokenType());
}
IElementType n1t;
IElementType n2t;
if (n1 instanceof ForeignLeafPsiElement) {
n1t = ((ForeignLeafPsiElement)n1).getForeignType();
n2t = n2.getTokenType();
}
else {
n1t = dereferenceToken(n1.getElementType());
n2t = dereferenceToken(n2.getTokenType());
}
return Comparing.equal(n1t, n2t);
}
private static IElementType dereferenceToken(IElementType probablyWrapper) {
if (probablyWrapper instanceof TokenWrapper) {
return dereferenceToken(((TokenWrapper)probablyWrapper).getDelegate());
}
return probablyWrapper;
}
@Override
public boolean hashCodesEqual(@Nonnull final ASTNode n1, @Nonnull final LighterASTNode n2) {
if (n1 instanceof LeafElement && n2 instanceof Token) {
boolean isForeign1 = n1 instanceof ForeignLeafPsiElement;
boolean isForeign2 = n2.getTokenType() instanceof ForeignLeafType;
if (isForeign1 != isForeign2) return false;
if (isForeign1) {
return StringUtil.equals(n1.getText(), ((ForeignLeafType)n2.getTokenType()).getValue());
}
return ((LeafElement)n1).textMatches(((Token)n2).getText());
}
if (n1 instanceof PsiErrorElement && n2.getTokenType() == TokenType.ERROR_ELEMENT) {
final PsiErrorElement e1 = (PsiErrorElement)n1;
if (!Objects.equals(e1.getErrorDescriptionValue(), getErrorMessage(n2))) return false;
}
return ((TreeElement)n1).hc() == ((Node)n2).hc();
}
}
private static class MyTreeStructure implements FlyweightCapableTreeStructure<LighterASTNode> {
private final LimitedPool<Token> myPool;
private final LimitedPool<LazyParseableToken> myLazyPool;
private final StartMarker myRoot;
public MyTreeStructure(@Nonnull StartMarker root, @Nullable final MyTreeStructure parentTree) {
if (parentTree == null) {
myPool = new LimitedPool<>(1000, new LimitedPool.ObjectFactory<Token>() {
@Override
public void cleanup(@Nonnull final Token token) {
token.clean();
}
@Nonnull
@Override
public Token create() {
return new TokenNode();
}
});
myLazyPool = new LimitedPool<>(200, new LimitedPool.ObjectFactory<LazyParseableToken>() {
@Override
public void cleanup(@Nonnull final LazyParseableToken token) {
token.clean();
}
@Nonnull
@Override
public LazyParseableToken create() {
return new LazyParseableToken();
}
});
}
else {
myPool = parentTree.myPool;
myLazyPool = parentTree.myLazyPool;
}
myRoot = root;
}
@Override
@Nonnull
public LighterASTNode getRoot() {
return myRoot;
}
@Override
public LighterASTNode getParent(@Nonnull final LighterASTNode node) {
if (node instanceof ProductionMarker) {
return ((ProductionMarker)node).myParent;
}
if (node instanceof Token) {
return ((Token)node).myParentNode;
}
throw new UnsupportedOperationException("Unknown node type: " + node);
}
@Override
@Nonnull
public LighterASTNode prepareForGetChildren(@Nonnull final LighterASTNode node) {
return node;
}
private int count;
private LighterASTNode[] nodes;
@Override
public int getChildren(@Nonnull final LighterASTNode item, @Nonnull final Ref<LighterASTNode[]> into) {
if (item instanceof LazyParseableToken) {
final FlyweightCapableTreeStructure<LighterASTNode> tree = ((LazyParseableToken)item).parseContents();
final LighterASTNode root = tree.getRoot();
if (root instanceof ProductionMarker) {
((ProductionMarker)root).myParent = ((Token)item).myParentNode;
}
return tree.getChildren(tree.prepareForGetChildren(root), into); // todo: set offset shift for kids?
}
if (item instanceof Token || item instanceof ErrorItem) return 0;
StartMarker marker = (StartMarker)item;
count = 0;
ProductionMarker child = marker.myFirstChild;
int lexIndex = marker.myLexemeIndex;
while (child != null) {
lexIndex = insertLeaves(lexIndex, child.myLexemeIndex, marker.myBuilder, marker);
if (child instanceof StartMarker && ((StartMarker)child).myDoneMarker.myCollapse) {
int lastIndex = ((StartMarker)child).myDoneMarker.myLexemeIndex;
insertLeaf(child.getTokenType(), marker.myBuilder, child.myLexemeIndex, lastIndex, true, marker);
}
else {
ensureCapacity();
nodes[count++] = child;
}
if (child instanceof StartMarker) {
lexIndex = ((StartMarker)child).myDoneMarker.myLexemeIndex;
}
child = child.myNext;
}
insertLeaves(lexIndex, marker.myDoneMarker.myLexemeIndex, marker.myBuilder, marker);
into.set(nodes == null ? LighterASTNode.EMPTY_ARRAY : nodes);
nodes = null;
return count;
}
@Override
public void disposeChildren(final LighterASTNode[] nodes, final int count) {
if (nodes == null) return;
for (int i = 0; i < count; i++) {
final LighterASTNode node = nodes[i];
if (node instanceof LazyParseableToken) {
myLazyPool.recycle((LazyParseableToken)node);
}
else if (node instanceof Token) {
myPool.recycle((Token)node);
}
}
}
private void ensureCapacity() {
LighterASTNode[] old = nodes;
if (old == null) {
old = new LighterASTNode[10];
nodes = old;
}
else if (count >= old.length) {
LighterASTNode[] newStore = new LighterASTNode[count * 3 / 2];
System.arraycopy(old, 0, newStore, 0, count);
nodes = newStore;
}
}
private int insertLeaves(int curToken, int lastIdx, PsiBuilderImpl builder, StartMarker parent) {
lastIdx = Math.min(lastIdx, builder.myLexemeCount);
while (curToken < lastIdx) {
insertLeaf(builder.myLexTypes[curToken], builder, curToken, curToken + 1, false, parent);
curToken++;
}
return curToken;
}
private void insertLeaf(@Nonnull IElementType type,
@Nonnull PsiBuilderImpl builder,
int startLexemeIndex,
int endLexemeIndex,
boolean forceInsertion,
StartMarker parent) {
final int start = builder.myLexStarts[startLexemeIndex];
final int end = builder.myLexStarts[endLexemeIndex];
/* Corresponding code for heavy tree is located in {@link com.intellij.lang.impl.PsiBuilderImpl#insertLeaves}
and is applied only to plain lexemes */
if (start > end || !forceInsertion && start == end && !(type instanceof ILeafElementType)) {
return;
}
Token lexeme = obtainToken(type, builder, startLexemeIndex, endLexemeIndex, parent, start, end);
ensureCapacity();
nodes[count++] = lexeme;
}
@Nonnull
private Token obtainToken(@Nonnull IElementType type,
@Nonnull PsiBuilderImpl builder,
int startLexemeIndex,
int endLexemeIndex,
StartMarker parent,
int start,
int end) {
if (type instanceof ILightLazyParseableElementType) {
return obtainLazyToken(type, builder, startLexemeIndex, endLexemeIndex, parent, start, end);
}
Token lexeme = myPool.alloc();
lexeme.initToken(type, builder, parent, start, end);
return lexeme;
}
@Nonnull
private Token obtainLazyToken(@Nonnull IElementType type,
@Nonnull PsiBuilderImpl builder,
int startLexemeIndex,
int endLexemeIndex,
StartMarker parent,
int start,
int end) {
int startInFile = start + builder.myOffset;
LazyParseableToken token = builder.myChameleonCache.get(startInFile);
if (token == null) {
token = myLazyPool.alloc();
token.myStartIndex = startLexemeIndex;
token.myEndIndex = endLexemeIndex;
token.initToken(type, builder, parent, start, end);
builder.myChameleonCache.put(startInFile, token);
}
else {
if (token.myBuilder != builder || token.myStartIndex != startLexemeIndex || token.myEndIndex != endLexemeIndex) {
throw new AssertionError("Wrong chameleon cached");
}
}
token.myParentStructure = this;
return token;
}
@Nonnull
@Override
public CharSequence toString(@Nonnull LighterASTNode node) {
return myRoot.myBuilder.myText.subSequence(node.getStartOffset(), node.getEndOffset());
}
@Override
public int getStartOffset(@Nonnull LighterASTNode node) {
return node.getStartOffset();
}
@Override
public int getEndOffset(@Nonnull LighterASTNode node) {
return node.getEndOffset();
}
}
private static class ASTConverter implements Convertor<Node, ASTNode> {
@Nonnull
private final StartMarker myRoot;
private ASTConverter(@Nonnull StartMarker root) {
myRoot = root;
}
@Override
public ASTNode convert(final Node n) {
if (n instanceof Token) {
final Token token = (Token)n;
return token.myBuilder.createLeaf(token.getTokenType(), token.myTokenStart, token.myTokenEnd);
}
else if (n instanceof ErrorItem) {
return Factory.createErrorElement(((ErrorItem)n).myMessage);
}
else {
final StartMarker startMarker = (StartMarker)n;
final CompositeElement composite = n == myRoot ? (CompositeElement)myRoot.myBuilder.createRootAST(myRoot) : createComposite(startMarker);
startMarker.myBuilder.bind(startMarker, composite);
return composite;
}
}
}
@Override
public void setDebugMode(boolean dbgMode) {
myDebugMode = dbgMode;
}
@Nonnull
public Lexer getLexer() {
return myLexer;
}
@Nonnull
protected TreeElement createLeaf(@Nonnull IElementType type, final int start, final int end) {
CharSequence text = myCharTable.intern(myText, start, end);
if (myWhitespaces.contains(type)) {
return new PsiWhiteSpaceImpl(text);
}
if (type instanceof ICustomParsingType) {
return (TreeElement)((ICustomParsingType)type).parse(text, myCharTable);
}
if (type instanceof ILazyParseableElementType) {
return ASTFactory.lazy((ILazyParseableElementType)type, text);
}
return ASTFactory.leaf(type, myLanguageVersion, text);
}
@Override
@SuppressWarnings("unchecked")
public <T> T getUserData(@Nonnull Key<T> key) {
return key == FileContextUtil.CONTAINING_FILE_KEY ? (T)myFile : super.getUserData(key);
}
@Override
public <T> void putUserData(@Nonnull Key<T> key, @Nullable T value) {
if (key == FileContextUtil.CONTAINING_FILE_KEY) {
myFile = (PsiFile)value;
}
else {
super.putUserData(key, value);
}
}
private static class MyList extends ArrayList<ProductionMarker> {
// make removeRange method available.
@Override
protected void removeRange(final int fromIndex, final int toIndex) {
super.removeRange(fromIndex, toIndex);
}
private MyList() {
super(256);
}
}
private static class LazyParseableTokensCache {
final int[] myLexStarts;
final IElementType[] myLexTypes;
LazyParseableTokensCache(int[] lexStarts, IElementType[] lexTypes) {
myLexStarts = lexStarts;
myLexTypes = lexTypes;
}
}
}
| apache-2.0 |
MichaelRocks/libphonenumber-android | library/src/test/java/io/michaelrocks/libphonenumber/android/PhoneNumberMatchTest.java | 2455 | /*
* Copyright (C) 2011 The Libphonenumber Authors
* Copyright (C) 2017 Michael Rozumyanskiy
*
* 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.michaelrocks.libphonenumber.android;
import junit.framework.TestCase;
import io.michaelrocks.libphonenumber.android.Phonenumber.PhoneNumber;
/**
* Tests for {@link PhoneNumberMatch}.
*/
public class PhoneNumberMatchTest extends TestCase {
/**
* Tests the value type semantics. Equality and hash code must be based on the covered range and
* corresponding phone number. Range and number correctness are tested by
* {@link PhoneNumberMatcherTest}.
*/
public void testValueTypeSemantics() throws Exception {
PhoneNumber number = new PhoneNumber();
PhoneNumberMatch match1 = new PhoneNumberMatch(10, "1 800 234 45 67", number);
PhoneNumberMatch match2 = new PhoneNumberMatch(10, "1 800 234 45 67", number);
assertEquals(match1, match2);
assertEquals(match1.hashCode(), match2.hashCode());
assertEquals(match1.start(), match2.start());
assertEquals(match1.end(), match2.end());
assertEquals(match1.number(), match2.number());
assertEquals(match1.rawString(), match2.rawString());
assertEquals("1 800 234 45 67", match1.rawString());
}
/**
* Tests the value type semantics for matches with a null number.
*/
public void testIllegalArguments() throws Exception {
try {
new PhoneNumberMatch(-110, "1 800 234 45 67", new PhoneNumber());
fail();
} catch (IllegalArgumentException e) { /* success */ }
try {
new PhoneNumberMatch(10, "1 800 234 45 67", null);
fail();
} catch (NullPointerException e) { /* success */ }
try {
new PhoneNumberMatch(10, null, new PhoneNumber());
fail();
} catch (NullPointerException e) { /* success */ }
try {
new PhoneNumberMatch(10, null, null);
fail();
} catch (NullPointerException e) { /* success */ }
}
}
| apache-2.0 |
kishoreg/helix-actors | helix-core/src/main/java/org/apache/helix/messaging/handling/HelixTask.java | 11205 | package org.apache.helix.messaging.handling;
/*
* 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 java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.InstanceType;
import org.apache.helix.NotificationContext;
import org.apache.helix.NotificationContext.MapKey;
import org.apache.helix.PropertyKey;
import org.apache.helix.PropertyKey.Builder;
import org.apache.helix.messaging.handling.GroupMessageHandler.GroupMessageInfo;
import org.apache.helix.messaging.handling.MessageHandler.ErrorCode;
import org.apache.helix.messaging.handling.MessageHandler.ErrorType;
import org.apache.helix.model.CurrentState;
import org.apache.helix.model.Message;
import org.apache.helix.model.Message.Attributes;
import org.apache.helix.model.Message.MessageType;
import org.apache.helix.monitoring.StateTransitionContext;
import org.apache.helix.monitoring.StateTransitionDataPoint;
import org.apache.helix.util.StatusUpdateUtil;
import org.apache.log4j.Logger;
public class HelixTask implements MessageTask {
private static Logger logger = Logger.getLogger(HelixTask.class);
private final Message _message;
private final MessageHandler _handler;
private final NotificationContext _notificationContext;
private final HelixManager _manager;
StatusUpdateUtil _statusUpdateUtil;
HelixTaskExecutor _executor;
volatile boolean _isTimeout = false;
public HelixTask(Message message, NotificationContext notificationContext,
MessageHandler handler, HelixTaskExecutor executor) {
this._notificationContext = notificationContext;
this._message = message;
this._handler = handler;
this._manager = notificationContext.getManager();
_statusUpdateUtil = new StatusUpdateUtil();
_executor = executor;
}
@Override
public HelixTaskResult call() {
HelixTaskResult taskResult = null;
ErrorType type = null;
ErrorCode code = null;
long start = System.currentTimeMillis();
logger.info("handling task: " + getTaskId() + " begin, at: " + start);
HelixDataAccessor accessor = _manager.getHelixDataAccessor();
_statusUpdateUtil.logInfo(_message, HelixTask.class, "Message handling task begin execute",
accessor);
_message.setExecuteStartTimeStamp(new Date().getTime());
// add a concurrent map to hold currentStateUpdates for sub-messages of a batch-message
// partitionName -> csUpdate
if (_message.getBatchMessageMode() == true) {
_notificationContext.add(MapKey.CURRENT_STATE_UPDATE.toString(),
new ConcurrentHashMap<String, CurrentStateUpdate>());
}
// Handle the message
try {
taskResult = _handler.handleMessage();
} catch (InterruptedException e) {
taskResult = new HelixTaskResult();
taskResult.setException(e);
taskResult.setInterrupted(true);
_statusUpdateUtil.logError(_message, HelixTask.class, e,
"State transition interrupted, timeout:" + _isTimeout, accessor);
logger.info("Message " + _message.getMsgId() + " is interrupted");
} catch (Exception e) {
taskResult = new HelixTaskResult();
taskResult.setException(e);
taskResult.setMessage(e.getMessage());
String errorMessage =
"Exception while executing a message. " + e + " msgId: " + _message.getMsgId()
+ " type: " + _message.getMsgType();
logger.error(errorMessage, e);
_statusUpdateUtil.logError(_message, HelixTask.class, e, errorMessage, accessor);
}
// cancel timeout task
_executor.cancelTimeoutTask(this);
Exception exception = null;
try {
if (taskResult.isSuccess()) {
_statusUpdateUtil.logInfo(_message, _handler.getClass(),
"Message handling task completed successfully", accessor);
logger.info("Message " + _message.getMsgId() + " completed.");
} else {
type = ErrorType.INTERNAL;
if (taskResult.isInterrupted()) {
logger.info("Message " + _message.getMsgId() + " is interrupted");
code = _isTimeout ? ErrorCode.TIMEOUT : ErrorCode.CANCEL;
if (_isTimeout) {
int retryCount = _message.getRetryCount();
logger.info("Message timeout, retry count: " + retryCount + " msgId:"
+ _message.getMsgId());
_statusUpdateUtil.logInfo(_message, _handler.getClass(),
"Message handling task timeout, retryCount:" + retryCount, accessor);
// Notify the handler that timeout happens, and the number of retries left
// In case timeout happens (time out and also interrupted)
// we should retry the execution of the message by re-schedule it in
if (retryCount > 0) {
_message.setRetryCount(retryCount - 1);
HelixTask task = new HelixTask(_message, _notificationContext, _handler, _executor);
_executor.scheduleTask(task);
return taskResult;
}
}
} else // logging for errors
{
code = ErrorCode.ERROR;
String errorMsg =
"Message execution failed. msgId: " + getTaskId() + ", errorMsg: "
+ taskResult.getMessage();
logger.error(errorMsg);
_statusUpdateUtil.logError(_message, _handler.getClass(), errorMsg, accessor);
}
}
if (_message.getAttribute(Attributes.PARENT_MSG_ID) == null) {
// System.err.println("\t[dbg]remove msg: " + getTaskId());
removeMessageFromZk(accessor, _message);
reportMessageStat(_manager, _message, taskResult);
sendReply(accessor, _message, taskResult);
_executor.finishTask(this);
}
} catch (Exception e) {
exception = e;
type = ErrorType.FRAMEWORK;
code = ErrorCode.ERROR;
String errorMessage =
"Exception after executing a message, msgId: " + _message.getMsgId() + e;
logger.error(errorMessage, e);
_statusUpdateUtil.logError(_message, HelixTask.class, errorMessage, accessor);
} finally {
long end = System.currentTimeMillis();
logger.info("msg: " + _message.getMsgId() + " handling task completed, results:"
+ taskResult.isSuccess() + ", at: " + end + ", took:" + (end - start));
// Notify the handler about any error happened in the handling procedure, so that
// the handler have chance to finally cleanup
if (type == ErrorType.INTERNAL) {
_handler.onError(taskResult.getException(), code, type);
} else if (type == ErrorType.FRAMEWORK) {
_handler.onError(exception, code, type);
}
}
return taskResult;
}
private void removeMessageFromZk(HelixDataAccessor accessor, Message message) {
Builder keyBuilder = accessor.keyBuilder();
if (message.getTgtName().equalsIgnoreCase("controller")) {
// TODO: removeProperty returns boolean
accessor.removeProperty(keyBuilder.controllerMessage(message.getMsgId()));
} else {
accessor.removeProperty(keyBuilder.message(_manager.getInstanceName(), message.getMsgId()));
}
}
private void sendReply(HelixDataAccessor accessor, Message message, HelixTaskResult taskResult) {
if (_message.getCorrelationId() != null
&& !message.getMsgType().equals(MessageType.TASK_REPLY.toString())) {
logger.info("Sending reply for message " + message.getCorrelationId());
_statusUpdateUtil.logInfo(message, HelixTask.class, "Sending reply", accessor);
taskResult.getTaskResultMap().put("SUCCESS", "" + taskResult.isSuccess());
taskResult.getTaskResultMap().put("INTERRUPTED", "" + taskResult.isInterrupted());
if (!taskResult.isSuccess()) {
taskResult.getTaskResultMap().put("ERRORINFO", taskResult.getMessage());
}
Message replyMessage =
Message.createReplyMessage(_message, _manager.getInstanceName(),
taskResult.getTaskResultMap());
replyMessage.setSrcInstanceType(_manager.getInstanceType());
if (message.getSrcInstanceType() == InstanceType.PARTICIPANT) {
Builder keyBuilder = accessor.keyBuilder();
accessor.setProperty(keyBuilder.message(message.getMsgSrc(), replyMessage.getMsgId()),
replyMessage);
} else if (message.getSrcInstanceType() == InstanceType.CONTROLLER) {
Builder keyBuilder = accessor.keyBuilder();
accessor.setProperty(keyBuilder.controllerMessage(replyMessage.getMsgId()), replyMessage);
}
_statusUpdateUtil.logInfo(message, HelixTask.class,
"1 msg replied to " + replyMessage.getTgtName(), accessor);
}
}
private void reportMessageStat(HelixManager manager, Message message, HelixTaskResult taskResult) {
// report stat
if (!message.getMsgType().equals(MessageType.STATE_TRANSITION.toString())) {
return;
}
long now = new Date().getTime();
long msgReadTime = message.getReadTimeStamp();
long msgExecutionStartTime = message.getExecuteStartTimeStamp();
if (msgReadTime != 0 && msgExecutionStartTime != 0) {
long totalDelay = now - msgReadTime;
long executionDelay = now - msgExecutionStartTime;
if (totalDelay > 0 && executionDelay > 0) {
String fromState = message.getFromState();
String toState = message.getToState();
String transition = fromState + "--" + toState;
StateTransitionContext cxt =
new StateTransitionContext(manager.getClusterName(), manager.getInstanceName(),
message.getResourceName(), transition);
StateTransitionDataPoint data =
new StateTransitionDataPoint(totalDelay, executionDelay, taskResult.isSuccess());
_executor.getParticipantMonitor().reportTransitionStat(cxt, data);
}
} else {
logger.warn("message read time and start execution time not recorded.");
}
}
@Override
public String getTaskId() {
return _message.getId();
}
@Override
public Message getMessage() {
return _message;
}
@Override
public NotificationContext getNotificationContext() {
return _notificationContext;
}
@Override
public void onTimeout() {
_isTimeout = true;
_handler.onTimeout();
}
};
| apache-2.0 |
diguage/wanwan-site | src/main/dao/com/diguage/wanwan/dao/TaskMapper.java | 879 | package com.diguage.wanwan.dao;
import com.diguage.wanwan.entity.Task;
import com.diguage.wanwan.entity.TaskExample;
import com.diguage.wanwan.utils.MyBatisRepository;
import java.util.List;
import org.apache.ibatis.annotations.Param;
@MyBatisRepository
public interface TaskMapper {
int countByExample(TaskExample example);
int deleteByExample(TaskExample example);
int deleteByPrimaryKey(Integer id);
int insert(Task record);
int insertSelective(Task record);
List<Task> selectByExample(TaskExample example);
Task selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") Task record, @Param("example") TaskExample example);
int updateByExample(@Param("record") Task record, @Param("example") TaskExample example);
int updateByPrimaryKeySelective(Task record);
int updateByPrimaryKey(Task record);
} | apache-2.0 |
atulsm/Test_Projects | src/SyslogSimForAD.java | 4622 | import java.io.PrintWriter;
import java.net.Socket;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
public class SyslogSimForAD {
private static final int EPS = 2000;
private static final int NUM_THREADS = 1;
private static final int NUM_ES_PER_COLLECTOR = 1;
//private static final String SERVER = "localhost";
private static final String SERVER = "164.99.175.165";
private static final int PORT = 1469;
private static final boolean ssl = false;
private static final String[] msg = {
"MSWinEventLog 0 Security 1 Thu May 21 11:22:00 2009 593 Security SYSTEM User Success Audit TRAINING-NVLL2 Detailed Tracking A process has exited: Process ID: 1588 Image File Name: C:\\Program Files\\Snare\\SnareCore.exe User Name: TRAINING-NVLL2$ Domain: APPLABS Logon ID: (0x0,0x3E7) 0", //Windows collector
//"%ASA-6-302014: Teardown TCP connection 7177 for management:164.99.17.109/42257 to NP Identity Ifc:164.99.17.6/443 duration 0:00:00 bytes 2698 TCP FINs"
};
private static int threadNum =1;
public static void main(String[] args) throws Exception{
for(int i=0;i<NUM_THREADS;i++){
Thread.currentThread().sleep(100);
new Thread(){
public void run(){
String message = msg[threadNum %(msg.length)];
int local = threadNum++;
try{
Socket soc = null;
if(ssl){
soc = getSSLSocket();
}else{
soc = new Socket(SERVER,PORT);
}
PrintWriter writer = new PrintWriter(soc.getOutputStream());
long time = System.currentTimeMillis();
int localCount = 0;
while(true){
for(int j=0;j<NUM_ES_PER_COLLECTOR;j++){
writer.write("EventSource"+local+"."+j+" " +message + "\n");
writer.flush();
}
if(writer.checkError()){
break;
}
count ++;
localCount++;
long time1 = System.currentTimeMillis();
//check if 1 sec has passed
if((time1-time) >= 1000){
time = System.currentTimeMillis();
localCount=0;
}else if(localCount > EPS){
sleep(1000 - (time1 - time));
localCount = 0;
}
}
}catch(Exception e){
e.printStackTrace();
}
threadNum--;
}
}.start();
}
}
private static Socket getSSLSocket(){
SSLSocketFactory factory = null;
try {
SSLContext ctx;
KeyManagerFactory kmf;
KeyStore ks=null;
try{
ctx = SSLContext.getInstance("TLSv1.2");
}catch (Exception e) {
ctx = SSLContext.getInstance("TLS");
}
kmf = KeyManagerFactory.getInstance(KeyManagerFactory
.getDefaultAlgorithm());
ks = KeyStore.getInstance("JKS");
ks.load(null,null);
kmf.init(ks, null);
TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmFactory.init(ks);
TrustManager[] trustManagers = tmFactory.getTrustManagers();
X509TrustManager defaultTM = (X509TrustManager) trustManagers[0];
X509TrustManager allowAll = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
if(true){
return;
}
if(chain!= null && chain.length>0){
for(X509Certificate cert : chain){
cert.checkValidity();
}
}
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(kmf.getKeyManagers(),new TrustManager[]{allowAll},null);
factory = ctx.getSocketFactory();
return (SSLSocket)factory.createSocket(SERVER,PORT);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static int count = 0;
private static long lastTime = System.currentTimeMillis() - 1000;
static {
new Thread() {
public void run() {
while (true) {
System.out.println("EPS:" + (count *NUM_ES_PER_COLLECTOR)
/ ((System.currentTimeMillis() - lastTime) / 1000));
lastTime = System.currentTimeMillis();
count = 0;
try {
sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
if(threadNum==0){
break;
}
}
}
}.start();
}
}
| apache-2.0 |
srapisarda/ontop | ontop-protege/src/main/java/it/unibz/inf/ontop/protege/gui/tab/OntopSPARQLTab.java | 926 | package it.unibz.inf.ontop.protege.gui.tab;
/*
* #%L
* ontop-protege4
* %%
* Copyright (C) 2009 - 2013 KRDB Research Centre. Free University of Bozen Bolzano.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import org.protege.editor.owl.ui.OWLWorkspaceViewsTab;
public class OntopSPARQLTab extends OWLWorkspaceViewsTab {
@Override
public void initialise() {
super.initialise();
}
}
| apache-2.0 |
googleapis/google-api-java-client-services | clients/google-api-services-container/v1beta1/1.31.0/com/google/api/services/container/v1beta1/model/ILBSubsettingConfig.java | 2225 | /*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.container.v1beta1.model;
/**
* ILBSubsettingConfig contains the desired config of L4 Internal LoadBalancer subsetting on this
* cluster.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Kubernetes Engine API. For a detailed explanation
* see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class ILBSubsettingConfig extends com.google.api.client.json.GenericJson {
/**
* Enables l4 ILB subsetting for this cluster
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean enabled;
/**
* Enables l4 ILB subsetting for this cluster
* @return value or {@code null} for none
*/
public java.lang.Boolean getEnabled() {
return enabled;
}
/**
* Enables l4 ILB subsetting for this cluster
* @param enabled enabled or {@code null} for none
*/
public ILBSubsettingConfig setEnabled(java.lang.Boolean enabled) {
this.enabled = enabled;
return this;
}
@Override
public ILBSubsettingConfig set(String fieldName, Object value) {
return (ILBSubsettingConfig) super.set(fieldName, value);
}
@Override
public ILBSubsettingConfig clone() {
return (ILBSubsettingConfig) super.clone();
}
}
| apache-2.0 |
gawkermedia/googleads-java-lib | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201602/AudienceSegmentServiceInterfaceperformAudienceSegmentActionResponse.java | 1644 |
package com.google.api.ads.dfp.jaxws.v201602;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for performAudienceSegmentActionResponse element declaration.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <element name="performAudienceSegmentActionResponse">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="rval" type="{https://www.google.com/apis/ads/publisher/v201602}UpdateResult" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"rval"
})
@XmlRootElement(name = "performAudienceSegmentActionResponse")
public class AudienceSegmentServiceInterfaceperformAudienceSegmentActionResponse {
protected UpdateResult rval;
/**
* Gets the value of the rval property.
*
* @return
* possible object is
* {@link UpdateResult }
*
*/
public UpdateResult getRval() {
return rval;
}
/**
* Sets the value of the rval property.
*
* @param value
* allowed object is
* {@link UpdateResult }
*
*/
public void setRval(UpdateResult value) {
this.rval = value;
}
}
| apache-2.0 |
gawkermedia/googleads-java-lib | examples/dfp_axis/src/main/java/dfp/axis/v201511/audiencesegmentservice/CreateAudienceSegments.java | 6042 | // Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dfp.axis.v201511.audiencesegmentservice;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
import com.google.api.ads.dfp.axis.factory.DfpServices;
import com.google.api.ads.dfp.axis.v201511.AdUnitTargeting;
import com.google.api.ads.dfp.axis.v201511.AudienceSegment;
import com.google.api.ads.dfp.axis.v201511.AudienceSegmentServiceInterface;
import com.google.api.ads.dfp.axis.v201511.CustomCriteria;
import com.google.api.ads.dfp.axis.v201511.CustomCriteriaComparisonOperator;
import com.google.api.ads.dfp.axis.v201511.CustomCriteriaNode;
import com.google.api.ads.dfp.axis.v201511.CustomCriteriaSet;
import com.google.api.ads.dfp.axis.v201511.CustomCriteriaSetLogicalOperator;
import com.google.api.ads.dfp.axis.v201511.FirstPartyAudienceSegment;
import com.google.api.ads.dfp.axis.v201511.FirstPartyAudienceSegmentRule;
import com.google.api.ads.dfp.axis.v201511.InventoryTargeting;
import com.google.api.ads.dfp.axis.v201511.NetworkServiceInterface;
import com.google.api.ads.dfp.axis.v201511.RuleBasedFirstPartyAudienceSegment;
import com.google.api.ads.dfp.lib.client.DfpSession;
import com.google.api.client.auth.oauth2.Credential;
import java.util.Random;
/**
* This example creates new rule based first party audience segments. To
* determine which audience segments exist, run GetAllAudienceSegments.java.
*
* Credentials and properties in {@code fromFile()} are pulled from the
* "ads.properties" file. See README for more info.
*/
public class CreateAudienceSegments {
// Set the IDs of the custom criteria to be used in the segment rule.
private static final String CUSTOM_TARGETING_KEY_ID =
"INSERT_CUSTOM_TARGETING_KEY_ID_HERE";
private static final String CUSTOM_TARGETING_VALUE_ID =
"INSERT_CUSTOM_TARGETING_VALUE_ID_HERE";
public static void runExample(DfpServices dfpServices, DfpSession session,
long customTargetingKeyId, long customTargetingValueId) throws Exception {
// Get the AudienceSegmentService.
AudienceSegmentServiceInterface audienceSegmentService =
dfpServices.get(session, AudienceSegmentServiceInterface.class);
// Get the NetworkService.
NetworkServiceInterface networkService =
dfpServices.get(session, NetworkServiceInterface.class);
// Get the root ad unit ID used to target the whole site.
String rootAdUnitId = networkService.getCurrentNetwork().getEffectiveRootAdUnitId();
// Create inventory targeting.
InventoryTargeting inventoryTargeting = new InventoryTargeting();
// Create ad unit targeting for the root ad unit (i.e. the whole network).
AdUnitTargeting adUnitTargeting = new AdUnitTargeting();
adUnitTargeting.setAdUnitId(rootAdUnitId);
adUnitTargeting.setIncludeDescendants(true);
inventoryTargeting.setTargetedAdUnits(new AdUnitTargeting[] {adUnitTargeting});
// Create the custom criteria to be used in the segment rule.
// CUSTOM_TARGETING_KEY_ID == CUSTOM_TARGETING_VALUE_ID
CustomCriteria customCriteria = new CustomCriteria();
customCriteria.setKeyId(customTargetingKeyId);
customCriteria.setOperator(CustomCriteriaComparisonOperator.IS);
customCriteria.setValueIds(new long[] {customTargetingValueId});
// Create the custom criteria expression.
CustomCriteriaSet topCustomCriteriaSet = new CustomCriteriaSet();
topCustomCriteriaSet.setLogicalOperator(CustomCriteriaSetLogicalOperator.AND);
topCustomCriteriaSet.setChildren(new CustomCriteriaNode[] {customCriteria});
// Create the audience segment rule.
FirstPartyAudienceSegmentRule rule = new FirstPartyAudienceSegmentRule();
rule.setInventoryRule(inventoryTargeting);
rule.setCustomCriteriaRule(topCustomCriteriaSet);
// Create an audience segment.
RuleBasedFirstPartyAudienceSegment audienceSegment = new RuleBasedFirstPartyAudienceSegment();
audienceSegment.setName(
"Sports enthusiasts audience segment #" + new Random().nextInt(Integer.MAX_VALUE));
audienceSegment.setDescription("Sports enthusiasts between the ages of 20 and 30.");
audienceSegment.setPageViews(6);
audienceSegment.setRecencyDays(6);
audienceSegment.setMembershipExpirationDays(88);
audienceSegment.setRule(rule);
// Create the audience segment on the server.
AudienceSegment[] audienceSegments = audienceSegmentService.createAudienceSegments(
new FirstPartyAudienceSegment[] {audienceSegment});
for (AudienceSegment createdAudienceSegment : audienceSegments) {
System.out.printf(
"An audience segment with ID %d, name '%s', and type '%s' was created.%n",
createdAudienceSegment.getId(), createdAudienceSegment.getName(),
createdAudienceSegment.getType());
}
}
public static void main(String[] args) throws Exception {
// Generate a refreshable OAuth2 credential.
Credential oAuth2Credential = new OfflineCredentials.Builder()
.forApi(Api.DFP)
.fromFile()
.build()
.generateCredential();
// Construct a DfpSession.
DfpSession session = new DfpSession.Builder()
.fromFile()
.withOAuth2Credential(oAuth2Credential)
.build();
DfpServices dfpServices = new DfpServices();
runExample(dfpServices, session, Long.parseLong(CUSTOM_TARGETING_KEY_ID),
Long.parseLong(CUSTOM_TARGETING_VALUE_ID));
}
}
| apache-2.0 |
tripodsan/jackrabbit-oak | oak-upgrade/src/main/java/org/apache/jackrabbit/oak/upgrade/cli/MigrationFactory.java | 5326 | /*
* 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.jackrabbit.oak.upgrade.cli;
import java.io.IOException;
import java.util.Iterator;
import java.util.ServiceLoader;
import javax.jcr.RepositoryException;
import org.apache.jackrabbit.core.RepositoryContext;
import org.apache.jackrabbit.oak.plugins.blob.datastore.DataStoreBlobStore;
import org.apache.jackrabbit.oak.spi.blob.BlobStore;
import org.apache.jackrabbit.oak.spi.commit.CommitHook;
import org.apache.jackrabbit.oak.spi.state.NodeStore;
import org.apache.jackrabbit.oak.upgrade.RepositorySidegrade;
import org.apache.jackrabbit.oak.upgrade.RepositoryUpgrade;
import org.apache.jackrabbit.oak.upgrade.cli.parser.MigrationOptions;
import org.apache.jackrabbit.oak.upgrade.cli.parser.StoreArguments;
import com.google.common.collect.ImmutableList;
import com.google.common.io.Closer;
public class MigrationFactory {
protected final MigrationOptions options;
protected final StoreArguments stores;
protected final Closer closer;
public MigrationFactory(MigrationOptions options, StoreArguments stores, Closer closer) {
this.options = options;
this.stores = stores;
this.closer = closer;
}
public RepositoryUpgrade createUpgrade() throws IOException, RepositoryException {
RepositoryContext src = stores.getSrcStore().create(closer);
BlobStore srcBlobStore = new DataStoreBlobStore(src.getDataStore());
NodeStore dstStore = createTarget(closer, srcBlobStore);
return createUpgrade(src, dstStore);
}
public RepositorySidegrade createSidegrade() throws IOException {
BlobStore srcBlobStore = stores.getSrcBlobStore().create(closer);
NodeStore srcStore = stores.getSrcStore().create(srcBlobStore, closer);
NodeStore dstStore = createTarget(closer, srcBlobStore);
return createSidegrade(srcStore, dstStore);
}
protected NodeStore createTarget(Closer closer, BlobStore srcBlobStore) throws IOException {
BlobStore dstBlobStore;
if (options.isCopyBinariesByReference()) {
dstBlobStore = srcBlobStore;
} else {
dstBlobStore = stores.getDstBlobStore().create(closer);
}
NodeStore dstStore = stores.getDstStore().create(dstBlobStore, closer);
return dstStore;
}
protected RepositoryUpgrade createUpgrade(RepositoryContext source, NodeStore dstStore) {
RepositoryUpgrade upgrade = new RepositoryUpgrade(source, dstStore);
if (source.getDataStore() != null && options.isCopyBinariesByReference()) {
upgrade.setCopyBinariesByReference(true);
}
upgrade.setCopyVersions(options.getCopyVersions());
upgrade.setCopyOrphanedVersions(options.getCopyOrphanedVersions());
if (options.getIncludePaths() != null) {
upgrade.setIncludes(options.getIncludePaths());
}
if (options.getExcludePaths() != null) {
upgrade.setExcludes(options.getExcludePaths());
}
if (options.getMergePaths() != null) {
upgrade.setMerges(options.getMergePaths());
}
upgrade.setSkipLongNames(stores.isSkipLongNames());
upgrade.setSkipOnError(!options.isFailOnError());
upgrade.setEarlyShutdown(options.isEarlyShutdown());
upgrade.setSkipInitialization(options.isSkipInitialization());
ServiceLoader<CommitHook> loader = ServiceLoader.load(CommitHook.class);
Iterator<CommitHook> iterator = loader.iterator();
ImmutableList.Builder<CommitHook> builder = ImmutableList.<CommitHook> builder().addAll(iterator);
upgrade.setCustomCommitHooks(builder.build());
return upgrade;
}
private RepositorySidegrade createSidegrade(NodeStore srcStore, NodeStore dstStore) {
RepositorySidegrade sidegrade = new RepositorySidegrade(srcStore, dstStore);
sidegrade.setCopyVersions(options.getCopyVersions());
sidegrade.setCopyOrphanedVersions(options.getCopyOrphanedVersions());
if (options.getIncludePaths() != null) {
sidegrade.setIncludes(options.getIncludePaths());
}
if (options.getExcludePaths() != null) {
sidegrade.setExcludes(options.getExcludePaths());
}
if (options.getMergePaths() != null) {
sidegrade.setMerges(options.getMergePaths());
}
sidegrade.setSkipLongNames(stores.isSkipLongNames());
sidegrade.setSkipInitialization(options.isSkipInitialization());
return sidegrade;
}
}
| apache-2.0 |
NationalSecurityAgency/ghidra | Ghidra/Debug/Debugger-agent-dbgmodel/src/test/java/agent/dbgmodel/model/invm/InVmModelForDbgmodelInterpreterTest.java | 2589 | /* ###
* IP: GHIDRA
*
* 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 agent.dbgmodel.model.invm;
import static org.junit.Assert.assertNull;
import static org.junit.Assume.assumeTrue;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
import agent.dbgeng.model.AbstractModelForDbgengInterpreterTest;
import agent.dbgeng.model.WindowsSpecimen;
import agent.dbgeng.model.iface2.DbgModelTargetProcess;
import ghidra.dbg.target.TargetInterpreter;
import ghidra.dbg.target.TargetProcess;
import ghidra.dbg.test.AbstractDebuggerModelTest;
import ghidra.dbg.test.ProvidesTargetViaLaunchSpecimen;
import ghidra.dbg.util.PathUtils;
public class InVmModelForDbgmodelInterpreterTest extends AbstractModelForDbgengInterpreterTest
implements ProvidesTargetViaLaunchSpecimen {
@Override
public ModelHost modelHost() throws Throwable {
return new InVmDbgmodelModelHost();
}
@Override
public AbstractDebuggerModelTest getTest() {
return this;
}
@Override
protected List<String> seedPath() {
return PathUtils.parse("");
}
@Override
public List<String> getExpectedInterpreterPath() {
return PathUtils.parse("Sessions[0x0]");
}
@Override
protected void ensureInterpreterAvailable() throws Throwable {
obtainTarget();
}
@Override
@Ignore
@Test
public void testAttachViaInterpreterShowsInProcessContainer() throws Throwable {
super.testAttachViaInterpreterShowsInProcessContainer();
}
@Override
@Test
public void testLaunchViaInterpreterShowsInProcessContainer() throws Throwable {
assumeTrue(m.hasProcessContainer());
m.build();
DbgModelTargetProcess initialTarget = (DbgModelTargetProcess) obtainTarget();
DebuggerTestSpecimen specimen = WindowsSpecimen.NOTEPAD;
assertNull(getProcessRunning(specimen, this));
TargetInterpreter interpreter = findInterpreter();
for (String line : specimen.getLaunchScript()) {
waitOn(interpreter.execute(line));
}
TargetProcess process = retryForProcessRunning(specimen, this);
initialTarget.detach();
runTestKillViaInterpreter(process, interpreter);
}
}
| apache-2.0 |
Banno/sbt-plantuml-plugin | src/main/java/gen/lib/common/input__c.java | 70438 | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* Project Info: http://plantuml.com
*
* This file is part of Smetana.
* Smetana is a partial translation of Graphviz/Dot sources from C to Java.
*
* (C) Copyright 2009-2017, Arnaud Roques
*
* This translation is distributed under the same Licence as the original C program:
*
*************************************************************************
* Copyright (c) 2011 AT&T Intellectual Property
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: See CVS logs. Details at http://www.graphviz.org/
*************************************************************************
*
* THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC
* LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0]
*
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
*
* You may obtain a copy of the License at
*
* http://www.eclipse.org/legal/epl-v10.html
*
* 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 gen.lib.common;
import static gen.lib.cgraph.attr__c.agattr;
import static gen.lib.cgraph.attr__c.agget;
import static gen.lib.cgraph.obj__c.agroot;
import static gen.lib.cgraph.refstr__c.aghtmlstr;
import static gen.lib.common.emit__c.init_xdot;
import static gen.lib.common.labels__c.make_label;
import static gen.lib.common.labels__c.strdup_and_subst_obj;
import static gen.lib.common.memory__c.zmalloc;
import static gen.lib.common.utils__c.late_double;
import static gen.lib.common.utils__c.late_int;
import static gen.lib.common.utils__c.late_nnstring;
import static gen.lib.common.utils__c.late_string;
import static gen.lib.common.utils__c.mapbool;
import static gen.lib.common.utils__c.maptoken;
import static smetana.core.JUtils.EQ;
import static smetana.core.JUtils.NEQ;
import static smetana.core.JUtils.atof;
import static smetana.core.JUtils.atoi;
import static smetana.core.JUtils.enumAsInt;
import static smetana.core.JUtils.getenv;
import static smetana.core.JUtils.sizeof;
import static smetana.core.JUtils.strstr;
import static smetana.core.JUtilsDebug.ENTERING;
import static smetana.core.JUtilsDebug.LEAVING;
import static smetana.core.Macro.AGEDGE;
import static smetana.core.Macro.AGNODE;
import static smetana.core.Macro.AGRAPH;
import static smetana.core.Macro.GD_border;
import static smetana.core.Macro.GD_charset;
import static smetana.core.Macro.GD_drawing;
import static smetana.core.Macro.GD_exact_ranksep;
import static smetana.core.Macro.GD_flip;
import static smetana.core.Macro.GD_fontnames;
import static smetana.core.Macro.GD_has_labels;
import static smetana.core.Macro.GD_label;
import static smetana.core.Macro.GD_label_pos;
import static smetana.core.Macro.GD_nodesep;
import static smetana.core.Macro.GD_rankdir2;
import static smetana.core.Macro.GD_ranksep;
import static smetana.core.Macro.GD_showboxes;
import static smetana.core.Macro.N;
import static smetana.core.Macro.ROUND;
import static smetana.core.Macro.UNSUPPORTED;
import h.Agraph_s;
import h.boxf;
import h.fontname_kind;
import h.layout_t;
import h.pointf;
import smetana.core.CString;
import smetana.core.Z;
import smetana.core.__struct__;
public class input__c {
//1 2digov3edok6d5srhgtlmrycs
// extern lt_symlist_t lt_preloaded_symbols[]
//1 baedz5i9est5csw3epz3cv7z
// typedef Ppoly_t Ppolyline_t
//1 9k44uhd5foylaeoekf3llonjq
// extern Dtmethod_t* Dtset
//1 1ahfywsmzcpcig2oxm7pt9ihj
// extern Dtmethod_t* Dtbag
//1 anhghfj3k7dmkudy2n7rvt31v
// extern Dtmethod_t* Dtoset
//1 5l6oj1ux946zjwvir94ykejbc
// extern Dtmethod_t* Dtobag
//1 2wtf222ak6cui8cfjnw6w377z
// extern Dtmethod_t* Dtlist
//1 d1s1s6ibtcsmst88e3057u9r7
// extern Dtmethod_t* Dtstack
//1 axa7mflo824p6fspjn1rdk0mt
// extern Dtmethod_t* Dtqueue
//1 ega812utobm4xx9oa9w9ayij6
// extern Dtmethod_t* Dtdeque
//1 cyfr996ur43045jv1tjbelzmj
// extern Dtmethod_t* Dtorder
//1 wlofoiftbjgrrabzb2brkycg
// extern Dtmethod_t* Dttree
//1 12bds94t7voj7ulwpcvgf6agr
// extern Dtmethod_t* Dthash
//1 9lqknzty480cy7zsubmabkk8h
// extern Dtmethod_t _Dttree
//1 bvn6zkbcp8vjdhkccqo1xrkrb
// extern Dtmethod_t _Dthash
//1 9lidhtd6nsmmv3e7vjv9e10gw
// extern Dtmethod_t _Dtlist
//1 34ujfamjxo7xn89u90oh2k6f8
// extern Dtmethod_t _Dtqueue
//1 3jy4aceckzkdv950h89p4wjc8
// extern Dtmethod_t _Dtstack
//1 8dfqgf3u1v830qzcjqh9o8ha7
// extern Agmemdisc_t AgMemDisc
//1 18k2oh2t6llfsdc5x0wlcnby8
// extern Agiddisc_t AgIdDisc
//1 a4r7hi80gdxtsv4hdoqpyiivn
// extern Agiodisc_t AgIoDisc
//1 bnzt5syjb7mgeru19114vd6xx
// extern Agdisc_t AgDefaultDisc
//1 35y2gbegsdjilegaribes00mg
// extern Agdesc_t Agdirected, Agstrictdirected, Agundirected, Agstrictundirected
//1 c2rygslq6bcuka3awmvy2b3ow
// typedef Agsubnode_t Agnoderef_t
//1 xam6yv0dcsx57dtg44igpbzn
// typedef Dtlink_t Agedgeref_t
//1 nye6dsi1twkbddwo9iffca1j
// extern char *Version
//1 65mu6k7h7lb7bx14jpiw7iyxr
// extern char **Files
//1 2rpjdzsdyrvomf00zcs3u3dyn
// extern const char **Lib
//1 6d2f111lntd2rsdt4gswh5909
// extern char *CmdName
//1 a0ltq04fpeg83soa05a2fkwb2
// extern char *specificFlags
//1 1uv30qeqq2jh6uznlr4dziv0y
// extern char *specificItems
//1 7i4hkvngxe3x7lmg5h6b3t9g3
// extern char *Gvfilepath
//1 9jp96pa73kseya3w6sulxzok6
// extern char *Gvimagepath
//1 40ylumfu7mrvawwf4v2asvtwk
// extern unsigned char Verbose
//1 93st8awjy1z0h07n28qycbaka
// extern unsigned char Reduce
//1 f2vs67ts992erf8onwfglurzp
// extern int MemTest
//1 c6f8whijgjwwagjigmxlwz3gb
// extern char *HTTPServerEnVar
//1 cp4hzj7p87m7arw776d3bt7aj
// extern char *Output_file_name
//1 a3rqagofsgraie6mx0krzkgsy
// extern int graphviz_errors
//1 5up05203r4kxvjn1m4njcgq5x
// extern int Nop
//1 umig46cco431x14b3kosde2t
// extern double PSinputscale
//1 52bj6v8fqz39khasobljfukk9
// extern int Syntax_errors
//1 9ekf2ina8fsjj6y6i0an6somj
// extern int Show_cnt
//1 38di5qi3nkxkq65onyvconk3r
// extern char** Show_boxes
//1 6ri6iu712m8mpc7t2670etpcw
// extern int CL_type
//1 bomxiw3gy0cgd1ydqtek7fpxr
// extern unsigned char Concentrate
//1 cqy3gqgcq8empdrbnrhn84058
// extern double Epsilon
//1 64slegfoouqeg0rmbyjrm8wgr
// extern int MaxIter
//1 88wdinpnmfs4mab4aw62yb0bg
// extern int Ndim
//1 8bbad3ogcelqnnvo5br5s05gq
// extern int State
//1 17rnd8q45zclfn68qqst2vxxn
// extern int EdgeLabelsDone
//1 ymx1z4s8cznjifl2d9f9m8jr
// extern double Initial_dist
//1 a33bgl0c3uqb3trx419qulj1x
// extern double Damping
//1 d9lvrpjg1r0ojv40pod1xwk8n
// extern int Y_invert
//1 71efkfs77q5tq9ex6y0f4kanh
// extern int GvExitOnUsage
//1 4xy2dkdkv0acs2ue9eca8hh2e
// extern Agsym_t *G_activepencolor, *G_activefillcolor, *G_selectedpencolor, *G_selectedfillcolor, *G_visitedpencolor, *G_visitedfillcolor, *G_deletedpencolor, *G_deletedfillcolor, *G_ordering, *G_peripheries, *G_penwidth, *G_gradientangle, *G_margin
//1 9js5gxgzr74eakgtfhnbws3t9
// extern Agsym_t *N_height, *N_width, *N_shape, *N_color, *N_fillcolor, *N_activepencolor, *N_activefillcolor, *N_selectedpencolor, *N_selectedfillcolor, *N_visitedpencolor, *N_visitedfillcolor, *N_deletedpencolor, *N_deletedfillcolor, *N_fontsize, *N_fontname, *N_fontcolor, *N_margin, *N_label, *N_xlabel, *N_nojustify, *N_style, *N_showboxes, *N_sides, *N_peripheries, *N_ordering, *N_orientation, *N_skew, *N_distortion, *N_fixed, *N_imagescale, *N_layer, *N_group, *N_comment, *N_vertices, *N_z, *N_penwidth, *N_gradientangle
//1 anqllp9sj7wo45w6bm11j8trn
// extern Agsym_t *E_weight, *E_minlen, *E_color, *E_fillcolor, *E_activepencolor, *E_activefillcolor, *E_selectedpencolor, *E_selectedfillcolor, *E_visitedpencolor, *E_visitedfillcolor, *E_deletedpencolor, *E_deletedfillcolor, *E_fontsize, *E_fontname, *E_fontcolor, *E_label, *E_xlabel, *E_dir, *E_style, *E_decorate, *E_showboxes, *E_arrowsz, *E_constr, *E_layer, *E_comment, *E_label_float, *E_samehead, *E_sametail, *E_arrowhead, *E_arrowtail, *E_headlabel, *E_taillabel, *E_labelfontsize, *E_labelfontname, *E_labelfontcolor, *E_labeldistance, *E_labelangle, *E_tailclip, *E_headclip, *E_penwidth
//1 bh0z9puipqw7gymjd5h5b8s6i
// extern struct fdpParms_s* fdp_parms
//3 ciez0pfggxdljedzsbklq49f0
// static inline point pointof(int x, int y)
public static Object pointof(Object... arg) {
UNSUPPORTED("8e4tj258yvfq5uhsdpk37n5eq"); // static inline point pointof(int x, int y)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("c0j3k9xv06332q98k2pgpacto"); // point r;
UNSUPPORTED("12jimkrzqxavaie0cpapbx18c"); // r.x = x;
UNSUPPORTED("7ivmviysahgsc5nn9gtp7q2if"); // r.y = y;
UNSUPPORTED("a2hk6w52njqjx48nq3nnn2e5i"); // return r;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 c1s4k85p1cdfn176o3uryeros
// static inline pointf pointfof(double x, double y)
public static __struct__<pointf> pointfof(double x, double y) {
// WARNING!! STRUCT
return pointfof_w_(x, y).copy();
}
private static __struct__<pointf> pointfof_w_(double x, double y) {
ENTERING("c1s4k85p1cdfn176o3uryeros","pointfof");
try {
final __struct__<pointf> r = __struct__.from(pointf.class);
r.setDouble("x", x);
r.setDouble("y", y);
return r;
} finally {
LEAVING("c1s4k85p1cdfn176o3uryeros","pointfof");
}
}
//3 7cufnfitrh935ew093mw0i4b7
// static inline box boxof(int llx, int lly, int urx, int ury)
public static Object boxof(Object... arg) {
UNSUPPORTED("3lzesfdd337h31jrlib1czocm"); // static inline box boxof(int llx, int lly, int urx, int ury)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("52u27kayecy1i1e8bbo8f7s9r"); // box b;
UNSUPPORTED("cylhjlutoc0sc0uy7g98m9fb8"); // b.LL.x = llx, b.LL.y = lly;
UNSUPPORTED("242of6revxzx8hpe7yerrchz6"); // b.UR.x = urx, b.UR.y = ury;
UNSUPPORTED("2vmm1j57brhn455f8f3iyw6mo"); // return b;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 1vvsta5i8of59frav6uymguav
// static inline boxf boxfof(double llx, double lly, double urx, double ury)
public static __struct__<boxf> boxfof(double llx, double lly, double urx, double ury) {
// WARNING!! STRUCT
return boxfof_w_(llx, lly, urx, ury).copy();
}
private static __struct__<boxf> boxfof_w_(double llx, double lly, double urx, double ury) {
ENTERING("1vvsta5i8of59frav6uymguav","boxfof");
try {
final __struct__<boxf> b = __struct__.from(boxf.class);
b.getStruct("LL").setDouble("x", llx);
b.getStruct("LL").setDouble("y", lly);
b.getStruct("UR").setDouble("x", urx);
b.getStruct("UR").setDouble("y", ury);
return b;
} finally {
LEAVING("1vvsta5i8of59frav6uymguav","boxfof");
}
}
//3 1n5xl70wxuabyf97mclvilsm6
// static inline point add_point(point p, point q)
public static Object add_point(Object... arg) {
UNSUPPORTED("6iamka1fx8fk1rohzzse8phte"); // static inline point add_point(point p, point q)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("c0j3k9xv06332q98k2pgpacto"); // point r;
UNSUPPORTED("3n2sizjd0civbzm6iq7su1s2p"); // r.x = p.x + q.x;
UNSUPPORTED("65ygdo31w09i5i6bd2f7azcd3"); // r.y = p.y + q.y;
UNSUPPORTED("a2hk6w52njqjx48nq3nnn2e5i"); // return r;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 arrsbik9b5tnfcbzsm8gr2chx
// static inline pointf add_pointf(pointf p, pointf q)
public static __struct__<pointf> add_pointf(final __struct__<pointf> p, final __struct__<pointf> q) {
// WARNING!! STRUCT
return add_pointf_w_(p.copy(), q.copy()).copy();
}
private static __struct__<pointf> add_pointf_w_(final __struct__<pointf> p, final __struct__<pointf> q) {
ENTERING("arrsbik9b5tnfcbzsm8gr2chx","add_pointf");
try {
final __struct__<pointf> r = __struct__.from(pointf.class);
r.setDouble("x", p.getDouble("x") + q.getDouble("x"));
r.setDouble("y", p.getDouble("y") + q.getDouble("y"));
return r;
} finally {
LEAVING("arrsbik9b5tnfcbzsm8gr2chx","add_pointf");
}
}
//3 ai2dprak5y6obdsflguh5qbd7
// static inline point sub_point(point p, point q)
public static Object sub_point(Object... arg) {
UNSUPPORTED("cd602849h0bce8lu9xegka0ia"); // static inline point sub_point(point p, point q)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("c0j3k9xv06332q98k2pgpacto"); // point r;
UNSUPPORTED("4q4q9dveah93si8ajfv59gz27"); // r.x = p.x - q.x;
UNSUPPORTED("9f90ik0o2yqhanzntpy3d2ydy"); // r.y = p.y - q.y;
UNSUPPORTED("a2hk6w52njqjx48nq3nnn2e5i"); // return r;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 16f6pyogcv3j7n2p0n8giqqgh
// static inline pointf sub_pointf(pointf p, pointf q)
public static Object sub_pointf(Object... arg) {
UNSUPPORTED("dmufj44lddsnj0wjyxsg2fcso"); // static inline pointf sub_pointf(pointf p, pointf q)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("cvexv13y9fq49v0j4d5t4cm9f"); // pointf r;
UNSUPPORTED("4q4q9dveah93si8ajfv59gz27"); // r.x = p.x - q.x;
UNSUPPORTED("9f90ik0o2yqhanzntpy3d2ydy"); // r.y = p.y - q.y;
UNSUPPORTED("a2hk6w52njqjx48nq3nnn2e5i"); // return r;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 9k50jgrhc4f9824vf8ony74rw
// static inline point mid_point(point p, point q)
public static Object mid_point(Object... arg) {
UNSUPPORTED("evy44tdsmu3erff9dp2x835u2"); // static inline point mid_point(point p, point q)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("c0j3k9xv06332q98k2pgpacto"); // point r;
UNSUPPORTED("1a6p6fm57o0wt5ze2btsx06c7"); // r.x = (p.x + q.x) / 2;
UNSUPPORTED("1kbj5tgdmfi6kf4jgg6skhr6e"); // r.y = (p.y + q.y) / 2;
UNSUPPORTED("a2hk6w52njqjx48nq3nnn2e5i"); // return r;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 59c4f7im0ftyowhnzzq2v9o1x
// static inline pointf mid_pointf(pointf p, pointf q)
public static Object mid_pointf(Object... arg) {
UNSUPPORTED("381o63o9kb04d7gzg65v0r3q"); // static inline pointf mid_pointf(pointf p, pointf q)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("cvexv13y9fq49v0j4d5t4cm9f"); // pointf r;
UNSUPPORTED("c5vboetlr3mf43wns7iik6m1w"); // r.x = (p.x + q.x) / 2.;
UNSUPPORTED("bcdf562ldr3bjn78hcay5xd63"); // r.y = (p.y + q.y) / 2.;
UNSUPPORTED("a2hk6w52njqjx48nq3nnn2e5i"); // return r;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 5r18p38gisvcx3zsvbb9saixx
// static inline pointf interpolate_pointf(double t, pointf p, pointf q)
public static Object interpolate_pointf(Object... arg) {
UNSUPPORTED("894yimn33kmtm454llwdaotu8"); // static inline pointf interpolate_pointf(double t, pointf p, pointf q)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("ef2acl8wa2ooqcb5vz3098maz"); // pointf r;
UNSUPPORTED("5tpwuyf5iidesy80v8o4nwkmk"); // r.x = p.x + t * (q.x - p.x);
UNSUPPORTED("ewnrc5uloj3w5jbmsjcn3wja0"); // r.y = p.y + t * (q.y - p.y);
UNSUPPORTED("a2hk6w52njqjx48nq3nnn2e5i"); // return r;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 bxzrv2ghq04qk5cbyy68s4mol
// static inline point exch_xy(point p)
public static Object exch_xy(Object... arg) {
UNSUPPORTED("2vxya0v2fzlv5e0vjaa8d414"); // static inline point exch_xy(point p)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("c0j3k9xv06332q98k2pgpacto"); // point r;
UNSUPPORTED("60cojdwc2h7f0m51s9jdwvup7"); // r.x = p.y;
UNSUPPORTED("evp2x66oa4s1tlnc0ytxq2qbq"); // r.y = p.x;
UNSUPPORTED("a2hk6w52njqjx48nq3nnn2e5i"); // return r;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 9lt3e03tac6h6sydljrcws8fd
// static inline pointf exch_xyf(pointf p)
public static Object exch_xyf(Object... arg) {
UNSUPPORTED("8qamrobrqi8jsvvfrxkimrsnw"); // static inline pointf exch_xyf(pointf p)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("cvexv13y9fq49v0j4d5t4cm9f"); // pointf r;
UNSUPPORTED("60cojdwc2h7f0m51s9jdwvup7"); // r.x = p.y;
UNSUPPORTED("evp2x66oa4s1tlnc0ytxq2qbq"); // r.y = p.x;
UNSUPPORTED("a2hk6w52njqjx48nq3nnn2e5i"); // return r;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 8l9qhieokthntzdorlu5zn29b
// static inline box box_bb(box b0, box b1)
public static Object box_bb(Object... arg) {
UNSUPPORTED("36et5gmnjrby6o7bq9sgh1hx6"); // static inline box box_bb(box b0, box b1)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("52u27kayecy1i1e8bbo8f7s9r"); // box b;
UNSUPPORTED("8mr2c9xitsqi8z1plbp7ox1hu"); // b.LL.x = MIN(b0.LL.x, b1.LL.x);
UNSUPPORTED("2egu55ef4u1i03nwz01k7kcrl"); // b.LL.y = MIN(b0.LL.y, b1.LL.y);
UNSUPPORTED("9n6ei3odbgefwfxvql9whcpe"); // b.UR.x = MAX(b0.UR.x, b1.UR.x);
UNSUPPORTED("19ocysbuh4pxyft2bqhyhigr1"); // b.UR.y = MAX(b0.UR.y, b1.UR.y);
UNSUPPORTED("2vmm1j57brhn455f8f3iyw6mo"); // return b;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 clws9h3bbjm0lw3hexf8nl4c4
// static inline boxf boxf_bb(boxf b0, boxf b1)
public static Object boxf_bb(Object... arg) {
UNSUPPORTED("dyrqu4ww9osr9c86gqgmifcp6"); // static inline boxf boxf_bb(boxf b0, boxf b1)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("c57pq0f87j6dnbcvygu7v6k84"); // boxf b;
UNSUPPORTED("8mr2c9xitsqi8z1plbp7ox1hu"); // b.LL.x = MIN(b0.LL.x, b1.LL.x);
UNSUPPORTED("2egu55ef4u1i03nwz01k7kcrl"); // b.LL.y = MIN(b0.LL.y, b1.LL.y);
UNSUPPORTED("9n6ei3odbgefwfxvql9whcpe"); // b.UR.x = MAX(b0.UR.x, b1.UR.x);
UNSUPPORTED("19ocysbuh4pxyft2bqhyhigr1"); // b.UR.y = MAX(b0.UR.y, b1.UR.y);
UNSUPPORTED("2vmm1j57brhn455f8f3iyw6mo"); // return b;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 bit6ycxo1iqd2al92y8gkzlvb
// static inline box box_intersect(box b0, box b1)
public static Object box_intersect(Object... arg) {
UNSUPPORTED("34gv28cldst09bl71itjgviue"); // static inline box box_intersect(box b0, box b1)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("52u27kayecy1i1e8bbo8f7s9r"); // box b;
UNSUPPORTED("9slu7bixuymxttjic76ha2nl2"); // b.LL.x = MAX(b0.LL.x, b1.LL.x);
UNSUPPORTED("3uv943c2f82yuif249pf5azob"); // b.LL.y = MAX(b0.LL.y, b1.LL.y);
UNSUPPORTED("74tf5h16bc9zabq3s3dyny543"); // b.UR.x = MIN(b0.UR.x, b1.UR.x);
UNSUPPORTED("d99gcv3i7xes7y7rqf8ii20ux"); // b.UR.y = MIN(b0.UR.y, b1.UR.y);
UNSUPPORTED("2vmm1j57brhn455f8f3iyw6mo"); // return b;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 8gfybie7k6pgb3o1a6llgpwng
// static inline boxf boxf_intersect(boxf b0, boxf b1)
public static Object boxf_intersect(Object... arg) {
UNSUPPORTED("ape22b8z6jfg17gvo42hok9eb"); // static inline boxf boxf_intersect(boxf b0, boxf b1)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("c57pq0f87j6dnbcvygu7v6k84"); // boxf b;
UNSUPPORTED("9slu7bixuymxttjic76ha2nl2"); // b.LL.x = MAX(b0.LL.x, b1.LL.x);
UNSUPPORTED("3uv943c2f82yuif249pf5azob"); // b.LL.y = MAX(b0.LL.y, b1.LL.y);
UNSUPPORTED("74tf5h16bc9zabq3s3dyny543"); // b.UR.x = MIN(b0.UR.x, b1.UR.x);
UNSUPPORTED("d99gcv3i7xes7y7rqf8ii20ux"); // b.UR.y = MIN(b0.UR.y, b1.UR.y);
UNSUPPORTED("2vmm1j57brhn455f8f3iyw6mo"); // return b;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 7z8j2quq65govaaejrz7b4cvb
// static inline int box_overlap(box b0, box b1)
public static Object box_overlap(Object... arg) {
UNSUPPORTED("1e9k599x7ygct7r4cfdxlk9u9"); // static inline int box_overlap(box b0, box b1)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("7a9wwpu7dhdphd08y1ecw54w5"); // return OVERLAP(b0, b1);
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 4z0suuut2acsay5m8mg9dqjdu
// static inline int boxf_overlap(boxf b0, boxf b1)
public static Object boxf_overlap(Object... arg) {
UNSUPPORTED("905nejsewihwhhc3bhnrz9nwo"); // static inline int boxf_overlap(boxf b0, boxf b1)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("7a9wwpu7dhdphd08y1ecw54w5"); // return OVERLAP(b0, b1);
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 dd34swz5rmdgu3a2np2a4h1dy
// static inline int box_contains(box b0, box b1)
public static Object box_contains(Object... arg) {
UNSUPPORTED("aputfc30fjkvy6jx4otljaczq"); // static inline int box_contains(box b0, box b1)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("87ap80vrh2a4gpprbxr33lrg3"); // return CONTAINS(b0, b1);
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 8laj1bspbu2i1cjd9upr7xt32
// static inline int boxf_contains(boxf b0, boxf b1)
public static Object boxf_contains(Object... arg) {
UNSUPPORTED("7ccnttkiwt834yfyw0evcm18v"); // static inline int boxf_contains(boxf b0, boxf b1)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("87ap80vrh2a4gpprbxr33lrg3"); // return CONTAINS(b0, b1);
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 4wf5swkz24xx51ja2dynbycu1
// static inline pointf perp (pointf p)
public static Object perp(Object... arg) {
UNSUPPORTED("567wpqlg9rv63ynyvxd9sgkww"); // static inline pointf perp (pointf p)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("cvexv13y9fq49v0j4d5t4cm9f"); // pointf r;
UNSUPPORTED("2fyydy6t6yifjsczccsb9szeg"); // r.x = -p.y;
UNSUPPORTED("evp2x66oa4s1tlnc0ytxq2qbq"); // r.y = p.x;
UNSUPPORTED("a2hk6w52njqjx48nq3nnn2e5i"); // return r;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 6dtlpzv4mvgzb9o0b252yweuv
// static inline pointf scale (double c, pointf p)
public static Object scale(Object... arg) {
UNSUPPORTED("c1ngytew34bmkdb7vps5h3dh8"); // static inline pointf scale (double c, pointf p)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("cvexv13y9fq49v0j4d5t4cm9f"); // pointf r;
UNSUPPORTED("dznf7nac14snww4usquyd6r3r"); // r.x = c * p.x;
UNSUPPORTED("33kk73m8vjcux5tnjl8co2pe6"); // r.y = c * p.y;
UNSUPPORTED("a2hk6w52njqjx48nq3nnn2e5i"); // return r;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//1 1fi3wib3hc7ibek0vfrpx9k3i
// static char *usageFmt =
//1 cpzagrot2j4620xbm08g3qbaz
// static char *genericItems =
//1 ej8f5pc6itbjzywbvv9r7pgog
// static char *neatoFlags =
//1 6zygu4f39vz4q5m4oiz64om5v
// static char *neatoItems =
//1 a5i7jzdqfacw4bequdriv6cb9
// static char *fdpFlags =
//1 9hrf5y45qp9kii44glcd4nx6e
// static char *fdpItems =
//1 bw7swzrd97c859k69vhbo6xui
// static char *memtestFlags =
//1 dlf2hcbhlyk0xi7y4hhyxdjlg
// static char *memtestItems =
//1 bfkjkg4j8ncjq3fbcfon7ce1a
// static char *configFlags =
//1 cwsgle0ax1dh0i4rb6c4n90s8
// static char *configItems =
//3 18dk9rr2jwvw2k0pwd01u1rp
// int dotneato_usage(int exval)
public static Object dotneato_usage(Object... arg) {
UNSUPPORTED("cjfxortgnqo3ho8cb4mse3bjk"); // int dotneato_usage(int exval)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("9qo38fqtykhj9o5wf9n2mmvf9"); // FILE *outs;
UNSUPPORTED("6p2t5f6k16pthcnlxnvr8fxp2"); // if (exval > 0)
UNSUPPORTED("ajsyw6vt4yc7jws9my3dfqw55"); // outs = stderr;
UNSUPPORTED("div10atae09n36x269sl208r1"); // else
UNSUPPORTED("9ymsocy1jyvql8lvl7z9v3x1d"); // outs = stdout;
UNSUPPORTED("eo2ztyy17mz06ptqvcj5azpza"); // fprintf(outs, usageFmt, CmdName);
UNSUPPORTED("1nhpls9sffy8jo9sa7638u515"); // fputs(neatoFlags, outs);
UNSUPPORTED("578fe6racfp402cmjp3xuomor"); // fputs(fdpFlags, outs);
UNSUPPORTED("a3xdyyuyrv70igk8e8z4415gn"); // fputs(memtestFlags, outs);
UNSUPPORTED("59cqs6545cogaa8zbv9x1fep0"); // fputs(configFlags, outs);
UNSUPPORTED("9qmx2r5uawon9q2snigjcita"); // fputs(genericItems, outs);
UNSUPPORTED("18sodiqes6jpcc8fj1vlkj6bd"); // fputs(neatoItems, outs);
UNSUPPORTED("boxkj32094gcugdk6u9p1hppc"); // fputs(fdpItems, outs);
UNSUPPORTED("4yygtzneqsdphtbnhfta2lge0"); // fputs(memtestItems, outs);
UNSUPPORTED("8ywutcqn5x3zpugo58b72ualq"); // fputs(configItems, outs);
UNSUPPORTED("3rabv7gfkqu0ag8x2rjiyrjbr"); // if (GvExitOnUsage && (exval >= 0))
UNSUPPORTED("1swto2i8s568mypddkno5wez1"); // exit(exval);
UNSUPPORTED("3jphahsl7jw3c1c1u71vs8dj3"); // return (exval+1);
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 9s68av3h3ph5gjla9e2d3220t
// static char *getFlagOpt(int argc, char **argv, int *idx)
public static Object getFlagOpt(Object... arg) {
UNSUPPORTED("7i2co2mk6i4v2e5zed6cohfi0"); // static char *getFlagOpt(int argc, char **argv, int *idx)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("c0vo8zzyjurgsxynujp3wbwn3"); // int i = *idx;
UNSUPPORTED("9ldayvulqiau72gm4iigedbe"); // char *arg = argv[i];
UNSUPPORTED("1ii197c2ypmbtq6b4c6xrmqre"); // if (arg[2])
UNSUPPORTED("85bk7kest90gpgv6qhqqam6od"); // return arg + 2;
UNSUPPORTED("62vtkmbmceearvwa1gge24udl"); // if (i < argc - 1) {
UNSUPPORTED("chd2f5z6rt19lbaye25ej7q6j"); // i++;
UNSUPPORTED("dbe1l1xge33op9cemtc13bsld"); // arg = argv[i];
UNSUPPORTED("e7t6j4nall86kdxxvxopr6hl7"); // if (*arg && (*arg != '-')) {
UNSUPPORTED("a1qi3k2o6tudikh6zg6qxb32v"); // *idx = i;
UNSUPPORTED("aegbvj6xoqbt16mud86st36ex"); // return arg;
UNSUPPORTED("flupwh3kosf3fkhkxllllt1"); // }
UNSUPPORTED("dvgyxsnyeqqnyzq696k3vskib"); // }
UNSUPPORTED("5oxhd3fvp0gfmrmz12vndnjt"); // return 0;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 2dx6lb6fkeqxispmv7w0bgsat
// static char* dotneato_basename (char* path)
public static Object dotneato_basename(Object... arg) {
UNSUPPORTED("58z62a4pwz8fb1fqzgemmk2v"); // static char* dotneato_basename (char* path)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("60anbhq8j280g1jvxqcu76t4v"); // char* ret;
UNSUPPORTED("cmcyg2bmd7exlb7oegpilnua8"); // char* s = path;
UNSUPPORTED("7oz55r1w75doc5wm9wdr5ud7c"); // if (*s == '\0') return path; /* empty string */
UNSUPPORTED("48at50ffoqbw40aae7qlp0vus"); // while (*s) s++; s--;
UNSUPPORTED("tbim4ak38lvnw1gb72gj4hnh"); // /* skip over trailing slashes, nulling out as we go */
UNSUPPORTED("clj6wpwuuq0wl5g7f67hqvvfc"); // while ((s > path) && ((*s == '/') || (*s == '\\')))
UNSUPPORTED("f59muao0hgreza561qmmnlzum"); // *s-- = '\0';
UNSUPPORTED("18c1lv0flxz0ts64xlwuviv33"); // if (s == path) ret = path;
UNSUPPORTED("1nyzbeonram6636b1w955bypn"); // else {
UNSUPPORTED("4x9t5rl1kdp5nac9tewdf9x2n"); // while ((s > path) && ((*s != '/') && (*s != '\\'))) s--;
UNSUPPORTED("953u2wmr3tzfpiq8m06fdvhn5"); // if ((*s == '/') || (*s == '\\')) ret = s+1;
UNSUPPORTED("5dwayhic40dcurqedqxv1q7mj"); // else ret = path;
UNSUPPORTED("dvgyxsnyeqqnyzq696k3vskib"); // }
UNSUPPORTED("f3b7mj138albdr4lodyomke0z"); // return ret;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 ez0qfar6yuf01ivvqrnev06fv
// static void use_library(GVC_t *gvc, const char *name)
public static Object use_library(Object... arg) {
UNSUPPORTED("cjicty7s03euuxnpum74nrt6f"); // static void use_library(GVC_t *gvc, const char *name)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("8h89r8rhn7udjmeo8y259899y"); // static int cnt = 0;
UNSUPPORTED("30nxp5k7c6mdth5ymcpz1oxob"); // if (name) {
UNSUPPORTED("dwg0l3nktjnwky7m5lipngiot"); // Lib = ALLOC(cnt + 2, Lib, const char *);
UNSUPPORTED("axgfffz8lebk44oe1y1djiu6p"); // Lib[cnt++] = name;
UNSUPPORTED("3c388gk5lojcaen61m94i3x0w"); // Lib[cnt] = NULL;
UNSUPPORTED("dvgyxsnyeqqnyzq696k3vskib"); // }
UNSUPPORTED("comriuhmiu8kq7sayutlxoqbq"); // gvc->common.lib = Lib;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 dlfidqx2agrk43ikmxgzw9kgp
// static void global_def(agxbuf* xb, char *dcl, int kind, attrsym_t * ((*dclfun) (Agraph_t *, int kind, char *, char *)) )
public static Object global_def(Object... arg) {
UNSUPPORTED("zydu58d3g8obsevu9l8zo05i"); // static void global_def(agxbuf* xb, char *dcl, int kind,
UNSUPPORTED("zj9p9fdfpp3hwme7atl3cug3"); // attrsym_t * ((*dclfun) (Agraph_t *, int kind, char *, char *)) )
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("aexhdud6z2wbwwi73yppp0ynl"); // char *p;
UNSUPPORTED("c6ykztqlvb01grrqat3q7f8hg"); // char *rhs = "true";
UNSUPPORTED("7c3pfnvbbbnijw9cg9xkyyatm"); // attrsym_t *sym;
UNSUPPORTED("1qmhad0yyiddc207b8z5rm70x"); // if ((p = strchr(dcl, '='))) {
UNSUPPORTED("5s96z976xk7iglr5vvuad1dsb"); // agxbput_n (xb, dcl, p-dcl);
UNSUPPORTED("dbw9pn8xmpdqi11uffv4r6gxq"); // rhs = p+1;
UNSUPPORTED("dvgyxsnyeqqnyzq696k3vskib"); // }
UNSUPPORTED("div10atae09n36x269sl208r1"); // else
UNSUPPORTED("dv0ywo1nopy8xc9d9kfbn0hgz"); // agxbput (xb, dcl);
UNSUPPORTED("dhedzhv3dnzrq7ytgiqff11ku"); // sym = dclfun(NULL, kind, (((((xb)->ptr >= (xb)->eptr) ? agxbmore(xb,1) : 0), (int)(*(xb)->ptr++ = ((unsigned char)'\0'))),(char*)((xb)->ptr = (xb)->buf)), rhs);
UNSUPPORTED("6o4s3a3c3rae5ltba8nvab5px"); // sym->fixed = 1;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 5qvhl3c476hpwnik5r2ee5pin
// static int gvg_init(GVC_t *gvc, graph_t *g, char *fn, int gidx)
public static Object gvg_init(Object... arg) {
UNSUPPORTED("69zdfufo90wdjvfvsw59lz5n3"); // static int gvg_init(GVC_t *gvc, graph_t *g, char *fn, int gidx)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("c55ofvf49idlhjsnnxfqjpi9s"); // GVG_t *gvg;
UNSUPPORTED("1nqr81udw639pz7enx2hfhtn5"); // gvg = zmalloc(sizeof(GVG_t));
UNSUPPORTED("wpylwsmjyiuxs9f8x3srqmfs"); // if (!gvc->gvgs)
UNSUPPORTED("9y22l2dxq6artoaqqeeczdq1x"); // gvc->gvgs = gvg;
UNSUPPORTED("div10atae09n36x269sl208r1"); // else
UNSUPPORTED("2nndq73tw0aaltr2i1ajvsspn"); // gvc->gvg->next = gvg;
UNSUPPORTED("e9w6optlcophkwjmfin7kyi1i"); // gvc->gvg = gvg;
UNSUPPORTED("eish9dbcdxs6v4dh4sgg6uzjj"); // gvg->gvc = gvc;
UNSUPPORTED("27sxrps4axrp5fbl0qnenmif3"); // gvg->g = g;
UNSUPPORTED("5q4sypoeu8fbwv3a2p6qsnq73"); // gvg->input_filename = fn;
UNSUPPORTED("1wh5jhwi3fb70nrl37aoz6lhj"); // gvg->graph_index = gidx;
UNSUPPORTED("c9ckhc8veujmwcw0ar3u3zld4"); // return 0;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//1 6k1gxkaeteh3v4108asx0nu9q
// static graph_t *P_graph
//3 2zkpt5r5hmvqy31vbxai8aoww
// graph_t *gvPluginsGraph(GVC_t *gvc)
public static Object gvPluginsGraph(Object... arg) {
UNSUPPORTED("aq8xsrhhkbt250zdmff189jej"); // graph_t *gvPluginsGraph(GVC_t *gvc)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("eoghsuji192if07hz2zmt1geg"); // gvg_init(gvc, P_graph, "<internal>", 0);
UNSUPPORTED("5qryvsjfdmb52s891tbejpwi3"); // return P_graph;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 a4vyp310q1ezn1wiiqbhjazfi
// int dotneato_args_initialize(GVC_t * gvc, int argc, char **argv)
public static Object dotneato_args_initialize(Object... arg) {
UNSUPPORTED("3an9kpb8l897hglulndwlyhmk"); // int dotneato_args_initialize(GVC_t * gvc, int argc, char **argv)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("exs7yxl18noutslfdhd65grcd"); // char c, *rest, *layout;
UNSUPPORTED("d28hrwkttitp7p3zkyur6josm"); // const char *val;
UNSUPPORTED("e4nq5nxc3t4f7sn9hms693ro5"); // int i, v, nfiles;
UNSUPPORTED("h0or3v13348vfl22jqz895yc"); // unsigned char buf[128];
UNSUPPORTED("9gou5otj6s39l2cbyc8i5i5lq"); // agxbuf xb;
UNSUPPORTED("djkz3f3ke85c3ihtck61wzehd"); // int Kflag = 0;
UNSUPPORTED("e36z5l2h47e3sm6az444bpmte"); // /* establish if we are running in a CGI environment */
UNSUPPORTED("39kpbo7t3xw42psbqxwyosbtg"); // HTTPServerEnVar = getenv("SERVER_NAME");
UNSUPPORTED("bjgrdu955j26h6boths39zysy"); // /* establish Gvfilepath, if any */
UNSUPPORTED("9u1u08bh9yk3m8qjesa9h35o3"); // Gvfilepath = getenv("GV_FILE_PATH");
UNSUPPORTED("byzhjcmd87bu2q2ifs8d2zqmx"); // gvc->common.cmdname = dotneato_basename(argv[0]);
UNSUPPORTED("6t7yoiijwsc45jhh2ycc1zvqn"); // if (gvc->common.verbose) {
UNSUPPORTED("5jlgk53d79be5z8yrpqk31i41"); // fprintf(stderr, "%s - %s version %s (%s)\n",
UNSUPPORTED("a3fdnva5eaynygwl01w4i14vu"); // gvc->common.cmdname, gvc->common.info[0],
UNSUPPORTED("4cr6o6cpwligpzuiy9go86dtk"); // gvc->common.info[1], gvc->common.info[2]);
UNSUPPORTED("dvgyxsnyeqqnyzq696k3vskib"); // }
UNSUPPORTED("ebjtmwuwx6vwhxaswhb2j4mfm"); // /* configure for available plugins */
UNSUPPORTED("7y1a5ferpdpuzp8lj2nreef7e"); // /* needs to know if "dot -c" is set (gvc->common.config) */
UNSUPPORTED("1915n665xv0fno6lfzaikw5ml"); // /* must happen before trying to select any plugins */
UNSUPPORTED("b2umkw2rzz1ig1cngfiht4fmx"); // if (gvc->common.config) {
UNSUPPORTED("d3di2hukfdei22j9nlhb4lr4i"); // gvconfig(gvc, gvc->common.config);
UNSUPPORTED("ew35v5jfro4z9mn5cwzl5e0ha"); // exit (0);
UNSUPPORTED("dvgyxsnyeqqnyzq696k3vskib"); // }
UNSUPPORTED("9gg8gbp3jei0upfnr0b5i6fur"); // /* feed the globals */
UNSUPPORTED("36hh3435f786qyybpu0o87zjv"); // Verbose = gvc->common.verbose;
UNSUPPORTED("es2j9l0phjktwgdz1y2435lnm"); // CmdName = gvc->common.cmdname;
UNSUPPORTED("dhvbz69j0rmligcrm9974041x"); // nfiles = 0;
UNSUPPORTED("d1jh4myxvrwmm9xcl79yh24g1"); // for (i = 1; i < argc; i++)
UNSUPPORTED("32x1kvhg66oubz0hakj6dvxg1"); // if (argv[i] && argv[i][0] != '-')
UNSUPPORTED("5pk2vvpyoy1qbkfwm0d3cqpip"); // nfiles++;
UNSUPPORTED("d4gb5xxnp2a9dqmzsisy3d2x5"); // gvc->input_filenames = (char **)zmalloc((nfiles + 1)*sizeof(char *));
UNSUPPORTED("dhvbz69j0rmligcrm9974041x"); // nfiles = 0;
UNSUPPORTED("ci65k77x1b3nq6luu69s87oup"); // agxbinit(&xb, 128, buf);
UNSUPPORTED("9fp588sbdt939tsh4lldsi78p"); // for (i = 1; i < argc; i++) {
UNSUPPORTED("71ydjmz8tdkhga4y130hpfzd7"); // if (argv[i] && argv[i][0] == '-') {
UNSUPPORTED("a2i31gh8f8d1uzwvazthtdjhl"); // rest = &(argv[i][2]);
UNSUPPORTED("akiijvdhiis6rte3uan48lkio"); // switch (c = argv[i][1]) {
UNSUPPORTED("cnw3cn0y6fyfmhrj9i6zrj7yt"); // case 'G':
UNSUPPORTED("cyapeoqsbt759mwufn37a0j3w"); // if (*rest)
UNSUPPORTED("37iemzdcou8tf7mb850gmys6k"); // global_def(&xb, rest, AGRAPH, agattr);
UNSUPPORTED("d28blrbmwwqp80cyksuz7dwx9"); // else {
UNSUPPORTED("d10434bczuxvbju6r580xu4i3"); // fprintf(stderr, "Missing argument for -G flag\n");
UNSUPPORTED("3j6l9hq73a342kljq6expow6m"); // return (dotneato_usage(1));
UNSUPPORTED("6eq5kf0bj692bokt0bixy1ixh"); // }
UNSUPPORTED("9ekmvj13iaml5ndszqyxa8eq"); // break;
UNSUPPORTED("3za1kdrr0abcgx59eek9sst25"); // case 'N':
UNSUPPORTED("cyapeoqsbt759mwufn37a0j3w"); // if (*rest)
UNSUPPORTED("22su7vu663f22bni5gx0jkxq9"); // global_def(&xb, rest, AGNODE,agattr);
UNSUPPORTED("d28blrbmwwqp80cyksuz7dwx9"); // else {
UNSUPPORTED("14g4xc09ropngbhfr31tffeii"); // fprintf(stderr, "Missing argument for -N flag\n");
UNSUPPORTED("3j6l9hq73a342kljq6expow6m"); // return (dotneato_usage(1));
UNSUPPORTED("6eq5kf0bj692bokt0bixy1ixh"); // }
UNSUPPORTED("9ekmvj13iaml5ndszqyxa8eq"); // break;
UNSUPPORTED("30903uov1ouylqet6qkn3k0rw"); // case 'E':
UNSUPPORTED("cyapeoqsbt759mwufn37a0j3w"); // if (*rest)
UNSUPPORTED("b73i9nd8mv1m5tjqoqs0xawyw"); // global_def(&xb, rest, AGEDGE,agattr);
UNSUPPORTED("d28blrbmwwqp80cyksuz7dwx9"); // else {
UNSUPPORTED("6utrckluwkoaluhpksl5aa52s"); // fprintf(stderr, "Missing argument for -E flag\n");
UNSUPPORTED("3j6l9hq73a342kljq6expow6m"); // return (dotneato_usage(1));
UNSUPPORTED("6eq5kf0bj692bokt0bixy1ixh"); // }
UNSUPPORTED("9ekmvj13iaml5ndszqyxa8eq"); // break;
UNSUPPORTED("1ve8bjgk9dfpf0eremg7h6xzz"); // case 'T':
UNSUPPORTED("8xdr8a6r0v0ddt027euqcwvue"); // val = getFlagOpt(argc, argv, &i);
UNSUPPORTED("3w8hn108291bjaa11z3v4j97d"); // if (!val) {
UNSUPPORTED("cd45xgksaxjl5u63gikj5qcyu"); // fprintf(stderr, "Missing argument for -T flag\n");
UNSUPPORTED("3j6l9hq73a342kljq6expow6m"); // return (dotneato_usage(1));
UNSUPPORTED("6eq5kf0bj692bokt0bixy1ixh"); // }
UNSUPPORTED("72i7z40rqqngolv7pgnr45kl3"); // v = gvjobs_output_langname(gvc, val);
UNSUPPORTED("9cs6zbfun0bg9dhunbu1dwnox"); // if (!v) {
UNSUPPORTED("7ohbl1a39cg7xkg3hactpw7w3"); // fprintf(stderr, "Format: \"%s\" not recognized. Use one of:%s\n",
UNSUPPORTED("f2p3vxh49izcvsl9jvtkf6q3o"); // val, gvplugin_list(gvc, API_device, val));
UNSUPPORTED("910dtu59610pevhvj5yhrqcm4"); // if (GvExitOnUsage) exit(1);
UNSUPPORTED("7uqiarbyt9mx4hwdla4nbhj8p"); // return(2);
UNSUPPORTED("6eq5kf0bj692bokt0bixy1ixh"); // }
UNSUPPORTED("9ekmvj13iaml5ndszqyxa8eq"); // break;
UNSUPPORTED("8e0kz1b9axy6hx29fg32k1asu"); // case 'K':
UNSUPPORTED("8xdr8a6r0v0ddt027euqcwvue"); // val = getFlagOpt(argc, argv, &i);
UNSUPPORTED("3w8hn108291bjaa11z3v4j97d"); // if (!val) {
UNSUPPORTED("4387cb0sfakxesew55rctdheb"); // fprintf(stderr, "Missing argument for -K flag\n");
UNSUPPORTED("2ns70sizijh2h7z83rt81fqfk"); // return (dotneato_usage(1));
UNSUPPORTED("7nxu74undh30brb8laojud3f9"); // }
UNSUPPORTED("13d5md8v926ivibrbmgaktksx"); // v = gvlayout_select(gvc, val);
UNSUPPORTED("4pu52xhc37cufgh16nc8pjoa2"); // if (v == 999) {
UNSUPPORTED("8uoslbuyiw8828cnsd28ys8oh"); // fprintf(stderr, "There is no layout engine support for \"%s\"\n", val);
UNSUPPORTED("em4qxiev3phf1bnbh6vx4zjp9"); // if ((*(val)==*("dot")&&!strcmp(val,"dot"))) {
UNSUPPORTED("e46yvd7c19nfgratz9j0sg9d0"); // fprintf(stderr, "Perhaps \"dot -c\" needs to be run (with installer's privileges) to register the plugins?\n");
UNSUPPORTED("3e08x1y395304nd0y3uwffvim"); // }
UNSUPPORTED("cphaexi33y32dnefwtu3jsom4"); // else {
UNSUPPORTED("d3cg95zim5q97685u5v0sxrhv"); // fprintf(stderr, "Use one of:%s\n",
UNSUPPORTED("7ced84fhzz8sv21ptj4yf5b3p"); // gvplugin_list(gvc, API_layout, val));
UNSUPPORTED("dkxvw03k2gg9anv4dbze06axd"); // }
UNSUPPORTED("910dtu59610pevhvj5yhrqcm4"); // if (GvExitOnUsage) exit(1);
UNSUPPORTED("7uqiarbyt9mx4hwdla4nbhj8p"); // return(2);
UNSUPPORTED("7nxu74undh30brb8laojud3f9"); // }
UNSUPPORTED("8c0wmxuda35p1as4i2fh9yoti"); // Kflag = 1;
UNSUPPORTED("9ekmvj13iaml5ndszqyxa8eq"); // break;
UNSUPPORTED("5gsxsxc1w5fdmgnphelmjuqql"); // case 'P':
UNSUPPORTED("91ohbqvqagns01k8geznhjm7k"); // P_graph = gvplugin_graph(gvc);
UNSUPPORTED("9ekmvj13iaml5ndszqyxa8eq"); // break;
UNSUPPORTED("cxe7ytf67rip7dewog9rnbqqq"); // case 'V':
UNSUPPORTED("61p8yjtqxyg8jhsx9xyqa39my"); // fprintf(stderr, "%s - %s version %s (%s)\n",
UNSUPPORTED("chg3zu0nmmc2hpkc8a0cx08er"); // gvc->common.cmdname, gvc->common.info[0],
UNSUPPORTED("b9v3iookta64ex67ies4j4zva"); // gvc->common.info[1], gvc->common.info[2]);
UNSUPPORTED("2hk3eyce9u1ys3e3ycfmrtq9n"); // if (GvExitOnUsage) exit(0);
UNSUPPORTED("b9uibzxx0tu796r6pqyspuc8u"); // return (1);
UNSUPPORTED("9ekmvj13iaml5ndszqyxa8eq"); // break;
UNSUPPORTED("8et213nsqt44k6e0d06mh32mg"); // case 'l':
UNSUPPORTED("8xdr8a6r0v0ddt027euqcwvue"); // val = getFlagOpt(argc, argv, &i);
UNSUPPORTED("3w8hn108291bjaa11z3v4j97d"); // if (!val) {
UNSUPPORTED("3l9adyncbqlq4cr0dn291j8ms"); // fprintf(stderr, "Missing argument for -l flag\n");
UNSUPPORTED("3j6l9hq73a342kljq6expow6m"); // return (dotneato_usage(1));
UNSUPPORTED("6eq5kf0bj692bokt0bixy1ixh"); // }
UNSUPPORTED("a3ei53c2mnxhfpt33rezp6ll1"); // use_library(gvc, val);
UNSUPPORTED("9ekmvj13iaml5ndszqyxa8eq"); // break;
UNSUPPORTED("6t4c4wqag0c9inoine0vc6rzh"); // case 'o':
UNSUPPORTED("8xdr8a6r0v0ddt027euqcwvue"); // val = getFlagOpt(argc, argv, &i);
UNSUPPORTED("cgclbrsy2pcq9nt94cnmi4l1n"); // if (! gvc->common.auto_outfile_names)
UNSUPPORTED("6l1o8s3lihedxdhlhkt8bacw5"); // gvjobs_output_filename(gvc, val);
UNSUPPORTED("9ekmvj13iaml5ndszqyxa8eq"); // break;
UNSUPPORTED("3gzpswryl53n5xaxcbut8piyh"); // case 'q':
UNSUPPORTED("55tn4eqemjloic8o06vd4n3nc"); // if (*rest) {
UNSUPPORTED("5j8v456fg3eazoh4x59s440ph"); // v = atoi(rest);
UNSUPPORTED("ee277mlx9bo22lecmdsnie12n"); // if (v <= 0) {
UNSUPPORTED("3iwc3dzplzj2jkbze5cd6zfh9"); // fprintf(stderr,
UNSUPPORTED("6w3cyan5p5sb01pzz7n8i45h6"); // "Invalid parameter \"%s\" for -q flag - ignored\n",
UNSUPPORTED("77gwizewn0zj87535pi2g735m"); // rest);
UNSUPPORTED("2ndpjzfiv49aqobcgbi5tftoi"); // } else if (v == 1)
UNSUPPORTED("b4xb9n0clcaf5h0njzxmd6t8u"); // agseterr(AGERR);
UNSUPPORTED("9acag2yacl63g8rg6r1alu62x"); // else
UNSUPPORTED("eb2xug8syn6gd6cd1ms784rt0"); // agseterr(AGMAX);
UNSUPPORTED("738mi6h8ef0itznt34ngxe25o"); // } else
UNSUPPORTED("cyu314astki71lyhi8jonkon1"); // agseterr(AGERR);
UNSUPPORTED("9ekmvj13iaml5ndszqyxa8eq"); // break;
UNSUPPORTED("9laca56e8dr2klwt5asm5s92v"); // case 's':
UNSUPPORTED("55tn4eqemjloic8o06vd4n3nc"); // if (*rest) {
UNSUPPORTED("7p5xijseyywlgq947on87fbfy"); // PSinputscale = atof(rest);
UNSUPPORTED("te6xrfczv0b2rmmfw7n419bj"); // if (PSinputscale < 0) {
UNSUPPORTED("3iwc3dzplzj2jkbze5cd6zfh9"); // fprintf(stderr,
UNSUPPORTED("298zr2x6bn7osz168zt1qsgbn"); // "Invalid parameter \"%s\" for -s flag\n",
UNSUPPORTED("77gwizewn0zj87535pi2g735m"); // rest);
UNSUPPORTED("788fqd2nm2s7cyhjye34lwaho"); // return (dotneato_usage(1));
UNSUPPORTED("dkxvw03k2gg9anv4dbze06axd"); // }
UNSUPPORTED("e99bugzc8p62vi8asjsx3jnat"); // else if (PSinputscale == 0)
UNSUPPORTED("ca5magegib4z3wn2wbj91xdz5"); // PSinputscale = 72;
UNSUPPORTED("738mi6h8ef0itznt34ngxe25o"); // } else
UNSUPPORTED("cdz7sxlinpy8lsv4kjrrzvmlb"); // PSinputscale = 72;
UNSUPPORTED("9ekmvj13iaml5ndszqyxa8eq"); // break;
UNSUPPORTED("551eo7ey20lfrotadzc8xx636"); // case 'x':
UNSUPPORTED("ciou2ugu3ekwr7d8dtcmo8bqd"); // Reduce = NOT(0);
UNSUPPORTED("9ekmvj13iaml5ndszqyxa8eq"); // break;
UNSUPPORTED("6hwwmvxwrrrsv7qs0y53et76n"); // case 'y':
UNSUPPORTED("71s7bg2w58aqtjmpwed4525kz"); // Y_invert = NOT(0);
UNSUPPORTED("9ekmvj13iaml5ndszqyxa8eq"); // break;
UNSUPPORTED("eqbveikc3czxh4drpev1uzhla"); // case '?':
UNSUPPORTED("5tdq5fsx232bmgvcnkjmwox6c"); // return (dotneato_usage(0));
UNSUPPORTED("9ekmvj13iaml5ndszqyxa8eq"); // break;
UNSUPPORTED("bt2g0yhsy3c7keqyftf3c98ut"); // default:
UNSUPPORTED("ex8ddsq0de4n302ieh93s4nrw"); // agerr(AGERR, "%s: option -%c unrecognized\n\n", gvc->common.cmdname,
UNSUPPORTED("4fgwtijdvmyysu4tcsnigf36q"); // c);
UNSUPPORTED("5mxnk6d8u3qj69z7yzqkphjgw"); // return (dotneato_usage(1));
UNSUPPORTED("6t98dcecgbvbvtpycwiq2ynnj"); // }
UNSUPPORTED("ezl09f02n0cfigsaeyqsejcm0"); // } else if (argv[i])
UNSUPPORTED("ez69zldbihwem8y9yr9rmi9gt"); // gvc->input_filenames[nfiles++] = argv[i];
UNSUPPORTED("dvgyxsnyeqqnyzq696k3vskib"); // }
UNSUPPORTED("9ocnzhe59r19odwgtedwnydm"); // agxbfree (&xb);
UNSUPPORTED("56kll2bx8jbmqba2kk0pxvefe"); // /* if no -K, use cmd name to set layout type */
UNSUPPORTED("dy5okspyylmag8l3ke6of2fps"); // if (!Kflag) {
UNSUPPORTED("18vaoqlkvxjkxccqkm1cxljuo"); // layout = gvc->common.cmdname;
UNSUPPORTED("bshj1mtaoepm94oi9afocf8ou"); // if ((*(layout)==*("dot_static")&&!strcmp(layout,"dot_static"))
UNSUPPORTED("64dtzt25t15e7uoo50r0rsefx"); // || (*(layout)==*("dot_builtins")&&!strcmp(layout,"dot_builtins"))
UNSUPPORTED("klg5jjw0m71w4m5shlxzhfjy"); // || (*(layout)==*("lt-dot")&&!strcmp(layout,"lt-dot"))
UNSUPPORTED("42tigt1aywc44r9j37x5jq0ib"); // || (*(layout)==*("lt-dot_builtins")&&!strcmp(layout,"lt-dot_builtins"))
UNSUPPORTED("56pxlfwd1wodkyuswmf36lmwr"); // || (*(layout)==*("")&&!strcmp(layout,"")) /* when run as a process from Gvedit on Windows */
UNSUPPORTED("awdmf39ch8hkgicc7jwv9s67r"); // )
UNSUPPORTED("80rf3qgk59flt06kvnzepp9kt"); // layout = "dot";
UNSUPPORTED("e3pxmvk611turzkqpddzqql3e"); // i = gvlayout_select(gvc, layout);
UNSUPPORTED("cbslslfvt4zqfxukzdqeu902c"); // if (i == 999) {
UNSUPPORTED("2h041d156jcuzdn0h3t1kxz6b"); // fprintf(stderr, "There is no layout engine support for \"%s\"\n", layout);
UNSUPPORTED("6xr0y24n28bl6fmb7hwi2d6yh"); // if ((*(layout)==*("dot")&&!strcmp(layout,"dot")))
UNSUPPORTED("a9b0u4vno2ovyayhgdz2qi2l0"); // fprintf(stderr, "Perhaps \"dot -c\" needs to be run (with installer's privileges) to register the plugins?\n");
UNSUPPORTED("f3qa0cv737ikcre1vpqlkukio"); // else
UNSUPPORTED("3oqrxaejbit2ag4yv1f8std7v"); // fprintf(stderr, "Use one of:%s\n", gvplugin_list(gvc, API_layout, ""));
UNSUPPORTED("cziimyez7l7opmyxtz7i258x"); // if (GvExitOnUsage) exit(1);
UNSUPPORTED("8u2416o82oso1w72bexmapn9v"); // return(2);
UNSUPPORTED("flupwh3kosf3fkhkxllllt1"); // }
UNSUPPORTED("dvgyxsnyeqqnyzq696k3vskib"); // }
UNSUPPORTED("e8n0c84rizzjhmsff49m2fynz"); // /* if no -Txxx, then set default format */
UNSUPPORTED("5atdq1nn8pklea2e61l8ekie"); // if (!gvc->jobs || !gvc->jobs->output_langname) {
UNSUPPORTED("ejs6fyeynpj73y8zhc2xjcvrc"); // v = gvjobs_output_langname(gvc, "dot");
UNSUPPORTED("6lpp7llfms4w364wz03qdlrnl"); // if (!v) {
UNSUPPORTED("5di5qeuntrt4eii2azt25l076"); // // assert(v); /* "dot" should always be available as an output format */
UNSUPPORTED("18zn34qcs4vsdhhh831gn9vc9"); // fprintf(stderr,
UNSUPPORTED("5rhyltg4walgso272exe4gdqz"); // "Unable to find even the default \"-Tdot\" renderer. Has the config\nfile been generated by running \"dot -c\" with installer's priviledges?\n");
UNSUPPORTED("3r5dyo5vxrzten0rhlmlmhe8v"); // return(2);
UNSUPPORTED("flupwh3kosf3fkhkxllllt1"); // }
UNSUPPORTED("dvgyxsnyeqqnyzq696k3vskib"); // }
UNSUPPORTED("1i3ejmrslphirq6u7onu2i3cr"); // /* set persistent attributes here (if not already set from command line options) */
UNSUPPORTED("et68lvyh6row6cmvnxmw4nuvj"); // if (!agattr(NULL, AGNODE, "label", 0))
UNSUPPORTED("74v5uwoisv6m2lnnjv33219om"); // agattr(NULL, AGNODE, "label", "\\N");
UNSUPPORTED("5oxhd3fvp0gfmrmz12vndnjt"); // return 0;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 72no6ayfvjinlnupyn5jlmayg
// static boolean getdoubles2ptf(graph_t * g, char *name, pointf * result)
public static boolean getdoubles2ptf(Agraph_s g, CString name, pointf result) {
ENTERING("72no6ayfvjinlnupyn5jlmayg","getdoubles2ptf");
try {
CString p;
int i;
double xf, yf;
char c = '\0';
boolean rv = false;
if ((p = agget(g, name))!=null) {
UNSUPPORTED("21b2kes0vrizyai71yj9e2os3"); // i = sscanf(p, "%lf,%lf%c", &xf, &yf, &c);
UNSUPPORTED("9wua6uiybfvqd70huuo0yatcf"); // if ((i > 1) && (xf > 0) && (yf > 0)) {
UNSUPPORTED("8z2huopqt4m1rvfcd7vqatka4"); // result->x = ((((xf)*72>=0)?(int)((xf)*72 + .5):(int)((xf)*72 - .5)));
UNSUPPORTED("cil4j0n3iq35gr2pfewi2qawz"); // result->y = ((((yf)*72>=0)?(int)((yf)*72 + .5):(int)((yf)*72 - .5)));
UNSUPPORTED("9qnr8qmbz7pf3mmpebux0p08m"); // if (c == '!')
UNSUPPORTED("dqyb6drzg8ig5ecb31fq5c1d4"); // rv = (!(0));
UNSUPPORTED("flupwh3kosf3fkhkxllllt1"); // }
UNSUPPORTED("8k75h069sv2k9b6tgz77dscwd"); // else {
UNSUPPORTED("8wtaqjit9awt7xd08vuifknry"); // c = '\0';
UNSUPPORTED("705372l4htjtcvnq97l7i54g8"); // i = sscanf(p, "%lf%c", &xf, &c);
UNSUPPORTED("4n9k1twwfmxyet8tokr7xnktj"); // if ((i > 0) && (xf > 0)) {
UNSUPPORTED("8ui53rmpq7ao1p4yin0xqzszj"); // result->y = result->x = ((((xf)*72>=0)?(int)((xf)*72 + .5):(int)((xf)*72 - .5)));
UNSUPPORTED("1rflva1x66uhyqxr5zbpcsgnh"); // if (c == '!') rv = (!(0));
UNSUPPORTED("6t98dcecgbvbvtpycwiq2ynnj"); // }
UNSUPPORTED("flupwh3kosf3fkhkxllllt1"); // }
}
return rv;
} finally {
LEAVING("72no6ayfvjinlnupyn5jlmayg","getdoubles2ptf");
}
}
//3 1xg46gdvtsko1yrtm6mg4tsxy
// void getdouble(graph_t * g, char *name, double *result)
public static Object getdouble(Object... arg) {
UNSUPPORTED("5gfb0pnjet6us7l51d48x25aq"); // void getdouble(graph_t * g, char *name, double *result)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("aexhdud6z2wbwwi73yppp0ynl"); // char *p;
UNSUPPORTED("jnku6gn089m43hq5hndzrxzn"); // double f;
UNSUPPORTED("bifb8kht3vkytb74qbof9vpob"); // if ((p = agget(g, name))) {
UNSUPPORTED("4r30fz6hpqhfj44lip5cndh1m"); // if (sscanf(p, "%lf", &f) >= 1)
UNSUPPORTED("jepdvpsjq4757gzwaplghh4j"); // *result = f;
UNSUPPORTED("dvgyxsnyeqqnyzq696k3vskib"); // }
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 7c1tanyo6vwej9cqo0rkiv6sv
// graph_t *gvNextInputGraph(GVC_t *gvc)
public static Object gvNextInputGraph(Object... arg) {
UNSUPPORTED("a6jdteesa5ifdtthxxsohrlh2"); // graph_t *gvNextInputGraph(GVC_t *gvc)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("ccvkc7reh332l10k91bjvksnm"); // graph_t *g = NULL;
UNSUPPORTED("5dpauyujvamkm0ay3pfh999y3"); // static char *fn;
UNSUPPORTED("46orciiuryyogkvndndbawo06"); // static FILE *fp;
UNSUPPORTED("82yfc13etao3sz5hqypnt56oq"); // static FILE *oldfp;
UNSUPPORTED("1c51f3lle32l3xcfnkzig5ett"); // static int fidx, gidx;
UNSUPPORTED("6i509d0s1nqxjr873r5dz7gv5"); // while (!g) {
UNSUPPORTED("56tws2uz7mqhxwswpbpf94b5c"); // if (!fp) {
UNSUPPORTED("6d4ms2m7wzcyf2eofwsoz7jzu"); // if (!(fn = gvc->input_filenames[0])) {
UNSUPPORTED("eec7y1e55sjjkrx06jmtoyrz1"); // if (fidx++ == 0)
UNSUPPORTED("sln8j5e1981v4p6fvxyy4jjq"); // fp = stdin;
UNSUPPORTED("6t98dcecgbvbvtpycwiq2ynnj"); // }
UNSUPPORTED("6q044im7742qhglc4553noina"); // else {
UNSUPPORTED("btttznywgnyh5niqc16ebuucw"); // while ((fn = gvc->input_filenames[fidx++]) && !(fp = fopen(fn, "r"))) {
UNSUPPORTED("4futxtc5kgl4i6bw6j1xhws4s"); // agerr(AGERR, "%s: can't open %s\n", gvc->common.cmdname, fn);
UNSUPPORTED("o7u2b38bnefhf1l58zkel4i3"); // graphviz_errors++;
UNSUPPORTED("6eq5kf0bj692bokt0bixy1ixh"); // }
UNSUPPORTED("6t98dcecgbvbvtpycwiq2ynnj"); // }
UNSUPPORTED("flupwh3kosf3fkhkxllllt1"); // }
UNSUPPORTED("74qpksqxqa1hxoxfw5ugamyww"); // if (fp == NULL)
UNSUPPORTED("ai3czg6gaaxspsmndknpyvuiu"); // break;
UNSUPPORTED("2euu5u83dzpauthvjfy4vlcxg"); // if (oldfp != fp) {
UNSUPPORTED("cdwz1axrp68a13bwv1la3a736"); // agsetfile(fn ? fn : "<stdin>");
UNSUPPORTED("36hhlg0nbd0exjvtbe0fc5gj6"); // oldfp = fp;
UNSUPPORTED("flupwh3kosf3fkhkxllllt1"); // }
UNSUPPORTED("b1s6sspge1n2c2b0yukawa8jw"); // g = agread(fp,((Agdisc_t*)0));
UNSUPPORTED("wx1q1tyb5r9oziojtpc4vd1n"); // if (g) {
UNSUPPORTED("8r806yndx1ticudcknc3r1sp2"); // gvg_init(gvc, g, fn, gidx++);
UNSUPPORTED("ai3czg6gaaxspsmndknpyvuiu"); // break;
UNSUPPORTED("flupwh3kosf3fkhkxllllt1"); // }
UNSUPPORTED("7oaqgqiffegej6sz73ow4cwtw"); // if (fp != stdin)
UNSUPPORTED("caiflnlhuyqft76qr8gx91bf3"); // fclose (fp);
UNSUPPORTED("7y7knbs9950t3udidyrln8lmp"); // fp = NULL;
UNSUPPORTED("ecnsdkjxzhqh68kkz6fpbez04"); // gidx = 0;
UNSUPPORTED("dvgyxsnyeqqnyzq696k3vskib"); // }
UNSUPPORTED("2syri7q5tc0jyvwq8ecyfo3vr"); // return g;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 9t08dr2ks9qz1pyfz99awla6x
// static int findCharset (graph_t * g)
public static int findCharset(Agraph_s g) {
ENTERING("9t08dr2ks9qz1pyfz99awla6x","findCharset");
try {
return 0;
} finally {
LEAVING("9t08dr2ks9qz1pyfz99awla6x","findCharset");
}
}
//3 3bnmjpvynh1j9oh2p2vi0vh2m
// static void setRatio(graph_t * g)
public static void setRatio(Agraph_s g) {
ENTERING("3bnmjpvynh1j9oh2p2vi0vh2m","setRatio");
try {
CString p;
char c;
double ratio;
if ((p = agget(g, new CString("ratio")))!=null && ((c = p.charAt(0))!='\0')) {
UNSUPPORTED("7rk995hpmaqbbasmi40mqg0yw"); // switch (c) {
UNSUPPORTED("2v5u3irq50r1n2ccuna0y09lk"); // case 'a':
UNSUPPORTED("3jv8xrrloj92axkpkgolzwgo6"); // if ((*(p)==*("auto")&&!strcmp(p,"auto")))
UNSUPPORTED("8bdbsrt9sk4hnj3wm6z100qm"); // (((Agraphinfo_t*)(((Agobj_t*)(g))->data))->drawing)->ratio_kind = R_AUTO;
UNSUPPORTED("ai3czg6gaaxspsmndknpyvuiu"); // break;
UNSUPPORTED("f3lyz2cejs6yn5fyckhn7ba1"); // case 'c':
UNSUPPORTED("1v3jyjziibgnha1glbymorwg1"); // if ((*(p)==*("compress")&&!strcmp(p,"compress")))
UNSUPPORTED("coprfqf41n6byzz3nfneke6a"); // (((Agraphinfo_t*)(((Agobj_t*)(g))->data))->drawing)->ratio_kind = R_COMPRESS;
UNSUPPORTED("ai3czg6gaaxspsmndknpyvuiu"); // break;
UNSUPPORTED("2fzjr952o6hmcz3ad5arl2n8d"); // case 'e':
UNSUPPORTED("5s06nikh994hgncpwni2p4rwq"); // if ((*(p)==*("expand")&&!strcmp(p,"expand")))
UNSUPPORTED("eanijnkdjj1f6q7su4gmmijpj"); // (((Agraphinfo_t*)(((Agobj_t*)(g))->data))->drawing)->ratio_kind = R_EXPAND;
UNSUPPORTED("ai3czg6gaaxspsmndknpyvuiu"); // break;
UNSUPPORTED("8jntw084f69528np3kisw5ioc"); // case 'f':
UNSUPPORTED("105p0jwfnsptmrweig5mhpkn9"); // if ((*(p)==*("fill")&&!strcmp(p,"fill")))
UNSUPPORTED("eknfh3axjhorf2rfb914hdgbd"); // (((Agraphinfo_t*)(((Agobj_t*)(g))->data))->drawing)->ratio_kind = R_FILL;
UNSUPPORTED("ai3czg6gaaxspsmndknpyvuiu"); // break;
UNSUPPORTED("1drv0xz8hp34qnf72b4jpprg2"); // default:
UNSUPPORTED("e4fr8djxwn615yr0rj46vtdbd"); // ratio = atof(p);
UNSUPPORTED("43a0ik2dkpg3y58orisgkn32q"); // if (ratio > 0.0) {
UNSUPPORTED("azv56xi8njootl2n9l5bm1udc"); // (((Agraphinfo_t*)(((Agobj_t*)(g))->data))->drawing)->ratio_kind = R_VALUE;
UNSUPPORTED("ch5o67mezsw0v6iwxylb98myn"); // (((Agraphinfo_t*)(((Agobj_t*)(g))->data))->drawing)->ratio = ratio;
UNSUPPORTED("6t98dcecgbvbvtpycwiq2ynnj"); // }
UNSUPPORTED("ai3czg6gaaxspsmndknpyvuiu"); // break;
UNSUPPORTED("flupwh3kosf3fkhkxllllt1"); // }
UNSUPPORTED("dvgyxsnyeqqnyzq696k3vskib"); // }
}
} finally {
LEAVING("3bnmjpvynh1j9oh2p2vi0vh2m","setRatio");
}
}
//3 8gzdr3oil2d0e2o7m84wsszfg
// void graph_init(graph_t * g, boolean use_rankdir)
static CString rankname[] = new CString[] { new CString("local"), new CString("global"), new CString("none"), null };
static int rankcode[] = { 100, 101, 102, 100 };
static CString fontnamenames[] = new CString[] {new CString("gd"),new CString("ps"),new CString("svg"), null};
static int fontnamecodes[] = {enumAsInt(fontname_kind.class, "NATIVEFONTS"),enumAsInt(fontname_kind.class, "PSFONTS"),
enumAsInt(fontname_kind.class, "SVGFONTS"),-1};
public static void graph_init(Agraph_s g, boolean use_rankdir) {
ENTERING("8gzdr3oil2d0e2o7m84wsszfg","graph_init");
try {
CString p;
double xf;
int rankdir;
GD_drawing(g, zmalloc(sizeof(layout_t.class)));
/* set this up fairly early in case any string sizes are needed */
if ((p = agget(g, new CString("fontpath")))!=null || (p = getenv(new CString("DOTFONTPATH")))!=null) {
UNSUPPORTED("81bz3jcukzyotxiqgrlhn9cbq"); // /* overide GDFONTPATH in local environment if dot
UNSUPPORTED("6jgl7atk1m9yeam4auh127azw"); // * wants its own */
UNSUPPORTED("dyk0vc64gdzy1uwvsc2jqnjdw"); // static char *buf = 0;
UNSUPPORTED("8dywgree8jdjmj2ll2whbekhe"); // buf = grealloc(buf, strlen("GDFONTPATH=") + strlen(p) + 1);
UNSUPPORTED("d9ej6bo2s49vpstu3pql6tkrx"); // strcpy(buf, "GDFONTPATH=");
UNSUPPORTED("1s2jcd2h3eok7j6pclv20gyi2"); // strcat(buf, p);
UNSUPPORTED("abkxekvux4nramryfw2e8vcru"); // putenv(buf);
}
GD_charset(g, findCharset (g));
/*if (!HTTPServerEnVar) {
Gvimagepath = agget (g, "imagepath");
if (!Gvimagepath)
Gvimagepath = Gvfilepath;
}*/
GD_drawing(g).setDouble("quantum",
late_double(g, (agattr(g,AGRAPH,new CString("quantum"),null)), 0.0, 0.0));
/* setting rankdir=LR is only defined in dot,
* but having it set causes shape code and others to use it.
* The result is confused output, so we turn it off unless requested.
* This effective rankdir is stored in the bottom 2 bits of g->u.rankdir.
* Sometimes, the code really needs the graph's rankdir, e.g., neato -n
* with record shapes, so we store the real rankdir in the next 2 bits.
*/
rankdir = 0;
if ((p = agget(g, new CString("rankdir")))!=null) {
UNSUPPORTED("sp7zcza7w0dn7t66aj8rf4wn"); // if ((*(p)==*("LR")&&!strcmp(p,"LR")))
UNSUPPORTED("bjd2vk1jssqehllmgnqv601qd"); // rankdir = 1;
UNSUPPORTED("ry8itlrmblmuegdwk1iu1t0x"); // else if ((*(p)==*("BT")&&!strcmp(p,"BT")))
UNSUPPORTED("5hno0xn18yt443qg815w3c2s2"); // rankdir = 2;
UNSUPPORTED("aal39mi047mhafrsrxoutcffk"); // else if ((*(p)==*("RL")&&!strcmp(p,"RL")))
UNSUPPORTED("7vlda224wrgcdhr0ts3mndh5q"); // rankdir = 3;
}
if (use_rankdir)
GD_rankdir2(g, (rankdir << 2) | rankdir);
else
GD_rankdir2(g, (rankdir << 2));
xf = late_double(g, (agattr(g,AGRAPH,new CString("nodesep"),null)),
0.25, 0.02);
GD_nodesep(g, (ROUND((xf)*72)));
p = late_string(g, (agattr(g,AGRAPH,new CString("ranksep"),null)), null);
if (p!=null) {
UNSUPPORTED("c3p25g4289dxlei062z4eflss"); // if (sscanf(p, "%lf", &xf) == 0)
UNSUPPORTED("570vljex12zx5dkwi7mqa9knw"); // xf = 0.5;
UNSUPPORTED("8k75h069sv2k9b6tgz77dscwd"); // else {
UNSUPPORTED("p882lodfwy5v48rwbxvg5s9i"); // if (xf < 0.02)
UNSUPPORTED("dhhbmqv6n01j1eeyy7fpus1xw"); // xf = 0.02;
if (strstr(p, new CString("equally"))!=null)
GD_exact_ranksep(g, 1);
} else
xf = 0.5;
GD_ranksep(g, (ROUND((xf)*72)));
GD_showboxes(g, late_int(g, (agattr(g,AGRAPH,new CString("showboxes"),null)), 0, 0));
p = late_string(g, (agattr(g,AGRAPH,new CString("fontnames"),null)), null);
GD_fontnames(g, maptoken(p, fontnamenames, fontnamecodes));
setRatio(g);
GD_drawing(g).setBoolean("filled",
getdoubles2ptf(g, new CString("size"), (pointf) GD_drawing(g).getStruct("size").amp()));
getdoubles2ptf(g, new CString("page"), GD_drawing(g).getStruct("page").amp());
GD_drawing(g).setBoolean("centered", mapbool(agget(g, new CString("center"))));
if ((p = agget(g, new CString("rotate")))!=null)
GD_drawing(g).setBoolean("landscape", (atoi(p) == 90));
else if ((p = agget(g, new CString("orientation")))!=null)
GD_drawing(g).setBoolean("landscape", ((p.charAt(0) == 'l') || (p.charAt(0) == 'L')));
else if ((p = agget(g, new CString("landscape")))!=null)
GD_drawing(g).setBoolean("landscape", mapbool(p));
p = agget(g, new CString("clusterrank"));
Z.z().CL_type = maptoken(p, rankname, rankcode);
p = agget(g, new CString("concentrate"));
Z.z().Concentrate = mapbool(p);
Z.z().State = 0;
Z.z().EdgeLabelsDone = 0;
GD_drawing(g).setDouble("dpi", 0.0);
if (((p = agget(g, new CString("dpi")))!=null && p.charAt(0)!='\0')
|| ((p = agget(g, new CString("resolution")))!=null && p.charAt(0)!='\0'))
GD_drawing(g).setDouble("dpi", atof(p));
do_graph_label(g);
Z.z().Initial_dist = (1.0e+37);
Z.z().G_ordering = (agattr(g,AGRAPH,new CString("ordering"),null));
Z.z().G_gradientangle = (agattr(g,AGRAPH,new CString("gradientangle"),null));
Z.z().G_margin = (agattr(g,AGRAPH,new CString("margin"),null));
/* initialize nodes */
Z.z().N_height = (agattr(g,AGNODE,new CString("height"),null));
Z.z().N_width = (agattr(g,AGNODE,new CString("width"),null));
Z.z().N_shape = (agattr(g,AGNODE,new CString("shape"),null));
Z.z().N_color = (agattr(g,AGNODE,new CString("color"),null));
Z.z().N_fillcolor = (agattr(g,AGNODE,new CString("fillcolor"),null));
Z.z().N_style = (agattr(g,AGNODE,new CString("style"),null));
Z.z().N_fontsize = (agattr(g,AGNODE,new CString("fontsize"),null));
Z.z().N_fontname = (agattr(g,AGNODE,new CString("fontname"),null));
Z.z().N_fontcolor = (agattr(g,AGNODE,new CString("fontcolor"),null));
Z.z().N_label = (agattr(g,AGNODE,new CString("label"),null));
if (N(Z.z().N_label))
Z.z().N_label = agattr(g, AGNODE, new CString("label"), new CString("\\N"));
Z.z().N_xlabel = (agattr(g,AGNODE,new CString("xlabel"),null));
Z.z().N_showboxes = (agattr(g,AGNODE,new CString("showboxes"),null));
Z.z().N_penwidth = (agattr(g,AGNODE,new CString("penwidth"),null));
Z.z().N_ordering = (agattr(g,AGNODE,new CString("ordering"),null));
Z.z().N_margin = (agattr(g,AGNODE,new CString("margin"),null));
/* attribs for polygon shapes */
Z.z().N_sides = (agattr(g,AGNODE,new CString("sides"),null));
Z.z().N_peripheries = (agattr(g,AGNODE,new CString("peripheries"),null));
Z.z().N_skew = (agattr(g,AGNODE,new CString("skew"),null));
Z.z().N_orientation = (agattr(g,AGNODE,new CString("orientation"),null));
Z.z().N_distortion = (agattr(g,AGNODE,new CString("distortion"),null));
Z.z().N_fixed = (agattr(g,AGNODE,new CString("fixedsize"),null));
Z.z().N_imagescale = (agattr(g,AGNODE,new CString("imagescale"),null));
Z.z().N_nojustify = (agattr(g,AGNODE,new CString("nojustify"),null));
Z.z().N_layer = (agattr(g,AGNODE,new CString("layer"),null));
Z.z().N_group = (agattr(g,AGNODE,new CString("group"),null));
Z.z().N_comment = (agattr(g,AGNODE,new CString("comment"),null));
Z.z().N_vertices = (agattr(g,AGNODE,new CString("vertices"),null));
Z.z().N_z = (agattr(g,AGNODE,new CString("z"),null));
Z.z().N_gradientangle = (agattr(g,AGNODE,new CString("gradientangle"),null));
/* initialize edges */
Z.z().E_weight = (agattr(g,AGEDGE,new CString("weight"),null));
Z.z().E_color = (agattr(g,AGEDGE,new CString("color"),null));
Z.z().E_fillcolor = (agattr(g,AGEDGE,new CString("fillcolor"),null));
Z.z().E_fontsize = (agattr(g,AGEDGE,new CString("fontsize"),null));
Z.z().E_fontname = (agattr(g,AGEDGE,new CString("fontname"),null));
Z.z().E_fontcolor = (agattr(g,AGEDGE,new CString("fontcolor"),null));
Z.z().E_label = (agattr(g,AGEDGE,new CString("label"),null));
Z.z().E_xlabel = (agattr(g,AGEDGE,new CString("xlabel"),null));
Z.z().E_label_float = (agattr(g,AGEDGE,new CString("labelfloat"),null));
/* vladimir */
Z.z().E_dir = (agattr(g,AGEDGE,new CString("dir"),null));
Z.z().E_arrowhead = (agattr(g,AGEDGE,new CString("arrowhead"),null));
Z.z().E_arrowtail = (agattr(g,AGEDGE,new CString("arrowtail"),null));
Z.z().E_headlabel = (agattr(g,AGEDGE,new CString("headlabel"),null));
Z.z().E_taillabel = (agattr(g,AGEDGE,new CString("taillabel"),null));
Z.z().E_labelfontsize = (agattr(g,AGEDGE,new CString("labelfontsize"),null));
Z.z().E_labelfontname = (agattr(g,AGEDGE,new CString("labelfontname"),null));
Z.z().E_labelfontcolor = (agattr(g,AGEDGE,new CString("labelfontcolor"),null));
Z.z().E_labeldistance = (agattr(g,AGEDGE,new CString("labeldistance"),null));
Z.z().E_labelangle = (agattr(g,AGEDGE,new CString("labelangle"),null));
/* end vladimir */
Z.z().E_minlen = (agattr(g,AGEDGE,new CString("minlen"),null));
Z.z().E_showboxes = (agattr(g,AGEDGE,new CString("showboxes"),null));
Z.z().E_style = (agattr(g,AGEDGE,new CString("style"),null));
Z.z().E_decorate = (agattr(g,AGEDGE,new CString("decorate"),null));
Z.z().E_arrowsz = (agattr(g,AGEDGE,new CString("arrowsize"),null));
Z.z().E_constr = (agattr(g,AGEDGE,new CString("constraint"),null));
Z.z().E_layer = (agattr(g,AGEDGE,new CString("layer"),null));
Z.z().E_comment = (agattr(g,AGEDGE,new CString("comment"),null));
Z.z().E_tailclip = (agattr(g,AGEDGE,new CString("tailclip"),null));
Z.z().E_headclip = (agattr(g,AGEDGE,new CString("headclip"),null));
Z.z().E_penwidth = (agattr(g,AGEDGE,new CString("penwidth"),null));
/* background */
GD_drawing(g).setPtr("xdots", init_xdot (g));
/* initialize id, if any */
if ((p = agget(g, new CString("id")))!=null && p.charAt(0)!='\0')
GD_drawing(g).setPtr("id", strdup_and_subst_obj(p, g));
} finally {
LEAVING("8gzdr3oil2d0e2o7m84wsszfg","graph_init");
}
}
//3 46ypwxxdurpwoq7ee0nagnyuw
// void graph_cleanup(graph_t *g)
public static Object graph_cleanup(Object... arg) {
UNSUPPORTED("30nwbe5cpmxhh80h8xa9akr9z"); // void graph_cleanup(graph_t *g)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("dnom8brm7mdyz49mlyew1yfx4"); // if (GD_drawing(g) && GD_drawing(g)->xdots)
UNSUPPORTED("cbn0kehrijve4p68esddyi4cm"); // freeXDot ((xdot*)GD_drawing(g)->xdots);
UNSUPPORTED("4wfyhel6dchugc6m03gzcaqqx"); // if (GD_drawing(g) && GD_drawing(g)->id)
UNSUPPORTED("3uhbrv39ml1lee2b5i24tnmp2"); // free (GD_drawing(g)->id);
UNSUPPORTED("vcg73wzydblsuguqzall9cv4"); // free(GD_drawing(g));
UNSUPPORTED("1ia1a125sivdblphtrgblo6nr"); // GD_drawing(g) = NULL;
UNSUPPORTED("amdwcc4txs1rjdj436t6qt2k4"); // free_label(GD_label(g));
UNSUPPORTED("8jf0pz51pmyvkml9d1jqhncju"); // //FIX HERE , STILL SHALLOW
UNSUPPORTED("32tijapsyiumwfmjqrf8j6d41"); // //memset(&(g->u), 0, sizeof(Agraphinfo_t));
UNSUPPORTED("7e4eo7ldxaf48s2v3paft8j2c"); // agclean(g, AGRAPH,"Agraphinfo_t");
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 7rzv30lub416sffko0du3o6sx
// char* charsetToStr (int c)
public static Object charsetToStr(Object... arg) {
UNSUPPORTED("cqm25rponse4rsi686sbn1lo0"); // char*
UNSUPPORTED("b1ttom615vlztws5drinv8k4i"); // charsetToStr (int c)
UNSUPPORTED("erg9i1970wdri39osu8hx2a6e"); // {
UNSUPPORTED("cypok90bpbt6z74ak3nu63g1m"); // char* s;
UNSUPPORTED("239qe3atroys6jen2eufic7ex"); // switch (c) {
UNSUPPORTED("1nhgtydm95uz0oftevo3oly8e"); // case 0 :
UNSUPPORTED("2nidjssyf3n7w7cygka1k20t7"); // s = "UTF-8";
UNSUPPORTED("6aw91xzjmqvmtdvt1di23af8y"); // break;
UNSUPPORTED("6152devym3begeqtwle6okwtn"); // case 1 :
UNSUPPORTED("ct1k13idag6941hvbi9y2bzt3"); // s = "ISO-8859-1";
UNSUPPORTED("6aw91xzjmqvmtdvt1di23af8y"); // break;
UNSUPPORTED("brmutjgcyjq57ggmjk11na8lu"); // case 2 :
UNSUPPORTED("5irze7y061rfoysvsbc01net8"); // s = "BIG-5";
UNSUPPORTED("6aw91xzjmqvmtdvt1di23af8y"); // break;
UNSUPPORTED("cjimoqzt0qz3wos8m9h7g3hmh"); // default :
UNSUPPORTED("816pcwbgdg9rau7jfcj6xpoel"); // agerr(AGERR, "Unsupported charset value %d\n", c);
UNSUPPORTED("2nidjssyf3n7w7cygka1k20t7"); // s = "UTF-8";
UNSUPPORTED("6aw91xzjmqvmtdvt1di23af8y"); // break;
UNSUPPORTED("67k63k77j3kjabivb0i8hxrwd"); // }
UNSUPPORTED("dyq366cow9q7c8bh5jns3dlqo"); // return s;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
}
//3 5vks1zdadu5vjinaivs0j2bkb
// void do_graph_label(graph_t * sg)
public static void do_graph_label(Agraph_s sg) {
ENTERING("5vks1zdadu5vjinaivs0j2bkb","do_graph_label");
try {
CString str, pos, just;
int pos_ix;
/* it would be nice to allow multiple graph labels in the future */
if ((str = agget(sg, new CString("label")))!=null && (str.charAt(0) != '\0')) {
char pos_flag=0;
final __struct__<pointf> dimen = __struct__.from(pointf.class);
GD_has_labels(sg.getPtr("root"), GD_has_labels(sg.getPtr("root")) | (1 << 3));
GD_label(sg, make_label(sg, str, (aghtmlstr(str)!=0 ? (1 << 1) : (0 << 1)),
late_double(sg, (agattr(sg,AGRAPH,new CString("fontsize"),null)),
14.0, 1.0),
late_nnstring(sg, (agattr(sg,AGRAPH,new CString("fontname"),null)),
new CString("Times-Roman")),
late_nnstring(sg, (agattr(sg,AGRAPH,new CString("fontcolor"),null)),
new CString("black"))));
/* set label position */
pos = agget(sg, new CString("labelloc"));
if (NEQ(sg, agroot(sg))) {
if (pos!=null && (pos.charAt(0) == 'b'))
pos_flag = 0;
else
pos_flag = 1;
} else {
UNSUPPORTED("601b6yrqr391vnfpa74d7fec7"); // if (pos && (pos[0] == 't'))
UNSUPPORTED("bxai2kktsidvda3696ctyk63c"); // pos_flag = 1;
UNSUPPORTED("5c97f6vfxny0zz35l2bu4maox"); // else
UNSUPPORTED("6m5sy5ew8izdy8i10zb5o2dvu"); // pos_flag = 0;
}
just = agget(sg, new CString("labeljust"));
if (just!=null) {
UNSUPPORTED("3gxohpfqzahytaf7f9apn58az"); // if (just[0] == 'l')
UNSUPPORTED("ch7sydr4cg29o8ky9fbk5vnlg"); // pos_flag |= 2;
UNSUPPORTED("336to8kpmovx00pexhhenz74b"); // else if (just[0] == 'r')
UNSUPPORTED("evu9w6pw3kkh7z8w7t4rx4qxc"); // pos_flag |= 4;
}
GD_label_pos(sg, pos_flag);
if (EQ(sg, agroot(sg)))
return;
/* Set border information for cluster labels to allow space
*/
dimen.____(GD_label(sg).getStruct("dimen"));
dimen.setDouble("x", dimen.getDouble("x") + 4*4);
dimen.setDouble("y", dimen.getDouble("y") + 2*4);
if (N(GD_flip(agroot(sg)))) {
if ((GD_label_pos(sg) & 1)!=0)
pos_ix = 2;
else
pos_ix = 0;
GD_border(sg).plus(pos_ix).setStruct(dimen);
} else {
/* when rotated, the labels will be restored to TOP or BOTTOM */
UNSUPPORTED("cabz6xbjdvz5vmjulzrhlxh48"); // if ((((Agraphinfo_t*)(((Agobj_t*)(sg))->data))->label_pos) & 1)
UNSUPPORTED("dx7v6663o9o0x1j5r8z4wumxb"); // pos_ix = 1;
UNSUPPORTED("5c97f6vfxny0zz35l2bu4maox"); // else
UNSUPPORTED("97dtv6k7yw1qvfzgs65cj2v0l"); // pos_ix = 3;
UNSUPPORTED("21iuie8b11x65je8vampstgt6"); // (((Agraphinfo_t*)(((Agobj_t*)(sg))->data))->border)[pos_ix].x = dimen.y;
UNSUPPORTED("8cawl3kik853hkvgm39y34urs"); // (((Agraphinfo_t*)(((Agobj_t*)(sg))->data))->border)[pos_ix].y = dimen.x;
}
}
} finally {
LEAVING("5vks1zdadu5vjinaivs0j2bkb","do_graph_label");
}
}
}
| apache-2.0 |
vovagrechka/fucking-everything | phizdets/phizdets-idea/src/vgrechka/phizdetsidea/phizdets/debugger/PyCallSignatureTypeProvider.java | 2454 | /*
* Copyright 2000-2014 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 vgrechka.phizdetsidea.phizdets.debugger;
import com.intellij.openapi.util.Ref;
import vgrechka.phizdetsidea.phizdets.psi.PyCallable;
import vgrechka.phizdetsidea.phizdets.psi.PyFunction;
import vgrechka.phizdetsidea.phizdets.psi.PyNamedParameter;
import vgrechka.phizdetsidea.phizdets.psi.types.*;
import org.jetbrains.annotations.NotNull;
/**
* @author traff
*/
public class PyCallSignatureTypeProvider extends PyTypeProviderBase {
@Override
public Ref<PyType> getParameterType(@NotNull final PyNamedParameter param,
@NotNull final PyFunction func,
@NotNull TypeEvalContext context) {
final String name = param.getName();
if (name != null) {
final String typeName = PySignatureCacheManager.getInstance(param.getProject()).findParameterType(func, name);
if (typeName != null) {
final PyType type = PyTypeParser.getTypeByName(param, typeName);
if (type != null) {
return Ref.create(PyDynamicallyEvaluatedType.create(type));
}
}
}
return null;
}
@Override
public Ref<PyType> getReturnType(@NotNull final PyCallable callable, @NotNull TypeEvalContext context) {
if (callable instanceof PyFunction) {
PyFunction function = (PyFunction)callable;
PySignature signature = PySignatureCacheManager.getInstance(function.getProject()).findSignature(function);
if (signature != null && signature.getReturnType() != null) {
final String typeName = signature.getReturnType().getTypeQualifiedName();
if (typeName != null) {
final PyType type = PyTypeParser.getTypeByName(function, typeName);
if (type != null) {
return Ref.create(PyDynamicallyEvaluatedType.create(type));
}
}
}
}
return null;
}
}
| apache-2.0 |
fade4j/FragmentaryDemos | app/src/main/java/com/spacecowboy/fragmentarydemos/fragments/RecyclerHolder.java | 509 | package com.spacecowboy.fragmentarydemos.fragments;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.spacecowboy.fragmentarydemos.R;
/**
* @author: SpaceCowboy
* @date: 2018/3/6
* @description:
*/
public class RecyclerHolder extends RecyclerView.ViewHolder {
TextView mTvItem;
public RecyclerHolder(View itemView) {
super(itemView);
mTvItem = (TextView) itemView.findViewById(R.id.tv_item_recycler);
}
}
| apache-2.0 |
boxfish-project/bebase-samples | boot/src/main/java/cn/boxfish/samples/boot/Application.java | 652 | package cn.boxfish.samples.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
/**
* Created by undancer on 15/12/7.
*/
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder;
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
| apache-2.0 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/authentication/authenticationtacacspolicy_systemglobal_binding.java | 7321 | /*
* Copyright (c) 2008-2015 Citrix Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.citrix.netscaler.nitro.resource.config.authentication;
import com.citrix.netscaler.nitro.resource.base.*;
import com.citrix.netscaler.nitro.service.nitro_service;
import com.citrix.netscaler.nitro.service.options;
import com.citrix.netscaler.nitro.util.*;
import com.citrix.netscaler.nitro.exception.nitro_exception;
class authenticationtacacspolicy_systemglobal_binding_response extends base_response
{
public authenticationtacacspolicy_systemglobal_binding[] authenticationtacacspolicy_systemglobal_binding;
}
/**
* Binding class showing the systemglobal that can be bound to authenticationtacacspolicy.
*/
public class authenticationtacacspolicy_systemglobal_binding extends base_resource
{
private String boundto;
private Long priority;
private Long activepolicy;
private String name;
private Long __count;
/**
* <pre>
* Name of the TACACS+ policy.<br> Minimum length = 1
* </pre>
*/
public void set_name(String name) throws Exception{
this.name = name;
}
/**
* <pre>
* Name of the TACACS+ policy.<br> Minimum length = 1
* </pre>
*/
public String get_name() throws Exception {
return this.name;
}
/**
* <pre>
* The entity name to which policy is bound.
* </pre>
*/
public void set_boundto(String boundto) throws Exception{
this.boundto = boundto;
}
/**
* <pre>
* The entity name to which policy is bound.
* </pre>
*/
public String get_boundto() throws Exception {
return this.boundto;
}
/**
* <pre>
* .
* </pre>
*/
public Long get_priority() throws Exception {
return this.priority;
}
/**
* <pre>
* .
* </pre>
*/
public Long get_activepolicy() throws Exception {
return this.activepolicy;
}
/**
* <pre>
* converts nitro response into object and returns the object array in case of get request.
* </pre>
*/
protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception{
authenticationtacacspolicy_systemglobal_binding_response result = (authenticationtacacspolicy_systemglobal_binding_response) service.get_payload_formatter().string_to_resource(authenticationtacacspolicy_systemglobal_binding_response.class, response);
if(result.errorcode != 0) {
if (result.errorcode == 444) {
service.clear_session();
}
if(result.severity != null)
{
if (result.severity.equals("ERROR"))
throw new nitro_exception(result.message,result.errorcode);
}
else
{
throw new nitro_exception(result.message,result.errorcode);
}
}
return result.authenticationtacacspolicy_systemglobal_binding;
}
/**
* <pre>
* Returns the value of object identifier argument
* </pre>
*/
protected String get_object_name() {
return this.name;
}
/**
* Use this API to fetch authenticationtacacspolicy_systemglobal_binding resources of given name .
*/
public static authenticationtacacspolicy_systemglobal_binding[] get(nitro_service service, String name) throws Exception{
authenticationtacacspolicy_systemglobal_binding obj = new authenticationtacacspolicy_systemglobal_binding();
obj.set_name(name);
authenticationtacacspolicy_systemglobal_binding response[] = (authenticationtacacspolicy_systemglobal_binding[]) obj.get_resources(service);
return response;
}
/**
* Use this API to fetch filtered set of authenticationtacacspolicy_systemglobal_binding resources.
* filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
*/
public static authenticationtacacspolicy_systemglobal_binding[] get_filtered(nitro_service service, String name, String filter) throws Exception{
authenticationtacacspolicy_systemglobal_binding obj = new authenticationtacacspolicy_systemglobal_binding();
obj.set_name(name);
options option = new options();
option.set_filter(filter);
authenticationtacacspolicy_systemglobal_binding[] response = (authenticationtacacspolicy_systemglobal_binding[]) obj.getfiltered(service, option);
return response;
}
/**
* Use this API to fetch filtered set of authenticationtacacspolicy_systemglobal_binding resources.
* set the filter parameter values in filtervalue object.
*/
public static authenticationtacacspolicy_systemglobal_binding[] get_filtered(nitro_service service, String name, filtervalue[] filter) throws Exception{
authenticationtacacspolicy_systemglobal_binding obj = new authenticationtacacspolicy_systemglobal_binding();
obj.set_name(name);
options option = new options();
option.set_filter(filter);
authenticationtacacspolicy_systemglobal_binding[] response = (authenticationtacacspolicy_systemglobal_binding[]) obj.getfiltered(service, option);
return response;
}
/**
* Use this API to count authenticationtacacspolicy_systemglobal_binding resources configued on NetScaler.
*/
public static long count(nitro_service service, String name) throws Exception{
authenticationtacacspolicy_systemglobal_binding obj = new authenticationtacacspolicy_systemglobal_binding();
obj.set_name(name);
options option = new options();
option.set_count(true);
authenticationtacacspolicy_systemglobal_binding response[] = (authenticationtacacspolicy_systemglobal_binding[]) obj.get_resources(service,option);
if (response != null) {
return response[0].__count;
}
return 0;
}
/**
* Use this API to count the filtered set of authenticationtacacspolicy_systemglobal_binding resources.
* filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
*/
public static long count_filtered(nitro_service service, String name, String filter) throws Exception{
authenticationtacacspolicy_systemglobal_binding obj = new authenticationtacacspolicy_systemglobal_binding();
obj.set_name(name);
options option = new options();
option.set_count(true);
option.set_filter(filter);
authenticationtacacspolicy_systemglobal_binding[] response = (authenticationtacacspolicy_systemglobal_binding[]) obj.getfiltered(service, option);
if (response != null) {
return response[0].__count;
}
return 0;
}
/**
* Use this API to count the filtered set of authenticationtacacspolicy_systemglobal_binding resources.
* set the filter parameter values in filtervalue object.
*/
public static long count_filtered(nitro_service service, String name, filtervalue[] filter) throws Exception{
authenticationtacacspolicy_systemglobal_binding obj = new authenticationtacacspolicy_systemglobal_binding();
obj.set_name(name);
options option = new options();
option.set_count(true);
option.set_filter(filter);
authenticationtacacspolicy_systemglobal_binding[] response = (authenticationtacacspolicy_systemglobal_binding[]) obj.getfiltered(service, option);
if (response != null) {
return response[0].__count;
}
return 0;
}
} | apache-2.0 |
Just-/playn | android/src/playn/android/GameViewGL.java | 6803 | /**
* Copyright 2011 The PlayN Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package playn.android;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import playn.core.Keyboard;
import playn.core.Platform;
import playn.core.Pointer;
import playn.core.Touch;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.util.Log;
import android.view.SurfaceHolder;
public class GameViewGL extends GLSurfaceView implements SurfaceHolder.Callback {
private static volatile int contextId = 1;
public final AndroidGL20 gl20;
private final AndroidRendererGL renderer;
private final SurfaceHolder holder;
private GameLoop loop;
private final GameActivity activity;
private AndroidGraphics gfx;
private AndroidKeyboard keyboard;
private AndroidPointer pointer;
private AndroidTouch touch;
private boolean gameInitialized = false;
private boolean gameSizeSet = false; // Set by AndroidGraphics
private class AndroidRendererGL implements Renderer {
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
contextId++;
// EGLContext lost, so surfaces need to be rebuilt and redrawn.
if (gfx != null) {
gfx.ctx.onSurfaceCreated();
}
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
gl20.glViewport(0, 0, width, height);
if (AndroidPlatform.DEBUG_LOGS)
Log.d("playn", "Surface dimensions changed to ( " + width + " , " + height + ")");
}
@Override
public void onDrawFrame(GL10 gl) {
// Wait until onDrawFrame to make sure all the metrics
// are in place at this point.
if (!gameInitialized) {
AndroidPlatform.register(gl20, activity);
gfx = AndroidPlatform.instance.graphics();
keyboard = AndroidPlatform.instance.keyboard();
pointer = AndroidPlatform.instance.pointer();
touch = AndroidPlatform.instance.touch();
activity.main();
loop = new GameLoop();
loop.start();
gameInitialized = true;
}
// Handle updating, clearing the screen, and drawing
if (loop.running() && gameInitialized)
loop.run();
}
void onPause() {
if (gfx != null) {
gfx.ctx.onSurfaceLost();
}
}
}
public GameViewGL(AndroidGL20 _gl20, GameActivity activity, Context context) {
super(context);
this.gl20 = _gl20;
this.activity = activity;
holder = getHolder();
holder.addCallback(this);
setFocusable(true);
setEGLContextClientVersion(2);
if (activity.isHoneycombOrLater()) {
// FIXME: Need to use android3.0 as a Maven artifact for this to work
// setPreserveEGLContextOnPause(true);
}
this.setRenderer(renderer = new AndroidRendererGL());
setRenderMode(RENDERMODE_CONTINUOUSLY);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Default to filling all the available space when the game is first loads
Platform platform = activity.platform();
if (platform != null && gameSizeSet) {
int width = platform.graphics().width();
int height = platform.graphics().height();
if (width == 0 || height == 0) {
Log.e("playn", "Invalid game size set: (" + width + " , " + height + ")");
} else {
int minWidth = getSuggestedMinimumWidth();
int minHeight = getSuggestedMinimumHeight();
width = width > minWidth ? width : minWidth;
height = height > minHeight ? height : minHeight;
setMeasuredDimension(width, height);
if (AndroidPlatform.DEBUG_LOGS)
Log.d("playn", "Using game-specified sizing. (" + width + " , " + height + ")");
return;
}
}
if (AndroidPlatform.DEBUG_LOGS) Log.d("playn", "Using default sizing.");
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
void gameSizeSet() {
gameSizeSet = true;
}
static int contextId() {
return contextId;
}
/*
* Input and lifecycle functions called by the UI thread.
*/
public void notifyVisibilityChanged(int visibility) {
Log.i("playn", "notifyVisibilityChanged: " + visibility);
if (visibility == INVISIBLE) {
if (loop != null)
loop.pause();
onPause();
} else {
if (loop != null)
loop.start();
onResume();
}
}
@Override
public void onPause() {
queueEvent(new Runnable() {
// This method will be called on the rendering
// thread:
@Override
public void run() {
renderer.onPause();
}
});
super.onPause();
}
void onKeyDown(final Keyboard.Event event) {
queueEvent(new Runnable() {
@Override
public void run() {
keyboard.onKeyDown(event);
}
});
}
void onKeyTyped(final Keyboard.TypedEvent event) {
queueEvent(new Runnable() {
@Override
public void run() {
keyboard.onKeyTyped(event);
}
});
}
void onKeyUp(final Keyboard.Event event) {
queueEvent(new Runnable() {
@Override
public void run() {
keyboard.onKeyUp(event);
}
});
}
void onPointerStart(final Pointer.Event event) {
queueEvent(new Runnable() {
@Override
public void run() {
pointer.onPointerStart(event);
}
});
}
void onPointerDrag(final Pointer.Event event) {
queueEvent(new Runnable() {
@Override
public void run() {
pointer.onPointerDrag(event);
}
});
}
void onPointerEnd(final Pointer.Event event) {
queueEvent(new Runnable() {
@Override
public void run() {
pointer.onPointerEnd(event);
}
});
}
void onTouchStart(final Touch.Event[] touches) {
queueEvent(new Runnable() {
@Override
public void run() {
touch.onTouchStart(touches);
}
});
}
void onTouchMove(final Touch.Event[] touches) {
queueEvent(new Runnable() {
@Override
public void run() {
touch.onTouchMove(touches);
}
});
}
void onTouchEnd(final Touch.Event[] touches) {
queueEvent(new Runnable() {
@Override
public void run() {
touch.onTouchEnd(touches);
}
});
}
}
| apache-2.0 |
alpapad/ahome-titanium | ahome-titanium/src/com/ait/toolkit/titanium/mobile/modules/gmap/client/GMapView.java | 9679 | /*
Copyright (c) 2014 Ahomé Innovation Technologies. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.ait.toolkit.titanium.mobile.modules.gmap.client;
import java.util.Arrays;
import java.util.List;
import com.ait.toolkit.titanium.mobile.client.core.handlers.EventHandler;
import com.ait.toolkit.titanium.mobile.client.core.handlers.ui.CallbackRegistration;
import com.ait.toolkit.titanium.mobile.client.ui.View;
/**
* Map view is used for embedding native mapping capabilities as a view in your
* application.
* <p>
* With native maps, you can control the mapping location, the type of map, the
* zoom level and you can add custom annotations and routes directly to the map.
* Once the map view is displayed, the user can pan, zoom and tilt the map using
* the native control gestures.
* <p>
* All latitude and longitude values are specified in decimal degrees. Values in
* degrees, minutes and seconds (DMS) must be converted to decimal degrees
* before being passed to the map view.
* <p>
* You can add Annotation objects to the map to mark points of interest. An
* annotation has two states: selected and deselected. A deselected annotation
* is marked by a pin image. When selected, the full annotation is displayed,
* typically including a title and an optional subtitle.
* <p>
* You can add Route objects to the map to create paths between two or more
* points of interest.
*/
public class GMapView extends View {
public GMapView() {
jsObj = GMap.get().createView();
}
public native boolean isAnimate()/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
return jso.animate;
}-*/;
public native void setAnimate(boolean value)/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
jso.animate = value;
}-*/;
public native boolean enableZoomControls()/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
return jso.enableZoomControls;
}-*/;
public native void setEnableZoomControls(boolean value)/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
jso.enableZoomControls = value;
}-*/;
public native List<GMapAnnotation> getAnnotations()/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
var obj = jso.annotations;
return @com.ait.toolkit.titanium.mobile.modules.gmap.client.GMapAnnotation::fromArray(Lcom/google/gwt/core/client/JavaScriptObject;)(obj);
}-*/;
public native void setAnnotations(List<GMapAnnotation> values)/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
jso.annotations = @com.ait.toolkit.titanium.mobile.modules.gmap.client.GMapAnnotation::fromList(Ljava/util/List;)(values);
}-*/;
public void setAnnotations(GMapAnnotation... values) {
setAnnotations(Arrays.asList(values));
}
public native int getMapType()/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
return jso.mapType;
}-*/;
public native void setMapType(int value)/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
jso.mapType = value;
}-*/;
public native boolean isTrafic()/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
return jso.trafic;
}-*/;
public native void setTrafic(boolean value)/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
jso.trafic = value;
}-*/;
public native boolean isUserlocation()/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
return jso.userLocation;
}-*/;
public native void setUserlocation(boolean value)/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
jso.userLocation = value;
}-*/;
public native GMapRegionType getRegion()/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
var obj = jso.region;
return @com.ait.toolkit.titanium.mobile.modules.gmap.client.GMapRegionType::new(Lcom/google/gwt/core/client/JavaScriptObject;)(obj);
}-*/;
public native void setRegion(GMapRegionType value)/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
jso.region = value.@com.ait.toolkit.core.client.JsObject::getJsObj()();
}-*/;
public native void addAnnotation(GMapAnnotation value)/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
jso
.addAnnotation(value.@com.ait.toolkit.core.client.JsObject::getJsObj()());
}-*/;
public native void addAnnotations(List<GMapAnnotation> values)/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
jso
.addAnnotation(@com.ait.toolkit.titanium.mobile.modules.gmap.client.GMapAnnotation::fromList(Ljava/util/List;)(values));
}-*/;
public void addAnnotations(GMapAnnotation... annotations) {
this.addAnnotations(Arrays.asList(annotations));
}
public native void addRoute(GMapRoute value)/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
jso
.addRoute(value.@com.ait.toolkit.core.client.JsObject::getJsObj()());
}-*/;
public native void deselectAnnotation(GMapAnnotation value)/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
jso
.deselectAnnotation(value.@com.ait.toolkit.core.client.JsObject::getJsObj()());
}-*/;
public native void deselectAnnotation(String value)/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
jso.deselectAnnotation(value);
}-*/;
public native void removeAnnotation(GMapAnnotation value)/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
jso
.removeAnnotation(value.@com.ait.toolkit.core.client.JsObject::getJsObj()());
}-*/;
public native void removeAnnotations(List<GMapAnnotation> values)/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
jso
.removeAnnotations(@com.ait.toolkit.titanium.mobile.modules.gmap.client.GMapAnnotation::fromList(Ljava/util/List;)(values));
}-*/;
public void removeAnnotations(GMapAnnotation... annotations) {
this.removeAnnotations(Arrays.asList(annotations));
}
public native void removeRoute(GMapRoute value)/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
jso
.removeRoute(value.@com.ait.toolkit.core.client.JsObject::getJsObj()());
}-*/;
public native void selectAnnotation(GMapAnnotation value)/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
jso
.delectAnnotation(value.@com.ait.toolkit.core.client.JsObject::getJsObj()());
}-*/;
public native void selectAnnotation(String value)/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
jso.selectAnnotation(value);
}-*/;
/**
* Fired when the map completes loading.
*/
public void addCompleteHandler(EventHandler handler) {
this.addEventHandler("complete", handler);
}
/**
* Fired when the user interacts with a draggable annotation.
*/
public native CallbackRegistration addPinchChangedDragStateHandler(PinchChangedDragStateHandler handler)/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
var listener = function(e) {
var eventObject = @com.ait.toolkit.titanium.mobile.modules.gmap.client.PinchChangedDragStateEvent::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e);
handler.@com.ait.toolkit.titanium.mobile.modules.gmap.client.PinchChangedDragStateHandler::onPinchChangedDragState(Lcom/ait/toolkit/titanium/mobile/modules/gmap/client/PinchChangedDragStateEvent;)(eventObject);
};
var name = @com.ait.toolkit.titanium.mobile.modules.gmap.client.PinchChangedDragStateEvent::EVENT_NAME;
var v = jso.addEventListener(name, listener);
var toReturn = @com.ait.toolkit.titanium.mobile.client.core.handlers.ui.CallbackRegistration::new(Lcom/ait/toolkit/titanium/mobile/client/core/events/EventDispatcher;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(this,name,listener);
return toReturn;
}-*/;
/**
* Fired when the mapping region changes.
*/
public native CallbackRegistration addRegionChangedHandler(RegionChangedHandler handler)/*-{
var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
var listener = function(e) {
var eventObject = @com.ait.toolkit.titanium.mobile.modules.gmap.client.RegionChangedEvent::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e);
handler.@com.ait.toolkit.titanium.mobile.modules.gmap.client.RegionChangedHandler::onRegionChanged(Lcom/ait/toolkit/titanium/mobile/modules/gmap/client/RegionChangedEvent;)(eventObject);
};
var name = @com.ait.toolkit.titanium.mobile.modules.gmap.client.RegionChangedEvent::EVENT_NAME;
var v = jso.addEventListener(name, listener);
var toReturn = @com.ait.toolkit.titanium.mobile.client.core.handlers.ui.CallbackRegistration::new(Lcom/ait/toolkit/titanium/mobile/client/core/events/EventDispatcher;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(this,name,listener);
return toReturn;
}-*/;
}
| apache-2.0 |
Grokery/grokerylab | api/src/main/java/io/grokery/lab/api/common/CredentialProvider.java | 902 | package io.grokery.lab.api.common;
import com.amazonaws.AmazonClientException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
public class CredentialProvider implements AWSCredentialsProvider {
private String AccessKeyId;
private String SecretKey;
public CredentialProvider(String accessKeyId, String secretKey) {
this.AccessKeyId = accessKeyId;
this.SecretKey = secretKey;
}
public AWSCredentials getCredentials() {
if (this.AccessKeyId != null && this.SecretKey != null) {
return new BasicAWSCredentials(this.AccessKeyId, this.SecretKey);
}
throw new AmazonClientException("AWS credentials can not be null ");
}
public void refresh() {}
@Override
public String toString() {
return getClass().getSimpleName();
}
}
| apache-2.0 |
LTT-Gatech/CarCareAndroid | app/src/main/java/com/teamltt/carcare/activity/CarInfoEditActivity.java | 4293 | /*
* Copyright 2017, Team LTT
*
* 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.teamltt.carcare.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.teamltt.carcare.R;
import com.teamltt.carcare.database.DbHelper;
import com.teamltt.carcare.model.Vehicle;
public class CarInfoEditActivity extends AppCompatActivity {
private static final String TAG = "CarInfoEditActivity";
private boolean edited = false;
private DbHelper dbHelper;
long vehicleId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_car_info_edit);
vehicleId = getIntent().getLongExtra(CarInfoActivity.EXTRA_VEHICLE_ID, -1);
if (vehicleId == -1) {
Log.e(TAG, "invalid vehicle id");
finish();
}
dbHelper = new DbHelper(CarInfoEditActivity.this);
Vehicle vehicle = dbHelper.getVehicle(vehicleId);
if (vehicle == null) {
Log.e(TAG, "could not get vehicle properly");
} else {
updateUi(vehicle);
}
}
/**
* Marks the fields as data to be saved when the activity is Paused
* @param view The R.id.carInfoEditSave button in the view
*/
public void saveInfo(View view) {
Log.i(TAG, "saveInfo");
// TODO should this method work this way? Right now, it waits until onPause is called to actually save, even
// though the use has clicked the "save" button
edited = true;
back(view);
}
/**
* Returns to the previous activity. In this case, it should always be CarInfoActivity
* @param view The R.id.carInfoEditBack button in the view
*/
public void back(View view) {
finish();
}
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "onPause");
if (edited) {
if (updateVehicle()) {
Log.e(TAG, "could not update vehicle");
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
dbHelper.close();
}
private void updateUi(Vehicle vehicle) {
((TextView) findViewById(R.id.field_year)).setText(vehicle.getYear());
((TextView) findViewById(R.id.field_VIN)).setText(vehicle.getVin());
((TextView) findViewById(R.id.field_make)).setText(vehicle.getMake());
((TextView) findViewById(R.id.field_model)).setText(vehicle.getModel());
((TextView) findViewById(R.id.field_color)).setText(vehicle.getColor());
((TextView) findViewById(R.id.field_nickname)).setText(vehicle.getNickname());
((TextView) findViewById(R.id.field_license_plate)).setText(vehicle.getPlateNumber());
}
private boolean updateVehicle() {
String vin = ((TextView) findViewById(R.id.field_VIN)).getText().toString();
String make = ((TextView) findViewById(R.id.field_make)).getText().toString();
String model = ((TextView) findViewById(R.id.field_model)).getText().toString();
String year = ((TextView) findViewById(R.id.field_year)).getText().toString();
String color = ((TextView) findViewById(R.id.field_color)).getText().toString();
String nickname = ((TextView) findViewById(R.id.field_nickname)).getText().toString();
String plateNumber = ((TextView) findViewById(R.id.field_license_plate)).getText().toString();
Vehicle vehicle = new Vehicle(vin, make, model, year, color, nickname, plateNumber);
int numAffected = dbHelper.updateVehicle(vehicleId, vehicle);
return numAffected > 0;
}
}
| apache-2.0 |
cchao1024/TouchNews | app/src/main/java/com/github/cchao/touchnews/ui/fragment/ImageFragment.java | 2928 | package com.github.cchao.touchnews.ui.fragment;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.github.cchao.touchnews.R;
import com.github.cchao.touchnews.ui.adapter.ImageFragmentsPagerAdapter;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Created by cchao on 2016/3/30.
* E-mail: cchao1024@163.com
* Description:
*/
public class ImageFragment extends Fragment {
@Bind(R.id.tab_image)
TabLayout mTabLayout;
@Bind(R.id.viewpager_image)
ViewPager mViewPager;
String[] mTitles;
List mFragments;
FragmentPagerAdapter mFragmentsPagerAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initData();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_image, null);
ButterKnife.bind(this, view);
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setTableLayout();
}
private void initData() {
mTitles = getResources().getStringArray(R.array.news_titles);
mFragments = new ArrayList<>();
for (int i = 0; i < mTitles.length; i++) {
Bundle mBundle = new Bundle();
mBundle.putInt("flag", i);
// Fragment fragment = new NewsListFragments ( );
// fragment.setArguments ( mBundle );
// mFragments.add ( i, fragment );
}
}
private void setTableLayout() {
mFragmentsPagerAdapter = new ImageFragmentsPagerAdapter(getActivity().getSupportFragmentManager(), mTitles, mFragments);
mViewPager.setOffscreenPageLimit(mFragments.size());
mViewPager.setAdapter(mFragmentsPagerAdapter);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
// 将TabLayout和ViewPager进行关联,让两者联动起来
mTabLayout.setupWithViewPager(mViewPager);
}
}
| apache-2.0 |
jiaozhujun/c3f | src-core/com/youcan/core/CallBack.java | 954 | package com.youcan.core;
public class CallBack {
private String content = null;
private long timeout;
private boolean isTimeout = true;
public static final int CALLBACK_NONE = -1;
public static final int CALLBACK_TIMEOUT_ENDLESS = 0;
public CallBack(long timeout) {
this.timeout = timeout;
}
public String getContent() {
return content;
}
public long getTimeout() {
return timeout;
}
public void setTimeout(long timeout) {
this.timeout = timeout;
}
public synchronized String waitBack() {
try {
if (timeout >= 0) {
wait(timeout);
if (isTimeout) {
content = "TIMEOUT:" + timeout;
}
}
} catch (InterruptedException e) {
content = "InterruptedException:" + e.getMessage();
} finally {
isTimeout = true;
}
return content;
}
public synchronized void finished(String content) {
this.content = content;
isTimeout = false;
notify();
}
}
| apache-2.0 |
isisaddons/isis-app-quickstart | fixture/src/main/java/domainapp/fixture/scenarios/demo/DemoFixture.java | 2509 | /*
* 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 domainapp.fixture.scenarios.demo;
import java.net.URL;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Lists;
import com.google.common.io.Resources;
import org.apache.isis.applib.fixturescripts.FixtureScript;
import org.isisaddons.module.excel.dom.ExcelFixture;
import domainapp.dom.quick.QuickObject;
import domainapp.fixture.dom.quick.QuickObjectRowHandler;
import domainapp.fixture.dom.quick.QuickObjectsTearDown;
import lombok.Getter;
public class DemoFixture extends FixtureScript {
public DemoFixture() {
withDiscoverability(Discoverability.DISCOVERABLE);
}
/**
* The quick objects created by this fixture (output).
*/
@Getter
private final List<QuickObject> quickObjects = Lists.newArrayList();
@Override
protected void execute(final ExecutionContext ec) {
// zap everything
ec.executeChild(this, new QuickObjectsTearDown());
// load data from spreadsheet
final URL spreadsheet = Resources.getResource(DemoFixture.class, "DemoFixture.xlsx");
final ExcelFixture fs = new ExcelFixture(spreadsheet, getHandlers());
ec.executeChild(this, fs);
// make objects created by ExcelFixture available to our caller.
final Map<Class, List<Object>> objectsByClass = fs.getObjectsByClass();
getQuickObjects().addAll((List)objectsByClass.get(QuickObject.class));
getQuickObjects().addAll((List)objectsByClass.get(QuickObjectRowHandler.class));
}
private Class[] getHandlers() {
return new Class[]{
QuickObject.class,
QuickObjectRowHandler.class
};
}
}
| apache-2.0 |
xsocket/ksa | ksa-dao-root/ksa-logistics-dao/src/main/java/com/ksa/dao/logistics/mybatis/MybatisBookingNoteDao.java | 3334 | package com.ksa.dao.logistics.mybatis;
import java.util.HashMap;
import java.util.Map;
import org.springframework.util.StringUtils;
import com.ksa.dao.AbstractMybatisDao;
import com.ksa.dao.logistics.BookingNoteDao;
import com.ksa.model.logistics.BookingNote;
import com.ksa.model.logistics.BookingNoteState;
/**
* 基于 Mybaits 的 BookingNoteDao 实现。
*
* @author 麻文强
*
* @since v0.0.1
*/
public class MybatisBookingNoteDao extends AbstractMybatisDao implements BookingNoteDao {
@Override
public int insertBookingNote( BookingNote note ) throws RuntimeException {
return this.session.insert( "insert-logistics-bookingnote", note );
}
@Override
public int updateBookingNote( BookingNote note ) throws RuntimeException {
return this.session.update( "update-logistics-bookingnote", note );
}
@Override
public int updateBookingNoteState( BookingNote note ) throws RuntimeException {
return this.session.update( "update-logistics-bookingnote-state", note );
}
@Override
public int updateBookingNoteType( BookingNote note ) throws RuntimeException {
return this.session.update( "update-logistics-bookingnote-type", note );
}
@Override
public int updateBookingNoteChargeDate( BookingNote note ) throws RuntimeException {
return this.session.update( "update-logistics-bookingnote-chargedate", note );
}
@Override
public int deleteBookingNote( BookingNote note ) throws RuntimeException {
note.setState( BookingNoteState.DELETED ); // 将托单的状态设置为 '已删除'
return updateBookingNoteState( note );
}
@Override
public BookingNote selectBookingNoteById( String id ) throws RuntimeException {
return this.session.selectOne( "select-logistics-bookingnote-byid", id );
}
@Override
public int selectBookingNoteCount() throws RuntimeException {
return ( (Integer) this.session.selectOne( "count-logistics-bookingnote" ) ).intValue();
}
@Override
public int selectBookingNoteCount( String queryString ) throws RuntimeException {
Map<String, Object> para = new HashMap<String, Object>();
// FIXME 对应sql中参数名是 queryClauses,这个参数设置无用!只能查到全部数据!
para.put( "queryClause", new String[]{ queryString } );
return ( (Integer) this.session.selectOne( "count-logistics-bookingnote-query", para ) ).intValue();
}
@Override
public BookingNote selectBookingNoteByLading( BookingNote note ) throws RuntimeException {
if( !StringUtils.hasText( note.getHawb() ) && !StringUtils.hasText( note.getMawb() ) ) {
throw new IllegalArgumentException( "通过提单号查询托单时,主副提单号不能同时为空。" );
}
BookingNote param = new BookingNote();
param.setId( note.getId() );
if( StringUtils.hasText( note.getMawb() ) ) {
param.setMawb( note.getMawb() );
}
if( StringUtils.hasText( note.getHawb() ) ) {
param.setHawb( note.getHawb() );
}
return this.session.selectOne( "select-logistics-bookingnote-bylading", param );
}
}
| apache-2.0 |
JimBarrows/JavaDomainObjects | Products/src/main/java/jdo/product/model/Service.java | 405 | package jdo.product.model;
import javax.persistence.Entity;
import javax.xml.crypto.Data;
/**
* @author Jim
* @version 1.0
* @created 25-Dec-2007 9:54:38 AM
* @see Data Model Resource Book Volume 1 Figure 3.1, page 71
* @see Data Model Resource Book Volume 1 Figure 3.3, page 75
*/
@Entity
public class Service extends Product {
/**
*
*/
private static final long serialVersionUID = 1L;
} | apache-2.0 |
spring-projects/spring-framework | spring-context/src/main/java/org/springframework/context/annotation/ImportSelector.java | 3492 | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.annotation;
import java.util.function.Predicate;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.lang.Nullable;
/**
* Interface to be implemented by types that determine which @{@link Configuration}
* class(es) should be imported based on a given selection criteria, usually one or
* more annotation attributes.
*
* <p>An {@link ImportSelector} may implement any of the following
* {@link org.springframework.beans.factory.Aware Aware} interfaces,
* and their respective methods will be called prior to {@link #selectImports}:
* <ul>
* <li>{@link org.springframework.context.EnvironmentAware EnvironmentAware}</li>
* <li>{@link org.springframework.beans.factory.BeanFactoryAware BeanFactoryAware}</li>
* <li>{@link org.springframework.beans.factory.BeanClassLoaderAware BeanClassLoaderAware}</li>
* <li>{@link org.springframework.context.ResourceLoaderAware ResourceLoaderAware}</li>
* </ul>
*
* <p>Alternatively, the class may provide a single constructor with one or more of
* the following supported parameter types:
* <ul>
* <li>{@link org.springframework.core.env.Environment Environment}</li>
* <li>{@link org.springframework.beans.factory.BeanFactory BeanFactory}</li>
* <li>{@link java.lang.ClassLoader ClassLoader}</li>
* <li>{@link org.springframework.core.io.ResourceLoader ResourceLoader}</li>
* </ul>
*
* <p>{@code ImportSelector} implementations are usually processed in the same way
* as regular {@code @Import} annotations, however, it is also possible to defer
* selection of imports until all {@code @Configuration} classes have been processed
* (see {@link DeferredImportSelector} for details).
*
* @author Chris Beams
* @author Juergen Hoeller
* @since 3.1
* @see DeferredImportSelector
* @see Import
* @see ImportBeanDefinitionRegistrar
* @see Configuration
*/
public interface ImportSelector {
/**
* Select and return the names of which class(es) should be imported based on
* the {@link AnnotationMetadata} of the importing @{@link Configuration} class.
* @return the class names, or an empty array if none
*/
String[] selectImports(AnnotationMetadata importingClassMetadata);
/**
* Return a predicate for excluding classes from the import candidates, to be
* transitively applied to all classes found through this selector's imports.
* <p>If this predicate returns {@code true} for a given fully-qualified
* class name, said class will not be considered as an imported configuration
* class, bypassing class file loading as well as metadata introspection.
* @return the filter predicate for fully-qualified candidate class names
* of transitively imported configuration classes, or {@code null} if none
* @since 5.2.4
*/
@Nullable
default Predicate<String> getExclusionFilter() {
return null;
}
}
| apache-2.0 |
EvilMcJerkface/atlasdb | timelock-server/src/testCommon/java/com/palantir/atlasdb/timelock/Http2Agent.java | 1931 | /*
* (c) Copyright 2019 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.atlasdb.timelock;
import com.ea.agentloader.AgentLoader;
import java.lang.instrument.Instrumentation;
import org.mortbay.jetty.alpn.agent.Premain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** A very simple wrapper around the jetty-alpn-agent for dynamic loading. */
public final class Http2Agent {
private Http2Agent() {}
private static final Logger log = LoggerFactory.getLogger(Http2Agent.class);
private static boolean hasBeenInstalled = false;
/**
* Installs the jetty-alpn-agent dynamically.
* <p>
* This method protects itself from multiple invocations so may be called in multiple places, but will only
* ever invoke the installation once.
*/
public static synchronized void install() {
if (hasBeenInstalled) {
return;
}
try {
AgentLoader.loadAgentClass(Http2Agent.class.getName(), "");
hasBeenInstalled = true;
} catch (Exception e) {
log.warn("Unable to dynamically install jetty-alpn-agent via ea-agent-loader, proceeding anyway...", e);
}
}
/** Agent entry-point. */
public static void agentmain(String args, Instrumentation inst) throws Exception {
Premain.premain(args, inst);
}
}
| apache-2.0 |
vanilladb/vanillacore | src/main/java/org/vanilladb/core/storage/file/io/javanio/JavaNioFileChannel.java | 3075 | /*******************************************************************************
* Copyright 2016, 2017 vanilladb.org contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package org.vanilladb.core.storage.file.io.javanio;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.vanilladb.core.storage.file.io.IoBuffer;
import org.vanilladb.core.storage.file.io.IoChannel;
public class JavaNioFileChannel implements IoChannel {
private FileChannel fileChannel;
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
// Optimization: store the size of each table
private long fileSize;
public JavaNioFileChannel(File file) throws IOException {
@SuppressWarnings("resource")
RandomAccessFile f = new RandomAccessFile(file, "rws");
fileChannel = f.getChannel();
fileSize = fileChannel.size();
}
@Override
public int read(IoBuffer buffer, long position) throws IOException {
lock.readLock().lock();
try {
JavaNioByteBuffer javaBuffer = (JavaNioByteBuffer) buffer;
return fileChannel.read(javaBuffer.getByteBuffer(), position);
} finally {
lock.readLock().unlock();
}
}
@Override
public int write(IoBuffer buffer, long position) throws IOException {
lock.writeLock().lock();
try {
JavaNioByteBuffer javaBuffer = (JavaNioByteBuffer) buffer;
int writeSize = fileChannel.write(javaBuffer.getByteBuffer(), position);
// Check if we need to update the size
if (position + writeSize > fileSize)
fileSize = position + writeSize;
return writeSize;
} finally {
lock.writeLock().unlock();
}
}
@Override
public long append(IoBuffer buffer) throws IOException {
lock.writeLock().lock();
try {
JavaNioByteBuffer javaBuffer = (JavaNioByteBuffer) buffer;
int appendSize = fileChannel.write(javaBuffer.getByteBuffer(), fileSize);
fileSize += appendSize;
return fileSize;
} finally {
lock.writeLock().unlock();
}
}
@Override
public long size() throws IOException {
lock.readLock().lock();
try {
return fileSize;
} finally {
lock.readLock().unlock();
}
}
@Override
public void close() throws IOException {
lock.writeLock().lock();
try {
fileChannel.close();
} finally {
lock.writeLock().unlock();
}
}
}
| apache-2.0 |
sdgdsffdsfff/configcenter-client | src/main/java/com/baidu/cc/ConfigLoader.java | 18415 | /*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baidu.cc;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.springframework.util.Assert;
import com.baidu.bjf.remoting.mcpack.OperationTimeoutMcpackRpcProxyFactoryBean;
import com.baidu.bjf.util.StopWatch;
import com.baidu.cc.interfaces.ChangedConfigItem;
import com.baidu.cc.interfaces.ConfigItemChangedCallable;
import com.baidu.cc.interfaces.ConfigServerService;
import com.baidu.cc.interfaces.ExtConfigServerService;
import com.baidu.gson.Gson;
import com.google.gson.reflect.TypeToken;
/**
* Configuration loader utility class.
*
* @author xiemalin
* @since 1.0.0.0
*/
public class ConfigLoader {
/**
* Logger for this class
*/
private static final Logger LOGGER = Logger.getLogger(ConfigLoader.class);
/**
* JSON utility class to serialize configuration to file and reverse action.
*/
private Gson gson = new Gson();
/**
* file encode string
*/
private static final String FILE_ENCODE = "utf-8";
/**
* configuration server client instance.
*/
private ExtConfigServerService configServerService;
/**
* set configServerService instance.
* @param configServerService the configServerService to set
*/
public void setConfigServerService(ExtConfigServerService configServerService) {
this.configServerService = configServerService;
}
/**
* Configuration item changed callable instances.
*/
private Map<String, ConfigItemChangedCallable> callables = new HashMap<String, ConfigItemChangedCallable>();
/**
* Configuration center server user name.
*/
private String ccUser;
/**
* Configuration center server password.
*/
private String ccPassword;
/**
* Request configuration version
*/
private Long ccVersion;
/**
* 版本名称,如果不为空,则忽略ccVersion
*/
private String ccVersionName;
/**
* request configuration environment id under specified version.
*/
private Long ccEnvId;
/**
* project name
*/
private String projectName;
/**
* environment name
*/
private String envName;
/**
* set call back listen call back interval
*/
private long callbackInteval;
/**
* current version tag value
*/
private String versionTag;
/**
* local property file
*/
private File localPropertyFile;
/**
* set project name
* @param projectName the projectName to set
*/
public void setProjectName(String projectName) {
this.projectName = projectName;
}
/**
* set environment name
* @param envName the envName to set
*/
public void setEnvName(String envName) {
this.envName = envName;
}
/**
* set local property fiel
* @param localPropertyFile the localPropertyFile to set
*/
public void setLocalPropertyFile(File localPropertyFile) {
this.localPropertyFile = localPropertyFile;
}
/**
* get current version tag.
*
* @return the versionTag
*/
public String getVersionTag() {
return versionTag;
}
/**
* set current version tag.
* @param versionTag the versionTag to set
*/
public void setVersionTag(String versionTag) {
this.versionTag = versionTag;
}
/**
* set current version tag. and tag key will remove from map.
*
* @param configItems configuration items
*/
public void setVersionTag(Map<String, String> configItems) {
if (MapUtils.isEmpty(configItems)) {
this.versionTag = null;
return;
}
setVersionTag(configItems.get(ConfigServerService.TAG_KEY));
configItems.remove(ConfigServerService.TAG_KEY);
}
/**
* get call back listen call back interval
* @return the callbackInteval
*/
protected long getCallbackInteval() {
return callbackInteval;
}
/**
* configuration changed listener
*/
private ConfigChangedListener configChangedListener;
/**
* print current version id
*/
private void printUseVersionLog() {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Current use version id:" + ccVersion);
}
}
/**
* do initialize operation.
*/
public void init() {
//here need to check parameters
Assert.hasLength(ccUser, "property 'ccUser' is blank.");
Assert.notNull(configServerService, "property 'configServerService' is null");
if (ccVersion != null && ccVersion > 0) {
printUseVersionLog();
return;
}
//if set ccVersionName
Long vId = configServerService.getVersionId(ccUser, ccPassword, ccVersionName);
if (vId != null) {
ccVersion = vId;
printUseVersionLog();
return;
}
if (StringUtils.isNotBlank(projectName) &&
StringUtils.isNotBlank(envName)) {
long time = System.currentTimeMillis();
ccVersion = configServerService.getLastestConfigVersion(ccUser,
ccPassword, projectName, envName);
long timetook = System.currentTimeMillis() - time;
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Get configuration version id by projectName[" + projectName
+ "] and envName[" + envName + "] and get version is:" + ccVersion + " time took(ms):" + timetook);
}
printUseVersionLog();
return;
}
//check ccVersionName
//if ccEnvId is not null should check ccVersion
if (ccEnvId != null && ccEnvId > 0) {
//if ccVersion is not null then ccEnvId will be ignore
if (ccVersion != null && ccVersion > 0) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Found configuration version id[" + ccVersion
+ "] ccEnvId[" + ccEnvId + "] will be ignored.");
}
} else {
long time = System.currentTimeMillis();
//should get ccVersion id by ccEnvId
ccVersion = configServerService.getLastestConfigVersion(ccUser,
ccPassword, ccEnvId);
if (LOGGER.isInfoEnabled()) {
long timetook = System.currentTimeMillis() - time;
LOGGER.info("Get configuration version id by envId[" + ccEnvId
+ "] and get version is:" + ccVersion + " time took(ms):" + timetook);
}
}
}
Assert.notNull(ccVersion, "property 'ccVersion' is null");
}
/**
* set user name
* @param ccUser the ccUser to set
*/
public void setCcUser(String ccUser) {
this.ccUser = ccUser;
}
/**
* set password
* @param ccPassword the ccPassword to set
*/
public void setCcPassword(String ccPassword) {
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
encryptor.setPassword(ExtConfigServerService.class.getSimpleName());
//all password to transport should be encrypt
this.ccPassword = encryptor.encrypt(ccPassword);
}
/**
* set version
* @param ccVersion the ccVersion to set
*/
public void setCcVersion(Long ccVersion) {
this.ccVersion = ccVersion;
}
/**
* @param ccVersionName the ccVersionName to set
*/
public void setCcVersionName(String ccVersionName) {
this.ccVersionName = ccVersionName;
}
/**
* set environment id
* @param ccEnvId the ccEnvId to set
*/
public void setCcEnvId(Long ccEnvId) {
this.ccEnvId = ccEnvId;
}
/**
* set call back listen call back interval
* @param callbackInteval the callbackInteval to set
*/
public void setCallbackInteval(long callbackInteval) {
this.callbackInteval = callbackInteval;
}
/**
* do call back action.
*
* @param changedConfigItems changed config item list
*/
protected void doCallback(List<ChangedConfigItem> changedConfigItems) {
if (CollectionUtils.isEmpty(changedConfigItems)) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Empty changed config items call back.");
}
return;
}
if (MapUtils.isNotEmpty(callables)) {
Collection<ConfigItemChangedCallable> tmp;
tmp = new ArrayList<ConfigItemChangedCallable>(callables.values());
//for safety consider
List<ChangedConfigItem> changedItems = ListUtils.unmodifiableList(changedConfigItems);
//do call back to each call
for (ConfigItemChangedCallable configItemChangedCallable : tmp) {
try {
configItemChangedCallable.changed(changedItems);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
}
/**
* Delegate to get config items from {@link ConfigServerService}
* @return config item map
*/
public Map<String, String> getConfigItems() {
StopWatch sw = new StopWatch();
sw.start();
Map<String, String> ret = configServerService.getConfigItems(ccUser, ccPassword, ccVersion);
long timetook = sw.stop();
logRpcTimeTook(timetook, "getConfigItems");
return ret;
}
/**
* To log RPC method invoke message.
*
* @param timetook RPC invoke time took
* @param methodName RPC method name
*/
private void logRpcTimeTook(long timetook, String methodName) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("RPC method '" + methodName + "' time took(ms) :" + timetook);
}
}
/**
* Import configuration items into the server.
*
* @param ccVersion version id
* @param configItems configuration item list
*/
public void importConfigItems(long ccVersion, Map<String, String> configItems) {
StopWatch sw = new StopWatch();
sw.start();
configServerService.importConfigItems(ccUser, ccPassword, ccVersion, configItems);
long timetook = sw.stop();
logRpcTimeTook(timetook, "importConfigItems");
}
/**
* To check version tag is update or not.
* @return true if version tag is same.
*/
protected boolean checkVersionTag() {
StopWatch sw = new StopWatch();
sw.start();
boolean ret = configServerService.checkVersionTag(ccUser, ccPassword,
ccVersion, versionTag);
long timetook = sw.stop();
logRpcTimeTook(timetook, "checkVersionTag");
return ret;
}
/**
* get configuration item changed callable instances.
* @return the callables
*/
public Map<String, ConfigItemChangedCallable> getCallables() {
return callables;
}
/**
* set configuration item changed callable instances.
* @param callables the callables to set
*/
public void setCallables(Map<String, ConfigItemChangedCallable> callables) {
if (callables != null) {
this.callables.putAll(callables);
}
}
/**
* stop call back listening
*/
public synchronized void stop() {
if (configChangedListener != null) {
configChangedListener.close();
}
}
/**
* start call back listening.
*
* @param props current configuration item set.
*/
public synchronized void startListening(Properties props) {
if (configChangedListener == null) {
configChangedListener = new ConfigChangedListener(props, this);
}
if (configChangedListener.isStop()) {
configChangedListener.start();
}
}
/**
* Read property from local resource file
*
* @param props to merge from local
* @param localFile local resource file
* @throws IOException throw all file operation exception
*/
public void readLocal(Properties props, File localFile) throws IOException {
Assert.notNull(localFile, "Property 'localFile' is null.");
if (!localFile.exists()) {
throw new IOException("File not exist. " + localFile.getPath());
}
byte[] byteArray = FileUtils.readFileToByteArray(localFile);
Hex encoder = new Hex();
try {
byteArray = encoder.decode(byteArray);
} catch (DecoderException e) {
throw new IOException(e.getMessage());
}
String json = new String(byteArray, FILE_ENCODE);
Map<String, String> map = gson.fromJson(json,
new TypeToken<Map<String, String>>() {}.getType());
setVersionTag(map);
props.putAll(map);
}
/**
* Write property content to local resource file.
*
* @param configItems latest configuration items
* @param localFile loca resource file
* @throws IOException throw all file operation exception
*/
public void writeLocal(Map<String, String> configItems, File localFile) throws IOException {
Assert.notNull(localFile, "Property 'localFile' is null.");
if (!localFile.exists()) {
throw new IOException("File not exist. " + localFile.getPath());
}
String json = gson.toJson(configItems);
//to byte array
byte[] byteArray = json.getBytes(FILE_ENCODE);
Hex encoder = new Hex();
byteArray = encoder.encode(byteArray);
FileUtils.writeByteArrayToFile(localFile, byteArray);
}
/**
* If version tag changed will update latest configuration items.
*
* @param configItems latest configuration items
*/
public void onLatestUpdate(Map<String, String> configItems) {
if (localPropertyFile == null) {
return;
}
try {
writeLocal(configItems, localPropertyFile);
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
/**
* create {@link ConfigLoader} instance.
*
* @param propertySupport {@link ConfigLoaderPropertySupport}
* @return {@link ConfigLoader} instance.
*/
public static ConfigLoader createConfigLoader(ConfigLoaderPropertySupport propertySupport) {
//create configservice
ExtConfigServerService service;
service = createConfigService(propertySupport.getCcServerUrl(),
propertySupport.getConnectionTimeout(), propertySupport.getReadTimeout());
ConfigLoader configLoader = new ConfigLoader();
configLoader.setCcVersionName(propertySupport.getCcVersionName());
configLoader.setCcUser(propertySupport.getCcUser());
configLoader.setCcPassword(propertySupport.getCcPassword());
configLoader.setCallbackInteval(propertySupport.getCallbackInteval());
configLoader.setConfigServerService(service);
configLoader.init();
//get configruation items from server
Map<String, String> configItems = configLoader.getConfigItems();
//add call back listener here
configLoader.getCallables().put("cust_listener", propertySupport);
//以当前的数据为基准进行更新支持
Properties properties = new Properties();
properties.putAll(configItems);
configLoader.setVersionTag(configItems);
propertySupport.propertiesLoad(configItems);
if (propertySupport.isEnableUpdateCallback()) {
configLoader.startListening(properties);
}
return configLoader;
}
/**
* Create {@link ExtConfigServerService} proxy instance.
*
* @param ccServerUrl configuration center server URL.
* @param connectionTimeout connection time out
* @param readTimeout read time out
* @return {@link ExtConfigServerService} proxy instance.
*/
private static ExtConfigServerService createConfigService(String ccServerUrl, int connectionTimeout,
int readTimeout) {
OperationTimeoutMcpackRpcProxyFactoryBean proxy = new OperationTimeoutMcpackRpcProxyFactoryBean();
proxy.setServiceUrl(Constants.getServerUrl(ccServerUrl));
proxy.setServiceInterface(ExtConfigServerService.class);
proxy.setConnectionTimeout(connectionTimeout);
proxy.setSoTimeout(readTimeout);
//do initial
proxy.afterPropertiesSet();
return (ExtConfigServerService) proxy.getObject();
}
}
| apache-2.0 |
netixx/autotopo | src/main/java/fr/netixx/AutoTopo/notifications/aggregation/Direction.java | 620 | package fr.netixx.AutoTopo.notifications.aggregation;
import fr.netixx.AutoTopo.adapters.IDirection;
public class Direction implements IDirection {
double cosTheta;
double sinTheta;
public Direction(double cosTheta, double sinTheta) {
this.cosTheta = cosTheta;
this.sinTheta = sinTheta;
}
@Override
public double cosTheta() {
return cosTheta;
}
@Override
public double sinTheta() {
return sinTheta;
}
@Override
public double getLongitudeProjection(double value) {
return value * cosTheta;
}
@Override
public double getLatitudeProjection(double value) {
return value * sinTheta;
}
}
| apache-2.0 |
anton-johansson/counter-strike-overview | src/main/java/com/antonjohansson/counterstrike/service/gamestate/GameStateService.java | 1666 | /**
* Copyright (c) Anton Johansson <antoon.johansson@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.antonjohansson.counterstrike.service.gamestate;
import com.antonjohansson.counterstrike.persistence.account.IAccountDao;
import com.antonjohansson.counterstrike.persistence.gamestate.IGameStateDao;
import com.antonjohansson.counterstrike.service.gamestate.domain.GameState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Default implementation of {@link IGameStateService}.
*
* @author Anton Johansson
*/
@Service
class GameStateService implements IGameStateService
{
private final IAccountDao accountDao;
private final IGameStateDao gameStateDao;
@Autowired
GameStateService(IAccountDao accountDao, IGameStateDao gameStateDao)
{
this.accountDao = accountDao;
this.gameStateDao = gameStateDao;
}
/** {@inheritDoc} */
@Override
public void process(GameState gameState)
{
if (!isProcessable(gameState))
{
return;
}
gameStateDao.save(gameState);
}
private boolean isProcessable(GameState gameState)
{
return true;
}
}
| apache-2.0 |
ichigotake/android-sqlite-helper | sqlitehelper/src/test/java/net/ichigotake/sqlitehelper/ddl/CreateTableDefinitionTest.java | 4503 | package net.ichigotake.sqlitehelper.ddl;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Build;
import android.support.annotation.NonNull;
import junit.framework.Assert;
import net.ichigotake.sqlitehelper.BuildConfig;
import net.ichigotake.sqlitehelper.DatabaseHelper;
import net.ichigotake.sqlitehelper.MockConfiguration;
import net.ichigotake.sqlitehelper.MockTableDefinition;
import net.ichigotake.sqlitehelper.schema.Index;
import net.ichigotake.sqlitehelper.schema.DatabaseTable;
import net.ichigotake.sqlitehelper.schema.TableSchema;
import net.ichigotake.sqlitehelper.schema.UniqueField;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowApplication;
@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.KITKAT)
@RunWith(RobolectricGradleTestRunner.class)
public class CreateTableDefinitionTest {
private DatabaseTable mock() {
return new MockTableForCreateTableDefinition();
}
private DatabaseHelper sqliteHelper() {
return new DatabaseHelper(ShadowApplication.getInstance().getApplicationContext(), new MockConfiguration());
}
@Test
public void testBuildQueryAsCreateTableIfNotExists() {
DatabaseHelper sqlite = sqliteHelper();
CreateTable createTable = new CreateTable(
sqlite.getReadableDatabase(), mock().getTableSchema());
String expected = "CREATE TABLE IF NOT EXISTS mock_for_create_table (" +
"_id INTEGER PRIMARY KEY," +
"item_name TEXT," +
"item_type TEXT," +
"category_id INTEGER," +
"category_name TEXT," +
"UNIQUE (category_id)," +
"UNIQUE (item_name,item_type)" +
")";
Assert.assertEquals(expected, createTable.buildQueryAsCreateTableIfNotExists());
}
@Test
public void testBuildUniqueQuery() {
DatabaseHelper sqlite = sqliteHelper();
CreateTable createTable = new CreateTable(
sqlite.getReadableDatabase(), mock().getTableSchema());
UniqueField sample = new UniqueField(MockTableDefinition.Field.CATEGORY_ID);
Assert.assertEquals("UNIQUE (category_id)", createTable.buildQueryAsUnique(sample));
}
@Test
public void testCreateTable() {
SQLiteDatabase database = sqliteHelper().getWritableDatabase();
CreateTable createTable = new CreateTable(database, mock().getTableSchema());
{
Exception got = null;
try {
database.rawQuery("SELECT * FROM mock_for_create_table", new String[]{});
} catch (SQLiteException e) {
got = e;
}
Assert.assertTrue(got != null);
}
database.execSQL(createTable.buildQueryAsCreateTableIfNotExists());
{
database.execSQL("SELECT * FROM mock_for_create_table", new String[]{});
Assert.assertTrue(true);
}
}
@Test
public void testCreateIndex() {
TableSchema schema = mock().getTableSchema();
SQLiteDatabase database = sqliteHelper().getWritableDatabase();
CreateTable createTable = new CreateTable(database, schema);
Assert.assertTrue(!indexExists(database, schema));
createTable.createTableIfNotExists();
Assert.assertTrue(indexExists(database, schema));
}
private boolean indexExists(SQLiteDatabase database, TableSchema schema) {
if (schema.getIndexes().isEmpty()) {
throw new IllegalStateException("Indexes is empty");
}
CreateIndex createIndex = new CreateIndex(database, schema);
for (Index index : schema.getIndexes()) {
try {
String query = createIndex.buildCreateIndexClause(index)
.replace("IF NOT EXISTS ", "");
database.execSQL(query);
} catch (SQLiteException e) {
if (!e.getCause().getMessage().contains("already exists]")) {
return false;
}
}
}
return true;
}
}
class MockTableForCreateTableDefinition extends MockTableDefinition {
@NonNull
@Override
public String getTableName() {
return "mock_for_create_table";
}
} | apache-2.0 |
equella/Equella | Source/Plugins/Core/com.equella.core/src/com/tle/web/userscripts/service/UserScriptsModule.java | 1570 | /*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* The Apereo Foundation licenses this file to you under the Apache License,
* Version 2.0, (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tle.web.userscripts.service;
import com.google.inject.name.Names;
import com.tle.web.sections.equella.guice.SectionsModule;
import com.tle.web.userscripts.section.RootUserScriptsSection;
import com.tle.web.userscripts.section.ShowUserScriptsSection;
import com.tle.web.userscripts.section.UserScriptContributeSection;
public class UserScriptsModule extends SectionsModule {
@Override
protected void configure() {
bind(Object.class).annotatedWith(Names.named("userScriptsTree")).toProvider(userScriptsTree());
}
private NodeProvider userScriptsTree() {
NodeProvider node = node(RootUserScriptsSection.class);
node.innerChild(UserScriptContributeSection.class);
node.child(ShowUserScriptsSection.class);
return node;
}
}
| apache-2.0 |
realityforge/arez | processor/src/test/fixtures/expected/com/example/component_dependency/Arez_ComponentFieldDependencyModel.java | 5851 | package com.example.component_dependency;
import arez.Arez;
import arez.ArezContext;
import arez.Component;
import arez.Disposable;
import arez.SafeProcedure;
import arez.component.DisposeNotifier;
import arez.component.Identifiable;
import arez.component.internal.ComponentKernel;
import javax.annotation.Generated;
import javax.annotation.Nonnull;
import org.realityforge.braincheck.Guards;
@Generated("arez.processor.ArezProcessor")
final class Arez_ComponentFieldDependencyModel extends ComponentFieldDependencyModel implements Disposable, Identifiable<Integer>, DisposeNotifier {
private static volatile int $$arezi$$_nextId;
private final ComponentKernel $$arezi$$_kernel;
Arez_ComponentFieldDependencyModel() {
super();
final ArezContext $$arezv$$_context = Arez.context();
final int $$arezv$$_id = ++$$arezi$$_nextId;
final String $$arezv$$_name = Arez.areNamesEnabled() ? "com_example_component_dependency_ComponentFieldDependencyModel." + $$arezv$$_id : null;
final Component $$arezv$$_component = Arez.areNativeComponentsEnabled() ? $$arezv$$_context.component( "com_example_component_dependency_ComponentFieldDependencyModel", $$arezv$$_id, $$arezv$$_name, this::$$arezi$$_nativeComponentPreDispose ) : null;
this.$$arezi$$_kernel = new ComponentKernel( Arez.areZonesEnabled() ? $$arezv$$_context : null, Arez.areNamesEnabled() ? $$arezv$$_name : null, $$arezv$$_id, Arez.areNativeComponentsEnabled() ? $$arezv$$_component : null, Arez.areNativeComponentsEnabled() ? null : this::$$arezi$$_preDispose, null, null, true, false, false );
if ( null != this.foo ) {
DisposeNotifier.asDisposeNotifier( this.foo ).addOnDisposeListener( this, this::dispose );
}
this.$$arezi$$_kernel.componentConstructed();
this.$$arezi$$_kernel.componentComplete();
}
private int $$arezi$$_id() {
return this.$$arezi$$_kernel.getId();
}
@Override
@Nonnull
public Integer getArezId() {
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'getArezId' invoked on uninitialized component of type 'com_example_component_dependency_ComponentFieldDependencyModel'" );
}
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenConstructed(), () -> "Method named 'getArezId' invoked on un-constructed component named '" + ( null == this.$$arezi$$_kernel ? "?" : this.$$arezi$$_kernel.getName() ) + "'" );
}
return $$arezi$$_id();
}
private void $$arezi$$_preDispose() {
if ( null != this.foo ) {
DisposeNotifier.asDisposeNotifier( this.foo ).removeOnDisposeListener( this );
}
}
private void $$arezi$$_nativeComponentPreDispose() {
this.$$arezi$$_preDispose();
this.$$arezi$$_kernel.notifyOnDisposeListeners();
}
@Override
public void addOnDisposeListener(@Nonnull final Object key, @Nonnull final SafeProcedure action) {
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'addOnDisposeListener' invoked on uninitialized component of type 'com_example_component_dependency_ComponentFieldDependencyModel'" );
}
this.$$arezi$$_kernel.addOnDisposeListener( key, action );
}
@Override
public void removeOnDisposeListener(@Nonnull final Object key) {
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'removeOnDisposeListener' invoked on uninitialized component of type 'com_example_component_dependency_ComponentFieldDependencyModel'" );
}
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenConstructed(), () -> "Method named 'removeOnDisposeListener' invoked on un-constructed component named '" + ( null == this.$$arezi$$_kernel ? "?" : this.$$arezi$$_kernel.getName() ) + "'" );
}
this.$$arezi$$_kernel.removeOnDisposeListener( key );
}
@Override
public boolean isDisposed() {
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'isDisposed' invoked on uninitialized component of type 'com_example_component_dependency_ComponentFieldDependencyModel'" );
}
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenConstructed(), () -> "Method named 'isDisposed' invoked on un-constructed component named '" + ( null == this.$$arezi$$_kernel ? "?" : this.$$arezi$$_kernel.getName() ) + "'" );
}
return this.$$arezi$$_kernel.isDisposed();
}
@Override
public void dispose() {
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'dispose' invoked on uninitialized component of type 'com_example_component_dependency_ComponentFieldDependencyModel'" );
}
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenConstructed(), () -> "Method named 'dispose' invoked on un-constructed component named '" + ( null == this.$$arezi$$_kernel ? "?" : this.$$arezi$$_kernel.getName() ) + "'" );
}
this.$$arezi$$_kernel.dispose();
}
@Override
public String toString() {
if ( Arez.areNamesEnabled() ) {
return "ArezComponent[" + this.$$arezi$$_kernel.getName() + "]";
} else {
return super.toString();
}
}
}
| apache-2.0 |
silverbullet-dk/opentele-client-android | questionnaire-mainapp/src/dk/silverbullet/telemed/video/measurement/adapters/submitters/SubmitLungMeasurementTask.java | 788 | package dk.silverbullet.telemed.video.measurement.adapters.submitters;
import dk.silverbullet.telemed.device.vitalographlungmonitor.LungMeasurement;
import dk.silverbullet.telemed.video.measurement.MeasurementInformer;
import dk.silverbullet.telemed.video.measurement.MeasurementResult;
import dk.silverbullet.telemed.video.measurement.adapters.DeviceIdAndMeasurement;
public class SubmitLungMeasurementTask extends SubmitMeasurementTask<LungMeasurement> {
public SubmitLungMeasurementTask(MeasurementInformer informer) {
super(informer);
}
@Override
protected MeasurementResult createMeasurementResult(DeviceIdAndMeasurement<LungMeasurement> measurement) {
return new MeasurementResult(measurement.getDeviceId(), measurement.getMeasurement());
}
}
| apache-2.0 |
k21/buck | src/com/facebook/buck/cxx/AbstractPreprocessorFlags.java | 4861 | /*
* Copyright 2016-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.cxx;
import com.facebook.buck.cxx.toolchain.PathShortener;
import com.facebook.buck.cxx.toolchain.Preprocessor;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.RuleKeyObjectSink;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.args.Arg;
import com.facebook.buck.rules.args.StringArg;
import com.facebook.buck.rules.coercer.FrameworkPath;
import com.facebook.buck.util.Optionals;
import com.facebook.buck.util.immutables.BuckStyleImmutable;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.nio.file.Path;
import java.util.Optional;
import org.immutables.value.Value;
@Value.Immutable
@BuckStyleImmutable
abstract class AbstractPreprocessorFlags {
/** File set via {@code -include}. */
@Value.Parameter
public abstract Optional<SourcePath> getPrefixHeader();
/** Other flags included as is. */
@Value.Parameter
@Value.Default
public CxxToolFlags getOtherFlags() {
return CxxToolFlags.of();
}
/** Directories set via {@code -I}. */
@Value.Parameter
public abstract ImmutableSet<CxxHeaders> getIncludes();
/** Directories set via {@code -F}. */
@Value.Parameter
public abstract ImmutableSet<FrameworkPath> getFrameworkPaths();
@Value.Lazy
public CxxIncludePaths getCxxIncludePaths() {
return CxxIncludePaths.of(getIncludes(), getFrameworkPaths());
}
public Iterable<BuildRule> getDeps(SourcePathRuleFinder ruleFinder) {
ImmutableList.Builder<BuildRule> deps = ImmutableList.builder();
deps.addAll(
Optionals.toStream(getPrefixHeader())
.flatMap(ruleFinder.FILTER_BUILD_RULE_INPUTS)
.iterator());
for (CxxHeaders cxxHeaders : getIncludes()) {
cxxHeaders.getDeps(ruleFinder).forEachOrdered(deps::add);
}
for (FrameworkPath frameworkPath : getFrameworkPaths()) {
deps.addAll(frameworkPath.getDeps(ruleFinder));
}
for (Arg arg : getOtherFlags().getAllFlags()) {
deps.addAll(arg.getDeps(ruleFinder));
}
return deps.build();
}
/** Append to rule key the members which are not handled elsewhere. */
public void appendToRuleKey(RuleKeyObjectSink sink) {
sink.setReflectively("prefixHeader", getPrefixHeader());
sink.setReflectively("includes", getIncludes());
sink.setReflectively("frameworkRoots", getFrameworkPaths());
// Sanitize any relevant paths in the flags we pass to the preprocessor, to prevent them
// from contributing to the rule key.
sink.setReflectively("preprocessorFlags", getOtherFlags());
}
public CxxToolFlags getIncludePathFlags(
SourcePathResolver resolver,
PathShortener pathShortener,
Function<FrameworkPath, Path> frameworkPathTransformer,
Preprocessor preprocessor) {
return CxxToolFlags.explicitBuilder()
.addAllRuleFlags(
StringArg.from(
getCxxIncludePaths()
.getFlags(resolver, pathShortener, frameworkPathTransformer, preprocessor)))
.build();
}
public CxxToolFlags getNonIncludePathFlags(
SourcePathResolver resolver, Optional<CxxPrecompiledHeader> pch, Preprocessor preprocessor) {
ExplicitCxxToolFlags.Builder builder = CxxToolFlags.explicitBuilder();
ExplicitCxxToolFlags.addCxxToolFlags(builder, getOtherFlags());
builder.addAllRuleFlags(
StringArg.from(
preprocessor.prefixOrPCHArgs(
resolver,
getPrefixHeader(),
pch.map(CxxPrecompiledHeader::getSourcePathToOutput)
.map(resolver::getRelativePath))));
return builder.build();
}
public CxxToolFlags toToolFlags(
SourcePathResolver resolver,
PathShortener pathShortener,
Function<FrameworkPath, Path> frameworkPathTransformer,
Preprocessor preprocessor,
Optional<CxxPrecompiledHeader> pch) {
return CxxToolFlags.concat(
getNonIncludePathFlags(resolver, pch, preprocessor),
getIncludePathFlags(resolver, pathShortener, frameworkPathTransformer, preprocessor));
}
}
| apache-2.0 |
infochimps-forks/ezbake-training | ds-demo-webapp/src/main/java/ezbake/training/ElasticDatasetClient.java | 6465 | /* Copyright (C) 2013-2014 Computer Sciences Corporation
*
* 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 ezbake.training;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.UUID;
import java.util.ArrayList;
import org.apache.thrift.TException;
import org.apache.thrift.TSerializer;
import org.apache.thrift.protocol.TSimpleJSONProtocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ezbake.configuration.EzConfiguration;
import ezbake.configuration.constants.EzBakePropertyConstants;
import ezbake.data.common.ThriftClient;
import ezbake.data.elastic.thrift.EzElastic;
import ezbake.data.elastic.thrift.Document;
import ezbake.data.elastic.thrift.SearchResult;
import ezbake.data.elastic.thrift.Query;
import ezbake.groups.thrift.EzGroups;
import ezbake.groups.thrift.EzGroupsConstants;
import ezbake.groups.thrift.Group;
import ezbake.security.client.EzbakeSecurityClient;
import ezbake.thrift.ThriftClientPool;
import ezbake.base.thrift.AdvancedMarkings;
import ezbake.base.thrift.EzSecurityToken;
import ezbake.base.thrift.PlatformObjectVisibilities;
import ezbake.base.thrift.Visibility;
import org.elasticsearch.index.query.QueryBuilders;
public class ElasticDatasetClient {
private static final String EZELASTIC_SERVICE_NAME = "ezelastic";
private static final String APP_NAME = "ds_demo";
private static final Logger logger = LoggerFactory
.getLogger(ElasticDatasetClient.class);
private static ElasticDatasetClient instance;
private String app_name;
private ThriftClientPool pool;
private EzbakeSecurityClient securityClient;
private ElasticDatasetClient() {
createClient();
}
public static ElasticDatasetClient getInstance() {
if (instance == null) {
instance = new ElasticDatasetClient();
}
return instance;
}
public EzElastic.Client getThriftClient() throws TException {
return pool.getClient(this.app_name, EZELASTIC_SERVICE_NAME,
EzElastic.Client.class);
}
public void close() throws Exception {
ThriftClient.close();
}
public List<String> searchText(String collectionName, String searchText)
throws TException {
EzElastic.Client elasticClient = null;
List<String> results = new ArrayList<String>();
try {
EzSecurityToken token = securityClient.fetchTokenForProxiedUser();
elasticClient = getThriftClient();
logger.info("Query EzElastic text for {}...", searchText);
final SearchResult result = elasticClient.query(new Query(
QueryBuilders.termQuery("text", searchText).toString()),
token);
for (Document doc : result.getMatchingDocuments()) {
AdvancedMarkings advanched = doc.visibility
.getAdvancedMarkings();
String am = (advanched != null) ? advanched.toString() : "N/A";
results.add(doc.get_jsonObject() + ":"
+ doc.visibility.getFormalVisibility() + ":" + am);
}
logger.info("Text search results: {}", results);
} finally {
if (elasticClient != null) {
pool.returnToPool(elasticClient);
}
}
return results;
}
public void insertText(String text, String inputVisibility, String group)
throws TException {
EzElastic.Client elasticClient = null;
EzGroups.Client groupClient = null;
try {
EzSecurityToken token = securityClient.fetchTokenForProxiedUser();
elasticClient = getThriftClient();
Tweet tweet = new Tweet();
tweet.setTimestamp(System.currentTimeMillis());
tweet.setId(0);
tweet.setText(text);
tweet.setUserId(1);
tweet.setUserName("test");
tweet.setIsFavorite(new Random().nextBoolean());
tweet.setIsRetweet(new Random().nextBoolean());
TSerializer serializer = new TSerializer(
new TSimpleJSONProtocol.Factory());
String jsonContent = serializer.toString(tweet);
final Document doc = new Document();
doc.set_id(UUID.randomUUID().toString());
doc.set_type("TEST");
doc.set_jsonObject(jsonContent);
Visibility visibility = new Visibility();
visibility.setFormalVisibility(inputVisibility);
System.out.println(group);
if (!group.equals("none")) {
groupClient = pool.getClient(EzGroupsConstants.SERVICE_NAME,
EzGroups.Client.class);
try {
Group ezgroup;
try {
EzSecurityToken groupsToken = securityClient
.fetchTokenForProxiedUser(pool
.getSecurityId(EzGroupsConstants.SERVICE_NAME));
ezgroup = groupClient.getGroup(groupsToken, group);
} catch (org.apache.thrift.transport.TTransportException e) {
throw new TException("User is not part of : " + group);
}
PlatformObjectVisibilities platformObjectVisibilities = new PlatformObjectVisibilities();
platformObjectVisibilities
.addToPlatformObjectWriteVisibility(ezgroup.getId());
platformObjectVisibilities
.addToPlatformObjectReadVisibility(ezgroup.getId());
AdvancedMarkings advancedMarkings = new AdvancedMarkings();
advancedMarkings
.setPlatformObjectVisibility(platformObjectVisibilities);
visibility.setAdvancedMarkings(advancedMarkings);
visibility.setAdvancedMarkingsIsSet(true);
} catch (TException ex) {
ex.printStackTrace();
throw ex;
}
}
doc.setVisibility(visibility);
elasticClient.put(doc, token);
logger.info("Successful elastic client insert");
} finally {
if (elasticClient != null) {
pool.returnToPool(elasticClient);
}
if (groupClient != null) {
pool.returnToPool(groupClient);
}
}
}
void createClient() {
try {
EzConfiguration configuration = new EzConfiguration();
Properties properties = configuration.getProperties();
logger.info("in createClient, configuration: {}", properties);
securityClient = new EzbakeSecurityClient(properties);
pool = new ThriftClientPool(configuration.getProperties());
this.app_name = properties.getProperty(
EzBakePropertyConstants.EZBAKE_APPLICATION_NAME, APP_NAME);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
| apache-2.0 |
skimarxall/RxFlux | rxflux/src/main/java/com/hardsoftstudio/rxflux/dispatcher/RxBus.java | 710 | package com.hardsoftstudio.rxflux.dispatcher;
import rx.Observable;
import rx.subjects.PublishSubject;
import rx.subjects.SerializedSubject;
import rx.subjects.Subject;
/**
* Rx version of an EventBus
*/
public class RxBus {
private static RxBus instance;
private final Subject<Object, Object> bus = new SerializedSubject<>(PublishSubject.create());
private RxBus() {
}
public synchronized static RxBus getInstance() {
if (instance == null) {
instance = new RxBus();
}
return instance;
}
public void send(Object o) {
bus.onNext(o);
}
public Observable<Object> get() {
return bus;
}
public boolean hasObservers() {
return bus.hasObservers();
}
}
| apache-2.0 |
Netflix/zeno | src/test/java/com/netflix/zeno/fastblob/restorescenarios/TypeC.java | 850 | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.zeno.fastblob.restorescenarios;
public class TypeC {
private final int c1;
public TypeC(int c1) {
this.c1 = c1;
}
public int getC1() {
return c1;
}
}
| apache-2.0 |
Piotr12/ppi | src/android/Echo.java | 1645 | package pl.ayground.cordova.ppi;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* This class echoes a string called from JavaScript.
*/
public class Echo extends Plugin {
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public PluginResult execute(String action, JSONArray args, String callbackId) {
try {
if (action.equals("echo")) {
//String echo = args.getString(0);
Context context=this.cordova.getActivity().getApplicationContext();
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
float xDpi = metrics.xdpi;
float yDpi = metrics.ydpi;
String echo = "X:" + xDpi +"|Y:" +yDpi;
if (echo != null && echo.length() > 0) {
return new PluginResult(PluginResult.Status.OK, echo);
} else {
return new PluginResult(PluginResult.Status.ERROR);
}
} else {
return new PluginResult(PluginResult.Status.INVALID_ACTION);
}
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
} | apache-2.0 |
AlexD1991/dobrov | ad-test/src/test/java/by/auto/test/appmanager/NavigationHelper.java | 306 | package by.auto.test.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
/**
* Created by AlexD on 3/19/2017.
*/
public class NavigationHelper extends HelperBase{
NavigationHelper(WebDriver wd){
super(wd);
}
}
| apache-2.0 |
shige0501/android_lifecycle | app/src/androidTest/java/net/buildbox/test/android_lifecycle/ApplicationTest.java | 366 | package net.buildbox.test.android_lifecycle;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/model/EnableKinesisStreamingDestinationRequest.java | 5079 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.dynamodbv2.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/EnableKinesisStreamingDestination"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class EnableKinesisStreamingDestinationRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The name of the DynamoDB table.
* </p>
*/
private String tableName;
/**
* <p>
* The ARN for a Kinesis data stream.
* </p>
*/
private String streamArn;
/**
* <p>
* The name of the DynamoDB table.
* </p>
*
* @param tableName
* The name of the DynamoDB table.
*/
public void setTableName(String tableName) {
this.tableName = tableName;
}
/**
* <p>
* The name of the DynamoDB table.
* </p>
*
* @return The name of the DynamoDB table.
*/
public String getTableName() {
return this.tableName;
}
/**
* <p>
* The name of the DynamoDB table.
* </p>
*
* @param tableName
* The name of the DynamoDB table.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public EnableKinesisStreamingDestinationRequest withTableName(String tableName) {
setTableName(tableName);
return this;
}
/**
* <p>
* The ARN for a Kinesis data stream.
* </p>
*
* @param streamArn
* The ARN for a Kinesis data stream.
*/
public void setStreamArn(String streamArn) {
this.streamArn = streamArn;
}
/**
* <p>
* The ARN for a Kinesis data stream.
* </p>
*
* @return The ARN for a Kinesis data stream.
*/
public String getStreamArn() {
return this.streamArn;
}
/**
* <p>
* The ARN for a Kinesis data stream.
* </p>
*
* @param streamArn
* The ARN for a Kinesis data stream.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public EnableKinesisStreamingDestinationRequest withStreamArn(String streamArn) {
setStreamArn(streamArn);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getTableName() != null)
sb.append("TableName: ").append(getTableName()).append(",");
if (getStreamArn() != null)
sb.append("StreamArn: ").append(getStreamArn());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof EnableKinesisStreamingDestinationRequest == false)
return false;
EnableKinesisStreamingDestinationRequest other = (EnableKinesisStreamingDestinationRequest) obj;
if (other.getTableName() == null ^ this.getTableName() == null)
return false;
if (other.getTableName() != null && other.getTableName().equals(this.getTableName()) == false)
return false;
if (other.getStreamArn() == null ^ this.getStreamArn() == null)
return false;
if (other.getStreamArn() != null && other.getStreamArn().equals(this.getStreamArn()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getTableName() == null) ? 0 : getTableName().hashCode());
hashCode = prime * hashCode + ((getStreamArn() == null) ? 0 : getStreamArn().hashCode());
return hashCode;
}
@Override
public EnableKinesisStreamingDestinationRequest clone() {
return (EnableKinesisStreamingDestinationRequest) super.clone();
}
}
| apache-2.0 |
distribuitech/datos | datos-vfs/src/main/java/com/datos/vfs/tasks/AbstractSyncTask.java | 15000 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datos.vfs.tasks;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import com.datos.vfs.FileName;
import com.datos.vfs.FileObject;
import com.datos.vfs.NameScope;
import com.datos.vfs.Selectors;
import com.datos.vfs.util.Messages;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
/**
* An abstract file synchronization task. Scans a set of source files and
* folders, and a destination folder, and performs actions on missing and
* out-of-date files. Specifically, performs actions on the following:
* <ul>
* <li>Missing destination file.
* <li>Missing source file.
* <li>Out-of-date destination file.
* <li>Up-to-date destination file.
* </ul>
*
* TODO - Deal with case where dest file maps to a child of one of the source files.<br>
* TODO - Deal with case where dest file already exists and is incorrect type (not file, not a folder).<br>
* TODO - Use visitors.<br>
* TODO - Add default excludes.<br>
* TOOD - Allow selector, mapper, filters, etc to be specified.<br>
* TODO - Handle source/dest directories as well.<br>
* TODO - Allow selector to be specified for choosing which dest files to sync.
*/
public abstract class AbstractSyncTask
extends VfsTask
{
private final ArrayList<SourceInfo> srcFiles = new ArrayList<>();
private String destFileUrl;
private String destDirUrl;
private String srcDirUrl;
private boolean srcDirIsBase;
private boolean failonerror = true;
private String filesList;
/**
* Sets the destination file.
* @param destFile The destination file name.
*/
public void setDestFile(final String destFile)
{
this.destFileUrl = destFile;
}
/**
* Sets the destination directory.
* @param destDir The destination directory.
*/
public void setDestDir(final String destDir)
{
this.destDirUrl = destDir;
}
/**
* Sets the source file.
* @param srcFile The source file name.
*/
public void setSrc(final String srcFile)
{
final SourceInfo src = new SourceInfo();
src.setFile(srcFile);
addConfiguredSrc(src);
}
/**
* Sets the source directory.
* @param srcDir The source directory.
*/
public void setSrcDir(final String srcDir)
{
this.srcDirUrl = srcDir;
}
/**
* Sets whether the source directory should be consider as the base directory.
* @param srcDirIsBase true if the source directory is the base directory.
*/
public void setSrcDirIsBase(final boolean srcDirIsBase)
{
this.srcDirIsBase = srcDirIsBase;
}
/**
* Sets whether we should fail if there was an error or not.
* @param failonerror true if the operation should fail if there is an error.
*/
public void setFailonerror(final boolean failonerror)
{
this.failonerror = failonerror;
}
/**
* Sets whether we should fail if there was an error or not.
* @return true if the operation should fail if there was an error.
*/
public boolean isFailonerror()
{
return failonerror;
}
/**
* Sets the files to includes.
* @param filesList The list of files to include.
*/
public void setIncludes(final String filesList)
{
this.filesList = filesList;
}
/**
* Adds a nested <src> element.
* @param srcInfo A nested source element.
* @throws BuildException if the SourceInfo doesn't reference a file.
*/
public void addConfiguredSrc(final SourceInfo srcInfo)
throws BuildException
{
if (srcInfo.file == null)
{
final String message = Messages.getString("vfs.tasks/sync.no-source-file.error");
throw new BuildException(message);
}
srcFiles.add(srcInfo);
}
/**
* Executes this task.
* @throws BuildException if an error occurs.
*/
@Override
public void execute() throws BuildException
{
// Validate
if (destFileUrl == null && destDirUrl == null)
{
final String message =
Messages.getString("vfs.tasks/sync.no-destination.error");
logOrDie(message, Project.MSG_WARN);
return;
}
if (destFileUrl != null && destDirUrl != null)
{
final String message =
Messages.getString("vfs.tasks/sync.too-many-destinations.error");
logOrDie(message, Project.MSG_WARN);
return;
}
// Add the files of the includes attribute to the list
if (srcDirUrl != null && !srcDirUrl.equals(destDirUrl) && filesList != null && filesList.length() > 0)
{
if (!srcDirUrl.endsWith("/"))
{
srcDirUrl += "/";
}
final StringTokenizer tok = new StringTokenizer(filesList, ", \t\n\r\f", false);
while (tok.hasMoreTokens())
{
String nextFile = tok.nextToken();
// Basic compatibility with Ant fileset for directories
if (nextFile.endsWith("/**"))
{
nextFile = nextFile.substring(0, nextFile.length() - 2);
}
final SourceInfo src = new SourceInfo();
src.setFile(srcDirUrl + nextFile);
addConfiguredSrc(src);
}
}
if (srcFiles.size() == 0)
{
final String message = Messages.getString("vfs.tasks/sync.no-source-files.warn");
logOrDie(message, Project.MSG_WARN);
return;
}
// Perform the sync
try
{
if (destFileUrl != null)
{
handleSingleFile();
}
else
{
handleFiles();
}
}
catch (final BuildException e)
{
throw e;
}
catch (final Exception e)
{
throw new BuildException(e.getMessage(), e);
}
}
protected void logOrDie(final String message, final int level)
{
if (!isFailonerror())
{
log(message, level);
return;
}
throw new BuildException(message);
}
/**
* Copies the source files to the destination.
*/
private void handleFiles() throws Exception
{
// Locate the destination folder, and make sure it exists
final FileObject destFolder = resolveFile(destDirUrl);
destFolder.createFolder();
// Locate the source files, and make sure they exist
FileName srcDirName = null;
if (srcDirUrl != null)
{
srcDirName = resolveFile(srcDirUrl).getName();
}
final ArrayList<FileObject> srcs = new ArrayList<>();
for (int i = 0; i < srcFiles.size(); i++)
{
// Locate the source file, and make sure it exists
final SourceInfo src = srcFiles.get(i);
final FileObject srcFile = resolveFile(src.file);
if (!srcFile.exists())
{
final String message =
Messages.getString("vfs.tasks/sync.src-file-no-exist.warn", srcFile);
logOrDie(message, Project.MSG_WARN);
}
else
{
srcs.add(srcFile);
}
}
// Scan the source files
final Set<FileObject> destFiles = new HashSet<>();
for (int i = 0; i < srcs.size(); i++)
{
final FileObject rootFile = srcs.get(i);
final FileName rootName = rootFile.getName();
if (rootFile.isFile())
{
// Build the destination file name
String relName = null;
if (srcDirName == null || !srcDirIsBase)
{
relName = rootName.getBaseName();
}
else
{
relName = srcDirName.getRelativeName(rootName);
}
final FileObject destFile = destFolder.resolveFile(relName, NameScope.DESCENDENT);
// Do the copy
handleFile(destFiles, rootFile, destFile);
}
else
{
// Find matching files
// If srcDirIsBase is true, select also the sub-directories
final FileObject[] files = rootFile.findFiles(srcDirIsBase
? Selectors.SELECT_ALL : Selectors.SELECT_FILES);
for (final FileObject srcFile : files)
{
// Build the destination file name
String relName = null;
if (srcDirName == null || !srcDirIsBase)
{
relName = rootName.getRelativeName(srcFile.getName());
}
else
{
relName = srcDirName.getRelativeName(srcFile.getName());
}
final FileObject destFile =
destFolder.resolveFile(relName, NameScope.DESCENDENT);
// Do the copy
handleFile(destFiles, srcFile, destFile);
}
}
}
// Scan the destination files for files with no source file
if (detectMissingSourceFiles())
{
final FileObject[] allDestFiles = destFolder.findFiles(Selectors.SELECT_FILES);
for (final FileObject destFile : allDestFiles)
{
if (!destFiles.contains(destFile))
{
handleMissingSourceFile(destFile);
}
}
}
}
/**
* Handles a single file, checking for collisions where more than one
* source file maps to the same destination file.
*/
private void handleFile(final Set<FileObject> destFiles,
final FileObject srcFile,
final FileObject destFile) throws Exception
{
// Check for duplicate source files
if (destFiles.contains(destFile))
{
final String message = Messages.getString("vfs.tasks/sync.duplicate-source-files.warn", destFile);
logOrDie(message, Project.MSG_WARN);
}
else
{
destFiles.add(destFile);
}
// Handle the file
handleFile(srcFile, destFile);
}
/**
* Copies a single file.
*/
private void handleSingleFile() throws Exception
{
// Make sure there is exactly one source file, and that it exists
// and is a file.
if (srcFiles.size() > 1)
{
final String message =
Messages.getString("vfs.tasks/sync.too-many-source-files.error");
logOrDie(message, Project.MSG_WARN);
return;
}
final SourceInfo src = srcFiles.get(0);
final FileObject srcFile = resolveFile(src.file);
if (!srcFile.isFile())
{
final String message =
Messages.getString("vfs.tasks/sync.source-not-file.error", srcFile);
logOrDie(message, Project.MSG_WARN);
return;
}
// Locate the destination file
final FileObject destFile = resolveFile(destFileUrl);
// Do the copy
handleFile(srcFile, destFile);
}
/**
* Handles a single source file.
*/
private void handleFile(final FileObject srcFile,
final FileObject destFile)
throws Exception
{
if (!destFile.exists()
|| srcFile.getContent().getLastModifiedTime() > destFile.getContent().getLastModifiedTime())
{
// Destination file is out-of-date
handleOutOfDateFile(srcFile, destFile);
}
else
{
// Destination file is up-to-date
handleUpToDateFile(srcFile, destFile);
}
}
/**
* Handles an out-of-date file.
* <p>
* This is a file where the destination file
* either doesn't exist, or is older than the source file.
* <p>
* This implementation does nothing.
*
* @param srcFile The source file.
* @param destFile The destination file.
* @throws Exception Implementation can throw any Exception.
*/
protected void handleOutOfDateFile(final FileObject srcFile,
final FileObject destFile)
throws Exception
{
}
/**
* Handles an up-to-date file.
* <p>
* This is where the destination file exists and is
* newer than the source file.
* <p>
* This implementation does nothing.
*
* @param srcFile The source file.
* @param destFile The destination file.
* @throws Exception Implementation can throw any Exception.
*/
protected void handleUpToDateFile(final FileObject srcFile,
final FileObject destFile)
throws Exception
{
}
/**
* Handles a destination for which there is no corresponding source file.
* <p>
* This implementation does nothing.
*
* @param destFile The existing destination file.
* @throws Exception Implementation can throw any Exception.
*/
protected void handleMissingSourceFile(final FileObject destFile)
throws Exception
{
}
/**
* Check if this task cares about destination files with a missing source
* file.
* <p>
* This implementation returns false.
*
* @return True if missing file is detected.
*/
protected boolean detectMissingSourceFiles()
{
return false;
}
/**
* Information about a source file.
*/
public static class SourceInfo
{
private String file;
public void setFile(final String file)
{
this.file = file;
}
}
}
| apache-2.0 |
userByHu/coolweatherbyhu | app/src/test/java/hu/learn/coolweatherbyhu/ExampleUnitTest.java | 402 | package hu.learn.coolweatherbyhu;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | apache-2.0 |
bobmcwhirter/drools | drools-process/drools-jpdl/src/main/java/org/drools/jpdl/core/JpdlConnection.java | 3539 | package org.drools.jpdl.core;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.drools.workflow.core.Node;
import org.drools.workflow.core.impl.ConnectionImpl;
import org.jbpm.graph.def.Event;
import org.jbpm.graph.def.ExceptionHandler;
public class JpdlConnection extends ConnectionImpl {
private static final long serialVersionUID = 1L;
protected String condition;
private Map<String, Event> events;
private List<ExceptionHandler> exceptionHandlers;
public JpdlConnection(Node from, String fromType, Node to, String toType) {
super(from, fromType, to, toType);
}
public Map<String, Event> getEvents() {
return events;
}
public boolean hasEvents() {
return (events != null) && (events.size() > 0);
}
public Event getEvent(String eventType) {
Event event = null;
if (events != null) {
event = (Event) events.get(eventType);
}
return event;
}
public boolean hasEvent(String eventType) {
boolean hasEvent = false;
if (events != null) {
hasEvent = events.containsKey(eventType);
}
return hasEvent;
}
public Event addEvent(Event event) {
if (event == null) {
throw new IllegalArgumentException(
"can't add a null event to a graph element");
}
if (event.getEventType() == null) {
throw new IllegalArgumentException(
"can't add an event without an eventType to a graph element");
}
if (events == null) {
events = new HashMap<String, Event>();
}
events.put(event.getEventType(), event);
return event;
}
public Event removeEvent(Event event) {
Event removedEvent = null;
if (event == null) {
throw new IllegalArgumentException(
"can't remove a null event from a graph element");
}
if (event.getEventType() == null) {
throw new IllegalArgumentException(
"can't remove an event without an eventType from a graph element");
}
if (events != null) {
removedEvent = (Event) events.remove(event.getEventType());
}
return removedEvent;
}
public List getExceptionHandlers() {
return exceptionHandlers;
}
public ExceptionHandler addExceptionHandler(ExceptionHandler exceptionHandler) {
if (exceptionHandler == null) {
throw new IllegalArgumentException(
"can't add a null exceptionHandler to a connection");
}
if (exceptionHandlers == null) {
exceptionHandlers = new ArrayList<ExceptionHandler>();
}
exceptionHandlers.add(exceptionHandler);
return exceptionHandler;
}
public void removeExceptionHandler(ExceptionHandler exceptionHandler) {
if (exceptionHandler == null) {
throw new IllegalArgumentException(
"can't remove a null exceptionHandler from a connection");
}
if (exceptionHandlers != null) {
exceptionHandlers.remove(exceptionHandler);
}
}
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
}
| apache-2.0 |
JimBarrows/JavaDomainObjects | PeopleAndOrganizations/src/main/java/jdo/party/model/communication/CommunicationEventRoleType.java | 339 | package jdo.party.model.communication;
import javax.persistence.Entity;
import jdo.model.BaseType;
/**
* @author Jim
* @version 1.0
* @created 25-Dec-2007 9:54:27 AM
* @see Data Model Resource Book Volume 1 Figure 2.12, page 60
*/
@SuppressWarnings("serial")
@Entity
public class CommunicationEventRoleType extends BaseType {
} | apache-2.0 |
WestCoastInformatics/ihtsdo-refset-tool | jpa-model/src/test/java/org/ihtsdo/otf/refset/model/ModelUnit007Test.java | 8577 | /*
* Copyright 2015 West Coast Informatics, LLC
*/
package org.ihtsdo.otf.refset.model;
import static org.junit.Assert.assertTrue;
import org.apache.log4j.Logger;
import org.ihtsdo.otf.refset.helpers.CopyConstructorTester;
import org.ihtsdo.otf.refset.helpers.EqualsHashcodeTester;
import org.ihtsdo.otf.refset.helpers.GetterSetterTester;
import org.ihtsdo.otf.refset.helpers.XmlSerializationTester;
import org.ihtsdo.otf.refset.jpa.helpers.IndexedFieldTester;
import org.ihtsdo.otf.refset.jpa.helpers.NullableFieldTester;
import org.ihtsdo.otf.refset.rf2.AssociationReferenceConceptRefSetMember;
import org.ihtsdo.otf.refset.rf2.AttributeValueConceptRefSetMember;
import org.ihtsdo.otf.refset.rf2.ComplexMapRefSetMember;
import org.ihtsdo.otf.refset.rf2.Concept;
import org.ihtsdo.otf.refset.rf2.Description;
import org.ihtsdo.otf.refset.rf2.Relationship;
import org.ihtsdo.otf.refset.rf2.SimpleMapRefSetMember;
import org.ihtsdo.otf.refset.rf2.SimpleRefSetMember;
import org.ihtsdo.otf.refset.rf2.jpa.AssociationReferenceConceptRefSetMemberJpa;
import org.ihtsdo.otf.refset.rf2.jpa.AttributeValueConceptRefSetMemberJpa;
import org.ihtsdo.otf.refset.rf2.jpa.ComplexMapRefSetMemberJpa;
import org.ihtsdo.otf.refset.rf2.jpa.ConceptJpa;
import org.ihtsdo.otf.refset.rf2.jpa.DescriptionJpa;
import org.ihtsdo.otf.refset.rf2.jpa.RelationshipJpa;
import org.ihtsdo.otf.refset.rf2.jpa.SimpleMapRefSetMemberJpa;
import org.ihtsdo.otf.refset.rf2.jpa.SimpleRefSetMemberJpa;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Unit testing for {@link ConceptJpa}.
*/
public class ModelUnit007Test {
/** The model object to test. */
private ConceptJpa object;
/**
* Setup class.
*/
@BeforeClass
public static void setupClass() {
// do nothing
}
/**
* Setup.
*/
@Before
public void setup() {
object = new ConceptJpa();
}
/**
* Test getter and setter methods of model object.
*
* @throws Exception the exception
*/
@Test
public void testModelGetSet007() throws Exception {
Logger.getLogger(getClass()).debug("TEST testModelGetSet007");
GetterSetterTester tester = new GetterSetterTester(object);
tester.test();
}
/**
* Test equals and hascode methods.
*
* @throws Exception the exception
*/
@Test
public void testModelEqualsHashcode007() throws Exception {
Logger.getLogger(getClass()).debug("TEST testModelEqualsHashcode007");
EqualsHashcodeTester tester = new EqualsHashcodeTester(object);
tester.include("active");
tester.include("moduleId");
tester.include("terminology");
tester.include("terminologyId");
tester.include("version");
tester.include("definitionStatusId");
assertTrue(tester.testIdentitiyFieldEquals());
assertTrue(tester.testNonIdentitiyFieldEquals());
assertTrue(tester.testIdentityFieldNotEquals());
assertTrue(tester.testIdentitiyFieldHashcode());
assertTrue(tester.testNonIdentitiyFieldHashcode());
assertTrue(tester.testIdentityFieldDifferentHashcode());
}
/**
* Test copy constructor.
*
* @throws Exception the exception
*/
@Test
public void testModelCopy007() throws Exception {
Logger.getLogger(getClass()).debug("TEST testModelCopy007");
CopyConstructorTester tester = new CopyConstructorTester(object);
assertTrue(tester.testCopyConstructorDeep(Concept.class));
}
/**
* Test XML serialization.
*
* @throws Exception the exception
*/
@Test
public void testModelXmlSerialization007() throws Exception {
Logger.getLogger(getClass()).debug("TEST testModelXmlTransient007");
XmlSerializationTester tester = new XmlSerializationTester(object);
assertTrue(tester.testXmlSerialization());
}
/**
* Test deep copy.
*
* @throws Exception the exception
*/
@Test
public void testModelDeepCopy007() throws Exception {
Logger.getLogger(getClass()).debug("TEST testModelDeepCopy007");
Concept c = new ConceptJpa();
c.setId(1L);
c.setTerminologyId("1");
c.setDefaultPreferredName("1");
Description d = new DescriptionJpa();
d.setId(1L);
d.setTerminologyId("1");
d.setTerm("1");
d.setTypeId("1");
d.setConcept(c);
c.addDescription(d);
Relationship r = new RelationshipJpa();
r.setId(1L);
r.setTerminologyId("1");
r.setTypeId("1");
r.setSourceConcept(c);
r.setDestinationConcept(c);
c.addRelationship(r);
AttributeValueConceptRefSetMember avmember =
new AttributeValueConceptRefSetMemberJpa();
avmember.setTerminologyId("1");
avmember.setConcept(c);
c.addAttributeValueRefSetMember(avmember);
AssociationReferenceConceptRefSetMember asmember =
new AssociationReferenceConceptRefSetMemberJpa();
asmember.setTerminologyId("1");
asmember.setConcept(c);
c.addAssociationReferenceRefSetMember(asmember);
ComplexMapRefSetMember cmmember = new ComplexMapRefSetMemberJpa();
cmmember.setTerminologyId("1");
cmmember.setConcept(c);
c.addComplexMapRefSetMember(cmmember);
SimpleRefSetMember smember = new SimpleRefSetMemberJpa();
smember.setTerminologyId("1");
smember.setConcept(c);
c.addSimpleRefSetMember(smember);
SimpleMapRefSetMember smmember = new SimpleMapRefSetMemberJpa();
smmember.setTerminologyId("1");
smmember.setConcept(c);
c.addSimpleMapRefSetMember(smmember);
// Deep copy includes simple, simple map, complex map, attribute value, and
// association reference members
Concept c3 = new ConceptJpa(c, true);
assertTrue(c3.getDescriptions().size() == 1);
assertTrue(c3.getDescriptions().iterator().next().equals(d));
assertTrue(c3.getRelationships().size() == 1);
assertTrue(c3.getRelationships().iterator().next().equals(r));
assertTrue(c.equals(c3));
assertTrue(c3.getAttributeValueRefSetMembers().size() == 1);
assertTrue(c3.getAttributeValueRefSetMembers().iterator().next()
.equals(avmember));
assertTrue(c3.getAssociationReferenceRefSetMembers().size() == 1);
assertTrue(c3.getAssociationReferenceRefSetMembers().iterator().next()
.equals(asmember));
assertTrue(c3.getComplexMapRefSetMembers().size() == 1);
assertTrue(c3.getComplexMapRefSetMembers().iterator().next()
.equals(cmmember));
assertTrue(c3.getSimpleRefSetMembers().size() == 1);
assertTrue(c3.getSimpleRefSetMembers().iterator().next().equals(smember));
assertTrue(c3.getSimpleMapRefSetMembers().size() == 1);
assertTrue(c3.getSimpleMapRefSetMembers().iterator().next()
.equals(smmember));
}
/**
* Test not null fields.
*
* @throws Exception the exception
*/
@Test
public void testModelNotNullField007() throws Exception {
Logger.getLogger(getClass()).debug("TEST testModelNotNullField007");
NullableFieldTester tester = new NullableFieldTester(object);
tester.include("lastModified");
tester.include("lastModifiedBy");
tester.include("active");
tester.include("published");
tester.include("publishable");
tester.include("moduleId");
tester.include("terminologyId");
tester.include("terminology");
tester.include("version");
tester.include("fullyDefined");
tester.include("definitionStatusId");
tester.include("anonymous");
tester.include("defaultPreferredName");
assertTrue(tester.testNotNullFields());
}
/**
* Test field indexing.
*
* @throws Exception the exception
*/
@Test
public void testModelIndexedFields007() throws Exception {
Logger.getLogger(getClass()).debug("TEST testModelIndexedFields007");
// Test analyzed fields
IndexedFieldTester tester = new IndexedFieldTester(object);
tester.include("defaultPreferredName");
assertTrue(tester.testAnalyzedIndexedFields());
// Test non analyzed fields
assertTrue(tester.testAnalyzedIndexedFields());
tester = new IndexedFieldTester(object);
tester.include("effectiveTime");
tester.include("lastModified");
tester.include("lastModifiedBy");
tester.include("moduleId");
tester.include("terminologyId");
tester.include("terminology");
tester.include("version");
tester.include("defaultPreferredNameSort");
assertTrue(tester.testNotAnalyzedIndexedFields());
}
/**
* Teardown.
*/
@After
public void teardown() {
// do nothing
}
/**
* Teardown class.
*/
@AfterClass
public static void teardownClass() {
// do nothing
}
}
| apache-2.0 |
illegalprime/exGradeSpeed | exGradeSpeed/src/com/derangementinc/gradespeedmobile/activities/GradeSheet.java | 6473 | package com.derangementinc.gradespeedmobile.activities;
import com.derangementinc.gradespeedmobile.ConnectionManager;
import com.derangementinc.gradespeedmobile.LogIn;
import com.derangementinc.gradespeedmobile.R;
import com.derangementinc.gradespeedmobile.SettingsManager;
import com.derangementinc.gradespeedmobile.adapters.SummaryAdapter;
import com.derangementinc.gradespeedmobile.enums.Errors;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
public class GradeSheet extends Activity implements OnItemClickListener {
private ListView gradeList = null;
protected ProgressDialog progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grade_sheet);
gradeList = (ListView) this.findViewById(R.id.GradesList);
SummaryAdapter adapter = new SummaryAdapter(this);
gradeList.setAdapter(adapter);
gradeList.setOnItemClickListener(this);
this.registerForContextMenu(gradeList);
}
@Override
protected void onResume() {
super.onResume();
gradeList.setAdapter(new SummaryAdapter(this));
}
@Override
public void onPause() {
super.onPause();
if (progress != null)
progress.dismiss();
progress = null;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.no_settings, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_about:
Intent about = new Intent(getBaseContext(), AboutActivity.class);
startActivity(about);
return true;
case R.id.action_switchstudents:
changeStudents();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (id == -1) {
changeStudents();
}
else {
startSpecificsActivity(position);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuinfo) {
super.onCreateContextMenu(menu, view, menuinfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.cycle_menu, menu);
// TODO: Make it obvious that users can do this.
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int position = info.position;
int order = item.getOrder();
if (position >= ConnectionManager.ShortGrades.length) {
return true;
}
if (order < 10) {
startSpecificsActivity(position, order);
}
else if (order == 100) {
// View Note
}
else if (order == 200) {
// Send email
startEmailIntent(ConnectionManager.ShortGrades[position][ConnectionManager.TEACHER_NAME][ConnectionManager.URL].substring(7));
}
return true;
}
private void startSpecificsActivity(int course, int cycleUrlIndex) {
String[][] grades = ConnectionManager.ShortGrades[course];
String description = grades[ConnectionManager.COURSE_NAME][ConnectionManager.TEXT] + " (Period " + grades[ConnectionManager.COURSE_PERIOD][ConnectionManager.TEXT].substring(0, 1) + "): " + grades[ConnectionManager.TEACHER_NAME][ConnectionManager.TEXT];
String url = grades[ConnectionManager.CURRENT_GRADE][ConnectionManager.TEXT];
if (cycleUrlIndex == ConnectionManager.CURRENT_GRADE) {
SettingsManager.account.updateGradeForCurrent(url, course);
}
getSpecifics specificsLoader = new getSpecifics();
specificsLoader.setDescription(description);
specificsLoader.execute(grades[cycleUrlIndex][ConnectionManager.URL]);
}
public void startSpecificsActivity(int course) {
startSpecificsActivity(course, ConnectionManager.CURRENT_GRADE);
}
public void startEmailIntent(String address) {
// Create the Email intent
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
// Define the email address
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{address});
// Send it off to the Activity-Chooser
startActivity(Intent.createChooser(emailIntent, "Email Teacher with..."));
}
private void changeStudents() {
if (SettingsManager.account.hasOneChild()) {
Toast.makeText(getApplicationContext(), "Could not find data about your siblings.", Toast.LENGTH_LONG).show();
}
else {
Intent logBackIn = new Intent(getBaseContext(), LogIn.class);
logBackIn.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
logBackIn.putExtra(LogIn.TAG, LogIn.SWITCH_BROS);
startActivity(logBackIn);
}
}
private class getSpecifics extends AsyncTask<String, Void, Errors> {
private String description = "";
@Override
protected void onPreExecute() {
GradeSheet.this.progress = new ProgressDialog(GradeSheet.this, ProgressDialog.STYLE_SPINNER);
progress.setMessage("Getting specifics...");
progress.show();
}
@Override
protected Errors doInBackground(String... urls) {
return ConnectionManager.getLongGrades(urls[0]);
}
@Override
protected void onPostExecute(Errors successful) {
try {
progress.dismiss();
progress = null;
}
catch (Exception err) {}
if (successful.equals(Errors.NONE)) {
Intent intent = new Intent(getBaseContext(), Specifics.class);
intent.putExtra("description", description);
startActivity(intent);
}
else {
Intent logBackIn = new Intent(GradeSheet.this.getBaseContext(), LogIn.class);
logBackIn.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
logBackIn.putExtra(LogIn.TAG, LogIn.TIMEOUT);
startActivity(logBackIn);
}
}
public void setDescription(String description) {
this.description = description;
}
}
} | apache-2.0 |
daradurvs/ignite | modules/core/src/main/java/org/apache/ignite/cache/query/SqlFieldsQuery.java | 12936 | /*
* 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.ignite.cache.query;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.internal.processors.query.QueryUtils;
import org.apache.ignite.internal.util.tostring.GridToStringInclude;
import org.apache.ignite.internal.util.typedef.internal.A;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.jetbrains.annotations.Nullable;
/**
* SQL Fields query. This query can return specific fields of data based
* on SQL {@code 'select'} clause.
* <h1 class="header">Collocated Flag</h1>
* Collocation flag is used for optimization purposes. Whenever Ignite executes
* a distributed query, it sends sub-queries to individual cluster members.
* If you know in advance that the elements of your query selection are collocated
* together on the same node, usually based on some <b>affinity-key</b>, Ignite
* can make significant performance and network optimizations.
* <p>
* For example, in case of Word-Count example, we know that all identical words
* are processed on the same cluster member, because we use the {@code word} itself
* as affinity key. This allows Ignite to execute the {@code 'limit'} clause on
* the remote nodes and bring back only the small data set specified within the 'limit' clause,
* instead of the whole query result as would happen in a non-collocated execution.
*
* @see IgniteCache#query(Query)
*/
public class SqlFieldsQuery extends Query<List<?>> {
/** */
private static final long serialVersionUID = 0L;
/** Default value of the update internal batch size. */
private static final int DFLT_UPDATE_BATCH_SIZE = 1;
/** Default value of Query timeout. Default is -1 means no timeout is set. */
private static final int DFLT_QUERY_TIMEOUT = -1;
/** Do not remove. For tests only. */
@SuppressWarnings("NonConstantFieldWithUpperCaseName")
private static boolean DFLT_LAZY;
/** SQL Query. */
private String sql;
/** Arguments. */
@GridToStringInclude
private Object[] args;
/** Collocation flag. */
private boolean collocated;
/** Query timeout in millis. */
private int timeout = DFLT_QUERY_TIMEOUT;
/** */
private boolean enforceJoinOrder;
/** */
private boolean distributedJoins;
/** */
private boolean replicatedOnly;
/** Lazy mode is default since Ignite v.2.8. */
private boolean lazy = DFLT_LAZY;
/** Partitions for query */
private int[] parts;
/** Schema. */
private String schema;
/**
* Update internal batch size. Default is 1 to prevent deadlock on update where keys sequence are different in
* several concurrent updates.
*/
private int updateBatchSize = DFLT_UPDATE_BATCH_SIZE;
/**
* Copy constructs SQL fields query.
*
* @param qry SQL query.
*/
public SqlFieldsQuery(SqlFieldsQuery qry) {
sql = qry.sql;
args = qry.args;
collocated = qry.collocated;
timeout = qry.timeout;
enforceJoinOrder = qry.enforceJoinOrder;
distributedJoins = qry.distributedJoins;
replicatedOnly = qry.replicatedOnly;
lazy = qry.lazy;
parts = qry.parts;
schema = qry.schema;
updateBatchSize = qry.updateBatchSize;
}
/**
* Constructs SQL fields query.
*
* @param sql SQL query.
*/
public SqlFieldsQuery(String sql) {
setSql(sql);
}
/**
* Constructs SQL fields query.
*
* @param sql SQL query.
* @param collocated Collocated flag.
*/
public SqlFieldsQuery(String sql, boolean collocated) {
this.sql = sql;
this.collocated = collocated;
}
/**
* Gets SQL clause.
*
* @return SQL clause.
*/
public String getSql() {
return sql;
}
/**
* Sets SQL clause.
*
* @param sql SQL clause.
* @return {@code this} For chaining.
*/
public SqlFieldsQuery setSql(String sql) {
A.notNull(sql, "sql");
this.sql = sql;
return this;
}
/**
* Gets SQL arguments.
*
* @return SQL arguments.
*/
public Object[] getArgs() {
return args;
}
/**
* Sets SQL arguments.
*
* @param args SQL arguments.
* @return {@code this} For chaining.
*/
public SqlFieldsQuery setArgs(Object... args) {
this.args = args;
return this;
}
/**
* Gets the query execution timeout in milliseconds.
*
* @return Timeout value.
*/
public int getTimeout() {
return timeout;
}
/**
* Sets the query execution timeout. Query will be automatically cancelled if the execution timeout is exceeded.
* @param timeout Timeout value. Zero value disables timeout.
* @param timeUnit Time unit.
* @return {@code this} For chaining.
*/
public SqlFieldsQuery setTimeout(int timeout, TimeUnit timeUnit) {
this.timeout = QueryUtils.validateTimeout(timeout, timeUnit);
return this;
}
/**
* Checks if this query is collocated.
*
* @return {@code true} If the query is collocated.
*/
public boolean isCollocated() {
return collocated;
}
/**
* Sets flag defining if this query is collocated.
*
* Collocation flag is used for optimization purposes of queries with GROUP BY statements.
* Whenever Ignite executes a distributed query, it sends sub-queries to individual cluster members.
* If you know in advance that the elements of your query selection are collocated together on the same node and
* you group by collocated key (primary or affinity key), then Ignite can make significant performance and network
* optimizations by grouping data on remote nodes.
*
* @param collocated Flag value.
* @return {@code this} For chaining.
*/
public SqlFieldsQuery setCollocated(boolean collocated) {
this.collocated = collocated;
return this;
}
/**
* Checks if join order of tables if enforced.
*
* @return Flag value.
*/
public boolean isEnforceJoinOrder() {
return enforceJoinOrder;
}
/**
* Sets flag to enforce join order of tables in the query. If set to {@code true}
* query optimizer will not reorder tables in join. By default is {@code false}.
* <p>
* It is not recommended to enable this property until you are sure that
* your indexes and the query itself are correct and tuned as much as possible but
* query optimizer still produces wrong join order.
*
* @param enforceJoinOrder Flag value.
* @return {@code this} For chaining.
*/
public SqlFieldsQuery setEnforceJoinOrder(boolean enforceJoinOrder) {
this.enforceJoinOrder = enforceJoinOrder;
return this;
}
/**
* Specify if distributed joins are enabled for this query.
*
* @param distributedJoins Distributed joins enabled.
* @return {@code this} For chaining.
*/
public SqlFieldsQuery setDistributedJoins(boolean distributedJoins) {
this.distributedJoins = distributedJoins;
return this;
}
/**
* Check if distributed joins are enabled for this query.
*
* @return {@code true} If distributed joins enabled.
*/
public boolean isDistributedJoins() {
return distributedJoins;
}
/** {@inheritDoc} */
@Override public SqlFieldsQuery setPageSize(int pageSize) {
return (SqlFieldsQuery)super.setPageSize(pageSize);
}
/** {@inheritDoc} */
@Override public SqlFieldsQuery setLocal(boolean loc) {
return (SqlFieldsQuery)super.setLocal(loc);
}
/**
* Specify if the query contains only replicated tables.
* This is a hint for potentially more effective execution.
*
* @param replicatedOnly The query contains only replicated tables.
* @return {@code this} For chaining.
* @deprecated No longer used as of Apache Ignite 2.8.
*/
@Deprecated
public SqlFieldsQuery setReplicatedOnly(boolean replicatedOnly) {
this.replicatedOnly = replicatedOnly;
return this;
}
/**
* Check is the query contains only replicated tables.
*
* @return {@code true} If the query contains only replicated tables.
* @deprecated No longer used as of Apache Ignite 2.8.
*/
@Deprecated
public boolean isReplicatedOnly() {
return replicatedOnly;
}
/**
* Sets lazy query execution flag.
* <p>
* By default Ignite attempts to fetch the whole query result set to memory and send it to the client. For small
* and medium result sets this provides optimal performance and minimize duration of internal database locks, thus
* increasing concurrency.
* <p>
* If result set is too big to fit in available memory this could lead to excessive GC pauses and even
* OutOfMemoryError. Use this flag as a hint for Ignite to fetch result set lazily, thus minimizing memory
* consumption at the cost of moderate performance hit.
* <p>
* Defaults to {@code false}, meaning that the whole result set is fetched to memory eagerly.
*
* @param lazy Lazy query execution flag.
* @return {@code this} For chaining.
*/
public SqlFieldsQuery setLazy(boolean lazy) {
this.lazy = lazy;
return this;
}
/**
* Gets lazy query execution flag.
* <p>
* See {@link #setLazy(boolean)} for more information.
*
* @return Lazy flag.
*/
public boolean isLazy() {
return lazy;
}
/**
* Gets partitions for query, in ascending order.
*/
@Nullable public int[] getPartitions() {
return parts;
}
/**
* Sets partitions for a query.
* The query will be executed only on nodes which are primary for specified partitions.
* <p>
* Note what passed array'll be sorted in place for performance reasons, if it wasn't sorted yet.
*
* @param parts Partitions.
* @return {@code this} for chaining.
*/
public SqlFieldsQuery setPartitions(@Nullable int... parts) {
this.parts = prepare(parts);
return this;
}
/**
* Get schema for the query.
* If not set, current cache name is used, which means you can
* omit schema name for tables within the current cache.
*
* @return Schema. Null if schema is not set.
*/
@Nullable public String getSchema() {
return schema;
}
/**
* Set schema for the query.
* If not set, current cache name is used, which means you can
* omit schema name for tables within the current cache.
*
* @param schema Schema. Null to unset schema.
* @return {@code this} for chaining.
*/
public SqlFieldsQuery setSchema(@Nullable String schema) {
this.schema = schema;
return this;
}
/**
* Gets update internal bach size.
* Default is 1 to prevent deadlock on update where keys sequence are different in
* several concurrent updates.
*
* @return Update internal batch size
*/
public int getUpdateBatchSize() {
return updateBatchSize;
}
/**
* Sets update internal bach size.
* Default is 1 to prevent deadlock on update where keys sequence are different in
* several concurrent updates.
*
* @param updateBatchSize Update internal batch size.
* @return {@code this} for chaining.
*/
public SqlFieldsQuery setUpdateBatchSize(int updateBatchSize) {
A.ensure(updateBatchSize >= 1, "updateBatchSize cannot be lower than 1");
this.updateBatchSize = updateBatchSize;
return this;
}
/**
* @return Copy of this query.
*/
public SqlFieldsQuery copy() {
return new SqlFieldsQuery(this);
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(SqlFieldsQuery.class, this);
}
}
| apache-2.0 |
oldinaction/smjava | javaee/spring/src/main/java/cn/aezo/spring/base/annotation/aop/AopConfig.java | 524 | package cn.aezo.spring.base.annotation.aop;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/**
* Created by smalle on 2017/6/3.
*/
@Configuration // java配置类
@ComponentScan("cn.aezo.spring.base.annotation.aop") // 对于没有在java配置类中声明@Bean的需要进行扫描
@EnableAspectJAutoProxy // 开启Spring对AspectJ代理的支持
public class AopConfig {
}
| apache-2.0 |
Syn-Flow/Controller | src/main/java/edu/messagetype/OFXPacketOut.java | 6514 | package edu.messagetype;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;
import org.openflow.protocol.OFMessage;
import org.openflow.protocol.OFPort;
import org.openflow.protocol.OFType;
import org.openflow.protocol.action.OFAction;
import org.openflow.protocol.factory.OFActionFactory;
import org.openflow.protocol.factory.OFActionFactoryAware;
import org.openflow.util.HexString;
import org.openflow.util.U16;
public class OFXPacketOut extends OFMessage implements OFActionFactoryAware {
public static int MINIMUM_LENGTH = 24;
public static int BUFFER_ID_NONE = 0xffffffff;
protected OFActionFactory actionFactory;
protected int bufferId;
protected int inPort;
protected short actionsLength;
protected List<OFAction> actions;
protected byte[] packetData;
public OFXPacketOut() {
super();
this.type = OFType.OFX_PACKET_OUT;
this.length = U16.t(MINIMUM_LENGTH);
}
/**
* Creates a OFXPacketOut object with the packet's data, actions, and
* bufferId
*
* @param packetData
* the packet data
* @param actions
* actions to apply to the packet
* @param bufferId
* the buffer id
*/
public OFXPacketOut(byte[] packetData, List<OFAction> actions, int bufferId) {
super();
this.type = OFType.OFX_PACKET_OUT;
this.length = U16.t(MINIMUM_LENGTH);
this.packetData = packetData;
this.actions = actions;
this.bufferId = bufferId;
}
/**
* Get buffer_id
*
* @return
*/
public int getBufferId() {
return this.bufferId;
}
/**
* Set buffer_id
*
* @param bufferId
*/
public OFXPacketOut setBufferId(int bufferId) {
if (packetData != null && packetData.length > 0
&& bufferId != BUFFER_ID_NONE) {
throw new IllegalArgumentException(
"PacketOut should not have both bufferId and packetData set");
}
this.bufferId = bufferId;
return this;
}
/**
* Returns the packet data
*
* @return
*/
public byte[] getPacketData() {
return this.packetData;
}
/**
* Sets the packet data
*
* @param packetData
*/
public OFXPacketOut setPacketData(byte[] packetData) {
if (packetData != null && packetData.length > 0
&& bufferId != BUFFER_ID_NONE) {
throw new IllegalArgumentException(
"PacketOut should not have both bufferId and packetData set");
}
this.packetData = packetData;
return this;
}
/**
* Get in_port
*
* @return
*/
public int getInPort() {
return this.inPort;
}
/**
* Set in_port
*
* @param i
*/
public OFXPacketOut setInPort(int i) {
this.inPort = i;
return this;
}
/**
* Set in_port. Convenience method using OFPort enum.
*
* @param inPort
*/
public OFXPacketOut setInPort(OFPort inPort) {
this.inPort = inPort.getValue();
return this;
}
/**
* Get actions_len
*
* @return
*/
public short getActionsLength() {
return this.actionsLength;
}
/**
* Get actions_len, unsigned
*
* @return
*/
public int getActionsLengthU() {
return U16.f(this.actionsLength);
}
/**
* Set actions_len
*
* @param actionsLength
*/
public OFXPacketOut setActionsLength(short actionsLength) {
this.actionsLength = actionsLength;
return this;
}
/**
* Returns the actions contained in this message
*
* @return a list of ordered OFAction objects
*/
public List<OFAction> getActions() {
return this.actions;
}
/**
* Sets the list of actions on this message
*
* @param actions
* a list of ordered OFAction objects
*/
public OFXPacketOut setActions(List<OFAction> actions) {
this.actions = actions;
if (actions != null) {
int l = 0;
for (OFAction action : actions)
l += action.getLength();
this.actionsLength = U16.t(l);
}
return this;
}
@Override
public void setActionFactory(OFActionFactory actionFactory) {
this.actionFactory = actionFactory;
}
@Override
public void readFrom(ByteBuffer data) {
super.readFrom(data);
this.bufferId = data.getInt();
this.inPort = data.getInt();
this.actionsLength = data.getShort();
data.position(data.position() + 6);
if (this.actionFactory == null)
throw new RuntimeException("ActionFactory not set");
this.actions = this.actionFactory.parseActions(data,
getActionsLengthU());
this.packetData = new byte[getLengthU() - MINIMUM_LENGTH
- getActionsLengthU()];
data.get(this.packetData);
}
@Override
public void writeTo(ByteBuffer data) {
super.writeTo(data);
data.putInt(bufferId);
data.putInt(inPort);
data.putShort(actionsLength);
for (int i = 0; i < 6; i++)
data.put((byte) 0); // pad
for (OFAction action : actions) {
action.writeTo(data);
}
if (this.packetData != null)
data.put(this.packetData);
}
@Override
public int hashCode() {
final int prime = this.getClass().getSimpleName().hashCode();
int result = super.hashCode();
result = prime * result + ((actions == null) ? 0 : actions.hashCode());
result = prime * result + actionsLength;
result = prime * result + bufferId;
result = prime * result + inPort;
result = prime * result + Arrays.hashCode(packetData);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (!(obj instanceof OFXPacketOut)) {
return false;
}
OFXPacketOut other = (OFXPacketOut) obj;
if (actions == null) {
if (other.actions != null) {
return false;
}
} else if (!actions.equals(other.actions)) {
return false;
}
if (actionsLength != other.actionsLength) {
return false;
}
if (bufferId != other.bufferId) {
return false;
}
if (inPort != other.inPort) {
return false;
}
if (!Arrays.equals(packetData, other.packetData)) {
return false;
}
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "OFXPacketOut [actions=" + actions + ", actionsLength="
+ actionsLength + ", bufferId=0x"
+ Integer.toHexString(bufferId) + ", inPort=" + inPort
+ ", packetData=" + HexString.toHexString(packetData) + "]";
}
/*
* (non-Javadoc)
*
* @see org.openflow.protocol.OFMessage#computeLength()
*/
@Override
public void computeLength() {
int l = MINIMUM_LENGTH + ((packetData != null) ? packetData.length : 0);
int al = 0;
if (actions != null) {
for (OFAction action : actions) {
al += action.getLengthU();
}
}
this.length = U16.t(l + al);
this.actionsLength = U16.t(al);
}
}
| apache-2.0 |
bobmcwhirter/drools | drools-compiler/src/main/java/org/drools/guvnor/client/modeldriven/testing/ExecutionTrace.java | 779 | package org.drools.guvnor.client.modeldriven.testing;
import java.util.Date;
/**
* This contains lists of rules to include in the scenario (or exclude, as the case may be !).
* This will be used to filter the rule engines behaviour under test.
* @author Michael Neale
*/
public class ExecutionTrace implements Fixture {
/**
* This is the simulated date - leaving it as null means it will use
* the current time.
*/
public Date scenarioSimulatedDate = null;
/**
* The time taken for execution.
*/
public Long executionTimeResult;
/**
* This is pretty obvious really. The total firing count of all rules.
*/
public Long numberOfRulesFired;
/**
* A summary of the rules fired.
*/
public String[] rulesFired;
public ExecutionTrace() {}
}
| apache-2.0 |
bchristoph/FlatSQL | src/database/FlatSQL.java | 8122 | /**
*
*/
package database;
import java.util.ArrayList;
/**
* @author Bastian Christoph
*
* This is a SQL helper class and basically designed in order
* to simplify the SQL notation.
*
* The fact should not be changed, that the SQL formulation is
* kept as flat as possible with a low degree of abstraction
* in order to develop effective methods for bottleneck-identification
* and performance-improvements for database-related applications.
*
* Using the padding character '_' in the names we want to ensure
* intuitive formatting- alignment in the notation.
*
* Intuitively the SQL-clauses should be expandable over IDE-recommendation
*
*/
public class FlatSQL {
ArrayList<String> transactionStmtList = new ArrayList<String>();
/*
* specific:
* - Join, Project
* - SELECT ... FROM ...
*/
public String SELECT_______;
public String INTO_________;
public String FROM_________;
/*
* specific:
* - Used table, Table fields
* - INSERT INTO ... ( ... ) VALUES ...
* - UPDATE ... SET ... WHERE ...
*/
public String INSERT_INTO__;
public String VALUES_______;
public ArrayList<Long[]> VALUES_BATCH_ = new ArrayList<Long[]>();
public String UPDATE_______;
public String SET__________;
/*
* specific:
* - TRUNCATE ...
* - DELETE FROM ... WHERE ...
*/
public String TRUNCATE_____;
public String DELETE_______;
/*
* - ALTER TABLE ...
* - LOCK TABLE ...
* - UNLOCK TABLE ...
*/
public String ALTER_TABLE__;
public String LOCK_TABLES__;
/*
* general:
* - Select (Set-Field-Value, Set-Field-Ordering, Set-Count)
* - WHERE ...
* - GROUP BY ...
* - HAVING ...
*/
public String WHERE________;
public String GROUP_BY_____;
public String HAVING_______;
public String ORDER_BY_____;
public String LIMIT________;
public FlatSQL() {
this.clearTransactionList();
this.clear();
}
public void clearTransactionList() {
this.transactionStmtList.clear();
}
public void clear() {
this.SELECT_______ = "";
this.INTO_________ = "";
this.FROM_________ = "";
this.WHERE________ = "";
this.GROUP_BY_____ = "";
this.HAVING_______ = "";
this.ORDER_BY_____ = "";
this.LIMIT________ = "";
this.INSERT_INTO__ = "";
this.VALUES_______ = "";
this.UPDATE_______ = "";
this.SET__________ = "";
this.TRUNCATE_____ = "";
this.DELETE_______ = "";
this.ALTER_TABLE__ = "";
this.LOCK_TABLES__ = "";
}
public String filter_num(String aliasBase, String filterAlias, String filterField, int fieldValue) {
// this.qSQL.UPDATE_______ += "JOIN (SELECT " + webRessourceID + " AS WebressourceID) AS Q1 ";
// this.qSQL.UPDATE_______ += "ON (UTIP.WebRessourceID = Q1.WebRessourceID) ";
// --> this.qSQL.UPDATE_______ += this.qSQL.filter_num("UTIP", "Q1", "WebressourceID", webRessourceID);
// --> replaces: WHERE WebressourceID = <WebressourceID>
// --> moved to FROM / UPDATE clause
// this.qSQL.UPDATE_______ += "JOIN (SELECT 1 AS leafPredicted) AS Q2 ";
// this.qSQL.UPDATE_______ += "ON (UTIP.leafPredicted = Q2.leafPredicted) ";
// --> this.qSQL.UPDATE_______ += this.qSQL.filter_num("UTIP", "Q2", "leafPredicted", 1);
// --> replaces: WHERE leafPredicted = 1
// --> moved to FROM / UPDATE clause
String filterJoin = "";
filterJoin += "JOIN (SELECT "+fieldValue+" AS "+filterField+") AS "+filterAlias+" ";
filterJoin += "ON (";
filterJoin += aliasBase+"."+filterField+" = "+filterAlias+"."+filterField;
filterJoin += ") ";
return filterJoin;
}
public String filter_str(String aliasBase, String filterAlias, String filterField, String fieldValue) {
String filterJoin = "";
filterJoin += "JOIN (SELECT '"+fieldValue+"' AS "+filterField+") AS "+filterAlias+" ";
filterJoin += "ON (";
filterJoin += aliasBase+"."+filterField+" = "+filterAlias+"."+filterField;
filterJoin += ") ";
return filterJoin;
}
public String toSqlString() {
String sql = "";
if(this.INSERT_INTO__.compareTo("") != 0) {
sql += "INSERT INTO " + this.INSERT_INTO__ + " " + "\n";
if(this.VALUES_______.compareTo("") != 0) {
sql += "VALUES ";
sql += "(";
sql += this.VALUES_______;
sql += ")";
} else if(this.VALUES_BATCH_.size() > 1) {
sql += "VALUES ";
for(int i=0; i<this.VALUES_BATCH_.size()-1; i++) {
Long[] dataSet = this.VALUES_BATCH_.get(i);
sql += "(";
if(dataSet.length > 1) {
for(int j=0; j<dataSet.length-1; j++) {
sql += dataSet[j] + ", ";
}
sql += dataSet[dataSet.length-1];
} else {
sql += dataSet[dataSet.length-1];
}
sql += "), ";
}
Long[] dataSet = this.VALUES_BATCH_.get( this.VALUES_BATCH_.size()-1 );
sql += "(";
if(dataSet.length > 1) {
for(int j=0; j<dataSet.length-1; j++) {
sql += dataSet[j] + ", ";
}
sql += dataSet[dataSet.length-1];
} else {
sql += dataSet[dataSet.length-1];
}
sql += ")";
} else if(this.VALUES_BATCH_.size() == 1) {
sql += "VALUES ";
Long[] dataSet = this.VALUES_BATCH_.get(0);
sql += "(";
if(dataSet.length > 1) {
for(int j=0; j<dataSet.length-1; j++) {
sql += dataSet[j] + ", ";
}
sql += dataSet[dataSet.length-1];
} else {
sql += dataSet[dataSet.length-1];
}
sql += ")";
}
}
if(this.SELECT_______.compareTo("") != 0) {
sql += "SELECT " + this.SELECT_______ + " " + "\n";
/*
* SELECT t1.field1, t1.field2
* INTO @variable1, @variable2
* ( FROM table t1 )
*/
if(this.INTO_________.compareTo("") != 0) {
sql += "INTO " + this.INTO_________ + " " + "\n";
}
if(this.FROM_________.compareTo("") != 0) {
sql += "FROM " + this.FROM_________ + " " + "\n";
// } else {
// System.out.println("Error: Wrong Sql Statement");
// System.exit(1);
}
if(this.WHERE________.compareTo("") != 0) {
sql += "WHERE " + this.WHERE________ + " " + "\n";
}
if(this.GROUP_BY_____.compareTo("") != 0) {
sql += "GROUP BY " + this.GROUP_BY_____ + " " + "\n";
}
if(this.HAVING_______.compareTo("") != 0) {
sql += "HAVING " + this.HAVING_______ + " " + "\n";
}
if(this.ORDER_BY_____.compareTo("") != 0) {
sql += "ORDER BY " + this.ORDER_BY_____ + " " + "\n";
}
if(this.LIMIT________.compareTo("") != 0) {
sql += "LIMIT " + this.LIMIT________ + " " + "\n";
}
}
if(this.UPDATE_______.compareTo("") != 0) {
sql += "UPDATE " + this.UPDATE_______ + " " + "\n";
sql += "SET " + this.SET__________ + " " + "\n";
if(this.WHERE________.compareTo("") != 0) {
sql += "WHERE " + this.WHERE________ + " " + "\n";
}
}
if(this.TRUNCATE_____.compareTo("") != 0) {
sql += "TRUNCATE TABLE " + this.TRUNCATE_____ + " " + "\n";
}
if(this.ALTER_TABLE__.compareTo("") != 0) {
sql += "ALTER TABLE " + this.ALTER_TABLE__ + " " + "\n";
}
if(this.LOCK_TABLES__.compareTo("") != 0) {
sql += "LOCK TABLES " + this.LOCK_TABLES__ + " " + "\n";
}
if(this.DELETE_______.compareTo("") != 0) {
sql += "DELETE " + this.DELETE_______ + " " + "\n";
if(this.FROM_________.compareTo("") != 0) {
sql += "FROM " + this.FROM_________ + " " + "\n";
}
if(this.WHERE________.compareTo("") != 0) {
sql += "WHERE " + this.WHERE________ + " " + "\n";
}
}
if( (sql.compareTo("") == 0) && (this.transactionStmtList.size() > 0) ) {
for(int i=0; i<this.transactionStmtList.size(); i++) {
sql += this.transactionStmtList.get(i);
}
}
return sql;
}
public void addTransactionStmt() {
String sql = this.toSqlString();
this.transactionStmtList.add(sql + ";");
this.clear();
}
public ArrayList<String> getTransactionStmtList() {
return this.transactionStmtList;
}
}
| apache-2.0 |
djsilenceboy/LearnTest | Java_Learn/LearnDesignPattern/src/com/djs/learn/behavioral/chainOfResponsibility/AbstractHandlerTypeB.java | 201 |
package com.djs.learn.behavioral.chainOfResponsibility;
abstract class AbstractHandlerTypeB implements HandlerTypeBInterface
{
String name;
@Override
public String getName(){
return name;
}
}
| apache-2.0 |
wxb2939/rwxlicai | mzb-phone-app-android/MzbCustomerApp/src/main/java/com/xem/mzbcustomerapp/entity/GroupsData.java | 1021 | package com.xem.mzbcustomerapp.entity;
import java.io.Serializable;
/**
* Created by xuebing on 15/11/5.
*/
public class GroupsData implements Serializable {
// data:获取成功[{groupid:1,name:“面部套餐”,pic:“http://xx/xx”,price:150}]
// groupid:套餐id
// name:套餐名称
// pic:套餐图片
// price:套餐价
private String groupid;
private String name;
private String pic;
private String price;
public String getGroupid() {
return groupid;
}
public void setGroupid(String groupid) {
this.groupid = groupid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
| apache-2.0 |
everit-org/eosgi-e4-plugin | plugin/src/main/java/org/everit/osgi/dev/e4/plugin/ui/command/DebugCommandHandler.java | 1380 | /*
* Copyright (C) 2011 Everit Kft. (http://www.everit.org)
*
* 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.everit.osgi.dev.e4.plugin.ui.command;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.debug.core.ILaunchManager;
/**
* Command handler that launches an OSGi environment.
*
*/
public class DebugCommandHandler extends AbstractHandler {
@Override
public Object execute(final ExecutionEvent event) throws ExecutionException {
CommandUtil.executeInJobWithErrorHandling(event, "Launching OSGi Enviroment in debug mode",
(executableEnvironment, monitor) -> executableEnvironment.getEOSGiProject().launch(
executableEnvironment, ILaunchManager.DEBUG_MODE, monitor));
return null;
}
}
| apache-2.0 |
Shunika/java_tutorial1 | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbok/ContactCreationTest.java | 416 | package ru.stqa.pft.addressbok;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbok.tests.TestBase;
public class ContactCreationTest extends TestBase{
@Test
public void testContactCreation() {
goToAddNewContact();
fillContactForm(new ContactData("1name", "mname", "lname", "testcompany", "test street"));
submitContactCreation();
goToHomePage();
}
}
| apache-2.0 |
IWSDevelopers/iws | iws-ejb/src/main/java/net/iaeste/iws/ejb/CommitteeBean.java | 9764 | /*
* Licensed to IAESTE A.s.b.l. (IAESTE) under one or more contributor
* license agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership. The Authors
* (See the AUTHORS file distributed with this work) 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 net.iaeste.iws.ejb;
import net.iaeste.iws.api.Committees;
import net.iaeste.iws.api.constants.IWSErrors;
import net.iaeste.iws.api.dtos.AuthenticationToken;
import net.iaeste.iws.api.requests.CommitteeRequest;
import net.iaeste.iws.api.requests.FetchCommitteeRequest;
import net.iaeste.iws.api.requests.FetchInternationalGroupRequest;
import net.iaeste.iws.api.requests.FetchCountrySurveyRequest;
import net.iaeste.iws.api.requests.InternationalGroupRequest;
import net.iaeste.iws.api.requests.CountrySurveyRequest;
import net.iaeste.iws.api.responses.CommitteeResponse;
import net.iaeste.iws.api.responses.Response;
import net.iaeste.iws.api.responses.FetchCommitteeResponse;
import net.iaeste.iws.api.responses.FetchInternationalGroupResponse;
import net.iaeste.iws.api.responses.FetchCountrySurveyResponse;
import net.iaeste.iws.common.configuration.Settings;
import net.iaeste.iws.core.CommitteeController;
import net.iaeste.iws.core.notifications.Notifications;
import net.iaeste.iws.core.services.ServiceFactory;
import net.iaeste.iws.ejb.cdi.IWSBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.inject.Inject;
import javax.persistence.EntityManager;
/**
* Committee Bean, serves as the default EJB for the IWS Committee interface.
* It uses JNDI instances for the Persistence Context and the Notification
* Manager Bean.<br />
* The default implemenentation will catch any uncaught Exception. However,
* there are some types of Exceptions that should be handled by the Contained,
* and not by our error handling. Thus, only Runtime exceptions are caught. If
* a Checked Exception is discovered that also needs our attention, then the
* error handling must be extended to also deal with this. But for now, this
* should suffice.
*
* @author Kim Jensen / last $Author:$
* @version $Revision:$ / $Date:$
* @since IWS 1.0
*/
@Stateless
@Remote(Committees.class)
@TransactionAttribute(TransactionAttributeType.REQUIRED)
@TransactionManagement(TransactionManagementType.CONTAINER)
public class CommitteeBean implements Committees {
private static final Logger LOG = LoggerFactory.getLogger(CommitteeBean.class);
@Inject @IWSBean private EntityManager entityManager;
@Inject @IWSBean private Notifications notifications;
@Inject @IWSBean private SessionRequestBean session;
@Inject @IWSBean private Settings settings;
private Committees controller = null;
/**
* Setter for the JNDI injected persistence context. This allows us to also
* test the code, by invoking these setters on the instantiated Object.
*
* @param entityManager Transactional Entity Manager instance
*/
public void setEntityManager(final EntityManager entityManager) {
this.entityManager = entityManager;
}
/**
* Setter for the JNDI injected notification bean. This allows us to also
* test the code, by invoking these setters on the instantited Object.
*
* @param notificationManager Notification Manager Bean
*/
public void setNotificationManager(final NotificationManager notificationManager) {
this.notifications = notificationManager;
}
/**
* Setter for the JNDI injected Session Request bean. This allows us to also
* test the code, by invoking these setters on the instantiated Object.
*
* @param sessionRequestBean Session Request Bean
*/
public void setSessionRequestBean(final SessionRequestBean sessionRequestBean) {
this.session = sessionRequestBean;
}
/**
* Setter for the JNDI injected Settings bean. This allows us to also test
* the code, by invoking these setters on the instantiated Object.
*
* @param settings Settings Bean
*/
public void setSettings(final Settings settings) {
this.settings = settings;
}
@PostConstruct
public void postConstruct() {
final ServiceFactory factory = new ServiceFactory(entityManager, notifications, settings);
controller = new CommitteeController(factory);
}
// =========================================================================
// Implementation of methods from Committees in the API
// =========================================================================
/**
* {@inheritDoc}
*/
@Override
public FetchCommitteeResponse fetchCommittees(final AuthenticationToken token, final FetchCommitteeRequest request) {
final long start = System.nanoTime();
FetchCommitteeResponse response;
try {
response = controller.fetchCommittees(token, request);
LOG.info(session.generateLogAndUpdateSession("fetchCommittees", start, response, token));
} catch (RuntimeException e) {
LOG.error(session.generateLogAndSaveRequest("fetchCommittees", start, e, token, request), e);
response = new FetchCommitteeResponse(IWSErrors.ERROR, e.getMessage());
}
return response;
}
/**
* {@inheritDoc}
*/
@Override
public CommitteeResponse processCommittee(final AuthenticationToken token, final CommitteeRequest request) {
final long start = System.nanoTime();
CommitteeResponse response;
try {
response = controller.processCommittee(token, request);
LOG.info(session.generateLogAndUpdateSession("processCommittee", start, response, token));
} catch (RuntimeException e) {
LOG.error(session.generateLogAndSaveRequest("processCommittee", start, e, token, request), e);
response = new CommitteeResponse(IWSErrors.ERROR, e.getMessage());
}
return response;
}
/**
* {@inheritDoc}
*/
@Override
public FetchInternationalGroupResponse fetchInternationalGroups(final AuthenticationToken token, final FetchInternationalGroupRequest request) {
final long start = System.nanoTime();
FetchInternationalGroupResponse response;
try {
response = controller.fetchInternationalGroups(token, request);
LOG.info(session.generateLogAndUpdateSession("fetchInternationalGroups", start, response, token));
} catch (RuntimeException e) {
LOG.error(session.generateLogAndSaveRequest("fetchInternationalGroups", start, e, token, request), e);
response = new FetchInternationalGroupResponse(IWSErrors.ERROR, e.getMessage());
}
return response;
}
/**
* {@inheritDoc}
*/
@Override
public Response processInternationalGroup(final AuthenticationToken token, final InternationalGroupRequest request) {
final long start = System.nanoTime();
Response response;
try {
response = controller.processInternationalGroup(token, request);
LOG.info(session.generateLogAndUpdateSession("processInternationalGroup", start, response, token));
} catch (RuntimeException e) {
LOG.error(session.generateLogAndSaveRequest("processInternationalGroup", start, e, token, request), e);
response = new Response(IWSErrors.ERROR, e.getMessage());
}
return response;
}
/**
* {@inheritDoc}
*/
@Override
public FetchCountrySurveyResponse fetchCountrySurvey(final AuthenticationToken token, final FetchCountrySurveyRequest request) {
final long start = System.nanoTime();
FetchCountrySurveyResponse response;
try {
response = controller.fetchCountrySurvey(token, request);
LOG.info(session.generateLogAndUpdateSession("fetchCountrySurvey", start, response, token));
} catch (RuntimeException e) {
LOG.error(session.generateLogAndSaveRequest("fetchCountrySurvey", start, e, token, request), e);
response = new FetchCountrySurveyResponse(IWSErrors.ERROR, e.getMessage());
}
return response;
}
/**
* {@inheritDoc}
*/
@Override
public Response processCountrySurvey(final AuthenticationToken token, final CountrySurveyRequest request) {
final long start = System.nanoTime();
Response response;
try {
response = controller.processCountrySurvey(token, request);
LOG.info(session.generateLogAndUpdateSession("processCountrySurvey", start, response, token));
} catch (RuntimeException e) {
LOG.error(session.generateLogAndSaveRequest("processCountrySurvey", start, e, token, request), e);
response = new Response(IWSErrors.ERROR, e.getMessage());
}
return response;
}
}
| apache-2.0 |
aosp-mirror/platform_frameworks_support | recyclerview-selection/src/androidTest/java/androidx/recyclerview/selection/testing/TestOnItemActivatedListener.java | 1266 | /*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.recyclerview.selection.testing;
import static org.junit.Assert.assertEquals;
import android.view.MotionEvent;
import androidx.recyclerview.selection.ItemDetailsLookup.ItemDetails;
import androidx.recyclerview.selection.OnItemActivatedListener;
public final class TestOnItemActivatedListener<K> implements OnItemActivatedListener<K> {
private ItemDetails<K> mActivated;
@Override
public boolean onItemActivated(ItemDetails<K> item, MotionEvent e) {
mActivated = item;
return true;
}
public void assertActivated(ItemDetails<K> expected) {
assertEquals(expected, mActivated);
}
}
| apache-2.0 |
hurricup/intellij-community | platform/platform-impl/src/org/jetbrains/io/BuiltInServer.java | 7419 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.io;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ExceptionUtil;
import com.intellij.util.NotNullProducer;
import com.intellij.util.SystemProperties;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.oio.OioEventLoopGroup;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Random;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
public class BuiltInServer implements Disposable {
// Some antiviral software detect viruses by the fact of accessing these ports so we should not touch them to appear innocent.
private static final int[] FORBIDDEN_PORTS = {6953, 6969, 6970};
private final EventLoopGroup eventLoopGroup;
private final int port;
private final ChannelRegistrar channelRegistrar;
static {
// IDEA-120811
if (SystemProperties.getBooleanProperty("io.netty.random.id", true)) {
System.setProperty("io.netty.machineId", "9e43d860");
System.setProperty("io.netty.processId", Integer.toString(new Random().nextInt(65535)));
System.setProperty("io.netty.serviceThreadPrefix", "Netty ");
}
}
private BuiltInServer(@NotNull EventLoopGroup eventLoopGroup,
int port,
@NotNull ChannelRegistrar channelRegistrar) {
this.eventLoopGroup = eventLoopGroup;
this.port = port;
this.channelRegistrar = channelRegistrar;
}
@NotNull
public EventLoopGroup getEventLoopGroup() {
return eventLoopGroup;
}
public int getPort() {
return port;
}
public boolean isRunning() {
return !channelRegistrar.isEmpty();
}
@Override
public void dispose() {
channelRegistrar.close();
Logger.getInstance(BuiltInServer.class).info("web server stopped");
}
@NotNull
public static BuiltInServer start(int workerCount,
int firstPort,
int portsCount,
boolean tryAnyPort,
@Nullable NotNullProducer<ChannelHandler> handler) throws Exception {
return start(new NioEventLoopGroup(workerCount, new BuiltInServerThreadFactory()), true, firstPort, portsCount, tryAnyPort, handler);
}
@NotNull
public static BuiltInServer startNioOrOio(int workerCount,
int firstPort,
int portsCount,
boolean tryAnyPort,
@Nullable NotNullProducer<ChannelHandler> handler) throws Exception {
BuiltInServerThreadFactory threadFactory = new BuiltInServerThreadFactory();
NioEventLoopGroup nioEventLoopGroup;
try {
nioEventLoopGroup = new NioEventLoopGroup(workerCount, threadFactory);
}
catch (IllegalStateException e) {
Logger.getInstance(BuiltInServer.class).warn(e);
return start(new OioEventLoopGroup(1, threadFactory), true, 6942, 50, false, handler);
}
return start(nioEventLoopGroup, true, firstPort, portsCount, tryAnyPort, handler);
}
@NotNull
public static BuiltInServer start(@NotNull EventLoopGroup eventLoopGroup,
boolean isEventLoopGroupOwner,
int firstPort,
int portsCount,
boolean tryAnyPort,
@Nullable NotNullProducer<ChannelHandler> handler) throws Exception {
ChannelRegistrar channelRegistrar = new ChannelRegistrar();
ServerBootstrap bootstrap = NettyKt.serverBootstrap(eventLoopGroup);
configureChildHandler(bootstrap, channelRegistrar, handler);
int port = bind(firstPort, portsCount, tryAnyPort, bootstrap, channelRegistrar, isEventLoopGroupOwner);
return new BuiltInServer(eventLoopGroup, port, channelRegistrar);
}
static void configureChildHandler(@NotNull ServerBootstrap bootstrap,
@NotNull final ChannelRegistrar channelRegistrar,
@Nullable final NotNullProducer<ChannelHandler> channelHandler) {
final PortUnificationServerHandler portUnificationServerHandler = channelHandler == null ? new PortUnificationServerHandler() : null;
bootstrap.childHandler(new ChannelInitializer() {
@Override
protected void initChannel(@NotNull Channel channel) throws Exception {
channel.pipeline().addLast(channelRegistrar, channelHandler == null ? portUnificationServerHandler : channelHandler.produce());
}
});
}
private static int bind(int firstPort,
int portsCount,
boolean tryAnyPort,
@NotNull ServerBootstrap bootstrap,
@NotNull ChannelRegistrar channelRegistrar,
boolean isEventLoopGroupOwner) throws Exception {
InetAddress address = InetAddress.getLoopbackAddress();
for (int i = 0; i < portsCount; i++) {
int port = firstPort + i;
if (ArrayUtil.indexOf(FORBIDDEN_PORTS, i) >= 0) {
continue;
}
ChannelFuture future = bootstrap.bind(address, port).awaitUninterruptibly();
if (future.isSuccess()) {
channelRegistrar.setServerChannel(future.channel(), isEventLoopGroupOwner);
return port;
}
else if (!tryAnyPort && i == portsCount - 1) {
ExceptionUtil.rethrowAll(future.cause());
}
}
Logger.getInstance(BuiltInServer.class).info("We cannot bind to our default range, so, try to bind to any free port");
ChannelFuture future = bootstrap.bind(address, 0).awaitUninterruptibly();
if (future.isSuccess()) {
channelRegistrar.setServerChannel(future.channel(), isEventLoopGroupOwner);
return ((InetSocketAddress)future.channel().localAddress()).getPort();
}
ExceptionUtil.rethrowAll(future.cause());
return -1; // unreachable
}
public static void replaceDefaultHandler(@NotNull ChannelHandlerContext context, @NotNull ChannelHandler channelHandler) {
context.pipeline().replace(DelegatingHttpRequestHandler.class, "replacedDefaultHandler", channelHandler);
}
private static class BuiltInServerThreadFactory implements ThreadFactory {
private final AtomicInteger counter = new AtomicInteger();
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "Netty Builtin Server " + counter.incrementAndGet());
}
}
} | apache-2.0 |
aalmiray/griffon2 | samples/sample-javafx-java/griffon-app/models/sample/javafx/java/SampleModel.java | 2382 | /*
* Copyright 2008-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.javafx.java;
import griffon.core.GriffonApplication;
import griffon.core.artifact.GriffonModel;
import griffon.metadata.ArtifactProviderFor;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import org.codehaus.griffon.runtime.core.artifact.AbstractGriffonModel;
import javax.annotation.Nonnull;
import javax.inject.Inject;
@ArtifactProviderFor(GriffonModel.class)
public class SampleModel extends AbstractGriffonModel {
private StringProperty input; //<1>
private StringProperty output; //<1>
@Inject
public SampleModel(@Nonnull GriffonApplication application) {
super(application);
}
@Nonnull
public final StringProperty inputProperty() { //<2>
if (input == null) {
input = new SimpleStringProperty(this, "input");
}
return input;
}
public void setInput(String input) { //<3>
inputProperty().set(input);
}
public String getInput() { //<3>
return input == null ? null : inputProperty().get();
}
@Nonnull
public final StringProperty outputProperty() { //<2>
if (output == null) {
output = new SimpleStringProperty(this, "output");
}
return output;
}
public void setOutput(String output) { //<3>
outputProperty().set(output);
}
public String getOutput() { //<3>
return output == null ? null : outputProperty().get();
}
}
| apache-2.0 |
flitte/Gaffer | gaffer-core/function/src/main/java/gaffer/function/processor/Processor.java | 3115 | /*
* Copyright 2016 Crown Copyright
*
* 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 gaffer.function.processor;
import gaffer.function.context.FunctionContext;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
/**
* A <code>Processor</code> executes {@link gaffer.function.Function}s against {@link gaffer.function.Tuple}s. It
* uses {@link gaffer.function.context.FunctionContext}s to bind functions to data in tuples.
*
* @param <R> The type of reference used by tuples.
* @param <C> The type of {@link FunctionContext} to use.
*/
public abstract class Processor<R, C extends FunctionContext<?>> implements Cloneable {
protected List<C> functions;
/**
* Default constructor - used for serialisation.
*/
public Processor() {
}
/**
* Create a <code>Processor</code> that executes the given {@link gaffer.function.context.FunctionContext}s.
*
* @param functions {@link gaffer.function.context.FunctionContext}s to execute.
*/
public Processor(final Collection<C> functions) {
addFunctions(functions);
}
/**
* Add a {@link gaffer.function.context.FunctionContext} to be executed by this <code>Processor</code>.
*
* @param functionContext {@link gaffer.function.context.FunctionContext} to be executed.
*/
public void addFunction(final C functionContext) {
if (functions == null) {
functions = new LinkedList<>();
}
functions.add(functionContext);
}
/**
* Add a collection of {@link gaffer.function.context.FunctionContext}s to be executed by this
* <code>Processor</code>.
*
* @param functionContext {@link gaffer.function.context.FunctionContext}s to be executed.
*/
public void addFunctions(final Collection<C> functionContext) {
if (functions == null) {
functions = new LinkedList<>();
}
functions.addAll(functionContext);
}
/**
* @return {@link gaffer.function.context.FunctionContext}s to be executed by this <code>Processor</code>.
*/
public List<C> getFunctions() {
return functions;
}
/**
* @return Deep copy of this <code>Processor</code>.
*/
@SuppressWarnings("CloneDoesntDeclareCloneNotSupportedException")
public abstract Processor<R, C> clone();
/**
* @param functions {@link gaffer.function.context.FunctionContext}s to be executed by this <code>Processor</code>.
*/
void setFunctions(final List<C> functions) {
this.functions = functions;
}
}
| apache-2.0 |
caris/OSCAR-js | oscarexchange4j/src/test/java/com/caris/oscarexchange4j/proxy/TestResponse.java | 1090 | /**
* CARIS oscar - Open Spatial Component ARchitecture
*
* Copyright 2016 CARIS <http://www.caris.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.caris.oscarexchange4j.proxy;
import org.junit.Test;
import junit.framework.TestCase;
public class TestResponse extends TestCase {
/**
* Test the setFilename method and make sure
* it returns correctly.
*/
@Test
public void testSetFilename() {
Response r = new Response();
r.setFilename("Buildings.gml");
String filename = r.getFilename();
assertTrue(filename.equals("Buildings.gml"));
}
}
| apache-2.0 |
llarreta/larretasources | Commons/src/main/java/ar/com/larreta/commons/utils/iterators/IterableProperties.java | 874 | package ar.com.larreta.commons.utils.iterators;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;
import ar.com.larreta.commons.AppObject;
import ar.com.larreta.commons.AppObjectImpl;
public class IterableProperties extends Properties implements Iterator{
private AppObject appObject = new AppObjectImpl(getClass());
private PropertyAction action;
public IterableProperties(URL url, PropertyAction action){
this.action = action;
try {
load(url.openStream());
} catch (IOException e) {
appObject.getLog().error("Ocurrio un error cargando propiedades", e);
}
}
@Override
public void start() {
Enumeration keys = keys();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
String value = getProperty(key);
action.process(key, value);
}
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-macie2/src/main/java/com/amazonaws/services/macie2/model/CriterionAdditionalProperties.java | 23205 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.macie2.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Specifies the operator to use in a property-based condition that filters the results of a query for findings. For
* detailed information and examples of each operator, see <a
* href="https://docs.aws.amazon.com/macie/latest/user/findings-filter-basics.html">Fundamentals of filtering
* findings</a> in the <i>Amazon Macie User Guide</i>.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/macie2-2020-01-01/CriterionAdditionalProperties"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CriterionAdditionalProperties implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The value for the property matches (equals) the specified value. If you specify multiple values, Macie uses OR
* logic to join the values.
* </p>
*/
private java.util.List<String> eq;
/**
* <p>
* The value for the property exclusively matches (equals an exact match for) all the specified values. If you
* specify multiple values, Amazon Macie uses AND logic to join the values.
* </p>
* <p>
* You can use this operator with the following properties: customDataIdentifiers.detections.arn,
* customDataIdentifiers.detections.name, resourcesAffected.s3Bucket.tags.key,
* resourcesAffected.s3Bucket.tags.value, resourcesAffected.s3Object.tags.key,
* resourcesAffected.s3Object.tags.value, sensitiveData.category, and sensitiveData.detections.type.
* </p>
*/
private java.util.List<String> eqExactMatch;
/**
* <p>
* The value for the property is greater than the specified value.
* </p>
*/
private Long gt;
/**
* <p>
* The value for the property is greater than or equal to the specified value.
* </p>
*/
private Long gte;
/**
* <p>
* The value for the property is less than the specified value.
* </p>
*/
private Long lt;
/**
* <p>
* The value for the property is less than or equal to the specified value.
* </p>
*/
private Long lte;
/**
* <p>
* The value for the property doesn't match (doesn't equal) the specified value. If you specify multiple values,
* Macie uses OR logic to join the values.
* </p>
*/
private java.util.List<String> neq;
/**
* <p>
* The value for the property matches (equals) the specified value. If you specify multiple values, Macie uses OR
* logic to join the values.
* </p>
*
* @return The value for the property matches (equals) the specified value. If you specify multiple values, Macie
* uses OR logic to join the values.
*/
public java.util.List<String> getEq() {
return eq;
}
/**
* <p>
* The value for the property matches (equals) the specified value. If you specify multiple values, Macie uses OR
* logic to join the values.
* </p>
*
* @param eq
* The value for the property matches (equals) the specified value. If you specify multiple values, Macie
* uses OR logic to join the values.
*/
public void setEq(java.util.Collection<String> eq) {
if (eq == null) {
this.eq = null;
return;
}
this.eq = new java.util.ArrayList<String>(eq);
}
/**
* <p>
* The value for the property matches (equals) the specified value. If you specify multiple values, Macie uses OR
* logic to join the values.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setEq(java.util.Collection)} or {@link #withEq(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param eq
* The value for the property matches (equals) the specified value. If you specify multiple values, Macie
* uses OR logic to join the values.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CriterionAdditionalProperties withEq(String... eq) {
if (this.eq == null) {
setEq(new java.util.ArrayList<String>(eq.length));
}
for (String ele : eq) {
this.eq.add(ele);
}
return this;
}
/**
* <p>
* The value for the property matches (equals) the specified value. If you specify multiple values, Macie uses OR
* logic to join the values.
* </p>
*
* @param eq
* The value for the property matches (equals) the specified value. If you specify multiple values, Macie
* uses OR logic to join the values.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CriterionAdditionalProperties withEq(java.util.Collection<String> eq) {
setEq(eq);
return this;
}
/**
* <p>
* The value for the property exclusively matches (equals an exact match for) all the specified values. If you
* specify multiple values, Amazon Macie uses AND logic to join the values.
* </p>
* <p>
* You can use this operator with the following properties: customDataIdentifiers.detections.arn,
* customDataIdentifiers.detections.name, resourcesAffected.s3Bucket.tags.key,
* resourcesAffected.s3Bucket.tags.value, resourcesAffected.s3Object.tags.key,
* resourcesAffected.s3Object.tags.value, sensitiveData.category, and sensitiveData.detections.type.
* </p>
*
* @return The value for the property exclusively matches (equals an exact match for) all the specified values. If
* you specify multiple values, Amazon Macie uses AND logic to join the values.</p>
* <p>
* You can use this operator with the following properties: customDataIdentifiers.detections.arn,
* customDataIdentifiers.detections.name, resourcesAffected.s3Bucket.tags.key,
* resourcesAffected.s3Bucket.tags.value, resourcesAffected.s3Object.tags.key,
* resourcesAffected.s3Object.tags.value, sensitiveData.category, and sensitiveData.detections.type.
*/
public java.util.List<String> getEqExactMatch() {
return eqExactMatch;
}
/**
* <p>
* The value for the property exclusively matches (equals an exact match for) all the specified values. If you
* specify multiple values, Amazon Macie uses AND logic to join the values.
* </p>
* <p>
* You can use this operator with the following properties: customDataIdentifiers.detections.arn,
* customDataIdentifiers.detections.name, resourcesAffected.s3Bucket.tags.key,
* resourcesAffected.s3Bucket.tags.value, resourcesAffected.s3Object.tags.key,
* resourcesAffected.s3Object.tags.value, sensitiveData.category, and sensitiveData.detections.type.
* </p>
*
* @param eqExactMatch
* The value for the property exclusively matches (equals an exact match for) all the specified values. If
* you specify multiple values, Amazon Macie uses AND logic to join the values.</p>
* <p>
* You can use this operator with the following properties: customDataIdentifiers.detections.arn,
* customDataIdentifiers.detections.name, resourcesAffected.s3Bucket.tags.key,
* resourcesAffected.s3Bucket.tags.value, resourcesAffected.s3Object.tags.key,
* resourcesAffected.s3Object.tags.value, sensitiveData.category, and sensitiveData.detections.type.
*/
public void setEqExactMatch(java.util.Collection<String> eqExactMatch) {
if (eqExactMatch == null) {
this.eqExactMatch = null;
return;
}
this.eqExactMatch = new java.util.ArrayList<String>(eqExactMatch);
}
/**
* <p>
* The value for the property exclusively matches (equals an exact match for) all the specified values. If you
* specify multiple values, Amazon Macie uses AND logic to join the values.
* </p>
* <p>
* You can use this operator with the following properties: customDataIdentifiers.detections.arn,
* customDataIdentifiers.detections.name, resourcesAffected.s3Bucket.tags.key,
* resourcesAffected.s3Bucket.tags.value, resourcesAffected.s3Object.tags.key,
* resourcesAffected.s3Object.tags.value, sensitiveData.category, and sensitiveData.detections.type.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setEqExactMatch(java.util.Collection)} or {@link #withEqExactMatch(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param eqExactMatch
* The value for the property exclusively matches (equals an exact match for) all the specified values. If
* you specify multiple values, Amazon Macie uses AND logic to join the values.</p>
* <p>
* You can use this operator with the following properties: customDataIdentifiers.detections.arn,
* customDataIdentifiers.detections.name, resourcesAffected.s3Bucket.tags.key,
* resourcesAffected.s3Bucket.tags.value, resourcesAffected.s3Object.tags.key,
* resourcesAffected.s3Object.tags.value, sensitiveData.category, and sensitiveData.detections.type.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CriterionAdditionalProperties withEqExactMatch(String... eqExactMatch) {
if (this.eqExactMatch == null) {
setEqExactMatch(new java.util.ArrayList<String>(eqExactMatch.length));
}
for (String ele : eqExactMatch) {
this.eqExactMatch.add(ele);
}
return this;
}
/**
* <p>
* The value for the property exclusively matches (equals an exact match for) all the specified values. If you
* specify multiple values, Amazon Macie uses AND logic to join the values.
* </p>
* <p>
* You can use this operator with the following properties: customDataIdentifiers.detections.arn,
* customDataIdentifiers.detections.name, resourcesAffected.s3Bucket.tags.key,
* resourcesAffected.s3Bucket.tags.value, resourcesAffected.s3Object.tags.key,
* resourcesAffected.s3Object.tags.value, sensitiveData.category, and sensitiveData.detections.type.
* </p>
*
* @param eqExactMatch
* The value for the property exclusively matches (equals an exact match for) all the specified values. If
* you specify multiple values, Amazon Macie uses AND logic to join the values.</p>
* <p>
* You can use this operator with the following properties: customDataIdentifiers.detections.arn,
* customDataIdentifiers.detections.name, resourcesAffected.s3Bucket.tags.key,
* resourcesAffected.s3Bucket.tags.value, resourcesAffected.s3Object.tags.key,
* resourcesAffected.s3Object.tags.value, sensitiveData.category, and sensitiveData.detections.type.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CriterionAdditionalProperties withEqExactMatch(java.util.Collection<String> eqExactMatch) {
setEqExactMatch(eqExactMatch);
return this;
}
/**
* <p>
* The value for the property is greater than the specified value.
* </p>
*
* @param gt
* The value for the property is greater than the specified value.
*/
public void setGt(Long gt) {
this.gt = gt;
}
/**
* <p>
* The value for the property is greater than the specified value.
* </p>
*
* @return The value for the property is greater than the specified value.
*/
public Long getGt() {
return this.gt;
}
/**
* <p>
* The value for the property is greater than the specified value.
* </p>
*
* @param gt
* The value for the property is greater than the specified value.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CriterionAdditionalProperties withGt(Long gt) {
setGt(gt);
return this;
}
/**
* <p>
* The value for the property is greater than or equal to the specified value.
* </p>
*
* @param gte
* The value for the property is greater than or equal to the specified value.
*/
public void setGte(Long gte) {
this.gte = gte;
}
/**
* <p>
* The value for the property is greater than or equal to the specified value.
* </p>
*
* @return The value for the property is greater than or equal to the specified value.
*/
public Long getGte() {
return this.gte;
}
/**
* <p>
* The value for the property is greater than or equal to the specified value.
* </p>
*
* @param gte
* The value for the property is greater than or equal to the specified value.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CriterionAdditionalProperties withGte(Long gte) {
setGte(gte);
return this;
}
/**
* <p>
* The value for the property is less than the specified value.
* </p>
*
* @param lt
* The value for the property is less than the specified value.
*/
public void setLt(Long lt) {
this.lt = lt;
}
/**
* <p>
* The value for the property is less than the specified value.
* </p>
*
* @return The value for the property is less than the specified value.
*/
public Long getLt() {
return this.lt;
}
/**
* <p>
* The value for the property is less than the specified value.
* </p>
*
* @param lt
* The value for the property is less than the specified value.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CriterionAdditionalProperties withLt(Long lt) {
setLt(lt);
return this;
}
/**
* <p>
* The value for the property is less than or equal to the specified value.
* </p>
*
* @param lte
* The value for the property is less than or equal to the specified value.
*/
public void setLte(Long lte) {
this.lte = lte;
}
/**
* <p>
* The value for the property is less than or equal to the specified value.
* </p>
*
* @return The value for the property is less than or equal to the specified value.
*/
public Long getLte() {
return this.lte;
}
/**
* <p>
* The value for the property is less than or equal to the specified value.
* </p>
*
* @param lte
* The value for the property is less than or equal to the specified value.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CriterionAdditionalProperties withLte(Long lte) {
setLte(lte);
return this;
}
/**
* <p>
* The value for the property doesn't match (doesn't equal) the specified value. If you specify multiple values,
* Macie uses OR logic to join the values.
* </p>
*
* @return The value for the property doesn't match (doesn't equal) the specified value. If you specify multiple
* values, Macie uses OR logic to join the values.
*/
public java.util.List<String> getNeq() {
return neq;
}
/**
* <p>
* The value for the property doesn't match (doesn't equal) the specified value. If you specify multiple values,
* Macie uses OR logic to join the values.
* </p>
*
* @param neq
* The value for the property doesn't match (doesn't equal) the specified value. If you specify multiple
* values, Macie uses OR logic to join the values.
*/
public void setNeq(java.util.Collection<String> neq) {
if (neq == null) {
this.neq = null;
return;
}
this.neq = new java.util.ArrayList<String>(neq);
}
/**
* <p>
* The value for the property doesn't match (doesn't equal) the specified value. If you specify multiple values,
* Macie uses OR logic to join the values.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setNeq(java.util.Collection)} or {@link #withNeq(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param neq
* The value for the property doesn't match (doesn't equal) the specified value. If you specify multiple
* values, Macie uses OR logic to join the values.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CriterionAdditionalProperties withNeq(String... neq) {
if (this.neq == null) {
setNeq(new java.util.ArrayList<String>(neq.length));
}
for (String ele : neq) {
this.neq.add(ele);
}
return this;
}
/**
* <p>
* The value for the property doesn't match (doesn't equal) the specified value. If you specify multiple values,
* Macie uses OR logic to join the values.
* </p>
*
* @param neq
* The value for the property doesn't match (doesn't equal) the specified value. If you specify multiple
* values, Macie uses OR logic to join the values.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CriterionAdditionalProperties withNeq(java.util.Collection<String> neq) {
setNeq(neq);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getEq() != null)
sb.append("Eq: ").append(getEq()).append(",");
if (getEqExactMatch() != null)
sb.append("EqExactMatch: ").append(getEqExactMatch()).append(",");
if (getGt() != null)
sb.append("Gt: ").append(getGt()).append(",");
if (getGte() != null)
sb.append("Gte: ").append(getGte()).append(",");
if (getLt() != null)
sb.append("Lt: ").append(getLt()).append(",");
if (getLte() != null)
sb.append("Lte: ").append(getLte()).append(",");
if (getNeq() != null)
sb.append("Neq: ").append(getNeq());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CriterionAdditionalProperties == false)
return false;
CriterionAdditionalProperties other = (CriterionAdditionalProperties) obj;
if (other.getEq() == null ^ this.getEq() == null)
return false;
if (other.getEq() != null && other.getEq().equals(this.getEq()) == false)
return false;
if (other.getEqExactMatch() == null ^ this.getEqExactMatch() == null)
return false;
if (other.getEqExactMatch() != null && other.getEqExactMatch().equals(this.getEqExactMatch()) == false)
return false;
if (other.getGt() == null ^ this.getGt() == null)
return false;
if (other.getGt() != null && other.getGt().equals(this.getGt()) == false)
return false;
if (other.getGte() == null ^ this.getGte() == null)
return false;
if (other.getGte() != null && other.getGte().equals(this.getGte()) == false)
return false;
if (other.getLt() == null ^ this.getLt() == null)
return false;
if (other.getLt() != null && other.getLt().equals(this.getLt()) == false)
return false;
if (other.getLte() == null ^ this.getLte() == null)
return false;
if (other.getLte() != null && other.getLte().equals(this.getLte()) == false)
return false;
if (other.getNeq() == null ^ this.getNeq() == null)
return false;
if (other.getNeq() != null && other.getNeq().equals(this.getNeq()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getEq() == null) ? 0 : getEq().hashCode());
hashCode = prime * hashCode + ((getEqExactMatch() == null) ? 0 : getEqExactMatch().hashCode());
hashCode = prime * hashCode + ((getGt() == null) ? 0 : getGt().hashCode());
hashCode = prime * hashCode + ((getGte() == null) ? 0 : getGte().hashCode());
hashCode = prime * hashCode + ((getLt() == null) ? 0 : getLt().hashCode());
hashCode = prime * hashCode + ((getLte() == null) ? 0 : getLte().hashCode());
hashCode = prime * hashCode + ((getNeq() == null) ? 0 : getNeq().hashCode());
return hashCode;
}
@Override
public CriterionAdditionalProperties clone() {
try {
return (CriterionAdditionalProperties) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.macie2.model.transform.CriterionAdditionalPropertiesMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| apache-2.0 |
kiuby88/brooklyn-cloudfoundry | brooklyn-cloudfoundry/src/main/java/org/apache/brooklyn/cloudfoundry/location/CloudFoundryLocation.java | 19418 | /*
* 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.brooklyn.cloudfoundry.location;
import static org.apache.brooklyn.cloudfoundry.entity.CloudFoundryAppFromManifest.CONFIGURATION_CONTENTS;
import static org.apache.brooklyn.cloudfoundry.entity.CloudFoundryAppFromManifest.CONFIGURATION_URL;
import static org.apache.brooklyn.util.text.Strings.isBlank;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.brooklyn.api.entity.Entity;
import org.apache.brooklyn.api.location.LocationSpec;
import org.apache.brooklyn.api.location.MachineLocation;
import org.apache.brooklyn.api.location.MachineProvisioningLocation;
import org.apache.brooklyn.api.location.NoMachinesAvailableException;
import org.apache.brooklyn.cloudfoundry.entity.CloudFoundryAppFromManifest;
import org.apache.brooklyn.cloudfoundry.entity.VanillaCloudFoundryApplication;
import org.apache.brooklyn.core.entity.BrooklynConfigKeys;
import org.apache.brooklyn.core.location.AbstractLocation;
import org.apache.brooklyn.core.location.cloud.CloudLocationConfig;
import org.apache.brooklyn.location.ssh.SshMachineLocation;
import org.apache.brooklyn.util.collections.MutableMap;
import org.apache.brooklyn.util.core.ResourceUtils;
import org.apache.brooklyn.util.core.config.ConfigBag;
import org.apache.brooklyn.util.core.config.ResolvingConfigBag;
import org.apache.brooklyn.util.exceptions.PropagatedRuntimeException;
import org.apache.brooklyn.util.yaml.Yamls;
import org.cloudfoundry.client.CloudFoundryClient;
import org.cloudfoundry.client.v2.info.GetInfoRequest;
import org.cloudfoundry.client.v2.info.GetInfoResponse;
import org.cloudfoundry.operations.CloudFoundryOperations;
import org.cloudfoundry.operations.applications.ApplicationDetail;
import org.cloudfoundry.operations.applications.ApplicationHealthCheck;
import org.cloudfoundry.operations.applications.DeleteApplicationRequest;
import org.cloudfoundry.operations.applications.GetApplicationRequest;
import org.cloudfoundry.operations.applications.PushApplicationRequest;
import org.cloudfoundry.operations.applications.RestartApplicationRequest;
import org.cloudfoundry.operations.services.BindServiceInstanceRequest;
import org.cloudfoundry.operations.services.CreateServiceInstanceRequest;
import org.cloudfoundry.operations.services.DeleteServiceInstanceRequest;
import org.cloudfoundry.operations.services.ServiceInstanceSummary;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.UrlResource;
import com.google.common.base.Charsets;
import com.google.common.base.MoreObjects;
import com.google.common.base.Splitter;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
public class CloudFoundryLocation extends AbstractLocation implements MachineProvisioningLocation<MachineLocation>, CloudFoundryLocationConfig {
private static final Logger LOG = LoggerFactory.getLogger(CloudFoundryLocation.class);
private CloudFoundryOperations cloudFoundryOperations;
private CloudFoundryClient cloudFoundryClient;
public CloudFoundryLocation() {
super();
}
public CloudFoundryLocation(Map<?, ?> properties) {
super(properties);
}
@Override
public void init() {
super.init();
}
protected CloudFoundryClient getCloudFoundryClient() {
return getCloudFoundryClient(MutableMap.of());
}
protected CloudFoundryClient getCloudFoundryClient(Map<?, ?> flags) {
ConfigBag conf = (flags == null || flags.isEmpty())
? config().getBag()
: ConfigBag.newInstanceExtending(config().getBag(), flags);
return getCloudFoundryClient(conf);
}
protected CloudFoundryClient getCloudFoundryClient(ConfigBag config) {
if (cloudFoundryClient == null) {
CloudFoundryClientRegistry registry = getConfig(CF_CLIENT_REGISTRY);
cloudFoundryClient = registry.getCloudFoundryClient(
ResolvingConfigBag.newInstanceExtending(getManagementContext(), config), true);
}
return cloudFoundryClient;
}
protected CloudFoundryOperations getCloudFoundryOperations() {
return getCloudFoundryOperations(MutableMap.of());
}
protected CloudFoundryOperations getCloudFoundryOperations(Map<?, ?> flags) {
ConfigBag conf = (flags == null || flags.isEmpty())
? config().getBag()
: ConfigBag.newInstanceExtending(config().getBag(), flags);
return getCloudFoundryOperations(conf);
}
protected CloudFoundryOperations getCloudFoundryOperations(ConfigBag config) {
if (cloudFoundryOperations == null) {
CloudFoundryClientRegistry registry = getConfig(CF_CLIENT_REGISTRY);
cloudFoundryOperations = registry.getCloudFoundryOperations(
ResolvingConfigBag.newInstanceExtending(getManagementContext(), config), true);
}
return cloudFoundryOperations;
}
@Override
public MachineLocation obtain(Map<?, ?> flags) throws NoMachinesAvailableException {
ConfigBag setupRaw = ConfigBag.newInstanceExtending(config().getBag(), flags);
ConfigBag setup = ResolvingConfigBag.newInstanceExtending(getManagementContext(), setupRaw);
cloudFoundryClient = getCloudFoundryClient(setup);
return createCloudFoundryContainerLocation(setup);
}
private MachineLocation createCloudFoundryContainerLocation(ConfigBag setup) {
Entity entity = lookUpEntityFromCallerContext(setup.get(CALLER_CONTEXT)) ;
PushApplicationRequest pushApplicationRequest;
List<String> serviceInstanceNames;
if (isVanillaCloudFoundryApplication(entity)) {
pushApplicationRequest = createPushApplicationRequestFromVanillaCloudFoundryApplication(entity);
serviceInstanceNames = createInstanceServices(entity.config().get(VanillaCloudFoundryApplication.SERVICES));
} else if(isCloudFoundryAppFromManifet(entity)) {
Map<?, ?> manifestAsMap = getMapFromManifest(getManifestYamlFromEntity(entity));
pushApplicationRequest = createPushApplicationRequestFromManifest(manifestAsMap);
serviceInstanceNames = getServiceInstancesFromManifest(manifestAsMap);
} else {
throw new IllegalStateException("Can't deploy entity type different than " + VanillaCloudFoundryApplication.class.getSimpleName());
}
pushApplication(pushApplicationRequest);
String applicationName = pushApplicationRequest.getName();
// bind services
if (!serviceInstanceNames.isEmpty()) {
bindServices(applicationName, serviceInstanceNames);
restartApplication(applicationName);
}
LocationSpec<SshMachineLocation> locationSpec = buildLocationSpec(applicationName, setup.get(CALLER_CONTEXT));
return getManagementContext().getLocationManager().createLocation(locationSpec);
}
private LocationSpec<SshMachineLocation> buildLocationSpec(String applicationName, Object callerContext) {
ApplicationDetail applicationDetail = getApplicationDetail(applicationName);
String address = Iterables.getOnlyElement(applicationDetail.getUrls());
Integer port = getSshPort();
String sshCode = getCloudFoundryOperations().advanced().sshCode().block();
return LocationSpec.create(SshMachineLocation.class)
.configure("address", address)
.configure(CloudFoundryLocationConfig.APPLICATION_NAME, applicationName)
.configure(SshMachineLocation.PRIVATE_ADDRESSES, ImmutableList.of(address))
.configure(CloudLocationConfig.USER, String.format("cf:%s/0", applicationDetail.getId()))
.configure(SshMachineLocation.PASSWORD, sshCode)
.configure(SshMachineLocation.SSH_PORT, port)
.configure(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, true)
.configure(BrooklynConfigKeys.ONBOX_BASE_DIR, "/tmp")
.configure(CALLER_CONTEXT, callerContext);
}
private void pushApplication(PushApplicationRequest pushApplicationRequest) {
getCloudFoundryOperations().applications().push(pushApplicationRequest).block();
}
private Integer getSshPort() {
// see https://docs.cloudfoundry.org/devguide/deploy-apps/ssh-apps.html#other-ssh-access
GetInfoResponse info = getCloudFoundryClient().info().get(GetInfoRequest.builder().build()).block();
String sshEndpoint = info.getApplicationSshEndpoint();
return Integer.parseInt(Iterables.get(Splitter.on(":").split(sshEndpoint), 1));
}
private List getServiceInstancesFromManifest(Map<?, ?> manifestAsMap) {
return (List) manifestAsMap.get("services");
}
private Entity lookUpEntityFromCallerContext(Object callerContext) {
if (callerContext == null || !(callerContext instanceof Entity)) {
throw new IllegalStateException("Invalid caller context: " + callerContext);
}
return (Entity) callerContext;
}
private PushApplicationRequest createPushApplicationRequestFromVanillaCloudFoundryApplication(Entity entity) {
String applicationName = entity.config().get(VanillaCloudFoundryApplication.APPLICATION_NAME);
String domainName = entity.config().get(VanillaCloudFoundryApplication.APPLICATION_DOMAIN);
int memory = entity.config().get(VanillaCloudFoundryApplication.REQUIRED_MEMORY);
int disk = entity.config().get(VanillaCloudFoundryApplication.REQUIRED_DISK);
int instances = entity.config().get(VanillaCloudFoundryApplication.REQUIRED_INSTANCES);
String artifact = entity.config().get(VanillaCloudFoundryApplication.ARTIFACT_PATH);
Path artifactLocalPath = getArtifactLocalPath(artifact);
String buildpack = entity.config().get(VanillaCloudFoundryApplication.BUILDPACK);
return createPushApplicationRequest(applicationName, memory, disk, artifactLocalPath, buildpack, domainName, instances);
}
private PushApplicationRequest createPushApplicationRequestFromManifest(Map<?, ?> manifestAsMap) {
String applicationName = (String) manifestAsMap.get("name");
String buildpack = (String) manifestAsMap.get("buildpack");
Integer memory = MoreObjects.firstNonNull((Integer) manifestAsMap.get("memory"), 256);
Integer disk = MoreObjects.firstNonNull((Integer) manifestAsMap.get("disk"), 512);
String path = (String) manifestAsMap.get("path");
String domain = (String) manifestAsMap.get("domain");
Integer instances = MoreObjects.firstNonNull((Integer) manifestAsMap.get("instances"), 1);
Path artifactLocalPath = getArtifactLocalPath(path);
return createPushApplicationRequest(applicationName, memory, disk, artifactLocalPath, buildpack, domain, instances);
}
private String getManifestYamlFromEntity(Entity entity) {
String configurationUrl = entity.getConfig(CONFIGURATION_URL);
String configurationContents = entity.config().get(CONFIGURATION_CONTENTS);
// Exactly one of the two must have a value
if (isBlank(configurationUrl) == isBlank(configurationContents))
throw new IllegalArgumentException("Exactly one of the two must have a value: '"
+ CONFIGURATION_URL.getName() + "' or '" + CONFIGURATION_CONTENTS.getName() + "'.");
if (!isBlank(configurationUrl)) {
InputStream inputStream = new ResourceUtils(entity).getResourceFromUrl(configurationUrl);
return getStringFromInputStream(inputStream);
} else if (!isBlank(configurationContents)) {
return configurationContents;
} else {
throw new IllegalStateException("Cannot find configurationUrl nor configurationContents in the entity");
}
}
private Map<?, ?> getMapFromManifest(String yaml) {
return Yamls.getAs(Yamls.parseAll(yaml), Map.class);
}
private static String getStringFromInputStream(InputStream inputStream) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
String result;
int length;
try {
while ((length = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, length);
}
result = byteArrayOutputStream.toString(Charsets.UTF_8.name());
} catch (IOException e) {
throw Throwables.propagate(e);
}
return result;
}
private Path getArtifactLocalPath(String artifact) {
if (artifact == null) return null;
try {
return new UrlResource(artifact).getFile().toPath();
} catch (IOException e) {
throw Throwables.propagate(e);
}
}
@Override
public void release(MachineLocation machine) {
String applicationName = machine.config().get(CloudFoundryLocationConfig.APPLICATION_NAME);
List<ServiceInstanceSummary> serviceInstanceSummaries = getCloudFoundryOperations().services().listInstances().collectList().block();
List<String> instancesToBeDeleted = Lists.newArrayList();
for (ServiceInstanceSummary serviceInstanceSummary : serviceInstanceSummaries) {
for (String appName : serviceInstanceSummary.getApplications()) {
if (applicationName.equalsIgnoreCase(appName)) {
instancesToBeDeleted.add(serviceInstanceSummary.getName());
}
}
}
getCloudFoundryOperations().applications().delete(DeleteApplicationRequest.builder()
.name(applicationName)
.deleteRoutes(true)
.build()
).block();
// delete service instances bound to the application
for (String name : instancesToBeDeleted) {
getCloudFoundryOperations().services().deleteInstance(
DeleteServiceInstanceRequest.builder()
.name(name).build())
.block();
}
}
protected boolean isVanillaCloudFoundryApplication(Entity entity) {
return entity.getEntityType().getName().equalsIgnoreCase(VanillaCloudFoundryApplication.class.getName());
}
protected boolean isCloudFoundryAppFromManifet(Entity entity) {
return entity.getEntityType().getName().equalsIgnoreCase(CloudFoundryAppFromManifest.class.getName());
}
private List<String> createInstanceServices(List<Map<String, Object>> services) {
List<String> serviceInstanceNames = Lists.newArrayList();
for (Map<String, Object> service : services) {
for (Map.Entry<String, Object> stringObjectEntry : service.entrySet()) {
String serviceInstanceName = ((Map<String, String>)stringObjectEntry.getValue()).get("instanceName");
serviceInstanceNames.add(serviceInstanceName);
String planName = ((Map<String, String>)stringObjectEntry.getValue()).get("plan");
Map<String, ?> parameters = (Map<String, ?>) ((Map<String, Object>)stringObjectEntry.getValue()).get("parameters");
try {
getCloudFoundryOperations().services()
.createInstance(CreateServiceInstanceRequest.builder()
.serviceName(stringObjectEntry.getKey())
.serviceInstanceName(serviceInstanceName)
.planName(planName)
.parameters(parameters)
.build())
.block();
} catch (Exception e) {
LOG.error("Error creating the service {}, the error was {}", serviceInstanceName, e);
throw new PropagatedRuntimeException(e);
}
}
}
return serviceInstanceNames;
}
private PushApplicationRequest createPushApplicationRequest(String applicationName, int memory, int diskQuota, Path application, String buildpack, String domain, int instances) {
return PushApplicationRequest.builder()
.name(applicationName)
.healthCheckType(ApplicationHealthCheck.NONE) // TODO is it needed?
.randomRoute(true)
.buildpack(buildpack)
.application(application)
.instances(instances)
.domain(domain)
.diskQuota(diskQuota)
.memory(memory)
.build();
}
private ApplicationDetail getApplicationDetail(String applicationName) {
return getCloudFoundryOperations()
.applications().get(
GetApplicationRequest.builder().name(applicationName).build())
.block();
}
private void bindServices(String applicationName, List<String> serviceInstanceNames) {
for (String serviceInstanceName : serviceInstanceNames) {
try {
getCloudFoundryOperations().services()
.bind(
BindServiceInstanceRequest.builder()
.applicationName(applicationName)
.serviceInstanceName(serviceInstanceName)
.build()
).block();
} catch (Exception e) {
LOG.error("Error getting environment for application {} the error was ", applicationName, e);
throw new PropagatedRuntimeException(e);
}
}
}
private void restartApplication(String applicationName) {
getCloudFoundryOperations().applications()
.restart(
RestartApplicationRequest.builder()
.name(applicationName)
.build()
).block();
}
@Override
public MachineProvisioningLocation<MachineLocation> newSubLocation(Map<?, ?> map) {
return null;
}
@Override
public Map<String, Object> getProvisioningFlags(Collection<String> collection) {
return null;
}
}
| apache-2.0 |
griffon-plugins/griffon-coverflow-plugin | subprojects/griffon-coverflow-swing/src/main/java/com/blogofbug/swing/components/GradientPanel.java | 4312 | /*
* GradientPanel.java
*
* Created on November 22, 2006, 10:11 AM
*
*
* Copyright 2006-2007 Nigel Hughes
*
* 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.blogofbug.swing.components;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.image.BufferedImage;
/**
* Container that draws (in an optimized way) a gradient in the background
*
* @author bug
* <p/>
* Really trivial panel to draw the nice graduated background.
*/
public class GradientPanel extends JPanel implements ComponentListener {
/**
* Gradient start colour
*/
protected Color start;
/**
* Gradient end color
*/
protected Color end;
/**
* Gradient painter
*/
protected GradientPaint gp = null;
/**
* A pre-rendered gradient in an image
*/
protected BufferedImage cache = null;
/**
* Set the background to a single color
*
* @param color The color for a solid background
*/
public void setBackground(Color color) {
this.start = color;
this.end = color;
super.setBackground(color);
}
/**
* Sets two background colors for a gradient
*
* @param start Top (first) color
* @param end Bottom (final) color
*/
public void setBackground(Color start, Color end) {
this.start = start;
this.end = end;
makeGradient();
}
/**
* paints the gradient.
*
* @param graphics The graphics context
*/
public void paintComponent(Graphics graphics) {
if (start == end) {
super.paintComponent(graphics);
return;
}
Graphics2D g2 = (Graphics2D) graphics;
/*
//Thanks Romain Guy
if (cache == null || cache.getHeight() != getHeight()) {
cache = new BufferedImage(2, getHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = cache.createGraphics();
GradientPaint paint = new GradientPaint(0, 0, start,
0, getHeight(), end);
g2d.setPaint(paint);
g2d.fillRect(0, 0, 2, getHeight());
g2d.dispose();
}
g2.setPaint(new TexturePaint(cache, new Rectangle(0, 0, 1, getHeight())));
g2.fillRect(0, 0, getWidth(), getHeight());
//g2.drawImage(cache, 0, 0, getWidth(), getHeight(), null);
*/
gp = new GradientPaint((float) (getWidth() / 2), (float) getY(), start, (float) (getWidth() / 2), (float) getHeight(), end, false);
g2.setPaint(gp);
g2.fillRect(0, 0, getWidth(), getHeight());
super.paintChildren(graphics);
}
/**
* Pre-renders the gradient
*/
private void makeGradient() {
gp = new GradientPaint((float) (getWidth() / 2), (float) getY(), start, (float) (getWidth() / 2), (float) getHeight(), end, false);
}
/**
* Recalculates the gradient when it's resized
*
* @param componentEvent The event object
*/
public void componentResized(ComponentEvent componentEvent) {
makeGradient();
}
/**
* Ignored
*
* @param componentEvent The component event
*/
public void componentShown(ComponentEvent componentEvent) {
makeGradient();
}
/**
* Not used *
*
* @param componentEvent The event
*/
public void componentMoved(ComponentEvent componentEvent) {
}
/**
* Not used *
*
* @param componentEvent The event
*/
public void componentHidden(ComponentEvent componentEvent) {
}
}
| apache-2.0 |
alibaba/atlas | atlas-demo/AtlasDemo/remotebundle/src/main/java/com/taobao/remotebunle/RemoteBundleActivity.java | 324 | package com.taobao.remotebunle;
import android.app.Activity;
import android.os.Bundle;
public class RemoteBundleActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_remote_bundle);
}
}
| apache-2.0 |