repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
opennetworkinglab/onos | core/api/src/main/java/org/onosproject/net/meter/MeterRequest.java | 4300 | /*
* Copyright 2015-present Open Networking Foundation
*
* 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.onosproject.net.meter;
import org.onosproject.core.ApplicationId;
import org.onosproject.net.Annotated;
import org.onosproject.net.Annotations;
import org.onosproject.net.DeviceId;
import java.util.Collection;
import java.util.Optional;
/**
* Represents a generalized meter request to be deployed on a device.
*/
public interface MeterRequest extends Annotated {
enum Type {
ADD,
MODIFY,
REMOVE
}
/**
* The target device for this meter.
*
* @return a device id
*/
DeviceId deviceId();
/**
* The id of the application which created this meter.
*
* @return an application id
*/
ApplicationId appId();
/**
* The unit used within this meter.
*
* @return the unit
*/
Meter.Unit unit();
/**
* Signals whether this meter applies to bursts only.
*
* @return a boolean
*/
boolean isBurst();
/**
* The collection of bands to apply on the dataplane.
*
* @return a collection of bands.
*/
Collection<Band> bands();
/**
* Returns the callback context for this meter.
*
* @return an optional meter context
*/
Optional<MeterContext> context();
/**
* Returns the scope of this meter request.
*
* @return a meter scope
*/
MeterScope scope();
/**
* Returns the desired meter index of this meter request.
*
* @return an optional long index
*/
Optional<Long> index();
/**
* A meter builder.
*/
interface Builder {
/**
* Assigns the target device for this meter.
*
* @param deviceId a device id
* @return this
*/
Builder forDevice(DeviceId deviceId);
/**
* Assigns the application that built this meter.
*
* @param appId an application id
* @return this
*/
Builder fromApp(ApplicationId appId);
/**
* Assigns the @See Unit to use for this meter.
* Defaults to kb/s
*
* @param unit a unit
* @return this
*/
Builder withUnit(Meter.Unit unit);
/**
* Sets this meter as applicable to burst traffic only.
* Defaults to false.
*
* @return this
*/
Builder burst();
/**
* Assigns bands to this meter. There must be at least one band.
*
* @param bands a collection of bands
* @return this
*/
Builder withBands(Collection<Band> bands);
/**
* Assigns an execution context for this meter request.
*
* @param context a meter context
* @return this
*/
Builder withContext(MeterContext context);
/**
* Sets the annotations.
*
* @param annotations annotations
* @return builder object
*/
Builder withAnnotations(Annotations annotations);
/**
* Sets the scope.
*
* @param scope a meter scope
* @return this
*/
Builder withScope(MeterScope scope);
/**
* Sets the index.
*
* @param index an optional index
* @return this
*/
Builder withIndex(Long index);
/**
* Requests the addition of a meter.
*
* @return a meter request
*/
MeterRequest add();
/**
* Requests the removal of a meter.
*
* @return a meter request
*/
MeterRequest remove();
}
}
| apache-2.0 |
hortonworks/cloudbreak | usage-collection/src/test/java/com/sequenceiq/cloudbreak/usage/strategy/HttpUsageProcessingStrategyTest.java | 2059 | package com.sequenceiq.cloudbreak.usage.strategy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import com.cloudera.thunderhead.service.common.usage.UsageProto;
import com.sequenceiq.cloudbreak.usage.http.EdhHttpAdditionalField;
import com.sequenceiq.cloudbreak.usage.http.EdhHttpConfiguration;
import com.sequenceiq.cloudbreak.usage.http.UsageHttpRecordProcessor;
@ExtendWith(MockitoExtension.class)
public class HttpUsageProcessingStrategyTest {
@InjectMocks
private HttpUsageProcessingStrategy underTest;
@Mock
private UsageHttpRecordProcessor processor;
@Mock
private EdhHttpConfiguration edhHttpConfiguration;
@BeforeEach
public void setUp() {
underTest = new HttpUsageProcessingStrategy(processor, edhHttpConfiguration);
}
@Test
public void testProcessUsage() {
// GIVEN
EdhHttpAdditionalField field = new EdhHttpAdditionalField();
field.setKey("key");
field.setValue("val");
List<EdhHttpAdditionalField> fields = List.of(field);
given(edhHttpConfiguration.getAdditionalFields()).willReturn(fields);
doNothing().when(processor).processRecord(any());
UsageProto.Event event = UsageProto.Event.newBuilder()
.setCdpEnvironmentRequested(UsageProto.CDPEnvironmentRequested
.newBuilder()
.build())
.build();
// WHEN
underTest.processUsage(event, null);
// THEN
verify(edhHttpConfiguration, times(1)).getAdditionalFields();
verify(processor, times(1)).processRecord(any());
}
}
| apache-2.0 |
jbrisbin/disruptor | src/main/java/com/lmax/disruptor/SleepingWaitStrategy.java | 3741 | /*
* Copyright 2011 LMAX 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.lmax.disruptor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import static com.lmax.disruptor.util.Util.getMinimumSequence;
/**
* Sleeping strategy that initially spins, then uses a Thread.yield(), and eventually for the minimum number of nanos
* the OS and JVM will allow while the {@link com.lmax.disruptor.EventProcessor}s are waiting on a barrier.
*
* This strategy is a good compromise between performance and CPU resource. Latency spikes can occur after quiet periods.
*/
public final class SleepingWaitStrategy implements WaitStrategy
{
private static final int RETRIES = 200;
@Override
public long waitFor(final long sequence, final Sequence cursor, final Sequence[] dependents, final SequenceBarrier barrier)
throws AlertException, InterruptedException
{
long availableSequence;
int counter = RETRIES;
if (0 == dependents.length)
{
while ((availableSequence = cursor.get()) < sequence)
{
counter = applyWaitMethod(barrier, counter);
}
}
else
{
while ((availableSequence = getMinimumSequence(dependents)) < sequence)
{
counter = applyWaitMethod(barrier, counter);
}
}
return availableSequence;
}
@Override
public long waitFor(final long sequence, final Sequence cursor, final Sequence[] dependents, final SequenceBarrier barrier,
final long timeout, final TimeUnit sourceUnit)
throws AlertException, InterruptedException
{
final long timeoutMs = sourceUnit.toMillis(timeout);
final long startTime = System.currentTimeMillis();
long availableSequence;
int counter = RETRIES;
if (0 == dependents.length)
{
while ((availableSequence = cursor.get()) < sequence)
{
counter = applyWaitMethod(barrier, counter);
final long elapsedTime = System.currentTimeMillis() - startTime;
if (elapsedTime > timeoutMs)
{
break;
}
}
}
else
{
while ((availableSequence = getMinimumSequence(dependents)) < sequence)
{
counter = applyWaitMethod(barrier, counter);
final long elapsedTime = System.currentTimeMillis() - startTime;
if (elapsedTime > timeoutMs)
{
break;
}
}
}
return availableSequence;
}
@Override
public void signalAllWhenBlocking()
{
}
private int applyWaitMethod(final SequenceBarrier barrier, int counter)
throws AlertException
{
barrier.checkAlert();
if (counter > 100)
{
--counter;
}
else if (counter > 0)
{
--counter;
Thread.yield();
}
else
{
LockSupport.parkNanos(1L);
}
return counter;
}
}
| apache-2.0 |
solonaruvioletta/java_testing | soap-sample/src/main/java/net/webservicex/GeoIPServiceHttpPost.java | 1271 | package net.webservicex;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.bind.annotation.XmlSeeAlso;
/**
* This class was generated by Apache CXF 3.1.10
* 2017-03-27T14:24:35.019+03:00
* Generated source version: 3.1.10
*
*/
@WebService(targetNamespace = "http://www.webservicex.net/", name = "GeoIPServiceHttpPost")
@XmlSeeAlso({ObjectFactory.class})
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
public interface GeoIPServiceHttpPost {
/**
* GeoIPService - GetGeoIP enables you to easily look up countries by IP addresses
*/
@WebMethod(operationName = "GetGeoIP")
@WebResult(name = "GeoIP", targetNamespace = "http://www.webservicex.net/", partName = "Body")
public GeoIP getGeoIP(
@WebParam(partName = "IPAddress", name = "IPAddress", targetNamespace = "")
java.lang.String ipAddress
);
/**
* GeoIPService - GetGeoIPContext enables you to easily look up countries by Context
*/
@WebMethod(operationName = "GetGeoIPContext")
@WebResult(name = "GeoIP", targetNamespace = "http://www.webservicex.net/", partName = "Body")
public GeoIP getGeoIPContext();
}
| apache-2.0 |
nordpos-mobi/product-catalog | src/main/java/mobi/nordpos/catalog/action/WelcomeActionBean.java | 1921 | /**
* Copyright (c) 2012-2014 Nord Trading Network.
*
* 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 mobi.nordpos.catalog.action;
import mobi.nordpos.catalog.ext.Public;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
/**
* @author Andrey Svininykh <svininykh@gmail.com>
*/
@Public
public class WelcomeActionBean extends BaseActionBean {
private static final String PRESENT = "/WEB-INF/jsp/present.jsp";
private static final String INFO = "/WEB-INF/jsp/info.jsp";
@DefaultHandler
public Resolution title() {
return new ForwardResolution(PRESENT);
}
public Resolution info() {
return new ForwardResolution(INFO);
}
public String getCountry() {
return getContext().getLocale().getDisplayCountry();
}
public String getLanguage() {
return getContext().getLocale().getDisplayLanguage();
}
public String getServerInfo() {
return getContext().getServletContext().getServerInfo();
}
public String getJavaVersion() {
return System.getProperty("java.vendor") + " " + System.getProperty("java.version");
}
public String getOperationSystem() {
return System.getProperty("os.name") + " " + System.getProperty("os.version") + " " + System.getProperty("os.arch");
}
}
| apache-2.0 |
cherryhill/collectionspace-services | services/common/src/main/java/org/collectionspace/services/common/document/DocumentHandler.java | 11551 | /**
* This document is a part of the source code and related artifacts
* for CollectionSpace, an open source collections management system
* for museums and related institutions:
* http://www.collectionspace.org
* http://wiki.collectionspace.org
* Copyright 2009 University of California at Berkeley
* Licensed under the Educational Community License (ECL), Version 2.0.
* You may not use this file except in compliance with this License.
* You may obtain a copy of the ECL 2.0 License at
* https://source.collectionspace.org/collection-space/LICENSE.txt
*/
package org.collectionspace.services.common.document;
import java.util.Map;
import org.collectionspace.services.common.context.ServiceContext;
import org.collectionspace.services.common.query.QueryContext;
import org.collectionspace.services.lifecycle.Lifecycle;
import org.collectionspace.services.lifecycle.TransitionDef;
import org.nuxeo.ecm.core.api.DocumentModel;
/**
*
* DocumentHandler provides document processing methods. It is an interface
* between repository client and CollectionSpace service resource. It provides
* methods to setup request via repository client and handle its response.
*
* Typical call sequence is:
* Create handler and repository client
* Call XXX operation on the repository client and pass the handler
* repository client calls prepare on the handler
* The repository client then calls handle on the handler
*
* T - Entity Type (e.g. CollectionObjectsCommon)
* TL - Entity List Type (e.g. CollectionObjectsCommonList)
* WT - Wrapped Type (e.g. DocumentModel)
* WTL - Wrapped List Type (e.g. DocumentModelList)
*
*/
public interface DocumentHandler<T, TL, WT, WTL> {
public enum Action {
CREATE, GET, GET_ALL, UPDATE, DELETE, WORKFLOW
}
public Lifecycle getLifecycle();
public Lifecycle getLifecycle(String serviceObjectName);
/**
* getServiceContext returns service context
* @return
*/
public ServiceContext getServiceContext();
/**
* getServiceContextPath such as "/collectionobjects/"
* @return
*/
public String getServiceContextPath();
/**
* setServiceContext sets service contex to the handler
* @param ctx
*/
public void setServiceContext(ServiceContext ctx);
/**
* prepare is called by the client for preparation of stuff before
* invoking repository operation. this is mainly useful for create and
* update kind of actions
* @param action
* @throws Exception
*/
public void prepare(Action action) throws Exception;
/**
* updateWorkflowTransition - prepare for a workflow transition
*/
public void handleWorkflowTransition(DocumentWrapper<DocumentModel> wrapDoc, TransitionDef transitionDef) throws Exception;
/**
* prepareCreate processes documents before creating document in repository
* @throws Exception
*/
public void prepareCreate() throws Exception;
/**
* prepareUpdate processes documents for the update of document in repository
* @throws Exception
*/
public void prepareUpdate() throws Exception;
/**
* prepareGet processes query before retrieving document from
* repository
* @throws Exception
*/
public void prepareGet() throws Exception;
/**
* prepareGetAll processes query before retrieving document(s) from
* repository
* @throws Exception
*/
public void prepareGetAll() throws Exception;
/**
* prepareDelete processes delete before deleting document from repository
* @throws Exception
*/
public void prepareDelete() throws Exception;
/**
* prepare is called by the client to hand over the document processing task
* @param action
* @param doc wrapped doc
* @throws Exception
*/
public void handle(Action action, DocumentWrapper<?> docWrap) throws Exception;
/**
* handleCreate processes documents before creating document in repository
* @param wrapDoc
* @throws Exception
*/
public void handleCreate(DocumentWrapper<WT> wrapDoc) throws Exception;
/**
* handleUpdate processes documents for the update of document in repository
* @param wrapDoc
* @throws Exception
*/
public void handleUpdate(DocumentWrapper<WT> wrapDoc) throws Exception;
/**
* handleGet processes documents from repository before responding to consumer
* @param wrapDoc
* @throws Exception
*/
public void handleGet(DocumentWrapper<WT> wrapDoc) throws Exception;
/**
* handleGetAll processes documents from repository before responding to consumer
* @param wrapDoc
* @throws Exception
*/
public void handleGetAll(DocumentWrapper<WTL> wrapDoc) throws Exception;
/**
* handleDelete processes documents for the deletion of document in repository
* @param wrapDoc
* @throws Exception
*/
public void handleDelete(DocumentWrapper<WT> wrapDoc) throws Exception;
/**
* complete is called by the client to provide an opportunity to the handler
* to take care of stuff before closing session with the repository. example
* could be to reclaim resources or to populate response to the consumer
* @param wrapDoc
* @throws Exception
*/
public void complete(Action action, DocumentWrapper<?> wrapDoc) throws Exception;
/**
* completeCreate is called by the client to indicate completion of the create call.
* @param wrapDoc
* @throws Exception
*/
public void completeCreate(DocumentWrapper<WT> wrapDoc) throws Exception;
/**
* completeUpdate is called by the client to indicate completion of the update call.
* @param wrapDoc
* @throws Exception
*/
public void completeUpdate(DocumentWrapper<WT> wrapDoc) throws Exception;
/**
* completeGetis called by the client to indicate completion of the get call.
* @param wrapDoc
* @throws Exception
*/
public void completeGet(DocumentWrapper<WT> wrapDoc) throws Exception;
/**
* completeGetAll is called by the client to indicate completion of the getall.
* @param wrapDoc
* @throws Exception
*/
public void completeGetAll(DocumentWrapper<WTL> wrapDoc) throws Exception;
/**
* completeDelete is called by the client to indicate completion of the delete call.
* @param wrapDoc
* @throws Exception
*/
public void completeDelete(DocumentWrapper<WT> wrapDoc) throws Exception;
/**
* extractCommonPart extracts common part of a CS object from given document.
* this is usually called AFTER the get operation is invoked on the repository.
* Called in handle GET/GET_ALL actions.
* @param docWrap document
* @return common part of CS object
* @throws Exception
*/
public T extractCommonPart(DocumentWrapper<WT> docWrap) throws Exception;
/**
* fillCommonPart sets common part of CS object into given document
* this is usually called BEFORE create/update operations are invoked on the
* repository. Called in handle CREATE/UPDATE actions.
* @param obj input object
* @param docWrap target document
* @throws Exception
*/
public void fillCommonPart(T obj, DocumentWrapper<WT> docWrap) throws Exception;
/**
* extractCommonPart extracts common part of a CS object from given document.
* this is usually called AFTER bulk get (index/list) operation is invoked on
* the repository
* @param docWrap document
* @return common part of CS object
* @throws Exception
*/
public TL extractCommonPartList(DocumentWrapper<WTL> docWrap) throws Exception;
/**
* Extract paging info.
*
* @param theCommonList the the common list
* @param wrapDoc the wrap doc
* @return the tL
* @throws Exception the exception
*/
public TL extractPagingInfo(TL theCommonList, DocumentWrapper<WTL> wrapDoc) throws Exception;
/**
* fillCommonPartList sets list common part of CS object into given document
* this is usually called BEFORE bulk create/update on the repository
* (not yet supported)
* @param obj input object
* @param docWrap target document
* @throws Exception
*/
public void fillCommonPartList(TL obj, DocumentWrapper<WTL> docWrap) throws Exception;
/**
* getProperties
* @return
*/
public Map<String, Object> getProperties();
/**
* setProperties provides means to the CollectionSpace service resource to
* set up parameters before invoking any request via the client.
* @param properties
*/
public void setProperties(Map<String, Object> properties);
/**
* createDocumentFilter is a factory method to create a document
* filter that is relevant to be used with this document handler
* and corresponding storage client
*
* @return
*/
public DocumentFilter createDocumentFilter();
/**
* getDocumentFilter
* @return
*/
public DocumentFilter getDocumentFilter();
/**
* setDocumentFilter provides means to the CollectionSpace service resource to
* set up DocumentFilter values before invoking any request via the client.
* @param docFilter
*/
public void setDocumentFilter(DocumentFilter docFilter);
/**
* getCommonPart provides the common part of a CS object.
* @return common part of CS object
*/
public T getCommonPart();
/**
* setCommonPart sets common part of CS object as input for operation on
* repository
* @param obj input object
*/
public void setCommonPart(T obj);
/**
* getCommonPartList provides the default list object of a CS object.
* @return default list of CS object
*/
public TL getCommonPartList();
/**
* setCommonPartList sets common part list entry for CS object as input for operation on
* repository
* @param default list of CS object
*/
public void setCommonPartList(TL obj);
/**
* getQProperty get qualified property (useful for mapping to repository document property)
* @param prop
* @return
* @throws DocumentException
*/
public String getQProperty(String prop) throws DocumentException;
/**
* getUnQProperty unqualifies document property from repository
* @param qProp qualifeid property
* @return unqualified property
*/
public String getUnQProperty(String qProp);
/**
* Creates the CMIS query from the service context. Each document handler is responsible for returning a valid CMIS query using the
* information in the current service context -which includes things like the query parameters, etc.
* @throws DocumentException
*/
public String getCMISQuery(QueryContext queryContext) throws DocumentException;
/**
* Returns TRUE if a CMIS query should be used (instead of an NXQL query)
*/
public boolean isCMISQuery();
/**
* Returns TRUE if a JDBC/SQL query should be used (instead of an NXQL query)
*/
public boolean isJDBCQuery();
/**
* Returns parameter values, relevant to this document handler, that can be used in JDBC/SQL queries
*
* @return a set of zero or more parameter values relevant to this handler
*/
public Map<String,String> getJDBCQueryParams();
}
| apache-2.0 |
Kateryna-Gelashvili/fivesquare | src/main/java/org/k/ui/NewPlaceWindow.java | 1354 | package org.k.ui;
import com.vaadin.navigator.View;
import com.vaadin.ui.Button;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import org.k.dao.PlaceDAO;
import org.k.dao.PlaceDAOImpl;
import org.k.domain.Place;
public class NewPlaceWindow extends Window {
private final TextField nameField;
public NewPlaceWindow() {
super("Add new place");
setWidth("30%");
VerticalLayout windowContent = new VerticalLayout();
windowContent.setMargin(true);
windowContent.setSpacing(true);
setContent(windowContent);
nameField = new TextField("Name");
nameField.setWidth("100%");
Button saveButton = new Button("Save");
saveButton.addClickListener(new Button.ClickListener() {
@Override
public void buttonClick(Button.ClickEvent event) {
savePlace();
}
});
windowContent.addComponent(nameField);
windowContent.addComponent(saveButton);
center();
}
private void savePlace() {
if (!nameField.isEmpty()){
PlaceDAO placeDAO = PlaceDAOImpl.getInstance();
Place place = new Place();
place.setName(nameField.getValue());
placeDAO.addPlace(place);
}
close();
}
}
| apache-2.0 |
didi/DoraemonKit | Android/dokit/src/main/java/com/didichuxing/doraemonkit/kit/performance/PerformanceDokitViewManager.java | 3706 | package com.didichuxing.doraemonkit.kit.performance;
import android.content.Context;
import com.didichuxing.doraemonkit.DoKit;
import com.didichuxing.doraemonkit.util.ActivityUtils;
import com.didichuxing.doraemonkit.R;
import com.didichuxing.doraemonkit.kit.core.DokitViewManager;
import com.didichuxing.doraemonkit.kit.performance.datasource.DataSourceFactory;
import java.util.TreeMap;
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2019-10-11-16:05
* 描 述:性能监控 帧率、 CPU、RAM、流量监控统一显示的DokitView 管理类
* 修订历史:
* ================================================
*/
public class PerformanceDokitViewManager {
public static TreeMap<String, performanceViewInfo> singleperformanceViewInfos = new TreeMap<>();
/**
* @param performanceType 参考 DataSourceFactory
*/
public static void open(int performanceType, String title, PerformanceFragmentCloseListener listener) {
open(performanceType, title, PerformanceDokitView.DEFAULT_REFRESH_INTERVAL, listener);
}
public static void open(int performanceType, String title, int interval, PerformanceFragmentCloseListener listener) {
PerformanceDokitView performanceDokitView = DoKit.getDoKitView(ActivityUtils.getTopActivity(), PerformanceDokitView.class);
if (performanceDokitView == null) {
DoKit.launchFloating(PerformanceDokitView.class);
performanceDokitView = DoKit.getDoKitView(ActivityUtils.getTopActivity(), PerformanceDokitView.class);
performanceDokitView.addItem(performanceType, title, interval);
} else {
performanceDokitView.addItem(performanceType, title, interval);
}
performanceDokitView.addPerformanceFragmentCloseListener(listener);
singleperformanceViewInfos.put(title, new performanceViewInfo(performanceType, title, interval));
}
/**
* 性能检测设置页面关闭时调用
*
* @param listener
*/
public static void onPerformanceSettingFragmentDestroy(PerformanceFragmentCloseListener listener) {
PerformanceDokitView performanceDokitView = DoKit.getDoKitView(ActivityUtils.getTopActivity(), PerformanceDokitView.class);
if (performanceDokitView != null) {
performanceDokitView.removePerformanceFragmentCloseListener(listener);
}
}
/**
* @param performanceType 参考 DataSourceFactory
*/
public static void close(int performanceType, String title) {
PerformanceDokitView performanceDokitView = DoKit.getDoKitView(ActivityUtils.getTopActivity(), PerformanceDokitView.class);
if (performanceDokitView != null) {
performanceDokitView.removeItem(performanceType);
}
singleperformanceViewInfos.remove(title);
}
public static String getTitleByPerformanceType(Context context, int performanceType) {
String title = "";
switch (performanceType) {
case DataSourceFactory.TYPE_FPS:
title = context.getString(R.string.dk_kit_frame_info_desc);
break;
case DataSourceFactory.TYPE_CPU:
title = context.getString(R.string.dk_frameinfo_cpu);
break;
case DataSourceFactory.TYPE_RAM:
title = context.getString(R.string.dk_ram_detection_title);
break;
case DataSourceFactory.TYPE_NETWORK:
title = context.getString(R.string.dk_kit_net_monitor);
break;
default:
break;
}
return title;
}
}
| apache-2.0 |
OpenHFT/Java-Thread-Affinity | affinity/src/test/java/net/openhft/affinity/LockCheckTest.java | 2487 | /*
* Copyright 2016-2020 chronicle.software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package net.openhft.affinity;
import net.openhft.affinity.testimpl.TestFileLockBasedLockChecker;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import static net.openhft.affinity.LockCheck.IS_LINUX;
/**
* @author Rob Austin.
*/
public class LockCheckTest extends BaseAffinityTest {
private final TestFileLockBasedLockChecker lockChecker = new TestFileLockBasedLockChecker();
private int cpu = 11;
@Before
public void before() {
Assume.assumeTrue(IS_LINUX);
}
@Test
public void test() throws IOException {
Assert.assertTrue(LockCheck.isCpuFree(cpu));
LockCheck.updateCpu(cpu);
Assert.assertEquals(LockCheck.getPID(), LockCheck.getProcessForCpu(cpu));
}
@Test
public void testPidOnLinux() {
Assert.assertTrue(LockCheck.isProcessRunning(LockCheck.getPID()));
}
@Test
public void testReplace() throws IOException {
cpu++;
Assert.assertTrue(LockCheck.isCpuFree(cpu + 1));
LockCheck.replacePid(cpu, 123L);
Assert.assertEquals(123L, LockCheck.getProcessForCpu(cpu));
}
@Test
public void shouldNotBlowUpIfPidFileIsEmpty() throws Exception {
LockCheck.updateCpu(cpu);
final File file = lockChecker.doToFile(cpu);
new RandomAccessFile(file, "rw").setLength(0);
LockCheck.isCpuFree(cpu);
}
@Test
public void shouldNotBlowUpIfPidFileIsCorrupt() throws Exception {
LockCheck.updateCpu(cpu);
final File file = lockChecker.doToFile(cpu);
try (final FileWriter writer = new FileWriter(file, false)) {
writer.append("not a number\nnot a date");
}
LockCheck.isCpuFree(cpu);
}
} | apache-2.0 |
lorislab/postman | postman-impl/src/main/java/org/lorislab/postman/util/EmailUtil.java | 1731 | /*
* Copyright 2014 Andrej Petras.
*
* 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.lorislab.postman.util;
import org.lorislab.postman.api.model.Email;
import org.lorislab.postman.api.model.EmailConfig;
/**
* The email utility.
*
* @author Andrej Petras
*/
public final class EmailUtil {
/**
* The default constructor.
*/
private EmailUtil() {
// empty constructor
}
/**
* Updates the email base on the email configuration.
*
* @param email the email.
* @param config the email configuration.
*/
public static void configureEmail(final Email email, final EmailConfig config) {
// set email locale
email.setLocale(config.getLocale());
// set email from
email.setFrom(config.getFrom());
// sets the attributes
email.setContentType(config.getContentType());
email.setContentCharset(config.getContentCharset());
email.setTransferEncoding(config.getTransferEncoding());
// add special parameter
email.getParameters().put(EmailConfig.class.getSimpleName(), config);
email.getParameters().put(Email.class.getSimpleName(), email);
}
}
| apache-2.0 |
thirdiron/mendeley-android-sdk | library/src/main/java/com/mendeley/api/model/Box.java | 1127 | package com.mendeley.api.model;
public class Box {
public final Point topLeft;
public final Point bottomRight;
public final Integer page;
public Box(Point topLeft, Point bottomRight, Integer page) {
this.topLeft = topLeft;
this.bottomRight = bottomRight;
this.page = page;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Box box = (Box) o;
if (bottomRight != null ? !bottomRight.equals(box.bottomRight) : box.bottomRight != null)
return false;
if (page != null ? !page.equals(box.page) : box.page != null) return false;
if (topLeft != null ? !topLeft.equals(box.topLeft) : box.topLeft != null) return false;
return true;
}
@Override
public int hashCode() {
int result = topLeft != null ? topLeft.hashCode() : 0;
result = 31 * result + (bottomRight != null ? bottomRight.hashCode() : 0);
result = 31 * result + (page != null ? page.hashCode() : 0);
return result;
}
}
| apache-2.0 |
eSDK/esdk_cloud_fm_r3_native_java | source/FM/V1R3/esdk_fm_native_java/src/main/java/com/huawei/esdk/fusionmanager/local/impl/autogen/net/EspPolicyInfo.java | 3458 |
package com.huawei.esdk.fusionmanager.local.impl.autogen.net;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for EspPolicyInfo complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="EspPolicyInfo">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="authAlgorithm" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="encryption" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="lifeTime" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="pFSgroup" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "EspPolicyInfo", namespace = "http://request.model.vpn.soap.business.net.north.galaxmanager.com/xsd", propOrder = {
"authAlgorithm",
"encryption",
"lifeTime",
"pfSgroup"
})
public class EspPolicyInfo {
protected String authAlgorithm;
protected String encryption;
protected Integer lifeTime;
@XmlElement(name = "pFSgroup")
protected String pfSgroup;
/**
* Gets the value of the authAlgorithm property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAuthAlgorithm() {
return authAlgorithm;
}
/**
* Sets the value of the authAlgorithm property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAuthAlgorithm(String value) {
this.authAlgorithm = value;
}
/**
* Gets the value of the encryption property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEncryption() {
return encryption;
}
/**
* Sets the value of the encryption property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEncryption(String value) {
this.encryption = value;
}
/**
* Gets the value of the lifeTime property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getLifeTime() {
return lifeTime;
}
/**
* Sets the value of the lifeTime property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setLifeTime(Integer value) {
this.lifeTime = value;
}
/**
* Gets the value of the pfSgroup property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPFSgroup() {
return pfSgroup;
}
/**
* Sets the value of the pfSgroup property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPFSgroup(String value) {
this.pfSgroup = value;
}
}
| apache-2.0 |
wind-clothes/web-common | src/main/java/com/web/common/web/common/study/Nio/Acceptor.java | 257 | package com.web.common.web.common.study.Nio;
/**
* <pre>
* </pre>
* @author: chengweixiong@uworks.cc
* @date: 2016年7月27日 下午2:58:50
*/
public class Acceptor implements Runnable {
@Override
public void run() {
}
}
| apache-2.0 |
mikewalch/accumulo | test/src/main/java/org/apache/accumulo/test/mapreduce/AccumuloOutputFormatIT.java | 6004 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.accumulo.test.mapreduce;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map.Entry;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.BatchWriterConfig;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.client.mapreduce.AccumuloInputFormat;
import org.apache.accumulo.core.client.mapreduce.AccumuloOutputFormat;
import org.apache.accumulo.core.client.security.tokens.AuthenticationToken;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.harness.AccumuloClusterHarness;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.junit.Test;
public class AccumuloOutputFormatIT extends AccumuloClusterHarness {
private static AssertionError e1 = null;
private static class MRTester extends Configured implements Tool {
private static class TestMapper extends Mapper<Key,Value,Text,Mutation> {
Key key = null;
int count = 0;
@Override
protected void map(Key k, Value v, Context context) throws IOException, InterruptedException {
try {
if (key != null)
assertEquals(key.getRow().toString(), new String(v.get()));
assertEquals(k.getRow(), new Text(String.format("%09x", count + 1)));
assertEquals(new String(v.get()), String.format("%09x", count));
} catch (AssertionError e) {
e1 = e;
}
key = new Key(k);
count++;
}
@Override
protected void cleanup(Context context) throws IOException, InterruptedException {
Mutation m = new Mutation("total");
m.put("", "", Integer.toString(count));
context.write(new Text(), m);
}
}
@Override
public int run(String[] args) throws Exception {
if (args.length != 2) {
throw new IllegalArgumentException("Usage : " + MRTester.class.getName() + " <inputtable> <outputtable>");
}
String user = getAdminPrincipal();
AuthenticationToken pass = getAdminToken();
String table1 = args[0];
String table2 = args[1];
Job job = Job.getInstance(getConf(), this.getClass().getSimpleName() + "_" + System.currentTimeMillis());
job.setJarByClass(this.getClass());
job.setInputFormatClass(AccumuloInputFormat.class);
AccumuloInputFormat.setConnectorInfo(job, user, pass);
AccumuloInputFormat.setInputTableName(job, table1);
AccumuloInputFormat.setZooKeeperInstance(job, getCluster().getClientConfig());
job.setMapperClass(TestMapper.class);
job.setMapOutputKeyClass(Key.class);
job.setMapOutputValueClass(Value.class);
job.setOutputFormatClass(AccumuloOutputFormat.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Mutation.class);
AccumuloOutputFormat.setConnectorInfo(job, user, pass);
AccumuloOutputFormat.setCreateTables(job, false);
AccumuloOutputFormat.setDefaultTableName(job, table2);
AccumuloOutputFormat.setZooKeeperInstance(job, getCluster().getClientConfig());
job.setNumReduceTasks(0);
job.waitForCompletion(true);
return job.isSuccessful() ? 0 : 1;
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
conf.set("mapreduce.framework.name", "local");
conf.set("mapreduce.cluster.local.dir", new File(System.getProperty("user.dir"), "target/mapreduce-tmp").getAbsolutePath());
assertEquals(0, ToolRunner.run(conf, new MRTester(), args));
}
}
@Test
public void testMR() throws Exception {
String[] tableNames = getUniqueNames(2);
String table1 = tableNames[0];
String table2 = tableNames[1];
Connector c = getConnector();
c.tableOperations().create(table1);
c.tableOperations().create(table2);
BatchWriter bw = c.createBatchWriter(table1, new BatchWriterConfig());
for (int i = 0; i < 100; i++) {
Mutation m = new Mutation(new Text(String.format("%09x", i + 1)));
m.put(new Text(), new Text(), new Value(String.format("%09x", i).getBytes()));
bw.addMutation(m);
}
bw.close();
MRTester.main(new String[] {table1, table2});
assertNull(e1);
try (Scanner scanner = c.createScanner(table2, new Authorizations())) {
Iterator<Entry<Key,Value>> iter = scanner.iterator();
assertTrue(iter.hasNext());
Entry<Key,Value> entry = iter.next();
assertEquals(Integer.parseInt(new String(entry.getValue().get())), 100);
assertFalse(iter.hasNext());
}
}
}
| apache-2.0 |
dremio/dremio-oss | plugins/hive/src/main/java/com/dremio/exec/store/hive/exec/FSInputStreamWrapper.java | 2237 | /*
* Copyright (C) 2017-2019 Dremio Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dremio.exec.store.hive.exec;
import java.io.IOException;
import java.io.InputStream;
import org.apache.hadoop.fs.PositionedReadable;
import org.apache.hadoop.fs.Seekable;
import com.dremio.io.FSInputStream;
/**
* Wraps the FSInputStream so that it can be used to construct a FSDataInputStream
* which needs a seekable stream as source.
*/
public class FSInputStreamWrapper extends InputStream implements Seekable, PositionedReadable {
private final FSInputStream fsInputStream;
public FSInputStreamWrapper(FSInputStream fsInputStream) {
this.fsInputStream = fsInputStream;
}
@Override
public int read() throws IOException {
return fsInputStream.read();
}
@Override
public int read(long position, byte[] bytes, int offset, int length) throws IOException {
fsInputStream.setPosition(position);
return fsInputStream.read(bytes, offset, length);
}
@Override
public void readFully(long position, byte[] bytes, int offset, int length) throws IOException {
fsInputStream.setPosition(position);
fsInputStream.read(bytes, offset, length);
}
@Override
public void readFully(long position, byte[] bytes) throws IOException {
fsInputStream.setPosition(position);
fsInputStream.read(bytes);
}
@Override
public void seek(long position) throws IOException {
fsInputStream.setPosition(position);
}
@Override
public long getPos() throws IOException {
return fsInputStream.getPosition();
}
@Override
public boolean seekToNewSource(long position) throws IOException {
fsInputStream.setPosition(position);
return true;
}
}
| apache-2.0 |
bleidi/mars | mars-domain/src/main/java/me/bleidi/mars/domain/Main.java | 890 | package me.bleidi.mars.domain;
import java.awt.Point;
import java.util.Scanner;
import me.bleidi.mars.domain.sonda.Direcao;
import me.bleidi.mars.domain.sonda.Sonda;
import me.bleidi.mars.domain.terreno.Planalto;
public class Main {
public static void main(String[] args) {
try(Scanner scanner = new Scanner(System.in)){
int x = scanner.nextInt();
int y = scanner.nextInt();
Planalto planalto = new Planalto(x, y);
while(scanner.hasNext()){
x = scanner.nextInt();
y = scanner.nextInt();
Direcao direcao = Direcao.of(scanner.nextLine().trim().charAt(0));
Sonda sonda = new Sonda();
sonda.pousar(new Point(x,y), direcao);
String fila = scanner.nextLine();
fila.chars().mapToObj(i -> (char)i).forEach(c -> sonda.executar(c));
System.out.println(sonda);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
| apache-2.0 |
andrus/linkrest-emberjs | linkrest-emberjs/src/main/java/org/objectstyle/linkrest/emberjs/EmberJSSimpleResponseWriter.java | 2380 | package org.objectstyle.linkrest.emberjs;
import com.fasterxml.jackson.core.JsonGenerator;
import com.nhl.link.rest.SimpleResponse;
import com.nhl.link.rest.runtime.LinkRestRuntime;
import com.nhl.link.rest.runtime.jackson.IJacksonService;
import com.nhl.link.rest.runtime.jackson.JsonConvertable;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Configuration;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
public class EmberJSSimpleResponseWriter implements MessageBodyWriter<SimpleResponse> {
private IJacksonService jacksonService;
@Context
private Configuration configuration;
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return SimpleResponse.class.isAssignableFrom(type);
}
@Override
public long getSize(SimpleResponse simpleResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return -1;
}
@Override
public void writeTo(SimpleResponse simpleResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
getJacksonService().outputJson(new JsonConvertable() {
@Override
public void generateJSON(JsonGenerator out) throws IOException {
out.writeStartObject();
if (!simpleResponse.isSuccess()) {
out.writeFieldName("errors");
out.writeStartObject();
if (simpleResponse.getMessage() != null) {
out.writeStringField("msg", simpleResponse.getMessage());
}
out.writeEndObject();
}
out.writeEndObject();
}
}, entityStream);
}
private IJacksonService getJacksonService() {
if (jacksonService == null) {
jacksonService = LinkRestRuntime.service(IJacksonService.class, configuration);
}
return jacksonService;
}
}
| apache-2.0 |
a1018875550/PermissionDispatcher | processor/src/main/java/org/jokar/permissiondispatcher/processor/utils/ValidatorUtils.java | 5598 | package org.jokar.permissiondispatcher.processor.utils;
import org.jokar.permissiondispatcher.processor.RuntimePermissionsElement;
import org.jokar.permissiondispatcher.processor.event.ClassType;
import org.jokar.permissiondispatcher.processor.event.TypeResolver;
import org.jokar.permissiondispatcher.processor.exception.DuplicatedValueException;
import org.jokar.permissiondispatcher.processor.exception.MixPermissionTypeException;
import org.jokar.permissiondispatcher.processor.exception.NoAnnotatedMethodsException;
import org.jokar.permissiondispatcher.processor.exception.NoParametersAllowedException;
import org.jokar.permissiondispatcher.processor.exception.NoThrowsAllowedException;
import org.jokar.permissiondispatcher.processor.exception.PrivateMethodException;
import org.jokar.permissiondispatcher.processor.exception.WrongClassException;
import org.jokar.permissiondispatcher.processor.exception.WrongParametersException;
import org.jokar.permissiondispatcher.processor.exception.WrongReturnTypeException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeKind;
import static org.jokar.permissiondispatcher.processor.event.ClassType.getClassType;
import static org.jokar.permissiondispatcher.processor.utils.ProcessorUtil.getValueFromAnnotation;
import static org.jokar.permissiondispatcher.processor.utils.ProcessorUtil.isEmpty;
/**
* Created by JokAr on 16/8/23.
*/
public final class ValidatorUtils {
private static String WRITE_SETTINGS = "android.permission.WRITE_SETTINGS";
private static String SYSTEM_ALERT_WINDOW = "android.permission.SYSTEM_ALERT_WINDOW";
public static ClassType checkActivity(TypeElement element, TypeResolver resolver) {
ClassType classType = getClassType(element.getQualifiedName().toString(), resolver);
if (classType == null) {
throw new WrongClassException(element);
}
return classType;
}
public static void checkNotEmpty(List<ExecutableElement> elements, RuntimePermissionsElement element,
Class clazz) {
if (isEmpty(elements)) {
throw new NoAnnotatedMethodsException(element, clazz);
}
}
public static void checkPrivateMethods(List<ExecutableElement> elements, Class clazz) {
for (ExecutableElement element : elements) {
if (element.getModifiers().contains(Modifier.PRIVATE)) {
throw new PrivateMethodException(element, clazz);
}
}
}
/**
* Checks the return type of the elements in the provided list.
* <p/>
* Raises an exception if any element specifies a return type other than 'void'.
*/
public static void checkMethodSignature(List<ExecutableElement> elements) {
for (ExecutableElement element : elements) {
// Allow 'void' return type only
if (element.getReturnType().getKind() != TypeKind.VOID) {
throw new WrongReturnTypeException(element);
}
// Allow methods without 'throws' declaration only
if (!element.getThrownTypes().isEmpty()) {
throw new NoThrowsAllowedException(element);
}
}
}
/**
* Checks the elements in the provided list annotated with an annotation against duplicate values.
* <p/>
* Raises an exception if any annotation value is found multiple times.
*/
public static void checkDuplicatedValue(List<ExecutableElement> elements, Class clazz) {
Set<String> values = new HashSet<>();
for (ExecutableElement method : elements) {
List<String> value = getValueFromAnnotation(method, clazz);
if (!values.addAll(value)) {
throw new DuplicatedValueException(value, method, clazz);
}
}
}
public static void checkMethodParameters(List<ExecutableElement> elements, int methodCount,
String clazz, TypeResolver classType) {
for (ExecutableElement element : elements) {
List<? extends VariableElement> parameters = element.getParameters();
if (methodCount == 0 && !parameters.isEmpty()) {
throw new NoParametersAllowedException(element);
}
if (parameters.size() != methodCount) {
throw new WrongParametersException(element, clazz);
}
for (VariableElement variableElement : parameters) {
if (!classType.isSameType(variableElement.asType(), classType.typeMirrorOf(clazz))) {
throw new WrongParametersException(element, clazz);
}
}
}
}
public static void checkMixPermissionType(List<ExecutableElement> elements, Class clazz) {
for (ExecutableElement element : elements) {
List valueFromAnnotation = getValueFromAnnotation(element, clazz);
if (valueFromAnnotation.size() > 1) {
if (valueFromAnnotation.contains(WRITE_SETTINGS)) {
throw new MixPermissionTypeException(element, WRITE_SETTINGS);
} else if (valueFromAnnotation.contains(SYSTEM_ALERT_WINDOW)) {
throw new MixPermissionTypeException(element, SYSTEM_ALERT_WINDOW);
}
}
}
}
}
| apache-2.0 |
inbloom/secure-data-service | tools/csv2xml/src/org/slc/sli/sample/entities/GradeLevelsType.java | 2957 | /*
* Copyright 2012-2013 inBloom, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// 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: 2012.04.20 at 03:09:04 PM EDT
//
package org.slc.sli.sample.entities;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* The enumerated collection for specifying one or more grade levels.
*
* <p>Java class for GradeLevelsType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="GradeLevelsType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="GradeLevel" type="{http://ed-fi.org/0100}GradeLevelType" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "GradeLevelsType", propOrder = {
"gradeLevel"
})
public class GradeLevelsType {
@XmlElement(name = "GradeLevel", required = true)
protected List<GradeLevelType> gradeLevel;
/**
* Gets the value of the gradeLevel 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 gradeLevel property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getGradeLevel().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link GradeLevelType }
*
*
*/
public List<GradeLevelType> getGradeLevel() {
if (gradeLevel == null) {
gradeLevel = new ArrayList<GradeLevelType>();
}
return this.gradeLevel;
}
}
| apache-2.0 |
maheshika/carbon-mediation | components/mediation-ui/org.wso2.carbon.priority.executors.ui/src/main/java/org/wso2/carbon/priority/executors/ui/Executor.java | 10161 | /**
* Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.carbon.priority.executors.ui;
import org.apache.axiom.om.*;
import org.apache.axis2.AxisFault;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.SynapseConstants;
import javax.xml.namespace.QName;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
public class Executor {
private Log log = LogFactory.getLog(Executor.class);
public static final QName NAME_ATT = new QName(ExecutorConstants.NAME);
public static final QName CLASS_ATT = new QName("class");
public static final QName ATT_NAME = new QName(ExecutorConstants.NAME);
public static final QName ATT_VALUE = new QName(ExecutorConstants.VALUE);
public static final QName SIZE_ATT = new QName(ExecutorConstants.SIZE);
public static final QName PRIORITY_ATT = new QName(ExecutorConstants.PRIORITY);
public static final QName IS_FIXED_ATT = new QName(ExecutorConstants.IS_FIXED_SIZE);
public static final QName BEFORE_EXECUTE_HANDLER =
new QName(ExecutorConstants.BEFORE_EXECUTE_HANDLER);
public static final QName NEXT_QUEUE_ATT = new QName(ExecutorConstants.NEXT_QUEUE);
public static final QName MAX_ATT = new QName(ExecutorConstants.MAX);
public static final QName CORE_ATT = new QName(ExecutorConstants.CORE);
public static final QName KEEP_ALIVE_ATT = new QName(ExecutorConstants.KEEP_ALIVE);
private int core = 20;
private int max = 100;
private int keepAlive = 5;
private List<Queue> queues = new ArrayList<Queue>();
private String algorithm = null;
private String beforeExecuteHandler = null;
private String name = "";
private boolean isFixedSize = true;
public static final String NAMESPACE = SynapseConstants.SYNAPSE_NAMESPACE;
public void build(OMElement e) throws AxisFault {
QName queuesQName = createQname(NAMESPACE, ExecutorConstants.QUEUES);
QName queueQName = createQname(NAMESPACE, ExecutorConstants.QUEUE);
QName threadsQName = createQname(NAMESPACE, ExecutorConstants.THREADS);
OMAttribute nameAtt = e.getAttribute(NAME_ATT);
if (nameAtt != null && !"".equals(nameAtt.getAttributeValue())) {
setName(nameAtt.getAttributeValue());
}
// set the handler for calling before the message is put in to the queue
OMAttribute handlerAtt = e.getAttribute(BEFORE_EXECUTE_HANDLER);
if (handlerAtt != null) {
beforeExecuteHandler = handlerAtt.getAttributeValue();
}
// create the queue configuration
OMElement queuesEle = e.getFirstChildWithName(queuesQName);
if (queuesEle != null) {
OMAttribute nextQueueAtt = queuesEle.getAttribute(NEXT_QUEUE_ATT);
if (nextQueueAtt != null) {
algorithm = nextQueueAtt.getAttributeValue();
}
OMAttribute fixedSizeAtt = queuesEle.getAttribute(IS_FIXED_ATT);
if (fixedSizeAtt != null) {
isFixedSize = Boolean.parseBoolean(fixedSizeAtt.getAttributeValue());
}
// create the queue configuration
this.queues = createQueues(queueQName, queuesEle, isFixedSize);
} else {
handlerException("Queues configuration is mandatory");
}
OMElement threadsEle = e.getFirstChildWithName(threadsQName);
if (threadsEle != null) {
OMAttribute maxAttr = threadsEle.getAttribute(MAX_ATT);
if (maxAttr != null) {
setMax(Integer.parseInt(maxAttr.getAttributeValue()));
}
OMAttribute coreAttr = threadsEle.getAttribute(CORE_ATT);
if (coreAttr != null) {
setCore(Integer.parseInt(coreAttr.getAttributeValue()));
}
OMAttribute keepAliveAttr = threadsEle.getAttribute(KEEP_ALIVE_ATT);
if (keepAliveAttr != null) {
setKeepAlive(Integer.parseInt(keepAliveAttr.getAttributeValue()));
}
}
}
public OMElement serialize() {
OMFactory fac = OMAbstractFactory.getOMFactory();
OMNamespace nullNS = fac.createOMNamespace("", "");
OMElement executorElement = createElement(ExecutorConstants.PRIORITY_EXECUTOR, NAMESPACE);
if (name != null) {
executorElement.addAttribute(fac.createOMAttribute(ExecutorConstants.NAME,
nullNS, name));
}
if (beforeExecuteHandler != null) {
executorElement.addAttribute(fac.createOMAttribute(
ExecutorConstants.BEFORE_EXECUTE_HANDLER, nullNS,
beforeExecuteHandler));
}
// create the queues configuration
OMElement queuesEle = createElement(ExecutorConstants.QUEUES, NAMESPACE);
if (algorithm != null) {
queuesEle.addAttribute(fac.createOMAttribute(ExecutorConstants.NEXT_QUEUE, nullNS,
algorithm));
}
if (!isFixedSize) {
queuesEle.addAttribute(fac.createOMAttribute(ExecutorConstants.IS_FIXED_SIZE,
nullNS, Boolean.toString(false)));
}
for (Queue intQueue : queues) {
OMElement queueEle = createElement(ExecutorConstants.QUEUE, NAMESPACE);
if (isFixedSize) {
queueEle.addAttribute(fac.createOMAttribute(ExecutorConstants.SIZE, nullNS,
Integer.toString(intQueue.getCapacity())));
}
queueEle.addAttribute(fac.createOMAttribute(ExecutorConstants.PRIORITY, nullNS,
Integer.toString(intQueue.getPriority())));
queuesEle.addChild(queueEle);
}
executorElement.addChild(queuesEle);
// create the Threads configuration
OMElement threadsEle = createElement(ExecutorConstants.THREADS, NAMESPACE);
threadsEle.addAttribute(fac.createOMAttribute(
ExecutorConstants.MAX, nullNS, Integer.toString(max)));
threadsEle.addAttribute(fac.createOMAttribute(
ExecutorConstants.CORE, nullNS, Integer.toString(core)));
threadsEle.addAttribute(fac.createOMAttribute(
ExecutorConstants.KEEP_ALIVE, nullNS, Integer.toString(keepAlive)));
executorElement.addChild(threadsEle);
return executorElement;
}
private List<Queue> createQueues(
QName qQName, OMElement queuesEle, boolean isFixedSize) throws AxisFault {
List<Queue> internalQueues =
new ArrayList<Queue>();
Iterator it = queuesEle.getChildrenWithName(qQName);
while (it.hasNext()) {
int s = 0;
int p = 0;
OMElement qElement = (OMElement) it.next();
String size = qElement.getAttributeValue(SIZE_ATT);
String priority = qElement.getAttributeValue(PRIORITY_ATT);
if (priority != null) {
p = Integer.parseInt(priority);
} else {
handlerException("Priority must be specified");
}
if (size != null) {
s = Integer.parseInt(size);
} else if (isFixedSize) {
handlerException("Queues should have a " + ExecutorConstants.SIZE);
}
Queue queue;
if (isFixedSize) {
queue = new Queue(p, s);
} else {
queue = new Queue(p);
}
internalQueues.add(queue);
}
return internalQueues;
}
private void handlerException(String s) throws AxisFault {
log.error(s);
throw new AxisFault(s);
}
private static QName createQname(String namespace, String name) {
if (namespace == null) {
return new QName(name);
}
return new QName(namespace, name);
}
private static OMElement createElement(String name, String namespace) {
OMFactory fac = OMAbstractFactory.getOMFactory();
if (namespace == null) {
return fac.createOMElement(new QName(name));
}
OMNamespace omNamespace = fac.createOMNamespace(namespace, "");
return fac.createOMElement(name, omNamespace);
}
public int getCore() {
return core;
}
public int getMax() {
return max;
}
public int getKeepAlive() {
return keepAlive;
}
public String getAlgorithm() {
return algorithm;
}
public String getBeforeExecuteHandler() {
return beforeExecuteHandler;
}
public void setCore(int core) {
this.core = core;
}
public void setMax(int max) {
this.max = max;
}
public void setKeepAlive(int keep_alive) {
this.keepAlive = keep_alive;
}
public void setAlgorithm(String algorithm) {
this.algorithm = algorithm;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setBeforeExecuteHandler(String beforeExecuteHandler) {
this.beforeExecuteHandler = beforeExecuteHandler;
}
public List<Queue> getQueues() {
return queues;
}
public void setQueues(List<Queue> queues) {
this.queues = queues;
}
public boolean isFixedSize() {
return isFixedSize;
}
public void setFixedSize(boolean fixedSize) {
isFixedSize = fixedSize;
}
}
| apache-2.0 |
btcontract/lnwallet | app/src/main/java/com/thesurix/gesturerecycler/GestureManager.java | 7269 | package com.thesurix.gesturerecycler;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
/**
* Class that is responsible for gesture management for {@link RecyclerView} widget.
* @author thesurix
*/
public class GestureManager {
private GestureTouchHelperCallback mTouchHelperCallback;
private GestureManager(final Builder builder) {
final GestureAdapter adapter = (GestureAdapter) builder.recyclerView.getAdapter();
mTouchHelperCallback = new GestureTouchHelperCallback(adapter);
mTouchHelperCallback.setSwipeEnabled(builder.isSwipeEnabled);
mTouchHelperCallback.setLongPressDragEnabled(builder.isDragEnabled);
mTouchHelperCallback.setManualDragEnabled(builder.isManualDragEnabled);
final ItemTouchHelper touchHelper = new ItemTouchHelper(mTouchHelperCallback);
touchHelper.attachToRecyclerView(builder.recyclerView);
adapter.setGestureListener(new GestureListener(touchHelper));
if (builder.swipeFlags == Builder.INVALID_FLAG) {
mTouchHelperCallback.setSwipeFlagsForLayout(builder.recyclerView.getLayoutManager());
} else {
mTouchHelperCallback.setSwipeFlags(builder.swipeFlags);
}
if (builder.dragFlags == Builder.INVALID_FLAG) {
mTouchHelperCallback.setDragFlagsForLayout(builder.recyclerView.getLayoutManager());
} else {
mTouchHelperCallback.setDragFlags(builder.dragFlags);
}
}
/**
* Sets swipe gesture enabled or disabled.
* @param enabled true to enable, false to disable
*/
public void setSwipeEnabled(final boolean enabled) {
mTouchHelperCallback.setSwipeEnabled(enabled);
}
/**
* Sets long press drag gesture enabled or disabled.
* @param enabled true to enable, false to disable
*/
public void setLongPressDragEnabled(final boolean enabled) {
mTouchHelperCallback.setLongPressDragEnabled(enabled);
}
/**
* Sets manual drag gesture enabled or disabled.
* @param enabled true to enable, false to disable
*/
public void setManualDragEnabled(final boolean enabled) {
mTouchHelperCallback.setManualDragEnabled(enabled);
}
/**
* Returns true if swipe is enabled, false if swipe is disabled.
* @return swipe state
*/
public boolean isSwipeEnabled() {
return mTouchHelperCallback.isItemViewSwipeEnabled();
}
/**
* Returns true if long press drag is enabled, false if long press drag is disabled.
* @return long press drag state
*/
public boolean isLongPressDragEnabled() {
return mTouchHelperCallback.isLongPressDragEnabled();
}
/**
* Returns true if manual drag is enabled, false if manual drag is disabled.
* @return manual drag state
*/
public boolean isManualDragEnabled() {
return mTouchHelperCallback.isManualDragEnabled();
}
/**
* Class that builds {@link GestureManager} instance.
*/
public static class Builder{
private static final int INVALID_FLAG = -1;
private RecyclerView recyclerView;
private int swipeFlags = INVALID_FLAG;
private int dragFlags = INVALID_FLAG;
private boolean isSwipeEnabled;
private boolean isDragEnabled;
private boolean isManualDragEnabled;
/**
* Constructs {@link GestureManager} for the given RecyclerView.
* @param recyclerView RecyclerView instance
*/
public Builder(@NonNull final RecyclerView recyclerView) {
this.recyclerView = recyclerView;
}
/**
* Sets swipe gesture enabled or disabled.
* Swipe is disabled by default.
* @param enabled true to enable, false to disable
* @return returns builder instance
*/
public Builder setSwipeEnabled(final boolean enabled) {
isSwipeEnabled = enabled;
return this;
}
/**
* Sets long press drag gesture enabled or disabled.
* Long press drag is disabled by default.
* @param enabled true to enable, false to disable
* @return returns builder instance
*/
public Builder setLongPressDragEnabled(final boolean enabled) {
isDragEnabled = enabled;
return this;
}
/**
* Sets manual drag gesture enabled or disabled.
* Manual drag is disabled by default.
* @param enabled true to enable, false to disable
* @return returns builder instance
*/
public Builder setManualDragEnabled(final boolean enabled) {
isManualDragEnabled = enabled;
return this;
}
/**
* Sets flags for swipe and drag gesture. Do not set this flags if you want predefined flags for RecyclerView layout manager.
* See {@link ItemTouchHelper} flags.
*
* This method is deprecated, use {@link #setDragFlags(int)} or {@link #setSwipeFlags(int)}.
* @param swipeFlags flags for swipe gesture
* @param dragFlags flags for drag gesture
* @return returns builder instance
*/
@Deprecated
public Builder setGestureFlags(final int swipeFlags, final int dragFlags) {
this.swipeFlags = swipeFlags;
this.dragFlags = dragFlags;
return this;
}
/**
* Sets flags for swipe gesture. Do not set this flags if you want predefined flags for RecyclerView layout manager.
* See {@link ItemTouchHelper} flags.
* @param flags flags for swipe gesture
* @return returns builder instance
*/
public Builder setSwipeFlags(final int flags) {
swipeFlags = flags;
return this;
}
/**
* Sets flags for drag gesture. Do not set this flags if you want predefined flags for RecyclerView layout manager.
* See {@link ItemTouchHelper} flags.
* @param flags flags for drag gesture
* @return returns builder instance
*/
public Builder setDragFlags(final int flags) {
dragFlags = flags;
return this;
}
/**
* Builds {@link GestureManager} instance.
* @return returns GestureManager instance
*/
public GestureManager build() {
validateBuilder();
return new GestureManager(this);
}
private void validateBuilder() {
final boolean hasAdapter = recyclerView.getAdapter() instanceof GestureAdapter;
if (!hasAdapter) {
throw new IllegalArgumentException("RecyclerView does not have adapter that extends " + GestureAdapter.class.getName());
}
if (swipeFlags == INVALID_FLAG || dragFlags == INVALID_FLAG) {
if (recyclerView.getLayoutManager() == null) {
throw new IllegalArgumentException("No layout manager for RecyclerView. Provide custom flags or attach layout manager to RecyclerView.");
}
}
}
}
}
| apache-2.0 |
afs/rdf-delta | rdf-patch/src/main/java/org/seaborne/patch/RDFPatch.java | 1412 | /*
* 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.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*/
package org.seaborne.patch;
import org.apache.jena.graph.Node;
public interface RDFPatch {
// Long name - not preferred.
static final String PREVIOUS = "previous";
public PatchHeader header();
public default Node getHeader(String field) {
return header().get(field) ;
}
public default Node getId() {
return header().get(RDFPatchConst.ID);
}
public default Node getPrevious() {
Node n = header().get(RDFPatchConst.PREV);
if ( n == null )
n = header().get(PREVIOUS);
return n;
}
/** Act on the patch by sending it to a changes processor. */
public void apply(RDFChanges changes);
public boolean repeatable();
}
| apache-2.0 |
timstoner/stackexchangeimporter | src/main/java/com/example/stackexchange/cache/LinkTypeCacheLoader.java | 534 | package com.example.stackexchange.cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.example.stackexchange.entity.LinkType;
import com.example.stackexchange.repo.LinkTypeRepository;
import com.google.common.cache.CacheLoader;
@Component
public class LinkTypeCacheLoader extends CacheLoader<Long, LinkType> {
@Autowired
private LinkTypeRepository repo;
@Override
public LinkType load(Long key) throws Exception {
return repo.findOne(key);
}
}
| apache-2.0 |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/scanner/writer/S3ScanWriter.java | 13933 | package com.bazaarvoice.emodb.web.scanner.writer;
import com.amazonaws.AmazonClientException;
import com.amazonaws.event.ProgressEvent;
import com.amazonaws.event.ProgressListener;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.util.BinaryUtils;
import com.bazaarvoice.emodb.web.scanner.ScanUploadService;
import com.codahale.metrics.MetricRegistry;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.hash.Hashing;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.time.Duration;
import java.util.Iterator;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
/**
* ScanWriter implementation which uploads files to S3.
*/
public class S3ScanWriter extends TemporaryFileScanWriter {
private static final Duration DEFAULT_RETRY_DELAY = Duration.ofSeconds(5);
private static final int MAX_RETRIES = 3;
private static final Logger _log = LoggerFactory.getLogger(S3ScanWriter.class);
private final AmazonS3 _amazonS3;
private final ScheduledExecutorService _uploadService;
private final Set<ActiveUpload> _activeUploads = Sets.newSetFromMap(Maps.newConcurrentMap());
private Duration _retryDelay = DEFAULT_RETRY_DELAY;
@Inject
public S3ScanWriter(@Assisted int taskId, @Assisted URI baseUri, @Assisted Optional<Integer> maxOpenShards,
MetricRegistry metricRegistry, AmazonS3Provider amazonS3Provider,
@ScanUploadService ScheduledExecutorService uploadService, ObjectMapper objectMapper) {
super("s3", taskId, baseUri, Compression.GZIP, metricRegistry, maxOpenShards, objectMapper);
requireNonNull(amazonS3Provider, "amazonS3Provider is required");
String bucket = baseUri.getHost();
checkArgument(!Strings.isNullOrEmpty(bucket), "bucket is required");
_amazonS3 = amazonS3Provider.getS3ClientForBucket(bucket);
_uploadService = requireNonNull(uploadService, "uploadService is required");
}
public void setRetryDelay(Duration retryDelay) {
_retryDelay = retryDelay;
}
@Override
protected ListenableFuture<?> transfer(TransferKey transferKey, URI uri, File file) {
ActiveUpload activeUpload = new ActiveUpload(transferKey, uri, file);
ActiveUploadRunner runner = new ActiveUploadRunner(activeUpload);
return runner.start();
}
/**
* Callable class to perform an active upload and get metadata about the progress.
*/
private class ActiveUpload {
private final TransferKey _transferKey;
private final URI _uri;
private final String _bucket;
private final String _key;
private final File _file;
private int _attempts = 0;
private long _bytesTransferred = 0;
private Future<?> _uploadFuture;
private SettableFuture<String> _resultFuture;
ActiveUpload(TransferKey transferKey, URI uri, File file) {
_transferKey = transferKey;
_uri = uri;
_bucket = uri.getHost();
_key = getKeyFromPath(uri);
_file = file;
}
/**
* Starts an asynchronous upload and returns a ListenableFuture for handling the result.
*/
synchronized ListenableFuture<String> upload() {
// Reset values from possible prior attempt
_attempts += 1;
_bytesTransferred = 0;
// Separate the future returned to the caller from the future generated by submitting the
// putObject request. If the writer is closed then uploadFuture may be canceled before it executes,
// in which case it may not trigger any callbacks. To ensure there is always a callback resultFuture is
// tracked independently and, in the event that the upload is aborted, gets set on abort().
_resultFuture = SettableFuture.create();
_uploadFuture = _uploadService.submit(new Runnable() {
@Override
public void run() {
try {
ProgressListener progressListener = new ProgressListener() {
@Override
public void progressChanged(ProgressEvent progressEvent) {
// getBytesTransferred() returns zero for all events not pertaining to the file transfer
_bytesTransferred += progressEvent.getBytesTransferred();
}
};
PutObjectRequest putObjectRequest = new PutObjectRequest(_bucket, _key, _file);
putObjectRequest.setGeneralProgressListener(progressListener);
PutObjectResult result = _amazonS3.putObject(putObjectRequest);
_resultFuture.set(result.getETag());
} catch (Throwable t) {
_resultFuture.setException(t);
}
}
});
return _resultFuture;
}
synchronized TransferStatus getTransferStatus() {
return new TransferStatus(_transferKey, _file.length(), _attempts, _bytesTransferred);
}
synchronized void abort() {
// uploadFuture and resultFuture are set atomically so only need to null check for one.
if (_uploadFuture != null) {
try {
_resultFuture.setException(new IOException("Writer closed"));
_uploadFuture.cancel(true);
} finally {
_uploadFuture = null;
_resultFuture = null;
}
}
}
private URI getUri() {
return _uri;
}
private File getFile() {
return _file;
}
private int getAttempts() {
return _attempts;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ActiveUpload)) {
return false;
}
ActiveUpload that = (ActiveUpload) o;
return _transferKey.equals(that._transferKey);
}
@Override
public int hashCode() {
return _transferKey.hashCode();
}
}
/**
* Runnable for executing ActiveUploads and handling asynchronous callbacks.
*/
private class ActiveUploadRunner implements Runnable, FutureCallback<String> {
private final ActiveUpload _activeUpload;
private final SettableFuture<String> _finalFuture;
private ActiveUploadRunner(ActiveUpload activeUpload) {
_activeUpload = activeUpload;
_finalFuture = SettableFuture.create();
}
private ListenableFuture<String> start() {
// Since run() asynchronously starts the upload process starting the running is effectively
// just calling run() synchronously and returning the final future.
run();
return _finalFuture;
}
@Override
public void run() {
if (_closed) {
_finalFuture.setException(new IOException("Writer closed"));
}
ListenableFuture<String> attemptFuture = _activeUpload.upload();
Futures.addCallback(attemptFuture, this);
}
@Override
public void onSuccess(String result) {
_log.debug("Transferring file: id={}, file={}, uri={}... DONE",
_taskId, _activeUpload.getFile(), _activeUpload.getUri());
_activeUploads.remove(_activeUpload);
_finalFuture.set(result);
}
@Override
public void onFailure(Throwable t) {
// If the writer is closed then always propagate the exception immediately and
// don't bother logging a warning.
if (!_closed) {
if (_activeUpload.getAttempts() < MAX_RETRIES) {
try {
_uploadService.schedule(this, _retryDelay.toMillis(), TimeUnit.MILLISECONDS);
_log.debug("Transferring file failed, will retry: id={}, file={}, uri={}...",
_taskId, _activeUpload.getFile(), _activeUpload.getUri(), t);
return;
} catch (Throwable t2) {
// If the reschedule failed for any reason just fall through
// and propagate the exception now.
}
}
_log.warn("Transferring file failed, no more retries: id={}, file={}, uri={}",
_taskId, _activeUpload.getFile(), _activeUpload.getUri(), t);
}
_activeUploads.remove(_activeUpload);
_finalFuture.setException(t);
}
}
@Override
protected Map<TransferKey, TransferStatus> getStatusForActiveTransfers() {
Map<TransferKey, TransferStatus> statusMap = Maps.newHashMap();
for (ActiveUpload activeUpload : _activeUploads) {
TransferStatus transferStatus = activeUpload.getTransferStatus();
statusMap.put(transferStatus.getKey(), transferStatus);
}
return statusMap;
}
@Override
protected boolean writeScanCompleteFile(URI fileUri, byte[] contents)
throws IOException {
String bucket = fileUri.getHost();
String key = getKeyFromPath(fileUri);
try {
// The following will throw an exception unless the file already exists
_amazonS3.getObjectMetadata(bucket, key);
return false;
} catch (AmazonS3Exception e) {
if (e.getStatusCode() != Response.Status.NOT_FOUND.getStatusCode()) {
// Expected case is not found, meaning the file does not exist
// All other cases are some unexpected error
throw new IOException(e);
}
}
uploadContents(bucket, key, contents);
return true;
}
@Override
protected void writeLatestFile(URI fileUri, byte[] contents)
throws IOException {
String bucket = fileUri.getHost();
String key = getKeyFromPath(fileUri);
uploadContents(bucket, key, contents);
}
private String getKeyFromPath(URI uri) {
// S3 does not use leading slashes
String path = uri.getPath();
if (path.startsWith("/")) {
return path.substring(1);
}
return path;
}
private void uploadContents(String bucket, String key, byte[] contents)
throws IOException {
int failures = 0;
boolean uploaded = false;
while (!uploaded) {
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentType(MediaType.TEXT_PLAIN);
objectMetadata.setContentLength(contents.length);
objectMetadata.setContentMD5(BinaryUtils.toBase64(Hashing.md5().hashBytes(contents).asBytes()));
try {
_amazonS3.putObject(
new PutObjectRequest(bucket, key, new ByteArrayInputStream(contents), objectMetadata));
uploaded = true;
} catch (AmazonClientException e) {
if (++failures == MAX_RETRIES) {
throw new IOException(e);
}
try {
Thread.sleep(_retryDelay.toMillis());
} catch (InterruptedException e2) {
// Stop retrying and propagate the original exception
throw new IOException(e);
}
}
}
}
@Override
public void close() {
super.close();
// There is no locking, so continue aborting active uploads until there are none left
int abortedCount = -1;
while (abortedCount != 0) {
abortedCount = 0;
Iterator<ActiveUpload> activeUploadIterator = _activeUploads.iterator();
while (activeUploadIterator.hasNext()) {
ActiveUpload upload = activeUploadIterator.next();
abortedCount += 1;
try {
upload.abort();
} catch (Throwable t) {
// If we fail to stop an existing upload log it but otherwise move on; worse case is that the
// file gets transferred anyway.
_log.warn("Attempt to cancel active upload failed while closing S3ScanWriter: id={}", _taskId, t);
} finally {
activeUploadIterator.remove();
}
}
}
}
}
| apache-2.0 |
itohro/reladomo | reladomo/src/test/java/com/gs/fw/common/mithra/test/TestCrossDatabaseAdhocDeepFetch.java | 5857 | /*
Copyright 2016 Goldman Sachs.
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.gs.fw.common.mithra.test;
import java.sql.Timestamp;
import com.gs.collections.api.block.procedure.Procedure;
import com.gs.collections.api.block.procedure.Procedure2;
import com.gs.collections.api.block.procedure.primitive.ObjectIntProcedure;
import com.gs.fw.common.mithra.test.domain.*;
import junit.framework.TestCase;
import com.gs.fw.common.mithra.MithraManagerProvider;
import com.gs.fw.common.mithra.finder.Operation;
public class TestCrossDatabaseAdhocDeepFetch extends MithraTestAbstract
{
public void testOneToManyOneToOneSameAttributeAdhoc()
{
ParaPositionList nonOpList = getDeepFetchedNonOpList();
assertEquals(9, nonOpList.size());
int count = MithraManagerProvider.getMithraManager().getDatabaseRetrieveCount();
for(ParaPosition p: nonOpList)
{
p.getAccount();
}
assertEquals(count, MithraManagerProvider.getMithraManager().getDatabaseRetrieveCount());
}
public void testForEachForcesResolve()
{
ParaPositionList nonOpList = getDeepFetchedNonOpList();
int count = MithraManagerProvider.getMithraManager().getDatabaseRetrieveCount();
nonOpList.asGscList().forEach(new Procedure<ParaPosition>()
{
@Override
public void value(ParaPosition paraPosition)
{
paraPosition.getAccount();
}
});
// expect 1 extra retrieve for partial cache and 0 for full cache
assertTrue(MithraManagerProvider.getMithraManager().getDatabaseRetrieveCount() <= count + 1);
}
public void testForEachWithIndexForcesResolve()
{
ParaPositionList nonOpList = getDeepFetchedNonOpList();
int count = MithraManagerProvider.getMithraManager().getDatabaseRetrieveCount();
nonOpList.asGscList().forEachWithIndex(new ObjectIntProcedure<ParaPosition>()
{
@Override
public void value(ParaPosition paraPosition, int index)
{
paraPosition.getAccount();
}
});
// expect 1 extra retrieve for partial cache and 0 for full cache
assertTrue(MithraManagerProvider.getMithraManager().getDatabaseRetrieveCount() <= count + 1);
}
public void testForEachWithForcesResolve()
{
ParaPositionList nonOpList = getDeepFetchedNonOpList();
int count = MithraManagerProvider.getMithraManager().getDatabaseRetrieveCount();
nonOpList.asGscList().forEachWith(new Procedure2<ParaPosition, Object>()
{
@Override
public void value(ParaPosition paraPosition, Object o)
{
paraPosition.getAccount();
}
}, new Object());
// expect 1 extra retrieve for partial cache and 0 for full cache
assertTrue(MithraManagerProvider.getMithraManager().getDatabaseRetrieveCount() <= count + 1);
}
private ParaPositionList getDeepFetchedNonOpList()
{
Operation operation = ParaPositionFinder.businessDate().eq(Timestamp.valueOf("2011-09-30 23:59:00.0"));
ParaPositionList nonOpList = new ParaPositionList(ParaPositionFinder.findMany(operation));
nonOpList.deepFetch(ParaPositionFinder.account());
return nonOpList;
}
public void testOneToManyOneToOneSameAttribute()
{
Timestamp businessDate = Timestamp.valueOf("2011-09-30 23:59:00.0");
ParaPositionList list = new ParaPositionList();
for(int i=0;i<2000;i++)
{
ParaPosition pos = new ParaPosition(InfinityTimestamp.getParaInfinity());
pos.setAccountNumber("777"+i);
pos.setAccountSubtype(""+(i % 10));
pos.setBusinessDate(businessDate);
pos.setProductIdentifier("P"+i);
list.add(pos);
}
list.insertAll();
Operation operation = ParaPositionFinder.businessDate().eq(businessDate);
ParaPositionList nonOpList = ParaPositionFinder.findMany(operation);
nonOpList.deepFetch(ParaPositionFinder.account());
assertEquals(2009, nonOpList.size());
int count = MithraManagerProvider.getMithraManager().getDatabaseRetrieveCount();
for(ParaPosition p: nonOpList)
{
p.getAccount();
}
assertEquals(count, MithraManagerProvider.getMithraManager().getDatabaseRetrieveCount());
}
public void testHugeInClauseWithSourelessToSourceDeepFetch() throws Exception
{
ProductList list = new ProductList();
for (int i=0;i<1007;i++)
{
Product product = new Product();
product.setProductId(i);
list.add(product);
}
Timestamp buzDate = new Timestamp(timestampFormat.parse("2010-10-11 00:00:00").getTime());
list.deepFetch(ProductFinder.positions("A", buzDate));
list.forceResolve();
int retrievalCount = getRetrievalCount();
for(int i=0;i<list.size();i++)
{
list.get(i).getPositions("A", buzDate);
}
assertEquals(retrievalCount, getRetrievalCount());
}
} | apache-2.0 |
BUPTAnderson/apache-hive-2.1.1-src | ql/src/java/org/apache/hadoop/hive/ql/hooks/ATSHook.java | 9195 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.hooks;
import java.util.LinkedHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.QueryPlan;
import org.apache.hadoop.hive.ql.QueryState;
import org.apache.hadoop.hive.ql.exec.ExplainTask;
import org.apache.hadoop.hive.ql.exec.TaskFactory;
import org.apache.hadoop.hive.ql.exec.Utilities;
import org.apache.hadoop.hive.ql.plan.ExplainWork;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.yarn.api.records.timeline.TimelineEntity;
import org.apache.hadoop.yarn.api.records.timeline.TimelineEvent;
import org.apache.hadoop.yarn.client.api.TimelineClient;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
/**
* ATSHook sends query + plan info to Yarn App Timeline Server. To enable (hadoop 2.4 and up) set
* hive.exec.pre.hooks/hive.exec.post.hooks/hive.exec.failure.hooks to include this class.
*/
public class ATSHook implements ExecuteWithHookContext {
private static final Logger LOG = LoggerFactory.getLogger(ATSHook.class.getName());
private static final Object LOCK = new Object();
private static final int VERSION = 2;
private static ExecutorService executor;
private static TimelineClient timelineClient;
private enum EntityTypes { HIVE_QUERY_ID };
private enum EventTypes { QUERY_SUBMITTED, QUERY_COMPLETED };
private enum OtherInfoTypes {
QUERY, STATUS, TEZ, MAPRED, INVOKER_INFO, THREAD_NAME, VERSION
};
private enum PrimaryFilterTypes { user, requestuser, operationid };
private static final int WAIT_TIME = 3;
public ATSHook() {
synchronized(LOCK) {
if (executor == null) {
executor = Executors.newSingleThreadExecutor(
new ThreadFactoryBuilder().setDaemon(true).setNameFormat("ATS Logger %d").build());
YarnConfiguration yarnConf = new YarnConfiguration();
timelineClient = TimelineClient.createTimelineClient();
timelineClient.init(yarnConf);
timelineClient.start();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
executor.shutdown();
executor.awaitTermination(WAIT_TIME, TimeUnit.SECONDS);
executor = null;
} catch(InterruptedException ie) { /* ignore */ }
timelineClient.stop();
}
});
}
}
LOG.info("Created ATS Hook");
}
@Override
public void run(final HookContext hookContext) throws Exception {
final long currentTime = System.currentTimeMillis();
final HiveConf conf = new HiveConf(hookContext.getConf());
final QueryState queryState = hookContext.getQueryState();
executor.submit(new Runnable() {
@Override
public void run() {
try {
QueryPlan plan = hookContext.getQueryPlan();
if (plan == null) {
return;
}
String queryId = plan.getQueryId();
String opId = hookContext.getOperationId();
long queryStartTime = plan.getQueryStartTime();
String user = hookContext.getUgi().getUserName();
String requestuser = hookContext.getUserName();
if (hookContext.getUserName() == null ){
requestuser = hookContext.getUgi().getUserName() ;
}
int numMrJobs = Utilities.getMRTasks(plan.getRootTasks()).size();
int numTezJobs = Utilities.getTezTasks(plan.getRootTasks()).size();
if (numMrJobs + numTezJobs <= 0) {
return; // ignore client only queries
}
switch(hookContext.getHookType()) {
case PRE_EXEC_HOOK:
ExplainWork work = new ExplainWork(null,// resFile
null,// pCtx
plan.getRootTasks(),// RootTasks
plan.getFetchTask(),// FetchTask
null,// analyzer
false,// extended
true,// formatted
false,// dependency
false,// logical
false,// authorize
false,// userLevelExplain
null// cboInfo
);
@SuppressWarnings("unchecked")
ExplainTask explain = (ExplainTask) TaskFactory.get(work, conf);
explain.initialize(queryState, plan, null, null);
String query = plan.getQueryStr();
JSONObject explainPlan = explain.getJSONPlan(null, work);
String logID = conf.getLogIdVar(SessionState.get().getSessionId());
fireAndForget(conf, createPreHookEvent(queryId, query, explainPlan, queryStartTime,
user, requestuser, numMrJobs, numTezJobs, opId, logID));
break;
case POST_EXEC_HOOK:
fireAndForget(conf, createPostHookEvent(queryId, currentTime, user, requestuser, true, opId));
break;
case ON_FAILURE_HOOK:
fireAndForget(conf, createPostHookEvent(queryId, currentTime, user, requestuser , false, opId));
break;
default:
//ignore
break;
}
} catch (Exception e) {
LOG.info("Failed to submit plan to ATS: " + StringUtils.stringifyException(e));
}
}
});
}
TimelineEntity createPreHookEvent(String queryId, String query, JSONObject explainPlan,
long startTime, String user, String requestuser, int numMrJobs, int numTezJobs, String opId,
String logID) throws Exception {
JSONObject queryObj = new JSONObject(new LinkedHashMap<>());
queryObj.put("queryText", query);
queryObj.put("queryPlan", explainPlan);
LOG.info("Received pre-hook notification for :" + queryId);
if (LOG.isDebugEnabled()) {
LOG.debug("Otherinfo: " + queryObj.toString());
LOG.debug("Operation id: <" + opId + ">");
}
TimelineEntity atsEntity = new TimelineEntity();
atsEntity.setEntityId(queryId);
atsEntity.setEntityType(EntityTypes.HIVE_QUERY_ID.name());
atsEntity.addPrimaryFilter(PrimaryFilterTypes.user.name(), user);
atsEntity.addPrimaryFilter(PrimaryFilterTypes.requestuser.name(), requestuser);
if (opId != null) {
atsEntity.addPrimaryFilter(PrimaryFilterTypes.operationid.name(), opId);
}
TimelineEvent startEvt = new TimelineEvent();
startEvt.setEventType(EventTypes.QUERY_SUBMITTED.name());
startEvt.setTimestamp(startTime);
atsEntity.addEvent(startEvt);
atsEntity.addOtherInfo(OtherInfoTypes.QUERY.name(), queryObj.toString());
atsEntity.addOtherInfo(OtherInfoTypes.TEZ.name(), numTezJobs > 0);
atsEntity.addOtherInfo(OtherInfoTypes.MAPRED.name(), numMrJobs > 0);
atsEntity.addOtherInfo(OtherInfoTypes.INVOKER_INFO.name(), logID);
atsEntity.addOtherInfo(OtherInfoTypes.THREAD_NAME.name(), Thread.currentThread().getName());
atsEntity.addOtherInfo(OtherInfoTypes.VERSION.name(), VERSION);
return atsEntity;
}
TimelineEntity createPostHookEvent(String queryId, long stopTime, String user, String requestuser, boolean success,
String opId) {
LOG.info("Received post-hook notification for :" + queryId);
TimelineEntity atsEntity = new TimelineEntity();
atsEntity.setEntityId(queryId);
atsEntity.setEntityType(EntityTypes.HIVE_QUERY_ID.name());
atsEntity.addPrimaryFilter(PrimaryFilterTypes.user.name(), user);
atsEntity.addPrimaryFilter(PrimaryFilterTypes.requestuser.name(), requestuser);
if (opId != null) {
atsEntity.addPrimaryFilter(PrimaryFilterTypes.operationid.name(), opId);
}
TimelineEvent stopEvt = new TimelineEvent();
stopEvt.setEventType(EventTypes.QUERY_COMPLETED.name());
stopEvt.setTimestamp(stopTime);
atsEntity.addEvent(stopEvt);
atsEntity.addOtherInfo(OtherInfoTypes.STATUS.name(), success);
return atsEntity;
}
synchronized void fireAndForget(Configuration conf, TimelineEntity entity) throws Exception {
timelineClient.putEntities(entity);
}
}
| apache-2.0 |
justinkwony/ermaster-nhit | org.insightech.er/src/org/insightech/er/editor/controller/command/dbimport/ImportTableCommand.java | 8241 | package org.insightech.er.editor.controller.command.dbimport;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.draw2d.geometry.Insets;
import org.eclipse.draw2d.graph.DirectedGraph;
import org.eclipse.draw2d.graph.DirectedGraphLayout;
import org.eclipse.draw2d.graph.Edge;
import org.eclipse.draw2d.graph.Node;
import org.insightech.er.editor.controller.command.diagram_contents.element.node.AbstractCreateElementCommand;
import org.insightech.er.editor.model.ERDiagram;
import org.insightech.er.editor.model.diagram_contents.DiagramContents;
import org.insightech.er.editor.model.diagram_contents.element.connection.Bendpoint;
import org.insightech.er.editor.model.diagram_contents.element.connection.ConnectionElement;
import org.insightech.er.editor.model.diagram_contents.element.connection.Relation;
import org.insightech.er.editor.model.diagram_contents.element.node.Location;
import org.insightech.er.editor.model.diagram_contents.element.node.NodeElement;
import org.insightech.er.editor.model.diagram_contents.element.node.table.TableView;
import org.insightech.er.editor.model.diagram_contents.element.node.table.column.NormalColumn;
import org.insightech.er.editor.model.diagram_contents.not_element.group.ColumnGroup;
import org.insightech.er.editor.model.diagram_contents.not_element.group.GroupSet;
import org.insightech.er.editor.model.diagram_contents.not_element.sequence.Sequence;
import org.insightech.er.editor.model.diagram_contents.not_element.sequence.SequenceSet;
import org.insightech.er.editor.model.diagram_contents.not_element.tablespace.Tablespace;
import org.insightech.er.editor.model.diagram_contents.not_element.tablespace.TablespaceSet;
import org.insightech.er.editor.model.diagram_contents.not_element.trigger.Trigger;
import org.insightech.er.editor.model.diagram_contents.not_element.trigger.TriggerSet;
public class ImportTableCommand extends AbstractCreateElementCommand {
private static final int AUTO_GRAPH_LIMIT = 100;
private static final int ORIGINAL_X = 20;
private static final int ORIGINAL_Y = 20;
private static final int DISTANCE_X = 300;
private static final int DISTANCE_Y = 300;
private SequenceSet sequenceSet;
private TriggerSet triggerSet;
private TablespaceSet tablespaceSet;
private GroupSet columnGroupSet;
private List<NodeElement> nodeElementList;
private List<Sequence> sequences;
private List<Trigger> triggers;
private List<Tablespace> tablespaces;
private List<ColumnGroup> columnGroups;
public ImportTableCommand(ERDiagram diagram,
List<NodeElement> nodeElementList, List<Sequence> sequences,
List<Trigger> triggers, List<Tablespace> tablespaces,
List<ColumnGroup> columnGroups) {
super(diagram);
this.nodeElementList = nodeElementList;
this.sequences = sequences;
this.triggers = triggers;
this.tablespaces = tablespaces;
this.columnGroups = columnGroups;
DiagramContents diagramContents = this.diagram.getDiagramContents();
this.sequenceSet = diagramContents.getSequenceSet();
this.triggerSet = diagramContents.getTriggerSet();
this.tablespaceSet = diagramContents.getTablespaceSet();
this.columnGroupSet = diagramContents.getGroups();
this.decideLocation();
}
@SuppressWarnings("unchecked")
private void decideLocation() {
if (this.nodeElementList.size() < AUTO_GRAPH_LIMIT) {
DirectedGraph graph = new DirectedGraph();
Map<NodeElement, Node> nodeElementNodeMap = new HashMap<NodeElement, Node>();
int fontSize = this.diagram.getFontSize();
Insets insets = new Insets(5 * fontSize, 10 * fontSize,
35 * fontSize, 20 * fontSize);
for (NodeElement nodeElement : this.nodeElementList) {
Node node = new Node();
node.setPadding(insets);
graph.nodes.add(node);
nodeElementNodeMap.put(nodeElement, node);
}
for (NodeElement nodeElement : this.nodeElementList) {
for (ConnectionElement outgoing : nodeElement.getOutgoings()) {
Node sourceNode = nodeElementNodeMap.get(outgoing
.getSource());
Node targetNode = nodeElementNodeMap.get(outgoing
.getTarget());
if (sourceNode != targetNode) {
Edge edge = new Edge(sourceNode, targetNode);
graph.edges.add(edge);
}
}
}
DirectedGraphLayout layout = new DirectedGraphLayout();
layout.visit(graph);
for (NodeElement nodeElement : nodeElementNodeMap.keySet()) {
Node node = nodeElementNodeMap.get(nodeElement);
if (nodeElement.getWidth() == 0) {
nodeElement
.setLocation(new Location(node.x, node.y, -1, -1));
}
}
} else {
int numX = (int) Math.sqrt(this.nodeElementList.size());
int x = ORIGINAL_X;
int y = ORIGINAL_Y;
for (NodeElement nodeElement : this.nodeElementList) {
if (nodeElement.getWidth() == 0) {
nodeElement.setLocation(new Location(x, y, -1, -1));
x += DISTANCE_X;
if (x > DISTANCE_X * numX) {
x = ORIGINAL_X;
y += DISTANCE_Y;
}
}
}
}
}
/**
* {@inheritDoc}
*/
@Override
protected void doExecute() {
this.diagram.getEditor().getActiveEditor().removeSelection();
if (this.columnGroups != null) {
for (ColumnGroup columnGroup : columnGroups) {
this.columnGroupSet.add(columnGroup);
}
}
for (NodeElement nodeElement : this.nodeElementList) {
this.diagram.addNewContent(nodeElement);
this.addToCategory(nodeElement);
if (nodeElement instanceof TableView) {
for (NormalColumn normalColumn : ((TableView) nodeElement)
.getNormalColumns()) {
if (normalColumn.isForeignKey()) {
for (Relation relation : normalColumn.getRelationList()) {
if (relation.getSourceTableView() == nodeElement) {
this.setSelfRelation(relation);
}
}
}
}
}
}
for (Sequence sequence : sequences) {
this.sequenceSet.addObject(sequence);
}
for (Trigger trigger : triggers) {
this.triggerSet.addObject(trigger);
}
for (Tablespace tablespace : tablespaces) {
this.tablespaceSet.addObject(tablespace);
}
this.diagram.refreshChildren();
this.diagram.refreshOutline();
if (this.category != null) {
this.category.refresh();
}
}
private void setSelfRelation(Relation relation) {
boolean anotherSelfRelation = false;
TableView sourceTable = relation.getSourceTableView();
for (Relation otherRelation : sourceTable.getOutgoingRelations()) {
if (otherRelation == relation) {
continue;
}
if (otherRelation.getSource() == otherRelation.getTarget()) {
anotherSelfRelation = true;
break;
}
}
int rate = 0;
if (anotherSelfRelation) {
rate = 50;
} else {
rate = 100;
}
Bendpoint bendpoint0 = new Bendpoint(rate, rate);
bendpoint0.setRelative(true);
int xp = 100 - (rate / 2);
int yp = 100 - (rate / 2);
relation.setSourceLocationp(100, yp);
relation.setTargetLocationp(xp, 100);
relation.addBendpoint(0, bendpoint0);
}
/**
* {@inheritDoc}
*/
@Override
protected void doUndo() {
this.diagram.getEditor().getActiveEditor().removeSelection();
for (NodeElement nodeElement : this.nodeElementList) {
this.diagram.removeContent(nodeElement);
this.removeFromCategory(nodeElement);
if (nodeElement instanceof TableView) {
for (NormalColumn normalColumn : ((TableView) nodeElement)
.getNormalColumns()) {
this.diagram.getDiagramContents().getDictionary()
.remove(normalColumn);
}
}
}
for (Sequence sequence : sequences) {
this.sequenceSet.remove(sequence);
}
for (Trigger trigger : triggers) {
this.triggerSet.remove(trigger);
}
for (Tablespace tablespace : tablespaces) {
this.tablespaceSet.remove(tablespace);
}
if (this.columnGroups != null) {
for (ColumnGroup columnGroup : columnGroups) {
this.columnGroupSet.remove(columnGroup);
}
}
this.diagram.refreshChildren();
this.diagram.refreshOutline();
if (this.category != null) {
this.category.refresh();
}
}
}
| apache-2.0 |
gerdriesselmann/netty | transport/src/main/java/io/netty/channel/AbstractChannel.java | 39631 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.channel;
import static java.util.Objects.requireNonNull;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.socket.ChannelOutputShutdownEvent;
import io.netty.channel.socket.ChannelOutputShutdownException;
import io.netty.util.DefaultAttributeMap;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.UnstableApi;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.NoRouteToHostException;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.NotYetConnectedException;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
/**
* A skeletal {@link Channel} implementation.
*/
public abstract class AbstractChannel extends DefaultAttributeMap implements Channel {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(AbstractChannel.class);
private final Channel parent;
private final ChannelId id;
private final Unsafe unsafe;
private final ChannelPipeline pipeline;
private final ChannelFuture succeedFuture;
private final VoidChannelPromise unsafeVoidPromise = new VoidChannelPromise(this, false);
private final CloseFuture closeFuture;
private volatile SocketAddress localAddress;
private volatile SocketAddress remoteAddress;
private final EventLoop eventLoop;
private volatile boolean registered;
private boolean closeInitiated;
private Throwable initialCloseCause;
/** Cache for the string representation of this channel */
private boolean strValActive;
private String strVal;
/**
* Creates a new instance.
*
* @param parent
* the parent of this channel. {@code null} if there's no parent.
*/
protected AbstractChannel(Channel parent, EventLoop eventLoop) {
this.parent = parent;
this.eventLoop = validateEventLoop(eventLoop);
closeFuture = new CloseFuture(this, eventLoop);
succeedFuture = new SucceededChannelFuture(this, eventLoop);
id = newId();
unsafe = newUnsafe();
pipeline = newChannelPipeline();
}
/**
* Creates a new instance.
*
* @param parent
* the parent of this channel. {@code null} if there's no parent.
*/
protected AbstractChannel(Channel parent, EventLoop eventLoop, ChannelId id) {
this.parent = parent;
this.eventLoop = validateEventLoop(eventLoop);
closeFuture = new CloseFuture(this, eventLoop);
succeedFuture = new SucceededChannelFuture(this, eventLoop);
this.id = id;
unsafe = newUnsafe();
pipeline = newChannelPipeline();
}
private EventLoop validateEventLoop(EventLoop eventLoop) {
return requireNonNull(eventLoop, "eventLoop");
}
@Override
public final ChannelId id() {
return id;
}
/**
* Returns a new {@link DefaultChannelId} instance. Subclasses may override this method to assign custom
* {@link ChannelId}s to {@link Channel}s that use the {@link AbstractChannel#AbstractChannel(Channel, EventLoop)}
* constructor.
*/
protected ChannelId newId() {
return DefaultChannelId.newInstance();
}
/**
* Returns a new {@link ChannelPipeline} instance.
*/
protected ChannelPipeline newChannelPipeline() {
return new DefaultChannelPipeline(this);
}
@Override
public boolean isWritable() {
ChannelOutboundBuffer buf = unsafe.outboundBuffer();
return buf != null && buf.isWritable();
}
@Override
public long bytesBeforeUnwritable() {
ChannelOutboundBuffer buf = unsafe.outboundBuffer();
// isWritable() is currently assuming if there is no outboundBuffer then the channel is not writable.
// We should be consistent with that here.
return buf != null ? buf.bytesBeforeUnwritable() : 0;
}
@Override
public long bytesBeforeWritable() {
ChannelOutboundBuffer buf = unsafe.outboundBuffer();
// isWritable() is currently assuming if there is no outboundBuffer then the channel is not writable.
// We should be consistent with that here.
return buf != null ? buf.bytesBeforeWritable() : Long.MAX_VALUE;
}
@Override
public Channel parent() {
return parent;
}
@Override
public ChannelPipeline pipeline() {
return pipeline;
}
@Override
public ByteBufAllocator alloc() {
return config().getAllocator();
}
@Override
public EventLoop eventLoop() {
return eventLoop;
}
@Override
public SocketAddress localAddress() {
SocketAddress localAddress = this.localAddress;
if (localAddress == null) {
try {
this.localAddress = localAddress = unsafe().localAddress();
} catch (Error e) {
throw e;
} catch (Throwable t) {
// Sometimes fails on a closed socket in Windows.
return null;
}
}
return localAddress;
}
/**
* @deprecated no use-case for this.
*/
@Deprecated
protected void invalidateLocalAddress() {
localAddress = null;
}
@Override
public SocketAddress remoteAddress() {
SocketAddress remoteAddress = this.remoteAddress;
if (remoteAddress == null) {
try {
this.remoteAddress = remoteAddress = unsafe().remoteAddress();
} catch (Error e) {
throw e;
} catch (Throwable t) {
// Sometimes fails on a closed socket in Windows.
return null;
}
}
return remoteAddress;
}
/**
* @deprecated no use-case for this.
*/
@Deprecated
protected void invalidateRemoteAddress() {
remoteAddress = null;
}
@Override
public boolean isRegistered() {
return registered;
}
@Override
public ChannelFuture bind(SocketAddress localAddress) {
return pipeline.bind(localAddress);
}
@Override
public ChannelFuture connect(SocketAddress remoteAddress) {
return pipeline.connect(remoteAddress);
}
@Override
public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) {
return pipeline.connect(remoteAddress, localAddress);
}
@Override
public ChannelFuture disconnect() {
return pipeline.disconnect();
}
@Override
public ChannelFuture close() {
return pipeline.close();
}
@Override
public ChannelFuture register() {
return pipeline.register();
}
@Override
public ChannelFuture deregister() {
return pipeline.deregister();
}
@Override
public Channel flush() {
pipeline.flush();
return this;
}
@Override
public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) {
return pipeline.bind(localAddress, promise);
}
@Override
public ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) {
return pipeline.connect(remoteAddress, promise);
}
@Override
public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {
return pipeline.connect(remoteAddress, localAddress, promise);
}
@Override
public ChannelFuture disconnect(ChannelPromise promise) {
return pipeline.disconnect(promise);
}
@Override
public ChannelFuture close(ChannelPromise promise) {
return pipeline.close(promise);
}
@Override
public ChannelFuture register(ChannelPromise promise) {
return pipeline.register(promise);
}
@Override
public ChannelFuture deregister(ChannelPromise promise) {
return pipeline.deregister(promise);
}
@Override
public Channel read() {
pipeline.read();
return this;
}
@Override
public ChannelFuture write(Object msg) {
return pipeline.write(msg);
}
@Override
public ChannelFuture write(Object msg, ChannelPromise promise) {
return pipeline.write(msg, promise);
}
@Override
public ChannelFuture writeAndFlush(Object msg) {
return pipeline.writeAndFlush(msg);
}
@Override
public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) {
return pipeline.writeAndFlush(msg, promise);
}
@Override
public ChannelPromise newPromise() {
return new DefaultChannelPromise(this, eventLoop);
}
@Override
public ChannelProgressivePromise newProgressivePromise() {
return new DefaultChannelProgressivePromise(this, eventLoop);
}
@Override
public ChannelFuture newSucceededFuture() {
return succeedFuture;
}
@Override
public ChannelFuture newFailedFuture(Throwable cause) {
return new FailedChannelFuture(this, eventLoop, cause);
}
@Override
public ChannelFuture closeFuture() {
return closeFuture;
}
@Override
public Unsafe unsafe() {
return unsafe;
}
/**
* Create a new {@link AbstractUnsafe} instance which will be used for the life-time of the {@link Channel}
*/
protected abstract AbstractUnsafe newUnsafe();
/**
* Returns the ID of this channel.
*/
@Override
public final int hashCode() {
return id.hashCode();
}
/**
* Returns {@code true} if and only if the specified object is identical
* with this channel (i.e: {@code this == o}).
*/
@Override
public final boolean equals(Object o) {
return this == o;
}
@Override
public final int compareTo(Channel o) {
if (this == o) {
return 0;
}
return id().compareTo(o.id());
}
/**
* Returns the {@link String} representation of this channel. The returned
* string contains the {@linkplain #hashCode() ID}, {@linkplain #localAddress() local address},
* and {@linkplain #remoteAddress() remote address} of this channel for
* easier identification.
*/
@Override
public String toString() {
boolean active = isActive();
if (strValActive == active && strVal != null) {
return strVal;
}
SocketAddress remoteAddr = remoteAddress();
SocketAddress localAddr = localAddress();
if (remoteAddr != null) {
StringBuilder buf = new StringBuilder(96)
.append("[id: 0x")
.append(id.asShortText())
.append(", L:")
.append(localAddr)
.append(active? " - " : " ! ")
.append("R:")
.append(remoteAddr)
.append(']');
strVal = buf.toString();
} else if (localAddr != null) {
StringBuilder buf = new StringBuilder(64)
.append("[id: 0x")
.append(id.asShortText())
.append(", L:")
.append(localAddr)
.append(']');
strVal = buf.toString();
} else {
StringBuilder buf = new StringBuilder(16)
.append("[id: 0x")
.append(id.asShortText())
.append(']');
strVal = buf.toString();
}
strValActive = active;
return strVal;
}
@Override
public final ChannelPromise voidPromise() {
return pipeline.voidPromise();
}
protected final void readIfIsAutoRead() {
if (config().isAutoRead()) {
read();
}
}
/**
* {@link Unsafe} implementation which sub-classes must extend and use.
*/
protected abstract class AbstractUnsafe implements Unsafe {
private volatile ChannelOutboundBuffer outboundBuffer = new ChannelOutboundBuffer(AbstractChannel.this);
private RecvByteBufAllocator.Handle recvHandle;
private MessageSizeEstimator.Handle estimatorHandler;
private boolean inFlush0;
/** true if the channel has never been registered, false otherwise */
private boolean neverRegistered = true;
private void assertEventLoop() {
assert eventLoop.inEventLoop();
}
@Override
public RecvByteBufAllocator.Handle recvBufAllocHandle() {
if (recvHandle == null) {
recvHandle = config().getRecvByteBufAllocator().newHandle();
}
return recvHandle;
}
@Override
public final ChannelOutboundBuffer outboundBuffer() {
return outboundBuffer;
}
@Override
public final SocketAddress localAddress() {
return localAddress0();
}
@Override
public final SocketAddress remoteAddress() {
return remoteAddress0();
}
@Override
public final void register(final ChannelPromise promise) {
assertEventLoop();
if (isRegistered()) {
promise.setFailure(new IllegalStateException("registered to an event loop already"));
return;
}
try {
// check if the channel is still open as it could be closed in the mean time when the register
// call was outside of the eventLoop
if (!promise.setUncancellable() || !ensureOpen(promise)) {
return;
}
boolean firstRegistration = neverRegistered;
doRegister();
neverRegistered = false;
registered = true;
safeSetSuccess(promise);
pipeline.fireChannelRegistered();
// Only fire a channelActive if the channel has never been registered. This prevents firing
// multiple channel actives if the channel is deregistered and re-registered.
if (isActive()) {
if (firstRegistration) {
pipeline.fireChannelActive();
}
readIfIsAutoRead();
}
} catch (Throwable t) {
// Close the channel directly to avoid FD leak.
closeForcibly();
closeFuture.setClosed();
safeSetFailure(promise, t);
}
}
@Override
public final void bind(final SocketAddress localAddress, final ChannelPromise promise) {
assertEventLoop();
if (!promise.setUncancellable() || !ensureOpen(promise)) {
return;
}
// See: https://github.com/netty/netty/issues/576
if (Boolean.TRUE.equals(config().getOption(ChannelOption.SO_BROADCAST)) &&
localAddress instanceof InetSocketAddress &&
!((InetSocketAddress) localAddress).getAddress().isAnyLocalAddress() &&
!PlatformDependent.isWindows() && !PlatformDependent.maybeSuperUser()) {
// Warn a user about the fact that a non-root user can't receive a
// broadcast packet on *nix if the socket is bound on non-wildcard address.
logger.warn(
"A non-root user can't receive a broadcast packet if the socket " +
"is not bound to a wildcard address; binding to a non-wildcard " +
"address (" + localAddress + ") anyway as requested.");
}
boolean wasActive = isActive();
try {
doBind(localAddress);
} catch (Throwable t) {
safeSetFailure(promise, t);
closeIfClosed();
return;
}
if (!wasActive && isActive()) {
invokeLater(() -> {
pipeline.fireChannelActive();
readIfIsAutoRead();
});
}
safeSetSuccess(promise);
}
@Override
public final void disconnect(final ChannelPromise promise) {
assertEventLoop();
if (!promise.setUncancellable()) {
return;
}
boolean wasActive = isActive();
try {
doDisconnect();
// Reset remoteAddress and localAddress
remoteAddress = null;
localAddress = null;
} catch (Throwable t) {
safeSetFailure(promise, t);
closeIfClosed();
return;
}
if (wasActive && !isActive()) {
invokeLater(pipeline::fireChannelInactive);
}
safeSetSuccess(promise);
closeIfClosed(); // doDisconnect() might have closed the channel
}
@Override
public final void close(final ChannelPromise promise) {
assertEventLoop();
ClosedChannelException closedChannelException = new ClosedChannelException();
close(promise, closedChannelException, closedChannelException, false);
}
/**
* Shutdown the output portion of the corresponding {@link Channel}.
* For example this will clean up the {@link ChannelOutboundBuffer} and not allow any more writes.
*/
@UnstableApi
public final void shutdownOutput(final ChannelPromise promise) {
assertEventLoop();
shutdownOutput(promise, null);
}
/**
* Shutdown the output portion of the corresponding {@link Channel}.
* For example this will clean up the {@link ChannelOutboundBuffer} and not allow any more writes.
* @param cause The cause which may provide rational for the shutdown.
*/
private void shutdownOutput(final ChannelPromise promise, Throwable cause) {
if (!promise.setUncancellable()) {
return;
}
final ChannelOutboundBuffer outboundBuffer = this.outboundBuffer;
if (outboundBuffer == null) {
promise.setFailure(new ClosedChannelException());
return;
}
this.outboundBuffer = null; // Disallow adding any messages and flushes to outboundBuffer.
final Throwable shutdownCause = cause == null ?
new ChannelOutputShutdownException("Channel output shutdown") :
new ChannelOutputShutdownException("Channel output shutdown", cause);
Executor closeExecutor = prepareToClose();
if (closeExecutor != null) {
closeExecutor.execute(() -> {
try {
// Execute the shutdown.
doShutdownOutput();
promise.setSuccess();
} catch (Throwable err) {
promise.setFailure(err);
} finally {
// Dispatch to the EventLoop
eventLoop().execute(() ->
closeOutboundBufferForShutdown(pipeline, outboundBuffer, shutdownCause));
}
});
} else {
try {
// Execute the shutdown.
doShutdownOutput();
promise.setSuccess();
} catch (Throwable err) {
promise.setFailure(err);
} finally {
closeOutboundBufferForShutdown(pipeline, outboundBuffer, shutdownCause);
}
}
}
private void closeOutboundBufferForShutdown(
ChannelPipeline pipeline, ChannelOutboundBuffer buffer, Throwable cause) {
buffer.failFlushed(cause, false);
buffer.close(cause, true);
pipeline.fireUserEventTriggered(ChannelOutputShutdownEvent.INSTANCE);
}
private void close(final ChannelPromise promise, final Throwable cause,
final ClosedChannelException closeCause, final boolean notify) {
if (!promise.setUncancellable()) {
return;
}
if (closeInitiated) {
if (closeFuture.isDone()) {
// Closed already.
safeSetSuccess(promise);
} else if (!(promise instanceof VoidChannelPromise)) { // Only needed if no VoidChannelPromise.
// This means close() was called before so we just register a listener and return
closeFuture.addListener((ChannelFutureListener) future -> promise.setSuccess());
}
return;
}
closeInitiated = true;
final boolean wasActive = isActive();
final ChannelOutboundBuffer outboundBuffer = this.outboundBuffer;
this.outboundBuffer = null; // Disallow adding any messages and flushes to outboundBuffer.
Executor closeExecutor = prepareToClose();
if (closeExecutor != null) {
closeExecutor.execute(() -> {
try {
// Execute the close.
doClose0(promise);
} finally {
// Call invokeLater so closeAndDeregister is executed in the EventLoop again!
invokeLater(() -> {
if (outboundBuffer != null) {
// Fail all the queued messages
outboundBuffer.failFlushed(cause, notify);
outboundBuffer.close(closeCause);
}
fireChannelInactiveAndDeregister(wasActive);
});
}
});
} else {
try {
// Close the channel and fail the queued messages in all cases.
doClose0(promise);
} finally {
if (outboundBuffer != null) {
// Fail all the queued messages.
outboundBuffer.failFlushed(cause, notify);
outboundBuffer.close(closeCause);
}
}
if (inFlush0) {
invokeLater(() -> fireChannelInactiveAndDeregister(wasActive));
} else {
fireChannelInactiveAndDeregister(wasActive);
}
}
}
private void doClose0(ChannelPromise promise) {
try {
doClose();
closeFuture.setClosed();
safeSetSuccess(promise);
} catch (Throwable t) {
closeFuture.setClosed();
safeSetFailure(promise, t);
}
}
private void fireChannelInactiveAndDeregister(final boolean wasActive) {
deregister(voidPromise(), wasActive && !isActive());
}
@Override
public final void closeForcibly() {
try {
doClose();
} catch (Exception e) {
logger.warn("Failed to close a channel.", e);
}
}
@Override
public final void deregister(final ChannelPromise promise) {
assertEventLoop();
deregister(promise, false);
}
private void deregister(final ChannelPromise promise, final boolean fireChannelInactive) {
if (!promise.setUncancellable()) {
return;
}
if (!registered) {
safeSetSuccess(promise);
return;
}
// As a user may call deregister() from within any method while doing processing in the ChannelPipeline,
// we need to ensure we do the actual deregister operation later. This is needed as for example,
// we may be in the ByteToMessageDecoder.callDecode(...) method and so still try to do processing in
// the old EventLoop while the user already registered the Channel to a new EventLoop. Without delay,
// the deregister operation this could lead to have a handler invoked by different EventLoop and so
// threads.
//
// See:
// https://github.com/netty/netty/issues/4435
invokeLater(() -> {
try {
doDeregister();
} catch (Throwable t) {
logger.warn("Unexpected exception occurred while deregistering a channel.", t);
} finally {
if (fireChannelInactive) {
pipeline.fireChannelInactive();
}
// Some transports like local and AIO does not allow the deregistration of
// an open channel. Their doDeregister() calls close(). Consequently,
// close() calls deregister() again - no need to fire channelUnregistered, so check
// if it was registered.
if (registered) {
registered = false;
pipeline.fireChannelUnregistered();
}
safeSetSuccess(promise);
}
});
}
@Override
public final void beginRead() {
assertEventLoop();
if (!isActive()) {
return;
}
try {
doBeginRead();
} catch (final Exception e) {
invokeLater(() -> pipeline.fireExceptionCaught(e));
close(voidPromise());
}
}
@Override
public final void write(Object msg, ChannelPromise promise) {
assertEventLoop();
ChannelOutboundBuffer outboundBuffer = this.outboundBuffer;
if (outboundBuffer == null) {
// If the outboundBuffer is null we know the channel was closed and so
// need to fail the future right away. If it is not null the handling of the rest
// will be done in flush0()
// See https://github.com/netty/netty/issues/2362
safeSetFailure(promise, newClosedChannelException(initialCloseCause));
// release message now to prevent resource-leak
ReferenceCountUtil.release(msg);
return;
}
int size;
try {
msg = filterOutboundMessage(msg);
if (estimatorHandler == null) {
estimatorHandler = config().getMessageSizeEstimator().newHandle();
}
size = estimatorHandler.size(msg);
if (size < 0) {
size = 0;
}
} catch (Throwable t) {
safeSetFailure(promise, t);
ReferenceCountUtil.release(msg);
return;
}
outboundBuffer.addMessage(msg, size, promise);
}
@Override
public final void flush() {
assertEventLoop();
ChannelOutboundBuffer outboundBuffer = this.outboundBuffer;
if (outboundBuffer == null) {
return;
}
outboundBuffer.addFlush();
flush0();
}
@SuppressWarnings("deprecation")
protected void flush0() {
if (inFlush0) {
// Avoid re-entrance
return;
}
final ChannelOutboundBuffer outboundBuffer = this.outboundBuffer;
if (outboundBuffer == null || outboundBuffer.isEmpty()) {
return;
}
inFlush0 = true;
// Mark all pending write requests as failure if the channel is inactive.
if (!isActive()) {
try {
if (isOpen()) {
outboundBuffer.failFlushed(new NotYetConnectedException(), true);
} else {
// Do not trigger channelWritabilityChanged because the channel is closed already.
outboundBuffer.failFlushed(newClosedChannelException(initialCloseCause), false);
}
} finally {
inFlush0 = false;
}
return;
}
try {
doWrite(outboundBuffer);
} catch (Throwable t) {
if (t instanceof IOException && config().isAutoClose()) {
/**
* Just call {@link #close(ChannelPromise, Throwable, boolean)} here which will take care of
* failing all flushed messages and also ensure the actual close of the underlying transport
* will happen before the promises are notified.
*
* This is needed as otherwise {@link #isActive()} , {@link #isOpen()} and {@link #isWritable()}
* may still return {@code true} even if the channel should be closed as result of the exception.
*/
initialCloseCause = t;
close(voidPromise(), t, newClosedChannelException(t), false);
} else {
try {
shutdownOutput(voidPromise(), t);
} catch (Throwable t2) {
initialCloseCause = t;
close(voidPromise(), t2, newClosedChannelException(t), false);
}
}
} finally {
inFlush0 = false;
}
}
private ClosedChannelException newClosedChannelException(Throwable cause) {
ClosedChannelException exception = new ClosedChannelException();
if (cause != null) {
exception.initCause(cause);
}
return exception;
}
@Override
public final ChannelPromise voidPromise() {
assertEventLoop();
return unsafeVoidPromise;
}
protected final boolean ensureOpen(ChannelPromise promise) {
if (isOpen()) {
return true;
}
safeSetFailure(promise, newClosedChannelException(initialCloseCause));
return false;
}
/**
* Marks the specified {@code promise} as success. If the {@code promise} is done already, log a message.
*/
protected final void safeSetSuccess(ChannelPromise promise) {
if (!(promise instanceof VoidChannelPromise) && !promise.trySuccess()) {
logger.warn("Failed to mark a promise as success because it is done already: {}", promise);
}
}
/**
* Marks the specified {@code promise} as failure. If the {@code promise} is done already, log a message.
*/
protected final void safeSetFailure(ChannelPromise promise, Throwable cause) {
if (!(promise instanceof VoidChannelPromise) && !promise.tryFailure(cause)) {
logger.warn("Failed to mark a promise as failure because it's done already: {}", promise, cause);
}
}
protected final void closeIfClosed() {
if (isOpen()) {
return;
}
close(voidPromise());
}
private void invokeLater(Runnable task) {
try {
// This method is used by outbound operation implementations to trigger an inbound event later.
// They do not trigger an inbound event immediately because an outbound operation might have been
// triggered by another inbound event handler method. If fired immediately, the call stack
// will look like this for example:
//
// handlerA.inboundBufferUpdated() - (1) an inbound handler method closes a connection.
// -> handlerA.ctx.close()
// -> channel.unsafe.close()
// -> handlerA.channelInactive() - (2) another inbound handler method called while in (1) yet
//
// which means the execution of two inbound handler methods of the same handler overlap undesirably.
eventLoop().execute(task);
} catch (RejectedExecutionException e) {
logger.warn("Can't invoke task later as EventLoop rejected it", e);
}
}
/**
* Appends the remote address to the message of the exceptions caused by connection attempt failure.
*/
protected final Throwable annotateConnectException(Throwable cause, SocketAddress remoteAddress) {
if (cause instanceof ConnectException) {
return new AnnotatedConnectException((ConnectException) cause, remoteAddress);
}
if (cause instanceof NoRouteToHostException) {
return new AnnotatedNoRouteToHostException((NoRouteToHostException) cause, remoteAddress);
}
if (cause instanceof SocketException) {
return new AnnotatedSocketException((SocketException) cause, remoteAddress);
}
return cause;
}
/**
* Prepares to close the {@link Channel}. If this method returns an {@link Executor}, the
* caller must call the {@link Executor#execute(Runnable)} method with a task that calls
* {@link #doClose()} on the returned {@link Executor}. If this method returns {@code null},
* {@link #doClose()} must be called from the caller thread. (i.e. {@link EventLoop})
*/
protected Executor prepareToClose() {
return null;
}
}
/**
* Returns the {@link SocketAddress} which is bound locally.
*/
protected abstract SocketAddress localAddress0();
/**
* Return the {@link SocketAddress} which the {@link Channel} is connected to.
*/
protected abstract SocketAddress remoteAddress0();
/**
* Is called after the {@link Channel} is registered with its {@link EventLoop} as part of the register process.
*
* Sub-classes may override this method
*/
protected void doRegister() throws Exception {
eventLoop().unsafe().register(this);
}
/**
* Bind the {@link Channel} to the {@link SocketAddress}
*/
protected abstract void doBind(SocketAddress localAddress) throws Exception;
/**
* Disconnect this {@link Channel} from its remote peer
*/
protected abstract void doDisconnect() throws Exception;
/**
* Close the {@link Channel}
*/
protected abstract void doClose() throws Exception;
/**
* Called when conditions justify shutting down the output portion of the channel. This may happen if a write
* operation throws an exception.
*/
@UnstableApi
protected void doShutdownOutput() throws Exception {
doClose();
}
/**
* Deregister the {@link Channel} from its {@link EventLoop}.
*
* Sub-classes may override this method
*/
protected void doDeregister() throws Exception {
eventLoop().unsafe().deregister(this);
}
/**
* Schedule a read operation.
*/
protected abstract void doBeginRead() throws Exception;
/**
* Flush the content of the given buffer to the remote peer.
*/
protected abstract void doWrite(ChannelOutboundBuffer in) throws Exception;
/**
* Invoked when a new message is added to a {@link ChannelOutboundBuffer} of this {@link AbstractChannel}, so that
* the {@link Channel} implementation converts the message to another. (e.g. heap buffer -> direct buffer)
*/
protected Object filterOutboundMessage(Object msg) throws Exception {
return msg;
}
protected void validateFileRegion(DefaultFileRegion region, long position) throws IOException {
DefaultFileRegion.validate(region, position);
}
static final class CloseFuture extends DefaultChannelPromise {
CloseFuture(AbstractChannel ch, EventExecutor eventExecutor) {
super(ch, eventExecutor);
}
@Override
public ChannelPromise setSuccess() {
throw new IllegalStateException();
}
@Override
public ChannelPromise setFailure(Throwable cause) {
throw new IllegalStateException();
}
@Override
public boolean trySuccess() {
throw new IllegalStateException();
}
@Override
public boolean tryFailure(Throwable cause) {
throw new IllegalStateException();
}
boolean setClosed() {
return super.trySuccess();
}
}
private static final class AnnotatedConnectException extends ConnectException {
private static final long serialVersionUID = 3901958112696433556L;
AnnotatedConnectException(ConnectException exception, SocketAddress remoteAddress) {
super(exception.getMessage() + ": " + remoteAddress);
initCause(exception);
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
private static final class AnnotatedNoRouteToHostException extends NoRouteToHostException {
private static final long serialVersionUID = -6801433937592080623L;
AnnotatedNoRouteToHostException(NoRouteToHostException exception, SocketAddress remoteAddress) {
super(exception.getMessage() + ": " + remoteAddress);
initCause(exception);
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
private static final class AnnotatedSocketException extends SocketException {
private static final long serialVersionUID = 3896743275010454039L;
AnnotatedSocketException(SocketException exception, SocketAddress remoteAddress) {
super(exception.getMessage() + ": " + remoteAddress);
initCause(exception);
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
}
| apache-2.0 |
akiyamayami/TLCN | src/main/java/com/tlcn/validator/ModelUserValidator.java | 2682 | package com.tlcn.validator;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.springframework.web.multipart.MultipartFile;
import com.tlcn.dto.ModelUser;
import com.tlcn.service.UserService;
@Component
public class ModelUserValidator implements Validator{
@Autowired
private UserService userService;
private Pattern pattern;
private Matcher matcher;
private String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
@Override
public boolean supports(Class<?> clazz) {
return ModelUser.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
ModelUser user = (ModelUser) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "NotEmpty.User.email");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "NotEmpty.User.name");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phone", "NotEmpty.User.phone");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "birthday", "NotEmpty.User.birthday");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "roleID", "NotEmpty.User.roleID");
if(user.getEmail() != null && user.getEmail() != "" && !validateEmail(user.getEmail())){
errors.rejectValue("email", "WrongFormat.User.email");
}
if(user.getBirthday() != null){
if(Calendar.getInstance().getTime().getTime() < user.getBirthday().getTime())
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "birthday", "greaterThanToDay.Driver.birthday");
}
boolean userExist = userService.findAll().parallelStream().filter(u -> u.getEmail().equals(user.getEmail())).findFirst().isPresent();
if(userExist){
errors.rejectValue("email", "EmailExist.User.email");
}
MultipartFile file = user.getFile();
if(file != null)
{
String name = file.getOriginalFilename();
String ext = null;
ext = name.substring(name.lastIndexOf(".")+1,name.length()).toLowerCase();
System.out.println(ext);
if(!ext.equals("") && (ext.equals(name) || !ext.equals("jpg")))
errors.rejectValue("file", "InvalidExt.Driver.file");
else if(file.getSize() > 1024000){
errors.rejectValue("file", "BigSize.Driver.file");
}
}
}
private boolean validateEmail(String email) {
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
return matcher.matches();
}
}
| apache-2.0 |
simpher/FutureStrategy | src/com/future/analysis/TransactionInfo.java | 622 | package com.future.analysis;
public class TransactionInfo {
private final double min;
private final double max;
private final double unit;
private double current;
public TransactionInfo(double min, double max, double unit) {
this.min = min;
this.max = max;
this.unit = unit;
this.current = (min+max)/2;
}
public double getCurrent() {
return current;
}
public void setCurrent(double current) {
this.current = current;
}
public double getMin() {
return min;
}
public double getMax() {
return max;
}
public double getUnit() {
return unit;
}
}
| apache-2.0 |
lhangtk/EasyTeaching | src/com/stone/EasyTeaching/utilities/pulltorefresh/PullToRefreshScrollView.java | 3841 | /*******************************************************************************
* Copyright 2011, 2012 Chris Banes.
*
* 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.stone.EasyTeaching.utilities.pulltorefresh;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ScrollView;
import com.stone.EasyTeaching.R;
public class PullToRefreshScrollView extends PullToRefreshBase<ScrollView> {
public PullToRefreshScrollView(Context context) {
super(context);
}
public PullToRefreshScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PullToRefreshScrollView(Context context, Mode mode) {
super(context, mode);
}
public PullToRefreshScrollView(Context context, Mode mode, AnimationStyle style) {
super(context, mode, style);
}
@Override
public final Orientation getPullToRefreshScrollDirection() {
return Orientation.VERTICAL;
}
@Override
protected ScrollView createRefreshableView(Context context, AttributeSet attrs) {
ScrollView scrollView;
if (VERSION.SDK_INT >= VERSION_CODES.GINGERBREAD) {
scrollView = new InternalScrollViewSDK9(context, attrs);
} else {
scrollView = new ScrollView(context, attrs);
}
scrollView.setId(R.id.scrollview);
return scrollView;
}
@Override
protected boolean isReadyForPullStart() {
return mRefreshableView.getScrollY() == 0;
}
@Override
protected boolean isReadyForPullEnd() {
View scrollViewChild = mRefreshableView.getChildAt(0);
if (null != scrollViewChild) {
return mRefreshableView.getScrollY() >= (scrollViewChild.getHeight() - getHeight());
}
return false;
}
@TargetApi(9)
final class InternalScrollViewSDK9 extends ScrollView {
public InternalScrollViewSDK9(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX,
int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) {
final boolean returnValue = super.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX,
scrollRangeY, maxOverScrollX, maxOverScrollY, isTouchEvent);
// Does all of the hard work...
OverscrollHelper.overScrollBy(PullToRefreshScrollView.this, deltaX, scrollX, deltaY, scrollY,
getScrollRange(), isTouchEvent);
return returnValue;
}
/**
* Taken from the AOSP ScrollView source
*/
private int getScrollRange() {
int scrollRange = 0;
if (getChildCount() > 0) {
View child = getChildAt(0);
scrollRange = Math.max(0, child.getHeight() - (getHeight() - getPaddingBottom() - getPaddingTop()));
}
return scrollRange;
}
}
}
| apache-2.0 |
multi-os-engine/moe-core | moe.apple/moe.platform.ios/src/main/java/apple/enums/acl_tag_t.java | 998 | /*
Copyright 2014-2016 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package apple.enums;
import org.moe.natj.general.ann.Generated;
/**
* 23.2.5 ACL entry tag type bits - nonstandard
*/
@Generated
public final class acl_tag_t {
@Generated public static final int ACL_UNDEFINED_TAG = 0x00000000;
@Generated public static final int ACL_EXTENDED_ALLOW = 0x00000001;
@Generated public static final int ACL_EXTENDED_DENY = 0x00000002;
@Generated
private acl_tag_t() {
}
}
| apache-2.0 |
Gliby/libgdx | extensions/gdx-bullet/jni/swig-src/linearmath/com/badlogic/gdx/physics/bullet/linearmath/LinearMathConstants.java | 1118 | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.7
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.linearmath;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.Quaternion;
import com.badlogic.gdx.math.Matrix3;
import com.badlogic.gdx.math.Matrix4;
public interface LinearMathConstants {
public final static int BT_BULLET_VERSION = 283;
public final static double BT_LARGE_FLOAT = 1e18;
public final static double BT_ONE = 1.0;
public final static double BT_ZERO = 0.0;
public final static double BT_TWO = 2.0;
public final static double BT_HALF = 0.5;
public final static String btVector3DataName = "btVector3FloatData";
public final static int USE_BANCHLESS = 1;
public final static int BT_USE_PLACEMENT_NEW = 1;
}
| apache-2.0 |
reportportal/service-api | src/main/java/com/epam/ta/reportportal/core/project/settings/DeleteProjectSettingsHandler.java | 1683 | /*
* Copyright 2019 EPAM Systems
*
* 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.epam.ta.reportportal.core.project.settings;
import com.epam.ta.reportportal.commons.ReportPortalUser;
import com.epam.ta.reportportal.ws.model.OperationCompletionRS;
/**
* @author <a href="mailto:ihar_kahadouski@epam.com">Ihar Kahadouski</a>
*/
public interface DeleteProjectSettingsHandler {
/**
* Remove specified issue sub-type for specified project
*
* @param projectName Project name
* @param user User
* @param id Issue id
* @return OperationCompletionRS
*/
OperationCompletionRS deleteProjectIssueSubType(String projectName, ReportPortalUser user, Long id);
/**
* Delete {@link com.epam.ta.reportportal.entity.pattern.PatternTemplate} by ID and project ID
*
* @param projectName {@link com.epam.ta.reportportal.entity.project.Project#name}
* @param user {@link ReportPortalUser}
* @param id {@link com.epam.ta.reportportal.entity.pattern.PatternTemplate#id}
* @return {@link OperationCompletionRS}
*/
OperationCompletionRS deletePatternTemplate(String projectName, ReportPortalUser user, Long id);
}
| apache-2.0 |
google/supl-client | src/main/java/com/google/location/suplclient/asn1/supl2/lpp/BDS_GridModelSupport_r12.java | 4572 | // Copyright 2018 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
//
// 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.google.location.suplclient.asn1.supl2.lpp;
// Copyright 2008 Google Inc. All Rights Reserved.
/*
* This class is AUTOMATICALLY GENERATED. Do NOT EDIT.
*/
//
//
import com.google.location.suplclient.asn1.base.Asn1Sequence;
import com.google.location.suplclient.asn1.base.Asn1Tag;
import com.google.location.suplclient.asn1.base.BitStream;
import com.google.location.suplclient.asn1.base.BitStreamReader;
import com.google.location.suplclient.asn1.base.SequenceComponent;
import com.google.common.collect.ImmutableList;
import java.util.Collection;
import javax.annotation.Nullable;
/**
*
*/
public class BDS_GridModelSupport_r12 extends Asn1Sequence {
//
private static final Asn1Tag TAG_BDS_GridModelSupport_r12
= Asn1Tag.fromClassAndNumber(-1, -1);
public BDS_GridModelSupport_r12() {
super();
}
@Override
@Nullable
protected Asn1Tag getTag() {
return TAG_BDS_GridModelSupport_r12;
}
@Override
protected boolean isTagImplicit() {
return true;
}
public static Collection<Asn1Tag> getPossibleFirstTags() {
if (TAG_BDS_GridModelSupport_r12 != null) {
return ImmutableList.of(TAG_BDS_GridModelSupport_r12);
} else {
return Asn1Sequence.getPossibleFirstTags();
}
}
/**
* Creates a new BDS_GridModelSupport_r12 from encoded stream.
*/
public static BDS_GridModelSupport_r12 fromPerUnaligned(byte[] encodedBytes) {
BDS_GridModelSupport_r12 result = new BDS_GridModelSupport_r12();
result.decodePerUnaligned(new BitStreamReader(encodedBytes));
return result;
}
/**
* Creates a new BDS_GridModelSupport_r12 from encoded stream.
*/
public static BDS_GridModelSupport_r12 fromPerAligned(byte[] encodedBytes) {
BDS_GridModelSupport_r12 result = new BDS_GridModelSupport_r12();
result.decodePerAligned(new BitStreamReader(encodedBytes));
return result;
}
@Override protected boolean isExtensible() {
return true;
}
@Override public boolean containsExtensionValues() {
for (SequenceComponent extensionComponent : getExtensionComponents()) {
if (extensionComponent.isExplicitlySet()) return true;
}
return false;
}
@Override public Iterable<? extends SequenceComponent> getComponents() {
ImmutableList.Builder<SequenceComponent> builder = ImmutableList.builder();
return builder.build();
}
@Override public Iterable<? extends SequenceComponent>
getExtensionComponents() {
ImmutableList.Builder<SequenceComponent> builder = ImmutableList.builder();
return builder.build();
}
@Override public Iterable<BitStream> encodePerUnaligned() {
return super.encodePerUnaligned();
}
@Override public Iterable<BitStream> encodePerAligned() {
return super.encodePerAligned();
}
@Override public void decodePerUnaligned(BitStreamReader reader) {
super.decodePerUnaligned(reader);
}
@Override public void decodePerAligned(BitStreamReader reader) {
super.decodePerAligned(reader);
}
@Override public String toString() {
return toIndentedString("");
}
public String toIndentedString(String indent) {
StringBuilder builder = new StringBuilder();
builder.append("BDS_GridModelSupport_r12 = {\n");
final String internalIndent = indent + " ";
for (SequenceComponent component : getComponents()) {
if (component.isExplicitlySet()) {
builder.append(internalIndent)
.append(component.toIndentedString(internalIndent));
}
}
if (isExtensible()) {
builder.append(internalIndent).append("...\n");
for (SequenceComponent component : getExtensionComponents()) {
if (component.isExplicitlySet()) {
builder.append(internalIndent)
.append(component.toIndentedString(internalIndent));
}
}
}
builder.append(indent).append("};\n");
return builder.toString();
}
}
| apache-2.0 |
fengbaicanhe/itebooks-reptile | EbooksReptile/reptile-extractors/reptile-extractor-jsoup/src/test/java/com/poet/reptile/api/extractor/jsoup/Test.java | 554 | package com.poet.reptile.api.extractor.jsoup;
import com.poet.reptile.api.extractor.support.JsoupExtractorBuilder;
import com.poet.reptile.api.extractor.support.JsoupExtractor;
/**
* Created by xu on 2016/1/7.
*/
public class Test {
@org.junit.Test
public void testBuilder(){
JsoupExtractor categoryExtractor =
JsoupExtractorBuilder.startBuild(new TestJsoupEleProcessor())
.cssQuery("#menu-item-65>ul").build();
categoryExtractor.extractFromUrl("http://www.allitebooks.com/");
}
}
| apache-2.0 |
ufoscout/jpattern | gwt/src/test/java/com/jpattern/gwt/client/spike/BeanFactory.java | 517 | package com.jpattern.gwt.client.spike;
import com.google.web.bindery.autobean.shared.AutoBean;
import com.google.web.bindery.autobean.shared.AutoBeanFactory;
/**
*
* @author Francesco Cina'
*
* 23/ago/2011
*/
public interface BeanFactory extends AutoBeanFactory {
AutoBean<IBean> bean();
AutoBean<IBean> bean(IBean bean);
AutoBean<IBeanList> beanList();
AutoBean<IBeanList> beanList(IBeanList list);
AutoBean<IStringList> stringList();
AutoBean<IStringList> stringList(IStringList list);
}
| apache-2.0 |
fabiowin98/sqldocgen | org.dgl.sqldocgen/src/org/dgl/sqldocgen/Lang.java | 288 | package org.dgl.sqldocgen;
public class Lang {
public static final String NAME = "(SQLDOCGEN) Sql Documentation Generator";
public static final String VERSION = "1.1.2.0 5-FEB-2015";
public static final String AUTHOR = "Fabiowin98 (c)2014 http://fabiowin98.blogspot.com";
}
| apache-2.0 |
NetGhostMan/javawork | src/main/java/com/edison/seller/controller/SellerController.java | 1803 | package com.edison.seller.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.edison.demonstration.service.DemonstrationService;
import com.edison.meta.Product;
import com.edison.seller.service.SellerService;
import com.edison.uitl.MapUtil;
@Controller
public class SellerController {
@Autowired
MapUtil mapUtil;
@Autowired
SellerService sellerServiceImpl;
@Autowired
DemonstrationService demonstrationServiceImpl;
@RequestMapping("/public")
public String toPublic(HttpServletRequest request, ModelMap map) {
map = mapUtil.AfterAddUserMap(request, map);
return "public";
}
@RequestMapping("/publicSubmit")
public String dopublicSubmit(HttpServletRequest request, ModelMap map) {
map = mapUtil.AfterAddUserMap(request, map);
Product product = sellerServiceImpl.getProductFromGet(request);
if (product != null) {
sellerServiceImpl.saveProduct(product);
}
map.addAttribute("product", product);
return "publicSubmit";
}
@RequestMapping("/edit")
public String toEdit(ModelMap map, HttpServletRequest request) {
map = mapUtil.AfterAddUserMap(request, map);
Product product = demonstrationServiceImpl.getProductAll(request);
map.addAttribute("product", product);
return "edit";
}
@RequestMapping("/editSubmit")
public String doEditSubmit(ModelMap map, HttpServletRequest request) {
map = mapUtil.AfterAddUserMap(request, map);
Product product = sellerServiceImpl.getProductFromGet(request);
sellerServiceImpl.updateProduct(product);
map.addAttribute("product",product);
return "editSubmit";
}
}
| apache-2.0 |
DV8FromTheWorld/JDA | src/main/java/net/dv8tion/jda/internal/requests/RateLimiter.java | 2416 | /*
* Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.dv8tion.jda.internal.requests;
import net.dv8tion.jda.api.requests.Request;
import net.dv8tion.jda.internal.utils.JDALogger;
import org.slf4j.Logger;
import java.util.Iterator;
@SuppressWarnings("rawtypes")
public abstract class RateLimiter
{
//Implementations of this class exist in the net.dv8tion.jda.api.requests.ratelimit package.
protected static final Logger log = JDALogger.getLog(RateLimiter.class);
protected final Requester requester;
protected volatile boolean isShutdown = false, isStopped = false;
protected RateLimiter(Requester requester)
{
this.requester = requester;
}
protected boolean isSkipped(Iterator<Request> it, Request request)
{
if (request.isSkipped())
{
cancel(it, request);
return true;
}
return false;
}
private void cancel(Iterator<Request> it, Request request)
{
request.onCancelled();
it.remove();
}
// -- Required Implementations --
public abstract Long getRateLimit(Route.CompiledRoute route);
protected abstract void queueRequest(Request request);
protected abstract Long handleResponse(Route.CompiledRoute route, okhttp3.Response response);
// --- Default Implementations --
public boolean isRateLimited(Route.CompiledRoute route)
{
Long rateLimit = getRateLimit(route);
return rateLimit != null && rateLimit > 0L;
}
public abstract int cancelRequests();
public void init() {}
// Return true if no more requests will be processed
protected boolean stop()
{
isStopped = true;
return true;
}
protected void shutdown()
{
isShutdown = true;
stop();
}
}
| apache-2.0 |
VladThodo/behe-keyboard | app/src/main/java/com/vlath/keyboard/keyboard/KeyboardTheme.java | 8945 | /*
* Copyright (C) 2014 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.vlath.keyboard.keyboard;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.preference.PreferenceManager;
import android.util.Log;
import java.util.ArrayList;
import java.util.Arrays;
import com.vlath.keyboard.R;
public final class KeyboardTheme implements Comparable<KeyboardTheme> {
private static final String TAG = KeyboardTheme.class.getSimpleName();
static final String KLP_KEYBOARD_THEME_KEY = "pref_keyboard_layout_20110916";
static final String LXX_KEYBOARD_THEME_KEY = "pref_keyboard_theme_20140509";
// These should be aligned with Keyboard.themeId and Keyboard.Case.keyboardTheme
// attributes' values in attrs.xml.
public static final int THEME_ID_ICS = 0;
public static final int THEME_ID_KLP = 2;
public static final int THEME_ID_LXX_LIGHT = 3;
public static final int THEME_ID_LXX_DARK = 4;
public static final int DEFAULT_THEME_ID = THEME_ID_LXX_DARK;
private static KeyboardTheme[] AVAILABLE_KEYBOARD_THEMES;
/* package private for testing */
static final KeyboardTheme[] KEYBOARD_THEMES = {
new KeyboardTheme(THEME_ID_ICS, "ICS", R.style.KeyboardTheme_ICS,
// This has never been selected because we support ICS or later.
VERSION_CODES.BASE),
new KeyboardTheme(THEME_ID_KLP, "KLP", R.style.KeyboardTheme_KLP,
// Default theme for ICS, JB, and KLP.
VERSION_CODES.ICE_CREAM_SANDWICH),
new KeyboardTheme(THEME_ID_LXX_LIGHT, "LXXLight", R.style.KeyboardTheme_LXX_Light,
// Default theme for LXX.
Build.VERSION_CODES.LOLLIPOP),
new KeyboardTheme(THEME_ID_LXX_DARK, "LXXDark", R.style.KeyboardTheme_LXX_Dark,
// This has never been selected as default theme.
VERSION_CODES.BASE),
};
static {
// Sort {@link #KEYBOARD_THEME} by descending order of {@link #mMinApiVersion}.
Arrays.sort(KEYBOARD_THEMES);
}
public final int mThemeId;
public final int mStyleId;
public final String mThemeName;
public final int mMinApiVersion;
// Note: The themeId should be aligned with "themeId" attribute of Keyboard style
// in values/themes-<style>.xml.
private KeyboardTheme(final int themeId, final String themeName, final int styleId,
final int minApiVersion) {
mThemeId = themeId;
mThemeName = themeName;
mStyleId = styleId;
mMinApiVersion = minApiVersion;
}
@Override
public int compareTo(final KeyboardTheme rhs) {
if (mMinApiVersion > rhs.mMinApiVersion) return -1;
if (mMinApiVersion < rhs.mMinApiVersion) return 1;
return 0;
}
@Override
public boolean equals(final Object o) {
if (o == this) return true;
return (o instanceof KeyboardTheme) && ((KeyboardTheme)o).mThemeId == mThemeId;
}
@Override
public int hashCode() {
return mThemeId;
}
/* package private for testing */
static KeyboardTheme searchKeyboardThemeById(final int themeId,
final KeyboardTheme[] availableThemeIds) {
// TODO: This search algorithm isn't optimal if there are many themes.
for (final KeyboardTheme theme : availableThemeIds) {
if (theme.mThemeId == themeId) {
return theme;
}
}
return null;
}
/* package private for testing */
static KeyboardTheme getDefaultKeyboardTheme(final SharedPreferences prefs,
final int sdkVersion, final KeyboardTheme[] availableThemeArray) {
final String klpThemeIdString = prefs.getString(KLP_KEYBOARD_THEME_KEY, null);
if (klpThemeIdString != null) {
if (sdkVersion <= VERSION_CODES.KITKAT) {
try {
final int themeId = Integer.parseInt(klpThemeIdString);
final KeyboardTheme theme = searchKeyboardThemeById(themeId,
availableThemeArray);
if (theme != null) {
return theme;
}
Log.w(TAG, "Unknown keyboard theme in KLP preference: " + klpThemeIdString);
} catch (final NumberFormatException e) {
Log.w(TAG, "Illegal keyboard theme in KLP preference: " + klpThemeIdString, e);
}
}
// Remove old preference.
Log.i(TAG, "Remove KLP keyboard theme preference: " + klpThemeIdString);
prefs.edit().remove(KLP_KEYBOARD_THEME_KEY).apply();
}
// TODO: This search algorithm isn't optimal if there are many themes.
for (final KeyboardTheme theme : availableThemeArray) {
if (sdkVersion >= theme.mMinApiVersion) {
return theme;
}
}
return searchKeyboardThemeById(DEFAULT_THEME_ID, availableThemeArray);
}
public static String getKeyboardThemeName(final int themeId) {
final KeyboardTheme theme = searchKeyboardThemeById(themeId, KEYBOARD_THEMES);
return theme.mThemeName;
}
public static void saveKeyboardThemeId(final int themeId, final SharedPreferences prefs) {
saveKeyboardThemeId(themeId, prefs, Build.VERSION.SDK_INT);
}
/* package private for testing */
static String getPreferenceKey(final int sdkVersion) {
if (sdkVersion <= VERSION_CODES.KITKAT) {
return KLP_KEYBOARD_THEME_KEY;
}
return LXX_KEYBOARD_THEME_KEY;
}
/* package private for testing */
static void saveKeyboardThemeId(final int themeId, final SharedPreferences prefs,
final int sdkVersion) {
final String prefKey = getPreferenceKey(sdkVersion);
prefs.edit().putString(prefKey, Integer.toString(themeId)).apply();
}
public static KeyboardTheme getKeyboardTheme(final Context context) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final KeyboardTheme[] availableThemeArray = getAvailableThemeArray(context);
return getKeyboardTheme(prefs, Build.VERSION.SDK_INT, availableThemeArray);
}
/* package private for testing */
static KeyboardTheme[] getAvailableThemeArray(final Context context) {
if (AVAILABLE_KEYBOARD_THEMES == null) {
final int[] availableThemeIdStringArray = context.getResources().getIntArray(
R.array.keyboard_theme_ids);
final ArrayList<KeyboardTheme> availableThemeList = new ArrayList<>();
for (final int id : availableThemeIdStringArray) {
final KeyboardTheme theme = searchKeyboardThemeById(id, KEYBOARD_THEMES);
if (theme != null) {
availableThemeList.add(theme);
}
}
AVAILABLE_KEYBOARD_THEMES = availableThemeList.toArray(
new KeyboardTheme[availableThemeList.size()]);
Arrays.sort(AVAILABLE_KEYBOARD_THEMES);
}
return AVAILABLE_KEYBOARD_THEMES;
}
/* package private for testing */
static KeyboardTheme getKeyboardTheme(final SharedPreferences prefs, final int sdkVersion,
final KeyboardTheme[] availableThemeArray) {
final String lxxThemeIdString = prefs.getString(LXX_KEYBOARD_THEME_KEY, null);
if (lxxThemeIdString == null) {
return getDefaultKeyboardTheme(prefs, sdkVersion, availableThemeArray);
}
try {
final int themeId = Integer.parseInt(lxxThemeIdString);
final KeyboardTheme theme = searchKeyboardThemeById(themeId, availableThemeArray);
if (theme != null) {
return theme;
}
Log.w(TAG, "Unknown keyboard theme in LXX preference: " + lxxThemeIdString);
} catch (final NumberFormatException e) {
Log.w(TAG, "Illegal keyboard theme in LXX preference: " + lxxThemeIdString, e);
}
// Remove preference that contains unknown or illegal theme id.
prefs.edit().remove(LXX_KEYBOARD_THEME_KEY).apply();
return getDefaultKeyboardTheme(prefs, sdkVersion, availableThemeArray);
}
}
| apache-2.0 |
facebook/presto | presto-common/src/main/java/com/facebook/presto/common/RuntimeMetricName.java | 1265 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.common;
/**
* Names for RuntimeMetrics used in the core presto code base.
* Connectors could use arbitrary metric names not included in this class.
*/
public class RuntimeMetricName
{
private RuntimeMetricName()
{
}
public static final String DRIVER_COUNT_PER_TASK = "driverCountPerTask";
public static final String TASK_ELAPSED_TIME_NANOS = "taskElapsedTimeNanos";
public static final String OPTIMIZED_WITH_MATERIALIZED_VIEW = "optimizedWithMaterializedView";
public static final String FRAGMENT_RESULT_CACHE_HIT = "fragmentResultCacheHitCount";
public static final String FRAGMENT_RESULT_CACHE_MISS = "fragmentResultCacheMissCount";
}
| apache-2.0 |
road-framework/ROADDesigner | au.edu.swin.ict.road.designer/src/au/edu/swin/ict/road/designer/smc/impl/SmcFactoryImpl.java | 14051 | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package au.edu.swin.ict.road.designer.smc.impl;
import au.edu.swin.ict.road.designer.smc.AcquisitionRegime;
import au.edu.swin.ict.road.designer.smc.BehaviorTerm;
import au.edu.swin.ict.road.designer.smc.Constraint;
import au.edu.swin.ict.road.designer.smc.Contract;
import au.edu.swin.ict.road.designer.smc.DeonticType;
import au.edu.swin.ict.road.designer.smc.DirectionType;
import au.edu.swin.ict.road.designer.smc.ExternalFactLink;
import au.edu.swin.ict.road.designer.smc.Fact;
import au.edu.swin.ict.road.designer.smc.FactAccessor;
import au.edu.swin.ict.road.designer.smc.FactLink;
import au.edu.swin.ict.road.designer.smc.InMsg;
import au.edu.swin.ict.road.designer.smc.MessageAnalyzer;
import au.edu.swin.ict.road.designer.smc.MessageType;
import au.edu.swin.ict.road.designer.smc.Mode;
import au.edu.swin.ict.road.designer.smc.Operation;
import au.edu.swin.ict.road.designer.smc.OutMsg;
import au.edu.swin.ict.road.designer.smc.Parameter;
import au.edu.swin.ict.road.designer.smc.Player;
import au.edu.swin.ict.road.designer.smc.PlayerBinding;
import au.edu.swin.ict.road.designer.smc.ProcessDefinition;
import au.edu.swin.ict.road.designer.smc.ProvisionRegime;
import au.edu.swin.ict.road.designer.smc.ResultMsg;
import au.edu.swin.ict.road.designer.smc.Role;
import au.edu.swin.ict.road.designer.smc.SMC;
import au.edu.swin.ict.road.designer.smc.SmcFactory;
import au.edu.swin.ict.road.designer.smc.SmcPackage;
import au.edu.swin.ict.road.designer.smc.SrcMsg;
import au.edu.swin.ict.road.designer.smc.Task;
import au.edu.swin.ict.road.designer.smc.TaskRef;
import au.edu.swin.ict.road.designer.smc.Term;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EFactoryImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Factory</b>.
* <!-- end-user-doc -->
* @generated
*/
public class SmcFactoryImpl extends EFactoryImpl implements SmcFactory {
/**
* Creates the default factory implementation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static SmcFactory init() {
try {
SmcFactory theSmcFactory = (SmcFactory)EPackage.Registry.INSTANCE.getEFactory("http://smc/1.0");
if (theSmcFactory != null) {
return theSmcFactory;
}
}
catch (Exception exception) {
EcorePlugin.INSTANCE.log(exception);
}
return new SmcFactoryImpl();
}
/**
* Creates an instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SmcFactoryImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public EObject create(EClass eClass) {
switch (eClass.getClassifierID()) {
case SmcPackage.SMC: return createSMC();
case SmcPackage.ROLE: return createRole();
case SmcPackage.CONTRACT: return createContract();
case SmcPackage.PROCESS_DEFINITION: return createProcessDefinition();
case SmcPackage.BEHAVIOR_TERM: return createBehaviorTerm();
case SmcPackage.PLAYER_BINDING: return createPlayerBinding();
case SmcPackage.MESSAGE_ANALYZER: return createMessageAnalyzer();
case SmcPackage.EXTERNAL_FACT_LINK: return createExternalFactLink();
case SmcPackage.ACQUISITION_REGIME: return createAcquisitionRegime();
case SmcPackage.PROVISION_REGIME: return createProvisionRegime();
case SmcPackage.TASK: return createTask();
case SmcPackage.IN_MSG: return createInMsg();
case SmcPackage.PARAMETER: return createParameter();
case SmcPackage.RESULT_MSG: return createResultMsg();
case SmcPackage.OUT_MSG: return createOutMsg();
case SmcPackage.TERM: return createTerm();
case SmcPackage.OPERATION: return createOperation();
case SmcPackage.CONSTRAINT: return createConstraint();
case SmcPackage.TASK_REF: return createTaskRef();
case SmcPackage.FACT: return createFact();
case SmcPackage.SYSTEM: return createSystem();
case SmcPackage.PLAYER: return createPlayer();
case SmcPackage.FACT_LINK: return createFactLink();
case SmcPackage.FACT_ACCESSOR: return createFactAccessor();
case SmcPackage.SRC_MSG: return createSrcMsg();
default:
throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object createFromString(EDataType eDataType, String initialValue) {
switch (eDataType.getClassifierID()) {
case SmcPackage.MESSAGE_TYPE:
return createMessageTypeFromString(eDataType, initialValue);
case SmcPackage.DEONTIC_TYPE:
return createDeonticTypeFromString(eDataType, initialValue);
case SmcPackage.DIRECTION_TYPE:
return createDirectionTypeFromString(eDataType, initialValue);
case SmcPackage.MODE:
return createModeFromString(eDataType, initialValue);
default:
throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String convertToString(EDataType eDataType, Object instanceValue) {
switch (eDataType.getClassifierID()) {
case SmcPackage.MESSAGE_TYPE:
return convertMessageTypeToString(eDataType, instanceValue);
case SmcPackage.DEONTIC_TYPE:
return convertDeonticTypeToString(eDataType, instanceValue);
case SmcPackage.DIRECTION_TYPE:
return convertDirectionTypeToString(eDataType, instanceValue);
case SmcPackage.MODE:
return convertModeToString(eDataType, instanceValue);
default:
throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SMC createSMC() {
SMCImpl smc = new SMCImpl();
return smc;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Role createRole() {
RoleImpl role = new RoleImpl();
return role;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Contract createContract() {
ContractImpl contract = new ContractImpl();
return contract;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ProcessDefinition createProcessDefinition() {
ProcessDefinitionImpl processDefinition = new ProcessDefinitionImpl();
return processDefinition;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BehaviorTerm createBehaviorTerm() {
BehaviorTermImpl behaviorTerm = new BehaviorTermImpl();
return behaviorTerm;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PlayerBinding createPlayerBinding() {
PlayerBindingImpl playerBinding = new PlayerBindingImpl();
return playerBinding;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MessageAnalyzer createMessageAnalyzer() {
MessageAnalyzerImpl messageAnalyzer = new MessageAnalyzerImpl();
return messageAnalyzer;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ExternalFactLink createExternalFactLink() {
ExternalFactLinkImpl externalFactLink = new ExternalFactLinkImpl();
return externalFactLink;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public AcquisitionRegime createAcquisitionRegime() {
AcquisitionRegimeImpl acquisitionRegime = new AcquisitionRegimeImpl();
return acquisitionRegime;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ProvisionRegime createProvisionRegime() {
ProvisionRegimeImpl provisionRegime = new ProvisionRegimeImpl();
return provisionRegime;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Task createTask() {
TaskImpl task = new TaskImpl();
return task;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public InMsg createInMsg() {
InMsgImpl inMsg = new InMsgImpl();
return inMsg;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Parameter createParameter() {
ParameterImpl parameter = new ParameterImpl();
return parameter;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ResultMsg createResultMsg() {
ResultMsgImpl resultMsg = new ResultMsgImpl();
return resultMsg;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public OutMsg createOutMsg() {
OutMsgImpl outMsg = new OutMsgImpl();
return outMsg;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Term createTerm() {
TermImpl term = new TermImpl();
return term;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Operation createOperation() {
OperationImpl operation = new OperationImpl();
return operation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Constraint createConstraint() {
ConstraintImpl constraint = new ConstraintImpl();
return constraint;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TaskRef createTaskRef() {
TaskRefImpl taskRef = new TaskRefImpl();
return taskRef;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Fact createFact() {
FactImpl fact = new FactImpl();
return fact;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public au.edu.swin.ict.road.designer.smc.System createSystem() {
SystemImpl system = new SystemImpl();
return system;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Player createPlayer() {
PlayerImpl player = new PlayerImpl();
return player;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public FactLink createFactLink() {
FactLinkImpl factLink = new FactLinkImpl();
return factLink;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public FactAccessor createFactAccessor() {
FactAccessorImpl factAccessor = new FactAccessorImpl();
return factAccessor;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SrcMsg createSrcMsg() {
SrcMsgImpl srcMsg = new SrcMsgImpl();
return srcMsg;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MessageType createMessageTypeFromString(EDataType eDataType, String initialValue) {
MessageType result = MessageType.get(initialValue);
if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
return result;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String convertMessageTypeToString(EDataType eDataType, Object instanceValue) {
return instanceValue == null ? null : instanceValue.toString();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DeonticType createDeonticTypeFromString(EDataType eDataType, String initialValue) {
DeonticType result = DeonticType.get(initialValue);
if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
return result;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String convertDeonticTypeToString(EDataType eDataType, Object instanceValue) {
return instanceValue == null ? null : instanceValue.toString();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DirectionType createDirectionTypeFromString(EDataType eDataType, String initialValue) {
DirectionType result = DirectionType.get(initialValue);
if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
return result;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String convertDirectionTypeToString(EDataType eDataType, Object instanceValue) {
return instanceValue == null ? null : instanceValue.toString();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Mode createModeFromString(EDataType eDataType, String initialValue) {
Mode result = Mode.get(initialValue);
if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
return result;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String convertModeToString(EDataType eDataType, Object instanceValue) {
return instanceValue == null ? null : instanceValue.toString();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SmcPackage getSmcPackage() {
return (SmcPackage)getEPackage();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @deprecated
* @generated
*/
@Deprecated
public static SmcPackage getPackage() {
return SmcPackage.eINSTANCE;
}
} //SmcFactoryImpl
| apache-2.0 |
UnquietCode/Flapi | src/main/java/unquietcode/tools/flapi/graph/components/Transition.java | 2639 | /*********************************************************************
Copyright 2014 the Flapi 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 unquietcode.tools.flapi.graph.components;
import unquietcode.tools.flapi.graph.GenericVisitor;
import unquietcode.tools.flapi.graph.TransitionVisitor;
import unquietcode.tools.flapi.java.MethodSignature;
import unquietcode.tools.flapi.outline.MethodInfo;
import unquietcode.tools.flapi.runtime.TransitionType;
import java.util.ArrayList;
import java.util.List;
/**
* @author Ben Fagin
* @version 07-10-2012
*/
public abstract class Transition implements Comparable<Transition> {
private final List<StateClass> stateChain = new ArrayList<StateClass>();
private final List<Integer> chainParameterPositions = new ArrayList<Integer>();
private final TransitionType type;
private MethodInfo methodInfo = new MethodInfo();
private StateClass owner;
protected Transition(TransitionType type) {
this.type = type;
}
public TransitionType getType() {
return type;
}
public abstract void accept(TransitionVisitor visitor);
public void acceptForTraversal(GenericVisitor<StateClass> visitor) {
for (StateClass stateClass : stateChain) {
visitor.visit(stateClass);
}
}
public List<StateClass> getStateChain() {
return stateChain;
}
@Override
public int compareTo(Transition other) {
return methodInfo.getMethodSignature().compareTo(other.info().getMethodSignature());
}
void setOwner(StateClass owner) {
this.owner = owner;
}
public StateClass getOwner() {
return owner;
}
public MethodSignature getMethodSignature() {
return methodInfo.getMethodSignature();
}
public List<Integer> getChainParameterPositions() {
return chainParameterPositions;
}
public MethodInfo info() {
return methodInfo;
}
public void setMethodInfo(MethodInfo methodInfo) {
this.methodInfo = methodInfo;
}
public abstract Transition basicCopy();
protected void copy(Transition copy) {
copy.methodInfo = this.methodInfo.basicCopy();
copy.stateChain.addAll(this.stateChain);
}
} | apache-2.0 |
crate/crate | extensions/lang-js/src/main/java/io/crate/operation/language/JavaScriptLanguage.java | 4047 | /*
* Licensed to Crate.io GmbH ("Crate") under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. Crate licenses
* this file to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial agreement.
*/
package io.crate.operation.language;
import io.crate.expression.udf.UDFLanguage;
import io.crate.expression.udf.UserDefinedFunctionMetadata;
import io.crate.expression.udf.UserDefinedFunctionService;
import io.crate.metadata.Scalar;
import io.crate.metadata.functions.Signature;
import io.crate.types.DataType;
import org.elasticsearch.common.inject.Inject;
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Engine;
import org.graalvm.polyglot.HostAccess;
import org.graalvm.polyglot.PolyglotException;
import org.graalvm.polyglot.Source;
import org.graalvm.polyglot.Value;
import javax.annotation.Nullable;
import javax.script.ScriptException;
import java.io.IOException;
import java.util.Locale;
import java.util.stream.Collectors;
public class JavaScriptLanguage implements UDFLanguage {
static final String NAME = "javascript";
private static final Engine ENGINE = Engine.newBuilder()
.option("js.foreign-object-prototype", "true")
.option("engine.WarnInterpreterOnly", "false")
.build();
private static final HostAccess HOST_ACCESS = HostAccess.newBuilder()
.allowListAccess(true)
.allowArrayAccess(true)
.build();
@Inject
public JavaScriptLanguage(UserDefinedFunctionService udfService) {
udfService.registerLanguage(this);
}
public Scalar createFunctionImplementation(UserDefinedFunctionMetadata meta,
Signature signature) throws ScriptException {
return new JavaScriptUserDefinedFunction(signature, meta.definition());
}
@Nullable
public String validate(UserDefinedFunctionMetadata meta) {
try {
resolvePolyglotFunctionValue(meta.name(), meta.definition());
return null;
} catch (IllegalArgumentException | IOException | PolyglotException t) {
return String.format(Locale.ENGLISH, "Invalid JavaScript in function '%s.%s(%s)' AS '%s': %s",
meta.schema(),
meta.name(),
meta.argumentTypes().stream().map(DataType::getName).collect(Collectors.joining(", ")),
meta.definition(),
t.getMessage()
);
}
}
static Value resolvePolyglotFunctionValue(String functionName, String script) throws IOException {
var context = Context.newBuilder("js")
.engine(ENGINE)
.allowHostAccess(HOST_ACCESS)
.build();
var source = Source.newBuilder("js", script, functionName).build();
context.eval(source);
var polyglotFunctionValue = context.getBindings("js").getMember(functionName);
if (polyglotFunctionValue == null) {
throw new IllegalArgumentException(
"The name of the function signature '" + functionName + "' doesn't match " +
"the function name in the function definition.");
}
return polyglotFunctionValue;
}
public String name() {
return NAME;
}
}
| apache-2.0 |
piotr-j/VisEditor | plugins/vis-runtime-spine/src/main/java/com/esotericsoftware/spine/Skeleton.java | 15933 | /******************************************************************************
* Spine Runtimes Software License
* Version 2.3
*
* Copyright (c) 2013-2015, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable and
* non-transferable license to use, install, execute and perform the Spine
* Runtimes Software (the "Software") and derivative works solely for personal
* or internal use. Without the written permission of Esoteric Software (see
* Section 2 of the Spine Software License Agreement), you may not (a) modify,
* translate, adapt or otherwise create derivative works, improvements of the
* Software or develop new applications using the Software or (b) remove,
* delete, alter or obscure any trademarks or any copyright, trademark, patent
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
package com.esotericsoftware.spine;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;
import com.esotericsoftware.spine.attachments.Attachment;
import com.esotericsoftware.spine.attachments.MeshAttachment;
import com.esotericsoftware.spine.attachments.RegionAttachment;
import com.esotericsoftware.spine.attachments.WeightedMeshAttachment;
public class Skeleton {
final SkeletonData data;
final Array<Bone> bones;
final Array<Slot> slots;
Array<Slot> drawOrder;
final Array<IkConstraint> ikConstraints;
final Array<TransformConstraint> transformConstraints;
private final Array<Updatable> updateCache = new Array();
Skin skin;
final Color color;
float time;
boolean flipX, flipY;
float x, y;
public Skeleton (SkeletonData data) {
if (data == null) throw new IllegalArgumentException("data cannot be null.");
this.data = data;
bones = new Array(data.bones.size);
for (BoneData boneData : data.bones) {
Bone parent = boneData.parent == null ? null : bones.get(data.bones.indexOf(boneData.parent, true));
bones.add(new Bone(boneData, this, parent));
}
slots = new Array(data.slots.size);
drawOrder = new Array(data.slots.size);
for (SlotData slotData : data.slots) {
Bone bone = bones.get(data.bones.indexOf(slotData.boneData, true));
Slot slot = new Slot(slotData, bone);
slots.add(slot);
drawOrder.add(slot);
}
ikConstraints = new Array(data.ikConstraints.size);
for (IkConstraintData ikConstraintData : data.ikConstraints)
ikConstraints.add(new IkConstraint(ikConstraintData, this));
transformConstraints = new Array(data.transformConstraints.size);
for (TransformConstraintData transformConstraintData : data.transformConstraints)
transformConstraints.add(new TransformConstraint(transformConstraintData, this));
color = new Color(1, 1, 1, 1);
updateCache();
}
/** Copy constructor. */
public Skeleton (Skeleton skeleton) {
if (skeleton == null) throw new IllegalArgumentException("skeleton cannot be null.");
data = skeleton.data;
bones = new Array(skeleton.bones.size);
for (Bone bone : skeleton.bones) {
Bone parent = bone.parent == null ? null : bones.get(skeleton.bones.indexOf(bone.parent, true));
bones.add(new Bone(bone, this, parent));
}
slots = new Array(skeleton.slots.size);
for (Slot slot : skeleton.slots) {
Bone bone = bones.get(skeleton.bones.indexOf(slot.bone, true));
slots.add(new Slot(slot, bone));
}
drawOrder = new Array(slots.size);
for (Slot slot : skeleton.drawOrder)
drawOrder.add(slots.get(skeleton.slots.indexOf(slot, true)));
ikConstraints = new Array(skeleton.ikConstraints.size);
for (IkConstraint ikConstraint : skeleton.ikConstraints)
ikConstraints.add(new IkConstraint(ikConstraint, this));
transformConstraints = new Array(skeleton.transformConstraints.size);
for (TransformConstraint transformConstraint : skeleton.transformConstraints)
transformConstraints.add(new TransformConstraint(transformConstraint, this));
skin = skeleton.skin;
color = new Color(skeleton.color);
time = skeleton.time;
flipX = skeleton.flipX;
flipY = skeleton.flipY;
updateCache();
}
/** Caches information about bones and constraints. Must be called if bones or constraints are added or removed. */
public void updateCache () {
Array<Bone> bones = this.bones;
Array<Updatable> updateCache = this.updateCache;
Array<IkConstraint> ikConstraints = this.ikConstraints;
Array<TransformConstraint> transformConstraints = this.transformConstraints;
int ikConstraintsCount = ikConstraints.size;
int transformConstraintsCount = transformConstraints.size;
updateCache.clear();
for (int i = 0, n = bones.size; i < n; i++) {
Bone bone = bones.get(i);
updateCache.add(bone);
for (int ii = 0; ii < ikConstraintsCount; ii++) {
IkConstraint ikConstraint = ikConstraints.get(ii);
if (bone == ikConstraint.bones.peek()) {
updateCache.add(ikConstraint);
break;
}
}
}
for (int i = 0; i < transformConstraintsCount; i++) {
TransformConstraint transformConstraint = transformConstraints.get(i);
for (int ii = updateCache.size - 1; ii >= 0; ii--) {
if (updateCache.get(ii) == transformConstraint.bone) {
updateCache.insert(ii + 1, transformConstraint);
break;
}
}
}
}
/** Updates the world transform for each bone and applies constraints. */
public void updateWorldTransform () {
Array<Updatable> updateCache = this.updateCache;
for (int i = 0, n = updateCache.size; i < n; i++)
updateCache.get(i).update();
}
/** Sets the bones, constraints, and slots to their setup pose values. */
public void setToSetupPose () {
setBonesToSetupPose();
setSlotsToSetupPose();
}
/** Sets the bones and constraints to their setup pose values. */
public void setBonesToSetupPose () {
Array<Bone> bones = this.bones;
for (int i = 0, n = bones.size; i < n; i++)
bones.get(i).setToSetupPose();
Array<IkConstraint> ikConstraints = this.ikConstraints;
for (int i = 0, n = ikConstraints.size; i < n; i++) {
IkConstraint constraint = ikConstraints.get(i);
constraint.bendDirection = constraint.data.bendDirection;
constraint.mix = constraint.data.mix;
}
Array<TransformConstraint> transformConstraints = this.transformConstraints;
for (int i = 0, n = transformConstraints.size; i < n; i++) {
TransformConstraint constraint = transformConstraints.get(i);
TransformConstraintData data = constraint.data;
constraint.rotateMix = data.rotateMix;
constraint.translateMix = data.translateMix;
constraint.scaleMix = data.scaleMix;
constraint.shearMix = data.shearMix;
}
}
public void setSlotsToSetupPose () {
Array<Slot> slots = this.slots;
System.arraycopy(slots.items, 0, drawOrder.items, 0, slots.size);
for (int i = 0, n = slots.size; i < n; i++)
slots.get(i).setToSetupPose(i);
}
public SkeletonData getData () {
return data;
}
public Array<Bone> getBones () {
return bones;
}
/** @return May return null. */
public Bone getRootBone () {
if (bones.size == 0) return null;
return bones.first();
}
/** @return May be null. */
public Bone findBone (String boneName) {
if (boneName == null) throw new IllegalArgumentException("boneName cannot be null.");
Array<Bone> bones = this.bones;
for (int i = 0, n = bones.size; i < n; i++) {
Bone bone = bones.get(i);
if (bone.data.name.equals(boneName)) return bone;
}
return null;
}
/** @return -1 if the bone was not found. */
public int findBoneIndex (String boneName) {
if (boneName == null) throw new IllegalArgumentException("boneName cannot be null.");
Array<Bone> bones = this.bones;
for (int i = 0, n = bones.size; i < n; i++)
if (bones.get(i).data.name.equals(boneName)) return i;
return -1;
}
public Array<Slot> getSlots () {
return slots;
}
/** @return May be null. */
public Slot findSlot (String slotName) {
if (slotName == null) throw new IllegalArgumentException("slotName cannot be null.");
Array<Slot> slots = this.slots;
for (int i = 0, n = slots.size; i < n; i++) {
Slot slot = slots.get(i);
if (slot.data.name.equals(slotName)) return slot;
}
return null;
}
/** @return -1 if the bone was not found. */
public int findSlotIndex (String slotName) {
if (slotName == null) throw new IllegalArgumentException("slotName cannot be null.");
Array<Slot> slots = this.slots;
for (int i = 0, n = slots.size; i < n; i++)
if (slots.get(i).data.name.equals(slotName)) return i;
return -1;
}
/** Returns the slots in the order they will be drawn. The returned array may be modified to change the draw order. */
public Array<Slot> getDrawOrder () {
return drawOrder;
}
/** Sets the slots and the order they will be drawn. */
public void setDrawOrder (Array<Slot> drawOrder) {
this.drawOrder = drawOrder;
}
/** @return May be null. */
public Skin getSkin () {
return skin;
}
/** Sets a skin by name.
* @see #setSkin(Skin) */
public void setSkin (String skinName) {
Skin skin = data.findSkin(skinName);
if (skin == null) throw new IllegalArgumentException("Skin not found: " + skinName);
setSkin(skin);
}
/** Sets the skin used to look up attachments before looking in the {@link SkeletonData#getDefaultSkin() default skin}.
* Attachments from the new skin are attached if the corresponding attachment from the old skin was attached. If there was no
* old skin, each slot's setup mode attachment is attached from the new skin.
* @param newSkin May be null. */
public void setSkin (Skin newSkin) {
if (newSkin != null) {
if (skin != null)
newSkin.attachAll(this, skin);
else {
Array<Slot> slots = this.slots;
for (int i = 0, n = slots.size; i < n; i++) {
Slot slot = slots.get(i);
String name = slot.data.attachmentName;
if (name != null) {
Attachment attachment = newSkin.getAttachment(i, name);
if (attachment != null) slot.setAttachment(attachment);
}
}
}
}
skin = newSkin;
}
/** @return May be null. */
public Attachment getAttachment (String slotName, String attachmentName) {
return getAttachment(data.findSlotIndex(slotName), attachmentName);
}
/** @return May be null. */
public Attachment getAttachment (int slotIndex, String attachmentName) {
if (attachmentName == null) throw new IllegalArgumentException("attachmentName cannot be null.");
if (skin != null) {
Attachment attachment = skin.getAttachment(slotIndex, attachmentName);
if (attachment != null) return attachment;
}
if (data.defaultSkin != null) return data.defaultSkin.getAttachment(slotIndex, attachmentName);
return null;
}
/** @param attachmentName May be null. */
public void setAttachment (String slotName, String attachmentName) {
if (slotName == null) throw new IllegalArgumentException("slotName cannot be null.");
Array<Slot> slots = this.slots;
for (int i = 0, n = slots.size; i < n; i++) {
Slot slot = slots.get(i);
if (slot.data.name.equals(slotName)) {
Attachment attachment = null;
if (attachmentName != null) {
attachment = getAttachment(i, attachmentName);
if (attachment == null)
throw new IllegalArgumentException("Attachment not found: " + attachmentName + ", for slot: " + slotName);
}
slot.setAttachment(attachment);
return;
}
}
throw new IllegalArgumentException("Slot not found: " + slotName);
}
public Array<IkConstraint> getIkConstraints () {
return ikConstraints;
}
/** @return May be null. */
public IkConstraint findIkConstraint (String constraintName) {
if (constraintName == null) throw new IllegalArgumentException("constraintName cannot be null.");
Array<IkConstraint> ikConstraints = this.ikConstraints;
for (int i = 0, n = ikConstraints.size; i < n; i++) {
IkConstraint ikConstraint = ikConstraints.get(i);
if (ikConstraint.data.name.equals(constraintName)) return ikConstraint;
}
return null;
}
public Array<TransformConstraint> getTransformConstraints () {
return transformConstraints;
}
/** @return May be null. */
public TransformConstraint findTransformConstraint (String constraintName) {
if (constraintName == null) throw new IllegalArgumentException("constraintName cannot be null.");
Array<TransformConstraint> transformConstraints = this.transformConstraints;
for (int i = 0, n = transformConstraints.size; i < n; i++) {
TransformConstraint constraint = transformConstraints.get(i);
if (constraint.data.name.equals(constraintName)) return constraint;
}
return null;
}
/** Returns the axis aligned bounding box (AABB) of the region, mesh, and skinned mesh attachments for the current pose.
* @param offset The distance from the skeleton origin to the bottom left corner of the AABB.
* @param size The width and height of the AABB. */
public void getBounds (Vector2 offset, Vector2 size) {
Array<Slot> drawOrder = this.drawOrder;
float minX = Integer.MAX_VALUE, minY = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE, maxY = Integer.MIN_VALUE;
for (int i = 0, n = drawOrder.size; i < n; i++) {
Slot slot = drawOrder.get(i);
float[] vertices = null;
Attachment attachment = slot.attachment;
if (attachment instanceof RegionAttachment) {
vertices = ((RegionAttachment)attachment).updateWorldVertices(slot, false);
} else if (attachment instanceof MeshAttachment) {
vertices = ((MeshAttachment)attachment).updateWorldVertices(slot, true);
} else if (attachment instanceof WeightedMeshAttachment) {
vertices = ((WeightedMeshAttachment)attachment).updateWorldVertices(slot, true);
}
if (vertices != null) {
for (int ii = 0, nn = vertices.length; ii < nn; ii += 5) {
float x = vertices[ii], y = vertices[ii + 1];
minX = Math.min(minX, x);
minY = Math.min(minY, y);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
}
}
}
offset.set(minX, minY);
size.set(maxX - minX, maxY - minY);
}
public Color getColor () {
return color;
}
/** A convenience method for setting the skeleton color. The color can also be set by modifying {@link #getColor()}. */
public void setColor (Color color) {
this.color.set(color);
}
public boolean getFlipX () {
return flipX;
}
public void setFlipX (boolean flipX) {
this.flipX = flipX;
}
public boolean getFlipY () {
return flipY;
}
public void setFlipY (boolean flipY) {
this.flipY = flipY;
}
public void setFlip (boolean flipX, boolean flipY) {
this.flipX = flipX;
this.flipY = flipY;
}
public float getX () {
return x;
}
public void setX (float x) {
this.x = x;
}
public float getY () {
return y;
}
public void setY (float y) {
this.y = y;
}
public void setPosition (float x, float y) {
this.x = x;
this.y = y;
}
public float getTime () {
return time;
}
public void setTime (float time) {
this.time = time;
}
public void update (float delta) {
time += delta;
}
public String toString () {
return data.name != null ? data.name : super.toString();
}
}
| apache-2.0 |
dCache/jglobus-1.8 | src/org/globus/tools/ui/config/EJPanel.java | 1541 | /*
* Copyright 1999-2006 University of Chicago
*
* 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.globus.tools.ui.config;
import javax.swing.JOptionPane;
import java.awt.Insets;
import java.awt.Font;
import java.io.File;
import org.globus.tools.ui.util.JJPanel;
public class EJPanel extends JJPanel {
public static final String SIDE_TITLE = "Java CoG Kit";
public boolean checkFile(String file, String name) {
String msg = null;
if (file.length() == 0) {
msg = name + " must be specified.";
} else {
File f = new File(file);
if (!f.exists()) {
msg = name + " file not found.";
}
}
if (msg != null) {
JOptionPane.showMessageDialog(this, msg, name + " Error",
JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
public Insets getInsets() {
return new Insets(5, 5, 5, 5);
}
protected Font getFont(Font srcFont, int sizeDiff) {
return new Font(srcFont.getName(),
srcFont.getStyle(),
srcFont.getSize() + sizeDiff);
}
}
| apache-2.0 |
somnusdear/coolweather | app/src/main/java/com/somnusdear/coolweather/db/City.java | 848 | package com.somnusdear.coolweather.db;
import org.litepal.crud.DataSupport;
/**
* Created by Administrator on 2017/9/2.
*/
public class City extends DataSupport {
private int id;
private String cityName;
private int cityCode;
private int provinceId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public int getCityCode() {
return cityCode;
}
public void setCityCode(int cityCode) {
this.cityCode = cityCode;
}
public int getProvinceId() {
return provinceId;
}
public void setProvinceId(int provinceId) {
this.provinceId = provinceId;
}
}
| apache-2.0 |
mvs5465/jpo-ode | jpo-ode-core/src/main/java/us/dot/its/jpo/ode/model/ControlMessage.java | 2391 | /*******************************************************************************
* Copyright (c) 2015 US DOT - Joint Program Office
*
* The Government has unlimited rights to all documents/material produced under
* this task order. All documents and materials, to include the source code of
* any software produced under this contract, shall be Government owned and the
* property of the Government with all rights and privileges of ownership/copyright
* belonging exclusively to the Government. These documents and materials may
* not be used or sold by the Contractor without written permission from the CO.
* All materials supplied to the Government shall be the sole property of the
* Government and may not be used for any other purpose. This right does not
* abrogate any other Government rights.
*
* Contributors:
* Booz | Allen | Hamilton - initial API and implementation
*******************************************************************************/
package us.dot.its.jpo.ode.model;
import us.dot.its.jpo.ode.model.DdsRequest.Dialog;
public class ControlMessage {
private ControlTag tag;
private String encoding;
private Dialog dialog;
private long recordCount;
private String connectionDetails;
public ControlMessage() {
super();
}
public ControlMessage(ControlTag tag, String encoding, Dialog dialog) {
super();
this.tag = tag;
this.encoding = encoding;
this.dialog = dialog;
}
public ControlTag getTag() {
return tag;
}
public ControlMessage setTag(ControlTag tag) {
this.tag = tag;
return this;
}
public String getEncoding() {
return encoding;
}
public ControlMessage setEncoding(String encoding) {
this.encoding = encoding;
return this;
}
public Dialog getDialog() {
return dialog;
}
public ControlMessage setDialog(Dialog dialog) {
this.dialog = dialog;
return this;
}
public long getRecordCount() {
return recordCount;
}
public ControlMessage setRecordCount(long recordCount) {
this.recordCount = recordCount;
return this;
}
public String getConnectionDetails() {
return connectionDetails;
}
public ControlMessage setConnectionDetails(String connectionDetails) {
this.connectionDetails = connectionDetails;
return this;
}
}
| apache-2.0 |
lakshmiDRIP/DRIP | src/main/java/org/drip/analytics/support/LossQuadratureGenerator.java | 10937 |
package org.drip.analytics.support;
/*
* -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*/
/*!
* Copyright (C) 2017 Lakshmi Krishnamurthy
* Copyright (C) 2016 Lakshmi Krishnamurthy
* Copyright (C) 2015 Lakshmi Krishnamurthy
* Copyright (C) 2014 Lakshmi Krishnamurthy
* Copyright (C) 2013 Lakshmi Krishnamurthy
* Copyright (C) 2012 Lakshmi Krishnamurthy
* Copyright (C) 2011 Lakshmi Krishnamurthy
*
* This file is part of DRIP, a free-software/open-source library for buy/side financial/trading model
* libraries targeting analysts and developers
* https://lakshmidrip.github.io/DRIP/
*
* DRIP is composed of four main libraries:
*
* - DRIP Fixed Income - https://lakshmidrip.github.io/DRIP-Fixed-Income/
* - DRIP Asset Allocation - https://lakshmidrip.github.io/DRIP-Asset-Allocation/
* - DRIP Numerical Optimizer - https://lakshmidrip.github.io/DRIP-Numerical-Optimizer/
* - DRIP Statistical Learning - https://lakshmidrip.github.io/DRIP-Statistical-Learning/
*
* - DRIP Fixed Income: Library for Instrument/Trading Conventions, Treasury Futures/Options,
* Funding/Forward/Overnight Curves, Multi-Curve Construction/Valuation, Collateral Valuation and XVA
* Metric Generation, Calibration and Hedge Attributions, Statistical Curve Construction, Bond RV
* Metrics, Stochastic Evolution and Option Pricing, Interest Rate Dynamics and Option Pricing, LMM
* Extensions/Calibrations/Greeks, Algorithmic Differentiation, and Asset Backed Models and Analytics.
*
* - DRIP Asset Allocation: Library for model libraries for MPT framework, Black Litterman Strategy
* Incorporator, Holdings Constraint, and Transaction Costs.
*
* - DRIP Numerical Optimizer: Library for Numerical Optimization and Spline Functionality.
*
* - DRIP Statistical Learning: Library for Statistical Evaluation and Machine Learning.
*
* 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.
*/
/**
* LossQuadratureGenerator generates the decomposed Integrand Quadrature for the Loss Steps.
*
* @author Lakshmi Krishnamurthy
*/
public class LossQuadratureGenerator {
/**
* Generate the Set of Loss Quadrature Metrics from the Day Step Loss Periods
*
* @param comp Component for which the measures are to be generated
* @param valParams ValuationParams from which the periods are generated
* @param period The enveloping coupon period
* @param iWorkoutDate Date representing the absolute end of all the generated periods
* @param iPeriodUnit Day Step Size Unit of the generated Loss Quadrature Periods
* @param csqs The Market Parameters Curves/Quotes
*
* @return List of the generated LossQuadratureMetrics
*/
public static final java.util.List<org.drip.analytics.cashflow.LossQuadratureMetrics>
GenerateDayStepLossPeriods (
final org.drip.product.definition.CreditComponent comp,
final org.drip.param.valuation.ValuationParams valParams,
final org.drip.analytics.cashflow.CompositePeriod period,
final int iWorkoutDate,
final int iPeriodUnit,
final org.drip.param.market.CurveSurfaceQuoteContainer csqs)
{
if (null == comp || null == valParams || null == period || null == csqs) return null;
org.drip.state.discount.MergedDiscountForwardCurve dc = csqs.fundingState
(org.drip.state.identifier.FundingLabel.Standard (comp.payCurrency()));
if (null == dc) return null;
org.drip.state.credit.CreditCurve cc = csqs.creditState (comp.creditLabel());
if (null == cc) return null;
int iLossPayLag = comp.creditValuationParams().lossPayLag();
int iSubPeriodStartDate = period.startDate();
if (iSubPeriodStartDate > iWorkoutDate) return null;
int iPeriodEndDate = period.endDate();
int iValueDate = valParams.valueDate();
boolean bPeriodDone = false;
iPeriodEndDate = iPeriodEndDate < iWorkoutDate ? iPeriodEndDate : iWorkoutDate;
iSubPeriodStartDate = iSubPeriodStartDate < iValueDate ? iValueDate : iSubPeriodStartDate;
java.util.List<org.drip.analytics.cashflow.LossQuadratureMetrics> sLP = new
java.util.ArrayList<org.drip.analytics.cashflow.LossQuadratureMetrics>();
while (!bPeriodDone) {
int iSubPeriodEndDate = iSubPeriodStartDate + iPeriodUnit;
if (iSubPeriodEndDate < iValueDate) return null;
if (iSubPeriodEndDate >= iPeriodEndDate) {
bPeriodDone = true;
iSubPeriodEndDate = iPeriodEndDate;
}
try {
org.drip.analytics.cashflow.LossQuadratureMetrics lp =
org.drip.analytics.cashflow.LossQuadratureMetrics.MakeDefaultPeriod (iSubPeriodStartDate,
iSubPeriodEndDate, period.accrualDCF ((iSubPeriodStartDate + iSubPeriodEndDate) / 2),
comp.notional (iSubPeriodStartDate, iSubPeriodEndDate), comp.recovery
(iSubPeriodStartDate, iSubPeriodEndDate, cc), dc, cc, iLossPayLag);
if (null != lp) sLP.add (lp);
} catch (java.lang.Exception e) {
e.printStackTrace();
return null;
}
iSubPeriodStartDate = iSubPeriodEndDate;
}
return sLP;
}
/**
* Generate the Set of Loss Quadrature Metrics from the Day Step Loss Periods
*
* @param comp Component for which the measures are to be generated
* @param valParams ValuationParams from which the periods are generated
* @param period The enveloping coupon period
* @param iWorkoutDate The absolute end of all the generated periods
* @param iPeriodUnit Loss Grid Size Unit of the generated Loss Quadrature Periods
* @param csqs The Market Parameters Curves/Quotes
*
* @return List of the generated LossQuadratureMetrics
*/
public static final java.util.List<org.drip.analytics.cashflow.LossQuadratureMetrics>
GeneratePeriodUnitLossPeriods (
final org.drip.product.definition.CreditComponent comp,
final org.drip.param.valuation.ValuationParams valParams,
final org.drip.analytics.cashflow.CompositePeriod period,
final int iWorkoutDate,
final int iPeriodUnit,
final org.drip.param.market.CurveSurfaceQuoteContainer csqs)
{
if (null == comp || null == valParams || null == period || null == csqs) return null;
org.drip.state.discount.MergedDiscountForwardCurve dc = csqs.fundingState
(org.drip.state.identifier.FundingLabel.Standard (comp.payCurrency()));
if (null == dc) return null;
org.drip.state.credit.CreditCurve cc = csqs.creditState (comp.creditLabel());
if (null == cc) return null;
int iValueDate = valParams.valueDate();
int iPeriodEndDate = period.endDate();
int iSubPeriodStartDate = period.startDate();
boolean bPeriodDone = false;
iPeriodEndDate = iPeriodEndDate < iWorkoutDate ? iPeriodEndDate : iWorkoutDate;
iSubPeriodStartDate = iSubPeriodStartDate < iValueDate ? iValueDate : iSubPeriodStartDate;
int iDayStep = (iPeriodEndDate - iSubPeriodStartDate) / iPeriodUnit;
if (iSubPeriodStartDate > iWorkoutDate || iPeriodEndDate < iValueDate) return null;
if (iDayStep < org.drip.param.pricer.CreditPricerParams.PERIOD_DAY_STEPS_MINIMUM)
iDayStep = org.drip.param.pricer.CreditPricerParams.PERIOD_DAY_STEPS_MINIMUM;
int iLossPayLag = comp.creditValuationParams().lossPayLag();
java.util.List<org.drip.analytics.cashflow.LossQuadratureMetrics> sLP = new
java.util.ArrayList<org.drip.analytics.cashflow.LossQuadratureMetrics>();
while (!bPeriodDone) {
int iSubPeriodEndDate = iSubPeriodStartDate + iDayStep;
if (iSubPeriodEndDate < iValueDate) return null;
try {
if (iSubPeriodEndDate >= iPeriodEndDate) {
bPeriodDone = true;
iSubPeriodEndDate = iPeriodEndDate;
}
org.drip.analytics.cashflow.LossQuadratureMetrics lp =
org.drip.analytics.cashflow.LossQuadratureMetrics.MakeDefaultPeriod (iSubPeriodStartDate,
iSubPeriodEndDate, period.accrualDCF ((iSubPeriodStartDate + iSubPeriodEndDate) / 2),
comp.notional (iSubPeriodStartDate, iSubPeriodEndDate), comp.recovery
(iSubPeriodStartDate, iSubPeriodEndDate, cc), dc, cc, iLossPayLag);
if (null != lp) sLP.add (lp);
} catch (java.lang.Exception e) {
e.printStackTrace();
return null;
}
iSubPeriodStartDate = iSubPeriodEndDate;
}
return sLP;
}
/**
* Generate the Set of Loss Quadrature Metrics from the Day Step Loss Periods
*
* @param comp Component for which the measures are to be generated
* @param valParams ValuationParams from which the periods are generated
* @param period The Enveloping Coupon period
* @param iWorkoutDate The Absolute End of all the generated periods
* @param csqs The Market Parameters Curves/Quotes
*
* @return List of the generated LossQuadratureMetrics
*/
public static final java.util.List<org.drip.analytics.cashflow.LossQuadratureMetrics>
GenerateWholeLossPeriods (
final org.drip.product.definition.CreditComponent comp,
final org.drip.param.valuation.ValuationParams valParams,
final org.drip.analytics.cashflow.CompositePeriod period,
final int iWorkoutDate,
final org.drip.param.market.CurveSurfaceQuoteContainer csqs)
{
if (null == comp || null == valParams || null == period || null == csqs) return null;
org.drip.state.discount.MergedDiscountForwardCurve dc = csqs.fundingState
(org.drip.state.identifier.FundingLabel.Standard (comp.payCurrency()));
if (null == dc) return null;
org.drip.state.credit.CreditCurve cc = csqs.creditState (comp.creditLabel());
if (null == cc) return null;
int iPeriodStartDate = period.startDate();
if (iPeriodStartDate > iWorkoutDate) return null;
int iPeriodEndDate = period.endDate();
int iValueDate = valParams.valueDate();
iPeriodStartDate = iPeriodStartDate < iValueDate ? iValueDate : iPeriodStartDate;
iPeriodEndDate = iPeriodEndDate < iWorkoutDate ? iPeriodEndDate : iWorkoutDate;
int iLossPayLag = comp.creditValuationParams().lossPayLag();
java.util.List<org.drip.analytics.cashflow.LossQuadratureMetrics> sLP = new
java.util.ArrayList<org.drip.analytics.cashflow.LossQuadratureMetrics>();
try {
org.drip.analytics.cashflow.LossQuadratureMetrics lp =
org.drip.analytics.cashflow.LossQuadratureMetrics.MakeDefaultPeriod (iPeriodStartDate,
iPeriodEndDate, period.accrualDCF ((iPeriodStartDate + iPeriodEndDate) / 2),
comp.notional (iPeriodStartDate, iPeriodEndDate), comp.recovery (iPeriodStartDate,
iPeriodEndDate, cc), dc, cc, iLossPayLag);
if (null != lp) sLP.add (lp);
} catch (java.lang.Exception e) {
e.printStackTrace();
return null;
}
return sLP;
}
}
| apache-2.0 |
goldonship/java-design-pattern | creational/factory-method/simple-factory/src/main/java/org/goldonship/designpattern/creational/simplefactory/NoneAction.java | 259 | package org.goldonship.designpattern.creational.simplefactory;
/**
* * Created by Goldonship on 2017/10/25.
**/
public class NoneAction implements Action{
@Override
public Catalog send() {
throw new UnsupportedOperationException();
}
}
| apache-2.0 |
noear/Snacks | java/Snacks/src/main/java/noear/snacks/ONode.java | 8798 | package noear.snacks;
import noear.snacks.exts.Act1;
import noear.snacks.exts.Act2;
import noear.snacks.exts.Act3;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
/**
* Created by noear on 14-6-11.
*/
public class ONode extends ONodeBase {
public static String NULL_DEFAULT="null";
public static boolean BOOL_USE01=false;
public static FormatHanlder TIME_FORMAT_ACTION=(date)->{
if (date == null)
return "null";
else
return "\"" + date.toString() + "\"";
};
public static final ONode NULL = new ONode().asNull();
//=============
public ONode(){
}
/**输出自己,以供消费*/
public ONode exp(Act1<ONode> expr){
expr.run(this);
return this;
}
public <T> T map(T t, Act3<T,String,ONode> hander){
if(isObject()){
_object.members.forEach((k,v)->{
hander.run(t,k,v);
});
}
if(isArray()){
_array.elements.forEach(v->{
hander.run(t,null,v);
});
}
return t;
}
public <T> void val(T val){
valSet(val);
}
//返回自己(重新设置基础类型的值)//不适合做为公有的
protected <T> ONode valSet(T val){
tryInitValue();
_value.set(val);
return this;
}
public ONode(int value){
tryInitValue();
_value.set(value);
}
public ONode(long value){
tryInitValue();
_value.set(value);
}
public ONode(double value){
tryInitValue();
_value.set(value);
}
public ONode(String value){
tryInitValue();
_value.set(value);
}
public ONode(boolean value){
tryInitValue();
_value.set(value);
}
public ONode(Date value){
tryInitValue();
_value.set(value);
}
public boolean contains(String key) {
if (_object == null || _type != ONodeType.Object)
return false;
else
return _object.contains(key);
}
public int count()
{
if(isObject())
return _object.count();
if(isArray())
return _array.count();
return 0;
}
//========================
public double getDouble() {
if (_value == null)
return 0;
else
return _value.getDouble();
}
public double getDouble(int scale)
{
double temp = getDouble();
if(temp==0)
return 0;
else
return new BigDecimal(temp)
.setScale(scale,BigDecimal.ROUND_HALF_UP)
.doubleValue();
}
public int getInt() {
if (_value == null)
return 0;
else
return _value.getInt();
}
public boolean getBoolean() {
if (_value == null)
return false;
else
return _value.getBoolean();
}
public Date getDate() {
if (_value == null)
return null;
else
return _value.getDate();
}
public long getLong() {
if (_value == null)
return 0;
else
return _value.getLong();
}
public String getString() {
if (_value == null) {
if(isObject()){
return toJson();
}
if(isArray()){
return toJson();
}
return "";
}
else {
return _value.getString();
}
}
public <T> T getModel(Class<T> cls){
return (T)OMapper.map(this,cls);
}
//=============
//返回结果节点
public ONode get(int index) {
tryInitArray();
if (_array.elements.size() > index)
return _array.elements.get(index);
else
return null;
}
//返回结果节点,如果不存在则自动创建
public ONode get(String key) {
tryInitObject();
if (_object.contains(key))
return _object.get(key);
else {
ONode temp = new ONode();
_object.set(key, temp);
return temp;
}
}
//返回自己
public ONode add(ONode value) {
tryInitArray();
_array.add(value);
return this;
}
//返回自己
public ONode addAll(ONode ary) {
tryInitArray();
if (ary != null && ary.isArray()) {
_array.elements.addAll(ary._array.elements);
}
return this;
}
//返回自己
public <T> ONode addAll(Iterable<T> ary){
tryInitArray();
if(ary!=null) {
ary.forEach(m -> add(m));
}
return this;
}
//返回自己
public <T> ONode addAll(Iterable<T> ary, Act2<ONode,T> handler) {
tryInitArray();
if(ary!=null) {
ary.forEach(m -> handler.run(this.add(), m));
}
return this;
}
public ONode add(Object value){
tryInitArray();
if(value instanceof ONode){
add((ONode)value);
}else{
add(new ONode().valSet(value));
}
return this;
}
public ONode add(String value) {
return add(new ONode(value));
}
public ONode add(String value, boolean isOps) {
if (isOps) {
return add(ONode.tryLoad(value));
} else {
return add(new ONode(value));
}
}
public ONode add(int value) {
return add(new ONode(value));
}
public ONode add(long value) {
return add(new ONode(value));
}
public ONode add(double value) {
return add(new ONode(value));
}
public ONode add(boolean value) {
return add(new ONode(value));
}
public ONode add(Date value) {
return add(new ONode(value));
}
//返回新节点
public ONode add(){
ONode n = new ONode();
add(n);
return n;
}
public ONode rename(String key, String newKey){
if(isObject()) {
_object.rename(key, newKey);
}
if(isArray()){
for(ONode n : _array.elements) {
n.rename(key, newKey);
}
}
return this;
}
public boolean remove(String key){
if(isObject()) {
_object.remove(key);
return true;
}
if(isArray()){
for(ONode n : _array.elements) {
if(n.isObject()) {
n.remove(key);
}
}
return true;
}
return false;
}
//返回自己
public ONode setAll(ONode obj) {
tryInitObject();
if (obj != null && obj.isObject()) {
_object.members.putAll(obj._object.members);
}
return this;
}
//返回自己
public <T> ONode setAll(Map<String,T> map) {
tryInitObject();
if (map != null) {
map.forEach((k, v) -> {
set(k, v);
});
}
return this;
}
public <T> ONode setAll(Map<String,T> map, Act2<ONode,T> handler) {
tryInitObject();
if (map != null) {
map.forEach((k, v) -> {
handler.run(this.get(k), v);
});
}
return this;
}
//返回自己
public ONode set(String key,String value) {
return set(key, new ONode(value));
}
public ONode set(String key,String value, boolean isOps) {
if (isOps) {
return set(key, ONode.tryLoad(value));
} else {
return set(key, new ONode(value));
}
}
//返回自己
public ONode set(String key,int value) {
return set(key, new ONode(value));
}
//返回自己
public ONode set(String key,long value) {
return set(key, new ONode(value));
}
//返回自己
public ONode set(String key,double value) {
return set(key, new ONode(value));
}
//返回自己
public ONode set(String key,boolean value) {
return set(key, new ONode(value));
}
//返回自己
public ONode set(String key,Date value) {
return set(key, new ONode(value));
}
//返回自己
public ONode set(String key,ONode value) {
tryInitObject();
_object.set(key, value);
return this;
}
//返回自己
public ONode set(String key, Object value){
tryInitObject();
if(value instanceof ONode){
_object.set(key,(ONode) value);
}else{
_object.set(key, new ONode().valSet(value));
}
return this;
}
}
| apache-2.0 |
AI-comp/JavaChallenge2012 | src/main/java/net/javachallenge/players/others/Myu.java | 7316 | package net.javachallenge.players.others;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.javachallenge.api.ComputerPlayer;
import net.javachallenge.api.Field;
import net.javachallenge.api.Game;
import net.javachallenge.api.Material;
import net.javachallenge.api.Player;
import net.javachallenge.api.TrianglePoint;
import net.javachallenge.api.Vein;
import net.javachallenge.api.command.Command;
import net.javachallenge.api.command.Commands;
public class Myu extends ComputerPlayer {
private List<TrianglePoint> veinPoints;
private List<TrianglePoint> myVeinPoints = new ArrayList<TrianglePoint>();
private static boolean isFirst = true;
@Override
public String getName() {
return "Myu";
}
@Override
public TrianglePoint selectVein(Game game) {
Field field = game.getField();
Map<TrianglePoint, Vein> veins = field.getVeinMap();
Object[] tp = veins.keySet().toArray();
Point edge = getEdgeVeins(tp);
veinPoints = categolizeVeins(tp, edge);
return selectPoint(veins);
}
private Point getEdgeVeins(Object[] tp) {
int maxX = 0;
int minX = 100;
int maxY = 0;
int minY = 0;
for (int i = tp.length - 1; i >= 0; i--) {
TrianglePoint t = (TrianglePoint) tp[i];
int tmpX = t.getX();
int tmpY = t.getY();
if (maxX < tmpX) {
maxX = tmpX;
} else if (minX > tmpX) {
minX = tmpX;
}
if (maxY < tmpY) {
maxY = tmpY;
} else if (minY > tmpY) {
minY = tmpY;
}
}
return new Point(maxX + minX, maxY + minY);
}
private List<TrianglePoint> categolizeVeins(Object[] tp, Point edge) {
int maxNum = 0;
int zone = 0;
List<TrianglePoint> seVeins = new ArrayList<TrianglePoint>();
List<TrianglePoint> swVeins = new ArrayList<TrianglePoint>();
List<TrianglePoint> neVeins = new ArrayList<TrianglePoint>();
List<TrianglePoint> nwVeins = new ArrayList<TrianglePoint>();
for (int i = tp.length - 1; i >= 0; i--) {
TrianglePoint t = (TrianglePoint) tp[i];
if (t.getX() >= edge.x / 2) {
if (t.getY() >= edge.y / 2) {
seVeins.add(t);
if (seVeins.size() > maxNum) {
maxNum = seVeins.size();
zone = 0;
}
} else {
neVeins.add(t);
if (neVeins.size() > maxNum) {
maxNum = neVeins.size();
zone = 3;
}
}
} else {
if (t.getY() >= edge.x / 2) {
swVeins.add(t);
if (swVeins.size() > maxNum) {
maxNum = swVeins.size();
zone = 2;
}
} else {
nwVeins.add(t);
if (nwVeins.size() > maxNum) {
maxNum = nwVeins.size();
zone = 1;
}
}
}
}
List<TrianglePoint> points = new ArrayList<TrianglePoint>();
switch (zone) {
case 0:
points.addAll(seVeins);
points.addAll(swVeins);
points.addAll(neVeins);
points.addAll(nwVeins);
return points;
case 1:
points.addAll(nwVeins);
points.addAll(neVeins);
points.addAll(swVeins);
points.addAll(seVeins);
return points;
case 2:
points.addAll(swVeins);
points.addAll(seVeins);
points.addAll(nwVeins);
points.addAll(neVeins);
return points;
case 3:
points.addAll(neVeins);
points.addAll(nwVeins);
points.addAll(seVeins);
points.addAll(swVeins);
return points;
}
return seVeins;
}
private TrianglePoint selectPoint(Map<TrianglePoint, Vein> veins) {
int maxRP = 0;
Vein vein;
TrianglePoint point = veinPoints.get(0);
for (TrianglePoint t : veinPoints) {
vein = veins.get(t);
int rp = vein.getInitialRobotProductivity();
if (isFirst) {
if (maxRP <= rp && vein.getOwnerId() == -1 && vein.getMaterial() == Material.Gas) {
maxRP = rp;
point = t;
}
} else {
if (maxRP <= rp && vein.getOwnerId() == -1 && vein.getMaterial() == Material.Metal) {
maxRP = rp;
point = t;
}
}
}
isFirst = false;
myVeinPoints.add(point);
return point;
}
@Override
public List<Command> selectActions(Game game) {
Player myself = game.getMyPlayer();
Field field = game.getField();
Map<TrianglePoint, Vein> veinlist = field.getVeinMap();
int robots =
(int) ((veinlist.get(myVeinPoints.get(0)).getNumberOfRobots() + veinlist.get(
myVeinPoints.get(1)).getNumberOfRobots()) * 0.8);
List<Command> commands = new ArrayList<Command>();
boolean ugrbt = true;
boolean ugmtl = true;
for (TrianglePoint tp : myVeinPoints) {
Vein v = veinlist.get(tp);
int rank = v.getRobotRank();
if (ugmtl
&& myself.getMaterial(Material.Stone) > game.getSetting()
.getMaterialsForUpgradingMaterialRankFrom2To3(Material.Stone)
&& myself.getMaterial(Material.Gas) > game.getSetting()
.getMaterialsForUpgradingRobotRankFrom2To3(Material.Gas)) {
if (rank < 3) {
commands.add(Commands.upgradeMaterial(v.getLocation()));
ugmtl = false;
}
}
if (ugmtl
&& myself.getMaterial(Material.Stone) > game.getSetting()
.getMaterialsForUpgradingMaterialRankFrom1To2(Material.Stone)
&& myself.getMaterial(Material.Gas) > game.getSetting()
.getMaterialsForUpgradingRobotRankFrom1To2(Material.Gas)) {
if (rank < 2) {
commands.add(Commands.upgradeMaterial(v.getLocation()));
ugmtl = false;
}
}
if (ugrbt
&& myself.getMaterial(Material.Metal) > game.getSetting()
.getMaterialsForUpgradingRobotRankFrom2To3(Material.Metal)
&& myself.getMaterial(Material.Gas) > game.getSetting()
.getMaterialsForUpgradingRobotRankFrom2To3(Material.Gas)) {
if (rank < 3) {
commands.add(Commands.upgradeRobot(v.getLocation()));
ugrbt = false;
}
}
if (ugrbt
&& myself.getMaterial(Material.Metal) > game.getSetting()
.getMaterialsForUpgradingRobotRankFrom1To2(Material.Metal)
&& myself.getMaterial(Material.Gas) > game.getSetting()
.getMaterialsForUpgradingRobotRankFrom1To2(Material.Gas)) {
if (rank < 2) {
commands.add(Commands.upgradeRobot(v.getLocation()));
ugrbt = false;
}
}
}
Iterator<TrianglePoint> tp = veinPoints.iterator();
while (tp.hasNext()) {
TrianglePoint location = tp.next();
if (veinlist.get(location).getOwnerId() == game.getNeutralPlayerId()) {
if (veinlist.get(location).getNumberOfRobots() < robots * 0.8) {
for (TrianglePoint p : myVeinPoints) {
Vein v = veinlist.get(p);
commands.add(Commands.launch((int) (v.getNumberOfRobots() * 0.9), v.getLocation(),
location));
}
myVeinPoints.add(location);
tp.remove();
break;
}
}
}
this.saveTemporalCommands(commands);
return commands;
}
}
| apache-2.0 |
lpicanco/grails | src/persistence/org/codehaus/groovy/grails/orm/hibernate/metaclass/CreateCriteriaPersistentMethod.java | 1700 | /*
* Copyright 2004-2005 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.codehaus.groovy.grails.orm.hibernate.metaclass;
import grails.orm.HibernateCriteriaBuilder;
import groovy.lang.MissingMethodException;
import java.util.regex.Pattern;
import org.hibernate.SessionFactory;
/**
* Creates a HibernateCriteriaBuilder instance for the current class and returns it.
*
* eg. Account.createCriteria()
*
* @author Graeme Rocher
*/
public class CreateCriteriaPersistentMethod extends
AbstractStaticPersistentMethod {
private static final String METHOD_PATTERN = "^createCriteria$";
private static final String METHOD_SIGNATURE = "createCriteria";
public CreateCriteriaPersistentMethod(SessionFactory sessionFactory, ClassLoader classLoader) {
super(sessionFactory, classLoader, Pattern.compile(METHOD_PATTERN));
}
protected Object doInvokeInternal(Class clazz, String methodName,
Object[] arguments) {
if(arguments.length > 0)
throw new MissingMethodException(METHOD_SIGNATURE, clazz,arguments);
return new HibernateCriteriaBuilder(clazz,super.getHibernateTemplate().getSessionFactory());
}
}
| apache-2.0 |
elasticdog/elasticsearch | core/src/main/java/org/elasticsearch/search/aggregations/metrics/percentiles/tdigest/InternalTDigestPercentileRanks.java | 4087 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.aggregations.metrics.percentiles.tdigest;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.aggregations.metrics.percentiles.InternalPercentile;
import org.elasticsearch.search.aggregations.metrics.percentiles.Percentile;
import org.elasticsearch.search.aggregations.metrics.percentiles.PercentileRanks;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class InternalTDigestPercentileRanks extends AbstractInternalTDigestPercentiles implements PercentileRanks {
public static final String NAME = "tdigest_percentile_ranks";
public InternalTDigestPercentileRanks(String name, double[] cdfValues, TDigestState state, boolean keyed, DocValueFormat formatter,
List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData) {
super(name, cdfValues, state, keyed, formatter, pipelineAggregators, metaData);
}
/**
* Read from a stream.
*/
public InternalTDigestPercentileRanks(StreamInput in) throws IOException {
super(in);
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public Iterator<Percentile> iterator() {
return new Iter(keys, state);
}
@Override
public double percent(double value) {
return percentileRank(state, value);
}
@Override
public String percentAsString(double value) {
return valueAsString(String.valueOf(value));
}
@Override
public double value(double key) {
return percent(key);
}
@Override
protected AbstractInternalTDigestPercentiles createReduced(String name, double[] keys, TDigestState merged, boolean keyed,
List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData) {
return new InternalTDigestPercentileRanks(name, keys, merged, keyed, format, pipelineAggregators, metaData);
}
static double percentileRank(TDigestState state, double value) {
double percentileRank = state.cdf(value);
if (percentileRank < 0) {
percentileRank = 0;
}
else if (percentileRank > 1) {
percentileRank = 1;
}
return percentileRank * 100;
}
public static class Iter implements Iterator<Percentile> {
private final double[] values;
private final TDigestState state;
private int i;
public Iter(double[] values, TDigestState state) {
this.values = values;
this.state = state;
i = 0;
}
@Override
public boolean hasNext() {
return i < values.length;
}
@Override
public Percentile next() {
final Percentile next = new InternalPercentile(percentileRank(state, values[i]), values[i]);
++i;
return next;
}
@Override
public final void remove() {
throw new UnsupportedOperationException();
}
}
@Override
protected boolean doEquals(Object obj) {
return super.doEquals(obj);
}
}
| apache-2.0 |
hprange/wounit | src/main/java/com/wounit/rules/EditingContextFacade.java | 1975 | /**
* Copyright (C) 2009 hprange <hprange@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.wounit.rules;
import com.webobjects.eocontrol.EOEditingContext;
import com.webobjects.eocontrol.EOEnterpriseObject;
/**
* This class represents a simple facade to create and insert enterprise
* objects.
*
* @author <a href="mailto:hprange@gmail.com">Henrique Prange</a>
* @since 1.1
*/
abstract class EditingContextFacade {
/**
* The editing context to create and insert objects.
*/
protected final EOEditingContext editingContext;
/**
* Create a facade to create and insert <code>EOEnterpriseObjects</code>.
*
* @param editingContext
* the editing context where objects should be created/inserted.
*/
public EditingContextFacade(EOEditingContext editingContext) {
this.editingContext = editingContext;
}
/**
* Create and insert a new enterprise object for the type specified.
*
* @param type
* the type of the enterprise object to be created.
* @return Returns the new enterprise object.
*/
public abstract EOEnterpriseObject create(Class<? extends EOEnterpriseObject> type);
/**
* Insert a new enterprise object into the editing context.
*
* @param object
* the object to be inserted into the editing context
*/
public abstract void insert(EOEnterpriseObject object);
}
| apache-2.0 |
AvanzaBank/astrix | astrix-context/src/main/java/com/avanza/astrix/context/mbeans/PlatformMBeanServer.java | 2970 | /*
* Copyright 2014 Avanza Bank AB
*
* 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.avanza.astrix.context.mbeans;
import java.lang.management.ManagementFactory;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.PreDestroy;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PlatformMBeanServer implements MBeanServerFacade {
private static final AtomicInteger astrixContextCount = new AtomicInteger(0);
private final Logger logger = LoggerFactory.getLogger(PlatformMBeanServer.class);
private final Set<ObjectName> exportedMbeans = ConcurrentHashMap.newKeySet();
private final String domain;
public PlatformMBeanServer() {
int astrixContextId = astrixContextCount.incrementAndGet();
if (astrixContextId != 1) {
this.domain = "com.avanza.astrix.context." + astrixContextId;
} else {
this.domain = "com.avanza.astrix.context";
}
}
@Override
public void registerMBean(Object mbean, String folder, String name) {
try {
ObjectName objectName = getObjectName(folder, name);
logger.debug("Register mbean: name={}", objectName);
ManagementFactory.getPlatformMBeanServer().registerMBean(mbean, objectName);
exportedMbeans.add(objectName);
} catch (Exception e) {
logger.warn("Failed to export mbean: type={} domain={} subdomain={} name={}", mbean.getClass().getName(), domain, folder, name, e);
}
}
@Override
public void unregisterMBean(String folder, String name) {
unregisterMBean(getObjectName(folder, name));
}
private ObjectName getObjectName(String folder, String name) {
try {
return new ObjectName(domain + ":00=" + folder + ",name=" + name);
} catch (MalformedObjectNameException e) {
throw new RuntimeException(e);
}
}
@PreDestroy
public void destroy() {
exportedMbeans.forEach(this::unregisterMBean);
}
private void unregisterMBean(ObjectName objectName) {
try {
MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
if (platformMBeanServer.isRegistered(objectName)) {
logger.debug("Unregister mbean: name={}", objectName);
platformMBeanServer.unregisterMBean(objectName);
}
} catch (Exception e) {
logger.warn("Failed to unregister mbean: name={}", objectName);
}
}
}
| apache-2.0 |
mobilist/RxAndroid | sample-app/src/main/java/rx/android/samples/ListenInOutActivity.java | 2439 | package rx.android.samples;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.observables.ConnectableObservable;
import static rx.android.content.ContentObservable.bindActivity;
/**
* Activity that binds to a counting sequence and is able to listen in and out to that
* sequence by pressing a toggle button. The button disables itself once the sequence
* finishes.
*/
public class ListenInOutActivity extends Activity implements Observer<String> {
private Observable<String> source;
private Subscription subscription;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listen_in_out_activity);
textView = (TextView) findViewById(android.R.id.text1);
// in a production app, you would use dependency injection, fragments, or other
// means to preserve the observable, but this will suffice here
source = (Observable<String>) getLastNonConfigurationInstance();
if (source == null) {
source = SampleObservables.numberStrings(1, 100, 200).publish();
((ConnectableObservable) source).connect();
}
subscribeToSequence();
}
private void subscribeToSequence() {
subscription = bindActivity(this, source).subscribe(this);
}
@Override
public Object onRetainNonConfigurationInstance() {
return source;
}
@Override
protected void onDestroy() {
subscription.unsubscribe();
super.onDestroy();
}
@Override
public void onCompleted() {
TextView button = (TextView) findViewById(R.id.toggle_button);
button.setText("Completed");
button.setEnabled(false);
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
Toast.makeText(this, "Error: " + e, Toast.LENGTH_SHORT).show();
}
@Override
public void onNext(String s) {
textView.setText(s);
}
public void onSequenceToggleClicked(View view) {
if (((ToggleButton) view).isChecked()) {
subscription.unsubscribe();
} else {
subscribeToSequence();
}
}
}
| apache-2.0 |
lessthanoptimal/ejml | main/ejml-core/src/org/ejml/interfaces/decomposition/CholeskyLDLDecomposition_F32.java | 1207 | /*
* Copyright (c) 2009-2017, Peter Abeles. All Rights Reserved.
*
* This file is part of Efficient Java Matrix Library (EJML).
*
* 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.ejml.interfaces.decomposition;
import org.ejml.data.Matrix;
/**
* <p>
* Implementation of {@link CholeskyDecomposition} for 32-bit floats.
* </p>
*
* @author Peter Abeles
*/
public interface CholeskyLDLDecomposition_F32<MatrixType extends Matrix>
extends CholeskyLDLDecomposition<MatrixType> {
/**
* Returns the elements in the diagonal matrix
* @return array with diagonal elements. Array might be larger than the number of elements.
*/
float[] getDiagonal();
} | apache-2.0 |
Yangyazheng/azkaban_annotation | azkaban-common/src/main/java/azkaban/executor/selector/ExecutorFilter.java | 7573 | /*
* Copyright 2015 LinkedIn Corp.
*
* 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 azkaban.executor.selector;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import azkaban.executor.ExecutableFlow;
import azkaban.executor.Executor;
import azkaban.executor.ExecutorInfo;
/**
* 执行节点过滤器
* De-normalized version of the candidateFilter, which also contains the implementation of the factor filters.
* */
public final class ExecutorFilter extends CandidateFilter<Executor, ExecutableFlow> {
private static Map<String, FactorFilter<Executor, ExecutableFlow>> filterRepository = null;
/**
* Gets the name list of all available filters.
* @return the list of the names.
* */
public static Set<String> getAvailableFilterNames(){
return filterRepository.keySet();
}
// factor filter names.
private static final String STATICREMAININGFLOWSIZE_FILTER_NAME = "StaticRemainingFlowSize";
private static final String MINIMUMFREEMEMORY_FILTER_NAME = "MinimumFreeMemory";
private static final String CPUSTATUS_FILTER_NAME = "CpuStatus";
/**<pre>
* static initializer of the class.
* We will build the filter repository here.默认实现的几个过滤器,根据需要再注册使用,
* when a new filter is added, please do remember to register it here.
* </pre>
* */
static {
filterRepository = new HashMap<String, FactorFilter<Executor, ExecutableFlow>>();
filterRepository.put(STATICREMAININGFLOWSIZE_FILTER_NAME, getStaticRemainingFlowSizeFilter());
filterRepository.put(MINIMUMFREEMEMORY_FILTER_NAME, getMinimumReservedMemoryFilter());
filterRepository.put(CPUSTATUS_FILTER_NAME, getCpuStatusFilter());
}
/**
* constructor of the ExecutorFilter.
* @param filterList the list of filter to be registered, the parameter must be a not-empty and valid list object.
* */
public ExecutorFilter(Collection<String> filterList) {
// shortcut if the filter list is invalid. A little bit ugly to have to throw in constructor.
if (null == filterList || filterList.size() == 0){
logger.error("failed to initialize executor filter as the passed filter list is invalid or empty.");
throw new IllegalArgumentException("filterList");
}
// register the filters according to the list.
for (String filterName : filterList){
if (filterRepository.containsKey(filterName)){
this.registerFactorFilter(filterRepository.get(filterName));
} else {
logger.error(String.format("failed to initialize executor filter "+
"as the filter implementation for requested factor '%s' doesn't exist.",
filterName));
throw new IllegalArgumentException("filterList");
}
}
}
@Override
public String getName() {
return "ExecutorFilter";
}
/**<pre>
* 目前只是查看节点是否还能接受任务,若不能返回false,过滤掉这个执行节点的候选资格
* function to register the static remaining flow size filter.
* NOTE : this is a static filter which means the filter will be filtering based on the system standard which is not
* Coming for the passed flow.
* Ideally this filter will make sure only the executor hasn't reached the Max allowed # of executing flows.
*</pre>
* */
private static FactorFilter<Executor, ExecutableFlow> getStaticRemainingFlowSizeFilter(){
return FactorFilter.create(STATICREMAININGFLOWSIZE_FILTER_NAME, new FactorFilter.Filter<Executor, ExecutableFlow>() {
public boolean filterTarget(Executor filteringTarget, ExecutableFlow referencingObject) {
if (null == filteringTarget){
logger.debug(String.format("%s : filtering out the target as it is null.", STATICREMAININGFLOWSIZE_FILTER_NAME));
return false;
}
ExecutorInfo stats = filteringTarget.getExecutorInfo();
if (null == stats) {
logger.debug(String.format("%s : filtering out %s as it's stats is unavailable.",
STATICREMAININGFLOWSIZE_FILTER_NAME,
filteringTarget.toString()));
return false;
}
return stats.getRemainingFlowCapacity() > 0 ;
}
});
}
/**<pre>
* 过滤剩余内存大小不足预定值的执行节点,默认阈值为6G内存大小
* function to register the static Minimum Reserved Memory filter.
* NOTE : this is a static filter which means the filter will be filtering based on the system standard which is not
* Coming for the passed flow.
* This filter will filter out any executors that has the remaining memory below 6G
*</pre>
* */
private static FactorFilter<Executor, ExecutableFlow> getMinimumReservedMemoryFilter(){
return FactorFilter.create(MINIMUMFREEMEMORY_FILTER_NAME, new FactorFilter.Filter<Executor, ExecutableFlow>() {
private static final int MINIMUM_FREE_MEMORY = 6 * 1024;
public boolean filterTarget(Executor filteringTarget, ExecutableFlow referencingObject) {
if (null == filteringTarget){
logger.debug(String.format("%s : filtering out the target as it is null.", MINIMUMFREEMEMORY_FILTER_NAME));
return false;
}
ExecutorInfo stats = filteringTarget.getExecutorInfo();
if (null == stats) {
logger.debug(String.format("%s : filtering out %s as it's stats is unavailable.",
MINIMUMFREEMEMORY_FILTER_NAME,
filteringTarget.toString()));
return false;
}
return stats.getRemainingMemoryInMB() > MINIMUM_FREE_MEMORY ;
}
});
}
/**
* <pre>
* 根据CPU占用率过滤达到阈值的执行节点,目前CPU占用率阈值为95%
* function to register the static Maximum used CPU filter.
* NOTE : this is a static filter which means the filter will be filtering based on the system standard which
* is not Coming for the passed flow.
* This filter will filter out any executors that the current CPU usage exceed 95%
* </pre>
* */
private static FactorFilter<Executor, ExecutableFlow> getCpuStatusFilter(){
return FactorFilter.create(CPUSTATUS_FILTER_NAME, new FactorFilter.Filter<Executor, ExecutableFlow>() {
private static final int MAX_CPU_CURRENT_USAGE = 95;
public boolean filterTarget(Executor filteringTarget, ExecutableFlow referencingObject) {
if (null == filteringTarget){
logger.debug(String.format("%s : filtering out the target as it is null.", CPUSTATUS_FILTER_NAME));
return false;
}
ExecutorInfo stats = filteringTarget.getExecutorInfo();
if (null == stats) {
logger.debug(String.format("%s : filtering out %s as it's stats is unavailable.",
MINIMUMFREEMEMORY_FILTER_NAME,
filteringTarget.toString()));
return false;
}
return stats.getCpuUsage() < MAX_CPU_CURRENT_USAGE ;
}
});
}
}
| apache-2.0 |
weiwenqiang/GitHub | SelectWidget/glide-master/third_party/gif_decoder/src/test/java/com/bumptech/glide/gifdecoder/test/GifBytesTestUtil.java | 4377 | package com.bumptech.glide.gifdecoder.test;
import java.nio.ByteBuffer;
/**
* Utils for writing the bytes of various parts of GIFs to byte buffers.
*/
public class GifBytesTestUtil {
// Length in bytes.
public static final int HEADER_LENGTH = 13;
// Length in bytes.
public static final int IMAGE_DESCRIPTOR_LENGTH = 10;
// Length in bytes.
public static final int GRAPHICS_CONTROL_EXTENSION_LENGTH = 8;
public static int getColorTableLength(int numColors) {
return 3 * numColors;
}
public static int getImageDataSize(int lzwMinCodeSize) {
// TODO: fill this out.
return 4;
}
public static void writeFakeImageData(ByteBuffer out, int lzwMinCodeSize) {
// 1 for lzwMinCodeSize, 1 for length, 1 for min content, 1 for block terminator.
verifyRemaining(out, 4);
verifyShortValues(lzwMinCodeSize);
out.put((byte) lzwMinCodeSize);
// Block length.
out.put((byte) 0x01);
// Block content.
out.put((byte) 0x01);
// End of block.
out.put((byte) 0x00);
}
public static void writeColorTable(ByteBuffer out, int numColors) {
verifyRemaining(out, getColorTableLength(numColors));
for (int i = 0; i < numColors; i++) {
out.put((byte) (0xFF0000 & i));
out.put((byte) (0x00FF00 & i));
out.put((byte) (0x0000FF & i));
}
}
public static void writeImageDescriptor(ByteBuffer out, int imageLeft, int imageTop,
int imageWidth, int imageHeight, boolean hasLct, int numColors) {
verifyRemaining(out, IMAGE_DESCRIPTOR_LENGTH);
verifyShortValues(imageLeft, imageTop, imageWidth, imageHeight);
final byte packed;
if (hasLct) {
int size = log2(numColors) - 1;
packed = (byte) (0x80 | size);
} else {
packed = 0x00;
}
// Image separator
out.put((byte) 0x2C);
out.putShort((short) imageLeft).putShort((short) imageTop).putShort((short) imageWidth)
.putShort((short) imageHeight).put(packed);
}
private static int log2(int num) {
return (int) Math.round(Math.log(num) / Math.log(2));
}
public static void writeHeaderAndLsd(ByteBuffer out, int width, int height, boolean hasGct,
int gctSize) {
verifyRemaining(out, HEADER_LENGTH);
verifyShortValues(width, height);
// GIF
out.put((byte) 0x47).put((byte) 0x49).put((byte) 0x46);
// Version - 89a.
out.put((byte) 0x38).put((byte) 0x39).put((byte) 0x61);
/** LSD (Logical Screen Descriptor) **/
// Width.
out.putShort((short) width);
// Height.
out.putShort((short) height);
// Packed GCT (Global Color Table) flag + color resolution + sort flag + size of GCT.
// GCT flag (false) - most significant bit.
byte gctFlag = (byte) ((hasGct ? 1 : 0) << 7);
// Color resolution - next three bits.
byte colorResolution = 1 << 5;
// Sort flag - next bit;
byte sortFlag = 0 << 4;
// exponent of size of color table, size = 2^(1 + exponent) - least significant 3 bits.
byte size = (byte) gctSize;
byte packed = (byte) (gctFlag | colorResolution | sortFlag | size);
out.put(packed);
// Background color index.
out.put((byte) 0);
// Pixel aspect ratio.
out.put((byte) 0);
}
public static void writeGraphicsControlExtension(ByteBuffer out, int delayTime) {
verifyRemaining(out, GRAPHICS_CONTROL_EXTENSION_LENGTH);
verifyShortValues(delayTime);
// Extension inducer (constant).
out.put((byte) 0x21);
// Graphic control label (constant).
out.put((byte) 0xF9);
// Block size (constant).
out.put((byte) 0x04);
// Packed (disposal method, user input, transparent color flag)
out.put((byte) 0x00);
// Frame delay in 100ths of a second.
out.putShort((short) delayTime);
// Transparent color index.
out.put((byte) 0x00);
// Block terminator (constant).
out.put((byte) 0x00);
}
private static void verifyRemaining(ByteBuffer buffer, int expected) {
if (buffer.remaining() < expected) {
throw new IllegalArgumentException("Must have at least " + expected + " bytes to write");
}
}
private static void verifyShortValues(int... shortValues) {
for (int dimen : shortValues) {
if (dimen > Short.MAX_VALUE || dimen < 0) {
throw new IllegalArgumentException(
"Must pass in non-negative short dimensions, not: " + dimen);
}
}
}
}
| apache-2.0 |
boneman1231/org.apache.felix | trunk/org.osgi.foundation/src/main/java/java/util/HashSet.java | 1507 | /*
* $Header: /cvshome/build/ee.foundation/src/java/util/HashSet.java,v 1.6 2006/03/14 01:20:25 hargrave Exp $
*
* (C) Copyright 2001 Sun Microsystems, Inc.
* Copyright (c) OSGi Alliance (2001, 2005). 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 java.util;
public class HashSet extends java.util.AbstractSet implements java.util.Set, java.lang.Cloneable, java.io.Serializable {
public HashSet() { }
public HashSet(int var0) { }
public HashSet(int var0, float var1) { }
public HashSet(java.util.Collection var0) { }
public boolean add(java.lang.Object var0) { return false; }
public void clear() { }
public java.lang.Object clone() { return null; }
public boolean contains(java.lang.Object var0) { return false; }
public boolean isEmpty() { return false; }
public java.util.Iterator iterator() { return null; }
public boolean remove(java.lang.Object var0) { return false; }
public int size() { return 0; }
}
| apache-2.0 |
snuk182/aceim | vk/src/main/java/aceim/protocol/snuk182/vkontakte/internal/VkEngine.java | 22081 | package aceim.protocol.snuk182.vkontakte.internal;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import aceim.api.utils.Logger;
import aceim.api.utils.Logger.LoggerLevel;
import aceim.api.utils.Utils;
import aceim.protocol.snuk182.vkontakte.VkConstants;
import aceim.protocol.snuk182.vkontakte.VkEntityAdapter;
import aceim.protocol.snuk182.vkontakte.model.AccessToken;
import aceim.protocol.snuk182.vkontakte.model.ApiObject;
import aceim.protocol.snuk182.vkontakte.model.LongPollResponse;
import aceim.protocol.snuk182.vkontakte.model.LongPollResponse.LongPollResponseUpdate;
import aceim.protocol.snuk182.vkontakte.model.LongPollServer;
import aceim.protocol.snuk182.vkontakte.model.VkBuddy;
import aceim.protocol.snuk182.vkontakte.model.VkBuddyGroup;
import aceim.protocol.snuk182.vkontakte.model.VkChat;
import aceim.protocol.snuk182.vkontakte.model.VkMessage;
import aceim.protocol.snuk182.vkontakte.model.VkOnlineInfo;
import android.net.Uri;
import android.text.TextUtils;
final class VkEngine {
private static final String API_URL = "https://api.vk.com/method/";
private static final String TOKEN_URL = "https://oauth.vk.com/access_token";
private static final String PARAM_ACCESS_TOKEN = "access_token";
private final String accessToken;
private final String internalUserId;
private PollListenerThread listener;
private final VkEngineConnector connector;
VkEngine(String accessToken, String internalUserId) {
this.accessToken = accessToken;
this.internalUserId = internalUserId;
this.connector = new VkEngineConnector();
}
void sendTypingNotifications(String uid, boolean isChat) throws RequestFailedException {
Map<String, String> params = new HashMap<String, String>();
params.put(isChat ? "chat_id" : "uid", uid);
params.put("type", "typing");
doGetRequest("messages.setActivity", accessToken, params);
}
void setStatus(String statusString) throws RequestFailedException {
Map<String, String> params = new HashMap<String, String>();
params.put("text", statusString);
doGetRequest("status.set", accessToken, params);
}
void markMessagesAsRead(long[] messageIds) throws RequestFailedException {
if (messageIds == null || messageIds.length < 1) {
return;
}
StringBuilder sb = new StringBuilder();
for (int i=0; i<messageIds.length; i++) {
sb.append(messageIds[i]);
if (i < (messageIds.length - 1)) {
sb.append(',');
}
}
Map<String, String> params = new HashMap<String, String>();
params.put("mids", sb.toString());
doGetRequest("messages.markAsRead", accessToken, params);
}
List<VkChat> getGroupChats() throws RequestFailedException {
Map<String, String> params = new HashMap<String, String>();
params.put("count", "200");
String result = doGetRequest("messages.getDialogs", accessToken, params);
try {
JSONArray array = new JSONObject(result).getJSONArray("response");
List<String> chats = new ArrayList<String>();
for (int i=0; i<array.length(); i++) {
JSONObject jo = array.optJSONObject(i);
String chatId = null;
if (jo != null && !TextUtils.isEmpty((chatId = jo.optString("chat_id")))) {
chats.add(chatId);
}
}
List<VkChat> vkchats = new ArrayList<VkChat>(chats.size());
for (String chatId : chats) {
params.clear();
params.put("chat_id", chatId);
result = doGetRequest("messages.getChat", accessToken, params);
try {
VkChat chat = new VkChat(new JSONObject(result));
if (chat.getUsers().length > 2) {
vkchats.add(chat);
}
} catch (JSONException e) {
Logger.log(e);
}
}
return vkchats;
} catch (JSONException e) {
throw new RequestFailedException(e);
}
}
List<VkOnlineInfo> getOnlineBuddies() throws RequestFailedException {
String result = doGetRequest("friends.getOnline", accessToken, null);
return ApiObject.parseArray(result, VkOnlineInfo.class);
}
List<VkBuddyGroup> getBuddyGroupList() throws RequestFailedException {
String result = doGetRequest("friends.getLists", accessToken, null);
return ApiObject.parseArray(result, VkBuddyGroup.class);
}
List<VkBuddy> getBuddyList() throws RequestFailedException {
Map<String, String> params = new HashMap<String, String>();
params.put("fields", "first_name,last_name,nickname,photo_big,lid");
String result = doGetRequest("friends.get", accessToken, params);
return ApiObject.parseArray(result, VkBuddy.class);
}
Map<String, String> getPhotosById(String[] photoIds) throws RequestFailedException {
//return getSomethingByIds(photoIds, "photos.getById", "photos", otherParams, null, null);
StringBuilder sb = new StringBuilder();
for (int i=0; i<photoIds.length; i++) {
sb.append(photoIds[i]);
if (i < photoIds.length-1) {
sb.append(",");
}
}
Map<String, String> params = new HashMap<String, String>();
params.put("photos", sb.toString());
params.put("photo_sizes", "1");
String result = doGetRequest("photos.getById", accessToken, params);
Map<String, String> photos = new HashMap<String, String>();
try {
JSONArray array = new JSONObject(result).getJSONArray("response");
for (int i = 0; i < array.length(); i++) {
JSONObject jo = array.optJSONObject(i);
if (jo == null) {
continue;
}
JSONArray sizes = jo.optJSONArray("sizes");
int index = 0;
int topSize = 0;
for (int j=0; j<sizes.length(); j++) {
JSONObject sizeObject = sizes.getJSONObject(j);
int size = sizeObject.getInt("width");
if (topSize < size) {
topSize = size;
index = j;
}
}
String src = sizes.getJSONObject(index).getString("src");
photos.put(src, null);
}
} catch (JSONException e) {
Logger.log(e);
}
return photos;
}
Map<String, String> getDocsById(String[] docIds) throws RequestFailedException {
return getSomethingByIds(docIds, "docs.getById", "docs", null, "url", new String[]{"title"});
}
Map<String, String> getVideosById(String[] videoIds) throws RequestFailedException {
return getSomethingByIds(videoIds, "video.get", "videos", null, "player", new String[]{"title"});
}
Map<String, String> getAudiosById(String[] audioIds) throws RequestFailedException {
return getSomethingByIds(audioIds, "audio.getById", "audios", null, "url", new String[]{"artist", "title"});
}
private Map<String, String> getSomethingByIds(String[] ids, String methodName, String paramName, Map<String, String> otherParams, String sourceParam, String[] titleParam) throws RequestFailedException {
StringBuilder sb = new StringBuilder();
for (int i=0; i<ids.length; i++) {
sb.append(ids[i]);
if (i < ids.length-1) {
sb.append(",");
}
}
Map<String, String> params = new HashMap<String, String>();
params.put(paramName, sb.toString());
if (otherParams != null) {
params.putAll(otherParams);
}
String result = doGetRequest(methodName, accessToken, params);
Map<String, String> photos = new HashMap<String, String>();
try {
JSONArray array = new JSONObject(result).getJSONArray("response");
for (int i = 0; i < array.length(); i++) {
JSONObject jo = array.optJSONObject(i);
if (jo == null) {
continue;
}
String src = jo.optString(sourceParam);
String title = null;
if (titleParam != null && titleParam.length > 0) {
StringBuilder bb = new StringBuilder();
for (int j=0; j<titleParam.length; j++) {
bb.append(jo.optString(titleParam[j]));
if (j < titleParam.length-1) {
bb.append(" - ");
}
}
title = bb.toString();
}
photos.put(src, title);
}
} catch (JSONException e) {
Logger.log(e);
}
return photos;
}
VkBuddy getMyInfo() throws RequestFailedException {
Map<String, String> params = new HashMap<String, String>();
params.put("uids", internalUserId);
params.put("fields", "first_name,last_name,nickname,photo_big");
String result = doGetRequest("users.get", accessToken, params);
return ApiObject.parseArray(result, VkBuddy.class).get(0);
}
String requestStatus(long uid) throws RequestFailedException {
Map<String, String> params = new HashMap<String, String>();
params.put("uid", Long.toString(uid));
String result = doGetRequest("status.get", accessToken, params);
try {
return Utils.unescapeXMLString(new JSONObject(result).getJSONObject("response").getString("text"));
} catch (JSONException e) {
Logger.log(e);
throw new RequestFailedException(e);
}
}
void connectLongPoll(int pollWaitTime, LongPollCallback callback) throws RequestFailedException {
Logger.log("Get new longpoll server connection", LoggerLevel.VERBOSE);
try {
LongPollServer lpServer = getLongPollServer();
startLongPollConnection(pollWaitTime, lpServer, callback);
} catch (JSONException e) {
Logger.log(e);
}
}
List<VkBuddy> getUsersByIdList(long[] users) throws RequestFailedException {
if (users == null) return null;
StringBuilder sb = new StringBuilder();
for (int i=0; i<users.length; i++) {
long userId = users[i];
sb.append(userId);
if (i < (users.length - 1)) {
sb.append(",");
}
}
Map<String, String> params = new HashMap<String, String>();
params.put("uids", sb.toString());
params.put("fields", "first_name,last_name,nickname,photo_big");
String result = doGetRequest("users.get", accessToken, params);
return ApiObject.parseArray(result, VkBuddy.class);
}
VkChat getChatById(String chatId) throws RequestFailedException {
Map<String, String> params = new HashMap<String, String>();
params.put("chat_id", chatId);
String result = doGetRequest("messages.getChat", accessToken, params);
return new VkChat(result);
}
List<VkMessage> getLastChatMessages(String id, boolean isChat) throws RequestFailedException {
Map<String, String> params = new HashMap<String, String>();
params.put(isChat ? "chat_id" : "uid", id);
params.put("count", "3");
params.put("rev", "1");
String result = doGetRequest("messages.getHistory", accessToken, params);
return ApiObject.parseArray(result, VkMessage.class);
}
private LongPollServer getLongPollServer() throws JSONException, RequestFailedException {
String result = doGetRequest("messages.getLongPollServer", accessToken, null);
return new LongPollServer(result);
}
private String doGetRequest(String apiMethodName, String accessToken, Map<String, String> params) throws RequestFailedException {
if (accessToken == null) {
throw new IllegalStateException("Empty access token");
}
if (params == null) {
params = new HashMap<String, String>(1);
}
params.put(PARAM_ACCESS_TOKEN, accessToken);
return connector.request(Method.GET, API_URL + apiMethodName, VkEntityAdapter.map2NameValuePairs(params), null, null);
}
private void startLongPollConnection(int pollWaitTime, LongPollServer lpServer, LongPollCallback callback) {
if (listener != null && !listener.isInterrupted()) {
listener.interrupt();
}
listener = new PollListenerThread(pollWaitTime, lpServer, callback);
listener.start();
}
public long sendMessage(VkMessage message) throws RequestFailedException {
String result = doGetRequest("messages.send", accessToken, message.toParamsMap());
try {
return new JSONObject(result).getLong("response");
} catch (JSONException e) {
Logger.log(e);
return 0;
}
}
public byte[] getIcon(String url) throws RequestFailedException {
try {
return connector.requestRawStream(Method.GET, url, null, null, null, null);
} catch (Exception e) {
disconnect(e.getLocalizedMessage());
throw new RequestFailedException(e);
}
}
static AccessToken getAccessToken(String code) throws RequestFailedException {
List<NameValuePair> params = new ArrayList<NameValuePair>(4);
params.add(new BasicNameValuePair("client_id", VkApiConstants.API_ID));
params.add(new BasicNameValuePair("client_secret", VkApiConstants.API_SECRET));
params.add(new BasicNameValuePair("code", code));
params.add(new BasicNameValuePair("redirect_uri", VkConstants.OAUTH_REDIRECT_URL));
String json = new VkEngineConnector().request(Method.GET, TOKEN_URL, params, null, null);
try {
AccessToken token = new AccessToken(json);
return token;
} catch (JSONException e) {
Logger.log(e);
return null;
}
}
private final class PollListenerThread extends Thread {
private static final String LONGPOLL_MODE_GET_ATTACHMENTS = "2";
private final int pollWaitSeconds;
private final HttpClient httpClient = new DefaultHttpClient(getHttpParams());
private final String url;
private final String key;
private String ts;
private final LongPollCallback callback;
private String lastUpdate = "";
private volatile boolean isClosed = false;
private PollListenerThread(int pollWaitTime, LongPollServer lpServer, LongPollCallback callback) {
this.url = lpServer.getServer();
this.key = lpServer.getKey();
this.ts = lpServer.getTs();
this.callback = callback;
this.pollWaitSeconds = pollWaitTime > 0 ? pollWaitTime : Integer.parseInt(VkConstants.POLL_WAIT_TIME);
}
private void disconnect(String reason) {
if (!isInterrupted() && !isClosed) {
isClosed = true;
interrupt();
httpClient.getConnectionManager().shutdown();
if (callback != null) {
callback.disconnected(reason);
}
}
}
@Override
public void run() {
while (!isInterrupted() && !isClosed) {
List<NameValuePair> params = new ArrayList<NameValuePair>(5);
params.add(new BasicNameValuePair("act", "a_check"));
params.add(new BasicNameValuePair("key", key));
params.add(new BasicNameValuePair("ts", ts));
params.add(new BasicNameValuePair("wait", Integer.toString(pollWaitSeconds)));
params.add(new BasicNameValuePair("mode", LONGPOLL_MODE_GET_ATTACHMENTS));
try {
String responseString = connector.request(Method.GET, "http://" + url, params, null, null, httpClient);
LongPollResponse response = new LongPollResponse(responseString);
ts = response.getTs();
String currentUpdate = response.getUpdatesJSON();
if (!lastUpdate.equals(currentUpdate)) {
lastUpdate = currentUpdate;
for (LongPollResponseUpdate u : response.getUpdates()) {
processUpdate(u, callback);
}
} else {
Logger.log(" ... repeated " + currentUpdate);
Thread.sleep(1000);
}
if (response.isConnectionDead()) {
Logger.log("Dead longpoll connection", LoggerLevel.VERBOSE);
interrupt();
}
} catch (Exception e) {
Logger.log(e);
disconnect(e.getLocalizedMessage());
}
}
if (!isClosed) {
try {
connectLongPoll(pollWaitSeconds, callback);
} catch (RequestFailedException e) {
Logger.log(e);
}
}
}
private void processUpdate(LongPollResponseUpdate update, LongPollCallback callback) {
if (update == null) {
return;
}
switch (update.getType()) {
case BUDDY_ONLINE:
case BUDDY_OFFLINE_AWAY:
VkOnlineInfo vi = VkOnlineInfo.fromLongPollUpdate(update);
callback.onlineInfo(vi);
break;
case MSG_NEW:
VkMessage vkm = VkMessage.fromLongPollUpdate(update);
callback.message(vkm);
break;
case BUDDY_TYPING:
callback.typingNotification(update.getId(), 0);
break;
case BUDDY_TYPING_CHAT:
callback.typingNotification(Long.parseLong(update.getParams()[0]), update.getId());
break;
default:
Logger.log("LongPoll update: " + update.getType() + "/" + update.getId() + "/" + update.getParams(), LoggerLevel.INFO);
break;
}
}
}
public void disconnect(String reason) {
if (listener != null) {
listener.disconnect(reason);
}
}
private static HttpParams getHttpParams() {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 120000;
int timeoutSocket = 120000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
httpParameters.setParameter("http.useragent", "Android mobile");
httpParameters.setParameter(CoreConnectionPNames.TCP_NODELAY, Boolean.FALSE);
return httpParameters;
}
public static class RequestFailedException extends Exception {
private static final long serialVersionUID = -7412616341196774522L;
private RequestFailedException(Exception inner) {
super(inner);
}
private RequestFailedException(String reason) {
super(reason);
}
}
private enum Method {
POST, GET
}
public interface LongPollCallback {
void onlineInfo(VkOnlineInfo vi);
void message(VkMessage vkm);
void typingNotification(long contactId, long chatParticipantId);
void disconnected(String reason);
}
private static class VkEngineConnector {
private String lastRequest = "";
private String request(Method method, String url, List<NameValuePair> parameters, String content, List<? extends NameValuePair> nameValuePairs) throws RequestFailedException {
return request(method, url, parameters, content, nameValuePairs, null);
}
private String request(Method method, String url, List<NameValuePair> parameters, String content, List<? extends NameValuePair> nameValuePairs, HttpClient httpClient) throws RequestFailedException {
try {
byte[] resultBytes = requestRawStream(method, url, parameters, content, nameValuePairs, httpClient);
String result = new String(resultBytes, "UTF-8");
Logger.log("Got " + result, LoggerLevel.VERBOSE);
return result;
} catch (Exception e) {
throw new RequestFailedException(e);
}
}
private byte[] requestRawStream(Method method, String url, List<NameValuePair> parameters, String content, List<? extends NameValuePair> nameValuePairs, HttpClient httpClient) throws RequestFailedException, URISyntaxException, ClientProtocolException, IOException {
if (url.equals(lastRequest)) {
try {
Thread.sleep(400);
} catch (InterruptedException e) {}
}
lastRequest = url;
Uri.Builder b = new Uri.Builder();
b.encodedPath(url);
if (parameters != null) {
for (NameValuePair p : parameters) {
b.appendQueryParameter(p.getName(), p.getValue());
}
}
url = b.build().toString();
HttpRequestBase request;
switch (method) {
case GET:
request = new HttpGet(new URI(url));
break;
case POST:
request = new HttpPost(new URI(url));
if (nameValuePairs != null) {
((HttpPost) request).setEntity(new UrlEncodedFormEntity(nameValuePairs));
}
if (content != null) {
((HttpPost) request).setEntity(new StringEntity(content));
}
break;
default:
Logger.log("Unknown request method " + method, LoggerLevel.WTF);
return null;
}
HttpEntity httpEntity = null;
HttpClient innerHttpClient = httpClient;
try {
if (innerHttpClient == null){
innerHttpClient = new DefaultHttpClient(getHttpParams());
innerHttpClient.getParams().setParameter("http.useragent", "Android mobile");
}
request.addHeader("Accept-Encoding", "gzip");
Logger.log("Ask " + url, LoggerLevel.VERBOSE);
HttpResponse response = innerHttpClient.execute(request);
Logger.log("..." + response.getStatusLine().getStatusCode(), LoggerLevel.VERBOSE);
httpEntity = response.getEntity();
InputStream instream = httpEntity.getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
int read = -1;
while((read = instream.read(buffer, 0, buffer.length)) != -1) {
ostream.write(buffer, 0, read);
}
ostream.flush();
return ostream.toByteArray();
} finally {
if (httpEntity != null) {
httpEntity.consumeContent();
}
if (httpClient == null && innerHttpClient != null) {
innerHttpClient.getConnectionManager().shutdown();
}
}
}
}
}
| apache-2.0 |
dump247/aws-sdk-java | aws-java-sdk-elasticbeanstalk/src/main/java/com/amazonaws/services/elasticbeanstalk/model/ValidationMessage.java | 11086 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.elasticbeanstalk.model;
import java.io.Serializable;
/**
* <p>
* An error or warning for a desired configuration option value.
* </p>
*/
public class ValidationMessage implements Serializable, Cloneable {
/**
* <p>
* A message describing the error or warning.
* </p>
*/
private String message;
/**
* <p>
* An indication of the severity of this message:
* </p>
* <ul>
* <li> <code>error</code>: This message indicates that this is not a valid
* setting for an option.</li>
* <li> <code>warning</code>: This message is providing information you
* should take into account.</li>
* </ul>
*/
private String severity;
/** <p/> */
private String namespace;
/** <p/> */
private String optionName;
/**
* <p>
* A message describing the error or warning.
* </p>
*
* @param message
* A message describing the error or warning.
*/
public void setMessage(String message) {
this.message = message;
}
/**
* <p>
* A message describing the error or warning.
* </p>
*
* @return A message describing the error or warning.
*/
public String getMessage() {
return this.message;
}
/**
* <p>
* A message describing the error or warning.
* </p>
*
* @param message
* A message describing the error or warning.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ValidationMessage withMessage(String message) {
setMessage(message);
return this;
}
/**
* <p>
* An indication of the severity of this message:
* </p>
* <ul>
* <li> <code>error</code>: This message indicates that this is not a valid
* setting for an option.</li>
* <li> <code>warning</code>: This message is providing information you
* should take into account.</li>
* </ul>
*
* @param severity
* An indication of the severity of this message: </p>
* <ul>
* <li> <code>error</code>: This message indicates that this is not a
* valid setting for an option.</li>
* <li> <code>warning</code>: This message is providing information
* you should take into account.</li>
* @see ValidationSeverity
*/
public void setSeverity(String severity) {
this.severity = severity;
}
/**
* <p>
* An indication of the severity of this message:
* </p>
* <ul>
* <li> <code>error</code>: This message indicates that this is not a valid
* setting for an option.</li>
* <li> <code>warning</code>: This message is providing information you
* should take into account.</li>
* </ul>
*
* @return An indication of the severity of this message: </p>
* <ul>
* <li> <code>error</code>: This message indicates that this is not a
* valid setting for an option.</li>
* <li> <code>warning</code>: This message is providing information
* you should take into account.</li>
* @see ValidationSeverity
*/
public String getSeverity() {
return this.severity;
}
/**
* <p>
* An indication of the severity of this message:
* </p>
* <ul>
* <li> <code>error</code>: This message indicates that this is not a valid
* setting for an option.</li>
* <li> <code>warning</code>: This message is providing information you
* should take into account.</li>
* </ul>
*
* @param severity
* An indication of the severity of this message: </p>
* <ul>
* <li> <code>error</code>: This message indicates that this is not a
* valid setting for an option.</li>
* <li> <code>warning</code>: This message is providing information
* you should take into account.</li>
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see ValidationSeverity
*/
public ValidationMessage withSeverity(String severity) {
setSeverity(severity);
return this;
}
/**
* <p>
* An indication of the severity of this message:
* </p>
* <ul>
* <li> <code>error</code>: This message indicates that this is not a valid
* setting for an option.</li>
* <li> <code>warning</code>: This message is providing information you
* should take into account.</li>
* </ul>
*
* @param severity
* An indication of the severity of this message: </p>
* <ul>
* <li> <code>error</code>: This message indicates that this is not a
* valid setting for an option.</li>
* <li> <code>warning</code>: This message is providing information
* you should take into account.</li>
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see ValidationSeverity
*/
public void setSeverity(ValidationSeverity severity) {
this.severity = severity.toString();
}
/**
* <p>
* An indication of the severity of this message:
* </p>
* <ul>
* <li> <code>error</code>: This message indicates that this is not a valid
* setting for an option.</li>
* <li> <code>warning</code>: This message is providing information you
* should take into account.</li>
* </ul>
*
* @param severity
* An indication of the severity of this message: </p>
* <ul>
* <li> <code>error</code>: This message indicates that this is not a
* valid setting for an option.</li>
* <li> <code>warning</code>: This message is providing information
* you should take into account.</li>
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see ValidationSeverity
*/
public ValidationMessage withSeverity(ValidationSeverity severity) {
setSeverity(severity);
return this;
}
/**
* <p/>
*
* @param namespace
*/
public void setNamespace(String namespace) {
this.namespace = namespace;
}
/**
* <p/>
*
* @return
*/
public String getNamespace() {
return this.namespace;
}
/**
* <p/>
*
* @param namespace
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ValidationMessage withNamespace(String namespace) {
setNamespace(namespace);
return this;
}
/**
* <p/>
*
* @param optionName
*/
public void setOptionName(String optionName) {
this.optionName = optionName;
}
/**
* <p/>
*
* @return
*/
public String getOptionName() {
return this.optionName;
}
/**
* <p/>
*
* @param optionName
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ValidationMessage withOptionName(String optionName) {
setOptionName(optionName);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getMessage() != null)
sb.append("Message: " + getMessage() + ",");
if (getSeverity() != null)
sb.append("Severity: " + getSeverity() + ",");
if (getNamespace() != null)
sb.append("Namespace: " + getNamespace() + ",");
if (getOptionName() != null)
sb.append("OptionName: " + getOptionName());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ValidationMessage == false)
return false;
ValidationMessage other = (ValidationMessage) obj;
if (other.getMessage() == null ^ this.getMessage() == null)
return false;
if (other.getMessage() != null
&& other.getMessage().equals(this.getMessage()) == false)
return false;
if (other.getSeverity() == null ^ this.getSeverity() == null)
return false;
if (other.getSeverity() != null
&& other.getSeverity().equals(this.getSeverity()) == false)
return false;
if (other.getNamespace() == null ^ this.getNamespace() == null)
return false;
if (other.getNamespace() != null
&& other.getNamespace().equals(this.getNamespace()) == false)
return false;
if (other.getOptionName() == null ^ this.getOptionName() == null)
return false;
if (other.getOptionName() != null
&& other.getOptionName().equals(this.getOptionName()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode
+ ((getMessage() == null) ? 0 : getMessage().hashCode());
hashCode = prime * hashCode
+ ((getSeverity() == null) ? 0 : getSeverity().hashCode());
hashCode = prime * hashCode
+ ((getNamespace() == null) ? 0 : getNamespace().hashCode());
hashCode = prime * hashCode
+ ((getOptionName() == null) ? 0 : getOptionName().hashCode());
return hashCode;
}
@Override
public ValidationMessage clone() {
try {
return (ValidationMessage) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
}
| apache-2.0 |
nakamura5akihito/six-oval | src/main/java/io/opensec/six/oval/repository/DefinitionsElementQueryParams.java | 5797 | /**
* SIX OVAL - https://nakamura5akihito.github.io/
* Copyright (C) 2010 Akihito Nakamura
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.opensec.six.oval.repository;
import io.opensec.six.oval.model.ComponentType;
import io.opensec.six.oval.model.ElementType;
import io.opensec.util.repository.CommonQueryParams;
/**
* @author Akihito Nakamura, AIST
*/
public class DefinitionsElementQueryParams
extends CommonQueryParams
{
public static class Key
extends CommonQueryParams.Key
{
public static final String ID = "id";
public static final String VERSION = "version";
public static final String DEPRECATED = "deprecated";
public static final String TYPE = "type";
//DefinitionsElement.Type {definition, test, object, state, variable}
public static final String FAMILY = "family";
//Family {linux, unix, windows, ...}
public static final String COMPONENT = "component";
//Component {file, rpminfo, registry, ...}
public static final String REFERER = "referer";
// public static final String COMMENT = "comment"; // Use searchTerms instead!
//TODO: Is this required???
public static final String SCHEMA = "schema";
public static final String DOCUMENT = "document";
}
// Key
// /**
// * The default sorting order.
// */
// public static final String DEFAULT_ORDER = Key.ID;
/**
* Constructor.
*/
public DefinitionsElementQueryParams()
{
// setOrder( DEFAULT_ORDER );
//NOTE: Since the type of OVAL-IDs is String,
// this ordering specifies the lexicographical sorting,
// e.g. def:99 is bigger than def:111.
}
/**
*/
public void setId(
final String id
)
{
set( Key.ID, id );
}
public String getId()
{
return get( Key.ID );
}
/**
*/
public void setVersion(
final String version
)
{
set( Key.VERSION, version );
}
public String getVersion()
{
return get( Key.VERSION );
}
/**
*/
public void setDeprecated(
final String deprecated
)
{
set( Key.DEPRECATED, deprecated );
}
public String getDeprecated()
{
return get( Key.DEPRECATED );
}
/**
*/
public void setType(
final String type
)
{
if (type != null) {
ElementType.fromValue( type );
// DefinitionsElement.Type.fromValue( type );
// OvalEntityType.valueOf( type );
}
set( Key.TYPE, type );
}
public String getType()
{
return get( Key.TYPE );
}
/**
*/
public void setFamily(
final String family
)
{
//NOTE: list value!!!
// if (family != null) {
// Family.fromValue( family );
// }
set( Key.FAMILY, family );
}
public String getFamily()
{
return get( Key.FAMILY );
}
/**
*/
public void setComponent(
final String component
)
{
// if (component != null) {
// Component.fromValue( component );
// }
set( Key.COMPONENT, component );
}
public void setComponent(
final ComponentType component
)
{
// if (component != null) {
// Component.fromValue( component );
// }
if (component == null) {
setComponent( (String)null );
} else {
setComponent( component.value() );
}
}
public void setComponent(
final ComponentType[] component_list
)
{
if (component_list == null || component_list.length == 0) {
setComponent( (String)null );
} else {
StringBuffer s = new StringBuffer();
for (ComponentType c : component_list) {
if (c != null) {
if (s.length() > 0) {
s.append( LIST_DELIMITER );
}
s.append( c.value() );
}
}
setComponent( s.toString() );
}
}
public String getComponent()
{
return get( Key.COMPONENT );
}
/**
*/
public void setReferer(
final String referer
)
{
set( Key.REFERER, referer );
}
public String getReferer()
{
return get( Key.REFERER );
}
/**
*/
public void setSchema(
final String schema
)
{
set( Key.SCHEMA, schema );
}
public String getSchema()
{
return get( Key.SCHEMA );
}
/**
*/
public void setDocument(
final String document
)
{
set( Key.DOCUMENT, document );
}
public String getDocument()
{
return get( Key.DOCUMENT );
}
}
//
| apache-2.0 |
fazlan-nazeem/carbon-apimgt | components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/KeyManagerConfiguration.java | 2587 | /*
*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* /
*/
package org.wso2.carbon.apimgt.api.model;
import java.util.HashMap;
import java.util.Map;
/**
* Stores configurations specific for a KeyManager implementation. Certain features will be made available based on
* the values set in this Config.
*/
public class KeyManagerConfiguration {
private String name;
private String type;
private boolean enabled;
private String tenantDomain;
public enum TokenType {
EXCHANGED, ORIGINAL
}
public enum IdpTypeOfExchangedTokens {
Okta, KeyCloak, Auth0, PingFederate, ForgeRock, Microsoft, Asgardeo
}
private TokenType tokenType = TokenType.ORIGINAL;
private Map<String, Object> configuration = new HashMap<>();
public void addParameter(String name, Object value) {
configuration.put(name, value);
}
public Object getParameter(String name) {
return configuration.get(name);
}
public void setConfiguration(Map<String, Object> configuration) {
this.configuration = configuration;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getTenantDomain() {
return tenantDomain;
}
public void setTenantDomain(String tenantDomain) {
this.tenantDomain = tenantDomain;
}
public Map<String, Object> getConfiguration() {
return configuration;
}
public TokenType getTokenType() {
return tokenType;
}
public void setTokenType(TokenType tokenType) {
this.tokenType = tokenType;
}
}
| apache-2.0 |
sdavids/sdavids-commons-test | src/test/java/io/sdavids/commons/test/WithThreadExtension.java | 3138 | /*
* Copyright (c) 2018, Sebastian Davids
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.sdavids.commons.test;
import static java.lang.Thread.currentThread;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.jupiter.api.extension.ExtensionContext.Namespace.create;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ExtensionContext.Namespace;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
public class WithThreadExtension
implements AfterEachCallback, BeforeEachCallback, ParameterResolver {
private static final Namespace WITH_THREAD = create(WithThreadExtension.class);
private static final String THREAD = "thread";
@Retention(RUNTIME)
@Target(PARAMETER)
public @interface WithThread {}
@Override
public void beforeEach(ExtensionContext context) {
Thread thread =
new Thread(
() -> {
while (!currentThread().isInterrupted()) {
try {
MILLISECONDS.sleep(10L);
} catch (InterruptedException e) {
// allow thread to exit
}
}
},
context.getDisplayName());
thread.start();
context.getStore(WITH_THREAD).put(THREAD, thread);
}
@Override
public void afterEach(ExtensionContext context) {
Thread thread = context.getStore(WITH_THREAD).remove(THREAD, Thread.class);
if (thread == null) {
return;
}
MockServices.setServicesForThread(thread);
thread.interrupt();
}
@Override
public boolean supportsParameter(
ParameterContext parameterContext, ExtensionContext extensionContext) {
return parameterContext.isAnnotated(WithThread.class);
}
@Override
public Object resolveParameter(
ParameterContext parameterContext, ExtensionContext extensionContext) {
if (Thread.class.equals(parameterContext.getParameter().getType())) {
return extensionContext.getStore(WITH_THREAD).get(THREAD, Thread.class);
}
throw new ParameterResolutionException(
"Not a Thread: " + parameterContext.getParameter().getType());
}
}
| apache-2.0 |
ParkJinSang/Jinseng-Server | src/main/Main.java | 3711 | package main;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import common.LogReporter;
import common.TextUtil;
import core.http.HttpMethod;
import core.http.HttpRequest;
import core.http.HttpServer;
import core.http.HttpServiceRouter;
import core.http.HttpUrl;
import core.tcp.*;
import core.udp.UdpServer;
import operation.ConfigManager;
import operation.ServerStatus;
import operation.ServiceLauncher;
import sample.http.EchoWebService;
import sample.http.RestWebService;
import sample.http.WebSiteService;
import sample.tcp.ChatRoomService;
import sample.tcp.FileTransferService;
import sample.tcp.PrintService;
import sample.udp.EchoService;
public class Main {
private static void LaunchPrintServer(){
TcpServer server = new TcpServer(new PrintService());
try {
server.RunServer();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
server.EndServer();
}
private static void LaunchFileTransferServer(){
TcpServer server = new TcpServer(new FileTransferService());
try {
server.RunServer();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
server.EndServer();
}
private static void LaunchChatRoomServer(){
TcpServer server = new TcpServer(new ChatRoomService());
try {
server.RunServer();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
server.EndServer();
}
private static void LaunchEchoWebServer(){
// HttpServiceRouter route = new HttpServiceRouter();
// route.setRoutingMethod(HttpUrl.ANYURL, new EchoWebService());
HttpServer server = new HttpServer(new EchoWebService(), 60000);
try {
server.RunServer();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
server.EndServer();
}
private static void LaunchRestWebServer(){
HttpServiceRouter route = new HttpServiceRouter();
route.setRoutingMethod("/students/{name}/{grade}/{age}", new RestWebService());
HttpServer server = new HttpServer(route, 60000);
try {
server.RunServer();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
server.EndServer();
}
private static void LaunchWebSite(){
HttpServiceRouter route = new HttpServiceRouter();
route.setRoutingMethod(HttpUrl.ANYURL, new WebSiteService());
HttpServer server = new HttpServer(route, 60000);
try {
server.RunServer();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
server.EndServer();
}
private static void LaunchUdpEchoServer(){
UdpServer server = new UdpServer(new EchoService());
try {
server.RunServer();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
server.EndServer();
}
public static void main(String[] args){
System.out.println("Hello World");
/*** The way to start TCP Chatting server*/
// LaunchChatRoomServer();
/*** The way to run Echo web server*/
// LaunchEchoWebServer();
/*** The way to run Http Rest server*/
// LaunchRestWebServer();
/*** The way to check remote server status */
// LaunchWebSite();
/*** The way to check remote server status */
// System.out.println(ServerStatus.getStatus());
/*** The way to run server using configurations */
// ConfigManager man = new ConfigManager();
// man.loadFromFile("echo-server.xml");
//
// ServiceLauncher launcher = new ServiceLauncher();
// launcher.loadService(man.getConfigInfo("echo"));
// launcher.runService();
/*** The way to use Udp Echo server */
LaunchUdpEchoServer();
}
}
| apache-2.0 |
Vovchyk/android-rss-feed-reader | app/src/main/java/rss/feed/reader/ui/activities/ResetPasswordActivity.java | 1668 | package rss.feed.reader.ui.activities;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import butterknife.BindView;
import butterknife.OnClick;
import rss.feed.reader.R;
import rss.feed.reader.dagger.components.ActivityComponent;
import rss.feed.reader.ui.base.BasePresenterAwareActivity;
import rss.feed.reader.ui.contracts.ResetPasswordContract;
import rss.feed.reader.utils.GuiUtils;
/**
* Created by omartynets on 28.10.2016.
*/
public class ResetPasswordActivity extends BasePresenterAwareActivity<ResetPasswordContract.Presenter>
implements ResetPasswordContract.View {
@BindView(R.id.email)
EditText mEmailField;
@BindView(R.id.btn_reset_password)
Button mButtonReset;
@OnClick(R.id.btn_reset_password)
public void resetPassword() {
getPresenter().resetPassword(mEmailField.getText().toString().trim());
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reset_password);
}
@Override
public void showEmailError(int message) {
mEmailField.requestFocus();
mEmailField.setError(getString(R.string.email_error));
}
@Override
public void showSnackBar(String message) {
GuiUtils.showSnackBarWithCallback(findViewById(R.id.reset_password_root_layout), message);
}
@Override
public void navigateToMain() {
mNavigation.toSignInActivity();
finish();
}
@Override
protected void injectActivity(ActivityComponent activityComponent) {
activityComponent.inject(this);
}
}
| apache-2.0 |
mksmbrtsh/formulaDict | src/maximsblog/blogspot/com/jlatexmath/core/MatrixAtom.java | 15785 | /* MatrixAtom.java
* =========================================================================
* This file is part of the JLaTeXMath Library - http://forge.scilab.org/jlatexmath
*
* Copyright (C) 2009 DENIZET Calixte
*
* 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 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* A copy of the GNU General Public License can be found in the file
* LICENSE.txt provided with the source distribution of this program (see
* the META-INF directory in the source jar). This license can also be
* found on the GNU website at http://www.gnu.org/licenses/gpl.html.
*
* If you did not receive a copy of the GNU General Public License along
* with this program, contact the lead developer, or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
*/
package maximsblog.blogspot.com.jlatexmath.core;
import java.util.BitSet;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
/**
* A box representing a matrix.
*/
public class MatrixAtom extends Atom {
public static SpaceAtom hsep = new SpaceAtom(-1, null, TeXConstants.UNIT_EM, 1f,
0.0f, 0.0f);
public static SpaceAtom semihsep = new SpaceAtom(-1, null, TeXConstants.UNIT_EM,
0.5f, 0.0f, 0.0f);
public static SpaceAtom vsep_in = new SpaceAtom(-1, null, TeXConstants.UNIT_EX, 0.0f,
1f, 0.0f);
public static SpaceAtom vsep_ext_top = new SpaceAtom(-1, null, TeXConstants.UNIT_EX,
0.0f, 0.4f, 0.0f);
public static SpaceAtom vsep_ext_bot = new SpaceAtom(-1, null, TeXConstants.UNIT_EX,
0.0f, 0.4f, 0.0f);
public static final int ARRAY = 0;
public static final int MATRIX = 1;
public static final int ALIGN = 2;
public static final int ALIGNAT = 3;
public static final int FLALIGN = 4;
public static final int SMALLMATRIX = 5;
public static final int ALIGNED = 6;
public static final int ALIGNEDAT = 7;
private static final Box nullBox = new StrutBox(-1, null, 0, 0, 0, 0);
private ArrayOfAtoms matrix;
private int[] position;
private Map<Integer, VlineAtom> vlines = new HashMap<Integer, VlineAtom>();
private boolean isAlign;
private boolean isAlignat;
private boolean isFl;
private int type;
private boolean isPartial;
private boolean spaceAround;
private static SpaceAtom align = new SpaceAtom(-1, null,TeXConstants.MEDMUSKIP);
/**
* Creates an empty matrix
*
*/
public MatrixAtom(int index, String token, boolean isPartial, ArrayOfAtoms array, String options,
boolean spaceAround) {
super(index, token);
this.isPartial = isPartial;
this.matrix = array;
this.type = ARRAY;
this.spaceAround = spaceAround;
parsePositions(new StringBuffer(options));
}
/**
* Creates an empty matrix
*
*/
public MatrixAtom(int index, String token, boolean isPartial, ArrayOfAtoms array, String options) {
this(index, token, isPartial, array, options, false);
}
/**
* Creates an empty matrix
*
*/
public MatrixAtom(int index, String token, ArrayOfAtoms array, String options) {
this(index, token, false, array, options);
}
public MatrixAtom(int index, String token, boolean isPartial, ArrayOfAtoms array, int type) {
this(index, token, isPartial, array, type, false);
}
public MatrixAtom(int index, String token, boolean isPartial, ArrayOfAtoms array, int type,
boolean spaceAround) {
super(index, token);
this.isPartial = isPartial;
this.matrix = array;
this.type = type;
this.spaceAround = spaceAround;
if (type != MATRIX && type != SMALLMATRIX) {
position = new int[matrix.col];
for (int i = 0; i < matrix.col; i += 2) {
position[i] = TeXConstants.ALIGN_RIGHT;
if (i + 1 < matrix.col) {
position[i + 1] = TeXConstants.ALIGN_LEFT;
}
}
} else {
position = new int[matrix.col];
for (int i = 0; i < matrix.col; i++) {
position[i] = TeXConstants.ALIGN_CENTER;
}
}
}
public MatrixAtom(int index, String token, boolean isPartial, ArrayOfAtoms array, int type,
int alignment) {
this(index, token, isPartial, array, type, alignment, true);
}
public MatrixAtom(int index, String token, boolean isPartial, ArrayOfAtoms array, int type,
int alignment, boolean spaceAround) {
super(index, token);
this.isPartial = isPartial;
this.matrix = array;
this.type = type;
this.spaceAround = spaceAround;
position = new int[matrix.col];
for (int i = 0; i < matrix.col; i++) {
position[i] = alignment;
}
}
public MatrixAtom(int index, String token, ArrayOfAtoms array, int type) {
this(index, token, false, array, type);
}
private void parsePositions(StringBuffer opt) {
int len = opt.length();
int pos = 0;
char ch;
TeXFormula tf;
TeXParser tp;
List<Integer> lposition = new ArrayList<Integer>();
while (pos < len) {
ch = opt.charAt(pos);
switch (ch) {
case 'l':
lposition.add(TeXConstants.ALIGN_LEFT);
break;
case 'r':
lposition.add(TeXConstants.ALIGN_RIGHT);
break;
case 'c':
lposition.add(TeXConstants.ALIGN_CENTER);
break;
case '|':
int nb = 1;
while (++pos < len) {
ch = opt.charAt(pos);
if (ch != '|') {
pos--;
break;
} else {
nb++;
}
}
vlines.put(lposition.size(), new VlineAtom(index, token, nb));
break;
case '@':
pos++;
tf = new TeXFormula();
tp = new TeXParser(isPartial, opt.substring(pos), tf, false);
Atom at = tp.getArgument();
matrix.col++;
for (int j = 0; j < matrix.row; j++) {
matrix.array.get(j).add(lposition.size(), at);
}
lposition.add(TeXConstants.ALIGN_NONE);
pos += tp.getPos();
pos--;
break;
case '*':
pos++;
tf = new TeXFormula();
tp = new TeXParser(isPartial, opt.substring(pos), tf, false);
String[] args = tp.getOptsArgs(2, 0);
pos += tp.getPos();
int nrep = Integer.parseInt(args[1]);
String str = "";
for (int j = 0; j < nrep; j++) {
str += args[2];
}
opt.insert(pos, str);
len = opt.length();
pos--;
break;
case ' ':
case '\t':
break;
default:
lposition.add(TeXConstants.ALIGN_CENTER);
}
pos++;
}
for (int j = lposition.size(); j < matrix.col; j++) {
lposition.add(TeXConstants.ALIGN_CENTER);
}
if (lposition.size() != 0) {
Integer[] tab = lposition.toArray(new Integer[0]);
position = new int[tab.length];
for (int i = 0; i < tab.length; i++) {
position[i] = tab[i];
}
} else {
position = new int[] { TeXConstants.ALIGN_CENTER };
}
}
public Box[] getColumnSep(TeXEnvironment env, float width) {
int row = matrix.row;
int col = matrix.col;
Box[] arr = new Box[col + 1];
Box Align, AlignSep, Hsep;
float h, w = env.getTextwidth();
int i;
if (type == ALIGNED || type == ALIGNEDAT) {
w = Float.POSITIVE_INFINITY;
}
switch (type) {
case ARRAY:
// Array : hsep_col/2 elem hsep_col elem hsep_col ... hsep_col elem
// hsep_col/2
i = 1;
if (position[0] == TeXConstants.ALIGN_NONE) {
arr[1] = new StrutBox(index, token, 0.0f, 0.0f, 0.0f, 0.0f);
i = 2;
}
if (spaceAround) {
arr[0] = semihsep.createBox(env);
} else {
arr[0] = new StrutBox(index, token, 0.0f, 0.0f, 0.0f, 0.0f);
}
arr[col] = arr[0];
Hsep = hsep.createBox(env);
for (; i < col; i++) {
if (position[i] == TeXConstants.ALIGN_NONE) {
arr[i] = new StrutBox(index, token, 0.0f, 0.0f, 0.0f, 0.0f);
arr[i + 1] = arr[i];
i++;
} else {
arr[i] = Hsep;
}
}
return arr;
case MATRIX:
case SMALLMATRIX:
// Simple matrix : (hsep_col/2 or 0) elem hsep_col elem hsep_col ...
// hsep_col elem (hsep_col/2 or 0)
arr[0] = nullBox;
arr[col] = arr[0];
Hsep = hsep.createBox(env);
for (i = 1; i < col; i++) {
arr[i] = Hsep;
}
return arr;
case ALIGNED:
case ALIGN:
// Align env. : hsep=(textwidth-matWidth)/(2n+1) and hsep eq_lft
// \medskip el_rgt hsep ... hsep elem hsep
Align = align.createBox(env);
if (w != Float.POSITIVE_INFINITY) {
h = Math.max((w - width - (col / 2) * Align.getWidth())
/ (float) Math.floor((col + 3) / 2), 0);
AlignSep = new StrutBox(index, token, h, 0.0f, 0.0f, 0.0f);
} else {
AlignSep = hsep.createBox(env);
}
arr[col] = AlignSep;
for (i = 0; i < col; i++) {
if (i % 2 == 0) {
arr[i] = AlignSep;
} else {
arr[i] = Align;
}
}
break;
case ALIGNEDAT:
case ALIGNAT:
// Alignat env. : hsep=(textwidth-matWidth)/2 and hsep elem ... elem
// hsep
if (w != Float.POSITIVE_INFINITY) {
h = Math.max((w - width) / 2, 0);
} else {
h = 0;
}
Align = align.createBox(env);
Box empty = nullBox;
arr[0] = new StrutBox(index, token, h, 0.0f, 0.0f, 0.0f);
arr[col] = arr[0];
for (i = 1; i < col; i++) {
if (i % 2 == 0) {
arr[i] = empty;
} else {
arr[i] = Align;
}
}
break;
case FLALIGN:
// flalign env. : hsep=(textwidth-matWidth)/(2n+1) and hsep eq_lft
// \medskip el_rgt hsep ... hsep elem hsep
Align = align.createBox(env);
if (w != Float.POSITIVE_INFINITY) {
h = Math.max((w - width - (col / 2) * Align.getWidth())
/ (float) Math.floor((col - 1) / 2), 0);
AlignSep = new StrutBox(index, token, h, 0.0f, 0.0f, 0.0f);
} else {
AlignSep = hsep.createBox(env);
}
arr[0] = nullBox;
arr[col] = arr[0];
for (i = 1; i < col; i++) {
if (i % 2 == 0) {
arr[i] = AlignSep;
} else {
arr[i] = Align;
}
}
break;
}
if (w == Float.POSITIVE_INFINITY) {
arr[0] = nullBox;
arr[col] = arr[0];
}
return arr;
}
public Box createBox(TeXEnvironment env) {
int row = matrix.row;
int col = matrix.col;
Box[][] boxarr = new Box[row][col];
float[] lineDepth = new float[row];
float[] lineHeight = new float[row];
float[] rowWidth = new float[col];
float matW = 0;
float drt = env.getTeXFont().getDefaultRuleThickness(env.getStyle());
if (type == SMALLMATRIX) {
env = env.copy();
env.setStyle(TeXConstants.STYLE_SCRIPT);
}
List<MulticolumnAtom> listMulti = new ArrayList<MulticolumnAtom>();
for (int i = 0; i < row; i++) {
lineDepth[i] = 0;
lineHeight[i] = 0;
for (int j = 0; j < col; j++) {
Atom at = null;
try {
at = matrix.array.get(i).get(j);
} catch (Exception e) {
// The previous atom was an intertext atom
// position[j - 1] = -1;
boxarr[i][j - 1].type = TeXConstants.TYPE_INTERTEXT;
j = col - 1;
}
boxarr[i][j] = (at == null) ? nullBox : at.createBox(env);
lineDepth[i] = Math.max(boxarr[i][j].getDepth(), lineDepth[i]);
lineHeight[i] = Math.max(boxarr[i][j].getHeight(),
lineHeight[i]);
if (boxarr[i][j].type != TeXConstants.TYPE_MULTICOLUMN) {
rowWidth[j] = Math
.max(boxarr[i][j].getWidth(), rowWidth[j]);
} else {
((MulticolumnAtom) at).setRowColumn(i, j);
listMulti.add((MulticolumnAtom) at);
}
}
}
for (int i = 0; i < listMulti.size(); i++) {
MulticolumnAtom multi = listMulti.get(i);
int c = multi.getCol();
int r = multi.getRow();
int n = multi.getSkipped();
float w = 0;
for (int j = c; j < c + n; j++) {
w += rowWidth[j];
}
if (boxarr[r][c].getWidth() > w) {
float extraW = (boxarr[r][c].getWidth() - w) / n;
for (int j = c; j < c + n; j++) {
rowWidth[j] += extraW;
}
}
}
for (int j = 0; j < col; j++) {
matW += rowWidth[j];
}
Box[] Hsep = getColumnSep(env, matW);
for (int j = 0; j < col + 1; j++) {
matW += Hsep[j].getWidth();
if (vlines.get(j) != null) {
matW += vlines.get(j).getWidth(env);
}
}
VerticalBox vb = new VerticalBox(index, token);
Box Vsep = vsep_in.createBox(env);
vb.add(vsep_ext_top.createBox(env));
float vsepH = Vsep.getHeight();
float totalHeight = 0;
for (int i = 0; i < row; i++) {
HorizontalBox hb = new HorizontalBox(index, token);
for (int j = 0; j < col; j++) {
switch (boxarr[i][j].type) {
case -1:
case TeXConstants.TYPE_MULTICOLUMN:
if (j == 0) {
if (vlines.get(0) != null) {
VlineAtom vat = vlines.get(0);
vat.setHeight(lineHeight[i] + lineDepth[i]
+ Vsep.getHeight());
vat.setShift(lineDepth[i] + Vsep.getHeight() / 2);
Box vatBox = vat.createBox(env);
hb.add(new HorizontalBox(index, token, vatBox, Hsep[0].getWidth()
+ vatBox.getWidth(),
TeXConstants.ALIGN_LEFT));
} else {
hb.add(Hsep[0]);
}
}
boolean lastVline = true;
if (boxarr[i][j].type == -1) {
hb.add(new HorizontalBox(index, token, boxarr[i][j], rowWidth[j],
position[j]));
} else {
Box b = generateMulticolumn(env, Hsep, rowWidth, i, j);
MulticolumnAtom matom = (MulticolumnAtom) matrix.array
.get(i).get(j);
j += matom.getSkipped() - 1;
hb.add(b);
lastVline = matom.hasRightVline();
}
if (lastVline && vlines.get(j + 1) != null) {
VlineAtom vat = vlines.get(j + 1);
vat.setHeight(lineHeight[i] + lineDepth[i]
+ Vsep.getHeight());
vat.setShift(lineDepth[i] + Vsep.getHeight() / 2);
Box vatBox = vat.createBox(env);
if (j < col - 1) {
hb.add(new HorizontalBox(index, token, vatBox, Hsep[j + 1]
.getWidth() + vatBox.getWidth(),
TeXConstants.ALIGN_CENTER));
} else {
hb.add(new HorizontalBox(index, token, vatBox, Hsep[j + 1]
.getWidth() + vatBox.getWidth(),
TeXConstants.ALIGN_RIGHT));
}
} else {
hb.add(Hsep[j + 1]);
}
break;
case TeXConstants.TYPE_INTERTEXT:
float f = env.getTextwidth();
f = f == Float.POSITIVE_INFINITY ? rowWidth[j] : f;
hb = new HorizontalBox(index, token, boxarr[i][j], f,
TeXConstants.ALIGN_LEFT);
j = col - 1;
break;
case TeXConstants.TYPE_HLINE:
HlineAtom at = (HlineAtom) matrix.array.get(i).get(j);
at.setWidth(matW);
if (i >= 1
&& matrix.array.get(i - 1).get(j) instanceof HlineAtom) {
hb.add(new StrutBox(index, token, 0, 2 * drt, 0, 0));
at.setShift(-Vsep.getHeight() / 2 + drt);
} else {
at.setShift(-Vsep.getHeight() / 2);
}
hb.add(at.createBox(env));
j = col;
break;
}
}
if (boxarr[i][0].type != TeXConstants.TYPE_HLINE) {
hb.setHeight(lineHeight[i]);
hb.setDepth(lineDepth[i]);
vb.add(hb);
if (i < row - 1)
vb.add(Vsep);
} else {
vb.add(hb);
}
}
vb.add(vsep_ext_bot.createBox(env));
totalHeight = vb.getHeight() + vb.getDepth();
float axis = env.getTeXFont().getAxisHeight(env.getStyle());
vb.setHeight(totalHeight / 2 + axis);
vb.setDepth(totalHeight / 2 - axis);
return vb;
}
private Box generateMulticolumn(TeXEnvironment env, Box[] Hsep,
float[] rowWidth, int i, int j) {
float w = 0;
MulticolumnAtom mca = (MulticolumnAtom) matrix.array.get(i).get(j);
int k, n = mca.getSkipped();
for (k = j; k < j + n - 1; k++) {
w += rowWidth[k] + Hsep[k + 1].getWidth();
if (vlines.get(k + 1) != null) {
w += vlines.get(k + 1).getWidth(env);
}
}
w += rowWidth[k];
Box b = mca.createBox(env);
float bw = b.getWidth();
if (bw > w) {
// It isn't a good idea but for the moment I have no other solution
// !
w = 0;
}
mca.setWidth(w);
b = mca.createBox(env);
return b;
}
}
| apache-2.0 |
danielsomerfield/go-strong-auth-plugin | src/test/java/com/thoughtworks/go/strongauth/wire/GoAuthenticationRequestDecoderTest.java | 1444 | package com.thoughtworks.go.strongauth.wire;
import com.google.common.base.Optional;
import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest;
import com.thoughtworks.go.strongauth.authentication.AuthenticationRequest;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class GoAuthenticationRequestDecoderTest {
@Test
public void testDecodeAuthenticationValidRequest() {
GoPluginApiRequest request = mock(GoPluginApiRequest.class);
when(request.requestBody()).thenReturn("{\"username\":\"uname\",\"password\":\"pword\"}");
GoAuthenticationRequestDecoder decoder = new GoAuthenticationRequestDecoder();
Optional<AuthenticationRequest> maybeRequest = decoder.decode(request);
assertThat(maybeRequest, is(Optional.of(new AuthenticationRequest("uname", "pword"))));
}
@Test
public void testDecodeToAbsentForInvalidRequest() {
GoPluginApiRequest request = mock(GoPluginApiRequest.class);
when(request.requestBody()).thenReturn("{\"password\":\"pword\"}");
GoAuthenticationRequestDecoder decoder = new GoAuthenticationRequestDecoder();
Optional<AuthenticationRequest> maybeRequest = decoder.decode(request);
assertThat(maybeRequest, is(Optional.<AuthenticationRequest>absent()));
}
} | apache-2.0 |
ChinaQuants/Strata | modules/market/src/test/java/com/opengamma/strata/market/param/ParameterSizeTest.java | 1380 | /**
* Copyright (C) 2016 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.market.param;
import static com.opengamma.strata.collect.TestHelper.assertSerialization;
import static com.opengamma.strata.collect.TestHelper.coverBeanEquals;
import static com.opengamma.strata.collect.TestHelper.coverImmutableBean;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import com.opengamma.strata.market.curve.CurveName;
/**
* Test {@link ParameterSize}.
*/
@Test
public class ParameterSizeTest {
private static final CurveName CURVE_NAME = CurveName.of("Test");
//-------------------------------------------------------------------------
public void test_of() {
ParameterSize test = ParameterSize.of(CURVE_NAME, 3);
assertEquals(test.getName(), CURVE_NAME);
assertEquals(test.getParameterCount(), 3);
}
//-------------------------------------------------------------------------
public void coverage() {
ParameterSize test = ParameterSize.of(CURVE_NAME, 3);
coverImmutableBean(test);
ParameterSize test2 = ParameterSize.of(CurveName.of("Foo"), 4);
coverBeanEquals(test, test2);
}
public void test_serialization() {
ParameterSize test = ParameterSize.of(CURVE_NAME, 3);
assertSerialization(test);
}
}
| apache-2.0 |
ketao1989/tools | src/main/java/io/github/ketao1989/excutors/MyDelayedQueue.java | 883 | /*
* Copyright (c) 2015 taocoder.com. All Rights Reserved.
*/
package io.github.ketao1989.excutors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
/**
* @author tao.ke Date: 16/5/4 Time: 上午12:00
*/
public class MyDelayedQueue extends ScheduledThreadPoolExecutor {
public MyDelayedQueue(int corePoolSize) {
super(corePoolSize);
}
public MyDelayedQueue(int corePoolSize, ThreadFactory threadFactory) {
super(corePoolSize, threadFactory);
}
public MyDelayedQueue(int corePoolSize, RejectedExecutionHandler handler) {
super(corePoolSize, handler);
}
public MyDelayedQueue(int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
super(corePoolSize, threadFactory, handler);
}
}
| apache-2.0 |
bozzzzo/quark | quarkc/test/emit/expected/java/string_methods/src/main/java/string_methods_md/string_methods_test_join_does_Method.java | 752 | package string_methods_md;
public class string_methods_test_join_does_Method extends quark.reflect.Method implements io.datawire.quark.runtime.QObject {
public string_methods_test_join_does_Method() {
super("string_methods.test_join", "does", new java.util.ArrayList(java.util.Arrays.asList(new Object[]{"quark.String"})));
}
public Object invoke(Object object, java.util.ArrayList<Object> args) {
string_methods.test_join obj = (string_methods.test_join) (object);
return (obj).does((String) ((args).get(0)));
}
public String _getClass() {
return (String) (null);
}
public Object _getField(String name) {
return null;
}
public void _setField(String name, Object value) {}
}
| apache-2.0 |
xiuxin/Huntering | common/src/test/java/com/huntering/common/repository/RepositoryHelperIT.java | 17067 | /**
* Copyright (c) 2005-2012 https://github.com/zhangkaitao
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.huntering.common.repository;
import com.huntering.common.entity.Sex;
import com.huntering.common.entity.User;
import com.huntering.common.entity.search.Searchable;
import com.huntering.common.repository.RepositoryHelper;
import com.huntering.common.repository.callback.DefaultSearchCallback;
import com.huntering.common.repository.callback.SearchCallback;
import com.huntering.common.test.BaseUserIT;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import java.util.List;
/**
* <p>User: Zhang Kaitao
* <p>Date: 13-5-5 上午9:10
* <p>Version: 1.0
*/
public class RepositoryHelperIT extends BaseUserIT {
@PersistenceUnit
private EntityManagerFactory entityManagerFactory;
private RepositoryHelper repositoryHelper;
@Before
public void setUp() {
RepositoryHelper.setEntityManagerFactory(entityManagerFactory);
repositoryHelper = new RepositoryHelper(User.class);
}
@Test
public void testGetEntityManager() {
Assert.assertNotNull(repositoryHelper.getEntityManager());
}
@Test
public void testCount() {
String ql = "select count(o) from User o";
long expectedCount = repositoryHelper.count(ql) + 1;
User user = createUser();
repositoryHelper.getEntityManager().persist(user);
Assert.assertEquals(expectedCount, repositoryHelper.count(ql));
}
@Test
public void testCountWithCondition() {
User user = createUser();
repositoryHelper.getEntityManager().persist(user);
String ql = "select count(o) from User o where id >= ? and id <=?";
Assert.assertEquals(1, repositoryHelper.count(ql, user.getId(), user.getId()));
Assert.assertEquals(0, repositoryHelper.count(ql, user.getId(), 0L));
}
@Test
public void testFindAll() {
String ql = "select o from User o";
List<User> before = repositoryHelper.findAll(ql);
User user1 = createUser();
User user2 = createUser();
repositoryHelper.getEntityManager().persist(user1);
repositoryHelper.getEntityManager().persist(user2);
List<User> after = repositoryHelper.findAll(ql);
Assert.assertEquals(before.size() + 2, after.size());
Assert.assertTrue(after.contains(user1));
}
@Test
public void testFindAllWithCondition() {
String ql = "select o from User o where id>=? and id<=?";
List<User> before = repositoryHelper.findAll(ql, 0L, Long.MAX_VALUE);
User user1 = createUser();
User user2 = createUser();
User user3 = createUser();
User user4 = createUser();
repositoryHelper.getEntityManager().persist(user1);
repositoryHelper.getEntityManager().persist(user2);
repositoryHelper.getEntityManager().persist(user3);
repositoryHelper.getEntityManager().persist(user4);
List<User> after = repositoryHelper.findAll(ql, 0L, user2.getId());
Assert.assertEquals(before.size() + 2, after.size());
Assert.assertTrue(after.contains(user1));
Assert.assertTrue(after.contains(user2));
Assert.assertFalse(after.contains(user3));
Assert.assertFalse(after.contains(user4));
}
@Test
public void testFindAllWithPage() {
repositoryHelper.batchUpdate("delete from User");
User user1 = createUser();
User user2 = createUser();
User user3 = createUser();
User user4 = createUser();
repositoryHelper.getEntityManager().persist(user1);
repositoryHelper.getEntityManager().persist(user2);
repositoryHelper.getEntityManager().persist(user3);
repositoryHelper.getEntityManager().persist(user4);
String ql = "select o from User o";
Assert.assertEquals(4, repositoryHelper.findAll(ql, null).size());
List<User> list = repositoryHelper.findAll(ql, new PageRequest(0, 2));
Assert.assertEquals(2, list.size());
Assert.assertTrue(list.contains(user1));
}
@Test
public void testFindAllWithSort() {
repositoryHelper.batchUpdate("delete from User");
User user1 = createUser();
User user2 = createUser();
User user3 = createUser();
User user4 = createUser();
repositoryHelper.getEntityManager().persist(user1);
repositoryHelper.getEntityManager().persist(user2);
repositoryHelper.getEntityManager().persist(user3);
repositoryHelper.getEntityManager().persist(user4);
String ql = "select o from User o";
List<User> list = repositoryHelper.findAll(ql, new Sort(Sort.Direction.DESC, "id"));
Assert.assertEquals(4, list.size());
Assert.assertTrue(list.get(0).equals(user4));
}
@Test
public void testFindAllWithPageAndSort() {
repositoryHelper.batchUpdate("delete from User");
User user1 = createUser();
User user2 = createUser();
User user3 = createUser();
User user4 = createUser();
repositoryHelper.getEntityManager().persist(user1);
repositoryHelper.getEntityManager().persist(user2);
repositoryHelper.getEntityManager().persist(user3);
repositoryHelper.getEntityManager().persist(user4);
String ql = "select o from User o";
List<User> list = repositoryHelper.findAll(ql, new PageRequest(0, 2, new Sort(Sort.Direction.DESC, "id")));
Assert.assertEquals(2, list.size());
Assert.assertTrue(list.get(0).equals(user4));
Assert.assertTrue(list.contains(user3));
Assert.assertFalse(list.contains(user1));
}
@Test
public void testFindOne() {
User user1 = createUser();
User user2 = createUser();
repositoryHelper.getEntityManager().persist(user1);
repositoryHelper.getEntityManager().persist(user2);
String ql = "select o from User o where id=? and baseInfo.sex=?";
Assert.assertNotNull(repositoryHelper.findOne(ql, user1.getId(), Sex.male));
Assert.assertNull(repositoryHelper.findOne(ql, user1.getId(), Sex.female));
}
@Test
public void testFindAllWithSearchableAndDefaultSearchCallbck() {
User user1 = createUser();
User user2 = createUser();
User user3 = createUser();
User user4 = createUser();
repositoryHelper.getEntityManager().persist(user1);
repositoryHelper.getEntityManager().persist(user2);
repositoryHelper.getEntityManager().persist(user3);
repositoryHelper.getEntityManager().persist(user4);
Searchable searchable = Searchable.newSearchable();
searchable.addSearchParam("id_in", new Long[]{user1.getId(), user2.getId(), user3.getId()});
searchable.setPage(0, 2);
searchable.addSort(Sort.Direction.DESC, "id");
String ql = "from User where 1=1";
List<User> list = repositoryHelper.findAll(ql, searchable, SearchCallback.DEFAULT);
Assert.assertEquals(2, list.size());
Assert.assertEquals(user3, list.get(0));
}
@Test
public void testFindAllWithSearchableAndCustomSearchCallbck() {
User user1 = createUser();
User user2 = createUser();
user2.getBaseInfo().setRealname("lisi");
User user3 = createUser();
User user4 = createUser();
repositoryHelper.getEntityManager().persist(user1);
repositoryHelper.getEntityManager().persist(user2);
repositoryHelper.getEntityManager().persist(user3);
repositoryHelper.getEntityManager().persist(user4);
Searchable searchable = Searchable.newSearchable();
searchable.addSearchParam("realname", "zhang");
searchable.addSearchParam("id_lt", user4.getId());
searchable.setPage(0, 2);
searchable.addSort(Sort.Direction.DESC, "id");
SearchCallback customCallback = new DefaultSearchCallback() {
@Override
public void prepareQL(StringBuilder ql, Searchable search) {
//默认的
super.prepareQL(ql, search);
//自定义的
if (search.containsSearchKey("realname")) {//此处也可以使用realname_custom
ql.append(" and baseInfo.realname like :realname");
}
}
@Override
public void setValues(Query query, Searchable search) {
//默认的
super.setValues(query, search);
//自定义的
if (search.containsSearchKey("realname")) {
query.setParameter("realname", "%" + search.getValue("realname") + "%");
}
}
};
String ql = "from User where 1=1";
List<User> list = repositoryHelper.findAll(ql, searchable, customCallback);
Assert.assertEquals(2, list.size());
Assert.assertEquals(user3, list.get(0));
Assert.assertEquals(user1, list.get(1));
}
@Test
public void testFindAllWithSearchableAndCustomSearchCallbck2() {
User user1 = createUser();
User user2 = createUser();
user2.getBaseInfo().setRealname("lisi");
User user3 = createUser();
User user4 = createUser();
repositoryHelper.getEntityManager().persist(user1);
repositoryHelper.getEntityManager().persist(user2);
repositoryHelper.getEntityManager().persist(user3);
repositoryHelper.getEntityManager().persist(user4);
Searchable searchable = Searchable.newSearchable();
searchable.addSearchParam("realname", "zhang");
searchable.addSearchParam("id_lt", user4.getId());
searchable.setPage(0, 2);
searchable.addSort(Sort.Direction.DESC, "id");
SearchCallback customCallback = new DefaultSearchCallback() {
@Override
public void prepareQL(StringBuilder ql, Searchable search) {
//不调用默认的
if (search.containsSearchKey("id_lt")) {
ql.append(" and id < :id");
}
//自定义的
if (search.containsSearchKey("realname_custom")) {//此处也可以使用realname_custom
ql.append(" and baseInfo.realname like :realname");
}
}
@Override
public void setValues(Query query, Searchable search) {
//不调用默认的
if (search.containsSearchKey("id_lt")) {
query.setParameter("id", search.getValue("id_lt"));
}
//自定义的
if (search.containsSearchKey("realname")) {
query.setParameter("realname", "%" + search.getValue("realname") + "%");
}
}
};
String ql = "from User where 1=1";
List<User> list = repositoryHelper.findAll(ql, searchable, customCallback);
Assert.assertEquals(2, list.size());
Assert.assertEquals(user3, list.get(0));
Assert.assertEquals(user1, list.get(1));
}
@Test
public void testCountWithSearchableAndDefaultSearchCallbck() {
User user1 = createUser();
User user2 = createUser();
User user3 = createUser();
User user4 = createUser();
repositoryHelper.getEntityManager().persist(user1);
repositoryHelper.getEntityManager().persist(user2);
repositoryHelper.getEntityManager().persist(user3);
repositoryHelper.getEntityManager().persist(user4);
Searchable searchable = Searchable.newSearchable();
searchable.addSearchParam("id_in", new Long[]{user1.getId(), user2.getId(), user3.getId()});
searchable.addSort(Sort.Direction.DESC, "id");
String ql = "select count(*) from User where 1=1";
long total = repositoryHelper.count(ql, searchable, SearchCallback.DEFAULT);
Assert.assertEquals(3L, total);
}
@Test
public void testCountWithSearchableAndCustomSearchCallbck() {
User user1 = createUser();
User user2 = createUser();
user2.getBaseInfo().setRealname("lisi");
User user3 = createUser();
User user4 = createUser();
repositoryHelper.getEntityManager().persist(user1);
repositoryHelper.getEntityManager().persist(user2);
repositoryHelper.getEntityManager().persist(user3);
repositoryHelper.getEntityManager().persist(user4);
Searchable searchable = Searchable.newSearchable();
searchable.addSearchParam("realname", "zhang");
searchable.addSearchParam("id_lt", user4.getId());
searchable.setPage(0, 2);
searchable.addSort(Sort.Direction.DESC, "id");
SearchCallback customCallback = new DefaultSearchCallback() {
@Override
public void prepareQL(StringBuilder ql, Searchable search) {
//默认的
super.prepareQL(ql, search);
//自定义的
if (search.containsSearchKey("realname")) {//此处也可以使用realname_custom
ql.append(" and baseInfo.realname like :realname");
}
}
@Override
public void setValues(Query query, Searchable search) {
//默认的
super.setValues(query, search);
//自定义的
if (search.containsSearchKey("realname")) {
query.setParameter("realname", "%" + search.getValue("realname") + "%");
}
}
};
String ql = "select count(*) from User where 1=1";
long total = repositoryHelper.count(ql, searchable, customCallback);
Assert.assertEquals(2, total);
}
@Test
public void testCountWithSearchableAndCustomSearchCallbck2() {
User user1 = createUser();
User user2 = createUser();
user2.getBaseInfo().setRealname("lisi");
User user3 = createUser();
User user4 = createUser();
repositoryHelper.getEntityManager().persist(user1);
repositoryHelper.getEntityManager().persist(user2);
repositoryHelper.getEntityManager().persist(user3);
repositoryHelper.getEntityManager().persist(user4);
Searchable searchable = Searchable.newSearchable();
searchable.addSearchParam("realname", "zhang");
searchable.addSearchParam("id_lt", user4.getId());
searchable.setPage(0, 2);
searchable.addSort(Sort.Direction.DESC, "id");
SearchCallback customCallback = new DefaultSearchCallback() {
@Override
public void prepareQL(StringBuilder ql, Searchable search) {
//不调用默认的
if (search.containsSearchKey("id_lt")) {
ql.append(" and id < :id");
}
//自定义的
if (search.containsSearchKey("realname_custom")) {//此处也可以使用realname_custom
ql.append(" and baseInfo.realname like :realname");
}
}
@Override
public void setValues(Query query, Searchable search) {
//不调用默认的
if (search.containsSearchKey("id_lt")) {
query.setParameter("id", search.getValue("id_lt"));
}
//自定义的
if (search.containsSearchKey("realname")) {
query.setParameter("realname", "%" + search.getValue("realname") + "%");
}
}
};
String ql = "select count(*) from User where 1=1";
long total = repositoryHelper.count(ql, searchable, customCallback);
Assert.assertEquals(2, total);
}
@Test
public void testBatchUpdate() {
User user1 = createUser();
User user2 = createUser();
user2.getBaseInfo().setRealname("lisi");
User user3 = createUser();
User user4 = createUser();
repositoryHelper.getEntityManager().persist(user1);
repositoryHelper.getEntityManager().persist(user2);
repositoryHelper.getEntityManager().persist(user3);
repositoryHelper.getEntityManager().persist(user4);
String newPassword = "123321";
String updateQL = "update User set password=? where id=?";
repositoryHelper.batchUpdate(updateQL, newPassword, user1.getId());
clear();
user1 = repositoryHelper.findOne("from User where id=?", user1.getId());
Assert.assertEquals(newPassword, user1.getPassword());
}
}
| apache-2.0 |
palessandro/activejdbc | activejdbc/src/main/java/org/javalite/activejdbc/ModelRegistry.java | 5873 | /*
Copyright 2009-2016 Igor Polevoy
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.javalite.activejdbc;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import org.javalite.activejdbc.conversion.Converter;
import org.javalite.activejdbc.conversion.DateToStringConverter;
import org.javalite.activejdbc.conversion.StringToSqlDateConverter;
import org.javalite.activejdbc.conversion.StringToTimestampConverter;
import org.javalite.activejdbc.validation.AttributePresenceValidator;
import org.javalite.activejdbc.validation.NumericValidationBuilder;
import org.javalite.activejdbc.validation.NumericValidator;
import org.javalite.activejdbc.validation.ValidationBuilder;
import org.javalite.activejdbc.validation.Validator;
/**
* Stores metadata for a Model: converters, etc.
*
* @author ericbn
*/
class ModelRegistry {
private final List<CallbackListener> callbacks = new ArrayList<>();
private final Map<String, List<Converter>> attributeConverters = new CaseInsensitiveMap<>();
private final List<Validator> validators = new ArrayList<>();
void callbackWith(CallbackListener... listeners) {
callbackWith(Arrays.asList(listeners));
}
void callbackWith(Collection<CallbackListener> callbacks) {
this.callbacks.addAll(callbacks);
}
List<CallbackListener> callbacks() {
return callbacks;
}
/**
* Registers date converters (Date -> String -> java.sql.Date) for specified model attributes.
*/
void dateFormat(String pattern, String... attributes) {
dateFormat(new SimpleDateFormat(pattern), attributes);
}
/**
* Registers date converters (Date -> String -> java.sql.Date) for specified model attributes.
*/
void dateFormat(DateFormat format, String... attributes) {
convertWith(new DateToStringConverter(format), attributes);
convertWith(new StringToSqlDateConverter(format), attributes);
}
/**
* Registers timestamp converters (Date -> String -> java.sql.Timestamp) for specified model attributes.
*/
void timestampFormat(String pattern, String... attributes) {
timestampFormat(new SimpleDateFormat(pattern), attributes);
}
/**
* Registers timestamp converters (Date -> String -> java.sql.Timestamp) for specified model attributes.
*/
void timestampFormat(DateFormat format, String... attributes) {
convertWith(new DateToStringConverter(format), attributes);
convertWith(new StringToTimestampConverter(format), attributes);
}
/**
* Registers converter for specified model attributes.
*/
void convertWith(Converter converter, String... attributes) {
for (String attribute : attributes) {
convertWith(converter, attribute);
}
}
/**
* Registers converter for specified model attribute.
*/
void convertWith(Converter converter, String attribute) {
List<Converter> list = attributeConverters.get(attribute);
if (list == null) {
list = new ArrayList<>();
attributeConverters.put(attribute, list);
}
list.add(converter);
}
/**
* Returns converter for specified model attribute, able to convert from sourceClass to destinationClass.
* Returns null if no suitable converter was found.
*/
<S, T> Converter<S, T> converterForClass(String attribute, Class<S> sourceClass, Class<T> destinationClass) {
List<Converter> list = attributeConverters.get(attribute);
if (list != null) {
for (Converter converter : list) {
if (converter.canConvert(sourceClass, destinationClass)) {
return converter;
}
}
}
return null;
}
/**
* Returns converter for specified model attribute, able to convert value to an instance of destinationClass.
* Returns null if no suitable converter was found.
*/
<T> Converter<Object, T> converterForValue(String attribute, Object value, Class<T> destinationClass) {
return converterForClass(attribute,
value != null ? (Class<Object>) value.getClass() : Object.class, destinationClass);
}
ValidationBuilder validateWith(Validator validator) {
validators.add(validator);
return new ValidationBuilder(validator);
}
ValidationBuilder validateWith(List<Validator> list) {
this.validators.addAll(list);
return new ValidationBuilder(list);
}
NumericValidationBuilder validateNumericalityOf(String... attributes) {
List<NumericValidator> list = new ArrayList<>();
for (String attribute : attributes) {
NumericValidator validator = new NumericValidator(attribute);
list.add(validator);
validators.add(validator);
}
return new NumericValidationBuilder(list);
}
ValidationBuilder validatePresenceOf(String... attributes) {
List<Validator> list = new ArrayList<>();
for (String attribute : attributes) {
list.add(new AttributePresenceValidator(attribute));
}
return validateWith(list);
}
void removeValidator(Validator validator) {
validators.remove(validator);
}
List<Validator> validators() {
return validators;
}
}
| apache-2.0 |
NationalSecurityAgency/ghidra | Ghidra/Debug/Framework-Debugging/src/main/java/ghidra/dbg/memory/MemoryReader.java | 1111 | /* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.dbg.memory;
import java.util.concurrent.CompletableFuture;
/**
* The functional interface for reads from a cached memory
*
* @see CachedMemory
*/
public interface MemoryReader {
/**
* Read target memory
*
* If cached, any cached regions are removed from the request. If this results in non-contiguous
* regions, each generates a new request, forwarded to the wrapped read method.
*/
// TODO: Use ByteBuffer instead?
public CompletableFuture<byte[]> readMemory(long address, int length);
}
| apache-2.0 |
palessandro/activejdbc | activejdbc/src/test/java/org/javalite/activejdbc/BatchExecTest.java | 1921 | /*
Copyright 2009-2016 Igor Polevoy
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.
*/
/**
* @author Igor Polevoy: 12/17/13 3:05 PM
*/
package org.javalite.activejdbc;
import org.javalite.activejdbc.test.ActiveJDBCTest;
import org.junit.Test;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
public class BatchExecTest extends ActiveJDBCTest {
@Override
public void before() throws Exception {
super.before();
deleteFromTable("people");
}
@Test
public void shouldInsertAsBatch() {
PreparedStatement ps = Base.startBatch("insert into people (NAME, LAST_NAME, DOB) values(?, ?, ?)");
Base.addBatch(ps, "Mic", "Jagger", getDate(1962, 1, 1));
Base.addBatch(ps, "Marilyn", "Monroe", getDate(1932, 1, 1));
int[] counts = Base.executeBatch(ps);
the(counts.length).shouldBeEqual(2);
the(counts[0] == 1 || counts[0] == Statement.SUCCESS_NO_INFO).shouldBeTrue(); //Oracle!!
the(counts[1] == 1 || counts[1] == Statement.SUCCESS_NO_INFO).shouldBeTrue();
List<Map> people = Base.findAll("select * from people order by name");
the(people.size()).shouldBeEqual(2);
the(people.get(0).get("name")).shouldBeEqual("Marilyn");
the(people.get(1).get("name")).shouldBeEqual("Mic");
}
}
| apache-2.0 |
dhanji/sitebricks | sitebricks-acceptance-tests/src/test/java/com/google/sitebricks/acceptance/page/JspValidatingPage.java | 1145 | package com.google.sitebricks.acceptance.page;
import com.google.sitebricks.acceptance.util.AcceptanceTest;
import org.openqa.selenium.By;
import org.openqa.selenium.support.How;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import java.util.ArrayList;
import java.util.List;
public class JspValidatingPage {
@FindBy(how = How.XPATH, using = "//div[@class='errors'][1]/ul")
private WebElement constraintViolations;
private WebDriver driver;
public JspValidatingPage(WebDriver driver) {
this.driver = driver;
}
public List<String> getValidationViolations() {
List<String> items = new ArrayList<String>();
for (WebElement li : constraintViolations.findElements(By.tagName("li"))) {
items.add(li.getText().trim());
}
return items;
}
public static JspValidatingPage open(WebDriver driver) {
driver.get(AcceptanceTest.baseUrl() + "/jspvalidating");
driver.findElement(By.id("submit")).click();
return PageFactory.initElements(driver, JspValidatingPage.class);
}
}
| apache-2.0 |
everttigchelaar/camel-svn | components/camel-jing/src/test/java/org/apache/camel/component/validator/jing/RNCRouteTest.java | 1295 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.validator.jing;
import org.apache.camel.component.validator.ValidatorRouteTest;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @version
*/
public class RNCRouteTest extends ValidatorRouteTest {
protected ClassPathXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("org/apache/camel/component/validator/jing/rnc-context.xml");
}
} | apache-2.0 |
GoogleCloudPlatform/cloud-opensource-java | enforcer-rules/src/test/java/com/google/cloud/tools/dependencies/enforcer/LinkageCheckerRuleTest.java | 28883 | /*
* Copyright 2019 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
*
* 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.google.cloud.tools.dependencies.enforcer;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.cloud.tools.dependencies.enforcer.LinkageCheckerRule.DependencySection;
import com.google.cloud.tools.opensource.dependencies.OsProperties;
import com.google.cloud.tools.opensource.dependencies.RepositoryUtility;
import com.google.common.collect.ImmutableList;
import com.google.common.graph.Traverser;
import com.google.common.truth.Truth;
import java.io.File;
import java.net.URISyntaxException;
import java.net.URLClassLoader;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import org.apache.maven.artifact.handler.DefaultArtifactHandler;
import org.apache.maven.enforcer.rule.api.EnforcerLevel;
import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.DependencyManagement;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.DependencyResolutionException;
import org.apache.maven.project.DependencyResolutionRequest;
import org.apache.maven.project.DependencyResolutionResult;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectDependenciesResolver;
import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.eclipse.aether.RepositoryException;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.artifact.Artifact;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.collection.CollectRequest;
import org.eclipse.aether.graph.DefaultDependencyNode;
import org.eclipse.aether.graph.Dependency;
import org.eclipse.aether.graph.DependencyNode;
import org.eclipse.aether.resolution.ArtifactResolutionException;
import org.eclipse.aether.resolution.DependencyRequest;
import org.eclipse.aether.resolution.DependencyResult;
import org.eclipse.aether.transfer.ArtifactNotFoundException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers;
public class LinkageCheckerRuleTest {
private LinkageCheckerRule rule = new LinkageCheckerRule();
private RepositorySystem repositorySystem;
private RepositorySystemSession repositorySystemSession;
private Artifact dummyArtifactWithFile;
private MavenProject mockProject;
private EnforcerRuleHelper mockRuleHelper;
private Log mockLog;
private MavenSession mockMavenSession;
private MojoExecution mockMojoExecution;
private ProjectDependenciesResolver mockProjectDependenciesResolver;
private DependencyResolutionResult mockDependencyResolutionResult;
@Before
public void setup()
throws ExpressionEvaluationException, ComponentLookupException,
DependencyResolutionException, URISyntaxException {
repositorySystem = RepositoryUtility.newRepositorySystem();
repositorySystemSession = RepositoryUtility.newSession(repositorySystem);
dummyArtifactWithFile = createArtifactWithDummyFile("a:b:0.1");
setupMock();
}
private Artifact createArtifactWithDummyFile(String coordinates) throws URISyntaxException {
return new DefaultArtifact(coordinates)
.setFile(Paths.get(URLClassLoader.getSystemResource("dummy-0.0.1.jar").toURI()).toFile());
}
private void setupMock()
throws ExpressionEvaluationException, ComponentLookupException,
DependencyResolutionException {
mockProject = mock(MavenProject.class);
mockMavenSession = mock(MavenSession.class);
when(mockMavenSession.getRepositorySession()).thenReturn(repositorySystemSession);
mockRuleHelper = mock(EnforcerRuleHelper.class);
mockProjectDependenciesResolver = mock(ProjectDependenciesResolver.class);
mockDependencyResolutionResult = mock(DependencyResolutionResult.class);
mockLog = mock(Log.class);
when(mockRuleHelper.getLog()).thenReturn(mockLog);
when(mockRuleHelper.getComponent(ProjectDependenciesResolver.class))
.thenReturn(mockProjectDependenciesResolver);
when(mockProjectDependenciesResolver.resolve(any(DependencyResolutionRequest.class)))
.thenReturn(mockDependencyResolutionResult);
when(mockRuleHelper.evaluate("${session}")).thenReturn(mockMavenSession);
when(mockRuleHelper.evaluate("${project}")).thenReturn(mockProject);
mockMojoExecution = mock(MojoExecution.class);
when(mockMojoExecution.getLifecyclePhase()).thenReturn("verify");
when(mockRuleHelper.evaluate("${mojoExecution}")).thenReturn(mockMojoExecution);
org.apache.maven.artifact.DefaultArtifact rootArtifact =
new org.apache.maven.artifact.DefaultArtifact(
"com.google.cloud",
"linkage-checker-rule-test",
"0.0.1",
"compile",
"jar",
null,
new DefaultArtifactHandler());
rootArtifact.setFile(new File("dummy.jar"));
when(mockProject.getArtifact()).thenReturn(rootArtifact);
when(mockProject.getRemoteProjectRepositories())
.thenReturn(ImmutableList.of(RepositoryUtility.CENTRAL));
}
/**
* Returns a dependency graph node resolved from {@code coordinates}.
*/
private DependencyNode createResolvedDependencyGraph(String... coordinates)
throws RepositoryException {
CollectRequest collectRequest = new CollectRequest();
collectRequest.setRootArtifact(dummyArtifactWithFile);
collectRequest.setRepositories(ImmutableList.of(RepositoryUtility.CENTRAL));
collectRequest.setDependencies(
Arrays.stream(coordinates)
.map(DefaultArtifact::new)
.map(artifact -> new Dependency(artifact, "compile"))
.collect(toImmutableList()));
DependencyNode dependencyNode =
repositorySystem.collectDependencies(repositorySystemSession, collectRequest).getRoot();
DependencyRequest dependencyRequest = new DependencyRequest();
dependencyRequest.setRoot(dependencyNode);
DependencyResult dependencyResult =
repositorySystem.resolveDependencies(repositorySystemSession, dependencyRequest);
return dependencyResult.getRoot();
}
private void setupMockDependencyResolution(String... coordinates) throws RepositoryException {
// The root node is Maven artifact "a:b:0.1" that has dependencies specified as `coordinates`.
DependencyNode rootNode = createResolvedDependencyGraph(coordinates);
Traverser<DependencyNode> traverser = Traverser.forGraph(node -> node.getChildren());
// DependencyResolutionResult.getDependencies returns depth-first order
ImmutableList<Dependency> dummyDependencies =
ImmutableList.copyOf(traverser.depthFirstPreOrder(rootNode)).stream()
.map(DependencyNode::getDependency)
.filter(Objects::nonNull)
.collect(toImmutableList());
when(mockDependencyResolutionResult.getDependencies()).thenReturn(dummyDependencies);
when(mockDependencyResolutionResult.getResolvedDependencies())
.thenReturn(
ImmutableList.copyOf(traverser.breadthFirst(rootNode.getChildren())).stream()
.map(DependencyNode::getDependency)
.filter(Objects::nonNull)
.collect(toImmutableList()));
when(mockDependencyResolutionResult.getDependencyGraph()).thenReturn(rootNode);
when(mockProject.getDependencies())
.thenReturn(
dummyDependencies.subList(0, coordinates.length).stream()
.map(LinkageCheckerRuleTest::toDependency)
.collect(Collectors.toList()));
}
@Test
public void testExecute_shouldPassGoodProject()
throws EnforcerRuleException, RepositoryException {
// Since Guava 27, it requires com.google.guava:failureaccess artifact in its dependency.
setupMockDependencyResolution("com.google.guava:guava:27.0.1-jre");
// This should not raise an EnforcerRuleException
rule.execute(mockRuleHelper);
verify(mockLog).info("No error found");
}
@Test
public void testExecute_shouldPassGoodProject_sessionProperties()
throws EnforcerRuleException, RepositoryException, DependencyResolutionException {
setupMockDependencyResolution("com.google.guava:guava:27.0.1-jre");
rule.execute(mockRuleHelper);
ArgumentCaptor<DependencyResolutionRequest> argumentCaptor =
ArgumentCaptor.forClass(DependencyResolutionRequest.class);
verify(mockProjectDependenciesResolver).resolve(argumentCaptor.capture());
Map<String, String> propertiesUsedInSession =
argumentCaptor.getValue().getRepositorySession().getSystemProperties();
Truth.assertWithMessage(
"RepositorySystemSession should have variables such as os.detected.classifier")
.that(propertiesUsedInSession)
.containsAtLeastEntriesIn(OsProperties.detectOsProperties());
// There was a problem in resolving profiles because original properties were missing (#817)
Truth.assertWithMessage("RepositorySystemSession should have original properties")
.that(propertiesUsedInSession)
.containsAtLeastEntriesIn(repositorySystemSession.getSystemProperties());
}
@Test
public void testExecute_shouldFailForBadProject() throws RepositoryException {
try {
// This artifact is known to contain classes missing dependencies
setupMockDependencyResolution("com.google.appengine:appengine-api-1.0-sdk:1.9.64");
rule.execute(mockRuleHelper);
Assert.fail(
"The rule should raise an EnforcerRuleException for artifacts missing dependencies");
} catch (EnforcerRuleException ex) {
// pass
ArgumentCaptor<String> errorMessageCaptor = ArgumentCaptor.forClass(String.class);
verify(mockLog, times(1)).error(errorMessageCaptor.capture());
String errorMessage = errorMessageCaptor.getValue();
// Java 11 removed javax.activation package. Therefore the number of expected errors differs
// between Java 8 and Java 11.
// https://github.com/GoogleCloudPlatform/cloud-opensource-java/issues/1856
int expectedErrorCount = System.getProperty("java.version").startsWith("1.8.") ? 112 : 117;
Truth.assertThat(errorMessage)
.startsWith("Linkage Checker rule found " + expectedErrorCount + " errors:");
Truth.assertThat(errorMessage)
.contains(
"Problematic artifacts in the dependency tree:\n"
+ "com.google.appengine:appengine-api-1.0-sdk:1.9.64 is at:\n"
+ " a:b:jar:0.1 / com.google.appengine:appengine-api-1.0-sdk:1.9.64 (compile)");
assertEquals("Failed while checking class path. See above error report.", ex.getMessage());
}
}
@Test
public void testExecute_shouldFailForBadProject_reachableErrors() throws RepositoryException {
try {
// This pair of artifacts contains linkage errors on grpc-core's use of Verify. Because
// grpc-core is included in entry point jars, the errors are reachable.
setupMockDependencyResolution(
"com.google.api-client:google-api-client:1.27.0", "io.grpc:grpc-core:1.17.1");
rule.setReportOnlyReachable(true);
rule.execute(mockRuleHelper);
Assert.fail(
"The rule should raise an EnforcerRuleException for artifacts with reachable errors");
} catch (EnforcerRuleException ex) {
// pass
verify(mockLog)
.error(ArgumentMatchers.startsWith("Linkage Checker rule found 1 reachable error:"));
assertEquals(
"Failed while checking class path. See above error report.", ex.getMessage());
}
}
@Test
public void testExecute_shouldPassForBadProject_levelWarn()
throws RepositoryException, EnforcerRuleException {
// This pair of artifacts contains linkage errors on grpc-core's use of Verify. Because
// grpc-core is included in entry point jars, the errors are reachable.
setupMockDependencyResolution(
"com.google.api-client:google-api-client:1.27.0", "io.grpc:grpc-core:1.17.1");
rule.setReportOnlyReachable(true);
rule.setLevel(EnforcerLevel.WARN);
rule.execute(mockRuleHelper);
verify(mockLog)
.warn(ArgumentMatchers.startsWith("Linkage Checker rule found 1 reachable error:"));
}
@Test
public void testExecute_shouldPassGoodProject_unreachableErrors()
throws EnforcerRuleException, RepositoryException {
// This artifact has transitive dependency on grpc-netty-shaded, which has linkage errors for
// missing classes. They are all unreachable.
setupMockDependencyResolution("com.google.cloud:google-cloud-automl:0.81.0-beta");
rule.setReportOnlyReachable(true);
// This should not raise EnforcerRuleException because the linkage errors are unreachable.
rule.execute(mockRuleHelper);
}
private void setupMockDependencyManagementSection(String... coordinates) {
org.apache.maven.artifact.DefaultArtifact bomArtifact =
new org.apache.maven.artifact.DefaultArtifact(
"com.google.dummy",
"dummy-bom",
"0.1",
"compile",
"pom",
"",
new DefaultArtifactHandler());
when(mockProject.getArtifact()).thenReturn(bomArtifact);
DependencyManagement mockDependencyManagement = mock(DependencyManagement.class);
when(mockProject.getDependencyManagement()).thenReturn(mockDependencyManagement);
ImmutableList<org.apache.maven.model.Dependency> bomMembers =
Arrays.stream(coordinates)
.map(DefaultArtifact::new)
.map(artifact -> new Dependency(artifact, "compile"))
.map(LinkageCheckerRuleTest::toDependency)
.collect(toImmutableList());
when(mockDependencyManagement.getDependencies()).thenReturn(bomMembers);
when(mockMavenSession.getRepositorySession()).thenReturn(repositorySystemSession);
}
private static org.apache.maven.model.Dependency toDependency(Dependency resolvedDependency) {
org.apache.maven.model.Dependency dependency = new org.apache.maven.model.Dependency();
Artifact artifact = resolvedDependency.getArtifact();
dependency.setArtifactId(artifact.getArtifactId());
dependency.setGroupId(artifact.getGroupId());
dependency.setVersion(artifact.getVersion());
dependency.setOptional(dependency.isOptional());
dependency.setClassifier(artifact.getClassifier());
dependency.setExclusions(dependency.getExclusions());
dependency.setScope(dependency.getScope());
return dependency;
}
@Test
public void testExecute_shouldPassEmptyBom() throws EnforcerRuleException {
rule.setDependencySection(DependencySection.DEPENDENCY_MANAGEMENT);
setupMockDependencyManagementSection(); // empty BOM
// This should not raise an EnforcerRuleException
rule.execute(mockRuleHelper);
}
@Test
public void testExecute_shouldPassGoodBom() throws EnforcerRuleException {
rule.setDependencySection(DependencySection.DEPENDENCY_MANAGEMENT);
setupMockDependencyManagementSection(
"com.google.guava:guava:27.0.1-android",
"io.grpc:grpc-auth:1.18.0",
"com.google.api:api-common:1.7.0");
// This should not raise an EnforcerRuleException
rule.execute(mockRuleHelper);
}
@Test
public void testExecute_shouldFailBadBom() {
rule.setDependencySection(DependencySection.DEPENDENCY_MANAGEMENT);
setupMockDependencyManagementSection(
"com.google.api-client:google-api-client:1.27.0", "io.grpc:grpc-core:1.17.1");
try {
rule.execute(mockRuleHelper);
Assert.fail("Enforcer rule should detect conflict between google-api-client and grpc-core");
} catch (EnforcerRuleException ex) {
// pass
}
}
@Test
public void testExecute_shouldSkipBadBomWithNonPomPackaging() throws EnforcerRuleException {
rule.setDependencySection(DependencySection.DEPENDENCY_MANAGEMENT);
setupMockDependencyManagementSection(
"com.google.api-client:google-api-client:1.27.0", "io.grpc:grpc-core:1.17.1");
when(mockProject.getArtifact())
.thenReturn(
new org.apache.maven.artifact.DefaultArtifact(
"com.google.cloud",
"linkage-checker-rule-test-bom",
"0.0.1",
"compile",
"jar", // BOM should have pom here
null,
new DefaultArtifactHandler()));
rule.execute(mockRuleHelper);
}
@Test
public void testExecute_shouldSkipNonBomPom() throws EnforcerRuleException {
when(mockProject.getArtifact())
.thenReturn(
new org.apache.maven.artifact.DefaultArtifact(
"com.google.cloud",
"linkage-checker-rule-parent",
"0.0.1",
"compile",
"pom",
null,
new DefaultArtifactHandler()));
// No exception
rule.execute(mockRuleHelper);
}
@Test
public void testExecute_shouldExcludeTestScope() throws EnforcerRuleException {
org.apache.maven.model.Dependency dependency = new org.apache.maven.model.Dependency();
Artifact artifact = new DefaultArtifact("junit:junit:3.8.2");
dependency.setArtifactId(artifact.getArtifactId());
dependency.setGroupId(artifact.getGroupId());
dependency.setVersion(artifact.getVersion());
dependency.setClassifier(artifact.getClassifier());
dependency.setScope("test");
when(mockDependencyResolutionResult.getDependencyGraph()).thenReturn(
new DefaultDependencyNode(dummyArtifactWithFile)
);
when(mockProject.getDependencies())
.thenReturn(ImmutableList.of(dependency));
rule.execute(mockRuleHelper);
}
@Test
public void testExecute_shouldFailForBadProjectWithBundlePackaging() throws RepositoryException {
try {
// This artifact is known to contain classes missing dependencies
setupMockDependencyResolution("com.google.appengine:appengine-api-1.0-sdk:1.9.64");
org.apache.maven.artifact.DefaultArtifact rootArtifact =
new org.apache.maven.artifact.DefaultArtifact(
"com.google.cloud",
"linkage-checker-rule-test",
"0.0.1",
"compile",
"bundle", // Maven Bundle Plugin uses "bundle" packaging.
null,
new DefaultArtifactHandler());
rootArtifact.setFile(new File("dummy.jar"));
when(mockProject.getArtifact()).thenReturn(rootArtifact);
rule.execute(mockRuleHelper);
Assert.fail(
"The rule should raise an EnforcerRuleException for artifacts missing dependencies");
} catch (EnforcerRuleException ex) {
// Java 11 removed javax.activation package. Therefore the number of expected errors differs
// between Java 8 and Java 11.
// https://github.com/GoogleCloudPlatform/cloud-opensource-java/issues/1856
int expectedErrorCount = System.getProperty("java.version").startsWith("1.8.") ? 112 : 117;
// pass
verify(mockLog)
.error(
ArgumentMatchers.startsWith(
"Linkage Checker rule found " + expectedErrorCount + " errors:"));
assertEquals("Failed while checking class path. See above error report.", ex.getMessage());
}
}
@Test
public void testExecute_shouldFilterExclusionRule_java8()
throws RepositoryException, URISyntaxException {
try {
// This artifact is known to contain classes missing dependencies
setupMockDependencyResolution("com.google.appengine:appengine-api-1.0-sdk:1.9.64");
String exclusionFileLocation =
Paths.get(ClassLoader.getSystemResource("appengine-exclusion.xml").toURI())
.toAbsolutePath()
.toString();
rule.setExclusionFile(exclusionFileLocation);
rule.execute(mockRuleHelper);
Assert.fail(
"The rule should raise an EnforcerRuleException for artifacts missing dependencies");
} catch (EnforcerRuleException ex) {
// pass.
// Java 11 removed javax.activation package. Therefore the number of expected errors differs
// between Java 8 and Java 11.
// https://github.com/GoogleCloudPlatform/cloud-opensource-java/issues/1856
int expectedErrorCount = System.getProperty("java.version").startsWith("1.8.") ? 93 : 98;
verify(mockLog)
.error(
ArgumentMatchers.startsWith(
"Linkage Checker rule found " + expectedErrorCount + " errors:"));
assertEquals("Failed while checking class path. See above error report.", ex.getMessage());
}
}
private DependencyResolutionException createDummyResolutionException(
Artifact missingArtifact, DependencyResolutionResult resolutionResult) {
Throwable cause3 = new ArtifactNotFoundException(missingArtifact, null);
Throwable cause2 = new ArtifactResolutionException(null, "dummy 3", cause3);
Throwable cause1 = new DependencyResolutionException(resolutionResult, "dummy 2", cause2);
DependencyResolutionException exception =
new DependencyResolutionException(resolutionResult, "dummy 1", cause1);
return exception;
}
@Test
public void testArtifactTransferError()
throws RepositoryException, DependencyResolutionException {
DependencyNode graph = createResolvedDependencyGraph("org.apache.maven:maven-core:jar:3.5.2");
DependencyResolutionResult resolutionResult = mock(DependencyResolutionResult.class);
when(resolutionResult.getDependencyGraph()).thenReturn(graph);
DependencyResolutionException exception =
createDummyResolutionException(
new DefaultArtifact("aopalliance:aopalliance:1.0"), resolutionResult);
when(mockProjectDependenciesResolver.resolve(any())).thenThrow(exception);
try {
rule.execute(mockRuleHelper);
fail("The rule should throw EnforcerRuleException upon dependency resolution exception");
} catch (EnforcerRuleException expected) {
verify(mockLog)
.warn(
"aopalliance:aopalliance:jar:1.0 was not resolved. "
+ "Dependency path: a:b:jar:0.1 > "
+ "org.apache.maven:maven-core:jar:3.5.2 (compile) > "
+ "com.google.inject:guice:jar:no_aop:4.0 (compile) > "
+ "aopalliance:aopalliance:jar:1.0 (compile)");
}
}
@Test
public void testArtifactTransferError_acceptableMissingArtifact()
throws URISyntaxException, DependencyResolutionException, EnforcerRuleException {
// Creating a dummy tree
// com.google.foo:project
// +- com.google.foo:child1 (provided)
// +- com.google.foo:child2 (optional)
// +- xerces:xerces-impl:jar:2.6.2 (optional)
DefaultDependencyNode missingArtifactNode =
new DefaultDependencyNode(
new Dependency(
createArtifactWithDummyFile("xerces:xerces-impl:jar:2.6.2"), "compile", true));
DefaultDependencyNode child2 =
new DefaultDependencyNode(
new Dependency(
createArtifactWithDummyFile("com.google.foo:child2:1.0.0"), "compile", true));
child2.setChildren(ImmutableList.of(missingArtifactNode));
DefaultDependencyNode child1 =
new DefaultDependencyNode(
new Dependency(createArtifactWithDummyFile("com.google.foo:child1:1.0.0"), "provided"));
child1.setChildren(ImmutableList.of(child2));
DefaultDependencyNode root =
new DefaultDependencyNode(createArtifactWithDummyFile("com.google.foo:project:1.0.0"));
root.setChildren(ImmutableList.of(child1));
DependencyResolutionResult resolutionResult = mock(DependencyResolutionResult.class);
when(resolutionResult.getDependencyGraph()).thenReturn(root);
when(resolutionResult.getResolvedDependencies())
.thenReturn(
ImmutableList.of(
child1.getDependency(),
child2.getDependency(),
missingArtifactNode.getDependency()));
// xerces-impl does not exist in Maven Central
DependencyResolutionException exception =
createDummyResolutionException(missingArtifactNode.getArtifact(), resolutionResult);
when(mockProjectDependenciesResolver.resolve(any())).thenThrow(exception);
// Should not throw DependencyResolutionException, because the missing xerces-impl is under both
// provided and optional dependencies.
rule.execute(mockRuleHelper);
}
@Test
public void testArtifactTransferError_missingArtifactNotInGraph()
throws URISyntaxException, DependencyResolutionException, EnforcerRuleException {
// Creating a dummy tree
// com.google.foo:project
// +- com.google.foo:child1 (provided)
// +- com.google.foo:child2 (optional)
DefaultDependencyNode child2 =
new DefaultDependencyNode(
new Dependency(
createArtifactWithDummyFile("com.google.foo:child2:1.0.0"), "compile", true));
DefaultDependencyNode child1 =
new DefaultDependencyNode(
new Dependency(createArtifactWithDummyFile("com.google.foo:child1:1.0.0"), "provided"));
child1.setChildren(ImmutableList.of(child2));
DefaultDependencyNode root =
new DefaultDependencyNode(createArtifactWithDummyFile("com.google.foo:project:1.0.0"));
root.setChildren(ImmutableList.of(child1));
DependencyResolutionResult resolutionResult = mock(DependencyResolutionResult.class);
when(resolutionResult.getDependencyGraph()).thenReturn(root);
when(resolutionResult.getResolvedDependencies())
.thenReturn(ImmutableList.of(child1.getDependency(), child2.getDependency()));
// The exception is caused by this node but this node does not appear in the dependency graph.
DefaultDependencyNode missingArtifactNode =
new DefaultDependencyNode(
new Dependency(
createArtifactWithDummyFile("xerces:xerces-impl:jar:2.6.2"), "compile", true));
// xerces-impl does not exist in Maven Central
DependencyResolutionException exception =
createDummyResolutionException(missingArtifactNode.getArtifact(), resolutionResult);
when(mockProjectDependenciesResolver.resolve(any())).thenThrow(exception);
rule.execute(mockRuleHelper);
verify(mockLog)
.warn("xerces:xerces-impl:jar:2.6.2 was not resolved. Dependency path is unknown.");
}
@Test
public void testSkippingProjectWithoutFile() throws EnforcerRuleException {
when(mockProject.getArtifact())
.thenReturn(
new org.apache.maven.artifact.DefaultArtifact(
"com.google.cloud",
"foo-tests",
"0.0.1",
"compile",
"jar",
null,
new DefaultArtifactHandler()));
rule.execute(mockRuleHelper);
}
@Test
public void testValidatePhase() {
when(mockProject.getArtifact())
.thenReturn(
new org.apache.maven.artifact.DefaultArtifact(
"com.google.cloud",
"foo-tests",
"0.0.1",
"compile",
"jar",
null,
new DefaultArtifactHandler()));
when(mockMojoExecution.getLifecyclePhase()).thenReturn("validate");
try {
rule.execute(mockRuleHelper);
fail("The rule should throw EnforcerRuleException when running in validate phase");
} catch (EnforcerRuleException ex) {
assertEquals(
"To run the check on the compiled class files, the linkage checker enforcer rule should"
+ " be bound to the 'verify' phase. Current phase: validate",
ex.getMessage());
}
}
}
| apache-2.0 |
stevenyang001/OpenStudy4A | app/src/androidTest/java/com/open4a/openstudy/ExampleInstrumentedTest.java | 744 | package com.open4a.openstudy;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.open4a.openstudy", appContext.getPackageName());
}
}
| apache-2.0 |
weiwenqiang/GitHub | SelectWidget/glide-master/library/src/test/java/com/bumptech/glide/load/model/AssetUriLoaderTest.java | 1512 | package com.bumptech.glide.load.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
import android.content.res.AssetManager;
import android.net.Uri;
import com.bumptech.glide.load.Options;
import com.bumptech.glide.load.data.DataFetcher;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE, sdk = 18)
public class AssetUriLoaderTest {
private static final int IMAGE_SIDE = 10;
@Mock AssetUriLoader.AssetFetcherFactory<Object> factory;
@Mock DataFetcher<Object> fetcher;
private AssetUriLoader<Object> loader;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
loader = new AssetUriLoader<>(RuntimeEnvironment.application.getAssets(), factory);
}
@Test
public void testHandlesAssetUris() {
Uri assetUri = Uri.parse("file:///android_asset/assetName");
when(factory.buildFetcher(any(AssetManager.class), eq("assetName"))).thenReturn(fetcher);
assertTrue(loader.handles(assetUri));
assertEquals(fetcher, loader.buildLoadData(assetUri, IMAGE_SIDE, IMAGE_SIDE,
new Options()).fetcher);
}
}
| apache-2.0 |
xorware/android_frameworks_base | packages/SettingsLib/src/com/android/settingslib/drawer/SettingsDrawerActivity.java | 12237 | /**
* 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.settingslib.drawer;
import android.annotation.LayoutRes;
import android.annotation.Nullable;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.TypedArray;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.widget.DrawerLayout;
import android.util.ArraySet;
import android.util.Log;
import android.util.Pair;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toolbar;
import com.android.settingslib.R;
import com.android.settingslib.applications.InterestingConfigChanges;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class SettingsDrawerActivity extends Activity {
protected static final boolean DEBUG_TIMING = false;
private static final String TAG = "SettingsDrawerActivity";
public static final String EXTRA_SHOW_MENU = "show_drawer_menu";
private static List<DashboardCategory> sDashboardCategories;
private static HashMap<Pair<String, String>, Tile> sTileCache;
// Serves as a temporary list of tiles to ignore until we heard back from the PM that they
// are disabled.
private static ArraySet<ComponentName> sTileBlacklist = new ArraySet<>();
private static InterestingConfigChanges sConfigTracker;
private final PackageReceiver mPackageReceiver = new PackageReceiver();
private final List<CategoryListener> mCategoryListeners = new ArrayList<>();
private SettingsDrawerAdapter mDrawerAdapter;
private DrawerLayout mDrawerLayout;
private boolean mShowingMenu;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
long startTime = System.currentTimeMillis();
TypedArray theme = getTheme().obtainStyledAttributes(android.R.styleable.Theme);
if (!theme.getBoolean(android.R.styleable.Theme_windowNoTitle, false)) {
getWindow().addFlags(LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().addFlags(LayoutParams.FLAG_TRANSLUCENT_STATUS);
requestWindowFeature(Window.FEATURE_NO_TITLE);
}
super.setContentView(R.layout.settings_with_drawer);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
if (mDrawerLayout == null) {
return;
}
Toolbar toolbar = (Toolbar) findViewById(R.id.action_bar);
if (theme.getBoolean(android.R.styleable.Theme_windowNoTitle, false)) {
toolbar.setVisibility(View.GONE);
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
mDrawerLayout = null;
return;
}
getDashboardCategories();
setActionBar(toolbar);
mDrawerAdapter = new SettingsDrawerAdapter(this);
ListView listView = (ListView) findViewById(R.id.left_drawer);
listView.setAdapter(mDrawerAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(android.widget.AdapterView<?> parent, View view, int position,
long id) {
onTileClicked(mDrawerAdapter.getTile(position));
};
});
if (DEBUG_TIMING) Log.d(TAG, "onCreate took " + (System.currentTimeMillis() - startTime)
+ " ms");
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mShowingMenu && mDrawerLayout != null && item.getItemId() == android.R.id.home
&& mDrawerAdapter.getCount() != 0) {
openDrawer();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
if (mDrawerLayout != null) {
final IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
filter.addDataScheme("package");
registerReceiver(mPackageReceiver, filter);
new CategoriesUpdater().execute();
}
if (getIntent() != null && getIntent().getBooleanExtra(EXTRA_SHOW_MENU, false)) {
showMenuIcon();
}
}
@Override
protected void onPause() {
if (mDrawerLayout != null) {
unregisterReceiver(mPackageReceiver);
}
super.onPause();
}
public void addCategoryListener(CategoryListener listener) {
mCategoryListeners.add(listener);
}
public void remCategoryListener(CategoryListener listener) {
mCategoryListeners.remove(listener);
}
public void setIsDrawerPresent(boolean isPresent) {
if (isPresent) {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
updateDrawer();
} else {
if (mDrawerLayout != null) {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
mDrawerLayout = null;
}
}
}
public void openDrawer() {
if (mDrawerLayout != null) {
mDrawerLayout.openDrawer(Gravity.START);
}
}
public void closeDrawer() {
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawers();
}
}
@Override
public void setContentView(@LayoutRes int layoutResID) {
final ViewGroup parent = (ViewGroup) findViewById(R.id.content_frame);
if (parent != null) {
parent.removeAllViews();
}
LayoutInflater.from(this).inflate(layoutResID, parent);
}
@Override
public void setContentView(View view) {
((ViewGroup) findViewById(R.id.content_frame)).addView(view);
}
@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
((ViewGroup) findViewById(R.id.content_frame)).addView(view, params);
}
public void updateDrawer() {
if (mDrawerLayout == null) {
return;
}
// TODO: Do this in the background with some loading.
mDrawerAdapter.updateCategories();
if (mDrawerAdapter.getCount() != 0) {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
} else {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}
}
public void showMenuIcon() {
mShowingMenu = true;
getActionBar().setHomeAsUpIndicator(R.drawable.ic_menu);
getActionBar().setDisplayHomeAsUpEnabled(true);
}
public List<DashboardCategory> getDashboardCategories() {
if (sDashboardCategories == null) {
sTileCache = new HashMap<>();
sConfigTracker = new InterestingConfigChanges();
// Apply initial current config.
sConfigTracker.applyNewConfig(getResources());
sDashboardCategories = TileUtils.getCategories(this, sTileCache);
}
return sDashboardCategories;
}
protected void onCategoriesChanged() {
updateDrawer();
final int N = mCategoryListeners.size();
for (int i = 0; i < N; i++) {
mCategoryListeners.get(i).onCategoriesChanged();
}
}
public boolean openTile(Tile tile) {
closeDrawer();
if (tile == null) {
startActivity(new Intent(Settings.ACTION_SETTINGS).addFlags(
Intent.FLAG_ACTIVITY_CLEAR_TASK));
return true;
}
try {
int numUserHandles = tile.userHandle.size();
if (numUserHandles > 1) {
ProfileSelectDialog.show(getFragmentManager(), tile);
return false;
} else if (numUserHandles == 1) {
// Show menu on top level items.
tile.intent.putExtra(EXTRA_SHOW_MENU, true);
tile.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivityAsUser(tile.intent, tile.userHandle.get(0));
} else {
// Show menu on top level items.
tile.intent.putExtra(EXTRA_SHOW_MENU, true);
tile.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(tile.intent);
}
} catch (ActivityNotFoundException e) {
Log.w(TAG, "Couldn't find tile " + tile.intent, e);
}
return true;
}
protected void onTileClicked(Tile tile) {
if (openTile(tile)) {
finish();
}
}
public void onProfileTileOpen() {
finish();
}
public void setTileEnabled(ComponentName component, boolean enabled) {
PackageManager pm = getPackageManager();
int state = pm.getComponentEnabledSetting(component);
boolean isEnabled = state == PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
if (isEnabled != enabled || state == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
if (enabled) {
sTileBlacklist.remove(component);
} else {
sTileBlacklist.add(component);
}
pm.setComponentEnabledSetting(component, enabled
? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
: PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
new CategoriesUpdater().execute();
}
}
public interface CategoryListener {
void onCategoriesChanged();
}
private class CategoriesUpdater extends AsyncTask<Void, Void, List<DashboardCategory>> {
@Override
protected List<DashboardCategory> doInBackground(Void... params) {
if (sConfigTracker.applyNewConfig(getResources())) {
sTileCache.clear();
}
return TileUtils.getCategories(SettingsDrawerActivity.this, sTileCache);
}
@Override
protected void onPreExecute() {
if (sConfigTracker == null || sTileCache == null) {
getDashboardCategories();
}
}
@Override
protected void onPostExecute(List<DashboardCategory> dashboardCategories) {
for (int i = 0; i < dashboardCategories.size(); i++) {
DashboardCategory category = dashboardCategories.get(i);
for (int j = 0; j < category.tiles.size(); j++) {
Tile tile = category.tiles.get(j);
if (sTileBlacklist.contains(tile.intent.getComponent())) {
category.tiles.remove(j--);
}
}
}
sDashboardCategories = dashboardCategories;
onCategoriesChanged();
}
}
private class PackageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
new CategoriesUpdater().execute();
}
}
}
| apache-2.0 |
aifargonos/elk-reasoner | elk-proofs/src/main/java/org/semanticweb/elk/proofs/utils/InferencePrinter.java | 1209 | /**
*
*/
package org.semanticweb.elk.proofs.utils;
/*
* #%L
* ELK Proofs Package
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2011 - 2014 Department of Computer Science, University of Oxford
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import org.semanticweb.elk.proofs.inferences.Inference;
import org.semanticweb.elk.util.collections.Operations;
/**
* Prints inferences
*
* @author Pavel Klinov
*
* pavel.klinov@uni-ulm.de
*/
public class InferencePrinter {
public static String print(Inference inference) {
return String.format("%s( %s ) |- %s", inference.getRule().toString(), Operations.toString(inference.getPremises()), inference.getConclusion());
}
}
| apache-2.0 |
Udinei/pedido-venda | src/main/java/com/algawork/pedidovenda/controller/RelatorioPedidosEmitidosBean.java | 1787 | package com.algawork.pedidovenda.controller;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import org.hibernate.Session;
import com.algawork.pedidovenda.util.report.ExecutorRelatorio;
import com.algaworks.pedidovenda.util.jsf.FacesUtil;
@Named
@RequestScoped
public class RelatorioPedidosEmitidosBean implements Serializable {
private static final long serialVersionUID = 1L;
private Date dataInicio;
private Date dataFim;
@Inject
private FacesContext facesContext;
@Inject
private HttpServletResponse response;
@Inject
private EntityManager entityManager;
public void emitir() {
Map<String, Object> parametros = new HashMap();
parametros.put("data_inicio", this.dataInicio);
parametros.put("data_fim", this.dataFim);
ExecutorRelatorio executor = new ExecutorRelatorio("/relatorios/RelatorioPedidosEmitidos.jasper",
this.response, parametros, "Pedido Emitidos.pdf");
Session session = entityManager.unwrap(Session.class);
session.doWork(executor);
if (executor.isRelatorioGerado()) {
facesContext.responseComplete();
} else {
FacesUtil.addErrorMessage("A execução do relatório não retornou dados.");
}
}
@NotNull
public Date getDataInicio() {
return dataInicio;
}
public void setDataInicio(Date dataInicio) {
this.dataInicio = dataInicio;
}
@NotNull
public Date getDataFim() {
return dataFim;
}
public void setDataFim(Date dataFim) {
this.dataFim = dataFim;
}
} | apache-2.0 |
biboudis/streamalg | src/main/java/streams/algebras/ExecTakeStreamAlg.java | 207 | package streams.algebras;
/**
* Authors:
* Aggelos Biboudis (@biboudis)
* Nick Palladinos (@NickPalladinos)
*/
public interface ExecTakeStreamAlg<E, C> extends TakeStreamAlg<C>, ExecStreamAlg<E, C> {
}
| apache-2.0 |
consulo/consulo-java | java-psi-impl/src/main/java/com/intellij/psi/impl/source/PsiAnonymousClassImpl.java | 5913 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.impl.source;
import javax.annotation.Nonnull;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.impl.java.stubs.JavaStubElementTypes;
import com.intellij.psi.impl.java.stubs.PsiClassStub;
import com.intellij.psi.impl.source.tree.ChildRole;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.psi.util.PsiUtil;
import com.intellij.reference.SoftReference;
import com.intellij.util.IncorrectOperationException;
public class PsiAnonymousClassImpl extends PsiClassImpl implements PsiAnonymousClass
{
private SoftReference<PsiClassType> myCachedBaseType;
public PsiAnonymousClassImpl(final PsiClassStub stub)
{
super(stub, JavaStubElementTypes.ANONYMOUS_CLASS);
}
public PsiAnonymousClassImpl(final ASTNode node)
{
super(node);
}
@Override
protected Object clone()
{
PsiAnonymousClassImpl clone = (PsiAnonymousClassImpl) super.clone();
clone.myCachedBaseType = null;
return clone;
}
@Override
public void subtreeChanged()
{
super.subtreeChanged();
myCachedBaseType = null;
}
@Override
public PsiExpressionList getArgumentList()
{
return (PsiExpressionList) getNode().findChildByRoleAsPsiElement(ChildRole.ARGUMENT_LIST);
}
@Override
@Nonnull
public PsiJavaCodeReferenceElement getBaseClassReference()
{
final PsiElement baseRef = getFirstChild();
assert baseRef instanceof PsiJavaCodeReferenceElement : getText();
return (PsiJavaCodeReferenceElement) baseRef;
}
@Override
@Nonnull
public PsiClassType getBaseClassType()
{
final PsiClassStub stub = getGreenStub();
if(stub == null)
{
myCachedBaseType = null;
return getTypeByTree();
}
PsiClassType type = SoftReference.dereference(myCachedBaseType);
if(type != null)
{
return type;
}
if(!isInQualifiedNew() && !isDiamond(stub))
{
final String refText = stub.getBaseClassReferenceText();
assert refText != null : stub;
final PsiElementFactory factory = JavaPsiFacade.getInstance(getProject()).getElementFactory();
final PsiElement context = calcBasesResolveContext(PsiNameHelper.getShortClassName(refText), getExtendsList());
try
{
final PsiJavaCodeReferenceElement ref = factory.createReferenceFromText(refText, context);
((PsiJavaCodeReferenceElementImpl) ref).setKindWhenDummy(PsiJavaCodeReferenceElementImpl.Kind.CLASS_NAME_KIND);
type = factory.createType(ref);
}
catch(IncorrectOperationException e)
{
type = PsiType.getJavaLangObject(getManager(), getResolveScope());
}
myCachedBaseType = new SoftReference<PsiClassType>(type);
return type;
}
else
{
return getTypeByTree();
}
}
private boolean isDiamond(PsiClassStub stub)
{
if(PsiUtil.isLanguageLevel9OrHigher(this))
{
final String referenceText = stub.getBaseClassReferenceText();
if(referenceText != null && referenceText.endsWith(">"))
{
return StringUtil.trimEnd(referenceText, ">").trim().endsWith("<");
}
}
return false;
}
private PsiClassType getTypeByTree()
{
return JavaPsiFacade.getInstance(getProject()).getElementFactory().createType(getBaseClassReference());
}
@Override
public PsiIdentifier getNameIdentifier()
{
return null;
}
@Override
public String getQualifiedName()
{
return null;
}
@Override
public PsiModifierList getModifierList()
{
return null;
}
@Override
public boolean hasModifierProperty(@Nonnull String name)
{
return name.equals(PsiModifier.FINAL);
}
@Override
public PsiReferenceList getExtendsList()
{
return null;
}
@Override
public PsiReferenceList getImplementsList()
{
return null;
}
@Override
public PsiClass getContainingClass()
{
return null;
}
@Override
public boolean isInterface()
{
return false;
}
@Override
public boolean isAnnotationType()
{
return false;
}
@Override
public boolean isEnum()
{
return false;
}
@Override
public PsiTypeParameterList getTypeParameterList()
{
return null;
}
@Override
public PsiElement getOriginalElement()
{
return this;
}
@Override
public void accept(@Nonnull PsiElementVisitor visitor)
{
if(visitor instanceof JavaElementVisitor)
{
((JavaElementVisitor) visitor).visitAnonymousClass(this);
}
else
{
visitor.visitElement(this);
}
}
public String toString()
{
return "PsiAnonymousClass";
}
@Override
public boolean processDeclarations(@Nonnull PsiScopeProcessor processor, @Nonnull ResolveState state, PsiElement lastParent, @Nonnull PsiElement place)
{
if(lastParent instanceof PsiExpressionList)
{
return true;
}
if(lastParent instanceof PsiJavaCodeReferenceElement/* IMPORTANT: do not call getBaseClassReference() for lastParent == null and lastParent which is not under our node - loads tree!*/ &&
lastParent.getParent() == this && lastParent == getBaseClassReference())
{
return true;
}
return super.processDeclarations(processor, state, lastParent, place);
}
@Override
public boolean isInQualifiedNew()
{
final PsiClassStub stub = getGreenStub();
if(stub != null)
{
return stub.isAnonymousInQualifiedNew();
}
final PsiElement parent = getParent();
return parent instanceof PsiNewExpression && ((PsiNewExpression) parent).getQualifier() != null;
}
} | apache-2.0 |
NiteshKant/netty | codec-dns/src/test/java/io/netty/handler/codec/dns/TcpDnsTest.java | 3704 | /*
* Copyright 2021 The Netty Project
*
* The Netty Project 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:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.dns;
import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.ReferenceCountUtil;
import org.junit.jupiter.api.Test;
import java.util.Random;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class TcpDnsTest {
private static final String QUERY_DOMAIN = "www.example.com";
private static final long TTL = 600;
private static final byte[] QUERY_RESULT = new byte[]{(byte) 192, (byte) 168, 1, 1};
@Test
public void testQueryDecode() {
EmbeddedChannel channel = new EmbeddedChannel(new TcpDnsQueryDecoder());
int randomID = new Random().nextInt(60000 - 1000) + 1000;
DnsQuery query = new DefaultDnsQuery(randomID, DnsOpCode.QUERY)
.setRecord(DnsSection.QUESTION, new DefaultDnsQuestion(QUERY_DOMAIN, DnsRecordType.A));
assertTrue(channel.writeInbound(query));
DnsQuery readQuery = channel.readInbound();
assertThat(readQuery, is(query));
assertThat(readQuery.recordAt(DnsSection.QUESTION).name(), is(query.recordAt(DnsSection.QUESTION).name()));
assertFalse(channel.finish());
}
@Test
public void testResponseEncode() {
EmbeddedChannel channel = new EmbeddedChannel(new TcpDnsResponseEncoder());
int randomID = new Random().nextInt(60000 - 1000) + 1000;
DnsQuery query = new DefaultDnsQuery(randomID, DnsOpCode.QUERY)
.setRecord(DnsSection.QUESTION, new DefaultDnsQuestion(QUERY_DOMAIN, DnsRecordType.A));
DnsQuestion question = query.recordAt(DnsSection.QUESTION);
channel.writeInbound(newResponse(query, question, QUERY_RESULT));
DnsResponse readResponse = channel.readInbound();
assertThat(readResponse.recordAt(DnsSection.QUESTION), is((DnsRecord) question));
DnsRawRecord record = new DefaultDnsRawRecord(question.name(),
DnsRecordType.A, TTL, Unpooled.wrappedBuffer(QUERY_RESULT));
assertThat(readResponse.recordAt(DnsSection.ANSWER), is((DnsRecord) record));
assertThat(readResponse.<DnsRawRecord>recordAt(DnsSection.ANSWER).content(), is(record.content()));
ReferenceCountUtil.release(readResponse);
ReferenceCountUtil.release(record);
query.release();
assertFalse(channel.finish());
}
private static DefaultDnsResponse newResponse(DnsQuery query, DnsQuestion question, byte[]... addresses) {
DefaultDnsResponse response = new DefaultDnsResponse(query.id());
response.addRecord(DnsSection.QUESTION, question);
for (byte[] address : addresses) {
DefaultDnsRawRecord queryAnswer = new DefaultDnsRawRecord(question.name(),
DnsRecordType.A, TTL, Unpooled.wrappedBuffer(address));
response.addRecord(DnsSection.ANSWER, queryAnswer);
}
return response;
}
}
| apache-2.0 |
multi-os-engine/moe-core | moe.apple/moe.platform.ios/src/main/java/apple/carplay/protocol/CPSessionConfigurationDelegate.java | 1303 | package apple.carplay.protocol;
import apple.carplay.CPSessionConfiguration;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.ann.IsOptional;
import org.moe.natj.objc.ann.ObjCProtocolName;
import org.moe.natj.objc.ann.Selector;
@Generated
@Library("CarPlay")
@Runtime(ObjCRuntime.class)
@ObjCProtocolName("CPSessionConfigurationDelegate")
public interface CPSessionConfigurationDelegate {
@Generated
@IsOptional
@Selector("sessionConfiguration:contentStyleChanged:")
default void sessionConfigurationContentStyleChanged(CPSessionConfiguration sessionConfiguration,
@NUInt long contentStyle) {
throw new java.lang.UnsupportedOperationException();
}
/**
* This delegate is called whenever the types of limited user interfaces have changed.
*/
@Generated
@IsOptional
@Selector("sessionConfiguration:limitedUserInterfacesChanged:")
default void sessionConfigurationLimitedUserInterfacesChanged(CPSessionConfiguration sessionConfiguration,
@NUInt long limitedUserInterfaces) {
throw new java.lang.UnsupportedOperationException();
}
} | apache-2.0 |
greghogan/flink | flink-python/src/test/java/org/apache/flink/client/cli/PythonProgramOptionsTest.java | 4331 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.client.cli;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.python.PythonOptions;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.junit.Before;
import org.junit.Test;
import static org.apache.flink.client.cli.CliFrontendParser.PYARCHIVE_OPTION;
import static org.apache.flink.client.cli.CliFrontendParser.PYEXEC_OPTION;
import static org.apache.flink.client.cli.CliFrontendParser.PYFILES_OPTION;
import static org.apache.flink.client.cli.CliFrontendParser.PYMODULE_OPTION;
import static org.apache.flink.client.cli.CliFrontendParser.PYREQUIREMENTS_OPTION;
import static org.apache.flink.client.cli.CliFrontendParser.PY_OPTION;
import static org.apache.flink.python.PythonOptions.PYTHON_EXECUTABLE;
import static org.apache.flink.python.PythonOptions.PYTHON_REQUIREMENTS;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
/**
* Test for {@link PythonProgramOptions}.
*/
public class PythonProgramOptionsTest {
private Options options;
@Before
public void setUp() {
options = new Options();
options.addOption(PY_OPTION);
options.addOption(PYFILES_OPTION);
options.addOption(PYMODULE_OPTION);
options.addOption(PYREQUIREMENTS_OPTION);
options.addOption(PYARCHIVE_OPTION);
options.addOption(PYEXEC_OPTION);
}
@Test
public void testCreateProgramOptionsWithPythonCommandLine() throws CliArgsException {
String[] parameters = {
"-py", "test.py",
"-pym", "test",
"-pyfs", "test1.py,test2.zip,test3.egg,test4_dir",
"-pyreq", "a.txt#b_dir",
"-pyarch", "c.zip#venv,d.zip",
"-pyexec", "bin/python",
"userarg1", "userarg2"
};
CommandLine line = CliFrontendParser.parse(options, parameters, false);
PythonProgramOptions programOptions = (PythonProgramOptions) ProgramOptions.create(line);
Configuration config = new Configuration();
programOptions.applyToConfiguration(config);
assertEquals("test1.py,test2.zip,test3.egg,test4_dir", config.get(PythonOptions.PYTHON_FILES));
assertEquals("a.txt#b_dir", config.get(PYTHON_REQUIREMENTS));
assertEquals("c.zip#venv,d.zip", config.get(PythonOptions.PYTHON_ARCHIVES));
assertEquals("bin/python", config.get(PYTHON_EXECUTABLE));
assertArrayEquals(
new String[] {"--python", "test.py", "--pyModule", "test", "userarg1", "userarg2"},
programOptions.getProgramArgs());
}
@Test
public void testCreateProgramOptionsWithLongOptions() throws CliArgsException {
String[] args = {
"--python", "xxx.py",
"--pyModule", "xxx",
"--pyFiles", "/absolute/a.py,relative/b.py,relative/c.py",
"--pyRequirements", "d.txt#e_dir",
"--pyExecutable", "/usr/bin/python",
"--pyArchives", "g.zip,h.zip#data,h.zip#data2",
"userarg1", "userarg2"
};
CommandLine line = CliFrontendParser.parse(options, args, false);
PythonProgramOptions programOptions = (PythonProgramOptions) ProgramOptions.create(line);
Configuration config = new Configuration();
programOptions.applyToConfiguration(config);
assertEquals("/absolute/a.py,relative/b.py,relative/c.py", config.get(PythonOptions.PYTHON_FILES));
assertEquals("d.txt#e_dir", config.get(PYTHON_REQUIREMENTS));
assertEquals("g.zip,h.zip#data,h.zip#data2", config.get(PythonOptions.PYTHON_ARCHIVES));
assertEquals("/usr/bin/python", config.get(PYTHON_EXECUTABLE));
assertArrayEquals(
new String[] {"--python", "xxx.py", "--pyModule", "xxx", "userarg1", "userarg2"},
programOptions.getProgramArgs());
}
}
| apache-2.0 |
multi-os-engine/moe-core | moe.apple/moe.platform.ios/src/main/java/apple/homekit/HMCharacteristicMetadata.java | 6729 | /*
Copyright 2014-2016 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package apple.homekit;
import apple.NSObject;
import apple.foundation.NSArray;
import apple.foundation.NSMethodSignature;
import apple.foundation.NSNumber;
import apple.foundation.NSSet;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;
/**
* This class defines the metadata for a characteristic. Metadata provides
* further information about a characteristic’s value, which can be used
* for presentation purposes.
*/
@Generated
@Library("HomeKit")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class HMCharacteristicMetadata extends NSObject {
static {
NatJ.register();
}
@Generated
protected HMCharacteristicMetadata(Pointer peer) {
super(peer);
}
@Generated
@Selector("accessInstanceVariablesDirectly")
public static native boolean accessInstanceVariablesDirectly();
@Generated
@Owned
@Selector("alloc")
public static native HMCharacteristicMetadata alloc();
@Owned
@Generated
@Selector("allocWithZone:")
public static native HMCharacteristicMetadata allocWithZone(VoidPtr zone);
@Generated
@Selector("automaticallyNotifiesObserversForKey:")
public static native boolean automaticallyNotifiesObserversForKey(String key);
@Generated
@Selector("cancelPreviousPerformRequestsWithTarget:")
public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);
@Generated
@Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
@Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
@Mapped(ObjCObjectMapper.class) Object anArgument);
@Generated
@Selector("classFallbacksForKeyedArchiver")
public static native NSArray<String> classFallbacksForKeyedArchiver();
@Generated
@Selector("classForKeyedUnarchiver")
public static native Class classForKeyedUnarchiver();
@Generated
@Selector("debugDescription")
public static native String debugDescription_static();
@Generated
@Selector("description")
public static native String description_static();
@Generated
@Selector("hash")
@NUInt
public static native long hash_static();
@Generated
@Selector("instanceMethodForSelector:")
@FunctionPtr(name = "call_instanceMethodForSelector_ret")
public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);
@Generated
@Selector("instanceMethodSignatureForSelector:")
public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);
@Generated
@Selector("instancesRespondToSelector:")
public static native boolean instancesRespondToSelector(SEL aSelector);
@Generated
@Selector("isSubclassOfClass:")
public static native boolean isSubclassOfClass(Class aClass);
@Generated
@Selector("keyPathsForValuesAffectingValueForKey:")
public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);
@Generated
@Owned
@Selector("new")
public static native HMCharacteristicMetadata new_objc();
@Generated
@Selector("resolveClassMethod:")
public static native boolean resolveClassMethod(SEL sel);
@Generated
@Selector("resolveInstanceMethod:")
public static native boolean resolveInstanceMethod(SEL sel);
@Generated
@Selector("setVersion:")
public static native void setVersion_static(@NInt long aVersion);
@Generated
@Selector("superclass")
public static native Class superclass_static();
@Generated
@Selector("version")
@NInt
public static native long version_static();
/**
* The format of the value. Refer to HMCharacteristicMetadataFormat constants for supported units.
*/
@Generated
@Selector("format")
public native String format();
@Generated
@Selector("init")
public native HMCharacteristicMetadata init();
/**
* Manufacturer provided description for the characteristic to present to the user.
*/
@Generated
@Selector("manufacturerDescription")
public native String manufacturerDescription();
/**
* Max length value for the characteristic that indicates the maximum number of UTF-8 characters allowed if it has a format of "string".
*/
@Generated
@Selector("maxLength")
public native NSNumber maxLength();
/**
* The maximum value for the characteristic if it has a format of "int" or "float".
*/
@Generated
@Selector("maximumValue")
public native NSNumber maximumValue();
/**
* The minimum value for the characteristic if it has a format of "int" or "float".
*/
@Generated
@Selector("minimumValue")
public native NSNumber minimumValue();
/**
* Step value for the characteristic that indicates the minimum step value allowed if it has a format of "int" or "float".
*/
@Generated
@Selector("stepValue")
public native NSNumber stepValue();
/**
* The units of the value. Refer to HMCharacteristicMetadataUnits constants for supported units.
*/
@Generated
@Selector("units")
public native String units();
/**
* The subset of valid values supported by the characteristic when the format is unsigned integral type.
*/
@Generated
@Selector("validValues")
public native NSArray<? extends NSNumber> validValues();
}
| apache-2.0 |
linkedin/pinot | pinot-core/src/main/java/org/apache/pinot/core/plan/DictionaryBasedAggregationPlanNode.java | 2549 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pinot.core.plan;
import java.util.HashMap;
import java.util.Map;
import org.apache.pinot.core.indexsegment.IndexSegment;
import org.apache.pinot.core.operator.query.DictionaryBasedAggregationOperator;
import org.apache.pinot.core.query.aggregation.function.AggregationFunction;
import org.apache.pinot.core.query.request.context.ExpressionContext;
import org.apache.pinot.core.query.request.context.QueryContext;
import org.apache.pinot.core.segment.index.readers.Dictionary;
/**
* Dictionary based aggregation plan node.
*/
@SuppressWarnings("rawtypes")
public class DictionaryBasedAggregationPlanNode implements PlanNode {
private final IndexSegment _indexSegment;
private final AggregationFunction[] _aggregationFunctions;
private final Map<String, Dictionary> _dictionaryMap;
/**
* Constructor for the class.
*
* @param indexSegment Segment to process
* @param queryContext Query context
*/
public DictionaryBasedAggregationPlanNode(IndexSegment indexSegment, QueryContext queryContext) {
_indexSegment = indexSegment;
_aggregationFunctions = queryContext.getAggregationFunctions();
assert _aggregationFunctions != null;
_dictionaryMap = new HashMap<>();
for (AggregationFunction aggregationFunction : _aggregationFunctions) {
String column = ((ExpressionContext) aggregationFunction.getInputExpressions().get(0)).getIdentifier();
_dictionaryMap.computeIfAbsent(column, k -> _indexSegment.getDataSource(k).getDictionary());
}
}
@Override
public DictionaryBasedAggregationOperator run() {
return new DictionaryBasedAggregationOperator(_aggregationFunctions, _dictionaryMap,
_indexSegment.getSegmentMetadata().getTotalDocs());
}
}
| apache-2.0 |
minsons/wsyz | zrlog/src/test/java/com/fzb/test/TestController.java | 55 | package com.fzb.test;
public class TestController {
}
| apache-2.0 |
SimY4/xpath-to-xml | xpath-to-json-jackson/src/main/java/module-info.java | 256 | module com.github.simych.xpath.jackson {
requires transitive com.github.simych.xpath.core;
requires com.fasterxml.jackson.databind;
provides com.github.simy4.xpath.spi.NavigatorSpi with com.github.simy4.xpath.jackson.spi.JacksonNavigatorSpi;
} | apache-2.0 |
bigbugbb/iTracker | app/src/main/java/com/itracker/android/service/download/DownloadInterruptedException.java | 1225 | package com.itracker.android.service.download;
import java.io.IOException;
/**
* Thrown when a download is interrupted.
*/
class DownloadInterruptedException extends IOException {
private String mReason;
/**
* Constructs a new {@code FileDownloadInterruptedException} with its stack trace
* filled in.
*/
public DownloadInterruptedException() {
}
/**
* Constructs a new {@code FileDownloadInterruptedException} with its stack trace and
* detail message filled in.
*
* @param detailMessage
* the detail message for this exception.
*/
public DownloadInterruptedException(String detailMessage) {
super(detailMessage);
}
/**
* Constructs a new {@code FileDownloadInterruptedException} with its stack trace and
* detail message filled in.
*
* @param detailMessage
* the detail message for this exception.
* @param reason
* the reason for this interruption
*/
public DownloadInterruptedException(String detailMessage, String reason) {
super(detailMessage);
mReason = reason;
}
public String getReason() {
return mReason;
}
} | apache-2.0 |
SourceStudyNotes/Tomcat8 | src/main/java/org/apache/catalina/tribes/group/interceptors/StaticMembershipInterceptor.java | 5174 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.catalina.tribes.group.interceptors;
import java.util.ArrayList;
import org.apache.catalina.tribes.Channel;
import org.apache.catalina.tribes.ChannelException;
import org.apache.catalina.tribes.ChannelInterceptor;
import org.apache.catalina.tribes.Member;
import org.apache.catalina.tribes.group.AbsoluteOrder;
import org.apache.catalina.tribes.group.ChannelInterceptorBase;
import org.apache.catalina.tribes.util.StringManager;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
public class StaticMembershipInterceptor extends ChannelInterceptorBase {
private static final Log log = LogFactory.getLog(StaticMembershipInterceptor.class);
protected static final StringManager sm =
StringManager.getManager(StaticMembershipInterceptor.class.getPackage().getName());
protected final ArrayList<Member> members = new ArrayList<>();
protected Member localMember = null;
public StaticMembershipInterceptor() {
super();
}
public void addStaticMember(Member member) {
synchronized (members) {
if (!members.contains(member)) members.add(member);
}
}
public void removeStaticMember(Member member) {
synchronized (members) {
if (members.contains(member)) members.remove(member);
}
}
public void setLocalMember(Member member) {
this.localMember = member;
}
/**
* has members
*/
@Override
public boolean hasMembers() {
return super.hasMembers() || (members.size()>0);
}
/**
* Get all current cluster members
* @return all members or empty array
*/
@Override
public Member[] getMembers() {
if ( members.size() == 0 ) return super.getMembers();
else {
synchronized (members) {
Member[] others = super.getMembers();
Member[] result = new Member[members.size() + others.length];
for (int i = 0; i < others.length; i++) result[i] = others[i];
for (int i = 0; i < members.size(); i++) result[i + others.length] = members.get(i);
AbsoluteOrder.absoluteOrder(result);
return result;
}//sync
}//end if
}
/**
*
* @param mbr Member
* @return Member
*/
@Override
public Member getMember(Member mbr) {
if ( members.contains(mbr) ) return members.get(members.indexOf(mbr));
else return super.getMember(mbr);
}
/**
* Return the member that represents this node.
*
* @return Member
*/
@Override
public Member getLocalMember(boolean incAlive) {
if (this.localMember != null ) return localMember;
else return super.getLocalMember(incAlive);
}
/**
* Send notifications upwards
* @param svc int
* @throws ChannelException
*/
@Override
public void start(int svc) throws ChannelException {
if ( (Channel.SND_RX_SEQ&svc)==Channel.SND_RX_SEQ ) super.start(Channel.SND_RX_SEQ);
if ( (Channel.SND_TX_SEQ&svc)==Channel.SND_TX_SEQ ) super.start(Channel.SND_TX_SEQ);
final Member[] mbrs = members.toArray(new Member[members.size()]);
final ChannelInterceptorBase base = this;
Thread t = new Thread() {
@Override
public void run() {
for (int i=0; i<mbrs.length; i++ ) {
base.memberAdded(mbrs[i]);
}
}
};
t.start();
super.start(svc & (~Channel.SND_RX_SEQ) & (~Channel.SND_TX_SEQ));
// check required interceptors
TcpFailureDetector failureDetector = null;
TcpPingInterceptor pingInterceptor = null;
ChannelInterceptor prev = getPrevious();
while (prev != null) {
if (prev instanceof TcpFailureDetector ) failureDetector = (TcpFailureDetector) prev;
if (prev instanceof TcpPingInterceptor) pingInterceptor = (TcpPingInterceptor) prev;
prev = prev.getPrevious();
}
if (failureDetector == null) {
log.warn(sm.getString("staticMembershipInterceptor.no.failureDetector"));
}
if (pingInterceptor == null) {
log.warn(sm.getString("staticMembershipInterceptor.no.pingInterceptor"));
}
}
} | apache-2.0 |
weiwenqiang/GitHub | expert/jackson-core/src/main/java/com/fasterxml/jackson/core/JsonParseException.java | 3550 | /* Jackson JSON-processor.
*
* Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi
*/
package com.fasterxml.jackson.core;
import com.fasterxml.jackson.core.util.RequestPayload;
/**
* Exception type for parsing problems, used when non-well-formed content
* (content that does not conform to JSON syntax as per specification)
* is encountered.
*/
public class JsonParseException extends JsonProcessingException {
private static final long serialVersionUID = 3L;
protected transient JsonParser _processor;
/**
* Optional payload that can be assigned to pass along for error reporting
* or handling purposes. Core streaming parser implementations DO NOT
* initialize this; it is up to using applications and frameworks to
* populate it.
*
* @since 2.8
*/
protected RequestPayload _requestPayload;
/**
* Constructor that uses current parsing location as location, and
* sets processor (accessible via {@link #getProcessor()}) to
* specified parser.
*/
public JsonParseException(JsonParser p, String msg) {
super(msg, (p == null) ? null : p.getCurrentLocation());
_processor = p;
}
public JsonParseException(JsonParser p, String msg, Throwable root) {
super(msg, (p == null) ? null : p.getCurrentLocation(), root);
_processor = p;
}
public JsonParseException(JsonParser p, String msg, JsonLocation loc) {
super(msg, loc);
_processor = p;
}
public JsonParseException(JsonParser p, String msg, JsonLocation loc, Throwable root) {
super(msg, loc, root);
_processor = p;
}
/**
* Fluent method that may be used to assign originating {@link JsonParser},
* to be accessed using {@link #getProcessor()}.
*<p>
* NOTE: `this` instance is modified and no new instance is constructed.
*/
public JsonParseException withParser(JsonParser p) {
_processor = p;
return this;
}
/**
* Fluent method that may be used to assign payload to this exception,
* to let recipient access it for diagnostics purposes.
*<p>
* NOTE: `this` instance is modified and no new instance is constructed.
*/
public JsonParseException withRequestPayload(RequestPayload p) {
_requestPayload = p;
return this;
}
@Override
public JsonParser getProcessor() {
return _processor;
}
/**
* Method that may be called to find payload that was being parsed, if
* one was specified for parser that threw this Exception.
*
* @return request body, if payload was specified; `null` otherwise
*/
public RequestPayload getRequestPayload() {
return _requestPayload;
}
/**
* The method returns the String representation of the request payload if
* one was specified for parser that threw this Exception.
*
* @return request body as String, if payload was specified; `null` otherwise
*/
public String getRequestPayloadAsString() {
return (_requestPayload != null) ? _requestPayload.toString() : null;
}
/**
* Overriding the getMessage() to include the request body
*/
@Override
public String getMessage() {
String msg = super.getMessage();
if (_requestPayload != null) {
msg = new StringBuilder("\nRequest payload: ")
.append(_requestPayload.toString())
.toString();
}
return msg;
}
}
| apache-2.0 |
tianfengjingjing/YOFC_Stage1_RightOracle | src/com/yofc/odn/production/action/SegmentnumAction.java | 1406 | package com.yofc.odn.production.action;
import javax.annotation.Resource;
import com.opensymphony.xwork2.ActionSupport;
import com.yofc.odn.common.model.Staff;
import com.yofc.odn.production.model.Segmentnum;
import com.yofc.odn.production.service.SegmentnumService;
public class SegmentnumAction extends ActionSupport {
private SegmentnumService segmentnumService ;
private int segId;
private int segmentNumId;
public int getSegmentNumId() {
return segmentNumId;
}
public void setSegmentNumId(int segmentNumId) {
this.segmentNumId = segmentNumId;
}
private boolean flag = false; //
@Resource(name = "productionSegmentService")
public void setSegmentnumService(SegmentnumService segmentnumService) {
this.segmentnumService = segmentnumService;
}
public void setSegId(int segId) {
this.segId = segId;
}
public boolean getFlag(){
return this.flag;
}
public String execute(){
this.flag = this.segmentnumService.validInitStatue(segId);
return SUCCESS;
}
public String makeSegmentDefault(){
Segmentnum segmentnum=this.segmentnumService.findOneBySegmentNumId(segmentNumId);
if(segmentnum!=null){
Staff staff=new Staff();
staff.setStaffNum("");
segmentnum.setGetStaffNum(staff);
segmentnum.setStatus(0);
this.segmentnumService.updateSegment(segmentnum);
return SUCCESS;
}
return ERROR;
}
}
| apache-2.0 |
TranscendComputing/TopStackElasticCache | src/com/transcend/elasticache/worker/ModifyCacheClusterActionWorker.java | 4676 | package com.transcend.elasticache.worker;
import java.util.List;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.springframework.transaction.annotation.Transactional;
import com.amazonaws.services.elasticache.model.common.EcacheUtilV2;
import com.msi.tough.core.Appctx;
import com.msi.tough.model.AccountBean;
import com.msi.tough.model.elasticache.CacheClusterBean;
import com.msi.tough.model.elasticache.CacheNodeBean;
import com.msi.tough.model.elasticache.CacheParameterGroupBean;
import com.msi.tough.query.ServiceRequestContext;
import com.msi.tough.utils.AccountUtil;
import com.msi.tough.utils.EcacheUtil;
import com.msi.tough.utils.ElasticacheFaults;
import com.msi.tough.workflow.core.AbstractWorker;
import com.transcend.elasticache.message.ModifyCacheClusterActionMessage.ModifyCacheClusterActionRequestMessage;
import com.transcend.elasticache.message.ModifyCacheClusterActionMessage.ModifyCacheClusterActionResultMessage;
public class ModifyCacheClusterActionWorker extends
AbstractWorker<ModifyCacheClusterActionRequestMessage, ModifyCacheClusterActionResultMessage> {
private final static Logger logger = Appctx
.getLogger(ModifyCacheClusterActionWorker.class
.getName());
/**
* We need a local copy of this doWork to provide the transactional
* annotation. Transaction management is handled by the annotation, which
* can only be on a concrete class.
* @param req
* @return
* @throws Exception
*/
@Transactional
public ModifyCacheClusterActionResultMessage doWork(
ModifyCacheClusterActionRequestMessage req) throws Exception {
logger.debug("Performing work for ModifyCacheClusterAction.");
return super.doWork(req, getSession());
}
@Override
protected ModifyCacheClusterActionResultMessage doWork0(ModifyCacheClusterActionRequestMessage request,
ServiceRequestContext context) throws Exception {
logger.debug("into process0 - Modify CacheClusterAction");
final AccountBean account = context.getAccountBean();
final Session session = getSession();
ModifyCacheClusterActionResultMessage.Builder result = ModifyCacheClusterActionResultMessage.newBuilder();
final String clusterId = request.getCacheClusterId();
logger.debug("deleteCacheClusters");
logger.debug("ClusterID = " + clusterId);
// Validate cache cluster exists
final CacheClusterBean cc = EcacheUtil.getCacheClusterBean(session,
account.getId(), clusterId);
if (cc == null) {
throw ElasticacheFaults.CacheClusterNotFound();
}
// Validate State
if (!cc.getCacheClusterStatus().equals("available")) {
throw ElasticacheFaults.InvalidCacheClusterState();
}
boolean updateStatus = false;
if (request.getAutoMinorVersionUpgrade() != false) {
cc.setAutoMinorVersionUpgrade(request.getAutoMinorVersionUpgrade());
}
if (request.getEngineVersion() != null
&& !request.getEngineVersion().equals(cc.getEngineVersion())) {
cc.setNewEngineVersion(request.getEngineVersion());
updateStatus = true;
}
if (request.getNumCacheNodes() != 0
&& request.getNumCacheNodes() != cc.getNodeCount()) {
if (request.getNumCacheNodes() < cc.getNodeCount()) {
if (request.getCacheNodeIdsToRemoveList() != null) {
final List<String> remove = request
.getCacheNodeIdsToRemoveList();
final List<CacheNodeBean> cnbs = EcacheUtil
.selectCacheNodeBean(session, cc.getId());
int i = 0;
int noDel = 0;
for (final CacheNodeBean cnb : cnbs) {
i++;
for (final String rn : remove) {
if (i == Integer.parseInt(rn)) {
cnb.setNodeStatus("removing");
session.save(cnb);
noDel++;
}
}
}
}
}
cc.setNewNodeCount(request.getNumCacheNodes());
updateStatus = true;
}
if (updateStatus) {
cc.setCacheClusterStatus("modifying");
}
if (request.getCacheParameterGroupName() != null && !"".equals(request.getCacheParameterGroupName())) {
final CacheParameterGroupBean parameterGroup = EcacheUtil
.getCacheParameterGroupBean(session, account.getId(),
request.getCacheParameterGroupName());
if (parameterGroup == null && !"".equals(parameterGroup)) {
throw ElasticacheFaults.CacheParameterGroupNotFound();
}
if (parameterGroup.getId() != cc.getParameterGroupId()) {
cc.setParameterGroupId((long) parameterGroup.getId());
updateStatus = true;
}
}
session.save(cc);
if (request.getApplyImmediately()) {
EcacheUtil.rebootCluster(session, cc,
AccountUtil.toAccount(account));
}
result.setCacheCluster(EcacheUtilV2.toAwsCacheCluster(session, cc));
return result.buildPartial();
}
}
| apache-2.0 |