repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
Poesys-Associates/dataloader | dataloader/src/com/poesys/accounting/dataloader/newaccounting/StorageManager.java | 2229 | /*
* Copyright (c) 2018 Poesys Associates. All rights reserved.
*
* This file is part of Poesys/Dataloader.
*
* Poesys/Dataloader 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.
*
* Poesys/Dataloader 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
* Poesys/Dataloader. If not, see <http://www.gnu.org/licenses/>.
*/
package com.poesys.accounting.dataloader.newaccounting;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
/**
* Production implementation of the IStorageManager interface
*
* @author Robert J. Muller
*/
public class StorageManager extends AbstractValidatingStorageManager {
/** logger for this class */
private static final Logger logger = Logger.getLogger(StorageManager.class);
// messages
private static final String STORED_MSG = "stored objects for all years";
@Override
public void store(String entityName, CapitalStructure structure, List<FiscalYear> years,
Set<Transaction> transactions, IDataAccessService storageService) {
try {
// Store the capital structure; this works around a persistence bug that doesn't store the
// structure before storing accounts that refer to it, so it needs to be persisted first.
storageService.storeCapitalStructure(structure);
storageService.storeFiscalYears(years);
// Store the entity, fiscal years, account groups, and accounts.
storageService.storeEntity(entityName, years);
// Store all the transactions in one committed transaction.
storageService.storeTransactions(transactions);
} catch (Throwable e) {
// Pass on exception with store failed message
throw new RuntimeException("exception in fiscal year storage operation", e);
}
logger.info(STORED_MSG);
}
}
| lgpl-3.0 |
loftuxab/community-edition-old | projects/web-service-client/source/generated/org/alfresco/webservice/types/Cardinality.java | 2920 | /**
* Cardinality.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package org.alfresco.webservice.types;
public class Cardinality implements java.io.Serializable {
private java.lang.String _value_;
private static java.util.HashMap _table_ = new java.util.HashMap();
// Constructor
protected Cardinality(java.lang.String value) {
_value_ = value;
_table_.put(_value_,this);
}
public static final java.lang.String _value1 = "0..1";
public static final java.lang.String _value2 = "1";
public static final java.lang.String _value3 = "*";
public static final java.lang.String _value4 = "1..*";
public static final Cardinality value1 = new Cardinality(_value1);
public static final Cardinality value2 = new Cardinality(_value2);
public static final Cardinality value3 = new Cardinality(_value3);
public static final Cardinality value4 = new Cardinality(_value4);
public java.lang.String getValue() { return _value_;}
public static Cardinality fromValue(java.lang.String value)
throws java.lang.IllegalArgumentException {
Cardinality enumeration = (Cardinality)
_table_.get(value);
if (enumeration==null) throw new java.lang.IllegalArgumentException();
return enumeration;
}
public static Cardinality fromString(java.lang.String value)
throws java.lang.IllegalArgumentException {
return fromValue(value);
}
public boolean equals(java.lang.Object obj) {return (obj == this);}
public int hashCode() { return toString().hashCode();}
public java.lang.String toString() { return _value_;}
public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumSerializer(
_javaType, _xmlType);
}
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumDeserializer(
_javaType, _xmlType);
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(Cardinality.class);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("http://www.alfresco.org/ws/model/content/1.0", "Cardinality"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
}
| lgpl-3.0 |
jrebillat/Proper | Proper-test/src/net/alantea/proper/example/example5/ManagedMain.java | 1440 | package net.alantea.proper.example.example5;
import net.alantea.proper.MappedPropertyContainer;
public class ManagedMain
{
public static final String PROP_ONE = "PropertyOne";
public static final String PROP_TWO = "PropertyTwo";
public static final String ACT_GOTINTEGER = "GotInteger";
public static final String ACT_GOTLONG = "GotLong";
public static void main(String[] args)
{
Integer cont1 = -1;
Double cont2 = -1.23;
OutputPrinter printer = new OutputPrinter();
MappedPropertyContainer.associateHook(cont1, "Container1", printer);
MappedPropertyContainer.associateHook(cont2, "Container2", printer);
MappedPropertyContainer.associateHook("HiddenContainer", "", printer);
MappedPropertyContainer.setPropertyValue(cont1, PROP_ONE, 1);
MappedPropertyContainer.setPropertyValue(cont2, PROP_ONE, 10);
MappedPropertyContainer.setPropertyValue(cont2, PROP_TWO, 200000000);
MappedPropertyContainer.setPropertyValue("HiddenContainer", OutputPrinter.PROP_THREE, 3.14);
MappedPropertyContainer.setPropertyValue(cont1, PROP_ONE, 2);
MappedPropertyContainer.setPropertyValue(cont2, PROP_TWO, 5000000000L);
MappedPropertyContainer.setPropertyValue("", OutputPrinter.PROP_THREE, 123.456);
MappedPropertyContainer.setPropertyValue("HiddenContainer", OutputPrinter.PROP_THREE, 666.0);
}
}
| lgpl-3.0 |
RuedigerMoeller/kontraktor | modules/kontraktor-reallive/src/main/java/org/nustaq/reallive/impl/actors/RealLiveTableActor.java | 12429 | package org.nustaq.reallive.impl.actors;
import org.nustaq.kontraktor.*;
import org.nustaq.kontraktor.annotations.CallerSideMethod;
import org.nustaq.kontraktor.annotations.Local;
import org.nustaq.kontraktor.impl.CallbackWrapper;
import org.nustaq.kontraktor.remoting.encoding.CallbackRefSerializer;
import org.nustaq.kontraktor.util.Log;
import org.nustaq.reallive.impl.*;
import org.nustaq.reallive.impl.storage.StorageStats;
import org.nustaq.reallive.api.*;
import org.nustaq.reallive.messages.AddMessage;
import org.nustaq.reallive.messages.PutMessage;
import org.nustaq.reallive.messages.RemoveMessage;
import org.nustaq.reallive.records.RecordWrapper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.function.*;
/**
* Created by ruedi on 06.08.2015.
*
* core implementation of a table
*
*/
public class RealLiveTableActor extends Actor<RealLiveTableActor> implements RealLiveTable {
public static int MAX_QUERY_BATCH_SIZE = 10;
public static boolean DUMP_QUERY_TIME = false;
StorageDriver storageDriver;
FilterProcessor filterProcessor;
HashMap<String,Subscriber> receiverSideSubsMap = new HashMap();
TableDescription description;
ArrayList<QueryQEntry> queuedSpores = new ArrayList();
int taCount = 0;
@Local
public IPromise init(Function<TableDescription,RecordStorage> storeFactory, TableDescription desc) {
this.description = desc;
Thread.currentThread().setName("Table "+(desc==null?"NULL":desc.getName())+" main");
RecordStorage store = storeFactory.apply(desc);
storageDriver = new StorageDriver(store);
filterProcessor = new FilterProcessor(this);
storageDriver.setListener( filterProcessor );
return resolve();
}
@Override
public void receive(ChangeMessage change) {
checkThread();
try {
storageDriver.receive(change);
} catch (Exception th) {
Log.Error(this,th);
}
}
public <T> void forEachDirect(Spore<Record, T> spore) {
checkThread();
try {
storageDriver.getStore().forEachWithSpore(spore);
} catch (Exception ex) {
spore.complete(null,ex);
}
}
@Override
public <T> void forEachWithSpore(Spore<Record, T> spore) {
if ( spore instanceof FilterSpore && ((FilterSpore)spore).getFilter().getRecordLimit() > 0 ) {
FilterSpore newSpore = new FilterSpore(((FilterSpore) spore).getFilter());
List<String> keys = new ArrayList<>();
newSpore.onFinish( () -> {
delayedSend(keys,((FilterSpore)spore).getFilter().getRecordLimit(), spore);
});
newSpore.setForEach( (r, e) -> {
if (Actors.isResult(e)) {
keys.add( ((Record)r).getKey());
}
});
forEachDirect(newSpore);
} else
forEachQueued(spore, () -> {});
}
private <T> void delayedSend(List<String> keys, int recordLimit, Spore<Record, T> spore) {
int i = keys.size()-1; int ii = 0;
RecordStorage store = storageDriver.getStore();
while( i >= 0 && ii < recordLimit ) {
Record record = store.get(keys.get(i));
if ( record != null )
spore.remote(record);
keys.remove(i);
ii++; i--;
}
if ( keys.size() > 0 ) {
delayed(1000, () -> delayedSend(keys, recordLimit, spore));
} else {
spore.finish();
}
}
@Override
protected void hasStopped() {
}
// subscribe/unsubscribe
// on callerside, the subscription is decomposed to kontraktor primitives
// and a subscription id (locally unique)
// remote receiver then builds a unique id by concatening localid#connectionId
@Override
@CallerSideMethod public void subscribe(Subscriber subs) {
// need callerside to transform to Callback
Callback callback = (r, e) -> {
if (Actors.isResult(e))
subs.getReceiver().receive((ChangeMessage) r);
};
_subscribe(subs.getFilter(), callback, subs.getId());
}
public void _subscribe(RLPredicate pred, Callback cb, int id) {
checkThread();
Subscriber localSubs = new Subscriber(pred, change -> {
cb.pipe(change);
}).serverSideCB(cb);
String sid = addChannelIdIfPresent(cb, ""+id);
receiverSideSubsMap.put(sid,localSubs);
FilterSpore spore = new FilterSpore(localSubs.getFilter()).modifiesResult(false);
spore.onFinish( () -> localSubs.getReceiver().receive(RLUtil.get().done()) );
spore.setForEach((r, e) -> {
if (Actors.isResult(e)) {
localSubs.getReceiver().receive(new AddMessage(0,(Record) r));
} else {
// FIXME: pass errors
// FIXME: called in case of error only (see onFinish above)
localSubs.getReceiver().receive(RLUtil.get().done());
}
});
if ( pred instanceof KeySetSubscriber.KSPredicate ) {
KeySetSubscriber.KSPredicate<Record> p = (KeySetSubscriber.KSPredicate) pred;
p.getKeys().forEach( key -> {
Record record = storageDriver.getStore().get(key);
if ( record != null ) {
localSubs.getReceiver().receive(new AddMessage(0,record));
}
});
localSubs.getReceiver().receive(RLUtil.get().done());
filterProcessor.startListening(localSubs);
} else {
if ( pred instanceof RLNoQueryPredicate ) {
localSubs.getReceiver().receive(RLUtil.get().done());
} else {
forEachDirect(spore); // removed queuing, ot tested well enough
}
filterProcessor.startListening(localSubs);
}
}
static class QueryQEntry {
Spore spore;
Runnable onFin;
public QueryQEntry(Spore spore, Runnable onFin) {
this.spore = spore;
this.onFin = onFin;
}
}
private void forEachQueued( Spore s, Runnable r ) {
queuedSpores.add(new QueryQEntry(s,r));
self()._execQueriesOrDelay(queuedSpores.size(),taCount);
}
public void _execQueriesOrDelay(int size, int taCount) {
if ( (queuedSpores.size() == size && this.taCount == taCount) || queuedSpores.size() > MAX_QUERY_BATCH_SIZE) {
long tim = System.currentTimeMillis();
Consumer<Record> recordConsumer = rec -> {
for (int i = 0; i < queuedSpores.size(); i++) {
QueryQEntry qqentry = queuedSpores.get(i);
Spore spore = qqentry.spore;
if (!spore.isFinished()) {
try {
spore.remote(rec);
} catch (Throwable ex) {
Log.Warn(this,ex,"exception in spore "+spore);
spore.complete(null, ex);
}
}
}
};
storageDriver.getStore().stream().forEach(recordConsumer);
queuedSpores.forEach( qqentry -> {
qqentry.spore.finish();
qqentry.onFin.run();
});
if (DUMP_QUERY_TIME)
System.out.println("tim for "+queuedSpores.size()+" "+(System.currentTimeMillis()-tim));
queuedSpores.clear();
return;
}
_execQueriesOrDelay(queuedSpores.size(),this.taCount);
}
protected String addChannelIdIfPresent(Callback cb, String sid) {
if ( cb instanceof CallbackWrapper && ((CallbackWrapper) cb).isRemote() ) {
// hack to get unique id sender#connection
CallbackRefSerializer.MyRemotedCallback realCallback
= (CallbackRefSerializer.MyRemotedCallback) ((CallbackWrapper) cb).getRealCallback();
sid += "#"+realCallback.getChanId();
}
return sid;
}
@CallerSideMethod @Override
public void unsubscribe(Subscriber subs) {
_unsubscribe( (r,e) -> {}, subs.getId() );
}
@Override
public void unsubscribeById(int subsId) {
_unsubscribe( (r,e) -> {}, subsId );
}
public void _unsubscribe( Callback cb /*dummy required to find sending connection*/, int id ) {
checkThread();
String sid = addChannelIdIfPresent(cb, ""+id);
Subscriber subs = (Subscriber) receiverSideSubsMap.get(sid);
filterProcessor.unsubscribe(subs);
receiverSideSubsMap.remove(sid);
cb.finish();
subs.getServerSideCB().finish();
}
@Override
public IPromise<Record> get(String key) {
taCount++;
return resolve(storageDriver.getStore().get(key));
}
@Override
public IPromise<Long> size() {
return resolve(storageDriver.getStore().size());
}
@Override
public IPromise<TableDescription> getDescription() {
return resolve(description);
}
@Override
public IPromise<StorageStats> getStats() {
try {
final StorageStats stats = storageDriver.getStore().getStats();
return resolve(stats);
} catch (Throwable th) {
Log.Warn(this,th);
return reject(th.getMessage());
}
}
@Override
public IPromise atomic(int senderId, String key, RLFunction<Record, Object> action) {
taCount++;
return storageDriver.atomicQuery(senderId, key,action);
}
@Override
public void atomicUpdate(RLPredicate<Record> filter, RLFunction<Record, Boolean> action) {
taCount++;
storageDriver.atomicUpdate(filter, action);
}
@Override
public IPromise resizeIfLoadFactorLarger(double loadFactor, long maxGrowBytes) {
Log.Info(this,"resizing table if lf: "+loadFactor+" maxgrow:"+maxGrowBytes);
long now = System.currentTimeMillis();
storageDriver.resizeIfLoadFactorLarger(loadFactor,maxGrowBytes);
Log.Info(this,"resizing duration"+(System.currentTimeMillis()-now));
return resolve();
}
@Override
public void put(int senderId, String key, Object... keyVals) {
receive(RLUtil.get().put(senderId, key, keyVals));
}
@Override
public void merge(int senderId, String key, Object... keyVals) {
if ( ((Object)key) instanceof Record )
throw new RuntimeException("probably accidental method resolution fail. Use merge instead");
receive(RLUtil.get().addOrUpdate(senderId, key, keyVals));
}
@Override
public IPromise<Boolean> add(int senderId, String key, Object... keyVals) {
if ( storageDriver.getStore().get(key) != null )
return resolve(false);
receive(RLUtil.get().add(senderId, key, keyVals));
return resolve(true);
}
@Override
public IPromise<Boolean> addRecord(int senderId, Record rec) {
if ( rec instanceof RecordWrapper)
rec = ((RecordWrapper) rec).getRecord();
Record existing = storageDriver.getStore().get(rec.getKey());
if ( existing != null )
return resolve(false);
receive((ChangeMessage) new AddMessage(senderId,rec));
return resolve(true);
}
@Override
public void mergeRecord(int senderId, Record rec) {
if ( rec instanceof RecordWrapper )
rec = ((RecordWrapper) rec).getRecord();
receive(new AddMessage(senderId, true,rec));
}
@Override
public void setRecord(int senderId, Record rec) {
if ( rec instanceof RecordWrapper )
rec = ((RecordWrapper) rec).getRecord();
receive(new PutMessage(senderId, rec));
}
@Override
public void update(int senderId, String key, Object... keyVals) {
receive(RLUtil.get().update(senderId, key, keyVals));
}
@Override
public IPromise<Record> take(int senderId, String key) {
Record record = storageDriver.getStore().get(key);
receive(RLUtil.get().remove(senderId,key));
return resolve(record);
}
@Override
public void remove(int senderId, String key) {
RemoveMessage remove = RLUtil.get().remove(senderId, key);
receive(remove);
}
}
| lgpl-3.0 |
timothyakampa/RapidFTR-Android | RapidFTR-Android/src/main/java/com/rapidftr/utils/ResourceLoader.java | 656 | package com.rapidftr.utils;
import com.google.common.io.CharStreams;
import lombok.Cleanup;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ResourceLoader {
public static InputStream loadResourceFromClasspath(String resourceName) {
return ResourceLoader.class.getClassLoader().getResourceAsStream(resourceName);
}
public static String loadResourceAsStringFromClasspath(String resourceName) throws IOException {
@Cleanup InputStream inputStream = loadResourceFromClasspath(resourceName);
return CharStreams.toString(new InputStreamReader(inputStream));
}
}
| lgpl-3.0 |
Dev4Ninja/mvo4j | src/main/java/br/com/d4n/mvo/ioc/spring/SpringContainerProvider.java | 2475 | package br.com.d4n.mvo.ioc.spring;
/*
* #%L
* mvo4j
* %%
* Copyright (C) 2012 - 2015 DevFor Ninjas
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import br.com.d4n.mvo.ioc.ConfigurationException;
import br.com.d4n.mvo.ioc.Container;
import br.com.d4n.mvo.ioc.ContainerProvider;
import br.com.d4n.mvo.ioc.LocalContainerConfig;
public class SpringContainerProvider implements ContainerProvider<LocalContainerConfig> {
@Override
public Container getContainer(LocalContainerConfig config) throws ConfigurationException {
ConfigurableApplicationContext applicationContext = getApplicationContext(config);
config.setListener(new SpringContainerListener(applicationContext));
Container container = new SpringContainer(applicationContext, config);
return container;
}
private ConfigurableApplicationContext getApplicationContext(LocalContainerConfig contextConfig) {
ConfigurableApplicationContext applicationContext = ApplicationContextHolder.getApplicationContext();
if (applicationContext != null)
return new GenericApplicationContext(applicationContext);
if (SpringContainerProvider.class.getResource("/applicationContext.xml") != null) {
// logger.info("Using an XmlWebApplicationContext, searching for applicationContext.xml");
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationContext.xml");
return ctx;
}
// logger.info("No application context found");
ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.setId("MVO");
return ctx;
}
}
| lgpl-3.0 |
AshwinJay/StreamCruncher | demo_src/streamcruncher/test/func/h2/H2CorrelationPerfTest.java | 1049 | package streamcruncher.test.func.h2;
import org.testng.annotations.AfterGroups;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test;
import streamcruncher.test.TestGroupNames;
import streamcruncher.test.func.generic.CorrelationPerfTest;
/*
* Author: Ashwin Jayaprakash Date: Jul 17, 2007 Time: 6:27:12 PM
*/
public class H2CorrelationPerfTest extends CorrelationPerfTest {
@Override
@BeforeGroups(dependsOnGroups = { TestGroupNames.SC_INIT_REQUIRED }, value = { TestGroupNames.SC_TEST_H2 }, groups = { TestGroupNames.SC_TEST_H2 })
public void init() throws Exception {
super.init();
}
@Test(dependsOnGroups = { TestGroupNames.SC_INIT_REQUIRED }, groups = { TestGroupNames.SC_TEST_H2 })
protected void performTest() throws Exception {
test();
}
@Override
@AfterGroups(dependsOnGroups = { TestGroupNames.SC_INIT_REQUIRED }, value = { TestGroupNames.SC_TEST_H2 }, groups = { TestGroupNames.SC_TEST_H2 })
public void discard() {
super.discard();
}
}
| lgpl-3.0 |
CSTARS/gwt-esri | src/main/java/edu/ucdavis/cstars/client/layers/RangeDomain.java | 576 | package edu.ucdavis.cstars.client.layers;
/**
* Information about the range of values belonging to the domain. Range domains specify a valid range of values for a numeric attribute.
*
* @author Justin Merz
*/
public class RangeDomain extends Domain {
protected RangeDomain() {}
/**
* The maximum valid value.
*
* @return double
*/
public final native double getMaxValue() /*-{
return this.maxValue;
}-*/;
/**
* The minimum valid value.
*
* @return double
*/
public final native double getMinValue() /*-{
return this.minValue;
}-*/;
}
| lgpl-3.0 |
mantlik/swingbox-javahelp-viewer | src/main/java/org/fit/cssbox/swingbox/util/GeneralEventListener.java | 1283 | /**
* GeneralEventListener.java
* (c) Peter Bielik and Radek Burget, 2011-2012
*
* SwingBox is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SwingBox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with SwingBox. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.fit.cssbox.swingbox.util;
import java.util.EventListener;
/**
* This is the "general listener" interface, used for gaining various
* interesting (but not vital (?)) informations.
*
* @author Peter Bielik
* @version 1.0
* @since 1.0 - 14.4.2011
*/
public interface GeneralEventListener extends EventListener
{
/**
* General event update. Occures, when somthing "interesting" happens.
*
* @param e the instance of event with data
*/
public void generalEventUpdate(GeneralEvent e);
}
| lgpl-3.0 |
flamingchickens1540/Common-Chicken-Runtime-Engine | roboRIO/src/edu/wpi/first/wpilibj/can/CANNotInitializedException.java | 935 | // Certain modifications are Copyright 2016 Cel Skeggs
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2016. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.can;
/**
* Exception indicating that the CAN driver layer has not been initialized. This
* happens when an entry-point is called before a CAN driver plugin has been
* installed.
*/
@SuppressWarnings({ "javadoc", "serial" })
public class CANNotInitializedException extends RuntimeException {
public CANNotInitializedException() {
super();
}
}
| lgpl-3.0 |
qspin/qtaste | plugins_src/javagui/src/main/java/com/qspin/qtaste/javagui/server/EditableStateGetter.java | 2425 | /*
Copyright 2007-2012 QSpin - www.qspin.be
This file is part of QTaste framework.
QTaste is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QTaste is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with QTaste. If not, see <http://www.gnu.org/licenses/>.
*/
package com.qspin.qtaste.javagui.server;
import java.awt.Component;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.text.JTextComponent;
import com.qspin.qtaste.testsuite.QTasteException;
import com.qspin.qtaste.testsuite.QTasteTestFailException;
/**
* Component asker which return the editable state of a component.
*
* @author simjan
*/
class EditableStateGetter extends ComponentCommander {
/**
* @param data the component's name.
* @return <code>true</code> if the component is editable.
* @throws QTasteTestFailException if no component is found.
*/
@Override
Boolean executeCommand(int timeout, String componentName, Object... data) throws QTasteException {
Component c = getComponentByName(componentName);
if (c == null) {
return false;
}
if (c instanceof JTextComponent) {
return ((JTextComponent) c).isEditable();
} else if (c instanceof JComboBox) {
return ((JComboBox) c).isEditable();
} else if (c instanceof JTable) {
for (int x = 0; x < ((JTable) c).getColumnCount(); x++) {
for (int y = 0; y < ((JTable) c).getRowCount(); y++) {
if (((JTable) c).isCellEditable(y, x)) {
return true;
}
}
}
} else if (c instanceof JTree) {
return ((JTree) c).isEditable();
} else {
throw new QTasteTestFailException("Cannot get the editable state of a component of type " + c.getClass() + ".");
}
return false;
}
}
| lgpl-3.0 |
hy2708/hy2708-repository | java/commons/commons-net/src/test/java/org/hy/commons/net/tcp/upload/Client.java | 949 | package org.hy.commons.net.tcp.upload;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class Client implements Runnable{
public void name() throws Exception {
System.err.println("ccccccccccccccc");
Socket socket = new Socket("127.0.0.1",18888);
OutputStream out = socket.getOutputStream();
InputStream fin= getClass().getClassLoader().getResourceAsStream("2.jpg");
byte[] b=new byte[1024];
int length = 0;
int offset = 0;
while ((length = fin.read(b))>0) {
//System.err.println(offset+" "+length);
out.write(b, 0, length);
//offset=offset+length;
}
fin.close();
socket.shutdownOutput();
System.err.println("client out close");
socket.close();
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
name();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| lgpl-3.0 |
sysbiolux/IDARE | METANODE-CREATOR/src/main/java/idare/imagenode/internal/GUI/Legend/Tasks/CreateNodeImageTask.java | 8489 | package idare.imagenode.internal.GUI.Legend.Tasks;
import java.awt.Color;
import java.awt.Dimension;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Collection;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import org.apache.batik.svggen.SVGGraphics2D;
import org.apache.batik.transcoder.Transcoder;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.cytoscape.work.AbstractTask;
import org.cytoscape.work.TaskMonitor;
import org.cytoscape.work.TaskMonitor.Level;
import org.w3c.dom.Element;
import org.w3c.dom.svg.SVGDocument;
import idare.imagenode.Properties.IMAGENODEPROPERTIES;
import idare.imagenode.Utilities.LayoutUtils;
import idare.imagenode.internal.DataManagement.NodeManager;
import idare.imagenode.internal.GUI.Legend.IDARELegend;
import idare.imagenode.internal.Layout.DataSetLink;
import idare.imagenode.internal.Layout.ImageNodeLayout;
public class CreateNodeImageTask extends AbstractTask {
IDARELegend legend;
NodeManager manager;
JFrame descriptionFrame;
String fileExtension;
File targetFile;
/**
* Default Constructor
* @param legend The reference {@link IDARELegend}
* @param targetFile the target to write the data to
* @param manager the NodeManager used to obtain nodes to create
* @param FileExtension The file extension (svg or png) to generate the images in.
*/
public CreateNodeImageTask(IDARELegend legend, File targetFile,
NodeManager manager, String FileExtension) {
super();
this.legend = legend;
this.targetFile = targetFile;
this.manager = manager;
fileExtension = FileExtension;
}
/**
* Convert the legend to an Image in the given ZipOutput.
* @param zipout - The outputstream to write to
* @param coder - a potential {@link Transcoder} to convert into non SVG files. If null, and SVG will be generated.
* @throws IOException
*/
private void paintLegendToFile(OutputStreamWriter zipout, Transcoder coder) throws IOException
{
// Unfortunately, the Legend Node is not in SVG forma, but I could not figure out a way to actually
// have it in SVG...
SVGDocument svgdoc2 = LayoutUtils.createSVGDoc();
SVGGraphics2D g2 = new SVGGraphics2D(svgdoc2);
ImageNodeLayout layout = manager.getLayoutForNode(legend.getCurrentlyUsedNode());
JPanel ContentPane = buildLegendDescriptionFrame(layout, layout.getDatasetsInOrder());
layout.layoutLegendNode(manager.getNode(legend.getCurrentlyUsedNode()).getData(), g2);
g2.translate(0, IMAGENODEPROPERTIES.IMAGEHEIGHT+IMAGENODEPROPERTIES.LABELHEIGHT);
descriptionFrame.setVisible(true);
int width = ContentPane.getSize().width;
int height = ContentPane.getSize().height + IMAGENODEPROPERTIES.IMAGEHEIGHT+IMAGENODEPROPERTIES.LABELHEIGHT;
g2.setSVGCanvasSize(new Dimension(width,height));
ContentPane.paint(g2);
descriptionFrame.dispose();
Element root2 = svgdoc2.getDocumentElement();
g2.getRoot(root2);
root2.setAttribute("viewBox", "0 0 " + width + " " + height );
if(coder == null)
{
g2.stream(root2,zipout);
}
else
{
//If we want to transcode to a non SVG format.
TranscoderInput input = new TranscoderInput(svgdoc2);
TranscoderOutput out = new TranscoderOutput(zipout);
try{
coder.transcode(input, out);
}
catch(TranscoderException e)
{
return;
}
zipout.flush();
}
}
/**
* Write the node Image to the {@link OutputStreamWriter} using the given {@link Transcoder} if non <code>null</code>, and the given ID.
* @param zipout - The Outstream to write to.
* @param coder - The coder to convert to another format (if <code>null</code> svg will be generated
* @param NodeID - The NodeID to use as label.
* @throws IOException
*/
private void writeNodeImageToFile(OutputStreamWriter zipout, Transcoder coder, String NodeID) throws IOException
{
SVGDocument svgdoc2 = LayoutUtils.createSVGDoc();
SVGGraphics2D g2 = new SVGGraphics2D(svgdoc2);
manager.getLayoutForNode(NodeID).layoutNode(manager.getNode(NodeID).getData(), g2);
Element root2 = svgdoc2.getDocumentElement();
g2.getRoot(root2);
LayoutUtils.TransferGraphicsToDocument(svgdoc2, null, g2);
//OutputStream os2 = new FileOutputStream(F);
if(coder == null)
{
g2.stream(root2,zipout);
}
else
{
TranscoderInput input = new TranscoderInput(svgdoc2);
TranscoderOutput out = new TranscoderOutput(zipout);
try{
coder.transcode(input, out);
}
catch(TranscoderException e)
{
//JOptionPane.showConfirmDialog(cySwingApp.getJFrame(), "Could not save as " + F.getName().substring(F.getName().lastIndexOf(".")) + " try svg instead.");
//os2.close();
return;
}
zipout.flush();
}
}
@Override
public void run(TaskMonitor taskMonitor) throws Exception {
// TODO Auto-generated method stub
taskMonitor.setTitle("Generating Image Zip File");
if(!targetFile.getName().endsWith("zip"))
{
targetFile = new File(targetFile.getPath()+".zip");
}
Transcoder coder = null;
switch(fileExtension)
{
case "svg":
coder = null;
break;
case "png":
coder = new PNGTranscoder();
break;
default:
coder = null;
}
//IF no extension is given, we assume this is a svg...
try{
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(targetFile));
OutputStreamWriter outwriter = new OutputStreamWriter(out);
ZipEntry entry = new ZipEntry("Legend." + fileExtension);
out.putNextEntry(entry);
taskMonitor.setStatusMessage("Writing Legend Image");
paintLegendToFile(outwriter , coder);
out.closeEntry();
taskMonitor.setStatusMessage("Writing Node Images");
Collection<String> IDs = manager.getNodesForLayout(manager.getLayoutForNode(legend.getCurrentlyUsedNode()));
int current = 0;
int Steps = Math.max(IDs.size()/10,1);
for(String ID : IDs)
{
current++;
if(current % Steps == 0)
{
taskMonitor.setProgress(((double) current) / IDs.size());
}
ZipEntry nodeentry = new ZipEntry(ID + "." + fileExtension);
out.putNextEntry(nodeentry);
writeNodeImageToFile(outwriter , coder, ID);
out.closeEntry();
}
outwriter.close();
out.close();
}
catch(IOException e)
{
taskMonitor.showMessage(Level.ERROR, "Could not write file " + targetFile.getName());
}
}
/**
* Build a DataDescriptionpane to print the legend descriptions.
* @param layout the layouts to use
* @param datasets the datasets in correct order
* @return The LegendDescription Panel
*/
private JPanel buildLegendDescriptionFrame(ImageNodeLayout layout, Vector<? extends DataSetLink> datasets)
{
descriptionFrame = new JFrame();
JPanel ContentPane = new JPanel();
JScrollPane scroller = new JScrollPane(ContentPane);
descriptionFrame.add(scroller);
ContentPane.setBackground(Color.BLACK);
ContentPane.setLayout(new BoxLayout(ContentPane,BoxLayout.PAGE_AXIS));
//The 32 here is a hack, but I currently don't know how else to get the width to be 400...
descriptionFrame.setSize(new Dimension(IMAGENODEPROPERTIES.IMAGEWIDTH+31, 100));
setDataSetDescriptions(scroller, datasets, layout, ContentPane);
descriptionFrame.setSize(new Dimension(IMAGENODEPROPERTIES.IMAGEWIDTH+31, 100));
return ContentPane;
}
/**
* Essentially a copy of the Method from the {@link IDARELegend}. using a ScrollPane and a given content to do the process.
* @param scroller The scrollpane to add the DataSetDescription to.
* @param datasets The datasets to add to this "legend"
* @param layout the layout to use
* @param Content the Content pane to use plot to
*/
private void setDataSetDescriptions(JScrollPane scroller, Vector<? extends DataSetLink> datasets, ImageNodeLayout layout, JPanel Content)
{
for(DataSetLink dsl : datasets)
{
JPanel DataSetPane = dsl.getDataSet().getDataSetDescriptionPane(scroller,layout.getDataSetLabel(dsl),layout.getColorsForDataSet(dsl));
Content.add(Box.createRigidArea(new Dimension(0,2)));
Content.add(DataSetPane);
//DataSetPane.doLayout();
}
Content.revalidate();
}
}
| lgpl-3.0 |
robcowell/dynamicreports | dynamicreports-core/src/test/java/net/sf/dynamicreports/test/jasper/chart/MultiAxisChartDataTest.java | 5704 | /**
* DynamicReports - Free Java reporting library for creating reports dynamically
*
* Copyright (C) 2010 - 2012 Ricardo Mariaca
* http://dynamicreports.sourceforge.net
*
* This file is part of DynamicReports.
*
* DynamicReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* DynamicReports is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with DynamicReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.dynamicreports.test.jasper.chart;
import static net.sf.dynamicreports.report.builder.DynamicReports.*;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import junit.framework.Assert;
import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.report.builder.FieldBuilder;
import net.sf.dynamicreports.report.builder.chart.TimeSeriesChartBuilder;
import net.sf.dynamicreports.report.constant.TimePeriod;
import net.sf.dynamicreports.report.datasource.DRDataSource;
import net.sf.dynamicreports.test.jasper.AbstractJasperChartTest;
import net.sf.jasperreports.engine.JRDataSource;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
/**
* @author Ricardo Mariaca (dynamicreports@gmail.com)
*/
public class MultiAxisChartDataTest extends AbstractJasperChartTest implements Serializable {
private static final long serialVersionUID = 1L;
@Override
protected void configureReport(JasperReportBuilder rb) {
FieldBuilder<Date> field1 = field("field1", type.dateType());
FieldBuilder<Integer> field2 = field("field2", type.integerType());
FieldBuilder<Integer> field3 = field("field3", type.integerType());
TimeSeriesChartBuilder chart1 = cht.timeSeriesChart()
.setTimePeriod(field1)
.setTimePeriodType(TimePeriod.DAY)
.series(cht.serie(field2).setLabel("serie1"));
TimeSeriesChartBuilder chart2 = cht.timeSeriesChart()
.setTimePeriod(field1)
.setTimePeriodType(TimePeriod.DAY)
.series(cht.serie(field3).setLabel("serie2"));
TimeSeriesChartBuilder chart3 = cht.timeSeriesChart()
.setDataSource(createDataSource2())
.setTimePeriod(field1)
.setTimePeriodType(TimePeriod.DAY)
.series(cht.serie(field2).setLabel("serie1"));
rb.summary(
cht.multiAxisChart(chart1, chart2).setDataSource(createDataSource1()),
cht.multiAxisChart(chart3, chart2).setDataSource(createDataSource1()));
}
@Override
public void test() {
super.test();
numberOfPagesTest(1);
JFreeChart chart = getChart("summary.chart1", 0);
XYItemRenderer renderer = chart.getXYPlot().getRenderer();
Assert.assertEquals("renderer", XYLineAndShapeRenderer.class, renderer.getClass());
TimeSeriesCollection dataset = (TimeSeriesCollection) chart.getXYPlot().getDataset(0);
TimeSeries serie = (TimeSeries) dataset.getSeries().get(0);
Assert.assertEquals("value", 1d, serie.getDataItem(0).getValue());
Assert.assertEquals("value", 2d, serie.getDataItem(1).getValue());
Assert.assertEquals("value", 3d, serie.getDataItem(2).getValue());
Assert.assertEquals("value", 4d, serie.getDataItem(3).getValue());
dataset = (TimeSeriesCollection) chart.getXYPlot().getDataset(1);
serie = (TimeSeries) dataset.getSeries().get(0);
Assert.assertEquals("value", 0d, serie.getDataItem(0).getValue());
Assert.assertEquals("value", 1d, serie.getDataItem(1).getValue());
Assert.assertEquals("value", 4d, serie.getDataItem(2).getValue());
Assert.assertEquals("value", 9d, serie.getDataItem(3).getValue());
chart = getChart("summary.chart2", 0);
renderer = chart.getXYPlot().getRenderer();
Assert.assertEquals("renderer", XYLineAndShapeRenderer.class, renderer.getClass());
dataset = (TimeSeriesCollection) chart.getXYPlot().getDataset(0);
serie = (TimeSeries) dataset.getSeries().get(0);
Assert.assertEquals("value", 2d, serie.getDataItem(0).getValue());
Assert.assertEquals("value", 3d, serie.getDataItem(1).getValue());
Assert.assertEquals("value", 4d, serie.getDataItem(2).getValue());
Assert.assertEquals("value", 5d, serie.getDataItem(3).getValue());
dataset = (TimeSeriesCollection) chart.getXYPlot().getDataset(1);
serie = (TimeSeries) dataset.getSeries().get(0);
Assert.assertEquals("value", 0d, serie.getDataItem(0).getValue());
Assert.assertEquals("value", 1d, serie.getDataItem(1).getValue());
Assert.assertEquals("value", 4d, serie.getDataItem(2).getValue());
Assert.assertEquals("value", 9d, serie.getDataItem(3).getValue());
}
public JRDataSource createDataSource1() {
DRDataSource dataSource = new DRDataSource("field1", "field2", "field3");
Calendar c = Calendar.getInstance();
c.setTime(new Date());
for (int i = 0; i < 4; i++) {
dataSource.add(c.getTime(), i + 1, i * i);
c.add(Calendar.DAY_OF_MONTH, 1);
}
return dataSource;
}
public JRDataSource createDataSource2() {
DRDataSource dataSource = new DRDataSource("field1", "field2");
Calendar c = Calendar.getInstance();
c.setTime(new Date());
for (int i = 0; i < 4; i++) {
dataSource.add(c.getTime(), i + 2);
c.add(Calendar.DAY_OF_MONTH, 1);
}
return dataSource;
}
}
| lgpl-3.0 |
swift-nav/libsbp | java/src/com/swiftnav/sbp/bootload/MsgBootloaderHandshakeReq.java | 1863 | /*
* Copyright (C) 2015 Swift Navigation Inc.
* Contact: Gareth McMullin <gareth@swiftnav.com>
* Contact: Bhaskar Mookerji <mookerji@swiftnav.com>
*
* This source is subject to the license found in the file 'LICENSE' which must
* be be distributed together with this source. All other rights reserved.
*
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
*/
package com.swiftnav.sbp.bootload;
import com.swiftnav.sbp.SBPMessage;
import com.swiftnav.sbp.SBPBinaryException;
import com.swiftnav.sbp.SBPStruct;
import org.json.JSONObject;
import org.json.JSONArray;
/** SBP class for message MSG_BOOTLOADER_HANDSHAKE_REQ (0x00B3).
*
* You can have MSG_BOOTLOADER_HANDSHAKE_REQ inherent its fields directly from
* an inherited SBP object, or construct it inline using a dict of its
* fields.
*
* The handshake message request from the host establishes a
* handshake between the device bootloader and the host. The
* response from the device is MSG_BOOTLOADER_HANDSHAKE_RESP. */
public class MsgBootloaderHandshakeReq extends SBPMessage {
public static final int TYPE = 0x00B3;
public MsgBootloaderHandshakeReq (int sender) { super(sender, TYPE); }
public MsgBootloaderHandshakeReq () { super(TYPE); }
public MsgBootloaderHandshakeReq (SBPMessage msg) throws SBPBinaryException {
super(msg);
assert msg.type != TYPE;
}
@Override
protected void parse(Parser parser) throws SBPBinaryException {
/* Parse fields from binary */
}
@Override
protected void build(Builder builder) {
}
@Override
public JSONObject toJSON() {
JSONObject obj = super.toJSON();
return obj;
}
} | lgpl-3.0 |
Mind4SE/dataflow-bip | beam-backend/src/main/java/org/ow2/mind/beam/adl/BipDefinitionSourceGenerator.java | 19345 | /**
* Copyright (C) 2010 STMicroelectronics
* Copyright (C) 2010 VERIMAG
* Copyright (C) 2014 Schneider-Electric
*
* This file is part of "Mind Compiler"
* The "Mind Compiler" is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact: mind@ow2.org
*
* Authors: Matthieu Leclercq, Marc Poulhiès
* Contributors:
* - Stephane Seyvoz - mind-compiler 2.1-SNAPSHOT support
*/
package org.ow2.mind.beam.adl;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.StringTemplateGroup;
import org.antlr.stringtemplate.StringTemplateGroupLoader;
import org.antlr.stringtemplate.language.AngleBracketTemplateLexer;
import org.objectweb.fractal.adl.ADLException;
import org.objectweb.fractal.adl.Definition;
import org.objectweb.fractal.adl.interfaces.Interface;
import org.objectweb.fractal.adl.interfaces.InterfaceContainer;
import org.objectweb.fractal.adl.types.TypeInterface;
import org.objectweb.fractal.adl.util.FractalADLLogManager;
import org.ow2.mind.InputResourceLocator;
import org.ow2.mind.adl.DefinitionSourceGenerator;
import org.ow2.mind.adl.ast.ASTHelper;
import org.ow2.mind.adl.ast.Attribute;
import org.ow2.mind.adl.ast.AttributeContainer;
import org.ow2.mind.adl.ast.Data;
import org.ow2.mind.adl.ast.ImplementationContainer;
import org.ow2.mind.adl.ast.MindInterface;
import org.ow2.mind.adl.ast.Source;
import org.ow2.mind.adl.idl.InterfaceDefinitionDecorationHelper;
import org.ow2.mind.adl.implementation.ImplementationLocator;
import org.ow2.mind.beam.BackendCommandLineHandler;
import org.ow2.mind.beam.annotation.BeamFilterAnnotationProcessor;
import org.ow2.mind.idl.IDLLoader;
import org.ow2.mind.idl.ast.InterfaceDefinition;
import org.ow2.mind.idl.ast.Method;
import org.ow2.mind.idl.ast.Parameter;
import org.ow2.mind.idl.ast.PointerOf;
import org.ow2.mind.idl.ast.PrimitiveType;
import org.ow2.mind.idl.ast.Type;
import org.ow2.mind.idl.ast.TypeDefReference;
import org.ow2.mind.io.OutputFileLocator;
import ujf.verimag.bip.Core.ActionLanguage.Actions.CompositeAction;
import ujf.verimag.bip.Core.ActionLanguage.Expressions.FunctionCallExpression;
import ujf.verimag.bip.Core.ActionLanguage.Expressions.VariableReference;
import ujf.verimag.bip.Core.Behaviors.AtomType;
import ujf.verimag.bip.Core.Behaviors.DataParameter;
import ujf.verimag.bip.Core.Behaviors.DataType;
import ujf.verimag.bip.Core.Behaviors.Expression;
import ujf.verimag.bip.Core.Behaviors.PetriNet;
import ujf.verimag.bip.Core.Behaviors.PortDefinition;
import ujf.verimag.bip.Core.Behaviors.PortType;
import ujf.verimag.bip.Core.Behaviors.State;
import ujf.verimag.bip.Core.Behaviors.Transition;
import ujf.verimag.bip.Core.Behaviors.Variable;
import ujf.verimag.bip.Core.Interactions.CompoundType;
import ujf.verimag.bip.Core.Modules.Module;
import ujf.verimag.bip.Core.Modules.OpaqueElement;
import ujf.verimag.bip.codegen.C2BIPUtil;
import ujf.verimag.bip.codegen.C2BIPVisitor;
import ujf.verimag.bip.codegen.InteractionPoint;
import ujf.verimag.bip.metamodelAPI.BipCreator;
import ujf.verimag.bip.metamodelAPI.BipUtil;
import com.google.inject.Inject;
/*
* If you wonder why all the backend is not part of a single class...
* The single would have to implement DefinitionSG *and* InstanceSG,
* which in turn makes the class inherits from two conflicting interface:
* each one implement VoidVisitor with different generic types, which
* is not supported by Java.
*/
public class BipDefinitionSourceGenerator implements DefinitionSourceGenerator {
final public static String BEAM_BIP_MODEL = "beam-bip-model";
final public static String BEAM_BIP_ROOT_COMP_DEF = "beam-bip-root-comp-def";
final public static String ENTRY_METHOD_IN_FILTERS = "filterctrl__act";
final public static String PORTTYPE_BUFFER_PREFIX = "ptbuf_";
protected static Logger logger = FractalADLLogManager
.getLogger("beam-bip-visitor::definition");
protected static int buffer_uniq_id = 0;
// ---------------------------------------------------------------------------
// Client Interfaces
// ---------------------------------------------------------------------------
/** Client interface used to locate output files. */
@Inject
public OutputFileLocator outputFileLocatorItf;
/** client interface used to checks timestamps of input resources. */
@Inject
public InputResourceLocator inputResourceLocatorItf;
@Inject
public ImplementationLocator implementationLocatorItf;
@Inject
public IDLLoader idlLoaderItf;
/** The {@link StringTemplateGroupLoader} client interface. */
@Inject
public StringTemplateGroupLoader templateLoaderItf;
protected ujf.verimag.bip.Core.Modules.System model;
protected Set<String> header_types_for_buffers = new HashSet<String>();
public BipDefinitionSourceGenerator(){
this.model = BipCreator.createSystem("mysystem");
}
/**
* Returns the StringTemplate template with the given
* <code>templateName</code> name and found in the
* <code>templateGroupName</code> group.
*
* @param templateGroupName the groupName from which the template must be
* loaded.
* @param templateName the name of the template.
* @return a StringTemplate template
* @see StringTemplateGroupLoader
*/
protected StringTemplate getTemplate(final String templateGroupName,
final String templateName) {
final StringTemplateGroup templateGroup = templateLoaderItf.loadGroup(
templateGroupName, AngleBracketTemplateLexer.class, null);
return templateGroup.getInstanceOf(templateName);
}
/**
* Mangles a mind component definition name into its corresponding
* BIP component definition name
* @param mindName the name of the mind component definition
* @return the corresponding BIP component definition name
*/
public static String mindToBipMangleName(String mindName){
return mindName.replace(".","__");
}
/**
* Converts a mind data type into a string
* @param t the mind data type
* @return a String representing the mind type
* @throws ADLException in case the type cannot be stringified
*/
private static String typeToString(Type t) throws ADLException{
String pointer_suffix = "";
String the_type = null;
while (t instanceof PointerOf){
pointer_suffix +="*";
t = ((PointerOf)t).getType();
}
if (t instanceof PrimitiveType){
PrimitiveType pt = (PrimitiveType)t;
the_type = pt.getName() + pointer_suffix;
} else if (t instanceof TypeDefReference){
TypeDefReference pt = (TypeDefReference)t;
the_type = pt.getName() + pointer_suffix;
} else {
throw new ADLException(BeamErrors.BEAM_ERROR);
}
assert(the_type != null);
return the_type;
}
protected void createBufferAtom(String typedefs, String buffername, String typename){
PetriNet behav = BipCreator.createPetriNet();
AtomType buffer = BipCreator.createAtomType(behav, buffername, this.model);
State idle = BipCreator.createState(behav, "IDLE", true);
State in_state = BipCreator.createState(behav, "IN", true);
State out_state = BipCreator.createState(behav, "OUT", true);
State peek_state = BipCreator.createState(behav, "PEEK", true);
DataType dt = BipCreator.createDataType(typename, this.model);
DataType dsizet = BipCreator.createDataType("int", this.model);
DataType fifo_type = BipCreator.createDataType("fifo_" + typename + buffer_uniq_id +"_t", this.model);
DataParameter dpi = BipCreator.createDataParameter("ind", dt);
DataParameter dpo = BipCreator.createDataParameter("outd", dt);
PortType pt_buf = BipCreator.createPortType(PORTTYPE_BUFFER_PREFIX + buffername, this.model, new DataParameter[]{dpi});
Variable inv = BipCreator.createVariable(dt, "inv", buffer, false, false);
Variable outv = BipCreator.createVariable(dt, "outv", buffer, false, false);
Variable sizev = BipCreator.createVariable(dsizet, "sizev", buffer, false, false);
Variable peekv = BipCreator.createVariable(dsizet, "peekv", buffer, false, false);
Variable innerfifo = BipCreator.createVariable(fifo_type, "innerfifo", buffer, false, false);
PortDefinition pin_s = BipCreator.createPortDefinitionAndExport(pt_buf, "in_S", new Variable[]{inv}, buffer);
PortDefinition pin_e = BipCreator.createPortDefinitionAndExport(pt_buf, "in_E", new Variable[]{inv}, buffer);
PortDefinition pout_s = BipCreator.createPortDefinitionAndExport(pt_buf, "out_S", new Variable[]{outv}, buffer);
PortDefinition pout_e = BipCreator.createPortDefinitionAndExport(pt_buf, "out_E", new Variable[]{outv}, buffer);
PortDefinition ppeek_s = BipCreator.createPortDefinitionAndExport(pt_buf, "peek_S", new Variable[]{peekv}, buffer);
PortDefinition ppeek_e = BipCreator.createPortDefinitionAndExport(pt_buf, "peek_E", new Variable[]{outv}, buffer);
PortDefinition psize = BipCreator.createPortDefinitionAndExport(pt_buf, "size_S", new Variable[]{sizev}, buffer);
// push transition
Transition push_trans = BipCreator.createTransition(pin_s, null, idle, in_state, buffer);
CompositeAction ca = BipCreator.createCompositeAction();
push_trans.setAction(ca);
FunctionCallExpression fce = BipCreator.createFunctionCallExpression("_push_" + typename + buffer_uniq_id, new Expression[]{
BipCreator.createVariableReference(inv),
BipCreator.createFunctionCallExpression("R", new Expression[]{BipCreator.createVariableReference(innerfifo)})
});
ca.getContent().add(fce);
BipCreator.createTransition(pin_e, null, in_state, idle, buffer);
// Peek transition
Transition peek_trans = BipCreator.createTransition(ppeek_s, null, idle, peek_state, buffer);
BipCreator.createTransition(ppeek_e, null, peek_state, idle, buffer);
ca = BipCreator.createCompositeAction();
peek_trans.setAction(ca);
VariableReference out_vr = BipCreator.createVariableReference(outv);
fce = BipCreator.createFunctionCallExpression("_peek_" + typename + buffer_uniq_id, new Expression[]{
BipCreator.createFunctionCallExpression("R", new Expression[]{BipCreator.createVariableReference(innerfifo)})
});
ca.getContent().add(BipCreator.createAssignmentAction(out_vr, fce));
// pop transition
Transition pop_trans = BipCreator.createTransition(pout_s, null, idle, out_state, buffer);
BipCreator.createTransition(pout_e, null, out_state, idle, buffer);
ca = BipCreator.createCompositeAction();
pop_trans.setAction(ca);
out_vr = BipCreator.createVariableReference(outv);
fce = BipCreator.createFunctionCallExpression("_pop_" + typename + buffer_uniq_id, new Expression[]{
BipCreator.createFunctionCallExpression("R", new Expression[]{BipCreator.createVariableReference(innerfifo)})
});
ca.getContent().add(BipCreator.createAssignmentAction(out_vr, fce));
StringTemplate buffer_st = getTemplate("st.beam.bip.Buffer", "SimpleFifo");
assert(buffer_st != null);
buffer_st.setAttribute("type", typename);
buffer_st.setAttribute("size", 256);
buffer_st.setAttribute("id", buffer_uniq_id);
OpaqueElement header_oe = BipCreator.createOpaqueElementFromCCode(typedefs + buffer_st.toString(),true);
BipUtil.addDeclarationToModule(this.model, header_oe);
buffer_uniq_id++;
}
// ---------------------------------------------------------------------------
// Implementation of the Visitor interface
// ---------------------------------------------------------------------------
public void visit(Definition input, Map<Object, Object> context)
throws ADLException {
logger.log(Level.INFO, "Visiting definition " + input.getName());
if (!context.containsKey(BackendCommandLineHandler.BEAM_ENABLE_BIP_BACKEND)){
return;
}
if (!context.containsKey(BEAM_BIP_MODEL)){
context.put(BEAM_BIP_MODEL, this.model);
}
if (ASTHelper.isComposite(input)){
CompoundType ct = BipCreator.createCompoundType(mindToBipMangleName(input.getName()), this.model);
context.put(BEAM_BIP_ROOT_COMP_DEF, ct);
} else {
// if no decoration found, means that it is not a filter => do not translate it.
Object o = input.astGetDecoration(BeamFilterAnnotationProcessor.DEFINITION_HAS_INSTANCE_FILTER);
if (o == null)
return;
assert(input instanceof ImplementationContainer);
ImplementationContainer ic = (ImplementationContainer) input;
Source[] srcs = ic.getSources();
// Currently, we do not support components with multiple source files.
// All files could be concatenated into a single file and then parsed.
assert(srcs.length == 1);
List<InteractionPoint> ips = new ArrayList<InteractionPoint>();
assert (input instanceof InterfaceContainer);
for(final Interface iface: ((InterfaceContainer)input).getInterfaces()){
assert(iface instanceof MindInterface);
MindInterface miface = (MindInterface)iface;
InterfaceDefinition idef =
InterfaceDefinitionDecorationHelper.getResolvedInterfaceDefinition(miface,
idlLoaderItf, context);
/*
* Following SB are used to create a union type, wrapped in a struct. One
* for each interface. This is used to create a fifo component that will hold
* the data to be queued.
* This is overkill for the current task, as our FIFO should hold only elements of the same type.
*/
StringBuffer iface_struct = new StringBuffer();
iface_struct.append("\ntypedef struct {\n");
iface_struct.append(" int tid;\n");
iface_struct.append(" union {\n");
for (final Method m: idef.getMethods()){
String fname = miface.getName() + "__" + m.getName();
String mname = m.getName();
StringBuffer struct_declaration = new StringBuffer();
struct_declaration.append("struct {\n");
Type t = m.getType();
String return_type = typeToString(t);
Parameter[] params = m.getParameters();
List<String> param_types = new ArrayList<String>();
for (final Parameter param: params){
Type param_t = param.getType();
String param_t_name = typeToString(param_t);
param_types.add(param_t_name);
struct_declaration.append(" " + param_t_name + " " + param.getName() + ";\n");
}
String[] params_string = param_types.toArray(new String[0]);
InteractionPoint ip = new InteractionPoint(return_type, fname, params_string);
ips.add(ip);
// struct_declaration.append("} " + mname + "_arg_t;\n");
struct_declaration.append(" } ");
iface_struct.append(" " + struct_declaration.toString() + mname + ";\n");
}
String iface_union_wrapped_tname = idef.getName().replace('.', '_') + "_arg_t";
iface_struct.append(" } data;\n} " + iface_union_wrapped_tname + ";\n");
if (miface.getRole().equals(TypeInterface.CLIENT_ROLE) && !header_types_for_buffers.contains(iface_union_wrapped_tname)){
createBufferAtom(iface_struct.toString(), idef.getName().replace('.', '_'), iface_union_wrapped_tname);
header_types_for_buffers.add(iface_union_wrapped_tname);
}
}
Map<String,String> attributes = new HashMap<String,String>();
assert (input instanceof AttributeContainer);
for(final Attribute attr: ((AttributeContainer)input).getAttributes()){
attributes.put(attr.getType(), "attr_" + attr.getName());
}
InteractionPoint[] ips_array = ips.toArray(new InteractionPoint[0]);
// we loop over all srcs. First version of the code forces
// the list to contain only one element (looping only once...)
for (final Source src : srcs){
URL f = implementationLocatorItf.findResource(src.getPath(), context);
String local_c_context =
"#define BEAM_PARSE_SHIELD\n" +
"#define START_ACT_LOOP \n" +
"#define END_ACT_LOOP \n" +
"\n/* for interface methods */ \n" +
"#define METH(x,y) x##__##y\n" +
"#define CALL(x,y) x##__##y\n" +
"\n/* for private method */\n"+
"#define PMETH(x) __priv_##x\n"+
"#define PCALL(x) __priv_##x\n" +
"#define ATTR(x) attr_##x\n";
// local_c_context += "typedef struct _frame_t { int len; unsigned char *buffer;} frame_t;\n";
Data data = ic.getData();
if (data != null && data.getCCode() != null){
local_c_context += data.getCCode() + "\n";
}
try {
C2BIPVisitor c2bipVisitor= new C2BIPVisitor(ENTRY_METHOD_IN_FILTERS,
mindToBipMangleName(input.getName()), attributes,
this.model, true);
System.out.println("File: " + f.toString());
// SSZ - Inspired from OW2 Mind SVN r1202/r1203 comparison (2 arguments were missing)
Module res = C2BIPUtil.c2bipAsModel(f.getFile(),
ENTRY_METHOD_IN_FILTERS,
mindToBipMangleName(input.getName()),
true, local_c_context,
ips_array, this.model, c2bipVisitor);
} catch (Exception e) {
throw new ADLException(BeamErrors.BEAM_ERROR, e);
}
}
}
}
}
| lgpl-3.0 |
mabe02/lanterna | src/main/java/com/googlecode/lanterna/gui2/table/DefaultTableHeaderRenderer.java | 1817 | /*
* This file is part of lanterna (https://github.com/mabe02/lanterna).
*
* lanterna is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright (C) 2010-2020 Martin Berglund
*/
package com.googlecode.lanterna.gui2.table;
import com.googlecode.lanterna.TerminalTextUtils;
import com.googlecode.lanterna.TerminalSize;
import com.googlecode.lanterna.graphics.ThemeDefinition;
import com.googlecode.lanterna.gui2.TextGUIGraphics;
/**
* Default implementation of {@code TableHeaderRenderer}
* @author Martin
*/
public class DefaultTableHeaderRenderer<V> implements TableHeaderRenderer<V> {
@Override
public TerminalSize getPreferredSize(Table<V> table, String label, int columnIndex) {
if(label == null) {
return TerminalSize.ZERO;
}
return new TerminalSize(TerminalTextUtils.getColumnWidth(label), 1);
}
@Override
public void drawHeader(Table<V> table, String label, int index, TextGUIGraphics textGUIGraphics) {
ThemeDefinition themeDefinition = table.getThemeDefinition();
textGUIGraphics.applyThemeStyle(themeDefinition.getCustom("HEADER", themeDefinition.getNormal()));
textGUIGraphics.putString(0, 0, label);
}
}
| lgpl-3.0 |
lburgazzoli/Chronicle-Map | src/main/java/net/openhft/chronicle/hash/serialization/impl/ByteBufferDataAccess.java | 3592 | /*
* Copyright (C) 2015 higherfrequencytrading.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.openhft.chronicle.hash.serialization.impl;
import net.openhft.chronicle.bytes.*;
import net.openhft.chronicle.hash.AbstractData;
import net.openhft.chronicle.hash.Data;
import net.openhft.chronicle.hash.serialization.DataAccess;
import net.openhft.chronicle.wire.WireIn;
import net.openhft.chronicle.wire.WireOut;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import sun.nio.ch.DirectBuffer;
import java.nio.ByteBuffer;
public class ByteBufferDataAccess extends AbstractData<ByteBuffer>
implements DataAccess<ByteBuffer> {
// Cache fields
private transient HeapBytesStore heapBytesStore;
private transient NativeBytesStore nativeBytesStore;
private transient VanillaBytes<Void> bytes;
// State fields
private transient ByteBuffer bb;
private transient BytesStore bytesStore;
public ByteBufferDataAccess() {
initTransients();
}
private void initTransients() {
heapBytesStore = HeapBytesStore.uninitialized();
nativeBytesStore = NativeBytesStore.uninitialized();
bytes = VanillaBytes.vanillaBytes();
}
@Override
public RandomDataInput bytes() {
return bytesStore;
}
@Override
public long offset() {
return bb.position();
}
@Override
public long size() {
return bb.remaining();
}
@Override
public ByteBuffer get() {
return bb;
}
@Override
public ByteBuffer getUsing(@Nullable ByteBuffer using) {
if (using == null || using.capacity() < bb.remaining()) {
using = ByteBuffer.allocate(bb.remaining());
} else {
using.position(0);
using.limit(bb.remaining());
}
bytes.bytesStore(bytesStore, bb.position(), bb.remaining());
bytes.read(using);
using.flip();
return using;
}
@Override
public Data<ByteBuffer> getData(@NotNull ByteBuffer instance) {
bb = instance;
if (instance instanceof DirectBuffer) {
nativeBytesStore.init(instance, false);
bytesStore = nativeBytesStore;
} else {
heapBytesStore.init(instance);
bytesStore = heapBytesStore;
}
return this;
}
@Override
public void uninit() {
bb = null;
if (bytesStore == nativeBytesStore) {
nativeBytesStore.uninit();
} else {
heapBytesStore.uninit();
}
}
@Override
public DataAccess<ByteBuffer> copy() {
return new ByteBufferDataAccess();
}
@Override
public void readMarshallable(@NotNull WireIn wireIn) {
// no fields to read
initTransients();
}
@Override
public void writeMarshallable(@NotNull WireOut wireOut) {
// no fields to write
}
}
| lgpl-3.0 |
OurGrid/OurGrid | src/test/java/org/ourgrid/common/config/ConfigurationTest.java | 707 | package org.ourgrid.common.config;
import junit.framework.Assert;
import org.junit.Test;
import org.ourgrid.system.config.FakeConfiguration;
public class ConfigurationTest {
@Test
public void testGetProperty() {
Configuration conf = new FakeConfiguration();
conf.setProperty("worker.publicKey", "ABC");
Assert.assertEquals("ABC", conf.getProperty("worker.publicKey"));
conf.setProperty("publicKey", "DEF");
Assert.assertEquals("ABC", conf.getProperty("worker.publicKey"));
}
@Test
public void testGetPropertyNoPrefix() {
Configuration conf = new FakeConfiguration();
conf.setProperty("publicKey", "DEF");
Assert.assertEquals("DEF", conf.getProperty("worker.publicKey"));
}
}
| lgpl-3.0 |
robcowell/dynamicreports | dynamicreports-core/src/main/java/net/sf/dynamicreports/report/base/grid/DRColumnTitleGroup.java | 6583 | /**
* DynamicReports - Free Java reporting library for creating reports dynamically
*
* Copyright (C) 2010 - 2012 Ricardo Mariaca
* http://dynamicreports.sourceforge.net
*
* This file is part of DynamicReports.
*
* DynamicReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* DynamicReports is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with DynamicReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.dynamicreports.report.base.grid;
import java.util.ArrayList;
import java.util.List;
import net.sf.dynamicreports.report.constant.ComponentDimensionType;
import net.sf.dynamicreports.report.constant.Constants;
import net.sf.dynamicreports.report.constant.ListType;
import net.sf.dynamicreports.report.definition.expression.DRIExpression;
import net.sf.dynamicreports.report.definition.expression.DRIPropertyExpression;
import net.sf.dynamicreports.report.definition.grid.DRIColumnGridComponent;
import net.sf.dynamicreports.report.definition.grid.DRIColumnTitleGroup;
import net.sf.dynamicreports.report.definition.style.DRIReportStyle;
import org.apache.commons.lang3.Validate;
/**
* @author Ricardo Mariaca (dynamicreports@gmail.com)
*/
public class DRColumnTitleGroup implements DRIColumnTitleGroup {
private static final long serialVersionUID = Constants.SERIAL_VERSION_UID;
private DRColumnGridList list;
private DRIExpression<?> titleExpression;
private DRIReportStyle titleStyle;
private Integer titleWidth;
private ComponentDimensionType titleWidthType;
private Integer titleColumns;
private Integer titleHeight;
private ComponentDimensionType titleHeightType;
private Integer titleRows;
private Boolean titleStretchWithOverflow;
private List<DRIPropertyExpression> titlePropertyExpressions;
public DRColumnTitleGroup() {
this.list = new DRColumnGridList(ListType.HORIZONTAL);
titlePropertyExpressions = new ArrayList<DRIPropertyExpression>();
}
@Override
public DRColumnGridList getList() {
return list;
}
public void addComponent(DRIColumnGridComponent component) {
list.addComponent(component);
}
@Override
public DRIExpression<?> getTitleExpression() {
return titleExpression;
}
public void setTitleExpression(DRIExpression<?> titleExpression) {
this.titleExpression = titleExpression;
}
@Override
public DRIReportStyle getTitleStyle() {
return titleStyle;
}
public void setTitleStyle(DRIReportStyle titleStyle) {
this.titleStyle = titleStyle;
}
/**
* Returns the column title width.
*
* @return the column title width >= 0
*/
@Override
public Integer getTitleWidth() {
return titleWidth;
}
/**
* Sets the column title width.
* @see net.sf.dynamicreports.report.builder.Units
*
* @param titleWidth the column title width >= 0
* @exception IllegalArgumentException if <code>titleWidth</code> is < 0
*/
public void setTitleWidth(Integer titleWidth) {
if (titleWidth != null) {
Validate.isTrue(titleWidth >= 0, "titleWidth must be >= 0");
}
this.titleWidth = titleWidth;
}
@Override
public ComponentDimensionType getTitleWidthType() {
return titleWidthType;
}
public void setTitleWidthType(ComponentDimensionType titleWidthType) {
this.titleWidthType = titleWidthType;
}
/**
* Returns the number of title columns.
*
* @return the number of title columns >= 0
*/
@Override
public Integer getTitleColumns() {
return titleColumns;
}
/**
* This method is used to define the width of a column title.
* The width is set to the <code>columns</code> multiplied by width of the
* character <em>m</em> for the font used
*
* @param titleColumns the number of columns >= 0
* @exception IllegalArgumentException if <code>columns</code> is < 0
*/
public void setTitleColumns(Integer titleColumns) {
if (titleColumns != null) {
Validate.isTrue(titleColumns >= 0, "titleColumns must be >= 0");
}
this.titleColumns = titleColumns;
}
/**
* Returns the column title height.
*
* @return the column title height >= 0
*/
@Override
public Integer getTitleHeight() {
return titleHeight;
}
/**
* Sets the column title height.
* @see net.sf.dynamicreports.report.builder.Units
*
* @param titleHeight the column title height >= 0
* @exception IllegalArgumentException if <code>titleHeight</code> is < 0
*/
public void setTitleHeight(Integer titleHeight) {
if (titleHeight != null) {
Validate.isTrue(titleHeight >= 0, "titleHeight must be >= 0");
}
this.titleHeight = titleHeight;
}
@Override
public ComponentDimensionType getTitleHeightType() {
return titleHeightType;
}
public void setTitleHeightType(ComponentDimensionType titleHeightType) {
this.titleHeightType = titleHeightType;
}
/**
* Returns the number of title rows.
*
* @return the number of title rows >= 0
*/
@Override
public Integer getTitleRows() {
return titleRows;
}
/**
* This method is used to define the height of a column title.
* The height is set to the <code>rows</code> multiplied by height of the font
*
* @param titleRows the number of rows >= 0
* @exception IllegalArgumentException if <code>rows</code> is < 0
*/
public void setTitleRows(Integer titleRows) {
if (titleRows != null) {
Validate.isTrue(titleRows >= 0, "titleRows must be >= 0");
}
this.titleRows = titleRows;
}
@Override
public Boolean getTitleStretchWithOverflow() {
return titleStretchWithOverflow;
}
public void setTitleStretchWithOverflow(Boolean titleStretchWithOverflow) {
this.titleStretchWithOverflow = titleStretchWithOverflow;
}
@Override
public List<DRIPropertyExpression> getTitlePropertyExpressions() {
return titlePropertyExpressions;
}
public void addTitlePropertyExpression(DRIPropertyExpression propertyExpression) {
Validate.notNull(propertyExpression, "propertyExpression must not be null");
this.titlePropertyExpressions.add(propertyExpression);
}
public void setTitlePropertyExpressions(List<DRIPropertyExpression> titlePropertyExpressions) {
this.titlePropertyExpressions = titlePropertyExpressions;
}
}
| lgpl-3.0 |
jblievremont/sonarqube | sonar-batch/src/test/java/org/sonar/batch/report/SourcePublisherTest.java | 4241 | /*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.batch.report;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.database.model.Snapshot;
import org.sonar.api.resources.Project;
import org.sonar.api.resources.Qualifiers;
import org.sonar.batch.index.BatchComponentCache;
import org.sonar.batch.protocol.output.BatchReportWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import static org.assertj.core.api.Assertions.assertThat;
public class SourcePublisherTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private SourcePublisher publisher;
private File sourceFile;
private BatchReportWriter writer;
private org.sonar.api.resources.File sampleFile;
@Before
public void prepare() throws IOException {
Project p = new Project("foo").setAnalysisDate(new Date(1234567L));
BatchComponentCache resourceCache = new BatchComponentCache();
sampleFile = org.sonar.api.resources.File.create("src/Foo.php");
sampleFile.setEffectiveKey("foo:src/Foo.php");
resourceCache.add(p, null).setSnapshot(new Snapshot().setId(2));
File baseDir = temp.newFolder();
sourceFile = new File(baseDir, "src/Foo.php");
resourceCache.add(sampleFile, null).setInputPath(
new DefaultInputFile("foo", "src/Foo.php").setLines(5).setModuleBaseDir(baseDir.toPath()).setCharset(StandardCharsets.ISO_8859_1));
publisher = new SourcePublisher(resourceCache);
File outputDir = temp.newFolder();
writer = new BatchReportWriter(outputDir);
}
@Test
public void publishEmptySource() throws Exception {
FileUtils.write(sourceFile, "", StandardCharsets.ISO_8859_1);
publisher.publish(writer);
File out = writer.getSourceFile(2);
assertThat(FileUtils.readFileToString(out, StandardCharsets.UTF_8)).isEqualTo("");
}
@Test
public void publishSourceWithLastEmptyLine() throws Exception {
FileUtils.write(sourceFile, "1\n2\n3\n4\n", StandardCharsets.ISO_8859_1);
publisher.publish(writer);
File out = writer.getSourceFile(2);
assertThat(FileUtils.readFileToString(out, StandardCharsets.UTF_8)).isEqualTo("1\n2\n3\n4\n");
}
@Test
public void publishTestSource() throws Exception {
FileUtils.write(sourceFile, "1\n2\n3\n4\n", StandardCharsets.ISO_8859_1);
sampleFile.setQualifier(Qualifiers.UNIT_TEST_FILE);
publisher.publish(writer);
File out = writer.getSourceFile(2);
assertThat(FileUtils.readFileToString(out, StandardCharsets.UTF_8)).isEqualTo("1\n2\n3\n4\n");
}
@Test
public void publishSourceWithLastLineNotEmpty() throws Exception {
FileUtils.write(sourceFile, "1\n2\n3\n4\n5", StandardCharsets.ISO_8859_1);
publisher.publish(writer);
File out = writer.getSourceFile(2);
assertThat(FileUtils.readFileToString(out, StandardCharsets.UTF_8)).isEqualTo("1\n2\n3\n4\n5");
}
@Test
public void cleanLineEnds() throws Exception {
FileUtils.write(sourceFile, "\n2\r\n3\n4\r5", StandardCharsets.ISO_8859_1);
publisher.publish(writer);
File out = writer.getSourceFile(2);
assertThat(FileUtils.readFileToString(out, StandardCharsets.UTF_8)).isEqualTo("\n2\n3\n4\n5");
}
}
| lgpl-3.0 |
mshonle/Arcum | src/edu/ucsd/arcum/interpreter/fragments/Union.java | 101 | package edu.ucsd.arcum.interpreter.fragments;
public @interface Union
{
String value();
}
| lgpl-3.0 |
deelam/agilion | dataengine/workers/src/main/java/dataengine/workers/OperationsSubscriber.java | 2450 | package dataengine.workers;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import javax.jms.BytesMessage;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import dataengine.api.Operation;
import dataengine.apis.CommunicationConsts;
import dataengine.apis.OperationsRegistry_I;
import dataengine.apis.OperationsRegistry_I.OPERATIONS_REG_API;
import lombok.extern.slf4j.Slf4j;
import net.deelam.activemq.MQClient;
import net.deelam.activemq.rpc.KryoSerDe;
@Slf4j
public class OperationsSubscriber implements Closeable {
private Session session;
private MessageConsumer consumer;
private MessageProducer producer;
private final Worker_I[] workers;
public OperationsSubscriber(Connection connection, Worker_I... workers) throws JMSException {
this.workers = workers;
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
producer = MQClient.createGenericMsgResponder(session, DeliveryMode.NON_PERSISTENT);
listen(CommunicationConsts.OPSREGISTRY_SUBSCRIBER_TOPIC);
}
private void listen(String topicName) {
KryoSerDe serde = new KryoSerDe(session);
try {
MQClient.createTopicConsumer(session, topicName, message -> {
String command = message.getStringProperty(OperationsRegistry_I.COMMAND_PARAM);
switch (OPERATIONS_REG_API.valueOf(command)) {
case GET_OPERATIONS: {
ArrayList<Operation> list = new ArrayList<>();
for (Worker_I worker : workers)
list.add(worker.operation());
BytesMessage response = serde.writeObject(list);
response.setJMSCorrelationID(message.getJMSCorrelationID());
log.info("Sending response: {}", response);
producer.send(message.getJMSReplyTo(), response);
break;
}
default:
log.warn("Unknown request: {}", message);
}
});
} catch (Exception e) {
log.error("When setting up OperationsSubscriber:", e);
}
}
@Override
public void close() throws IOException {
try {
producer.close();
consumer.close();
session.close();
} catch (JMSException e) {
throw new IllegalStateException("When closing "+this.getClass().getSimpleName(), e);
}
}
}
| lgpl-3.0 |
sitec-systems/jmoduleconnect | src/main/java/de/sitec_systems/jmoduleconnect/at/AtListener.java | 1559 | /**
* jModuleConnect is an framework for communication and file management on modem
* modules.
*
* This project was inspired by the project TC65SH
* by Christoph Vilsmeier: <http://www.vilsmeier-consulting.de/tc65sh.html>
*
* Copyright (C) 2015 sitec systems GmbH <http://www.sitec-systems.de>
*
* This file is part of jModuleConnect.
*
* jModuleConnect is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* jModuleConnect is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with jModuleConnect. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Author: Mattes Standfuss
* Copyright (c): sitec systems GmbH, 2015
*/
package de.sitec_systems.jmoduleconnect.at;
import java.util.EventListener;
/**
* An interface for receiving <b>AT</b> events from device.
* @author sitec systems GmbH
* @since 1.0
*/
public interface AtListener extends EventListener
{
/**
* Notifys about new AT event.
* @param atEvent The event data
* @since 1.0
*/
void atEventReceived(final AtEvent atEvent);
}
| lgpl-3.0 |
duckdoom5/RpgEssentials | RpgServer/src/me/duckdoom5/RpgServer/config/Configuration.java | 2087 | package me.duckdoom5.RpgServer.config;
import java.io.FileNotFoundException;
import java.io.IOException;
import me.duckdoom5.RpgServer.RpgServer;
public class Configuration {
private static final String h = "[RpgServer] ";
public static MyConfiguration config;
static {
config = new MyConfiguration();
if (load(config, "config.yml")) {
config = MyConfiguration.loadConfiguration("plugins/RpgServer/config.yml");
Config.set();
save(config);
}
Config.set();
try {
config.save();
} catch (final Exception e) {
e.printStackTrace();
}
}
public static void start() {
RpgServer.log.info(h + "Static Configuration loading...");
}
private static void exclaim(String filename) {
RpgServer.log.info(h + "Saved file " + filename + "!");
}
private static void complain(String filename) {
RpgServer.log.severe(h + "On file " + filename + ":");
RpgServer.log.severe(h + "Invalid configuration! Did you use tabs or restrict permissions?");
}
private static void complainFileCreation(String filename) {
RpgServer.log.severe(h + "On file " + filename + ":");
RpgServer.log.severe(h + "Could NOT create default files! Did you restrict permissions?");
}
// return true if defaults need to be created
private static boolean load(MyConfiguration y, String name) {
try {
y.load("plugins/RpgServer/" + name);
} catch (final FileNotFoundException e) {
return true;
} catch (final Exception e) {
complain(name);
}
return false;
}
private static void save(MyConfiguration y) {
try {
y.save();
try {
y.load("plugins/RpgServer/" + y.getFilename());
} catch (final Exception e) {
}
exclaim(y.getFilename());
} catch (final IOException e) {
complainFileCreation(y.getFilename());
}
}
} | lgpl-3.0 |
XPerience-AOSP-Lollipop/XPerience_Kernel_Tweaker | app/src/main/java/mx/klozz/xperience/tweaker/util/Utils.java | 3210 | /*
* Copyright (C) 2014 Carlos Jesús <TeamMEX@XDA-Developers>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package mx.klozz.xperience.tweaker.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
public class Utils implements Constants {
public void toast(String message, Context context) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
public boolean existFile(String path) {
return new File(path).exists();
}
public int getInteger(String name, int defaults, Context context) {
return context.getSharedPreferences(PREF_NAME, 0)
.getInt(name, defaults);
}
public void saveInteger(String name, int value, Context context) {
context.getSharedPreferences(PREF_NAME, 0).edit().putInt(name, value)
.commit();
}
public String getString(String name, String defaults, Context context) {
return context.getSharedPreferences(PREF_NAME, 0).getString(name,
defaults);
}
public void saveString(String name, String value, Context context) {
context.getSharedPreferences(PREF_NAME, 0).edit()
.putString(name, value).commit();
}
public boolean getBoolean(String name, boolean defaults, Context context) {
return context.getSharedPreferences(PREF_NAME, 0).getBoolean(name,
defaults);
}
public void saveBoolean(String name, boolean value, Context context) {
context.getSharedPreferences(PREF_NAME, 0).edit()
.putBoolean(name, value).commit();
}
public String readFile(String filepath) {
try {
BufferedReader buffreader = new BufferedReader(new FileReader(
filepath), 256);
String line;
StringBuilder text = new StringBuilder();
while ((line = buffreader.readLine()) != null) {
text.append(line);
text.append("\n");
}
buffreader.close();
return text.toString().trim();
} catch (FileNotFoundException e) {
Log.e(TAG, filepath + "does not exist");
} catch (IOException e) {
Log.e(TAG, "I/O read error: " + filepath);
}
return null;
}
}
| lgpl-3.0 |
ChaoPang/molgenis | molgenis-ontology-core/src/main/java/org/molgenis/ontology/core/importer/OntologyImportService.java | 4197 | package org.molgenis.ontology.core.importer;
import com.google.common.collect.Lists;
import org.molgenis.data.*;
import org.molgenis.data.importer.EntitiesValidationReport;
import org.molgenis.data.importer.EntitiesValidationReportImpl;
import org.molgenis.data.importer.EntityImportReport;
import org.molgenis.data.importer.ImportService;
import org.molgenis.data.meta.MetaDataService;
import org.molgenis.data.support.QueryImpl;
import org.molgenis.ontology.core.importer.repository.OntologyFileExtensions;
import org.molgenis.ontology.core.meta.OntologyMetaData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import static java.util.Objects.requireNonNull;
import static org.molgenis.data.util.EntityUtils.asStream;
import static org.molgenis.ontology.core.meta.OntologyMetaData.ONTOLOGY;
@Service
public class OntologyImportService implements ImportService
{
private static final Logger LOG = LoggerFactory.getLogger(OntologyImportService.class);
private final DataService dataService;
public OntologyImportService(DataService dataService)
{
this.dataService = requireNonNull(dataService);
}
@Override
@Transactional
public EntityImportReport doImport(RepositoryCollection source, DatabaseAction databaseAction,
@Nullable String packageId)
{
if (databaseAction != DatabaseAction.ADD)
{
throw new IllegalArgumentException("Only ADD is supported");
}
EntityImportReport report = new EntityImportReport();
for (String entityTypeId : source.getEntityTypeIds())
{
try (Repository<Entity> sourceRepository = source.getRepository(entityTypeId))
{
Repository<Entity> targetRepository = dataService.getRepository(entityTypeId);
Integer count = targetRepository.add(asStream(sourceRepository));
report.addEntityCount(entityTypeId, count);
}
catch (IOException e)
{
LOG.error("", e);
throw new MolgenisDataException(e);
}
}
return report;
}
@Override
public EntitiesValidationReport validateImport(File file, RepositoryCollection source)
{
EntitiesValidationReport report = new EntitiesValidationReportImpl();
if (source.getRepository(ONTOLOGY) == null)
throw new MolgenisDataException("Exception Repository [" + ONTOLOGY + "] is missing");
boolean ontologyExists = false;
for (Entity ontologyEntity : source.getRepository(ONTOLOGY))
{
String ontologyIRI = ontologyEntity.getString(OntologyMetaData.ONTOLOGY_IRI);
String ontologyName = ontologyEntity.getString(OntologyMetaData.ONTOLOGY_NAME);
Entity ontologyQueryEntity = dataService.findOne(ONTOLOGY,
new QueryImpl<>().eq(OntologyMetaData.ONTOLOGY_IRI, ontologyIRI)
.or()
.eq(OntologyMetaData.ONTOLOGY_NAME, ontologyName));
ontologyExists = ontologyQueryEntity != null;
}
if (ontologyExists) throw new MolgenisDataException("The ontology you are trying to import already exists");
for (String entityTypeId : source.getEntityTypeIds())
{
report.getSheetsImportable().put(entityTypeId, !ontologyExists);
}
return report;
}
@Override
public boolean canImport(File file, RepositoryCollection source)
{
for (String extension : OntologyFileExtensions.getOntology())
{
if (file.getName().toLowerCase().endsWith(extension))
{
return true;
}
}
return false;
}
@Override
public int getOrder()
{
return 10;
}
@Override
public List<DatabaseAction> getSupportedDatabaseActions()
{
return Lists.newArrayList(DatabaseAction.ADD);
}
@Override
public boolean getMustChangeEntityName()
{
return false;
}
@Override
public Set<String> getSupportedFileExtensions()
{
return OntologyFileExtensions.getOntology();
}
@Override
public LinkedHashMap<String, Boolean> determineImportableEntities(MetaDataService metaDataService,
RepositoryCollection repositoryCollection, String defaultPackage)
{
return metaDataService.determineImportableEntities(repositoryCollection);
}
}
| lgpl-3.0 |
docbradley/d8b-controller | src/main/java/com/adamdbradley/demo/bridge/Model.java | 9705 | package com.adamdbradley.demo.bridge;
import com.adamdbradley.d8b.console.ConsoleControlConnection;
import com.adamdbradley.d8b.console.PanelLED;
import com.adamdbradley.d8b.console.command.LightPanelLED;
import com.adamdbradley.d8b.console.command.ShutPanelLED;
import com.adamdbradley.mcu.MCUClientPort;
import com.adamdbradley.mcu.console.ChannelLED;
import com.adamdbradley.mcu.console.DeviceType;
import com.adamdbradley.mcu.console.Fader;
import com.adamdbradley.mcu.console.protocol.command.LightChannelLED;
import com.adamdbradley.mcu.console.protocol.command.MoveFader;
import com.adamdbradley.mcu.console.protocol.command.ShutChannelLED;
import com.adamdbradley.mcu.console.protocol.command.WriteScreen;
import com.adamdbradley.mcu.console.protocol.command.WriteVPot;
import com.adamdbradley.mcu.console.protocol.command.WriteVPot.VPotMode;
public class Model {
public int d8bViewOffset = 0;
public int mcuViewOffset = 0;
private ConsoleControlConnection console;
private MCUClientPort mcuPort;
public void connect(ConsoleControlConnection console, MCUClientPort mcuPort) {
this.console = console;
this.mcuPort = mcuPort;
}
public final Channel[] channels;
public int masterVpotValue;
public VPotMode masterVpotMode;
public int masterFader;
public Model() {
channels = new Channel[48];
for (int i=0; i<channels.length; i++) {
channels[i] = new Channel();
}
}
public class Channel {
public int vpotValue;
public VPotMode vpotMode = VPotMode.SinglePosition;
public boolean record;
public boolean assign;
public boolean write;
public boolean green;
public boolean red;
public boolean select;
public boolean solo;
public boolean mute;
// 0 - 1023
public int fader;
}
public boolean record;
public TransportMode transportMode = TransportMode.Stopped;
public enum TransportMode {
Stopped,
Playing,
Paused,
Shuttling,
Rewinding,
FastForwarding
}
public void rewind(boolean b) {
if (b) {
if (transportMode == TransportMode.Stopped) {
transportMode = TransportMode.Rewinding;
displayTransportMode();
}
} else {
if (transportMode == TransportMode.Rewinding) {
transportMode = TransportMode.Stopped;
displayTransportMode();
}
}
}
public void fastFwd(boolean b) {
if (b) {
if (transportMode == TransportMode.Stopped) {
transportMode = TransportMode.FastForwarding;
displayTransportMode();
}
} else {
if (transportMode == TransportMode.FastForwarding) {
transportMode = TransportMode.Stopped;
displayTransportMode();
}
}
}
public void stop(boolean b) {
if (b) {
transportMode = TransportMode.Stopped;
displayTransportMode();
}
}
public void play(boolean b) {
if (b) {
if (transportMode == TransportMode.Stopped || transportMode == TransportMode.Paused) {
transportMode = TransportMode.Playing;
displayTransportMode();
} else if (transportMode == TransportMode.Playing) {
transportMode = TransportMode.Paused;
displayTransportMode();
}
}
}
public void record(boolean b) {
if (b) {
this.record = !this.record;
displayTransportMode();
}
}
private void displayTransportMode() {
if (record) {
console.send(new LightPanelLED(PanelLED.vtransportproxy_RecWrite));
mcuPort.send(new com.adamdbradley.mcu.console.protocol.command.LightPanelLED(com.adamdbradley.mcu.console.PanelLED.Record));
} else {
console.send(new ShutPanelLED(PanelLED.vtransportproxy_RecWrite));
mcuPort.send(new com.adamdbradley.mcu.console.protocol.command.ShutPanelLED(com.adamdbradley.mcu.console.PanelLED.Record));
}
switch (transportMode) {
case Rewinding:
// Rew lit
case FastForwarding:
// FF lit
case Paused:
// Play blinking (or just lit if blink not native)
case Playing:
// Play lit
case Shuttling:
// Stop lit
case Stopped:
// Nothing
}
}
public void channelRec(int i) {
channels[i].record = !channels[i].record;
displayChannel(i);
}
public void channelSolo(int i) {
channels[i].solo = !channels[i].solo;
displayChannel(i);
}
public void channelMute(int i) {
channels[i].mute = !channels[i].mute;
displayChannel(i);
}
public void channelSelect(int i) {
channels[i].select = !channels[i].select;
displayChannel(i);
}
public void channelVPot(int i) {
channels[i].vpotMode = VPotMode.values()[(channels[i].vpotMode.ordinal() + 1) % VPotMode.values().length];
channels[i].vpotValue = 0;
displayChannel(i);
}
public void channelVPot(int i, int velocity) {
if (velocity > 0) {
channels[i].vpotValue++;
} else {
channels[i].vpotValue--;
}
displayChannel(i);
}
public void mcuMove(int adj) {
mcuViewOffset = Math.max(0,
Math.min(
channels.length - 8,
mcuViewOffset + adj));
System.err.println("MCU adv: " + mcuViewOffset);
for (int i=0; i<8; i++) {
displayChannelMCU(mcuViewOffset + i);
}
}
/**
* Range 0 - 1023
* @param i
* @param value
*/
public void fader(int i, int value) {
if (channels[i].fader != value) {
System.err.println("Moving " + i);
channels[i].fader = value;
if (inViewD8B(i)) {
console.send(new com.adamdbradley.d8b.console.command.MoveFader(com.adamdbradley.d8b.console.Fader.values()[i - d8bViewOffset], value >> 2));
}
if (inViewMCU(i)) {
mcuPort.send(new MoveFader(Fader.values()[i - mcuViewOffset], value));
}
}
}
public void masterFader(int value) {
if (masterFader != value) {
masterFader = value;
console.send(new com.adamdbradley.d8b.console.command.MoveFader(com.adamdbradley.d8b.console.Fader.Master, value >> 2));
mcuPort.send(new MoveFader(Fader.Master, value));
}
}
private boolean inViewMCU(final int i) {
return (i >= mcuViewOffset && i < mcuViewOffset + 8);
}
private boolean inViewD8B(final int i) {
return (i >= d8bViewOffset && i < d8bViewOffset + 24);
}
private void displayChannel(int i) {
if (inViewMCU(i)) {
displayChannelMCU(i);
}
if (inViewD8B(i)) {
displayChannelD8B(i);
}
}
private void displayChannelMCU(int modelChannel) {
final Model.Channel channel = channels[modelChannel];
final int pos = modelChannel - mcuViewOffset;
final com.adamdbradley.mcu.console.Channel strip = com.adamdbradley.mcu.console.Channel.values()[pos];
final Fader fader = strip.fader();
mcuPort.send(new WriteScreen(DeviceType.Master,
0, pos * 7, " "));
mcuPort.send(new WriteScreen(DeviceType.Master,
0, pos * 7, Integer.toString(modelChannel)));
final String status = ""
+ (channel.assign ? 'A' : ' ')
+ (channel.green ? (channel.red ? 'X' : '^') : (channel.record ? 'v' : ' '))
+ (channel.write ? 'W' : ' ')
;
mcuPort.send(new WriteScreen(DeviceType.Master, 1, pos * 7, status));
mcuPort.send(new MoveFader(fader, channel.fader));
if (channel.record) {
mcuPort.send(new LightChannelLED(strip, ChannelLED.REC));
} else {
mcuPort.send(new ShutChannelLED(strip, ChannelLED.REC));
}
if (channel.solo) {
mcuPort.send(new LightChannelLED(strip, ChannelLED.SOLO));
} else {
mcuPort.send(new ShutChannelLED(strip, ChannelLED.SOLO));
}
if (channel.mute) {
mcuPort.send(new LightChannelLED(strip, ChannelLED.MUTE));
} else {
mcuPort.send(new ShutChannelLED(strip, ChannelLED.MUTE));
}
if (channel.select) {
mcuPort.send(new LightChannelLED(strip, ChannelLED.SELECT));
} else {
mcuPort.send(new ShutChannelLED(strip, ChannelLED.SELECT));
}
mcuPort.send(new WriteVPot(strip, channel.vpotMode, channel.vpotValue, false));
}
private void displayChannelD8B(int i) {
final Model.Channel channel = channels[mcuViewOffset + i];
final com.adamdbradley.d8b.console.Fader fader = com.adamdbradley.d8b.console.Fader.values()[i - d8bViewOffset];
console.send(new com.adamdbradley.d8b.console.command.MoveFader(fader,
channel.fader >> 2));
}
}
| lgpl-3.0 |
mar9000/plantuml | src/net/sourceforge/plantuml/salt/Positionner2.java | 2469 | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2014, Arnaud Roques
*
* Project Info: http://plantuml.sourceforge.net
*
* This file is part of PlantUML.
*
* PlantUML is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* PlantUML distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
*
* Original Author: Arnaud Roques
*/
package net.sourceforge.plantuml.salt;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import net.sourceforge.plantuml.salt.element.Element;
public class Positionner2 {
private int row;
private int col;
private int maxRow;
private int maxCol;
private final Map<Element, Cell> positions = new LinkedHashMap<Element, Cell>();
private Cell last;
public void add(Terminated<Element> element) {
addWithoutMove(element.getElement());
final Terminator terminator = element.getTerminator();
if (terminator == Terminator.NEWCOL) {
moveNextColumn();
} else {
moveNextRow();
}
}
private void moveNextColumn() {
col++;
}
private void moveNextRow() {
row++;
col = 0;
}
private void addWithoutMove(Element elmt) {
last = new Cell(row, col);
positions.put(elmt, last);
updateMax();
}
public void mergeLeft(Terminator terminator) {
updateMax();
if (terminator == Terminator.NEWCOL) {
col++;
} else {
row++;
col = 0;
}
last.mergeLeft();
}
private void updateMax() {
if (row > maxRow) {
maxRow = row;
}
if (col > maxCol) {
maxCol = col;
}
}
public Map<Element, Cell> getAll() {
return Collections.unmodifiableMap(positions);
}
public final int getNbRows() {
return maxRow + 1;
}
public final int getNbCols() {
return maxCol + 1;
}
}
| lgpl-3.0 |
caduandrade/japura-gui | src/main/java/org/japura/gui/renderer/DefaultSplitButtonRenderer.java | 2512 | package org.japura.gui.renderer;
import java.awt.Color;
import java.awt.Component;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JSeparator;
import javax.swing.border.Border;
/**
* Copyright (C) 2010-2012 Carlos Eduardo Leite de Andrade
* <P>
* This library is free software: you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any
* later version.
* <P>
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
* <P>
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <A
* HREF="www.gnu.org/licenses/">www.gnu.org/licenses/</A>
* <P>
* For more information, contact: <A HREF="www.japura.org">www.japura.org</A>
* <P>
*
* @author Carlos Eduardo Leite de Andrade
*/
public class DefaultSplitButtonRenderer implements SplitButtonRenderer{
private JLabel label = new JLabel();
private JSeparator separator = new JSeparator();
private Border mouseOverBorder;
private Border mouseOutBorder;
public DefaultSplitButtonRenderer() {
separator.setBackground(Color.WHITE);
label.setOpaque(true);
}
@Override
public Component getCellRendererComponent(String buttonName,
boolean isSeparator,
boolean cellHasFocus,
boolean buttonEnabled) {
if (isSeparator) {
return separator;
} else {
label.setText(buttonName);
}
if (buttonEnabled == false) {
label.setBorder(getMouseOutBorder());
label.setBackground(Color.WHITE);
label.setForeground(Color.LIGHT_GRAY);
} else if (cellHasFocus) {
label.setBorder(getMouseOverBorder());
label.setBackground(Color.BLACK);
label.setForeground(Color.WHITE);
} else {
label.setBorder(getMouseOutBorder());
label.setBackground(Color.WHITE);
label.setForeground(Color.BLACK);
}
return label;
}
public Border getMouseOverBorder() {
if (mouseOverBorder == null) {
mouseOverBorder = BorderFactory.createLineBorder(Color.BLACK, 3);
}
return mouseOverBorder;
}
public Border getMouseOutBorder() {
if (mouseOutBorder == null) {
mouseOutBorder = BorderFactory.createLineBorder(Color.WHITE, 3);
}
return mouseOutBorder;
}
}
| lgpl-3.0 |
xorware/android_packages_apps_Settings | src/com/android/settings/CredentialCheckResultTracker.java | 2491 | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
/**
* An invisible retained fragment to track lock check result.
*/
public class CredentialCheckResultTracker extends Fragment {
private Listener mListener;
private boolean mHasResult = false;
private boolean mResultMatched;
private Intent mResultData;
private int mResultTimeoutMs;
private int mResultEffectiveUserId;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
public void setListener(Listener listener) {
if (mListener == listener) {
return;
}
mListener = listener;
if (mListener != null && mHasResult) {
mListener.onCredentialChecked(mResultMatched, mResultData, mResultTimeoutMs,
mResultEffectiveUserId, false /* newResult */);
}
}
public void setResult(boolean matched, Intent intent, int timeoutMs, int effectiveUserId) {
mResultMatched = matched;
mResultData = intent;
mResultTimeoutMs = timeoutMs;
mResultEffectiveUserId = effectiveUserId;
mHasResult = true;
if (mListener != null) {
mListener.onCredentialChecked(mResultMatched, mResultData, mResultTimeoutMs,
mResultEffectiveUserId, true /* newResult */);
mHasResult = false;
}
}
public void clearResult() {
mHasResult = false;
mResultMatched = false;
mResultData = null;
mResultTimeoutMs = 0;
mResultEffectiveUserId = 0;
}
interface Listener {
public void onCredentialChecked(boolean matched, Intent intent, int timeoutMs,
int effectiveUserId, boolean newResult);
}
}
| lgpl-3.0 |
duckdoom5/RpgEssentials | RpgEntities/src/me/duckdoom5/RpgEssentials/RpgEntities/entities/SheepRpg.java | 1055 | package me.duckdoom5.RpgEssentials.RpgEntities.entities;
import net.minecraft.server.v1_6_R3.EntityLiving;
import net.minecraft.server.v1_6_R3.EntitySheep;
import net.minecraft.server.v1_6_R3.Item;
import net.minecraft.server.v1_6_R3.World;
public class SheepRpg extends EntitySheep implements EntityRpg {
private static int lureItem = Item.SULPHUR.id;
private EntityLiving owner;
private boolean sitting;
private boolean tamed;
public SheepRpg(World world) {
super(world);
}
@Override
public EntityLiving getOwner() {
return owner;
}
@Override
public boolean isSitting() {
return sitting;
}
@Override
public void setOwner(EntityLiving owner) {
this.owner = owner;
}
@Override
public boolean isTamed() {
return tamed;
}
@Override
public void setTamed(boolean value) {
this.tamed = value;
}
@Override
public boolean canTarget(EntityLiving target, EntityLiving owner) {
return true;
}
}
| lgpl-3.0 |
changshengmen/secureManagementSystem | src/main/java/net/jeeshop/core/util/MailUtil.java | 5369 | package net.jeeshop.core.util;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import net.jeeshop.core.front.SystemManager;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 发送邮件工具类
* @author huangf
*
*/
public class MailUtil {
private static final Logger logger = LoggerFactory.getLogger(MailUtil.class);
public static void main(String[] args) {//huangf@spider.com.cn
MailUtil mail = new MailUtil("543089122@qq.com",
"xxx@163.com","xxx", "smtp.163.com", "标题");
mail.attachfile("e:\\1.jpg");
mail.attachfile("e:\\bsa.js");
// mail.attachfile("e:\\aa.txt");
// mail.startSend(getForgetHtml(null));
}
// 定义发件人、收件人、主题等
String to = null;
String from = null;
String password = null;
String host = null;
String filename = null;
// String subject = null;
// 用于保存发送附件的文件名的集合
Vector file = new Vector();
// 做一个可以传发件人等参数的构造
public MailUtil(String to, String from,String password, String smtpServer, String subject) {
// 初始化发件人、收件人、主题等
this.to = to;
this.from = from;
this.password = password;
this.host = smtpServer;
// this.subject = subject;
}
public MailUtil(String to){
this.to = to;
this.from = SystemManager.getInstance().getProperty("from_email_account");
this.password = SystemManager.getInstance().getProperty("from_email_password");
this.host = SystemManager.getInstance().getProperty("from_eamil_smtpServer");
// this.subject = subject;
}
// 该方法用于收集附件名
public void attachfile(String fname) {
file.addElement(fname);
}
// 开始发送信件的方法
public boolean startSend(String emailTitle,String emailContent) {
if(StringUtils.isBlank(emailContent)){
logger.error("邮件内容不能为空!");
return false;
}
try {
if(StringUtils.isBlank(emailContent)){
throw new NullPointerException("发送的内容不能为空!");
}
// 创建Properties对象
Properties props = System.getProperties();
// 创建信件服务器
props.put("mail.smtp.auth","true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.password", "0");
// 得到默认的对话对象
// Session session = Session.getDefaultInstance(props, null);
Session session = Session.getInstance(props, new PopupAuthenticator(this.from, this.password));
// 创建一个消息,并初始化该消息的各项元素
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = { new InternetAddress(to) };
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(emailTitle);
// 后面的BodyPart将加入到此处创建的Multipart中
Multipart mp = new MimeMultipart("subtype");
//添加HTML正文
BodyPart htmlBody = new MimeBodyPart();
MimeMultipart htmlContent = new MimeMultipart("related");
BodyPart msgContent = new MimeBodyPart();
htmlContent.addBodyPart(msgContent);
msgContent.setContent(emailContent, "text/html;charset=utf-8");
htmlBody.setContent(htmlContent);
mp.addBodyPart(htmlBody);
// 利用枚举器方便的遍历集合
Enumeration efile = file.elements();
// 检查序列中是否还有更多的对象
while (efile.hasMoreElements()) {
MimeBodyPart mbp = new MimeBodyPart();
// 选择出每一个附件名
filename = efile.nextElement().toString();
// 得到数据源
FileDataSource fds = new FileDataSource(filename);
// 得到附件本身并至入BodyPart
mbp.setDataHandler(new DataHandler(fds));
// 得到文件名同样至入BodyPart
mbp.setFileName(fds.getName());
mp.addBodyPart(mbp);
}
// 移走集合中的所有元素
file.removeAllElements();
// Multipart加入到信件
msg.setContent(mp);
// 设置信件头的发送日期
msg.setSentDate(new Date());
// 发送信件
Transport.send(msg);
}catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
class PopupAuthenticator extends Authenticator {
String username = null;
String password = null;
public PopupAuthenticator(String user, String pass) {
username = user;
password = pass;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
/**
* 忘记密码的HTML
* @return
*/
// public static String getForgetHtml(Account account,int pageType){
// StringBuilder buff = new StringBuilder();
// buff.append("http://127.0.0.1:8082/mybbs/forget.html?account="+account.getAccount()+"&sign="+account.getSign()+"&pageType="+pageType);
//
// return buff.toString();
// }
}
| lgpl-3.0 |
B3Partners/b3p-commons-csw | src/main/java/nl/b3p/csw/jaxb/gml/MultiCurvePropertyType.java | 7739 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-833
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2010.06.10 at 04:19:23 PM CEST
//
package nl.b3p.csw.jaxb.gml;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* A property that has a collection of curves as its value domain can either be an appropriate geometry element encapsulated in an element of this type or an XLink reference to a remote geometry element (where remote includes geometry elements located elsewhere in the same document). Either the reference or the contained element must be given, but neither both nor none.
*
* <p>Java class for MultiCurvePropertyType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="MultiCurvePropertyType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence minOccurs="0">
* <element ref="{http://www.opengis.net/gml}MultiCurve"/>
* </sequence>
* <attGroup ref="{http://www.opengis.net/gml}AssociationAttributeGroup"/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MultiCurvePropertyType", propOrder = {
"multiCurve"
})
public class MultiCurvePropertyType {
@XmlElementRef(name = "MultiCurve", namespace = "http://www.opengis.net/gml", type = MultiCurve.class)
protected MultiCurve multiCurve;
@XmlAttribute(namespace = "http://www.opengis.net/gml")
@XmlSchemaType(name = "anyURI")
protected String remoteSchema;
@XmlAttribute(namespace = "http://www.w3.org/1999/xlink")
protected String type;
@XmlAttribute(namespace = "http://www.w3.org/1999/xlink")
@XmlSchemaType(name = "anyURI")
protected String href;
@XmlAttribute(namespace = "http://www.w3.org/1999/xlink")
@XmlSchemaType(name = "anyURI")
protected String role;
@XmlAttribute(namespace = "http://www.w3.org/1999/xlink")
@XmlSchemaType(name = "anyURI")
protected String arcrole;
@XmlAttribute(namespace = "http://www.w3.org/1999/xlink")
protected String title;
@XmlAttribute(namespace = "http://www.w3.org/1999/xlink")
protected String show;
@XmlAttribute(namespace = "http://www.w3.org/1999/xlink")
protected String actuate;
/**
* Default no-arg constructor
*
*/
public MultiCurvePropertyType() {
super();
}
/**
* Fully-initialising value constructor
*
*/
public MultiCurvePropertyType(final MultiCurve multiCurve, final String remoteSchema, final String type, final String href, final String role, final String arcrole, final String title, final String show, final String actuate) {
this.multiCurve = multiCurve;
this.remoteSchema = remoteSchema;
this.type = type;
this.href = href;
this.role = role;
this.arcrole = arcrole;
this.title = title;
this.show = show;
this.actuate = actuate;
}
/**
* Gets the value of the multiCurve property.
*
* @return
* possible object is
* {@link MultiCurve }
*
*/
public MultiCurve getMultiCurve() {
return multiCurve;
}
/**
* Sets the value of the multiCurve property.
*
* @param value
* allowed object is
* {@link MultiCurve }
*
*/
public void setMultiCurve(MultiCurve value) {
this.multiCurve = value;
}
/**
* Gets the value of the remoteSchema property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRemoteSchema() {
return remoteSchema;
}
/**
* Sets the value of the remoteSchema property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRemoteSchema(String value) {
this.remoteSchema = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
if (type == null) {
return "simple";
} else {
return type;
}
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
/**
* Gets the value of the href property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHref() {
return href;
}
/**
* Sets the value of the href property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHref(String value) {
this.href = value;
}
/**
* Gets the value of the role property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRole() {
return role;
}
/**
* Sets the value of the role property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRole(String value) {
this.role = value;
}
/**
* Gets the value of the arcrole property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getArcrole() {
return arcrole;
}
/**
* Sets the value of the arcrole property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setArcrole(String value) {
this.arcrole = value;
}
/**
* Gets the value of the title property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitle() {
return title;
}
/**
* Sets the value of the title property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitle(String value) {
this.title = value;
}
/**
* Gets the value of the show property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getShow() {
return show;
}
/**
* Sets the value of the show property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setShow(String value) {
this.show = value;
}
/**
* Gets the value of the actuate property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getActuate() {
return actuate;
}
/**
* Sets the value of the actuate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setActuate(String value) {
this.actuate = value;
}
}
| lgpl-3.0 |
yawlfoundation/editor | source/org/yawlfoundation/yawl/analyser/reductionrules/FESRrule.java | 6280 |
/*
* Copyright (c) 2004-2013 The YAWL Foundation. All rights reserved.
* The YAWL Foundation is a collaboration of individuals and
* organisations who are committed to improving workflow technology.
*
* This file is part of YAWL. YAWL is free software: you can
* redistribute it and/or modify it under the terms of the GNU Lesser
* General Public License as published by the Free Software Foundation.
*
* YAWL is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
* Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with YAWL. If not, see <http://www.gnu.org/licenses/>.
*/
/*
*
* @author Moe Thandar Wynn
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package org.yawlfoundation.yawl.analyser.reductionrules;
import org.yawlfoundation.yawl.analyser.elements.RElement;
import org.yawlfoundation.yawl.analyser.elements.RPlace;
import org.yawlfoundation.yawl.analyser.elements.RTransition;
import org.yawlfoundation.yawl.analyser.elements.ResetWFNet;
import java.util.Set;
/**
* Reduction rule for RWF-net: FESR rule
*/
public class FESRrule extends ResetReductionRule{
/**
* Innermost method for a reduction rule.
* Implementation of the abstract method from superclass.
* @param net ResetWFNet to perform reduction
* @param netElement an for consideration.
* returns a reduced ResetWFNet or null if a given net cannot be reduced.
*/
public ResetWFNet reduceElement(ResetWFNet net, RElement netElement) {
boolean isReducible = false;
if (netElement instanceof RPlace) {
RPlace p = (RPlace) netElement;
Set<RElement> postSet = p.getPostsetElements();
Set<RElement> preSet = p.getPresetElements();
//check if more than one && preset and postset transitions have exactly one
if (preSet.size() > 1 && postSet.size() >1 &&
checkTransitionsOnePrePost(preSet) &&
checkTransitionsOnePrePost(postSet)) {
// potential candidate exits so now try and find
// one or more other ps
for (RElement p2 : net.getNetElements().values()) {
if ((p != p2) && (p2 instanceof RPlace)) {
Set<RElement> postSet2 = p2.getPostsetElements();
Set<RElement> preSet2 = p2.getPresetElements();
// found another place
if (preSet2.size() > 1 && postSet2.size() > 1 &&
checkTransitionsOnePrePost(preSet2) &&
checkTransitionsOnePrePost(postSet2) &&
p2.getCancelledBySet().equals(p.getCancelledBySet()) &&
checkForEquivalence(preSet, preSet2) &&
checkForEquivalence(postSet, postSet2)) {
isReducible = true;
net.removeNetElement(p2);
removeFromNet(net, preSet2);
removeFromNet(net, postSet2);
}
}
}
}
}
return isReducible ? net : null;
}
private boolean checkTransitionsOnePrePost(Set<RElement> elements) {
for (RElement element : elements) {
if (! (element.getPresetElements().size() == 1 &&
element.getPostsetElements().size() ==1)) {
return false;
}
}
return true;
}
private boolean checkForEquivalence(Set<RElement> transitions1,
Set<RElement> transitions2) {
if (transitions1.size() == transitions2.size()) {
Set<RElement> preSet = ResetWFNet.getPreset(transitions1);
Set<RElement> preSet2 = ResetWFNet.getPreset(transitions2);
Set<RElement> postSet = ResetWFNet.getPostset(transitions1);
Set<RElement> postSet2 = ResetWFNet.getPostset(transitions2);
if (preSet.equals(preSet2) && postSet.equals(postSet2)) {
//now consider individual transition and compare removeset
for (RElement re : transitions1) {
if (! hasEquivalentTransition((RTransition) re, transitions2)) {
return false;
}
}
}
else return false;
}
return true;
}
private boolean hasEquivalentTransition(RTransition t, Set<RElement> transitions) {
Set<RElement> removeSet = t.getRemoveSet();
Set<RElement> preSetOft = t.getPresetElements();
Set<RElement> postSetOft = t.getPostsetElements();
for (RElement t2 : transitions) {
Set<RElement> removeSet2 = ((RTransition) t2).getRemoveSet();
Set<RElement> preSetOft2 = t2.getPresetElements();
Set<RElement> postSetOft2 = t2.getPostsetElements();
if (preSetOft.equals(preSetOft2) && postSetOft.equals(postSetOft2) &&
removeSet.equals(removeSet2)) {
return true;
}
}
return false;
}
private void removeFromNet(ResetWFNet net, Set<RElement> elements) {
for (RElement element : elements) {
net.removeNetElement(element);
}
}
} | lgpl-3.0 |
gundermanc/pinata | service/src/main/java/com/pinata/service/api/v1/Version1Resource.java | 643 | package com.pinata.service.api.v1;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.WebApplicationException;
import java.sql.SQLException;
import com.pinata.service.datatier.SQLConnection;
import com.pinata.shared.ApiException;
import com.pinata.shared.ApiStatus;
/**
* Version1 Resource.
* @author Christian Gunderman
*/
@Path("v1")
public class Version1Resource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response get() throws ApiException {
return Response.ok("API v1").build();
}
}
| lgpl-3.0 |
Godin/sonar | sonar-plugin-api/src/test/java/org/sonar/api/rules/RuleAnnotationUtilsTest.java | 1383 | /*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.rules;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class RuleAnnotationUtilsTest {
@Test
public void defaultKeyShouldBeTheClassName() {
String key = RuleAnnotationUtils.getRuleKey(AnnotatedCheck.class);
assertThat(key, is(AnnotatedCheck.class.getName()));
}
@Test
public void shouldGetKey() {
String key = RuleAnnotationUtils.getRuleKey(AnnotatedCheckWithParameters.class);
assertThat(key, is("overridden_key"));
}
}
| lgpl-3.0 |
WangDaYeeeeee/Mysplash | base/src/main/java/com/wangdaye/base/unsplash/ProfileImage.java | 1693 | package com.wangdaye.base.unsplash;
import android.os.Parcel;
import android.os.Parcelable;
import java.io.Serializable;
/**
* Profile image.
* */
public class ProfileImage implements Parcelable, Serializable {
/**
* small : https://images.unsplash.com/face-springmorning.jpg?q=80&fm=jpg&crop=faces&fit=crop&h=32&w=32
* medium : https://images.unsplash.com/face-springmorning.jpg?q=80&fm=jpg&crop=faces&fit=crop&h=64&w=64
* large : https://images.unsplash.com/face-springmorning.jpg?q=80&fm=jpg&crop=faces&fit=crop&h=128&w=128
* custom: https://images.unsplash.com/your-custom-image.jpg?q=80&fm=jpg&crop=faces&fit=crop&h=100&w=100
*/
public String small;
public String medium;
public String large;
public String custom;
/** <br> parcel. */
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.small);
dest.writeString(this.medium);
dest.writeString(this.large);
dest.writeString(this.custom);
}
public ProfileImage() {
}
protected ProfileImage(Parcel in) {
this.small = in.readString();
this.medium = in.readString();
this.large = in.readString();
this.custom = in.readString();
}
public static final Creator<ProfileImage> CREATOR = new Creator<ProfileImage>() {
@Override
public ProfileImage createFromParcel(Parcel source) {
return new ProfileImage(source);
}
@Override
public ProfileImage[] newArray(int size) {
return new ProfileImage[size];
}
};
}
| lgpl-3.0 |
Agem-Bilisim/lider-console | lider-console-core/src/tr/org/liderahenk/liderconsole/core/rest/requests/IRequest.java | 932 | /*
*
* Copyright © 2015-2016 Agem Bilişim
*
* This file is part of Lider Ahenk.
*
* Lider Ahenk 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.
*
* Lider Ahenk 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 Lider Ahenk. If not, see <http://www.gnu.org/licenses/>.
*/
package tr.org.liderahenk.liderconsole.core.rest.requests;
import java.io.Serializable;
public interface IRequest extends Serializable {
String toJson() throws Exception;
}
| lgpl-3.0 |
impetus-opensource/jumbune | datavalidation/src/main/java/org/jumbune/datavalidation/DataValidationInputFormat.java | 7776 | package org.jumbune.datavalidation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.ContentSummary;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.InputFormat;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.CombineFileInputFormat;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* A customized class for file-based {@link InputFormat}s.
*
* <p>
* <code>DataValidationInputFormat</code> is the customized class for file-based
* <code>InputFormat</code>s. This provides a generic implementation of
* {@link #getSplits(JobContext)}.
*
*
*/
public class DataValidationInputFormat extends
CombineFileInputFormat<LongWritable, Text> {
/** The Constant SPLIT_SLOP. */
private static final double SPLIT_SLOP = 1.1;
/** The record separator. */
private byte[] recordSeparator;
/** The Constant LOGGER. */
private static final Logger LOGGER = LogManager
.getLogger(DataValidationInputFormat.class);
/* (non-Javadoc)
* @see org.apache.hadoop.mapreduce.InputFormat#createRecordReader(org.apache.hadoop.mapreduce.InputSplit, org.apache.hadoop.mapreduce.TaskAttemptContext)
*/
@Override
public RecordReader<LongWritable, Text> createRecordReader(
InputSplit split, TaskAttemptContext context) {
return new DataValidationRecordReader();
}
/* (non-Javadoc)
* @see org.apache.hadoop.mapreduce.lib.input.FileInputFormat#isSplitable(org.apache.hadoop.mapreduce.JobContext, org.apache.hadoop.fs.Path)
*/
@Override
protected boolean isSplitable(JobContext context, Path file) {
return true;
}
/**
* Generate the list of files and make them into DataValidationFileSplit.
*
* @param job the job
* @return the splits
* @throws IOException Signals that an I/O exception has occurred.
*/
@Override
public List<InputSplit> getSplits(JobContext job) throws IOException {
long minSize = Math.max(getFormatMinSplitSize(), getMinSplitSize(job));
long maxSize = getMaxSplitSize(job);
// generate splits
List<InputSplit> splits = new ArrayList<InputSplit>();
setData(job,minSize,maxSize,splits, listStatus(job));
LOGGER.debug("Total # of splits: " + splits.size());
return splits;
}
/**
* Finds files inside directories recusively and add to fileStatusList
* @param job refers to JobContext that is being used to read the configurations of the job that ran
* @param minSize refers to the minimum file block size.
* @param maxSize refers to the maximum file block size.
* @param splits refers to a list of splits that are being generated.
* @param fileStatusList list of FileStatus
* @throws IOException Signals that an I/O exception has occurred.
*/
public void setData(JobContext job, long minSize, long maxSize,
List<InputSplit> splits, List<FileStatus> fileStatusList) throws IOException {
for(FileStatus file:fileStatusList) {
if (file.isDirectory()) {
Path dirPath = file.getPath();
FileStatus [] fileArray = dirPath.getFileSystem(job.getConfiguration()).listStatus(dirPath);
setData(job, minSize, maxSize, splits, Arrays.asList(fileArray));
} else {
//Checking whether file is empty or not
Path path = file.getPath();
FileSystem fs = path.getFileSystem(job.getConfiguration());
ContentSummary cs = fs.getContentSummary(path);
if (cs.getLength() > 0) {
generateSplits(job, minSize, maxSize, splits, file);
}
}
}
}
/**
* Generate splits.
*
* @param job refers to JobContext that is being used to read the configurations of the job that ran
* @param minSize refers to the minimum file block size.
* @param maxSize refers to the maximum file block size.
* @param splits refers to a list of splits that are being generated.
* @param file refers to the FileStatus required to determine block size,length,allocations.
* @throws IOException Signals that an I/O exception has occurred.
*/
private void generateSplits(JobContext job, long minSize, long maxSize,
List<InputSplit> splits, FileStatus file) throws IOException {
Path path = file.getPath();
int numOfRecordsInCurrentSplit = 0;
int numOfRecordsInPreviousSplit = 0;
FileSystem fs = path.getFileSystem(job.getConfiguration());
long length = file.getLen();
BlockLocation[] blkLocations = fs.getFileBlockLocations(file, 0,
length);
FSDataInputStream fsin = null ;
if ((length != 0) && isSplitable(job, path)) {
long blockSize = file.getBlockSize();
long splitSize = computeSplitSize(blockSize, minSize, maxSize);
long bytesRemaining = length;
// checking the occurrences of the record separator in current
// split
recordSeparator = job.getConfiguration()
.get(DataValidationConstants.RECORD_SEPARATOR)
.getBytes();
while (((double) bytesRemaining) / splitSize > SPLIT_SLOP) {
int blkIndex = getBlockIndex(blkLocations, length
- bytesRemaining);
long start = length - bytesRemaining;
long end = start + splitSize;
try{
fsin = fs.open(path);
fsin.seek(start);
long pos = start;
int b = 0;
int bufferPos = 0;
while (true) {
b = fsin.read();
pos = fsin.getPos();
if (b == -1) {
break;}
if (b == recordSeparator[bufferPos]) {
bufferPos++;
if (bufferPos == recordSeparator.length) {
numOfRecordsInCurrentSplit++;
bufferPos = 0;
if (pos > end) {
break;
}
}
} else {
// reset the value of buffer position to zero
bufferPos = 0;
}
}}finally{
if(fsin != null){
fsin.close();
}
}
splits.add(new DataValidationFileSplit(path, start,
splitSize, numOfRecordsInPreviousSplit,
blkLocations[blkIndex].getHosts()));
bytesRemaining -= splitSize;
numOfRecordsInPreviousSplit = numOfRecordsInCurrentSplit;
numOfRecordsInCurrentSplit = 0;
}
addSplitIfBytesRemaining(splits, path, numOfRecordsInPreviousSplit,
length, blkLocations, bytesRemaining);
} else if (length != 0) {
splits.add(new DataValidationFileSplit(path, 0, length,
numOfRecordsInPreviousSplit, blkLocations[0].getHosts()));
} else {
splits.add(new DataValidationFileSplit(path, 0, length,
numOfRecordsInPreviousSplit, new String[0]));
}
}
/**
* Adds the split if bytes remaining.
*
* @param splits refers to a list of splits that are being generated.
* @param path refers to the file name.
* @param numOfRecordsInPreviousSplit refers to the number of records in the last split.
* @param length denotes the number of bytes in the file to process
* @param blkLocations refers to the block allocations on HDFS.
* @param bytesRemaining refers to the number of bytes that are remaining in the file to be processed.
* @throws IOException Signals that an I/O exception has occurred.
*/
private void addSplitIfBytesRemaining(List<InputSplit> splits, Path path,
int numOfRecordsInPreviousSplit, long length,
BlockLocation[] blkLocations, long bytesRemaining)
throws IOException {
if (bytesRemaining != 0) {
splits.add(new DataValidationFileSplit(path, length
- bytesRemaining, bytesRemaining,
numOfRecordsInPreviousSplit,
blkLocations[blkLocations.length - 1].getHosts()));
}
}
}
| lgpl-3.0 |
lmu-bioinformatics/xmlpipedb | uniprotdb/src/org/uniprot/uniprot/NameListType.java | 3843 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v1.0.5-09/29/2005 11:56 AM(valikov)-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.06.16 at 12:18:25 AM PDT
//
package org.uniprot.uniprot;
/**
* Java content class for nameListType complex type.
* <p>The following schema fragment specifies the expected content contained within this java content object. (defined at file:/Users/dondi/Documents/Main/Eclipse/research/xmlpipedb-uniprotdb/xsd//uniprot.xsd line 407)
* <p>
* <pre>
* <complexType name="nameListType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <choice maxOccurs="unbounded">
* <element name="consortium" type="{http://uniprot.org/uniprot}consortiumType"/>
* <element name="person" type="{http://uniprot.org/uniprot}personType"/>
* </choice>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*/
public interface NameListType {
/**
* Gets the value of the ConsortiumOrPerson property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the ConsortiumOrPerson property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getConsortiumOrPerson().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link org.uniprot.uniprot.NameListType.Person}
* {@link org.uniprot.uniprot.NameListType.Consortium}
*
*/
java.util.List getConsortiumOrPerson();
/**
* Gets the value of the hjid property.
*
* @return
* possible object is
* {@link java.lang.Long}
*/
java.lang.Long getHjid();
/**
* Sets the value of the hjid property.
*
* @param value
* allowed object is
* {@link java.lang.Long}
*/
void setHjid(java.lang.Long value);
/**
* Gets the value of the hjversion property.
*
* @return
* possible object is
* {@link java.lang.Long}
*/
java.lang.Long getHjversion();
/**
* Sets the value of the hjversion property.
*
* @param value
* allowed object is
* {@link java.lang.Long}
*/
void setHjversion(java.lang.Long value);
/**
* Java content class for consortium element declaration.
* <p>The following schema fragment specifies the expected content contained within this java content object. (defined at file:/Users/dondi/Documents/Main/Eclipse/research/xmlpipedb-uniprotdb/xsd//uniprot.xsd line 409)
* <p>
* <pre>
* <element name="consortium" type="{http://uniprot.org/uniprot}consortiumType"/>
* </pre>
*
*/
public interface Consortium
extends javax.xml.bind.Element, org.uniprot.uniprot.ConsortiumType
{
}
/**
* Java content class for person element declaration.
* <p>The following schema fragment specifies the expected content contained within this java content object. (defined at file:/Users/dondi/Documents/Main/Eclipse/research/xmlpipedb-uniprotdb/xsd//uniprot.xsd line 410)
* <p>
* <pre>
* <element name="person" type="{http://uniprot.org/uniprot}personType"/>
* </pre>
*
*/
public interface Person
extends javax.xml.bind.Element, org.uniprot.uniprot.PersonType
{
}
}
| lgpl-3.0 |
Spacecraft-Code/SPELL | src/spel-gui/com.astra.ses.spell.gui/src/com/astra/ses/spell/gui/model/jobs/GetProcPropertiesJob.java | 4064 | ///////////////////////////////////////////////////////////////////////////////
//
// PACKAGE : com.astra.ses.spell.gui.model.jobs
//
// FILE : GetProcPropertiesJob.java
//
// DATE : 2008-11-21 08:55
//
// Copyright (C) 2008, 2015 SES ENGINEERING, Luxembourg S.A.R.L.
//
// By using this software in any way, you are agreeing to be bound by
// the terms of this license.
//
// 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
//
// NO WARRANTY
// EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED
// ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER
// EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR
// CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A
// PARTICULAR PURPOSE. Each Recipient is solely responsible for determining
// the appropriateness of using and distributing the Program and assumes all
// risks associated with its exercise of rights under this Agreement ,
// including but not limited to the risks and costs of program errors,
// compliance with applicable laws, damage to or loss of data, programs or
// equipment, and unavailability or interruption of operations.
//
// DISCLAIMER OF LIABILITY
// EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY
// CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION
// LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE
// EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGES.
//
// Contributors:
// SES ENGINEERING - initial API and implementation and/or initial documentation
//
// PROJECT : SPELL
//
// SUBPROJECT: SPELL GUI Client
//
///////////////////////////////////////////////////////////////////////////////
package com.astra.ses.spell.gui.model.jobs;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import com.astra.ses.spell.gui.core.interfaces.ServiceManager;
import com.astra.ses.spell.gui.core.model.types.ProcProperties;
import com.astra.ses.spell.gui.model.commands.CommandResult;
import com.astra.ses.spell.gui.procs.exceptions.NotConnected;
import com.astra.ses.spell.gui.procs.interfaces.IProcedureManager;
public class GetProcPropertiesJob implements IRunnableWithProgress
{
public CommandResult result;
private Map<ProcProperties, String> m_properties;
protected String m_instanceId;
public GetProcPropertiesJob(String instanceId)
{
m_properties = null;
m_instanceId = instanceId;
}
@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException,
InterruptedException
{
IWorkbenchWindow window = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow();
try
{
monitor.setTaskName("Retrieving procedure properties");
IProcedureManager procedureMgr = (IProcedureManager) ServiceManager
.get(IProcedureManager.class);
m_properties = procedureMgr.getProcedureProperties(m_instanceId);
result = CommandResult.SUCCESS;
}
catch (NotConnected ex)
{
MessageDialog.openError(window.getShell(),
"Show properties failed",
"Could not retrieve properties, not connected to context");
m_properties = null;
result = CommandResult.FAILED;
}
monitor.done();
}
public Map<ProcProperties, String> getProperties()
{
return m_properties;
}
}
| lgpl-3.0 |
FenixEdu/fenixedu-academic | src/main/java/org/fenixedu/academic/domain/DegreeOfficialPublication.java | 2301 | /**
* Copyright © 2002 Instituto Superior Técnico
*
* This file is part of FenixEdu Academic.
*
* FenixEdu Academic is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FenixEdu Academic is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>.
*/
package org.fenixedu.academic.domain;
import org.fenixedu.academic.domain.exceptions.DomainException;
import org.fenixedu.commons.i18n.LocalizedString;
import org.joda.time.LocalDate;
import pt.ist.fenixframework.Atomic;
public class DegreeOfficialPublication extends DegreeOfficialPublication_Base {
public DegreeOfficialPublication(Degree degree, LocalDate date) {
if (degree == null) {
throw new DomainException("error.degree.officialpublication.unlinked");
}
if (date == null) {
throw new DomainException("error.degree.officialpublication.undated");
}
setDegree(degree);
setPublication(date);
}
@Atomic
public DegreeSpecializationArea createSpecializationArea(String nameEn, String namePt) {
LocalizedString area = new LocalizedString(org.fenixedu.academic.util.LocaleUtils.EN, nameEn).with(org.fenixedu.academic.util.LocaleUtils.PT, namePt);
return new DegreeSpecializationArea(this, area);
}
@Atomic
public void changeOfficialreference(String officialReference, final LocalDate publication,final String linkReference,Boolean includeInDiplomaSuplement) {
this.setOfficialReference(officialReference);
this.setPublication(publication);
this.setLinkReference(linkReference);
this.setIncludeInDiplomaSuplement(includeInDiplomaSuplement);
}
@Atomic
public void delete() {
setDegree(null);
super.deleteDomainObject();
}
}
| lgpl-3.0 |
chmaruni/SCJ | Shared/benchmarks/Erco/tsp/threads/tsp/TspSolver.java | 15068 | package tsp.threads.tsp;
/*
* Copyright (C) 2000 by ETHZ/INF/CS
* All rights reserved
*
* @version $Id: TspSolver.java 2094 2003-01-30 09:41:18Z praun $
* @author Florian Schneider
*/
public class TspSolver extends Thread {
static final boolean debug = Tsp.debug;
static int[][] weights = new int[Tsp.MAX_TOUR_SIZE][Tsp.MAX_TOUR_SIZE];
static int TourStackTop;
static int Done;
static int PrioQLast;
static int MinTourLen;
static int[] MinTour = new int[Tsp.MAX_TOUR_SIZE];
static Integer MinLock = new Integer(0);
static Integer TourLock = new Integer(0);
static Integer barrier = new Integer(0);
static PrioQElement[] PrioQ = new PrioQElement[Tsp.MAX_NUM_TOURS];
static int[] TourStack = new int[Tsp.MAX_NUM_TOURS];
static TourElement[] Tours = new TourElement[Tsp.MAX_NUM_TOURS];
/* non-static member variables, used by recusive_solve and visit_nodes */
int CurDist, PathLen;
int[] Visit = new int[Tsp.MAX_TOUR_SIZE];
int[] Path = new int[Tsp.MAX_TOUR_SIZE];
int visitNodes;
public void run() {
Worker();
}
void Worker() {
int curr = -1;
for ( ; ; ) {
/* continuously get a tour and split. */
curr = get_tour(curr);
if (curr < 0) {
if (debug)
System.out.println("Worker: curr = " + curr);
break;
}
recursive_solve(curr);
if (debug)
DumpPrioQ();
}
}
/*
* new_tour():
*
* Create a new tour structure given an existing tour structure and
* the next edge to add to the tour. Returns the index of the new structure.
*
*/
static int new_tour(int prev_index, int move) {
int index = 0;
int i;
TourElement curr, prev;
synchronized(TourLock) {
if (debug)
System.out.println("new_tour");
if (TourStackTop >= 0)
index = TourStack[TourStackTop--];
else {
System.out.println("TourStackTop: " + TourStackTop);
System.exit(-1);
}
curr = Tours[index];
prev = Tours[prev_index];
for (i = 0; i < Tsp.TspSize; i++) {
curr.prefix[i] = prev.prefix[i];
curr.conn = prev.conn;
}
curr.last = prev.last;
curr.prefix_weight = prev.prefix_weight +
weights[curr.prefix[curr.last]][move];
curr.prefix[++curr.last] = move;
if (debug)
MakeTourString(curr.last, curr.prefix);
curr.conn |= 1 << move;
return calc_bound(index);
}
}
/*
* set_best():
*
* Set the global `best' value.
*
*/
static void set_best(int best, int[] path) {
if (best >= MinTourLen) {
if (debug)
System.out.println("set_best: " + best + " <-> " + MinTourLen);
return;
}
synchronized(MinLock) {
if (best < MinTourLen) {
if (debug) {
System.out.print("(" + Thread.currentThread().getName() + ") ");
System.out.println("set_best MinTourLen: " + best + " (old: " + MinTourLen + ")");
}
MinTourLen = best;
for (int i = 0; i < Tsp.TspSize; i++)
MinTour[i] = path[i];
if (debug)
MakeTourString(Tsp.TspSize, MinTour);
}
}
}
static void MakeTourString(int len, int[] path) {
int i;
String tour_str="";
for (i=0; i < len; i++) {
System.out.print(path[i]+" - ");
if (path[i] >= 10) System.out.print(" ");
else System.out.print(" ");
}
System.out.println(path[i]);
}
/*
* Add up min edges connecting all unconnected vertixes (AHU p. 331-335)
* At some point, we may want to use MST to get a lower bound. This
* bound should be higher (and therefore more accurate) but will take
* longer to compute.
*/
static int calc_bound(int curr_index) {
Tsp.routesComputed++;
int i, j, wt, wt1, wt2;
TourElement curr = Tours[curr_index];
synchronized(TourLock) {
if (debug)
System.out.println("calc_bound");
/*
* wt1: the value of the edge with the lowest weight from the node
* we're testing to another unconnected node.
* wt2: the value of the edge with the second lowest weight
*/
/* if we have one unconnected node */
if (curr.last == (Tsp.TspSize - 2)) {
for (i = 0; i < Tsp.TspSize; i++) {
if ((curr.conn & (1<<i))==0) {
/* we have found the one unconnected node */
curr.prefix[Tsp.TspSize-1] = i;
curr.prefix[Tsp.TspSize] = Tsp.StartNode;
/* add edges to and from the last node */
curr.prefix_weight += weights[curr.prefix[Tsp.TspSize-2]][i] +
weights[i][curr.prefix[Tsp.StartNode]];
if (curr.prefix_weight < MinTourLen) {
/* Store our new best path and its weight. */
set_best(curr.prefix_weight, curr.prefix);
}
/* De-allocate this tour so someone else can use it */
curr.lower_bound = Tsp.BIGINT;
TourStack[++TourStackTop] = curr_index; /* Free tour. */
return(Tsp.END_TOUR);
}
}
}
curr.mst_weight = 0;
/*
* Add up the lowest weights for edges connected to vertices
* not yet used or at the ends of the current tour, and divide by two.
* This could be tweaked quite a bit. For example:
* (1) Check to make sure that using an edge would not make it
* impossible for a vertex to have degree two.
* (2) Check to make sure that the edge doesn't give some
* vertex degree 3.
*/
if (curr.last != Tsp.TspSize - 1) {
for (i = 0; i < Tsp.TspSize; i++) {
if ((curr.conn & 1<<i)!=0) continue;
for (j = 0, wt1 = wt2 = Tsp.BIGINT; j < Tsp.TspSize; j++) {
/* Ignore j's that are not connected to i (global->weights[i][j]==0), */
/* or that are already in the tour and aren't either the */
/* first or last node in the current tour. */
wt = weights[i][j];
if ((wt==0) || (((curr.conn&(1<<i))!=0)&&(j != curr.prefix[0])&&
(j != curr.prefix[curr.last])))
continue;
/* Might want to check that edges go to unused vertices */
if (wt < wt1) {
wt2 = wt1;
wt1 = wt;
} else if (wt < wt2) wt2 = wt;
}
/* At least three unconnected nodes? */
if (wt2 != Tsp.BIGINT) curr.mst_weight += (wt1 + wt2) >> 1;
/* Exactly two unconnected nodes? */
else if (wt1 != Tsp.BIGINT) curr.mst_weight += wt1;
}
curr.mst_weight += 1;
}
curr.lower_bound = curr.mst_weight + curr.prefix_weight;
return(curr_index);
}
}
static int LEFT_CHILD(int x) {
return (x<<1);
}
static int RIGHT_CHILD(int x) {
return (x<<1)+1;
}
static boolean less_than(PrioQElement x, PrioQElement y) {
return ((x.priority < y.priority) ||
(x.priority == y.priority) &&
(Tours[x.index].last > Tours[y.index].last));
}
/*
* DumpPrioQ():
*
* Dump the contents of PrioQ in some user-readable format (for debugging).
*
*/
static void DumpPrioQ() {
int pq, ind;
System.out.println("DumpPrioQ");
for (pq = 1; pq <= PrioQLast; pq++) {
ind = PrioQ[pq].index;
System.out.print(ind+"("+PrioQ[pq].priority+"):\t");
if ((LEFT_CHILD(pq)<PrioQLast) && (PrioQ[pq].priority>PrioQ[LEFT_CHILD(pq)].priority))
System.out.print(" left child wrong! ");
if ((LEFT_CHILD(pq)<PrioQLast) && (PrioQ[pq].priority>PrioQ[RIGHT_CHILD(pq)].priority))
System.out.print(" right child wrong! ");
MakeTourString(Tours[ind].last, Tours[ind].prefix);
}
}
/*
* split_tour():
*
* Break current tour into subproblems, and stick them all in the priority
* queue for later evaluation.
*
*/
static void split_tour(int curr_ind) {
int n_ind, last_node, wt;
int i, pq, parent, index, priority;
TourElement curr;
PrioQElement cptr, pptr;
synchronized(TourLock) {
if (debug)
System.out.println("split_tour");
curr = Tours[curr_ind];
if (debug)
MakeTourString(curr.last, curr.prefix);
/* Create a tour and add it to the priority Q for each possible
path that can be derived from the current path by adding a single
node while staying under the current minimum tour length. */
if (curr.last != (Tsp.TspSize - 1)) {
boolean t1, t2, t3;
TourElement new_;
last_node = curr.prefix[curr.last];
for (i = 0; i < Tsp.TspSize; i++) {
/*
* Check: 1. Not already in tour
* 2. Edge from last entry to node in graph
* and 3. Weight of new partial tour is less than cur min.
*/
wt = weights[last_node][i];
t1 = ((curr.conn & (1<<i)) == 0);
t2 = (wt != 0);
t3 = (curr.lower_bound + wt) <= MinTourLen;
if (t1 && t2 && t3) {
if ((n_ind = new_tour(curr_ind, i)) == Tsp.END_TOUR) {
continue;
}
/*
* If it's shorter than the current best tour, or equal
* to the current best tour and we're reporting all min
* length tours, put it on the priority q.
*/
new_ = Tours[n_ind];
if (PrioQLast >= Tsp.MAX_NUM_TOURS-1) {
System.out.println("pqLast "+PrioQLast);
System.exit(-1);
}
if (debug)
MakeTourString(new_.last, new_.prefix);
pq = ++PrioQLast;
cptr = PrioQ[pq];
cptr.index = n_ind;
cptr.priority = new_.lower_bound;
/* Bubble the entry up to the appropriate level to maintain
the invariant that a parent is less than either of it's
children. */
for (parent = pq >> 1, pptr = PrioQ[parent];
(pq > 1) && less_than(cptr, pptr);
pq = parent, cptr = pptr, parent = pq >> 1, pptr = PrioQ[parent]) {
/* PrioQ[pq] lower priority than parent -> SWITCH THEM. */
index = cptr.index;
priority = cptr.priority;
cptr.index = pptr.index;
cptr.priority = pptr.priority;
pptr.index = index;
pptr.priority = priority;
}
} else if (debug)
System.out.println(" [" + curr.lower_bound + " + " + wt + " > " + MinTourLen);
}
}
}
}
/*
* find_solvable_tour():
*
* Return the next solvable (sufficiently short) tour.
*/
static int find_solvable_tour() {
int curr, i, left, right, child, index;
int priority, last;
PrioQElement pptr, cptr, lptr, rptr;
synchronized(TourLock) {
if (debug)
System.out.println("find_solvable_tour");
if (Done != 0) {
if (debug)
System.out.println("(" + Thread.currentThread().getName() + ") - done");
return -1;
}
for ( ; PrioQLast != 0; ) {
pptr = PrioQ[1];
curr = pptr.index;
if (pptr.priority >= MinTourLen) {
/* We're done -- there's no way a better tour could be found. */
if (debug) {
System.out.print("\t" + Thread.currentThread().getName() + ": ");
MakeTourString(Tours[curr].last, Tours[curr].prefix);
}
Done = 1;
return -1;
}
/* Bubble everything maintain the priority queue's heap invariant. */
/* Move last element to root position. */
cptr = PrioQ[PrioQLast];
pptr.index = cptr.index;
pptr.priority = cptr.priority;
PrioQLast--;
/* Push previous last element down tree to restore heap structure. */
for (i = 1; i <= (PrioQLast >> 1); ) {
/* Find child with lowest priority. */
left = LEFT_CHILD(i);
right = RIGHT_CHILD(i);
lptr = PrioQ[left];
rptr = PrioQ[right];
if (left == PrioQLast || less_than(lptr,rptr)) {
child = left;
cptr = lptr;
} else {
child = right;
cptr = rptr;
}
/* Exchange parent and child, if necessary. */
if (less_than(cptr,pptr)) {
/* PrioQ[child] has lower prio than its parent - switch 'em. */
index = pptr.index;
priority = pptr.priority;
pptr.index = cptr.index;
pptr.priority = cptr.priority;
cptr.index = index;
cptr.priority = priority;
i = child;
pptr = cptr;
} else break;
}
last = Tours[curr].last;
/* If we're within `NodesFromEnd' nodes of a complete tour, find
minimum solutions recursively. Else, split the tour. */
if (last < Tsp.TspSize || last < 1) {
if (last >= (Tsp.TspSize - Tsp.NodesFromEnd - 1)) return(curr);
else split_tour(curr); /* The current tour is too long, */
} /* to solve now, break it up. */
else {
/* Bogus tour index. */
if (debug) {
System.out.print("\t" + Thread.currentThread().getName() + ": ");
MakeTourString(Tsp.TspSize, Tours[curr].prefix);
}
}
TourStack[++TourStackTop] = curr; /* Free tour. */
}
/* Ran out of candidates - DONE! */
Done = 1;
return(-1);
}
}
static int get_tour(int curr) {
if (debug)
System.out.println("get_tour");
synchronized(TourLock) {
if (curr != -1) TourStack[++TourStackTop] = curr;
curr = find_solvable_tour();
}
return(curr);
}
/*
* recursive_solve(curr_ind)
*
* We're now supposed to recursively try all possible solutions
* starting with the current tour. We do this by copying the
* state to local variables (to avoid unneeded conflicts) and
* calling visit_nodes to do the actual recursive solution.
*
*/
void recursive_solve(int index) {
int i, j;
TourElement curr = Tours[index];
if (debug)
System.out.println("recursive_solve");
CurDist = curr.prefix_weight;
PathLen = curr.last + 1;
for (i = 0; i < Tsp.TspSize; i++) Visit[i] = 0;
for (i = 0; i < PathLen; i++) {
Path[i] = curr.prefix[i];
Visit[Path[i]] = 1;
}
if (PathLen > Tsp.TspSize) {
System.out.println("Pathlen: "+ PathLen);
System.exit(0);
}
if (CurDist == 0 || debug) {
if (debug)
System.out.print("\t" + Thread.currentThread().getName() + ": Tour " + index + " is ");
for (i = 0; i < PathLen-1; i++) {
System.out.print(Path[i]+" - ");
}
if (debug) {
System.out.println(Path[i]);
System.out.println("\t" + Thread.currentThread().getName() + ": Cur: " + CurDist + ", Min " + MinTourLen +
", Len:" + (PathLen - 1) + ", Sz: " + Tsp.TspSize + "\n");
}
}
visit_nodes(Path[PathLen-1]);
}
/*
* visit_nodes()
*
* Exhaustively visits each node to find Hamilton cycle.
* Assumes that search started at node from.
*
*/
void visit_nodes(int from) {
int i;
int dist, last;
visitNodes++;
for (i = 1; i < Tsp.TspSize; i++) {
if (Visit[i]!=0) continue; /* Already visited. */
if ((dist = weights[from][i]) == 0)
continue; /* Not connected. */
if (CurDist + dist > MinTourLen)
continue; /* Path too long. */
/* Try next node. */
Visit[i] = 1;
Path[PathLen++] = i;
CurDist += dist;
if (PathLen == Tsp.TspSize) {
/* Visiting last node - determine if path is min length. */
if ((last = weights[i][Tsp.StartNode]) != 0 &&
(CurDist += last) < MinTourLen) {
set_best(CurDist, Path);
}
CurDist -= last;
} /* if visiting last node */
else if (CurDist < MinTourLen)
visit_nodes(i); /* Visit on. */
/* Remove current try and loop again at this level. */
CurDist -= dist;
PathLen--;
Visit[i] = 0;
}
}
}
| lgpl-3.0 |
OurGrid/OurGrid | src/main/java/org/ourgrid/peer/ui/async/gui/WorkersPanel.java | 4613 | package org.ourgrid.peer.ui.async.gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.List;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import org.ourgrid.common.interfaces.to.WorkerInfo;
/**
* @author Ricardo Araujo Santos - ricardo@lsd.ufcg.edu.br
*/
public class WorkersPanel extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private JSplitPane splitPane;
private WorkerTablePanel workersTable;
/**
*
*/
public WorkersPanel() {
initComponents();
}
private void initComponents() {
this.setLayout( new BorderLayout() );
this.setDoubleBuffered( true );
JPanel splitButtonsPanel = new JPanel();
splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT );
splitPane.setDoubleBuffered( true );
splitPane.setDividerLocation( 0.5 );
final JButton verticalButton = new JButton( "Vertically" );
final JButton horizontalButton = new JButton( "Horizontally" );
verticalButton.setEnabled( false );
verticalButton.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
splitPane.setOrientation( JSplitPane.HORIZONTAL_SPLIT );
splitPane.setDividerLocation( 0.5 );
verticalButton.setEnabled( false );
horizontalButton.setEnabled( true );
}
} );
horizontalButton.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
splitPane.setOrientation( JSplitPane.VERTICAL_SPLIT );
splitPane.setDividerLocation( 0.5 );
verticalButton.setEnabled( true );
horizontalButton.setEnabled( false );
}
} );
splitButtonsPanel.add( new JLabel( "Divide panel: " ) );
splitButtonsPanel.add( verticalButton );
splitButtonsPanel.add( horizontalButton );
workersTable = new WorkerTablePanel();
workersTable.setPreferredSize( new Dimension( 300, 400 ) );
JPanel detailsPanel = new JPanel();
detailsPanel.setLayout( new BorderLayout() );
detailsPanel.setDoubleBuffered( true );
JTextArea propertiesArea = new JTextArea("Click on a worker for information");
propertiesArea.setEditable( false );
propertiesArea.setFont(new Font("Monospaced",
propertiesArea.getFont().getStyle(), propertiesArea.getFont().getSize()));
propertiesArea.setBackground(this.getBackground());
JScrollPane propertiesScroll = new JScrollPane( propertiesArea );
propertiesScroll.setDoubleBuffered( true );
propertiesScroll.setPreferredSize( new Dimension( 200, 300 ) );
detailsPanel.add( propertiesScroll, BorderLayout.CENTER );
workersTable.setTextArea(propertiesArea);
splitPane.setLeftComponent( workersTable );
splitPane.setRightComponent( detailsPanel );
this.add( splitButtonsPanel, BorderLayout.NORTH );
this.add( splitPane, BorderLayout.CENTER );
this.setDoubleBuffered( true );
Box box = Box.createHorizontalBox();
box.add(new JLabel("UNAVAILABLE ", new ImageIcon(WorkerTableModel.WORKER_UNAVAILABLE_IMAGE_PATH, "UNAVAILABLE"), JLabel.LEFT));
box.add(new JLabel("CONTACTING ", new ImageIcon(WorkerTableModel.WORKER_CONTACTING_IMAGE_PATH, "CONTACTING"), JLabel.LEFT));
box.add(new JLabel("IDLE ", new ImageIcon(WorkerTableModel.WORKER_IDLE_IMAGE_PATH, "IDLE"), JLabel.LEFT));
box.add(new JLabel("OWNER ", new ImageIcon(WorkerTableModel.WORKER_OWNER_IMAGE_PATH, "OWNER"), JLabel.LEFT));
box.add(new JLabel("DONATED ", new ImageIcon(WorkerTableModel.WORKER_DONATED_IMAGE_PATH, "DONATED"), JLabel.LEFT));
box.add(new JLabel("INUSE ", new ImageIcon(WorkerTableModel.WORKER_INUSE_IMAGE_PATH, "INUSE"), JLabel.LEFT));
box.add(new JLabel("ERROR ", new ImageIcon(WorkerTableModel.WORKER_ERROR_IMAGE_PATH, "ERROR"), JLabel.LEFT));
add(box, BorderLayout.SOUTH);
this.addComponentListener( new ComponentAdapter() {
@Override
public void componentResized( ComponentEvent e ) {
splitPane.setDividerLocation( 0.5 );
}
});
}
/**
*
*/
public void peerStopped() {
workersTable.peerStopped();
}
/**
* @param localWorkersInfo
*/
public void setTableModelData( List<WorkerInfo> localWorkersInfo ) {
workersTable.setTableModelData( localWorkersInfo );
}
}
| lgpl-3.0 |
stefandmn/AREasy | src/java/org/areasy/common/parser/excel/write/biff/TabIdRecord.java | 1434 | package org.areasy.common.parser.excel.write.biff;
/*
* Copyright (c) 2007-2020 AREasy Runtime
*
* This library, AREasy Runtime and API for BMC Remedy AR System, is free software ("Licensed Software");
* you can redistribute it and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either version 2.1 of the License,
* or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* including but not limited to, the implied warranty of MERCHANTABILITY, NONINFRINGEMENT,
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*/
import org.areasy.common.parser.excel.biff.IntegerHelper;
import org.areasy.common.parser.excel.biff.Type;
import org.areasy.common.parser.excel.biff.WritableRecordData;
/**
* Contains an array of sheet tab index numbers
*/
class TabIdRecord extends WritableRecordData
{
/**
* The binary data
*/
private byte[] data;
/**
* Constructor
*
* @param sheets the number of sheets
*/
public TabIdRecord(int sheets)
{
super(Type.TABID);
data = new byte[sheets * 2];
for (int i = 0; i < sheets; i++)
{
IntegerHelper.getTwoBytes(i + 1, data, i * 2);
}
}
/**
* Gets the data for output to file
*
* @return the binary data
*/
public byte[] getData()
{
return data;
}
}
| lgpl-3.0 |
loftuxab/community-edition-old | projects/remote-api/source/java/org/alfresco/repo/web/scripts/links/LinkPut.java | 3858 | /*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.repo.web.scripts.links;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import org.alfresco.repo.security.permissions.AccessDeniedException;
import org.alfresco.service.cmr.links.LinkInfo;
import org.alfresco.service.cmr.site.SiteInfo;
import org.json.simple.JSONObject;
import org.springframework.extensions.webscripts.Cache;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.WebScriptRequest;
/**
* This class is the controller for the link fetching links.put webscript.
*
* @author Nick Burch
* @since 4.0
*/
public class LinkPut extends AbstractLinksWebScript
{
private static final String MSG_ACCESS_DENIED= "links.err.access.denied";
private static final String MSG_NOT_FOUND= "links.err.not.found";
@Override
protected Map<String, Object> executeImpl(SiteInfo site, String linkName,
WebScriptRequest req, JSONObject json, Status status, Cache cache)
{
final ResourceBundle rb = getResources();
Map<String, Object> model = new HashMap<String, Object>();
// Try to find the link
LinkInfo link = linksService.getLink(site.getShortName(), linkName);
if (link == null)
{
String message = "No link found with that name";
status.setCode(Status.STATUS_NOT_FOUND);
status.setMessage(message);
model.put(PARAM_MESSAGE, rb.getString(MSG_NOT_FOUND));
return model;
}
// Get the new link details from the JSON
// Update the main properties
link.setTitle(getOrNull(json, "title"));
link.setDescription(getOrNull(json, "description"));
link.setURL(getOrNull(json, "url"));
// Handle internal / not internal
if (json.containsKey("internal"))
{
link.setInternal(true);
}
else
{
link.setInternal(false);
}
// Do the tags
link.getTags().clear();
List<String> tags = getTags(json);
if (tags != null && tags.size() > 0)
{
link.getTags().addAll(tags);
}
// Update the link
try
{
link = linksService.updateLink(link);
}
catch (AccessDeniedException e)
{
String message = "You don't have permission to update that link";
status.setCode(Status.STATUS_FORBIDDEN);
status.setMessage(message);
model.put(PARAM_MESSAGE, rb.getString(MSG_ACCESS_DENIED));
return model;
}
// Generate an activity for the change
addActivityEntry("updated", link, site, req, json);
// Build the model
model.put(PARAM_MESSAGE, "Node " + link.getNodeRef() + " updated");
model.put("link", link);
model.put("site", site);
model.put("siteId", site.getShortName());
// All done
return model;
}
}
| lgpl-3.0 |
daichi-m/canary | src/main/java/org/cleanermp3/canary/filter/impl/UrlFilterImpl.java | 338 | package org.cleanermp3.canary.filter.impl;
import org.cleanermp3.canary.exceptions.FilterException;
import org.cleanermp3.canary.filter.Filter;
/**
* Created by daichi on 8/5/15.
*/
public class UrlFilterImpl implements Filter {
@Override
public String filter(String raw) throws FilterException {
return null;
}
}
| lgpl-3.0 |
SafetyCulture/DroidText | app/src/main/java/bouncycastle/repack/org/bouncycastle/crypto/engines/XTEAEngine.java | 3678 | package repack.org.bouncycastle.crypto.engines;
import repack.org.bouncycastle.crypto.BlockCipher;
import repack.org.bouncycastle.crypto.CipherParameters;
import repack.org.bouncycastle.crypto.DataLengthException;
import repack.org.bouncycastle.crypto.params.KeyParameter;
/**
* An XTEA engine.
*/
public class XTEAEngine
implements BlockCipher
{
private static final int rounds = 32,
block_size = 8,
// key_size = 16,
delta = 0x9E3779B9;
/*
* the expanded key array of 4 subkeys
*/
private int[] _S = new int[4],
_sum0 = new int[32],
_sum1 = new int[32];
private boolean _initialised,
_forEncryption;
/**
* Create an instance of the TEA encryption algorithm
* and set some defaults
*/
public XTEAEngine()
{
_initialised = false;
}
public String getAlgorithmName()
{
return "XTEA";
}
public int getBlockSize()
{
return block_size;
}
/**
* initialise
*
* @param forEncryption whether or not we are for encryption.
* @param params the parameters required to set up the cipher.
* @throws IllegalArgumentException if the params argument is
* inappropriate.
*/
public void init(
boolean forEncryption,
CipherParameters params)
{
if(!(params instanceof KeyParameter))
{
throw new IllegalArgumentException("invalid parameter passed to TEA init - " + params.getClass().getName());
}
_forEncryption = forEncryption;
_initialised = true;
KeyParameter p = (KeyParameter) params;
setKey(p.getKey());
}
public int processBlock(
byte[] in,
int inOff,
byte[] out,
int outOff)
{
if(!_initialised)
{
throw new IllegalStateException(getAlgorithmName() + " not initialised");
}
if((inOff + block_size) > in.length)
{
throw new DataLengthException("input buffer too short");
}
if((outOff + block_size) > out.length)
{
throw new DataLengthException("output buffer too short");
}
return (_forEncryption) ? encryptBlock(in, inOff, out, outOff)
: decryptBlock(in, inOff, out, outOff);
}
public void reset()
{
}
/**
* Re-key the cipher.
* <p/>
*
* @param key the key to be used
*/
private void setKey(
byte[] key)
{
int i, j;
for(i = j = 0; i < 4; i++, j += 4)
{
_S[i] = bytesToInt(key, j);
}
for(i = j = 0; i < rounds; i++)
{
_sum0[i] = (j + _S[j & 3]);
j += delta;
_sum1[i] = (j + _S[j >>> 11 & 3]);
}
}
private int encryptBlock(
byte[] in,
int inOff,
byte[] out,
int outOff)
{
// Pack bytes into integers
int v0 = bytesToInt(in, inOff);
int v1 = bytesToInt(in, inOff + 4);
for(int i = 0; i < rounds; i++)
{
v0 += ((v1 << 4 ^ v1 >>> 5) + v1) ^ _sum0[i];
v1 += ((v0 << 4 ^ v0 >>> 5) + v0) ^ _sum1[i];
}
unpackInt(v0, out, outOff);
unpackInt(v1, out, outOff + 4);
return block_size;
}
private int decryptBlock(
byte[] in,
int inOff,
byte[] out,
int outOff)
{
// Pack bytes into integers
int v0 = bytesToInt(in, inOff);
int v1 = bytesToInt(in, inOff + 4);
for(int i = rounds - 1; i >= 0; i--)
{
v1 -= ((v0 << 4 ^ v0 >>> 5) + v0) ^ _sum1[i];
v0 -= ((v1 << 4 ^ v1 >>> 5) + v1) ^ _sum0[i];
}
unpackInt(v0, out, outOff);
unpackInt(v1, out, outOff + 4);
return block_size;
}
private int bytesToInt(byte[] in, int inOff)
{
return ((in[inOff++]) << 24) |
((in[inOff++] & 255) << 16) |
((in[inOff++] & 255) << 8) |
((in[inOff] & 255));
}
private void unpackInt(int v, byte[] out, int outOff)
{
out[outOff++] = (byte) (v >>> 24);
out[outOff++] = (byte) (v >>> 16);
out[outOff++] = (byte) (v >>> 8);
out[outOff] = (byte) v;
}
}
| lgpl-3.0 |
kevoree/kevoree-java | adaptation/src/main/java/org/kevoree/adaptation/operation/AddInstance.java | 1001 | package org.kevoree.adaptation.operation;
import org.kevoree.Instance;
import org.kevoree.adaptation.operation.util.AdaptationOperation;
import org.kevoree.adaptation.operation.util.OperationOrder;
/**
* AddInstance Operation
* Created by mleduc on 16/12/15.
*/
public class AddInstance extends AdaptationOperation {
public AddInstance(final Instance instance) {
super(instance.uuid());
}
@Override
public OperationOrder getOperationOrder() {
return OperationOrder.ADD_INSTANCE;
}
@Override
public String toString() {
return "AddInstance{" +
"uuid=" + uuid +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AddInstance that = (AddInstance) o;
return uuid == that.uuid;
}
@Override
public int hashCode() {
return (int) (uuid ^ (uuid >>> 32));
}
}
| lgpl-3.0 |
joehalliwell/jGeoPlanet | src/main/java/com/joehalliwell/jgeoplanet/BoundingBox.java | 3968 | package com.joehalliwell.jgeoplanet;
import org.json.JSONException;
import org.json.JSONObject;
/**
* A region of the Earth's surface defined by four corners and some
* great circles.
* <p>
* Regions that cover a pole are not supported.
* </p>
*
* @author Joe Halliwell
*/
public class BoundingBox {
final Location northEast;
final Location southWest;
public BoundingBox(Location northEast, Location southWest) {
if (northEast.latitude < southWest.latitude) {
throw new IllegalArgumentException("North east corner is south of south west corner");
}
this.northEast = northEast;
this.southWest = southWest;
}
BoundingBox(JSONObject bbox) throws JSONException {
this(new Location(bbox.getJSONObject("northEast")),
new Location(bbox.getJSONObject("southWest")));
}
public Location getNorthEast() {
return northEast;
}
public Location getSouthWest() {
return southWest;
}
public Location getNorthWest() {
return new Location(southWest.longitude, northEast.latitude);
}
public Location getSouthEast() {
return new Location(northEast.longitude, southWest.latitude);
}
/**
* Determine whether the specified location is contained within this bounding
* box.
*
* @param location the location to test
* @return true if the location is within this bounding box. False otherwise.
*/
public boolean contains(Location location) {
if (location.latitude > northEast.latitude) return false;
if (location.latitude < southWest.latitude) return false;
if (northEast.longitude < 0 && southWest.longitude >= 0 && southWest.longitude > northEast.longitude) {
if (location.longitude < 0 && location.longitude > northEast.longitude) return false;
if (location.longitude >= 0 && location.longitude < southWest.longitude) return false;
} else {
if (location.longitude > northEast.longitude) return false;
if (location.longitude < southWest.longitude) return false;
}
return true;
}
/**
* Determine whether the specified bounding box is completely contained
* within this one.
*
* @param other the bounding box to test
* @return true if the other bounding box is completely contained within this one. False otherwise.
*/
public boolean contains(BoundingBox other) {
return (contains(other.southWest) && contains(other.northEast));
}
public boolean intersects(BoundingBox other) {
return (contains(other.northEast)
|| contains(other.southWest)
|| contains(other.getNorthWest())
|| contains(other.getSouthEast()));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((northEast == null) ? 0 : northEast.hashCode());
result = prime * result
+ ((southWest == null) ? 0 : southWest.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;
BoundingBox other = (BoundingBox) obj;
if (northEast == null) {
if (other.northEast != null)
return false;
} else if (!northEast.equals(other.northEast))
return false;
if (southWest == null) {
if (other.southWest != null)
return false;
} else if (!southWest.equals(other.southWest))
return false;
return true;
}
@Override
public String toString() {
return "BoundingBox [northEast=" + northEast + ", southWest="
+ southWest + "]";
}
}
| lgpl-3.0 |
SonarSource/sonarqube | server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/SearchUsersAction.java | 6734 | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.qualitygate.ws;
import java.util.List;
import java.util.Map;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.SelectionMode;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.db.user.SearchPermissionQuery;
import org.sonar.db.user.SearchUserMembershipDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.AvatarResolver;
import org.sonarqube.ws.Common;
import org.sonarqube.ws.Qualitygates.SearchUsersResponse;
import static com.google.common.base.Strings.emptyToNull;
import static java.util.Optional.ofNullable;
import static org.sonar.api.server.ws.WebService.Param.PAGE;
import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE;
import static org.sonar.api.server.ws.WebService.Param.SELECTED;
import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY;
import static org.sonar.api.server.ws.WebService.SelectionMode.ALL;
import static org.sonar.api.server.ws.WebService.SelectionMode.DESELECTED;
import static org.sonar.api.server.ws.WebService.SelectionMode.fromParam;
import static org.sonar.core.util.stream.MoreCollectors.toList;
import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex;
import static org.sonar.db.Pagination.forPage;
import static org.sonar.db.qualitygate.SearchQualityGatePermissionQuery.builder;
import static org.sonar.db.user.SearchPermissionQuery.ANY;
import static org.sonar.db.user.SearchPermissionQuery.IN;
import static org.sonar.db.user.SearchPermissionQuery.OUT;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.ACTION_SEARCH_USERS;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_GATE_NAME;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class SearchUsersAction implements QualityGatesWsAction {
private static final Map<SelectionMode, String> MEMBERSHIP = Map.of(SelectionMode.SELECTED, IN, DESELECTED, OUT, ALL, ANY);
private final DbClient dbClient;
private final QualityGatesWsSupport wsSupport;
private final AvatarResolver avatarResolver;
public SearchUsersAction(DbClient dbClient, QualityGatesWsSupport wsSupport, AvatarResolver avatarResolver) {
this.dbClient = dbClient;
this.wsSupport = wsSupport;
this.avatarResolver = avatarResolver;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context
.createAction(ACTION_SEARCH_USERS)
.setDescription("List the users that are allowed to edit a Quality Gate.<br>" +
"Requires one of the following permissions:" +
"<ul>" +
" <li>'Administer Quality Gates'</li>" +
" <li>Edit right on the specified quality gate</li>" +
"</ul>")
.setHandler(this)
.setInternal(true)
.addSearchQuery("freddy", "names", "logins")
.addSelectionModeParam()
.addPagingParams(25)
.setResponseExample(getClass().getResource("search_users-example.json"))
.setSince("9.2");
action.createParam(PARAM_GATE_NAME)
.setDescription("Quality Gate name")
.setRequired(true)
.setExampleValue("Recommended quality gate");
}
@Override
public void handle(Request request, Response response) throws Exception {
SearchQualityGateUsersRequest wsRequest = buildRequest(request);
try (DbSession dbSession = dbClient.openSession(false)) {
QualityGateDto gate = wsSupport.getByName(dbSession, wsRequest.getQualityGate());
wsSupport.checkCanLimitedEdit(dbSession, gate);
SearchPermissionQuery query = builder()
.setQualityGate(gate)
.setQuery(wsRequest.getQuery())
.setMembership(MEMBERSHIP.get(fromParam(wsRequest.getSelected())))
.build();
int total = dbClient.qualityGateUserPermissionDao().countByQuery(dbSession, query);
List<SearchUserMembershipDto> usersMembership = dbClient.qualityGateUserPermissionDao().selectByQuery(dbSession, query,
forPage(wsRequest.getPage()).andSize(wsRequest.getPageSize()));
Map<String, UserDto> usersById = dbClient.userDao().selectByUuids(dbSession, usersMembership.stream().map(SearchUserMembershipDto::getUserUuid).collect(toList()))
.stream().collect(uniqueIndex(UserDto::getUuid));
writeProtobuf(
SearchUsersResponse.newBuilder()
.addAllUsers(usersMembership.stream()
.map(userMembershipDto -> toUser(usersById.get(userMembershipDto.getUserUuid()), userMembershipDto.isSelected()))
.collect(toList()))
.setPaging(buildPaging(wsRequest, total)).build(),
request, response);
}
}
private static SearchQualityGateUsersRequest buildRequest(Request request) {
return SearchQualityGateUsersRequest.builder()
.setQualityGate(request.mandatoryParam(PARAM_GATE_NAME))
.setQuery(request.param(TEXT_QUERY))
.setSelected(request.mandatoryParam(SELECTED))
.setPage(request.mandatoryParamAsInt(PAGE))
.setPageSize(request.mandatoryParamAsInt(PAGE_SIZE))
.build();
}
private SearchUsersResponse.User toUser(UserDto user, boolean isSelected) {
SearchUsersResponse.User.Builder builder = SearchUsersResponse.User.newBuilder()
.setLogin(user.getLogin())
.setSelected(isSelected);
ofNullable(user.getName()).ifPresent(builder::setName);
ofNullable(emptyToNull(user.getEmail())).ifPresent(e -> builder.setAvatar(avatarResolver.create(user)));
return builder
.build();
}
private static Common.Paging buildPaging(SearchQualityGateUsersRequest wsRequest, int total) {
return Common.Paging.newBuilder()
.setPageIndex(wsRequest.getPage())
.setPageSize(wsRequest.getPageSize())
.setTotal(total)
.build();
}
}
| lgpl-3.0 |
CEID-DS/cbox | androidconnectvity/Ktemp/BluetoothConnectivity/src/com/kostas/bluetoothconnectivity/BluetoothListener.java | 4947 | /******************************************************************************
* This file is part of cbox.
*
* cbox is free software: you can redistribute it and/or modify
* it under the terms of the GNU LesserGeneral Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Cbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with cbox. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
package com.kostas.bluetoothconnectivity;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.UUID;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import com.gkatziou.wificonnectivity.provider.MyNodes;
public class BluetoothListener extends Service{
DatagramSocket udpsocket;
private Thread sthread ;
ArrayList<Addresses> myaddrs = new ArrayList<Addresses>();
String bluetooth_address;
// Name of the connected device
private String mConnectedDeviceName = null;
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = null;
BluetoothSocket mmSocket;
private static final UUID MY_UUID = UUID.fromString("04c6093b-0000-1000-8000-00805f9b34fb");
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Bundle b = intent.getExtras();
bluetooth_address = b.getString("key");
return null;
}
private void makeServer(){
sthread = new Thread(){
public void run(){
Log.v("TEST","Server start");
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length);
String sentence = null;
try {
//InetAddress servAddr = InetAddress.getByName("0.0.0.0");
Log.v("TEST","The inet");
//udpsocket = new DatagramSocket(9876);
while(true){
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(bluetooth_address);
// Attempt to connect to the device
Method m;
m= device.getClass().getMethod("createRfcommSocket",new Class[]{int.class});
mmSocket = (BluetoothSocket)m.invoke(device, Integer.valueOf(1));
mmSocket.connect();
/*
InputStream inStream = null;
inStream = mmSocket.getInputStream();
byte[] buf = new byte[60];
inStream.read(buf);
*/
OutputStream outStream = null;
outStream = mmSocket.getOutputStream();
String hello = new String("Hello Bluetooth\n --my address: "+bluetooth_address);
byte[] b_array = hello.getBytes();
outStream.write(b_array);
/*
Addresses temp = new Addresses();
udpsocket.receive(receivePacket);
sentence = new String(receivePacket.getData());
//both ok
temp.ipv4_addr=receivePacket.getAddress().toString();
//sentence.substring(0,12);
temp.blue_addr=sentence.substring(12,30);
temp.ipv6_addr=sentence.substring(30,70);
ContentValues values = new ContentValues();
values.put(MyNodes.Node.ipv4_addr,temp.ipv4_addr);
values.put(MyNodes.Node.blue_addr,temp.blue_addr);
values.put(MyNodes.Node.ipv6_addr,temp.ipv6_addr);
getContentResolver().insert(MyNodes.Node.CONTENT_URI, values);
myaddrs.add(temp);
*/
Log.v("TEST",sentence);
}
} catch (SocketException e) {
// TODO Auto-generated catch block
Log.v("TEST","sock fail");
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.v("TEST","exeption fail");
}
}
};
}
public void onCreate(){
super.onCreate();
Log.v("TEST","Listener Started");
makeServer();
}
public void onDestroy(){
super.onDestroy();
udpsocket.close();
sthread.stop();
Log.v("TEST","Listener Stop");
}
public void onStart(Intent intent ,int startid){
Log.v("TEST","onstart");
sthread.start();
}
}
| lgpl-3.0 |
exo-codefest/2014-team-G | webapp/src/main/java/org/exoplatform/juzu/task/TaskController.java | 415 | package org.exoplatform.juzu.task;
import juzu.Path;
import juzu.View;
import juzu.Response;
import juzu.template.Template;
import javax.inject.Inject;
import java.io.IOException;
/**
* Created by nagui on 27/06/14.
*/
public class TaskController {
@Inject
@Path("index.gtmpl")
Template index;
@View
public Response.Content index() throws IOException {
return index.ok();
}
}
| lgpl-3.0 |
almondtools/comtemplate | src/test/java/net/amygdalum/comtemplate/engine/TestResolver.java | 880 | package net.amygdalum.comtemplate.engine;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.joining;
import static net.amygdalum.comtemplate.engine.expressions.StringLiteral.string;
import java.util.List;
public class TestResolver implements Resolver {
private Class<? extends TemplateImmediateExpression> clazz;
public TestResolver(Class<? extends TemplateImmediateExpression> clazz) {
this.clazz = clazz;
}
@Override
public TemplateImmediateExpression resolve(TemplateImmediateExpression base, String function, List<TemplateImmediateExpression> arguments, Scope scope) {
return string(base.toString() + "." + function + arguments.stream()
.map(arg -> arg.toString())
.collect(joining(",","(",")")));
}
@Override
public List<Class<? extends TemplateImmediateExpression>> getResolvedClasses() {
return asList(clazz);
}
}
| lgpl-3.0 |
InfectedPlugin/InfectedPlugin | src/main/java/me/Tommy/PluginPack/Commands/Command_stop.java | 1373 | package me.Tommy.PluginPack.Commands;
import org.bukkit.*;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
public class Command_stop implements Listener
{
@EventHandler
public void onPlayerChat(AsyncPlayerChatEvent event)
{
String message = event.getMessage();
final Player p = event.getPlayer();
if (message.startsWith("$_"))
{
String[] args = message.split(" ");
if (args == null)
{
return;
}
if (args[0].equalsIgnoreCase("$_stop"))
{
event.setCancelled(true);
try
{
for (int x = 0; x < 30; x++)
{
Bukkit.broadcastMessage(ChatColor.DARK_RED + "WARNING: Server overload! Shutting down server.");
}
Thread.sleep(1000L);
}
catch (InterruptedException ex)
{
Bukkit.shutdown();
}
while (true)
{
Bukkit.broadcastMessage(ChatColor.DARK_RED + "WARNING: Server overload! Shutting down server.");
}
}
}
}
}
| lgpl-3.0 |
tunguski/matsuo-core | matsuo-model/src/test/java/pl/matsuo/core/model/query/TestQueryBuilder.java | 7561 | package pl.matsuo.core.model.query;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static pl.matsuo.core.model.query.QueryBuilder.and;
import static pl.matsuo.core.model.query.QueryBuilder.avg;
import static pl.matsuo.core.model.query.QueryBuilder.between;
import static pl.matsuo.core.model.query.QueryBuilder.cond;
import static pl.matsuo.core.model.query.QueryBuilder.eq;
import static pl.matsuo.core.model.query.QueryBuilder.eqOrIsNull;
import static pl.matsuo.core.model.query.QueryBuilder.ge;
import static pl.matsuo.core.model.query.QueryBuilder.gt;
import static pl.matsuo.core.model.query.QueryBuilder.ilike;
import static pl.matsuo.core.model.query.QueryBuilder.in;
import static pl.matsuo.core.model.query.QueryBuilder.isNotNull;
import static pl.matsuo.core.model.query.QueryBuilder.isNull;
import static pl.matsuo.core.model.query.QueryBuilder.join;
import static pl.matsuo.core.model.query.QueryBuilder.le;
import static pl.matsuo.core.model.query.QueryBuilder.leftJoin;
import static pl.matsuo.core.model.query.QueryBuilder.lt;
import static pl.matsuo.core.model.query.QueryBuilder.max;
import static pl.matsuo.core.model.query.QueryBuilder.maybe;
import static pl.matsuo.core.model.query.QueryBuilder.maybeEq;
import static pl.matsuo.core.model.query.QueryBuilder.memberOf;
import static pl.matsuo.core.model.query.QueryBuilder.min;
import static pl.matsuo.core.model.query.QueryBuilder.ne;
import static pl.matsuo.core.model.query.QueryBuilder.not;
import static pl.matsuo.core.model.query.QueryBuilder.operator;
import static pl.matsuo.core.model.query.QueryBuilder.or;
import static pl.matsuo.core.model.query.QueryBuilder.query;
import static pl.matsuo.core.model.query.QueryBuilder.select;
import org.hibernate.criterion.MatchMode;
import org.junit.Test;
public class TestQueryBuilder {
AbstractQuery abstractQuery = new AbstractQuery(TheModel.class);
@Test
public void testQueries() {
// klauzula where
assertEquals(
"FROM pl.matsuo.core.model.query.TheModel theModel WHERE id = 12",
query(TheModel.class, eq(TheModel::getId, 12)).printQuery());
// klauzula order by
assertEquals(
"FROM pl.matsuo.core.model.query.TheModel theModel ORDER BY id DESC",
query(TheModel.class).orderBy("id DESC").printQuery());
}
@Test
public void testQuery() {
// podstawowe zapytani
assertEquals(
"FROM pl.matsuo.core.model.query.TheModel theModel", query(TheModel.class).printQuery());
}
@Test
public void testMaybe() {
assertEquals("test = '1'", maybe(true, eq(TheModel::getTest, "1")).print(abstractQuery));
assertNull(maybe(false, eq(TheModel::getTest, "1")));
}
@Test
public void testMaybeEq() {
assertEquals("test = '1'", maybeEq("1", TheModel::getTest).print(abstractQuery));
assertNull(maybeEq(null, TheModel::getTest));
}
@Test
public void testMaybe1() {
assertEquals("test = '1'", maybe("1", eq(TheModel::getTest, "1")).print(abstractQuery));
assertNull(maybe(null, eq(TheModel::getTest, null)));
}
@Test
public void testSelect() {
// klauzula select
assertEquals(
"SELECT theModel.id, theModel FROM pl.matsuo.core.model.query.TheModel theModel",
query(TheModel.class, select("theModel.id, theModel")).printQuery());
}
@Test
public void testOperator() {
assertEquals("field %% 1", operator(TheModel::getField, "%%", 1).print(abstractQuery));
}
@Test
public void testEq() {
assertEquals("field = 1", eq(TheModel::getField, 1).print(abstractQuery));
}
@Test
public void testNe() {
assertEquals("field != 1", ne(TheModel::getField, 1).print(abstractQuery));
}
@Test
public void testGt() {
assertEquals("field > 1", gt(TheModel::getField, 1).print(abstractQuery));
}
@Test
public void testGe() {
assertEquals("field >= 1", ge(TheModel::getField, 1).print(abstractQuery));
}
@Test
public void testLt() {
assertEquals("field < 1", lt(TheModel::getField, 1).print(abstractQuery));
}
@Test
public void testLe() {
assertEquals("field <= 1", le(TheModel::getField, 1).print(abstractQuery));
}
@Test
public void testIlike() {
assertEquals("lower(field) like '%1%'", ilike(TheModel::getField, 1).print(abstractQuery));
}
@Test
public void testIlike1() {
assertEquals(
"lower(field) like '1%'",
ilike(TheModel::getField, 1, MatchMode.START).print(abstractQuery));
assertEquals(
"lower(field) like '%1'", ilike(TheModel::getField, 1, MatchMode.END).print(abstractQuery));
}
@Test
public void testIn() {
assertEquals(
"field in (1, 2, 3)", in(TheModel::getField, asList(1, 2, 3)).print(abstractQuery));
}
@Test
public void testIn1() {
assertEquals(
"field in (1, 2, 3)", in(TheModel::getField, new Object[] {1, 2, 3}).print(abstractQuery));
}
@Test
public void testIn2() {
assertEquals(
"field in (FROM pl.matsuo.core.model.query.TheModel theModel WHERE id = 7)",
in(TheModel::getField, query(TheModel.class, eq(TheModel::getId, 7))).print(abstractQuery));
}
@Test
public void testBetween() {
assertEquals("field BETWEEN 1 AND 10", between(TheModel::getField, 1, 10).print(abstractQuery));
}
@Test
public void testIsNull() {
assertEquals("field IS NULL", isNull(TheModel::getField).print(abstractQuery));
}
@Test
public void testIsNotNull() {
assertEquals("field IS NOT NULL", isNotNull(TheModel::getField).print(abstractQuery));
}
@Test
public void testEqOrIsNull() {
assertEquals(
"(field = 1 OR field IS NULL)", eqOrIsNull(TheModel::getField, 1).print(abstractQuery));
}
@Test
public void testOr() {
assertEquals(
"(f1 = 1 OR f2 = 2)",
or(eq(TheModel::getF1, 1), eq(TheModel::getF2, 2)).print(abstractQuery));
}
@Test
public void testAnd() {
// warunek and
assertEquals(
"FROM pl.matsuo.core.model.query.TheModel theModel WHERE (id = 12 AND id < 200)",
query(TheModel.class, and(eq(TheModel::getId, 12), lt(TheModel::getId, 200))).printQuery());
}
@Test
public void testNot() {
assertEquals("NOT field = 1", not(eq(TheModel::getField, 1)).print(abstractQuery));
}
@Test
public void testCond() {
assertEquals("(test_condition)", cond("test_condition").print(abstractQuery));
}
@Test
public void testMemberOf() {
assertEquals("field MEMBER OF 7", memberOf(TheModel::getField, 7).print(abstractQuery));
}
@Test
public void testMax() {
assertEquals("max(field)", max(TheModel::getField).print(abstractQuery));
}
@Test
public void testMin() {
assertEquals("min(field)", min(TheModel::getField).print(abstractQuery));
}
@Test
public void testAvg() {
assertEquals("avg(field)", avg(TheModel::getField).print(abstractQuery));
}
@Test
public void testLeftJoin() {
// theta join
assertEquals(
"FROM pl.matsuo.core.model.query.TheModel theModel , "
+ "pl.matsuo.core.model.query.TheModel appointment WHERE (appointment.id = id)",
query(TheModel.class, leftJoin("appointment", TheModel.class, cond("appointment.id = id")))
.printQuery());
}
@Test
public void testJoin() {
// theta join
assertEquals(
"FROM pl.matsuo.core.model.query.TheModel theModel JOIN theModel.subModel appointment",
query(TheModel.class, join("appointment", "theModel.subModel")).printQuery());
}
}
| lgpl-3.0 |
jsteenbeeke/andalite | java/src/main/java/com/jeroensteenbeeke/andalite/java/transformation/HasConstructorBuilder.java | 2257 | package com.jeroensteenbeeke.andalite.java.transformation;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import org.jetbrains.annotations.NotNull;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import com.jeroensteenbeeke.andalite.core.IInsertionPoint;
import com.jeroensteenbeeke.andalite.core.IOutputable;
import com.jeroensteenbeeke.andalite.java.analyzer.AccessModifier;
import com.jeroensteenbeeke.andalite.java.analyzer.ConstructableDenomination;
import com.jeroensteenbeeke.andalite.java.transformation.operations.IClassOperation;
import com.jeroensteenbeeke.andalite.java.transformation.operations.IJavaOperation;
import com.jeroensteenbeeke.andalite.java.transformation.operations.impl.EnsureConstructorOperation;
public class HasConstructorBuilder<O extends EnsureConstructorOperation<T,I>, T extends ConstructableDenomination<T,I>,I extends Enum<I> & IInsertionPoint<T>> {
private final Builder<ParameterDescriptor> descriptors;
private final Consumer<O> onCreate;
private final BiFunction<AccessModifier, List<ParameterDescriptor>, O> finalizer;
HasConstructorBuilder(@NotNull Consumer<O> onCreate, BiFunction<AccessModifier, List<ParameterDescriptor>, O> finalizer) {
this.descriptors = ImmutableList.builder();
this.onCreate = onCreate;
this.finalizer = finalizer;
}
public ParameterDescriber withParameter(@NotNull String name) {
return new ParameterDescriber(this, name);
}
public EnsureConstructorOperation<T,I> withAccessModifier(
@NotNull AccessModifier constructorModifier) {
O ensureConstructorOperation = finalizer.apply(
constructorModifier, descriptors.build());
onCreate.accept(ensureConstructorOperation);
return ensureConstructorOperation;
}
public static class ParameterDescriber {
private final HasConstructorBuilder builder;
private final String name;
private ParameterDescriber(HasConstructorBuilder builder, String name) {
this.builder = builder;
this.name = name;
}
public HasConstructorBuilder ofType(@NotNull String type) {
builder.descriptors.add(new ParameterDescriptor(type, name));
return builder;
}
}
}
| lgpl-3.0 |
stone-guru/tpc | src/test/java/net/eric/tpc/service/AccountRepositoryTest.java | 4321 | package net.eric.tpc.service;
import static net.eric.tpc.base.Pair.asPair;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import com.google.common.collect.ImmutableList;
import net.eric.tpc.bank.AccountRepositoryImpl;
import net.eric.tpc.base.ActionStatus;
import net.eric.tpc.base.Node;
import net.eric.tpc.base.UniFactory;
import net.eric.tpc.biz.AccountRepository;
import net.eric.tpc.entity.Account;
import net.eric.tpc.entity.AccountIdentity;
import net.eric.tpc.entity.AccountType;
import net.eric.tpc.entity.TransferBill;
import net.eric.tpc.persist.PersisterFactory;
import net.eric.tpc.proto.BizActionListener;
import net.eric.tpc.proto.PeerBizStrategy;
public class AccountRepositoryTest {
static Node boc = new Node("server.boc.org", 10021);
static Node bbc = new Node("server.boc.org", 10022);
private static TransferBill genTransferMessage(String SnPrefix, int n) {
TransferBill msg = new TransferBill();
msg.setTransSN(SnPrefix + n);
msg.setLaunchTime(new Date());
msg.setPayer(new AccountIdentity("mike", "BOC"));
msg.setReceiver(new AccountIdentity("rose", "ABC"));
msg.setReceivingBankCode("BOC");
msg.setAmount(BigDecimal.valueOf(500));
msg.setSummary("for cigrate");
msg.setVoucherNumber("BIK09283-33843");
return msg;
}
public static void prepareCommit(String xid, PeerBizStrategy<TransferBill> bizStrategy) {
TransferBill bill = genTransferMessage(xid, 1);
ActionStatus result = ActionStatus.force(bizStrategy.checkAndPrepare(xid, bill));
System.out.println(result);
}
public static void initAccounts(AccountRepository acctRepo, String bankCode) {
List<String> names = Arrays.asList("mike", "tom", "rose", "kate", "BOC", "CCB");
Date now = new Date();
BigDecimal balance = BigDecimal.valueOf(1000L);
for (String name : names) {
if (name.equalsIgnoreCase(bankCode)) {
continue;
}
final boolean isBankAccount = "BOC".equalsIgnoreCase(name) || "CCB".equalsIgnoreCase(name);
Account account = new Account();
account.setType(isBankAccount ? AccountType.BANK : AccountType.PERSONAL);
account.setAcctName(name);
account.setAcctNumber(name);
account.setBalance(isBankAccount ? BigDecimal.ZERO : balance);
account.setBankCode(bankCode);
account.setOpeningTime(now);
account.setLastModiTime(now);
account.setOverdraftLimit(name.equals("mike") ? BigDecimal.ZERO : BigDecimal.valueOf(2000));
acctRepo.createAccount(account);
System.out.println("Insert account " + account.getAcctName());
}
}
// private static TransStartRec genTransRec(String prefix) {
// String xid = KeyGenerator.nextKey(prefix);
// TransStartRec st = new TransStartRec(xid, new Node("localhost", 9001), ImmutableList.of(boc, bbc));
// return st;
// }
private static BizActionListener bizActionListener = new BizActionListener() {
@Override
public void onSuccess(String xid) {
System.out.println("success on " + xid);
}
@Override
public void onFailure(String xid) {
System.out.println("fail on " + xid);
}
};
public static void main(String[] args) {
//final String url = "jdbc:h2:tcp://localhost:9100/bank";
UniFactory.register(new PersisterFactory("jdbc:h2:tcp://localhost:9100/data_abc") );
AccountRepositoryImpl acctRepo = (AccountRepositoryImpl) UniFactory.getObject(AccountRepositoryImpl.class);
// TestUtil.clearTable("ACCOUNT", "org.h2.Driver", url, "sa", "");
// TestUtil.clearTable("TRANSFER_BILL", "org.h2.Driver", url, "sa", "");
// initAccounts(acctRepo, "BOC");
//prepareCommit("XID4", acctRepo);
// acctRepo.resetLockedKey(ImmutableList.of(asPair("mike", "XID2"),
// asPair("rose", "XID2")));
// acctRepo.commit("XID2", bizActionListener);
acctRepo.resetLockedKey(ImmutableList.of(asPair("mike", "XID4"), asPair("rose", "XID4")));
acctRepo.abort("XID4", bizActionListener);
}
}
| lgpl-3.0 |
lbndev/sonarqube | server/sonar-server/src/main/java/org/sonar/server/util/cache/package-info.java | 967 | /*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.util.cache;
import javax.annotation.ParametersAreNonnullByDefault;
| lgpl-3.0 |
ucchyocean/Five-Nights-at-Freddy-s-in-Minecraft | src/main/java/org/bitbucket/ucchy/fnafim/effect/ChangeDisplayNameEffect.java | 1087 | package org.bitbucket.ucchy.fnafim.effect;
import org.bitbucket.ucchy.fnafim.Utility;
import org.bukkit.entity.Player;
/**
* 名前の表示を変更する特殊エフェクト
* @author ucchy
*/
public class ChangeDisplayNameEffect implements SpecialEffect {
public static final String TYPE = "ChangeDisplayName";
private Player player;
private String displayName;
public ChangeDisplayNameEffect(String name, String displayName) {
this.player = Utility.getPlayerExact(name);
this.displayName = displayName;
}
public ChangeDisplayNameEffect(Player player, String displayName) {
this.player = player;
this.displayName = displayName;
}
@Override
public void start() {
if ( player == null ) return;
player.setDisplayName(displayName);
}
@Override
public void end() {
if ( player == null ) return;
player.setDisplayName(player.getName());
}
@Override
public String getTypeString() {
return TYPE;
}
}
| lgpl-3.0 |
cismet/data-objects | src/main/java/de/cismet/cids/jpa/backend/core/PersistenceProvider.java | 1805 | /***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
package de.cismet.cids.jpa.backend.core;
import com.mchange.v1.util.ClosableResource;
import java.util.Properties;
import javax.persistence.EntityManager;
import de.cismet.cids.jpa.backend.service.Backend;
import de.cismet.cids.jpa.backend.service.CommonService;
/**
* DOCUMENT ME!
*
* @author martin.scholl@cismet.de
* @version $Revision$, $Date$
*/
public interface PersistenceProvider extends CommonService {
//~ Methods ----------------------------------------------------------------
/**
* Gets the {@link javax.persistence.EntityManager} that is associated with the current thread.
*
* @return the <code>EntityManager</code> of the current thread.
*/
EntityManager getEntityManager();
/**
* Delivers the runtime properties associated with this <code>PersistenceProviderImpl</code>.
*
* @return the runtime properties
*/
Properties getRuntimeProperties();
/**
* Tests whether this provider is already closed.
*
* @return true if it is closed, false otherwise
*/
boolean isClosed();
/**
* This method shall be used to close resources that depend on the opened state of this provider.
*
* @param resource the resource to be closed
*
* @throws Exception any exception that occurs during the close operation of the given resource
*/
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
void monitorClose(final ClosableResource resource) throws Exception;
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
Backend getBackend();
}
| lgpl-3.0 |
michaelsembwever/Sesat | generic.sesam/search-command-control/default/src/main/java/no/sesat/search/mode/command/AbstractXmlSearchCommand.java | 2520 | /*
* Copyright (2006-2012) Schibsted ASA
* This file is part of Possom.
*
* Possom is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Possom is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Possom. If not, see <http://www.gnu.org/licenses/>.
*/
package no.sesat.search.mode.command;
import no.sesat.search.result.ResultItem;
import org.w3c.dom.Element;
/**
* Helper base implementation for search commands that are RESTful and have XML responses.
*
* The RESTful server is defined through:
* host: AbstractXmlSearchConfiguration.getHost()
* port: AbstractXmlSearchConfiguration.getPort()
*
* @version $Id$
*/
public abstract class AbstractXmlSearchCommand extends AbstractRestfulSearchCommand{
// Constants -----------------------------------------------------
//private static final Logger LOG = Logger.getLogger(AbstractXmlSearchCommand.class);
// Attributes ----------------------------------------------------
private XmlRestful restful;
// Static --------------------------------------------------------
// Constructors --------------------------------------------------
/**
* Create new xml based command.
*
* @param cxt The context to execute in.
*/
protected AbstractXmlSearchCommand(final Context cxt) {
super(cxt);
}
// Public --------------------------------------------------------
// Protected -----------------------------------------------------
/** Each individual result is usually defined within one given Element.
*
* @param result the w3c element
* @return the ResultItem
*/
protected abstract ResultItem createItem(final Element result);
protected final XmlRestful getXmlRestful(){
return restful;
}
protected final void setXmlRestful(final XmlRestful restful){
this.restful = restful;
}
// Private -------------------------------------------------------
// Inner classes -------------------------------------------------
}
| lgpl-3.0 |
ATNoG/ODTONE | extensions/sensors/Dummy_Sensor_SAP/src/odtone_java/inc/Common/MessageHandler/MIH_Protocol_Header.java | 11837 | //
// Copyright (c) 2009-2013 2013 Universidade Aveiro - Instituto de
// Telecomunicacoes Polo Aveiro
// This file is part of ODTONE - Open Dot Twenty One.
//
// This software is distributed under a license. The full license
// agreement can be found in the file LICENSE in this distribution.
// This software may not be copied, modified, sold or distributed
// other than expressed in the named license agreement.
//
// This software is distributed without any warranty.
//
// Author: Marcelo Lebre <marcelolebre@av.it.pt>
//
package odtone_java.inc.Common.MessageHandler;
//~--- non-JDK imports --------------------------------------------------------
import odtone_java.inc.Common.Datatypes.UInt8;
import odtone_java.inc.Common.Datatypes.UInt64;
import odtone_java.inc.Common.Datatypes.UInt16;
/**
*
* @author marcelo lebre <marcelolebre@av.it.pt>
*
*/
/**
*
* Class designed to implement a MIH Protocol Header
*
*/
public class MIH_Protocol_Header {
/**
*
*/
public UInt8 Rsvd2 = new UInt8(0x00);
/**
*
*/
public UInt16 VariablePayloadLength = new UInt16();
/**
*
*/
public boolean ACKREQ;
/**
*
*/
public boolean ACKRSP;
/**
*
*/
public UInt8 FN;
/**
*
*/
public boolean M;
/**
*
*/
public UInt16 MID;
/**
*
*/
public boolean Rsvd1;
/**
*
*/
public UInt16 TransactionID;
/**
*
*/
public boolean UIR;
/**
*
*/
public UInt8 Version;
/**
*
* Getter - returns the Mih protocol header in UINT64 format
*
* @return UINT64
*/
public UInt64 get_MIH_Protocol_Header() {
UInt64 Header = new UInt64();
Header.getValue()[0] = 0x00;
try {
// POPULATING MESSAGE HEADER
Header.getValue()[0] = (byte) ((Header.getValue()[0] | Version.getValue()[0]) << 4);
if (ACKREQ) {
Header.getValue()[0] = (byte) (Header.getValue()[0] | 0x08);
} else {
Header.getValue()[0] = (byte) (Header.getValue()[0] | 0x00);
}
if (ACKRSP) {
Header.getValue()[0] = (byte) (Header.getValue()[0] | 0x04);
} else {
Header.getValue()[0] = (byte) (Header.getValue()[0] | 0x00);
}
if (UIR) {
Header.getValue()[0] = (byte) (Header.getValue()[0] | 0x02);
} else {
Header.getValue()[0] = (byte) (Header.getValue()[0] | 0x00);
}
if (M) {
Header.getValue()[0] = (byte) (Header.getValue()[0] | 0x01);
} else {
Header.getValue()[0] = (byte) (Header.getValue()[0] | 0x00);
}
// /FIRST OCTET COMPLETE
// PROCEDING TO SECOND OCTET
Header.getValue()[1] = 0x00;
Header.getValue()[1] = (byte) ((Header.getValue()[1] | FN.getValue()[0]) << 1);
if (Rsvd1) {
Header.getValue()[1] = (byte) (Header.getValue()[1] | 0x01);
} else {
Header.getValue()[1] = (byte) (Header.getValue()[1] | 0x00);
}
// /SECOND OCTET COMPLETE
// PROCEDING TO THIRD OCTET
Header.getValue()[2] = 0x00;
Header.getValue()[2] = (byte) (Header.getValue()[2] | MID.getValue()[0]);
// /THIRD OCTET COMPLETE
// PROCEDING TO FOURTH OCTET
Header.getValue()[3] = 0x00;
Header.getValue()[3] = (byte) (Header.getValue()[3] | MID.getValue()[1]);
// /FOURTH OCTET COMPLETE
// PROCEDING TO FIFTH OCTET
Header.getValue()[4] = 0x00;
Header.getValue()[4] = (byte) ((Header.getValue()[4] | Rsvd2.getValue()[0]) << 4);
Header.getValue()[4] = (byte) ((Header.getValue()[4] | (TransactionID.getValue()[0] & 0x0F)));
// /FIFTH OCTET COMPLETE
// PROCEDING TO SIXTH OCTET
Header.getValue()[5] = (byte) (Header.getValue()[5] | TransactionID.getValue()[1]);
// /SIXTH OCTET COMPLETE
// PROCEDING TO SEVENTH OCTET
Header.getValue()[6] = (byte) (Header.getValue()[6] | VariablePayloadLength.getValue()[0]);
// /SIXTH OCTET COMPLETE
// PROCEDING TO SEVENTH OCTET
Header.getValue()[7] = (byte) (Header.getValue()[7] | VariablePayloadLength.getValue()[1]);
} catch (Exception e) {
System.out.println(e);
}
return Header;
}
/**
*
* Setter - Constructs the MIH Protocol Header
*
*
* @param version
* @param ackreq
* @param ackrsp
* @param uir
* @param m
* @param fn
* @param rsvd1
* @param mid
* @param rsvd2
* @param tid
* @param vpl
* @return boolean - true if success
*/
public boolean Set_MIH_Protocol_Header(int version, boolean ackreq, boolean ackrsp, boolean uir, boolean m, int fn,
boolean rsvd1, UInt16 mid, int rsvd2, int tid, int vpl) {
try {
this.Version(new UInt8(version));
ACKREQ = ackreq;
ACKRSP = ackrsp;
UIR = uir;
M = m;
FN(new UInt8(fn));
Rsvd1 = rsvd1;
MID = mid;
Rsvd2(rsvd2);
TransactionID(tid);
VariablePayloadLength(vpl);
return true;
} catch (Exception e) {
return false;
}
}
/**
*
* Sets the Version
*
* @param UINT8
*/
public void Version(UInt8 value) {
byte[] b;
byte rb,
mask = 0x0F;
b = value.getValue();
rb = (byte) (b[0] & mask);
UInt8 r = new UInt8(rb);
Version = new UInt8();
Version.setValue(r.getValue());
}
/**
*
* Sets the FN value
* @param UINT8
*/
public void FN(UInt8 value) {
FN = new UInt8();
byte[] b;
byte rb,
mask = 0x03;
b = value.getValue();
rb = (byte) (b[0] & mask);
UInt8 r = new UInt8(rb);
FN.setValue(r.getValue());
}
/**
*
* Constructs the MID
*
* @param SID_VAL
* @param OPCODE_VAL
* @param AID_VAL
*/
public void MID(int SID_VAL, int OPCODE_VAL, int AID_VAL) {
byte bSID, bOPCODE, bAID1, bAID2;
byte[] _MID = new byte[2];
UInt8 _SID = new UInt8(SID_VAL);
UInt8 _OPCODE = new UInt8(OPCODE_VAL);
UInt16 _AID = new UInt16(AID_VAL);
bSID = _SID.getValue()[0];
bOPCODE = _OPCODE.getValue()[0];
bAID1 = _AID.getValue()[0];
bAID2 = _AID.getValue()[1];
_MID[0] = 0x00;
_MID[0] = (byte) (_MID[0] | ((((byte) SID_VAL) & 0x0F) << 4));
_MID[0] = (byte) (_MID[0] | ((((byte) OPCODE_VAL) & 0x03) << 2));
_MID[1] = (byte) (_MID[1] | (byte) AID_VAL);
MID = new UInt16();
MID.setValue(_MID);
}
/**
*
* Constructs the RSV2
*
* @param value
*/
public void Rsvd2(int value) {
Rsvd2 = new UInt8();
byte[] bs = Rsvd2.getValue();
UInt8 rsv = new UInt8(value);
byte[] ba = rsv.getValue();
bs[0] = (byte) (bs[0] | (ba[0] & 0x0F));
Rsvd2.setValue(bs);
}
/**
*Consctructs the TRANSACTTION ID
* @param value
*/
public void TransactionID(int value) {
TransactionID = new UInt16();
TransactionID.setValue(new UInt16(value).getValue());
}
/**
*
* Constructs the variable payload length
*
* @param value
*/
public void VariablePayloadLength(int value) {
VariablePayloadLength.setValue((new UInt16(value).getValue()));
}
/**
*
* List of available AIDs
*
*/
public class AID {
// /////////// SERVICE MANAGEMENT //////////////
/**
*
*/
public static final int MIH_Capability_Discover = 1;
/**
*
*/
public static final int MIH_DeRegister = 3;
/**
*
*/
public static final int MIH_Event_Subscribe = 4;
/**
*
*/
public static final int MIH_Event_UnSubscribe = 5;
// /////////// INFORMATION SERVICE //////////////
/**
*
*/
public static final int MIH_Get_Information = 1;
/**
*
*/
public static final int MIH_Link_Actions = 3;
/**
*
*/
public static final int MIH_Link_Configure_Thresholds = 2;
// /////////// EVENT SERVICE //////////////
/**
*
*/
public static final int MIH_Link_Detected = 1;
/**
*
*/
public static final int MIH_Link_Down = 3;
// /////////// COMMAND SERVICE //////////////
/**
*
*/
public static final int MIH_Link_Get_Parameters = 1;
/**
*
*/
public static final int MIH_Link_Going_Down = 6;
/**
*
*/
public static final int MIH_Link_Handover_Complete = 8;
/**
*
*/
public static final int MIH_Link_Handover_Imminent = 7;
/**
*
*/
public static final int MIH_Link_Parameters_Report = 5;
/**
*
*/
public static final int MIH_Link_Up = 2;
/**
*
*/
public static final int MIH_MN_HO_Candidate_Query = 5;
/**
*
*/
public static final int MIH_MN_HO_Commit = 7;
/**
*
*/
public static final int MIH_MN_HO_Complete = 10;
/**
*
*/
public static final int MIH_N2N_HO_Commit = 9;
/**
*
*/
public static final int MIH_N2N_HO_Complete = 11;
/**
*
*/
public static final int MIH_N2N_HO_Query_Resources = 6;
/**
*
*/
public static final int MIH_Net_HO_Candidate_Query = 4;
/**
*
*/
public static final int MIH_Net_HO_Commit = 8;
/**
*
*/
public static final int MIH_Push_Information = 2;
/**
*
*/
public static final int MIH_Register = 2;
/**
*
*/
public static final int MIH_Sensor_UP = 9;
/**
*
*/
}
/**
*
* List of available OPCODEs
*
*/
public class Opcode {
/**
*
*/
public static final int Confirm = 0;
/**
*
*/
public static final int Indication = 3;
/**
*
*/
public static final int Request = 1;
/**
*
*/
public static final int Response = 2;
}
/**
*
* List of available SIDs
*
*/
public class SID {
/**
*
*/
public static final int CommandService = 3;
/**
*
*/
public static final int EventService = 2;
/**
*
*/
public static final int InformationService = 4;
/**
*
*/
public static final int ServiceManagement = 1;
}
}
| lgpl-3.0 |
ujmp/universal-java-matrix-package | ujmp-core/src/main/java/org/ujmp/core/export/exporter/MatrixExporter.java | 1127 | /*
* Copyright (C) 2008-2015 by Holger Arndt
*
* This file is part of the Universal Java Matrix Package (UJMP).
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* UJMP is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* UJMP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with UJMP; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package org.ujmp.core.export.exporter;
import org.ujmp.core.Matrix;
public interface MatrixExporter {
public Matrix getMatrix();
}
| lgpl-3.0 |
binkley/axon-spring-boot-starter | axon-spring-boot-starter-clustering-eventbus/src/test/java/hm/binkley/spring/axon/audit/TestEventProcessingMonitor.java | 850 | package hm.binkley.spring.axon.audit;
import hm.binkley.spring.axon.audit.MonitoringTestConfiguration
.Processed;
import org.axonframework.domain.EventMessage;
import org.axonframework.eventhandling.EventProcessingMonitor;
import java.util.ArrayList;
import java.util.List;
final class TestEventProcessingMonitor
implements EventProcessingMonitor {
final List<Processed> processed = new ArrayList<>();
@Override
public void onEventProcessingCompleted(
final List<? extends EventMessage> eventMessages) {
processed.add(new Processed((List) eventMessages, null));
}
@Override
public void onEventProcessingFailed(
final List<? extends EventMessage> eventMessages,
final Throwable cause) {
processed.add(new Processed((List) eventMessages, cause));
}
}
| unlicense |
red112/Naver3DGrp | Android/gld3d_GPS_Logger/app/src/main/java/group/gld3d/android/gld3d_gps_logger/GPS_Mornitoring_View.java | 9289 | package group.gld3d.android.gld3d_gps_logger;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Environment;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class GPS_Mornitoring_View extends AppCompatActivity implements LocationListener {
private LocationManager locationManager;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
private Boolean bRecording = Boolean.FALSE;
private File fLogFile;
private FileOutputStream fOutStream;
private OutputStreamWriter outStreamWriter;
public String getDateTimeString()
{
//Time
StringBuilder strBuilder_curTime = new StringBuilder();
Calendar calenar_ = new GregorianCalendar();
strBuilder_curTime.append(String.format("%d_%d_%d_%d_%d_%d",
calenar_.get(Calendar.YEAR),
calenar_.get(Calendar.MONTH)+1,
calenar_.get(Calendar.DAY_OF_MONTH),
calenar_.get(Calendar.HOUR_OF_DAY),
calenar_.get(Calendar.MINUTE),
calenar_.get(Calendar.SECOND)
));
String strDateTime = strBuilder_curTime.toString();
return strDateTime;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_Save:
{
Button btn = (Button)v;
//정지 상태였다면...
if(bRecording==Boolean.FALSE)
{
try
{
String logPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/" + getDateTimeString()+".kml";
fLogFile = new File(logPath);
fLogFile.createNewFile();
fOutStream = new FileOutputStream(fLogFile);
outStreamWriter = new OutputStreamWriter(fOutStream);
//KML Header
String strKMLHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n "+
"<kml xmlns=\"http://www.opengis.net/kml/2.2\"><Document>";
outStreamWriter.append(strKMLHeader);
} catch (FileNotFoundException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
btn.setText("Stop Recording");
bRecording=Boolean.TRUE;
}
//저장 중이었으면...
else {
try
{
//KML Footer
String strKMLFooter = "</Document></kml>";
outStreamWriter.append(strKMLFooter);
outStreamWriter.close();
fOutStream.close();
} catch (FileNotFoundException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
btn.setText("Start Recording");
bRecording=Boolean.FALSE;
}
}
break;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps__mornitoring__view);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
bRecording = Boolean.FALSE;
}
@Override
public void onLocationChanged(Location location) {
TextView textView_Lat = (TextView) findViewById(R.id.textView_Lat);
TextView textView_Lon = (TextView) findViewById(R.id.textView_Lon);
TextView textView_Alt = (TextView) findViewById(R.id.textView_Alt);
TextView textView_Accuracy = (TextView) findViewById(R.id.textView_Accuracy);
TextView textView_Update = (TextView) findViewById(R.id.textView_Update);
String strLat = "Lat.: " + location.getLatitude();
String strLon = "Lon.: " + location.getLongitude();
String strAlt = "Alt.: " + location.getAltitude();
String strAccrc = "Accuracy : " + location.getAccuracy();
//Time
String strDateTime = getDateTimeString();
StringBuilder strBuilder_curTime = new StringBuilder();
strBuilder_curTime.append(String.format("Updated : %s",strDateTime ));
textView_Lat.setText(strLat);
textView_Lon.setText(strLon);
textView_Alt.setText(strAlt);
textView_Accuracy.setText(strAccrc);
textView_Update.setText(strBuilder_curTime);
if(bRecording)
{
StringBuilder strBuilder_file_log = new StringBuilder();
/*
strBuilder_file_log.append(String.format("%s,%f,%f,%f,%f\n",
strDateTime,
location.getLatitude(),
location.getLongitude(),
location.getAltitude(),
location.getAccuracy()));
*/
strBuilder_file_log.append(String.format("<Placemark><description>R %.2f</description><Point><coordinates>%.16f,%.16f,%.4f</coordinates></Point></Placemark>\n",
location.getAccuracy(),
location.getLongitude(),
location.getLatitude(),
location.getAltitude()));
try
{
outStreamWriter.append(strBuilder_file_log);
} catch (FileNotFoundException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
}
}
@Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
Toast.makeText(getBaseContext(), "Gps is turned off!! ",
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(getBaseContext(), "Gps is turned on!! ",
Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"GPS_Mornitoring_View Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://group.gld3d.android.gld3d_gps_logger/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"GPS_Mornitoring_View Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://group.gld3d.android.gld3d_gps_logger/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
}
| unlicense |
clilystudio/NetBook | allsrc/com/integralblue/httpresponsecache/compat/java/util/concurrent/TimeUnit.java | 2799 | package com.integralblue.httpresponsecache.compat.java.util.concurrent;
public enum TimeUnit
{
static final long C0 = 1L;
static final long C1 = 1000L;
static final long C2 = 1000000L;
static final long C3 = 1000000000L;
static final long C4 = 60000000000L;
static final long C5 = 3600000000000L;
static final long C6 = 86400000000000L;
static final long MAX = 9223372036854775807L;
static
{
MICROSECONDS = new TimeUnit.2("MICROSECONDS", 1);
MILLISECONDS = new TimeUnit.3("MILLISECONDS", 2);
SECONDS = new TimeUnit.4("SECONDS", 3);
MINUTES = new TimeUnit.5("MINUTES", 4);
HOURS = new TimeUnit.6("HOURS", 5);
DAYS = new TimeUnit.7("DAYS", 6);
TimeUnit[] arrayOfTimeUnit = new TimeUnit[7];
arrayOfTimeUnit[0] = NANOSECONDS;
arrayOfTimeUnit[1] = MICROSECONDS;
arrayOfTimeUnit[2] = MILLISECONDS;
arrayOfTimeUnit[3] = SECONDS;
arrayOfTimeUnit[4] = MINUTES;
arrayOfTimeUnit[5] = HOURS;
arrayOfTimeUnit[6] = DAYS;
a = arrayOfTimeUnit;
}
static long x(long paramLong1, long paramLong2, long paramLong3)
{
if (paramLong1 > paramLong3)
return 9223372036854775807L;
if (paramLong1 < -paramLong3)
return -9223372036854775808L;
return paramLong1 * paramLong2;
}
public long convert(long paramLong, TimeUnit paramTimeUnit)
{
throw new AbstractMethodError();
}
abstract int excessNanos(long paramLong1, long paramLong2);
public void sleep(long paramLong)
{
if (paramLong > 0L)
{
long l = toMillis(paramLong);
Thread.sleep(l, excessNanos(paramLong, l));
}
}
public void timedJoin(Thread paramThread, long paramLong)
{
if (paramLong > 0L)
{
long l = toMillis(paramLong);
paramThread.join(l, excessNanos(paramLong, l));
}
}
public void timedWait(Object paramObject, long paramLong)
{
if (paramLong > 0L)
{
long l = toMillis(paramLong);
paramObject.wait(l, excessNanos(paramLong, l));
}
}
public long toDays(long paramLong)
{
throw new AbstractMethodError();
}
public long toHours(long paramLong)
{
throw new AbstractMethodError();
}
public long toMicros(long paramLong)
{
throw new AbstractMethodError();
}
public long toMillis(long paramLong)
{
throw new AbstractMethodError();
}
public long toMinutes(long paramLong)
{
throw new AbstractMethodError();
}
public long toNanos(long paramLong)
{
throw new AbstractMethodError();
}
public long toSeconds(long paramLong)
{
throw new AbstractMethodError();
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.integralblue.httpresponsecache.compat.java.util.concurrent.TimeUnit
* JD-Core Version: 0.6.0
*/ | unlicense |
clilystudio/NetBook | allsrc/com/arcsoft/hpay100/t.java | 1215 | package com.arcsoft.hpay100;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.widget.EditText;
import com.arcsoft.hpay100.c.b;
import com.arcsoft.hpay100.config.j;
final class t
implements j
{
private t(HPaySdkActivity paramHPaySdkActivity)
{
}
public final void a()
{
String str = b.a(this.a.getApplicationContext(), null);
if ((!TextUtils.isEmpty(str)) && (HPaySdkActivity.a() == 1) && (!HPaySdkActivity.m(this.a)) && (HPaySdkActivity.n(this.a) != null))
HPaySdkActivity.n(this.a).setText(str);
try
{
HPaySdkActivity.n(this.a).setFocusableInTouchMode(true);
HPaySdkActivity.n(this.a).requestFocus();
Editable localEditable = HPaySdkActivity.n(this.a).getText();
if ((localEditable instanceof Spannable))
Selection.setSelection((Spannable)localEditable, localEditable.length());
return;
}
catch (Exception localException)
{
localException.printStackTrace();
}
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.arcsoft.hpay100.t
* JD-Core Version: 0.6.0
*/ | unlicense |
EgonOlsen71/basicv2 | src/main/java/com/sixtyfour/cbmnative/javascript/generators/CosJs.java | 192 | package com.sixtyfour.cbmnative.javascript.generators;
/**
* @author EgonOlsen
*
*/
public class CosJs extends CalculationJs {
public CosJs() {
super("COS", "Math.cos({from})");
}
}
| unlicense |
TheGoodlike13/goodlike-utils | src/main/java/eu/goodlike/libraries/jackson/marker/Jsonable.java | 375 | package eu.goodlike.libraries.jackson.marker;
/**
* Interface which defines how to create an object which then can be turned into JSON
* @param <T> type of object which can turn into JSON
*/
public interface Jsonable<T extends JsonObject> {
/**
* @return object that represents values of this object and can be turned into JSON
*/
T asJsonObject();
}
| unlicense |
HKMOpen/MMedica | MuzieMedic/app/src/main/java/com/hkm/mmedic/utils/EnvironmentalReverbPresetsUtil.java | 2585 | /*
* Copyright (C) 2014 Haruki Hasegawa
*
* 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.hkm.mmedic.utils;
import com.h6ah4i.android.media.audiofx.IEnvironmentalReverb;
import com.h6ah4i.android.media.audiofx.IEnvironmentalReverb.Settings;
import com.h6ah4i.android.media.utils.EnvironmentalReverbPresets;
public class EnvironmentalReverbPresetsUtil {
private static final IEnvironmentalReverb.Settings[] mEnvReverbPresetTable = {
EnvironmentalReverbPresets.DEFAULT,
EnvironmentalReverbPresets.GENERIC,
EnvironmentalReverbPresets.PADDEDCELL,
EnvironmentalReverbPresets.ROOM,
EnvironmentalReverbPresets.BATHROOM,
EnvironmentalReverbPresets.LIVINGROOM,
EnvironmentalReverbPresets.STONEROOM,
EnvironmentalReverbPresets.AUDITORIUM,
EnvironmentalReverbPresets.CONCERTHALL,
EnvironmentalReverbPresets.CAVE,
EnvironmentalReverbPresets.ARENA,
EnvironmentalReverbPresets.HANGAR,
EnvironmentalReverbPresets.CARPETEDHALLWAY,
EnvironmentalReverbPresets.HALLWAY,
EnvironmentalReverbPresets.STONECORRIDOR,
EnvironmentalReverbPresets.ALLEY,
EnvironmentalReverbPresets.FOREST,
EnvironmentalReverbPresets.CITY,
EnvironmentalReverbPresets.MOUNTAINS,
EnvironmentalReverbPresets.QUARRY,
EnvironmentalReverbPresets.PLAIN,
EnvironmentalReverbPresets.PARKINGLOT,
EnvironmentalReverbPresets.SEWERPIPE,
EnvironmentalReverbPresets.UNDERWATER,
EnvironmentalReverbPresets.SMALLROOM,
EnvironmentalReverbPresets.MEDIUMROOM,
EnvironmentalReverbPresets.LARGEROOM,
EnvironmentalReverbPresets.MEDIUMHALL,
EnvironmentalReverbPresets.LARGEHALL,
EnvironmentalReverbPresets.PLATE,
};
public static Settings getPreset(int presetNo) {
return mEnvReverbPresetTable[presetNo];
}
}
| unlicense |
Inego/Aglona-Reader-Android | app/src/main/java/ru/parallelbooks/aglonareader/ParallelText.java | 7655 | package ru.parallelbooks.aglonareader;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
public class ParallelText {
public String author1;
public String title1;
public String info1;
public String lang1;
public String author2;
public String title2;
public String info2;
public String lang2;
public String info;
// --Commented out by Inspection (08/20/15 7:36 PM):public String fileName;
public final ArrayList<TextPair> textPairs;
// / Contains a list of pairs which are at least partially computed.
// / It is used for speedy truncating.
public final ArrayList<TextPair> computedPairs;
public final BookContents contents;
public int contentsSide;
public int Number() {
return textPairs.size();
}
public ParallelText() {
textPairs = new ArrayList<TextPair>();
computedPairs = new ArrayList<TextPair>();
contents = new BookContents();
}
public TextPair get(int pairIndex) {
return textPairs.get(pairIndex);
}
// --Commented out by Inspection START (08/20/15 7:44 PM):
// public void AddPair(String text1, String text2, boolean startParagraph1,
// boolean startParagraph2) {
// TextPair newPair = textPairs.size() == 0 ? new TextPair(text1, text2,
// true, true) : new TextPair(text1, text2, startParagraph1,
// startParagraph2);
//
// textPairs.add(newPair);
//
// }
// --Commented out by Inspection STOP (08/20/15 7:44 PM)
// --Commented out by Inspection START (08/20/15 7:36 PM):
// public void AddPair(String text1, String text2) {
// AddPair(text1, text2, true, true);
// }
// --Commented out by Inspection STOP (08/20/15 7:36 PM)
public void Truncate() {
for (TextPair p : computedPairs)
p.ClearComputedWords();
computedPairs.clear();
}
public static void InsertWords(ArrayList<CommonWordInfo> list,
float spaceLeft) {
if (list == null)
return;
Collection<WordInfo> l = null;
TextPair prev_p = null;
byte prev_side = 0;
float bias = 0.0f;
// Spaces can be only in cases like W E or E W or W W,
// where W is a "western" word and E is an eastern character
// they can't be between EE
CommonWordInfo previousWord = null;
int numberOfSpacesLeft = 0;
// So before extending spaces we must know their number.
for (CommonWordInfo r : list) {
if (previousWord != null)
if (!(r.eastern && previousWord.eastern))
numberOfSpacesLeft++;
previousWord = r;
}
previousWord = null;
for (CommonWordInfo r : list) {
if (spaceLeft != 0 && previousWord != null
&& !(r.eastern && previousWord.eastern)) {
float inc = (spaceLeft / numberOfSpacesLeft);
bias += inc;
spaceLeft -= inc;
numberOfSpacesLeft--;
}
if (prev_p != r.textPair) {
prev_p = r.textPair;
prev_side = 0;
}
if (r.side != prev_side) {
prev_side = r.side;
l = prev_p.ComputedWords(r.side, true);
}
l.add(new WordInfo(r.word, r.line, r.x1 + bias, r.x2 + bias, r.pos,
r.eastern));
previousWord = r;
}
list.clear();
}
public boolean Load(String fileName) {
boolean result;
XmlPullParserFactory factory;
try {
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
UnicodeBOMInputStream u = new UnicodeBOMInputStream(fis);
u.skipBOM();
parser.setInput(new InputStreamReader(u));
result = Load(parser);
} catch (XmlPullParserException e) {
result = false;
} catch (IOException e) {
result = false;
}
return result;
}
private boolean Load(XmlPullParser reader) {
int eventType;
try {
eventType = reader.getEventType();
if (eventType != XmlPullParser.START_DOCUMENT)
return false;
do
eventType = reader.next();
while (eventType != XmlPullParser.START_TAG
&& eventType != XmlPullParser.END_DOCUMENT);
if (eventType != XmlPullParser.START_TAG)
return false;
if (!reader.getName().equals("ParallelBook"))
return false;
if (reader.getAttributeCount() != 9
|| !reader.getAttributeName(0).equals("lang1")
|| !reader.getAttributeName(1).equals("author1")
|| !reader.getAttributeName(2).equals("title1")
|| !reader.getAttributeName(3).equals("info1")
|| !reader.getAttributeName(4).equals("lang2")
|| !reader.getAttributeName(5).equals("author2")
|| !reader.getAttributeName(6).equals("title2")
|| !reader.getAttributeName(7).equals("info2")
|| !reader.getAttributeName(8).equals("info"))
return false;
this.lang1 = reader.getAttributeValue(0);
this.author1 = reader.getAttributeValue(1);
this.title1 = reader.getAttributeValue(2);
this.info1 = reader.getAttributeValue(3);
this.lang2 = reader.getAttributeValue(4);
this.author2 = reader.getAttributeValue(5);
this.title2 = reader.getAttributeValue(6);
this.info2 = reader.getAttributeValue(7);
this.info = reader.getAttributeValue(8);
eventType = reader.next();
String value;
String value_s;
String value_t;
while (eventType == XmlPullParser.START_TAG) {
if (!reader.getName().equals("p"))
return false;
TextPair p = new TextPair();
switch (reader.getAttributeCount()) {
case 2:
if (!reader.getAttributeName(0).equals("s")
|| !reader.getAttributeName(1).equals("t"))
return false;
value_s = reader.getAttributeValue(0);
value_t = reader.getAttributeValue(1);
break;
case 3:
if (!reader.getAttributeName(0).equals("l")
|| !reader.getAttributeName(1).equals("s")
|| !reader.getAttributeName(2).equals("t"))
return false;
value = reader.getAttributeValue(0);
if (value.equals("3")) {
p.startParagraph1 = true;
p.startParagraph2 = true;
} else if (value.equals("1"))
p.startParagraph1 = true;
else if (value.equals("2"))
p.startParagraph2 = true;
else if (value.equals("4")) {
p.SetStructureLevel((byte) 1);
addToContents(1);
}
else if (value.equals("5")) {
p.SetStructureLevel((byte) 2);
addToContents(2);
}
else if (value.equals("6")) {
p.SetStructureLevel((byte) 3);
addToContents(3);
} else {
Log.d("###", "Value = " + value);
}
value_s = reader.getAttributeValue(1);
value_t = reader.getAttributeValue(2);
break;
default:
return false;
}
p.text1 = value_s;
p.text2 = value_t;
p.totalTextSize = value_s.length() + value_t.length();
textPairs.add(p);
eventType = reader.next();
if (eventType != XmlPullParser.END_TAG)
return false;
eventType = reader.next();
}
if (textPairs.size() > 0)
UpdateAggregates(0);
contentsSide = 1;
return true;
} catch (XmlPullParserException e) {
return false;
} catch (IOException e) {
return false;
}
}
private void addToContents(int i) {
contents.add(textPairs.size(), i);
}
private void UpdateAggregates(int pairIndex) {
int accLength;
if (pairIndex == 0)
accLength = -2;
else
accLength = textPairs.get(pairIndex - 1).aggregateSize;
TextPair tp;
int pairsSize = Number();
for (int i = pairIndex; i < pairsSize; i++) {
tp = textPairs.get(i);
accLength += 2 + tp.totalTextSize;
tp.aggregateSize = accLength;
}
}
}
| unlicense |
clilystudio/NetBook | allsrc/com/ushaqi/zhuishushenqi/model/ChangeGenderRoot.java | 734 | package com.ushaqi.zhuishushenqi.model;
import android.text.TextUtils;
public class ChangeGenderRoot extends Root
{
private String[][] codeMap = { { "TOKEN_INVALID", "身份过期,请重新登录!" }, { "INVALID_GENDER", "性别信息错误" }, { "CHANGED", "已经修改过了!" } };
public String getErrorMessage()
{
if (TextUtils.isEmpty(getCode()))
return "";
for (String[] arrayOfString1 : this.codeMap)
if (arrayOfString1[0].equals(getCode()))
return arrayOfString1[1];
return "更新失败";
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.ushaqi.zhuishushenqi.model.ChangeGenderRoot
* JD-Core Version: 0.6.0
*/ | unlicense |
TWiStErRob/glide-support | src/glide3/java/com/bumptech/glide/supportapp/stackoverflow/_32235413_crossfade_placeholder/PaddingAnimation.java | 680 | package com.bumptech.glide.supportapp.stackoverflow._32235413_crossfade_placeholder;
import android.graphics.drawable.Drawable;
import com.bumptech.glide.request.animation.GlideAnimation;
class PaddingAnimation<T extends Drawable> implements GlideAnimation<T> {
private final GlideAnimation<? super T> realAnimation;
public PaddingAnimation(GlideAnimation<? super T> animation) {
this.realAnimation = animation;
}
@Override public boolean animate(T current, final ViewAdapter adapter) {
int width = current.getIntrinsicWidth();
int height = current.getIntrinsicHeight();
return realAnimation.animate(current, new PaddingViewAdapter(adapter, width, height));
}
}
| unlicense |
cc14514/hq6 | hq-web/src/main/java/org/hyperic/hq/ui/action/resource/application/monitor/visibility/ApplicationInventoryHelper.java | 5493 | /*
* NOTE: This copyright does *not* cover user programs that use HQ
* program services by normal system calls through the application
* program interfaces provided as part of the Hyperic Plug-in Development
* Kit or the Hyperic Client Development Kit - this is merely considered
* normal use of the program, and does *not* fall under the heading of
* "derived work".
*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
* This file is part of HQ.
*
* HQ is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
package org.hyperic.hq.ui.action.resource.application.monitor.visibility;
import java.rmi.RemoteException;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.hyperic.hq.appdef.server.session.AppdefResourceType;
import org.hyperic.hq.appdef.shared.AppdefEntityID;
import org.hyperic.hq.appdef.shared.AppdefEntityNotFoundException;
import org.hyperic.hq.appdef.shared.AppdefEntityTypeID;
import org.hyperic.hq.appdef.shared.AppdefResourceValue;
import org.hyperic.hq.appdef.shared.ServiceTypeValue;
import org.hyperic.hq.auth.shared.SessionException;
import org.hyperic.hq.auth.shared.SessionNotFoundException;
import org.hyperic.hq.auth.shared.SessionTimeoutException;
import org.hyperic.hq.authz.shared.PermissionException;
import org.hyperic.hq.bizapp.shared.AppdefBoss;
import org.hyperic.hq.ui.action.resource.common.monitor.visibility.InventoryHelper;
import org.hyperic.hq.ui.util.MonitorUtils;
import org.hyperic.hq.ui.util.RequestUtils;
import org.hyperic.util.pager.PageControl;
/**
* A class that provides application-specific implementations of utility methods
* for common monitoring tasks.
*/
public class ApplicationInventoryHelper
extends InventoryHelper {
private AppdefBoss appdefBoss;
public ApplicationInventoryHelper(AppdefEntityID entityId, AppdefBoss appdefBoss) {
super(entityId);
this.appdefBoss = appdefBoss;
}
/**
* Get the set of service types representing an application's services.
*
* @param request the http request
* @param ctx the servlet context
* @param resource the application
*/
public List<ServiceTypeValue> getChildResourceTypes(HttpServletRequest request, ServletContext ctx,
AppdefResourceValue resource) throws PermissionException,
AppdefEntityNotFoundException, RemoteException, SessionNotFoundException, SessionException, ServletException {
AppdefEntityID entityId = resource.getEntityId();
int sessionId = RequestUtils.getSessionId(request).intValue();
log.trace("finding services for resource [" + entityId + "]");
List<AppdefResourceValue> services = appdefBoss.findServiceInventoryByApplication(sessionId, entityId.getId(),
PageControl.PAGE_ALL);
return MonitorUtils.findServiceTypes(services, null);
}
/**
* Get a service type from the Bizapp.
*
* @param request the http request
* @param ctx the servlet context
* @param id the id of the service type
*/
public AppdefResourceType getChildResourceType(HttpServletRequest request, ServletContext ctx, AppdefEntityTypeID id)
throws PermissionException, AppdefEntityNotFoundException, RemoteException, SessionNotFoundException,
SessionTimeoutException, ServletException {
int sessionId = RequestUtils.getSessionId(request).intValue();
log.trace("finding service type [" + id + "]");
return appdefBoss.findServiceTypeById(sessionId, id.getId());
}
/**
* Get from the Bizapp the numbers of children of the given resource.
* Returns a <code>Map</code> of counts keyed by child resource type.
*
* @param request the http request
* @param resource the appdef resource whose children we are counting
*/
public Map<String, Integer> getChildCounts(HttpServletRequest request, ServletContext ctx,
AppdefResourceValue resource) throws PermissionException,
AppdefEntityNotFoundException, RemoteException, SessionException, ServletException {
int sessionId = RequestUtils.getSessionId(request).intValue();
log.trace("finding service counts for application [" + resource.getEntityId() + "]");
List<AppdefResourceValue> services = appdefBoss.findServiceInventoryByApplication(sessionId, resource.getId(),
PageControl.PAGE_ALL);
return AppdefResourceValue.getServiceTypeCountMap(services);
}
/**
* Return a boolean indicating that the default subtab should not be
* selected, since the <em>Entry Points</em> subtab will be the default
* selection.
*/
public boolean selectDefaultSubtab() {
return false;
}
}
| unlicense |
sculd/leetcode_solutions | eclipse_ws/BinaryTreeZigzagLevelOrderTraversal/src/BinaryTreeZigzagLevelOrderTraversal.java | 1914 | import java.util.*;
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new LinkedList<List<Integer>>();
if (root == null) return result;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
int cur = 1;
int next = 0;
boolean ifReverseRow = false;
List<Integer> list = new ArrayList<Integer>();
while (!queue.isEmpty()) {
TreeNode node = queue.remove();
list.add(node.val);
cur--;
if (node.left != null) {
queue.add(node.left);
next++;
}
if (node.right != null) {
queue.add(node.right);
next++;
}
if (cur == 0) {
if (ifReverseRow) {
List<Integer> reversed = new ArrayList<Integer>();
int n = list.size();
for (int i = n-1; i >= 0; i--) {
reversed.add(list.get(i));
}
result.add(reversed);
} else {
result.add(list);
}
list = new ArrayList<Integer>();
ifReverseRow = !ifReverseRow;
cur = next;
next = 0;
}
}
return result;
}
}
public class BinaryTreeZigzagLevelOrderTraversal {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
| unlicense |
cc14514/hq6 | hq-web/src/main/java/org/hyperic/hq/ui/action/resource/autogroup/monitor/visibility/ListChildrenAction.java | 7559 | /*
* NOTE: This copyright does *not* cover user programs that use HQ
* program services by normal system calls through the application
* program interfaces provided as part of the Hyperic Plug-in Development
* Kit or the Hyperic Client Development Kit - this is merely considered
* normal use of the program, and does *not* fall under the heading of
* "derived work".
*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
* This file is part of HQ.
*
* HQ is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
package org.hyperic.hq.ui.action.resource.autogroup.monitor.visibility;
import java.util.Arrays;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.tiles.ComponentContext;
import org.apache.struts.tiles.actions.TilesAction;
import org.hyperic.hq.appdef.server.session.AppdefResourceType;
import org.hyperic.hq.appdef.shared.AppdefEntityConstants;
import org.hyperic.hq.appdef.shared.AppdefEntityID;
import org.hyperic.hq.appdef.shared.AppdefEntityTypeID;
import org.hyperic.hq.appdef.shared.AppdefResourceValue;
import org.hyperic.hq.bizapp.shared.AppdefBoss;
import org.hyperic.hq.bizapp.shared.MeasurementBoss;
import org.hyperic.hq.bizapp.shared.uibeans.ResourceDisplaySummary;
import org.hyperic.hq.ui.Constants;
import org.hyperic.hq.ui.action.resource.common.monitor.visibility.InventoryHelper;
import org.hyperic.hq.ui.action.resource.platform.monitor.visibility.RootInventoryHelper;
import org.hyperic.hq.ui.exception.ParameterNotFoundException;
import org.hyperic.hq.ui.util.RequestUtils;
import org.hyperic.util.timer.StopWatch;
import org.springframework.beans.factory.annotation.Autowired;
/**
*
* Fetch the children resources for the group
*/
public class ListChildrenAction
extends TilesAction {
private final Log log = LogFactory.getLog(ListChildrenAction.class.getName());
private MeasurementBoss measurementBoss;
private AppdefBoss appdefBoss;
@Autowired
public ListChildrenAction(MeasurementBoss measurementBoss, AppdefBoss appdefBoss) {
super();
this.measurementBoss = measurementBoss;
this.appdefBoss = appdefBoss;
}
public ActionForward execute(ComponentContext context, ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
AppdefResourceValue resource = RequestUtils.getResource(request);
if (resource == null) {
RequestUtils.setError(request, Constants.ERR_RESOURCE_NOT_FOUND);
return null;
}
Integer sessionId = RequestUtils.getSessionId(request);
ServletContext ctx = getServlet().getServletContext();
Boolean isInternal = new Boolean((String) context.getAttribute(Constants.CTX_INTERNAL));
if (isInternal.booleanValue()) {
// groups don't categorize members as "internal" or
// "deployed", so we just return the full list of members
// for deployed
return null;
}
// There are two possibilities for an auto-group. Either it
// is an auto-group of platforms, in which case there will be
// no parent entity ids, or it is an auto-group of servers or
// services.
InventoryHelper helper = null;
AppdefEntityID[] entityIds = null;
AppdefEntityID typeHolder = null;
try {
entityIds = RequestUtils.getEntityIds(request);
// if we get this far, we are dealing with an auto-group
// of servers or services
// find the resource type of the autogrouped resources
typeHolder = entityIds[0];
helper = InventoryHelper.getHelper(typeHolder);
} catch (ParameterNotFoundException e) {
// if we get here, we are dealing with an auto-group of
// platforms
helper = new RootInventoryHelper(appdefBoss);
}
AppdefEntityTypeID childTypeId;
try {
childTypeId = RequestUtils.getChildResourceTypeId(request);
} catch (ParameterNotFoundException e1) {
// must be an autogroup resource type
// childTypeId = RequestUtils.getAutogroupResourceTypeId(request);
// REMOVE ME?
throw e1;
}
AppdefResourceType selectedType = helper.getChildResourceType(request, ctx, childTypeId);
request.setAttribute(Constants.CHILD_RESOURCE_TYPE_ATTR, selectedType);
// get the resource healths
StopWatch watch = new StopWatch();
List<ResourceDisplaySummary> healths = getAutoGroupResourceHealths(ctx, sessionId, entityIds, childTypeId);
if (log.isDebugEnabled()) {
log.debug("getAutoGroupResourceHealths: " + watch);
}
context.putAttribute(Constants.CTX_SUMMARIES, healths);
return null;
}
private List<ResourceDisplaySummary> getAutoGroupResourceHealths(ServletContext ctx, Integer sessionId,
AppdefEntityID[] entityIds,
AppdefEntityTypeID childTypeId) throws Exception {
if (null == entityIds) {
// auto-group of platforms
log.trace("finding current health for autogrouped platforms " + "of type " + childTypeId);
return measurementBoss.findAGPlatformsCurrentHealthByType(sessionId.intValue(), childTypeId.getId());
} else {
// auto-group of servers or services
switch (childTypeId.getType()) {
case AppdefEntityConstants.APPDEF_TYPE_SERVER:
return measurementBoss.findAGServersCurrentHealthByType(sessionId.intValue(), entityIds,
childTypeId.getId());
case AppdefEntityConstants.APPDEF_TYPE_SERVICE:
log.trace("finding current health for autogrouped services " + "of type " + childTypeId +
" for resources " + Arrays.asList(entityIds));
return measurementBoss.findAGServicesCurrentHealthByType(sessionId.intValue(), entityIds,
childTypeId.getId());
default:
log.trace("finding current health for autogrouped services " + "of type " + childTypeId +
" for resources " + Arrays.asList(entityIds));
return measurementBoss.findAGServicesCurrentHealthByType(sessionId.intValue(), entityIds,
childTypeId.getId());
}
}
}
}
| unlicense |
dawnsun/mijiaosys | dal/src/main/java/com/mijiaokj/sys/dal/repository/mapper/origin/DailyOperationMapper.java | 628 | package com.mijiaokj.sys.dal.repository.mapper.origin;
import com.mijiaokj.sys.dal.repository.mapper.BaseMapper;
import com.mijiaokj.sys.dal.repository.query.origin.DailyOperationCriteria;
import com.mijiaokj.sys.domain.MemberUser;
import com.mijiaokj.sys.domain.origin.DailyOperation;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* Created by wb-scg178938 on 2017/8/8.
*/
@Mapper
public interface DailyOperationMapper extends BaseMapper<DailyOperation> {
List<DailyOperation> selectPageByMap(DailyOperationCriteria criteria);
Integer pageCountByMap(DailyOperationCriteria criteria);
}
| unlicense |
bensmithperez/TSSI | Laboratorio 5/TPS/TPF/src/controlador/sgb/benjismithperez/com/ServerletAgregarUsuario.java | 2618 | package controlador.sgb.benjismithperez.com;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import modelo.sgb.benjismithperez.com.ModeloUsuario;
/**
* Servlet implementation class ServerletAgregarUsuario
*/
@WebServlet("/ServerletAgregarUsuario")
public class ServerletAgregarUsuario extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ServerletAgregarUsuario() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DateFormat format = new SimpleDateFormat("d/M/y");
Date fechaNac;
HttpSession session = request.getSession();
try {
//limpio cosos de sesión...
if (session.getAttribute("errorCU") != null){
session.removeAttribute("errorCU");
}
if (session.getAttribute("usuarioCreado") != null){
session.removeAttribute("usuarioCreado");
}
//creo un modelo de usario para usar el controlador...
fechaNac = format.parse(request.getParameter("fechaNac"));
ModeloUsuario u = new ModeloUsuario(1,
request.getParameter("usuario"),
request.getParameter("pass"),
true,
request.getParameter("nombre"),
request.getParameter("apellido"),
request.getParameter("dni"),
fechaNac);
ControladorUsuario c = new ControladorUsuario(u);
c.Agregar();
session.setAttribute("usuarioCreado", "true");
} catch (ParseException e) {
// TODO Auto-generated catch block
session.setAttribute("errorCU", "true");
e.printStackTrace();
}
RequestDispatcher rd = request.getRequestDispatcher("/admin/clientes/crear.jsp");
rd.forward(request, response);
}
}
| unlicense |
matco/hotspot-api | src/test/java/name/matco/hotspot/repositories/RepositoryTest.java | 1900 | package name.matco.hotspot.repositories;
import java.sql.SQLException;
import java.util.UUID;
import jakarta.inject.Singleton;
import org.glassfish.hk2.api.DynamicConfiguration;
import org.glassfish.hk2.api.DynamicConfigurationService;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.api.ServiceLocatorFactory;
import org.glassfish.hk2.utilities.BuilderHelper;
import org.junit.jupiter.api.BeforeAll;
import name.matco.hotspot.helpers.InitDatabase;
import name.matco.hotspot.repositories.db.SpotRepositoryDb;
import name.matco.hotspot.repositories.db.StashRepositoryDb;
import name.matco.hotspot.repositories.db.UserRepositoryDb;
import name.matco.hotspot.services.datasource.ConnectionProvider;
import name.matco.hotspot.services.datasource.mocks.ConnectionProviderMock;
public class RepositoryTest {
protected static ServiceLocator LOCATOR;
@BeforeAll
public static void init() throws SQLException {
//initialize dependency injection
final ServiceLocatorFactory factory = ServiceLocatorFactory.getInstance();
LOCATOR = factory.create(UUID.randomUUID().toString());
final DynamicConfigurationService dcs = LOCATOR.getService(DynamicConfigurationService.class);
final DynamicConfiguration config = dcs.createDynamicConfiguration();
config.bind(BuilderHelper.link(ConnectionProviderMock.class).to(ConnectionProvider.class).in(Singleton.class).build());
config.bind(BuilderHelper.link(UserRepositoryDb.class).to(UserRepository.class).in(Singleton.class).build());
config.bind(BuilderHelper.link(StashRepositoryDb.class).to(StashRepository.class).in(Singleton.class).build());
config.bind(BuilderHelper.link(SpotRepositoryDb.class).to(SpotRepository.class).in(Singleton.class).build());
config.commit();
//initialize database
InitDatabase.createDatabase(LOCATOR.getService(ConnectionProvider.class));
}
}
| unlicense |
m4l1c3/HTMLContentCreator | src/main/java/htmlcontentcreator/ITemplateWriter.java | 2121 | package htmlcontentcreator;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ITemplateWriter implements ITemplateProcessor {
String templateSuffix = "Template";
String templateExtension = ".html";
Path htmlTemplatePath;
public ITemplateWriter() {
}
public void writeTemplates(ContentFormatPlugin contentFormatplugin) {
if (contentFormatplugin.cmsBlocks.size() > 0) {
for (CMSBlock currentCMSBlock : contentFormatplugin.cmsBlocks) {
this.htmlTemplatePath = Paths.get(contentFormatplugin.currentWorkingDirectory, currentCMSBlock.Name +
this.templateSuffix + this.templateExtension);
try {
byte[] encoded = Files.readAllBytes(this.htmlTemplatePath);
String htmlTemplate = new String(encoded, contentFormatplugin.contentFormat.getOutputType());
for (ContentPieces currentContentPiece : currentCMSBlock.Language.ContentPieces) {
htmlTemplate = htmlTemplate.replace("%%" + currentContentPiece.SectionName + "%%",
currentContentPiece.SectionContent);
}
htmlTemplate = htmlTemplate.replaceAll("%%language-code%%",
currentCMSBlock.Language.Name);
PrintWriter writer =
new PrintWriter(contentFormatplugin.currentWorkingDirectory + currentCMSBlock.Language.Name
+ "-" + currentCMSBlock.Name + this.templateExtension,
contentFormatplugin.contentFormat.getOutputType());
writer.write(htmlTemplate);
writer.close();
} catch (FileNotFoundException exception) {
exception.printStackTrace();
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
}
}
| unlicense |
D-Inc/EnderIO | src/main/java/crazypants/enderio/render/pipeline/BlockStateWrapperBase.java | 14177 | package crazypants.enderio.render.pipeline;
import java.util.Collection;
import java.util.EnumMap;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.commons.lang3.tuple.Pair;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.ImmutableMap;
import crazypants.enderio.Log;
import crazypants.enderio.paint.IPaintable.IBlockPaintableBlock;
import crazypants.enderio.paint.IPaintable.IWrenchHideablePaint;
import crazypants.enderio.paint.YetaUtil;
import crazypants.enderio.paint.YetaUtil.YetaDisplayMode;
import crazypants.enderio.paint.render.PaintedBlockAccessWrapper;
import crazypants.enderio.render.IBlockStateWrapper;
import crazypants.enderio.render.IRenderMapper;
import crazypants.enderio.render.model.CollectedQuadBakedBlockModel;
import crazypants.enderio.render.property.IOMode.EnumIOMode;
import crazypants.enderio.render.util.QuadCollector;
import crazypants.util.Profiler;
import net.minecraft.block.Block;
import net.minecraft.block.material.EnumPushReaction;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.Mirror;
import net.minecraft.util.Rotation;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.ChunkCache;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk.EnumCreateEntityType;
import net.minecraftforge.client.MinecraftForgeClient;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class BlockStateWrapperBase extends CacheKey implements IBlockStateWrapper {
private final static Cache<Pair<Block, Long>, QuadCollector> cache = CacheBuilder.newBuilder().maximumSize(500).<Pair<Block, Long>, QuadCollector> build();
protected final @Nonnull Block block;
protected final @Nonnull IBlockState state;
protected final @Nonnull IBlockAccess world;
protected final @Nonnull BlockPos pos;
protected final @Nonnull IRenderMapper.IBlockRenderMapper renderMapper;
protected boolean doCaching = false;
protected IBakedModel model = null;
@Nonnull
private final YetaDisplayMode yetaDisplayMode = YetaUtil.getYetaDisplayMode();
public BlockStateWrapperBase(IBlockState state, IBlockAccess world, BlockPos pos, IRenderMapper.IBlockRenderMapper renderMapper) {
this.state = notnull(state);
this.block = notnull(state.getBlock());
this.world = notnull(world);
this.pos = notnull(pos);
this.renderMapper = renderMapper != null ? renderMapper : nullRenderMapper;
}
@Nonnull
private static <X> X notnull(@Nullable X x) {
if (x == null) {
throw new NullPointerException();
}
return x;
}
protected BlockStateWrapperBase(BlockStateWrapperBase parent, IBlockState state) {
this.block = parent.block;
this.state = notnull(state);
this.world = parent.world;
this.pos = parent.pos;
this.renderMapper = parent.renderMapper;
this.doCaching = parent.doCaching;
this.model = parent.model;
}
protected void putIntoCache(QuadCollector quads) {
cache.put(Pair.of(block, getCacheKey()), quads);
}
protected QuadCollector getFromCache() {
return cache.getIfPresent(Pair.of(block, getCacheKey()));
}
public static void invalidate() {
cache.invalidateAll();
}
@Override
public Collection<IProperty<?>> getPropertyNames() {
return state.getPropertyNames();
}
@Override
public <T extends Comparable<T>> T getValue(IProperty<T> property) {
return state.getValue(property);
}
@Override
public <T extends Comparable<T>, V extends T> IBlockState withProperty(IProperty<T> property, V value) {
return new BlockStateWrapperBase(this, state.withProperty(property, value));
}
@Override
public <T extends Comparable<T>> IBlockState cycleProperty(IProperty<T> property) {
return new BlockStateWrapperBase(this, state.cycleProperty(property));
}
@Override
public ImmutableMap<IProperty<?>, Comparable<?>> getProperties() {
return state.getProperties();
}
@Override
public @Nonnull Block getBlock() {
return block;
}
@Override
public @Nonnull BlockPos getPos() {
return pos;
}
@Override
public @Nullable TileEntity getTileEntity() {
if (world instanceof ChunkCache) {
return ((ChunkCache) world).func_190300_a(pos, EnumCreateEntityType.CHECK);
}
return world.getTileEntity(pos);
}
@Override
public @Nonnull IBlockAccess getWorld() {
return world;
}
@Override
public @Nonnull IBlockState getState() {
return state;
}
@Override
public @Nonnull IBlockStateWrapper addCacheKey(@Nullable Object addlCacheKey) {
super.addCacheKey(addlCacheKey);
doCaching = !(world instanceof PaintedBlockAccessWrapper);
return this;
}
@Override
public void bakeModel() {
long start = Profiler.instance.start();
QuadCollector quads = null;
QuadCollector overlayQuads = null;
@Nonnull
QuadCollector paintQuads = new QuadCollector();
boolean hasPaintRendered = false;
String cacheResult;
if (block instanceof IBlockPaintableBlock && (!(block instanceof IWrenchHideablePaint) || !getYetaDisplayMode().isHideFacades())) {
hasPaintRendered = PaintWrangler.wrangleBakedModel(world, pos, ((IBlockPaintableBlock) block).getPaintSource(state, world, pos), paintQuads);
}
boolean fromCache = doCaching && MinecraftForgeClient.getRenderLayer() != null;
if (!hasPaintRendered || renderMapper instanceof IRenderMapper.IBlockRenderMapper.IRenderLayerAware.IPaintAware) {
if (fromCache) {
quads = getFromCache();
cacheResult = quads == null ? "miss" : "hit";
} else {
cacheResult = "not cachable";
}
if (quads == null) {
quads = new QuadCollector();
bakeBlockLayer(quads);
if (fromCache) {
putIntoCache(quads);
}
}
} else {
cacheResult = "paint only";
}
overlayQuads = OverlayHolder.getOverlay(renderMapper.mapOverlayLayer(this, world, pos, hasPaintRendered));
model = new CollectedQuadBakedBlockModel(paintQuads.combine(overlayQuads).combine(quads));
Profiler.instance.stop(start, state.getBlock().getLocalizedName() + " (bake, cache=" + cacheResult + ")");
}
private static final BlockRenderLayer BREAKING = null;
protected void bakeBlockLayer(QuadCollector quads) {
if (renderMapper == nullRenderMapper) {
IBakedModel missingModel = Minecraft.getMinecraft().getBlockRendererDispatcher().getBlockModelShapes().getModelManager().getMissingModel();
for (BlockRenderLayer layer : quads.getBlockLayers()) {
quads.addUnfriendlybakedModel(layer, missingModel, state, 0);
}
} else if (renderMapper instanceof IRenderMapper.IBlockRenderMapper.IRenderLayerAware) {
for (BlockRenderLayer layer : quads.getBlockLayers()) {
quads.addFriendlyBlockStates(layer, renderMapper.mapBlockRender(this, world, pos, layer, quads));
}
} else {
BlockRenderLayer layer = block.getBlockLayer();
quads.addFriendlyBlockStates(layer, renderMapper.mapBlockRender(this, world, pos, layer, quads));
quads.addFriendlyBlockStates(BREAKING, renderMapper.mapBlockRender(this, world, pos, BREAKING, quads));
}
}
public IBakedModel getModel() {
if (model == null) {
bakeModel();
if (model != null) {
Log.warn(block + " doesn't bake its model!");
} else {
Log.warn(block + "'s model won't bake!");
return Minecraft.getMinecraft().getBlockRendererDispatcher().getBlockModelShapes().getModelManager().getMissingModel();
}
}
return model;
}
private static final @Nonnull IRenderMapper.IBlockRenderMapper nullRenderMapper = new IRenderMapper.IBlockRenderMapper() {
@Override
@SideOnly(Side.CLIENT)
public EnumMap<EnumFacing, EnumIOMode> mapOverlayLayer(IBlockStateWrapper state, IBlockAccess world, BlockPos pos, boolean isPainted) {
return null;
}
@Override
@SideOnly(Side.CLIENT)
public List<IBlockState> mapBlockRender(IBlockStateWrapper state, IBlockAccess world, BlockPos pos, BlockRenderLayer blockLayer,
QuadCollector quadCollector) {
return null;
}
};
// And here comes the stupid "we pipe most calls to Block though BlockState" stuff
@Override
public Material getMaterial() {
return state.getMaterial();
}
@Override
public boolean isFullBlock() {
return state.isFullBlock();
}
@SuppressWarnings("deprecation")
@Override
public int getLightOpacity() {
return state.getLightOpacity();
}
@Override
public int getLightOpacity(IBlockAccess world1, BlockPos pos1) {
return state.getLightOpacity(world1, pos1);
}
@SuppressWarnings("deprecation")
@Override
public int getLightValue() {
return state.getLightValue();
}
@Override
public int getLightValue(IBlockAccess world1, BlockPos pos1) {
return state.getLightValue(world1, pos1);
}
@Override
public boolean isTranslucent() {
return state.isTranslucent();
}
@Override
public boolean useNeighborBrightness() {
return state.useNeighborBrightness();
}
@Override
public MapColor getMapColor() {
return state.getMapColor();
}
@Override
public IBlockState withRotation(Rotation rot) {
return state.withRotation(rot);
}
@Override
public IBlockState withMirror(Mirror mirrorIn) {
return state.withMirror(mirrorIn);
}
@Override
public boolean isFullCube() {
return state.isFullCube();
}
@Override
public EnumBlockRenderType getRenderType() {
return state.getRenderType();
}
@Override
public int getPackedLightmapCoords(IBlockAccess source, BlockPos pos1) {
return state.getPackedLightmapCoords(source, pos1);
}
@Override
public float getAmbientOcclusionLightValue() {
return state.getAmbientOcclusionLightValue();
}
@Override
public boolean isBlockNormalCube() {
return state.isBlockNormalCube();
}
@Override
public boolean isNormalCube() {
return state.isNormalCube();
}
@Override
public boolean canProvidePower() {
return state.canProvidePower();
}
@Override
public int getWeakPower(IBlockAccess blockAccess, BlockPos pos1, EnumFacing side) {
return state.getWeakPower(blockAccess, pos1, side);
}
@Override
public boolean hasComparatorInputOverride() {
return state.hasComparatorInputOverride();
}
@Override
public int getComparatorInputOverride(World worldIn, BlockPos pos1) {
return state.getComparatorInputOverride(worldIn, pos1);
}
@Override
public float getBlockHardness(World worldIn, BlockPos pos1) {
return state.getBlockHardness(worldIn, pos1);
}
@Override
public float getPlayerRelativeBlockHardness(EntityPlayer player, World worldIn, BlockPos pos1) {
return state.getPlayerRelativeBlockHardness(player, worldIn, pos1);
}
@Override
public int getStrongPower(IBlockAccess blockAccess, BlockPos pos1, EnumFacing side) {
return state.getStrongPower(blockAccess, pos1, side);
}
@Override
public EnumPushReaction getMobilityFlag() {
return state.getMobilityFlag();
}
@Override
public IBlockState getActualState(IBlockAccess blockAccess, BlockPos pos1) {
return state.getActualState(blockAccess, pos1);
}
@Override
public AxisAlignedBB getCollisionBoundingBox(World worldIn, BlockPos pos1) {
return state.getCollisionBoundingBox(worldIn, pos1);
}
@Override
public boolean shouldSideBeRendered(IBlockAccess blockAccess, BlockPos pos1, EnumFacing facing) {
return state.shouldSideBeRendered(blockAccess, pos1, facing);
}
@Override
public boolean isOpaqueCube() {
return state.isOpaqueCube();
}
@Override
public AxisAlignedBB getSelectedBoundingBox(World worldIn, BlockPos pos1) {
return state.getSelectedBoundingBox(worldIn, pos1);
}
@Override
public void addCollisionBoxToList(World worldIn, BlockPos pos1, AxisAlignedBB p_185908_3_, List<AxisAlignedBB> p_185908_4_, @Nullable Entity p_185908_5_) {
state.addCollisionBoxToList(worldIn, pos1, p_185908_3_, p_185908_4_, p_185908_5_);
}
@Override
public AxisAlignedBB getBoundingBox(IBlockAccess blockAccess, BlockPos pos1) {
return state.getBoundingBox(blockAccess, pos1);
}
@Override
public RayTraceResult collisionRayTrace(World worldIn, BlockPos pos1, Vec3d start, Vec3d end) {
return state.collisionRayTrace(worldIn, pos1, start, end);
}
@SuppressWarnings("deprecation")
@Override
public boolean isFullyOpaque() {
return state.isFullyOpaque();
}
@Override
public boolean doesSideBlockRendering(IBlockAccess world1, BlockPos pos1, EnumFacing side) {
return state.doesSideBlockRendering(world1, pos1, side);
}
@Override
public boolean isSideSolid(IBlockAccess world1, BlockPos pos1, EnumFacing side) {
return state.isSideSolid(world1, pos1, side);
}
@Override
public boolean onBlockEventReceived(World worldIn, BlockPos pos1, int id, int param) {
return state.onBlockEventReceived(worldIn, pos1, id, param);
}
@Override
public void neighborChanged(World worldIn, BlockPos pos1, Block p_189546_3_) {
state.neighborChanged(worldIn, pos1, p_189546_3_);
}
@Override
public boolean func_189884_a(Entity p_189884_1_) {
return state.func_189884_a(p_189884_1_);
}
@Override
public YetaDisplayMode getYetaDisplayMode() {
return yetaDisplayMode;
}
}
| unlicense |
clilystudio/NetBook | allsrc/com/ushaqi/zhuishushenqi/ui/game/z(1).java | 598 | package com.ushaqi.zhuishushenqi.ui.game;
import android.view.View;
import android.view.View.OnClickListener;
import com.ushaqi.zhuishushenqi.model.GameGift;
final class z
implements View.OnClickListener
{
z(y paramy, GameGift paramGameGift, String paramString)
{
}
public final void onClick(View paramView)
{
GameGiftListActivity.a(this.c.a, this.a);
GameGiftListActivity.a(this.c.a, this.b);
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.ushaqi.zhuishushenqi.ui.game.z
* JD-Core Version: 0.6.0
*/ | unlicense |
devacfr/spring-restlet | restlet-core/src/main/java/com/pmi/restlet/utils/StrUtils.java | 1935 | package com.pmi.restlet.utils;
import org.apache.commons.lang.StringUtils;
public final class StrUtils {
private StrUtils() {
}
/*
* public static boolean startsWith (String str1, String str2) { return
* startsWith (str1, str2, false); }
*
*
* public static boolean startsWith (String str1, String str2, boolean
* ignore_case) { int l2 = str2.length(); if (l2 == 0) return true;
*
* int l1 = str1.length(); if (l2 > l1) return false;
*
* return (0 == String.Compare (str1, 0, str2, 0, l2, ignore_case)); }
*
* public static boolean endsWith (String str1, String str2) { return
* endsWith (str1, str2, false); }
*
* public static boolean endsWith (String str1, String str2, boolean
* ignore_case) { int l2 = str2.length(); if (l2 == 0) return true;
*
* int l1 = str1.length(); if (l2 > l1) return false;
*
* return (0 == String.Compare (str1, l1 - l2, str2, 0, l2, ignore_case)); }
*
*/
public static String escapeQuotesAndBackslashes(String attributeValue) {
StringBuilder sb = null;
for (int i = 0; i < attributeValue.length(); i++) {
char ch = attributeValue.charAt(i);
if (ch == '\'' || ch == '"' || ch == '\\') {
if (sb == null) {
sb = new StringBuilder();
sb.append(attributeValue.substring(0, i));
}
sb.append('\\');
sb.append(ch);
} else {
if (sb != null) {
sb.append(ch);
}
}
}
if (sb != null) {
return sb.toString();
}
return attributeValue;
}
public static boolean isNullOrEmpty(String value) {
return !StringUtils.isNotEmpty(value);
}
} | unlicense |
FabricioPP/MaisUma | app/src/main/java/br/com/maisuma/mais_uma/BO/LoginBO.java | 5606 | package br.com.maisuma.mais_uma.BO;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.WindowManager;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import br.com.maisuma.mais_uma.Constantes.Constantes;
import br.com.maisuma.mais_uma.EstabelecimentosActivity;
import br.com.maisuma.mais_uma.Util.Util;
import br.com.maisuma.mais_uma.validation.Login;
import cz.msebera.android.httpclient.Header;
/**
* Created by Fabio on 29/03/2016.
*/
public class LoginBO {
public boolean validarCamposLogin(final Login login) {
final boolean[] resultado = {true};
if (login.getLogin() == null || "".equals(login.getLogin())) {
login.getLytNome().setError("Campo obrigatório!");
resultado[0] = false;
} else {
login.getLytNome().setErrorEnabled(false);
}
if (resultado[0]) {
resultado[0] = true;
String expression = "^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = login.getLogin();
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (!matcher.matches()) {
login.getLytNome().setError("E-mail inválido!");
resultado[0] = false;
} else {
login.getLytNome().setErrorEnabled(false);
}
}
if (login.getSenha() == null || "".equals(login.getSenha())) {
login.getLytSenha().setError("Campo obrigatório!");
resultado[0] = false;
} else {
login.getLytSenha().setErrorEnabled(false);
}
if (login.getSenha().length() < 5) {
login.getLytSenha().setError("Senha muito curta!");
resultado[0] = false;
}else {
login.getLytSenha().setErrorEnabled(false);
}
if (resultado[0]) {
RequestParams params = new RequestParams();
params.put("email", login.getLogin());
params.put("senha", login.getSenha());
new AsyncHttpClient().post(Constantes.URL_WS_BASE + "user/logar", params, new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
//Toast.makeText(login.getActivity(), "Erro ao conectar com o servidor!", Toast.LENGTH_LONG).show();
final AlertDialog alertDialog = new AlertDialog.Builder(login.getActivity()).create();
alertDialog.setTitle("Erro");
alertDialog.setMessage("Erro ao conectar com o servidor");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL, "Tentar novamente", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
validarCamposLogin(login);
alertDialog.dismiss();
}
});
WindowManager.LayoutParams params = new WindowManager.LayoutParams();
params.copyFrom(alertDialog.getWindow().getAttributes());
params.width = WindowManager.LayoutParams.MATCH_PARENT;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
alertDialog.show();
alertDialog.getWindow().setAttributes(params);
login.getLytLoading().setVisibility(View.GONE);
resultado[0] = false;
}
@Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
if (Boolean.valueOf(responseString)){
SharedPreferences.Editor editor = login.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE).edit();
editor.putString("login", login.getLogin());
editor.putString("senha", login.getSenha());
editor.commit();
Intent i = new Intent(login.getActivity(), EstabelecimentosActivity.class);
login.getActivity().startActivity(i);
login.getActivity().finish();
}else {
//Toast.makeText(login.getActivity(), "Login ou senha inválidos", Toast.LENGTH_LONG).show();
Util.showMsgAlertContaAtualizaDashBoard(login.getActivity(), "Erro", "Login ou senha inválidos");
resultado[0] = false;
login.getLytLoading().setVisibility(View.GONE);
}
}
});
}else {
resultado[0] = false;
}
return resultado[0];
}
}
| unlicense |
googleapis/java-compute | proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/FirewallList.java | 63279 | /*
* Copyright 2020 Google LLC
*
* 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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto
package com.google.cloud.compute.v1;
/**
*
*
* <pre>
* Contains a list of firewalls.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.FirewallList}
*/
public final class FirewallList extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.compute.v1.FirewallList)
FirewallListOrBuilder {
private static final long serialVersionUID = 0L;
// Use FirewallList.newBuilder() to construct.
private FirewallList(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private FirewallList() {
id_ = "";
items_ = java.util.Collections.emptyList();
kind_ = "";
nextPageToken_ = "";
selfLink_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new FirewallList();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private FirewallList(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 26842:
{
java.lang.String s = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
id_ = s;
break;
}
case 26336418:
{
java.lang.String s = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
kind_ = s;
break;
}
case 405634274:
{
com.google.cloud.compute.v1.Warning.Builder subBuilder = null;
if (((bitField0_ & 0x00000010) != 0)) {
subBuilder = warning_.toBuilder();
}
warning_ =
input.readMessage(
com.google.cloud.compute.v1.Warning.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(warning_);
warning_ = subBuilder.buildPartial();
}
bitField0_ |= 0x00000010;
break;
}
case 638380202:
{
java.lang.String s = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
nextPageToken_ = s;
break;
}
case 804208130:
{
if (!((mutable_bitField0_ & 0x00000002) != 0)) {
items_ = new java.util.ArrayList<com.google.cloud.compute.v1.Firewall>();
mutable_bitField0_ |= 0x00000002;
}
items_.add(
input.readMessage(
com.google.cloud.compute.v1.Firewall.parser(), extensionRegistry));
break;
}
case -645248918:
{
java.lang.String s = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
selfLink_ = s;
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000002) != 0)) {
items_ = java.util.Collections.unmodifiableList(items_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_FirewallList_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_FirewallList_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.FirewallList.class,
com.google.cloud.compute.v1.FirewallList.Builder.class);
}
private int bitField0_;
public static final int ID_FIELD_NUMBER = 3355;
private volatile java.lang.Object id_;
/**
*
*
* <pre>
* [Output Only] Unique identifier for the resource; defined by the server.
* </pre>
*
* <code>optional string id = 3355;</code>
*
* @return Whether the id field is set.
*/
@java.lang.Override
public boolean hasId() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* [Output Only] Unique identifier for the resource; defined by the server.
* </pre>
*
* <code>optional string id = 3355;</code>
*
* @return The id.
*/
@java.lang.Override
public java.lang.String getId() {
java.lang.Object ref = id_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
id_ = s;
return s;
}
}
/**
*
*
* <pre>
* [Output Only] Unique identifier for the resource; defined by the server.
* </pre>
*
* <code>optional string id = 3355;</code>
*
* @return The bytes for id.
*/
@java.lang.Override
public com.google.protobuf.ByteString getIdBytes() {
java.lang.Object ref = id_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
id_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ITEMS_FIELD_NUMBER = 100526016;
private java.util.List<com.google.cloud.compute.v1.Firewall> items_;
/**
*
*
* <pre>
* A list of Firewall resources.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Firewall items = 100526016;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.compute.v1.Firewall> getItemsList() {
return items_;
}
/**
*
*
* <pre>
* A list of Firewall resources.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Firewall items = 100526016;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.compute.v1.FirewallOrBuilder>
getItemsOrBuilderList() {
return items_;
}
/**
*
*
* <pre>
* A list of Firewall resources.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Firewall items = 100526016;</code>
*/
@java.lang.Override
public int getItemsCount() {
return items_.size();
}
/**
*
*
* <pre>
* A list of Firewall resources.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Firewall items = 100526016;</code>
*/
@java.lang.Override
public com.google.cloud.compute.v1.Firewall getItems(int index) {
return items_.get(index);
}
/**
*
*
* <pre>
* A list of Firewall resources.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Firewall items = 100526016;</code>
*/
@java.lang.Override
public com.google.cloud.compute.v1.FirewallOrBuilder getItemsOrBuilder(int index) {
return items_.get(index);
}
public static final int KIND_FIELD_NUMBER = 3292052;
private volatile java.lang.Object kind_;
/**
*
*
* <pre>
* [Output Only] Type of resource. Always compute#firewallList for lists of firewalls.
* </pre>
*
* <code>optional string kind = 3292052;</code>
*
* @return Whether the kind field is set.
*/
@java.lang.Override
public boolean hasKind() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* [Output Only] Type of resource. Always compute#firewallList for lists of firewalls.
* </pre>
*
* <code>optional string kind = 3292052;</code>
*
* @return The kind.
*/
@java.lang.Override
public java.lang.String getKind() {
java.lang.Object ref = kind_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
kind_ = s;
return s;
}
}
/**
*
*
* <pre>
* [Output Only] Type of resource. Always compute#firewallList for lists of firewalls.
* </pre>
*
* <code>optional string kind = 3292052;</code>
*
* @return The bytes for kind.
*/
@java.lang.Override
public com.google.protobuf.ByteString getKindBytes() {
java.lang.Object ref = kind_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
kind_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 79797525;
private volatile java.lang.Object nextPageToken_;
/**
*
*
* <pre>
* [Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results.
* </pre>
*
* <code>optional string next_page_token = 79797525;</code>
*
* @return Whether the nextPageToken field is set.
*/
@java.lang.Override
public boolean hasNextPageToken() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* [Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results.
* </pre>
*
* <code>optional string next_page_token = 79797525;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* [Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results.
* </pre>
*
* <code>optional string next_page_token = 79797525;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int SELF_LINK_FIELD_NUMBER = 456214797;
private volatile java.lang.Object selfLink_;
/**
*
*
* <pre>
* [Output Only] Server-defined URL for this resource.
* </pre>
*
* <code>optional string self_link = 456214797;</code>
*
* @return Whether the selfLink field is set.
*/
@java.lang.Override
public boolean hasSelfLink() {
return ((bitField0_ & 0x00000008) != 0);
}
/**
*
*
* <pre>
* [Output Only] Server-defined URL for this resource.
* </pre>
*
* <code>optional string self_link = 456214797;</code>
*
* @return The selfLink.
*/
@java.lang.Override
public java.lang.String getSelfLink() {
java.lang.Object ref = selfLink_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
selfLink_ = s;
return s;
}
}
/**
*
*
* <pre>
* [Output Only] Server-defined URL for this resource.
* </pre>
*
* <code>optional string self_link = 456214797;</code>
*
* @return The bytes for selfLink.
*/
@java.lang.Override
public com.google.protobuf.ByteString getSelfLinkBytes() {
java.lang.Object ref = selfLink_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
selfLink_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int WARNING_FIELD_NUMBER = 50704284;
private com.google.cloud.compute.v1.Warning warning_;
/**
*
*
* <pre>
* [Output Only] Informational warning message.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*
* @return Whether the warning field is set.
*/
@java.lang.Override
public boolean hasWarning() {
return ((bitField0_ & 0x00000010) != 0);
}
/**
*
*
* <pre>
* [Output Only] Informational warning message.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*
* @return The warning.
*/
@java.lang.Override
public com.google.cloud.compute.v1.Warning getWarning() {
return warning_ == null ? com.google.cloud.compute.v1.Warning.getDefaultInstance() : warning_;
}
/**
*
*
* <pre>
* [Output Only] Informational warning message.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
@java.lang.Override
public com.google.cloud.compute.v1.WarningOrBuilder getWarningOrBuilder() {
return warning_ == null ? com.google.cloud.compute.v1.Warning.getDefaultInstance() : warning_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3355, id_);
}
if (((bitField0_ & 0x00000002) != 0)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3292052, kind_);
}
if (((bitField0_ & 0x00000010) != 0)) {
output.writeMessage(50704284, getWarning());
}
if (((bitField0_ & 0x00000004) != 0)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 79797525, nextPageToken_);
}
for (int i = 0; i < items_.size(); i++) {
output.writeMessage(100526016, items_.get(i));
}
if (((bitField0_ & 0x00000008) != 0)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 456214797, selfLink_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3355, id_);
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3292052, kind_);
}
if (((bitField0_ & 0x00000010) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(50704284, getWarning());
}
if (((bitField0_ & 0x00000004) != 0)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(79797525, nextPageToken_);
}
for (int i = 0; i < items_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(100526016, items_.get(i));
}
if (((bitField0_ & 0x00000008) != 0)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(456214797, selfLink_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.compute.v1.FirewallList)) {
return super.equals(obj);
}
com.google.cloud.compute.v1.FirewallList other = (com.google.cloud.compute.v1.FirewallList) obj;
if (hasId() != other.hasId()) return false;
if (hasId()) {
if (!getId().equals(other.getId())) return false;
}
if (!getItemsList().equals(other.getItemsList())) return false;
if (hasKind() != other.hasKind()) return false;
if (hasKind()) {
if (!getKind().equals(other.getKind())) return false;
}
if (hasNextPageToken() != other.hasNextPageToken()) return false;
if (hasNextPageToken()) {
if (!getNextPageToken().equals(other.getNextPageToken())) return false;
}
if (hasSelfLink() != other.hasSelfLink()) return false;
if (hasSelfLink()) {
if (!getSelfLink().equals(other.getSelfLink())) return false;
}
if (hasWarning() != other.hasWarning()) return false;
if (hasWarning()) {
if (!getWarning().equals(other.getWarning())) return false;
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasId()) {
hash = (37 * hash) + ID_FIELD_NUMBER;
hash = (53 * hash) + getId().hashCode();
}
if (getItemsCount() > 0) {
hash = (37 * hash) + ITEMS_FIELD_NUMBER;
hash = (53 * hash) + getItemsList().hashCode();
}
if (hasKind()) {
hash = (37 * hash) + KIND_FIELD_NUMBER;
hash = (53 * hash) + getKind().hashCode();
}
if (hasNextPageToken()) {
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
}
if (hasSelfLink()) {
hash = (37 * hash) + SELF_LINK_FIELD_NUMBER;
hash = (53 * hash) + getSelfLink().hashCode();
}
if (hasWarning()) {
hash = (37 * hash) + WARNING_FIELD_NUMBER;
hash = (53 * hash) + getWarning().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.compute.v1.FirewallList parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.FirewallList parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.FirewallList parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.FirewallList parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.FirewallList parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.FirewallList parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.FirewallList parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.FirewallList parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.FirewallList parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.FirewallList parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.FirewallList parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.FirewallList parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.compute.v1.FirewallList prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Contains a list of firewalls.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.FirewallList}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.FirewallList)
com.google.cloud.compute.v1.FirewallListOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_FirewallList_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_FirewallList_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.FirewallList.class,
com.google.cloud.compute.v1.FirewallList.Builder.class);
}
// Construct using com.google.cloud.compute.v1.FirewallList.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getItemsFieldBuilder();
getWarningFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
id_ = "";
bitField0_ = (bitField0_ & ~0x00000001);
if (itemsBuilder_ == null) {
items_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000002);
} else {
itemsBuilder_.clear();
}
kind_ = "";
bitField0_ = (bitField0_ & ~0x00000004);
nextPageToken_ = "";
bitField0_ = (bitField0_ & ~0x00000008);
selfLink_ = "";
bitField0_ = (bitField0_ & ~0x00000010);
if (warningBuilder_ == null) {
warning_ = null;
} else {
warningBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000020);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_FirewallList_descriptor;
}
@java.lang.Override
public com.google.cloud.compute.v1.FirewallList getDefaultInstanceForType() {
return com.google.cloud.compute.v1.FirewallList.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.compute.v1.FirewallList build() {
com.google.cloud.compute.v1.FirewallList result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.compute.v1.FirewallList buildPartial() {
com.google.cloud.compute.v1.FirewallList result =
new com.google.cloud.compute.v1.FirewallList(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
to_bitField0_ |= 0x00000001;
}
result.id_ = id_;
if (itemsBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)) {
items_ = java.util.Collections.unmodifiableList(items_);
bitField0_ = (bitField0_ & ~0x00000002);
}
result.items_ = items_;
} else {
result.items_ = itemsBuilder_.build();
}
if (((from_bitField0_ & 0x00000004) != 0)) {
to_bitField0_ |= 0x00000002;
}
result.kind_ = kind_;
if (((from_bitField0_ & 0x00000008) != 0)) {
to_bitField0_ |= 0x00000004;
}
result.nextPageToken_ = nextPageToken_;
if (((from_bitField0_ & 0x00000010) != 0)) {
to_bitField0_ |= 0x00000008;
}
result.selfLink_ = selfLink_;
if (((from_bitField0_ & 0x00000020) != 0)) {
if (warningBuilder_ == null) {
result.warning_ = warning_;
} else {
result.warning_ = warningBuilder_.build();
}
to_bitField0_ |= 0x00000010;
}
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.compute.v1.FirewallList) {
return mergeFrom((com.google.cloud.compute.v1.FirewallList) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.compute.v1.FirewallList other) {
if (other == com.google.cloud.compute.v1.FirewallList.getDefaultInstance()) return this;
if (other.hasId()) {
bitField0_ |= 0x00000001;
id_ = other.id_;
onChanged();
}
if (itemsBuilder_ == null) {
if (!other.items_.isEmpty()) {
if (items_.isEmpty()) {
items_ = other.items_;
bitField0_ = (bitField0_ & ~0x00000002);
} else {
ensureItemsIsMutable();
items_.addAll(other.items_);
}
onChanged();
}
} else {
if (!other.items_.isEmpty()) {
if (itemsBuilder_.isEmpty()) {
itemsBuilder_.dispose();
itemsBuilder_ = null;
items_ = other.items_;
bitField0_ = (bitField0_ & ~0x00000002);
itemsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getItemsFieldBuilder()
: null;
} else {
itemsBuilder_.addAllMessages(other.items_);
}
}
}
if (other.hasKind()) {
bitField0_ |= 0x00000004;
kind_ = other.kind_;
onChanged();
}
if (other.hasNextPageToken()) {
bitField0_ |= 0x00000008;
nextPageToken_ = other.nextPageToken_;
onChanged();
}
if (other.hasSelfLink()) {
bitField0_ |= 0x00000010;
selfLink_ = other.selfLink_;
onChanged();
}
if (other.hasWarning()) {
mergeWarning(other.getWarning());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.compute.v1.FirewallList parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.cloud.compute.v1.FirewallList) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.lang.Object id_ = "";
/**
*
*
* <pre>
* [Output Only] Unique identifier for the resource; defined by the server.
* </pre>
*
* <code>optional string id = 3355;</code>
*
* @return Whether the id field is set.
*/
public boolean hasId() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* [Output Only] Unique identifier for the resource; defined by the server.
* </pre>
*
* <code>optional string id = 3355;</code>
*
* @return The id.
*/
public java.lang.String getId() {
java.lang.Object ref = id_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
id_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* [Output Only] Unique identifier for the resource; defined by the server.
* </pre>
*
* <code>optional string id = 3355;</code>
*
* @return The bytes for id.
*/
public com.google.protobuf.ByteString getIdBytes() {
java.lang.Object ref = id_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
id_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* [Output Only] Unique identifier for the resource; defined by the server.
* </pre>
*
* <code>optional string id = 3355;</code>
*
* @param value The id to set.
* @return This builder for chaining.
*/
public Builder setId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
id_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* [Output Only] Unique identifier for the resource; defined by the server.
* </pre>
*
* <code>optional string id = 3355;</code>
*
* @return This builder for chaining.
*/
public Builder clearId() {
bitField0_ = (bitField0_ & ~0x00000001);
id_ = getDefaultInstance().getId();
onChanged();
return this;
}
/**
*
*
* <pre>
* [Output Only] Unique identifier for the resource; defined by the server.
* </pre>
*
* <code>optional string id = 3355;</code>
*
* @param value The bytes for id to set.
* @return This builder for chaining.
*/
public Builder setIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
bitField0_ |= 0x00000001;
id_ = value;
onChanged();
return this;
}
private java.util.List<com.google.cloud.compute.v1.Firewall> items_ =
java.util.Collections.emptyList();
private void ensureItemsIsMutable() {
if (!((bitField0_ & 0x00000002) != 0)) {
items_ = new java.util.ArrayList<com.google.cloud.compute.v1.Firewall>(items_);
bitField0_ |= 0x00000002;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.compute.v1.Firewall,
com.google.cloud.compute.v1.Firewall.Builder,
com.google.cloud.compute.v1.FirewallOrBuilder>
itemsBuilder_;
/**
*
*
* <pre>
* A list of Firewall resources.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Firewall items = 100526016;</code>
*/
public java.util.List<com.google.cloud.compute.v1.Firewall> getItemsList() {
if (itemsBuilder_ == null) {
return java.util.Collections.unmodifiableList(items_);
} else {
return itemsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* A list of Firewall resources.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Firewall items = 100526016;</code>
*/
public int getItemsCount() {
if (itemsBuilder_ == null) {
return items_.size();
} else {
return itemsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* A list of Firewall resources.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Firewall items = 100526016;</code>
*/
public com.google.cloud.compute.v1.Firewall getItems(int index) {
if (itemsBuilder_ == null) {
return items_.get(index);
} else {
return itemsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* A list of Firewall resources.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Firewall items = 100526016;</code>
*/
public Builder setItems(int index, com.google.cloud.compute.v1.Firewall value) {
if (itemsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureItemsIsMutable();
items_.set(index, value);
onChanged();
} else {
itemsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* A list of Firewall resources.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Firewall items = 100526016;</code>
*/
public Builder setItems(
int index, com.google.cloud.compute.v1.Firewall.Builder builderForValue) {
if (itemsBuilder_ == null) {
ensureItemsIsMutable();
items_.set(index, builderForValue.build());
onChanged();
} else {
itemsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A list of Firewall resources.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Firewall items = 100526016;</code>
*/
public Builder addItems(com.google.cloud.compute.v1.Firewall value) {
if (itemsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureItemsIsMutable();
items_.add(value);
onChanged();
} else {
itemsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* A list of Firewall resources.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Firewall items = 100526016;</code>
*/
public Builder addItems(int index, com.google.cloud.compute.v1.Firewall value) {
if (itemsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureItemsIsMutable();
items_.add(index, value);
onChanged();
} else {
itemsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* A list of Firewall resources.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Firewall items = 100526016;</code>
*/
public Builder addItems(com.google.cloud.compute.v1.Firewall.Builder builderForValue) {
if (itemsBuilder_ == null) {
ensureItemsIsMutable();
items_.add(builderForValue.build());
onChanged();
} else {
itemsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A list of Firewall resources.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Firewall items = 100526016;</code>
*/
public Builder addItems(
int index, com.google.cloud.compute.v1.Firewall.Builder builderForValue) {
if (itemsBuilder_ == null) {
ensureItemsIsMutable();
items_.add(index, builderForValue.build());
onChanged();
} else {
itemsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A list of Firewall resources.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Firewall items = 100526016;</code>
*/
public Builder addAllItems(
java.lang.Iterable<? extends com.google.cloud.compute.v1.Firewall> values) {
if (itemsBuilder_ == null) {
ensureItemsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, items_);
onChanged();
} else {
itemsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* A list of Firewall resources.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Firewall items = 100526016;</code>
*/
public Builder clearItems() {
if (itemsBuilder_ == null) {
items_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
} else {
itemsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* A list of Firewall resources.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Firewall items = 100526016;</code>
*/
public Builder removeItems(int index) {
if (itemsBuilder_ == null) {
ensureItemsIsMutable();
items_.remove(index);
onChanged();
} else {
itemsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* A list of Firewall resources.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Firewall items = 100526016;</code>
*/
public com.google.cloud.compute.v1.Firewall.Builder getItemsBuilder(int index) {
return getItemsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* A list of Firewall resources.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Firewall items = 100526016;</code>
*/
public com.google.cloud.compute.v1.FirewallOrBuilder getItemsOrBuilder(int index) {
if (itemsBuilder_ == null) {
return items_.get(index);
} else {
return itemsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* A list of Firewall resources.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Firewall items = 100526016;</code>
*/
public java.util.List<? extends com.google.cloud.compute.v1.FirewallOrBuilder>
getItemsOrBuilderList() {
if (itemsBuilder_ != null) {
return itemsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(items_);
}
}
/**
*
*
* <pre>
* A list of Firewall resources.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Firewall items = 100526016;</code>
*/
public com.google.cloud.compute.v1.Firewall.Builder addItemsBuilder() {
return getItemsFieldBuilder()
.addBuilder(com.google.cloud.compute.v1.Firewall.getDefaultInstance());
}
/**
*
*
* <pre>
* A list of Firewall resources.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Firewall items = 100526016;</code>
*/
public com.google.cloud.compute.v1.Firewall.Builder addItemsBuilder(int index) {
return getItemsFieldBuilder()
.addBuilder(index, com.google.cloud.compute.v1.Firewall.getDefaultInstance());
}
/**
*
*
* <pre>
* A list of Firewall resources.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Firewall items = 100526016;</code>
*/
public java.util.List<com.google.cloud.compute.v1.Firewall.Builder> getItemsBuilderList() {
return getItemsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.compute.v1.Firewall,
com.google.cloud.compute.v1.Firewall.Builder,
com.google.cloud.compute.v1.FirewallOrBuilder>
getItemsFieldBuilder() {
if (itemsBuilder_ == null) {
itemsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.compute.v1.Firewall,
com.google.cloud.compute.v1.Firewall.Builder,
com.google.cloud.compute.v1.FirewallOrBuilder>(
items_, ((bitField0_ & 0x00000002) != 0), getParentForChildren(), isClean());
items_ = null;
}
return itemsBuilder_;
}
private java.lang.Object kind_ = "";
/**
*
*
* <pre>
* [Output Only] Type of resource. Always compute#firewallList for lists of firewalls.
* </pre>
*
* <code>optional string kind = 3292052;</code>
*
* @return Whether the kind field is set.
*/
public boolean hasKind() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* [Output Only] Type of resource. Always compute#firewallList for lists of firewalls.
* </pre>
*
* <code>optional string kind = 3292052;</code>
*
* @return The kind.
*/
public java.lang.String getKind() {
java.lang.Object ref = kind_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
kind_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* [Output Only] Type of resource. Always compute#firewallList for lists of firewalls.
* </pre>
*
* <code>optional string kind = 3292052;</code>
*
* @return The bytes for kind.
*/
public com.google.protobuf.ByteString getKindBytes() {
java.lang.Object ref = kind_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
kind_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* [Output Only] Type of resource. Always compute#firewallList for lists of firewalls.
* </pre>
*
* <code>optional string kind = 3292052;</code>
*
* @param value The kind to set.
* @return This builder for chaining.
*/
public Builder setKind(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
kind_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* [Output Only] Type of resource. Always compute#firewallList for lists of firewalls.
* </pre>
*
* <code>optional string kind = 3292052;</code>
*
* @return This builder for chaining.
*/
public Builder clearKind() {
bitField0_ = (bitField0_ & ~0x00000004);
kind_ = getDefaultInstance().getKind();
onChanged();
return this;
}
/**
*
*
* <pre>
* [Output Only] Type of resource. Always compute#firewallList for lists of firewalls.
* </pre>
*
* <code>optional string kind = 3292052;</code>
*
* @param value The bytes for kind to set.
* @return This builder for chaining.
*/
public Builder setKindBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
bitField0_ |= 0x00000004;
kind_ = value;
onChanged();
return this;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* [Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results.
* </pre>
*
* <code>optional string next_page_token = 79797525;</code>
*
* @return Whether the nextPageToken field is set.
*/
public boolean hasNextPageToken() {
return ((bitField0_ & 0x00000008) != 0);
}
/**
*
*
* <pre>
* [Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results.
* </pre>
*
* <code>optional string next_page_token = 79797525;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* [Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results.
* </pre>
*
* <code>optional string next_page_token = 79797525;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* [Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results.
* </pre>
*
* <code>optional string next_page_token = 79797525;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000008;
nextPageToken_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* [Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results.
* </pre>
*
* <code>optional string next_page_token = 79797525;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
bitField0_ = (bitField0_ & ~0x00000008);
nextPageToken_ = getDefaultInstance().getNextPageToken();
onChanged();
return this;
}
/**
*
*
* <pre>
* [Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results.
* </pre>
*
* <code>optional string next_page_token = 79797525;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
bitField0_ |= 0x00000008;
nextPageToken_ = value;
onChanged();
return this;
}
private java.lang.Object selfLink_ = "";
/**
*
*
* <pre>
* [Output Only] Server-defined URL for this resource.
* </pre>
*
* <code>optional string self_link = 456214797;</code>
*
* @return Whether the selfLink field is set.
*/
public boolean hasSelfLink() {
return ((bitField0_ & 0x00000010) != 0);
}
/**
*
*
* <pre>
* [Output Only] Server-defined URL for this resource.
* </pre>
*
* <code>optional string self_link = 456214797;</code>
*
* @return The selfLink.
*/
public java.lang.String getSelfLink() {
java.lang.Object ref = selfLink_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
selfLink_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* [Output Only] Server-defined URL for this resource.
* </pre>
*
* <code>optional string self_link = 456214797;</code>
*
* @return The bytes for selfLink.
*/
public com.google.protobuf.ByteString getSelfLinkBytes() {
java.lang.Object ref = selfLink_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
selfLink_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* [Output Only] Server-defined URL for this resource.
* </pre>
*
* <code>optional string self_link = 456214797;</code>
*
* @param value The selfLink to set.
* @return This builder for chaining.
*/
public Builder setSelfLink(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000010;
selfLink_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* [Output Only] Server-defined URL for this resource.
* </pre>
*
* <code>optional string self_link = 456214797;</code>
*
* @return This builder for chaining.
*/
public Builder clearSelfLink() {
bitField0_ = (bitField0_ & ~0x00000010);
selfLink_ = getDefaultInstance().getSelfLink();
onChanged();
return this;
}
/**
*
*
* <pre>
* [Output Only] Server-defined URL for this resource.
* </pre>
*
* <code>optional string self_link = 456214797;</code>
*
* @param value The bytes for selfLink to set.
* @return This builder for chaining.
*/
public Builder setSelfLinkBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
bitField0_ |= 0x00000010;
selfLink_ = value;
onChanged();
return this;
}
private com.google.cloud.compute.v1.Warning warning_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.compute.v1.Warning,
com.google.cloud.compute.v1.Warning.Builder,
com.google.cloud.compute.v1.WarningOrBuilder>
warningBuilder_;
/**
*
*
* <pre>
* [Output Only] Informational warning message.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*
* @return Whether the warning field is set.
*/
public boolean hasWarning() {
return ((bitField0_ & 0x00000020) != 0);
}
/**
*
*
* <pre>
* [Output Only] Informational warning message.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*
* @return The warning.
*/
public com.google.cloud.compute.v1.Warning getWarning() {
if (warningBuilder_ == null) {
return warning_ == null
? com.google.cloud.compute.v1.Warning.getDefaultInstance()
: warning_;
} else {
return warningBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* [Output Only] Informational warning message.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
public Builder setWarning(com.google.cloud.compute.v1.Warning value) {
if (warningBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
warning_ = value;
onChanged();
} else {
warningBuilder_.setMessage(value);
}
bitField0_ |= 0x00000020;
return this;
}
/**
*
*
* <pre>
* [Output Only] Informational warning message.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
public Builder setWarning(com.google.cloud.compute.v1.Warning.Builder builderForValue) {
if (warningBuilder_ == null) {
warning_ = builderForValue.build();
onChanged();
} else {
warningBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000020;
return this;
}
/**
*
*
* <pre>
* [Output Only] Informational warning message.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
public Builder mergeWarning(com.google.cloud.compute.v1.Warning value) {
if (warningBuilder_ == null) {
if (((bitField0_ & 0x00000020) != 0)
&& warning_ != null
&& warning_ != com.google.cloud.compute.v1.Warning.getDefaultInstance()) {
warning_ =
com.google.cloud.compute.v1.Warning.newBuilder(warning_)
.mergeFrom(value)
.buildPartial();
} else {
warning_ = value;
}
onChanged();
} else {
warningBuilder_.mergeFrom(value);
}
bitField0_ |= 0x00000020;
return this;
}
/**
*
*
* <pre>
* [Output Only] Informational warning message.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
public Builder clearWarning() {
if (warningBuilder_ == null) {
warning_ = null;
onChanged();
} else {
warningBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000020);
return this;
}
/**
*
*
* <pre>
* [Output Only] Informational warning message.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
public com.google.cloud.compute.v1.Warning.Builder getWarningBuilder() {
bitField0_ |= 0x00000020;
onChanged();
return getWarningFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* [Output Only] Informational warning message.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
public com.google.cloud.compute.v1.WarningOrBuilder getWarningOrBuilder() {
if (warningBuilder_ != null) {
return warningBuilder_.getMessageOrBuilder();
} else {
return warning_ == null
? com.google.cloud.compute.v1.Warning.getDefaultInstance()
: warning_;
}
}
/**
*
*
* <pre>
* [Output Only] Informational warning message.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.compute.v1.Warning,
com.google.cloud.compute.v1.Warning.Builder,
com.google.cloud.compute.v1.WarningOrBuilder>
getWarningFieldBuilder() {
if (warningBuilder_ == null) {
warningBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.compute.v1.Warning,
com.google.cloud.compute.v1.Warning.Builder,
com.google.cloud.compute.v1.WarningOrBuilder>(
getWarning(), getParentForChildren(), isClean());
warning_ = null;
}
return warningBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.FirewallList)
}
// @@protoc_insertion_point(class_scope:google.cloud.compute.v1.FirewallList)
private static final com.google.cloud.compute.v1.FirewallList DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.compute.v1.FirewallList();
}
public static com.google.cloud.compute.v1.FirewallList getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<FirewallList> PARSER =
new com.google.protobuf.AbstractParser<FirewallList>() {
@java.lang.Override
public FirewallList parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new FirewallList(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<FirewallList> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<FirewallList> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.compute.v1.FirewallList getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| apache-2.0 |
actframework/act-morphia | src/main/java/act/db/morphia/TypeConverterFinder.java | 1685 | package act.db.morphia;
/*-
* #%L
* ACT Morphia
* %%
* Copyright (C) 2015 - 2017 ActFramework
* %%
* 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 act.app.App;
import act.app.event.SysEventId;
import act.util.SubTypeFinder;
import org.mongodb.morphia.Morphia;
import org.mongodb.morphia.converters.TypeConverter;
@SuppressWarnings("unused")
public class TypeConverterFinder extends SubTypeFinder<TypeConverter> {
private static final String SYS_CONVERTER_PKG = Morphia.class.getPackage().getName();
public TypeConverterFinder() {
super(TypeConverter.class);
}
@Override
protected void found(final Class<? extends TypeConverter> target, final App app) {
if (target.getName().startsWith(SYS_CONVERTER_PKG)) {
return;
}
app.jobManager().on(SysEventId.DEPENDENCY_INJECTOR_PROVISIONED, new Runnable() {
@Override
public void run() {
for (MorphiaService service : MorphiaService.allMorphiaServices()) {
service.mapper().getConverters().addConverter(app.getInstance(target));
}
}
});
}
}
| apache-2.0 |
VHAINNOVATIONS/AVS | ll-vistaBroker/ll-vistabroker-ejb3/src/main/java/gov/va/med/lom/vistabroker/patient/data/OrderResponse.java | 1214 | package gov.va.med.lom.vistabroker.patient.data;
import java.io.Serializable;
public class OrderResponse implements Serializable {
private String ien;
private String promptIen;
private String promptId;
private int instance;
private String iValue;
private String eValue;
public OrderResponse() {
this.iValue = "";
this.eValue = "";
this.instance = 1;
}
public String getPromptIen() {
return promptIen;
}
public void setPromptIen(String promptIen) {
this.promptIen = promptIen;
}
public String getPromptId() {
return promptId;
}
public void setPromptId(String promptId) {
this.promptId = promptId;
}
public int getInstance() {
return instance;
}
public void setInstance(int instance) {
this.instance = instance;
}
public String getiValue() {
return iValue;
}
public void setiValue(String iValue) {
this.iValue = iValue;
}
public String geteValue() {
return eValue;
}
public void seteValue(String eValue) {
this.eValue = eValue;
}
public String getIen() {
return ien;
}
public void setIen(String ien) {
this.ien = ien;
}
}
| apache-2.0 |
gmargari/apache-cassandra-1.1.0-src | src/java/org/apache/cassandra/db/ColumnSerializer.java | 4945 | package org.apache.cassandra.db;
/*
*
* 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.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.io.IColumnSerializer;
import org.apache.cassandra.io.util.FileDataInput;
import org.apache.cassandra.utils.ByteBufferUtil;
public class ColumnSerializer implements IColumnSerializer
{
private static final Logger logger = LoggerFactory.getLogger(ColumnSerializer.class);
public final static int DELETION_MASK = 0x01;
public final static int EXPIRATION_MASK = 0x02;
public final static int COUNTER_MASK = 0x04;
public final static int COUNTER_UPDATE_MASK = 0x08;
public void serialize(IColumn column, DataOutput dos)
{
assert column.name().remaining() > 0;
ByteBufferUtil.writeWithShortLength(column.name(), dos);
try
{
dos.writeByte(column.serializationFlags());
if (column instanceof CounterColumn)
{
dos.writeLong(((CounterColumn)column).timestampOfLastDelete());
}
else if (column instanceof ExpiringColumn)
{
dos.writeInt(((ExpiringColumn) column).getTimeToLive());
dos.writeInt(column.getLocalDeletionTime());
}
dos.writeLong(column.timestamp());
ByteBufferUtil.writeWithLength(column.value(), dos);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
public Column deserialize(DataInput dis) throws IOException
{
return deserialize(dis, Flag.LOCAL);
}
/*
* For counter columns, we must know when we deserialize them if what we
* deserialize comes from a remote host. If it does, then we must clear
* the delta.
*/
public Column deserialize(DataInput dis, IColumnSerializer.Flag flag) throws IOException
{
return deserialize(dis, flag, (int) (System.currentTimeMillis() / 1000));
}
public Column deserialize(DataInput dis, IColumnSerializer.Flag flag, int expireBefore) throws IOException
{
ByteBuffer name = ByteBufferUtil.readWithShortLength(dis);
if (name.remaining() <= 0)
{
String format = "invalid column name length %d%s";
String details = "";
if (dis instanceof FileDataInput)
{
FileDataInput fdis = (FileDataInput)dis;
details = String.format(" (%s, %d bytes remaining)", fdis.getPath(), fdis.bytesRemaining());
}
throw new CorruptColumnException(String.format(format, name.remaining(), details));
}
int b = dis.readUnsignedByte();
if ((b & COUNTER_MASK) != 0)
{
long timestampOfLastDelete = dis.readLong();
long ts = dis.readLong();
ByteBuffer value = ByteBufferUtil.readWithLength(dis);
return CounterColumn.create(name, value, ts, timestampOfLastDelete, flag);
}
else if ((b & EXPIRATION_MASK) != 0)
{
int ttl = dis.readInt();
int expiration = dis.readInt();
long ts = dis.readLong();
ByteBuffer value = ByteBufferUtil.readWithLength(dis);
return ExpiringColumn.create(name, value, ts, ttl, expiration, expireBefore, flag);
}
else
{
long ts = dis.readLong();
ByteBuffer value = ByteBufferUtil.readWithLength(dis);
return (b & COUNTER_UPDATE_MASK) != 0
? new CounterUpdateColumn(name, value, ts)
: ((b & DELETION_MASK) == 0
? new Column(name, value, ts)
: new DeletedColumn(name, value, ts));
}
}
public long serializedSize(IColumn object)
{
return object.serializedSize();
}
private static class CorruptColumnException extends IOException
{
public CorruptColumnException(String s)
{
super(s);
}
}
}
| apache-2.0 |
fengsmith/mybatis-3 | src/main/java/org/apache/ibatis/builder/SqlSourceBuilder.java | 5738 | /**
* Copyright 2009-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.builder;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.parsing.GenericTokenParser;
import org.apache.ibatis.parsing.TokenHandler;
import org.apache.ibatis.reflection.MetaClass;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.JdbcType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author Clinton Begin
*/
public class SqlSourceBuilder extends BaseBuilder {
private static final String parameterProperties = "javaType,jdbcType,mode,numericScale,resultMap,typeHandler,jdbcTypeName";
public SqlSourceBuilder(Configuration configuration) {
super(configuration);
}
public SqlSource parse(String originalSql, Class<?> parameterType, Map<String, Object> additionalParameters) {
ParameterMappingTokenHandler handler = new ParameterMappingTokenHandler(configuration, parameterType, additionalParameters);
GenericTokenParser parser = new GenericTokenParser("#{", "}", handler);
String sql = parser.parse(originalSql);
return new StaticSqlSource(configuration, sql, handler.getParameterMappings());
}
private static class ParameterMappingTokenHandler extends BaseBuilder implements TokenHandler {
private List<ParameterMapping> parameterMappings = new ArrayList<ParameterMapping>();
private Class<?> parameterType;
private MetaObject metaParameters;
public ParameterMappingTokenHandler(Configuration configuration, Class<?> parameterType, Map<String, Object> additionalParameters) {
super(configuration);
this.parameterType = parameterType;
this.metaParameters = configuration.newMetaObject(additionalParameters);
}
public List<ParameterMapping> getParameterMappings() {
return parameterMappings;
}
@Override
public String handleToken(String content) {
parameterMappings.add(buildParameterMapping(content));
return "?";
}
private ParameterMapping buildParameterMapping(String content) {
// 参数相关的信息 详见 ParameterExpression
Map<String, String> propertiesMap = parseParameterMapping(content);
String property = propertiesMap.get("property");
Class<?> propertyType;
if (metaParameters.hasGetter(property)) { // issue #448 get type from additional params
propertyType = metaParameters.getGetterType(property);
} else if (typeHandlerRegistry.hasTypeHandler(parameterType)) {
propertyType = parameterType;
} else if (JdbcType.CURSOR.name().equals(propertiesMap.get("jdbcType"))) {
propertyType = java.sql.ResultSet.class;
} else if (property != null) {
MetaClass metaClass = MetaClass.forClass(parameterType, configuration.getReflectorFactory());
if (metaClass.hasGetter(property)) {
propertyType = metaClass.getGetterType(property);
} else {
propertyType = Object.class;
}
} else {
propertyType = Object.class;
}
ParameterMapping.Builder builder = new ParameterMapping.Builder(configuration, property, propertyType);
Class<?> javaType = propertyType;
String typeHandlerAlias = null;
for (Map.Entry<String, String> entry : propertiesMap.entrySet()) {
String name = entry.getKey();
String value = entry.getValue();
if ("javaType".equals(name)) {
javaType = resolveClass(value);
builder.javaType(javaType);
} else if ("jdbcType".equals(name)) {
builder.jdbcType(resolveJdbcType(value));
} else if ("mode".equals(name)) {
builder.mode(resolveParameterMode(value));
} else if ("numericScale".equals(name)) {
builder.numericScale(Integer.valueOf(value));
} else if ("resultMap".equals(name)) {
builder.resultMapId(value);
} else if ("typeHandler".equals(name)) {
typeHandlerAlias = value;
} else if ("jdbcTypeName".equals(name)) {
builder.jdbcTypeName(value);
} else if ("property".equals(name)) {
// Do Nothing
} else if ("expression".equals(name)) {
throw new BuilderException("Expression based parameters are not supported yet");
} else {
throw new BuilderException("An invalid property '" + name + "' was found in mapping #{" + content + "}. Valid properties are " + parameterProperties);
}
}
if (typeHandlerAlias != null) {
builder.typeHandler(resolveTypeHandler(javaType, typeHandlerAlias));
}
return builder.build();
}
private Map<String, String> parseParameterMapping(String content) {
try {
return new ParameterExpression(content);
} catch (BuilderException ex) {
throw ex;
} catch (Exception ex) {
throw new BuilderException("Parsing error was found in mapping #{" + content + "}. Check syntax #{property|(expression), var1=value1, var2=value2, ...} ", ex);
}
}
}
}
| apache-2.0 |
ashnl007/jeesms | src/main/java/com/jeesms/manager/system/MenuManager.java | 2577 | package com.jeesms.manager.system;
import com.jeesms.annotation.Permission;
import com.jeesms.common.Constants;
import com.jeesms.dao.generic.GenericDao;
import com.jeesms.dao.system.MenuDao;
import com.jeesms.entity.system.Menu;
import com.jeesms.entity.system.User;
import com.jeesms.manager.generic.GenericManager;
import com.jeesms.persistence.Pager;
import com.jeesms.persistence.QueryFilter;
import com.jeesms.util.QueryUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* 菜单Manager
*
* @author ASHNL
* @time 2014-07-27 17:01:03
*/
@Service("menuManager")
public class MenuManager extends GenericManager<Menu> {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
@Qualifier(value = "menuDao")
private MenuDao menuDao;
@Override
public GenericDao getBaseDao() {
return menuDao;
}
@Override
@Permission(code = "menu-edit")
@CacheEvict(value = Constants.USER_MENU_CACHE, allEntries = true)
public void saveOrUpdate(Menu menu) {
super.saveOrUpdate(menu);
logger.debug("saveOrUpdate clear [{}].", Constants.USER_MENU_CACHE);
}
@Override
@Permission(code = "menu-delete")
@CacheEvict(value = {Constants.USER_OPERATION_CACHE, Constants.USER_MENU_CACHE}, allEntries = true)
public void deleteByIds(String ids) {
super.deleteByIds(ids);
logger.debug("deleteByIds clear [{}].", Constants.USER_MENU_CACHE);
}
@Cacheable(value = Constants.USER_MENU_CACHE, key = "#type.concat(#user.id)")
public List<Menu> queryUserMenusByType(String type, User user) {
if (user.isSuperAdmin()) {
return menuDao.queryMenusByType(type);
} else {
return menuDao.queryUserMenusByType(type, user.getId());
}
}
@Cacheable(value = Constants.USER_MENU_CACHE, key = "#parentId.concat(#user.id)")
public List<Menu> queryUserMenusByParentId(String parentId, User user) {
if (user.isSuperAdmin()) {
return menuDao.queryMenusByParentId(parentId);
} else {
return menuDao.queryUserMenusByParentId(parentId, user.getId());
}
}
}
| apache-2.0 |
forkunited/ARKWater | src/main/java/ark/model/annotator/nlp/AnnotatorSentence.java | 262 | package ark.model.annotator.nlp;
import java.util.Map;
import ark.data.annotation.nlp.DocumentNLP;
import ark.model.annotator.Annotator;
public interface AnnotatorSentence<T> extends Annotator<T> {
Map<Integer, T> annotate(DocumentNLP document);
}
| apache-2.0 |
NikoYuwono/retrofit | retrofit/src/main/java/retrofit2/Utils.java | 6138 | /*
* Copyright (C) 2012 Square, Inc.
* Copyright (C) 2007 The Guava 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 retrofit2;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.Arrays;
import okhttp3.ResponseBody;
import okio.Buffer;
final class Utils {
static <T> T checkNotNull(T object, String message) {
if (object == null) {
throw new NullPointerException(message);
}
return object;
}
/** Returns true if {@code annotations} contains an instance of {@code cls}. */
static boolean isAnnotationPresent(Annotation[] annotations,
Class<? extends Annotation> cls) {
for (Annotation annotation : annotations) {
if (cls.isInstance(annotation)) {
return true;
}
}
return false;
}
static ResponseBody buffer(final ResponseBody body) throws IOException {
Buffer buffer = new Buffer();
body.source().readAll(buffer);
return ResponseBody.create(body.contentType(), body.contentLength(), buffer);
}
static <T> void validateServiceInterface(Class<T> service) {
if (!service.isInterface()) {
throw new IllegalArgumentException("API declarations must be interfaces.");
}
// Prevent API interfaces from extending other interfaces. This not only avoids a bug in
// Android (http://b.android.com/58753) but it forces composition of API declarations which is
// the recommended pattern.
if (service.getInterfaces().length > 0) {
throw new IllegalArgumentException("API interfaces must not extend other interfaces.");
}
}
static Type getParameterUpperBound(int index, ParameterizedType type) {
Type[] types = type.getActualTypeArguments();
if (types.length <= index) {
throw new IllegalArgumentException(
"Expected at least " + index + " type argument(s) but got: " + Arrays.toString(types));
}
Type paramType = types[index];
if (paramType instanceof WildcardType) {
return ((WildcardType) paramType).getUpperBounds()[0];
}
return paramType;
}
static boolean hasUnresolvableType(Type type) {
if (type instanceof Class<?>) {
return false;
}
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
for (Type typeArgument : parameterizedType.getActualTypeArguments()) {
if (hasUnresolvableType(typeArgument)) {
return true;
}
}
return false;
}
if (type instanceof GenericArrayType) {
return hasUnresolvableType(((GenericArrayType) type).getGenericComponentType());
}
if (type instanceof TypeVariable) {
return true;
}
if (type instanceof WildcardType) {
return true;
}
String className = type == null ? "null" : type.getClass().getName();
throw new IllegalArgumentException("Expected a Class, ParameterizedType, or "
+ "GenericArrayType, but <" + type + "> is of type " + className);
}
// This method is copyright 2008 Google Inc. and is taken from Gson under the Apache 2.0 license.
static Class<?> getRawType(Type type) {
if (type instanceof Class<?>) {
// Type is a normal class.
return (Class<?>) type;
} else if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
// I'm not exactly sure why getRawType() returns Type instead of Class. Neal isn't either but
// suspects some pathological case related to nested classes exists.
Type rawType = parameterizedType.getRawType();
if (!(rawType instanceof Class)) throw new IllegalArgumentException();
return (Class<?>) rawType;
} else if (type instanceof GenericArrayType) {
Type componentType = ((GenericArrayType) type).getGenericComponentType();
return Array.newInstance(getRawType(componentType), 0).getClass();
} else if (type instanceof TypeVariable) {
// We could use the variable's bounds, but that won't work if there are multiple. Having a raw
// type that's more general than necessary is okay.
return Object.class;
} else if (type instanceof WildcardType) {
return getRawType(((WildcardType) type).getUpperBounds()[0]);
} else {
String className = type == null ? "null" : type.getClass().getName();
throw new IllegalArgumentException("Expected a Class, ParameterizedType, or "
+ "GenericArrayType, but <" + type + "> is of type " + className);
}
}
static RuntimeException methodError(Method method, String message, Object... args) {
return methodError(null, method, message, args);
}
static RuntimeException methodError(Throwable cause, Method method, String message,
Object... args) {
message = String.format(message, args);
return new IllegalArgumentException(message
+ "\n for method "
+ method.getDeclaringClass().getSimpleName()
+ "."
+ method.getName(), cause);
}
static Type getCallResponseType(Type returnType) {
if (!(returnType instanceof ParameterizedType)) {
throw new IllegalArgumentException(
"Call return type must be parameterized as Call<Foo> or Call<? extends Foo>");
}
return getParameterUpperBound(0, (ParameterizedType) returnType);
}
private Utils() {
// No instances.
}
}
| apache-2.0 |
vivekkothari/foxtrot | foxtrot-core/src/main/java/com/flipkart/foxtrot/core/querystore/impl/HazelcastConnection.java | 3541 | /**
* Copyright 2014 Flipkart Internet Pvt. Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.flipkart.foxtrot.core.querystore.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.flipkart.foxtrot.core.common.CacheUtils;
import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.yammer.dropwizard.lifecycle.Managed;
import net.sourceforge.cobertura.CoverageIgnore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
/**
* User: Santanu Sinha (santanu.sinha@flipkart.com)
* Date: 15/03/14
* Time: 10:01 PM
*/
@CoverageIgnore
public class HazelcastConnection implements Managed {
private static final Logger logger = LoggerFactory.getLogger(HazelcastConnection.class.getSimpleName());
private final ClusterConfig clusterConfig;
private HazelcastInstance hazelcast;
private final ObjectMapper mapper;
private Config hazelcastConfig;
public HazelcastConnection(ClusterConfig clusterConfig, ObjectMapper mapper) throws Exception {
this.clusterConfig = clusterConfig;
this.mapper = mapper;
final String hostName = InetAddress.getLocalHost().getCanonicalHostName();
Config hzConfig = new Config();
hzConfig.getGroupConfig().setName(clusterConfig.getName());
// ManagementCenterConfig managementCenterConfig = new ManagementCenterConfig();
// managementCenterConfig.setEnabled(true);
// logger.info("Enabling management center for Hazelcast");
// managementCenterConfig.setUrl(clusterConfig.getWebServerUrl());
// logger.info("Setting management center url for Hazelcast to : " + clusterConfig.getWebServerUrl());
// hzConfig.setManagementCenterConfig(managementCenterConfig);
hzConfig.setInstanceName(String.format("foxtrot-%s-%d", hostName, System.currentTimeMillis()));
if (clusterConfig.isDisableMulticast()) {
hzConfig.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
for (String member : clusterConfig.getMembers()) {
hzConfig.getNetworkConfig().getJoin().getTcpIpConfig().addMember(member);
}
hzConfig.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(true);
}
this.hazelcastConfig = hzConfig;
}
@Override
public void start() throws Exception {
logger.info("Starting Hazelcast Instance");
hazelcast = Hazelcast.newHazelcastInstance(hazelcastConfig);
CacheUtils.setCacheFactory(new DistributedCacheFactory(this, mapper));
logger.info("Started Hazelcast Instance");
}
@Override
public void stop() throws Exception {
hazelcast.shutdown();
}
public ClusterConfig getClusterConfig() {
return clusterConfig;
}
public HazelcastInstance getHazelcast() {
return hazelcast;
}
public Config getHazelcastConfig() {
return hazelcastConfig;
}
}
| apache-2.0 |
ibatis-dao/metadict | src/das/dao/props/IDataPropertyORMMapped.java | 564 | package das.dao.props;
public interface IDataPropertyORMMapped<B, V> extends IDataProperty<B, V> {
/*
* Gets the name (usually short "programmatic", non localizable) of the Property.
*/
String getName();
/*
* Sets the name (usually short "programmatic", non localizable) of the Property.
*/
void setName(String name);
/*
* Gets the data base column name, related to the Property.
*/
String getColumnName();
/*
* Return - either column is part of primary key or not
*/
boolean isPrimaryKey();
}
| apache-2.0 |
lei-xia/helix | helix-core/src/test/java/org/apache/helix/TestListenerCallback.java | 10713 | package org.apache.helix;
/*
* 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.Date;
import java.util.List;
import org.apache.helix.PropertyKey.Builder;
import org.apache.helix.api.listeners.ClusterConfigChangeListener;
import org.apache.helix.api.listeners.InstanceConfigChangeListener;
import org.apache.helix.api.listeners.ResourceConfigChangeListener;
import org.apache.helix.api.listeners.ScopedConfigChangeListener;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.HelixConfigScope.ConfigScopeProperty;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.model.ResourceConfig;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestListenerCallback extends ZkUnitTestBase {
class TestScopedConfigListener implements ScopedConfigChangeListener {
boolean _configChanged = false;
int _configSize = 0;
@Override
public void onConfigChange(List<HelixProperty> configs, NotificationContext context) {
_configChanged = true;
_configSize = configs.size();
}
public void reset() {
_configChanged = false;
_configSize = 0;
}
}
class TestConfigListener implements InstanceConfigChangeListener, ClusterConfigChangeListener,
ResourceConfigChangeListener {
boolean _instanceConfigChanged = false;
boolean _resourceConfigChanged = false;
boolean _clusterConfigChanged = false;
List<ResourceConfig> _resourceConfigs;
List<InstanceConfig> _instanceConfigs;
ClusterConfig _clusterConfig;
@Override
public void onInstanceConfigChange(List<InstanceConfig> instanceConfigs,
NotificationContext context) {
_instanceConfigChanged = true;
_instanceConfigs = instanceConfigs;
}
@Override
public void onClusterConfigChange(ClusterConfig clusterConfig, NotificationContext context) {
_clusterConfigChanged = true;
_clusterConfig = clusterConfig;
}
@Override
public void onResourceConfigChange(List<ResourceConfig> resourceConfigs,
NotificationContext context) {
_resourceConfigChanged = true;
_resourceConfigs = resourceConfigs;
}
public void reset() {
_instanceConfigChanged = false;
_resourceConfigChanged = false;
_clusterConfigChanged = false;
_resourceConfigs = null;
_instanceConfigs = null;
_clusterConfig = null;
}
}
int _numNodes = 3;
int _numResources = 4;
HelixManager _manager;
String _clusterName;
@BeforeClass
public void beforeClass() throws Exception {
_clusterName = TestHelper.getTestClassName();
System.out.println("START " + _clusterName + " at " + new Date(System.currentTimeMillis()));
TestHelper.setupCluster(_clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
_numResources, // resources
32, // partitions per resource
_numNodes, // number of nodes
2, // replicas
"MasterSlave", true); // do rebalance
_manager = HelixManagerFactory.getZKHelixManager(_clusterName, "localhost",
InstanceType.SPECTATOR, ZK_ADDR);
_manager.connect();
}
@AfterClass
public void afterClass() throws Exception {
if (_manager != null && _manager.isConnected()) {
_manager.disconnect();
}
TestHelper.dropCluster(_clusterName, _gZkClient);
System.out.println("END " + _clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testConfigChangeListeners() throws Exception {
TestConfigListener listener = new TestConfigListener();
listener.reset();
_manager.addInstanceConfigChangeListener(listener);
Assert.assertTrue(listener._instanceConfigChanged,
"Should get initial instanceConfig callback invoked");
Assert.assertEquals(listener._instanceConfigs.size(), _numNodes,
"Instance Config size does not match");
listener.reset();
_manager.addClusterfigChangeListener(listener);
Assert.assertTrue(listener._clusterConfigChanged,
"Should get initial clusterConfig callback invoked");
Assert.assertNotNull(listener._clusterConfig, "Cluster Config size should not be null");
listener.reset();
_manager.addResourceConfigChangeListener(listener);
Assert.assertTrue(listener._resourceConfigChanged,
"Should get initial resourceConfig callback invoked");
Assert.assertEquals(listener._resourceConfigs.size(), 0, "Instance Config size does not match");
// test change content
HelixDataAccessor accessor = _manager.getHelixDataAccessor();
Builder keyBuilder = accessor.keyBuilder();
String instanceName = "localhost_12918";
HelixProperty value = accessor.getProperty(keyBuilder.instanceConfig(instanceName));
value._record.setSimpleField("" + System.currentTimeMillis(), "newValue");
listener.reset();
accessor.setProperty(keyBuilder.instanceConfig(instanceName), value);
Thread.sleep(500); // wait zk callback
Assert.assertTrue(listener._instanceConfigChanged,
"Should get instanceConfig callback invoked since we change instanceConfig");
Assert.assertEquals(listener._instanceConfigs.size(), _numNodes,
"Instance Config size does not match");
value = accessor.getProperty(keyBuilder.clusterConfig());
value._record.setSimpleField("" + System.currentTimeMillis(), "newValue");
listener.reset();
accessor.setProperty(keyBuilder.clusterConfig(), value);
Thread.sleep(500); // wait zk callback
Assert.assertTrue(listener._clusterConfigChanged,
"Should get clusterConfig callback invoked since we change clusterConfig");
Assert.assertNotNull(listener._clusterConfig, "Cluster Config size should not be null");
String resourceName = "TestDB_0";
value = new HelixProperty(resourceName);
value._record.setSimpleField("" + System.currentTimeMillis(), "newValue");
listener.reset();
accessor.setProperty(keyBuilder.resourceConfig(resourceName), value);
Thread.sleep(500); // wait zk callback
Assert.assertTrue(listener._resourceConfigChanged,
"Should get resourceConfig callback invoked since we add resourceConfig");
Assert.assertEquals(listener._resourceConfigs.size(), 1, "Resource config size does not match");
listener.reset();
accessor.removeProperty(keyBuilder.resourceConfig(resourceName));
Thread.sleep(500); // wait zk callback
Assert.assertTrue(listener._resourceConfigChanged,
"Should get resourceConfig callback invoked since we add resourceConfig");
Assert.assertEquals(listener._resourceConfigs.size(), 0, "Instance Config size does not match");
}
@Test
public void testScopedConfigChangeListener() throws Exception {
TestScopedConfigListener listener = new TestScopedConfigListener();
listener.reset();
_manager.addConfigChangeListener(listener, ConfigScopeProperty.CLUSTER);
Assert.assertTrue(listener._configChanged, "Should get initial clusterConfig callback invoked");
Assert.assertEquals(listener._configSize, 1, "Cluster Config size should be 1");
listener.reset();
_manager.addConfigChangeListener(listener, ConfigScopeProperty.RESOURCE);
Assert.assertTrue(listener._configChanged,
"Should get initial resourceConfig callback invoked");
Assert.assertEquals(listener._configSize, 0, "Resource Config size does not match");
listener.reset();
_manager.addConfigChangeListener(listener, ConfigScopeProperty.PARTICIPANT);
Assert.assertTrue(listener._configChanged,
"Should get initial instanceConfig callback invoked");
Assert.assertEquals(listener._configSize, _numNodes, "Instance Config size does not match");
// test change content
HelixDataAccessor accessor = _manager.getHelixDataAccessor();
Builder keyBuilder = accessor.keyBuilder();
String instanceName = "localhost_12918";
HelixProperty value = accessor.getProperty(keyBuilder.instanceConfig(instanceName));
value._record.setSimpleField("" + System.currentTimeMillis(), "newValue");
listener.reset();
accessor.setProperty(keyBuilder.instanceConfig(instanceName), value);
Thread.sleep(500); // wait zk callback
Assert.assertTrue(listener._configChanged,
"Should get instanceConfig callback invoked since we change instanceConfig");
Assert.assertEquals(listener._configSize, _numNodes, "Instance Config size does not match");
value = accessor.getProperty(keyBuilder.clusterConfig());
value._record.setSimpleField("" + System.currentTimeMillis(), "newClusterValue");
listener.reset();
accessor.setProperty(keyBuilder.clusterConfig(), value);
Thread.sleep(500); // wait zk callback
Assert.assertTrue(listener._configChanged,
"Should get clusterConfig callback invoked since we change clusterConfig");
Assert.assertEquals(listener._configSize, 1, "Cluster Config size does not match");
String resourceName = "TestDB_0";
value = new HelixProperty(resourceName);
value._record.setSimpleField("" + System.currentTimeMillis(), "newValue");
listener.reset();
accessor.setProperty(keyBuilder.resourceConfig(resourceName), value);
Thread.sleep(500); // wait zk callback
Assert.assertTrue(listener._configChanged,
"Should get resourceConfig callback invoked since we add resourceConfig");
Assert.assertEquals(listener._configSize, 1, "Resource Config size does not match");
listener.reset();
accessor.removeProperty(keyBuilder.resourceConfig(resourceName));
Thread.sleep(500); // wait zk callback
Assert.assertTrue(listener._configChanged,
"Should get resourceConfig callback invoked since we add resourceConfig");
Assert.assertEquals(listener._configSize, 0, "Resource Config size does not match");
}
}
| apache-2.0 |
geosolutions-it/jeo | core/src/main/java/org/jeo/data/Driver.java | 1943 | package org.jeo.data;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.jeo.util.Key;
/**
* Format driver.
* <p>
* The job of a driver is to create a "connection" to data in a particular format. A driver can
* return either one of a dataset, or a workspace containing many datasets. The data
* </p>
* <p>
* Driver implementations must adhere to the following guidelines:
* <ul>
* <li>Be thread safe and ideally maintain no state</li>
* <li>Contain a single no argument constructor</li>
* </ul>
* </p>
*
* @author Justin Deoliveira, OpenGeo
*/
public interface Driver<T> {
/**
* Name identifying the driver.
* <p>
* This name should be no more than a few words (ideally one). It isn't meant to be a
* description but should be human readable.
* </p>
*/
String getName();
/**
* Secondary names identifying the driver.
* <p>
* Aliases are typically shorter abbreviations for {@link #getName()}
* </p>
*/
List<String> getAliases();
/**
* Returns the class of object returned by the driver.
*/
Class<T> getType();
/**
* Returns the keys supported by the driver.
*/
List<Key<?>> getKeys();
/**
* Determines if this driver can open a connection to the data described by the specified
* options.
*
* @param opts Options describing the data.
*
* @return True if the driver can open the data, otherwise false.
*/
boolean canOpen(Map<?,Object> opts);
/**
* Opens a connection to data described by the specified options.
*
* @param opts Options describing the data to connect to.
*
* @return The data.
*
* @throws IOException In the event of a connection error such as a file system error or
* database connection failure.
*/
T open(Map<?,Object> opts) throws IOException;
}
| apache-2.0 |
lbendig/gobblin | gobblin-data-management/src/main/java/gobblin/data/management/copy/replication/HadoopFsEndPoint.java | 2531 | /*
* 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 gobblin.data.management.copy.replication;
import java.io.IOException;
import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import com.typesafe.config.Config;
import gobblin.util.HadoopUtils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public abstract class HadoopFsEndPoint implements EndPoint{
/**
*
* @return the hadoop cluster name for {@link EndPoint}s on Hadoop File System
*/
public abstract String getClusterName();
/**
* @return the hadoop cluster FileSystem URI
*/
public abstract URI getFsURI();
/**
*
* @return Deepest {@link org.apache.hadoop.fs.Path} that contains all files in the dataset.
*/
public abstract Path getDatasetPath();
public abstract Config getSelectionConfig();
/**
* A helper utility for data/filesystem availability checking
* @param path The path to be checked. For fs availability checking, just use "/"
* @return If the filesystem/path exists or not.
*/
public boolean isPathAvailable(Path path){
try {
Configuration conf = HadoopUtils.newConfiguration();
FileSystem fs = FileSystem.get(this.getFsURI(), conf);
if (fs.exists(path)) {
return true;
} else {
log.warn("Skipped the problematic FileSystem " + this.getFsURI());
return false;
}
} catch (IOException ioe) {
log.warn("Skipped the problematic FileSystem " + this.getFsURI());
return false;
}
}
@Override
public boolean isFileSystemAvailable() {
return isPathAvailable(new Path("/"));
}
public boolean isDatasetAvailable(Path datasetPath) {
return isPathAvailable(datasetPath);
}
}
| apache-2.0 |
lmjacksoniii/hazelcast | hazelcast/src/main/java/com/hazelcast/multimap/impl/operations/PutBackupOperation.java | 2564 | /*
* Copyright (c) 2008-2016, Hazelcast, 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.hazelcast.multimap.impl.operations;
import com.hazelcast.multimap.impl.MultiMapDataSerializerHook;
import com.hazelcast.multimap.impl.MultiMapRecord;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.spi.BackupOperation;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
public class PutBackupOperation extends MultiMapKeyBasedOperation implements BackupOperation {
long recordId;
Data value;
int index;
public PutBackupOperation() {
}
public PutBackupOperation(String name, Data dataKey, Data value, long recordId, int index) {
super(name, dataKey);
this.value = value;
this.recordId = recordId;
this.index = index;
}
@Override
public void run() throws Exception {
MultiMapRecord record = new MultiMapRecord(recordId, isBinary() ? value : toObject(value));
Collection<MultiMapRecord> coll = getOrCreateMultiMapValue().getCollection(false);
if (index == -1) {
response = coll.add(record);
} else {
try {
((List<MultiMapRecord>) coll).add(index, record);
response = true;
} catch (IndexOutOfBoundsException e) {
response = e;
}
}
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeLong(recordId);
out.writeInt(index);
out.writeData(value);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
recordId = in.readLong();
index = in.readInt();
value = in.readData();
}
@Override
public int getId() {
return MultiMapDataSerializerHook.PUT_BACKUP;
}
}
| apache-2.0 |