text
stringlengths 7
1.01M
|
|---|
package com.lavasoft;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceFeature;
import javax.xml.ws.Service;
/**
* <b>A web service which performs GetIpAddress Lookups.</b>
*
* This class was generated by Apache CXF 3.2.5
* 2018-08-02T14:26:55.380+02:00
* Generated source version: 3.2.5
*
*/
@WebServiceClient(name = "GeoIPService",
wsdlLocation = "file:src/main/resources/geoipservice.wsdl",
targetNamespace = "http://lavasoft.com/")
public class GeoIPService extends Service {
public final static URL WSDL_LOCATION;
public final static QName SERVICE = new QName("http://lavasoft.com/", "GeoIPService");
public final static QName GeoIPServiceSoap = new QName("http://lavasoft.com/", "GeoIPServiceSoap");
public final static QName GeoIPServiceSoap12 = new QName("http://lavasoft.com/", "GeoIPServiceSoap12");
public final static QName GeoIPServiceHttpGet = new QName("http://lavasoft.com/", "GeoIPServiceHttpGet");
public final static QName GeoIPServiceHttpPost = new QName("http://lavasoft.com/", "GeoIPServiceHttpPost");
static {
URL url = null;
try {
url = new URL("file:src/main/resources/geoipservice.wsdl");
} catch (MalformedURLException e) {
java.util.logging.Logger.getLogger(GeoIPService.class.getName())
.log(java.util.logging.Level.INFO,
"Can not initialize the default wsdl from {0}", "file:src/main/resources/geoipservice.wsdl");
}
WSDL_LOCATION = url;
}
public GeoIPService(URL wsdlLocation) {
super(wsdlLocation, SERVICE);
}
public GeoIPService(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
public GeoIPService() {
super(WSDL_LOCATION, SERVICE);
}
public GeoIPService(WebServiceFeature ... features) {
super(WSDL_LOCATION, SERVICE, features);
}
public GeoIPService(URL wsdlLocation, WebServiceFeature ... features) {
super(wsdlLocation, SERVICE, features);
}
public GeoIPService(URL wsdlLocation, QName serviceName, WebServiceFeature ... features) {
super(wsdlLocation, serviceName, features);
}
/**
*
* @return
* returns GeoIPServiceSoap
*/
@WebEndpoint(name = "GeoIPServiceSoap")
public GeoIPServiceSoap getGeoIPServiceSoap() {
return super.getPort(GeoIPServiceSoap, GeoIPServiceSoap.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns GeoIPServiceSoap
*/
@WebEndpoint(name = "GeoIPServiceSoap")
public GeoIPServiceSoap getGeoIPServiceSoap(WebServiceFeature... features) {
return super.getPort(GeoIPServiceSoap, GeoIPServiceSoap.class, features);
}
/**
*
* @return
* returns GeoIPServiceSoap
*/
@WebEndpoint(name = "GeoIPServiceSoap12")
public GeoIPServiceSoap getGeoIPServiceSoap12() {
return super.getPort(GeoIPServiceSoap12, GeoIPServiceSoap.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns GeoIPServiceSoap
*/
@WebEndpoint(name = "GeoIPServiceSoap12")
public GeoIPServiceSoap getGeoIPServiceSoap12(WebServiceFeature... features) {
return super.getPort(GeoIPServiceSoap12, GeoIPServiceSoap.class, features);
}
/**
*
* @return
* returns GeoIPServiceHttpGet
*/
@WebEndpoint(name = "GeoIPServiceHttpGet")
public GeoIPServiceHttpGet getGeoIPServiceHttpGet() {
return super.getPort(GeoIPServiceHttpGet, GeoIPServiceHttpGet.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns GeoIPServiceHttpGet
*/
@WebEndpoint(name = "GeoIPServiceHttpGet")
public GeoIPServiceHttpGet getGeoIPServiceHttpGet(WebServiceFeature... features) {
return super.getPort(GeoIPServiceHttpGet, GeoIPServiceHttpGet.class, features);
}
/**
*
* @return
* returns GeoIPServiceHttpPost
*/
@WebEndpoint(name = "GeoIPServiceHttpPost")
public GeoIPServiceHttpPost getGeoIPServiceHttpPost() {
return super.getPort(GeoIPServiceHttpPost, GeoIPServiceHttpPost.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns GeoIPServiceHttpPost
*/
@WebEndpoint(name = "GeoIPServiceHttpPost")
public GeoIPServiceHttpPost getGeoIPServiceHttpPost(WebServiceFeature... features) {
return super.getPort(GeoIPServiceHttpPost, GeoIPServiceHttpPost.class, features);
}
}
|
package io.openvidu.recording.java;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App
{
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
}
}
|
package com.github.mongobeej;
import com.github.mongobeej.changeset.ChangeEntry;
import com.github.mongobeej.resources.EnvironmentMock;
import com.github.mongobeej.test.changelogs.AnotherMongobeeTestResource;
import com.github.mongobeej.test.profiles.def.UnProfiledChangeLog;
import com.github.mongobeej.test.profiles.dev.ProfiledDevChangeLog;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import static com.github.mongobeej.utils.TestQueries.changeQuery;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class MongobeeProfileTest extends MongobeeBaseTest {
private static final int CHANGELOG_COUNT = 10;
@Test
public void shouldRunDevProfileAndNonAnnotated() throws Exception {
// given
mongobee.setSpringEnvironment(new EnvironmentMock("dev", "test"));
mongobee.setChangeLogsScanPackage(ProfiledDevChangeLog.class.getPackage().getName());
when(changeEntryDao.isNewChange(any(ChangeEntry.class))).thenReturn(true);
// when
mongobee.execute();
// then
long change1 = mongoDatabase.getCollection(CHANGELOG_COLLECTION_NAME)
.countDocuments(changeQuery("Pdev1"));
assertEquals(1, change1); // no-@Profile should not match
long change2 = mongoDatabase.getCollection(CHANGELOG_COLLECTION_NAME)
.countDocuments(changeQuery("Pdev4"));
assertEquals(1, change2); // @Profile("dev") should not match
long change3 = mongoDatabase.getCollection(CHANGELOG_COLLECTION_NAME)
.countDocuments(changeQuery("Pdev3"));
assertEquals(0, change3); // @Profile("default") should not match
}
@Test
public void shouldRunUnprofiledChangeLog() throws Exception {
// given
mongobee.setSpringEnvironment(new EnvironmentMock("test"));
mongobee.setChangeLogsScanPackage(UnProfiledChangeLog.class.getPackage().getName());
when(changeEntryDao.isNewChange(any(ChangeEntry.class))).thenReturn(true);
// when
mongobee.execute();
// then
long change1 = mongoDatabase.getCollection(CHANGELOG_COLLECTION_NAME)
.countDocuments(changeQuery("Pdev1"));
assertEquals(1, change1);
long change2 = mongoDatabase.getCollection(CHANGELOG_COLLECTION_NAME)
.countDocuments(changeQuery("Pdev2"));
assertEquals(1, change2);
long change3 = mongoDatabase.getCollection(CHANGELOG_COLLECTION_NAME)
.countDocuments(changeQuery("Pdev3"));
assertEquals(1, change3); // @Profile("dev") should not match
long change4 = mongoDatabase.getCollection(CHANGELOG_COLLECTION_NAME)
.countDocuments(changeQuery("Pdev4"));
assertEquals(0, change4); // @Profile("pro") should not match
long change5 = mongoDatabase.getCollection(CHANGELOG_COLLECTION_NAME)
.countDocuments(changeQuery("Pdev5"));
assertEquals(1, change5); // @Profile("!pro") should match
}
@Test
public void shouldNotRunAnyChangeSet() throws Exception {
// given
mongobee.setSpringEnvironment(new EnvironmentMock("foobar"));
mongobee.setChangeLogsScanPackage(ProfiledDevChangeLog.class.getPackage().getName());
when(changeEntryDao.isNewChange(any(ChangeEntry.class))).thenReturn(true);
// when
mongobee.execute();
// then
long changes = mongoDatabase.getCollection(CHANGELOG_COLLECTION_NAME).countDocuments();
assertEquals(0, changes);
}
@Test
public void shouldRunChangeSetsWhenNoEnv() throws Exception {
// given
mongobee.setSpringEnvironment(null);
mongobee.setChangeLogsScanPackage(AnotherMongobeeTestResource.class.getPackage().getName());
when(changeEntryDao.isNewChange(any(ChangeEntry.class))).thenReturn(true);
// when
mongobee.execute();
// then
long changes = mongoDatabase.getCollection(CHANGELOG_COLLECTION_NAME).countDocuments();
assertEquals(CHANGELOG_COUNT, changes);
}
@Test
public void shouldRunChangeSetsWhenEmptyEnv() throws Exception {
// given
mongobee.setSpringEnvironment(new EnvironmentMock());
mongobee.setChangeLogsScanPackage(AnotherMongobeeTestResource.class.getPackage().getName());
when(changeEntryDao.isNewChange(any(ChangeEntry.class))).thenReturn(true);
// when
mongobee.execute();
// then
long changes = mongoDatabase.getCollection(CHANGELOG_COLLECTION_NAME).countDocuments();
assertEquals(CHANGELOG_COUNT, changes);
}
@Test
public void shouldRunAllChangeSets() throws Exception {
// given
mongobee.setSpringEnvironment(new EnvironmentMock("dev"));
mongobee.setChangeLogsScanPackage(AnotherMongobeeTestResource.class.getPackage().getName());
when(changeEntryDao.isNewChange(any(ChangeEntry.class))).thenReturn(true);
// when
mongobee.execute();
// then
long changes = mongoDatabase.getCollection(CHANGELOG_COLLECTION_NAME).countDocuments();
assertEquals(CHANGELOG_COUNT, changes);
}
@After
public void cleanUp() {
mongobee.setMongoTemplate(null);
}
}
|
package android.support.design.widget;
import android.view.animation.Animation;
import android.view.animation.Transformation;
abstract class C extends Animation
{
private float a;
private float b;
private C(A paramA)
{
}
protected abstract float a();
protected void applyTransformation(float paramFloat, Transformation paramTransformation)
{
M localM = this.c.a;
localM.a(this.a + paramFloat * this.b, localM.a);
}
public void reset()
{
super.reset();
this.a = this.c.a.b;
this.b = (a() - this.a);
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: android.support.design.widget.C
* JD-Core Version: 0.6.0
*/
|
/**
* PhonebookGroupResource.java
* in package: * org.net9.minipie.server.api
* by Mini-Pie Project
*/
package org.net9.minipie.server.api;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import org.net9.minipie.server.data.field.InfoField;
import org.net9.minipie.server.exception.DataFormatException;
import org.net9.minipie.server.exception.InvalidRequestException;
import org.net9.minipie.server.logic.Handler;
import org.net9.minipie.server.logic.operation.group.QuitGroup;
import org.net9.minipie.server.logic.operation.group.admin.EditGroupInfo;
/**
* @author LeeThree
*
*/
public class PhonebookGroupResource extends BaseResource {
private long groupId;
/**
* Constructor
*/
public PhonebookGroupResource() {
}
/**
* @param groupId
* the groupId to set
*/
public void setGroupId(long groupId) {
this.groupId = groupId;
}
@PUT
public Response put(@FormParam("field") String field,
@FormParam("value") String value) {
if (field != null && !field.isEmpty() && value != null
&& !value.isEmpty()) {
try {
new Handler<Void>(new EditGroupInfo(getUserId(), groupId,
value, InfoField.value(field))).execute();
} catch (DataFormatException e) {
throw new InvalidRequestException(e);
}
return Response.ok().build();
}
throw new InvalidRequestException(
"No valid parameter provided: field and value expected.");
}
@DELETE
public Response delete() {
new Handler<Void>(new QuitGroup(getUserId(), groupId)).execute();
return Response.ok().build();
}
@Path("user")
public PhonebookGroupUserResource getGroupUsers() {
PhonebookGroupUserResource user = getSubResource(PhonebookGroupUserResource.class);
user.setGroupId(groupId);
return user;
}
@Path("contact")
public PhonebookGroupContactResource getGroupContacts() {
PhonebookGroupContactResource contact = getSubResource(PhonebookGroupContactResource.class);
contact.setGroupId(groupId);
return contact;
}
}
|
/*
* Copyright 2015-2017 Real Logic 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
*
* 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 uk.co.real_logic.artio.protocol;
import io.aeron.logbuffer.ControlledFragmentHandler.Action;
import org.agrona.DirectBuffer;
import uk.co.real_logic.artio.messages.DisconnectReason;
import uk.co.real_logic.artio.messages.MessageStatus;
public interface ProtocolHandler
{
Action onMessage(
DirectBuffer buffer,
int offset,
int length,
int libraryId,
long connectionId,
long sessionId,
int sequenceIndex,
int messageType,
long timestamp,
MessageStatus status,
int sequenceNumber,
long position);
Action onDisconnect(int libraryId, long connectionId, DisconnectReason reason);
}
|
/*******************************************************************************
* Copyright (c) 2015 OpenDSE
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
package net.sf.opendse.optimization;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import net.sf.opendse.model.Specification;
import org.opt4j.core.DoubleValue;
import org.opt4j.core.IntegerValue;
import org.opt4j.core.Objective;
import org.opt4j.core.Objectives;
import org.opt4j.core.problem.Evaluator;
import com.google.inject.Inject;
import com.google.inject.Provider;
public class DesignSpaceExplorationEvaluator implements Evaluator<ImplementationWrapper> {
protected final List<ImplementationEvaluator> evaluators;
protected final Provider<Objectives> objectivesProvider;
@Inject
public DesignSpaceExplorationEvaluator(Set<ImplementationEvaluator> evaluators, Provider<Objectives> objectivesProvider) {
super();
this.evaluators = new ArrayList<ImplementationEvaluator>(evaluators);
this.objectivesProvider = objectivesProvider;
Collections.sort(this.evaluators, new Comparator<ImplementationEvaluator>() {
@Override
public int compare(ImplementationEvaluator o1, ImplementationEvaluator o2) {
Integer i1 = o1.getPriority();
Integer i2 = o2.getPriority();
return i1.compareTo(i2);
}
});
}
@Override
public Objectives evaluate(ImplementationWrapper wrapper) {
Objectives objectives = objectivesProvider.get();
for (ImplementationEvaluator evaluator : evaluators) {
Specification impl = evaluator.evaluate(wrapper.getImplementation(), objectives);
if (impl != null) {
wrapper.setImplementation(impl);
}
for (Objective objective : objectives.getKeys()) {
String attribute = objective.getName() + ":OBJECTIVE";
Object value = objectives.get(objective);
if (value instanceof DoubleValue) {
value = ((DoubleValue) value).getValue();
} else if (value instanceof IntegerValue) {
value = ((IntegerValue) value).getValue();
} else {
value = value.toString();
}
Specification implementation = wrapper.getImplementation();
if (implementation != null) {
implementation.setAttribute(attribute, value);
}
}
}
return objectives;
}
}
|
/*
* LUSID API
* # Introduction This page documents the [LUSID APIs](https://www.lusid.com/api/swagger), which allows authorised clients to query and update their data within the LUSID platform. SDKs to interact with the LUSID APIs are available in the following languages : * [C#](https://github.com/finbourne/lusid-sdk-csharp) * [Java](https://github.com/finbourne/lusid-sdk-java) * [JavaScript](https://github.com/finbourne/lusid-sdk-js) * [Python](https://github.com/finbourne/lusid-sdk-python) # Data Model The LUSID API has a relatively lightweight but extremely powerful data model. One of the goals of LUSID was not to enforce on clients a single rigid data model but rather to provide a flexible foundation onto which clients can map their own data models. The core entities in LUSID provide a minimal structure and set of relationships, and the data model can be extended using Properties. The LUSID data model is exposed through the LUSID APIs. The APIs provide access to both business objects and the meta data used to configure the systems behaviours. The key business entities are: - * **Portfolios** A portfolio is a container for transactions and holdings (a **Transaction Portfolio**) or constituents (a **Reference Portfolio**). * **Derived Portfolios**. Derived Portfolios allow Portfolios to be created based on other Portfolios, by overriding or adding specific items. * **Holdings** A Holding is a quantity of an Instrument or a balance of cash within a Portfolio. Holdings can only be adjusted via Transactions. * **Transactions** A Transaction is an economic event that occurs in a Portfolio, causing its holdings to change. * **Corporate Actions** A corporate action is a market event which occurs to an Instrument and thus applies to all portfolios which holding the instrument. Examples are stock splits or mergers. * **Constituents** A constituent is a record in a Reference Portfolio containing an Instrument and an associated weight. * **Instruments** An instrument represents a currency, tradable instrument or OTC contract that is attached to a transaction and a holding. * **Properties** All major entities allow additional user defined properties to be associated with them. For example, a Portfolio manager may be associated with a portfolio. Meta data includes: - * **Transaction Types** Transactions are booked with a specific transaction type. The types are client defined and are used to map the Transaction to a series of movements which update the portfolio holdings. * **Properties Types** Types of user defined properties used within the system. ## Scope All data in LUSID is segregated at the client level. Entities in LUSID are identifiable by a unique code. Every entity lives within a logical data partition known as a Scope. Scope is an identity namespace allowing two entities with the same unique code to co-exist within individual address spaces. For example, prices for equities from different vendors may be uploaded into different scopes such as `client/vendor1` and `client/vendor2`. A portfolio may then be valued using either of the price sources by referencing the appropriate scope. LUSID Clients cannot access scopes of other clients. ## Instruments LUSID has its own built-in instrument master which you can use to master your own instrument universe. Every instrument must be created with one or more unique market identifiers, such as [FIGI](https://openfigi.com/). For any non-listed instruments (eg OTCs), you can upload an instrument against a custom ID of your choosing. In addition, LUSID will allocate each instrument a unique 'LUSID instrument identifier'. The LUSID instrument identifier is what is used when uploading transactions, holdings, prices, etc. The API exposes an `instrument/lookup` endpoint which can be used to lookup these LUSID identifiers using their market identifiers. Cash can be referenced using the ISO currency code prefixed with \"`CCY_`\" e.g. `CCY_GBP` ## Instrument Data Instrument data can be uploaded to the system using the [Instrument Properties](#tag/InstrumentProperties) endpoint. | Field|Type|Description | | ---|---|--- | | Key|propertykey|The key of the property. This takes the format {domain}/{scope}/{code} e.g. 'Instrument/system/Name' or 'Transaction/strategy/quantsignal'. | | Value|string|The value of the property. | | EffectiveFrom|datetimeoffset|The effective datetime from which the property is valid. | ## Transaction Portfolios Portfolios are the top-level entity containers within LUSID, containing transactions, corporate actions and holdings. The transactions build up the portfolio holdings on which valuations, analytics profit & loss and risk can be calculated. Properties can be associated with Portfolios to add in additional data. Portfolio properties can be changed over time, for example to allow a Portfolio Manager to be linked with a Portfolio. Additionally, portfolios can be securitised and held by other portfolios, allowing LUSID to perform \"drill-through\" into underlying fund holdings ### Derived Portfolios LUSID also allows for a portfolio to be composed of another portfolio via derived portfolios. A derived portfolio can contain its own transactions and also inherits any transactions from its parent portfolio. Any changes made to the parent portfolio are automatically reflected in derived portfolio. Derived portfolios in conjunction with scopes are a powerful construct. For example, to do pre-trade what-if analysis, a derived portfolio could be created a new namespace linked to the underlying live (parent) portfolio. Analysis can then be undertaken on the derived portfolio without affecting the live portfolio. ### Transactions A transaction represents an economic activity against a Portfolio. Transactions are processed according to a configuration. This will tell the LUSID engine how to interpret the transaction and correctly update the holdings. LUSID comes with a set of transaction types you can use out of the box, or you can configure your own set(s) of transactions. For more details see the [LUSID Getting Started Guide for transaction configuration.](https://support.lusid.com/configuring-transaction-types) | Field|Type|Description | | ---|---|--- | | TransactionId|string|The unique identifier for the transaction. | | Type|string|The type of the transaction e.g. 'Buy', 'Sell'. The transaction type should have been pre-configured via the System Configuration API endpoint. If it hasn't been pre-configured the transaction will still be updated or inserted however you will be unable to generate the resultant holdings for the portfolio that contains this transaction as LUSID does not know how to process it. | | InstrumentIdentifiers|map|A set of instrument identifiers to use to resolve the transaction to a unique instrument. | | TransactionDate|dateorcutlabel|The date of the transaction. | | SettlementDate|dateorcutlabel|The settlement date of the transaction. | | Units|decimal|The number of units transacted in the associated instrument. | | TransactionPrice|transactionprice|The price for each unit of the transacted instrument in the transaction currency. | | TotalConsideration|currencyandamount|The total value of the transaction in the settlement currency. | | ExchangeRate|decimal|The exchange rate between the transaction and settlement currency. For example if the transaction currency is in USD and the settlement currency is in GBP this this the USD/GBP rate. | | TransactionCurrency|currency|The transaction currency. | | Properties|map|Set of unique transaction properties and associated values to store with the transaction. Each property must be from the 'Transaction' domain. | | CounterpartyId|string|The identifier for the counterparty of the transaction. | | Source|string|The source of the transaction. This is used to look up the appropriate transaction group set in the transaction type configuration. | From these fields, the following values can be calculated * **Transaction value in Transaction currency**: TotalConsideration / ExchangeRate * **Transaction value in Portfolio currency**: Transaction value in Transaction currency * TradeToPortfolioRate #### Example Transactions ##### A Common Purchase Example Three example transactions are shown in the table below. They represent a purchase of USD denominated IBM shares within a Sterling denominated portfolio. * The first two transactions are for separate buy and fx trades * Buying 500 IBM shares for $71,480.00 * A spot foreign exchange conversion to fund the IBM purchase. (Buy $71,480.00 for £54,846.60) * The third transaction is an alternate version of the above trades. Buying 500 IBM shares and settling directly in Sterling. | Column | Buy Trade | Fx Trade | Buy Trade with foreign Settlement | | ----- | ----- | ----- | ----- | | TransactionId | FBN00001 | FBN00002 | FBN00003 | | Type | Buy | FxBuy | Buy | | InstrumentIdentifiers | { \"figi\", \"BBG000BLNNH6\" } | { \"CCY\", \"CCY_USD\" } | { \"figi\", \"BBG000BLNNH6\" } | | TransactionDate | 2018-08-02 | 2018-08-02 | 2018-08-02 | | SettlementDate | 2018-08-06 | 2018-08-06 | 2018-08-06 | | Units | 500 | 71480 | 500 | | TransactionPrice | 142.96 | 1 | 142.96 | | TradeCurrency | USD | USD | USD | | ExchangeRate | 1 | 0.7673 | 0.7673 | | TotalConsideration.Amount | 71480.00 | 54846.60 | 54846.60 | | TotalConsideration.Currency | USD | GBP | GBP | | Trade/default/TradeToPortfolioRate* | 0.7673 | 0.7673 | 0.7673 | [* This is a property field] ##### A Forward FX Example LUSID has a flexible transaction modelling system, meaning there are a number of different ways of modelling forward fx trades. The default LUSID transaction types are FwdFxBuy and FwdFxSell. Using these transaction types, LUSID will generate two holdings for each Forward FX trade, one for each currency in the trade. An example Forward Fx trade to sell GBP for USD in a JPY-denominated portfolio is shown below: | Column | Forward 'Sell' Trade | Notes | | ----- | ----- | ---- | | TransactionId | FBN00004 | | | Type | FwdFxSell | | | InstrumentIdentifiers | { \"Instrument/default/Currency\", \"GBP\" } | | | TransactionDate | 2018-08-02 | | | SettlementDate | 2019-02-06 | Six month forward | | Units | 10000.00 | Units of GBP | | TransactionPrice | 1 | | | TradeCurrency | GBP | Currency being sold | | ExchangeRate | 1.3142 | Agreed rate between GBP and USD | | TotalConsideration.Amount | 13142.00 | Amount in the settlement currency, USD | | TotalConsideration.Currency | USD | Settlement currency | | Trade/default/TradeToPortfolioRate | 142.88 | Rate between trade currency, GBP and portfolio base currency, JPY | Please note that exactly the same economic behaviour could be modelled using the FwdFxBuy Transaction Type with the amounts and rates reversed. ### Holdings A holding represents a position in an instrument or cash on a given date. | Field|Type|Description | | ---|---|--- | | InstrumentUid|string|The unqiue Lusid Instrument Id (LUID) of the instrument that the holding is in. | | SubHoldingKeys|map|The sub-holding properties which identify the holding. Each property will be from the 'Transaction' domain. These are configured when a transaction portfolio is created. | | Properties|map|The properties which have been requested to be decorated onto the holding. These will be from the 'Instrument' or 'Holding' domain. | | HoldingType|string|The type of the holding e.g. Position, Balance, CashCommitment, Receivable, ForwardFX etc. | | Units|decimal|The total number of units of the holding. | | SettledUnits|decimal|The total number of settled units of the holding. | | Cost|currencyandamount|The total cost of the holding in the transaction currency. | | CostPortfolioCcy|currencyandamount|The total cost of the holding in the portfolio currency. | | Transaction|transaction|The transaction associated with an unsettled holding. | ## Corporate Actions Corporate actions are represented within LUSID in terms of a set of instrument-specific 'transitions'. These transitions are used to specify the participants of the corporate action, and the effect that the corporate action will have on holdings in those participants. ### Corporate Action | Field|Type|Description | | ---|---|--- | | CorporateActionCode|code|The unique identifier of this corporate action | | Description|string| | | AnnouncementDate|datetimeoffset|The announcement date of the corporate action | | ExDate|datetimeoffset|The ex date of the corporate action | | RecordDate|datetimeoffset|The record date of the corporate action | | PaymentDate|datetimeoffset|The payment date of the corporate action | | Transitions|corporateactiontransition[]|The transitions that result from this corporate action | ### Transition | Field|Type|Description | | ---|---|--- | | InputTransition|corporateactiontransitioncomponent|Indicating the basis of the corporate action - which security and how many units | | OutputTransitions|corporateactiontransitioncomponent[]|What will be generated relative to the input transition | ### Example Corporate Action Transitions #### A Dividend Action Transition In this example, for each share of IBM, 0.20 units (or 20 pence) of GBP are generated. | Column | Input Transition | Output Transition | | ----- | ----- | ----- | | Instrument Identifiers | { \"figi\" : \"BBG000BLNNH6\" } | { \"ccy\" : \"CCY_GBP\" } | | Units Factor | 1 | 0.20 | | Cost Factor | 1 | 0 | #### A Split Action Transition In this example, for each share of IBM, we end up with 2 units (2 shares) of IBM, with total value unchanged. | Column | Input Transition | Output Transition | | ----- | ----- | ----- | | Instrument Identifiers | { \"figi\" : \"BBG000BLNNH6\" } | { \"figi\" : \"BBG000BLNNH6\" } | | Units Factor | 1 | 2 | | Cost Factor | 1 | 1 | #### A Spinoff Action Transition In this example, for each share of IBM, we end up with 1 unit (1 share) of IBM and 3 units (3 shares) of Celestica, with 85% of the value remaining on the IBM share, and 5% in each Celestica share (15% total). | Column | Input Transition | Output Transition 1 | Output Transition 2 | | ----- | ----- | ----- | ----- | | Instrument Identifiers | { \"figi\" : \"BBG000BLNNH6\" } | { \"figi\" : \"BBG000BLNNH6\" } | { \"figi\" : \"BBG000HBGRF3\" } | | Units Factor | 1 | 1 | 3 | | Cost Factor | 1 | 0.85 | 0.15 | ## Reference Portfolios Reference portfolios are portfolios that contain constituents with weights. They are designed to represent entities such as indices and benchmarks. ### Constituents | Field|Type|Description | | ---|---|--- | | InstrumentIdentifiers|map|Unique instrument identifiers | | InstrumentUid|string|LUSID's internal unique instrument identifier, resolved from the instrument identifiers | | Currency|decimal| | | Weight|decimal| | | FloatingWeight|decimal| | ## Portfolio Groups Portfolio groups allow the construction of a hierarchy from portfolios and groups. Portfolio operations on the group are executed on an aggregated set of portfolios in the hierarchy. For example: * Global Portfolios _(group)_ * APAC _(group)_ * Hong Kong _(portfolio)_ * Japan _(portfolio)_ * Europe _(group)_ * France _(portfolio)_ * Germany _(portfolio)_ * UK _(portfolio)_ In this example **Global Portfolios** is a group that consists of an aggregate of **Hong Kong**, **Japan**, **France**, **Germany** and **UK** portfolios. ## Properties Properties are key-value pairs that can be applied to any entity within a domain (where a domain is `trade`, `portfolio`, `security` etc). Properties must be defined before use with a `PropertyDefinition` and can then subsequently be added to entities. ## Schema A detailed description of the entities used by the API and parameters for endpoints which take a JSON document can be retrieved via the `schema` endpoint. ## Meta data The following headers are returned on all responses from LUSID | Name | Purpose | | --- | --- | | lusid-meta-duration | Duration of the request | | lusid-meta-success | Whether or not LUSID considered the request to be successful | | lusid-meta-requestId | The unique identifier for the request | | lusid-schema-url | Url of the schema for the data being returned | | lusid-property-schema-url | Url of the schema for any properties | # Error Codes | Code|Name|Description | | ---|---|--- | | <a name=\"-10\">-10</a>|Server Configuration Error| | | <a name=\"-1\">-1</a>|Unknown error|An unexpected error was encountered on our side. | | <a name=\"102\">102</a>|Version Not Found| | | <a name=\"103\">103</a>|Api Rate Limit Violation| | | <a name=\"104\">104</a>|Instrument Not Found| | | <a name=\"105\">105</a>|Property Not Found| | | <a name=\"106\">106</a>|Portfolio Recursion Depth| | | <a name=\"108\">108</a>|Group Not Found| | | <a name=\"109\">109</a>|Portfolio Not Found| | | <a name=\"110\">110</a>|Property Schema Not Found| | | <a name=\"111\">111</a>|Portfolio Ancestry Not Found| | | <a name=\"112\">112</a>|Portfolio With Id Already Exists| | | <a name=\"113\">113</a>|Orphaned Portfolio| | | <a name=\"119\">119</a>|Missing Base Claims| | | <a name=\"121\">121</a>|Property Not Defined| | | <a name=\"122\">122</a>|Cannot Delete System Property| | | <a name=\"123\">123</a>|Cannot Modify Immutable Property Field| | | <a name=\"124\">124</a>|Property Already Exists| | | <a name=\"125\">125</a>|Invalid Property Life Time| | | <a name=\"126\">126</a>|Property Constraint Style Excludes Properties| | | <a name=\"127\">127</a>|Cannot Modify Default Data Type| | | <a name=\"128\">128</a>|Group Already Exists| | | <a name=\"129\">129</a>|No Such Data Type| | | <a name=\"130\">130</a>|Undefined Value For Data Type| | | <a name=\"131\">131</a>|Unsupported Value Type Defined On Data Type| | | <a name=\"132\">132</a>|Validation Error| | | <a name=\"133\">133</a>|Loop Detected In Group Hierarchy| | | <a name=\"134\">134</a>|Undefined Acceptable Values| | | <a name=\"135\">135</a>|Sub Group Already Exists| | | <a name=\"138\">138</a>|Price Source Not Found| | | <a name=\"139\">139</a>|Analytic Store Not Found| | | <a name=\"141\">141</a>|Analytic Store Already Exists| | | <a name=\"143\">143</a>|Client Instrument Already Exists| | | <a name=\"144\">144</a>|Duplicate In Parameter Set| | | <a name=\"147\">147</a>|Results Not Found| | | <a name=\"148\">148</a>|Order Field Not In Result Set| | | <a name=\"149\">149</a>|Operation Failed| | | <a name=\"150\">150</a>|Elastic Search Error| | | <a name=\"151\">151</a>|Invalid Parameter Value| | | <a name=\"153\">153</a>|Command Processing Failure| | | <a name=\"154\">154</a>|Entity State Construction Failure| | | <a name=\"155\">155</a>|Entity Timeline Does Not Exist| | | <a name=\"156\">156</a>|Concurrency Conflict Failure| | | <a name=\"157\">157</a>|Invalid Request| | | <a name=\"158\">158</a>|Event Publish Unknown| | | <a name=\"159\">159</a>|Event Query Failure| | | <a name=\"160\">160</a>|Blob Did Not Exist| | | <a name=\"162\">162</a>|Sub System Request Failure| | | <a name=\"163\">163</a>|Sub System Configuration Failure| | | <a name=\"165\">165</a>|Failed To Delete| | | <a name=\"166\">166</a>|Upsert Client Instrument Failure| | | <a name=\"167\">167</a>|Illegal As At Interval| | | <a name=\"168\">168</a>|Illegal Bitemporal Query| | | <a name=\"169\">169</a>|Invalid Alternate Id| | | <a name=\"170\">170</a>|Cannot Add Source Portfolio Property Explicitly| | | <a name=\"171\">171</a>|Entity Already Exists In Group| | | <a name=\"173\">173</a>|Entity With Id Already Exists| | | <a name=\"174\">174</a>|Derived Portfolio Details Do Not Exist| | | <a name=\"176\">176</a>|Portfolio With Name Already Exists| | | <a name=\"177\">177</a>|Invalid Transactions| | | <a name=\"178\">178</a>|Reference Portfolio Not Found| | | <a name=\"179\">179</a>|Duplicate Id| | | <a name=\"180\">180</a>|Command Retrieval Failure| | | <a name=\"181\">181</a>|Data Filter Application Failure| | | <a name=\"182\">182</a>|Search Failed| | | <a name=\"183\">183</a>|Movements Engine Configuration Key Failure| | | <a name=\"184\">184</a>|Fx Rate Source Not Found| | | <a name=\"185\">185</a>|Accrual Source Not Found| | | <a name=\"186\">186</a>|Access Denied| | | <a name=\"187\">187</a>|Invalid Identity Token| | | <a name=\"188\">188</a>|Invalid Request Headers| | | <a name=\"189\">189</a>|Price Not Found| | | <a name=\"190\">190</a>|Invalid Sub Holding Keys Provided| | | <a name=\"191\">191</a>|Duplicate Sub Holding Keys Provided| | | <a name=\"192\">192</a>|Cut Definition Not Found| | | <a name=\"193\">193</a>|Cut Definition Invalid| | | <a name=\"194\">194</a>|Time Variant Property Deletion Date Unspecified| | | <a name=\"195\">195</a>|Perpetual Property Deletion Date Specified| | | <a name=\"196\">196</a>|Time Variant Property Upsert Date Unspecified| | | <a name=\"197\">197</a>|Perpetual Property Upsert Date Specified| | | <a name=\"200\">200</a>|Invalid Unit For Data Type| | | <a name=\"201\">201</a>|Invalid Type For Data Type| | | <a name=\"202\">202</a>|Invalid Value For Data Type| | | <a name=\"203\">203</a>|Unit Not Defined For Data Type| | | <a name=\"204\">204</a>|Units Not Supported On Data Type| | | <a name=\"205\">205</a>|Cannot Specify Units On Data Type| | | <a name=\"206\">206</a>|Unit Schema Inconsistent With Data Type| | | <a name=\"207\">207</a>|Unit Definition Not Specified| | | <a name=\"208\">208</a>|Duplicate Unit Definitions Specified| | | <a name=\"209\">209</a>|Invalid Units Definition| | | <a name=\"210\">210</a>|Invalid Instrument Identifier Unit| | | <a name=\"211\">211</a>|Holdings Adjustment Does Not Exist| | | <a name=\"212\">212</a>|Could Not Build Excel Url| | | <a name=\"213\">213</a>|Could Not Get Excel Version| | | <a name=\"214\">214</a>|Instrument By Code Not Found| | | <a name=\"215\">215</a>|Entity Schema Does Not Exist| | | <a name=\"216\">216</a>|Feature Not Supported On Portfolio Type| | | <a name=\"217\">217</a>|Quote Not Found| | | <a name=\"218\">218</a>|Invalid Quote Identifier| | | <a name=\"219\">219</a>|Invalid Metric For Data Type| | | <a name=\"220\">220</a>|Invalid Instrument Definition| | | <a name=\"221\">221</a>|Instrument Upsert Failure| | | <a name=\"222\">222</a>|Reference Portfolio Request Not Supported| | | <a name=\"223\">223</a>|Transaction Portfolio Request Not Supported| | | <a name=\"224\">224</a>|Invalid Property Value Assignment| | | <a name=\"230\">230</a>|Transaction Type Not Found| | | <a name=\"231\">231</a>|Transaction Type Duplication| | | <a name=\"232\">232</a>|Portfolio Does Not Exist At Given Date| | | <a name=\"233\">233</a>|Query Parser Failure| | | <a name=\"234\">234</a>|Duplicate Constituent| | | <a name=\"235\">235</a>|Unresolved Instrument Constituent| | | <a name=\"236\">236</a>|Unresolved Instrument In Transition| | | <a name=\"237\">237</a>|Missing Side Definitions| | | <a name=\"299\">299</a>|Invalid Recipe| | | <a name=\"300\">300</a>|Missing Recipe| | | <a name=\"301\">301</a>|Dependencies| | | <a name=\"304\">304</a>|Portfolio Preprocess Failure| | | <a name=\"310\">310</a>|Valuation Engine Failure| | | <a name=\"311\">311</a>|Task Factory Failure| | | <a name=\"312\">312</a>|Task Evaluation Failure| | | <a name=\"313\">313</a>|Task Generation Failure| | | <a name=\"314\">314</a>|Engine Configuration Failure| | | <a name=\"315\">315</a>|Model Specification Failure| | | <a name=\"320\">320</a>|Market Data Key Failure| | | <a name=\"321\">321</a>|Market Resolver Failure| | | <a name=\"322\">322</a>|Market Data Failure| | | <a name=\"330\">330</a>|Curve Failure| | | <a name=\"331\">331</a>|Volatility Surface Failure| | | <a name=\"332\">332</a>|Volatility Cube Failure| | | <a name=\"350\">350</a>|Instrument Failure| | | <a name=\"351\">351</a>|Cash Flows Failure| | | <a name=\"352\">352</a>|Reference Data Failure| | | <a name=\"360\">360</a>|Aggregation Failure| | | <a name=\"361\">361</a>|Aggregation Measure Failure| | | <a name=\"370\">370</a>|Result Retrieval Failure| | | <a name=\"371\">371</a>|Result Processing Failure| | | <a name=\"372\">372</a>|Vendor Result Processing Failure| | | <a name=\"373\">373</a>|Vendor Result Mapping Failure| | | <a name=\"374\">374</a>|Vendor Library Unauthorised| | | <a name=\"375\">375</a>|Vendor Connectivity Error| | | <a name=\"376\">376</a>|Vendor Interface Error| | | <a name=\"377\">377</a>|Vendor Pricing Failure| | | <a name=\"378\">378</a>|Vendor Translation Failure| | | <a name=\"379\">379</a>|Vendor Key Mapping Failure| | | <a name=\"380\">380</a>|Vendor Reflection Failure| | | <a name=\"390\">390</a>|Attempt To Upsert Duplicate Quotes| | | <a name=\"391\">391</a>|Corporate Action Source Does Not Exist| | | <a name=\"392\">392</a>|Corporate Action Source Already Exists| | | <a name=\"393\">393</a>|Instrument Identifier Already In Use| | | <a name=\"394\">394</a>|Properties Not Found| | | <a name=\"395\">395</a>|Batch Operation Aborted| | | <a name=\"400\">400</a>|Invalid Iso4217 Currency Code| | | <a name=\"401\">401</a>|Cannot Assign Instrument Identifier To Currency| | | <a name=\"402\">402</a>|Cannot Assign Currency Identifier To Non Currency| | | <a name=\"403\">403</a>|Currency Instrument Cannot Be Deleted| | | <a name=\"404\">404</a>|Currency Instrument Cannot Have Economic Definition| | | <a name=\"405\">405</a>|Currency Instrument Cannot Have Lookthrough Portfolio| | | <a name=\"406\">406</a>|Cannot Create Currency Instrument With Multiple Identifiers| | | <a name=\"407\">407</a>|Specified Currency Is Undefined| | | <a name=\"410\">410</a>|Index Does Not Exist| | | <a name=\"411\">411</a>|Sort Field Does Not Exist| | | <a name=\"413\">413</a>|Negative Pagination Parameters| | | <a name=\"414\">414</a>|Invalid Search Syntax| | | <a name=\"415\">415</a>|Filter Execution Timeout| | | <a name=\"420\">420</a>|Side Definition Inconsistent| | | <a name=\"450\">450</a>|Invalid Quote Access Metadata Rule| | | <a name=\"451\">451</a>|Access Metadata Not Found| | | <a name=\"452\">452</a>|Invalid Access Metadata Identifier| | | <a name=\"460\">460</a>|Standard Resource Not Found| | | <a name=\"461\">461</a>|Standard Resource Conflict| | | <a name=\"462\">462</a>|Calendar Not Found| | | <a name=\"463\">463</a>|Date In A Calendar Not Found| | | <a name=\"464\">464</a>|Invalid Date Source Data| | | <a name=\"465\">465</a>|Invalid Timezone| | | <a name=\"601\">601</a>|Person Identifier Already In Use| | | <a name=\"602\">602</a>|Person Not Found| | | <a name=\"603\">603</a>|Cannot Set Identifier| | | <a name=\"617\">617</a>|Invalid Recipe Specification In Request| | | <a name=\"618\">618</a>|Inline Recipe Deserialisation Failure| | | <a name=\"619\">619</a>|Identifier Types Not Set For Entity| | | <a name=\"620\">620</a>|Cannot Delete All Client Defined Identifiers| | | <a name=\"650\">650</a>|The Order requested was not found.| | | <a name=\"654\">654</a>|The Allocation requested was not found.| | | <a name=\"655\">655</a>|Cannot build the fx forward target with the given holdings.| | | <a name=\"656\">656</a>|Group does not contain expected entities.| | | <a name=\"667\">667</a>|Relation definition already exists| | | <a name=\"673\">673</a>|Missing entitlements for entities in Group| | | <a name=\"674\">674</a>|Next Best Action not found| | | <a name=\"676\">676</a>|Relation definition not defined| | | <a name=\"677\">677</a>|Invalid entity identifier for relation| | | <a name=\"681\">681</a>|Sorting by specified field not supported|One or more of the provided fields to order by were either invalid or not supported. | | <a name=\"682\">682</a>|Too many fields to sort by|The number of fields to sort the data by exceeds the number allowed by the endpoint | | <a name=\"684\">684</a>|Sequence Not Found| | | <a name=\"685\">685</a>|Sequence Already Exists| | | <a name=\"686\">686</a>|Non-cycling sequence has been exhausted| | | <a name=\"687\">687</a>|Legal Entity Identifier Already In Use| | | <a name=\"688\">688</a>|Legal Entity Not Found| | | <a name=\"689\">689</a>|The supplied pagination token is invalid| | | <a name=\"690\">690</a>|Property Type Is Not Supported| | | <a name=\"691\">691</a>|Multiple Tax-lots For Currency Type Is Not Supported| |
*
* The version of the OpenAPI document: 0.11.2220
* Contact: info@finbourne.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.finbourne.lusid.model;
import com.finbourne.lusid.model.Property;
import com.finbourne.lusid.model.WeekendMask;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
/**
* Model tests for UpdateCalendarRequest
*/
public class UpdateCalendarRequestTest {
private final UpdateCalendarRequest model = new UpdateCalendarRequest();
/**
* Model tests for UpdateCalendarRequest
*/
@Test
public void testUpdateCalendarRequest() {
// TODO: test UpdateCalendarRequest
}
/**
* Test the property 'weekendMask'
*/
@Test
public void weekendMaskTest() {
// TODO: test weekendMask
}
/**
* Test the property 'sourceProvider'
*/
@Test
public void sourceProviderTest() {
// TODO: test sourceProvider
}
/**
* Test the property 'properties'
*/
@Test
public void propertiesTest() {
// TODO: test properties
}
}
|
/*
The MIT License (MIT)
Copyright (c) 2014 Ahmad Barqawi (github.com/Barqawiz)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.iaraby.views;
import com.iaraby.data.DBAdapter;
import com.iaraby.db.helper.lib.SimpleCursorLoader;
import com.iaraby.keep.R;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.Toast;
public class KeepFragment extends ListFragment
implements LoaderCallbacks<Cursor>, OnItemLongClickListener{
private SimpleCursorAdapter adapter;
private SimpleCursorLoader loader;
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Initial
customUI();
getListView().setOnItemLongClickListener(this);
// Control
populateList();
} // method: on create
public void populateList() {
String[] from = new String[] { DBAdapter.KEEP_TABLE.COL_DATA, DBAdapter.KEEP_TABLE.COL_COLOR };
int[] to = new int[] { R.id.textView1, R.id.item_color};
getLoaderManager().initLoader(1, null, this);
adapter = new SimpleCursorAdapter(getActivity(), R.layout.keep_item, null, from, to,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
adapter.setViewBinder(new Binder());
setListAdapter(adapter);
adapter.notifyDataSetChanged();
}
private void customUI() {
getListView().setCacheColorHint(0);
getListView().setDivider(null);
getListView().setDividerHeight((int)getResources().getDimension(R.dimen.devider_padding));
getListView().setVerticalScrollBarEnabled(false);
getListView().setHorizontalScrollBarEnabled(false);
getListView().setSelector(R.drawable.list_selector);
}
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
if (DBAdapter.getInstance().isOpen() && id > 0) {
DBAdapter.getInstance().removeKeep(id);
loader.onContentChanged();
Toast.makeText(getActivity(), getString(R.string.deleted), Toast.LENGTH_LONG).show();
}
return true;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//when receive 10 and 10 from add dialog thats mean refresh the list
if (resultCode == 10 && requestCode == 10) {
if (loader != null)
loader.onContentChanged();
}
super.onActivityResult(requestCode, resultCode, data);
}
/*Cursor loader*/
@Override
public Loader<Cursor> onCreateLoader(int args0, Bundle bundel) {
loader = new SimpleCursorLoader(getActivity()) {
@Override
public Cursor loadInBackground() {
Cursor cursor = DBAdapter.getInstance().getKeep();
return cursor;
}
};
return loader;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (adapter != null && cursor != null)
adapter.swapCursor(cursor);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
if (adapter != null)
adapter.swapCursor(null);
}
/*Bind*/
class Binder implements SimpleCursorAdapter.ViewBinder {
@Override
public boolean setViewValue(View view, Cursor cursor, int index) {
if (view.getId() == R.id.item_color) {
String color = cursor.getString(cursor.getColumnIndex(DBAdapter.KEEP_TABLE.COL_COLOR));
if (color != null)
((ImageView)view).setBackgroundColor(Color.parseColor(color));
}
return false;
}
} //class: handle list view bind
} // class: Fragment
|
package com.special.coolweather.gson;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by Special on 2017/10/26.
*/
public class Weather {
public String status;
public Basic basic;
public AQI aqi;
public Now now;
public Suggestion suggestion;
@SerializedName("daily_forecast")
public List<Forecast> forecastList;
}
|
package androidx.appcompat.widget;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.DrawableContainer;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.InsetDrawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.ScaleDrawable;
import android.os.Build;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.RestrictTo;
import androidx.appcompat.graphics.drawable.DrawableWrapper;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.core.graphics.drawable.WrappedDrawable;
import java.lang.reflect.Field;
@RestrictTo({RestrictTo.Scope.LIBRARY_GROUP})
/* loaded from: classes.dex */
public class DrawableUtils {
public static final Rect INSETS_NONE = new Rect();
private static final String TAG = "DrawableUtils";
private static final String VECTOR_DRAWABLE_CLAZZ_NAME = "android.graphics.drawable.VectorDrawable";
private static Class<?> sInsetsClazz;
static {
if (Build.VERSION.SDK_INT >= 18) {
try {
sInsetsClazz = Class.forName("android.graphics.Insets");
} catch (ClassNotFoundException e) {
}
}
}
private DrawableUtils() {
}
public static Rect getOpticalBounds(Drawable drawable) {
if (sInsetsClazz != null) {
try {
Drawable drawable2 = DrawableCompat.unwrap(drawable);
Object insets = drawable2.getClass().getMethod("getOpticalInsets", new Class[0]).invoke(drawable2, new Object[0]);
if (insets != null) {
Rect result = new Rect();
Field[] fields = sInsetsClazz.getFields();
for (Field field : fields) {
String name = field.getName();
char c = 65535;
switch (name.hashCode()) {
case -1383228885:
if (name.equals("bottom")) {
c = 3;
break;
}
break;
case 115029:
if (name.equals("top")) {
c = 1;
break;
}
break;
case 3317767:
if (name.equals("left")) {
c = 0;
break;
}
break;
case 108511772:
if (name.equals("right")) {
c = 2;
break;
}
break;
}
switch (c) {
case 0:
result.left = field.getInt(insets);
continue;
case 1:
result.top = field.getInt(insets);
continue;
case 2:
result.right = field.getInt(insets);
continue;
case 3:
result.bottom = field.getInt(insets);
continue;
}
}
return result;
}
} catch (Exception e) {
Log.e(TAG, "Couldn't obtain the optical insets. Ignoring.");
}
}
return INSETS_NONE;
}
public static void fixDrawable(@NonNull Drawable drawable) {
if (Build.VERSION.SDK_INT == 21 && VECTOR_DRAWABLE_CLAZZ_NAME.equals(drawable.getClass().getName())) {
fixVectorDrawableTinting(drawable);
}
}
public static boolean canSafelyMutateDrawable(@NonNull Drawable drawable) {
if (Build.VERSION.SDK_INT < 15 && (drawable instanceof InsetDrawable)) {
return false;
}
if (Build.VERSION.SDK_INT < 15 && (drawable instanceof GradientDrawable)) {
return false;
}
if (Build.VERSION.SDK_INT < 17 && (drawable instanceof LayerDrawable)) {
return false;
}
if (drawable instanceof DrawableContainer) {
Drawable.ConstantState state = drawable.getConstantState();
if (state instanceof DrawableContainer.DrawableContainerState) {
for (Drawable child : ((DrawableContainer.DrawableContainerState) state).getChildren()) {
if (!canSafelyMutateDrawable(child)) {
return false;
}
}
}
} else if (drawable instanceof WrappedDrawable) {
return canSafelyMutateDrawable(((WrappedDrawable) drawable).getWrappedDrawable());
} else {
if (drawable instanceof DrawableWrapper) {
return canSafelyMutateDrawable(((DrawableWrapper) drawable).getWrappedDrawable());
}
if (drawable instanceof ScaleDrawable) {
return canSafelyMutateDrawable(((ScaleDrawable) drawable).getDrawable());
}
}
return true;
}
private static void fixVectorDrawableTinting(Drawable drawable) {
int[] originalState = drawable.getState();
if (originalState == null || originalState.length == 0) {
drawable.setState(ThemeUtils.CHECKED_STATE_SET);
} else {
drawable.setState(ThemeUtils.EMPTY_STATE_SET);
}
drawable.setState(originalState);
}
public static PorterDuff.Mode parseTintMode(int value, PorterDuff.Mode defaultMode) {
switch (value) {
case 3:
return PorterDuff.Mode.SRC_OVER;
case 4:
case 6:
case 7:
case 8:
case 10:
case 11:
case 12:
case 13:
default:
return defaultMode;
case 5:
return PorterDuff.Mode.SRC_IN;
case 9:
return PorterDuff.Mode.SRC_ATOP;
case 14:
return PorterDuff.Mode.MULTIPLY;
case 15:
return PorterDuff.Mode.SCREEN;
case 16:
return PorterDuff.Mode.ADD;
}
}
}
|
package dev.patika.app.entity.concretes;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.List;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class PermanentInstructor extends Instructor{
private double fixedSalary;
@Builder(builderMethodName = "PermanentInstructorBuilder")
public PermanentInstructor(String fullName, String address, String phoneNumber, List<Course> courses, double fixedSalary) {
super(fullName, address, phoneNumber, courses);
this.fixedSalary = fixedSalary;
}
}
|
package br.com.df.sgp.validator;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import br.com.df.sgp.util.CPFUtils;
/**
*
* @author Wenderson Ferreira
*
*/
@FacesValidator("CPFValidator")
public class CPFValidator implements Validator {
@Override
public void validate(FacesContext ctx, UIComponent ui, Object value) throws ValidatorException {
if(value != null && !value.equals("")){
String cpf = (String) value;
boolean valid = CPFUtils.validate(cpf);
if(!valid){
FacesMessage msg = new FacesMessage("CPF Inválido", "CPF Inválido");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(msg);
}
}
}
}
|
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * 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.impetus.kundera.tests.crossdatastore.pickr.entities.photographer;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_M_M_1_1;
/**
* Entity class representing a photographer
*
* @author amresh.singh
*/
@Entity
@Table(name = "PHOTOGRAPHER", schema = "Pickr")
public class PhotographerBi_M_M_1_1
{
@Id
@Column(name = "PHOTOGRAPHER_ID")
private int photographerId;
@Column(name = "PHOTOGRAPHER_NAME")
private String photographerName;
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(/* schema = "Pickr", */name = "PHOTOGRAPHER_ALBUM", joinColumns = { @JoinColumn(name = "PHOTOGRAPHER_ID") }, inverseJoinColumns = { @JoinColumn(name = "ALBUM_ID") })
private List<AlbumBi_M_M_1_1> albums;
/**
* @return the photographerId
*/
public int getPhotographerId()
{
return photographerId;
}
/**
* @param photographerId
* the photographerId to set
*/
public void setPhotographerId(int photographerId)
{
this.photographerId = photographerId;
}
/**
* @return the photographerName
*/
public String getPhotographerName()
{
return photographerName;
}
/**
* @param photographerName
* the photographerName to set
*/
public void setPhotographerName(String photographerName)
{
this.photographerName = photographerName;
}
/**
* @return the albums
*/
public List<AlbumBi_M_M_1_1> getAlbums()
{
return albums;
}
/**
* @param albums
* the albums to set
*/
public void addAlbum(AlbumBi_M_M_1_1 album)
{
if (this.albums == null || this.albums.isEmpty())
{
this.albums = new ArrayList<AlbumBi_M_M_1_1>();
}
this.albums.add(album);
}
}
|
package org.zmsoft.weixin.api;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.zmsoft.framework.beans.UserBean;
import org.zmsoft.framework.beans.common.RESTResultBean;
import org.zmsoft.framework.support.MyBeanFactoryHelper;
import org.zmsoft.framework.utils.EmptyHelper;
import org.zmsoft.framework.weixin.bean.WxCallBackParamBean;
import org.zmsoft.framework.weixin.service.ISWxInviteProcessSupport;
import org.zmsoft.weixin.MyWeixinCommonSupport;
import com.alibaba.fastjson.JSONObject;
/**
* 菜单入口(用户授权)邀请
*
* @author Zmsoft
* @version 0.1.0 2018/4/2
* @since 0.1.0 2018/4/2
*/
@Controller
public class WxInviteController extends MyWeixinCommonSupport {
/**
* 邀请地址
*
* @param [playerId]
* @return ModelAndView
* @throws Exception
* @author Zmsoft
* @version 0.1.0 2018/4/2
* @since 0.1.0 2018/4/2
*/
@RequestMapping(value = "/WXInvite/{playerId}", method = RequestMethod.GET)
public ModelAndView doWXInvite(@PathVariable String playerId) throws Exception {
logger.debug("doWXHomeIndex==>>>" + playerId);
ModelAndView model = new ModelAndView("/weixin/WXIndex");
// 回调地址
model.addObject("redirect", URLEncoder.encode(getSystemConfigService().getApiServerUrl() + "/WXInvite/Back/" + playerId, SYSTEM_CHARSET));
// 目标地址
model.addObject("login_href", "/WXIndex/Login/1");
model.addObject("appid", getWxConfigService().getWxAppID());
model.addObject("state", 2);
model.addObject("playerId", playerId);
logger.debug("doWXHomeIndex==>>>" + model);
return model;
}
/**
* 活动(商品文章)分享邀请地址
*
* @param [playerId]
* @return ModelAndView
* @throws Exception
* @author Zmsoft
* @version 0.1.0 2018/4/2
* @since 0.1.0 2018/4/2
*/
@RequestMapping(value = "/WXInvite/{playerId}/{classify}/{itemId}/{orderId}", method = RequestMethod.GET)
public ModelAndView doWXInviteClassify(@PathVariable String playerId, @PathVariable String classify, @PathVariable String itemId, @PathVariable String orderId) throws Exception {
logger.debug("doWXHomeIndex==>>>" + playerId);
ModelAndView model = new ModelAndView("/weixin/WXIndex");
// 回调地址
model.addObject("redirect", URLEncoder.encode(getSystemConfigService().getApiServerUrl() + "/WXInvite/Back/" + playerId + URL_SLASH + itemId + URL_SLASH + orderId, SYSTEM_CHARSET));
// 目标地址
model.addObject("login_href", "/WXIndex/Login/1");
model.addObject("appid", getWxConfigService().getWxAppID());
model.addObject("state", 2);
model.addObject("playerId", playerId);
logger.debug("doWXHomeIndex==>>>" + model);
return model;
}
/**
* 微信授权回调地址-微信菜单地址
*
* @param [request,
* response, playerId, wxUserBean]
* @return ModelAndView
* @throws Exception
* @author Zmsoft
* @version 0.1.0 2018/4/2
* @since 0.1.0 2018/4/2
*/
@RequestMapping(value = "/WXInvite/Back/{playerId}", method = RequestMethod.GET)
public ModelAndView doWXBack(HttpServletRequest request, HttpServletResponse response,
@PathVariable String playerId,
WxCallBackParamBean wxCallBackParamBean) throws Exception {
ModelAndView model = new ModelAndView("/weixin/WXerror");
logger.debug("doWXBack==>>>" + playerId);
logger.debug("====doWXBack=====doWXBack====code>>>>>>>>>>>" + wxCallBackParamBean.getCode());
if (EmptyHelper.isEmpty(wxCallBackParamBean.getCode()))
model.addObject("msg", "授权失败!");
else {
// 第二步:通过code换取网页授权access_token
wxCallBackParamBean.setAppid(getWxConfigService().getWxAppID());
wxCallBackParamBean.setSecret(getWxConfigService().getWxAppSecret());
JSONObject wxmsg = myWeixinCommonSupport.loadAccessToken(wxCallBackParamBean);
String openId = wxmsg.getString("openid");
if (EmptyHelper.isNotEmpty(openId)) {
logger.info("====doWXBack====doWXBack=====openId>>>>>>>>>>>" + openId);
wxCallBackParamBean.setOpenid(openId);
wxCallBackParamBean.setAccess_token(wxmsg.getString("access_token"));
wxCallBackParamBean.setChannel(playerId);// 渠道
wxCallBackParamBean.setClassify(ZERO);
// 开始自动登录
return doWXLogin(request, response, playerId, wxCallBackParamBean);
} else {
model.addObject("msg", "授权失败!");
}
}
return model;
}
/**
* 微信授权回调地址-微信菜单地址
*
* @param [request,
* response, playerId, wxUserBean]
* @return ModelAndView
* @throws Exception
* @author Zmsoft
* @version 0.1.0 2018/4/2
* @since 0.1.0 2018/4/2
*/
@RequestMapping(value = "/WXInvite/Back/{playerId}/{classify}/{itemId}/{orderId}", method = RequestMethod.GET)
public ModelAndView doWXBack(HttpServletRequest request, HttpServletResponse response,
@PathVariable String playerId, @PathVariable String classify, @PathVariable String itemId, @PathVariable String orderId,
WxCallBackParamBean wxCallBackParamBean) throws Exception {
ModelAndView model = new ModelAndView("/weixin/WXerror");
logger.debug("doWXBack==>>>" + playerId);
logger.debug("====doWXBack=====doWXBack====code>>>>>>>>>>>" + wxCallBackParamBean.getCode());
if (EmptyHelper.isEmpty(wxCallBackParamBean.getCode()))
model.addObject("msg", "授权失败!");
else {
// 第二步:通过code换取网页授权access_token
wxCallBackParamBean.setAppid(getWxConfigService().getWxAppID());
wxCallBackParamBean.setSecret(getWxConfigService().getWxAppSecret());
JSONObject wxmsg = myWeixinCommonSupport.loadAccessToken(wxCallBackParamBean);
String openId = wxmsg.getString("openid");
if (EmptyHelper.isNotEmpty(openId)) {
logger.info("====doWXBack====doWXBack=====openId>>>>>>>>>>>" + openId);
wxCallBackParamBean.setOpenid(openId);
wxCallBackParamBean.setAccess_token(wxmsg.getString("access_token"));
////////////////////////////////////////////////////
wxCallBackParamBean.setChannel(SYSTEM);// 渠道ID
wxCallBackParamBean.setPlayerId(playerId);// 渠道推广员ID
wxCallBackParamBean.setClassify(classify);
wxCallBackParamBean.setItemId(itemId);
wxCallBackParamBean.setOrderId(orderId);
////////////////////////////////////////////////////
// 开始自动登录
return doWXLogin(request, response, playerId, wxCallBackParamBean);
} else {
model.addObject("msg", "授权失败!");
}
}
return model;
}
private ModelAndView doWXLogin(HttpServletRequest request, HttpServletResponse response, String playerId, WxCallBackParamBean wxCallBackParamBean) throws Exception {
logger.debug("doWXMenuMain==>>>" + playerId);
logger.debug("doWXMenuMain==>>>" + wxCallBackParamBean);
// 开始自动登录
RESTResultBean<UserBean> result = getPlayerLoginService().doWeixinLogin(request, response, wxCallBackParamBean);
ModelAndView model = new ModelAndView("/weixin/WXHome");
model.addObject("token", result.getToken());
model.addObject("user", result.getData());
model.addObject("data", wxCallBackParamBean);
model.addObject("menuId", wxCallBackParamBean.getClassify());
model.addObject("apiServerUrl", getSystemConfigService().getApiServerUrl());
model.addObject("pcServerUrl", getSystemConfigService().getPcServerUrl());
model.addObject("wxServerUrl", getSystemConfigService().getWxServerUrl());
//激活拦截器
ISWxInviteProcessSupport myWxInviteProcessSupport = MyBeanFactoryHelper.getBean(ISWxInviteProcessSupport.class.getSimpleName());
if(EmptyHelper.isNotEmpty(myWxInviteProcessSupport)){
myWxInviteProcessSupport.doProcess(wxCallBackParamBean);
}
return model;
}
}
|
/*******************************************************************************
* Copyright (c) 2000, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.corext.dom;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jdt.core.dom.ASTMatcher;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.SimpleName;
public class JdtASTMatcher extends ASTMatcher {
public boolean match(SimpleName node, Object other) {
boolean isomorphic= super.match(node, other);
if (! isomorphic || !(other instanceof SimpleName))
return false;
SimpleName name= (SimpleName)other;
IBinding nodeBinding= node.resolveBinding();
IBinding otherBinding= name.resolveBinding();
if (nodeBinding == null) {
if (otherBinding != null) {
return false;
}
} else {
if (nodeBinding != otherBinding) {
return false;
}
}
if (node.resolveTypeBinding() != name.resolveTypeBinding())
return false;
return true;
}
public static boolean doNodesMatch(ASTNode one, ASTNode other) {
Assert.isNotNull(one);
Assert.isNotNull(other);
return one.subtreeMatch(new JdtASTMatcher(), other);
}
}
|
/**
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.zookeeper.server;
import java.io.Flushable;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This RequestProcessor logs requests to disk. It batches the requests to do
* the io efficiently. The request is not passed to the next RequestProcessor
* until its log has been synced to disk.
*/
public class SyncRequestProcessor extends Thread implements RequestProcessor {
private static final Logger LOG = LoggerFactory.getLogger(SyncRequestProcessor.class);
private final ZooKeeperServer zks;
private final LinkedBlockingQueue<Request> queuedRequests =
new LinkedBlockingQueue<Request>();
private final RequestProcessor nextProcessor;
private Thread snapInProcess = null;
volatile private boolean running;
/**
* Transactions that have been written and are waiting to be flushed to
* disk. Basically this is the list of SyncItems whose callbacks will be
* invoked after flush returns successfully.
*/
private final LinkedList<Request> toFlush = new LinkedList<Request>();
private final Random r = new Random(System.nanoTime());
/**
* The number of log entries to log before starting a snapshot
*/
private static int snapCount = ZooKeeperServer.getSnapCount();
private final Request requestOfDeath = Request.requestOfDeath;
public SyncRequestProcessor(ZooKeeperServer zks,
RequestProcessor nextProcessor) {
super("SyncThread:" + zks.getServerId());
this.zks = zks;
this.nextProcessor = nextProcessor;
running = true;
}
/**
* used by tests to check for changing
* snapcounts
* @param count
*/
public static void setSnapCount(int count) {
snapCount = count;
}
/**
* used by tests to get the snapcount
* @return the snapcount
*/
public static int getSnapCount() {
return snapCount;
}
@Override
public void run() {
try {
int logCount = 0;
// we do this in an attempt to ensure that not all of the servers
// in the ensemble take a snapshot at the same time
int randRoll = r.nextInt(snapCount / 2);
while (true) {
Request si = null;
if (toFlush.isEmpty()) {
si = queuedRequests.take();
} else {
si = queuedRequests.poll();
if (si == null) {
flush(toFlush);
continue;
}
}
if (si == requestOfDeath) {
break;
}
if (si != null) {
// track the number of records written to the log
if (zks.getZKDatabase().append(si)) {
logCount++;
if (logCount > (snapCount / 2 + randRoll)) {
randRoll = r.nextInt(snapCount / 2);
// roll the log
zks.getZKDatabase().rollLog();
// take a snapshot
if (snapInProcess != null && snapInProcess.isAlive()) {
LOG.warn("Too busy to snap, skipping");
} else {
snapInProcess = new Thread("Snapshot Thread") {
public void run() {
try {
zks.takeSnapshot();
} catch (Exception e) {
LOG.warn("Unexpected exception", e);
}
}
};
snapInProcess.start();
}
logCount = 0;
}
} else if (toFlush.isEmpty()) {
// optimization for read heavy workloads
// iff this is a read, and there are no pending
// flushes (writes), then just pass this to the next
// processor
nextProcessor.processRequest(si);
if (nextProcessor instanceof Flushable) {
((Flushable) nextProcessor).flush();
}
continue;
}
toFlush.add(si);
if (toFlush.size() > 1000) {
flush(toFlush);
}
}
}
} catch (Throwable t) {
LOG.error("Severe unrecoverable error, exiting", t);
running = false;
System.exit(11);
}
LOG.info("SyncRequestProcessor exited!");
}
private void flush(LinkedList<Request> toFlush) throws IOException, RequestProcessorException {
if (toFlush.isEmpty())
return;
zks.getZKDatabase().commit();
while (!toFlush.isEmpty()) {
Request i = toFlush.remove();
nextProcessor.processRequest(i);
}
if (nextProcessor instanceof Flushable) {
((Flushable) nextProcessor).flush();
}
}
public void shutdown() {
LOG.info("Shutting down");
queuedRequests.add(requestOfDeath);
try {
if (running) {
this.join();
}
} catch (InterruptedException e) {
LOG.warn("Interrupted while wating for " + this + " to finish");
}
nextProcessor.shutdown();
}
public void processRequest(Request request) {
// request.addRQRec(">sync");
queuedRequests.add(request);
}
}
|
/*
* Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved.
*/
package de.hybris.platform.integrationservices.model.impl;
import de.hybris.platform.core.model.ItemModel;
import de.hybris.platform.integrationservices.model.AttributeSettableChecker;
import de.hybris.platform.integrationservices.model.TypeAttributeDescriptor;
/**
* An attribute settable checker that always returns {@code false}.
*/
public class NullAttributeSettableChecker implements AttributeSettableChecker
{
@Override
public boolean isSettable(final ItemModel item, final TypeAttributeDescriptor attribute)
{
return false;
}
}
|
package de.madcyph3r.materialnavigationdrawer.activity;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.LinkedList;
import java.util.List;
import de.madcyph3r.materialnavigationdrawer.MaterialNavigationDrawer;
import de.madcyph3r.materialnavigationdrawer.R;
import de.madcyph3r.materialnavigationdrawer.head.MaterialHeadItem;
import de.madcyph3r.materialnavigationdrawer.listener.MaterialHeadItemChangeListener;
import de.madcyph3r.materialnavigationdrawer.listener.MaterialSectionOnClickListener;
import de.madcyph3r.materialnavigationdrawer.menu.MaterialMenu;
import de.madcyph3r.materialnavigationdrawer.menu.item.section.MaterialItemSection;
import de.madcyph3r.materialnavigationdrawer.menu.item.section.MaterialItemSectionOnClick;
@SuppressLint("InflateParams")
public abstract class MaterialNavHeadItemActivity<Fragment> extends MaterialNavigationDrawer implements MaterialHeadItem.OnHeadItemDataLoaded {
private int animationTransition;
// global vars view headItem
private ImageView headItemFirstPhoto;
private ImageView headItemSecondPhoto;
private ImageView headItemThirdPhoto;
private ImageView headItemBackground;
private TextView headItemTitle;
private TextView headItemSubTitle;
private ImageView headItemBackgroundSwitcher;
private ImageButton headItemButtonSwitcher;
private LinearLayout headItemBackgroundGradientLL;
// global vars headItem
private List<MaterialHeadItem> headItemManager;
private MaterialHeadItemChangeListener headItemChangedListener;
private MaterialMenu switcherExtraMenu;
private boolean beforeOtherHeadItems;
private boolean headItemSwitchShowForce;
private boolean headItemSwitcherOpen = false;
private Drawable headItemBackgroundGradient;
private boolean staticHeadItemBackground = false;
private int headItemTitleColor;
private int headItemSubTitleColor;
private MaterialNavHeadItemActivity materialNavHeadItemActivity;
@Override
/**
* Do not Override this method!!!
* Use init() instead, see example app
*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
materialNavHeadItemActivity = this;
// init headItems
initHeadItemVars();
// init headItem listeners
// set listener without sound. sound is called in the own listener
headItemFirstPhoto.setSoundEffectsEnabled(false);
headItemFirstPhoto.setOnClickListener(headItemFirstOnClickListener);
headItemBackground.setSoundEffectsEnabled(false);
headItemBackground.setOnClickListener(headItemBackgroundOnClickListener);
headItemSecondPhoto.setSoundEffectsEnabled(false);
headItemSecondPhoto.setOnClickListener(headItemSecondOnClickListener);
headItemThirdPhoto.setSoundEffectsEnabled(false);
headItemThirdPhoto.setOnClickListener(headItemThirdOnClickListener);
// init kitkat dependencies
Resources.Theme theme = this.getTheme();
initKitKatDependencies(theme);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
// DEVELOPER CALL TO INIT
init(savedInstanceState);
// load here header and menu
initHeaderAndMenu(savedInstanceState);
//afterInit();
afterInit(savedInstanceState);
}
protected void afterSetContentView() {
Resources.Theme theme = this.getTheme();
initThemeVars(theme);
// init views
initHeadViews();
}
protected void setContentView() {
if (belowToolbar)
setContentView(R.layout.activity_material_navigation_drawer_below_toolbar);
else
setContentView(R.layout.activity_material_navigation_drawer);
}
// init methods
@SuppressLint("LongLogTag")
private void initThemeVars(Resources.Theme theme) {
// init theme params
TypedValue typedValue = new TypedValue();
theme.resolveAttribute(R.attr.headItemStyle, typedValue, true);
// Values of the Account
TypedArray values = theme.obtainStyledAttributes(typedValue.resourceId, R.styleable.MaterialHeadItem);
headItemTitleColor = values.getColor(R.styleable.MaterialHeadItem_titleColor, 0x00FFFFFF);
headItemSubTitleColor = values.getColor(R.styleable.MaterialHeadItem_subTitleColor, 0x00FFFFFF);
headItemBackgroundGradient = values.getDrawable(R.styleable.MaterialHeadItem_backgroundGradient);
}
private void initHeadItemVars() {
headItemSwitchShowForce = false;
headItemManager = new LinkedList<>();
switcherExtraMenu = new MaterialMenu();
animationTransition = 500;
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@SuppressWarnings("deprecation")
private void initHeadViews() {
headItemTitle = (TextView) this.findViewById(R.id.current_head_item_title);
headItemTitle.setTextColor(headItemTitleColor);
headItemSubTitle = (TextView) this.findViewById(R.id.current_head_item_sub_title);
headItemSubTitle.setTextColor(headItemSubTitleColor);
headItemFirstPhoto = (ImageView) this.findViewById(R.id.current_head_item_photo);
headItemSecondPhoto = (ImageView) this.findViewById(R.id.second_head_item_photo);
headItemThirdPhoto = (ImageView) this.findViewById(R.id.third_head_item_photo);
headItemBackground = (ImageView) this.findViewById(R.id.current_back_item_background);
headItemBackgroundSwitcher = (ImageView) this.findViewById(R.id.background_switcher);
headItemButtonSwitcher = (ImageButton) this.findViewById(R.id.user_switcher);
headItemBackgroundGradientLL = (LinearLayout) this.findViewById(R.id.background_gradient);
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
headItemBackgroundGradientLL.setBackgroundDrawable(headItemBackgroundGradient);
} else {
headItemBackgroundGradientLL.setBackground(headItemBackgroundGradient);
}
}
private void initKitKatDependencies(Resources.Theme theme) {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT && kitkatTraslucentStatusbar) {
RelativeLayout.LayoutParams photoParams = (RelativeLayout.LayoutParams) headItemFirstPhoto.getLayoutParams();
photoParams.setMargins((int) (16 * displayDensity), resources.getDimensionPixelSize(R.dimen.traslucentPhotoMarginTop), 0, 0);
headItemFirstPhoto.setLayoutParams(photoParams);
}
}
protected void initDrawerPrivateType(int width) {
int heightHeader = 0;
if (headerDPHeight == 0)
heightHeader = (9 * width) / 16;
else {
Resources r = getResources();
heightHeader = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, headerDPHeight, r.getDisplayMetrics());
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
if (!belowToolbar)
heightHeader += (int) (24 * displayDensity);
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT && kitkatTraslucentStatusbar)
if (!belowToolbar)
heightHeader += (int) (25 * displayDensity);
headItemBackground.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, heightHeader));
headItemBackgroundSwitcher.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, heightHeader));
}
private void initHeaderAndMenu(Bundle savedInstanceState) {
// init headitem views
if (headItemManager.size() > 0) {
//currentHeadItem = headItemManager.get(0);
notifyHeadItemsDataChanged();
} else {
throw new RuntimeException("No head item");
}
if (headItemManager.get(0).getMenu() != null) {
MaterialMenu menu = headItemManager.get(0).getMenu();
loadMenu(menu);
// load fragment on start from menu
if (isLoadFragmentOnStartFromMenu()) {
loadStartFragmentFromMenu(menu, "isLoadFragmentOnStartFromMenu is true, but the menu has no MaterialItemSectionFragment. Add one MaterialItemSectionFragment or set isLoadFragmentOnStartFromMenu to false and set your own fragment");
}
}
}
private void loadHeadItemSwitcherMenu(MaterialMenu menu) {
loadMenu(menu);
}
private int getHeadItemNumber(MaterialHeadItem headItem) {
return headItemManager.indexOf(headItem);
}
private MaterialHeadItem findHeadItemNumber(int number) {
for (MaterialHeadItem headItem : headItemManager)
if (getHeadItemNumber(headItem) == number)
return headItem;
return null;
}
// change the headItem1 with headItem 2 in the headItemManager list
private void changeHeadItems(MaterialHeadItem headItem1, MaterialHeadItem headItem2) {
int index1 = headItemManager.indexOf(headItem1);
int index2 = headItemManager.indexOf(headItem2);
MaterialHeadItem headItemTmp = headItemManager.get(index1);
headItemManager.set(index1, headItem2);
headItemManager.set(index2, headItemTmp);
}
private void switchHeadItemsList(MaterialHeadItem oldHeadItem, MaterialHeadItem newFirstHeadItem) {
// change button back
headItemButtonSwitcher.setImageResource(R.drawable.ic_arrow_drop_down_white_24dp);
headItemSwitcherOpen = false;
changeHeadItems(oldHeadItem, newFirstHeadItem);
// load new first head item information
notifyHeadItemDataChangedSwitch();
if (newFirstHeadItem.getMenu() != null && newFirstHeadItem.getMenu().getItems() != null && newFirstHeadItem.getMenu().getItems().size() > 0) {
MaterialMenu menu = newFirstHeadItem.getMenu();
//MaterialMenu tmpMenu = currentMenu;
//loadMenu(menu);
// load fragment on headitem change
if (menu != currentMenu) {
loadMenu(menu);
sectionFragmentLastBackPatternList.clear();
if (newFirstHeadItem.isLoadFragmentOnChanged()) {
loadStartFragmentFromMenu(menu, "isLoadFragmentOnChanged is true, but the menu has no" +
" MaterialItemSectionFragment. Add one MaterialItemSectionFragment or set" +
" isLoadFragmentOnStartFromMenu to false and set your own fragment");
} else if (currentMenu.getItems().contains(getCurrentSectionFragment())) {
getCurrentSectionFragment().select();
}
} else if (currentMenu.getItems().contains(getCurrentSectionFragment())) {
getCurrentSectionFragment().select();
}
if (headItemManager.get(0).isCloseDrawerOnChanged() && !deviceSupportMultiPane()) {
drawerLayout.closeDrawer(drawerViewGroup);
}
}
}
private void switchHeadItemsIcon(final MaterialHeadItem newFirstHeadItem, boolean animation) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH && animation) {
// change with animation
switchHeadItemsIconApi14(newFirstHeadItem);
} else {
//change no animation
changeHeadItems(headItemManager.get(0), newFirstHeadItem);
notifyHeadItemsDataChanged();
if (newFirstHeadItem.getMenu() != null && newFirstHeadItem.getMenu().getItems() != null && newFirstHeadItem.getMenu().getItems().size() > 0) {
MaterialMenu menu = newFirstHeadItem.getMenu();
//MaterialMenu tmpMenu = currentMenu;
// load fragment on headitem change
if (menu != currentMenu) {
loadMenu(menu);
sectionFragmentLastBackPatternList.clear();
if (newFirstHeadItem.isLoadFragmentOnChanged()) {
loadStartFragmentFromMenu(menu, "isLoadFragmentOnChanged is true, but the menu has no" +
" MaterialItemSectionFragment. Add one MaterialItemSectionFragment or set" +
" isLoadFragmentOnStartFromMenu to false and set your own fragment");
} else if (currentMenu.getItems().contains(getCurrentSectionFragment())) {
getCurrentSectionFragment().select();
}
} else if (currentMenu.getItems().contains(getCurrentSectionFragment())) {
getCurrentSectionFragment().select();
}
if (headItemManager.get(0).isCloseDrawerOnChanged() && !deviceSupportMultiPane()) {
drawerLayout.closeDrawer(drawerViewGroup);
}
}
// set switcher button to default
headItemButtonSwitcher.setImageResource(R.drawable.ic_arrow_drop_down_white_24dp);
headItemSwitcherOpen = false;
}
}
@TargetApi(14)
private void switchHeadItemsIconApi14(final MaterialHeadItem newFirstHeadItem) {
final ImageView floatingPhotoImage = new ImageView(this);
Rect startingRect = new Rect();
Rect finalRect = new Rect();
Point offsetHover = new Point();
// 64dp primary user image / 40dp other user image = 1.6 scale
float finalScale = 1.6f;
// get right statusbar height
final int statusBarHeight;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT || (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT && !kitkatTraslucentStatusbar)) {
statusBarHeight = (int) (25 * displayDensity);
} else {
statusBarHeight = 0;
}
// get clicked headItem
ImageView headItemPhotoClicked;
if (getHeadItemNumber(newFirstHeadItem) == MaterialHeadItem.SECOND_HEADITEM) {
headItemPhotoClicked = headItemSecondPhoto;
} else { // must be head item 3
headItemPhotoClicked = headItemThirdPhoto;
}
headItemPhotoClicked.getGlobalVisibleRect(startingRect, offsetHover);
floatingPhotoImage.setImageDrawable(headItemPhotoClicked.getDrawable());
// add floating image, this image will get moved and animated
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(headItemPhotoClicked.getWidth(), headItemPhotoClicked.getHeight());
params.setMargins(offsetHover.x, offsetHover.y - statusBarHeight, 0, 0);
drawerViewGroup.addView(floatingPhotoImage, params);
// get the drawable photo from the first headItem
headItemPhotoClicked.setImageDrawable(headItemManager.get(0).getPhoto());
// need for headItemBackground switch
headItemBackgroundSwitcher.setImageDrawable(newFirstHeadItem.getBackground());
headItemFirstPhoto.getGlobalVisibleRect(finalRect);
//calculate offset for the move
int offset = (((finalRect.bottom - finalRect.top) - (startingRect.bottom - finalRect.top)) / 2);
finalRect.offset(offset, offset - statusBarHeight);
startingRect.offset(0, -statusBarHeight);
// generate animator set
AnimatorSet set = new AnimatorSet();
set
// si ingrandisce l'immagine e la si sposta a sinistra.
.play(ObjectAnimator.ofFloat(floatingPhotoImage, View.X, startingRect.left, finalRect.left))
.with(ObjectAnimator.ofFloat(floatingPhotoImage, View.Y, headItemPhotoClicked.getTop(), headItemFirstPhoto.getTop() + offset))
.with(ObjectAnimator.ofFloat(floatingPhotoImage, View.SCALE_X, 1f, finalScale))
.with(ObjectAnimator.ofFloat(floatingPhotoImage, View.SCALE_Y, 1f, finalScale))
.with(ObjectAnimator.ofFloat(headItemFirstPhoto, View.ALPHA, 1f, 0f))
.with(ObjectAnimator.ofFloat(headItemBackground, View.ALPHA, 1f, 0f))
.with(ObjectAnimator.ofFloat(headItemPhotoClicked, View.SCALE_X, 0f, 1f))
.with(ObjectAnimator.ofFloat(headItemPhotoClicked, View.SCALE_Y, 0f, 1f));
set.setDuration(animationTransition);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
@SuppressLint("NewApi")
@Override
public void onAnimationEnd(Animator animation) {
((View) headItemFirstPhoto).setAlpha(1);
setFirstHeadItemPhoto(newFirstHeadItem.getPhoto());
// remove floating image after animation
drawerViewGroup.removeView(floatingPhotoImage);
// set title and subtitle
setHeadItemTitle(newFirstHeadItem.getTitle());
setHeadItemSubTitle(newFirstHeadItem.getSubTitle());
System.out.println();
// show new background
if (!staticHeadItemBackground && newFirstHeadItem.getBackground() != null)
setHeadItemBackground(newFirstHeadItem.getBackground());
((View) headItemBackground).setAlpha(1);
// switch old and new headitem in the manager list
changeHeadItems(headItemManager.get(0), newFirstHeadItem);
// load head item menu
if (newFirstHeadItem.getMenu() != null && newFirstHeadItem.getMenu().getItems() != null && newFirstHeadItem.getMenu().getItems().size() > 0) {
MaterialMenu menu = newFirstHeadItem.getMenu();
//MaterialMenu tmpMenu = currentMenu;
//loadMenu(menu);
// load fragment on headitem change
if (menu != currentMenu) {
loadMenu(menu);
sectionFragmentLastBackPatternList.clear();
if (newFirstHeadItem.isLoadFragmentOnChanged()) {
loadStartFragmentFromMenu(menu, "isLoadFragmentOnChanged is true, but the menu has no" +
" MaterialItemSectionFragment. Add one MaterialItemSectionFragment or set" +
" isLoadFragmentOnStartFromMenu to false and set your own fragment");
} else if (currentMenu.getItems().contains(getCurrentSectionFragment())) {
getCurrentSectionFragment().select();
}
} else if (currentMenu.getItems().contains(getCurrentSectionFragment())) {
getCurrentSectionFragment().select();
}
headItemButtonSwitcher.setImageResource(R.drawable.ic_arrow_drop_down_white_24dp);
headItemSwitcherOpen = false;
if (headItemManager.get(0).isCloseDrawerOnChanged() && !deviceSupportMultiPane()) {
drawerLayout.closeDrawer(drawerViewGroup);
}
}
}
@Override
public void onAnimationCancel(Animator animation) {
onAnimationEnd(animation);
}
});
set.start();
}
private void recycleHeadItem() {
for (MaterialHeadItem headItem : headItemManager) {
headItem.recycleDrawable();
}
}
public void removeHeadItem(MaterialHeadItem headItem) {
removeHeadItem(headItemManager.indexOf(headItem));
}
public void removeHeadItem(int location) {
if (headItemManager.size() == 1)
throw new RuntimeException("You can't remove all head items.");
headItemManager.remove(location);
if (headItemManager.size() > 3 || headItemSwitchShowForce) {
headItemButtonSwitcher.setImageResource(R.drawable.ic_arrow_drop_down_white_24dp);
headItemButtonSwitcher.setVisibility(View.VISIBLE);
} else {
headItemButtonSwitcher.setVisibility(View.GONE);
}
notifyHeadItemsDataChanged();
}
public void addHeadItem(MaterialHeadItem headItem) {
addHeadItem(headItem, false);
}
public void addHeadItem(MaterialHeadItem headItem, boolean notify) {
headItem.setHeadItemDataLoadedListener(this);
headItemManager.add(headItem);
if (headItemManager.size() == 4) {
headItemButtonSwitcher.setOnClickListener(headItemSwitcher);
}
if (headItemManager.size() > 3 || headItemSwitchShowForce) {
headItemButtonSwitcher.setImageResource(R.drawable.ic_arrow_drop_down_white_24dp);
headItemButtonSwitcher.setVisibility(View.VISIBLE);
} else {
headItemButtonSwitcher.setVisibility(View.GONE);
}
if (notify)
notifyHeadItemsDataChanged();
}
private void notifyHeadItemDataChangedSwitch() {
this.setFirstHeadItemPhoto(headItemManager.get(0).getPhoto());
if (!staticHeadItemBackground && headItemManager.get(0).getBackground() != null)
this.setHeadItemBackground(headItemManager.get(0).getBackground());
this.setHeadItemTitle(headItemManager.get(0).getTitle());
this.setHeadItemSubTitle(headItemManager.get(0).getSubTitle());
}
/**
* Reload Application data from HeadItem Information
*/
public void notifyHeadItemsDataChanged() {
if (headItemManager.size() >= 3) {
this.setThirdHeadItemPhoto(findHeadItemNumber(MaterialHeadItem.THIRD_HEADITEM).getPhoto());
this.setSecondHeadItemPhoto(findHeadItemNumber(MaterialHeadItem.SECOND_HEADITEM).getPhoto());
this.setFirstHeadItemPhoto(headItemManager.get(0).getPhoto());
if (!staticHeadItemBackground && headItemManager.get(0).getBackground() != null)
this.setHeadItemBackground(headItemManager.get(0).getBackground());
this.setHeadItemTitle(headItemManager.get(0).getTitle());
this.setHeadItemSubTitle(headItemManager.get(0).getSubTitle());
} else if (headItemManager.size() == 2) {
this.setThirdHeadItemPhoto(null);
this.setSecondHeadItemPhoto(findHeadItemNumber(MaterialHeadItem.SECOND_HEADITEM).getPhoto());
this.setFirstHeadItemPhoto(headItemManager.get(0).getPhoto());
if (!staticHeadItemBackground && headItemManager.get(0).getBackground() != null)
this.setHeadItemBackground(headItemManager.get(0).getBackground());
this.setHeadItemTitle(headItemManager.get(0).getTitle());
this.setHeadItemSubTitle(headItemManager.get(0).getSubTitle());
} else if (headItemManager.size() == 1) {
this.setThirdHeadItemPhoto(null);
this.setSecondHeadItemPhoto(null);
this.setFirstHeadItemPhoto(headItemManager.get(0).getPhoto());
if (!staticHeadItemBackground && headItemManager.get(0).getBackground() != null)
this.setHeadItemBackground(headItemManager.get(0).getBackground());
this.setHeadItemTitle(headItemManager.get(0).getTitle());
this.setHeadItemSubTitle(headItemManager.get(0).getSubTitle());
}
}
@Override
public abstract void init(Bundle savedInstanceState);
/**
* listener Head Item Listener
*/
private View.OnClickListener headItemBackgroundOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!drawerTouchLocked) {
if (headItemManager.get(0).getBackgroundOnClickListener() != null) {
headItemBackground.setSoundEffectsEnabled(true);
v.playSoundEffect(android.view.SoundEffectConstants.CLICK);
headItemFirstPhoto.setSoundEffectsEnabled(false);
headItemManager.get(0).getBackgroundOnClickListener().onClick(headItemManager.get(0));
if (headItemManager.get(0).isCloseDrawerBackgroundOnClick()) {
drawerLayout.closeDrawer(drawerViewGroup);
}
}
}
}
};
private View.OnClickListener headItemFirstOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!drawerTouchLocked) {
if (headItemManager.get(0).getAvatarOnClickListener() != null) {
headItemFirstPhoto.setSoundEffectsEnabled(true);
v.playSoundEffect(android.view.SoundEffectConstants.CLICK);
headItemFirstPhoto.setSoundEffectsEnabled(false);
headItemManager.get(0).getAvatarOnClickListener().onClick(headItemManager.get(0));
if (headItemManager.get(0).isCloseDrawerAvatarOnClick() && !deviceSupportMultiPane()) {
drawerLayout.closeDrawer(drawerViewGroup);
}
}
}
}
};
private View.OnClickListener headItemSecondOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!drawerTouchLocked) {
MaterialHeadItem headItem = findHeadItemNumber(MaterialHeadItem.SECOND_HEADITEM);
if (headItem != null) {
headItemSecondPhoto.setSoundEffectsEnabled(true);
v.playSoundEffect(android.view.SoundEffectConstants.CLICK);
headItemSecondPhoto.setSoundEffectsEnabled(false);
if (headItemChangedListener != null)
headItemChangedListener.onBeforeChangeHeadItem(headItem);
switchHeadItemsIcon(headItem, true);
if (headItemChangedListener != null)
headItemChangedListener.onAfterChangeHeadItem(headItem);
} else {
if (headItemManager.get(0).getBackgroundOnClickListener() != null) {
headItemSecondPhoto.setSoundEffectsEnabled(true);
v.playSoundEffect(android.view.SoundEffectConstants.CLICK);
headItemSecondPhoto.setSoundEffectsEnabled(false);
headItemManager.get(0).getBackgroundOnClickListener().onClick(headItemManager.get(0));
if (headItemManager.get(0).isCloseDrawerBackgroundOnClick() && !deviceSupportMultiPane()) {
drawerLayout.closeDrawer(drawerViewGroup);
}
}
}
}
}
};
private View.OnClickListener headItemThirdOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!drawerTouchLocked) {
MaterialHeadItem headItem = findHeadItemNumber(MaterialHeadItem.THIRD_HEADITEM);
if (headItem != null) {
headItemThirdPhoto.setSoundEffectsEnabled(true);
v.playSoundEffect(android.view.SoundEffectConstants.CLICK);
headItemThirdPhoto.setSoundEffectsEnabled(false);
if (headItemChangedListener != null)
headItemChangedListener.onBeforeChangeHeadItem(headItem);
switchHeadItemsIcon(headItem, true);
if (headItemChangedListener != null)
headItemChangedListener.onAfterChangeHeadItem(headItem);
} else {// if there is no second account user clicked for open it
//accountListener.onAccountOpening(currentAccount);
if (headItemManager.get(0).getBackgroundOnClickListener() != null) {
headItemThirdPhoto.setSoundEffectsEnabled(true);
v.playSoundEffect(android.view.SoundEffectConstants.CLICK);
headItemThirdPhoto.setSoundEffectsEnabled(false);
headItemManager.get(0).getBackgroundOnClickListener().onClick(headItemManager.get(0));
if (headItemManager.get(0).isCloseDrawerBackgroundOnClick() && !deviceSupportMultiPane()) {
drawerLayout.closeDrawer(drawerViewGroup);
}
}
}
}
}
};
private View.OnClickListener headItemSwitcher = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!headItemSwitcherOpen) {
// create menu with accounts in the headManagerList >= 3 (starting 3)
headItemSwitcherOpen = true;
headItemButtonSwitcher.setImageResource(R.drawable.ic_arrow_drop_up_white_24dp);
MaterialMenu menu = new MaterialMenu();
for (int i = 3; i < headItemManager.size(); i++) {
final MaterialHeadItem headItem = headItemManager.get(i);
MaterialItemSectionOnClick section = new MaterialItemSectionOnClick(materialNavHeadItemActivity, headItem.getTitle(), headItem.getPhoto());
section.setOnSectionClickListener(new MaterialSectionOnClickListener() {
@Override
public void onClick(MaterialItemSection section, View view) {
switchHeadItemsList(headItemManager.get(0), headItem);
}
});
menu.add(section);
}
// add extra menu
if (beforeOtherHeadItems)
menu.getItems().addAll(0, switcherExtraMenu.getItems());
else
menu.getItems().addAll(switcherExtraMenu.getItems());
//currentMenu = menu;
loadHeadItemSwitcherMenu(menu);
} else {
// load old menu
headItemButtonSwitcher.setImageResource(R.drawable.ic_arrow_drop_down_white_24dp);
headItemSwitcherOpen = false;
//currentMenu = getCurrentHeadItem().getMenu();
loadMenu(getCurrentHeadItem().getMenu());
}
}
};
@Override
protected void onDestroy() {
super.onDestroy();
// recycle bitmaps
recycleHeadItem();
}
/* @Override
protected void onSaveInstanceState(Bundle outState) {
}
*/
/**
* states in minsecond that the drawer will need to wait before jumping into another view or intent to start
*
* @return in minseconds
*/
protected int getSmoothPauseFromSelectingItem() {
return 200;
}
@Override
public void onUserPhotoLoaded(MaterialHeadItem headItem) {
if (getHeadItemNumber(headItem) <= MaterialHeadItem.THIRD_HEADITEM)
notifyHeadItemsDataChanged();
}
@Override
public void onBackgroundLoaded(MaterialHeadItem headItem) {
if (getHeadItemNumber(headItem) <= MaterialHeadItem.THIRD_HEADITEM)
notifyHeadItemsDataChanged();
}
// getter and setter
public MaterialHeadItem getCurrentHeadItem() {
return headItemManager.get(0);
}
public MaterialMenu getCurrentMenu() {
return currentMenu;
}
public void setHeadItemOnChangeListener(MaterialHeadItemChangeListener listener) {
this.headItemChangedListener = listener;
}
public List<MaterialHeadItem> getHeadItemManager() {
return headItemManager;
}
public void setSwitcherExtraMenu(MaterialMenu switcherExtraMenu, boolean beforeOtherHeadItems) {
this.switcherExtraMenu = switcherExtraMenu;
this.beforeOtherHeadItems = beforeOtherHeadItems;
}
public boolean isSwitchShowForce() {
return headItemSwitchShowForce;
}
public void setSwitchShowForce(boolean headItemSwitchShowForce) {
this.headItemSwitchShowForce = headItemSwitchShowForce;
if (headItemSwitchShowForce) {
headItemButtonSwitcher.setImageResource(R.drawable.ic_arrow_drop_down_white_24dp);
headItemButtonSwitcher.setVisibility(View.VISIBLE);
headItemButtonSwitcher.setOnClickListener(headItemSwitcher);
} else {
headItemButtonSwitcher.setVisibility(View.GONE);
}
}
public void setHeadItemBackground(Drawable background) {
setHeadItemBackground(background, false);
}
public void setHeadItemBackground(Drawable background, boolean staticBackground) {
staticHeadItemBackground = staticBackground;
this.headItemBackground.setImageDrawable(background);
}
public void setHeadItemSubTitle(String email) {
headItemSubTitle.setText(email);
}
public void setHeadItemTitle(String headItemTitle) {
this.headItemTitle.setText(headItemTitle);
}
public void setFirstHeadItemPhoto(Drawable photo) {
headItemFirstPhoto.setImageDrawable(photo);
}
public void setSecondHeadItemPhoto(Drawable photo) {
headItemSecondPhoto.setImageDrawable(photo);
}
public void setThirdHeadItemPhoto(Drawable photo) {
headItemThirdPhoto.setImageDrawable(photo);
}
public int getAnimationTransition() {
return animationTransition;
}
public void setAnimationTransition(int animationTransition) {
this.animationTransition = animationTransition;
}
}
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * 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. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|util
package|;
end_package
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|File
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|FileInputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|FileOutputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|FilenameFilter
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|IOException
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|InputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|OutputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|nio
operator|.
name|file
operator|.
name|Files
import|;
end_import
begin_import
import|import
name|java
operator|.
name|nio
operator|.
name|file
operator|.
name|Path
import|;
end_import
begin_import
import|import
name|java
operator|.
name|nio
operator|.
name|file
operator|.
name|StandardCopyOption
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|ArrayList
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|List
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Stack
import|;
end_import
begin_comment
comment|/** * Collection of File and Folder utility methods. */
end_comment
begin_class
specifier|public
specifier|final
class|class
name|IOHelper
block|{
specifier|protected
specifier|static
specifier|final
name|int
name|MAX_DIR_NAME_LENGTH
decl_stmt|;
specifier|protected
specifier|static
specifier|final
name|int
name|MAX_FILE_NAME_LENGTH
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|int
name|DEFAULT_BUFFER_SIZE
init|=
literal|4096
decl_stmt|;
specifier|private
name|IOHelper
parameter_list|()
block|{ }
specifier|public
specifier|static
name|String
name|getDefaultDataDirectory
parameter_list|()
block|{
return|return
name|getDefaultDirectoryPrefix
argument_list|()
operator|+
literal|"activemq-data"
return|;
block|}
specifier|public
specifier|static
name|String
name|getDefaultStoreDirectory
parameter_list|()
block|{
return|return
name|getDefaultDirectoryPrefix
argument_list|()
operator|+
literal|"amqstore"
return|;
block|}
comment|/** * Allows a system property to be used to overload the default data * directory which can be useful for forcing the test cases to use a target/ * prefix */
specifier|public
specifier|static
name|String
name|getDefaultDirectoryPrefix
parameter_list|()
block|{
try|try
block|{
return|return
name|System
operator|.
name|getProperty
argument_list|(
literal|"org.apache.activemq.default.directory.prefix"
argument_list|,
literal|""
argument_list|)
return|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
return|return
literal|""
return|;
block|}
block|}
comment|/** * Converts any string into a string that is safe to use as a file name. The * result will only include ascii characters and numbers, and the "-","_", * and "." characters. * * @param name * @return safe name of the directory */
specifier|public
specifier|static
name|String
name|toFileSystemDirectorySafeName
parameter_list|(
name|String
name|name
parameter_list|)
block|{
return|return
name|toFileSystemSafeName
argument_list|(
name|name
argument_list|,
literal|true
argument_list|,
name|MAX_DIR_NAME_LENGTH
argument_list|)
return|;
block|}
specifier|public
specifier|static
name|String
name|toFileSystemSafeName
parameter_list|(
name|String
name|name
parameter_list|)
block|{
return|return
name|toFileSystemSafeName
argument_list|(
name|name
argument_list|,
literal|false
argument_list|,
name|MAX_FILE_NAME_LENGTH
argument_list|)
return|;
block|}
comment|/** * Converts any string into a string that is safe to use as a file name. The * result will only include ascii characters and numbers, and the "-","_", * and "." characters. * * @param name * @param dirSeparators * @param maxFileLength * @return file system safe name */
specifier|public
specifier|static
name|String
name|toFileSystemSafeName
parameter_list|(
name|String
name|name
parameter_list|,
name|boolean
name|dirSeparators
parameter_list|,
name|int
name|maxFileLength
parameter_list|)
block|{
name|int
name|size
init|=
name|name
operator|.
name|length
argument_list|()
decl_stmt|;
name|StringBuffer
name|rc
init|=
operator|new
name|StringBuffer
argument_list|(
name|size
operator|*
literal|2
argument_list|)
decl_stmt|;
for|for
control|(
name|int
name|i
init|=
literal|0
init|;
name|i
operator|<
name|size
condition|;
name|i
operator|++
control|)
block|{
name|char
name|c
init|=
name|name
operator|.
name|charAt
argument_list|(
name|i
argument_list|)
decl_stmt|;
name|boolean
name|valid
init|=
name|c
operator|>=
literal|'a'
operator|&&
name|c
operator|<=
literal|'z'
decl_stmt|;
name|valid
operator|=
name|valid
operator|||
operator|(
name|c
operator|>=
literal|'A'
operator|&&
name|c
operator|<=
literal|'Z'
operator|)
expr_stmt|;
name|valid
operator|=
name|valid
operator|||
operator|(
name|c
operator|>=
literal|'0'
operator|&&
name|c
operator|<=
literal|'9'
operator|)
expr_stmt|;
name|valid
operator|=
name|valid
operator|||
operator|(
name|c
operator|==
literal|'_'
operator|)
operator|||
operator|(
name|c
operator|==
literal|'-'
operator|)
operator|||
operator|(
name|c
operator|==
literal|'.'
operator|)
operator|||
operator|(
name|c
operator|==
literal|'#'
operator|)
operator|||
operator|(
name|dirSeparators
operator|&&
operator|(
operator|(
name|c
operator|==
literal|'/'
operator|)
operator|||
operator|(
name|c
operator|==
literal|'\\'
operator|)
operator|)
operator|)
expr_stmt|;
if|if
condition|(
name|valid
condition|)
block|{
name|rc
operator|.
name|append
argument_list|(
name|c
argument_list|)
expr_stmt|;
block|}
else|else
block|{
comment|// Encode the character using hex notation
name|rc
operator|.
name|append
argument_list|(
literal|'#'
argument_list|)
expr_stmt|;
name|rc
operator|.
name|append
argument_list|(
name|HexSupport
operator|.
name|toHexFromInt
argument_list|(
name|c
argument_list|,
literal|true
argument_list|)
argument_list|)
expr_stmt|;
block|}
block|}
name|String
name|result
init|=
name|rc
operator|.
name|toString
argument_list|()
decl_stmt|;
if|if
condition|(
name|result
operator|.
name|length
argument_list|()
operator|>
name|maxFileLength
condition|)
block|{
name|result
operator|=
name|result
operator|.
name|substring
argument_list|(
name|result
operator|.
name|length
argument_list|()
operator|-
name|maxFileLength
argument_list|,
name|result
operator|.
name|length
argument_list|()
argument_list|)
expr_stmt|;
block|}
return|return
name|result
return|;
block|}
specifier|public
specifier|static
name|boolean
name|delete
parameter_list|(
name|File
name|top
parameter_list|)
block|{
name|boolean
name|result
init|=
literal|true
decl_stmt|;
name|Stack
argument_list|<
name|File
argument_list|>
name|files
init|=
operator|new
name|Stack
argument_list|<
name|File
argument_list|>
argument_list|()
decl_stmt|;
comment|// Add file to the stack to be processed...
name|files
operator|.
name|push
argument_list|(
name|top
argument_list|)
expr_stmt|;
comment|// Process all files until none remain...
while|while
condition|(
operator|!
name|files
operator|.
name|isEmpty
argument_list|()
condition|)
block|{
name|File
name|file
init|=
name|files
operator|.
name|pop
argument_list|()
decl_stmt|;
if|if
condition|(
name|file
operator|.
name|isDirectory
argument_list|()
condition|)
block|{
name|File
name|list
index|[]
init|=
name|file
operator|.
name|listFiles
argument_list|()
decl_stmt|;
if|if
condition|(
name|list
operator|==
literal|null
operator|||
name|list
operator|.
name|length
operator|==
literal|0
condition|)
block|{
comment|// The current directory contains no entries...
comment|// delete directory and continue...
name|result
operator|&=
name|file
operator|.
name|delete
argument_list|()
expr_stmt|;
block|}
else|else
block|{
comment|// Add back the directory since it is not empty....
comment|// and when we process it again it will be empty and can be
comment|// deleted safely...
name|files
operator|.
name|push
argument_list|(
name|file
argument_list|)
expr_stmt|;
for|for
control|(
name|File
name|dirFile
range|:
name|list
control|)
block|{
if|if
condition|(
name|dirFile
operator|.
name|isDirectory
argument_list|()
condition|)
block|{
comment|// Place the directory on the stack...
name|files
operator|.
name|push
argument_list|(
name|dirFile
argument_list|)
expr_stmt|;
block|}
else|else
block|{
comment|// This is a simple file, delete it...
name|result
operator|&=
name|dirFile
operator|.
name|delete
argument_list|()
expr_stmt|;
block|}
block|}
block|}
block|}
else|else
block|{
comment|// This is a simple file, delete it...
name|result
operator|&=
name|file
operator|.
name|delete
argument_list|()
expr_stmt|;
block|}
block|}
return|return
name|result
return|;
block|}
specifier|public
specifier|static
name|boolean
name|deleteFile
parameter_list|(
name|File
name|fileToDelete
parameter_list|)
block|{
if|if
condition|(
name|fileToDelete
operator|==
literal|null
operator|||
operator|!
name|fileToDelete
operator|.
name|exists
argument_list|()
condition|)
block|{
return|return
literal|true
return|;
block|}
name|boolean
name|result
init|=
name|deleteChildren
argument_list|(
name|fileToDelete
argument_list|)
decl_stmt|;
name|result
operator|&=
name|fileToDelete
operator|.
name|delete
argument_list|()
expr_stmt|;
return|return
name|result
return|;
block|}
specifier|public
specifier|static
name|boolean
name|deleteChildren
parameter_list|(
name|File
name|parent
parameter_list|)
block|{
if|if
condition|(
name|parent
operator|==
literal|null
operator|||
operator|!
name|parent
operator|.
name|exists
argument_list|()
condition|)
block|{
return|return
literal|false
return|;
block|}
name|boolean
name|result
init|=
literal|true
decl_stmt|;
if|if
condition|(
name|parent
operator|.
name|isDirectory
argument_list|()
condition|)
block|{
name|File
index|[]
name|files
init|=
name|parent
operator|.
name|listFiles
argument_list|()
decl_stmt|;
if|if
condition|(
name|files
operator|==
literal|null
condition|)
block|{
name|result
operator|=
literal|false
expr_stmt|;
block|}
else|else
block|{
for|for
control|(
name|int
name|i
init|=
literal|0
init|;
name|i
operator|<
name|files
operator|.
name|length
condition|;
name|i
operator|++
control|)
block|{
name|File
name|file
init|=
name|files
index|[
name|i
index|]
decl_stmt|;
if|if
condition|(
name|file
operator|.
name|getName
argument_list|()
operator|.
name|equals
argument_list|(
literal|"."
argument_list|)
operator|||
name|file
operator|.
name|getName
argument_list|()
operator|.
name|equals
argument_list|(
literal|".."
argument_list|)
condition|)
block|{
continue|continue;
block|}
if|if
condition|(
name|file
operator|.
name|isDirectory
argument_list|()
condition|)
block|{
name|result
operator|&=
name|deleteFile
argument_list|(
name|file
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|result
operator|&=
name|file
operator|.
name|delete
argument_list|()
expr_stmt|;
block|}
block|}
block|}
block|}
return|return
name|result
return|;
block|}
specifier|public
specifier|static
name|void
name|moveFile
parameter_list|(
name|File
name|src
parameter_list|,
name|File
name|targetDirectory
parameter_list|)
throws|throws
name|IOException
block|{
if|if
condition|(
operator|!
name|src
operator|.
name|renameTo
argument_list|(
operator|new
name|File
argument_list|(
name|targetDirectory
argument_list|,
name|src
operator|.
name|getName
argument_list|()
argument_list|)
argument_list|)
condition|)
block|{
comment|// If rename fails we must do a true deep copy instead.
name|Path
name|sourcePath
init|=
name|src
operator|.
name|toPath
argument_list|()
decl_stmt|;
name|Path
name|targetDirPath
init|=
name|targetDirectory
operator|.
name|toPath
argument_list|()
decl_stmt|;
try|try
block|{
name|Files
operator|.
name|move
argument_list|(
name|sourcePath
argument_list|,
name|targetDirPath
operator|.
name|resolve
argument_list|(
name|sourcePath
operator|.
name|getFileName
argument_list|()
argument_list|)
argument_list|,
name|StandardCopyOption
operator|.
name|REPLACE_EXISTING
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|IOException
name|ex
parameter_list|)
block|{
throw|throw
operator|new
name|IOException
argument_list|(
literal|"Failed to move "
operator|+
name|src
operator|+
literal|" to "
operator|+
name|targetDirectory
operator|+
literal|" - "
operator|+
name|ex
operator|.
name|getMessage
argument_list|()
argument_list|)
throw|;
block|}
block|}
block|}
specifier|public
specifier|static
name|void
name|moveFiles
parameter_list|(
name|File
name|srcDirectory
parameter_list|,
name|File
name|targetDirectory
parameter_list|,
name|FilenameFilter
name|filter
parameter_list|)
throws|throws
name|IOException
block|{
if|if
condition|(
operator|!
name|srcDirectory
operator|.
name|isDirectory
argument_list|()
condition|)
block|{
throw|throw
operator|new
name|IOException
argument_list|(
literal|"source is not a directory"
argument_list|)
throw|;
block|}
if|if
condition|(
name|targetDirectory
operator|.
name|exists
argument_list|()
operator|&&
operator|!
name|targetDirectory
operator|.
name|isDirectory
argument_list|()
condition|)
block|{
throw|throw
operator|new
name|IOException
argument_list|(
literal|"target exists and is not a directory"
argument_list|)
throw|;
block|}
else|else
block|{
name|mkdirs
argument_list|(
name|targetDirectory
argument_list|)
expr_stmt|;
block|}
name|List
argument_list|<
name|File
argument_list|>
name|filesToMove
init|=
operator|new
name|ArrayList
argument_list|<
name|File
argument_list|>
argument_list|()
decl_stmt|;
name|getFiles
argument_list|(
name|srcDirectory
argument_list|,
name|filesToMove
argument_list|,
name|filter
argument_list|)
expr_stmt|;
for|for
control|(
name|File
name|file
range|:
name|filesToMove
control|)
block|{
if|if
condition|(
operator|!
name|file
operator|.
name|isDirectory
argument_list|()
condition|)
block|{
name|moveFile
argument_list|(
name|file
argument_list|,
name|targetDirectory
argument_list|)
expr_stmt|;
block|}
block|}
block|}
specifier|public
specifier|static
name|void
name|copyFile
parameter_list|(
name|File
name|src
parameter_list|,
name|File
name|dest
parameter_list|)
throws|throws
name|IOException
block|{
name|copyFile
argument_list|(
name|src
argument_list|,
name|dest
argument_list|,
literal|null
argument_list|)
expr_stmt|;
block|}
specifier|public
specifier|static
name|void
name|copyFile
parameter_list|(
name|File
name|src
parameter_list|,
name|File
name|dest
parameter_list|,
name|FilenameFilter
name|filter
parameter_list|)
throws|throws
name|IOException
block|{
if|if
condition|(
name|src
operator|.
name|getCanonicalPath
argument_list|()
operator|.
name|equals
argument_list|(
name|dest
operator|.
name|getCanonicalPath
argument_list|()
argument_list|)
operator|==
literal|false
condition|)
block|{
if|if
condition|(
name|src
operator|.
name|isDirectory
argument_list|()
condition|)
block|{
name|mkdirs
argument_list|(
name|dest
argument_list|)
expr_stmt|;
name|List
argument_list|<
name|File
argument_list|>
name|list
init|=
name|getFiles
argument_list|(
name|src
argument_list|,
name|filter
argument_list|)
decl_stmt|;
for|for
control|(
name|File
name|f
range|:
name|list
control|)
block|{
if|if
condition|(
name|f
operator|.
name|isFile
argument_list|()
condition|)
block|{
name|File
name|target
init|=
operator|new
name|File
argument_list|(
name|getCopyParent
argument_list|(
name|src
argument_list|,
name|dest
argument_list|,
name|f
argument_list|)
argument_list|,
name|f
operator|.
name|getName
argument_list|()
argument_list|)
decl_stmt|;
name|copySingleFile
argument_list|(
name|f
argument_list|,
name|target
argument_list|)
expr_stmt|;
block|}
block|}
block|}
elseif|else
if|if
condition|(
name|dest
operator|.
name|isDirectory
argument_list|()
condition|)
block|{
name|mkdirs
argument_list|(
name|dest
argument_list|)
expr_stmt|;
name|File
name|target
init|=
operator|new
name|File
argument_list|(
name|dest
argument_list|,
name|src
operator|.
name|getName
argument_list|()
argument_list|)
decl_stmt|;
name|copySingleFile
argument_list|(
name|src
argument_list|,
name|target
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|copySingleFile
argument_list|(
name|src
argument_list|,
name|dest
argument_list|)
expr_stmt|;
block|}
block|}
block|}
specifier|static
name|File
name|getCopyParent
parameter_list|(
name|File
name|from
parameter_list|,
name|File
name|to
parameter_list|,
name|File
name|src
parameter_list|)
block|{
name|File
name|result
init|=
literal|null
decl_stmt|;
name|File
name|parent
init|=
name|src
operator|.
name|getParentFile
argument_list|()
decl_stmt|;
name|String
name|fromPath
init|=
name|from
operator|.
name|getAbsolutePath
argument_list|()
decl_stmt|;
if|if
condition|(
name|parent
operator|.
name|getAbsolutePath
argument_list|()
operator|.
name|equals
argument_list|(
name|fromPath
argument_list|)
condition|)
block|{
comment|// one level down
name|result
operator|=
name|to
expr_stmt|;
block|}
else|else
block|{
name|String
name|parentPath
init|=
name|parent
operator|.
name|getAbsolutePath
argument_list|()
decl_stmt|;
name|String
name|path
init|=
name|parentPath
operator|.
name|substring
argument_list|(
name|fromPath
operator|.
name|length
argument_list|()
argument_list|)
decl_stmt|;
name|result
operator|=
operator|new
name|File
argument_list|(
name|to
operator|.
name|getAbsolutePath
argument_list|()
operator|+
name|File
operator|.
name|separator
operator|+
name|path
argument_list|)
expr_stmt|;
block|}
return|return
name|result
return|;
block|}
specifier|static
name|List
argument_list|<
name|File
argument_list|>
name|getFiles
parameter_list|(
name|File
name|dir
parameter_list|,
name|FilenameFilter
name|filter
parameter_list|)
block|{
name|List
argument_list|<
name|File
argument_list|>
name|result
init|=
operator|new
name|ArrayList
argument_list|<
name|File
argument_list|>
argument_list|()
decl_stmt|;
name|getFiles
argument_list|(
name|dir
argument_list|,
name|result
argument_list|,
name|filter
argument_list|)
expr_stmt|;
return|return
name|result
return|;
block|}
specifier|static
name|void
name|getFiles
parameter_list|(
name|File
name|dir
parameter_list|,
name|List
argument_list|<
name|File
argument_list|>
name|list
parameter_list|,
name|FilenameFilter
name|filter
parameter_list|)
block|{
if|if
condition|(
operator|!
name|list
operator|.
name|contains
argument_list|(
name|dir
argument_list|)
condition|)
block|{
name|list
operator|.
name|add
argument_list|(
name|dir
argument_list|)
expr_stmt|;
name|String
index|[]
name|fileNames
init|=
name|dir
operator|.
name|list
argument_list|(
name|filter
argument_list|)
decl_stmt|;
for|for
control|(
name|int
name|i
init|=
literal|0
init|;
name|i
operator|<
name|fileNames
operator|.
name|length
condition|;
name|i
operator|++
control|)
block|{
name|File
name|f
init|=
operator|new
name|File
argument_list|(
name|dir
argument_list|,
name|fileNames
index|[
name|i
index|]
argument_list|)
decl_stmt|;
if|if
condition|(
name|f
operator|.
name|isFile
argument_list|()
condition|)
block|{
name|list
operator|.
name|add
argument_list|(
name|f
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|getFiles
argument_list|(
name|dir
argument_list|,
name|list
argument_list|,
name|filter
argument_list|)
expr_stmt|;
block|}
block|}
block|}
block|}
specifier|public
specifier|static
name|void
name|copySingleFile
parameter_list|(
name|File
name|src
parameter_list|,
name|File
name|dest
parameter_list|)
throws|throws
name|IOException
block|{
name|FileInputStream
name|fileSrc
init|=
operator|new
name|FileInputStream
argument_list|(
name|src
argument_list|)
decl_stmt|;
name|FileOutputStream
name|fileDest
init|=
operator|new
name|FileOutputStream
argument_list|(
name|dest
argument_list|)
decl_stmt|;
name|copyInputStream
argument_list|(
name|fileSrc
argument_list|,
name|fileDest
argument_list|)
expr_stmt|;
block|}
specifier|public
specifier|static
name|void
name|copyInputStream
parameter_list|(
name|InputStream
name|in
parameter_list|,
name|OutputStream
name|out
parameter_list|)
throws|throws
name|IOException
block|{
try|try
block|{
name|byte
index|[]
name|buffer
init|=
operator|new
name|byte
index|[
name|DEFAULT_BUFFER_SIZE
index|]
decl_stmt|;
name|int
name|len
init|=
name|in
operator|.
name|read
argument_list|(
name|buffer
argument_list|)
decl_stmt|;
while|while
condition|(
name|len
operator|>=
literal|0
condition|)
block|{
name|out
operator|.
name|write
argument_list|(
name|buffer
argument_list|,
literal|0
argument_list|,
name|len
argument_list|)
expr_stmt|;
name|len
operator|=
name|in
operator|.
name|read
argument_list|(
name|buffer
argument_list|)
expr_stmt|;
block|}
block|}
finally|finally
block|{
name|in
operator|.
name|close
argument_list|()
expr_stmt|;
name|out
operator|.
name|close
argument_list|()
expr_stmt|;
block|}
block|}
static|static
block|{
name|MAX_DIR_NAME_LENGTH
operator|=
name|Integer
operator|.
name|getInteger
argument_list|(
literal|"MaximumDirNameLength"
argument_list|,
literal|200
argument_list|)
expr_stmt|;
name|MAX_FILE_NAME_LENGTH
operator|=
name|Integer
operator|.
name|getInteger
argument_list|(
literal|"MaximumFileNameLength"
argument_list|,
literal|64
argument_list|)
expr_stmt|;
block|}
specifier|public
specifier|static
name|int
name|getMaxDirNameLength
parameter_list|()
block|{
return|return
name|MAX_DIR_NAME_LENGTH
return|;
block|}
specifier|public
specifier|static
name|int
name|getMaxFileNameLength
parameter_list|()
block|{
return|return
name|MAX_FILE_NAME_LENGTH
return|;
block|}
specifier|public
specifier|static
name|void
name|mkdirs
parameter_list|(
name|File
name|dir
parameter_list|)
throws|throws
name|IOException
block|{
if|if
condition|(
name|dir
operator|.
name|exists
argument_list|()
condition|)
block|{
if|if
condition|(
operator|!
name|dir
operator|.
name|isDirectory
argument_list|()
condition|)
block|{
throw|throw
operator|new
name|IOException
argument_list|(
literal|"Failed to create directory '"
operator|+
name|dir
operator|+
literal|"', regular file already existed with that name"
argument_list|)
throw|;
block|}
block|}
else|else
block|{
if|if
condition|(
operator|!
name|dir
operator|.
name|mkdirs
argument_list|()
condition|)
block|{
throw|throw
operator|new
name|IOException
argument_list|(
literal|"Failed to create directory '"
operator|+
name|dir
operator|+
literal|"'"
argument_list|)
throw|;
block|}
block|}
block|}
block|}
end_class
end_unit
|
package com.francescomabilia.model;
import com.francescomabilia.model.infrazione.Multa;
import com.francescomabilia.model.percorrimenti.Percorrimento;
import java.util.List;
/**
* Classe che definisce il gestore delle Statistiche di una tratta
*/
public class GestoreStatistiche {
//Metodi
/**
* Calcolo medio della velocita istantanea di una tratta
* @param velocita Lista delle velocita istantanee nella tratta
* @return Media delle velocita istantanee di una tratta
*/
public static Integer calcolaVelocitaIstantaneaMedia(List<Integer> velocita) {
if (velocita.size() == 0){
return 0;
}
int velMax = 0;
for (Integer vel : velocita) {
velMax += vel;
}
velMax = velMax/(velocita.size());
return velMax;
}
/**
* Calcolo medio della velocita media di una tratta
* @param velocita Lista delle velocita media nella tratta
* @return Media delle velocita medie di una tratta
*/
public static Double calcolaVelocitaMediaMedia(List<Double> velocita){
if (velocita.size() == 0){
return 0D;
}
double velMax = 0;
for (Double vel : velocita) {
velMax += vel;
}
velMax = velMax/(velocita.size());
return velMax;
}
/**
* Calcolo del numero di percorrimenti di una tratta
* @param percorrimenti Lista dei percorrimenti di una tratta
* @return Numero di percorrimenti di una tratta
*/
public static Integer calcolaNPercorrimenti(List<Percorrimento> percorrimenti){
return percorrimenti.size();
}
/**
* Calcolo delle multe
* @return Numero delle multe
*/
public static Integer calcolaMultaEffettuate(){
return Multa.counter;
}
/**
* Calcolo medio della percorrenza di una tratta
* @param time Lista dei tempi di percorrimento della tratta
* @return Tempo medio del percorrimento di una tratta
*/
public static Integer calcolaTempoPercorrenzaMedio(List<Long> time){
if (time.size() == 0){
return 0;
}
long timeMax = 0L;
for (long tempTime : time) {
timeMax += tempTime;
}
timeMax = timeMax/(time.size());
return (int)timeMax;
}
}
|
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.social.connect.support;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.springframework.core.GenericTypeResolver;
import org.springframework.social.ExpiredAuthorizationException;
import org.springframework.social.ServiceProvider;
import org.springframework.social.connect.ApiAdapter;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2ServiceProvider;
/**
* An OAuth2-based Connection implementation.
* In general, this implementation is expected to be suitable for all OAuth2-based providers and should not require subclassing.
* Subclasses of {@link OAuth2ConnectionFactory} should be favored to encapsulate details specific to an OAuth2-based provider.
* @author Keith Donald
* @param <A> the service provider's API type
* @see OAuth2ConnectionFactory
*/
public class OAuth2Connection<A> extends AbstractConnection<A> {
private static final long serialVersionUID = 4057584084077577480L;
private transient final OAuth2ServiceProvider<A> serviceProvider;
private String accessToken;
private String refreshToken;
private Long expireTime;
private transient A api;
private transient A apiProxy;
/**
* Creates a new {@link OAuth2Connection} from a access grant response.
* Designed to be called to establish a new {@link OAuth2Connection} after receiving an access grant successfully.
* The providerUserId may be null in this case: if so, this constructor will try to resolve it using the service API obtained from the {@link OAuth2ServiceProvider}.
* @param providerId the provider id e.g. "facebook".
* @param providerUserId the provider user id (may be null if not returned as part of the access grant)
* @param accessToken the granted access token
* @param refreshToken the granted refresh token
* @param expireTime the access token expiration time
* @param serviceProvider the OAuth2-based ServiceProvider
* @param apiAdapter the ApiAdapter for the ServiceProvider
*/
public OAuth2Connection(String providerId, String providerUserId, String accessToken, String refreshToken, Long expireTime,
OAuth2ServiceProvider<A> serviceProvider, ApiAdapter<A> apiAdapter) {
super(apiAdapter);
this.serviceProvider = serviceProvider;
initAccessTokens(accessToken, refreshToken, expireTime);
initApi();
initApiProxy();
initKey(providerId, providerUserId);
}
/**
* Creates a new {@link OAuth2Connection} from the data provided.
* Designed to be called when re-constituting an existing {@link Connection} from {@link ConnectionData}.
* @param data the data holding the state of this connection
* @param serviceProvider the OAuth2-based ServiceProvider
* @param apiAdapter the ApiAdapter for the ServiceProvider
*/
public OAuth2Connection(ConnectionData data, OAuth2ServiceProvider<A> serviceProvider, ApiAdapter<A> apiAdapter) {
super(data, apiAdapter);
this.serviceProvider = serviceProvider;
initAccessTokens(data.getAccessToken(), data.getRefreshToken(), data.getExpireTime());
initApi();
initApiProxy();
}
// implementing Connection
public boolean hasExpired() {
synchronized (getMonitor()) {
return expireTime != null && System.currentTimeMillis() >= expireTime;
}
}
public void refresh() {
synchronized (getMonitor()) {
AccessGrant accessGrant = serviceProvider.getOAuthOperations().refreshAccess(refreshToken, null);
initAccessTokens(accessGrant.getAccessToken(), accessGrant.getRefreshToken(), accessGrant.getExpireTime());
initApi();
}
}
public A getApi() {
if (apiProxy != null) {
return apiProxy;
} else {
if (getMonitor() == null) {
return api;
}
synchronized (getMonitor()) {
return api;
}
}
}
@Override
public ConnectionData createData() {
synchronized (getMonitor()) {
return new ConnectionData(getKey().getProviderId(), getKey().getProviderUserId(), getDisplayName(), getProfileUrl(), getImageUrl(), accessToken, null, refreshToken, expireTime, getProviderUnionId());
}
}
// internal helpers
private void initAccessTokens(String accessToken, String refreshToken, Long expireTime) {
this.accessToken = accessToken;
this.refreshToken = refreshToken;
this.expireTime = expireTime;
}
private void initApi() {
api = serviceProvider.getApi(accessToken);
}
@SuppressWarnings("unchecked")
private void initApiProxy() {
Class<?> apiType = GenericTypeResolver.resolveTypeArgument(serviceProvider.getClass(), ServiceProvider.class);
if (apiType.isInterface()) {
apiProxy = (A) Proxy.newProxyInstance(apiType.getClassLoader(), new Class<?>[] { apiType }, new ApiInvocationHandler());
}
}
private class ApiInvocationHandler implements InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
synchronized (getMonitor()) {
if (hasExpired()) {
throw new ExpiredAuthorizationException(getKey().getProviderId());
}
try {
return method.invoke(OAuth2Connection.this.api, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
}
}
// equas() and hashCode() generated by Eclipse
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((accessToken == null) ? 0 : accessToken.hashCode());
result = prime * result + ((expireTime == null) ? 0 : expireTime.hashCode());
result = prime * result + ((refreshToken == null) ? 0 : refreshToken.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!super.equals(obj)) return false;
if (getClass() != obj.getClass()) return false;
@SuppressWarnings("rawtypes")
OAuth2Connection other = (OAuth2Connection) obj;
if (accessToken == null) {
if (other.accessToken != null) return false;
} else if (!accessToken.equals(other.accessToken)) return false;
if (expireTime == null) {
if (other.expireTime != null) return false;
} else if (!expireTime.equals(other.expireTime)) return false;
if (refreshToken == null) {
if (other.refreshToken != null) return false;
} else if (!refreshToken.equals(other.refreshToken)) return false;
return true;
}
}
|
// Template Source: BaseEntity.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.models;
import com.microsoft.graph.serializer.ISerializer;
import com.microsoft.graph.serializer.IJsonBackedObject;
import com.microsoft.graph.serializer.AdditionalDataManager;
import java.util.EnumSet;
import com.microsoft.graph.http.BaseCollectionPage;
import com.microsoft.graph.models.RolePermission;
import com.microsoft.graph.models.RoleAssignment;
import com.microsoft.graph.models.Entity;
import com.microsoft.graph.requests.RoleAssignmentCollectionPage;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Role Definition.
*/
public class RoleDefinition extends Entity implements IJsonBackedObject {
/**
* The Description.
* Description of the Role definition.
*/
@SerializedName(value = "description", alternate = {"Description"})
@Expose
@Nullable
public String description;
/**
* The Display Name.
* Display Name of the Role definition.
*/
@SerializedName(value = "displayName", alternate = {"DisplayName"})
@Expose
@Nullable
public String displayName;
/**
* The Is Built In.
* Type of Role. Set to True if it is built-in, or set to False if it is a custom role definition.
*/
@SerializedName(value = "isBuiltIn", alternate = {"IsBuiltIn"})
@Expose
@Nullable
public Boolean isBuiltIn;
/**
* The Role Permissions.
* List of Role Permissions this role is allowed to perform. These must match the actionName that is defined as part of the rolePermission.
*/
@SerializedName(value = "rolePermissions", alternate = {"RolePermissions"})
@Expose
@Nullable
public java.util.List<RolePermission> rolePermissions;
/**
* The Role Assignments.
* List of Role assignments for this role definition.
*/
@SerializedName(value = "roleAssignments", alternate = {"RoleAssignments"})
@Expose
@Nullable
public RoleAssignmentCollectionPage roleAssignments;
/**
* Sets the raw JSON object
*
* @param serializer the serializer
* @param json the JSON object to set this object to
*/
public void setRawObject(@Nonnull final ISerializer serializer, @Nonnull final JsonObject json) {
if (json.has("roleAssignments")) {
roleAssignments = serializer.deserializeObject(json.get("roleAssignments"), RoleAssignmentCollectionPage.class);
}
}
}
|
package com.funtime.dubbo.mapper;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.funtime.dubbo.entity.OperationLog;
/**
* <p>
* 操作行为 Mapper 接口
* </p>
*
* @author Steven
* @since 2018-09-20
*/
public interface OperationLogMapper extends BaseMapper<OperationLog> {
}
|
package rocks.inspectit.ui.rcp.details.generator.impl;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import rocks.inspectit.shared.all.communication.DefaultData;
import rocks.inspectit.shared.all.communication.data.LoggingData;
import rocks.inspectit.ui.rcp.InspectIT;
import rocks.inspectit.ui.rcp.InspectITImages;
import rocks.inspectit.ui.rcp.details.DetailsCellContent;
import rocks.inspectit.ui.rcp.details.DetailsTable;
import rocks.inspectit.ui.rcp.details.generator.IDetailsGenerator;
import rocks.inspectit.ui.rcp.repository.RepositoryDefinition;
/**
* Realization of the <code>IDetailsGenerator</code> for logging entries.
*
* @author Stefan Siegl
*/
public class LoggingDetailsGenerator implements IDetailsGenerator {
/**
* {@inheritDoc}
*/
@Override
public boolean canGenerateFor(DefaultData defaultData) {
return defaultData instanceof LoggingData;
}
/**
* {@inheritDoc}
*/
@Override
public DetailsTable generate(DefaultData defaultData, RepositoryDefinition repositoryDefinition, Composite parent, FormToolkit toolkit) {
LoggingData loggingData = (LoggingData) defaultData;
DetailsTable table = new DetailsTable(parent, toolkit, "Logging Info", 1);
table.addContentRow("Level:", InspectIT.getDefault().getImage(InspectITImages.IMG_LOGGING_LEVEL), new DetailsCellContent[] { new DetailsCellContent(loggingData.getLevel()) });
table.addContentRow("Message:", InspectIT.getDefault().getImage(InspectITImages.IMG_LOG), new DetailsCellContent[] { new DetailsCellContent(loggingData.getMessage()) });
return table;
}
}
|
package com.levigo.jadice.format.jpeg2000.internal.marker;
import com.levigo.jadice.format.jpeg2000.JPEG2000Exception;
import com.levigo.jadice.format.jpeg2000.internal.codestream.Codestream;
import com.levigo.jadice.format.jpeg2000.internal.param.DirectParameterInfo;
import com.levigo.jadice.format.jpeg2000.internal.param.Parameters;
import com.levigo.jadice.format.jpeg2000.internal.param.PropertiesParameterInfo;
import com.levigo.jadice.format.jpeg2000.msg.CodestreamMessages;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
/**
* Defined in <i>ITU-T.800, A.7.1</i>.
* <p>
* <b>Function:</b> Describes the length of every tile-part in the codestream. Each tile-part's length is measured from
* the first byte of the {@link SOT} marker segment to the end of the bit-stream data of that tile-part. The value of
* each individual tile-part length in the TLM marker segment is the same as the value in the corresponding {@link
* SOT#Psot} in the SOT marker segment.
* <p>
* <b>Usage:</b> Main header. Optional use in the main header only. There may be multiple {@link TLM} marker segments
* in the main header.
* <p>
* <b>Length:</b> Variable depending on the number of tile-parts in the codestream.
*/
public class TLM extends AbstractMarkerSegment {
/**
* Length of marker segment in bytes (not including the marker). The value of this parameter is determined by
* equation <i>ITU-T.800, (A-7)</i>.
*/
public int Ltlm;
/**
* Index of this marker segment relative to all other {@link TLM} marker segments present in the <b>current</b>
* header. The sequence of <code>(Ttlm<sup>i</sup>, Ptlm<sup>i</sup>)</code> pairs from this marker segment is
* concatenated, in order of increasing {@link #Ztlm}, with the sequences of pairs from other marker segments. The
* jth entry in the resulting list contains the tile index and tile-part length pair for the jth tile-part appearing
* in the codestream.
*/
public int Ztlm;
/** Size of the {@link #Ttlm} and {@link #Ptlm} parameters. */
public int Stlm;
/**
* Tile index of the ith tile-part. Either none or one value for every tile-part. The number of tile-parts in each
* tile can be derived from this marker segment (or the concatenated list of all such markers) or from a non-zero
* {@link SOT#TNsot} parameter, if present.
*/
public List<Integer> Ttlm;
/**
* Length, in bytes, from the beginning of the {@link SOT} marker of the ith tile-part to the end of the bit stream
* data for that tile-part. One value for every tile-part.
*/
public List<Integer> Ptlm;
@Override
public Marker getMarker() {
return Marker.TLM;
}
@Override
public MarkerKey getMarkerKey() {
return new MarkerKey(getMarker(), Ztlm);
}
@Override
protected void read(ImageInputStream source, Codestream codestream) throws IOException, JPEG2000Exception {
Ltlm = source.readUnsignedShort();
Ztlm = source.readUnsignedByte();
Stlm = source.readUnsignedByte();
final int numTtlmBits = numTtlmBits(Parameters.extract(Stlm, MASK_ST));
if(numTtlmBits > 0) {
Ttlm = new LinkedList<>();
}
final int numPtlmBits = numPtlmBits(Parameters.extract(Stlm, MASK_SP));
Ptlm = new LinkedList<>();
int remainingBits = (Ltlm - 4) << 3;
while (remainingBits > 0) {
if (numTtlmBits > 0) {
Ttlm.add((int) (source.readBits(numTtlmBits) & 0xFFFF));
remainingBits -= numTtlmBits;
}
Ptlm.add((int) source.readBits(numPtlmBits));
remainingBits -= numPtlmBits;
}
}
private int numTtlmBits(final int st) throws JPEG2000Exception {
switch (st){
case VALUE_T_SIZE_8:
return 8;
case VALUE_T_SIZE_16:
return 16;
case VALUE_T_SIZE_0:
return 0;
}
throw new JPEG2000Exception(CodestreamMessages.ILLEGAL_PARAMETER_VALUE, "Stlm ST", st);
}
private int numPtlmBits(int sp) throws JPEG2000Exception {
switch(sp){
case VALUE_P_SIZE_16:
return 16;
case VALUE_P_SIZE_32:
return 32;
}
throw new JPEG2000Exception(CodestreamMessages.ILLEGAL_PARAMETER_VALUE, "Stlm SP", sp);
}
@Override
protected void write(ImageOutputStream sink, Codestream codestream) throws IOException {
sink.writeShort(Ltlm);
sink.writeByte(Ztlm);
sink.writeByte(Stlm);
for (int i = 0; i < Ptlm.size(); i++) {
if (Ttlm != null) {
if (Parameters.isValue(Stlm, MASK_ST, VALUE_T_SIZE_16)) {
sink.writeShort(Ttlm.get(i));
} else if (Parameters.isValue(Stlm, MASK_ST, VALUE_T_SIZE_8)) {
sink.writeByte(Ttlm.get(i));
}
}
if (Parameters.isSet(Stlm, MASK_SP)) {
sink.writeShort(Ptlm.get(i));
} else {
sink.writeByte(Ptlm.get(i));
}
}
}
@Override
protected void validate(Codestream codestream) throws JPEG2000Exception {
}
@Override
protected void fillMarkerInfo(MarkerInfo markerInfo) {
markerInfo.add(new PropertiesParameterInfo("Ltlm", Ltlm, "TLM.L"));
markerInfo.add(new PropertiesParameterInfo("Ztlm", Ztlm, "TLM.Z"));
markerInfo.add(new PropertiesParameterInfo("Stlm", Stlm, "TLM.S"));
if (Ttlm != null) {
markerInfo.add(new PropertiesParameterInfo("Ttlm", "TLM.T"));
for (int i = 0; i < Ttlm.size(); i++) {
markerInfo.add(new DirectParameterInfo("Ttlm[" + i + "]", Ttlm.get(i)));
}
}
markerInfo.add(new PropertiesParameterInfo("Ptlm", "TLM.P"));
for (int i = 0; i < Ptlm.size(); i++) {
markerInfo.add(new DirectParameterInfo("Ptlm[" + i + "]", Ptlm.get(i)));
}
}
private static final int MASK_ST = 0x30;
private static final int VALUE_T_SIZE_0 = 0x00;
private static final int VALUE_T_SIZE_8 = 0x10;
private static final int VALUE_T_SIZE_16 = 0x20;
private static final int MASK_SP = 0x40;
private static final int VALUE_P_SIZE_16 = 0x00;
private static final int VALUE_P_SIZE_32 = 0x40;
}
|
package es.redmic.db.common.model;
/*-
* #%L
* DB
* %%
* Copyright (C) 2019 REDMIC Project / Server
* %%
* 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 java.util.UUID;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.MappedSuperclass;
@MappedSuperclass
public class UuidModel extends UpdatableModel {
public UuidModel() {
super();
}
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(unique = true, nullable = true)
private UUID uuid;
public String getUuid() {
return uuid.toString();
}
public void setUuid(String uuid) {
if (uuid != null)
this.uuid = UUID.fromString(uuid);
}
}
|
/*
* Licensed to 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.expression.scalar.arithmetic;
import io.crate.data.Input;
import io.crate.metadata.FunctionIdent;
import io.crate.metadata.FunctionInfo;
import io.crate.metadata.TransactionContext;
import io.crate.metadata.Scalar;
import io.crate.types.DataType;
import java.util.Arrays;
import java.util.Set;
import java.util.function.BinaryOperator;
public final class BinaryScalar<T> extends Scalar<T, T> {
private final BinaryOperator<T> func;
private final FunctionInfo info;
private final DataType<T> type;
public BinaryScalar(BinaryOperator<T> func, String name, DataType<T> type, Set<FunctionInfo.Feature> feature) {
this.func = func;
this.info = new FunctionInfo(new FunctionIdent(name, Arrays.asList(type, type)), type, FunctionInfo.Type.SCALAR, feature);
this.type = type;
}
@Override
public FunctionInfo info() {
return info;
}
@Override
public T evaluate(TransactionContext txnCtx, Input<T>[] args) {
T arg0Value = type.value(args[0].value());
T arg1Value = type.value(args[1].value());
if (arg0Value == null) {
return null;
}
if (arg1Value == null) {
return null;
}
return func.apply(arg0Value, arg1Value);
}
}
|
package com.flash.merchant.controller;
import com.flash.merchant.utils.SecurityUtil;
import com.flash.transaction.api.IPayChannelService;
import com.flash.transaction.api.dto.PayChannelDto;
import com.flash.transaction.api.dto.PayChannelParamDto;
import com.flash.transaction.api.dto.PlatformChannelDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author yuelimin
* @version 1.0.0
* @since 11
*/
@RestController
@Api(value = "商户应用-渠道和支付参数相关", tags = {"PlatformPara"})
public class PlatformParamController {
@Reference
private IPayChannelService iPayChannelService;
@GetMapping("/my/pay-channel-params/apps/{appId}/platform-channels/{platformChannel}")
@ApiOperation("获取指定应用指定服务类型下所包含的原始支付渠道参数列表")
public List<PayChannelParamDto> queryChannelParam(@PathVariable("appId") String appId, @PathVariable("platformChannel") String platformChannel) {
return iPayChannelService.queryPayChannelParamByApplicationPlatform(appId, platformChannel);
}
@GetMapping("/my/pay-channel-params/apps/{appId}/platform-channels/{platformChannel}/pay-channels/{payChannel}")
@ApiOperation("获取指定应用指定服务类型下所包含的某个原始支付参数")
public PayChannelParamDto queryPayChannelParam(@PathVariable("appId") String appId, @PathVariable("platformChannel") String platformChannel, @PathVariable("payChannel") String payChannel) {
return iPayChannelService.queryParamByApplicationPlatformAndPayChannel(appId, platformChannel, payChannel);
}
@RequestMapping(value = "/my/pay-channel-params", method = {RequestMethod.POST, RequestMethod.PUT})
@ApiOperation("保存支付渠道参数")
public void createPayChannelParam(@RequestBody PayChannelParamDto payChannelParamDto) {
Long merchantId = SecurityUtil.getMerchantId();
payChannelParamDto.setMerchantId(merchantId);
iPayChannelService.savePayChannelParam(payChannelParamDto);
}
@GetMapping("/my/pay-channels/platform-channel/{platformChannelCode}")
@ApiOperation("根据平台服务类型获取支付渠道列表")
public List<PayChannelDto> queryPayChannelByPlatformChannel(@PathVariable("platformChannelCode") String code) {
return iPayChannelService.queryPayChannelByPlatformChannel(code);
}
@GetMapping("/my/merchants/apps/platform-channels")
@ApiOperation("查询应用是否绑定服务")
public Integer queryAppBindPlatformChannel(@RequestParam("appId") String appId, @RequestParam("platformChannel") String platformChannel) {
return iPayChannelService.queryAppBindPlatformChannels(appId, platformChannel);
}
@PostMapping("/my/apps/{appId}/platform-channels")
@ApiOperation(value = "绑定服务类型")
public void bindPlatformForApp(@PathVariable("appId") String appId, @RequestParam("platformChannelCodes") String platformChannelCodes) {
iPayChannelService.bindPlatformChannelForApp(appId, platformChannelCodes);
}
@GetMapping("/my/platform-channels")
@ApiOperation(value = "获取平台服务类型")
public List<PlatformChannelDto> queryPlatformChanel() {
return iPayChannelService.queryPlatformChannel();
}
}
|
package pinacolada.interfaces.subscribers;
import com.megacrit.cardcrawl.cards.AbstractCard;
import pinacolada.cards.base.PCLCardCooldown;
public interface OnCooldownTriggeredSubscriber
{
boolean OnCooldownTriggered(AbstractCard card, PCLCardCooldown cooldown);
}
|
package at.ac.tuwien.big.sbsml.codegen.lib;
import java.util.Random;
public class Util {
private static Random random = new Random(233434);
public static double random() {
return random.nextDouble();
}
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_BLACK = "\u001B[30m";
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_YELLOW = "\u001B[33m";
public static final String ANSI_BLUE = "\u001B[34m";
public static final String ANSI_PURPLE = "\u001B[35m";
public static final String ANSI_CYAN = "\u001B[36m";
public static final String ANSI_WHITE = "\u001B[37m";
public static final String ANSI_BOLD = "\u001b[1m";
public static final String ANSI_ITALIC = "\u001b[3m";
}
|
/*
* Copyright 2015 JBoss, by Red Hat, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.uberfire.ext.wires.bpmn.api.model.impl.nodes;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.jboss.errai.common.client.api.annotations.Portable;
import org.uberfire.ext.wires.bpmn.api.model.BpmnEdge;
import org.uberfire.ext.wires.bpmn.api.model.BpmnGraph;
import org.uberfire.ext.wires.bpmn.api.model.BpmnGraphNode;
import org.uberfire.ext.wires.bpmn.api.model.Content;
import org.uberfire.ext.wires.bpmn.api.model.Property;
import org.uberfire.ext.wires.bpmn.api.model.Role;
import org.uberfire.ext.wires.bpmn.api.model.impl.content.DefaultContentImpl;
import org.uberfire.ext.wires.bpmn.api.model.impl.properties.DefaultPropertyImpl;
import org.uberfire.ext.wires.bpmn.api.model.impl.roles.DefaultRoleImpl;
import org.uberfire.ext.wires.bpmn.api.model.impl.types.StringType;
import org.uberfire.ext.wires.bpmn.beliefs.graph.Graph;
import org.uberfire.ext.wires.bpmn.beliefs.graph.impl.GraphImpl;
import org.uberfire.ext.wires.bpmn.beliefs.graph.impl.GraphNodeImpl;
import org.uberfire.ext.wires.bpmn.beliefs.graph.impl.MapGraphStore;
/**
* A BPMN "Process"
*/
@Portable
public class ProcessNode extends GraphNodeImpl<Content, BpmnEdge> implements
BpmnGraph,
BpmnGraphNode {
private Graph<Content, BpmnGraphNode> graph = new GraphImpl<Content, BpmnGraphNode>(new MapGraphStore<BpmnGraphNode>());
private Set<Role> roles = new HashSet<Role>() {{
add(new DefaultRoleImpl("canContainArtifacts"));
}};
private Set<Property> properties = new HashSet<Property>() {{
add(new DefaultPropertyImpl("processn",
new StringType(),
"Process Name",
"Process Name",
false,
false));
add(new DefaultPropertyImpl("documentation",
new StringType(),
"Documentation",
"This attribute is used to annotate the BPMN element, such as descriptions and other documentation.",
false,
true));
}};
public ProcessNode() {
setContent(new DefaultContentImpl("BPMNProcess",
"BPMN-Process",
"A BPMN 2.0 Process.",
roles,
properties));
}
@Override
public BpmnGraphNode addNode(final BpmnGraphNode node) {
return graph.addNode(node);
}
@Override
public BpmnGraphNode removeNode(final int id) {
return graph.removeNode(id);
}
@Override
public BpmnGraphNode getNode(final int id) {
return graph.getNode(id);
}
@Override
public int size() {
return graph.size();
}
@Override
public Iterator<BpmnGraphNode> iterator() {
return graph.iterator();
}
@Override
public ProcessNode copy() {
final ProcessNode copy = new ProcessNode();
copy.setContent(this.getContent().copy());
for (BpmnGraphNode node : graph) {
copy.addNode(node.copy());
}
return copy;
}
@Override
public String toString() {
return "ProcessNode{" +
"graph=" + graph +
", roles=" + roles +
", properties=" + properties +
'}';
}
}
|
/*
* Copyright 2021 Gypsophila open source organization.
*
* Licensed under the Apache License,Version2.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.gypsophila.athena.common.exception;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* @author lixiaoshuang
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class AthenaException extends RuntimeException {
private int errorCode;
private String errorMessage;
public AthenaException(String errorMessage) {
super(errorMessage);
}
public AthenaException(int errorCode, String errorMessage) {
super(errorMessage);
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
}
|
/*
*
* * Copyright 2015 Skymind,Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.deeplearning4j.earlystopping;
import lombok.Data;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import java.io.Serializable;
import java.util.Map;
/** EarlyStoppingResult: contains the results of the early stopping training, such as:
* - Why the training was terminated
* - Score vs. epoch
* - Epoch that the best model was found
* - Score of the best model
* - The best model (MultiLayerNetwork) itself
* @author Alex Black
*/
@Data
public class EarlyStoppingResult implements Serializable {
public enum TerminationReason {Error, IterationTerminationCondition, EpochTerminationCondition};
private TerminationReason terminationReason;
private String terminationDetails;
private Map<Integer,Double> scoreVsEpoch;
private int bestModelEpoch;
private double bestModelScore;
private int totalEpochs;
private MultiLayerNetwork bestModel;
public EarlyStoppingResult(TerminationReason terminationReason, String terminationDetails, Map<Integer,Double> scoreVsEpoch,
int bestModelEpoch, double bestModelScore, int totalEpochs, MultiLayerNetwork bestModel ){
this.terminationReason = terminationReason;
this.terminationDetails = terminationDetails;
this.scoreVsEpoch = scoreVsEpoch;
this.bestModelEpoch = bestModelEpoch;
this.bestModelScore = bestModelScore;
this.totalEpochs = totalEpochs;
this.bestModel = bestModel;
}
@Override
public String toString(){
return "EarlyStoppingResult(terminationReason=" + terminationReason + ",details="+terminationDetails +
",bestModelEpoch="+bestModelEpoch + ",bestModelScore="+bestModelScore + ",totalEpochs="+totalEpochs + ")";
}
}
|
/*
* Copyright Strimzi authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.strimzi.api.kafka.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import io.fabric8.kubernetes.api.model.ResourceRequirements;
import io.strimzi.crdgenerator.annotations.Description;
import io.strimzi.crdgenerator.annotations.Minimum;
import io.sundr.builder.annotations.Buildable;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* Representation of the User Operator.
*/
@Buildable(
editableEnabled = false,
builderPackage = "io.fabric8.kubernetes.api.builder"
)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"watchedNamespace", "image",
"reconciliationIntervalSeconds", "zookeeperSessionTimeoutSeconds",
"livenessProbe", "readinessProbe",
"resources", "logging", "jvmOptions"})
@EqualsAndHashCode
public class EntityUserOperatorSpec implements UnknownPropertyPreserving, Serializable {
private static final long serialVersionUID = 1L;
public static final int DEFAULT_HEALTHCHECK_DELAY = 10;
public static final int DEFAULT_HEALTHCHECK_TIMEOUT = 5;
public static final int DEFAULT_ZOOKEEPER_PORT = 2181;
public static final long DEFAULT_FULL_RECONCILIATION_INTERVAL_SECONDS = 120;
public static final long DEFAULT_ZOOKEEPER_SESSION_TIMEOUT_SECONDS = 6;
private String watchedNamespace;
private String image;
private long reconciliationIntervalSeconds = DEFAULT_FULL_RECONCILIATION_INTERVAL_SECONDS;
private long zookeeperSessionTimeoutSeconds = DEFAULT_ZOOKEEPER_SESSION_TIMEOUT_SECONDS;
private Probe livenessProbe;
private Probe readinessProbe;
private ResourceRequirements resources;
private Logging logging;
private JvmOptions jvmOptions;
private Map<String, Object> additionalProperties = new HashMap<>(0);
@Description("The namespace the User Operator should watch.")
public String getWatchedNamespace() {
return watchedNamespace;
}
public void setWatchedNamespace(String watchedNamespace) {
this.watchedNamespace = watchedNamespace;
}
@Description("The image to use for the User Operator")
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@Description("Interval between periodic reconciliations.")
@Minimum(0)
public long getReconciliationIntervalSeconds() {
return reconciliationIntervalSeconds;
}
public void setReconciliationIntervalSeconds(long reconciliationIntervalSeconds) {
this.reconciliationIntervalSeconds = reconciliationIntervalSeconds;
}
@Description("Timeout for the ZooKeeper session")
@Minimum(0)
public long getZookeeperSessionTimeoutSeconds() {
return zookeeperSessionTimeoutSeconds;
}
public void setZookeeperSessionTimeoutSeconds(long zookeeperSessionTimeoutSeconds) {
this.zookeeperSessionTimeoutSeconds = zookeeperSessionTimeoutSeconds;
}
@Description("CPU and memory resources to reserve.")
public ResourceRequirements getResources() {
return resources;
}
public void setResources(ResourceRequirements resources) {
this.resources = resources;
}
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@Description("Pod liveness checking.")
public Probe getLivenessProbe() {
return livenessProbe;
}
public void setLivenessProbe(Probe livenessProbe) {
this.livenessProbe = livenessProbe;
}
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@Description("Pod readiness checking.")
public Probe getReadinessProbe() {
return readinessProbe;
}
public void setReadinessProbe(Probe readinessProbe) {
this.readinessProbe = readinessProbe;
}
@Description("Logging configuration")
@JsonInclude(value = JsonInclude.Include.NON_NULL)
public Logging getLogging() {
return logging;
}
public void setLogging(Logging logging) {
this.logging = logging;
}
@Override
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@Override
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@Description("JVM Options for pods")
public JvmOptions getJvmOptions() {
return jvmOptions;
}
public void setJvmOptions(JvmOptions jvmOptions) {
this.jvmOptions = jvmOptions;
}
}
|
/*
* Copyright 2017-2021 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.http.server.exceptions.response;
import io.micronaut.context.annotation.Secondary;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.http.MediaType;
import io.micronaut.http.MutableHttpResponse;
import io.micronaut.http.hateoas.Link;
import io.micronaut.http.hateoas.Resource;
import io.micronaut.http.hateoas.JsonError;
import io.micronaut.jackson.JacksonConfiguration;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
/**
* Creates Hateoas JSON error responses.
*
* @author James Kleeh
* @since 2.4.0
*/
@Singleton
@Secondary
public class HateoasErrorResponseProcessor implements ErrorResponseProcessor<JsonError> {
private final boolean alwaysSerializeErrorsAsList;
public HateoasErrorResponseProcessor(JacksonConfiguration jacksonConfiguration) {
this.alwaysSerializeErrorsAsList = jacksonConfiguration.isAlwaysSerializeErrorsAsList();
}
@Override
@NonNull
public MutableHttpResponse<JsonError> processResponse(@NonNull ErrorContext errorContext, @NonNull MutableHttpResponse<?> response) {
JsonError error;
if (!errorContext.hasErrors()) {
error = new JsonError(response.getStatus().getReason());
} else if (errorContext.getErrors().size() == 1 && !alwaysSerializeErrorsAsList) {
Error jsonError = errorContext.getErrors().get(0);
error = new JsonError(jsonError.getMessage());
jsonError.getPath().ifPresent(error::path);
} else {
error = new JsonError(response.getStatus().getReason());
List<Resource> errors = new ArrayList<>();
for (Error jsonError : errorContext.getErrors()) {
errors.add(new JsonError(jsonError.getMessage()).path(jsonError.getPath().orElse(null)));
}
error.embedded("errors", errors);
}
error.link(Link.SELF, Link.of(errorContext.getRequest().getUri()));
return response.body(error).contentType(MediaType.APPLICATION_JSON_TYPE);
}
}
|
package com.mobile.bonrix.bonrixappstore.utility;
import android.app.Activity;
import android.content.res.Resources;
import android.util.Log;
import com.mobile.bonrix.bonrixappstore.R;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by CRAFT BOX on 5/1/2017.
*/
public class RetrofitClient {
static String TAG = "RetrofitClient";
private static Retrofit retrofit = null;
public static String Image_url;
// public static String service_url = Resources.getSystem().getResourceName(R.string.service_url);
// public static String Image_url = Resources.getSystem().getResourceName(R.string.Image_url);
// public static String service_url = "http://bonrix.myappstore.co.in/BonrixAppStore/Services/Service.asmx/";
// public static String Image_url = "http://bonrix.myappstore.co.in/BonrixAppStore/Raw_Details/Store/easovation/App/";
public static Retrofit getClient(Activity activity) {
String service_url = activity.getResources().getString(R.string.service_url);
Image_url = activity.getResources().getString(R.string.Image_url);
Log.e(TAG, "service_url " + service_url);
if (retrofit == null) {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(36000, TimeUnit.SECONDS)
.connectTimeout(36000, TimeUnit.SECONDS)
.build();
retrofit = new Retrofit.Builder()
.baseUrl(service_url)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
|
/*
* Copyright 2016-2021 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.chime.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/chime-2018-05-01/CreateUser" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateUserRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The Amazon Chime account ID.
* </p>
*/
private String accountId;
/**
* <p>
* The user name.
* </p>
*/
private String username;
/**
* <p>
* The user's email address.
* </p>
*/
private String email;
/**
* <p>
* The user type.
* </p>
*/
private String userType;
/**
* <p>
* The Amazon Chime account ID.
* </p>
*
* @param accountId
* The Amazon Chime account ID.
*/
public void setAccountId(String accountId) {
this.accountId = accountId;
}
/**
* <p>
* The Amazon Chime account ID.
* </p>
*
* @return The Amazon Chime account ID.
*/
public String getAccountId() {
return this.accountId;
}
/**
* <p>
* The Amazon Chime account ID.
* </p>
*
* @param accountId
* The Amazon Chime account ID.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateUserRequest withAccountId(String accountId) {
setAccountId(accountId);
return this;
}
/**
* <p>
* The user name.
* </p>
*
* @param username
* The user name.
*/
public void setUsername(String username) {
this.username = username;
}
/**
* <p>
* The user name.
* </p>
*
* @return The user name.
*/
public String getUsername() {
return this.username;
}
/**
* <p>
* The user name.
* </p>
*
* @param username
* The user name.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateUserRequest withUsername(String username) {
setUsername(username);
return this;
}
/**
* <p>
* The user's email address.
* </p>
*
* @param email
* The user's email address.
*/
public void setEmail(String email) {
this.email = email;
}
/**
* <p>
* The user's email address.
* </p>
*
* @return The user's email address.
*/
public String getEmail() {
return this.email;
}
/**
* <p>
* The user's email address.
* </p>
*
* @param email
* The user's email address.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateUserRequest withEmail(String email) {
setEmail(email);
return this;
}
/**
* <p>
* The user type.
* </p>
*
* @param userType
* The user type.
* @see UserType
*/
public void setUserType(String userType) {
this.userType = userType;
}
/**
* <p>
* The user type.
* </p>
*
* @return The user type.
* @see UserType
*/
public String getUserType() {
return this.userType;
}
/**
* <p>
* The user type.
* </p>
*
* @param userType
* The user type.
* @return Returns a reference to this object so that method calls can be chained together.
* @see UserType
*/
public CreateUserRequest withUserType(String userType) {
setUserType(userType);
return this;
}
/**
* <p>
* The user type.
* </p>
*
* @param userType
* The user type.
* @return Returns a reference to this object so that method calls can be chained together.
* @see UserType
*/
public CreateUserRequest withUserType(UserType userType) {
this.userType = userType.toString();
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getAccountId() != null)
sb.append("AccountId: ").append(getAccountId()).append(",");
if (getUsername() != null)
sb.append("Username: ").append(getUsername()).append(",");
if (getEmail() != null)
sb.append("Email: ").append("***Sensitive Data Redacted***").append(",");
if (getUserType() != null)
sb.append("UserType: ").append(getUserType());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CreateUserRequest == false)
return false;
CreateUserRequest other = (CreateUserRequest) obj;
if (other.getAccountId() == null ^ this.getAccountId() == null)
return false;
if (other.getAccountId() != null && other.getAccountId().equals(this.getAccountId()) == false)
return false;
if (other.getUsername() == null ^ this.getUsername() == null)
return false;
if (other.getUsername() != null && other.getUsername().equals(this.getUsername()) == false)
return false;
if (other.getEmail() == null ^ this.getEmail() == null)
return false;
if (other.getEmail() != null && other.getEmail().equals(this.getEmail()) == false)
return false;
if (other.getUserType() == null ^ this.getUserType() == null)
return false;
if (other.getUserType() != null && other.getUserType().equals(this.getUserType()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getAccountId() == null) ? 0 : getAccountId().hashCode());
hashCode = prime * hashCode + ((getUsername() == null) ? 0 : getUsername().hashCode());
hashCode = prime * hashCode + ((getEmail() == null) ? 0 : getEmail().hashCode());
hashCode = prime * hashCode + ((getUserType() == null) ? 0 : getUserType().hashCode());
return hashCode;
}
@Override
public CreateUserRequest clone() {
return (CreateUserRequest) super.clone();
}
}
|
/***************************************************************/
/****** DO NOT EDIT THIS CLASS bc-java SOURCE FILE ******/
/***************************************************************/
package org.bouncycastle.asn1;
/**
* Exception thrown when correctly encoded, but unexpected data is found in a stream while building an object.
*/
public class ASN1ParsingException
extends IllegalStateException
{
private Throwable cause;
/**
* Base constructor
*
* @param message a message concerning the exception.
*/
public ASN1ParsingException(String message)
{
super(message);
}
/**
* Constructor when this exception is due to another one.
*
* @param message a message concerning the exception.
* @param cause the exception that caused this exception to be thrown.
*/
public ASN1ParsingException(String message, Throwable cause)
{
super(message);
this.cause = cause;
}
/**
* Return the underlying cause of this exception, if any.
*
* @return the exception causing this one, null if there isn't one.
*/
public Throwable getCause()
{
return cause;
}
}
|
// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
package jodd.joy.servers;
import jodd.io.FileUtil;
import org.apache.catalina.startup.Tomcat;
import java.io.File;
/**
* Embedded Tomcat server for integration tests.
*/
public class TomcatTestServer extends TestServerBase {
// ---------------------------------------------------------------- instance
protected File webRoot;
protected Tomcat tomcat;
public void start() throws Exception {
webRoot = prepareWebApplication();
final String workingDir = System.getProperty("java.io.tmpdir");
tomcat = new Tomcat();
tomcat.setPort(8173);
tomcat.setBaseDir(workingDir);
tomcat.addWebapp("", webRoot.getAbsolutePath());
tomcat.start();
}
public void stop() throws Exception {
tomcat.stop();
tomcat.destroy();
FileUtil.deleteDir(webRoot);
}
}
|
package me.aki.linkstone.compiler;
import static org.objectweb.asm.Opcodes.*;
import me.aki.linkstone.compiler.meta.*;
import me.aki.linkstone.annotations.Version;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodNode;
import java.util.*;
/**
* Removes all classes, methods, fields, getters and setters that do not exist for a certain version.
* It does also rename getters and setters.
*/
public class TemplateTransformer {
private final static String GETTER_PREFIX = "$linkstone$getter$";
private final static String SETTER_PREFIX = "$linkstone$setter$";
private final Version version;
public TemplateTransformer(Version version) {
this.version = version;
}
public void processClasses(List<ClassNode> cns) {
Iterator<ClassNode> iter = cns.iterator();
while (iter.hasNext()) {
ClassNode cn = iter.next();
ClassfileMeta meta = ClassfileMeta.from(cn);
if(meta.hasAnnotation() && !meta.getVersions().contains(version)) {
iter.remove();
continue;
}
processFieldAccessors(cn);
processFields(cn.fields);
processMethods(cn.methods);
}
}
private void processFieldAccessors(ClassNode cn) {
AccessorCollector accessors = new AccessorCollector(cn);
for(FieldNode fn : accessors.getFields()) {
FieldMeta fieldMeta = FieldMeta.from(fn);
if(!fieldMeta.hasAnnotation())continue;
for(MethodNode getter : accessors.getGetters(fn)) {
MethodMeta meta = MethodMeta.from(getter);
if(!meta.getVersions().contains(this.version)) {
cn.methods.remove(getter);
}
getter.access = setPublic(getter.access);
getter.name = GETTER_PREFIX + fn.name;
}
for(MethodNode setter : accessors.getSetters(fn)) {
MethodMeta meta = MethodMeta.from(setter);
if(!meta.getVersions().contains(this.version)) {
cn.methods.remove(meta);
}
setter.access = setPublic(setter.access);
setter.name = SETTER_PREFIX + fn.name;
}
}
}
private int setPublic(int access) {
access |= ACC_PUBLIC;
access &= ~ACC_PRIVATE;
access &= ~ACC_PROTECTED;
return access;
}
private void processFields(List<FieldNode> fields) {
Iterator<FieldNode> iter = fields.iterator();
while (iter.hasNext()) {
FieldNode fn = iter.next();
FieldMeta meta = FieldMeta.from(fn);
if(meta.hasAnnotation() && !meta.getVersions().contains(version)) {
iter.remove();
}
}
}
private void processMethods(List<MethodNode> methods) {
Iterator<MethodNode> iter = methods.iterator();
while (iter.hasNext()) {
MethodNode mn = iter.next();
MethodMeta meta = MethodMeta.from(mn);
if(meta.hasAnnotation() && !meta.getVersions().contains(version)) {
iter.remove();
}
}
}
}
|
/*
* Copyright © 2009 HotPads (admin@hotpads.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 io.datarouter.instrumentation.exception;
import java.util.Date;
public class ExceptionRecordDto{
public final String id;
public final Date created;
public final String serviceName;
public final String serverName;
public final String stackTrace;
public final String type;
public final String appVersion;
public final String exceptionLocation;
public final String methodName;
public final Integer lineNumber;
public final String callOrigin;
public ExceptionRecordDto(
String id,
Date created,
String serviceName,
String serverName,
String stackTrace,
String type,
String appVersion,
String exceptionLocation,
String methodName,
Integer lineNumber,
String callOrigin){
this.id = id;
this.created = created;
this.serviceName = serviceName;
this.serverName = serverName;
this.stackTrace = stackTrace;
this.type = type;
this.appVersion = appVersion;
this.exceptionLocation = exceptionLocation;
this.methodName = methodName;
this.lineNumber = lineNumber;
this.callOrigin = callOrigin;
}
}
|
package org.bian.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.validation.Valid;
/**
* BQReferenceRetrieveOutputModelReferenceInstanceAnalysis
*/
public class BQReferenceRetrieveOutputModelReferenceInstanceAnalysis {
private Object referenceInstanceAnalysisRecord = null;
private String referenceInstanceAnalysisReportType = null;
private String referenceInstanceAnalysisParameters = null;
private Object referenceInstanceAnalysisReport = null;
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The inputs and results of the instance analysis that can be on-going, periodic and actual and projected
* @return referenceInstanceAnalysisRecord
**/
public Object getReferenceInstanceAnalysisRecord() {
return referenceInstanceAnalysisRecord;
}
public void setReferenceInstanceAnalysisRecord(Object referenceInstanceAnalysisRecord) {
this.referenceInstanceAnalysisRecord = referenceInstanceAnalysisRecord;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Code general-info: The type of external performance analysis report available
* @return referenceInstanceAnalysisReportType
**/
public String getReferenceInstanceAnalysisReportType() {
return referenceInstanceAnalysisReportType;
}
public void setReferenceInstanceAnalysisReportType(String referenceInstanceAnalysisReportType) {
this.referenceInstanceAnalysisReportType = referenceInstanceAnalysisReportType;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The selection parameters for the analysis (e.g. period, algorithm type)
* @return referenceInstanceAnalysisParameters
**/
public String getReferenceInstanceAnalysisParameters() {
return referenceInstanceAnalysisParameters;
}
public void setReferenceInstanceAnalysisParameters(String referenceInstanceAnalysisParameters) {
this.referenceInstanceAnalysisParameters = referenceInstanceAnalysisParameters;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The external analysis report in any suitable form including selection filters where appropriate
* @return referenceInstanceAnalysisReport
**/
public Object getReferenceInstanceAnalysisReport() {
return referenceInstanceAnalysisReport;
}
public void setReferenceInstanceAnalysisReport(Object referenceInstanceAnalysisReport) {
this.referenceInstanceAnalysisReport = referenceInstanceAnalysisReport;
}
}
|
package com.martiansoftware.io;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
/**
* This class is similar to the standard java.io.FileOutputStream, except that
* all writes are directed to a temporary file, which then atomically replaces
* the destination file when the stream is closed.
*
* The strategy is to:
* <ol>
* <li>write to a temporary file in the same directory as the destination file.</li>
* <li>create a backup of the original file (if it exists) in the same directory</li>
* <li>atomically copy the temporary file to the destination file</li>
* <li>delete the backup file</li>
* </ol>
*
* If anything goes wrong, the temporary file will be deleted. If anything goes
* wrong between backing up and replacing the original, a backup file may
* remain on disk (and can be obtained via getBackup()). If all goes well,
* no temporary or backup files will remain on disk after closing the stream.
*
* @author Marty Lamb
*/
public class AtomicFileOutputStream extends OutputStream {
private final Path _dest; // user-specified destination file
private final Path _tmp; // temporary file to which writes are redirected
private final Path _bak; // backup of destination file made when stream is closed
private final FileOutputStream _tmpOut; // writes to tmp file
/**
* Creates a new AtomicFileOutputStream to write to or replace the specified File
* @param file the File to write to or replace
* @throws IOException
*/
public AtomicFileOutputStream(File file) throws IOException {
this (file.toPath());
}
/**
* Creates a new AtomicFileOutputStream to write to or replace the File at the specified Path
* @param path the path of the File to write to or replace
* @throws IOException
*/
public AtomicFileOutputStream(Path path) throws IOException {
_dest = path;
try {
_tmp = Files.createTempFile(_dest.getParent(),
_dest.getFileName() + ".",
".tmp");
_bak = _tmp.resolveSibling(_tmp.getFileName().toString().replaceAll("\\.tmp$", ".bak"));
_tmpOut = new FileOutputStream(_tmp.toFile());
} catch (IOException e) {
cleanup();
throw e;
}
}
/**
* Returns the Path of a possibly nonexistent backup copy of the original File that is being replaced (if any)
* @return the Path of a possibly nonexistent backup copy of the original File that is being replaced (if any)
*/
public Path getBackup() { return _bak; }
/**
* Aborts the write process, leaving the destination file untouched
* @throws IOException
*/
public void cancel() throws IOException {
try { _tmpOut.close(); } catch (IOException ignored) {}
io(() -> finish(false));
}
// wraps around an IO operation to clean up any temporary files if an exception occurs
private void io(DelegatedIo d) throws IOException {
try { d.io(); }
catch (IOException e) {
cleanup();
throw e;
}
}
// perform the final operations to move the temporary file to its final destination
private void finish(boolean success) throws IOException {
if (success) {
try {
// copy original to .bak
if (Files.exists(_dest)) Files.copy(_dest, _bak, StandardCopyOption.REPLACE_EXISTING);
// atomically move tmp over original
Files.move(_tmp, _dest, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
cleanup();
throw(e);
}
}
cleanup();
Files.deleteIfExists(_bak); // only delete backup if everything works
}
private void cleanup() {
try { Files.deleteIfExists(_tmp); } catch (IOException ignored) {}
}
@FunctionalInterface private interface DelegatedIo {
public void io() throws IOException;
}
@Override public void close() throws IOException {
io(() -> _tmpOut.close());
io(() -> finish(true));
}
@Override public void flush() throws IOException {
io(() -> _tmpOut.flush());
}
@Override public void write(byte[] b) throws IOException {
io(() -> _tmpOut.write(b));
}
@Override public void write(byte[] b, int off, int len) throws IOException {
io(() -> _tmpOut.write(b, off, len));
}
@Override public void write(int b) throws IOException {
io(() -> _tmpOut.write(b));
}
}
|
package fr.syncrase.ecosyst.domain;
import java.io.Serializable;
import javax.persistence.*;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
/**
* A Sol.
*/
@Entity
@Table(name = "sol")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Sol implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
@Column(name = "id")
private Long id;
@Column(name = "ph_min")
private Double phMin;
@Column(name = "ph_max")
private Double phMax;
@Column(name = "type")
private String type;
@Column(name = "richesse")
private String richesse;
// jhipster-needle-entity-add-field - JHipster will add fields here
public Long getId() {
return this.id;
}
public Sol id(Long id) {
this.setId(id);
return this;
}
public void setId(Long id) {
this.id = id;
}
public Double getPhMin() {
return this.phMin;
}
public Sol phMin(Double phMin) {
this.setPhMin(phMin);
return this;
}
public void setPhMin(Double phMin) {
this.phMin = phMin;
}
public Double getPhMax() {
return this.phMax;
}
public Sol phMax(Double phMax) {
this.setPhMax(phMax);
return this;
}
public void setPhMax(Double phMax) {
this.phMax = phMax;
}
public String getType() {
return this.type;
}
public Sol type(String type) {
this.setType(type);
return this;
}
public void setType(String type) {
this.type = type;
}
public String getRichesse() {
return this.richesse;
}
public Sol richesse(String richesse) {
this.setRichesse(richesse);
return this;
}
public void setRichesse(String richesse) {
this.richesse = richesse;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Sol)) {
return false;
}
return id != null && id.equals(((Sol) o).id);
}
@Override
public int hashCode() {
// see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
return getClass().hashCode();
}
// prettier-ignore
@Override
public String toString() {
return "Sol{" +
"id=" + getId() +
", phMin=" + getPhMin() +
", phMax=" + getPhMax() +
", type='" + getType() + "'" +
", richesse='" + getRichesse() + "'" +
"}";
}
}
|
package org.robolectric.shadows;
import static com.google.common.truth.Truth.assertThat;
import static org.robolectric.Shadows.shadowOf;
import android.app.Activity;
import android.speech.tts.TextToSpeech;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class ShadowTextToSpeechTest {
private TextToSpeech textToSpeech;
private Activity activity;
private TextToSpeech.OnInitListener listener;
@Before
public void setUp() throws Exception {
activity = Robolectric.buildActivity(Activity.class).create().get();
listener = new TextToSpeech.OnInitListener() {
@Override public void onInit(int i) {
}
};
textToSpeech = new TextToSpeech(activity, listener);
}
@Test
public void shouldNotBeNull() throws Exception {
assertThat(textToSpeech).isNotNull();
assertThat(shadowOf(textToSpeech)).isNotNull();
}
@Test
public void getContext_shouldReturnContext() throws Exception {
assertThat(shadowOf(textToSpeech).getContext()).isEqualTo(activity);
}
@Test
public void getOnInitListener_shouldReturnListener() throws Exception {
assertThat(shadowOf(textToSpeech).getOnInitListener()).isEqualTo(listener);
}
@Test
public void getLastSpokenText_shouldReturnSpokenText() throws Exception {
textToSpeech.speak("Hello", TextToSpeech.QUEUE_FLUSH, null);
assertThat(shadowOf(textToSpeech).getLastSpokenText()).isEqualTo("Hello");
}
@Test
public void getLastSpokenText_shouldReturnMostRecentText() throws Exception {
textToSpeech.speak("Hello", TextToSpeech.QUEUE_FLUSH, null);
textToSpeech.speak("Hi", TextToSpeech.QUEUE_FLUSH, null);
assertThat(shadowOf(textToSpeech).getLastSpokenText()).isEqualTo("Hi");
}
@Test
public void clearLastSpokenText_shouldSetLastSpokenTextToNull() throws Exception {
textToSpeech.speak("Hello", TextToSpeech.QUEUE_FLUSH, null);
shadowOf(textToSpeech).clearLastSpokenText();
assertThat(shadowOf(textToSpeech).getLastSpokenText()).isNull();
}
@Test
public void isShutdown_shouldReturnFalseBeforeShutdown() throws Exception {
assertThat(shadowOf(textToSpeech).isShutdown()).isFalse();
}
@Test
public void isShutdown_shouldReturnTrueAfterShutdown() throws Exception {
textToSpeech.shutdown();
assertThat(shadowOf(textToSpeech).isShutdown()).isTrue();
}
@Test
public void isStopped_shouldReturnTrueBeforeSpeak() throws Exception {
assertThat(shadowOf(textToSpeech).isStopped()).isTrue();
}
@Test
public void isStopped_shouldReturnTrueAfterStop() throws Exception {
textToSpeech.stop();
assertThat(shadowOf(textToSpeech).isStopped()).isTrue();
}
@Test
public void isStopped_shouldReturnFalseAfterSpeak() throws Exception {
textToSpeech.speak("Hello", TextToSpeech.QUEUE_FLUSH, null);
assertThat(shadowOf(textToSpeech).isStopped()).isFalse();
}
@Test
public void getQueueMode_shouldReturnMostRecentQueueMode() throws Exception {
textToSpeech.speak("Hello", TextToSpeech.QUEUE_ADD, null);
assertThat(shadowOf(textToSpeech).getQueueMode()).isEqualTo(TextToSpeech.QUEUE_ADD);
}
}
|
/*
* 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.table.runtime.util.collections.binary;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.core.memory.MemorySegment;
import org.apache.flink.core.memory.MemorySegmentFactory;
import org.apache.flink.runtime.io.disk.RandomAccessInputView;
import org.apache.flink.runtime.io.disk.SimpleCollectingOutputView;
import org.apache.flink.runtime.memory.AbstractPagedInputView;
import org.apache.flink.runtime.memory.MemoryManager;
import org.apache.flink.table.data.binary.BinaryRowData;
import org.apache.flink.table.runtime.typeutils.BinaryRowDataSerializer;
import org.apache.flink.table.runtime.typeutils.PagedTypeSerializer;
import org.apache.flink.table.runtime.util.KeyValueIterator;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.util.MathUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static org.apache.flink.util.Preconditions.checkArgument;
/**
* Bytes based hash map. It can be used for performing aggregations where the aggregated values are
* fixed-width, because the data is stored in continuous memory, AggBuffer of variable length cannot
* be applied to this HashMap. The KeyValue form in hash map is designed to reduce the cost of key
* fetching in lookup. The memory is divided into two areas:
*
* <p>Bucket area: pointer + hashcode.
*
* <ul>
* <li>Bytes 0 to 4: a pointer to the record in the record area
* <li>Bytes 4 to 8: key's full 32-bit hashcode
* </ul>
*
* <p>Record area: the actual data in linked list records, a record has four parts:
*
* <ul>
* <li>Bytes 0 to 4: len(k)
* <li>Bytes 4 to 4 + len(k): key data
* <li>Bytes 4 + len(k) to 8 + len(k): len(v)
* <li>Bytes 8 + len(k) to 8 + len(k) + len(v): value data
* </ul>
*
* <p>{@code BytesHashMap} are influenced by Apache Spark BytesToBytesMap.
*/
public abstract class AbstractBytesHashMap<K> extends BytesMap<K, BinaryRowData> {
private static final Logger LOG = LoggerFactory.getLogger(AbstractBytesHashMap.class);
/**
* Set true when valueTypeInfos.length == 0. Usually in this case the BytesHashMap will be used
* as a HashSet. The value from {@link AbstractBytesHashMap#append(LookupInfo info,
* BinaryRowData value)} will be ignored when hashSetMode set. The reusedValue will always point
* to a 16 bytes long MemorySegment acted as each BytesHashMap entry's value part when appended
* to make the BytesHashMap's spilling work compatible.
*/
private final boolean hashSetMode;
/** Used to serialize map key into RecordArea's MemorySegments. */
protected final PagedTypeSerializer<K> keySerializer;
/** Used to serialize hash map value into RecordArea's MemorySegments. */
private final BinaryRowDataSerializer valueSerializer;
private volatile RecordArea.EntryIterator destructiveIterator = null;
public AbstractBytesHashMap(
final Object owner,
MemoryManager memoryManager,
long memorySize,
PagedTypeSerializer<K> keySerializer,
LogicalType[] valueTypes) {
this(owner, memoryManager, memorySize, keySerializer, valueTypes.length);
}
public AbstractBytesHashMap(
final Object owner,
MemoryManager memoryManager,
long memorySize,
PagedTypeSerializer<K> keySerializer,
int valueArity) {
super(owner, memoryManager, memorySize, keySerializer);
this.recordArea = new RecordArea();
this.keySerializer = keySerializer;
this.valueSerializer = new BinaryRowDataSerializer(valueArity);
if (valueArity == 0) {
this.hashSetMode = true;
this.reusedValue = new BinaryRowData(0);
this.reusedValue.pointTo(MemorySegmentFactory.wrap(new byte[8]), 0, 8);
LOG.info("BytesHashMap with hashSetMode = true.");
} else {
this.hashSetMode = false;
this.reusedValue = this.valueSerializer.createInstance();
}
checkArgument(
memorySize > INIT_BUCKET_MEMORY_IN_BYTES, "The minBucketMemorySize is not valid!");
final int initBucketSegmentNum =
MathUtils.roundDownToPowerOf2((int) (INIT_BUCKET_MEMORY_IN_BYTES / segmentSize));
// allocate and initialize MemorySegments for bucket area
initBucketSegments(initBucketSegmentNum);
LOG.info(
"BytesHashMap with initial memory segments {}, {} in bytes, init allocating {} for bucket area.",
reservedNumBuffers,
reservedNumBuffers * segmentSize,
initBucketSegmentNum);
}
// ----------------------- Abstract Interface -----------------------
@Override
public long getNumKeys() {
return numElements;
}
// ----------------------- Public interface -----------------------
/**
* Append an value into the hash map's record area.
*
* @return An BinaryRowData mapping to the memory segments in the map's record area belonging to
* the newly appended value.
* @throws EOFException if the map can't allocate much more memory.
*/
public BinaryRowData append(LookupInfo<K, BinaryRowData> lookupInfo, BinaryRowData value)
throws IOException {
try {
if (numElements >= growthThreshold) {
growAndRehash();
// update info's bucketSegmentIndex and bucketOffset
lookup(lookupInfo.key);
}
BinaryRowData toAppend = hashSetMode ? reusedValue : value;
int pointerToAppended = recordArea.appendRecord(lookupInfo, toAppend);
bucketSegments
.get(lookupInfo.bucketSegmentIndex)
.putInt(lookupInfo.bucketOffset, pointerToAppended);
bucketSegments
.get(lookupInfo.bucketSegmentIndex)
.putInt(lookupInfo.bucketOffset + ELEMENT_POINT_LENGTH, lookupInfo.keyHashCode);
numElements++;
recordArea.setReadPosition(pointerToAppended);
((RecordArea) recordArea).skipKey();
return recordArea.readValue(reusedValue);
} catch (EOFException e) {
numSpillFiles++;
spillInBytes += recordArea.getSegmentsSize();
throw e;
}
}
public long getNumSpillFiles() {
return numSpillFiles;
}
public long getUsedMemoryInBytes() {
return bucketSegments.size() * ((long) segmentSize) + recordArea.getSegmentsSize();
}
public long getSpillInBytes() {
return spillInBytes;
}
public long getNumElements() {
return numElements;
}
/** Returns an iterator for iterating over the entries of this map. */
@SuppressWarnings("WeakerAccess")
public KeyValueIterator<K, BinaryRowData> getEntryIterator() {
if (destructiveIterator != null) {
throw new IllegalArgumentException(
"DestructiveIterator is not null, so this method can't be invoke!");
}
return ((RecordArea) recordArea).entryIterator();
}
/** @return the underlying memory segments of the hash map's record area */
@SuppressWarnings("WeakerAccess")
public ArrayList<MemorySegment> getRecordAreaMemorySegments() {
return ((RecordArea) recordArea).segments;
}
@SuppressWarnings("WeakerAccess")
public List<MemorySegment> getBucketAreaMemorySegments() {
return bucketSegments;
}
/** release the map's record and bucket area's memory segments. */
public void free() {
free(false);
}
/** @param reservedRecordMemory reserved fixed memory or not. */
public void free(boolean reservedRecordMemory) {
recordArea.release();
destructiveIterator = null;
super.free(reservedRecordMemory);
}
/** reset the map's record and bucket area's memory segments for reusing. */
public void reset() {
// reset the record segments.
recordArea.reset();
destructiveIterator = null;
super.reset();
}
/**
* @return true when BytesHashMap's valueTypeInfos.length == 0. Any appended value will be
* ignored and replaced with a reusedValue as a present tag.
*/
@VisibleForTesting
boolean isHashSetMode() {
return hashSetMode;
}
// ----------------------- Private methods -----------------------
static int getVariableLength(LogicalType[] types) {
int length = 0;
for (LogicalType type : types) {
if (!BinaryRowData.isInFixedLengthPart(type)) {
// find a better way of computing generic type field variable-length
// right now we use a small value assumption
length += 16;
}
}
return length;
}
// ----------------------- Record Area -----------------------
private final class RecordArea implements BytesMap.RecordArea<K, BinaryRowData> {
private final ArrayList<MemorySegment> segments = new ArrayList<>();
private final RandomAccessInputView inView;
private final SimpleCollectingOutputView outView;
RecordArea() {
this.outView = new SimpleCollectingOutputView(segments, memoryPool, segmentSize);
this.inView = new RandomAccessInputView(segments, segmentSize);
}
public void release() {
returnSegments(segments);
segments.clear();
}
public void reset() {
release();
// request a new memory segment from freeMemorySegments
// reset segmentNum and positionInSegment
outView.reset();
inView.setReadPosition(0);
}
// ----------------------- Append -----------------------
public int appendRecord(LookupInfo<K, BinaryRowData> lookupInfo, BinaryRowData value)
throws IOException {
final long oldLastPosition = outView.getCurrentOffset();
// serialize the key into the BytesHashMap record area
int skip = keySerializer.serializeToPages(lookupInfo.getKey(), outView);
long offset = oldLastPosition + skip;
// serialize the value into the BytesHashMap record area
valueSerializer.serializeToPages(value, outView);
if (offset > Integer.MAX_VALUE) {
LOG.warn(
"We can't handle key area with more than Integer.MAX_VALUE bytes,"
+ " because the pointer is a integer.");
throw new EOFException();
}
return (int) offset;
}
@Override
public long getSegmentsSize() {
return segments.size() * ((long) segmentSize);
}
// ----------------------- Read -----------------------
public void setReadPosition(int position) {
inView.setReadPosition(position);
}
public boolean readKeyAndEquals(K lookupKey) throws IOException {
reusedKey = keySerializer.mapFromPages(reusedKey, inView);
return lookupKey.equals(reusedKey);
}
/** @throws IOException when invalid memory address visited. */
void skipKey() throws IOException {
keySerializer.skipRecordFromPages(inView);
}
public BinaryRowData readValue(BinaryRowData reuse) throws IOException {
// depends on BinaryRowDataSerializer to check writing skip
// and to find the real start offset of the data
return valueSerializer.mapFromPages(reuse, inView);
}
// ----------------------- Iterator -----------------------
private KeyValueIterator<K, BinaryRowData> entryIterator() {
return new EntryIterator();
}
private final class EntryIterator extends AbstractPagedInputView
implements KeyValueIterator<K, BinaryRowData> {
private int count = 0;
private int currentSegmentIndex = 0;
private EntryIterator() {
super(segments.get(0), segmentSize, 0);
destructiveIterator = this;
}
@Override
public boolean advanceNext() throws IOException {
if (count < numElements) {
count++;
// segment already is useless any more.
keySerializer.mapFromPages(reusedKey, this);
valueSerializer.mapFromPages(reusedValue, this);
return true;
}
return false;
}
@Override
public K getKey() {
return reusedKey;
}
@Override
public BinaryRowData getValue() {
return reusedValue;
}
public boolean hasNext() {
return count < numElements;
}
@Override
protected int getLimitForSegment(MemorySegment segment) {
return segmentSize;
}
@Override
protected MemorySegment nextSegment(MemorySegment current) {
return segments.get(++currentSegmentIndex);
}
}
}
}
|
package cn.mailu.LushX.searcher.impl;
import org.junit.Test;
import static org.junit.Assert.*;
public class ChenluoLushxSearcherImplTest {
ChenluoLushxSearcherImpl chenluoLushxSearcher=new ChenluoLushxSearcherImpl();
@Test
public void parsePage() throws Exception {
chenluoLushxSearcher.parsePage("");
}
}
|
/*
* Copyright (c) 2014 EMC Corporation
* All Rights Reserved
*/
package com.emc.storageos.management.backup;
import java.util.List;
import java.util.TreeSet;
public class BackupFileSet extends TreeSet<BackupFile> {
int quorumSize;
public BackupFileSet(int quorumSize) {
this.quorumSize = quorumSize;
}
public BackupFileSet subsetOf(String tag, BackupType type, String node) {
BackupFileSet set = new BackupFileSet(this.quorumSize);
for (BackupFile file : this) {
if (file.matches(tag, type, node)) {
set.add(file);
}
}
return set;
}
public void addAll(List<BackupSetInfo> infos, String node) {
for (BackupSetInfo info : infos) {
this.add(new BackupFile(info, node));
}
}
public TreeSet<String> uniqueNodes() {
TreeSet<String> uniqueNodes = new TreeSet<>();
for (BackupFile file : this) {
uniqueNodes.add(file.node);
}
return uniqueNodes;
}
public TreeSet<String> uniqueTags() {
TreeSet<String> tagSet = new TreeSet<>();
for (BackupFile file : this) {
tagSet.add(file.tag);
}
return tagSet;
}
/**
* Given a list of files for a tag, check if they can form a valid backup set
*/
public boolean isValid() {
if (size() == 0) {
return false;
}
String backupTag = this.first().tag;
BackupFileSet zkFiles = subsetOf(backupTag, BackupType.zk, null);
BackupFileSet dbFiles = subsetOf(backupTag, BackupType.db, null);
BackupFileSet geodbFiles = subsetOf(backupTag, BackupType.geodb, null);
BackupFileSet geodbmultivdcFiles = subsetOf(backupTag, BackupType.geodbmultivdc, null);
BackupFileSet infoFile = subsetOf(backupTag, BackupType.info, null);
if (zkFiles.size() == 0 || dbFiles.size() < this.quorumSize || geodbFiles.size() < this.quorumSize
&& geodbmultivdcFiles.size() < this.quorumSize || infoFile.size() == 0) {
return false;
}
return true;
}
}
|
/*******************************************************************************
* 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 apps.sightlyperf.test;
import java.util.Iterator;
import javax.script.Bindings;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.scripting.sightly.pojo.Use;
public class Test implements Use {
private String text = null;
private String tag = null;
private boolean includeChildren = false;
private Iterator<Resource> children = null;
public void init(Bindings bindings) {
Resource resource = (Resource)bindings.get("resource");
ValueMap properties = (ValueMap)bindings.get("properties");
if (properties != null) {
Object text = properties.get("text");
if (text != null) {
this.text = text.toString();
}
Object tag = properties.get("tag");
if (tag != null) {
this.tag = tag.toString();
}
Object includeChildren = properties.get("includeChildren");
if (includeChildren != null) {
this.includeChildren = Boolean.parseBoolean(includeChildren.toString());
this.children = resource.listChildren();
}
}
if (this.text == null) {
this.text = resource.getPath();
}
}
public String getText() {
return this.text;
}
public String getTag() {
return tag;
}
public String getStartTag() {
if (tag == null) {
return null;
}
return "<" + tag + ">";
}
public String getEndTag() {
if (tag == null) {
return null;
}
return "</" + tag + ">";
}
public boolean getIncludeChildren() {
return includeChildren;
}
public Iterator<Resource> getChildren() {
return this.children;
}
}
|
package org.spa.controller.item;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.spa.model.ItemImpl;
/**
* An interface that created to expose data of an item in the application<br/>
* This interface created so we can implement it at the model layer without expose the model implementation to the view layer
*
* @author Haim Adrian
* @since 11-Jun-20
*/
@JsonDeserialize(as = ItemImpl.class)
public interface Item {
/**
* @return Unique ID of this item
*/
String getId();
/**
* @return Name of this item
*/
String getName();
/**
* @return The category that this item belongs to. e.g. CPU
*/
String getCategory();
/**
* @return Some description about this item. Can be long, multi-line string
*/
String getDescription();
/**
* @return The price of this item. This is the original price that the store's management paid on the item
*/
double getPrice();
/**
* @return Profit percentage - How much money, in percentage with respect to the price, the store's management earns
*/
double getProfitPercent();
/**
* @return Discount percentage - How much money, in percentage with respect to the price+profit, the store's management gives
*/
double getDiscountPercent();
/**
* @return How many occurrences of this item there are
*/
int getCount();
/**
* @return The price after adding it the profit and discount values
*/
default double getActualPrice() {
return getPriceWithProfit() - getDiscountValue();
}
/**
* @return The price after adding it the profit value
*/
default double getPriceWithProfit() {
return getPrice() + getProfitValue();
}
/**
* @return The profit of this item
*/
default double getProfitValue() {
return getPrice() * (getProfitPercent() / 100.0);
}
/**
* @return The discount of this item
*/
default double getDiscountValue() {
return getPriceWithProfit() * (getDiscountPercent() / 100.0);
}
}
|
package com.stripe.example.activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.stripe.android.PaymentConfiguration;
import com.stripe.android.Stripe;
import com.stripe.android.model.Card;
import com.stripe.android.model.PaymentIntent;
import com.stripe.android.model.PaymentIntentParams;
import com.stripe.android.model.SourceParams;
import com.stripe.android.view.CardInputWidget;
import com.stripe.example.R;
import com.stripe.example.controller.ErrorDialogHandler;
import com.stripe.example.controller.ProgressDialogController;
import com.stripe.example.module.RetrofitFactory;
import com.stripe.example.service.StripeService;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;
public class PaymentIntentActivity extends AppCompatActivity {
private static final String TAG = PaymentIntentActivity.class.getName();
private static final String RETURN_URL = "stripe://payment_intent_return";
private ProgressDialogController mProgressDialogController;
private ErrorDialogHandler mErrorDialogHandler;
private CompositeSubscription mCompositeSubscription;
private Stripe mStripe;
private StripeService mStripeService;
private String mClientSecret;
private Button mConfirmPaymentIntent;
private Button mRetrievePaymentIntent;
private CardInputWidget mCardInputWidget;
private TextView mPaymentIntentValue;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment_intent_demo);
Button createPaymentIntent = findViewById(R.id.btn_create_payment_intent);
mRetrievePaymentIntent = findViewById(R.id.btn_retrieve_payment_intent);
mConfirmPaymentIntent = findViewById(R.id.btn_confirm_payment_intent);
mPaymentIntentValue = findViewById(R.id.payment_intent_value);
mCardInputWidget = findViewById(R.id.card_input_widget);
mProgressDialogController =
new ProgressDialogController(getSupportFragmentManager());
mErrorDialogHandler = new ErrorDialogHandler(getSupportFragmentManager());
mCompositeSubscription = new CompositeSubscription();
mStripe = new Stripe(this);
Retrofit retrofit = RetrofitFactory.getInstance();
mStripeService = retrofit.create(StripeService.class);
createPaymentIntent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
createPaymentIntent();
}
});
mRetrievePaymentIntent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
retrievePaymentIntent(mClientSecret);
}
});
mConfirmPaymentIntent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Card card = mCardInputWidget.getCard();
if (card != null) {
confirmPaymentIntent(mClientSecret, card);
}
}
});
}
private Map<String, Object> createPaymentIntentParams() {
Map<String, Object> params = new HashMap<>();
params.put("allowed_source_types[]", "card");
params.put("amount", 1000);
params.put("currency", "usd");
return params;
}
void createPaymentIntent() {
Subscription subscription = mStripeService.createPaymentIntent(createPaymentIntentParams())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(new Action0() {
@Override
public void call() {
mProgressDialogController.setMessageResource(R.string.creating_payment_intent);
mProgressDialogController.startProgress();
}
})
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
mProgressDialogController.finishProgress();
}
})
.subscribe(
// Because we've made the mapping above, we're now subscribing
// to the result of creating a 3DS Source
new Action1<ResponseBody>() {
@Override
public void call(ResponseBody responseBody) {
try {
JSONObject jsonObject = new JSONObject(responseBody.string());
mClientSecret = jsonObject.optString("secret");
mConfirmPaymentIntent.setEnabled(mClientSecret != null);
mRetrievePaymentIntent.setEnabled(mClientSecret != null);
} catch (IOException | JSONException exception) {
Log.e(TAG, exception.toString());
}
}
},
new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
mErrorDialogHandler.showError(throwable.getLocalizedMessage());
}
}
);
mCompositeSubscription.add(subscription);
}
void retrievePaymentIntent(final String clientSecret) {
final Observable<PaymentIntent> paymentIntentObservable =
Observable.fromCallable(
new Callable<PaymentIntent>() {
@Override
public PaymentIntent call() throws Exception {
PaymentIntentParams paymentIntentParams =
PaymentIntentParams.createRetrievePaymentIntentParams(clientSecret);
return mStripe.retrievePaymentIntentSynchronous(
paymentIntentParams,
PaymentConfiguration.getInstance().getPublishableKey());
}
});
Subscription subscription = paymentIntentObservable
.subscribeOn(Schedulers.io())
.doOnSubscribe(new Action0() {
@Override
public void call() {
mProgressDialogController.setMessageResource(R.string.retrieving_payment_intent);
mProgressDialogController.startProgress();
}
})
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
mProgressDialogController.finishProgress();
}
})
.observeOn(AndroidSchedulers.mainThread()).subscribe(
new Action1<PaymentIntent>() {
@Override
public void call(PaymentIntent paymentIntent) {
if (paymentIntent != null) {
mPaymentIntentValue.setText(paymentIntent.toJson().toString());
} else {
mPaymentIntentValue.setText(R.string.error_while_retrieving_payment_intent);
}
}
},
new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
Log.e(TAG, throwable.toString());
}
}
);
mCompositeSubscription.add(subscription);
}
void confirmPaymentIntent(final String clientSecret, Card card) {
final SourceParams sourceParams = SourceParams.createCardParams(card);
final Observable<PaymentIntent> paymentIntentObservable =
Observable.fromCallable(
new Callable<PaymentIntent>() {
@Override
public PaymentIntent call() throws Exception {
PaymentIntentParams paymentIntentParams =
PaymentIntentParams.createConfirmPaymentIntentWithSourceDataParams(
sourceParams,
clientSecret,
RETURN_URL);
return mStripe.confirmPaymentIntentSynchronous(
paymentIntentParams,
PaymentConfiguration.getInstance().getPublishableKey());
}
});
Subscription subscription = paymentIntentObservable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(new Action0() {
@Override
public void call() {
mProgressDialogController.setMessageResource(R.string.confirming_payment_intent);
mProgressDialogController.startProgress();
}
})
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
mProgressDialogController.finishProgress();
}
})
.subscribe(
new Action1<PaymentIntent>() {
@Override
public void call(PaymentIntent paymentIntent) {
if (paymentIntent != null) {
mPaymentIntentValue.setText(paymentIntent.toString());
Uri authUrl = paymentIntent.getAuthorizationUrl();
if (paymentIntent.getStatus().equals("requires_source_action") && authUrl != null) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, authUrl);
startActivity(browserIntent);
}
}
}
},
new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
Log.e(TAG, throwable.toString());
}
}
);
mCompositeSubscription.add(subscription);
}
}
|
package com.dsa.dp;
import java.util.Arrays;
/**
Given a string S and a string T, count the number of distinct subsequences of S which equals T.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none)
of the characters without disturbing the relative positions of the remaining characters.
(ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).
Here is an example:
S = "rabbbit", T = "rabbit"
ra bbit
rab bit
rabb it
Return 3.
The idea is the following:
we will build an array res where res[i+1][j+1] means that S[0..j] contains T[0..i] that many times as distinct subsequences.
Therefore the result will be res[T.length()][S.length()].
we can build this array rows-by-rows:
the first row must be filled with 1. That’s because the empty string is a subsequence of any string but only 1 time.
So res[0][j] = 1 for every j. So with this we not only make our lives easier, but we also return correct value if T is an empty string.
the first column of every rows except the first must be 0. This is because an empty string cannot contain a non-empty string
as a substring – the very first item of the array: res[0][0] = 1, because an empty string contains the empty string 1 time.
So the matrix looks like this:
S 0123....j
T +----------+
|1111111111|
0 |0 |
1 |0 |
2 |0 |
. |0 |
. |0 |
i |0 |
From here we can easily fill the whole grid: for each (x, y), we check if S[x] == T[y] we add the previous item and
the previous item in the previous row, otherwise we copy the previous item in the same row. The reason is simple:
if the current character in S doesn’t equal to current character T, then we have the same number of
distinct subsequences as we had without the new character.
if the current character in S equal to the current character T, then the distinct number of subsequences:
the number we had before plus the distinct number of subsequences we had with less longer T and less longer S.
An example:
S: [acdabefbc] and T: [ab]
first we check with a:
* *
S = [acdabefbc]
res[1] = [0111222222]
then we check with ab:
* * ]
S = [acdabefbc]
res[1] = [0111222222]
res[2] = [0000022244]
And the result is 4, as the distinct subsequences are:
S = [a b ]
S = [a b ]
S = [ ab ]
S = [ a b ]
*/
public class DistinctSubsequences {
public static int distinctSubSeq(String S, String T) {
// array creation
int[][] res = new int[T.length()+1][S.length()+1];
// filling the first row: with 1s
for(int j=0; j<=S.length(); j++) {
res[0][j] = 1;
}
// the first column is 0 by default in every other rows but the first, which we need.
for(int i=0; i<T.length(); i++) {
for(int j=0; j<S.length(); j++) {
if(T.charAt(i) == S.charAt(j)) {
res[i+1][j+1] = res[i][j] + res[i+1][j];
} else {
res[i+1][j+1] = res[i+1][j];
}
}
}
/*
for(int i = 0; i<3; i++) {
for(int j=0; j<10; j++){
System.out.print(res[i][j] + " ");
}
System.out.println(" ");
}
*/
return res[T.length()][S.length()];
}
public static void main(String[] args) {
int res = distinctSubSeq("acdabefbc", "ab");
System.out.println(res);
}
}
|
package it.unibz.inf.ontop.owlapi;
import it.unibz.inf.ontop.injection.OntopSQLOWLAPIConfiguration;
import it.unibz.inf.ontop.answering.reformulation.ExecutableQuery;
import it.unibz.inf.ontop.answering.reformulation.impl.SQLExecutableQuery;
import it.unibz.inf.ontop.owlapi.OntopOWLFactory;
import it.unibz.inf.ontop.owlapi.OntopOWLReasoner;
import it.unibz.inf.ontop.owlapi.connection.OntopOWLConnection;
import it.unibz.inf.ontop.owlapi.connection.OntopOWLStatement;
import it.unibz.inf.ontop.owlapi.resultset.OWLBindingSet;
import it.unibz.inf.ontop.owlapi.resultset.TupleOWLResultSet;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.semanticweb.owlapi.model.OWLObject;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class RedundantJoinFKProfTest {
private static final String CREATE_SCRIPT = "src/test/resources/test/redundant_join/redundant_join_fk_create.sql";
private static final String DROP_SCRIPT = "src/test/resources/test/redundant_join/redundant_join_fk_drop.sql";
private static final String OWL_FILE = "src/test/resources/test/redundant_join/redundant_join_fk_test.owl";
private static final String ODBA_FILE = "src/test/resources/test/redundant_join/redundant_join_fk_test.obda";
private static final String NO_OPTIMIZATION_MSG = "The table professors should not be used";
private static final String URL = "jdbc:h2:mem:professor";
private static final String USER = "sa";
private static final String PASSWORD = "sa";
private Connection conn;
@Before
public void setUp() throws Exception {
conn = DriverManager.getConnection(URL, USER, PASSWORD);
Statement st = conn.createStatement();
FileReader reader = new FileReader(CREATE_SCRIPT);
BufferedReader in = new BufferedReader(reader);
StringBuilder bf = new StringBuilder();
String line = in.readLine();
while (line != null) {
bf.append(line);
line = in.readLine();
}
in.close();
st.executeUpdate(bf.toString());
conn.commit();
}
@After
public void tearDown() throws Exception {
dropTables();
conn.close();
}
private void dropTables() throws SQLException, IOException {
Statement st = conn.createStatement();
FileReader reader = new FileReader(DROP_SCRIPT);
BufferedReader in = new BufferedReader(reader);
StringBuilder bf = new StringBuilder();
String line = in.readLine();
while (line != null) {
bf.append(line);
line = in.readLine();
}
in.close();
st.executeUpdate(bf.toString());
st.close();
conn.commit();
}
@Test
public void testQuery() throws Exception {
String query = "PREFIX : <http://www.semanticweb.org/user/ontologies/2016/8/untitled-ontology-84#>\n" +
"PREFIX owl: <http://www.w3.org/2002/07/owl#>\n" +
"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n" +
"PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n" +
"PREFIX xml: <http://www.w3.org/XML/1998/namespace>\n" +
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n" +
"SELECT * {\n" +
"?p a :Professor ; :teaches ?c .\n" +
"}";
List<String> expectedValues = new ArrayList<>();
expectedValues.add("<http://www.semanticweb.org/user/ontologies/2016/8/untitled-ontology-84#professor/1>");
expectedValues.add("<http://www.semanticweb.org/user/ontologies/2016/8/untitled-ontology-84#professor/1>");
expectedValues.add("<http://www.semanticweb.org/user/ontologies/2016/8/untitled-ontology-84#professor/3>");
expectedValues.add("<http://www.semanticweb.org/user/ontologies/2016/8/untitled-ontology-84#professor/8>");
String sql = checkReturnedValuesAndReturnSql(query, expectedValues);
System.out.println("SQL Query: \n" + sql);
assertFalse(NO_OPTIMIZATION_MSG, sql.contains("professors"));
assertFalse(NO_OPTIMIZATION_MSG, sql.contains("PROFESSORS"));
}
private String checkReturnedValuesAndReturnSql(String query, List<String> expectedValues) throws Exception {
OntopOWLFactory factory = OntopOWLFactory.defaultFactory();
OntopSQLOWLAPIConfiguration config = OntopSQLOWLAPIConfiguration.defaultBuilder()
.nativeOntopMappingFile(ODBA_FILE)
.ontologyFile(OWL_FILE)
.jdbcUrl(URL)
.jdbcUser(USER)
.jdbcPassword(PASSWORD)
.enableTestMode()
.build();
OntopOWLReasoner reasoner = factory.createReasoner(config);
// Now we are ready for querying
OntopOWLConnection conn = reasoner.getConnection();
OntopOWLStatement st = conn.createStatement();
String sql;
int i = 0;
List<String> returnedValues = new ArrayList<>();
try {
ExecutableQuery executableQuery = st.getExecutableQuery(query);
if (! (executableQuery instanceof SQLExecutableQuery))
throw new IllegalStateException("A SQLExecutableQuery was expected");
sql = ((SQLExecutableQuery)executableQuery).getSQL();
TupleOWLResultSet rs = st.executeSelectQuery(query);
while (rs.hasNext()) {
final OWLBindingSet bindingSet = rs.next();
OWLObject ind1 = bindingSet.getOWLObject("p");
// log.debug(ind1.toString());
returnedValues.add(ind1.toString());
java.lang.System.out.println(ind1);
i++;
}
} catch (Exception e) {
throw e;
} finally {
conn.close();
reasoner.dispose();
}
assertTrue(String.format("%s instead of \n %s", returnedValues.toString(), expectedValues.toString()),
returnedValues.equals(expectedValues));
assertTrue(String.format("Wrong size: %d (expected %d)", i, expectedValues.size()), expectedValues.size() == i);
return sql;
}
}
|
package com.billow.alipay.wap.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.billow.alipay.base.service.impl.AliPayBaseServiceImpl;
import com.billow.alipay.wap.config.AliPayWapConfig;
import com.billow.alipay.wap.model.OrderInfo;
import com.billow.alipay.wap.service.AliPayUpdateOrderStausService;
import com.billow.alipay.wap.service.AliPayWapService;
import com.billow.alipay.wap.utils.AliPayUtils;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* @author liuyongtao
* @create 2019-12-24 11:30
*/
@Slf4j
public class AliPayWapServiceImpl extends AliPayBaseServiceImpl implements AliPayWapService {
private AliPayWapConfig aliPayWapConfig;
private AlipayClient alipayClient;
public AliPayWapServiceImpl(@NonNull AliPayWapConfig aliPayWapConfig) {
this.aliPayWapConfig = aliPayWapConfig;
this.alipayClient = new DefaultAlipayClient(aliPayWapConfig.getGatewayUrl(), aliPayWapConfig.getAppId(),
aliPayWapConfig.getPrivateKey(), aliPayWapConfig.getFormat(), aliPayWapConfig.getCharset(),
aliPayWapConfig.getAliPayPublicKey(), aliPayWapConfig.getSignType());
super.setAlipayClient(this.alipayClient);
}
@Override
public AlipayTradeWapPayResponse wapPay(AlipayTradeWapPayModel model) throws Exception {
log.debug("请求入参:{}", JSONObject.toJSONString(model));
AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
request.setBizModel(model);
AlipayTradeWapPayResponse execute = alipayClient.execute(request);
log.debug("请求出参:{}", JSONObject.toJSONString(execute));
if (!execute.isSuccess()) {
throw new RuntimeException("手机网站支付接口2.0,支付失败,请稍后重试!");
}
return execute;
}
@Override
public String notifyUrl(HttpServletRequest request, AliPayUpdateOrderStausService updateOrderStausService) {
log.debug("异常通知========>>>>>");
try {
return this.callBackNotify(request, updateOrderStausService);
} catch (Exception e) {
log.error(e.getLocalizedMessage());
}
log.debug("notify_url 验证失败");
return "failure";
}
private String callBackNotify(HttpServletRequest request, AliPayUpdateOrderStausService updateOrderStausService) throws Exception {
Map<String, String> map = AliPayUtils.toMap(request);
log.debug("请求入参:{}", JSONObject.toJSONString(map));
// 验签名
boolean verifyResult = AlipaySignature.rsaCheckV1(map, aliPayWapConfig.getAliPayPublicKey(),
aliPayWapConfig.getCharset(), aliPayWapConfig.getSignType());
log.debug("验证:{}", verifyResult);
if (verifyResult) {
if (updateOrderStausService != null) {
OrderInfo orderInfo = new OrderInfo(map.get("app_id"), map.get("out_trade_no"),
map.get("total_amount"), map.get("trade_no"));
// 业务校验
updateOrderStausService.checkOrderData(orderInfo);
// 更新订单状态
updateOrderStausService.updateOrderStatus(orderInfo);
}
return "success";
}
return "failure";
}
}
|
package xreliquary.compat.jei;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.item.crafting.ShapelessRecipe;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import xreliquary.crafting.FragmentRecipeHelper;
import xreliquary.init.ModItems;
import xreliquary.items.MobCharmRegistry;
import xreliquary.reference.Reference;
import java.util.ArrayList;
import java.util.List;
public class SpawnEggRecipeMaker {
private SpawnEggRecipeMaker() {}
public static List<ShapelessRecipe> getRecipes() {
List<ShapelessRecipe> recipes = new ArrayList<>();
for (String regName : MobCharmRegistry.getRegisteredNames()) {
Ingredient fragmentIngredient = Ingredient.fromStacks(ModItems.MOB_CHARM_FRAGMENT.getStackFor(regName));
Ingredient eggIngredient = Ingredient.fromItems(Items.EGG);
NonNullList<Ingredient> inputs = NonNullList.create();
inputs.add(fragmentIngredient);
inputs.add(fragmentIngredient);
inputs.add(eggIngredient);
ItemStack output = FragmentRecipeHelper.getSpawnEggStack(regName);
ResourceLocation id = new ResourceLocation(Reference.MOD_ID, "xreliquary.fragment_to_spawn_egg." + output.getTranslationKey());
recipes.add(new ShapelessRecipe(id, "xreliquary.fragment_to_spawn_egg", output, inputs));
}
return recipes;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package at.adridi.finanzverwaltung.converter;
import at.adridi.finanzverwaltung.db.DAO;
import at.adridi.finanzverwaltung.model.Ausgabenkategorie;
import java.util.List;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
/**
*
* @author adridi
*/
@FacesConverter("susgabenKategorieConverter")
public class AusgabenKategorieConverter implements Converter {
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value == null || value.trim().isEmpty()) {
return "";
} else {
DAO dao = new DAO();
List<Ausgabenkategorie> liste = dao.getAllAusgabenkategorie();
Ausgabenkategorie kategorieAusgewaehlt=null;
for (Ausgabenkategorie a : liste) {
if ((a.getKategoriebezeichnung()).equals(value)) {
kategorieAusgewaehlt = a;
}
}
return kategorieAusgewaehlt;
}
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value == null) {
return "";
} else {
return value.toString();
}
}
}
|
package tech.zone84.examples.batches;
import com.google.common.collect.Maps;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
public class ChangeAggregator {
public Collection<AggregatedPropertyChange> aggregate(List<PropertyChange> batch) {
var buckets = Maps.<Bucket, Aggregation>newLinkedHashMap();
for (var item: batch) {
var aggregation = buckets.computeIfAbsent(new Bucket(item.deviceId(), item.property()), bucket -> new Aggregation());
aggregation.aggregate(item.change());
}
return buckets.entrySet()
.stream()
.map(entry -> entry.getValue().toPropertyChange(entry.getKey()))
.collect(Collectors.toList());
}
record Bucket(int deviceId, String propertyName) {}
private class Aggregation {
private int change = 0;
private int mergedChanges = 0;
void aggregate(int valueChange) {
change += valueChange;
mergedChanges++;
}
AggregatedPropertyChange toPropertyChange(Bucket bucket) {
return new AggregatedPropertyChange(
bucket.deviceId(), bucket.propertyName(), change, mergedChanges
);
}
}
}
|
package com.gpch.login.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "message")
public class ChatMessage {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "message_id")
private int id;
@Column(name = "content")
private String content;
@Column(name = "sender")
private String sender;
@Column(name = "type")
private MessageType type;
public enum MessageType {CHAT, LEAVE, JOIN}
}
|
/*
* Copyright 2011 Red Hat, Inc. and/or its affiliates.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
package org.infinispan.configuration.cache;
/**
* Cache replication mode.
*/
public enum CacheMode {
/**
* Data is not replicated.
*/
LOCAL,
/**
* Data replicated synchronously.
*/
REPL_SYNC,
/**
* Data replicated asynchronously.
*/
REPL_ASYNC,
/**
* Data invalidated synchronously.
*/
INVALIDATION_SYNC,
/**
* Data invalidated asynchronously.
*/
INVALIDATION_ASYNC,
/**
* Synchronous DIST
*/
DIST_SYNC,
/**
* Async DIST
*/
DIST_ASYNC;
/**
* Returns true if the mode is invalidation, either sync or async.
*/
public boolean isInvalidation() {
return this == INVALIDATION_SYNC || this == INVALIDATION_ASYNC;
}
public boolean isSynchronous() {
return this == REPL_SYNC || this == DIST_SYNC || this == INVALIDATION_SYNC || this == LOCAL;
}
public boolean isClustered() {
return this != LOCAL;
}
public boolean isDistributed() {
return this == DIST_SYNC || this == DIST_ASYNC;
}
public boolean isReplicated() {
return this == REPL_SYNC || this == REPL_ASYNC;
}
public CacheMode toSync() {
switch (this) {
case REPL_ASYNC:
return REPL_SYNC;
case INVALIDATION_ASYNC:
return INVALIDATION_SYNC;
case DIST_ASYNC:
return DIST_SYNC;
default:
return this;
}
}
public CacheMode toAsync() {
switch (this) {
case REPL_SYNC:
return REPL_ASYNC;
case INVALIDATION_SYNC:
return INVALIDATION_ASYNC;
case DIST_SYNC:
return DIST_ASYNC;
default:
return this;
}
}
public String friendlyCacheModeString() {
switch (this) {
case REPL_SYNC:
case REPL_ASYNC:
return "REPLICATED";
case INVALIDATION_SYNC:
case INVALIDATION_ASYNC:
return "INVALIDATED";
case DIST_SYNC:
case DIST_ASYNC:
return "DISTRIBUTED";
case LOCAL:
return "LOCAL";
}
throw new IllegalArgumentException("Unknown cache mode " + this);
}
}
|
package com.seedfinding.mccore.net;
import java.io.IOException;
public interface IByteSerializable {
void read(ByteBuffer buffer) throws IOException;
void write(ByteBuffer buffer) throws IOException;
}
|
package org.protege.editor.owl.model.search;
import org.protege.editor.owl.ui.renderer.styledstring.StyledString;
import org.semanticweb.owlapi.model.OWLObject;
/**
* Author: Matthew Horridge<br>
* Stanford University<br>
* Bio-Medical Informatics Research Group<br>
* Date: 18/09/2012
* <p>
* A SearchMetadata object contains a (partial) string representation of some object that can be searched. There
* are various categories of SearchMetadata objects as defined by the {@link SearchCategory} enum. Further
* more, each SearchMetadata object can belong to a subgroup.
* </p>
*/
public class SearchMetadata implements Comparable<SearchMetadata> {
private SearchCategory category;
private String groupDescription;
private OWLObject subject;
private String subjectRendering;
private String searchString;
/**
* Records search metadata for a given object.
* @param category The category which the search metadata falls into.
* @param groupDescription The description (human readable name) of the subgroup which the metadata falls into.
* @param subject The subject to which the search string pertains to. This is usually an entity or an ontology
* i.e.
* something which can be selected in Protege.
* @param subjectRendering A rendering of the subject. This rendering is used to compare search metadata objects.
* @param searchString The string that should be searched.
*/
public SearchMetadata(SearchCategory category, String groupDescription, OWLObject subject, String subjectRendering, String searchString) {
this.category = category;
this.groupDescription = groupDescription;
this.subject = subject;
this.subjectRendering = subjectRendering;
this.searchString = searchString;
}
/**
* Gets the category which this SearchMetadata belongs to.
* @return The SearchMetadataCategory. Not <code>null</code>.
*/
public SearchCategory getCategory() {
return category;
}
/**
* Gets the group description of this SearchMetadata object.
* @return The group description. Not <code>null</code>.
*/
public String getGroupDescription() {
return groupDescription;
}
/**
* Gets the subject of this SearchMetadata object. The subject is the main object that can be selected in protege
* to which the search string pertains. For example, the subject of a data property assertion would be the subject
* individual.
* @return The subject. Not <code>null</code>.
*/
public OWLObject getSubject() {
return subject;
}
/**
* Gets the rendering of the subject of this SearchMetadata.
* @return The subject rendering. Not <code>null</code>.
*/
public String getSubjectRendering() {
return subjectRendering;
}
/**
* Determines whether the search string provided by this SearchMetadata object is in fact the display name
* rendering
* of the subject of this SearchMetadata object.
* @return <code>true</code> if the search string is a display name, otherwise <code>false</code>.
*/
public boolean isSearchStringEntityRendering() {
return category == SearchCategory.DISPLAY_NAME;
}
/**
* Gets the search string which this SearchMetadata object records.
* @return The search string. Not <code>null</code>.
*/
public String getSearchString() {
return searchString;
}
/**
* Gets a stylised version of the search string. This stylised version contains exactly the same underlying string
* as returned by {@link #getSearchString()}.
* @return A {@link StyledString} rendering of the search string (for display in a UI). Not <code>null</code>.
*/
public StyledString getStyledSearchSearchString() {
return new StyledString(searchString);
}
public int compareTo(SearchMetadata o) {
int catDiff = this.category.compareTo(o.category);
if (catDiff != 0) {
return catDiff;
}
int typeDiff = this.groupDescription.compareTo(o.groupDescription);
if (typeDiff != 0) {
return typeDiff;
}
int subjectRenderingDiff = this.subjectRendering.compareTo(o.subjectRendering);
if (subjectRenderingDiff != 0) {
return subjectRenderingDiff;
}
int subjectDiff = this.subject.compareTo(o.subject);
if (subjectDiff != 0) {
return subjectDiff;
}
return searchString.compareTo(o.searchString);
}
}
|
/**
* This package consists of configuration files to enable dozer custom converters to work and serve as demonstration. <br>
* this basically helps user in understanding how the bean configuration file and the dozerBeanMapping.xml needs to be setup for getting the custom converters to work
* <p>
*
* <pre>
* Change Log
* ===============================================================================
* Date Description
* --------- ---------------------------------------------------------------
* July-2015 Added beans.xml which contain all constant converters and example objects.
* Used bean-default.properties to cut-short the repeating package names in the class field of bean definition
* Used to set system properties(have also added logging.properties) for java.util.Logger to format the log lines to my taste
* Added dozerBeanMapping.xml to capture the example object conversions of different types.
* </pre>
* The dozer bean mapping xml needs to be looked at the following specifics to get these custom converters working
* <br>
* The custom-converter-param values have the following special prefixes for a purpose:
* <ll>
* <li> A value for such as custom-converter-param=<b><i>bean:bean-name</i></b> indicates that the
* target object will be assigned directly from a bean whose id is <i>bean-name</i> from the bean configuration file.
* This is used for complete substitution of target fields.
* Please refer to map-id="source-to-substitute-target" in the dozerBeanMapping.xml for completeness.
* <li> A value for such as custom-converter-id="to-date" indicates that the
* field of a class will be assigned a constant (date in this case) object.
* <li> A value for such as custom-converter-param="map-id:source-to-target" indicates that the
* singular element type to be mapped to a list of destination target type;
* it is imperative a mapping between singular elements of source and target mapping must alread exists
* </ll>
*/
|
/*
* 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 fr.pilato.elasticsearch.tools.alias;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AliasElasticsearchUpdater {
private static final Logger logger = LoggerFactory.getLogger(AliasElasticsearchUpdater.class);
/**
* Create an alias if needed
* @param client Client to use
* @param alias Alias name
* @param index Index name
* @throws Exception When alias can not be set
*/
@Deprecated
public static void createAlias(Client client, String alias, String index) throws Exception {
logger.trace("createAlias({},{})", alias, index);
AcknowledgedResponse response = client.admin().indices().prepareAliases().addAlias(index, alias).get();
if (!response.isAcknowledged()) throw new Exception("Could not define alias [" + alias + "] for index [" + index + "].");
logger.trace("/createAlias({},{})", alias, index);
}
/**
* Create an alias if needed
* @param client Client to use
* @param alias Alias name
* @param index Index name
* @throws Exception When alias can not be set
*/
public static void createAlias(RestClient client, String alias, String index) throws Exception {
logger.trace("createAlias({},{})", alias, index);
assert client != null;
assert alias != null;
assert index != null;
Request request = new Request("POST", "/_aliases/");
request.setJsonEntity("{\"actions\":[{\"add\":{\"index\":\"" + index +"\",\"alias\":\"" + alias +"\"}}]}");
Response response = client.performRequest(request);
if (response.getStatusLine().getStatusCode() != 200) {
logger.warn("Could not create alias [{}] on index [{}]", alias, index);
throw new Exception("Could not create alias ["+alias+"] on index ["+index+"].");
}
logger.trace("/createAlias({},{})", alias, index);
}
}
|
package org.omg.hw.performance;
/**
* Generated from IDL interface "PerformanceManagementMgr_I"
* @author JacORB IDL compiler V 2.2.3, 10-Dec-2005
*/
public final class PerformanceManagementMgr_IHolder implements org.omg.CORBA.portable.Streamable{
public PerformanceManagementMgr_I value;
public PerformanceManagementMgr_IHolder()
{
}
public PerformanceManagementMgr_IHolder (final PerformanceManagementMgr_I initial)
{
value = initial;
}
public org.omg.CORBA.TypeCode _type()
{
return PerformanceManagementMgr_IHelper.type();
}
public void _read (final org.omg.CORBA.portable.InputStream in)
{
value = PerformanceManagementMgr_IHelper.read (in);
}
public void _write (final org.omg.CORBA.portable.OutputStream _out)
{
PerformanceManagementMgr_IHelper.write (_out,value);
}
}
|
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.support;
import org.springframework.aop.ClassFilter;
import org.springframework.aop.MethodMatcher;
import org.springframework.aop.Pointcut;
/**
* 动态方法匹配的 Pointcut。
* <p>
* Convenient superclass when we want to force subclasses to
* implement MethodMatcher interface, but subclasses
* will want to be pointcuts. The getClassFilter() method can
* be overridden to customize ClassFilter behaviour as well.
*
* @author Rod Johnson
*/
public abstract class DynamicMethodMatcherPointcut extends DynamicMethodMatcher implements Pointcut {
@Override
public ClassFilter getClassFilter() {
return ClassFilter.TRUE;
}
@Override
public final MethodMatcher getMethodMatcher() {
return this;
}
}
|
/**
* 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 me.mingshan.magpie.api;
import java.io.Serializable;
/**
* Interface that logEvent.
*
* @author mingshan
*/
public interface Event extends Serializable {
/**
* Gets byte array of the message.
*
* @return the byte array
*/
byte[] getMessage();
/**
* Gets the name of current thread.
*
* @return the name
*/
String getThreadName();
/**
* Gets the id of current thread.
*
* @return the id
*/
long getThreadId();
/**
* The flag to indicate if this is the last event in a batch from the {@code RingBuffer}.
*
* @return see comments
*/
boolean isEndOfBatch();
}
|
// Copyright 2018 Twitter. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.twitter.heron.eco.submit;
import org.apache.storm.StormSubmitter;
import org.apache.storm.generated.StormTopology;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.twitter.heron.api.Config;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.internal.verification.VerificationModeFactory.times;
@RunWith(PowerMockRunner.class)
@PrepareForTest(StormSubmitter.class)
public class EcoSubmitterTest {
private EcoSubmitter subject;
@Before
public void setUpForEachTestCase() {
subject = new EcoSubmitter();
}
@Test
public void submitTopology_AllGood_BehavesAsExpected()
throws Exception {
Config config = new Config();
StormTopology topology = new StormTopology();
PowerMockito.spy(StormSubmitter.class);
PowerMockito.doNothing().when(StormSubmitter.class, "submitTopology",
any(String.class), any(Config.class), any(StormTopology.class));
subject.submitTopology("name", config, topology);
PowerMockito.verifyStatic(times(1));
StormSubmitter.submitTopology(anyString(), any(Config.class), any(StormTopology.class));
}
}
|
/*
* ====================================================================
* 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.poi.ss.formula.functions;
import static org.junit.Assert.assertEquals;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.junit.Test;
import java.io.IOException;
/**
*
*/
public class TestSumifsXSSF {
/**
* handle null cell predicate
*/
@Test
public void testBug60858() throws IOException {
try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("bug60858.xlsx")) {
FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator();
Sheet sheet = wb.getSheetAt(0);
Cell cell = sheet.getRow(1).getCell(5);
fe.evaluate(cell);
assertEquals(0.0, cell.getNumericCellValue(), 0.0000000000000001);
}
}
}
|
/*
* Copyright 2018 - 2019 Paul Hagedorn (Panzer1119)
*
* 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 de.codemakers.base.util.interfaces;
import java.io.Serializable;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
@FunctionalInterface
public interface Timestamp extends Serializable {
long getTimestamp();
default Instant toInstant() {
return Instant.ofEpochMilli(getTimestamp());
}
default ZonedDateTime toLocalZonedDateTime() {
return toZonedDateTime(ZoneId.systemDefault());
}
default ZonedDateTime toZonedDateTime(ZoneId zone) {
return ZonedDateTime.ofInstant(toInstant(), zone);
}
default LocalDateTime toLocalDateTime() {
return LocalDateTime.ofInstant(toInstant(), ZoneId.systemDefault());
}
default String toLocalISOZonedDateTime() {
return toISOZonedDateTime(ZoneId.systemDefault());
}
default String toISOZonedDateTime(ZoneId zone) {
return toZonedDateTime(zone).format(DateTimeFormatter.ISO_ZONED_DATE_TIME);
}
}
|
/*
* Copyright (c) 2005-2019 Substance Kirill Grouchnikov. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* o Neither the name of Substance Kirill Grouchnikov nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.pushingpixels.substance.internal.ui;
import org.pushingpixels.substance.api.*;
import org.pushingpixels.substance.internal.*;
import org.pushingpixels.substance.internal.painter.BackgroundPaintingUtils;
import org.pushingpixels.substance.internal.utils.*;
import org.pushingpixels.trident.Timeline;
import org.pushingpixels.trident.callback.UIThreadTimelineCallbackAdapter;
import org.pushingpixels.trident.swing.SwingComponentTimeline;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.BasicScrollPaneUI;
import javax.swing.table.JTableHeader;
import java.awt.*;
import java.beans.*;
import java.util.*;
/**
* UI for scroll panes in <b>Substance</b> look and feel.
*
* @author Kirill Grouchnikov
*/
public class SubstanceScrollPaneUI extends BasicScrollPaneUI {
/**
* Property change listener on {@link SubstanceSynapse#WATERMARK_VISIBLE} and
* <code>layoutManager</code> properties.
*/
private PropertyChangeListener substancePropertyChangeListener;
/**
* Listener on the vertical scroll bar. Installed for the smart tree scroll (see
* {@link SubstanceSlices.AnimationFacet#TREE_SMART_SCROLL_ANIMATION}.
*/
private ChangeListener substanceVerticalScrollbarChangeListener;
/**
* Timeline for the current horizontal scroll under smart tree scroll mode.
*/
private Timeline horizontalScrollTimeline;
private Set<SubstanceWidget> lafWidgets;
/**
* Creates new UI delegate.
*
* @param comp Component.
* @return UI delegate for the component.
*/
public static ComponentUI createUI(JComponent comp) {
SubstanceCoreUtilities.testComponentCreationThreadingViolation(comp);
return new SubstanceScrollPaneUI();
}
private SubstanceScrollPaneUI() {
}
@Override
public void installUI(JComponent c) {
this.lafWidgets = SubstanceWidgetRepository.getRepository().getMatchingWidgets(c);
super.installUI(c);
for (SubstanceWidget lafWidget : this.lafWidgets) {
lafWidget.installUI();
}
}
@Override
public void uninstallUI(JComponent c) {
for (SubstanceWidget lafWidget : this.lafWidgets) {
lafWidget.uninstallUI();
}
super.uninstallUI(c);
}
@Override
protected void installDefaults(final JScrollPane scrollpane) {
super.installDefaults(scrollpane);
if (SubstanceCoreUtilities.toDrawWatermark(scrollpane) && (SubstanceCortex.ComponentScope
.getCurrentSkin(scrollpane).getWatermark() != null)) {
scrollpane.setOpaque(false);
scrollpane.getViewport().setOpaque(false);
}
SwingUtilities.invokeLater(() -> installTableHeaderCornerFiller(scrollpane));
for (SubstanceWidget lafWidget : this.lafWidgets) {
lafWidget.installDefaults();
}
}
@Override
protected void uninstallDefaults(JScrollPane c) {
Component upperRight = c.getCorner(JScrollPane.UPPER_RIGHT_CORNER);
if (upperRight instanceof UIResource) {
c.setCorner(JScrollPane.UPPER_RIGHT_CORNER, null);
}
Component upperLeft = c.getCorner(JScrollPane.UPPER_LEFT_CORNER);
if (upperLeft instanceof UIResource) {
c.setCorner(JScrollPane.UPPER_LEFT_CORNER, null);
}
for (SubstanceWidget lafWidget : this.lafWidgets) {
lafWidget.uninstallDefaults();
}
super.uninstallDefaults(c);
}
@Override
protected void installListeners(final JScrollPane c) {
super.installListeners(c);
this.substancePropertyChangeListener = (PropertyChangeEvent evt) -> {
if (SubstanceSynapse.WATERMARK_VISIBLE.equals(evt.getPropertyName())) {
boolean toBleed = SubstanceCoreUtilities.toDrawWatermark(c);
c.setOpaque(!toBleed);
c.getViewport().setOpaque(!toBleed);
Component view = c.getViewport().getView();
if (view instanceof JComponent)
((JComponent) view).setOpaque(!toBleed);
}
if ("background".equals(evt.getPropertyName())) {
// propagate application-specific background color to the
// scroll bars.
Color newBackgr = (Color) evt.getNewValue();
if (!(newBackgr instanceof UIResource)) {
JScrollBar vertical = scrollpane.getVerticalScrollBar();
if (vertical != null) {
if (vertical.getBackground() instanceof UIResource) {
vertical.setBackground(newBackgr);
}
}
JScrollBar horizontal = scrollpane.getHorizontalScrollBar();
if (horizontal != null) {
if (horizontal.getBackground() instanceof UIResource) {
horizontal.setBackground(newBackgr);
}
}
}
}
if ("columnHeader".equals(evt.getPropertyName())
|| "componentOrientation".equals(evt.getPropertyName())
|| "ancestor".equals(evt.getPropertyName())) {
SwingUtilities.invokeLater(() -> {
// need to switch the corner filler based on the
// current scroll pane state.
if (scrollpane != null) {
installTableHeaderCornerFiller(scrollpane);
}
});
}
};
c.addPropertyChangeListener(this.substancePropertyChangeListener);
this.substanceVerticalScrollbarChangeListener = (ChangeEvent e) -> {
// check if it's a horizontally scrollable tree inside
if ((c.getHorizontalScrollBar() != null) && c.getHorizontalScrollBar().isVisible()
&& (c.getViewport().getView() instanceof JTree)) {
JTree tree = (JTree) c.getViewport().getView();
// check if the smart scroll is enabled
if (AnimationConfigurationManager.getInstance().isAnimationAllowed(
SubstanceSlices.AnimationFacet.TREE_SMART_SCROLL_ANIMATION, tree)) {
SubstanceTreeUI treeUI = (SubstanceTreeUI) tree.getUI();
final Rectangle viewportRect = c.getViewport().getViewRect();
int pivotX = treeUI.getPivotRendererX(viewportRect);
int currPivotX = viewportRect.x;// + viewportRect.width
// / 2;
int delta = pivotX - currPivotX;
int finalX = viewportRect.x + delta;
if (finalX < 0) {
delta -= finalX;
}
final int finalDelta = delta;
if (Math.abs(finalDelta) > viewportRect.width / 6) {
if (horizontalScrollTimeline != null) {
// abort previous horizontal scroll
horizontalScrollTimeline.abort();
}
horizontalScrollTimeline = SwingComponentTimeline.componentBuilder(tree)
.addCallback(new UIThreadTimelineCallbackAdapter() {
@Override
public void onTimelinePulse(float durationFraction,
float timelinePosition) {
if (timelinePosition >= 0.5) {
int nudge =
(int) (finalDelta * (timelinePosition - 0.5));
c.getViewport().setViewPosition(
new Point(viewportRect.x + nudge,
viewportRect.y));
}
}
})
.setEase((float durationFraction) -> {
if (durationFraction < 0.5) {
return 0.5f * durationFraction;
}
return 0.25f + (durationFraction - 0.5f) * 0.75f / 0.5f;
}).setDuration(2 * AnimationConfigurationManager.getInstance()
.getTimelineDuration())
.build();
horizontalScrollTimeline.play();
}
}
}
};
c.getVerticalScrollBar().getModel()
.addChangeListener(this.substanceVerticalScrollbarChangeListener);
for (SubstanceWidget lafWidget : this.lafWidgets) {
lafWidget.installListeners();
}
}
@Override
protected void uninstallListeners(JComponent c) {
c.removePropertyChangeListener(this.substancePropertyChangeListener);
this.substancePropertyChangeListener = null;
JScrollPane jsp = (JScrollPane) c;
jsp.getVerticalScrollBar().getModel()
.removeChangeListener(this.substanceVerticalScrollbarChangeListener);
this.substanceVerticalScrollbarChangeListener = null;
for (SubstanceWidget lafWidget : this.lafWidgets) {
lafWidget.uninstallListeners();
}
super.uninstallListeners(c);
}
@Override
public void update(Graphics g, JComponent c) {
BackgroundPaintingUtils.updateIfOpaque(g, c);
JScrollPane jsp = (JScrollPane) c;
LayoutManager lm = jsp.getLayout();
ScrollPaneLayout scrollLm = null;
if (lm instanceof ScrollPaneLayout) {
scrollLm = (ScrollPaneLayout) lm;
}
if (scrollLm != null) {
Set<Component> corners = new HashSet<>();
if (scrollLm.getCorner(ScrollPaneLayout.LOWER_LEFT_CORNER) != null) {
corners.add(scrollLm.getCorner(ScrollPaneLayout.LOWER_LEFT_CORNER));
}
if (scrollLm.getCorner(ScrollPaneLayout.LOWER_RIGHT_CORNER) != null) {
corners.add(scrollLm.getCorner(ScrollPaneLayout.LOWER_RIGHT_CORNER));
}
if (scrollLm.getCorner(ScrollPaneLayout.UPPER_LEFT_CORNER) != null) {
corners.add(scrollLm.getCorner(ScrollPaneLayout.UPPER_LEFT_CORNER));
}
if (scrollLm.getCorner(ScrollPaneLayout.UPPER_RIGHT_CORNER) != null) {
corners.add(scrollLm.getCorner(ScrollPaneLayout.UPPER_RIGHT_CORNER));
}
if (SubstanceCoreUtilities.isOpaque(c)) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(SubstanceColorUtilities
.getBackgroundFillColorScrollBar(this.scrollpane.getVerticalScrollBar()));
for (Component corner : corners) {
g2d.fill(corner.getBounds());
// BackgroundPaintingUtils.fillAndWatermark(g, c, c
// .getBackground(), corner.getBounds());
}
JScrollBar horizontal = this.scrollpane.getHorizontalScrollBar();
JScrollBar vertical = this.scrollpane.getVerticalScrollBar();
if ((horizontal != null) && (vertical != null)) {
if (this.scrollpane.getComponentOrientation().isLeftToRight()) {
// Bottom right corner
if (scrollLm.getCorner(ScrollPaneLayout.LOWER_RIGHT_CORNER) == null) {
g2d.fillRect(horizontal.getX() + horizontal.getWidth(),
horizontal.getY(), vertical.getWidth(), horizontal.getHeight());
}
} else {
// Bottom left corner
if (scrollLm.getCorner(ScrollPaneLayout.LOWER_LEFT_CORNER) == null) {
g2d.fillRect(0, horizontal.getY(), vertical.getWidth(),
horizontal.getHeight());
}
}
}
}
}
super.paint(g, c);
}
/**
* Installs a corner filler that matches the table header. This is done to provide a continuous
* appearance for tables with table headers placed in scroll panes.
*
* @param scrollpane Scroll pane.
*/
private void installTableHeaderCornerFiller(JScrollPane scrollpane) {
// install custom scroll pane corner filler
// for continuous painting of table headers
JViewport columnHeader = scrollpane.getColumnHeader();
// System.out.println("Column header " + columnHeader);
if (columnHeader == null) {
return;
}
Component columnHeaderComp = columnHeader.getView();
// System.out.println("Column header comp " + columnHeaderComp);
if (!(columnHeaderComp instanceof JTableHeader)) {
return;
}
JTableHeader tableHeader = (JTableHeader) columnHeaderComp;
TableHeaderUI tableHeaderUI = tableHeader.getUI();
if (!(tableHeaderUI instanceof SubstanceTableHeaderUI)) {
return;
}
SubstanceTableHeaderUI ui = (SubstanceTableHeaderUI) tableHeaderUI;
JComponent scrollPaneCornerFiller = ui.getScrollPaneCornerFiller();
String cornerKey = scrollpane.getComponentOrientation().isLeftToRight()
? JScrollPane.UPPER_RIGHT_CORNER
: JScrollPane.UPPER_LEFT_CORNER;
Component cornerComp = scrollpane.getCorner(cornerKey);
// Corner component can be replaced when the current one is null or
// UIResource
boolean canReplace = (cornerComp == null) || (cornerComp instanceof UIResource);
// System.out.println(canReplace + ":" + cornerComp);
if (canReplace) {
scrollpane.setCorner(cornerKey, scrollPaneCornerFiller);
}
}
}
|
/*
* Copyright 2020 Red Hat, Inc. and/or 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.
*/
package org.optaplanner.core.api.function;
import java.util.Objects;
import java.util.function.Predicate;
/**
* Represents a predicate (boolean-valued function) of five arguments.
* This is the five-arity specialization of {@link Predicate}.
*
* <p>
* This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #test(Object, Object, Object, Object, Object)}.
*
* @param <A> the type of the first argument to the predicate
* @param <B> the type of the second argument the predicate
* @param <C> the type of the third argument the predicate
* @param <D> the type of the fourth argument the predicate
* @param <E> the type of the fifth argument the predicate
*
* @see Predicate
*/
@FunctionalInterface
public interface PentaPredicate<A, B, C, D, E> {
/**
* Evaluates this predicate on the given arguments.
*
* @param a the first input argument
* @param b the second input argument
* @param c the third input argument
* @param d the fourth input argument
* @param e the fifth input argument
* @return {@code true} if the input arguments match the predicate,
* otherwise {@code false}
*/
boolean test(A a, B b, C c, D d, E e);
/**
* Returns a composed predicate that represents a short-circuiting logical
* AND of this predicate and another. When evaluating the composed
* predicate, if this predicate is {@code false}, then the {@code other}
* predicate is not evaluated.
*
* <p>
* Any exceptions thrown during evaluation of either predicate are relayed
* to the caller; if evaluation of this predicate throws an exception, the
* {@code other} predicate will not be evaluated.
*
* @param other a predicate that will be logically-ANDed with this predicate
* @return a composed predicate that represents the short-circuiting logical
* AND of this predicate and the {@code other} predicate
* @throws NullPointerException if other is null
*/
default PentaPredicate<A, B, C, D, E> and(
PentaPredicate<? super A, ? super B, ? super C, ? super D, ? super E> other) {
Objects.requireNonNull(other);
return (A a, B b, C c, D d, E e) -> test(a, b, c, d, e) && other.test(a, b, c, d, e);
}
/**
* Returns a predicate that represents the logical negation of this
* predicate.
*
* @return a predicate that represents the logical negation of this
* predicate
*/
default PentaPredicate<A, B, C, D, E> negate() {
return (A a, B b, C c, D d, E e) -> !test(a, b, c, d, e);
}
/**
* Returns a composed predicate that represents a short-circuiting logical
* OR of this predicate and another. When evaluating the composed
* predicate, if this predicate is {@code true}, then the {@code other}
* predicate is not evaluated.
*
* <p>
* Any exceptions thrown during evaluation of either predicate are relayed
* to the caller; if evaluation of this predicate throws an exception, the
* {@code other} predicate will not be evaluated.
*
* @param other a predicate that will be logically-ORed with this predicate
* @return a composed predicate that represents the short-circuiting logical
* OR of this predicate and the {@code other} predicate
* @throws NullPointerException if other is null
*/
default PentaPredicate<A, B, C, D, E> or(
PentaPredicate<? super A, ? super B, ? super C, ? super D, ? super E> other) {
Objects.requireNonNull(other);
return (A a, B b, C c, D d, E e) -> test(a, b, c, d, e) || other.test(a, b, c, d, e);
}
}
|
/* 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.flowable.cmmn.engine.impl.runtime;
import java.util.HashMap;
import java.util.Map;
import org.flowable.common.engine.api.query.QueryProperty;
/**
* @author Joram Barrez
*/
public class PlanItemInstanceQueryProperty implements QueryProperty {
private static final long serialVersionUID = 1L;
private static final Map<String, PlanItemInstanceQueryProperty> properties = new HashMap<>();
public static final PlanItemInstanceQueryProperty START_TIME = new PlanItemInstanceQueryProperty("RES.START_TIME_");
public static final PlanItemInstanceQueryProperty NAME = new PlanItemInstanceQueryProperty("RES.NAME_");
private String name;
public PlanItemInstanceQueryProperty(String name) {
this.name = name;
properties.put(name, this);
}
public String getName() {
return name;
}
public static PlanItemInstanceQueryProperty findByName(String propertyName) {
return properties.get(propertyName);
}
}
|
package net;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.nio.charset.Charset;
public class rP {
public static ByteBuf a(ByteBuf var0) {
return Unpooled.wrappedBuffer(var0);
}
public static ByteBuf a(byte[] var0) {
return Unpooled.wrappedBuffer(var0);
}
public static ByteBuf a() {
return Unpooled.buffer();
}
public static ByteBuf a(int var0) {
return Unpooled.buffer(var0);
}
public static ByteBuf a(CharSequence var0, Charset var1) {
return Unpooled.copiedBuffer(var0, var1);
}
}
|
/*
* Copyright 2000-2013 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.appengine.descriptor;
import com.intellij.appengine.facet.AppEngineFacet;
import com.intellij.appengine.util.AppEngineUtil;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.xml.XmlFile;
import com.intellij.xml.XmlSchemaProvider;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* @author nik
*/
public class AppEngineWebSchemaProvider extends XmlSchemaProvider {
private static final Set<String> FILE_NAMES = new HashSet<String>(Arrays.asList(AppEngineUtil.APP_ENGINE_WEB_XML_NAME,
AppEngineUtil.JDO_CONFIG_XML_NAME));
@Override
public boolean isAvailable(@NotNull XmlFile file) {
if (!FILE_NAMES.contains(file.getName())) {
return false;
}
final Module module = ModuleUtilCore.findModuleForPsiElement(file);
return AppEngineFacet.getAppEngineFacetByModule(module) != null;
}
@Override
public XmlFile getSchema(@NotNull @NonNls String url, @Nullable Module module, @NotNull PsiFile baseFile) {
if (module == null) {
return null;
}
if (url.startsWith("http://appengine.google.com/ns/")) {
AppEngineFacet facet = AppEngineFacet.getAppEngineFacetByModule(module);
if (facet != null) {
final File file = facet.getSdk().getWebSchemeFile();
final VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByIoFile(file);
if (virtualFile != null) {
final PsiFile psiFile = PsiManager.getInstance(module.getProject()).findFile(virtualFile);
if (psiFile instanceof XmlFile) {
return (XmlFile)psiFile;
}
}
}
}
else if (url.startsWith("http://java.sun.com/xml/ns/jdo/jdoconfig")) {
final PsiPackage jdoPackage = JavaPsiFacade.getInstance(module.getProject()).findPackage("javax.jdo");
final GlobalSearchScope scope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module);
if (jdoPackage != null) {
for (PsiDirectory directory : jdoPackage.getDirectories(scope)) {
final PsiFile file = directory.findFile("jdoconfig_2_3.xsd");
if (file instanceof XmlFile) {
return (XmlFile)file;
}
}
}
}
return null;
}
}
|
package br.eti.kinoshita.commons.text;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.ResourceBundle;
import java.util.Set;
public class NamesParserResourceBundle extends ResourceBundle {
@Override
protected Object handleGetObject(String key) {
switch(key) {
case "name":
return "Name";
case "surname":
return "Surname";
}
return null;
}
@Override
public Enumeration<String> getKeys() {
return Collections.enumeration(keySet());
}
@Override
protected Set<String> handleKeySet() {
return new HashSet<String>(Arrays.asList("name", "surname"));
}
}
|
package me.chanjar.weixin.mp.api.impl;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import me.chanjar.weixin.common.WxType;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxError;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.fs.FileUtils;
import me.chanjar.weixin.common.util.http.BaseMediaDownloadRequestExecutor;
import me.chanjar.weixin.common.util.http.MediaUploadRequestExecutor;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
import me.chanjar.weixin.mp.api.WxMpMaterialService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.material.WxMediaImgUploadResult;
import me.chanjar.weixin.mp.bean.material.WxMpMaterial;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialArticleUpdate;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialCountResult;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialFileBatchGetResult;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNews;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNewsBatchGetResult;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialVideoInfoResult;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
import me.chanjar.weixin.mp.util.requestexecuter.material.MaterialDeleteRequestExecutor;
import me.chanjar.weixin.mp.util.requestexecuter.material.MaterialNewsInfoRequestExecutor;
import me.chanjar.weixin.mp.util.requestexecuter.material.MaterialUploadRequestExecutor;
import me.chanjar.weixin.mp.util.requestexecuter.material.MaterialVideoInfoRequestExecutor;
import me.chanjar.weixin.mp.util.requestexecuter.material.MaterialVoiceAndImageDownloadRequestExecutor;
import me.chanjar.weixin.mp.util.requestexecuter.media.MediaImgUploadRequestExecutor;
/**
* Created by Binary Wang on 2016/7/21.
*/
public class WxMpMaterialServiceImpl implements WxMpMaterialService {
private WxMpService wxMpService;
public WxMpMaterialServiceImpl(WxMpService wxMpService) {
this.wxMpService = wxMpService;
}
@Override
public WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream inputStream) throws WxErrorException {
File tmpFile = null;
try {
tmpFile = FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), fileType);
return this.mediaUpload(mediaType, tmpFile);
} catch (IOException e) {
throw new WxErrorException(WxError.builder().errorCode(-1).errorMsg(e.getMessage()).build(), e);
} finally {
if (tmpFile != null) {
tmpFile.delete();
}
}
}
@Override
public WxMediaUploadResult mediaUpload(String mediaType, File file) throws WxErrorException {
String url = String.format(MEDIA_UPLOAD_URL, mediaType);
return this.wxMpService.execute(MediaUploadRequestExecutor.create(this.wxMpService.getRequestHttp()), url, file);
}
@Override
public File mediaDownload(String mediaId) throws WxErrorException {
return this.wxMpService.execute(
BaseMediaDownloadRequestExecutor.create(this.wxMpService.getRequestHttp(), this.wxMpService.getWxMpConfigStorage().getTmpDirFile()),
MEDIA_GET_URL,
"media_id=" + mediaId);
}
@Override
public WxMediaImgUploadResult mediaImgUpload(File file) throws WxErrorException {
return this.wxMpService.execute(MediaImgUploadRequestExecutor.create(this.wxMpService.getRequestHttp()), IMG_UPLOAD_URL, file);
}
@Override
public WxMpMaterialUploadResult materialFileUpload(String mediaType, WxMpMaterial material) throws WxErrorException {
String url = String.format(MATERIAL_ADD_URL, mediaType);
return this.wxMpService.execute(MaterialUploadRequestExecutor.create(this.wxMpService.getRequestHttp()), url, material);
}
@Override
public WxMpMaterialUploadResult materialNewsUpload(WxMpMaterialNews news) throws WxErrorException {
if (news == null || news.isEmpty()) {
throw new IllegalArgumentException("news is empty!");
}
String responseContent = this.wxMpService.post(NEWS_ADD_URL, news.toJson());
return WxMpMaterialUploadResult.fromJson(responseContent);
}
@Override
public InputStream materialImageOrVoiceDownload(String mediaId) throws WxErrorException {
return this.wxMpService.execute(MaterialVoiceAndImageDownloadRequestExecutor
.create(this.wxMpService.getRequestHttp(), this.wxMpService.getWxMpConfigStorage().getTmpDirFile()), MATERIAL_GET_URL, mediaId);
}
@Override
public WxMpMaterialVideoInfoResult materialVideoInfo(String mediaId) throws WxErrorException {
return this.wxMpService.execute(MaterialVideoInfoRequestExecutor.create(this.wxMpService.getRequestHttp()), MATERIAL_GET_URL, mediaId);
}
@Override
public WxMpMaterialNews materialNewsInfo(String mediaId) throws WxErrorException {
return this.wxMpService.execute(MaterialNewsInfoRequestExecutor.create(this.wxMpService.getRequestHttp()), MATERIAL_GET_URL, mediaId);
}
@Override
public boolean materialNewsUpdate(WxMpMaterialArticleUpdate wxMpMaterialArticleUpdate) throws WxErrorException {
String responseText = this.wxMpService.post(NEWS_UPDATE_URL, wxMpMaterialArticleUpdate.toJson());
WxError wxError = WxError.fromJson(responseText, WxType.MP);
if (wxError.getErrorCode() == 0) {
return true;
} else {
throw new WxErrorException(wxError);
}
}
@Override
public boolean materialDelete(String mediaId) throws WxErrorException {
return this.wxMpService.execute(MaterialDeleteRequestExecutor.create(this.wxMpService.getRequestHttp()), MATERIAL_DEL_URL, mediaId);
}
@Override
public WxMpMaterialCountResult materialCount() throws WxErrorException {
String responseText = this.wxMpService.get(MATERIAL_GET_COUNT_URL, null);
WxError wxError = WxError.fromJson(responseText, WxType.MP);
if (wxError.getErrorCode() == 0) {
return WxMpGsonBuilder.create().fromJson(responseText, WxMpMaterialCountResult.class);
} else {
throw new WxErrorException(wxError);
}
}
@Override
public WxMpMaterialNewsBatchGetResult materialNewsBatchGet(int offset, int count) throws WxErrorException {
Map<String, Object> params = new HashMap<>();
params.put("type", WxConsts.MaterialType.NEWS);
params.put("offset", offset);
params.put("count", count);
String responseText = this.wxMpService.post(MATERIAL_BATCHGET_URL, WxGsonBuilder.create().toJson(params));
WxError wxError = WxError.fromJson(responseText, WxType.MP);
if (wxError.getErrorCode() == 0) {
return WxMpGsonBuilder.create().fromJson(responseText, WxMpMaterialNewsBatchGetResult.class);
} else {
throw new WxErrorException(wxError);
}
}
@Override
public WxMpMaterialFileBatchGetResult materialFileBatchGet(String type, int offset, int count) throws WxErrorException {
Map<String, Object> params = new HashMap<>();
params.put("type", type);
params.put("offset", offset);
params.put("count", count);
String responseText = this.wxMpService.post(MATERIAL_BATCHGET_URL, WxGsonBuilder.create().toJson(params));
WxError wxError = WxError.fromJson(responseText, WxType.MP);
if (wxError.getErrorCode() == 0) {
return WxMpGsonBuilder.create().fromJson(responseText, WxMpMaterialFileBatchGetResult.class);
} else {
throw new WxErrorException(wxError);
}
}
}
|
public class Contact {
private String name;
private String phoneNumber;
public Contact(String name, String phoneNumber) {
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName() {
return name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public static Contact createContact(String name, String phoneNumber) {
return new Contact(name, phoneNumber);
}
}
|
/*
* 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.usergrid.services.notifications.gcm;
import com.google.android.gcm.server.*;
import org.apache.usergrid.persistence.entities.Notification;
import org.apache.usergrid.persistence.entities.Notifier;
import org.apache.usergrid.services.notifications.InactiveDeviceManager;
import org.mortbay.util.ajax.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.usergrid.services.ServicePayload;
import org.apache.usergrid.persistence.EntityManager;
import org.apache.usergrid.persistence.exceptions.RequiredPropertyNotFoundException;
import org.apache.usergrid.services.notifications.ConnectionException;
import org.apache.usergrid.services.notifications.ProviderAdapter;
import org.apache.usergrid.services.notifications.TaskTracker;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class GCMAdapter implements ProviderAdapter {
private static final Logger logger = LoggerFactory.getLogger(GCMAdapter.class);
private static final int SEND_RETRIES = 3;
private static int BATCH_SIZE = 1000;
private final Notifier notifier;
private EntityManager entityManager;
private ConcurrentHashMap<Long,Batch> batches;
private static final String ttlKey = "time_to_live";
private static final String priorityKey = "priority";
private static final String dataKey = "data";
public GCMAdapter(EntityManager entityManager,Notifier notifier){
this.notifier = notifier;
this.entityManager = entityManager;
batches = new ConcurrentHashMap<>();
}
@Override
public void testConnection() throws Exception {
Sender sender = new Sender(notifier.getApiKey());
Message message = new Message.Builder().addData("registration_id", "").build();
List<String> ids = new ArrayList<>();
ids.add("device_token");
try {
MulticastResult result = sender.send(message, ids, 1);
if (logger.isTraceEnabled()) {
logger.trace("testConnection result: {}", result);
}
} catch (InvalidRequestException e){
// do nothing, we don't have a valid device token to test with
if (logger.isTraceEnabled()) {
logger.trace("no valid device token");
}
}
catch (IOException e) {
if(isInvalidRequestException(e)){
throw new InvalidRequestException(401, Constants.ERROR_INVALID_REGISTRATION);
}else {
throw new ConnectionException(e.getMessage(), e);
}
}
}
@Override
public void sendNotification(String providerId, Object payload, Notification notification, TaskTracker tracker)
throws Exception {
Map<String,Object> map = (Map<String, Object>) payload;
if(!map.containsKey(ttlKey) && notification.getExpire() != null){
// ttl provided to GCM is in seconds. calculate the difference from now
long ttlSeconds = notification.getExpireTTLSeconds();
// max ttl for gcm is 4 weeks - https://developers.google.com/cloud-messaging/http-server-ref
ttlSeconds = ttlSeconds <= 2419200 ? ttlSeconds : 2419200;
map.put(ttlKey, (int)ttlSeconds);//needs to be int
}
if(!map.containsKey(priorityKey) && notification.getPriority() != null){
map.put(priorityKey, notification.getPriority());
}
Batch batch = getBatch( map);
batch.add(providerId, tracker);
}
private Batch getBatch( Map<String, Object> payload) {
synchronized (this) {
Batch batch = new Batch(notifier,null);
if( payload != null ) {
long hash = payload.hashCode(); // assume there won't be collisions in our amount of concurrency
batch = batches.get(hash);
if (batch == null) {
batch = new Batch(notifier, payload);
batches.put(hash, batch);
}
}
return batch;
}
}
@Override
public void doneSendingNotifications() throws Exception {
synchronized (this) {
for (Batch batch : batches.values()) {
batch.send();
}
}
}
@Override
public void removeInactiveDevices( ) throws Exception {
Batch batch = getBatch( null);
if(batch != null) {
Map<String,Date> map = batch.getAndClearInactiveDevices();
InactiveDeviceManager deviceManager = new InactiveDeviceManager(notifier,entityManager);
deviceManager.removeInactiveDevices(map);
}
}
@Override
public Map<String, Object> translatePayload(Object payload)
throws Exception {
Map<String, Object> mapPayload = new HashMap<String, Object>();
if (payload instanceof Map) {
mapPayload = (Map<String, Object>) payload;
} else if (payload instanceof String) {
mapPayload.put(dataKey, payload);
} else {
throw new IllegalArgumentException(
"GCM Payload must be either a Map or a String");
}
if (JSON.toString(mapPayload).length() > 4096) {
throw new IllegalArgumentException(
"GCM payloads must be 4096 characters or less");
}
return mapPayload;
}
@Override
public void validateCreateNotifier(ServicePayload payload) throws Exception {
if (payload.getProperty("apiKey") == null) {
throw new RequiredPropertyNotFoundException("notifier", "apiKey");
}
}
@Override
public void stop() {
try {
synchronized (this) {
for (Batch batch : batches.values()) {
batch.send();
}
}
}catch (Exception e){
logger.error("error while trying to send on stop",e);
}
}
@Override
public Notifier getNotifier() {
return notifier;
}
// this is a hack because Google library can't parse exceptions properly when you have a bad API key
private boolean isInvalidRequestException(IOException ie){
String message = ie.getMessage();
return message.contains("Could not post JSON requests to GCM");
}
private class Batch {
private Notifier notifier;
private Map payload;
private List<String> ids;
private List<TaskTracker> trackers;
private Map<String, Date> inactiveDevices = new HashMap<>();
Batch(Notifier notifier, Map<String,Object> payload) {
this.notifier = notifier;
this.payload = payload;
this.ids = new ArrayList<>();
this.trackers = new ArrayList<>();
}
synchronized Map<String, Date> getAndClearInactiveDevices() {
Map<String, Date> map = inactiveDevices;
inactiveDevices = new HashMap<String, Date>();
return map;
}
void add(String id, TaskTracker tracker) throws Exception {
synchronized (this) {
if(!ids.contains(id)) { //dedupe to a device
ids.add(id);
trackers.add(tracker);
if (ids.size() == BATCH_SIZE) {
send();
}
}else{
tracker.completed();
}
}
}
void send() throws Exception {
synchronized (this) {
if (ids.size() == 0)
return;
Sender sender = new Sender(notifier.getApiKey());
Message.Builder builder = new Message.Builder();
if(payload.containsKey(ttlKey)){
builder.timeToLive((int)payload.get(ttlKey));
payload.remove(ttlKey);
}
if(payload.containsKey(priorityKey)){
try{
builder.priority(Message.Priority.valueOf(payload.get(priorityKey).toString().toUpperCase()));
}catch(Exception e){
// couldn't determine the priority from the notification, default to "normal"
builder.priority(Message.Priority.NORMAL);
}
payload.remove(priorityKey);
}
builder.setData(payload);
// GCM will accept Map<String,Object> but builder.build().toString() will throw a class cast
// exception, but luckily Message.toString() is not used anywhere in the GCM SDK or Usergrid
Message message = builder.build();
MulticastResult multicastResult;
try{
multicastResult = sender.send(message, ids, SEND_RETRIES);
}catch (IOException e) {
if(isInvalidRequestException(e)){
String error = Constants.ERROR_INVALID_REGISTRATION;
for(int i=0; i < ids.size(); i++){
trackers.get(i).failed(error, error);
}
this.ids.clear();
this.trackers.clear();
return;
}else {
throw new ConnectionException(e.getMessage(), e);
}
}
if (logger.isTraceEnabled()) {
logger.trace("sendNotification result: {}", multicastResult);
}
for (int i = 0; i < multicastResult.getResults().size(); i++) {
Result result = multicastResult.getResults().get(i);
if (result.getMessageId() != null) {
String canonicalRegId = result.getCanonicalRegistrationId();
trackers.get(i).completed(canonicalRegId);
} else {
String error = result.getErrorCodeName();
trackers.get(i).failed(error, error);
if (Constants.ERROR_NOT_REGISTERED.equals(error) || Constants.ERROR_INVALID_REGISTRATION.equals(error)) {
inactiveDevices.put(ids.get(i), new Date());
}
}
}
this.ids.clear();
this.trackers.clear();
}
}
}
}
|
package kr.o_r.prodzpod.ophiuchus.common.util;
public class ThisMod {
public static final String ID = "%MODID%";
public static final String NAME = "%MODNAME%";
public static final String VERSION = "%VERSION%";
public static final String PREFIX = ID + ":";
public static final String TEXTURE = PREFIX + "textures/";
public static final boolean DEBUG = true; // FALSE THIS AFTER LIB IS SET UP
}
|
/*
* Copyright 2017 Confluent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package io.confluent.ksql.function.udaf.min;
import io.confluent.ksql.function.AggregateFunctionFactory;
import io.confluent.ksql.function.KsqlAggregateFunction;
import io.confluent.ksql.util.KsqlException;
import java.util.Arrays;
import java.util.List;
import org.apache.kafka.connect.data.Schema;
public class MinAggFunctionFactory extends AggregateFunctionFactory {
private static final String FUNCTION_NAME = "MIN";
public MinAggFunctionFactory() {
super(
FUNCTION_NAME,
Arrays.asList(
new DoubleMinKudaf(FUNCTION_NAME, -1), new LongMinKudaf(FUNCTION_NAME, -1),
new IntegerMinKudaf(FUNCTION_NAME, -1)));
}
@Override
public KsqlAggregateFunction getProperAggregateFunction(final List<Schema> argTypeList) {
for (final KsqlAggregateFunction<?, ?> ksqlAggregateFunction : getAggregateFunctionList()) {
if (ksqlAggregateFunction.hasSameArgTypes(argTypeList)) {
return ksqlAggregateFunction;
}
}
throw new KsqlException("No Max aggregate function with " + argTypeList.get(0) + " "
+ " argument type exists!");
}
}
|
// Java program to perform TimSort.
public class TimSort
{
static int RUN = 32;
// this function sorts array from left index to
// to right index which is of size atmost RUN
public static void insertionSort(int[] arr, int left, int right)
{
for (int i = left + 1; i <= right; i++)
{
int temp = arr[i];
int j = i - 1;
while (j >= left && arr[j] > temp)
{
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
}
// merge function merges the sorted runs
public static void merge(int[] arr, int l,
int m, int r)
{
// original array is broken in two parts
// left and right array
int len1 = m - l + 1, len2 = r - m;
int[] left = new int[len1];
int[] right = new int[len2];
for (int x = 0; x < len1; x++)
{
left[x] = arr[l + x];
}
for (int x = 0; x < len2; x++)
{
right[x] = arr[m + 1 + x];
}
int i = 0;
int j = 0;
int k = l;
// after comparing, we merge those two array
// in larger sub array
while (i < len1 && j < len2)
{
if (left[i] <= right[j])
{
arr[k] = left[i];
i++;
}
else
{
arr[k] = right[j];
j++;
}
k++;
}
// copy remaining elements of left, if any
while (i < len1)
{
arr[k] = left[i];
k++;
i++;
}
// copy remaining element of right, if any
while (j < len2)
{
arr[k] = right[j];
k++;
j++;
}
}
// iterative Timsort function to sort the
// array[0...n-1] (similar to merge sort)
public static void timSort(int[] arr, int n)
{
// Sort individual subarrays of size RUN
for (int i = 0; i < n; i += RUN)
{
insertionSort(arr, i, Math.min((i + 31), (n - 1)));
}
// start merging from size RUN (or 32). It will merge
// to form size 64, then 128, 256 and so on ....
for (int size = RUN; size < n; size = 2 * size)
{
// pick starting point of left sub array. We
// are going to merge arr[left..left+size-1]
// and arr[left+size, left+2*size-1]
// After every merge, we increase left by 2*size
for (int left = 0; left < n; left += 2 * size)
{
// find ending point of left sub array
// mid+1 is starting point of right sub array
int mid = left + size - 1;
int right = Math.min((left + 2 * size - 1), (n - 1));
// merge sub array arr[left.....mid] &
// arr[mid+1....right]
merge(arr, left, mid, right);
}
}
}
// utility function to print the Array
public static void printArray(int[] arr, int n)
{
for (int i = 0; i < n; i++)
{
System.out.print(arr[i] + " ");
}
System.out.print("\n");
}
// Driver code
public static void main(String[] args)
{
int[] arr = {5, 21, 7, 23, 19};
int n = arr.length;
System.out.print("Given Array is\n");
printArray(arr, n);
timSort(arr, n);
System.out.print("After Sorting Array is\n");
printArray(arr, n);
}
}
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.module07challenge;
import android.content.Context;
import com.facebook.flipper.android.AndroidFlipperClient;
import com.facebook.flipper.android.utils.FlipperUtils;
import com.facebook.flipper.core.FlipperClient;
import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin;
import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin;
import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin;
import com.facebook.flipper.plugins.inspector.DescriptorMapping;
import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin;
import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor;
import com.facebook.flipper.plugins.network.NetworkFlipperPlugin;
import com.facebook.flipper.plugins.react.ReactFlipperPlugin;
import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.modules.network.NetworkingModule;
import okhttp3.OkHttpClient;
public class ReactNativeFlipper {
public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
if (FlipperUtils.shouldEnableFlipper(context)) {
final FlipperClient client = AndroidFlipperClient.getInstance(context);
client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults()));
client.addPlugin(new ReactFlipperPlugin());
client.addPlugin(new DatabasesFlipperPlugin(context));
client.addPlugin(new SharedPreferencesFlipperPlugin(context));
client.addPlugin(CrashReporterPlugin.getInstance());
NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
NetworkingModule.setCustomClientBuilder(
new NetworkingModule.CustomClientBuilder() {
@Override
public void apply(OkHttpClient.Builder builder) {
builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
}
});
client.addPlugin(networkFlipperPlugin);
client.start();
// Fresco Plugin needs to ensure that ImagePipelineFactory is initialized
// Hence we run if after all native modules have been initialized
ReactContext reactContext = reactInstanceManager.getCurrentReactContext();
if (reactContext == null) {
reactInstanceManager.addReactInstanceEventListener(
new ReactInstanceManager.ReactInstanceEventListener() {
@Override
public void onReactContextInitialized(ReactContext reactContext) {
reactInstanceManager.removeReactInstanceEventListener(this);
reactContext.runOnNativeModulesQueueThread(
new Runnable() {
@Override
public void run() {
client.addPlugin(new FrescoFlipperPlugin());
}
});
}
});
} else {
client.addPlugin(new FrescoFlipperPlugin());
}
}
}
}
|
package CrackingCoding;
import java.util.ArrayList;
public class c9_4 {
public static ArrayList<ArrayList<Integer>> getSubsets(
ArrayList<Integer> set, int index) {
ArrayList<ArrayList<Integer>> allsubsets;
if (set.size() == index) { // Base case - add empty set
allsubsets = new ArrayList<ArrayList<Integer>>();
allsubsets.add(new ArrayList<Integer>());
} else {
allsubsets = getSubsets(set, index + 1);
int item = set.get(index);
ArrayList<ArrayList<Integer>> moresubsets = new ArrayList<ArrayList<Integer>>();
for (ArrayList<Integer> subset : allsubsets) {
ArrayList<Integer> newsubset = new ArrayList<Integer>();
newsubset.addAll(subset); //
newsubset.add(item);
moresubsets.add(newsubset);
}
allsubsets.addAll(moresubsets);
}
return allsubsets;
}
public static ArrayList<Integer> convertIntToSet(int x,
ArrayList<Integer> set) {
ArrayList<Integer> subset = new ArrayList<Integer>();
int index = 0;
for (int k = x; k > 0; k >>= 1) {
if ((k & 1) == 1) {
subset.add(set.get(index));
}
index++;
}
return subset;
}
public static ArrayList<ArrayList<Integer>> getSubsets2(
ArrayList<Integer> set) {
ArrayList<ArrayList<Integer>> allsubsets = new ArrayList<ArrayList<Integer>>();
int max = 1 << set.size(); /* Compute 2^n */
for (int k = 0; k < max; k++) {
ArrayList<Integer> subset = convertIntToSet(k, set);
allsubsets.add(subset);
}
return allsubsets;
}
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 3; i++) {
list.add(i);
}
ArrayList<ArrayList<Integer>> subsets = getSubsets(list, 0);
System.out.println(subsets.toString());
ArrayList<ArrayList<Integer>> subsets2 = getSubsets2(list);
System.out.println(subsets2.toString());
}
}
|
/**
* 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.nutch.urlfilter.api;
// JDK imports
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
// Logging imports
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// Nutch imports
import org.apache.nutch.net.URLFilter;
//import org.apache.nutch.urlfilter.automaton.TestAutomatonURLFilter;
//import org.apache.nutch.urlfilter.regex.TestRegexURLFilter;
//import org.junit.runners.Suite;
//import org.junit.runner.RunWith;
/**
* JUnit based test of class <code>RegexURLFilterBase</code>.
*/
//@RunWith(Suite.class)
//@Suite.SuiteClasses({TestAutomatonURLFilter.class, TestRegexURLFilter.class})
public abstract class RegexURLFilterBaseTest {
/** My logger */
protected static final Logger LOG = LoggerFactory.getLogger(RegexURLFilterBaseTest.class);
private final static String SEPARATOR = System.getProperty("file.separator");
private final static String SAMPLES = System.getProperty("test.data", "/home/talat/workspace/nutch/src/plugin/urlfilter-automaton/sample");
protected abstract URLFilter getURLFilter(Reader rules);
protected void bench(int loops, String file) {
try {
bench(loops,
new FileReader(SAMPLES + SEPARATOR + file + ".rules"),
new FileReader(SAMPLES + SEPARATOR + file + ".urls"));
} catch (Exception e) {
fail(e.toString());
}
}
protected void bench(int loops, Reader rules, Reader urls) {
long start = System.currentTimeMillis();
try {
URLFilter filter = getURLFilter(rules);
FilteredURL[] expected = readURLFile(urls);
for (int i=0; i<loops; i++) {
test(filter, expected);
}
} catch (Exception e) {
fail(e.toString());
}
LOG.info("bench time (" + loops + ") " +
(System.currentTimeMillis()-start) + "ms");
}
protected void test(String file) {
try {
test(new FileReader(SAMPLES + SEPARATOR + file + ".rules"),
new FileReader(SAMPLES + SEPARATOR + file + ".urls"));
} catch (Exception e) {
fail(e.toString());
}
}
protected void test(Reader rules, Reader urls) {
try {
test(getURLFilter(rules), readURLFile(urls));
} catch (Exception e) {
fail(e.toString());
}
}
protected void test(URLFilter filter, FilteredURL[] expected) {
for (int i=0; i<expected.length; i++) {
String result = filter.filter(expected[i].url);
if (result != null) {
assertTrue(expected[i].url, expected[i].sign);
} else {
assertFalse(expected[i].url, expected[i].sign);
}
}
}
private static FilteredURL[] readURLFile(Reader reader) throws IOException {
BufferedReader in = new BufferedReader(reader);
List<FilteredURL> list = new ArrayList<FilteredURL>();
String line;
while((line=in.readLine()) != null) {
if (line.length() != 0) {
list.add(new FilteredURL(line));
}
}
return (FilteredURL[]) list.toArray(new FilteredURL[list.size()]);
}
private static class FilteredURL {
boolean sign;
String url;
FilteredURL(String line) {
switch (line.charAt(0)) {
case '+' :
sign = true;
break;
case '-' :
sign = false;
break;
default :
// Simply ignore...
}
url = line.substring(1);
}
}
}
|
package imd.ufrn.br.cashbooks.repository;
import imd.ufrn.br.cashbooks.model.Cliente;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ClienteRepository extends JpaRepository<Cliente, Long>{
}
|
/*
* Copyright 2010-2017 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.
*/
/**
* AWS Java SDK annotations.
*/
package software.amazon.awssdk.annotation;
|
package com.zup.academy.eduardoribeiro.Proposta.compartilhado.validacao;
import com.zup.academy.eduardoribeiro.Proposta.biometria.CadastroBiometriaRequest;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import java.util.Base64;
@Component
public class Base64Validator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return clazz.isAssignableFrom(CadastroBiometriaRequest.class);
}
@Override
public void validate(Object target, Errors errors) {
if (errors.hasErrors()) {
return;
}
CadastroBiometriaRequest request = (CadastroBiometriaRequest) target;
String fingerprint = request.getFingerprint();
try {
Base64.getDecoder().decode(fingerprint);
} catch (IllegalArgumentException exception) {
errors.rejectValue("fingerprint", null, "Biometria deve estar em formato Base64");
}
}
}
|
/*
* Copyright 2013-2020 Erudika. http://erudika.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For issues and patches go to: https://github.com/erudika
*/
package com.erudika.scoold.utils;
import com.erudika.para.utils.Config;
import com.erudika.para.utils.Utils;
import static com.erudika.scoold.ScooldServer.AUTH_COOKIE;
import static com.erudika.scoold.ScooldServer.HOMEPAGE;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.NoConnectionReuseStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
/**
* Various utilities for HTTP stuff - cookies, AJAX, etc.
* @author Alex Bogdanovski [alex@erudika.com]
*/
public final class HttpUtils {
private static CloseableHttpClient httpclient;
/**
* Default private constructor.
*/
private HttpUtils() { }
static CloseableHttpClient getHttpClient() {
if (httpclient == null) {
int timeout = 5 * 1000;
httpclient = HttpClientBuilder.create().
setConnectionReuseStrategy(new NoConnectionReuseStrategy()).
setDefaultRequestConfig(RequestConfig.custom().
setConnectTimeout(timeout).
setConnectionRequestTimeout(timeout).
setCookieSpec(CookieSpecs.STANDARD).
setSocketTimeout(timeout).
build()).
build();
}
return httpclient;
}
/**
* Checks if a request comes from JavaScript.
* @param request HTTP request
* @return true if AJAX
*/
public static boolean isAjaxRequest(HttpServletRequest request) {
return "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With")) ||
"XMLHttpRequest".equalsIgnoreCase(request.getParameter("X-Requested-With"));
}
/////////////////////////////////////////////
// COOKIE & STATE UTILS
/////////////////////////////////////////////
/**
* Sets a cookie.
* @param name the name
* @param value the value
* @param req HTTP request
* @param res HTTP response
*/
public static void setStateParam(String name, String value, HttpServletRequest req, HttpServletResponse res) {
setStateParam(name, value, req, res, false);
}
/**
* Sets a cookie.
* @param name the name
* @param value the value
* @param req HTTP request
* @param res HTTP response
* @param httpOnly HTTP only flag
*/
public static void setStateParam(String name, String value, HttpServletRequest req,
HttpServletResponse res, boolean httpOnly) {
setRawCookie(name, value, req, res, httpOnly, -1);
}
/**
* Reads a cookie.
* @param name the name
* @param req HTTP request
* @return the cookie value
*/
public static String getStateParam(String name, HttpServletRequest req) {
return getCookieValue(req, name);
}
/**
* Deletes a cookie.
* @param name the name
* @param req HTTP request
* @param res HTTP response
*/
public static void removeStateParam(String name, HttpServletRequest req,
HttpServletResponse res) {
setRawCookie(name, "", req, res, false, 0);
}
/**
* Sets a cookie.
* @param name the name
* @param value the value
* @param req HTTP request
* @param res HTTP response
* @param httpOnly HTTP only flag
* @param maxAge max age
*/
public static void setRawCookie(String name, String value, HttpServletRequest req,
HttpServletResponse res, boolean httpOnly, int maxAge) {
if (StringUtils.isBlank(name) || value == null || req == null || res == null) {
return;
}
Cookie cookie = new Cookie(name, value);
cookie.setHttpOnly(httpOnly);
cookie.setMaxAge(maxAge < 0 ? Config.SESSION_TIMEOUT_SEC : maxAge);
cookie.setPath("/");
cookie.setSecure(req.isSecure());
res.addCookie(cookie);
}
/**
* Reads a cookie.
* @param name the name
* @param req HTTP request
* @return the cookie value
*/
public static String getCookieValue(HttpServletRequest req, String name) {
if (StringUtils.isBlank(name) || req == null) {
return null;
}
Cookie[] cookies = req.getCookies();
if (cookies == null) {
return null;
}
//Otherwise, we have to do a linear scan for the cookie.
for (Cookie cookie : cookies) {
if (cookie.getName().equals(name)) {
return cookie.getValue();
}
}
return null;
}
/**
* Fetches an avatar at a given URL.
* @param url image URL
* @param res response
* @return the content of the image or null
*/
public static void getAvatar(String url, HttpServletResponse res) {
if (StringUtils.isBlank(url)) {
getDefaultAvatarImage(res);
return;
}
HttpGet get = new HttpGet(url);
get.setHeader(HttpHeaders.USER_AGENT, "Scoold Image Validator, https://scoold.com");
try (CloseableHttpResponse img = HttpUtils.getHttpClient().execute(get)) {
if (img.getStatusLine().getStatusCode() == HttpStatus.SC_OK && img.getEntity() != null) {
String contentType = img.getEntity().getContentType().getValue();
if (StringUtils.equalsAnyIgnoreCase(contentType, "image/gif", "image/jpeg", "image/jpg", "image/png",
"image/webp", "image/bmp", "image/svg+xml")) {
for (Header header : img.getAllHeaders()) {
res.setHeader(header.getName(), header.getValue());
}
if (!res.containsHeader(org.apache.http.HttpHeaders.CACHE_CONTROL)) {
res.setHeader(org.apache.http.HttpHeaders.CACHE_CONTROL, "max-age=" + TimeUnit.HOURS.toSeconds(24));
}
IOUtils.copy(img.getEntity().getContent(), res.getOutputStream());
}
} else {
getDefaultAvatarImage(res);
}
} catch (IOException ex) {
getDefaultAvatarImage(res);
LoggerFactory.getLogger(HttpUtils.class).debug("Failed to get user avatar from {}: {}", url, ex.getMessage());
}
}
private static void getDefaultAvatarImage(HttpServletResponse res) {
try {
String anon = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"
+ "<svg xmlns=\"http://www.w3.org/2000/svg\" id=\"svg8\" width=\"756\" height=\"756\" "
+ "version=\"1\" viewBox=\"0 0 200 200\">\n"
+ " <g id=\"layer1\" transform=\"translate(0 -97)\">\n"
+ " <rect id=\"rect1433\" width=\"282\" height=\"245\" x=\"-34\" y=\"79\" fill=\"#ececec\" rx=\"2\"/>\n"
+ " </g>\n"
+ " <g id=\"layer2\" fill=\"gray\">\n"
+ " <circle id=\"path1421\" cx=\"102\" cy=\"-70\" r=\"42\" transform=\"scale(1 -1)\"/>\n"
+ " <ellipse id=\"path1423\" cx=\"101\" cy=\"201\" rx=\"71\" ry=\"95\"/>\n"
+ " </g>\n"
+ "</svg>";
res.setContentType("image/svg+xml");
res.setHeader(org.apache.http.HttpHeaders.CACHE_CONTROL, "max-age=" + TimeUnit.HOURS.toSeconds(24));
res.setHeader(org.apache.http.HttpHeaders.ETAG, Utils.md5(anon));
IOUtils.copy(new ByteArrayInputStream(anon.getBytes()), res.getOutputStream());
} catch (IOException e) {
LoggerFactory.getLogger(HttpUtils.class).
debug("Failed to set default user avatar. {}", e.getMessage());
}
}
/**
* Sets the session cookie.
* @param jwt a JWT from Para
* @param req req
* @param res res
*/
public static void setAuthCookie(String jwt, HttpServletRequest req, HttpServletResponse res) {
if (StringUtils.isBlank(jwt)) {
return;
}
int maxAge = Config.SESSION_TIMEOUT_SEC;
String expires = DateFormatUtils.format(System.currentTimeMillis() + (maxAge * 1000),
"EEE, dd-MMM-yyyy HH:mm:ss z", TimeZone.getTimeZone("GMT"));
StringBuilder sb = new StringBuilder();
sb.append(AUTH_COOKIE).append("=").append(jwt).append(";");
sb.append("Path=/;");
sb.append("Expires=").append(expires).append(";");
sb.append("Max-Age=").append(maxAge).append(";");
sb.append("HttpOnly;");
sb.append("SameSite=Lax");
res.addHeader(javax.ws.rs.core.HttpHeaders.SET_COOKIE, sb.toString());
}
/**
* @param req req
* @return the original protected URL visited before authentication
*/
public static String getBackToUrl(HttpServletRequest req) {
String backtoFromCookie = Utils.urlDecode(HttpUtils.getStateParam("returnto", req));
return (StringUtils.isBlank(backtoFromCookie) ? HOMEPAGE : backtoFromCookie);
}
}
|
package de.samdev.absgdx.framework.menu.elements;
import java.util.ArrayList;
import java.util.List;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import de.samdev.absgdx.framework.GameSettings;
import de.samdev.absgdx.framework.menu.GUITextureProvider;
import de.samdev.absgdx.framework.menu.attributes.CheckState;
import de.samdev.absgdx.framework.menu.attributes.RectangleRadius;
import de.samdev.absgdx.framework.menu.attributes.TristateBoolean;
import de.samdev.absgdx.framework.menu.attributes.VisualButtonState;
import de.samdev.absgdx.framework.menu.events.MenuSettingsTreeListener;
import de.samdev.absgdx.framework.util.dependentProperties.BooleanProperty;
import de.samdev.absgdx.framework.util.dependentProperties.DependentProperty;
import de.samdev.absgdx.framework.util.dependentProperties.RootProperty;
/**
* A click-able Button
*/
public class MenuSettingsTree extends MenuBaseElement {
/**
* Class to represent a single row in the MenuSettingsTree
*/
private class MenuSettingsTreeRow extends MenuCheckBox {
private final List<MenuSettingsTreeRow> children;
private final MenuSettingsTree treeowner;
private final DependentProperty property;
private MenuImage innerImageRight;
public MenuSettingsTreeRow(String rootidentifier, GUITextureProvider texprovider, DependentProperty property, MenuSettingsTree owner) {
super(rootidentifier + "+" + property.name, texprovider);
this.treeowner = owner;
this.children = new ArrayList<MenuSettingsTreeRow>();
this.property = property;
setContent(property.name);
for (DependentProperty child : property.getChildren()) {
children.add(new MenuSettingsTreeRow(identifier, texprovider, child, owner));
}
setChecked(true);
setLabelPadding(new RectangleRadius(5, 10, 5, 0));
innerImageRight = new MenuImage();
}
@Override
protected TextureRegion getCheckTexture() {
if (children.isEmpty()) {
return getTextureProvider().get(treeowner.getClass(), GUITextureProvider.IDENT_TEX_DEPTREE_LEAF);
} else {
return getTextureProvider().get(treeowner.getClass(), GUITextureProvider.IDENT_TEX_CHECK_IMG, CheckState.fromBoolean(isChecked()));
}
}
@Override
public MenuBaseElement getElementAt(int x, int y) {
if (isChecked()) {
for (MenuSettingsTreeRow element : children) {
if (element.getElementAt(x, y) != null)
return element.getElementAt(x, y);
}
}
if (this.getBoundaries().contains(x, y))
return this;
return null;
}
@Override
public List<MenuBaseElement> getDirectInnerElements() {
List<MenuBaseElement> result = new ArrayList<MenuBaseElement>();
result.add(innerImage);
result.add(innerLabel);
result.add(innerImageRight);
return result;
}
public List<MenuBaseElement> getAllVisibleChildren() {
List<MenuBaseElement> result = new ArrayList<MenuBaseElement>();
result.add(this);
if (!isChecked())
return result;
for (MenuSettingsTreeRow child : children) {
result.addAll(child.getAllVisibleChildren());
}
return result;
}
@Override
public void onPointerClicked() {
if (innerImage.getBoundaries().contains(Gdx.input.getX() - getCoordinateOffsetX(), Gdx.input.getY() - getCoordinateOffsetY())) {
super.onPointerClicked();
} else if (innerLabel.getBoundaries().contains(Gdx.input.getX() - getCoordinateOffsetX(), Gdx.input.getY() - getCoordinateOffsetY())) {
if (property instanceof BooleanProperty) {
((BooleanProperty)property).set(! property.getBooleanValue());
}
}
}
public List<MenuBaseElement> getTree() {
List<MenuBaseElement> result = new ArrayList<MenuBaseElement>();
result.add(this);
for (MenuSettingsTreeRow child : children) {
result.addAll(child.getTree());
}
return result;
}
public int innerRender(SpriteBatch sbatch, BitmapFont font, int positionY, int depth, int offX, int offY) {
setUpInnerElements(positionY, depth);
if (positionY >= treeowner.padding.top) {
super.render(sbatch, font, offX, offY);
innerImageRight.render(sbatch, font, offX, offY);
}
positionY += getHeight() + treeowner.rowGap;
if (isChecked()) {
for (MenuSettingsTreeRow child : children) {
if (positionY + treeowner.rowHeight > treeowner.getHeight() - treeowner.padding.bottom)
return positionY;
positionY = child.innerRender(sbatch, font, positionY, depth+1, offX, offY);
}
}
return positionY;
}
public int innerDebugRender(ShapeRenderer srenderer, int positionY, int depth, int offX, int offY) {
setUpInnerElements(positionY, depth);
if (positionY >= treeowner.padding.top) {
srenderer.begin(ShapeType.Line);
{
srenderer.setColor(treeowner.owner.getAgdxGame().settings.debugMenuBordersColorL2.get());
srenderer.rect(offX + getPositionX(), offY + getPositionY(), getWidth(), getHeight());
}
srenderer.end();
}
positionY += getHeight() + treeowner.rowGap;
if (isChecked()) {
for (MenuSettingsTreeRow child : children) {
if (positionY + treeowner.rowHeight > treeowner.getHeight() - treeowner.padding.bottom)
return positionY;
positionY = child.innerDebugRender(srenderer, positionY, depth+1, offX, offY);
}
}
return positionY;
}
private void setUpInnerElements(int positionY, int depth) {
setWidth(treeowner.getWidth() - treeowner.padding.getHorizontalSum() - treeowner.rowHeight*depth);
setHeight(treeowner.rowHeight);
setPositionX(treeowner.padding.left + treeowner.rowHeight*depth);
setPositionY(positionY);
setColor(treeowner.color);
innerImageRight.setHeight(treeowner.rowHeight);
innerImageRight.setWidth(treeowner.rowHeight);
innerImageRight.setPositionX(treeowner.getWidth() - treeowner.padding.left - treeowner.rowHeight);
innerImageRight.setPositionY(positionY);
innerImageRight.setImage(getTextureProvider().get(treeowner.getClass(), GUITextureProvider.IDENT_TEX_DEPTREE_BOOL, property.isActive() ? TristateBoolean.TRUE : (property.getBooleanValue() ? TristateBoolean.INTERMEDIATE : TristateBoolean.FALSE)));
}
}
private final MenuSettingsTreeRow root;
private RectangleRadius padding = new RectangleRadius(15, 15, 15, 15);
private int rowGap = 5;
private int rowHeight = 20;
private Color color = Color.WHITE;
private Color scrollbarColor = Color.LIGHT_GRAY;
private int scrollbarWidth = 5;
private int scroll = 0;
/**
* Creates a new MenuButton
*
* @param rootproperty The DependentProperties root node
*/
public MenuSettingsTree(RootProperty rootproperty) {
super();
root = new MenuSettingsTreeRow(identifier, textureprovider, rootproperty, this);
if (getTextureProvider().hasGeneric9SideTextures(getClass(), VisualButtonState.NORMAL))
setPadding(get9SidePadding(VisualButtonState.NORMAL));
}
/**
* Creates a new MenuButton
*
* @param texprovider the texture provider for this element
* @param rootproperty The DependentProperties root node
*/
public MenuSettingsTree(GUITextureProvider texprovider, RootProperty rootproperty) {
super(texprovider);
root = new MenuSettingsTreeRow(identifier + "+" + rootproperty.name, textureprovider, rootproperty, this);
if (getTextureProvider().hasGeneric9SideTextures(getClass(), VisualButtonState.NORMAL))
setPadding(get9SidePadding(VisualButtonState.NORMAL));
}
/**
* Creates a new MenuButton
*
* @param identifier the unique button identifier
* @param texprovider the texture provider for this element
* @param rootproperty The DependentProperties root node
*/
public MenuSettingsTree(String identifier, GUITextureProvider texprovider, RootProperty rootproperty) {
super(identifier, texprovider);
root = new MenuSettingsTreeRow(identifier + "+" + rootproperty.name, textureprovider, rootproperty, this);
if (getTextureProvider().hasGeneric9SideTextures(getClass(), VisualButtonState.NORMAL))
setPadding(get9SidePadding(VisualButtonState.NORMAL));
}
@Override
public void render(SpriteBatch sbatch, BitmapFont font, int offX, int offY) {
if (getTextureProvider().hasGeneric9SideTextures(getClass())) {
render9SideTexture(sbatch, offX, offY);
}
if (getTextureProvider().hasPaddingTextures(getClass())) {
renderPaddingTexture(sbatch, offX, offY);
}
root.innerRender(sbatch, font, padding.top - scroll * (rowHeight + rowGap), 0, offX + getPositionX(), offY + getPositionY());
}
@Override
public void renderCustom(SpriteBatch sbatch, ShapeRenderer srenderer, BitmapFont font, int offX, int offY) {
int rows = root.getAllVisibleChildren().size();
int vrows = (getHeight() - padding.getVerticalSum()) / (rowHeight + rowGap);
if (vrows < rows) {
float sbheight = (vrows * 1f / rows) * getHeight();
float sbfreespace = getHeight() - sbheight;
float sbperc = scroll * 1f / (rows - vrows);
float sby = sbperc * sbfreespace;
srenderer.begin(ShapeType.Filled);
{
srenderer.setColor(getScrollbarColor());
srenderer.rect(offX + getPositionX() + getWidth() - 1, offY + getPositionY() + sby + 1, -scrollbarWidth, sbheight - 2);
}
srenderer.end();
}
}
@Override
public void renderDebug(ShapeRenderer srenderer, GameSettings settings, int offX, int offY) {
if (settings.debugMenuBorders.isActive())
{
root.innerDebugRender(srenderer, padding.top - scroll * (rowHeight + rowGap), 0, offX + getPositionX(), offY + getPositionY());
}
}
@Override
public void update(float delta) {
onScroll(0);
}
/**
* Adds a new listener
*
* @param l the new listener
*/
public void addSettingsTreeListener(MenuSettingsTreeListener l) {
super.addElementListener(l);
}
/**
* @return the text padding
*/
public RectangleRadius getPadding() {
return padding;
}
/**
* Set the padding of the text
*
* @param padding the new padding
*/
public void setPadding(RectangleRadius padding) {
this.padding = padding;
}
/**
* Set the padding of the text
*
* @param top the top padding
* @param left the left padding
* @param bottom the bottom padding
* @param right the right padding
*/
public void setPadding(int top, int left, int bottom, int right) {
this.padding = new RectangleRadius(top, left, bottom, right);
}
@Override
public MenuBaseElement getElementAt(int x, int y) {
return this;
}
@Override
public void onPointerClicked() {
super.onPointerClicked();
MenuBaseElement element = root.getElementAt(Gdx.input.getX() - root.getCoordinateOffsetX(), Gdx.input.getY() - root.getCoordinateOffsetY());
if (element != null)
element.onPointerClicked();
}
/**
* @return the gap between the single rows
*/
public int getRowGap() {
return rowGap;
}
/**
* Set the gap between the rows
*
* @param rowGap the gap (in pixel)
*/
public void setRowGap(int rowGap) {
this.rowGap = rowGap;
}
/**
* @return the font color
*/
public Color getColor() {
return color;
}
/**
* Set the font color
*
* @param color the new color
*/
public void setColor(Color color) {
this.color = color;
}
/**
* @return the height of a single row
*/
public int getRowHeight() {
return rowHeight;
}
/**
* Set the height of a single row
*
* @param height the row height (in pixel)
*/
public void setRowHeight(int height) {
this.rowHeight = height;
}
/**
* @return the color of the scrollbar
*/
public Color getScrollbarColor() {
return scrollbarColor;
}
/**
* Set the color of the scrollbar
*
* @param scrollbarColor the new color
*/
public void setScrollbarColor(Color scrollbarColor) {
this.scrollbarColor = scrollbarColor;
}
/**
* @return the width of the scrollbar
*/
public int getScrollbarWidth() {
return scrollbarWidth;
}
/**
* Set the width of the scrollbar
*
* @param scrollbarWidth the scrollbar width (in pixel)
*/
public void setScrollbarWidth(int scrollbarWidth) {
this.scrollbarWidth = scrollbarWidth;
}
@Override
public void onScroll(int amount) {
scroll += Math.signum(amount);
int rows = root.getAllVisibleChildren().size();
int vrows = (getHeight() - padding.getVerticalSum()) / (rowHeight + rowGap);
if (scroll + vrows > rows) scroll = rows - vrows;
if (scroll < 0) scroll = 0;
}
@Override
public List<MenuBaseElement> getDirectInnerElements() {
return root.getTree();
}
@Override
public MenuBaseElement getElementByID(String id) {
return identifier.equals(id) ? this : null;
}
}
|
package it.maconsulting.teams.application.member.port.out;
import it.maconsulting.teams.domain.model.Member;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.Optional;
/**
* @author Michele Arciprete
* @since 0.0.1-SNAPSHOT
*/
public interface CreateMemberPort {
Member create(Member member);
}
|
package com.taotao.rest.service.impl;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.utils.JsonUtils;
import com.taotao.mapper.TbContentMapper;
import com.taotao.pojo.TbContent;
import com.taotao.pojo.TbContentExample;
import com.taotao.pojo.TbContentExample.Criteria;
import com.taotao.rest.component.JedisClient;
import com.taotao.rest.service.ContentService;
/**
* 内容查询服务
*
* @author Jerry
*
*/
@Service
public class ContentServiceImpl implements ContentService {
@Autowired
private TbContentMapper contentMapper;
@Autowired
private JedisClient jedisClient;
@Value("${REDIS_CONTENT_KEY}")
private String REDIS_CONTENT_KEY;
/*
* 根据cid 查询内容列表
*
* @see
* com.taotao.rest.service.ContentService#getContentList(java.lang.Long)
*/
@Override
public List<TbContent> getContentList(Long cid) {
// 添加缓存
try {
String json = jedisClient.hget(REDIS_CONTENT_KEY, cid + "");
if (!StringUtils.isBlank(json)) {
List<TbContent> list = JsonUtils.jsonToList(json, TbContent.class);
return list;
}
} catch (Exception e) {
e.printStackTrace();
}
TbContentExample example = new TbContentExample();
Criteria criteria = example.createCriteria();
criteria.andCategoryIdEqualTo(cid);
List<TbContent> list = contentMapper.selectByExampleWithBLOBs(example);
if(list.size()>0){
try {
jedisClient.hset(REDIS_CONTENT_KEY, cid+"", JsonUtils.objectToJson(list));
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
/*
* 同步redis
* (non-Javadoc)
* @see com.taotao.rest.service.ContentService#syncCOntent(java.lang.Long)
*/
@Override
public TaotaoResult syncContent(Long cid) {
jedisClient.hdel(REDIS_CONTENT_KEY, cid + "");
return TaotaoResult.ok();
}
}
|
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package com.sap.walton.engineExt;
import android.net.http.SslError;
import android.webkit.ValueCallback;
import android.webkit.WebResourceResponse;
import org.crosswalk.engine.XWalkWebViewEngine;
import org.xwalk.core.XWalkView;
import org.crosswalk.engine.XWalkCordovaResourceClient;
public class XWalkCordovaResourceClientExt extends XWalkCordovaResourceClient {
private static final String TAG = "XWalkCordovaResourceClientExt";
public XWalkCordovaResourceClientExt(XWalkWebViewEngine parentEngine) {
super(parentEngine);
}
/**
* Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable).
* The errorCode parameter corresponds to one of the ERROR_* constants.
*
* @param view The WebView that is initiating the callback.
* @param errorCode The error code corresponding to an ERROR_* value.
* @param description A String describing the error.
* @param failingUrl The url that failed to load.
*/
@Override
public void onReceivedLoadError(XWalkView view, int errorCode, String description,
String failingUrl) {
super.onReceivedLoadError(view, errorCode, description, failingUrl);
}
@Override
public WebResourceResponse shouldInterceptLoadRequest(XWalkView view, String url) {
return super.shouldInterceptLoadRequest(view, url);
}
@Override
public boolean shouldOverrideUrlLoading(XWalkView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
@Override
public void onReceivedSslError(XWalkView view, ValueCallback<Boolean> callback, SslError error) {
callback.onReceiveValue(true);
// super.onReceivedSslError(view, callback, error);
}
}
|
/*
* TaskUnifier
* Copyright (c) 2013, Benjamin Leclerc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of TaskUnifier or the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.leclercb.taskunifier.gui.components.calendar;
import com.leclercb.taskunifier.api.models.Task;
import com.leclercb.taskunifier.gui.commons.events.ModelSelectionChangeSupported;
import com.leclercb.taskunifier.gui.components.tasksearchertree.TaskSearcherView;
public interface TaskCalendarView extends ModelSelectionChangeSupported {
public abstract TaskSearcherView getTaskSearcherView();
public abstract Task[] getSelectedTasks();
public abstract void refreshTasks();
public abstract boolean shouldBeDisplayed(Task task);
public abstract void focusAndSearch(String text);
}
|
package server.api.models;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Singleton;
@Singleton
public class TopologyCatalog {
public List<TopologyDeco> topologies;
public Map<String, TopologyDeco> index;
public TopologyCatalog() {
this.topologies = new ArrayList<>();
this.index = new HashMap<>();
}
public List<TopologyDeco> getTopologies() {
return topologies;
}
public void setTopologies(List<TopologyDeco> topologies) {
this.topologies = topologies;
topologies.forEach(topology -> addIndex(topology));
}
public void addIndex(TopologyDeco topology) {
this.index.put(topology.getTeam(), topology);
}
public void addTopology(TopologyDeco topology) {
topologies.add(topology);
addIndex(topology);
}
public boolean exist(String team) {
return index.keySet().contains(team);
}
public TopologyDeco getByTeam(String team) {
return index.get(team);
}
}
|
package com.wenj91.fastgql.core.sql;
import com.wenj91.fastgql.core.graphql.FastGraphQLSchema;
import com.wenj91.fastgql.core.graphql.GraphQLField;
import graphql.language.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class OrderByUtils {
public static String orderByToSQL(List<OrderBy> orderByList) {
return orderByList.stream().map(OrderBy::sqlString).collect(Collectors.joining(", "));
}
public static Set<TableAlias> orderByListToTableAliasSet(List<OrderBy> orderByList) {
return orderByList.stream()
.map(OrderBy::createTableAliasSet)
.flatMap(Collection::stream)
.collect(Collectors.toUnmodifiableSet());
}
private static Stream<OrderBy> createOrderByStream(
ObjectValue objectValue,
String tableName,
String tableAlias,
String foreignTableAlias,
List<LeftJoin> leftJoins,
FastGraphQLSchema fastGraphQLSchema) {
return objectValue.getChildren().stream()
.map(node -> (ObjectField) node)
.flatMap(
objectField -> {
GraphQLField graphQLField =
fastGraphQLSchema.fieldAt(tableName, objectField.getName());
switch (graphQLField.getReferenceType()) {
case REFERENCING:
List<LeftJoin> leftJoinsCopy = new ArrayList<>(leftJoins);
String foreignTableName = graphQLField.getForeignName().getTableName();
String nextForeignAlias = foreignTableAlias + "r";
leftJoinsCopy.add(
new LeftJoin(
foreignTableName,
foreignTableAlias,
tableAlias,
graphQLField.getQualifiedName().getKeyName(),
graphQLField.getForeignName().getKeyName()));
return createOrderByStream(
(ObjectValue) objectField.getValue(),
foreignTableName,
foreignTableAlias,
nextForeignAlias,
leftJoinsCopy,
fastGraphQLSchema);
case NONE:
SelectColumn selectColumn = new SelectColumn(
tableAlias,
Column.builder()
.columnName(graphQLField.getName()
.getKeyName())
.columnName(graphQLField.getQualifiedName()
.getKeyName()).build());
return Stream.of(
new OrderBy(
leftJoins,
selectColumn,
((EnumValue) objectField.getValue()).getName())
);
default:
throw new RuntimeException("Unsupported field type for order by");
}
});
}
static List<OrderBy> createOrderBy(
Argument argument,
String tableName,
String tableAlias,
FastGraphQLSchema fastGraphQLSchema) {
Stream<OrderBy> orderByStream =
argument.getValue() instanceof ArrayValue
? ((ArrayValue) argument.getValue())
.getValues().stream()
.flatMap(
value ->
createOrderByStream(
(ObjectValue) value,
tableName,
tableAlias,
"f",
List.of(),
fastGraphQLSchema))
: createOrderByStream(
(ObjectValue) argument.getValue(),
tableName,
tableAlias,
"f",
List.of(),
fastGraphQLSchema);
return orderByStream.collect(Collectors.toList());
}
}
|
/*
* Copyright 2011-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.logs.model;
import java.io.Serializable;
/**
*
*/
public class FilterLogEventsResult implements Serializable, Cloneable {
/**
* <p>
* A list of <code>FilteredLogEvent</code> objects representing the matched
* events from the request.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<FilteredLogEvent> events;
/**
* <p>
* A list of <code>SearchedLogStream</code> objects indicating which log
* streams have been searched in this request and whether each has been
* searched completely or still has more to be paginated.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<SearchedLogStream> searchedLogStreams;
/**
* <p>
* A pagination token obtained from a <code>FilterLogEvents</code> response
* to continue paginating the FilterLogEvents results. This token is omitted
* from the response when there are no other events to display.
* </p>
*/
private String nextToken;
/**
* <p>
* A list of <code>FilteredLogEvent</code> objects representing the matched
* events from the request.
* </p>
*
* @return A list of <code>FilteredLogEvent</code> objects representing the
* matched events from the request.
*/
public java.util.List<FilteredLogEvent> getEvents() {
if (events == null) {
events = new com.amazonaws.internal.SdkInternalList<FilteredLogEvent>();
}
return events;
}
/**
* <p>
* A list of <code>FilteredLogEvent</code> objects representing the matched
* events from the request.
* </p>
*
* @param events
* A list of <code>FilteredLogEvent</code> objects representing the
* matched events from the request.
*/
public void setEvents(java.util.Collection<FilteredLogEvent> events) {
if (events == null) {
this.events = null;
return;
}
this.events = new com.amazonaws.internal.SdkInternalList<FilteredLogEvent>(
events);
}
/**
* <p>
* A list of <code>FilteredLogEvent</code> objects representing the matched
* events from the request.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if
* any). Use {@link #setEvents(java.util.Collection)} or
* {@link #withEvents(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param events
* A list of <code>FilteredLogEvent</code> objects representing the
* matched events from the request.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public FilterLogEventsResult withEvents(FilteredLogEvent... events) {
if (this.events == null) {
setEvents(new com.amazonaws.internal.SdkInternalList<FilteredLogEvent>(
events.length));
}
for (FilteredLogEvent ele : events) {
this.events.add(ele);
}
return this;
}
/**
* <p>
* A list of <code>FilteredLogEvent</code> objects representing the matched
* events from the request.
* </p>
*
* @param events
* A list of <code>FilteredLogEvent</code> objects representing the
* matched events from the request.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public FilterLogEventsResult withEvents(
java.util.Collection<FilteredLogEvent> events) {
setEvents(events);
return this;
}
/**
* <p>
* A list of <code>SearchedLogStream</code> objects indicating which log
* streams have been searched in this request and whether each has been
* searched completely or still has more to be paginated.
* </p>
*
* @return A list of <code>SearchedLogStream</code> objects indicating which
* log streams have been searched in this request and whether each
* has been searched completely or still has more to be paginated.
*/
public java.util.List<SearchedLogStream> getSearchedLogStreams() {
if (searchedLogStreams == null) {
searchedLogStreams = new com.amazonaws.internal.SdkInternalList<SearchedLogStream>();
}
return searchedLogStreams;
}
/**
* <p>
* A list of <code>SearchedLogStream</code> objects indicating which log
* streams have been searched in this request and whether each has been
* searched completely or still has more to be paginated.
* </p>
*
* @param searchedLogStreams
* A list of <code>SearchedLogStream</code> objects indicating which
* log streams have been searched in this request and whether each
* has been searched completely or still has more to be paginated.
*/
public void setSearchedLogStreams(
java.util.Collection<SearchedLogStream> searchedLogStreams) {
if (searchedLogStreams == null) {
this.searchedLogStreams = null;
return;
}
this.searchedLogStreams = new com.amazonaws.internal.SdkInternalList<SearchedLogStream>(
searchedLogStreams);
}
/**
* <p>
* A list of <code>SearchedLogStream</code> objects indicating which log
* streams have been searched in this request and whether each has been
* searched completely or still has more to be paginated.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if
* any). Use {@link #setSearchedLogStreams(java.util.Collection)} or
* {@link #withSearchedLogStreams(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param searchedLogStreams
* A list of <code>SearchedLogStream</code> objects indicating which
* log streams have been searched in this request and whether each
* has been searched completely or still has more to be paginated.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public FilterLogEventsResult withSearchedLogStreams(
SearchedLogStream... searchedLogStreams) {
if (this.searchedLogStreams == null) {
setSearchedLogStreams(new com.amazonaws.internal.SdkInternalList<SearchedLogStream>(
searchedLogStreams.length));
}
for (SearchedLogStream ele : searchedLogStreams) {
this.searchedLogStreams.add(ele);
}
return this;
}
/**
* <p>
* A list of <code>SearchedLogStream</code> objects indicating which log
* streams have been searched in this request and whether each has been
* searched completely or still has more to be paginated.
* </p>
*
* @param searchedLogStreams
* A list of <code>SearchedLogStream</code> objects indicating which
* log streams have been searched in this request and whether each
* has been searched completely or still has more to be paginated.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public FilterLogEventsResult withSearchedLogStreams(
java.util.Collection<SearchedLogStream> searchedLogStreams) {
setSearchedLogStreams(searchedLogStreams);
return this;
}
/**
* <p>
* A pagination token obtained from a <code>FilterLogEvents</code> response
* to continue paginating the FilterLogEvents results. This token is omitted
* from the response when there are no other events to display.
* </p>
*
* @param nextToken
* A pagination token obtained from a <code>FilterLogEvents</code>
* response to continue paginating the FilterLogEvents results. This
* token is omitted from the response when there are no other events
* to display.
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* <p>
* A pagination token obtained from a <code>FilterLogEvents</code> response
* to continue paginating the FilterLogEvents results. This token is omitted
* from the response when there are no other events to display.
* </p>
*
* @return A pagination token obtained from a <code>FilterLogEvents</code>
* response to continue paginating the FilterLogEvents results. This
* token is omitted from the response when there are no other events
* to display.
*/
public String getNextToken() {
return this.nextToken;
}
/**
* <p>
* A pagination token obtained from a <code>FilterLogEvents</code> response
* to continue paginating the FilterLogEvents results. This token is omitted
* from the response when there are no other events to display.
* </p>
*
* @param nextToken
* A pagination token obtained from a <code>FilterLogEvents</code>
* response to continue paginating the FilterLogEvents results. This
* token is omitted from the response when there are no other events
* to display.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public FilterLogEventsResult withNextToken(String nextToken) {
setNextToken(nextToken);
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 (getEvents() != null)
sb.append("Events: " + getEvents() + ",");
if (getSearchedLogStreams() != null)
sb.append("SearchedLogStreams: " + getSearchedLogStreams() + ",");
if (getNextToken() != null)
sb.append("NextToken: " + getNextToken());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof FilterLogEventsResult == false)
return false;
FilterLogEventsResult other = (FilterLogEventsResult) obj;
if (other.getEvents() == null ^ this.getEvents() == null)
return false;
if (other.getEvents() != null
&& other.getEvents().equals(this.getEvents()) == false)
return false;
if (other.getSearchedLogStreams() == null
^ this.getSearchedLogStreams() == null)
return false;
if (other.getSearchedLogStreams() != null
&& other.getSearchedLogStreams().equals(
this.getSearchedLogStreams()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null
&& other.getNextToken().equals(this.getNextToken()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode
+ ((getEvents() == null) ? 0 : getEvents().hashCode());
hashCode = prime
* hashCode
+ ((getSearchedLogStreams() == null) ? 0
: getSearchedLogStreams().hashCode());
hashCode = prime * hashCode
+ ((getNextToken() == null) ? 0 : getNextToken().hashCode());
return hashCode;
}
@Override
public FilterLogEventsResult clone() {
try {
return (FilterLogEventsResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
}
|
/*
* 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.lucene.codecs.simpletext;
import java.io.IOException;
import org.apache.lucene.codecs.StoredFieldsWriter;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.FieldInfos;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IOUtils;
/**
* Writes plain-text stored fields.
* <p>
* <b>FOR RECREATIONAL USE ONLY</b>
* @lucene.experimental
*/
public class SimpleTextStoredFieldsWriter extends StoredFieldsWriter {
private int numDocsWritten = 0;
private IndexOutput out;
final static String FIELDS_EXTENSION = "fld";
final static BytesRef TYPE_STRING = new BytesRef("string");
final static BytesRef TYPE_BINARY = new BytesRef("binary");
final static BytesRef TYPE_INT = new BytesRef("int");
final static BytesRef TYPE_LONG = new BytesRef("long");
final static BytesRef TYPE_FLOAT = new BytesRef("float");
final static BytesRef TYPE_DOUBLE = new BytesRef("double");
final static BytesRef END = new BytesRef("END");
final static BytesRef DOC = new BytesRef("doc ");
final static BytesRef FIELD = new BytesRef(" field ");
final static BytesRef NAME = new BytesRef(" name ");
final static BytesRef TYPE = new BytesRef(" type ");
final static BytesRef VALUE = new BytesRef(" value ");
private final BytesRefBuilder scratch = new BytesRefBuilder();
public SimpleTextStoredFieldsWriter(Directory directory, String segment, IOContext context) throws IOException {
boolean success = false;
try {
out = directory.createOutput(IndexFileNames.segmentFileName(segment, "", FIELDS_EXTENSION), context);
success = true;
} finally {
if (!success) {
IOUtils.closeWhileHandlingException(this);
}
}
}
@Override
public void startDocument() throws IOException {
write(DOC);
write(Integer.toString(numDocsWritten));
newLine();
numDocsWritten++;
}
@Override
public void writeField(FieldInfo info, IndexableField field) throws IOException {
write(FIELD);
write(Integer.toString(info.number));
newLine();
write(NAME);
write(field.name());
newLine();
write(TYPE);
final Number n = field.numericValue();
if (n != null) {
if (n instanceof Byte || n instanceof Short || n instanceof Integer) {
write(TYPE_INT);
newLine();
write(VALUE);
write(Integer.toString(n.intValue()));
newLine();
} else if (n instanceof Long) {
write(TYPE_LONG);
newLine();
write(VALUE);
write(Long.toString(n.longValue()));
newLine();
} else if (n instanceof Float) {
write(TYPE_FLOAT);
newLine();
write(VALUE);
write(Float.toString(n.floatValue()));
newLine();
} else if (n instanceof Double) {
write(TYPE_DOUBLE);
newLine();
write(VALUE);
write(Double.toString(n.doubleValue()));
newLine();
} else {
throw new IllegalArgumentException("cannot store numeric type " + n.getClass());
}
} else {
BytesRef bytes = field.binaryValue();
if (bytes != null) {
write(TYPE_BINARY);
newLine();
write(VALUE);
write(bytes);
newLine();
} else if (field.stringValue() == null) {
throw new IllegalArgumentException("field " + field.name() + " is stored but does not have binaryValue, stringValue nor numericValue");
} else {
write(TYPE_STRING);
newLine();
write(VALUE);
write(field.stringValue());
newLine();
}
}
}
@Override
public void finish(FieldInfos fis, int numDocs) throws IOException {
if (numDocsWritten != numDocs) {
throw new RuntimeException("mergeFields produced an invalid result: docCount is " + numDocs
+ " but only saw " + numDocsWritten + " file=" + out.toString() + "; now aborting this merge to prevent index corruption");
}
write(END);
newLine();
SimpleTextUtil.writeChecksum(out, scratch);
}
@Override
public void close() throws IOException {
try {
IOUtils.close(out);
} finally {
out = null;
}
}
private void write(String s) throws IOException {
SimpleTextUtil.write(out, s, scratch);
}
private void write(BytesRef bytes) throws IOException {
SimpleTextUtil.write(out, bytes);
}
private void newLine() throws IOException {
SimpleTextUtil.writeNewline(out);
}
@Override
public long ramBytesUsed() {
return Integer.BYTES; // something > 0
}
}
|
// This file is made available under Elastic License 2.0.
// This file is based on code available under the Apache license here:
// https://github.com/apache/incubator-doris/blob/master/fe/fe-core/src/main/java/org/apache/doris/catalog/ScalarType.java
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.starrocks.catalog;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.gson.annotations.SerializedName;
import com.starrocks.common.AnalysisException;
import com.starrocks.common.Config;
import com.starrocks.thrift.TColumnType;
import com.starrocks.thrift.TScalarType;
import com.starrocks.thrift.TTypeDesc;
import com.starrocks.thrift.TTypeNode;
import com.starrocks.thrift.TTypeNodeType;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.Objects;
/**
* Describes a scalar type. For most types this class just wraps a PrimitiveType enum,
* but for types like CHAR and DECIMAL, this class contain additional information.
* <p>
* Scalar types have a few ways they can be compared to other scalar types. They can be:
* 1. completely identical,
* 2. implicitly castable (convertible without loss of precision)
* 3. subtype. For example, in the case of decimal, a type can be decimal(*, *)
* indicating that any decimal type is a subtype of the decimal type.
*/
public class ScalarType extends Type implements Cloneable {
private static final Logger LOG = LogManager.getLogger(ScalarType.class);
// SQL allows the engine to pick the default precision. We pick the largest
// precision that is supported by the smallest decimal type in the BE (4 bytes).
public static final int DEFAULT_PRECISION = 9;
public static final int DEFAULT_SCALE = 0; // SQL standard
// Longest supported VARCHAR and CHAR, chosen to match Hive.
public static final int DEFAULT_STRING_LENGTH = 65533;
public static final int MAX_VARCHAR_LENGTH = 1048576;
public static final int MAX_CHAR_LENGTH = 255;
// HLL DEFAULT LENGTH 2^14(registers) + 1(type)
public static final int MAX_HLL_LENGTH = 16385;
@SerializedName(value = "type")
private final PrimitiveType type;
// Only used for type CHAR.
@SerializedName(value = "len")
private int len = -1;
private boolean isAssignedStrLenInColDefinition = false;
// Only used if type is DECIMAL. -1 (for both) is used to represent a
// decimal with any precision and scale.
// It is invalid to have one by -1 and not the other.
// TODO: we could use that to store DECIMAL(8,*), indicating a decimal
// with 8 digits of precision and any valid ([0-8]) scale.
@SerializedName(value = "precision")
private int precision;
@SerializedName(value = "scale")
private int scale;
protected ScalarType(PrimitiveType type) {
this.type = type;
}
public static ScalarType createType(PrimitiveType type, int len, int precision, int scale) {
switch (type) {
case CHAR:
return createCharType(len);
case VARCHAR:
return createVarcharType(len);
case DECIMALV2:
return createDecimalV2Type(precision, scale);
case DECIMAL32:
case DECIMAL64:
case DECIMAL128:
return createDecimalV3Type(type, precision, scale);
default:
return createType(type);
}
}
public static ScalarType createType(PrimitiveType type) {
ScalarType res = PRIMITIVE_TYPE_SCALAR_TYPE_MAP.get(type);
Preconditions.checkNotNull(res, "unknown type " + type);
return res;
}
public static ScalarType createType(String type) {
ScalarType res = STATIC_TYPE_MAP.get(type);
Preconditions.checkNotNull(res, "unknown type " + type);
return res;
}
/**
* Create type from parser, needs to infer type from simple name
*/
public static ScalarType createTypeFromParser(String typeName, Integer length, Integer precision, Integer scale) {
if (length != null) {
if (StringUtils.startsWithIgnoreCase(typeName, "VARCHAR")) {
return createVarchar(length);
} else if (StringUtils.startsWithIgnoreCase(typeName, "CHAR")) {
return createCharType(length);
} else if ("STRING".equalsIgnoreCase(typeName)) {
return DEFAULT_STRING;
}
} else if (StringUtils.startsWithIgnoreCase(typeName, "DECIMAL")) {
if ("DECIMAL".equalsIgnoreCase(typeName)) {
if (precision != null) {
return ScalarType.createUnifiedDecimalType(precision, scale);
} else {
return ScalarType.createUnifiedDecimalType(10, 0);
}
} else if ("DECIMALV2".equalsIgnoreCase(typeName)) {
if (precision != null) {
return ScalarType.createDecimalV2Type(precision, scale);
} else {
return ScalarType.createDecimalV2Type();
}
}
PrimitiveType primitive = createType(typeName).getPrimitiveType();
if (precision == null || scale == null) {
return ScalarType.createDecimalV3Type(primitive);
} else {
return ScalarType.createDecimalV3Type(primitive, precision, scale);
}
} else {
return createType(typeName);
}
throw new IllegalArgumentException("Unsupported type: " + typeName);
}
public static ScalarType createCharType(int len) {
ScalarType type = new ScalarType(PrimitiveType.CHAR);
type.len = len;
return type;
}
private static boolean isDecimalV3Enabled() {
return Config.enable_decimal_v3;
}
public static void checkEnableDecimalV3() throws AnalysisException {
if (!isDecimalV3Enabled()) {
throw new AnalysisException("Config field enable_decimal_v3 is false now, " +
"turn it on before decimal32/64/128 are used, " +
"execute cmd 'admin set frontend config (\"enable_decimal_v3\" = \"true\")' " +
"on every FE server");
}
}
private static AnalysisException decimalParseError(String errorMsg) {
final String hint =
"Legal format is 'DECIMAL(precision, scale)', " +
"constraints 0<precision<=38 and 0<=scale<=precision must be hold. ";
return new AnalysisException(hint + "error='" + errorMsg + "'");
}
/**
* Unified decimal is used for parser, which creating default decimal from name
*/
public static ScalarType createUnifiedDecimalType() throws AnalysisException {
throw decimalParseError("both precision and scale are absent");
}
public static ScalarType createUnifiedDecimalType(int precision) throws AnalysisException {
throw decimalParseError("scale is absent");
}
public static ScalarType createUnifiedDecimalType(int precision, int scale) {
if (isDecimalV3Enabled()) {
// use decimal64 even if precision <= 9, because decimal32 is vulnerable to overflow
// and casted to decimal64 before expression evaluations are performed on it in BE, so
// decimal32 has a performance penalty.
PrimitiveType pt = precision <= 18 ? PrimitiveType.DECIMAL64 : PrimitiveType.DECIMAL128;
return createDecimalV3Type(pt, precision, scale);
} else {
return createDecimalV2Type(precision, scale);
}
}
public static ScalarType createDecimalV2Type() {
return DEFAULT_DECIMALV2;
}
public static ScalarType createDecimalV2Type(int precision) {
return createDecimalV2Type(precision, DEFAULT_SCALE);
}
public static ScalarType createDecimalV2Type(int precision, int scale) {
ScalarType type = new ScalarType(PrimitiveType.DECIMALV2);
type.precision = precision;
type.scale = scale;
return type;
}
public static ScalarType createDecimalV3Type(PrimitiveType type, int precision, int scale) {
Preconditions.checkArgument(0 < precision && precision <= PrimitiveType.getMaxPrecisionOfDecimal(type),
"DECIMAL's precision should range from 1 to 38");
Preconditions.checkArgument(0 <= scale && scale <= precision,
"DECIMAL(P[,S]) type P must be greater than or equal to the value of S");
ScalarType scalarType = new ScalarType(type);
scalarType.precision = precision;
scalarType.scale = scale;
return scalarType;
}
// 0's type is decimal32(0,0)
public static ScalarType createDecimalV3TypeForZero() {
ScalarType scalarType = new ScalarType(PrimitiveType.DECIMAL32);
scalarType.precision = 0;
scalarType.scale = 0;
return scalarType;
}
/**
* Wildcard decimal is used for function matching
*/
public static ScalarType createWildcardDecimalV3Type(PrimitiveType type) {
Preconditions.checkArgument(type.isDecimalV3Type());
ScalarType scalarType = new ScalarType(type);
scalarType.precision = -1;
scalarType.scale = -1;
return scalarType;
}
public static ScalarType createDecimalV3Type(PrimitiveType type, int precision) {
int defaultScale = PrimitiveType.getDefaultScaleOfDecimal(type);
return createDecimalV3Type(type, precision, Math.min(precision, defaultScale));
}
public static ScalarType createDecimalV3Type(PrimitiveType type) {
int maxPrecision = PrimitiveType.getMaxPrecisionOfDecimal(type);
int defaultScale = PrimitiveType.getDefaultScaleOfDecimal(type);
return createDecimalV3Type(type, maxPrecision, defaultScale);
}
public static ScalarType createDecimalV3NarrowestType(int precision, int scale) {
if (precision == 0 && scale == 0) {
return createDecimalV3TypeForZero();
}
final int decimal32MaxPrecision = PrimitiveType.getMaxPrecisionOfDecimal(PrimitiveType.DECIMAL32);
final int decimal64MaxPrecision = PrimitiveType.getMaxPrecisionOfDecimal(PrimitiveType.DECIMAL64);
final int decimal128MaxPrecision = PrimitiveType.getMaxPrecisionOfDecimal(PrimitiveType.DECIMAL128);
if (0 < precision && precision <= decimal32MaxPrecision) {
return createDecimalV3Type(PrimitiveType.DECIMAL32, precision, scale);
} else if (decimal32MaxPrecision < precision && precision <= decimal64MaxPrecision) {
return createDecimalV3Type(PrimitiveType.DECIMAL64, precision, scale);
} else if (decimal64MaxPrecision < precision && precision <= decimal128MaxPrecision) {
return createDecimalV3Type(PrimitiveType.DECIMAL128, precision, scale);
} else {
Preconditions.checkState(false,
"Illegal decimal precision(1 to 38): pecision=" + precision);
return ScalarType.INVALID;
}
}
public static ScalarType createDefaultString() {
ScalarType stringType = ScalarType.createVarcharType(ScalarType.DEFAULT_STRING_LENGTH);
stringType.setAssignedStrLenInColDefinition();
return stringType;
}
public static ScalarType createVarcharType(int len) {
// length checked in analysis
ScalarType type = new ScalarType(PrimitiveType.VARCHAR);
type.len = len;
return type;
}
public static ScalarType createVarchar(int len) {
// length checked in analysis
ScalarType type = new ScalarType(PrimitiveType.VARCHAR);
type.len = len;
return type;
}
public static ScalarType createVarcharType() {
return Type.VARCHAR;
}
public static ScalarType createHllType() {
ScalarType type = new ScalarType(PrimitiveType.HLL);
type.len = MAX_HLL_LENGTH;
return type;
}
// A common type for two decimal v3 types means that if t2 = getCommonTypeForDecimalV3(t0, t1),
// two invariants following is always holds:
// 1. t2's integer part is sufficient to hold both t0 and t1's counterparts: i.e.
// t2.precision - t2.scale = max((t0.precision - t0.scale), (t1.precision - t1.scale))
// 2. t2's fraction part is sufficient to hold both t0 and t1's counterparts: i.e.
// t2.scale = max(t0.scale, t1.scale)
public static ScalarType getCommonTypeForDecimalV3(ScalarType lhs, ScalarType rhs) {
Preconditions.checkState(lhs.isDecimalV3() && rhs.isDecimalV3());
int lhsPrecision = lhs.getScalarPrecision();
int lhsScale = lhs.getScalarScale();
int rhsPrecision = rhs.getScalarPrecision();
int rhsScale = rhs.getScalarScale();
int lhsIntegerPartWidth = lhsPrecision - lhsScale;
int rhsIntegerPartWidth = rhsPrecision - rhsScale;
int integerPartWidth = Math.max(lhsIntegerPartWidth, rhsIntegerPartWidth);
int scale = Math.max(lhsScale, rhsScale);
int precision = integerPartWidth + scale;
if (precision > 38) {
return ScalarType.DOUBLE;
} else {
// the common type's PrimitiveType of two decimal types should wide enough, i.e
// the common type of (DECIMAL32, DECIMAL64) should be DECIMAL64
PrimitiveType primitiveType =
PrimitiveType.getWiderDecimalV3Type(lhs.getPrimitiveType(), rhs.getPrimitiveType());
// the narrowestType for specified precision and scale is just wide properly to hold a decimal value, i.e
// DECIMAL128(7,4), DECIMAL64(7,4) and DECIMAL32(7,4) can all be held in a DECIMAL32(7,4) type without
// precision loss.
Type narrowestType = ScalarType.createDecimalV3NarrowestType(precision, scale);
primitiveType = PrimitiveType.getWiderDecimalV3Type(primitiveType, narrowestType.getPrimitiveType());
// create a commonType with wider primitive type.
return ScalarType.createDecimalV3Type(primitiveType, precision, scale);
}
}
// getAssigmentCompatibleTypeOfDecimalV3 is used by FunctionCallExpr for finding the common Type of argument types.
// i.e.
// least(decimal64(15,2), decimal32(5,4)) match least instance: least(decimal64(18,4), decimal64(18,4));
// least(double, decimal128(38,7)) match least instance: least(double, double).
public static ScalarType getAssigmentCompatibleTypeOfDecimalV3(
ScalarType decimalType, ScalarType otherType) {
Preconditions.checkState(decimalType.isDecimalV3());
// same triple (type, precision, scale)
if (decimalType.equals(otherType)) {
PrimitiveType type = PrimitiveType.getWiderDecimalV3Type(PrimitiveType.DECIMAL64, decimalType.type);
return ScalarType.createDecimalV3Type(type, decimalType.precision, decimalType.scale);
}
switch (otherType.getPrimitiveType()) {
case DECIMALV2:
return getCommonTypeForDecimalV3(decimalType,
createDecimalV3Type(PrimitiveType.DECIMAL128, 27, 9));
case DECIMAL32:
case DECIMAL64:
case DECIMAL128:
return getCommonTypeForDecimalV3(decimalType, otherType);
case BOOLEAN:
return getCommonTypeForDecimalV3(decimalType,
createDecimalV3Type(PrimitiveType.DECIMAL32, 1, 0));
case TINYINT:
return getCommonTypeForDecimalV3(decimalType,
createDecimalV3Type(PrimitiveType.DECIMAL32, 3, 0));
case SMALLINT:
return getCommonTypeForDecimalV3(decimalType,
createDecimalV3Type(PrimitiveType.DECIMAL32, 5, 0));
case INT:
return getCommonTypeForDecimalV3(decimalType,
createDecimalV3Type(PrimitiveType.DECIMAL64, 10, 0));
case BIGINT:
return getCommonTypeForDecimalV3(decimalType,
createDecimalV3Type(PrimitiveType.DECIMAL128, 19, 0));
case LARGEINT:
return getCommonTypeForDecimalV3(decimalType,
createDecimalV3Type(PrimitiveType.DECIMAL128, 38, 0));
case FLOAT:
case DOUBLE:
case CHAR:
case VARCHAR:
case DATE:
case DATETIME:
return DOUBLE;
default:
return INVALID;
}
}
/**
* Return type t such that values from both t1 and t2 can be assigned to t.
* If strict, only return types when there will be no loss of precision.
* Returns INVALID_TYPE if there is no such type or if any of t1 and t2
* is INVALID_TYPE.
*/
public static ScalarType getAssignmentCompatibleType(ScalarType t1, ScalarType t2, boolean strict) {
if (!t1.isValid() || !t2.isValid()) {
return INVALID;
}
if (t1.equals(t2)) {
return t1;
}
if (t1.isNull()) {
return t2;
}
if (t2.isNull()) {
return t1;
}
boolean t1IsHLL = t1.type == PrimitiveType.HLL;
boolean t2IsHLL = t2.type == PrimitiveType.HLL;
if (t1IsHLL || t2IsHLL) {
if (t1IsHLL && t2IsHLL) {
return createHllType();
}
return INVALID;
}
if (t1.isStringType() || t2.isStringType()) {
return createVarcharType(Math.max(t1.len, t2.len));
}
if (t1.isDecimalV3()) {
return getAssigmentCompatibleTypeOfDecimalV3(t1, t2);
}
if (t2.isDecimalV3()) {
return getAssigmentCompatibleTypeOfDecimalV3(t2, t1);
}
if (t1.isDecimalOfAnyVersion() && t2.isDate() || t1.isDate() && t2.isDecimalOfAnyVersion()) {
return INVALID;
}
if (t1.isDecimalV2() || t2.isDecimalV2()) {
return DECIMALV2;
}
PrimitiveType smallerType =
(t1.type.ordinal() < t2.type.ordinal() ? t1.type : t2.type);
PrimitiveType largerType =
(t1.type.ordinal() > t2.type.ordinal() ? t1.type : t2.type);
PrimitiveType result = compatibilityMatrix[smallerType.ordinal()][largerType.ordinal()];
Preconditions.checkNotNull(result, String.format("No assignment from %s to %s", t1, t2));
return createType(result);
}
/**
* Returns true t1 can be implicitly cast to t2, false otherwise.
* If strict is true, only consider casts that result in no loss of precision.
*/
public static boolean isImplicitlyCastable(ScalarType t1, ScalarType t2, boolean strict) {
return getAssignmentCompatibleType(t1, t2, strict).matchesType(t2);
}
// TODO(mofei) Why call implicit cast in the explicit cast context
public static boolean canCastTo(ScalarType type, ScalarType targetType) {
return PrimitiveType.isImplicitCast(type.getPrimitiveType(), targetType.getPrimitiveType());
}
@Override
public String toString() {
if (type == PrimitiveType.CHAR) {
if (isWildcardChar()) {
return "CHAR";
}
return "CHAR(" + len + ")";
} else if (type.isDecimalV2Type()) {
if (isWildcardDecimal()) {
return "DECIMAL";
}
return "DECIMAL(" + precision + "," + scale + ")";
} else if (type.isDecimalV3Type()) {
if (isWildcardDecimal()) {
return type.toString();
}
return type + "(" + precision + "," + scale + ")";
} else if (type == PrimitiveType.VARCHAR) {
if (isWildcardVarchar()) {
return "VARCHAR";
}
return "VARCHAR(" + len + ")";
}
return type.toString();
}
@Override
public String toSql(int depth) {
StringBuilder stringBuilder = new StringBuilder();
switch (type) {
case CHAR:
stringBuilder.append("char").append("(").append(len).append(")");
break;
case VARCHAR:
stringBuilder.append("varchar").append("(").append(len).append(")");
break;
case DECIMALV2:
stringBuilder.append("decimal").append("(").append(precision).append(", ").append(scale).append(")");
break;
case DECIMAL32:
case DECIMAL64:
case DECIMAL128:
stringBuilder.append(type.toString().toLowerCase()).append("(").append(precision).append(", ")
.append(scale).append(")");
break;
case BOOLEAN:
return "boolean";
case TINYINT:
return "tinyint(4)";
case SMALLINT:
return "smallint(6)";
case INT:
return "int(11)";
case BIGINT:
return "bigint(20)";
case LARGEINT:
return "largeint(40)";
case FLOAT:
case DOUBLE:
case DATE:
case DATETIME:
case HLL:
case BITMAP:
case PERCENTILE:
case JSON:
stringBuilder.append(type.toString().toLowerCase());
break;
default:
stringBuilder.append("unknown type: ").append(type);
break;
}
return stringBuilder.toString();
}
@Override
protected String prettyPrint(int lpad) {
return Strings.repeat(" ", lpad) + toSql();
}
@Override
public void toThrift(TTypeDesc container) {
TTypeNode node = new TTypeNode();
container.types.add(node);
switch (type) {
case VARCHAR:
case CHAR:
case HLL: {
node.setType(TTypeNodeType.SCALAR);
TScalarType scalarType = new TScalarType();
scalarType.setType(type.toThrift());
scalarType.setLen(len);
node.setScalar_type(scalarType);
break;
}
case DECIMALV2:
case DECIMAL32:
case DECIMAL64:
case DECIMAL128: {
node.setType(TTypeNodeType.SCALAR);
TScalarType scalarType = new TScalarType();
scalarType.setType(type.toThrift());
scalarType.setScale(scale);
scalarType.setPrecision(precision);
node.setScalar_type(scalarType);
break;
}
default: {
node.setType(TTypeNodeType.SCALAR);
TScalarType scalarType = new TScalarType();
scalarType.setType(type.toThrift());
node.setScalar_type(scalarType);
break;
}
}
}
public int decimalPrecision() {
Preconditions.checkState(type.isDecimalV2Type() || type.isDecimalV3Type());
return precision;
}
public int decimalScale() {
Preconditions.checkState(type.isDecimalV2Type() || type.isDecimalV3Type());
return scale;
}
@Override
public PrimitiveType getPrimitiveType() {
return type;
}
public int ordinal() {
return type.ordinal();
}
public int getLength() {
return len;
}
public void setLength(int len) {
this.len = len;
}
public boolean isAssignedStrLenInColDefinition() {
return isAssignedStrLenInColDefinition;
}
public void setAssignedStrLenInColDefinition() {
this.isAssignedStrLenInColDefinition = true;
}
// add scalar infix to override with getPrecision
public int getScalarScale() {
return scale;
}
public int getScalarPrecision() {
return precision;
}
@Override
public boolean isWildcardDecimal() {
return (type.isDecimalV2Type() || type.isDecimalV3Type())
&& precision == -1 && scale == -1;
}
@Override
public boolean isWildcardVarchar() {
return (type == PrimitiveType.VARCHAR || type == PrimitiveType.HLL) && len == -1;
}
@Override
public boolean isWildcardChar() {
return type == PrimitiveType.CHAR && len == -1;
}
@Override
public boolean isSupported() {
return type != PrimitiveType.BINARY;
}
@Override
public int getSlotSize() {
return type.getSlotSize();
}
@Override
public int getTypeSize() {
return type.getTypeSize();
}
/**
* Returns true if this object is of type t.
* Handles wildcard types. That is, if t is the wildcard type variant
* of 'this', returns true.
*/
@Override
public boolean matchesType(Type t) {
if (t.isPseudoType()) {
return t.matchesType(this);
}
if (this.getPrimitiveType() == t.getPrimitiveType()) {
Preconditions.checkArgument(t.isScalarType());
return !this.isDecimalV3()
|| t.isWildcardDecimal()
|| this.isWildcardDecimal()
|| (getScalarScale() == ((ScalarType) t).getScalarScale());
}
if (this.isStringType() && t.isStringType()) {
return true;
}
return isDecimalV2() && t.isDecimalV2();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof ScalarType)) {
return false;
}
ScalarType other = (ScalarType) o;
if (type != other.type) {
return false;
}
if (type == PrimitiveType.CHAR) {
return len == other.len;
}
if (type == PrimitiveType.VARCHAR) {
return len == other.len;
}
if (type.isDecimalV2Type() || type.isDecimalV3Type()) {
return precision == other.precision && scale == other.scale;
}
return true;
}
@Override
public int getStorageLayoutBytes() {
switch (type) {
case BOOLEAN:
case TINYINT:
return 1;
case SMALLINT:
return 2;
case INT:
case FLOAT:
case DECIMAL32:
return 4;
case BIGINT:
case TIME:
case DATETIME:
case DECIMAL64:
return 8;
case DECIMAL128:
case LARGEINT:
case DECIMALV2:
return 16;
case DOUBLE:
return 12;
case DATE:
return 3;
case CHAR:
case VARCHAR:
return len;
case HLL:
return 16385;
case BITMAP:
return 1024; // this is a estimated value
case JSON:
return 128; // estimated value
default:
return 0;
}
}
@Override
public TColumnType toColumnTypeThrift() {
TColumnType thrift = new TColumnType();
thrift.type = type.toThrift();
if (type == PrimitiveType.CHAR || type == PrimitiveType.VARCHAR || type == PrimitiveType.HLL) {
thrift.setLen(len);
}
if (type.isDecimalV2Type() || type.isDecimalV3Type()) {
thrift.setPrecision(precision);
thrift.setScale(scale);
}
return thrift;
}
@Override
public int hashCode() {
int result = 0;
result = 31 * result + Objects.hashCode(type);
result = 31 * result + precision;
result = 31 * result + scale;
return result;
}
@Override
public ScalarType clone() {
return (ScalarType) super.clone();
}
}
|
/*
* Copyright © 2014 - 2018 Leipzig University (Database Research Group)
*
* 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.gradoop.flink.model.impl.id;
import org.gradoop.common.model.impl.id.GradoopId;
import org.gradoop.common.model.impl.id.GradoopIdSet;
import org.gradoop.flink.model.GradoopFlinkTestBase;
import org.gradoop.flink.model.impl.GradoopFlinkTestUtils;
import org.junit.Test;
import static org.gradoop.flink.model.impl.GradoopFlinkTestUtils.writeAndRead;
import static org.junit.Assert.assertEquals;
public class GradoopIdSerializationTest extends GradoopFlinkTestBase {
@Test
public void testGradoopIdSerialization() throws Exception {
GradoopId idIn = GradoopId.get();
assertEquals("GradoopIds were not equal", idIn,
GradoopFlinkTestUtils.writeAndRead(idIn));
}
@Test
public void testGradoopIdSetSerialization() throws Exception {
GradoopIdSet idsIn = GradoopIdSet.fromExisting(
GradoopId.get(), GradoopId.get());
assertEquals("GradoopIdSets were not equal", idsIn,
GradoopFlinkTestUtils.writeAndRead(idsIn));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.